diff --git a/claude-code/CHANGELOG.md b/claude-code/CHANGELOG.md index 9f7a099f..8a537082 100644 --- a/claude-code/CHANGELOG.md +++ b/claude-code/CHANGELOG.md @@ -5,6 +5,26 @@ All notable changes to the AgenTrust for Claude Code plugin. ## Unreleased ### Fixed +- **An unreadable signing key is no longer replaced with a new one.** A corrupt + or invalid `signing_key.json` minted a fresh identity and overwrote the file, + so anyone who pinned the old key saw verification fail with nothing to say + why. It now stops and names the file, as the Codex plugin does. A new key is + written through a temporary file at 0600, so it is never readable by others, + even briefly; before, it was written at the umask and narrowed afterwards. +- **A catalog no verifier would accept is refused instead of hashed.** The + catalog root now refuses what the SDK's builder refuses: a repeated or + NUL-carrying `tool_id`, a digest that is not sha256 hex, more than 1,000,000 + tools. +- **The manifest's `tool_manifest.catalog_hash` no longer contradicts its own + tool list.** It was a SHA-256 over the tool names, while agent-manifest spec + 3.2.3 defines it as the RFC 9162 Merkle root over the listed tools, which a + verifier recomputes. Every manifest therefore verified as `MISMATCH`, and the + tests checked only `signature_verified`, so it went unnoticed. The root now + follows the spec and is checked against the SDK's own construction. +- **`verification_key.json` now names the issuer its key signs for.** A verifier + needs that under agent-manifest spec 5.3.3, and agent-manifest 0.16 reports a + manifest checked without it as `UNVERIFIABLE`. The README snippet passes it as + `trusted_key_issuers`. - **The TRACE Trust Record is signed with the plugin's persisted key, not a throwaway one.** `sign_all` called `agentrust_trace.generate_key()` for each record, so the private half was discarded at once and the only copy of the diff --git a/claude-code/README.md b/claude-code/README.md index 23679217..76f2c7f3 100644 --- a/claude-code/README.md +++ b/claude-code/README.md @@ -137,13 +137,15 @@ files: ([trace-spec](https://github.com/agentrust-io/trace-spec)). - **`verification_key.json`**, the public key for the manifest. -These are shareable proof a third party can verify without trusting your machine. +A third party can verify both against a key they have pinned, without trusting +your machine. The manifest is signed with a **persistent** key kept at `~/.claude/agentrust/signing_key.json`. It is generated once, reused every run, and its private half never leaves your machine, so every record you produce carries the same signing identity. `verification_key.json` publishes only the -public half (`{key_id, public_key_b64url}`). +public half (`{key_id, public_key_b64url}`) and the issuer it signs for +(`issuers`), which a verifier needs under agent-manifest spec 5.3.3. Confirm the TRACE record against the conformance suite: @@ -153,17 +155,34 @@ trace-tests verify --record trace.json --level 0 python -m trace_tests.cli verify --record trace.json --level 0 ``` -Verify the Agent Manifest on any machine, using only the published public key: +Verify the Agent Manifest on any machine against a key you have pinned. The +key, and the issuer it signs for, are your own trust decision: take them once +from a channel you trust, such as the producing machine or its owner, and keep +them. Copied from `verification_key.json` alone they prove only that whoever +wrote these files signed them. The issuer is `spiffe://claude-code.local/self-signed` +on every install, so the key is what tells one producer from another; it names a +key that signs its own records, not an organization that vouched for it. ```python import json from agent_manifest import VerificationContext, verify_manifest, RevocationStore -manifest = json.load(open("manifest.json")) -vk = json.load(open("verification_key.json")) -ctx = VerificationContext(trusted_keys={vk["key_id"]: vk["public_key_b64url"]}) +PINNED_KEY_ID = "" # your pins, not read from the files +PINNED_PUBLIC_KEY = "" +PINNED_ISSUERS = ["spiffe://claude-code.local/self-signed"] + +with open("manifest.json", encoding="utf-8") as f: + manifest = json.load(f) +ctx = VerificationContext( + trusted_keys={PINNED_KEY_ID: PINNED_PUBLIC_KEY}, + trusted_key_issuers={PINNED_KEY_ID: PINNED_ISSUERS}, +) result = verify_manifest(manifest, ctx, RevocationStore()) -print(result.result, result.signature_verified) # VALID True (any tampering -> MISMATCH False) +print(result.result.name, result.signature_verified) +# INCOMPLETE True: the pinned key signed it for that issuer. INCOMPLETE because no +# artifact hashes were checked; pass system_prompt_hash, policy_bundle_hash and +# tool_catalog_hash to VerificationContext to check them too. +# Changed after signing, or another key or issuer: MISMATCH False. ``` ## Known limits (read before relying on it) diff --git a/claude-code/engine/capture.py b/claude-code/engine/capture.py index 16ba0262..70fbbb3d 100644 --- a/claude-code/engine/capture.py +++ b/claude-code/engine/capture.py @@ -31,9 +31,10 @@ import argparse import base64 +import hashlib import json import os -import stat +import re import sys import time from datetime import datetime, timedelta, timezone @@ -75,6 +76,46 @@ # hashing (files only, never secrets) # --------------------------------------------------------------------------- # _sha_bytes = core.sha_bytes + + +def _catalog_root(tools): + """agent-manifest spec 3.2.3 catalog_hash: the RFC 9162 Merkle root over the + listed tools sorted by tool_id, each leaf H(0x00 || tool_id || 0x00 || + schema digest || description digest). A verifier recomputes it from the + list, so a root built any other way makes the manifest contradict itself. + + Refuses what the SDK's builder refuses, rather than hashing a catalog no + verifier would accept: a repeated or NUL-carrying tool_id, a digest that is + not sha256 hex, more than 1,000,000 tools.""" + if len(tools) > 1000000: + raise ValueError("catalog_hash: more than 1,000,000 tools") + ids = [t["tool_id"] for t in tools] + if len(set(ids)) != len(ids) or any("\x00" in i for i in ids): + raise ValueError("catalog_hash: each tool_id must be unique and free of NUL") + + def h(data): + return hashlib.sha256(data).digest() + + def digest(value): + if not re.fullmatch(r"sha256:[0-9a-f]{64}", value): + raise ValueError("catalog_hash: %r is not a sha256 digest" % (value,)) + return bytes.fromhex(value[len("sha256:"):]) + + leaves = [ + h(b"\x00" + t["tool_id"].encode("utf-8") + b"\x00" + + digest(t["schema_hash"]) + digest(t["description_hash"])) + for t in sorted(tools, key=lambda t: t["tool_id"]) + ] + + def root(nodes): + if len(nodes) == 1: + return nodes[0] + k = 1 + while k * 2 < len(nodes): + k *= 2 + return h(b"\x01" + root(nodes[:k]) + root(nodes[k:])) + + return "sha256:" + (root(leaves) if leaves else h(b"")).hex() _sha_file = core.sha_file _uuid7 = core.uuid7 _now_iso = core.now_iso @@ -414,7 +455,7 @@ def build_manifest(cur: dict) -> dict: "bound_at": now, }, "tool_manifest": { - "catalog_hash": cur["hashes"]["tool_catalog"], + "catalog_hash": _catalog_root(tools), "tools": tools, "allow_dynamic_registration": True, "rug_pull_policy": "deny-and-alert", @@ -481,14 +522,18 @@ def sign_all(cur: dict, outdir: Path) -> tuple[dict, dict]: (outdir / "trace.json").write_text(json.dumps(trace, indent=2), encoding="utf-8") # Publish the public key so a third party can verify manifest.json and # trace.json without trusting this machine: load it into the verifier's - # trusted_keys as {key_id: public_key_b64url}. The private key never leaves - # ~/.claude. + # trusted_keys as {key_id: public_key_b64url}, and its issuers into + # trusted_key_issuers. The private key never leaves ~/.claude. verification_key = { "algorithm": "Ed25519", "key_id": kp.key_id, "public_key_b64url": kp.public_b64url(), - "note": "load as {key_id: public_key_b64url} into the verifier's trusted_keys; " - "verifies both manifest.json and trace.json, which share this key", + # The issuer this key signs for. agent-manifest spec 5.3.3 needs it. + "issuers": [manifest["issuer"]], + "note": "Verifies manifest.json and trace.json, which share this key. Pin the " + "key and its issuers through a channel you trust, then load them into " + "trusted_keys and trusted_key_issuers; copied from this file alone they " + "prove only that whoever wrote it signed both records.", } (outdir / "verification_key.json").write_text( json.dumps(verification_key, indent=2), encoding="utf-8" @@ -509,19 +554,34 @@ def _load_or_create_manifest_keypair(): from agent_manifest import Ed25519KeyPair, generate_ed25519 from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + # A key file that exists but cannot be read is never replaced: a new key + # would be a new identity, and anyone who pinned the old one would see + # verification fail with nothing to say why. existing = _load(SIGNING_KEY) - if existing and isinstance(existing.get("private_b64url"), str): + if SIGNING_KEY.exists() and not ( + existing and isinstance(existing.get("private_b64url"), str) + ): + raise SystemExit( + "The AgenTrust signing key is unreadable. Restore it from backup or move it " + "aside before generating a new identity: %s" % SIGNING_KEY + ) + if existing: try: pad = "=" * (-len(existing["private_b64url"]) % 4) raw = base64.urlsafe_b64decode(existing["private_b64url"] + pad) priv = Ed25519PrivateKey.from_private_bytes(raw) return Ed25519KeyPair(priv, priv.public_key()) except (ValueError, TypeError): - pass # corrupt key file: fall through and mint a fresh one + raise SystemExit( + "The AgenTrust signing key is invalid. Restore it or move it aside: %s" + % SIGNING_KEY + ) kp = generate_ed25519() - SIGNING_KEY.parent.mkdir(parents=True, exist_ok=True) - SIGNING_KEY.write_text( + # Written to a temporary file at 0600 and moved into place, so the private + # key is never readable by others, even briefly, whatever the umask. + core.atomic_write( + SIGNING_KEY, json.dumps( { "algorithm": "Ed25519", @@ -532,12 +592,8 @@ def _load_or_create_manifest_keypair(): }, indent=2, ), - encoding="utf-8", + mode=0o600, ) - try: # best-effort owner-only permissions (no-op on filesystems without it) - os.chmod(SIGNING_KEY, stat.S_IRUSR | stat.S_IWUSR) - except OSError: - pass return kp diff --git a/claude-code/tests/test_claude_code_capture.py b/claude-code/tests/test_claude_code_capture.py index 72fe714e..14e884ed 100644 --- a/claude-code/tests/test_claude_code_capture.py +++ b/claude-code/tests/test_claude_code_capture.py @@ -8,6 +8,7 @@ import base64 import importlib.util import json +import os from pathlib import Path import pytest @@ -539,7 +540,10 @@ def test_manifest_is_externally_verifiable_and_tamper_evident(tmp_path, monkeypa vk = json.loads((out / "verification_key.json").read_text(encoding="utf-8")) assert vk["key_id"] == manifest["signature"]["key_id"] - ctx = VerificationContext(trusted_keys={vk["key_id"]: vk["public_key_b64url"]}) + ctx = VerificationContext( + trusted_keys={vk["key_id"]: vk["public_key_b64url"]}, + trusted_key_issuers={vk["key_id"]: vk["issuers"]}, + ) # a third party with only the published public key verifies the manifest good = verify_manifest(manifest, ctx, RevocationStore()) @@ -754,3 +758,173 @@ def test_verified_digest_is_reported_together_with_its_limit(self): def test_section_is_omitted_when_integrity_was_not_checked(self): assert "BASELINE ITSELF INTACT" not in capture.render_report(self._snap(), None, False) + + +@pytest.fixture +def signed(tmp_path, monkeypatch): + pytest.importorskip("agent_manifest") + _point_signing_key(tmp_path, monkeypatch) + cur = capture.snapshot({"model_id": "claude-x", "builtin_tools": ["Bash", "Read"], "mcp_servers": ["github"]}) + manifest, trace = capture.sign_all(cur, tmp_path / "records") + vk = json.loads((tmp_path / "records" / "verification_key.json").read_text(encoding="utf-8")) + return manifest, trace, vk + + +# --------------------------------------------------------------------------- +# The published manifest is consistent, and issuer authorization holds. +# --------------------------------------------------------------------------- +def _sdk_enforces_issuer_policy(): + import importlib.metadata + + major, minor = (int(p) for p in importlib.metadata.version("agent-manifest").split(".")[:2]) + return (major, minor) >= (0, 16) + + +@pytest.mark.parametrize("count", range(10)) +def test_catalog_root_matches_the_sdk(count): + """Spec 3.2.3's Merkle root, checked against the SDK's own construction.""" + pytest.importorskip("agent_manifest") + from agent_manifest import ToolEntry + from agent_manifest._merkle import build_catalog_tree + + tools = [ + { + "tool_id": "t.%d" % ((i * 7) % 10), # unsorted on purpose + "tool_name": "t%d" % i, + "endpoint_id": "spiffe://x.local/t", + "schema_hash": "sha256:" + ("%02x" % i) * 32, + "description_hash": "sha256:" + ("%02x" % (i + 100)) * 32, + "version": "1.0.0", + "egress_destinations": [], + } + for i in range(count) + ] + expected = build_catalog_tree([ToolEntry.model_validate(t) for t in tools]) + assert capture._catalog_root(tools) == expected + + +def _verify(manifest, key_id, public_key, issuers): + from agent_manifest import RevocationStore, VerificationContext, verify_manifest + + return verify_manifest( + manifest, + VerificationContext( + trusted_keys={key_id: public_key}, + trusted_key_issuers=None if issuers is None else {key_id: issuers}, + ), + RevocationStore(), + ) + + +def test_published_manifest_does_not_contradict_itself(signed): + manifest, _trace, vk = signed + assert vk["issuers"] == [manifest["issuer"]] + result = _verify(manifest, vk["key_id"], vk["public_key_b64url"], vk["issuers"]) + assert result.signature_verified is True + assert result.fields_verified.tool_manifest.name != "MISMATCH" + assert result.result.name != "MISMATCH" + + +@pytest.mark.parametrize( + "issuers", + [ + ["spiffe://elsewhere.example/issuer"], + [], + ], + ids=["another-issuer", "empty-list"], +) +def test_a_key_not_authorized_for_the_issuer_is_refused(signed, issuers): + manifest, _trace, vk = signed + result = _verify(manifest, vk["key_id"], vk["public_key_b64url"], issuers) + assert result.result.name == "MISMATCH" + assert result.signature_verified is False + + +def test_any_listed_issuer_authorizes(signed): + manifest, _trace, vk = signed + issuers = ["spiffe://elsewhere.example/issuer", manifest["issuer"]] + result = _verify(manifest, vk["key_id"], vk["public_key_b64url"], issuers) + assert result.signature_verified is True + + +def test_an_issuer_changed_after_signing_is_refused(signed): + manifest, _trace, vk = signed + tampered = json.loads(json.dumps(manifest)) + tampered["issuer"] = "spiffe://elsewhere.example/issuer" + result = _verify(tampered, vk["key_id"], vk["public_key_b64url"], [tampered["issuer"]]) + assert result.signature_verified is False + assert result.result.name != "VALID" + + +def test_the_key_must_be_trusted_under_its_own_id(signed): + manifest, _trace, vk = signed + result = _verify(manifest, "0" * 64, vk["public_key_b64url"], vk["issuers"]) + assert result.signature_verified is False + + +def test_no_issuer_policy_is_unverifiable(signed): + if not _sdk_enforces_issuer_policy(): + pytest.skip("agent-manifest < 0.16 does not require an issuer policy") + manifest, _trace, vk = signed + result = _verify(manifest, vk["key_id"], vk["public_key_b64url"], None) + assert result.result.name == "UNVERIFIABLE" + assert result.signature_verified is False + + +@pytest.mark.parametrize( + "bad, message", + [ + ([("a", "11"), ("a", "22")], "unique"), + ([("a\x00b", "11")], "NUL"), + ([("a", "sha512:" + "11" * 32)], "not a sha256 digest"), + ([("a", "sha256:" + "1" * 63)], "not a sha256 digest"), + ([("a", "sha256:" + "AB" * 32)], "not a sha256 digest"), + ], + ids=["duplicate-id", "nul-in-id", "other-algorithm", "short-digest", "uppercase-hex"], +) +def test_catalog_root_refuses_what_the_sdk_refuses(bad, message): + def tool(tool_id, digest): + value = digest if ":" in digest else "sha256:" + digest * 32 + return {"tool_id": tool_id, "schema_hash": value, "description_hash": "sha256:" + "33" * 32} + + with pytest.raises(ValueError, match=message): + capture._catalog_root([tool(i, d) for i, d in bad]) + + +def test_empty_catalog_root_is_the_rfc_9162_empty_tree(): + import hashlib + + assert capture._catalog_root([]) == "sha256:" + hashlib.sha256(b"").hexdigest() + + +@pytest.mark.parametrize( + "content", + ["{broken", "[]", '{"private_b64url": 7}', '{"private_b64url": "!!"}'], + ids=["truncated", "not-object", "wrong-type", "not-a-key"], +) +def test_an_unreadable_signing_key_is_never_replaced(tmp_path, monkeypatch, content): + """A new key is a new identity; anyone who pinned the old one would see + verification fail with nothing to say why.""" + pytest.importorskip("agent_manifest") + _point_signing_key(tmp_path, monkeypatch) + capture.SIGNING_KEY.parent.mkdir(parents=True) + capture.SIGNING_KEY.write_text(content, encoding="utf-8") + with pytest.raises(SystemExit, match="signing key is (unreadable|invalid)"): + capture._load_or_create_manifest_keypair() + assert capture.SIGNING_KEY.read_text(encoding="utf-8") == content + + +def test_new_signing_key_is_never_written_wider_than_owner_only(tmp_path, monkeypatch): + """The final mode alone cannot show it: writing then chmod-ing also ends at + 0600, but leaves the key readable in between. The key must go through the + temporary-file write that sets 0600 before any byte lands.""" + pytest.importorskip("agent_manifest") + _point_signing_key(tmp_path, monkeypatch) + writes = [] + real = capture.core.atomic_write + monkeypatch.setattr(capture.core, "atomic_write", lambda path, content, mode=None: (writes.append((path, mode)), real(path, content, mode=mode))) + monkeypatch.setattr(type(capture.SIGNING_KEY), "write_text", lambda *a, **k: pytest.fail("plain write of the key")) + capture._load_or_create_manifest_keypair() + assert writes == [(capture.SIGNING_KEY, 0o600)] + if os.name == "posix": + assert capture.SIGNING_KEY.stat().st_mode & 0o777 == 0o600 diff --git a/plugins/agentrust-codex/CHANGELOG.md b/plugins/agentrust-codex/CHANGELOG.md index d7aa7b4d..915548b9 100644 --- a/plugins/agentrust-codex/CHANGELOG.md +++ b/plugins/agentrust-codex/CHANGELOG.md @@ -4,6 +4,29 @@ All notable changes to the AgenTrust for Codex plugin. ## Unreleased +### Fixed +- **Tool names that share a slug no longer share a `tool_id`.** `foo` and `FOO` + both became `codex.mcp.foo`, which the SDK refuses, so the manifest failed its + own verification. Colliding ids now gain a short hash of the full name; every + other id is unchanged. +- **A catalog no verifier would accept is refused instead of hashed.** The + catalog root now refuses what the SDK's builder refuses: a repeated or + NUL-carrying `tool_id`, a digest that is not sha256 hex, more than 1,000,000 + tools. +- **The TRACE record is signed with the persisted key published in + `verification_key.json`, not a throwaway one.** Before, nobody could verify + `trace.json` except against the key inside it, and the agent had a new TRACE + identity every session. The Claude Code plugin fixed the same bug earlier. +- **The manifest's `tool_manifest.catalog_hash` no longer contradicts its own + tool list.** It was a SHA-256 over the tool names, while agent-manifest spec + 3.2.3 defines it as the RFC 9162 Merkle root over the listed tools, which a + verifier recomputes. Every manifest therefore verified as `MISMATCH`, and the + tests checked only `signature_verified`, so it went unnoticed. The root now + follows the spec and is checked against the SDK's own construction. +- **`verification_key.json` now names the issuer its key signs for.** A verifier + needs that under agent-manifest spec 5.3.3, and agent-manifest 0.16 reports a + manifest checked without it as `UNVERIFIABLE`. + ### Breaking - Drift detection now requires the separately published `agentrust-capture-core` package; the previous vendored fallback was removed. diff --git a/plugins/agentrust-codex/README.md b/plugins/agentrust-codex/README.md index c81a9e14..b0ecbb9b 100644 --- a/plugins/agentrust-codex/README.md +++ b/plugins/agentrust-codex/README.md @@ -108,9 +108,13 @@ exists only to make a local smoke-test command reproducible. hardware-attestation claim. - The instruction fingerprint covers visible `AGENTS.md` layers and the local memory summary, not Codex's internal system prompt. -- A third party can verify the manifest signature with - `verification_key.json`. Verifying each artifact binding requires runtime - hashes measured outside the signed manifest. +- A third party can verify the manifest and the TRACE record, which share one + key, against a key and issuer they have pinned through a channel they trust. + Copied from `verification_key.json` alone they prove only that whoever wrote + the files signed them. The issuer `spiffe://codex.local/self-signed` names a + key that signs its own records, not an organization that vouched for it. + Verifying each artifact binding requires runtime hashes measured outside the + signed manifest. - SessionStart exposes the model and permission mode but no complete built-in tool roster. The tool catalog covers configured MCP servers, installed enabled plugins, and any tools supplied through the engine's explicit CLI diff --git a/plugins/agentrust-codex/engine/capture.py b/plugins/agentrust-codex/engine/capture.py index e162b721..e7563ec4 100644 --- a/plugins/agentrust-codex/engine/capture.py +++ b/plugins/agentrust-codex/engine/capture.py @@ -71,6 +71,46 @@ _sha_bytes = core.sha_bytes + + +def _catalog_root(tools): + """agent-manifest spec 3.2.3 catalog_hash: the RFC 9162 Merkle root over the + listed tools sorted by tool_id, each leaf H(0x00 || tool_id || 0x00 || + schema digest || description digest). A verifier recomputes it from the + list, so a root built any other way makes the manifest contradict itself. + + Refuses what the SDK's builder refuses, rather than hashing a catalog no + verifier would accept: a repeated or NUL-carrying tool_id, a digest that is + not sha256 hex, more than 1,000,000 tools.""" + if len(tools) > 1000000: + raise ValueError("catalog_hash: more than 1,000,000 tools") + ids = [t["tool_id"] for t in tools] + if len(set(ids)) != len(ids) or any("\x00" in i for i in ids): + raise ValueError("catalog_hash: each tool_id must be unique and free of NUL") + + def h(data): + return hashlib.sha256(data).digest() + + def digest(value): + if not re.fullmatch(r"sha256:[0-9a-f]{64}", value): + raise ValueError("catalog_hash: %r is not a sha256 digest" % (value,)) + return bytes.fromhex(value[len("sha256:"):]) + + leaves = [ + h(b"\x00" + t["tool_id"].encode("utf-8") + b"\x00" + + digest(t["schema_hash"]) + digest(t["description_hash"])) + for t in sorted(tools, key=lambda t: t["tool_id"]) + ] + + def root(nodes): + if len(nodes) == 1: + return nodes[0] + k = 1 + while k * 2 < len(nodes): + k *= 2 + return h(b"\x01" + root(nodes[:k]) + root(nodes[k:])) + + return "sha256:" + (root(leaves) if leaves else h(b"")).hex() _sha_file = core.sha_file _sha_mapping = core.sha_mapping _now_iso = core.now_iso @@ -671,6 +711,16 @@ def build_manifest(current: Mapping[str, Any]) -> Dict[str, Any]: "egress_destinations": [], } ) + # _slug folds case and punctuation, so two names can share an id ("foo" and + # "FOO"). The spec needs each tool_id once, so only colliding ids gain a short + # hash of their full name; every other id stays as it was. + counts: Dict[str, int] = {} + for tool in tools: + counts[tool["tool_id"]] = counts.get(tool["tool_id"], 0) + 1 + for tool in tools: + if counts[tool["tool_id"]] > 1: + suffix = hashlib.sha256(tool["tool_name"].encode("utf-8")).hexdigest()[:12] + tool["tool_id"] = "%s.%s" % (tool["tool_id"], suffix) scope = [ "codex:%s=%s" % (key, value) @@ -706,7 +756,7 @@ def build_manifest(current: Mapping[str, Any]) -> Dict[str, Any]: "bound_at": now, }, "tool_manifest": { - "catalog_hash": current["hashes"]["tool_catalog"], + "catalog_hash": _catalog_root(tools), "tools": tools, "allow_dynamic_registration": True, "rug_pull_policy": "deny-and-alert", @@ -830,7 +880,7 @@ def sign_all( ) try: from agent_manifest import Ed25519Signer, Ed25519Verifier, Manifest - from agentrust_trace import generate_key, sign_record + from agentrust_trace import sign_record except ImportError as error: raise SystemExit( "Signing needs the released packages in requirements.txt " @@ -844,7 +894,9 @@ def sign_all( Ed25519Verifier(keypair.public_bytes).verify( manifest, manifest["signature"]["signature_value"] ) - trace = sign_record(build_trace(current), generate_key()) + # The record shares the manifest's persisted key, published below, so a third + # party can verify it and the agent keeps one TRACE identity across sessions. + trace = sign_record(build_trace(current), keypair.private_key) outdir.mkdir(parents=True, exist_ok=True) _save(outdir / "manifest.json", manifest) @@ -853,7 +905,12 @@ def sign_all( "algorithm": "Ed25519", "key_id": keypair.key_id, "public_key_b64url": keypair.public_b64url(), - "note": "Load this key into agent-manifest trusted_keys to verify the manifest signature.", + # The issuer this key signs for. agent-manifest spec 5.3.3 needs it. + "issuers": [manifest["issuer"]], + "note": "Verifies manifest.json and trace.json, which share this key. Pin the " + "key and its issuers through a channel you trust, then load them into " + "trusted_keys and trusted_key_issuers; copied from this file alone they " + "prove only that whoever wrote it signed both records.", } _save(outdir / "verification_key.json", verification_key) return manifest, trace diff --git a/plugins/agentrust-codex/integration.yaml b/plugins/agentrust-codex/integration.yaml index 914d62c8..6611a8d6 100644 --- a/plugins/agentrust-codex/integration.yaml +++ b/plugins/agentrust-codex/integration.yaml @@ -21,3 +21,4 @@ trace_roles: tested_against: agent-manifest: 0.12.0 agentrust-trace: 0.10.0 + agentrust-trace-tests: 0.4.1 diff --git a/plugins/agentrust-codex/skills/agent-integrity/SKILL.md b/plugins/agentrust-codex/skills/agent-integrity/SKILL.md index 8fb7da71..30ff9b5d 100644 --- a/plugins/agentrust-codex/skills/agent-integrity/SKILL.md +++ b/plugins/agentrust-codex/skills/agent-integrity/SKILL.md @@ -77,7 +77,10 @@ to the changed category. For signed output, report these checks: - `manifest.json` carries an Ed25519 signature and - `verification_key.json` contains the public verification key. State that + `verification_key.json` contains the public verification key for both + records. A verifier pins that key, with the issuer + `spiffe://codex.local/self-signed` (the same on every install), through a + channel they trust. State that this verifies signature integrity. Artifact-binding verification needs separately measured runtime hashes. - `trace.json` is a TRACE Level 0 software-integrity record. Level 0 does not diff --git a/plugins/agentrust-codex/tests/test_codex_capture.py b/plugins/agentrust-codex/tests/test_codex_capture.py index b4d5902d..804b75e1 100644 --- a/plugins/agentrust-codex/tests/test_codex_capture.py +++ b/plugins/agentrust-codex/tests/test_codex_capture.py @@ -2,6 +2,7 @@ from __future__ import annotations +import base64 import io import importlib.util import json @@ -361,7 +362,8 @@ def test_signed_outputs_verify_and_pass_trace_level_zero(tmp_path, monkeypatch): (out / "verification_key.json").read_text(encoding="utf-8") ) context = VerificationContext( - trusted_keys={verification_key["key_id"]: verification_key["public_key_b64url"]} + trusted_keys={verification_key["key_id"]: verification_key["public_key_b64url"]}, + trusted_key_issuers={verification_key["key_id"]: verification_key["issuers"]}, ) good = verify_manifest(manifest, context, RevocationStore()) assert good.signature_verified is True @@ -584,3 +586,190 @@ class _SealArgs: def __init__(self, **over): for key, value in over.items(): setattr(self, key, value) + + +@pytest.fixture +def signed(tmp_path, monkeypatch): + pytest.importorskip("agent_manifest") + pytest.importorskip("agentrust_trace") + manifest, trace = capture.sign_all(_signable_snapshot(tmp_path, monkeypatch), tmp_path / "records") + vk = json.loads((tmp_path / "records" / "verification_key.json").read_text(encoding="utf-8")) + return manifest, trace, vk + + +def test_trace_record_is_externally_verifiable_with_the_published_key(signed): + """Before, the record was signed with a throwaway key that verification_key.json + did not publish, so nobody could verify it without trusting its own cnf.jwk.""" + from agentrust_trace import verify_record + from cryptography.exceptions import InvalidSignature + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + + _manifest, trace, vk = signed + verify_record(trace, {"kty": "OKP", "crv": "Ed25519", "x": vk["public_key_b64url"]}, max_age_seconds=None) + other = Ed25519PrivateKey.generate().public_key().public_bytes_raw() + other_x = base64.urlsafe_b64encode(other).decode().rstrip("=") + with pytest.raises((InvalidSignature, ValueError)): + verify_record(trace, {"kty": "OKP", "crv": "Ed25519", "x": other_x}, max_age_seconds=None) + + +def test_manifest_and_trace_share_one_stable_identity(tmp_path, monkeypatch): + pytest.importorskip("agent_manifest") + pytest.importorskip("agentrust_trace") + current = _signable_snapshot(tmp_path, monkeypatch) + first_manifest, first_trace = capture.sign_all(current, tmp_path / "run1") + second_manifest, second_trace = capture.sign_all(current, tmp_path / "run2") + published = json.loads( + (tmp_path / "run1" / "verification_key.json").read_text(encoding="utf-8") + )["public_key_b64url"] + assert first_trace["cnf"]["jwk"]["x"] == published + assert second_trace["cnf"]["jwk"]["x"] == published + assert first_manifest["signature"]["key_id"] == second_manifest["signature"]["key_id"] + from agentrust_trace import verify_record + + pinned = {"kty": "OKP", "crv": "Ed25519", "x": published} + for trace in (first_trace, second_trace): # both sessions verify under one pinned key + verify_record(trace, pinned, max_age_seconds=None) + + +# --------------------------------------------------------------------------- +# The published manifest is consistent, and issuer authorization holds. +# --------------------------------------------------------------------------- +def _sdk_enforces_issuer_policy(): + import importlib.metadata + + major, minor = (int(p) for p in importlib.metadata.version("agent-manifest").split(".")[:2]) + return (major, minor) >= (0, 16) + + +@pytest.mark.parametrize("count", range(10)) +def test_catalog_root_matches_the_sdk(count): + """Spec 3.2.3's Merkle root, checked against the SDK's own construction.""" + pytest.importorskip("agent_manifest") + from agent_manifest import ToolEntry + from agent_manifest._merkle import build_catalog_tree + + tools = [ + { + "tool_id": "t.%d" % ((i * 7) % 10), # unsorted on purpose + "tool_name": "t%d" % i, + "endpoint_id": "spiffe://x.local/t", + "schema_hash": "sha256:" + ("%02x" % i) * 32, + "description_hash": "sha256:" + ("%02x" % (i + 100)) * 32, + "version": "1.0.0", + "egress_destinations": [], + } + for i in range(count) + ] + expected = build_catalog_tree([ToolEntry.model_validate(t) for t in tools]) + assert capture._catalog_root(tools) == expected + + +def _verify(manifest, key_id, public_key, issuers): + from agent_manifest import RevocationStore, VerificationContext, verify_manifest + + return verify_manifest( + manifest, + VerificationContext( + trusted_keys={key_id: public_key}, + trusted_key_issuers=None if issuers is None else {key_id: issuers}, + ), + RevocationStore(), + ) + + +def test_published_manifest_does_not_contradict_itself(signed): + manifest, _trace, vk = signed + assert vk["issuers"] == [manifest["issuer"]] + result = _verify(manifest, vk["key_id"], vk["public_key_b64url"], vk["issuers"]) + assert result.signature_verified is True + assert result.fields_verified.tool_manifest.name != "MISMATCH" + assert result.result.name != "MISMATCH" + + +@pytest.mark.parametrize( + "issuers", + [ + ["spiffe://elsewhere.example/issuer"], + [], + ], + ids=["another-issuer", "empty-list"], +) +def test_a_key_not_authorized_for_the_issuer_is_refused(signed, issuers): + manifest, _trace, vk = signed + result = _verify(manifest, vk["key_id"], vk["public_key_b64url"], issuers) + assert result.result.name == "MISMATCH" + assert result.signature_verified is False + + +def test_any_listed_issuer_authorizes(signed): + manifest, _trace, vk = signed + issuers = ["spiffe://elsewhere.example/issuer", manifest["issuer"]] + result = _verify(manifest, vk["key_id"], vk["public_key_b64url"], issuers) + assert result.signature_verified is True + + +def test_an_issuer_changed_after_signing_is_refused(signed): + manifest, _trace, vk = signed + tampered = json.loads(json.dumps(manifest)) + tampered["issuer"] = "spiffe://elsewhere.example/issuer" + result = _verify(tampered, vk["key_id"], vk["public_key_b64url"], [tampered["issuer"]]) + assert result.signature_verified is False + assert result.result.name != "VALID" + + +def test_the_key_must_be_trusted_under_its_own_id(signed): + manifest, _trace, vk = signed + result = _verify(manifest, "0" * 64, vk["public_key_b64url"], vk["issuers"]) + assert result.signature_verified is False + + +def test_no_issuer_policy_is_unverifiable(signed): + if not _sdk_enforces_issuer_policy(): + pytest.skip("agent-manifest < 0.16 does not require an issuer policy") + manifest, _trace, vk = signed + result = _verify(manifest, vk["key_id"], vk["public_key_b64url"], None) + assert result.result.name == "UNVERIFIABLE" + assert result.signature_verified is False + + +@pytest.mark.parametrize( + "bad, message", + [ + ([("a", "11"), ("a", "22")], "unique"), + ([("a\x00b", "11")], "NUL"), + ([("a", "sha512:" + "11" * 32)], "not a sha256 digest"), + ([("a", "sha256:" + "1" * 63)], "not a sha256 digest"), + ([("a", "sha256:" + "AB" * 32)], "not a sha256 digest"), + ], + ids=["duplicate-id", "nul-in-id", "other-algorithm", "short-digest", "uppercase-hex"], +) +def test_catalog_root_refuses_what_the_sdk_refuses(bad, message): + def tool(tool_id, digest): + value = digest if ":" in digest else "sha256:" + digest * 32 + return {"tool_id": tool_id, "schema_hash": value, "description_hash": "sha256:" + "33" * 32} + + with pytest.raises(ValueError, match=message): + capture._catalog_root([tool(i, d) for i, d in bad]) + + +def test_empty_catalog_root_is_the_rfc_9162_empty_tree(): + import hashlib + + assert capture._catalog_root([]) == "sha256:" + hashlib.sha256(b"").hexdigest() + + +def test_slug_collisions_get_distinct_tool_ids_and_verify(tmp_path, monkeypatch): + """"foo" and "FOO" share a slug; the SDK refuses a repeated tool_id.""" + pytest.importorskip("agent_manifest") + from agent_manifest import ToolEntry + from agent_manifest._merkle import build_catalog_tree + + current = dict(_signable_snapshot(tmp_path, monkeypatch)) + current["tools"] = sorted(set(current.get("tools", [])) | {"mcp:foo", "mcp:FOO", "mcp:f.o-o!"}) + manifest = capture.build_manifest(current) + tools = manifest["artifacts"]["tool_manifest"]["tools"] + ids = [t["tool_id"] for t in tools] + assert len(ids) == len(set(ids)) + assert "codex.mcp.foo" not in ids # both colliding ids were disambiguated + root = build_catalog_tree([ToolEntry.model_validate(t) for t in tools]) + assert manifest["artifacts"]["tool_manifest"]["catalog_hash"] == root