Repository navigation
feat(keymanager): add AWS KMS adapter for TL and RA signing keys - #169
CharmingGroot wants to merge 10 commits into
Conversation
Add keys.type "aws-kms" with two settings: - keys.aws-kms.region: optional region override - keys.aws-kms.keys: maps each signing key ID to an existing KMS key ID, key ARN, or alias Validation rejects a missing block, an empty map, and empty entries. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
AWSKMSKeyManager implements port.KeyManager with existing KMS keys: - EnsureKey checks that the mapped key is an enabled ECC_NIST_P256 key with SIGN_VERIFY usage. It never creates a key. - EnsureKey pins the key ID to the key ARN that KMS resolved. The TL and RA read their public key once at startup, so a re-pointed alias takes effect on the next restart instead of signing with a key the service has not published. - Sign sends the SHA-256 digest with MessageType DIGEST and returns the ASN.1 DER signature, the same format FileKeyManager produces. - The public key is fetched once, and Verify checks signatures without calling KMS. Callers keep their own key IDs. The RA's event JWS kid stays the same and KMS references do not appear in signed output. The tests check that receipts, status tokens, and detached JWS made through the adapter verify. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
ans-ra and ans-tl pick the file or AWS KMS key manager in buildKeyManager, like buildServerIssuer and selectDNSVerifier. EnsureKey is not part of port.KeyManager, so each main declares a small unexported interface that adds it. Moving EnsureKey into the port would also mean updating ten test fakes under internal/. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
Add a README section on the aws-kms config: - the required key spec and usage - the IAM permissions each service needs - how to export the RA public key for the TL's producerKeys, since the RA writes no ans-ra-signer.pub when its key is in KMS - that remapping a key ID is a key rotation, and that a re-pointed alias takes effect on the next restart CLAUDE.md and the local configs mention the new option. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
|
One more question, separate from the points in the description. The AWS SDK adds about 2.8 MB to each binary (stripped |
There was a problem hiding this comment.
Thanks, really appreciate the contribution.
EnsureKey is not part of port.KeyManager, so each main.go declares a small unexported interface that adds it. Moving it into the port would also require updating ten test fakes under internal/, so I left the port unchanged. I can move it if you prefer.
Keep EnsureKey in the two commands. The RA and TL startup paths are its only production callers. The file adapter creates a missing key, while the KMS adapter validates and pins an existing key. The small local interfaces express what startup needs and let the ten test fakes keep implementing the service contract they actually use. RA startup interface (https://github.com/agentnameservice/ans/blob/3a1eadf/cmd/ans-ra/main.go#L493-L498) · TL startup interface (https://github.com/agentnameservice/ans/blob/3a1eadf/cmd/ans-tl/main.go#L331-L336)
Error logs include the KMS key reference (ARN or alias), and an ARN contains the account ID. I considered it an identifier rather than a secret and left it in. It never appears in signed output.
I recommend to keep the KMS reference in operator logs, and fix the public TL error response before merge. The ARN identifies the key and grants no access by itself. The adapter also logs the resolved ARN at INFO on successful startup, which helps operators confirm which key an alias selected. You are right about signed output. The issue is that the receipt and status-token handlers can return the wrapped AWS error verbatim in an HTTP 500, potentially exposing the account ID, role, or key ARN to callers. I recommend to match the RA’s generic An internal error occurred. response and keep the diagnostic detail in server logs. KMS logging (https://github.com/agentnameservice/ans/blob/3a1eadf/internal/adapter/keymanager/awskms.go#L113-L131) · TL error response
(https://github.com/agentnameservice/ans/blob/3a1eadf/internal/tl/handler/handler.go#L738-L750) · RA error response (https://github.com/agentnameservice/ans/blob/3a1eadf/internal/ra/handler/
errors.go#L103-L123)
1. [P1] TL key rotation breaks verification of previously issued receipts
A receipt proves historical inclusion and has no expiry. A verifier starting after a routine key rotation must still be able to verify the original receipt bytes using the public key identified by the receipt’s protected kid. This applies to receipts held by clients as well as those cached by the TL. The Go SDK checks status-token expiry separately. SDK receipt verification · SDK status-token expiry
Repointing the KMS alias takes effect when the TL restarts. At that point, /root-keys publishes only the replacement key. The SQLite receipt cache is indexed by leaf index and tree size. If the tree size is unchanged, a verifier asking for the same receipt gets the bytes signed by the previous key. I confirmed that those bytes verify only with the previous key. Rotation guidance · Receipt cache lookup · Published root key
sequenceDiagram
participant V as Verifier
participant TL as Transparency log
participant DB as Receipt cache
Note over TL,DB: Before rotation, TL cached a receipt signed by key A
Note over V,DB: TL restarts with key B at the same tree size
V->>TL: GET /root-keys
TL-->>V: Public key B
V->>TL: GET receipt for the same leaf
TL->>DB: Look up leaf index and tree size
DB-->>TL: Receipt signed by key A
TL-->>V: Cached receipt
Note over V: Verification with key B fails
Persist each TL signing key’s public verification line for the life of the log. Across routine rotations, publish the current and historical lines together at /root-keys, preserving the original log origin and kid for each key. The retired private key can be disabled for signing. The Go SDK accepts multiple lines and selects the verification key by kid. TL response format · SDK response parser · SDK key lookup
Acceptance test. Save a receipt signed by key A. Rotate to key B, restart the TL, and issue a fresh status token. Initialize a Go SDK verifier from the restarted TL’s /root-keys response with an empty local cache. It must verify both the saved receipt with A and the fresh token with B.
2. [P2] Public TL errors can disclose AWS identifiers
The KMS adapter wraps the SDK error from Sign. The TL’s receipt and status-token handlers pass signing failures to an error mapper that includes the full error text in the HTTP 500 response. With public reads enabled, an anonymous caller can receive an AWS access-denied message containing the account, IAM role, or key ARN. Keep the diagnostic cause in server logs and return a generic detail to the caller, following the RA’s existing error handling. KMS signing error · TL error response · RA error response
3. [P2] Revocation holds the RA’s only database connection while KMS signs
Both V1 and V2 revocation sign the outbox event inside the SQLite transaction. The RA sets its connection pool size to one. A slow KMS response or SDK retry therefore blocks unrelated database reads and writes for the duration of the call. Revocation transaction · Outbox signing · Connection limit
sequenceDiagram
participant R as Revocation handler
participant DB as SQLite connection
participant K as AWS KMS
participant Q as Unrelated RA request
R->>DB: Begin transaction and update revocation state
R->>K: Sign the outbox event
Q->>DB: Request a connection
Note over DB,Q: Request waits while revocation holds the connection
K-->>R: Signature
R->>DB: Insert signed outbox row and commit
DB-->>Q: Connection becomes available
Prepare and sign the candidate event before opening the transaction. Inside the transaction, re-validate the state and certificate inputs used to sign it, then commit the revocation and the matching signed outbox row together.
4. [P2] Checkpoint signing has no overall deadline
Both checkpoint signers use context.Background(), and the adapter passes the context directly to KMS. If a signing response stalls, checkpoint publication can stop advancing. A new leaf then has to wait for a signed checkpoint before the TL can issue its receipt. C2SP checkpoint signer · JWS checkpoint signer · KMS call
flowchart TD
A["Checkpoint signer calls KMS"] --> B{"Does signing finish?"}
B -->|Yes, successfully| C["TL can publish the signed checkpoint"]
B -->|Response stalls| D["Signer keeps waiting without a deadline"]
D --> E["Latest signed checkpoint stays behind the new leaf"]
E --> F["Receipt request returns HTTP 503 with Retry-After"]
Set a finite deadline on KMS operations and honor any shorter deadline supplied by the caller.
5. [P2] The RA reports ready when its role lacks permission to sign
A role with kms:DescribeKey and kms:GetPublicKey passes EnsureKey even if it lacks kms:Sign. The RA then returns HTTP 200 from its readiness endpoint and can accept registrations that fail at activation. Check signing authorization against the pinned key at startup. KMS supports Sign with DryRun for this purpose. Startup key check · RA readiness handler · AWS permission testing
6. [P2] RA key rotation requires a fresh producer key ID
On an existing deployment, replacing the PEM in producerKeys under the same ID and restarting the TL leaves the old key in SQLite. Bootstrap skips IDs that already exist. Once the RA starts signing with the replacement key, the TL looks up the old public key for the event’s kid and rejects the signature. README rotation guidance · Bootstrap duplicate handling · Producer key lookup
Document the following rollout order so the TL can verify both newly signed events and pending outbox deliveries.
sequenceDiagram
participant O as Operator
participant TL as TL producer-key store
participant RA as Registration authority
O->>TL: Register public key B under a fresh key ID
O->>RA: Map the fresh ID to KMS key B and switch signer.keyId
Note over TL,RA: Both producer keys are trusted during the rollout
RA->>TL: Deliver new events signed with key B
RA->>TL: Deliver any queued events signed with key A
Note over O,RA: Wait for old signers to stop and old-key deliveries to drain
O->>TL: Retire key A
Verification
go test -race -count=1 ./...passed at the reviewed commit.- The repository’s pinned
golangci-lintv2.11.4 reported zero new issues against the PR base. - A separate local check changed the receipt signer while reusing the SQLite cache at the same tree size. The service returned the original receipt, which verified only with the previous public key. This check used local signing keys.
- A local Go SDK check supplied two verification lines in a simulated
/root-keysresponse. A fresh key store verified a receipt signed by A and a status token signed by B in either line order. Supplying only B caused verification of the saved receipt to fail.
With public reads enabled, the TL puts the error from a failed signing call into the detail of the HTTP 500 response on the receipt and status-token routes. When AWS KMS rejects the call, that error holds the AWS message, which can name the account, the IAM role, and the key ARN, so an anonymous caller could read them. The adapter is the only code that knows the AWS error format, so the fix belongs here and not in the TL handlers. Translating provider errors at the port boundary also protects every other caller of the KeyManager the same way. - Returned errors carry only the AWS error code, such as "kms sign: AccessDeniedException". The code still tells a missing permission apart from a disabled key or throttling, and the adapter already logs the full error at ERROR, so operators keep the detail. - NotFoundException still wraps ErrKeyNotFound, the sentinel FileKeyManager also returns, and context cancellation and deadline errors stay matchable with errors.Is, so a timeout can be told apart from a KMS rejection. - The tests cover every exception type in the KMS types package plus access denied, throttling, exhausted retries, context errors, and transport errors, for DescribeKey, GetPublicKey, and Sign. Each case compares the full returned error, so any text beyond the expected code fails the test, without relying on a list of known identifiers. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
The TL signs checkpoints with context.Background() and signs each appended event while holding its single-writer gate. The RA signs revocation events inside its single-connection SQLite transaction. None of these contexts carries a deadline, so an AWS KMS call that never answers stalls checkpoint publication (new receipts stay at 503), blocks every TL append behind the gate, and holds the RA's only database connection. With the KMS endpoint unreachable, a TL built from the previous commit was still waiting after 30 seconds; with this change it gave up after the configured 2 seconds. - Every KMS call runs under context.WithTimeout, derived from the caller's context and cancelled when the call returns, so nothing is shared between calls. The limit covers the SDK's retries and defaults to 10s, which leaves room for retries on a call that normally answers in milliseconds. A shorter deadline from the caller still wins. - A timed-out call fails before anything is committed: the TL appends to the log only after signing, Tessera retries checkpoint publication on its next interval, and the RA rolls back the transaction. Every caller can retry the operation. - keys.aws-kms.timeout sets the limit and must not be negative. The commands pass it only when it is positive, as they do for the vLEI verifier's present-timeout. - The limit lives in the adapter rather than in the TL and RA callers, so their signing paths stay unchanged. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
EnsureKey checked the key with DescribeKey and GetPublicKey only, so a role without kms:Sign passed the startup check. The TL then exited on its first checkpoint signature, but the RA has nothing to sign at startup: it answered its readiness probe with HTTP 200 and would accept registrations that could only fail at activation. With kms:Sign removed from the role, an RA built from the previous commit reported ready. - EnsureKey ends with a Sign request that sets DryRun. KMS answers a permitted DryRun with DryRunOperationException and signs nothing, so that answer counts as success; any other error fails EnsureKey and both services stop at startup. - The DryRun request goes to the pinned key ARN with the same digest type and algorithm as real signatures, so it checks the permission that Sign will need. It uses the per-call timeout, and its errors carry only the AWS error code, like the other KMS calls. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
DescribeKey, GetPublicKey, Sign, and the DryRun permission check each repeated the same steps: run under the per-call timeout, log the full AWS error, and return an error that carries only the AWS error code. Repeating them by hand made it possible for a new KMS call to skip the timeout or return the raw AWS message, which is the leak the error translation exists to prevent. - callKMS holds those steps in one place, and each call site keeps only the request it sends. EnsureKey still lists its checks in order, because each step uses what the previous one returned. - Failures log one message, "KMS call failed", with an op field naming the call, instead of a different message per call. - Behavior is unchanged; the existing tests pass with only the two log assertions updated for the new message. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
The README called remapping a key ID a key rotation. For the TL key that does not hold: the TL publishes only its current key at /root-keys, so receipts signed before the change no longer verify. The sentence is removed. How the TL should keep old keys verifiable is a question for the TL rather than this adapter. The TL also seeds producerKeys only for key IDs it does not already store. Replacing the RA key under the same ID left the old public key in place, and the TL rejected the next RA event with 422 "signature does not verify". - The README gives the RA rollout under a new key ID: register the new public key, switch signer.keyId, keep the old key until queued events are delivered, then revoke it. The steps were followed against AWS KMS with two RA keys. - It keeps the note that a changed key or a re-pointed alias takes effect on the next restart, since the adapter resolves an alias to its key ARN at startup. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
|
Thanks for the thorough review. A few of these I should have caught myself 😅 I kept every change inside the adapter. Items 1 and 3 could also affect the TL and the RA outside the adapter, so I left them out of this PR and would like to discuss them first.
AS-IS / TO-BEAS-IS sequenceDiagram
participant C as Caller
participant TL as TL
participant KM as KMS adapter
participant K as AWS KMS
C->>TL: GET status-token
TL->>KM: Sign
KM->>K: Sign
K-->>KM: AccessDenied (account, role, ARN)
rect rgba(207, 34, 46, 0.16)
KM-->>TL: Full AWS message
TL-->>C: 500 detail with account, role, ARN
end
TO-BE sequenceDiagram
participant C as Caller
participant TL as TL
participant KM as KMS adapter
participant K as AWS KMS
C->>TL: GET status-token
TL->>KM: Sign
KM->>K: Sign
K-->>KM: AccessDenied (account, role, ARN)
rect rgba(46, 160, 67, 0.18)
Note over KM: Detail stays in the operator log, not sent to callers
KM-->>TL: keymanager: ans-tl-attestation: kms sign: AccessDeniedException
TL-->>C: 500 detail: call path, key ID, error code
Note over C: No account, role, or ARN
end
AS-IS / TO-BEAS-IS sequenceDiagram
participant R as Revocation
participant DB as SQLite connection
participant K as AWS KMS
R->>DB: Begin transaction
R->>K: Sign outbox event
Note over K: No answer
rect rgba(207, 34, 46, 0.16)
Note over DB: Held with no limit
end
TO-BE (this PR) sequenceDiagram
participant R as Revocation
participant DB as SQLite connection
participant K as AWS KMS
R->>DB: Begin transaction
R->>K: Sign outbox event (via adapter, with deadline)
Note over K: No answer
rect rgba(46, 160, 67, 0.18)
Note over R: Adapter stops waiting at the deadline
R->>DB: Roll back and release
end
AS-IS / TO-BEAS-IS sequenceDiagram
participant S as Checkpoint signer
participant K as AWS KMS
S->>K: Sign (context.Background)
Note over K: No answer
rect rgba(207, 34, 46, 0.16)
Note over S: Waits, so no new checkpoint and receipts stay 503
end
TO-BE sequenceDiagram
participant S as Checkpoint signer
participant K as AWS KMS
S->>K: Sign (via adapter, with deadline)
Note over K: No answer
rect rgba(46, 160, 67, 0.18)
Note over S: Adapter stops waiting at the deadline
Note over S: Tessera retries on the next interval
end
AS-IS / TO-BEAS-IS sequenceDiagram
participant RA as RA startup
participant K as AWS KMS
RA->>K: DescribeKey
K-->>RA: OK
RA->>K: GetPublicKey
K-->>RA: OK
rect rgba(207, 34, 46, 0.16)
Note over RA: Ready (200), fails later at activation
end
TO-BE sequenceDiagram
participant RA as RA startup
participant K as AWS KMS
RA->>K: DescribeKey, GetPublicKey
K-->>RA: OK
rect rgba(46, 160, 67, 0.18)
RA->>K: Sign (DryRun)
K-->>RA: AccessDenied
Note over RA: Startup fails
end
Needs discussionThe changes below sit in the TL and the RA, outside the adapter, so I left them out of this PR. How would you like them handled?
|
callKMS logged every failed KMS call at ERROR, including calls whose context the caller canceled. The TL signs status tokens with the request context, so a client that disconnects mid-request, or a shutdown, wrote an ERROR line for an expected cancellation, and a busy TL could fill its error log with them. - A failure caused by context.Canceled is logged at DEBUG. Other failures, including a deadline that the timeout set, stay at ERROR because they point at KMS or its configuration. - The returned error does not change. Signed-off-by: Ho Geun Choi <ohyes9711@gmail.com>
Related issue
#164
Summary
Adds
keys.type: aws-kms, aport.KeyManageradapter that lets the TL and RA sign with existing AWS KMS keys.AWSKMSKeyManagermaps each key ID (ans-tl-attestation,ans-ra-signer) to a KMS key ID, ARN, or alias. The key ID remains the published name, so the RA's event JWSkiddoes not change and no KMS reference appears in signed output.EnsureKeychecks that the key is an enabledECC_NIST_P256key withSIGN_VERIFYusage and never creates one.CreateKeyreturnsErrUnsupportedOperation.EnsureKeyalso pins the key ID to the key ARN that KMS resolves. The TL and RA read their public key once at startup, so the service keeps signing with the key it published, and a re-pointed alias takes effect on the next restart.Signsends the SHA-256 digest withMessageType=DIGESTand returns the DER signature, the same format asFileKeyManager. The public key is read once, andVerifychecks signatures against it without calling KMS.kms:DescribeKey,kms:GetPublicKey,kms:Sign) and how to export the RA public key for the TL'sproducerKeys.internal/port,internal/ra, andinternal/tlare unchanged.The commits are split by area (config, adapter, cmd wiring, docs), and each one builds and passes its tests on its own.
Points to check
EnsureKeyis not part ofport.KeyManager, so eachmain.godeclares a small unexported interface that adds it. Moving it into the port would also require updating ten test fakes underinternal/, so I left the port unchanged. I can move it if you prefer.If I missed anything, or if something should be added or improved, please let me know.
Testing
Tested against live AWS KMS with
ECC_NIST_P256/SIGN_VERIFYkeys behind aliases, one for the TL and one for the RA:scripts/demo/start.shwith both services switched tokeys.type: aws-kms(a local copy; the script is not changed in this PR).scripts/demo/run-lifecycle.shcompleted every step, including the SCITT receipt andans-verify./root-keyspublishes the same SubjectPublicKeyInfo that KMSGetPublicKeyreturns for the TL key.kid: ans-ra-signer. No KMS ARN or alias appears in the TL events, receipts, or/root-keys.kms:DescribeKeyorkms:GetPublicKey, startup failed inEnsureKeywithAccessDeniedException. Withoutkms:Sign, the startup check passed, but the TL exited when it signed its first checkpoint./root-keysdid not change. Without the ARN pin, the same run failed atans-verifywithno key verified the receipt. After a restart, the TL used the new key, and/root-keysmatched it.make test-coverpasses (internal 90.34%, adapter package 93.0%), andgo test -raceis clean.AI assistance
Assisted-by: Claude Code (claude-opus-5-5)
Checklist
git commit -s) certifying the DCO