RFC-0031: Security Audit of the v4 Product Branch

  • Status: Proposed; amends the open rule of RFC-0011.

  • Owner: Security owner.

  • Last updated: 2026-11-30

Scope and method

The audit covered every runtime module of src/cryptography_suite, the five provider distributions, the JavaScript reader and sealer, the CLI, the CI workflows, and the dependencies, at commit 18211e6. It used five methods:

  • Adversarial review. Every parser of attacker-controlled input, every key-selection decision, and every trust boundary, read line by line.

  • Dependency audit. pip-audit over the installed dependency set. It found no known vulnerabilities.

  • Supply-chain review.

    • Every workflow action is pinned to a full commit SHA.

    • Permissions are declared per job, with write scopes and OIDC only for the release and documentation jobs.

    • No workflow uses pull_request_target or interpolates event text into scripts.

  • Secret scan. The tree and the full history held no credentials, only PEM markers and dummy test inputs.

  • Mutation testing. An AST harness (it lives outside the repository) deletes each guard that raises, moves each bound comparison by one, and replaces each compare_digest with True in the security-critical modules. It counts the mutants the module’s tests fail to detect.

Findings

ID

Severity

Finding

Fix

F-1

High

Opening tried any recipient of a configured provider, with the key the envelope named.

Trusted keys only, below.

F-2

High

AWS KMS decrypted with the recipient’s version, not its key_id. Google Cloud KMS decapsulated with a version it never checked against key_id.

Key chosen by key_id; a mismatched version is refused.

F-3

Medium

Vault Transit key names reached request paths unescaped.

Vault’s own name grammar enforced.

F-4

Medium

One dishonest custodian could block a distributed recovery, unidentified.

Robust reconstruction and blame.

F-5

Low

One envelope could repeat a recipient to multiply key-service calls.

Each key version asked once.

F-6

Low

The CLI printed unauthenticated envelope text raw.

Non-printing characters escaped.

F-7

Info

The JavaScript reader leaves key trust to the unwrap callback.

Documented, with an example.

F-9

Medium

Google Cloud KMS calls used the client library’s default retry (60 seconds per call) and, for decapsulate, no timeout at all. They outlived provider_timeout_ms and multiplied the policy’s retries.

No library retry; each call gets the time left.

F-10

Medium

Azure Key Vault calls used the SDK’s default retry policy (ten retries, backoff up to two minutes each, a seven-day overall timeout) unless the caller had configured otherwise.

No SDK retry; per-call timeouts from the deadline.

F-11

High (availability)

With the real Azure SDK on Python 3.11 and later, describe_key found no wrap capability, so sealing to Azure always failed.

Enum members are read by value.

F-8

Medium

Checksummed vectors were checked out with CRLF on Windows (core.autocrlf), breaking their checksum. This was a regression from the COSE-HPKE commit.

.gitattributes.

F-12

Medium

The AWS package advised retries={"max_attempts": 1}, which botocore reads as one retry: two attempts per call, so throttling doubled the policy’s attempts (botocore’s default made it three). Missing credentials were reported as an unavailable service.

A client that would retry is refused; credential failures are PROVIDER_AUTH_FAILED.

F-1: an envelope under the attacker’s key opened as authentic

Envelope encryption without signatures is authentic because only a holder of a wrapping key can make a recipient that opens. That holds only if the reader decides which wrapping keys count.

Protector sent every recipient of a configured provider to that provider, and the cloud providers asked their service for the key the recipient named. A key service decrypts with any key the caller’s credentials can use. This includes a key in another account whose key policy grants the reader decrypt, which its owner can grant alone, and another tenant’s key in a shared service or branch store.

So whoever controls such a key could seal any plaintext, under any context they know, and the reader would return it as verified. The KMS calls would also land in the attacker’s audit log. The same holds for hierarchical branch keys and HPKE identities held by one provider for several tenants. This is the problem AWS Encryption SDK’s strict mode addresses.

Decision. open, open_stream, open_range, rewrap, and rewrap_stream unwrap only recipients that name a trusted key. The trusted keys are the recipient keys (primary_key, additional_keys) and the new decryption_keys, at most 256, distinct, each of a configured provider.

A recipient matches a trusted key when the provider is the same, its key_id equals the trusted key’s key_id or that key’s canonical identifier, and a version, if pinned, is equal. The canonical identifier is the one describe_key returns, such as the ARN an AWS alias names. It is resolved only when some recipient matches nothing literally, and is cached for five minutes. A resolution failure is reported only if no other trusted recipient opens. A recipient naming any other key is never sent to a provider, and opening fails with KEY_NOT_FOUND when none is trusted.

