From 688f03841bc1703db6cd51330c39573674c40193 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Tue, 20 Oct 2026 03:24:49 -0700 Subject: [PATCH 1/2] fix: Verifier: genuine non-Ed25519 receipts can never classify as unsupported (SEL-334) Linear: SEL-334 Refs https://github.com/agentmiddleware/agent-middleware/issues/124 Engine: codex (fleet coding engine, Grok Bot dispatch) --- gateway/app/routers/mcp_public.py | 2 +- gateway/docs/key-management.md | 6 +- gateway/failure_lab/verifier.py | 72 +++++++--- gateway/tests/test_failure_lab_verifier.py | 132 ++++++++++++++++++ sdk/python/src/b2a_sdk/edge_client.py | 5 +- sdk/python/src/b2a_sdk/receipt_verifier.py | 129 +++++++++++++---- .../tests/test_local_permit_validator.py | 17 +++ .../tests/test_receipt_verifier_signed.py | 86 ++++++++++++ sdk/typescript/src/verify.ts | 98 +++++++++++-- sdk/typescript/test/verify.test.ts | 75 +++++++++- spec/key-set-v0.1.md | 14 +- spec/receipt-v0.1.md | 9 +- spec/test-vectors/README.md | 2 +- spec/test-vectors/generate.py | 47 ++++++- spec/test-vectors/receipts.json | 46 +++++- spec/test-vectors/test_contract.py | 2 + spec/test-vectors/test_generate.py | 2 + 17 files changed, 670 insertions(+), 74 deletions(-) diff --git a/gateway/app/routers/mcp_public.py b/gateway/app/routers/mcp_public.py index d5d8cad1a..a588fa7f9 100644 --- a/gateway/app/routers/mcp_public.py +++ b/gateway/app/routers/mcp_public.py @@ -384,7 +384,7 @@ def _mcp_error(code: int, message: str) -> McpError: return McpError(mcp_types.ErrorData(code=code, message=message)) -async def _published_key_set() -> dict[str, bytes] | None: +async def _published_key_set() -> dict[str, bytes | _receipt_verifier.VerificationKey] | None: """Load the same key set a verifier gets from trust-keys.json. ``None`` means "no usable keys right now" — the tool-level analogue of diff --git a/gateway/docs/key-management.md b/gateway/docs/key-management.md index 8d438f9b6..091474ef7 100644 --- a/gateway/docs/key-management.md +++ b/gateway/docs/key-management.md @@ -70,8 +70,10 @@ the choice is per-deployment. The receipt format does not change. `alg` stays `Ed25519` for Vault and GCP KMS. For AWS KMS until Ed25519 is native, the `alg` field becomes -`ECDSA-P256-SHA256` and verification code must accept both algorithms keyed -by the receipt's `alg` field. +`ECDSA-P256-SHA256`. Offline verifiers can check that algorithm using the +published key's `alg`, but receipt v0.1 still classifies a genuine P-256 +receipt as `unsupported`. Enabling that KMS signing path also requires an +explicit receipt-format policy update. ### Concrete code changes diff --git a/gateway/failure_lab/verifier.py b/gateway/failure_lab/verifier.py index d53648a05..15bcf181f 100644 --- a/gateway/failure_lab/verifier.py +++ b/gateway/failure_lab/verifier.py @@ -15,7 +15,7 @@ ---------------- ``SIGNATURE_VALID`` - The Ed25519 signature verifies over the exact ``signing_input`` bytes, + The signature verifies over the exact ``signing_input`` bytes, under the key named *inside* those signed bytes. This says the holder of that private key signed this statement. Nothing more. @@ -53,7 +53,9 @@ from enum import Enum from typing import Any -from cryptography.exceptions import InvalidSignature +from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey ED25519_RAW_LENGTH = 32 @@ -75,6 +77,11 @@ class KeySource(str, Enum): OUT_OF_BAND_PIN = "out_of_band_pin" +@dataclass(frozen=True) +class _P256Key: + public_key: ec.EllipticCurvePublicKey + + @dataclass(frozen=True) class Claim: name: str @@ -138,8 +145,8 @@ def _b64(value: Any, *, urlsafe: bool = False) -> bytes | None: return None -def parse_key_document(document: Any) -> dict[str, bytes]: - """Read ``/.well-known/trust-keys.json`` into ``{kid: raw_public_key}``. +def parse_key_document(document: Any) -> dict[str, bytes | _P256Key]: + """Read raw Ed25519 or DER SPKI P-256 keys from ``trust-keys.json``. Keys the issuing plane marks disabled are dropped: a revoked key must not keep validating receipts because a cached document still lists it. @@ -149,7 +156,7 @@ def parse_key_document(document: Any) -> dict[str, bytes]: entries = document.get("keys") if not isinstance(entries, list): raise ValueError("key document has no 'keys' list") - keys: dict[str, bytes] = {} + keys: dict[str, bytes | _P256Key] = {} for entry in entries: if not isinstance(entry, dict): continue @@ -158,6 +165,20 @@ def parse_key_document(document: Any) -> dict[str, bytes]: continue if entry.get("status") == "disabled": continue + if entry.get("alg") == "ECDSA-P256-SHA256": + der = _b64(entry.get("public_key_b64", "")) + if der is None: + continue + try: + public_key = serialization.load_der_public_key(der) + except (ValueError, UnsupportedAlgorithm): + continue + if not isinstance(public_key, ec.EllipticCurvePublicKey) or not isinstance( + public_key.curve, ec.SECP256R1 + ): + continue + keys[kid] = _P256Key(public_key) + continue if entry.get("alg") not in (None, "Ed25519"): continue raw = _b64(entry.get("public_key_b64", "")) @@ -215,7 +236,7 @@ def field_coverage(bundle: dict[str, Any]) -> dict[str, str]: def verify( bundle: Any, - keys: dict[str, bytes], + keys: dict[str, bytes | _P256Key], *, key_source: KeySource = KeySource.ISSUER_ORIGIN, expected_issuer: str | None = None, @@ -287,32 +308,45 @@ def fail(reason: str, *, key_id: str | None = None) -> VerificationReport: return fail("signed payload names no key", key_id=None) algorithm = payload.get("alg", "Ed25519") - if algorithm != "Ed25519": - return fail(f"unsupported signature algorithm {algorithm!r}", key_id=key_id) - signature = _b64(signature_b64) - if signature is None or len(signature) != ED25519_SIGNATURE_LENGTH: - return fail("signature is not a 64-byte Ed25519 signature", key_id=key_id) + if signature is None: + return fail("signature is not valid base64", key_id=key_id) - raw_key = keys.get(key_id) - if raw_key is None: + key = keys.get(key_id) + if key is None: return fail(f"no published key for kid {key_id!r}", key_id=key_id) - if len(raw_key) != ED25519_RAW_LENGTH: - return fail(f"key {key_id!r} is not a 32-byte Ed25519 key", key_id=key_id) try: - Ed25519PublicKey.from_public_bytes(raw_key).verify( - signature, signing_input.encode("utf-8") - ) + signing_bytes = signing_input.encode("utf-8") + if isinstance(key, _P256Key): + key_algorithm = "ECDSA-P256-SHA256" + key.public_key.verify(signature, signing_bytes, ec.ECDSA(hashes.SHA256())) + else: + key_algorithm = "Ed25519" + if len(signature) != ED25519_SIGNATURE_LENGTH: + return fail( + "signature is not a 64-byte Ed25519 signature", key_id=key_id + ) + if len(key) != ED25519_RAW_LENGTH: + return fail( + f"key {key_id!r} is not a 32-byte Ed25519 key", key_id=key_id + ) + Ed25519PublicKey.from_public_bytes(key).verify(signature, signing_bytes) except InvalidSignature: return fail("signature does not verify over signing_input", key_id=key_id) except (ValueError, UnicodeEncodeError) as exc: return fail(f"signature could not be checked: {exc}", key_id=key_id) + if algorithm != key_algorithm: + return fail( + f"signed algorithm {algorithm!r} does not match published key algorithm {key_algorithm!r}", + key_id=key_id, + ) + signature_claim = Claim( "SIGNATURE_VALID", ClaimStatus.ESTABLISHED, - f"Ed25519 signature verifies over signing_input under kid {key_id!r}", + f"{key_algorithm} signature verifies over signing_input under kid {key_id!r}", ) # Envelope/payload disagreement: the signature still verifies, so this is diff --git a/gateway/tests/test_failure_lab_verifier.py b/gateway/tests/test_failure_lab_verifier.py index 4a9208058..dcf3e846f 100644 --- a/gateway/tests/test_failure_lab_verifier.py +++ b/gateway/tests/test_failure_lab_verifier.py @@ -15,6 +15,8 @@ from pathlib import Path import pytest +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from failure_lab.verifier import ( @@ -29,6 +31,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] KEY_ID = "lab-test-ed25519" +P256_KEY_ID = "lab-test-p256" @pytest.fixture @@ -66,6 +69,135 @@ def signed_bundle() -> tuple[dict, dict[str, bytes]]: return bundle, {KEY_ID: raw_public} +@pytest.fixture +def p256_signed_bundle(): + private = ec.generate_private_key(ec.SECP256R1()) + public_der = private.public_key().public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + payload = { + "kid": P256_KEY_ID, + "alg": "ECDSA-P256-SHA256", + "receipt_id": "rcpt-p256", + } + signing_input = json.dumps(payload, sort_keys=True, separators=(",", ":")) + bundle = { + "kid": P256_KEY_ID, + "alg": "ECDSA-P256-SHA256", + "receipt_id": "rcpt-p256", + "signing_input": signing_input, + "signature": base64.b64encode( + private.sign(signing_input.encode(), ec.ECDSA(hashes.SHA256())) + ).decode(), + } + document = { + "keys": [ + { + "kid": P256_KEY_ID, + "alg": "ECDSA-P256-SHA256", + "status": "active", + "public_key_b64": base64.b64encode(public_der).decode(), + } + ] + } + return bundle, document, private + + +def test_genuine_p256_receipt_establishes_only_signature(p256_signed_bundle): + bundle, document, _ = p256_signed_bundle + report = verify(bundle, parse_key_document(document)) + + assert report.signature.status is ClaimStatus.ESTABLISHED + assert "ECDSA-P256-SHA256" in report.signature.reason + assert report.issuer_trust.status is ClaimStatus.NOT_ESTABLISHED + assert report.downstream_execution.status is ClaimStatus.NOT_ESTABLISHED + + +@pytest.mark.parametrize( + "signing_input", + [ + lambda text: text.replace("rcpt-p256", "rcpt-other"), + lambda text: text.replace("ECDSA-P256-SHA256", "Ed25519"), + ], +) +def test_p256_signed_byte_edit_fails_signature(p256_signed_bundle, signing_input): + bundle, document, _ = p256_signed_bundle + changed = {**bundle, "signing_input": signing_input(bundle["signing_input"])} + + report = verify(changed, parse_key_document(document)) + + assert report.signature.status is ClaimStatus.FAILED + assert report.signature.reason == "signature does not verify over signing_input" + + +def test_p256_invalid_signature_and_unknown_key_fail(p256_signed_bundle): + bundle, document, _ = p256_signed_bundle + keys = parse_key_document(document) + malformed_signature = { + **bundle, + "signature": base64.b64encode(b"\x30\x00").decode(), + } + + assert verify(malformed_signature, keys).signature.status is ClaimStatus.FAILED + assert verify(bundle, {}).signature.status is ClaimStatus.FAILED + + +def test_p256_signed_algorithm_must_match_published_key(p256_signed_bundle): + bundle, document, private = p256_signed_bundle + payload = json.loads(bundle["signing_input"]) + payload["alg"] = "Ed25519" + signing_input = json.dumps(payload, sort_keys=True, separators=(",", ":")) + mislabeled = { + **bundle, + "signing_input": signing_input, + "signature": base64.b64encode( + private.sign(signing_input.encode(), ec.ECDSA(hashes.SHA256())) + ).decode(), + } + + report = verify(mislabeled, parse_key_document(document)) + + assert report.signature.status is ClaimStatus.FAILED + assert "does not match published key algorithm" in report.signature.reason + + +def test_p256_key_document_rejects_disabled_wrong_curve_and_invalid_der( + p256_signed_bundle, +): + bundle, document, _ = p256_signed_bundle + valid = document["keys"][0] + wrong_curve = ( + ec.generate_private_key(ec.SECP384R1()) + .public_key() + .public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + ) + document = { + "keys": [ + {**valid, "kid": "disabled", "status": "disabled"}, + { + **valid, + "kid": "wrong-curve", + "public_key_b64": base64.b64encode(wrong_curve).decode(), + }, + { + **valid, + "kid": "invalid-der", + "public_key_b64": base64.b64encode(b"bad").decode(), + }, + valid, + ] + } + + keys = parse_key_document(document) + + assert set(keys) == {P256_KEY_ID} + assert verify(bundle, keys).signature.status is ClaimStatus.ESTABLISHED + + def test_verifier_imports_neither_the_app_nor_the_product_sdk(): """A verifier that shares code with the signer cannot catch a shared bug.""" probe = ( diff --git a/sdk/python/src/b2a_sdk/edge_client.py b/sdk/python/src/b2a_sdk/edge_client.py index a59bf6074..f32546d0c 100644 --- a/sdk/python/src/b2a_sdk/edge_client.py +++ b/sdk/python/src/b2a_sdk/edge_client.py @@ -54,6 +54,7 @@ from .errors import PermitDeniedError from .receipt_verifier import ( VerificationError, + VerificationKey, canonical_json, key_set_from_document, verify_ed25519, @@ -299,7 +300,7 @@ class LocalPermitValidator: session do not silently overrun the cached budget. """ - def __init__(self, permit: dict[str, Any], key_set: dict[str, bytes]) -> None: + def __init__(self, permit: dict[str, Any], key_set: dict[str, bytes | VerificationKey]) -> None: self._permit = dict(permit) self._key_set = dict(key_set) # Locally reserved credits and per-tool call counts, advanced by @@ -471,7 +472,7 @@ def verify_permit(self, permit: dict[str, Any] | None = None) -> bool: except (KeyError, TypeError, ValueError, ArithmeticError): return False raw_public_key = self._key_set.get(payload["kid"]) - if raw_public_key is None or len(raw_public_key) != 32: + if not isinstance(raw_public_key, bytes) or len(raw_public_key) != 32: return False if len(signature) != 64: return False diff --git a/sdk/python/src/b2a_sdk/receipt_verifier.py b/sdk/python/src/b2a_sdk/receipt_verifier.py index ff55b6c9d..3496e3f60 100644 --- a/sdk/python/src/b2a_sdk/receipt_verifier.py +++ b/sdk/python/src/b2a_sdk/receipt_verifier.py @@ -42,6 +42,7 @@ __all__ = [ "CANONICALIZATION", "VerificationError", + "VerificationKey", "VerificationResult", "VerificationStatus", "canonical_json", @@ -57,6 +58,7 @@ _ED25519_RAW_LEN = 32 _ED25519_SIGNATURE_LEN = 64 +_P256_ALGORITHM = "ECDSA-P256-SHA256" class VerificationStatus(str, Enum): @@ -84,6 +86,14 @@ class VerificationError(Exception): """Raised only for programming errors, never for a failed verification.""" +@dataclass(frozen=True) +class VerificationKey: + """A non-Ed25519 public key with its published signing algorithm.""" + + alg: str + public_key: bytes + + @dataclass(frozen=True) class VerificationResult: """Outcome of checking one receipt bundle.""" @@ -185,13 +195,12 @@ def _contains_invalid_unicode(value: Any) -> bool: return False -def key_set_from_document(document: Any) -> dict[str, bytes]: - """Extract usable Ed25519 public keys from a ``trust-keys.json`` document. +def key_set_from_document(document: Any) -> dict[str, bytes | VerificationKey]: + """Extract verification keys from a ``trust-keys.json`` document. - Accepts either the ``public_key_b64`` form or the JWK mirror. Keys the - issuing plane marks ``disabled`` are dropped, matching the plane's own - refusal to verify against them — a revoked key must not keep validating - receipts just because a cached copy of the document still lists it. + Ed25519 keys retain their legacy raw-byte representation. P-256 keys use + DER SubjectPublicKeyInfo bytes and retain their algorithm tag. Keys the + issuing plane marks ``disabled`` are dropped. """ if not isinstance(document, dict): raise VerificationError("key set document must be a JSON object") @@ -200,7 +209,7 @@ def key_set_from_document(document: Any) -> dict[str, bytes]: if not isinstance(entries, list): raise VerificationError("key set document has no 'keys' list") - keys: dict[str, bytes] = {} + keys: dict[str, bytes | VerificationKey] = {} for entry in entries: if not isinstance(entry, dict): continue @@ -209,7 +218,13 @@ def key_set_from_document(document: Any) -> dict[str, bytes]: continue if entry.get("status") == "disabled": continue - if entry.get("alg") not in (None, "Ed25519"): + alg = entry.get("alg") + if alg == _P256_ALGORITHM: + raw = _b64decode(entry.get("public_key_b64", "")) + # A published kid with unusable material is malformed, not absent. + keys[kid] = VerificationKey(alg, raw or b"") + continue + if alg not in (None, "Ed25519"): continue # Fall through to the JWK mirror whenever the raw form is absent, @@ -267,6 +282,55 @@ def _verify_ed25519_signature( return True +def _verify_p256_signature( + der_public_key: bytes, + signature: bytes, + signing_bytes: bytes, +) -> bool | None: + """Return None for malformed P-256 key/signature material.""" + try: + from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature + except ImportError as exc: # pragma: no cover - depends on install extras + raise VerificationError( + "P-256 verification requires the 'cryptography' package. " + 'Install it with: pip install "b2a-sdk[verify]"' + ) from exc + + try: + public_key = serialization.load_der_public_key(der_public_key) + decode_dss_signature(signature) + except (ValueError, UnsupportedAlgorithm): + return None + if not isinstance(public_key, ec.EllipticCurvePublicKey) or not isinstance( + public_key.curve, ec.SECP256R1 + ): + return None + try: + public_key.verify(signature, signing_bytes, ec.ECDSA(hashes.SHA256())) + except InvalidSignature: + return False + except Exception as exc: + raise VerificationError("P-256 verifier failed unexpectedly") from exc + return True + + +def _verify_signature_for_key( + key: bytes | VerificationKey, + signature: bytes, + signing_bytes: bytes, +) -> bool | None: + if isinstance(key, bytes): + if len(key) != _ED25519_RAW_LEN or len(signature) != _ED25519_SIGNATURE_LEN: + return None + return _verify_ed25519_signature(key, signature, signing_bytes) + if isinstance(key, VerificationKey) and key.alg == _P256_ALGORITHM: + return _verify_p256_signature(key.public_key, signature, signing_bytes) + return None + + def verify_ed25519( raw_public_key: bytes, signature: bytes, @@ -303,7 +367,7 @@ def _fail( def verify_bundle( bundle: Any, - key_set: dict[str, bytes], + key_set: dict[str, bytes | VerificationKey], *, expected_issuer: str | None = None, ) -> VerificationResult: @@ -312,8 +376,8 @@ def verify_bundle( Args: bundle: The object returned by ``GET /v1/receipts/{id}/portable``, either as a dict or a JSON string. - key_set: Mapping of key id to raw 32-byte Ed25519 public key, as - produced by :func:`key_set_from_document`. + key_set: Mapping of key id to raw Ed25519 bytes or a tagged P-256 + public key, as produced by :func:`key_set_from_document`. expected_issuer: When given, the unauthenticated envelope's ``issuer`` label must match. This catches accidental relabeling but does not authenticate the issuer; that requires a trusted public key. @@ -400,12 +464,6 @@ def verify_bundle( "signature is not valid base64", key_id=key_id, ) - if len(signature) != _ED25519_SIGNATURE_LEN: - return _fail( - VerificationStatus.MALFORMED, - "signature is not a 64-byte Ed25519 signature", - key_id=key_id, - ) raw_public_key = key_set.get(key_id) if raw_public_key is None: @@ -417,13 +475,14 @@ def verify_bundle( # would let a forger name a nonexistent kid to downgrade a detectable # inconsistency into "refresh your key set and try again". envelope_key = key_set.get(envelope_key_id) if envelope_key_id != key_id else None - if envelope_key is not None and len(envelope_key) == _ED25519_RAW_LEN: + if envelope_key is not None: try: probe_bytes = signing_input.encode("utf-8") except UnicodeEncodeError: probe_bytes = None - if probe_bytes is not None and _verify_ed25519_signature( - envelope_key, signature, probe_bytes + if ( + probe_bytes is not None + and _verify_signature_for_key(envelope_key, signature, probe_bytes) is True ): return _fail( VerificationStatus.MISMATCH, @@ -438,12 +497,18 @@ def verify_bundle( f"no published key for kid {key_id!r}", key_id=key_id, ) - if len(raw_public_key) != _ED25519_RAW_LEN: + if isinstance(raw_public_key, bytes) and len(raw_public_key) != _ED25519_RAW_LEN: return _fail( VerificationStatus.MALFORMED, f"public key for kid {key_id!r} is not a 32-byte Ed25519 key", key_id=key_id, ) + if isinstance(raw_public_key, bytes) and len(signature) != _ED25519_SIGNATURE_LEN: + return _fail( + VerificationStatus.MALFORMED, + "signature is not a 64-byte Ed25519 signature", + key_id=key_id, + ) try: signing_bytes = signing_input.encode("utf-8") @@ -457,23 +522,35 @@ def verify_bundle( # The signature covers signing_input verbatim. Re-serializing the parsed # object here would silently "fix" a payload whose bytes were altered in a # way that survives a JSON round trip, so the original string is used. - if not _verify_ed25519_signature(raw_public_key, signature, signing_bytes): + signature_valid = _verify_signature_for_key(raw_public_key, signature, signing_bytes) + if signature_valid is None: + return _fail( + VerificationStatus.MALFORMED, + "public key or signature is not valid for its published algorithm", + key_id=key_id, + ) + if not signature_valid: return _fail( VerificationStatus.INVALID, "signature does not verify over signing_input", key_id=key_id, ) - # The signature held, so algorithm and canonicalization are the signer's - # claim. A different algorithm, or a canonicalization this verifier does - # not implement, is UNSUPPORTED. That judgment is not available when the - # signature failed: that case already returned INVALID above. + # The signature held under the published key's algorithm. Receipt v0.1 + # accepts Ed25519 only; a genuine P-256 signature can now be identified + # as unsupported without mistaking it for a malformed Ed25519 signature. if algorithm != "Ed25519": return _fail( VerificationStatus.UNSUPPORTED, f"unsupported signature algorithm: {algorithm!r}", key_id=key_id, ) + if isinstance(raw_public_key, VerificationKey): + return _fail( + VerificationStatus.UNSUPPORTED, + f"unsupported verification key algorithm: {raw_public_key.alg!r}", + key_id=key_id, + ) if isinstance(signed_canonicalization, str) and signed_canonicalization != CANONICALIZATION: return _fail( VerificationStatus.UNSUPPORTED, diff --git a/sdk/python/tests/test_local_permit_validator.py b/sdk/python/tests/test_local_permit_validator.py index 8a601cf5a..ac8e6958b 100644 --- a/sdk/python/tests/test_local_permit_validator.py +++ b/sdk/python/tests/test_local_permit_validator.py @@ -169,6 +169,23 @@ def test_verify_permit_accepts_genuine_signature(): assert _validator(permit, key_document).verify_permit() is True +def test_p256_receipt_key_does_not_verify_an_ed25519_permit(): + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric import ec + + permit, key_document = _build_signed_permit() + public_der = ( + ec.generate_private_key(ec.SECP256R1()) + .public_key() + .public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) + ) + key_document["keys"][0].update( + alg="ECDSA-P256-SHA256", public_key_b64=base64.b64encode(public_der).decode() + ) + + assert _validator(permit, key_document).verify_permit() is False + + def test_verify_permit_normalizes_api_value_forms(): """Naive timestamps and non-normalized decimals canonicalize identically. diff --git a/sdk/python/tests/test_receipt_verifier_signed.py b/sdk/python/tests/test_receipt_verifier_signed.py index b6f37b7c7..73a897038 100644 --- a/sdk/python/tests/test_receipt_verifier_signed.py +++ b/sdk/python/tests/test_receipt_verifier_signed.py @@ -387,6 +387,92 @@ def test_key_set_rejects_a_non_object_document(): key_set_from_document(["not", "a", "dict"]) +def test_genuine_p256_receipt_is_unsupported_only_after_signature_verification(): + """The dormant KMS algorithm is recognizable without accepting it as v0.1.""" + pytest.importorskip("cryptography") + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec + + private_key = ec.generate_private_key(ec.SECP256R1()) + public_der = private_key.public_key().public_bytes( + serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo + ) + kid = "p256-test-key" + algorithm = "ECDSA-P256-SHA256" + signing_input = canonical_json(_payload(kid=kid, alg=algorithm)) + signature = private_key.sign(signing_input.encode("utf-8"), ec.ECDSA(hashes.SHA256())) + bundle = { + "kid": kid, + "alg": algorithm, + "signing_input": signing_input, + "signature": base64.b64encode(signature).decode(), + } + document = { + "keys": [ + { + "kid": kid, + "alg": algorithm, + "status": "active", + "public_key_b64": base64.b64encode(public_der).decode(), + } + ] + } + keys = key_set_from_document(document) + + assert kid in keys + assert verify_bundle(bundle, {}).status is VerificationStatus.UNKNOWN_KEY + genuine = verify_bundle(bundle, keys) + assert genuine.status is VerificationStatus.UNSUPPORTED + assert not genuine.is_tampered + + ed_claim = canonical_json(_payload(kid=kid, alg="Ed25519")) + ed_claim_signature = private_key.sign(ed_claim.encode("utf-8"), ec.ECDSA(hashes.SHA256())) + mislabeled = dict( + bundle, + alg="Ed25519", + signing_input=ed_claim, + signature=base64.b64encode(ed_claim_signature).decode(), + ) + mismatched_algorithm = verify_bundle(mislabeled, keys) + assert mismatched_algorithm.status is VerificationStatus.UNSUPPORTED + assert "verification key algorithm" in (mismatched_algorithm.reason or "") + + altered = dict( + bundle, signing_input=signing_input.replace('"outcome":"success"', '"outcome":"denied"') + ) + assert verify_bundle(altered, keys).status is VerificationStatus.INVALID + + other_key = ec.generate_private_key(ec.SECP256R1()) + wrong_signature = other_key.sign(signing_input.encode("utf-8"), ec.ECDSA(hashes.SHA256())) + assert ( + verify_bundle( + dict(bundle, signature=base64.b64encode(wrong_signature).decode()), keys + ).status + is VerificationStatus.INVALID + ) + assert ( + verify_bundle(dict(bundle, signature=base64.b64encode(b"\x30\x00").decode()), keys).status + is VerificationStatus.MALFORMED + ) + + document["keys"][0]["status"] = "disabled" + assert ( + verify_bundle(bundle, key_set_from_document(document)).status + is VerificationStatus.UNKNOWN_KEY + ) + document["keys"][0]["status"] = "active" + document["keys"][0]["public_key_b64"] = base64.b64encode(b"not DER").decode() + assert ( + verify_bundle(bundle, key_set_from_document(document)).status + is VerificationStatus.MALFORMED + ) + document["keys"][0]["public_key_b64"] = "!!!!" + assert ( + verify_bundle(bundle, key_set_from_document(document)).status + is VerificationStatus.MALFORMED + ) + + def _write_cli_inputs(tmp_path, bundle, key_set): bundle_path = tmp_path / "bundle.json" keys_path = tmp_path / "trust-keys.json" diff --git a/sdk/typescript/src/verify.ts b/sdk/typescript/src/verify.ts index e35c6c191..5497c4299 100644 --- a/sdk/typescript/src/verify.ts +++ b/sdk/typescript/src/verify.ts @@ -4,11 +4,11 @@ * Mirrors the Python verifier in sdk/python (b2a_sdk.receipt_verifier): * every reported field is read from the signed bytes, and "cannot tell" * (unknown_key, malformed, unsupported) is kept apart from "rejected" - * (invalid, mismatch). No network access; Node's built-in Ed25519 only. + * (invalid, mismatch). No network access; uses Node's built-in cryptography. * * Licensed under Apache-2.0. */ -import { createPublicKey, verify as edVerify } from "node:crypto"; +import { createPublicKey, verify as cryptoVerify } from "node:crypto"; export const CANONICALIZATION = "awi-canonical-json/1"; @@ -34,7 +34,15 @@ export interface VerificationResult { claims?: Record; } -export type KeySet = Map; +export const P256_ALGORITHM = "ECDSA-P256-SHA256"; + +export interface P256VerificationKey { + alg: typeof P256_ALGORITHM; + /** DER SubjectPublicKeyInfo, as returned by AWS KMS GetPublicKey. */ + publicKeyDer: Buffer; +} + +export type KeySet = Map; const RAW_KEY_LEN = 32; const SIG_LEN = 64; @@ -66,7 +74,7 @@ export function canonicalJson(value: unknown): string { return ser(value); } -/** Extract usable Ed25519 public keys from a trust-keys.json document. */ +/** Extract verification keys from a trust-keys.json document. */ export function keySetFromDocument(doc: unknown): KeySet { const keys: KeySet = new Map(); if (!doc || typeof doc !== "object" || !Array.isArray((doc as { keys?: unknown }).keys)) { @@ -78,6 +86,12 @@ export function keySetFromDocument(doc: unknown): KeySet { const kid = (e.kid ?? e.key_id) as unknown; if (typeof kid !== "string" || !kid) continue; if (e.status === "disabled") continue; + if (e.alg === P256_ALGORITHM) { + // Retain malformed published material so verification reports malformed + // instead of treating a known kid as an unknown key. + keys.set(kid, { alg: P256_ALGORITHM, publicKeyDer: b64(e.public_key_b64 ?? "") ?? Buffer.alloc(0) }); + continue; + } if (e.alg !== undefined && e.alg !== null && e.alg !== "Ed25519") continue; let raw = b64(e.public_key_b64 ?? ""); if (!raw || raw.length !== RAW_KEY_LEN) { @@ -186,12 +200,65 @@ function parseJsonPreservingUnsafeIntegers(text: string): unknown { function edOk(raw: Buffer, sig: Buffer, msg: Buffer): boolean { try { const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: raw.toString("base64url") }, format: "jwk" }); - return edVerify(null, msg, key, sig); + return cryptoVerify(null, msg, key, sig); } catch { return false; } } +function p256PublicKey(key: P256VerificationKey): ReturnType | null { + if (!Buffer.isBuffer(key.publicKeyDer)) return null; + try { + const publicKey = createPublicKey({ key: key.publicKeyDer, format: "der", type: "spki" }); + return publicKey.asymmetricKeyType === "ec" && publicKey.asymmetricKeyDetails?.namedCurve === "prime256v1" + ? publicKey : null; + } catch { + return null; + } +} + +function derLength(bytes: Buffer, offset: number): [number, number] | null { + if (offset >= bytes.length) return null; + const first = bytes[offset++]!; + if (first < 0x80) return [first, offset]; + const count = first & 0x7f; + if (count === 0 || count > 6 || offset + count > bytes.length || bytes[offset] === 0) return null; + let length = 0; + for (let i = 0; i < count; i++) length = length * 256 + bytes[offset++]!; + return length >= 0x80 ? [length, offset] : null; +} + +function isDerEcdsaSignature(sig: Buffer): boolean { + if (sig[0] !== 0x30) return false; + const sequence = derLength(sig, 1); + if (!sequence || sequence[0] !== sig.length - sequence[1]) return false; + let offset = sequence[1]; + for (let i = 0; i < 2; i++) { + if (sig[offset++] !== 0x02) return false; + const integer = derLength(sig, offset); + if (!integer || integer[0] === 0 || integer[0] > sig.length - integer[1]) return false; + offset = integer[1]; + const first = sig[offset]!; + if (first & 0x80 || (integer[0] > 1 && first === 0 && !(sig[offset + 1]! & 0x80))) return false; + offset += integer[0]; + } + return offset === sig.length; +} + +function p256Ok(key: ReturnType, sig: Buffer, msg: Buffer): boolean { + try { + return cryptoVerify("sha256", msg, key, sig); + } catch { + return false; + } +} + +function signatureValid(key: Buffer | P256VerificationKey, sig: Buffer, msg: Buffer): boolean { + if (Buffer.isBuffer(key)) return key.length === RAW_KEY_LEN && sig.length === SIG_LEN && edOk(key, sig, msg); + const publicKey = key.alg === P256_ALGORITHM ? p256PublicKey(key) : null; + return publicKey !== null && isDerEcdsaSignature(sig) && p256Ok(publicKey, sig, msg); +} + /** Verify one portable receipt bundle against a caller-supplied key set. */ export function verifyBundle(bundle: unknown, keySet: KeySet, expectedIssuer?: string): VerificationResult { if (typeof bundle === "string") { @@ -237,26 +304,29 @@ export function verifyBundle(bundle: unknown, keySet: KeySet, expectedIssuer?: s const sig = b64(sigB64); if (!sig) return fail("malformed", "signature is not valid base64", kid); - if (sig.length !== SIG_LEN) return fail("malformed", "signature is not a 64-byte Ed25519 signature", kid); const msg = Buffer.from(signingInput, "utf8"); const raw = keySet.get(kid); - // A key that is present but the wrong length cannot be judged. Reporting - // that as invalid would call the receipt tampered. - if (raw && raw.length !== RAW_KEY_LEN) { - return fail("malformed", `public key for kid ${kid} is not a 32-byte Ed25519 key`, kid); - } if (!raw) { const envKey = envKid !== kid ? keySet.get(envKid) : undefined; - if (envKey && envKey.length === RAW_KEY_LEN && edOk(envKey, sig, msg)) { + if (envKey && signatureValid(envKey, sig, msg)) { return fail("mismatch", `signed under kid ${envKid} but the payload names kid ${kid}`, kid); } return fail("unknown_key", `no published key for kid ${kid}`, kid); } - if (raw.length !== RAW_KEY_LEN) return fail("malformed", `public key for kid ${kid} is not a 32-byte Ed25519 key`, kid); - if (!edOk(raw, sig, msg)) return fail("invalid", "signature does not verify over signing_input", kid); + if (Buffer.isBuffer(raw)) { + if (sig.length !== SIG_LEN) return fail("malformed", "signature is not a 64-byte Ed25519 signature", kid); + if (raw.length !== RAW_KEY_LEN) return fail("malformed", `public key for kid ${kid} is not a 32-byte Ed25519 key`, kid); + if (!edOk(raw, sig, msg)) return fail("invalid", "signature does not verify over signing_input", kid); + } else { + const publicKey = raw.alg === P256_ALGORITHM ? p256PublicKey(raw) : null; + if (!publicKey) return fail("malformed", `public key for kid ${kid} is not a P-256 DER SPKI key`, kid); + if (!isDerEcdsaSignature(sig)) return fail("malformed", "signature is not a DER ECDSA signature", kid); + if (!p256Ok(publicKey, sig, msg)) return fail("invalid", "signature does not verify over signing_input", kid); + } if (alg !== "Ed25519") return fail("unsupported", `unsupported signature algorithm: ${String(alg)}`, kid); + if (!Buffer.isBuffer(raw)) return fail("unsupported", `unsupported verification key algorithm: ${raw.alg}`, kid); if (typeof signedCanon === "string" && signedCanon !== CANONICALIZATION) { return fail("unsupported", `unsupported canonicalization: ${signedCanon}`, kid); } diff --git a/sdk/typescript/test/verify.test.ts b/sdk/typescript/test/verify.test.ts index 426e52bc3..9de0fb03f 100644 --- a/sdk/typescript/test/verify.test.ts +++ b/sdk/typescript/test/verify.test.ts @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { createHash, generateKeyPairSync, sign } from "node:crypto"; import { CANONICALIZATION, + P256_ALGORITHM, canonicalJson, keySetFromDocument, verifyBundle, @@ -12,6 +13,9 @@ import { const keyPair = generateKeyPairSync("ed25519"); const otherPair = generateKeyPairSync("ed25519"); +const p256Pair = generateKeyPairSync("ec", { namedCurve: "prime256v1" }); +const otherP256Pair = generateKeyPairSync("ec", { namedCurve: "prime256v1" }); +const p256PublicDer = p256Pair.publicKey.export({ type: "spki", format: "der" }); const rawKey = Buffer.from( (keyPair.publicKey.export({ format: "jwk" }).x as string), "base64url", @@ -48,6 +52,18 @@ function statusOf(bundle: unknown, ks: KeySet = keys(), issuer?: string): string return verifyBundle(bundle, ks, issuer).status; } +function p256Keys(status = "active", publicKeyDer = p256PublicDer): KeySet { + return keySetFromDocument({ + keys: [{ kid: "p256-key", alg: P256_ALGORITHM, status, public_key_b64: publicKeyDer.toString("base64") }], + }); +} + +function sealP256(body: Record = { receipt_id: "rcpt-p256", kid: "p256-key", alg: P256_ALGORITHM }): Record { + const signingInput = JSON.stringify(body); + const signature = sign("sha256", Buffer.from(signingInput, "utf8"), p256Pair.privateKey).toString("base64"); + return { signing_input: signingInput, signature, kid: "p256-key", alg: P256_ALGORITHM }; +} + test("valid bundle verifies and reports claims from the signed bytes", () => { const result = verifyBundle( seal(payload({ tool: "partner.echo", credits_charged: "1" })), @@ -268,6 +284,60 @@ test("signed RS256 algorithm is unsupported, driven by the signer", () => { assert.equal(statusOf(bundle), "unsupported"); }); +test("genuine P-256 receipt is unsupported only after its DER signature verifies", () => { + const ks = p256Keys(); + const key = ks.get("p256-key"); + assert.ok(key && !Buffer.isBuffer(key)); + assert.equal(key.alg, P256_ALGORITHM); + assert.deepEqual(key.publicKeyDer, p256PublicDer); + + const bundle = sealP256(); + assert.equal(statusOf(bundle, new Map()), "unknown_key"); + const result = verifyBundle(bundle, ks); + assert.equal(result.status, "unsupported"); + assert.equal(result.ok, false); +}); + +test("altered P-256 signed bytes and signatures are invalid", () => { + const bundle = sealP256(); + assert.equal(statusOf({ ...bundle, signing_input: (bundle.signing_input as string).replace("rcpt-p256", "rcpt-f256") }, p256Keys()), "invalid"); + const wrongSignature = sign("sha256", Buffer.from(bundle.signing_input as string), otherP256Pair.privateKey).toString("base64"); + assert.equal(statusOf({ ...bundle, signature: wrongSignature }, p256Keys()), "invalid"); +}); + +test("base64-decoded malformed P-256 DER signatures are malformed", () => { + const bundle = sealP256(); + const notDer = Buffer.alloc(70).toString("base64"); + const nonMinimalInteger = Buffer.from("300702020001020101", "hex").toString("base64"); + assert.equal(statusOf({ ...bundle, signature: notDer }, p256Keys()), "malformed"); + assert.equal(statusOf({ ...bundle, signature: nonMinimalInteger }, p256Keys()), "malformed"); +}); + +test("missing and disabled P-256 keys are unknown_key", () => { + const bundle = sealP256(); + assert.equal(statusOf(bundle, new Map()), "unknown_key"); + assert.equal(statusOf(bundle, p256Keys("disabled")), "unknown_key"); +}); + +test("malformed or wrong-curve P-256 public keys are malformed", () => { + const bundle = sealP256(); + assert.equal(statusOf(bundle, p256Keys("active", Buffer.from("bad DER"))), "malformed"); + const p384 = generateKeyPairSync("ec", { namedCurve: "secp384r1" }); + const p384Der = p384.publicKey.export({ type: "spki", format: "der" }); + assert.equal(statusOf(bundle, p256Keys("active", p384Der)), "malformed"); + assert.equal(statusOf({ ...bundle, signature: "!!!!" }, p256Keys()), "malformed"); +}); + +test("P-256 signed kid confusion is a mismatch", () => { + const bundle = sealP256({ receipt_id: "rcpt-p256", kid: "ghost", alg: P256_ALGORITHM }); + assert.equal(statusOf(bundle, p256Keys()), "mismatch"); +}); + +test("P-256 verification key cannot mark an Ed25519-declared receipt verified", () => { + const bundle = sealP256({ receipt_id: "rcpt-p256", kid: "p256-key", alg: "Ed25519" }); + assert.equal(statusOf(bundle, p256Keys()), "unsupported"); +}); + test("signed unknown canonicalization is unsupported", () => { const bundle = seal({ ...payload(), canonicalization: "other/9" }); assert.equal(statusOf(bundle), "unsupported"); @@ -361,7 +431,10 @@ test("key set reads raw, key_id alias and JWK mirror forms", () => { ], }); assert.deepEqual(new Set(ks.keys()), new Set(["raw", "alias", "jwk-only"])); - for (const value of ks.values()) assert.equal(value.length, 32); + for (const value of ks.values()) { + assert.ok(Buffer.isBuffer(value)); + assert.equal(value.length, 32); + } }); test("key set drops disabled keys, wrong algs and unusable entries", () => { diff --git a/spec/key-set-v0.1.md b/spec/key-set-v0.1.md index 81bed1e5b..5c139ce35 100644 --- a/spec/key-set-v0.1.md +++ b/spec/key-set-v0.1.md @@ -17,10 +17,16 @@ A gateway publishes its receipt and permit verification keys at } ``` -- A verifier uses `public_key_b64` when it decodes to 32 bytes. It uses the - `jwk` mirror only when that raw form is missing or unusable. Publish both - only when they are the same key: a usable `public_key_b64` wins when they - disagree, and the signature check then fails closed against the raw key. +- For a key with `alg: "ECDSA-P256-SHA256"`, `public_key_b64` is base64 of a + DER X.509 SubjectPublicKeyInfo P-256 public key, as returned by AWS KMS + `GetPublicKey`. Its receipt signature is base64 of DER ECDSA with SHA-256 + over the exact UTF-8 `signing_input` bytes. This dormant algorithm has no + JWK mirror requirement. The per-key `alg` selects the verification primitive; + an untrusted receipt field never selects a different primitive for that key. +- For Ed25519, a verifier uses `public_key_b64` when it decodes to 32 bytes. + It uses the `jwk` mirror only when that raw form is missing or unusable. Publish + both only when they are the same key: a usable `public_key_b64` wins when + they disagree, and the signature check then fails closed against the raw key. - Keys with `status` `active` or `retired` are verification keys. `retired` means this key no longer signs new objects, and objects it already signed still verify. Keys with `status` `disabled` must be dropped before diff --git a/spec/receipt-v0.1.md b/spec/receipt-v0.1.md index b355cc891..0364aadb7 100644 --- a/spec/receipt-v0.1.md +++ b/spec/receipt-v0.1.md @@ -89,8 +89,13 @@ Full trigger table: [`../gateway/docs/failure-semantics.md`](../gateway/docs/fai | `invalid` | Signature does not verify | reject (tampered) | | `mismatch` | Signature verified, but the bundle disagrees with the signed payload. Covers a different envelope `receipt_id`, `kid`, `alg`, or `canonicalization`. A `payload_hash` that does not match a recomputation is not a mismatch: verifiers never recompute it (see `payload_hash` in [`README.md`](README.md)) | reject | | `unknown_key` | Verifier does not hold the signed `kid`, including when that key is present but `disabled` | cannot judge; refresh keys | -| `malformed` | Bundle cannot be parsed, or the signature is not 64 bytes of base64 | cannot judge | -| `unsupported` | The signed payload's `alg` or `canonicalization` is not implemented, and the signature over `signing_input` checked out. The envelope alone must not produce this status | cannot judge | +| `malformed` | Bundle cannot be parsed, or the signature or published key is malformed for its algorithm | cannot judge | +| `unsupported` | The signature over `signing_input` checked out under the published key, but the signed payload's `alg` or `canonicalization` is not accepted by receipt v0.1. A genuine `ECDSA-P256-SHA256` receipt reaches this status; an envelope claim alone cannot produce it | cannot judge | + +The key document's per-key `alg` selects Ed25519 or P-256/SHA-256 signature +verification. Receipt v0.1 accepts Ed25519 receipts only. P-256 verification +exists to distinguish a genuine future-algorithm receipt from altered bytes; +it does not enable the dormant KMS signing path. Reference verifiers: Python (`sdk/python`, CLI `b2a-verify-receipt`) and TypeScript (`sdk/typescript`). Both pass [`test-vectors/`](test-vectors/). diff --git a/spec/test-vectors/README.md b/spec/test-vectors/README.md index 4e3bc7af9..a96c44aea 100644 --- a/spec/test-vectors/README.md +++ b/spec/test-vectors/README.md @@ -8,7 +8,7 @@ envelope fields that disagree with the signed payload, an advisory payload_hash that does not match recomputation (still verified when signed), a float-bearing payload that verifies without re-serialization, - an unsupported algorithm, and malformed bundles. + a genuine P-256 signature classified as unsupported, and malformed bundles. - `generate.py`: regenerates both files from `gateway/tests/fixtures/`. Check an implementation: diff --git a/spec/test-vectors/generate.py b/spec/test-vectors/generate.py index b01d3b455..1d23dc1d0 100644 --- a/spec/test-vectors/generate.py +++ b/spec/test-vectors/generate.py @@ -21,6 +21,8 @@ import json from pathlib import Path +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat @@ -435,6 +437,47 @@ def _synthetic_cases( ] +def _p256_cases(base_bundle: dict) -> list[dict]: + """Fixed, public test key for the dormant KMS receipt algorithm.""" + key = ec.derive_private_key(1, ec.SECP256R1()) + kid = "sk_p256_test" + algorithm = "ECDSA-P256-SHA256" + payload = _with_hash(dict(json.loads(base_bundle["signing_input"]), kid=kid, alg=algorithm)) + signing_input = canonical_json(payload) + signature = key.sign( + signing_input.encode("utf-8"), ec.ECDSA(hashes.SHA256(), deterministic_signing=True) + ) + bundle = { + "receipt_id": payload["receipt_id"], + "kid": kid, + "alg": algorithm, + "canonicalization": CANONICALIZATION, + "signing_input": signing_input, + "signature": b64(signature), + } + keys = { + "keys": [ + { + "kid": kid, + "alg": algorithm, + "status": "active", + "public_key_b64": b64( + key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) + ), + } + ] + } + return [ + {"name": "p256.valid", "bundle": bundle, "keys": keys, "expect": "unsupported"}, + { + "name": "p256.tampered_payload", + "bundle": dict(bundle, signing_input=tamper_outcome(signing_input)), + "keys": keys, + "expect": "invalid", + }, + ] + + def build_cases( golden_dir: Path | None = None, key: Ed25519PrivateKey | None = None ) -> list[dict]: @@ -455,6 +498,7 @@ def build_cases( f"{BASE_FIXTURE} fixture is required to build the synthetic cases" ) cases.extend(_synthetic_cases(base_bundle, signing, _public_raw(signing))) + cases.extend(_p256_cases(base_bundle)) cases.append( { "name": "malformed.no_signature", @@ -474,7 +518,8 @@ def render_receipts(key: Ed25519PrivateKey | None = None) -> str: "Synthetic cases cover a revoked key, envelope fields that disagree " "with the signed payload, an advisory payload_hash that does not match " "recomputation (still verified when signed), a float-bearing payload " - "that verifies without re-serialization, an unsupported algorithm, " + "that verifies without re-serialization, a genuine P-256 signature " + "that is unsupported by receipt v0.1, " "and malformed bundles." ), "cases": build_cases(key=signing), diff --git a/spec/test-vectors/receipts.json b/spec/test-vectors/receipts.json index 0fa65bf0d..38549ab3a 100644 --- a/spec/test-vectors/receipts.json +++ b/spec/test-vectors/receipts.json @@ -1,5 +1,5 @@ { - "_comment": "Receipt verification vectors. Each case is checked against keys.json unless it carries its own 'keys'. 'expect' is the verifier status. Synthetic cases cover a revoked key, envelope fields that disagree with the signed payload, an advisory payload_hash that does not match recomputation (still verified when signed), a float-bearing payload that verifies without re-serialization, an unsupported algorithm, and malformed bundles.", + "_comment": "Receipt verification vectors. Each case is checked against keys.json unless it carries its own 'keys'. 'expect' is the verifier status. Synthetic cases cover a revoked key, envelope fields that disagree with the signed payload, an advisory payload_hash that does not match recomputation (still verified when signed), a float-bearing payload that verifies without re-serialization, a genuine P-256 signature that is unsupported by receipt v0.1, and malformed bundles.", "cases": [ { "name": "denial_constraints.valid", @@ -702,6 +702,50 @@ }, "expect": "malformed" }, + { + "name": "p256.valid", + "bundle": { + "receipt_id": "rcpt_golden_0001", + "kid": "sk_p256_test", + "alg": "ECDSA-P256-SHA256", + "canonicalization": "awi-canonical-json/1", + "signing_input": "{\"alg\":\"ECDSA-P256-SHA256\",\"audit_event_id\":\"aud_golden_0001\",\"created_at\":\"2026-09-14T17:00:00+00:00\",\"credits_authorized\":\"2.5\",\"credits_charged\":\"2.5\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_p256_test\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"82875835b1681a7b0659dbb2f447766c95e98e0d7a170447be2629392f2d11d3\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0001\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "MEYCIQDlVAh1vFlliQionl54R+fsfuqAD5fY2GMt3sgy0SIGiQIhAPAJpvtSC2YktkC+2kyaHKJ4OAqQO9tA96cMY9xdcW92" + }, + "keys": { + "keys": [ + { + "kid": "sk_p256_test", + "alg": "ECDSA-P256-SHA256", + "status": "active", + "public_key_b64": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9Q==" + } + ] + }, + "expect": "unsupported" + }, + { + "name": "p256.tampered_payload", + "bundle": { + "receipt_id": "rcpt_golden_0001", + "kid": "sk_p256_test", + "alg": "ECDSA-P256-SHA256", + "canonicalization": "awi-canonical-json/1", + "signing_input": "{\"alg\":\"ECDSA-P256-SHA256\",\"audit_event_id\":\"aud_golden_0001\",\"created_at\":\"2026-09-14T17:00:00+00:00\",\"credits_authorized\":\"2.5\",\"credits_charged\":\"2.5\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_p256_test\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"xsuccess\",\"payload_hash\":\"82875835b1681a7b0659dbb2f447766c95e98e0d7a170447be2629392f2d11d3\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0001\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "MEYCIQDlVAh1vFlliQionl54R+fsfuqAD5fY2GMt3sgy0SIGiQIhAPAJpvtSC2YktkC+2kyaHKJ4OAqQO9tA96cMY9xdcW92" + }, + "keys": { + "keys": [ + { + "kid": "sk_p256_test", + "alg": "ECDSA-P256-SHA256", + "status": "active", + "public_key_b64": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9Q==" + } + ] + }, + "expect": "invalid" + }, { "name": "malformed.no_signature", "bundle": { diff --git a/spec/test-vectors/test_contract.py b/spec/test-vectors/test_contract.py index 6c7d08a0d..4351fb511 100644 --- a/spec/test-vectors/test_contract.py +++ b/spec/test-vectors/test_contract.py @@ -28,6 +28,8 @@ "synthetic.float_payload_verifies": "verified", "synthetic.unsupported_alg": "unsupported", "synthetic.unsupported_canonicalization": "unsupported", + "p256.valid": "unsupported", + "p256.tampered_payload": "invalid", "synthetic.envelope_kid_mismatch": "mismatch", "synthetic.envelope_alg_mismatch": "mismatch", "synthetic.envelope_canonicalization_mismatch": "mismatch", diff --git a/spec/test-vectors/test_generate.py b/spec/test-vectors/test_generate.py index c7fd50723..8d9f3d1b2 100644 --- a/spec/test-vectors/test_generate.py +++ b/spec/test-vectors/test_generate.py @@ -76,6 +76,8 @@ def _verifier(): "synthetic.short_raw_key_uses_jwk": "verified", "synthetic.unsupported_alg": "unsupported", "synthetic.unsupported_canonicalization": "unsupported", + "p256.valid": "unsupported", + "p256.tampered_payload": "invalid", "synthetic.malformed_signature": "malformed", "synthetic.malformed_signature_length": "malformed", "synthetic.malformed_signing_input": "malformed", From 240bbdf3e75f7cc837ad24cb23be974a18da0c64 Mon Sep 17 00:00:00 2001 From: Christopher <131207452+PetrefiedThunder@users.noreply.github.com> Date: Tue, 20 Oct 2026 05:58:44 -0700 Subject: [PATCH 2/2] fix: resolve CI and update with main (SEL-334 retry pass, grok) --- gateway/app/routers/mcp_public.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/gateway/app/routers/mcp_public.py b/gateway/app/routers/mcp_public.py index a588fa7f9..b6228b5d6 100644 --- a/gateway/app/routers/mcp_public.py +++ b/gateway/app/routers/mcp_public.py @@ -34,7 +34,7 @@ import logging import sys from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any import mcp.types as mcp_types from fastapi import APIRouter, HTTPException, Request @@ -59,6 +59,9 @@ get_signing_key_service, ) +if TYPE_CHECKING: + from b2a_sdk.receipt_verifier import VerificationKey + # Image layout: both Dockerfiles copy the in-repo SDK to /sdk/python, install # it, and set PYTHONPATH=/sdk/python/src. From /app/app/routers/mcp_public.py, @@ -384,7 +387,7 @@ def _mcp_error(code: int, message: str) -> McpError: return McpError(mcp_types.ErrorData(code=code, message=message)) -async def _published_key_set() -> dict[str, bytes | _receipt_verifier.VerificationKey] | None: +async def _published_key_set() -> dict[str, bytes | VerificationKey] | None: """Load the same key set a verifier gets from trust-keys.json. ``None`` means "no usable keys right now" — the tool-level analogue of