diff --git a/CHANGELOG.md b/CHANGELOG.md index 028986d8d..59dda7db7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ This repository starts with a fresh history. Releases are listed here once tagge loading the calls file raises `ReplayError` naming the record. - Replay: new `amw-replay --require-verified` flag exits 2 unless every recorded receipt verified against `--recorded-keys`. +- Receipts: new optional signed fields `enforcement_mode` ("enforce" or + "permissive") and `gateway_build` (build commit). Each is signed only when set, + so older receipts still verify. Migration 052 adds the columns. - Replay: whitespace-only recorded `approval_id` now raises `ReplayError` like the empty string, and `amw-replay` writes `receipts.jsonl`, `summary.json`, and `keys.json` atomically (temp file in the output dir, then rename), leaving no diff --git a/gateway/app/db/models.py b/gateway/app/db/models.py index 5e26cb410..474be7e48 100644 --- a/gateway/app/db/models.py +++ b/gateway/app/db/models.py @@ -897,6 +897,10 @@ class ReceiptModel(SQLModel, table=True): # Signed only when present so receipts created before migration 032 keep # verifying byte-for-byte. reason_code: Optional[str] = Field(default=None, max_length=128) + # Provenance signed into receipts issued from 052 onward. NULL on legacy + # receipts, whose signatures do not cover these fields. + enforcement_mode: Optional[str] = Field(default=None, max_length=16) + gateway_build: Optional[str] = Field(default=None, max_length=64) audit_event_id: Optional[str] = Field( default=None, max_length=50, diff --git a/gateway/app/schemas/trust.py b/gateway/app/schemas/trust.py index e62eccf81..734dd9a4f 100644 --- a/gateway/app/schemas/trust.py +++ b/gateway/app/schemas/trust.py @@ -320,6 +320,10 @@ class ReceiptResponse(ActionPermitFields): credits_charged: Decimal outcome: str reason_code: str | None = None + # "enforce" when trust mode refuses unpermitted calls, else "permissive". + enforcement_mode: str | None = None + # Commit SHA of the gateway image that signed the receipt, when known. + gateway_build: str | None = None audit_event_id: str | None # Human approval that authorized this invoke, when the permit required one. approval_id: str | None = None diff --git a/gateway/app/services/receipts.py b/gateway/app/services/receipts.py index dd6cfd408..6d601ba46 100644 --- a/gateway/app/services/receipts.py +++ b/gateway/app/services/receipts.py @@ -11,6 +11,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.sql.elements import ColumnElement +from app.core.build_metadata import get_build_commit_sha from app.core.config import DuplicateGuardMode, get_settings from app.core.resilience import run_with_write_conflict_retry from app.core.time import utc_now @@ -80,6 +81,14 @@ def _action_binding(model: PermitModel | ReceiptModel) -> dict[str, Any]: return ActionPermitFields.model_validate(values).model_dump(exclude_none=True) +def receipt_enforcement_mode() -> str | None: + """The trust posture this process enforces, as signed into receipts.""" + settings = get_settings() + if settings.TRUST_MODE_ENABLED and not settings.ALLOW_LEGACY_UNPERMITTED_MCP: + return "enforce" + return "permissive" + + def receipt_model_to_response(model: ReceiptModel) -> ReceiptResponse: return ReceiptResponse( **_action_binding(model), @@ -97,6 +106,8 @@ def receipt_model_to_response(model: ReceiptModel) -> ReceiptResponse: credits_charged=model.credits_charged, outcome=model.outcome, reason_code=model.reason_code, + enforcement_mode=model.enforcement_mode, + gateway_build=model.gateway_build, audit_event_id=model.audit_event_id, approval_id=model.approval_id, constraints_evaluated=_loads_dict(model.constraints_evaluated_json), @@ -132,6 +143,11 @@ def _verification_payload( } if model.reason_code is not None: payload["reason_code"] = model.reason_code + # Signed only when set, so receipts issued before 052 keep verifying. + if model.enforcement_mode is not None: + payload["enforcement_mode"] = model.enforcement_mode + if model.gateway_build is not None: + payload["gateway_build"] = model.gateway_build if include_linkage and model.idempotency_record_id is not None: payload["idempotency_record_id"] = model.idempotency_record_id if include_linkage and model.dispatch_attempt_id is not None: @@ -458,6 +474,12 @@ async def existing_response( } if reason_code is not None: payload["reason_code"] = reason_code + enforcement_mode = receipt_enforcement_mode() + gateway_build = get_build_commit_sha() + if enforcement_mode is not None: + payload["enforcement_mode"] = enforcement_mode + if gateway_build is not None: + payload["gateway_build"] = gateway_build # Keep historical receipt signatures valid: these additive fields are # signed only on receipts that actually carry the new linkage. if idempotency_record_id is not None: @@ -512,6 +534,8 @@ def build_model() -> ReceiptModel: credits_charged=credits_charged, outcome=outcome, reason_code=reason_code, + enforcement_mode=enforcement_mode, + gateway_build=gateway_build, audit_event_id=audit_event_id, approval_id=approval_id, constraints_evaluated_json=json.dumps(constraints_evaluated) diff --git a/gateway/docs/openapi.json b/gateway/docs/openapi.json index 029ddb6c9..d0e6920d0 100644 --- a/gateway/docs/openapi.json +++ b/gateway/docs/openapi.json @@ -10133,6 +10133,28 @@ ], "title": "Reason Code" }, + "enforcement_mode": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Enforcement Mode" + }, + "gateway_build": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Gateway Build" + }, "audit_event_id": { "anyOf": [ { diff --git a/gateway/docs/schema-052-rollout.md b/gateway/docs/schema-052-rollout.md new file mode 100644 index 000000000..7efb29f68 --- /dev/null +++ b/gateway/docs/schema-052-rollout.md @@ -0,0 +1,21 @@ +# Schema 052: receipt enforcement mode and gateway build + +Migration `052_receipt_mode_build` revises `051_sqlite_boolean_defaults`. It +adds nullable `receipts.enforcement_mode` (`enforce` or `permissive`) and +`receipts.gateway_build` (the image commit SHA from +`app.core.build_metadata.get_build_commit_sha`, NULL when unknown). Receipts +issued after 052 sign both fields when set; existing receipts stay NULL and +keep verifying with their original signatures. No row is updated. + +## Compatibility release + +Production boot requires the database revision to match the packaged head, so +a 051-packaged image cannot restart after 052 is applied. Qualify a +052-capable image against a disposable PostgreSQL upgrade from 051 first. +These release checks have not been run against staging or production. + +## Rollback boundary + +Downgrade to 051 refuses while any receipt carries either field, because +dropping signed fields would make those receipts fail verification. Recover +with a 052-capable image and the database left at 052. diff --git a/gateway/migrations/versions/052_receipt_mode_build.py b/gateway/migrations/versions/052_receipt_mode_build.py new file mode 100644 index 000000000..8e14bd686 --- /dev/null +++ b/gateway/migrations/versions/052_receipt_mode_build.py @@ -0,0 +1,52 @@ +"""Record the enforcement mode and gateway build on receipts. + +Revision ID: 052_receipt_mode_build +Revises: 051_sqlite_boolean_defaults + +Adds nullable ``receipts.enforcement_mode`` and ``receipts.gateway_build``. +Existing receipts stay NULL, and their signatures do not cover these fields, +so they keep verifying. Columns are added only when missing. +""" + +import sqlalchemy as sa +from alembic import op + +revision: str = "052_receipt_mode_build" +down_revision: str = "051_sqlite_boolean_defaults" +branch_labels = None +depends_on = None + +COLUMNS = (("enforcement_mode", 16), ("gateway_build", 64)) + + +def upgrade() -> None: + existing = {c["name"] for c in sa.inspect(op.get_bind()).get_columns("receipts")} + missing = [(name, size) for name, size in COLUMNS if name not in existing] + if not missing: + return + with op.batch_alter_table("receipts") as batch_op: + for name, size in missing: + batch_op.add_column(sa.Column(name, sa.String(length=size), nullable=True)) + + +def downgrade() -> None: + # A receipt signed with these fields cannot verify once they are dropped, + # so refuse rather than silently invalidate signed evidence. + signed = ( + op.get_bind() + .execute( + sa.text( + "SELECT COUNT(*) FROM receipts " + "WHERE enforcement_mode IS NOT NULL OR gateway_build IS NOT NULL" + ) + ) + .scalar_one() + ) + if signed: + raise RuntimeError( + f"052 downgrade refused: {signed} receipt(s) carry signed " + "enforcement_mode/gateway_build values that 051 cannot store" + ) + with op.batch_alter_table("receipts") as batch_op: + batch_op.drop_column("gateway_build") + batch_op.drop_column("enforcement_mode") diff --git a/gateway/tests/fixtures/receipt_signing_golden/success_enforcement_build.json b/gateway/tests/fixtures/receipt_signing_golden/success_enforcement_build.json new file mode 100644 index 000000000..d33454534 --- /dev/null +++ b/gateway/tests/fixtures/receipt_signing_golden/success_enforcement_build.json @@ -0,0 +1,5 @@ +{ + "signature_b64_over_test_seed": "ij5D5zN7SmVmsdfpNdnRfcqKxefmpBkMaNl3uaQ9kzDVXsHYm8bpCTv4+uILG2nJaLk377ziq/Vgd/+elmY5Bw==", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"enforce\",\"gateway_build\":\"0123456789abcdef0123456789abcdef01234567\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"e3d1cb8f6369020b87a3ba8b48c3108e335312f145b952ca69481e893f7be090\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0005\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signing_input_sha256": "12bbc80225eede4e0e9912adf5cf9e9639823c3cb7681723ffa3be2ded27567e" +} diff --git a/gateway/tests/fixtures/receipt_signing_golden/success_permissive.json b/gateway/tests/fixtures/receipt_signing_golden/success_permissive.json new file mode 100644 index 000000000..13dfe55e9 --- /dev/null +++ b/gateway/tests/fixtures/receipt_signing_golden/success_permissive.json @@ -0,0 +1,5 @@ +{ + "signature_b64_over_test_seed": "0yzqc74K4pSRk4GTbh84j9oT0p2x1PF5nql2o3nj4uogrUBEukMfd8WDMlBrNsSrsXFbugLlSKWcex5ONB8xCg==", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"permissive\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"cf576b4daa8eb839999dc82d2c11bd21b37d522caefcbcc916d0dfee35947eff\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0006\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signing_input_sha256": "b6974c6a391007871b52f9b076aac25b8053ada1dadb2c2c8ca81a82b025fd9b" +} diff --git a/gateway/tests/test_action_migrations.py b/gateway/tests/test_action_migrations.py index bab9e443e..bd13ab577 100644 --- a/gateway/tests/test_action_migrations.py +++ b/gateway/tests/test_action_migrations.py @@ -29,6 +29,7 @@ "action_public_tool_id", "action_upstream_binding_hash", ) +RECEIPT_PROVENANCE_FIELDS = ("enforcement_mode", "gateway_build") ACTION_REVISION = "042_permit_action_binding" SCRUB_REVISION = "041_scrub_content_owner_keys" CONTENT_TABLES = ("content_pipelines", "content_campaigns") @@ -230,7 +231,8 @@ def sql(statement): {"version_num": head_revision} ] for table, old in before.items(): - assert sql(f"SELECT * FROM {table}")[0] == {**old, **dict.fromkeys(FIELDS)} + new_fields = FIELDS + (RECEIPT_PROVENANCE_FIELDS if table == "receipts" else ()) + assert sql(f"SELECT * FROM {table}")[0] == {**old, **dict.fromkeys(new_fields)} for table in CONTENT_TABLES: assert sql(f"SELECT owner_key FROM {table} ORDER BY owner_key") == [ {"owner_key": ""}, @@ -247,7 +249,8 @@ def sql(statement): result = migrate(url, "head") assert result.returncode == 0, result.stderr for table, old in before.items(): - assert sql(f"SELECT * FROM {table}")[0] == {**old, **dict.fromkeys(FIELDS)} + new_fields = FIELDS + (RECEIPT_PROVENANCE_FIELDS if table == "receipts" else ()) + assert sql(f"SELECT * FROM {table}")[0] == {**old, **dict.fromkeys(new_fields)} assert sql( "SELECT column_name FROM information_schema.columns " f"WHERE table_schema='public' AND table_name='{table}' " diff --git a/gateway/tests/test_policy_replay.py b/gateway/tests/test_policy_replay.py index ec325a084..b46f6a78e 100644 --- a/gateway/tests/test_policy_replay.py +++ b/gateway/tests/test_policy_replay.py @@ -47,9 +47,13 @@ #: human-approval rule below. NO_APPROVAL_SUCCESSES = { "success_action_v1.json", + "success_enforcement_build.json", "success_legacy.json", "success_linked.json", + "success_permissive.json", } +# The corpus is every golden receipt; counts follow the fixture set. +GOLDEN_COUNT = len(list(GOLDEN_DIR.glob("*.json"))) def _recorded_keys(): @@ -147,7 +151,7 @@ def _audit(event: str, _args) -> None: def test_replay_forwards_nothing_library(tmp_path, tripwire): result = replay_calls(_calls(), load_policy_bundle(_approval_rule(tmp_path))) - assert len(result.receipts) == 6 + assert len(result.receipts) == GOLDEN_COUNT assert tripwire.calls == [] assert tripwire.socket_events == [] @@ -169,7 +173,7 @@ def test_replay_forwards_nothing_cli(tmp_path, tripwire, capsys): assert tripwire.calls == [] assert tripwire.socket_events == [] lines = (tmp_path / "out" / "receipts.jsonl").read_text().splitlines() - assert len(lines) == 6 + assert len(lines) == GOLDEN_COUNT def test_network_is_sealed_during_replay(): @@ -188,7 +192,7 @@ def test_network_is_sealed_during_replay(): def test_one_signed_receipt_per_call_verifies(tmp_path): calls = _calls() result = replay_calls(calls, load_policy_bundle(_approval_rule(tmp_path))) - assert len(result.receipts) == len(calls) == 6 + assert len(result.receipts) == len(calls) == GOLDEN_COUNT assert sorted(_claims(r)["call_hash"] for r in result.receipts) == sorted( c.call_hash for c in calls ) @@ -307,8 +311,10 @@ def test_summary_counts_match_receipts(tmp_path): json.loads(line) for line in (out / "receipts.jsonl").read_text().splitlines() ] changes = [_claims(r)["change"] for r in receipts] - assert summary["total"] == len(receipts) == 6 - assert summary["allow_to_deny"] == changes.count("allow_to_deny") == 5 + assert summary["total"] == len(receipts) == GOLDEN_COUNT + assert ( + summary["allow_to_deny"] == changes.count("allow_to_deny") == GOLDEN_COUNT - 1 + ) assert summary["deny_to_allow"] == changes.count("deny_to_allow") == 0 assert summary["unchanged"] == changes.count("unchanged") == 1 assert ( @@ -691,7 +697,7 @@ def test_replay_receipt_marks_verified_recordings(tmp_path): result = replay_calls(calls, load_policy_bundle(_approval_rule(tmp_path))) assert [_claims(r)["recorded_signature_verified"] for r in result.receipts] == [ True - ] * 6 + ] * GOLDEN_COUNT def test_replay_receipt_marks_unverified_recordings(tmp_path): @@ -700,7 +706,7 @@ def test_replay_receipt_marks_unverified_recordings(tmp_path): result = replay_calls(calls, load_policy_bundle(_approval_rule(tmp_path))) assert [_claims(r)["recorded_signature_verified"] for r in result.receipts] == [ False - ] * 6 + ] * GOLDEN_COUNT def test_recorded_envelope_mismatch_raises(tmp_path): @@ -752,7 +758,7 @@ def test_replay_daily_spend_limit_without_usage_denies(tmp_path): result = replay_calls( _calls(), load_policy_bundle(_bundle(tmp_path, {"daily_spend_limit": "100.00"})) ) - assert len(result.receipts) == 6 + assert len(result.receipts) == GOLDEN_COUNT for receipt in result.receipts: claims = _claims(receipt) if claims["old_decision"] == "deny": @@ -1027,7 +1033,7 @@ def _strip_verification(path, **kwargs): ) assert code == 2 captured = capsys.readouterr() - assert "6 unverified" in captured.err + assert f"{GOLDEN_COUNT} unverified" in captured.err assert captured.out == "" assert not (out / "summary.json").exists() assert not (out / "receipts.jsonl").exists() @@ -1050,7 +1056,7 @@ def test_cli_require_verified_passes_when_all_verified(tmp_path, capsys): ) assert code == 0, capsys.readouterr().err summary = json.loads((out / "summary.json").read_text()) - assert summary["total"] == 6 + assert summary["total"] == GOLDEN_COUNT # --- 24. CLI outputs are written atomically ----------------------------------- @@ -1195,9 +1201,9 @@ def test_cli_overwrite_prepopulated_out_writes_new_contents(tmp_path, capsys): for name, content in old.items(): assert (out / name).read_text() != content summary = json.loads((out / "summary.json").read_text()) - assert summary["total"] == 6 + assert summary["total"] == GOLDEN_COUNT receipts = (out / "receipts.jsonl").read_text().splitlines() - assert len(receipts) == 6 + assert len(receipts) == GOLDEN_COUNT def test_cli_backup_link_failure_falls_back_to_copy(tmp_path, capsys, monkeypatch): diff --git a/gateway/tests/test_receipt_mode_build.py b/gateway/tests/test_receipt_mode_build.py new file mode 100644 index 000000000..0da3a349a --- /dev/null +++ b/gateway/tests/test_receipt_mode_build.py @@ -0,0 +1,145 @@ +"""Receipts sign the enforcement mode and gateway build they were issued under.""" + +from __future__ import annotations + +import json +from decimal import Decimal + +import pytest +from httpx import ASGITransport, AsyncClient + +from app.db.database import get_session_factory +from app.db.models import ReceiptModel +from app.main import app +from app.services import receipts as receipts_module +from app.services.receipts import ReceiptService, get_receipt_service +from tests.test_trust_helpers import create_tool_permit, provision_agent_wallet + +BUILD = "e70595326d57e9ac3f8e2eacff53536212f57c1b" +OTHER_BUILD = "e3bf41bc6ddbb245b8205b1329be6497a0462074" + + +@pytest.fixture +async def client(): + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as c: + yield c + + +async def _issue( + client, monkeypatch, *, build: str | None, tool: str, mode: str | None = "enforce" +): + monkeypatch.setattr(receipts_module, "get_build_commit_sha", lambda: build) + monkeypatch.setattr(receipts_module, "receipt_enforcement_mode", lambda: mode) + provisioned = await provision_agent_wallet(client) + permit = await create_tool_permit( + client, + wallet_id=provisioned["agent_wallet_id"], + key_id=provisioned["key_id"], + tool_name=tool, + idem_key=f"permit-{tool}", + ) + return await get_receipt_service().create_receipt( + permit_id=permit["permit_id"], + wallet_id=provisioned["agent_wallet_id"], + key_id=provisioned["key_id"], + tool=tool, + request_payload={"v": 1}, + response_payload=None, + ledger_entry_id=None, + credits_authorized=Decimal("1"), + credits_charged=Decimal("0"), + outcome="denied", + reason_code="permit_tool_not_allowed", + audit_event_id=None, + ) + + +async def _mutate(receipt_id: str, **fields) -> None: + async with get_session_factory()() as session: + model = await session.get(ReceiptModel, receipt_id) + for key, value in fields.items(): + setattr(model, key, value) + session.add(model) + await session.commit() + + +def _verify(receipt_id: str): + return get_receipt_service().verify_receipt(receipt_id) + + +@pytest.mark.anyio +async def test_new_receipt_signs_mode_and_build(client, clean_database, monkeypatch): + receipt = await _issue(client, monkeypatch, build=BUILD, tool="mode-build-echo") + assert receipt.enforcement_mode == "enforce" + assert receipt.gateway_build == BUILD + ok, _, _ = await _verify(receipt.receipt_id) + assert ok + async with get_session_factory()() as session: + model = await session.get(ReceiptModel, receipt.receipt_id) + signed = json.loads( + await ReceiptService().signing_input_for_model(model, session=session) + ) + assert signed["enforcement_mode"] == "enforce" + assert signed["gateway_build"] == BUILD + + +@pytest.mark.anyio +async def test_unknown_build_is_omitted_but_mode_signed( + client, clean_database, monkeypatch +): + receipt = await _issue(client, monkeypatch, build=None, tool="mode-nobuild-echo") + assert receipt.gateway_build is None + assert receipt.enforcement_mode == "enforce" + assert (await _verify(receipt.receipt_id))[0] + + +@pytest.mark.anyio +@pytest.mark.parametrize( + "fields", + [ + {"enforcement_mode": "permissive"}, + {"gateway_build": OTHER_BUILD}, + {"enforcement_mode": None}, + {"gateway_build": None}, + ], +) +async def test_tampering_breaks_verification( + client, clean_database, monkeypatch, fields +): + receipt = await _issue(client, monkeypatch, build=BUILD, tool="mode-tamper-echo") + await _mutate(receipt.receipt_id, **fields) + assert not (await _verify(receipt.receipt_id))[0] + + +@pytest.mark.anyio +async def test_legacy_receipt_without_fields_still_verifies( + client, clean_database, monkeypatch +): + """A receipt signed before 052 has neither field and must keep verifying.""" + receipt = await _issue( + client, monkeypatch, build=None, tool="mode-legacy-echo", mode=None + ) + assert receipt.enforcement_mode is None and receipt.gateway_build is None + assert (await _verify(receipt.receipt_id))[0] + # Adding a field after the fact is tampering too. + await _mutate(receipt.receipt_id, enforcement_mode="enforce") + assert not (await _verify(receipt.receipt_id))[0] + + +def test_permissive_mode_reported(monkeypatch): + class _S: + TRUST_MODE_ENABLED = False + ALLOW_LEGACY_UNPERMITTED_MCP = True + + monkeypatch.setattr(receipts_module, "get_settings", lambda: _S()) + assert receipts_module.receipt_enforcement_mode() == "permissive" + + +def test_enforce_mode_reported(monkeypatch): + class _S: + TRUST_MODE_ENABLED = True + ALLOW_LEGACY_UNPERMITTED_MCP = False + + monkeypatch.setattr(receipts_module, "get_settings", lambda: _S()) + assert receipts_module.receipt_enforcement_mode() == "enforce" diff --git a/gateway/tests/test_receipt_signing_input_snapshot.py b/gateway/tests/test_receipt_signing_input_snapshot.py index 2e030a355..1a8dee350 100644 --- a/gateway/tests/test_receipt_signing_input_snapshot.py +++ b/gateway/tests/test_receipt_signing_input_snapshot.py @@ -5,7 +5,7 @@ or the payload_hash derivation changes what an offline verifier must reconstruct, and silently invalidates every receipt already issued. -This test freezes five representative receipts to byte-exact canonical +This test freezes representative receipts to byte-exact canonical JSON, and freezes the Ed25519 signature over those bytes under a fixed test seed (Ed25519 is deterministic, so the signature is a second pin on the same bytes). @@ -91,6 +91,24 @@ def _base_model(**overrides) -> ReceiptModel: ), True, ), + # Migration 052 signs enforcement_mode and gateway_build only when set. + # Pin both populated, and enforcement_mode alone, so a refactor cannot + # drop or reorder either field while the omitted-field goldens stay green. + "success_enforcement_build": ( + _base_model( + receipt_id="rcpt_golden_0005", + enforcement_mode="enforce", + gateway_build="0123456789abcdef0123456789abcdef01234567", + ), + True, + ), + "success_permissive": ( + _base_model( + receipt_id="rcpt_golden_0006", + enforcement_mode="permissive", + ), + True, + ), # Current-format success receipt with full governed-dispatch linkage. "success_linked": (_base_model(), True), # Legacy-format signature: linkage fields excluded from signing input. diff --git a/gateway/tests/test_spec_conformance.py b/gateway/tests/test_spec_conformance.py index 4b1052f18..d7af933ca 100644 --- a/gateway/tests/test_spec_conformance.py +++ b/gateway/tests/test_spec_conformance.py @@ -100,8 +100,8 @@ "payload_hash", } # Additive receipt members named in spec/receipt-v0.1.md ("approval ids, -# action bindings, constraint denials") plus reason_code, which the gateway -# signs when present. +# action bindings, constraint denials, enforcement posture") plus reason_code, +# which the gateway signs when present. RECEIPT_ADDITIVE = { "reason_code", "approval_id", @@ -112,6 +112,8 @@ "action_schema_version", "action_public_tool_id", "action_upstream_binding_hash", + "enforcement_mode", + "gateway_build", } # Always-signed receipt members: present even when the value is null. RECEIPT_ALWAYS_SIGNED = RECEIPT_DOCUMENTED - { diff --git a/gateway/tests/test_sqlite_legacy_boolean_defaults.py b/gateway/tests/test_sqlite_legacy_boolean_defaults.py index 0b958858b..e6f34b716 100644 --- a/gateway/tests/test_sqlite_legacy_boolean_defaults.py +++ b/gateway/tests/test_sqlite_legacy_boolean_defaults.py @@ -35,7 +35,7 @@ def _defaults(connection): def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): script = ScriptDirectory.from_config(Config("alembic.ini")) - assert script.get_heads() == ["051_sqlite_boolean_defaults"] + assert len(script.get_heads()) == 1 assert script.get_revision("051_sqlite_boolean_defaults").down_revision == ( "050_demo_key_first_used" ) @@ -117,7 +117,7 @@ def test_upgrade_repairs_legacy_sqlite_defaults(tmp_path, monkeypatch): for table, _ in _COLUMNS } - _upgrade(monkeypatch, db_path, "head") + _upgrade(monkeypatch, db_path, "051_sqlite_boolean_defaults") with sqlite3.connect(db_path) as connection: assert set(_defaults(connection).values()) == {"0"} for table, column, key in ( diff --git a/spec/receipt-v0.1.md b/spec/receipt-v0.1.md index 0364aadb7..258581570 100644 --- a/spec/receipt-v0.1.md +++ b/spec/receipt-v0.1.md @@ -43,10 +43,12 @@ of its own, is a `mismatch`. | `created_at` | ISO-8601 UTC | | `alg`, `kid`, `payload_hash` | See [`README.md`](README.md) | -Additional members (approval ids, action bindings, constraint denials) are -additive, as for permits. `reason_code`, `approval_id`, -`constraints_evaluated`, and the action-binding members are omitted when they -have no value. `idempotency_record_id` and `dispatch_attempt_id` are omitted +Additional members (approval ids, action bindings, constraint denials, +enforcement posture) are additive, as for permits. `enforcement_mode` is +`"enforce"` or `"permissive"`, the trust posture the issuing gateway enforced. +`gateway_build` is the commit SHA of the issuing gateway build. `reason_code`, +`approval_id`, `constraints_evaluated`, `enforcement_mode`, `gateway_build`, +and the action-binding members are omitted when they have no value. `idempotency_record_id` and `dispatch_attempt_id` are omitted unless that signature included linkage, so an older success receipt can omit both. `response_hash` and `ledger_entry_id` are not omitted: they are JSON `null` instead. Dropping a null changes the signed bytes. diff --git a/spec/test-vectors/receipts.json b/spec/test-vectors/receipts.json index b78911693..b8d3d5d2d 100644 --- a/spec/test-vectors/receipts.json +++ b/spec/test-vectors/receipts.json @@ -190,6 +190,69 @@ }, "expect": "unknown_key" }, + { + "name": "success_enforcement_build.valid", + "bundle": { + "receipt_id": "rcpt_golden_0005", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"enforce\",\"gateway_build\":\"0123456789abcdef0123456789abcdef01234567\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"e3d1cb8f6369020b87a3ba8b48c3108e335312f145b952ca69481e893f7be090\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0005\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "ij5D5zN7SmVmsdfpNdnRfcqKxefmpBkMaNl3uaQ9kzDVXsHYm8bpCTv4+uILG2nJaLk377ziq/Vgd/+elmY5Bw==" + }, + "expect": "verified" + }, + { + "name": "success_enforcement_build.bad_signature", + "bundle": { + "receipt_id": "rcpt_golden_0005", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"enforce\",\"gateway_build\":\"0123456789abcdef0123456789abcdef01234567\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"e3d1cb8f6369020b87a3ba8b48c3108e335312f145b952ca69481e893f7be090\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0005\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "iz5D5zN7SmVmsdfpNdnRfcqKxefmpBkMaNl3uaQ9kzDVXsHYm8bpCTv4+uILG2nJaLk377ziq/Vgd/+elmY5Bw==" + }, + "expect": "invalid" + }, + { + "name": "success_enforcement_build.tampered_payload", + "bundle": { + "receipt_id": "rcpt_golden_0005", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"enforce\",\"gateway_build\":\"0123456789abcdef0123456789abcdef01234567\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"xsuccess\",\"payload_hash\":\"e3d1cb8f6369020b87a3ba8b48c3108e335312f145b952ca69481e893f7be090\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0005\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "ij5D5zN7SmVmsdfpNdnRfcqKxefmpBkMaNl3uaQ9kzDVXsHYm8bpCTv4+uILG2nJaLk377ziq/Vgd/+elmY5Bw==" + }, + "expect": "invalid" + }, + { + "name": "success_enforcement_build.envelope_receipt_id_mismatch", + "bundle": { + "receipt_id": "rcpt_not_the_signed_one", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"enforce\",\"gateway_build\":\"0123456789abcdef0123456789abcdef01234567\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"e3d1cb8f6369020b87a3ba8b48c3108e335312f145b952ca69481e893f7be090\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0005\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "ij5D5zN7SmVmsdfpNdnRfcqKxefmpBkMaNl3uaQ9kzDVXsHYm8bpCTv4+uILG2nJaLk377ziq/Vgd/+elmY5Bw==" + }, + "expect": "mismatch" + }, + { + "name": "success_enforcement_build.unknown_key", + "bundle": { + "receipt_id": "rcpt_golden_0005", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"enforce\",\"gateway_build\":\"0123456789abcdef0123456789abcdef01234567\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"e3d1cb8f6369020b87a3ba8b48c3108e335312f145b952ca69481e893f7be090\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0005\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "ij5D5zN7SmVmsdfpNdnRfcqKxefmpBkMaNl3uaQ9kzDVXsHYm8bpCTv4+uILG2nJaLk377ziq/Vgd/+elmY5Bw==" + }, + "keys": { + "keys": [] + }, + "expect": "unknown_key" + }, { "name": "success_legacy.valid", "bundle": { @@ -379,6 +442,69 @@ }, "expect": "unknown_key" }, + { + "name": "success_permissive.valid", + "bundle": { + "receipt_id": "rcpt_golden_0006", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"permissive\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"cf576b4daa8eb839999dc82d2c11bd21b37d522caefcbcc916d0dfee35947eff\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0006\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "0yzqc74K4pSRk4GTbh84j9oT0p2x1PF5nql2o3nj4uogrUBEukMfd8WDMlBrNsSrsXFbugLlSKWcex5ONB8xCg==" + }, + "expect": "verified" + }, + { + "name": "success_permissive.bad_signature", + "bundle": { + "receipt_id": "rcpt_golden_0006", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"permissive\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"cf576b4daa8eb839999dc82d2c11bd21b37d522caefcbcc916d0dfee35947eff\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0006\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "0izqc74K4pSRk4GTbh84j9oT0p2x1PF5nql2o3nj4uogrUBEukMfd8WDMlBrNsSrsXFbugLlSKWcex5ONB8xCg==" + }, + "expect": "invalid" + }, + { + "name": "success_permissive.tampered_payload", + "bundle": { + "receipt_id": "rcpt_golden_0006", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"permissive\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"xsuccess\",\"payload_hash\":\"cf576b4daa8eb839999dc82d2c11bd21b37d522caefcbcc916d0dfee35947eff\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0006\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "0yzqc74K4pSRk4GTbh84j9oT0p2x1PF5nql2o3nj4uogrUBEukMfd8WDMlBrNsSrsXFbugLlSKWcex5ONB8xCg==" + }, + "expect": "invalid" + }, + { + "name": "success_permissive.envelope_receipt_id_mismatch", + "bundle": { + "receipt_id": "rcpt_not_the_signed_one", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"permissive\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"cf576b4daa8eb839999dc82d2c11bd21b37d522caefcbcc916d0dfee35947eff\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0006\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "0yzqc74K4pSRk4GTbh84j9oT0p2x1PF5nql2o3nj4uogrUBEukMfd8WDMlBrNsSrsXFbugLlSKWcex5ONB8xCg==" + }, + "expect": "mismatch" + }, + { + "name": "success_permissive.unknown_key", + "bundle": { + "receipt_id": "rcpt_golden_0006", + "kid": "sk_golden_0001", + "alg": "Ed25519", + "canonicalization": "awi-canonical-json/1", + "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\",\"dispatch_attempt_id\":\"disp_golden_0001\",\"enforcement_mode\":\"permissive\",\"idempotency_record_id\":\"idem_golden_0001\",\"key_id\":\"key_golden_0001\",\"kid\":\"sk_golden_0001\",\"ledger_entry_id\":\"led_golden_0001\",\"outcome\":\"success\",\"payload_hash\":\"cf576b4daa8eb839999dc82d2c11bd21b37d522caefcbcc916d0dfee35947eff\",\"permit_id\":\"pmt_golden_0001\",\"receipt_id\":\"rcpt_golden_0006\",\"request_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"response_hash\":\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\",\"tool\":\"golden-path-echo\",\"wallet_id\":\"agt-golden-0001\"}", + "signature": "0yzqc74K4pSRk4GTbh84j9oT0p2x1PF5nql2o3nj4uogrUBEukMfd8WDMlBrNsSrsXFbugLlSKWcex5ONB8xCg==" + }, + "keys": { + "keys": [] + }, + "expect": "unknown_key" + }, { "name": "synthetic.disabled_key", "bundle": {