agentlighthouse-verify 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.5
2
+ Name: agentlighthouse-verify
3
+ Version: 0.4.0
4
+ Summary: Standalone, dependency-minimal verifier for AgentLighthouse receipts
5
+ Project-URL: Homepage, https://github.com/neural-nomad1709/agentlighthouse
6
+ Project-URL: Repository, https://github.com/neural-nomad1709/agentlighthouse
7
+ Author: Amit Kala
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.12
11
+ Requires-Dist: cryptography>=43
12
+ Description-Content-Type: text/markdown
13
+
14
+ # agentlighthouse-verify
15
+
16
+ **Standalone verifier for AgentLighthouse evidence.**
17
+
18
+ [AgentLighthouse](https://github.com/neural-nomad1709/agentlighthouse) is a
19
+ security mediator for AI agents. It writes a signed receipt for every decision
20
+ it takes. This package checks those receipts, and it does so without the
21
+ mediator: it does not import the runtime, and its only dependency is
22
+ [`cryptography`](https://pypi.org/project/cryptography/).
23
+
24
+ That separation is the point. An auditor, a customer or a regulator can verify
25
+ the evidence with a small tool they can read end to end, and does not have to
26
+ trust the operator's binary.
27
+
28
+ - **Source:** <https://github.com/neural-nomad1709/agentlighthouse>
29
+ - **Receipt specification:** [receipt-v1](https://github.com/neural-nomad1709/agentlighthouse/blob/main/spec/receipt-v1.md)
30
+ - **License:** MIT
31
+ - **Python:** 3.12 or newer
32
+
33
+ ## Contents
34
+
35
+ - [Install](#install)
36
+ - [Verify a ledger](#verify-a-ledger)
37
+ - [What can be verified](#what-can-be-verified)
38
+ - [What verification checks](#what-verification-checks)
39
+ - [Command line](#command-line)
40
+ - [The receipt format](#the-receipt-format)
41
+ - [Trust model](#trust-model)
42
+ - [Related packages](#related-packages)
43
+ - [License](#license)
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install agentlighthouse-verify
49
+ ```
50
+
51
+ This installs one command, `al-verify`.
52
+
53
+ ## Verify a ledger
54
+
55
+ You need two files from the operator: the ledger and the mediator's public
56
+ key.
57
+
58
+ ```bash
59
+ al-verify ledger.jsonl --pubkey mediator_ed25519.pub
60
+ ```
61
+
62
+ ```
63
+ chain of 11 receipt(s) verified from genesis
64
+ OK
65
+ ```
66
+
67
+ The exit code is `0` when everything verifies and non-zero when anything does
68
+ not, so the command can gate a pipeline.
69
+
70
+ ## What can be verified
71
+
72
+ | Input | What it is |
73
+ |---|---|
74
+ | A receipt (`.json`) | One mediated decision |
75
+ | A ledger (`.jsonl`, or a JSON array) | The full chain of receipts, from the first one |
76
+ | A posture attestation | A signed per-organization summary of posture and evidence over a period |
77
+ | A rule bundle | A signed set of detection rules; the mediator refuses to load an unsigned or altered one |
78
+
79
+ ## What verification checks
80
+
81
+ Verification is fail-closed. Any one failure fails the whole run.
82
+
83
+ 1. **The record hash.** The receipt is canonicalized with RFC 8785 (JCS) and
84
+ hashed with SHA-256. The result must equal the `record_hash` the receipt
85
+ carries, so a changed field is detected.
86
+ 2. **The signature.** `sig` must be a valid Ed25519 signature over that hash
87
+ by the mediator key you supplied.
88
+ 3. **The chain.** Each receipt's `prev_hash` must equal the previous receipt's
89
+ `record_hash`, and sequence numbers must be contiguous from genesis. A
90
+ removed, reordered or inserted receipt is detected.
91
+
92
+ The canonicalization and the hash chain are implemented in this package from
93
+ the specification, with no third-party code, so the trust surface stays small
94
+ enough to audit.
95
+
96
+ ## Command line
97
+
98
+ ```
99
+ al-verify [--pubkey PUBKEY] [--quiet] [--version] receipt
100
+ ```
101
+
102
+ | Argument | Meaning |
103
+ |---|---|
104
+ | `receipt` | Path to a receipt `.json`, a `.jsonl` ledger, an attestation or a rule bundle |
105
+ | `--pubkey` | The mediator's public key: a file, or the key inline as hex. Default: `keys/mediator_ed25519.pub` |
106
+ | `--quiet` | Print only the final verdict |
107
+ | `--version` | Print the version |
108
+
109
+ ## The receipt format
110
+
111
+ A receipt records exactly one decision:
112
+
113
+ ```json
114
+ {
115
+ "v": 1,
116
+ "seq": 42,
117
+ "ts": "2026-07-10T12:00:00.000Z",
118
+ "actor": "spiffe://acme/agent/claude-code",
119
+ "action": "mcp_tool_call",
120
+ "target": "tool:send_email",
121
+ "verdict": "block",
122
+ "findings": [
123
+ { "scanner": "tool_policy", "rule_id": "policy.default_deny", "severity": "high", "owasp": "ASI03", "mitre": "T1078" }
124
+ ],
125
+ "block_reason": "TOOL_NOT_ALLOWED",
126
+ "policy_hash": "sha256:...",
127
+ "redaction": { "aws-access-key": 1 },
128
+ "prev_hash": "sha256:...",
129
+ "record_hash": "sha256:...",
130
+ "sig": "ed25519:..."
131
+ }
132
+ ```
133
+
134
+ - `actor` is the identity the decision is bound to.
135
+ - `action` comes from a closed vocabulary. The vocabulary grows additively, so
136
+ this verifier still checks a receipt that carries a newer action.
137
+ - `redaction` holds counts per class. A receipt never carries the secret or
138
+ the personal data that was redacted.
139
+
140
+ The format is specified, with a JSON Schema, in
141
+ [receipt-v1](https://github.com/neural-nomad1709/agentlighthouse/blob/main/spec/receipt-v1.md).
142
+ The specification is MIT-licensed, so third parties can produce and verify
143
+ receipts without this code.
144
+
145
+ ## Trust model
146
+
147
+ Verification proves that the receipts were signed by the holder of the key you
148
+ supplied and that the chain has not been altered since. It follows that:
149
+
150
+ - **The public key must reach you through a channel you trust.** A ledger and
151
+ a key handed over together by the same party prove only that they match.
152
+ - **A verified chain is complete from genesis to its last receipt.** It does
153
+ not show that the mediator saw every action an agent took. That depends on
154
+ how the mediator is deployed: see the
155
+ [architecture document](https://github.com/neural-nomad1709/agentlighthouse/blob/main/docs/architecture.md).
156
+ - **A posture attestation names the chain head it was cut from**, so it can be
157
+ tied back to a ledger you have verified.
158
+
159
+ ## Related packages
160
+
161
+ | Package | What it is |
162
+ |---|---|
163
+ | [agentlighthouse-core](https://pypi.org/project/agentlighthouse-core/) | The mediator that produces the receipts. It depends on this package. |
164
+ | [agentlighthouse-governance](https://pypi.org/project/agentlighthouse-governance/) | Organizations, role-based access, budgets and signed posture attestation. |
165
+
166
+ ## License
167
+
168
+ MIT. See the `LICENSE` file shipped with this package.
@@ -0,0 +1,9 @@
1
+ al_verify/__init__.py,sha256=B41AaD5FipIUWHsNRFpJpHOZWimN2UbROPWOXWjqmjQ,1489
2
+ al_verify/canonical.py,sha256=7rQ_scoQtRPZ9i93QPyR0YSG5sZ2TnhEh6TBcKSAyjM,2867
3
+ al_verify/cli.py,sha256=8C_3D4-Y07hK5OLHSi8CCYvGwxLcEddEpaknr0u-Mto,4791
4
+ al_verify/verify.py,sha256=8hK5HoKFDWk0YcvL-whiaLJjiXtSL2gkwyvBdubXDkw,8194
5
+ agentlighthouse_verify-0.4.0.dist-info/METADATA,sha256=UDQl-bgTkHYmHCROmUSaG16Gs_euHTZtr29MneWBxFU,6065
6
+ agentlighthouse_verify-0.4.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ agentlighthouse_verify-0.4.0.dist-info/entry_points.txt,sha256=5hLNZWS1pbTdYtgW0khCnRmchwfzE2_mWUPxcs2uM_Y,49
8
+ agentlighthouse_verify-0.4.0.dist-info/licenses/LICENSE,sha256=QvwVREpwY5_cU3N3-4FtDaQNdnQg7IzyLxrIsxdcNlE,1066
9
+ agentlighthouse_verify-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ al-verify = al_verify.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Amit Kala
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
al_verify/__init__.py ADDED
@@ -0,0 +1,58 @@
1
+ """al-verify — standalone AgentLighthouse receipt verifier (MIT).
2
+
3
+ Public API is intentionally tiny and dependency-light so third parties can audit
4
+ AgentLighthouse evidence without installing al-core.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from .canonical import CanonicalizationError, canonicalize
10
+ from .verify import (
11
+ GENESIS_PREV_HASH,
12
+ HASH_PREFIX,
13
+ SIG_PREFIX,
14
+ ChainBroken,
15
+ MalformedReceipt,
16
+ RecordHashMismatch,
17
+ SignatureInvalid,
18
+ VerificationError,
19
+ compute_record_hash,
20
+ load_public_key,
21
+ record_hash_input,
22
+ sha256_hex,
23
+ signing_input,
24
+ verify_chain,
25
+ verify_receipt,
26
+ verify_signature,
27
+ )
28
+
29
+ from importlib.metadata import PackageNotFoundError, version as _dist_version
30
+
31
+ # The version lives in pyproject.toml (scripts/bump-version.sh); read it back
32
+ # from the installed distribution so the two cannot drift.
33
+ try:
34
+ __version__ = _dist_version("agentlighthouse-verify")
35
+ except PackageNotFoundError: # running from a source tree that is not installed
36
+ __version__ = "0+unknown"
37
+
38
+ __all__ = [
39
+ "__version__",
40
+ "canonicalize",
41
+ "CanonicalizationError",
42
+ "GENESIS_PREV_HASH",
43
+ "HASH_PREFIX",
44
+ "SIG_PREFIX",
45
+ "VerificationError",
46
+ "ChainBroken",
47
+ "MalformedReceipt",
48
+ "RecordHashMismatch",
49
+ "SignatureInvalid",
50
+ "compute_record_hash",
51
+ "load_public_key",
52
+ "record_hash_input",
53
+ "sha256_hex",
54
+ "signing_input",
55
+ "verify_chain",
56
+ "verify_receipt",
57
+ "verify_signature",
58
+ ]
al_verify/canonical.py ADDED
@@ -0,0 +1,66 @@
1
+ """RFC 8785 JSON Canonicalization Scheme (JCS) — minimal, self-contained.
2
+
3
+ This is the canonicalization used to hash and sign AgentLighthouse receipts.
4
+ It lives in the *verifier* (not core) on purpose: a third party must be able to
5
+ reproduce the exact bytes that were signed using only this file + a JSON parser.
6
+
7
+ Scope note (fail-closed by construction):
8
+ Receipts use only strings, integers, booleans, null, objects and arrays.
9
+ Floating-point numbers are intentionally REJECTED: RFC 8785 mandates
10
+ ECMAScript `Number.prototype.toString` for them, which is subtle and
11
+ error-prone. Every numeric receipt field (seq, counts, severity-as-string)
12
+ is an integer or string, so refusing floats removes a whole class of
13
+ canonicalization ambiguity rather than papering over it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ from typing import Any
20
+
21
+
22
+ class CanonicalizationError(ValueError):
23
+ """Raised when a value cannot be canonicalized per this JCS profile."""
24
+
25
+
26
+ def _encode_string(s: str) -> str:
27
+ # Python's json string encoder already matches RFC 8785 string rules:
28
+ # it emits the short escapes \" \\ \b \t \n \f \r, encodes other control
29
+ # characters (< 0x20) as \u00xx, does NOT escape '/', and (with
30
+ # ensure_ascii=False) leaves all other code points as literal UTF-8.
31
+ return json.dumps(s, ensure_ascii=False, separators=(",", ":"))
32
+
33
+
34
+ def _encode(value: Any) -> str:
35
+ # bool must be checked before int (bool is a subclass of int in Python).
36
+ if value is None:
37
+ return "null"
38
+ if value is True:
39
+ return "true"
40
+ if value is False:
41
+ return "false"
42
+ if isinstance(value, str):
43
+ return _encode_string(value)
44
+ if isinstance(value, int):
45
+ return str(value)
46
+ if isinstance(value, float):
47
+ raise CanonicalizationError(
48
+ "floats are not permitted in receipts; use integers or strings"
49
+ )
50
+ if isinstance(value, dict):
51
+ # RFC 8785: object members are sorted by the UTF-16 code units of their
52
+ # keys. Encoding each key to UTF-16 big-endian and comparing the byte
53
+ # sequences yields exactly that ordering (correct even for astral keys).
54
+ for k in value:
55
+ if not isinstance(k, str):
56
+ raise CanonicalizationError(f"object keys must be strings, got {type(k)!r}")
57
+ items = sorted(value.items(), key=lambda kv: kv[0].encode("utf-16-be"))
58
+ return "{" + ",".join(_encode_string(k) + ":" + _encode(v) for k, v in items) + "}"
59
+ if isinstance(value, (list, tuple)):
60
+ return "[" + ",".join(_encode(v) for v in value) + "]"
61
+ raise CanonicalizationError(f"unsupported type for canonicalization: {type(value)!r}")
62
+
63
+
64
+ def canonicalize(value: Any) -> bytes:
65
+ """Return the RFC 8785 JCS canonical form of ``value`` as UTF-8 bytes."""
66
+ return _encode(value).encode("utf-8")
al_verify/cli.py ADDED
@@ -0,0 +1,133 @@
1
+ """``al-verify`` command line: verify a receipt, a receipt chain, or an attestation.
2
+
3
+ Usage:
4
+ al-verify RECEIPT.json [--pubkey KEY]
5
+ al-verify LEDGER.jsonl [--pubkey KEY] # newline-delimited or JSON array
6
+ al-verify ATTESTATION.json [--pubkey KEY] # signed per-org posture (Phase 6)
7
+
8
+ KEY may be a path to a public-key file (64-hex or PEM) or an inline 64-hex
9
+ string. Defaults to ``keys/mediator_ed25519.pub``. Exit code is 0 only when
10
+ every receipt verifies; any failure exits non-zero (fail-closed).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import os
18
+ import sys
19
+ from pathlib import Path
20
+ from typing import Any
21
+
22
+ from . import __version__
23
+ from .verify import (
24
+ ATTESTATION_KIND,
25
+ RULE_BUNDLE_KIND,
26
+ VerificationError,
27
+ load_public_key,
28
+ verify_attestation,
29
+ verify_chain,
30
+ verify_receipt,
31
+ verify_rule_bundle,
32
+ )
33
+
34
+ DEFAULT_PUBKEY = "keys/mediator_ed25519.pub"
35
+
36
+
37
+ def _load_pubkey(arg: str):
38
+ # An existing path wins; otherwise treat the argument as an inline hex key.
39
+ p = Path(arg)
40
+ if p.exists():
41
+ return load_public_key(p.read_bytes())
42
+ return load_public_key(arg)
43
+
44
+
45
+ def _parse_receipts(text: str) -> tuple[list[dict[str, Any]], bool]:
46
+ """Return (receipts, is_chain). is_chain True for arrays / JSONL."""
47
+ stripped = text.strip()
48
+ if not stripped:
49
+ raise ValueError("input is empty")
50
+ try:
51
+ doc = json.loads(stripped)
52
+ except json.JSONDecodeError:
53
+ # Fall back to newline-delimited JSON (one receipt per line).
54
+ receipts = [json.loads(line) for line in stripped.splitlines() if line.strip()]
55
+ return receipts, True
56
+ if isinstance(doc, dict):
57
+ return [doc], False
58
+ if isinstance(doc, list):
59
+ return doc, True
60
+ raise ValueError("top-level JSON must be an object (receipt) or array (chain)")
61
+
62
+
63
+ def main(argv: list[str] | None = None) -> int:
64
+ parser = argparse.ArgumentParser(
65
+ prog="al-verify",
66
+ description="Independently verify AgentLighthouse receipts (hash chain + Ed25519).",
67
+ )
68
+ parser.add_argument("receipt", help="path to a receipt .json or a .jsonl ledger")
69
+ parser.add_argument(
70
+ "--pubkey",
71
+ default=os.environ.get("AL_PUBKEY", DEFAULT_PUBKEY),
72
+ help=f"public key file or inline hex (default: {DEFAULT_PUBKEY})",
73
+ )
74
+ parser.add_argument("--quiet", action="store_true", help="only report the final verdict")
75
+ parser.add_argument("--version", action="version", version=f"al-verify {__version__}")
76
+ args = parser.parse_args(argv)
77
+
78
+ try:
79
+ public_key = _load_pubkey(args.pubkey)
80
+ except Exception as exc: # noqa: BLE001 — surface any key-loading failure clearly
81
+ print(f"FAIL: could not load public key from {args.pubkey!r}: {exc}", file=sys.stderr)
82
+ return 2
83
+
84
+ try:
85
+ text = Path(args.receipt).read_text(encoding="utf-8")
86
+ receipts, is_chain = _parse_receipts(text)
87
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
88
+ print(f"FAIL: could not read receipts from {args.receipt!r}: {exc}", file=sys.stderr)
89
+ return 2
90
+
91
+ try:
92
+ if is_chain:
93
+ n = verify_chain(receipts, public_key)
94
+ if not args.quiet:
95
+ print(f"chain of {n} receipt(s) verified from genesis")
96
+ elif receipts[0].get("kind") == RULE_BUNDLE_KIND:
97
+ bundle = receipts[0]
98
+ verify_rule_bundle(bundle, public_key)
99
+ if not args.quiet:
100
+ print(
101
+ f"rule bundle {bundle.get('bundle_id')!r} verified "
102
+ f"({len(bundle.get('rules', []))} rule(s), "
103
+ f"approved by {bundle.get('approved_by')!r})"
104
+ )
105
+ elif receipts[0].get("kind") == ATTESTATION_KIND:
106
+ att = receipts[0]
107
+ verify_attestation(att, public_key)
108
+ if not args.quiet:
109
+ chain = att.get("chain", {})
110
+ print(
111
+ f"posture attestation for org={att.get('org')!r} verified "
112
+ f"(level {att.get('evidence_level')}, "
113
+ f"{att.get('evidence', {}).get('events')} events, "
114
+ f"chain head {str(chain.get('head'))[:23]}...)"
115
+ )
116
+ else:
117
+ rec = receipts[0]
118
+ verify_receipt(rec, public_key)
119
+ if not args.quiet:
120
+ print(
121
+ f"receipt seq={rec.get('seq')} action={rec.get('action')!r} "
122
+ f"verdict={rec.get('verdict')!r} verified"
123
+ )
124
+ except VerificationError as exc:
125
+ print(f"FAIL: {type(exc).__name__}: {exc}", file=sys.stderr)
126
+ return 1
127
+
128
+ print("OK")
129
+ return 0
130
+
131
+
132
+ if __name__ == "__main__": # pragma: no cover
133
+ raise SystemExit(main())
al_verify/verify.py ADDED
@@ -0,0 +1,227 @@
1
+ """Receipt verification: hash chain + Ed25519 signature.
2
+
3
+ This module defines the *canonical truth* about how a receipt is hashed and
4
+ signed. ``al-core`` imports these functions when building receipts so the
5
+ producing and verifying sides are provably symmetric; a third party can verify
6
+ with only this package installed (no ``al-core``).
7
+
8
+ Hashing/signing procedure (receipt schema v1):
9
+ 1. ``record_hash`` = "sha256:" + hex( SHA-256( JCS(receipt \\ {record_hash, sig}) ) )
10
+ — commits to every field except record_hash and sig, *including* prev_hash.
11
+ 2. ``sig`` = "ed25519:" + b64( Ed25519.sign( JCS(receipt \\ {sig}) ) )
12
+ — signs the record_hash together with all other content.
13
+ 3. Chain: ``prev_hash`` of record N equals ``record_hash`` of record N-1.
14
+ The genesis record's prev_hash is ``GENESIS_PREV_HASH``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import hashlib
21
+ from typing import Any, Iterable
22
+
23
+ from cryptography.exceptions import InvalidSignature
24
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
25
+ from cryptography.hazmat.primitives.serialization import load_pem_public_key
26
+
27
+ from .canonical import canonicalize
28
+
29
+ HASH_PREFIX = "sha256:"
30
+ SIG_PREFIX = "ed25519:"
31
+ GENESIS_PREV_HASH = HASH_PREFIX + "0" * 64
32
+
33
+
34
+ class VerificationError(Exception):
35
+ """Base class for all receipt verification failures (fail-closed)."""
36
+
37
+
38
+ class RecordHashMismatch(VerificationError):
39
+ pass
40
+
41
+
42
+ class SignatureInvalid(VerificationError):
43
+ pass
44
+
45
+
46
+ class ChainBroken(VerificationError):
47
+ pass
48
+
49
+
50
+ class MalformedReceipt(VerificationError):
51
+ pass
52
+
53
+
54
+ def sha256_hex(data: bytes) -> str:
55
+ return HASH_PREFIX + hashlib.sha256(data).hexdigest()
56
+
57
+
58
+ def _without(receipt: dict[str, Any], *keys: str) -> dict[str, Any]:
59
+ return {k: v for k, v in receipt.items() if k not in keys}
60
+
61
+
62
+ def record_hash_input(receipt: dict[str, Any]) -> bytes:
63
+ """Canonical bytes that ``record_hash`` is computed over."""
64
+ return canonicalize(_without(receipt, "record_hash", "sig"))
65
+
66
+
67
+ def signing_input(receipt: dict[str, Any]) -> bytes:
68
+ """Canonical bytes that ``sig`` is computed over (includes record_hash)."""
69
+ return canonicalize(_without(receipt, "sig"))
70
+
71
+
72
+ def compute_record_hash(receipt: dict[str, Any]) -> str:
73
+ return sha256_hex(record_hash_input(receipt))
74
+
75
+
76
+ def _load_pem(data: bytes) -> Ed25519PublicKey:
77
+ key = load_pem_public_key(data)
78
+ if not isinstance(key, Ed25519PublicKey):
79
+ raise MalformedReceipt("public key is not an Ed25519 key")
80
+ return key
81
+
82
+
83
+ def load_public_key(source: str | bytes) -> Ed25519PublicKey:
84
+ """Load an Ed25519 public key from 64-char hex, raw 32 bytes, or PEM.
85
+
86
+ Accepts either a string (hex or PEM text) or bytes. Bytes of exactly length
87
+ 32 are treated as a raw key; other bytes are decoded as text first, so a
88
+ ``.pub`` file containing hex (our on-disk format) loads correctly.
89
+ """
90
+ if isinstance(source, bytes):
91
+ if len(source) == 32:
92
+ return Ed25519PublicKey.from_public_bytes(source)
93
+ try:
94
+ source = source.decode("utf-8")
95
+ except UnicodeDecodeError:
96
+ return _load_pem(source)
97
+ text = source.strip()
98
+ compact = "".join(text.split())
99
+ if len(compact) == 64:
100
+ try:
101
+ return Ed25519PublicKey.from_public_bytes(bytes.fromhex(compact))
102
+ except ValueError:
103
+ pass
104
+ return _load_pem(text.encode("utf-8"))
105
+
106
+
107
+ def _require(receipt: dict[str, Any], field: str) -> Any:
108
+ if field not in receipt:
109
+ raise MalformedReceipt(f"receipt missing required field: {field!r}")
110
+ return receipt[field]
111
+
112
+
113
+ def verify_record_hash(receipt: dict[str, Any]) -> None:
114
+ stored = _require(receipt, "record_hash")
115
+ expected = compute_record_hash(receipt)
116
+ if stored != expected:
117
+ raise RecordHashMismatch(
118
+ f"record_hash mismatch: stored {stored!r} != computed {expected!r}"
119
+ )
120
+
121
+
122
+ def verify_signature(receipt: dict[str, Any], public_key: Ed25519PublicKey) -> None:
123
+ sig = _require(receipt, "sig")
124
+ if not isinstance(sig, str) or not sig.startswith(SIG_PREFIX):
125
+ raise MalformedReceipt(f"sig must be an '{SIG_PREFIX}...' string")
126
+ try:
127
+ raw = base64.b64decode(sig[len(SIG_PREFIX):], validate=True)
128
+ except (ValueError, TypeError) as exc:
129
+ raise MalformedReceipt(f"sig is not valid base64: {exc}") from exc
130
+ try:
131
+ public_key.verify(raw, signing_input(receipt))
132
+ except InvalidSignature as exc:
133
+ raise SignatureInvalid("Ed25519 signature does not verify") from exc
134
+
135
+
136
+ def verify_receipt(
137
+ receipt: dict[str, Any],
138
+ public_key: Ed25519PublicKey,
139
+ expected_prev_hash: str | None = None,
140
+ ) -> str:
141
+ """Verify one receipt fully. Returns its ``record_hash`` (for chaining).
142
+
143
+ Raises a ``VerificationError`` subclass on any failure — never returns on a
144
+ bad receipt (fail-closed).
145
+ """
146
+ verify_record_hash(receipt)
147
+ verify_signature(receipt, public_key)
148
+ if expected_prev_hash is not None:
149
+ actual = _require(receipt, "prev_hash")
150
+ if actual != expected_prev_hash:
151
+ raise ChainBroken(
152
+ f"prev_hash mismatch at seq {receipt.get('seq')}: "
153
+ f"expected {expected_prev_hash!r}, found {actual!r}"
154
+ )
155
+ return receipt["record_hash"]
156
+
157
+
158
+ ATTESTATION_KIND = "al.posture-attestation.v1"
159
+ RULE_BUNDLE_KIND = "al.rule-bundle.v1"
160
+
161
+
162
+ def verify_rule_bundle(
163
+ bundle: dict[str, Any], public_key: Ed25519PublicKey
164
+ ) -> str:
165
+ """Verify a signed learned-rule bundle. Returns its ``record_hash``.
166
+
167
+ A rule bundle changes what the mediator blocks, so it is *code* in the only
168
+ sense that matters. It is signed with the mediator key and verified before
169
+ load — an unsigned or tampered bundle is refused, never "loaded with a
170
+ warning". Same canonicalization + signature procedure as a receipt, so this
171
+ dependency-minimal verifier can check one with no runtime present.
172
+ """
173
+ kind = _require(bundle, "kind")
174
+ if kind != RULE_BUNDLE_KIND:
175
+ raise MalformedReceipt(
176
+ f"not a rule bundle: kind={kind!r} (want {RULE_BUNDLE_KIND!r})")
177
+ for field in ("bundle_id", "created_ts", "rules", "approved_by"):
178
+ _require(bundle, field)
179
+ if not isinstance(bundle["rules"], list):
180
+ raise MalformedReceipt("rule bundle 'rules' must be a list")
181
+ verify_record_hash(bundle)
182
+ verify_signature(bundle, public_key)
183
+ return bundle["record_hash"]
184
+
185
+
186
+ def verify_attestation(
187
+ attestation: dict[str, Any], public_key: Ed25519PublicKey
188
+ ) -> str:
189
+ """Verify a signed per-org posture attestation. Returns its ``record_hash``.
190
+
191
+ An attestation is a standalone signed statement (no ``prev_hash`` chain) —
192
+ it *quotes* the chain head it was cut from, so an auditor can tie it back to
193
+ the ledger. It uses the same canonicalization and signature procedure as a
194
+ receipt, so this verifier needs no AgentLighthouse runtime and no
195
+ governance code to check one.
196
+ """
197
+ kind = _require(attestation, "kind")
198
+ if kind != ATTESTATION_KIND:
199
+ raise MalformedReceipt(
200
+ f"not an attestation: kind={kind!r} (want {ATTESTATION_KIND!r})")
201
+ for field in ("org", "issued_ts", "chain", "posture", "evidence"):
202
+ _require(attestation, field)
203
+ verify_record_hash(attestation)
204
+ verify_signature(attestation, public_key)
205
+ return attestation["record_hash"]
206
+
207
+
208
+ def verify_chain(
209
+ receipts: Iterable[dict[str, Any]],
210
+ public_key: Ed25519PublicKey,
211
+ genesis_prev_hash: str = GENESIS_PREV_HASH,
212
+ ) -> int:
213
+ """Verify an ordered sequence of receipts as a hash chain.
214
+
215
+ Returns the number of receipts verified. Raises on the first failure.
216
+ """
217
+ expected_prev = genesis_prev_hash
218
+ count = 0
219
+ last_seq: int | None = None
220
+ for receipt in receipts:
221
+ seq = receipt.get("seq")
222
+ if last_seq is not None and isinstance(seq, int) and seq != last_seq + 1:
223
+ raise ChainBroken(f"non-contiguous seq: {last_seq} -> {seq}")
224
+ expected_prev = verify_receipt(receipt, public_key, expected_prev)
225
+ last_seq = seq if isinstance(seq, int) else last_seq
226
+ count += 1
227
+ return count