From b33b7141717e83a4037b3a43a3bc4ac066ae79e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 07:12:39 +0000 Subject: [PATCH] feat(identity): pin trusted keys in verify_signatures; stop claiming attribution without them verify_signatures only checked that the key written in each entry signed it. A ledger rewritten and re-signed with a fresh key passed, yet the result said "Attribution proven" and the README said impersonation was caught. New load_trusted_keys() and am verify-sig --trusted-keys FILE ( lines, * for any agent): a signature by a key not trusted for the entry's agent FAILs, and so does an unsigned entry from an agent with a trusted key. Without trusted keys the OK message now says the keys are not pinned. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Aq8kkjKAMDjSSK54hcWnuc --- CHANGELOG.md | 12 ++++++ README.md | 15 +++++-- README_KO.md | 13 ++++-- actmirror/__init__.py | 4 +- actmirror/am.py | 98 ++++++++++++++++++++++++++++++++++++------- docs/GUIDE.md | 11 +++-- docs/GUIDE_KO.md | 8 +++- tests/test_am.py | 74 ++++++++++++++++++++++++++++++++ 8 files changed, 207 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 198e371..3656575 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [Unreleased] +### Added +- **Trusted keys for `verify_signatures` / `am verify-sig --trusted-keys FILE`.** A file of + ` ` lines (`*` = any agent), read by the new `load_trusted_keys()`. With + it, an entry signed by a key not trusted for its agent FAILs, and so does an unsigned entry + from an agent that has a trusted key. + +### Changed +- Without trusted keys, `verify_signatures` no longer says "Attribution proven". It only ever + checked that the key written in each entry signed it, so a ledger rewritten and re-signed + with a fresh key also passed. The OK message now says the keys are not pinned. The README + and GUIDE no longer claim impersonation is caught without trusted keys. + ### Fixed - **Tests on non-UTF-8 consoles (e.g. Korean Windows, cp949):** test subprocesses now write and are read as UTF-8 (`tests/conftest.py` + `encoding="utf-8"`); 7 tests failed diff --git a/README.md b/README.md index a2b73ae..297ddbf 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,8 @@ Demo (3-agent family, attack included): `PYTHONPATH=. python examples/demo_famil | `cross_witness` | tuple | mutual pin between two ledgers | | `family_round` | list | every agent pins every other | | `family_verify` | [Finding] | verify the whole family | -| `verify_signatures` | [Finding] | verify the optional signed-identity layer | +| `verify_signatures` | [Finding] | verify the optional signed-identity layer (pass `trusted_keys` to check WHO signed) | +| `load_trusted_keys` | dict | read a ` ` trusted-keys file | | `to_aat` / `export_aat` / `verify_aat` | list / int / [Finding] | IETF AAT draft -11 export (see below) | @@ -208,13 +209,19 @@ pip install action-mirror[signing] am keygen --out jebi.key # one keypair per agent am record --agent jebi --action eval --target exp1 --sign jebi.key -am verify-sig # checks every signed entry +echo "jebi " > trusted_keys.txt # keep this OUTSIDE the ledger +am verify-sig --trusted-keys trusted_keys.txt # checks every signed entry ``` Each signed entry carries a `pubkey` (chained — the claimed key can't be swapped without breaking the chain) and a `sig` over its seal. `verify_signatures` (CLI `verify-sig`) recomputes the seal -from the content and checks the signature, so it catches **both** impersonation (signed with the -wrong key) **and** tampering (body changed after signing). +from the content and checks the signature, so it catches tampering (body changed after signing). + +It catches **impersonation only with trusted keys.** Without them it can only check that each +entry was signed by the key written *in that entry*, and whoever rewrites a ledger can re-sign it +with a fresh key. With `--trusted-keys` (lines of ` `, `*` for any agent) an +entry signed by a key not trusted for its agent FAILs, and so does an unsigned entry from an agent +that has a trusted key. Keep the trusted-keys file somewhere the ledger's writer cannot change. **Honest scope — do not oversell.** A signature proves *the holder of this key signed it* (attribution · impersonation-resistance · non-repudiation). It does **not** prove independence: diff --git a/README_KO.md b/README_KO.md index 5134327..ecfd6d1 100644 --- a/README_KO.md +++ b/README_KO.md @@ -138,7 +138,8 @@ am --ledger jebi.jsonl export-aat --out jebi.aat.jsonl # IETF AAT 초안 -11 | `cross_witness` | tuple | 두 원장 상호 핀 | | `family_round` | list | 전원이 전원을 핀 | | `family_verify` | [Finding] | 가족 전체 검증 | -| `verify_signatures` | [Finding] | 선택적 서명-신원 레이어 검증 | +| `verify_signatures` | [Finding] | 선택적 서명-신원 레이어 검증 (`trusted_keys`를 주면 누가 서명했는지 확인) | +| `load_trusted_keys` | dict | ` ` 신뢰 키 파일 읽기 | | `to_aat` / `export_aat` / `verify_aat` | list / int / [Finding] | IETF AAT 초안 -11 내보내기 (아래 참조) | 각 함수의 시그니처·판정은 **[완전 가이드](docs/GUIDE_KO.md)** 참조. @@ -192,8 +193,14 @@ am verify-sig # 모든 서명 엔 ``` 서명 엔트리는 `pubkey`(체인됨 — 주장한 키를 체인 안 깨고 못 바꿈)와 seal에 대한 `sig`를 답니다. -`verify_signatures`(CLI `verify-sig`)는 *내용에서 seal을 재계산*해 서명을 검증하므로, **사칭**(틀린 -키로 서명)과 **내용 위조**(서명 후 본문 변경)를 *둘 다* 잡습니다. +`verify_signatures`(CLI `verify-sig`)는 *내용에서 seal을 재계산*해 서명을 검증하므로 **내용 위조**(서명 +후 본문 변경)를 잡습니다. + +**사칭은 신뢰 키가 있을 때만 잡습니다.** 신뢰 키가 없으면 각 엔트리가 *그 엔트리에 적힌* 키로 서명됐는지만 +볼 수 있고, 원장을 다시 쓰는 사람은 새 키로 다시 서명하면 됩니다. `--trusted-keys`(한 줄에 +` `, 모든 에이전트는 `*`)를 주면, 그 에이전트에게 신뢰되지 않은 키로 서명한 엔트리와 +신뢰 키가 있는 에이전트의 무서명 엔트리가 FAIL입니다. 신뢰 키 파일은 원장을 쓰는 쪽이 고칠 수 없는 곳에 +두세요. **정직한 범위 — 안 팔기.** 서명은 *이 키 보유자가 서명했다*(귀속·사칭저항·부인불가)를 증명합니다. **독립은 증명 못 합니다**: 한 운영자가 키를 여럿 발급(Sybil)할 수 있고, 자기 키를 든 에이전트는 diff --git a/actmirror/__init__.py b/actmirror/__init__.py index 512a8c1..a28d4d7 100644 --- a/actmirror/__init__.py +++ b/actmirror/__init__.py @@ -1,13 +1,13 @@ """🪪 Action Mirror — agent action provenance + mutual witness (mirror family #3).""" from .am import ( - record, history, attest, verify_chain, verify_signatures, + record, history, attest, verify_chain, verify_signatures, load_trusted_keys, witness_peer, verify_peer, cross_witness, family_round, family_verify, report, Finding, ) from .aat import to_aat, export_aat, verify_aat __all__ = [ - "record", "history", "attest", "verify_chain", "verify_signatures", + "record", "history", "attest", "verify_chain", "verify_signatures", "load_trusted_keys", "witness_peer", "verify_peer", "cross_witness", "family_round", "family_verify", "report", "Finding", "to_aat", "export_aat", "verify_aat", ] diff --git a/actmirror/am.py b/actmirror/am.py index 855db48..b077271 100644 --- a/actmirror/am.py +++ b/actmirror/am.py @@ -254,20 +254,78 @@ def verify_chain(ledger_path: str) -> list[Finding]: f"Chain intact — {len(entries)} entries verified.")] -def verify_signatures(ledger_path: str) -> list[Finding]: +def load_trusted_keys(path: str) -> dict[str, set[str]]: + """Read a trusted-keys file: one key per line, `` ``. + + ``*`` as the agent trusts a key for any agent. Blank lines and ``#`` comments are + ignored. Keep this file OUTSIDE the ledger's control: its value is that someone who + rewrites the ledger cannot also rewrite which keys you expect. + """ + keys: dict[str, set[str]] = {} + with open(path, encoding="utf-8") as f: + for n, line in enumerate(f, 1): + line = line.split("#", 1)[0].strip() + if not line: + continue + parts = line.split() + if len(parts) != 2: + raise ValueError(f"{path}:{n}: expected ' ', got {line!r}") + agent, key = parts + try: + if len(bytes.fromhex(key)) != 32: + raise ValueError + except ValueError: + raise ValueError(f"{path}:{n}: not a 32-byte Ed25519 public key in hex: {key!r}") + keys.setdefault(agent, set()).add(key.lower()) + return keys + + +def verify_signatures(ledger_path: str, + trusted_keys: dict[str, set[str]] | None = None) -> list[Finding]: """Verify the cryptographic identity layer: every entry that carries a pubkey must have a valid signature of its seal under that key. Entries without a pubkey are unsigned (OK — - the 'who' is self-asserted, see README). Requires the [signing] extra to check signatures.""" + the 'who' is self-asserted, see README). Requires the [signing] extra to check signatures. + + Without ``trusted_keys`` this proves only that each signed entry is self-consistent: the + key IN the entry signed it. Anyone who rewrites a ledger can sign it again with a fresh + key, so that alone says nothing about WHO signed. With ``trusted_keys`` (agent -> set of + pubkey hex, ``"*"`` for any agent; see ``load_trusted_keys``): + + - a signed entry whose key is not trusted for its ``agent`` FAILs (impersonation); + - an UNSIGNED entry whose ``agent`` has trusted keys FAILs — otherwise an impersonator + would simply leave the signature off. + """ from . import identity entries = _load_entries(ledger_path) signed = [e for e in entries if e.get("pubkey")] + findings: list[Finding] = [] + if trusted_keys is not None: + anyone = {k.lower() for k in trusted_keys.get("*", set())} + untrusted, missing = [], [] + for i, e in enumerate(entries, 1): + agent = e.get("agent") + allowed = {k.lower() for k in trusted_keys.get(agent, set())} | anyone + if e.get("pubkey"): + if str(e["pubkey"]).lower() not in allowed: + untrusted.append(i) + elif agent in trusted_keys: + missing.append(i) + if untrusted or missing: + parts = [] + if untrusted: + parts.append(f"signed by a key not trusted for its agent at entr" + f"{'y' if len(untrusted) == 1 else 'ies'} {untrusted}") + if missing: + parts.append(f"unsigned although the agent has a trusted key at entr" + f"{'y' if len(missing) == 1 else 'ies'} {missing}") + findings.append(Finding("🔑 identity", "FAIL", "; ".join(parts) + ".")) if not signed: - return [Finding("🔑 identity", "OK", - "No signed entries — 'who' is self-asserted (unsigned).")] + return findings or [Finding("🔑 identity", "OK", + "No signed entries — 'who' is self-asserted (unsigned).")] if not identity.available(): - return [Finding("🔑 identity", "WARN", - f"{len(signed)} signed entries present but cryptography not installed — " - "pip install action-mirror[signing] to verify.")] + return findings + [Finding("🔑 identity", "WARN", + f"{len(signed)} signed entries present but cryptography not " + "installed — pip install action-mirror[signing] to verify.")] bad = [] for i, e in enumerate(entries, 1): if not e.get("pubkey"): @@ -282,13 +340,21 @@ def verify_signatures(ledger_path: str) -> list[Finding]: if not e.get("sig") or not identity.verify(e["pubkey"], real_seal, e["sig"]): bad.append(i) if bad: - return [Finding("🔑 identity", "FAIL", - f"Invalid/forged signature at entr{'y' if len(bad)==1 else 'ies'} {bad} " - "— signed 'who' does not verify.")] + return findings + [Finding("🔑 identity", "FAIL", + f"Invalid/forged signature at entr{'y' if len(bad)==1 else 'ies'} " + f"{bad} — signed 'who' does not verify.")] + if findings: + return findings keys = {e["pubkey"][:12] for e in signed} + if trusted_keys is None: + return [Finding("🔑 identity", "OK", + f"{len(signed)} signed entries are self-consistent across {len(keys)} " + "key(s). Keys are NOT pinned: a rewritten ledger re-signed with a new key " + "also passes. Pass trusted keys (CLI --trusted-keys) to check who signed.")] return [Finding("🔑 identity", "OK", - f"{len(signed)} signed entries verified across {len(keys)} key(s). " - "(Attribution proven; independence is NOT — one operator may hold many keys.)")] + f"{len(signed)} signed entries verified against trusted keys " + f"({len(keys)} key(s)). Attribution holds for those keys; independence is " + "NOT proven — one operator may hold many keys.")] # ───────────────────────────────────────────────────────────── @@ -562,7 +628,10 @@ def _cli() -> int: kg = sub.add_parser("keygen", help="Generate an Ed25519 identity keypair ([signing] extra)") kg.add_argument("--out", required=True, help="Path to write the private key") - sub.add_parser("verify-sig", help="Verify the signed-identity layer of my ledger") + vs = sub.add_parser("verify-sig", help="Verify the signed-identity layer of my ledger") + vs.add_argument("--trusted-keys", default=None, + help="File of ' ' lines ('*' = any agent). Signed entries " + "must use a trusted key for their agent; listed agents must sign.") h = sub.add_parser("history", help="Query sealed actions") h.add_argument("--agent", default=None) @@ -643,7 +712,8 @@ def _cli() -> int: print(f"🔑 keypair written: {args.out} (keep private!)\n pubkey: {pub}") return 0 if args.cmd == "verify-sig": - fs = verify_signatures(args.ledger) + trusted = load_trusted_keys(args.trusted_keys) if args.trusted_keys else None + fs = verify_signatures(args.ledger, trusted_keys=trusted) for f in fs: print(f" {f}") return 1 if any(f.level == "FAIL" for f in fs) else 0 diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 94e350a..66ab7e4 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -190,6 +190,7 @@ mutual tamper-evidence. Wire both up deliberately, not by default. | `family_round` | list | every agent pins every other | | `family_verify` | [Finding] | verify the whole family | | `verify_signatures` | [Finding] | verify the optional signed-identity layer | +| `load_trusted_keys` | dict | read a trusted-keys file | --- @@ -197,12 +198,16 @@ mutual tamper-evidence. Wire both up deliberately, not by default. Verifies the optional Ed25519 signed-identity layer (`[signing]` extra). Entries created with `record(..., sign_key=...)` carry a chained `pubkey` and a `sig` over the (recomputed) seal. -`verify_signatures` confirms each signature — catching both impersonation (wrong key) and -tampering (body changed after signing). Entries with no `pubkey` are unsigned and pass as OK (the +`verify_signatures` confirms each signature, catching tampering (body changed after signing). +It catches impersonation only with `trusted_keys` (agent -> pubkeys, read with +`load_trusted_keys(path)` from ` ` lines): a signature by a key not trusted for +the entry's agent FAILs, and so does an unsigned entry from an agent that has a trusted key. +Without trusted keys it checks only that the key written in the entry signed it. Entries with no `pubkey` are unsigned and pass as OK (the `who` is self-asserted). **Attribution only — not independence**: one operator can hold many keys. ```python -am.report("identity", am.verify_signatures("jebi.jsonl")) +am.report("identity", am.verify_signatures( + "jebi.jsonl", trusted_keys=am.load_trusted_keys("trusted_keys.txt"))) ``` --- diff --git a/docs/GUIDE_KO.md b/docs/GUIDE_KO.md index de97ca9..b4d7362 100644 --- a/docs/GUIDE_KO.md +++ b/docs/GUIDE_KO.md @@ -186,6 +186,7 @@ cron/loop가 `family_round()`를 돌리면 가족 전체에 상시 상호 변조 | `family_round` | list | 전원이 전원을 핀 | | `family_verify` | [Finding] | 가족 전체 검증 | | `verify_signatures` | [Finding] | 선택적 서명-신원 레이어 검증 | +| `load_trusted_keys` | dict | 신뢰 키 파일 읽기 | --- @@ -193,11 +194,14 @@ cron/loop가 `family_round()`를 돌리면 가족 전체에 상시 상호 변조 선택적 Ed25519 서명-신원 레이어(`[signing]` extra)를 검증한다. `record(..., sign_key=...)`로 만든 엔트리는 체인된 `pubkey`와 (재계산한) seal에 대한 `sig`를 단다. `verify_signatures`는 각 서명을 -확인 — 사칭(틀린 키)과 위조(서명 후 본문 변경)를 둘 다 잡는다. `pubkey` 없는 엔트리는 무서명이라 +확인해 위조(서명 후 본문 변경)를 잡는다. 사칭은 `trusted_keys`(`load_trusted_keys(path)`로 읽은 +`에이전트 -> 공개키` 목록)를 줄 때만 잡는다: 그 에이전트에게 신뢰되지 않은 키의 서명과, 신뢰 키가 있는 +에이전트의 무서명 엔트리가 FAIL. 신뢰 키 없이는 "엔트리 안의 키로 서명됨"까지만 확인한다. `pubkey` 없는 엔트리는 무서명이라 OK 통과(`누구`는 자기선언). **귀속만 — 독립 아님**: 한 운영자가 키를 여럿 들 수 있다. ```python -am.report("identity", am.verify_signatures("jebi.jsonl")) +am.report("identity", am.verify_signatures( + "jebi.jsonl", trusted_keys=am.load_trusted_keys("trusted_keys.txt"))) ``` --- diff --git a/tests/test_am.py b/tests/test_am.py index 714191c..dbcdb44 100644 --- a/tests/test_am.py +++ b/tests/test_am.py @@ -438,3 +438,77 @@ def counting_open(file, *a, **kw): assert read_sizes, "nothing was read at all — the counter is not wired to the lookup" assert sum(read_sizes) < size // 10, ( f"read {sum(read_sizes)} of {size} bytes — the lookup is still scanning the ledger") + + +# ─── trusted keys: impersonation is only caught when the expected key is pinned ─── +def _signing_or_skip(): + from actmirror import identity + if not identity.available(): + import pytest + pytest.skip("signing extra not installed") + return identity + + +def test_without_trusted_keys_a_resigned_ledger_still_passes(tmp_path): + """The gap trusted keys close: an impersonator signs with their OWN key and passes.""" + identity = _signing_or_skip() + l = L(tmp_path) + mallory = str(tmp_path / "mallory.key") + identity.generate(mallory) + am.record(l, agent="jebi", action="eval", sign_key=mallory) + f = am.verify_signatures(l)[0] + assert f.level == "OK" and "NOT pinned" in f.msg + + +def test_load_trusted_keys_and_impersonation(tmp_path): + identity = _signing_or_skip() + l = L(tmp_path) + jebi, mallory = str(tmp_path / "jebi.key"), str(tmp_path / "mallory.key") + jebi_pub = identity.generate(jebi) + identity.generate(mallory) + tk = tmp_path / "trusted.txt" + tk.write_text(f"# who may sign as whom\njebi {jebi_pub}\n", encoding="utf-8") + trusted = am.load_trusted_keys(str(tk)) + assert trusted == {"jebi": {jebi_pub}} + + am.record(l, agent="jebi", action="eval", sign_key=jebi) + am.record(l, agent="seara", action="note") # agent with no trusted key: fine unsigned + assert [f.level for f in am.verify_signatures(l, trusted_keys=trusted)] == ["OK"] + + am.record(l, agent="jebi", action="eval", sign_key=mallory) # impersonation + am.record(l, agent="jebi", action="eval") # signature simply left off + fs = am.verify_signatures(l, trusted_keys=trusted) + assert fs[0].level == "FAIL" + assert "not trusted for its agent at entry [3]" in fs[0].msg + assert "unsigned although the agent has a trusted key at entry [4]" in fs[0].msg + + +def test_wildcard_trusted_key_and_bad_file(tmp_path): + import pytest + identity = _signing_or_skip() + l = L(tmp_path) + k = str(tmp_path / "ops.key") + pub = identity.generate(k) + am.record(l, agent="anyone", action="x", sign_key=k) + assert am.verify_signatures(l, trusted_keys={"*": {pub}})[0].level == "OK" + bad = tmp_path / "bad.txt" + bad.write_text("jebi not-hex\n", encoding="utf-8") + with pytest.raises(ValueError, match="bad.txt:1"): + am.load_trusted_keys(str(bad)) + + +def test_cli_verify_sig_trusted_keys_exit_code(tmp_path): + import subprocess, sys + identity = _signing_or_skip() + l = L(tmp_path) + jebi, mallory = str(tmp_path / "jebi.key"), str(tmp_path / "mallory.key") + jebi_pub = identity.generate(jebi) + identity.generate(mallory) + am.record(l, agent="jebi", action="eval", sign_key=mallory) + tk = tmp_path / "trusted.txt" + tk.write_text(f"jebi {jebi_pub}\n", encoding="utf-8") + run = lambda *a: subprocess.run([sys.executable, "-m", "actmirror.am", "--ledger", l, *a], + capture_output=True, encoding="utf-8") + assert run("verify-sig").returncode == 0 + r = run("verify-sig", "--trusted-keys", str(tk)) + assert r.returncode == 1 and "not trusted" in r.stdout