import assert from 'node:assert/strict'; import { generateKeyPairSync, sign, verify } from 'node:crypto'; import { createServer } from 'node:http'; import { once } from 'node:events'; import { join } from 'node:path'; import { setTimeout as wait } from 'node:timers/promises'; import { pathToFileURL } from 'node:url'; const source = process.env.KEYSIGNER_SOURCE; if (!source) throw new Error('Set KEYSIGNER_SOURCE to your KeySigner source checkout.'); const workerTest = pathToFileURL(join(source, 'workers/api/test/')).href; const { apiRequest, withMf } = await import(workerTest + 'helpers.mjs'); const { ADMIN, askToken, binding, issued, key, nowSeconds, publishedKeys, } = await import(workerTest + 'workload-tokens-fixture.mjs'); const firstKey = 'local-first-key'; const secondKey = 'local-second-key'; const keys = new Map([firstKey, secondKey].map(id => [id, generateKeyPairSync('ec', { namedCurve: 'prime256v1' })], )); const audience = 'test-service'; const lifetime = 12; const overlap = 2; let available = true; const kms = createServer(async (request, response) => { const chunks = []; for await (const chunk of request) chunks.push(chunk); const body = JSON.parse(Buffer.concat(chunks)); const operation = request.headers['x-amz-target']; const signingKey = keys.get(body.KeyId); response.setHeader('content-type', 'application/x-amz-json-1.1'); if (signingKey && operation === 'TrentService.GetPublicKey') { return response.end(JSON.stringify({ KeySpec: 'ECC_NIST_P256', KeyUsage: 'SIGN_VERIFY', PublicKey: signingKey.publicKey.export({ type: 'spki', format: 'der' }).toString('base64'), })); } if (available && signingKey && operation === 'TrentService.Sign' && body.MessageType === 'RAW' && body.SigningAlgorithm === 'ECDSA_SHA_256') { const signature = sign('sha256', Buffer.from(body.Message, 'base64'), signingKey.privateKey); return response.end(JSON.stringify({ Signature: signature.toString('base64') })); } response.writeHead(400).end(JSON.stringify({ message: 'Fixture refused the operation' })); }); const decode = part => JSON.parse(Buffer.from(part, 'base64url')); const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url'); function signatureValid(token, keyId) { const [head, payload, signature] = token.split('.'); const verifier = { key: keys.get(keyId).publicKey, dsaEncoding: 'ieee-p1363' }; return verify('sha256', Buffer.from(head + '.' + payload), verifier, Buffer.from(signature, 'base64url')); } function verifyTestToken(token, keyId, subject) { const [head, payload] = token.split('.'); const claims = decode(payload); assert(signatureValid(token, keyId), 'The expected test key did not sign the token'); assert.equal(claims.aud, audience); assert.equal(claims.sub, subject); assert(nowSeconds() < claims.exp, 'The test token expired'); return { kid: decode(head).kid, expires: claims.exp }; } async function checkPublishedKey(worker, kid, keyId) { const published = (await publishedKeys(worker)).find(entry => entry.kid === kid); assert(published, 'The expected public key was missing'); const { kty, crv, x, y } = published; assert.deepEqual({ kty, crv, x, y }, keys.get(keyId).publicKey.export({ format: 'jwk' })); } const waitUntil = seconds => wait(Math.max(0, seconds * 1000 - Date.now()) + 100); try { await once(kms.listen(0, '127.0.0.1'), 'listening'); await withMf(async worker => { const { binding_id, subject } = await binding(worker, { audience, token_seconds: lifetime, downstream_credential_seconds: 900, }); const separate = await binding(worker, { audience, label: 'separate-workload' }); const { token } = await issued(worker, binding_id); const original = verifyTestToken(token, firstKey, subject); const [head, payload, signature] = token.split('.'); const changed = [head, encode({ ...decode(payload), aud: 'different-service' }), signature].join('.'); assert(!signatureValid(changed, firstKey)); console.log('Verified the test token. Changing its audience broke the signature.'); available = false; const refused = await askToken(worker, binding_id); assert.equal(refused.response.status, 502); assert.equal(refused.json.error, 'workload_kms_failed'); assert.equal(refused.json.token, undefined); console.log('KeySigner refused to issue a token when signing failed.'); available = true; const rotation = await apiRequest(worker, 'POST', '/v1/workload-issuer/rotations', ADMIN, { kms_key_id: secondKey }, key()); assert.equal(rotation.response.status, 201, rotation.text); const { kid, active_from } = rotation.json; assert.notEqual(kid, original.kid); const beforeCutover = (await issued(worker, binding_id)).token; const previous = verifyTestToken(beforeCutover, firstKey, subject); assert.equal(previous.kid, original.kid); await checkPublishedKey(worker, kid, secondKey); await checkPublishedKey(worker, original.kid, firstKey); await waitUntil(active_from); const afterCutover = (await issued(worker, binding_id)).token; assert.equal(verifyTestToken(afterCutover, secondKey, subject).kid, kid); verifyTestToken(beforeCutover, firstKey, subject); await checkPublishedKey(worker, original.kid, firstKey); console.log('Both public keys appeared before cutover. The next token verified with the replacement key.'); const revoked = await apiRequest(worker, 'POST', '/v1/workload-bindings/' + binding_id + '/revoke', ADMIN, {}, key()); assert.equal(revoked.response.status, 200, revoked.text); const denied = await askToken(worker, binding_id); assert.equal(denied.response.status, 409); assert.equal(denied.json.error, 'binding_revoked'); assert.equal(denied.json.token, undefined); verifyTestToken(afterCutover, secondKey, subject); verifyTestToken((await issued(worker, separate.binding_id)).token, secondKey, separate.subject); const coverage = await apiRequest(worker, 'GET', '/v1/workload-coverage', ADMIN); assert.equal(coverage.response.status, 200, coverage.text); const record = coverage.json.bindings.find(entry => entry.binding_id === binding_id); assert.equal(record.state, 'revoked'); assert.equal(record.revocation_window_seconds, lifetime + 900); console.log('Revocation stopped new tokens for one binding. Its unexpired token and a separate binding still worked.'); await waitUntil(Math.max(active_from, previous.expires) + overlap); assert(!(await publishedKeys(worker)).some(entry => entry.kid === original.kid)); await checkPublishedKey(worker, kid, secondKey); console.log('The retiring public key disappeared after its last token expired and the overlap ended.'); }, { vars: { KEYSIGNER_WORKLOAD_KMS_KEY_ID: firstKey, KEYSIGNER_WORKLOAD_KMS_REGION: 'us-east-1', KEYSIGNER_WORKLOAD_KMS_ENDPOINT: 'http://127.0.0.1:' + kms.address().port, KEYSIGNER_WORKLOAD_KEY_LEAD_SECONDS: '5', KEYSIGNER_WORKLOAD_KEY_OVERLAP_SECONDS: String(overlap), KEYSIGNER_WORKLOAD_TOKEN_FLOOR_SECONDS: String(lifetime), AWS_ACCESS_KEY_ID: 'test', AWS_SECRET_ACCESS_KEY: 'test', }, }); } finally { kms.close(); }