diff --git a/gateway/tests/test_receipt_portability.py b/gateway/tests/test_receipt_portability.py index d0a65886a..3705731b3 100644 --- a/gateway/tests/test_receipt_portability.py +++ b/gateway/tests/test_receipt_portability.py @@ -549,7 +549,7 @@ def _hashed_payload(payload): return {**body, "payload_hash": sha256_hex(body)} -def test_validly_signed_payload_with_a_wrong_payload_hash_is_rejected(): +def test_validly_signed_payload_with_a_wrong_payload_hash_verifies(): kid, key_set, sign = _local_signer() payload = _hashed_payload( {"receipt_id": "rcpt-x", "kid": kid, "tool": "search", "outcome": "success"} @@ -558,8 +558,8 @@ def test_validly_signed_payload_with_a_wrong_payload_hash_is_rejected(): result = verify_bundle(_signed_bundle(payload, kid=kid, sign=sign), key_set) - assert result.status is VerificationStatus.MISMATCH - assert "payload_hash" in (result.reason or "") + assert result.status is VerificationStatus.VERIFIED + assert result.claims["payload_hash"] == "f" * 64 def test_signature_under_a_key_the_payload_does_not_name_is_rejected(): diff --git a/gateway/tests/test_spec_conformance.py b/gateway/tests/test_spec_conformance.py index 9059ade73..4b1052f18 100644 --- a/gateway/tests/test_spec_conformance.py +++ b/gateway/tests/test_spec_conformance.py @@ -449,7 +449,10 @@ def test_valid_vectors_have_documented_payloads(self): payload = json.loads(case["bundle"]["signing_input"]) assert RECEIPT_ALWAYS_SIGNED <= set(payload), case["name"] assert set(payload) <= RECEIPT_DOCUMENTED | RECEIPT_ADDITIVE, case["name"] - assert _recompute_payload_hash(payload), case["name"] + if case["name"] == "synthetic.payload_hash_mismatch": + assert not _recompute_payload_hash(payload), case["name"] + else: + assert _recompute_payload_hash(payload), case["name"] assert payload["outcome"] in SPEC_OUTCOMES, case["name"] assert re.fullmatch(r"\d+(\.\d+)?", payload["credits_authorized"]) assert re.fullmatch(r"\d+(\.\d+)?", payload["credits_charged"]) diff --git a/sdk/python/src/b2a_sdk/receipt_verifier.py b/sdk/python/src/b2a_sdk/receipt_verifier.py index 60bca4311..ff55b6c9d 100644 --- a/sdk/python/src/b2a_sdk/receipt_verifier.py +++ b/sdk/python/src/b2a_sdk/receipt_verifier.py @@ -34,7 +34,6 @@ import base64 import binascii -import hashlib import json from dataclasses import dataclass, field from enum import Enum @@ -141,9 +140,10 @@ def canonical_json(payload: Any) -> str: """Serialize already-decoded JSON the way the trust plane signs it. The rules are: keys sorted at every level, no insignificant whitespace, - and non-ASCII escaped. Numbers and timestamps are already strings by the - time they reach a signed payload, so no numeric formatting rules are - needed here — which is what makes this reimplementable in any language. + and non-ASCII escaped. Signed payloads may carry JSON numbers (floats, + exponents, large integers), whose rendering differs between languages, + so this helper is for *signing* new payloads only. Verification never + re-serializes the signed bytes: the signature covers them verbatim. """ return json.dumps( payload, @@ -515,25 +515,12 @@ def verify_bundle( key_id=key_id, ) - stated_hash = payload.get("payload_hash") - if isinstance(stated_hash, str): - inner = {k: v for k, v in payload.items() if k != "payload_hash"} - try: - canonical = canonical_json(inner) - except (RecursionError, ValueError): - return _fail( - VerificationStatus.MALFORMED, - "signed payload exceeds the supported JSON nesting depth", - key_id=key_id, - ) - computed = hashlib.sha256(canonical.encode("utf-8")).hexdigest() - if computed != stated_hash: - return _fail( - VerificationStatus.MISMATCH, - "payload_hash does not match the signed payload", - key_id=key_id, - ) - + # payload_hash is advisory and never recomputed here. The Ed25519 check + # above already covers signing_input verbatim, payload_hash included, so + # any edit to the signed bytes is INVALID. Re-serializing the parsed + # payload would reject genuine receipts: JSON numbers do not round-trip + # across languages (the gateway signs floats such as 1.0 and 4e-05, and + # integers above 2^53 lose precision in some parsers). receipt_id = payload.get("receipt_id") if not isinstance(receipt_id, str) or not receipt_id: return _fail( diff --git a/sdk/python/tests/test_receipt_verifier_signed.py b/sdk/python/tests/test_receipt_verifier_signed.py index e6548c613..b6f37b7c7 100644 --- a/sdk/python/tests/test_receipt_verifier_signed.py +++ b/sdk/python/tests/test_receipt_verifier_signed.py @@ -269,6 +269,46 @@ def test_payload_without_payload_hash_verifies(): assert result.status is VerificationStatus.VERIFIED, result.reason +def test_signed_payload_hash_is_advisory(): + """A wrong but signed payload_hash still verifies; the signature covers it.""" + kid, key_set, sign = _local_signer() + payload = _payload(kid=kid) + payload["payload_hash"] = "0" * 64 + + result = verify_bundle(_signed_bundle(payload, kid=kid, sign=sign), key_set) + + assert result.status is VerificationStatus.VERIFIED, result.reason + + +def test_editing_payload_hash_without_resigning_is_invalid(): + bundle, key_set = _verified_bundle() + good = json.loads(bundle["signing_input"])["payload_hash"] + + result = verify_bundle(_retarget(bundle, good, "0" * 64), key_set) + + assert result.status is VerificationStatus.INVALID + assert result.is_tampered + + +def test_float_bearing_payload_verifies_without_reserialization(): + """Floats the gateway signs (1.0, 0.0) verify; numbers are never rechecked.""" + kid, key_set, sign = _local_signer() + payload = _payload(kid=kid) + del payload["payload_hash"] + payload["constraints_evaluated"] = { + "jev_risk_guard": {"latency_ms": 0.0, "injected_instructions": 1.0} + } + inner = {k: v for k, v in payload.items() if k != "payload_hash"} + payload["payload_hash"] = hashlib.sha256(canonical_json(inner).encode("utf-8")).hexdigest() + bundle = _signed_bundle(payload, kid=kid, sign=sign) + assert '"latency_ms":0.0' in bundle["signing_input"] + assert '"injected_instructions":1.0' in bundle["signing_input"] + + result = verify_bundle(bundle, key_set) + + assert result.status is VerificationStatus.VERIFIED, result.reason + + def test_extra_envelope_fields_are_ignored(): bundle, key_set = _verified_bundle() bundle = {**bundle, "keys_url": "/.well-known/trust-keys.json", "future_field": {"n": 1}} diff --git a/sdk/typescript/src/verify.ts b/sdk/typescript/src/verify.ts index fff5af76b..e35c6c191 100644 --- a/sdk/typescript/src/verify.ts +++ b/sdk/typescript/src/verify.ts @@ -8,7 +8,7 @@ * * Licensed under Apache-2.0. */ -import { createHash, createPublicKey, verify as edVerify } from "node:crypto"; +import { createPublicKey, verify as edVerify } from "node:crypto"; export const CANONICALIZATION = "awi-canonical-json/1"; @@ -26,6 +26,11 @@ export interface VerificationResult { reason?: string; receiptId?: string; keyId?: string; + /** + * Fields read from the signed bytes. An integer that does not fit in a JS + * number is the signed decimal text (a string), so the claim matches the + * bytes the signature covered. + */ claims?: Record; } @@ -118,6 +123,66 @@ function hasLoneSurrogate(value: unknown): boolean { return false; } +const PLAIN_INTEGER = /^-?(?:0|[1-9]\d*)$/; +const JSON_NUMBER = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y; + +/** + * True when a JSON integer token is not the number JSON.parse would return. + * 9007199254740993 becomes 9007199254740992; the signed digits must be kept. + */ +function integerLexemeRounds(lexeme: string): boolean { + if (!PLAIN_INTEGER.test(lexeme)) return false; + const digits = lexeme.startsWith("-") ? lexeme.slice(1) : lexeme; + // A finite double stops near 1e308. Longer tokens are not that number, and + // they do not need a BigInt the size of the token. + if (digits.length > 400) return true; + const asNumber = Number(lexeme); + if (!Number.isFinite(asNumber)) return true; + return BigInt(lexeme) !== BigInt(asNumber); +} + +/** + * Parse JSON, quoting integer tokens that a JS number would round. + * Strings are copied through, so digits inside a string stay a string. + */ +function parseJsonPreservingUnsafeIntegers(text: string): unknown { + let out = ""; + let i = 0; + while (i < text.length) { + const c = text[i]!; + if (c === '"') { + const start = i; + i += 1; + while (i < text.length) { + if (text[i] === "\\") { + i += 2; + continue; + } + if (text[i] === '"') { + i += 1; + break; + } + i += 1; + } + out += text.slice(start, i); + continue; + } + if (c === "-" || (c >= "0" && c <= "9")) { + JSON_NUMBER.lastIndex = i; + const match = JSON_NUMBER.exec(text); + if (match && match.index === i) { + const lexeme = match[0]; + i += lexeme.length; + out += integerLexemeRounds(lexeme) ? JSON.stringify(lexeme) : lexeme; + continue; + } + } + out += c; + i += 1; + } + return JSON.parse(out); +} + function edOk(raw: Buffer, sig: Buffer, msg: Buffer): boolean { try { const key = createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: raw.toString("base64url") }, format: "jwk" }); @@ -148,7 +213,9 @@ export function verifyBundle(bundle: unknown, keySet: KeySet, expectedIssuer?: s let payload: unknown; try { - payload = JSON.parse(signingInput); + // JSON.parse rounds integers above 2^53. Claims are read from this + // object, so those tokens stay the signed decimal text. + payload = parseJsonPreservingUnsafeIntegers(signingInput); } catch { return fail("malformed", "signing_input is not valid JSON", envKid); } @@ -201,18 +268,13 @@ export function verifyBundle(bundle: unknown, keySet: KeySet, expectedIssuer?: s const envelopeCanon = b.canonicalization === undefined ? CANONICALIZATION : b.canonicalization; if (envelopeCanon !== expectedCanon) return fail("mismatch", "bundle canonicalization differs from the signed payload", kid); - if (typeof p.payload_hash === "string") { - const inner: Record = { ...p }; - delete inner.payload_hash; - let canonical: string; - try { - canonical = canonicalJson(inner); - } catch { - return fail("malformed", "signed payload exceeds the supported JSON nesting depth", kid); - } - const computed = createHash("sha256").update(canonical, "utf8").digest("hex"); - if (computed !== p.payload_hash) return fail("mismatch", "payload_hash does not match the signed payload", kid); - } + // payload_hash is advisory and never recomputed here. The Ed25519 check + // above already covers signing_input verbatim, payload_hash included, so + // any edit to the signed bytes is invalid. Re-serializing the parsed + // payload would reject genuine receipts: JSON numbers do not round-trip + // across languages (Python signs 1.0 and 4e-05; this parser reads them as + // 1 and 0.00004). Integers that do not fit in a JS number are returned as + // the signed decimal text, not the rounded number. const receiptId = p.receipt_id; if (typeof receiptId !== "string" || !receiptId) return fail("malformed", "signed payload has no receipt_id", kid); if (b.receipt_id !== undefined && b.receipt_id !== null && b.receipt_id !== receiptId) return fail("mismatch", "bundle receipt_id does not match the signed receipt_id", kid, receiptId); diff --git a/sdk/typescript/test/vectors.test.ts b/sdk/typescript/test/vectors.test.ts index 2f30d4c92..aeafc5a50 100644 --- a/sdk/typescript/test/vectors.test.ts +++ b/sdk/typescript/test/vectors.test.ts @@ -16,6 +16,21 @@ for (const c of cases) { }); } +test("float-bearing vector keeps the signed integer above 2^53", () => { + const floatCase = cases.find((c: { name: string }) => c.name === "synthetic.float_payload_verifies"); + const result = verifyBundle(floatCase.bundle, keys); + assert.equal(result.status, "verified"); + const guard = ( + result.claims?.constraints_evaluated as { + jev_risk_guard: { big: unknown; latency_ms: unknown; injected_instructions: unknown; tiny: unknown }; + } + ).jev_risk_guard; + assert.equal(guard.big, "9007199254740993"); + assert.equal(guard.latency_ms, 0); + assert.equal(guard.injected_instructions, 1); + assert.equal(guard.tiny, 4e-05); +}); + test("canonical JSON sorts keys and escapes non-ASCII", () => { assert.equal(canonicalJson({ b: 1, a: ["é", null] }), '{"a":["\\u00e9",null],"b":1}'); }); diff --git a/sdk/typescript/test/verify.test.ts b/sdk/typescript/test/verify.test.ts index 1f4fbcefa..426e52bc3 100644 --- a/sdk/typescript/test/verify.test.ts +++ b/sdk/typescript/test/verify.test.ts @@ -155,26 +155,37 @@ test("envelope kid differing from a verified payload is mismatch", () => { assert.equal(statusOf(bundle, new Map([["key-1", rawKey]])), "mismatch"); }); -test("correct payload_hash verifies; wrong payload_hash is mismatch", () => { +test("payload_hash is advisory: a signed wrong hash still verifies", () => { const inner = payload({ credits_charged: "1" }); const good = createHash("sha256").update(canonicalJson(inner), "utf8").digest("hex"); assert.equal(statusOf(seal({ ...inner, payload_hash: good })), "verified"); assert.equal( statusOf(seal({ ...inner, payload_hash: "0".repeat(64) })), - "mismatch", + "verified", ); }); +test("editing payload_hash without re-signing is invalid", () => { + const inner = payload({ credits_charged: "1" }); + const good = createHash("sha256").update(canonicalJson(inner), "utf8").digest("hex"); + const bundle = seal({ ...inner, payload_hash: good }); + const forged = { + ...bundle, + signing_input: (bundle.signing_input as string).replace(good, "0".repeat(64)), + }; + assert.equal(statusOf(forged), "invalid"); +}); + function deepField(depth: number): unknown { let deep: unknown = 0; for (let i = 0; i < depth; i++) deep = { nest: deep }; return deep; } -test("deeply nested payload with payload_hash is malformed, never a throw", () => { +test("deeply nested payload with payload_hash still verifies, never throws", () => { const body = { ...payload({ payload_hash: "0".repeat(64) }), deep: deepField(3000) }; const result = verifyBundle(seal(body), keys()); - assert.equal(result.status, "malformed"); + assert.equal(result.status, "verified"); }); test("deeply nested payload without payload_hash still verifies", () => { @@ -383,13 +394,72 @@ test("disabled key verifies nothing: its receipts are unknown_key", () => { assert.equal(verifyBundle(seal(payload()), ks).status, "unknown_key"); }); -test( - "float payload_hash does not round-trip across languages", - { skip: "JS prints 1.0 as 1, so a hash computed over Python-style 1.0 cannot verify here; numbers must be strings per spec" }, - () => { - assert.equal(canonicalJson({ v: 1.0 }), '{"v":1.0}'); - }, -); +test("integer above 2^53 is returned as the signed digits", () => { + const signingInput = + '{"constraints_evaluated":{"jev_risk_guard":{"big":9007199254740993,"exact":9007199254740992,"neg":-9007199254740993,"note":"9007199254740993","pow10":10000000000000000,"safe":1}},"kid":"key-1","receipt_id":"rcpt-1"}'; + const signature = sign( + null, + Buffer.from(signingInput, "utf8"), + keyPair.privateKey, + ).toString("base64"); + const result = verifyBundle( + { signing_input: signingInput, signature, kid: "key-1" }, + keys(), + ); + assert.equal(result.status, "verified"); + const guard = ( + result.claims?.constraints_evaluated as { + jev_risk_guard: { + big: unknown; + exact: unknown; + neg: unknown; + note: unknown; + pow10: unknown; + safe: unknown; + }; + } + ).jev_risk_guard; + assert.equal(guard.big, "9007199254740993"); + assert.equal(typeof guard.big, "string"); + assert.notEqual(guard.big, 9007199254740992); + // Powers of two (and 10^16) that fit in a double stay numbers. + assert.equal(guard.exact, 9007199254740992); + assert.equal(guard.pow10, 10000000000000000); + assert.equal(guard.neg, "-9007199254740993"); + assert.equal(guard.note, "9007199254740993"); + assert.equal(guard.safe, 1); + + const tampered = signingInput.replace("9007199254740993", "9007199254740994"); + const bad = verifyBundle( + { signing_input: tampered, signature, kid: "key-1" }, + keys(), + ); + assert.equal(bad.status, "invalid"); + assert.equal(bad.claims, undefined); +}); + +test("float-bearing payload signed Python-style verifies", () => { + // The gateway signs floats Python renders as 1.0/0.0. seal() would print + // them as 1/0, so the signed bytes are built as a string instead. + const innerJson = + '{"constraints_evaluated":{"jev_risk_guard":{"injected_instructions":1.0,"latency_ms":0.0}},"kid":"key-1","receipt_id":"rcpt-1"}'; + const hash = createHash("sha256").update(innerJson, "utf8").digest("hex"); + const signingInput = innerJson.replace( + ',"receipt_id"', + `,"payload_hash":"${hash}","receipt_id"`, + ); + assert.match(signingInput, /1\.0/); + const signature = sign( + null, + Buffer.from(signingInput, "utf8"), + keyPair.privateKey, + ).toString("base64"); + const result = verifyBundle( + { signing_input: signingInput, signature, kid: "key-1" }, + keys(), + ); + assert.equal(result.status, "verified"); +}); test( "unexpected crypto backend failure raises instead of reporting invalid", diff --git a/spec/README.md b/spec/README.md index bc33ac02c..2b49dfed3 100644 --- a/spec/README.md +++ b/spec/README.md @@ -33,8 +33,11 @@ breaking changes will bump the version. Propose changes with a spec RFC issue checks the bytes it was given. - **`payload_hash`:** lowercase hex SHA-256 of the canonical JSON of the signed payload *without* the `payload_hash` member. It is itself part of the signed - bytes. A signature over a payload whose `payload_hash` does not match that - computation is a `mismatch`, not a valid receipt. + bytes, so the signature covers it: editing it without re-signing is + `invalid`. Verifiers treat it as advisory and never recompute it, because + signed payloads may carry JSON numbers (floats, exponents, integers above + 2^53) whose rendering differs between languages, and re-serializing the + parsed payload would reject genuine receipts. - **`kid`:** the signing key id, inside the signed payload. Key selection uses the signed `kid`, never the unauthenticated envelope. diff --git a/spec/receipt-v0.1.md b/spec/receipt-v0.1.md index d13ee1f3c..b355cc891 100644 --- a/spec/receipt-v0.1.md +++ b/spec/receipt-v0.1.md @@ -87,7 +87,7 @@ Full trigger table: [`../gateway/docs/failure-semantics.md`](../gateway/docs/fai |---|---|---| | `verified` | Signature holds over the signed bytes and the envelope agrees | yes | | `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`, and a `payload_hash` that is not the SHA-256 of the canonical payload with that member removed | reject | +| `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 | diff --git a/spec/test-vectors/README.md b/spec/test-vectors/README.md index 9ab05647a..4e3bc7af9 100644 --- a/spec/test-vectors/README.md +++ b/spec/test-vectors/README.md @@ -5,9 +5,10 @@ - `receipts.json`: cases with a `bundle`, optional `keys` override, and the `expect`ed verifier status. Built from the gateway's golden receipt fixtures plus tampered variants. Synthetic cases add retired and disabled keys, - envelope fields that disagree with the signed payload, a signed - payload_hash that does not match, an unsupported algorithm, and malformed - bundles. + 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. - `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 be32d37af..b01d3b455 100644 --- a/spec/test-vectors/generate.py +++ b/spec/test-vectors/generate.py @@ -259,6 +259,23 @@ def _synthetic_cases( lied = dict(payload) lied["payload_hash"] = "0" * 64 + # Numbers Python renders one way and other languages another (1.0, 0.0, + # 4e-05, integers above 2^53): the gateway signs such payloads inside + # constraints_evaluated.jev_risk_guard, so one vector carries them and + # must still verify without any re-serialization. + float_payload = _with_hash( + dict( + payload, + constraints_evaluated={ + "jev_risk_guard": { + "latency_ms": 0.0, + "injected_instructions": 1.0, + "tiny": 4e-05, + "big": 9007199254740993, + } + }, + ) + ) unsupported_alg = _with_hash(dict(payload, alg="RS256")) unsupported_canon = _with_hash(dict(payload, canonicalization="other/9")) @@ -322,9 +339,17 @@ def _synthetic_cases( "expect": "mismatch", }, { + # payload_hash is advisory: the signature covers the lying hash, + # so this still verifies. Editing the hash without re-signing is + # what fails, as invalid. "name": "synthetic.payload_hash_mismatch", "bundle": sign_bundle(key, lied), - "expect": "mismatch", + "expect": "verified", + }, + { + "name": "synthetic.float_payload_verifies", + "bundle": sign_bundle(key, float_payload), + "expect": "verified", }, { "name": "synthetic.jwk_only_key", @@ -447,8 +472,10 @@ def render_receipts(key: Ed25519PrivateKey | None = None) -> str: "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, a signed payload_hash that does not match, " - "an unsupported algorithm, and malformed bundles." + "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." ), "cases": build_cases(key=signing), } diff --git a/spec/test-vectors/receipts.json b/spec/test-vectors/receipts.json index 148342541..0fa65bf0d 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, a signed payload_hash that does not match, 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, an unsupported algorithm, and malformed bundles.", "cases": [ { "name": "denial_constraints.valid", @@ -479,7 +479,19 @@ "signing_input": "{\"alg\":\"Ed25519\",\"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_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"0000000000000000000000000000000000000000000000000000000000000000\",\"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": "YuG5THQUP2JmMfNUX9sRqw5yQ5CH8a2kwN4aAvN3UUi6YL/WzktI+Zwq9JFI7QmpQiV4cBhisi23UehBsYHcCw==" }, - "expect": "mismatch" + "expect": "verified" + }, + { + "name": "synthetic.float_payload_verifies", + "bundle": { + "receipt_id": "rcpt_golden_0001", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "signing_input": "{\"alg\":\"Ed25519\",\"audit_event_id\":\"aud_golden_0001\",\"constraints_evaluated\":{\"jev_risk_guard\":{\"big\":9007199254740993,\"injected_instructions\":1.0,\"latency_ms\":0.0,\"tiny\":4e-05}},\"created_at\":\"2026-09-14T17:00:00+00:00\",\"credits_authorized\":\"2.5\",\"credits_charged\":\"2.5\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"11b7b9107cab5a0d55d85769c92e8c1f298c0e16687b513168606bd948be4a22\",\"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": "boPfJde3bzAMu6FeEzakfZuhzrtghFFqwmsktoDzDWnFL3y1jpZ7cL8col4QCaKPrD31Kx+RcLCgk6e09jqFBw==" + }, + "expect": "verified" }, { "name": "synthetic.jwk_only_key", diff --git a/spec/test-vectors/test_contract.py b/spec/test-vectors/test_contract.py index 7e9f28e71..6c7d08a0d 100644 --- a/spec/test-vectors/test_contract.py +++ b/spec/test-vectors/test_contract.py @@ -24,7 +24,8 @@ "synthetic.disabled_key": "unknown_key", "synthetic.jwk_only_key": "verified", "synthetic.raw_key_beats_jwk": "invalid", - "synthetic.payload_hash_mismatch": "mismatch", + "synthetic.payload_hash_mismatch": "verified", + "synthetic.float_payload_verifies": "verified", "synthetic.unsupported_alg": "unsupported", "synthetic.unsupported_canonicalization": "unsupported", "synthetic.envelope_kid_mismatch": "mismatch", @@ -104,8 +105,18 @@ def test_unsupported_alg_is_inside_the_signed_bytes_not_the_envelope(): assert case["bundle"]["alg"] == "Ed25519" -def test_payload_hash_mismatch_is_a_signature_that_still_verifies(): - """The signature covers the lying hash. The hash check is separate.""" +def test_signed_payload_hash_is_advisory_not_a_recheck(): + """The signature covers the lying hash, and that is what verifies.""" case = _by_name(_load_cases())["synthetic.payload_hash_mismatch"] signed = json.loads(case["bundle"]["signing_input"]) assert signed["payload_hash"] != generate.payload_hash(signed) + + +def test_float_payload_verifies_without_reserialization(): + """The float vector must really carry renderings other languages mangle.""" + case = _by_name(_load_cases())["synthetic.float_payload_verifies"] + raw = case["bundle"]["signing_input"] + assert '"latency_ms":0.0' in raw + assert '"injected_instructions":1.0' in raw + assert '"tiny":4e-05' in raw + assert '"big":9007199254740993' in raw diff --git a/spec/test-vectors/test_generate.py b/spec/test-vectors/test_generate.py index 811a81e4a..c7fd50723 100644 --- a/spec/test-vectors/test_generate.py +++ b/spec/test-vectors/test_generate.py @@ -69,7 +69,8 @@ def _verifier(): "synthetic.envelope_kid_mismatch": "mismatch", "synthetic.envelope_alg_mismatch": "mismatch", "synthetic.envelope_canonicalization_mismatch": "mismatch", - "synthetic.payload_hash_mismatch": "mismatch", + "synthetic.payload_hash_mismatch": "verified", + "synthetic.float_payload_verifies": "verified", "synthetic.jwk_only_key": "verified", "synthetic.raw_key_beats_jwk": "invalid", "synthetic.short_raw_key_uses_jwk": "verified", @@ -172,14 +173,19 @@ def test_wrong_raw_key_is_not_rescued_by_a_matching_jwk(generated): assert rescued.status.value == "verified" -def test_payload_hash_lie_and_kid_downgrade_are_rejected(generated): +def test_signed_payload_hash_lie_still_verifies(generated): key_set_from_document, verify_bundle = _verifier() _module, receipts, keys = generated active = key_set_from_document(keys) by_name = _by_name(receipts) lied = verify_bundle(by_name["synthetic.payload_hash_mismatch"]["bundle"], active) - assert lied.status.value == "mismatch" + assert lied.status.value == "verified" + + floats = verify_bundle( + by_name["synthetic.float_payload_verifies"]["bundle"], active + ) + assert floats.status.value == "verified" def test_outcome_tamper_only_prefixes_the_signed_outcome(generated): module, receipts, _keys = generated