The CLI trusts every key its configuration names. The conformance reader trusts every key its corpus publishes, and all 248 outcomes are unchanged.

F-2: the key used must be the key the key_id names

Trust is checked on key_id, so a provider must use the key that key_id names:

  • AWS. The AWS provider passed version (an ARN) as KeyId. A recipient with the trusted ARN as key_id and the attacker’s ARN as version defeated F-1’s check. Both fields are the key ARN by construction, so a recipient whose fields differ is refused before KMS is called, and Decrypt uses key_id.

  • Google Cloud. The provider’s KEM path decapsulated with version. The version must now be a numeric version of key_id (<key>/cryptoKeyVersions/<n>); the same rule applies in describe_key.

  • Azure and Vault. Azure selects by key_id within the configured vault, and Vault by name within the mount. The HPKE, quorum, and hierarchical providers hold only registered keys.

F-3: Vault key names in request paths

hvac formats /v1/{mount}/decrypt/{name} with urllib.parse.quote. That call leaves / and .. intact, and urllib3 then removes the dot segments. A name such as ../../other-mount/decrypt/k therefore reached another mount or API with the reader’s token. F-1 already keeps such names away from the provider. As defence in depth, the provider now refuses any name outside Vault’s grammar for Transit names (\w(?:[\w.@-]*\w)?, ASCII) with KEY_NOT_FOUND, without calling hvac, in describe_key, wrap, unwrap, and for health_key. The Azure SDK rejects such names itself, which was tested.

F-4: a dishonest custodian blocked recovery

A custodian decrypts their own share and re-encrypts it to the ceremony. A dishonest one can therefore return anything. The integrity tag caught a wrong reconstruction, but recovery always combined the first releases it held. One bad release blocked recovery for good, whatever other releases arrived, and nobody learned whose it was.

Shares decrypted by local identities are authenticated by their HPKE binding. So recovery now:

  1. combines the local shares with each combination of released shares (at most C(16, 8) = 12,870), skipping any release of the wrong length, until the tag verifies;

  2. evaluates the recovered polynomial at every other released share’s point;

  3. discards each release that does not lie on that polynomial and lists its request (with the custodian’s key fingerprint) in RecoveryCeremony.rejected.

With threshold honest releases among those received, recovery succeeds.

F-9: Google Cloud KMS calls outlived the policy deadline

Testing the provider through the real google-cloud-kms client exposed default call settings that the in-memory fakes could not show. encrypt, decrypt, and the get_* calls retry by default for up to 60 seconds, with a 60-second timeout; decapsulate has no default timeout at all. Because the provider called the client without arguments, three things followed:

  • Its calls ignored the operation’s deadline.

  • The library’s retries multiplied the policy’s bounded attempts, so provider_max_attempts=5 could mean five minutes.

  • A stuck Decapsulate could hang an open indefinitely.

Decision. Every call passes retry=None and a timeout of the seconds left before the ProviderRequest deadline (60 without one). A request whose deadline has passed is not sent; it fails with a retryable PROVIDER_TIMEOUT.

tests/provider_packages/test_gcp_kms_client.py drives the provider through the real client, whose method table carries the library’s real defaults, over an in-process transport. Requests are the official proto types, and responses are real protos with real enums and wrappers. Seven of its tests fail on the previous code and pass now.

Azure’s SDK takes retry and timeout options per call, which F-10 below uses. boto3 and hvac take them only on the client; see the residual risks.

F-10 and F-11: the Azure provider against the real SDK

tests/provider_packages/test_azure_keyvault_client.py drives the provider through the real KeyClient and CryptographyClient. Calls go through azure-core’s real pipeline (Key Vault challenge authentication, RetryPolicy, RequestsTransport) down to a requests adapter, which answers the Key Vault REST API in process with real RSA-OAEP-256.

  • F-11. The provider read key operations and key types with str(). The SDK’s KeyOperation and KeyType are str enums, and from Python 3.11 str(KeyOperation.wrap_key) is "KeyOperation.wrap_key", not "wrapKey". With the real SDK, every Azure key therefore described without wrap capability, and sealing to Azure failed on every supported Python version. The fakes returned plain strings and never showed it. Enum members are now read by value.

  • F-10. Unless the caller had configured otherwise, the SDK’s default RetryPolicy (ten retries, backoff of up to two minutes, a seven-day overall timeout) stacked on the policy’s retries. The provider now passes retry_total=0 and connection and read timeouts of the time left on every call, and a passed deadline is not sent.

On the previous code, all ten of the file’s tests fail. With only F-11’s fix applied, the four that cover F-10 still fail: hidden retries swallowed 503 and 504, and an expired deadline was sent.

