Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions claude-code/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 26 additions & 7 deletions claude-code/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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 = "<key_id>" # your pins, not read from the files
PINNED_PUBLIC_KEY = "<public_key_b64url>"
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)
Expand Down
86 changes: 71 additions & 15 deletions claude-code/engine/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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"
Expand All @@ -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",
Expand All @@ -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


Expand Down
Loading
Loading