Skip to content

feat(kms): decode EncryptionContext, and refuse a ciphertext that disagrees (#979) - #990

Merged
scttfrdmn merged 1 commit into
mainfrom
feat/kms-encryption-context
Sep 17, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
feat/kms-encryption-context

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

Closes #979.

Encrypt, Decrypt, both GenerateDataKey* operations and both ends of ReEncrypt take an encryption context. Substrate decoded none of the six members, so a context was accepted and lost, and the refusal AWS publishes for a mismatch could not be reached. API_Encrypt states the rule as a consequence rather than a footnote:

If you specify an EncryptionContext when encrypting data, you must specify the same encryption context (a case-sensitive exact match) when decrypting the data. Otherwise, the request to decrypt fails with an InvalidCiphertextException.

An application that encrypts under {"tenant": "acme"} and decrypts without it is broken in production and passed here. That is the whole of the issue.

The format change, and why it is JSON

The stub ciphertext was base64("kms:{keyID}:" + base64(plaintext)) — enough for Decrypt to find its key and nothing else. It is now a base64-wrapped JSON envelope carrying the key ID, the encryption algorithm, the encryption context and the plaintext, behind a format marker.

JSON rather than a delimited string is a correctness requirement, not a preference. An encryption context is caller-supplied text, so a key or a value may contain any delimiter. A delimited format needs escaping, and an escaping bug produces a ciphertext that decrypts to the wrong context — the exact failure this feature exists to detect. json.Marshal also sorts map keys, so the blob is deterministic without a canonicalization pass of substrate's own; a test asserts that two Encrypt calls whose contexts differ only in JSON key order return byte-identical ciphertext, because a blob varying with the caller's ordering could not be replayed.

The marker is a version string rather than a bare tag, so a blob from the previous format fails to decode rather than being read with the wrong field meanings. A test walks five foreign blobs — not base64, base64 but not JSON, JSON without the marker, the pre-#979 format, and an envelope naming no key — and all five answer InvalidCiphertextException/400.

Two refusals, and which half of each is published

Request Substrate answers Provenance
The context matches exactly 200, plaintext round-trips Published
An empty context against an absent one, either direction 200 Substrate's reading — AWS documents no way to tell {} from an omitted member
The contexts differ in any key, value or case InvalidCiphertextException/400 Published end to end: the code by API_Encrypt's sentence, the condition by the code's own gloss ("…such as the encryption context, is corrupted, missing, or otherwise invalid")
The algorithm is not the one that encrypted the data InvalidCiphertextException/400 The behaviour is published ("if you specify a different algorithm, the Decrypt operation fails"); the code is substrate's reading, resting on "or otherwise invalid"

Eight mismatch shapes are walked, including the two the issue names — recorded-and-none-supplied, and none-recorded-and-one-supplied. Neither is a special case in the code (maps.Equal answers both), which is exactly why both are asserted: an implementation comparing only the keys it was given passes the value rows and fails these two.

The algorithm is checked before the context, and both after the named-key, key-usage, key-state and key-spec checks. AWS orders none of it, so both orderings are recorded as substrate's: the algorithm is what a real implementation needs to attempt a decryption at all, and an algorithm the key does not admit is a fact about the key, knowable without holding the ciphertext, where a mismatch is a fact about these particular bytes. IncorrectKeyException is the near miss for both and is wrong for both — it is about the key the caller named, which checkNamedKeyMatches already answers.

Both messages render both contexts, which is licensed rather than assumed: the member's gloss is "a collection of non-secret key-value pairs", and API_GenerateDataKey adds "do not include confidential or sensitive information in this field. This field may be displayed in plaintext in CloudTrail logs and other output." A refusal a caller cannot act on is not worth answering.

The asymmetric split is AWS's, in two different directions

The context is recorded only under a symmetric encryption key. API_ReEncrypt is decisive: "a destination encryption context is valid only when the destination KMS key is a symmetric encryption KMS key. The standard ciphertext format for asymmetric KMS keys does not include fields for metadata." An asymmetric ciphertext has nowhere to hold one and AWS publishes no code for sending one, so recording it would invent a refusal AWS cannot produce. Substrate accepts the member and ignores it — #827's honest reading — and the test for it asserts the opposite shape from every other one here: two different contexts across an Encrypt and a Decrypt under an RSA key must succeed. A later change that recorded the context unconditionally fails exactly that and nothing else.

The algorithm is recorded for every key regardless, although AWS's asymmetric format holds no metadata either. AWS reaches the same observable answer cryptographically — decrypting RSA ciphertext with the wrong OAEP hash fails — and substrate models the observation, not the mechanism. That is the scope rule applied rather than bent: the divergence is in bytes inside the blob, which no caller is entitled to read, and the agreement is in the answer, which every caller is. It is also the only way to reach the algorithm refusal at all, since SYMMETRIC_DEFAULT admits exactly one algorithm and so has nothing to disagree about.

ReEncrypt is where the two members are visibly different things

SourceEncryptionContext is matched against the incoming blob — "enter the same encryption context that was used to encrypt the ciphertext" — while DestinationEncryptionContext is written into the outgoing one. So a ReEncrypt is the call that changes a ciphertext's context, and one consequence is worth stating because nothing in AWS's text suggests otherwise: re-encrypting with no destination context strips the context rather than inheriting the source's. A caller relying on inheritance would find its data readable without the context it believed it had set, so a test pins it.

Both GenerateDataKey* operations record the context and neither publishes InvalidCiphertextException, which is consistent — the recording happens there and the refusal at Decrypt. The assertion is the only thing a caller can observe, since the data key is opaque: the wrapped key decrypts under the recorded context and is refused without it.

One shared matcher

Decrypt and ReEncrypt's source end go through one kmsCheckCiphertextMatchesRequest, on the #961/#969 precedent — those issues found one operation refusing nothing that its four siblings refused, which is what a per-site check invites. The member names differ between the two (EncryptionAlgorithm against SourceEncryptionAlgorithm) so they are passed in, following kmsResolveEncryptionAlgorithm.

kmsIsSymmetricEncryptionKey is a named predicate rather than an inline comparison because the condition is narrower than "not asymmetric" — the four HMAC_* specs are symmetric, hold key material and encrypt nothing. kmsReportsKeyMaterialID (#978) now routes through the same predicate, since it decides the identical question.

Recorded as still unmodelled

kms:EncryptionContext:<key> and kms:EncryptionContextKeys are not evaluated, so a key policy or grant constraining a context is accepted and has no effect on authorization. The published limits on a context's total size and on the reserved aws: key prefix are likewise unenforced. Both are stated in docs/services.md rather than left to be discovered.

Verification

The nine-command gate passes. Coverage holds the baseline at 84.4% emulator / 83.9% total. Every assertion goes over the wire (#765) and asserts the status alongside the code (#923).

Compatibility

A ciphertext written by an earlier release no longer decodes. Decrypt and ReEncrypt answer InvalidCiphertextException/400 for it rather than reading its fields under the new meanings. Any test holding a hard-coded substrate ciphertext, or one persisted across releases, must be regenerated by calling Encrypt again. A caller that sends an encryption context on encrypt and not on decrypt now gets the refusal AWS gives, where it previously got a 200.

…agrees (#979)

All six encryption-context members went undecoded, so a context was accepted
and lost and the refusal AWS publishes for a mismatch was unreachable.

The stub ciphertext becomes a base64-wrapped JSON envelope recording the key
ID, the encryption algorithm, the encryption context and the plaintext, behind
a format marker. Decrypt and ReEncrypt's source end now answer
InvalidCiphertextException/400 for a context that is not an exact
case-sensitive match, and for an encryption algorithm that the key admits but
which did not write those bytes. A context is recorded only under a symmetric
encryption key, because AWS's asymmetric ciphertext format holds no metadata.

This changes the ciphertext format: a blob from an earlier release no longer
decodes.
@scttfrdmn scttfrdmn added this to the v0.118.0 milestone Sep 17, 2026
@codecov

codecov Bot commented Sep 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.98990% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
emulator/kms_ciphertext.go 97.67% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn merged commit 7f7d25b into main Sep 17, 2026
17 checks passed
@scttfrdmn
scttfrdmn deleted the feat/kms-encryption-context branch September 17, 2026 06:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

kms: the stub ciphertext carries only a key ID, so an encryption-context or algorithm mismatch cannot answer InvalidCiphertextException

1 participant