F-12: the AWS provider against the real SDK

tests/provider_packages/test_aws_kms_client.py drives the provider through a real boto3 KMS client. botocore validates each request against the KMS service model, serializes it, signs it with SigV4, runs its retry handler, and parses every response and error document; an in-process KMS answers at the before-send hook.

  • Stacked retries. botocore’s max_attempts counts retries, not attempts, and normalizes {"max_attempts": 1} to two total attempts. With the configuration the package recommended, a throttled seal under the default policy sent six requests instead of three; with botocore’s defaults, nine. The provider now reads the client’s effective retry configuration and refuses any client that makes more than one attempt per call, naming {"total_max_attempts": 1}. Clients that are not botocore clients, such as test doubles, are not checked.

  • Credentials. botocore raises NoCredentialsError and its relatives before any request is sent. They were reported as PROVIDER_UNAVAILABLE and are now PROVIDER_AUTH_FAILED, not retryable.

On the previous code, five of the file’s tests fail: the four client configurations that retry are accepted, and missing credentials are reported as unavailable. The other tests confirm, through the real client, F-1 (a key the reader’s credentials can use but does not trust receives no Decrypt), F-2 (Decrypt is pinned to the recorded key ARN), the binding, the error mapping of every KMS error document, escrow fallback for a disabled key, grant tokens, and the health check.

