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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
`<agent> <pubkey_hex>` 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
Expand Down
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<agent> <pubkey_hex>` trusted-keys file |

| `to_aat` / `export_aat` / `verify_aat` | list / int / [Finding] | IETF AAT draft -11 export (see below) |

Expand Down Expand Up @@ -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 <pubkey printed by keygen>" > 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 `<agent> <pubkey_hex>`, `*` 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:
Expand Down
13 changes: 10 additions & 3 deletions README_KO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | `<agent> <pubkey_hex>` 신뢰 키 파일 읽기 |
| `to_aat` / `export_aat` / `verify_aat` | list / int / [Finding] | IETF AAT 초안 -11 내보내기 (아래 참조) |

각 함수의 시그니처·판정은 **[완전 가이드](docs/GUIDE_KO.md)** 참조.
Expand Down Expand Up @@ -192,8 +193,14 @@ am verify-sig # 모든 서명 엔
```

서명 엔트리는 `pubkey`(체인됨 — 주장한 키를 체인 안 깨고 못 바꿈)와 seal에 대한 `sig`를 답니다.
`verify_signatures`(CLI `verify-sig`)는 *내용에서 seal을 재계산*해 서명을 검증하므로, **사칭**(틀린
키로 서명)과 **내용 위조**(서명 후 본문 변경)를 *둘 다* 잡습니다.
`verify_signatures`(CLI `verify-sig`)는 *내용에서 seal을 재계산*해 서명을 검증하므로 **내용 위조**(서명
후 본문 변경)를 잡습니다.

**사칭은 신뢰 키가 있을 때만 잡습니다.** 신뢰 키가 없으면 각 엔트리가 *그 엔트리에 적힌* 키로 서명됐는지만
볼 수 있고, 원장을 다시 쓰는 사람은 새 키로 다시 서명하면 됩니다. `--trusted-keys`(한 줄에
`<agent> <pubkey_hex>`, 모든 에이전트는 `*`)를 주면, 그 에이전트에게 신뢰되지 않은 키로 서명한 엔트리와
신뢰 키가 있는 에이전트의 무서명 엔트리가 FAIL입니다. 신뢰 키 파일은 원장을 쓰는 쪽이 고칠 수 없는 곳에
두세요.

**정직한 범위 — 안 팔기.** 서명은 *이 키 보유자가 서명했다*(귀속·사칭저항·부인불가)를 증명합니다.
**독립은 증명 못 합니다**: 한 운영자가 키를 여럿 발급(Sybil)할 수 있고, 자기 키를 든 에이전트는
Expand Down
4 changes: 2 additions & 2 deletions actmirror/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
Expand Down
98 changes: 84 additions & 14 deletions actmirror/am.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, ``<agent> <pubkey_hex>``.

``*`` 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 '<agent> <pubkey_hex>', 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"):
Expand All @@ -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.")]


# ─────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -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 '<agent> <pubkey_hex>' 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)
Expand Down Expand Up @@ -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
Expand Down
11 changes: 8 additions & 3 deletions docs/GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,19 +190,24 @@ 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 |

---

### `verify_signatures(ledger) → [Finding]`

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 `<agent> <pubkey_hex>` 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")))
```

---
Expand Down
8 changes: 6 additions & 2 deletions docs/GUIDE_KO.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,18 +186,22 @@ cron/loop가 `family_round()`를 돌리면 가족 전체에 상시 상호 변조
| `family_round` | list | 전원이 전원을 핀 |
| `family_verify` | [Finding] | 가족 전체 검증 |
| `verify_signatures` | [Finding] | 선택적 서명-신원 레이어 검증 |
| `load_trusted_keys` | dict | 신뢰 키 파일 읽기 |

---

### `verify_signatures(ledger) → [Finding]`

선택적 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")))
```

---
Expand Down
Loading
Loading