F-5 to F-8

  • F-5. An envelope may carry 32 recipients that all name one trusted key. Each key version (provider, key, version) is now tried at most once.

  • F-6. inspect text output printed the envelope’s policy_id raw. The format rejects C0 controls, but C1 controls such as CSI (U+009B) and bidirectional overrides such as U+202E could reach the terminal. They are now escaped.

  • F-7. The JavaScript README now shows unwrap skipping untrusted keyIds and explains why.

  • F-8. tests/vectors/** and conformance/** are -text, so no checkout rewrites their bytes. A contract test pins the rule.

Components reviewed without findings

  • Suite 1. An HKDF-SHA-512 schedule, a 256-bit key commitment, STREAM nonces, and AAD with the final flag.

  • The envelope parser. Every length is checked before it is read, and the protected preamble is bound.

  • Range-read truncation. A record boundary moved by truncation fails authentication as a final record.

  • The audit chain.

    • Records must be canonical JSON without duplicate keys.

    • Each signature has one valid base64url spelling.

    • The verifying key’s type fixes the schema, and checkpoints detect truncation.

  • The canonical context encoding.

  • Retry classification and deadlines.

  • The filesystem sink.

    • Operations are relative to a directory descriptor, with O_NOFOLLOW on each component.

    • Temporaries are created with O_EXCL and mode 0600 from the start.

    • Commits use no-replace links, and Windows reparse points are rejected.

  • The CLI’s secret handling. Secrets come only from a descriptor or stdin, never from argv or the environment.

  • The JavaScript reader. Its comparisons are constant-time.

  • COSE-HPKE. Covered by RFC-0030’s vectors, differential tests, and mutation run.

Mutation testing

The harness made 425 mutants in twelve modules. The first run, on 18211e6, was stopped after 95 so the rest could run on the fixed code; killed mutants of unchanged files were carried over, and survivors were run again once the gaps were closed.

Module

Mutants

Detected

Equivalent

envelope/codec.py

78

74

4

envelope/suites.py

10

10

0

_internal/cbor.py

34

31

3

protector.py

86

78

8

context.py

7

6

1

cose/__init__.py

57

54

3

cose/_hpke.py

8

6

2

cose/_cbor.py

18

16

2

providers/hpke.py

22

12

10

providers/quorum.py

54

45

9

providers/hierarchical.py

32

30

2

audit/chain.py

19

15

4

Total

425

377 (88.7%)

48

Every survivor was read against the code, and each one closed a test gap or is equivalent.

  • Test gaps, now closed (70 mutants). The new tests are in tests/unit/test_codec_boundaries.py, tests/integration/test_policy_limits_exact.py, and additions to the COSE, context, hierarchical, quorum, and trusted-key tests.

    • Every parser and policy limit at its exact value and one past it.

    • Canonical CBOR widths at each boundary.

    • A header without label 7, and an envelope with no records.

    • A range read at exactly the end of a truncated envelope, which must not pass as “no more data”.

    • An exact alias-cache expiry.

    • COSE: kty true with an OKP curve, alg 35.0, an EC2 key with x and d but no y, and integers passed as data.

    • An empty context key.

    • Released shares of 1 and 8,192 bytes, and padded ceremony messages.

    • Hierarchical construction bounds and an exactly full cache.

  • Equivalent (48). Each check is redundant: deleting it or moving its bound changes no outcome, because the same input is refused next, with the same error type and code.

    • Strict CBOR decoder. Its container-length and _take guards are backed by the end-of-input check. The COSE decoder’s are backed the same way.

    • Envelope parser. header_length == 0 is backed by the empty-CBOR failure, and the map-type checks by the label checks that follow.

    • Argument checks. In Protector, bytes and len raise TypeError themselves.

    • Key encodings. HPKE validates them in pyca/cryptography.

    • Quorum bodies. The integrity tag covers the whole wrapped quorum body, so its header and length checks never decide alone.

    • Audit chain. ML-DSA rejects an empty signature, and canonical re-encoding rejects duplicate keys.

    • Text and PEM size bounds. In the HPKE provider, their exact values cannot be valid input.

    • Comparisons whose equal case cannot occur.

    These checks are kept on purpose: they fail early, bound work before allocation, and give the specific error.

Provider distributions

A second run applied the same operators to the five provider distributions, with each package’s tests, including the real-SDK tests.

Package

Mutants

Detected

Equivalent

cryptography-suite-aws-kms

14

14

0

cryptography-suite-gcp-kms

20

19

1

cryptography-suite-azure-keyvault

16

16

0

cryptography-suite-hashicorp-vault

18

18

0

cryptography-suite-opentelemetry

7

7

0

Total

75

74

1

The first pass left nine survivors. Eight were test gaps, all at an exact boundary, now closed in tests/provider_packages/test_provider_boundaries.py:

  • a deadline reached exactly, refused before the SDK is called (Google Cloud, Azure);

  • a KEM ciphertext no longer than its encapsulation, refused without a Decapsulate call (Google Cloud);

  • an Azure key version that expires, or becomes valid, at the current instant;

  • both bounds of the OpenTelemetry sink’s queue.

The equivalent mutant extends the HKDF-Expand loop of the Google Cloud KEM key schedule by one block, which the truncation that follows discards.

Test and validation requirements

Test file

Covers

tests/integration/test_trusted_keys.py

F-1 and F-5 on every opening path: an envelope under an untrusted key never reaches the provider; untrusted recipients are skipped; version pinning; alias resolution, caching, expiry, and re-pointing; resolution failures; descriptions for another provider; argument validation; one attempt per key version.

tests/provider_packages/test_aws_kms.py

F-1 and F-2 for AWS.

tests/provider_packages/test_gcp_kms_post_quantum.py

F-2 for Google Cloud.

tests/provider_packages/test_hashicorp_vault.py

F-3.

tests/integration/test_quorum_ceremony.py

F-4.

tests/cli/test_cli.py

F-6.

tests/contract/test_trust_claims.py

F-8.

tests/provider_packages/test_gcp_kms_client.py

F-9, and the Google Cloud provider through the real client.

tests/provider_packages/test_azure_keyvault_client.py

F-10, F-11, and the Azure provider through the real SDK pipeline.

tests/provider_packages/test_aws_kms_client.py

F-12, and the AWS provider through the real boto3 client.

tests/unit/test_codec_boundaries.py, tests/integration/test_policy_limits_exact.py

Mutation-testing gaps.

tests/provider_packages/test_provider_boundaries.py

Mutation-testing gaps in the provider distributions.

Each finding’s regression test fails on 18211e6 and passes after the fix; this was verified by running the tests against that commit. The suite stays at 100% line and branch coverage. The COSE decoders survived about 1.7 million fuzzed calls (288,000 inputs, six decoders each), and the envelope reading paths 165,000 (27,500 corrupted envelopes, six paths each), with no exception outside the typed errors.

Residual risks and recommendations

  • Alias re-pointing. After an alias is re-pointed, envelopes under its old key open through the alias only until the five-minute cache expires. List retired keys in decryption_keys before re-pointing.

  • No sender authentication. Base-mode HPKE recipients, including COSE-HPKE and escrow, authenticate the recipient, not the sender: anyone holding the public key can seal to it. When the origin matters, sign the envelope or keep the HPKE recipient as escrow next to a KMS primary.

  • Per-client timeouts (AWS, Vault). boto3 and hvac take timeouts only when the client is built, so the policy’s deadline is checked between attempts but cannot cut a call in flight short. botocore defaults to 60 seconds to connect and 60 to read, and hvac to 30. Both packages’ READMEs build the client with timeouts well inside the default and enterprise deadline of 30 seconds; the AWS provider also enforces a single attempt (F-12).

  • No independent audit yet. An external audit of the format, the suite, and these providers remains the release gate for 4.0.0.