diff --git a/.github/workflows/auditant-evidence-bundle-conformance.yml b/.github/workflows/auditant-evidence-bundle-conformance.yml new file mode 100644 index 00000000..c9352713 --- /dev/null +++ b/.github/workflows/auditant-evidence-bundle-conformance.yml @@ -0,0 +1,100 @@ +name: auditant-evidence-bundle conformance + +on: + push: + paths: + - "integrations/auditant-evidence-bundle/**" + - ".github/workflows/auditant-evidence-bundle-conformance.yml" + pull_request: + paths: + - "integrations/auditant-evidence-bundle/**" + - ".github/workflows/auditant-evidence-bundle-conformance.yml" + schedule: + - cron: "0 6 * * 1" + workflow_dispatch: + +permissions: + contents: read + +jobs: + conformance: + strategy: + fail-fast: false + matrix: + python: ["3.11", "3.12", "3.13"] + os: [ubuntu-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 + with: + python-version: ${{ matrix.python }} + + - name: Install exact released dependencies + run: | + python -m pip install --upgrade pip==26.2.1 + python -m pip install --no-cache-dir \ + "agentrust-trace==0.11.0" \ + "agentrust-trace-tests==0.6.2" \ + "agentrust-trace-adapters==0.2.0" \ + "pytest==9.1.1" + + - name: Install only the thin integration locally + run: python -m pip install --no-deps -e "integrations/auditant-evidence-bundle" + + - name: Integration tests + run: python -m pytest integrations/auditant-evidence-bundle/tests -q + + - name: Emit a TRACE record from the Auditant-made fixture + run: | + python integrations/auditant-evidence-bundle/examples/emit_record.py \ + --out auditant.trace.json + + - name: Determine TRACE conformance level + run: | + trace-tests report \ + --record auditant.trace.json \ + --max-level 2 \ + --json auditant-trace-report.json + python - <<'PY' + import json + from pathlib import Path + + report = json.loads(Path("auditant-trace-report.json").read_text()) + assert report["tooling"]["suite"] == "0.6.2" + assert report["tooling"]["library"] == "0.11.0" + assert report["highest_level_passed"] == 0 + assert report["levels"][0]["passed"] is True + assert report["levels"][1]["passed"] is False + assert report["levels"][2]["passed"] is False + PY + + - name: Transcript hash is the tool-call events, recomputed here + run: | + python - <<'PY' + import hashlib, json + from pathlib import Path + + import rfc8785 + + record = json.loads(Path("auditant.trace.json").read_text()) + bundle = json.loads(Path("integrations/auditant-evidence-bundle/fixtures/auditant-full.json").read_text()) + calls = [e for e in bundle["events"] if e["actionType"] == "tool_call"] + assert record["tool_transcript"]["hash"] == "sha256:" + hashlib.sha256(rfc8785.dumps(calls)).hexdigest() + assert record["tool_transcript"]["call_count"] == len(calls) + assert record["origin"]["source_event_id"] == bundle["events"][-1]["eventId"] + PY + + - name: Enforce declared TRACE Level 0 + run: trace-tests verify --record auditant.trace.json --level 0 + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: auditant-conformance-${{ matrix.os }}-py${{ matrix.python }} + path: | + integrations/auditant-evidence-bundle/fixtures/auditant-full.json + auditant.trace.json + auditant-trace-report.json diff --git a/README.md b/README.md index 24f06c62..8dd5fb7e 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ TRACE only works as a standard if it is genuinely neutral. Integrations are list | [AAIF Authority Comparison Runner](integrations/alakris-authority-comparison/) | Alakris Research | trace | community | | [Agent Replay](integrations/altrudev-agent-replay/) | Altru.dev | trace | verified | | [Frequency Agent Execution Assurance](integrations/altrudev-frequency-agent-execution-assurance/) | Altru.dev | trace | community | +| [Auditant evidence bundle](integrations/auditant-evidence-bundle/) | Auditant | trace | community | | [Bernstein MCP verifier](integrations/bernstein-mcp/) | Bernstein | trace | verified | | [CHAP](integrations/chap/) | agentrust-io | trace | verified | | [AI Agent Incident Register](integrations/companyscope-incident-register/) | CompanyScope | agent-manifest | verified | diff --git a/integrations/auditant-evidence-bundle/README.md b/integrations/auditant-evidence-bundle/README.md new file mode 100644 index 00000000..cf21b908 --- /dev/null +++ b/integrations/auditant-evidence-bundle/README.md @@ -0,0 +1,90 @@ +# Auditant evidence bundle to TRACE + +Auditant records an AI agent's model calls, tool calls and policy decisions in a hash chain and exports them as an evidence bundle ([`GET /v1/export`](https://auditant.co/docs/api#get-v1-export), bundle format 1.0.0). `auditant_trace.py` re-checks a bundle offline and, only if it verifies, emits a TRACE v0.2 **log-import** Trust Record at **Level 0** (software-only). The record is assembled by [`agentrust-trace-adapters`](../../packages/agentrust-trace-adapters/) `build_record`, so it carries no placeholder values. + +## The checks + +Every check fails closed: one failure anywhere and no record is written. + +1. **Structure.** Each field a check reads is present with the right type. Integers are integers (a JSON `true` is not a tree size), digests are `sha256:` plus 64 hex characters, and a JSON object may not repeat a key. Malformed input is reported as `BundleNotVerified`, never raised as another exception. +2. **Chain.** `seq` increments by one, each `prevHash` equals the previous `eventHash` (the first links to `startHead` when the export starts mid-log, and to the all-zero genesis hash when it starts at `seq` 0), and each `eventHash` equals `sha256` over the [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785) form of the event without its `eventHash`. +3. **Checkpoints.** Every checkpoint in the bundle must verify, not only the one that anchors it: its key is listed in the bundle (and pinned, when `--pin-key` is given), its origin is this log's, its fields re-serialise to the signed body, its signature is canonical base64 and verifies, and if its tree size falls inside the exported window its head equals the recomputed chain head at that size. A checkpoint that ends outside the window gets every check except the head, which the bundle cannot recompute, and does not count for anchoring. +4. **Anchoring, at both ends.** A verified checkpoint covers the last event, and the head the bundle starts from is either the genesis hash or signed by a verified checkpoint. Without the second half, an export with its first events deleted would pass for a shorter one. + +A record is built only from a **whole log** (first `seq` 0). A ranged export can verify, but TRACE has no field that says a record covers part of a log, so a record from one would read as the whole of it, with a transcript, model and policy facts that silently omit everything before the excerpt. + +## What an Auditant checkpoint is, and is not + +The signed body uses the line layout of a [C2SP tlog-checkpoint](https://c2sp.org/tlog-checkpoint) (origin, tree size, base64 hash), but the hash line is the head of a **linear hash chain**, the `eventHash` of the last event, **not an RFC 6962 Merkle tree root**, and the signature is a bare ECDSA P-256 / SHA-256 signature over the body, not a C2SP signed note. So it is not a C2SP checkpoint: there are no inclusion or consistency proofs, and C2SP witnesses and tools do not apply. Checking a bundle means walking every event, which this adapter does. + +## What it does not claim + +- No hardware attestation. `runtime.platform` is `software-only`; Level 1 fails `TR-RTE-001`, `TR-RTE-004` and `TR-APR-005` by design. +- A bundle carries its own public keys, so a valid checkpoint signature shows the bundle agrees with itself, not who made it. Pass `--pin-key KEYID=PEMFILE` with a key obtained out of band to require it; then every checkpoint must be signed by a pinned key. +- RFC 3161 timestamp tokens on checkpoints are not checked. +- The bundle does not carry the agent's workload identity, the policy bundle's bytes or the agent's artifact digest. The operator supplies all three, and nothing is derived from the log ID or from policy names. +- `appraisal.status` is `none`. Building a record is not an appraisal. + +## Field mapping + +| TRACE field | Value | +|---|---| +| `subject` | `--subject`: the agent workload's SPIFFE URI or DID, from the operator. The bundle's `actor.id` is an Auditant-scoped name, not an identity | +| `model` | the one provider and model the bundle's `model_call` events name in `cost.provider` / `cost.model`. With several, `--model-provider` and `--model-id` choose, and a choice must match a `model_call` event: a value given for one half is never replaced by inference. A `model_call` event that names no model is refused | +| `policy.bundle_hash` | `sha256` of `--policy-bundle`, the bytes of the policy the deployment runs | +| `policy.enforcement_mode` | `--enforcement-mode`, no default: `enforce` when tool calls were held by policy before they ran, `advisory` when decisions were only recorded, `declared` when no policy was evaluated. A bundle holding `policy_decision` events shows a policy was evaluated, so `declared` is refused for it | +| `tool_transcript.hash` | `sha256` over the RFC 8785 form of the bundle's `tool_call` events, in order, each exactly as exported (`eventHash` included); omitted when there are none | +| `tool_transcript.call_count` | number of `tool_call` events | +| `origin` | `kind: log-import`; `producer`: `--producer`, default `https://auditant.co` (a self-hosted deployment passes its own URL); `source_event_id`: the `eventId` of the last event, the one the anchoring checkpoint covers | +| `runtime.measurement` | `build_record`'s software commitment over producer, subject and policy hash; with `platform: software-only` it is not a hardware measurement | +| `build_provenance.digest` | `--workload-digest`: the agent's image or artifact digest, from the operator (`slsa_level: 0`) | +| `cnf.jwk` | the public half of the key the record is signed with | + +## Run it + +Against released packages, on a fixture made by Auditant's own exporter: + +```bash +pip install "agentrust-trace==0.11.0" "agentrust-trace-adapters==0.2.0" "agentrust-trace-tests==0.6.2" "pytest==9.1.1" +pip install --no-deps -e integrations/auditant-evidence-bundle +python -m pytest integrations/auditant-evidence-bundle/tests -q +python integrations/auditant-evidence-bundle/examples/emit_record.py --out auditant.trace.json +trace-tests verify --record auditant.trace.json --level 0 +``` + +On a real export: + +```bash +auditant-trace bundle.json --out bundle.trace.json \ + --subject spiffe://example.org/agent/support-bot \ + --policy-bundle policy.cedar \ + --enforcement-mode advisory \ + --workload-digest sha256:<64 hex> \ + --data-class confidential \ + --pin-key auditant-1a2b3c4d5e6f=operator-checkpoint-key.pem \ + --signing-key trace-signing-key.pem +``` + +Without `--signing-key`, `TRACE_PRIVATE_KEY_PEM` is used, else an ephemeral Ed25519 key with a warning. + +## What is verified + +The fixtures in [`fixtures/`](fixtures/) were made by Auditant's own TypeScript core and passed its own verifier, so the tests check this adapter against an independent producer, not against bundles it wrote itself. A reviewer can reproduce: + +1. The tests (66): + - whole and ranged exports verify, and only a whole log yields a record; + - deleting the first events is caught, a ranged export needs a signed start, and a `startHead` at tree size 0 must be the genesis hash; + - each TRACE field carries the meaning in the table above; + - model choices are checked against the events; + - an edited, deleted, reordered or truncated event, a broken start link and a missing key each produce no record; + - a failed checkpoint fails the bundle even when another checkpoint anchors it, and so does a checkpoint under an unlisted key, one for another log, or one that contradicts the chain; + - an unpinned key fails when keys are pinned; + - non-canonical base64 (unused bits, missing padding, a newline, the URL-safe alphabet) is refused, in the signature and in a signed body; + - a boolean or float where an integer belongs, missing keys (an `eventId` included), wrong types, duplicate keys, deeply nested input, non-JSON bytes and non-object JSON are refused as `BundleNotVerified`; + - the CLI writes nothing for a bundle that fails and exits 2 with a message on a missing file or a malformed `--pin-key`. +2. `trace-tests verify --level 0`: `Result: PASS (15 checks, 4 skipped)`, with `agentrust-trace` 0.11.0 and `agentrust-trace-tests` 0.6.2. `trace-tests report --max-level 2` gives highest level passed 0. +3. `tool_transcript.hash` equals `sha256` of the RFC 8785 form of `fixtures/auditant-full.json`'s `tool_call` events. + +## Conformance CI + +`.github/workflows/auditant-evidence-bundle-conformance.yml` installs the pinned released packages, runs the tests, emits a record from the fixture, asserts the level report (0 passes, 1 and 2 fail), recomputes the transcript hash from the fixture, and enforces Level 0. diff --git a/integrations/auditant-evidence-bundle/auditant_trace.py b/integrations/auditant-evidence-bundle/auditant_trace.py new file mode 100644 index 00000000..dcb84ce4 --- /dev/null +++ b/integrations/auditant-evidence-bundle/auditant_trace.py @@ -0,0 +1,605 @@ +"""Map an Auditant evidence bundle to a TRACE v0.2 log-import Trust Record. + +An Auditant evidence bundle (``GET /v1/export``, bundle format 1.0.0) is one JSON +file: a run of hash-chained agent events, signed checkpoints over the chain head, +and the public keys for those signatures. This module re-checks the bundle offline +and only then builds a record. Every check fails closed: one failure anywhere and +no record is built. + +1. Structure: the fields each check reads are present and have the right type. + Integers are integers (a JSON ``true`` is not a tree size), digests are + ``sha256:`` plus 64 hex characters, and a JSON object may not repeat a key. +2. Chain: ``seq`` increments by one, each ``prevHash`` equals the previous + ``eventHash`` (the first links to ``startHead`` when the export starts + mid-log, to the all-zero genesis hash when it starts at ``seq`` 0), and each + ``eventHash`` equals ``sha256`` over the RFC 8785 form of the event without + its ``eventHash``. +3. Checkpoints: every checkpoint in the bundle must verify, not just one. Its key + is listed in the bundle (and pinned, when keys are pinned), its origin is this + log's, its fields re-serialise to the signed body, its signature is canonical + base64 and verifies, and if its tree size falls inside the exported window its + head equals the recomputed chain head at that size. A checkpoint outside the + window is checked for all of that except the head, which the bundle cannot + recompute, and is not used for anchoring. +4. Anchoring: a verified checkpoint covers the last event in the bundle, and the + head the bundle starts from is either the genesis hash or signed by a verified + checkpoint, so deleting the first events cannot pass for a shorter export. + +A record is built only from a whole log (first ``seq`` 0). A ranged export can +verify, but TRACE has no field that says a record covers part of a log, so a +record from one would read as the whole of it. + +**What an Auditant checkpoint is, and is not.** Its signed body uses the line +layout of a C2SP tlog-checkpoint (origin, tree size, base64 hash), but the hash +line is the head of a linear hash chain, the ``eventHash`` of the last event, not +an RFC 6962 Merkle tree root, and the signature is a bare ECDSA P-256 / SHA-256 +signature over the body, not a C2SP signed note. It is therefore not a C2SP +checkpoint: there are no inclusion or consistency proofs, and C2SP witnesses and +tools do not apply. Checking a bundle means walking every event, which this does. + +Not checked: RFC 3161 timestamp tokens on checkpoints, and whether a key is the +operator's real key. A bundle carries its own public keys, so a valid signature +shows the bundle agrees with itself, not who made it. Pass ``pinned_keys`` with +keys obtained out of band to require them. + +The record is assembled by ``agentrust_trace_adapters.build_record`` and claims +only what the bundle or the operator supplies. The bundle names the model, the +tool calls and the anchored event. It does not carry the workload's identity, the +policy bundle's bytes or the workload's artifact digest, so the operator supplies +``subject``, ``policy_bundle`` and ``workload_digest``; nothing is derived from +the log ID or from policy names. +""" + +from __future__ import annotations + +import argparse +import base64 +import hashlib +import json +import re +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import rfc8785 +from agentrust_trace_adapters import MissingEvidence, PolicyEvidence, SourceSystem, build_record +from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from agentrust_trace.models import TrustRecord +from agentrust_trace.sign import key_to_jwk, load_key, load_signing_key, sign_record + +__all__ = [ + "BundleCheck", + "BundleNotVerified", + "build_trust_record", + "check_bundle", + "models_in_bundle", + "select_model", + "tool_transcript_bytes", +] + +SUPPORTED_BUNDLE_VERSIONS = frozenset({"1.0.0"}) +CHECKPOINT_ORIGIN_PREFIX = "auditant.dev" +GENESIS = "sha256:" + "0" * 64 +# A URI: build_record also carries the producer as appraisal.verifier, which the schema types as a URI. +DEFAULT_PRODUCER = "https://auditant.co" +ENFORCEMENT_MODES = PolicyEvidence.MODES +_DIGEST = re.compile(r"sha256:[0-9a-f]{64}") + + +class BundleNotVerified(ValueError): + """The bundle did not verify; no record may be built from it.""" + + def __init__(self, reasons: list[str]) -> None: + super().__init__("; ".join(reasons)) + self.reasons = reasons + + +@dataclass +class BundleCheck: + ok: bool + log_id: str + events: int + anchored_through_size: int = 0 + anchoring_body: str | None = None + anchoring_head: str | None = None + anchored_event_id: str | None = None + reasons: list[str] = field(default_factory=list) + + +def _is_int(value: Any) -> bool: + # bool is a subclass of int in Python; JSON true is not a sequence number. + return type(value) is int + + +def _is_digest(value: Any) -> bool: + return isinstance(value, str) and _DIGEST.fullmatch(value) is not None + + +def _b64decode_canonical(text: str) -> bytes: + """Strict base64: standard alphabet, correct padding, and the one encoding of its bytes.""" + raw = base64.b64decode(text, validate=True) + if base64.b64encode(raw).decode("ascii") != text: + raise ValueError("base64 is not in canonical form") + return raw + + +def event_hash(event: dict[str, Any]) -> str: + """``sha256`` over the RFC 8785 form of the event minus ``eventHash``.""" + payload = {k: v for k, v in event.items() if k != "eventHash"} + return "sha256:" + hashlib.sha256(rfc8785.dumps(payload)).hexdigest() + + +def checkpoint_body(checkpoint: dict[str, Any]) -> str: + """The signed body: origin, tree size, base64 of the chain head, newline-terminated.""" + head = bytes.fromhex(checkpoint["headHash"][len("sha256:") :]) + return "\n".join( + [checkpoint["origin"], str(checkpoint["treeSize"]), base64.b64encode(head).decode(), ""] + ) + + +def _public_key(pem: str) -> ec.EllipticCurvePublicKey: + key = serialization.load_pem_public_key(pem.encode()) + if not isinstance(key, ec.EllipticCurvePublicKey) or key.curve.name != "secp256r1": + raise ValueError("not an ECDSA P-256 public key") + return key + + +def _spki(pem: str) -> bytes: + return _public_key(pem).public_bytes( + serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo + ) + + +def _structure(bundle: Any) -> list[str]: + """Shape errors, so that no later check can raise on unexpected content.""" + if not isinstance(bundle, dict): + return [f"the bundle is a JSON {type(bundle).__name__}, not an object"] + reasons: list[str] = [] + version = bundle.get("bundleVersion") + if version not in SUPPORTED_BUNDLE_VERSIONS: + reasons.append(f"unsupported bundleVersion {version!r}") + log_id = bundle.get("logId") + if not isinstance(log_id, str) or not log_id: + reasons.append("logId is missing or not a string") + + events = bundle.get("events") + if not isinstance(events, list) or not events: + reasons.append("events is missing, empty or not a list") + else: + for i, event in enumerate(events): + where = f"events[{i}]" + if not isinstance(event, dict): + reasons.append(f"{where} is not an object") + continue + if not _is_int(event.get("seq")) or event["seq"] < 0: + reasons.append(f"{where}.seq is not a non-negative integer") + for key in ("prevHash", "eventHash"): + if not _is_digest(event.get(key)): + reasons.append(f"{where}.{key} is not a sha256 digest") + for key in ("logId", "actionType"): + if not isinstance(event.get(key), str): + reasons.append(f"{where}.{key} is not a string") + if not isinstance(event.get("eventId"), str) or not event["eventId"]: + reasons.append(f"{where}.eventId is not a non-empty string") + + checkpoints = bundle.get("checkpoints") + if not isinstance(checkpoints, list): + reasons.append("checkpoints is missing or not a list") + else: + for i, signed in enumerate(checkpoints): + where = f"checkpoints[{i}]" + if not isinstance(signed, dict) or not isinstance(signed.get("checkpoint"), dict): + reasons.append(f"{where} is not a signed checkpoint object") + continue + cp = signed["checkpoint"] + if not isinstance(cp.get("origin"), str): + reasons.append(f"{where}.checkpoint.origin is not a string") + if not _is_int(cp.get("treeSize")) or cp["treeSize"] < 1: + reasons.append(f"{where}.checkpoint.treeSize is not a positive integer") + if not _is_digest(cp.get("headHash")): + reasons.append(f"{where}.checkpoint.headHash is not a sha256 digest") + for key in ("body", "keyId", "signature"): + if not isinstance(signed.get(key), str): + reasons.append(f"{where}.{key} is not a string") + + keys = bundle.get("publicKeys") + if not isinstance(keys, list): + reasons.append("publicKeys is missing or not a list") + else: + seen: set[str] = set() + for i, entry in enumerate(keys): + if not ( + isinstance(entry, dict) + and isinstance(entry.get("keyId"), str) + and isinstance(entry.get("pem"), str) + ): + reasons.append(f"publicKeys[{i}] needs a string keyId and pem") + continue + if entry["keyId"] in seen: + reasons.append(f"publicKeys lists {entry['keyId']!r} more than once") + seen.add(entry["keyId"]) + + start = bundle.get("startHead") + if start is not None: + if not ( + isinstance(start, dict) + and _is_int(start.get("treeSize")) + and start["treeSize"] >= 0 + and _is_digest(start.get("headHash")) + ): + reasons.append("startHead needs a non-negative integer treeSize and a sha256 headHash") + elif start.get("logId", log_id) != log_id: + reasons.append("startHead belongs to another log") + elif start["treeSize"] == 0 and start["headHash"] != GENESIS: + reasons.append("startHead at tree size 0 is not the genesis hash") + return reasons + + +def _check(bundle: Any, pinned_keys: dict[str, str] | None) -> BundleCheck: + reasons = _structure(bundle) + if reasons: + log_id = bundle.get("logId") if isinstance(bundle, dict) else None + events = bundle.get("events") if isinstance(bundle, dict) else None + return BundleCheck( + False, + log_id if isinstance(log_id, str) else "", + len(events) if isinstance(events, list) else 0, + reasons=reasons, + ) + + log_id: str = bundle["logId"] + events: list[dict[str, Any]] = bundle["events"] + start = bundle.get("startHead") + + # 2. Chain. + first_size = events[0]["seq"] + if start is not None: + expected_seq, expected_prev = start["treeSize"], start["headHash"] + elif first_size == 0: + expected_seq, expected_prev = 0, GENESIS + else: + # An excerpt without startHead links to whatever its first event names; step 3 + # accepts that only if a verified checkpoint signs that head. + expected_seq, expected_prev = first_size, events[0]["prevHash"] + head_at: dict[int, str] = {expected_seq: expected_prev} + for event in events: + seq = event["seq"] + if event["logId"] != log_id: + reasons.append(f"event {seq} belongs to log {event['logId']!r}") + if seq != expected_seq: + reasons.append(f"sequence gap: expected {expected_seq}, found {seq}") + if event["prevHash"] != expected_prev: + reasons.append(f"broken link at {seq}") + try: + recomputed = event_hash(event) + except (rfc8785.CanonicalizationError, TypeError, ValueError) as exc: + reasons.append(f"event {seq} has no RFC 8785 form ({exc})") + else: + if recomputed != event["eventHash"]: + reasons.append(f"content altered at {seq}") + head_at[seq + 1] = event["eventHash"] + expected_seq, expected_prev = seq + 1, event["eventHash"] + if reasons: + return BundleCheck(False, log_id, len(events), reasons=reasons) + + # 3. Checkpoints. Every one must verify; none is skipped because another passed. + window_start = start["treeSize"] if start is not None else first_size + last_size = events[-1]["seq"] + 1 + origin = f"{CHECKPOINT_ORIGIN_PREFIX}/{log_id}" + keys = {entry["keyId"]: entry["pem"] for entry in bundle["publicKeys"]} + anchor: dict[str, Any] | None = None + start_pinned = window_start == 0 # the genesis hash needs no signature + for i, signed in enumerate(bundle["checkpoints"]): + cp = signed["checkpoint"] + size, key_id = cp["treeSize"], signed["keyId"] + label = f"checkpoint {i} (tree size {size})" + pem = keys.get(key_id) + if pem is None: + reasons.append(f"{label}: signed by {key_id!r}, which the bundle does not list") + continue + try: + listed = _spki(pem) + except (ValueError, UnsupportedAlgorithm) as exc: + reasons.append(f"{label}: key {key_id!r} is unreadable ({exc})") + continue + if pinned_keys is not None: + pinned = pinned_keys.get(key_id) + try: + pinned_ok = pinned is not None and _spki(pinned) == listed + except (ValueError, UnsupportedAlgorithm) as exc: + reasons.append(f"{label}: pinned key {key_id!r} is unreadable ({exc})") + continue + if not pinned_ok: + reasons.append(f"{label}: key {key_id!r} is not a pinned key") + continue + if cp["origin"] != origin: + reasons.append(f"{label}: origin {cp['origin']!r} is not this log's {origin!r}") + continue + if checkpoint_body(cp) != signed["body"]: + reasons.append(f"{label}: fields do not match the signed body") + continue + try: + signature = _b64decode_canonical(signed["signature"]) + _public_key(pem).verify(signature, signed["body"].encode(), ec.ECDSA(hashes.SHA256())) + except InvalidSignature: + reasons.append(f"{label}: signature does not verify") + continue + except ValueError as exc: + reasons.append(f"{label}: signature is unreadable ({exc})") + continue + if window_start <= size <= last_size: + if head_at.get(size) != cp["headHash"]: + reasons.append( + f"{label}: contradicts the chain; it signs head {cp['headHash']} " + f"where the events give {head_at.get(size)}" + ) + continue + if size == window_start: + start_pinned = True + if size == last_size: + anchor = {"body": signed["body"], "head": cp["headHash"]} + # Outside the window: verified above, but the bundle cannot recompute its head. + + # 4. Anchoring, at both ends. A start nothing signs could be any head, so an + # export with its first events deleted would otherwise pass as a shorter one. + if not start_pinned: + reasons.append( + f"the bundle starts at tree size {window_start} and no verified checkpoint " + "signs the head it starts from" + ) + if anchor is None: + reasons.append( + f"no verified checkpoint covers the last event (the bundle ends at tree size {last_size})" + ) + if reasons: + return BundleCheck(False, log_id, len(events), reasons=reasons) + return BundleCheck( + True, + log_id, + len(events), + anchored_through_size=last_size, + anchoring_body=anchor["body"], + anchoring_head=anchor["head"], + anchored_event_id=events[-1]["eventId"], + ) + + +def check_bundle(bundle: Any, *, pinned_keys: dict[str, str] | None = None) -> BundleCheck: + """Re-verify a parsed bundle offline. Never raises on bad content: it reports it. + + Every structural problem the checks know about is reported with its own reason. + The broad ``except`` below is a last line, so that an input nobody anticipated + still fails closed instead of escaping as an exception. + """ + try: + return _check(bundle, pinned_keys) + except Exception as exc: # noqa: BLE001 - fail closed on anything unanticipated + return BundleCheck(False, "", 0, reasons=[f"bundle could not be checked ({type(exc).__name__}: {exc})"]) + + +def _no_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + out: dict[str, Any] = {} + for key, value in pairs: + if key in out: + raise ValueError(f"duplicate JSON key {key!r}") + out[key] = value + return out + + +def parse_bundle(bundle_bytes: bytes) -> Any: + """Parse bundle bytes, refusing a JSON object that repeats a key.""" + if not isinstance(bundle_bytes, (bytes, bytearray)): + raise BundleNotVerified(["the bundle must be given as bytes"]) + try: + return json.loads(bundle_bytes, object_pairs_hook=_no_duplicate_keys) + except (UnicodeDecodeError, ValueError) as exc: + raise BundleNotVerified([f"the bundle is not valid JSON ({exc})"]) from None + except RecursionError: + raise BundleNotVerified(["the bundle nests too deeply to parse"]) from None + + +def models_in_bundle(bundle: dict[str, Any]) -> list[tuple[str, str]]: + """Distinct (provider, model) pairs the bundle's ``model_call`` events name. + + Read from ``cost.provider`` and ``cost.model``. A ``model_call`` event that does + not name both raises: the record would otherwise name a model the evidence never + identified. + """ + seen: set[tuple[str, str]] = set() + for event in bundle["events"]: + if event.get("actionType") != "model_call": + continue + cost = event.get("cost") + provider = cost.get("provider") if isinstance(cost, dict) else None + model = cost.get("model") if isinstance(cost, dict) else None + if not (isinstance(provider, str) and provider and isinstance(model, str) and model): + raise MissingEvidence( + f"the model_call event at seq {event.get('seq')} does not name its provider " + "and model (cost.provider, cost.model), so the bundle cannot support a record " + "that names its model" + ) + seen.add((provider, model)) + return sorted(seen) + + +def select_model( + bundle: dict[str, Any], provider: str | None = None, model_id: str | None = None +) -> tuple[str, str]: + """The one (provider, model) the record names, checked against the bundle. + + With neither given, the bundle must name exactly one. A given value narrows the + bundle's pairs and must leave exactly one: an explicit choice is never accepted + without a ``model_call`` event behind it, and a value given for one half is + never replaced by the other half's inference. + """ + models = models_in_bundle(bundle) + if not models: + raise MissingEvidence("the bundle has no model_call event, so it names no model") + matches = [ + (p, m) + for p, m in models + if (provider is None or p == provider) and (model_id is None or m == model_id) + ] + if len(matches) == 1: + return matches[0] + if not matches: + asked = f"{provider or '*'} / {model_id or '*'}" + raise ValueError(f"{asked} is not a model the bundle's model_call events name; they name {models}") + raise ValueError( + f"the bundle names {len(matches)} models {matches}; pass --model-provider and " + "--model-id to choose one" + ) + + +def tool_transcript_bytes(bundle: dict[str, Any]) -> bytes: + """The tool-call transcript: RFC 8785 form of the ``tool_call`` events, in order. + + Each event exactly as exported, ``eventHash`` included, so anyone holding the + bundle can recompute ``tool_transcript.hash`` and it is bound to the chain. + """ + return rfc8785.dumps([e for e in bundle["events"] if e.get("actionType") == "tool_call"]) + + +def build_trust_record( + bundle_bytes: bytes, + *, + subject: str, + policy_bundle: bytes, + enforcement_mode: str, + workload_digest: str, + data_class: str, + jwk: dict[str, Any], + model_provider: str | None = None, + model_id: str | None = None, + producer: str = DEFAULT_PRODUCER, + pinned_keys: dict[str, str] | None = None, + iat: int | None = None, +) -> dict[str, Any]: + """Return an unsigned Level 0 Trust Record for a bundle that verifies. + + ``subject`` (SPIFFE URI or DID), ``policy_bundle`` (the bytes of the policy in + force) and ``workload_digest`` (the agent's artifact digest) come from the + operator because the bundle does not carry them. ``enforcement_mode`` has no + default: pass what the deployment did for the whole window (``enforce`` when + tool calls were held by policy before they ran, ``advisory`` when decisions were + recorded only, ``declared`` when no policy was evaluated, which a bundle holding + ``policy_decision`` events contradicts and is refused). + """ + bundle = parse_bundle(bundle_bytes) + check = check_bundle(bundle, pinned_keys=pinned_keys) + if not check.ok: + raise BundleNotVerified(check.reasons) + if bundle["events"][0]["seq"] != 0: + # TRACE has no field that says a record covers part of a log, so a record from + # an excerpt would read as the whole of it: its transcript, model and policy + # facts would silently omit everything before the excerpt. + raise BundleNotVerified( + [ + f"the bundle starts at seq {bundle['events'][0]['seq']}, not 0; a record is " + "built only from a whole log, because nothing in it could say it covers part" + ] + ) + decisions = sum(1 for e in bundle["events"] if e.get("actionType") == "policy_decision") + if enforcement_mode == "declared" and decisions: + # TRACE v0.2: "A producer that evaluates policy MUST NOT use [declared]". + raise ValueError( + f"the bundle records {decisions} policy decision(s), so a policy was evaluated; " + "'declared' says nothing evaluated it. Pass advisory or enforce." + ) + provider, model = select_model(bundle, model_provider, model_id) + tool_calls = sum(1 for e in bundle["events"] if e.get("actionType") == "tool_call") + return build_record( + source=SourceSystem( + producer=producer, + kind="log-import", + # The event the anchoring checkpoint covers, by Auditant's own event id. + source_event_id=check.anchored_event_id, + ), + subject=subject, + model_provider=provider, + model_id=model, + policy=PolicyEvidence(bundle=policy_bundle, enforcement_mode=enforcement_mode), + data_class=data_class, + jwk=jwk, + transcript_bytes=tool_transcript_bytes(bundle) if tool_calls else None, + tool_call_count=tool_calls if tool_calls else None, + workload_digest=workload_digest, + iat=iat, + ) + + +def _pins(items: list[str]) -> dict[str, str] | None: + if not items: + return None + pins: dict[str, str] = {} + for item in items: + key_id, _, path = item.partition("=") + if not key_id or not path: + raise ValueError(f"--pin-key takes KEYID=PEMFILE, got {item!r}") + pins[key_id] = Path(path).read_text() + return pins + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("bundle", type=Path, help="Auditant evidence bundle (JSON)") + ap.add_argument("--out", type=Path, required=True, help="where to write the signed record") + ap.add_argument("--subject", required=True, help="spiffe:// or did: identity of the agent workload") + ap.add_argument("--policy-bundle", type=Path, required=True, help="file holding the policy bytes in force") + ap.add_argument("--enforcement-mode", required=True, choices=ENFORCEMENT_MODES) + ap.add_argument("--workload-digest", required=True, help="sha256:/sha384: digest of the agent's artifact") + ap.add_argument("--data-class", required=True) + ap.add_argument("--model-provider") + ap.add_argument("--model-id") + ap.add_argument("--producer", default=DEFAULT_PRODUCER, help="URI of the system that produced the bundle (a self-hosted Auditant: its own URL)") + ap.add_argument("--pin-key", action="append", default=[], metavar="KEYID=PEMFILE") + ap.add_argument( + "--signing-key", + type=Path, + help="Ed25519 private key PEM; otherwise TRACE_PRIVATE_KEY_PEM, else an ephemeral key", + ) + args = ap.parse_args(argv) + + try: + key = load_key(args.signing_key.read_text()) if args.signing_key else load_signing_key() + bundle_bytes = args.bundle.read_bytes() + policy_bytes = args.policy_bundle.read_bytes() + pins = _pins(args.pin_key) + except (OSError, ValueError) as exc: + print(f"cannot read the inputs, no record written: {exc}", file=sys.stderr) + return 2 + try: + record = build_trust_record( + bundle_bytes, + subject=args.subject, + policy_bundle=policy_bytes, + enforcement_mode=args.enforcement_mode, + workload_digest=args.workload_digest, + data_class=args.data_class, + jwk=key_to_jwk(key), + model_provider=args.model_provider, + model_id=args.model_id, + producer=args.producer, + pinned_keys=pins, + ) + except BundleNotVerified as exc: + print("bundle did not verify, no record written:", file=sys.stderr) + for reason in exc.reasons: + print(" " + reason, file=sys.stderr) + return 2 + except ValueError as exc: # MissingEvidence included + print(f"cannot build a truthful record, none written: {exc}", file=sys.stderr) + return 2 + signed = sign_record(record, key) + TrustRecord.model_validate(signed) + args.out.write_text(json.dumps(signed, indent=2) + "\n") + print(args.out) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/auditant-evidence-bundle/examples/demo-policy.cedar b/integrations/auditant-evidence-bundle/examples/demo-policy.cedar new file mode 100644 index 00000000..005d1d99 --- /dev/null +++ b/integrations/auditant-evidence-bundle/examples/demo-policy.cedar @@ -0,0 +1,4 @@ +// Demo policy for the example record, matching the fixture's "refund-limit" decision: +// a refund is allowed up to 100. An operator passes the policy file their deployment runs. +permit(principal, action == Action::"issue_refund", resource) +when { context.amount <= 100 }; diff --git a/integrations/auditant-evidence-bundle/examples/demo-workload.txt b/integrations/auditant-evidence-bundle/examples/demo-workload.txt new file mode 100644 index 00000000..be0373ab --- /dev/null +++ b/integrations/auditant-evidence-bundle/examples/demo-workload.txt @@ -0,0 +1,2 @@ +Demo workload artifact. It stands in for the refund agent's image or build artifact, whose +digest an operator passes as --workload-digest. Auditant does not record that digest. diff --git a/integrations/auditant-evidence-bundle/examples/emit_record.py b/integrations/auditant-evidence-bundle/examples/emit_record.py new file mode 100644 index 00000000..bc02fd22 --- /dev/null +++ b/integrations/auditant-evidence-bundle/examples/emit_record.py @@ -0,0 +1,48 @@ +"""Emit a Level 0 TRACE record from the committed fixture (CI / reviewer). + +The bundle is ``fixtures/auditant-full.json``, exported by Auditant's own TypeScript +core, not by this adapter. The operator inputs are demo stand-ins: a SPIFFE ID under +example.org, the policy file ``examples/demo-policy.cedar``, and the digest of +``examples/demo-workload.txt`` in place of an agent image. + + python emit_record.py --out trust-record.json +""" + +from __future__ import annotations + +import argparse +import hashlib +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +sys.path.insert(0, str(ROOT)) + +import auditant_trace # noqa: E402 + +FIXTURE = ROOT / "fixtures" / "auditant-full.json" +SUBJECT = "spiffe://example.org/agent/refund-agent" + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--out", type=Path, default=Path("trust-record.json")) + args = ap.parse_args() + workload = "sha256:" + hashlib.sha256((HERE / "demo-workload.txt").read_bytes()).hexdigest() + # advisory: the fixture records a policy decision, and nothing establishes that it held a call. + return auditant_trace.main( + [ + str(FIXTURE), + "--out", str(args.out), + "--subject", SUBJECT, + "--policy-bundle", str(HERE / "demo-policy.cedar"), + "--enforcement-mode", "advisory", + "--workload-digest", workload, + "--data-class", "internal", + ] + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/auditant-evidence-bundle/fixtures/README.md b/integrations/auditant-evidence-bundle/fixtures/README.md new file mode 100644 index 00000000..3c47add2 --- /dev/null +++ b/integrations/auditant-evidence-bundle/fixtures/README.md @@ -0,0 +1,11 @@ +# Fixtures + +Made by Auditant's own TypeScript core (`@auditant/core`: `appendEvent`, `checkpointFromHead`, `signCheckpoint`, bundle format 1.0.0), not by `auditant_trace.py`, so the tests check this adapter against an independent producer. Each file passed Auditant's own `verifyBundle` with its key trusted before it was written here. + +The events are synthetic and the P-256 signing key was generated for these files and discarded: they prove nothing about any real deployment. + +| File | What it is | +|---|---| +| `auditant-full.json` | A whole log: 8 events from `seq` 0, checkpoints at tree size 4 and 8 | +| `auditant-ranged.json` | The same log exported from the middle: events 4 to 7, `startHead` at tree size 4, the same two checkpoints | +| `auditant-two-models.json` | 8 events whose two `model_call` events name different models, one checkpoint at 8 | diff --git a/integrations/auditant-evidence-bundle/fixtures/auditant-full.json b/integrations/auditant-evidence-bundle/fixtures/auditant-full.json new file mode 100644 index 00000000..c990d743 --- /dev/null +++ b/integrations/auditant-evidence-bundle/fixtures/auditant-full.json @@ -0,0 +1,259 @@ +{ + "bundleVersion": "1.0.0", + "logId": "demo_org/prod", + "from": "2026-11-27T00:00:00.000Z", + "to": "2026-11-27T23:59:59.999Z", + "exportedAt": "2026-11-27T10:05:00.000Z", + "publicKeys": [ + { + "keyId": "auditant-fbd28f98423e", + "pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE82vl8qkypFk1t7PcswTy3PDikZgM\n8RRp1hFv0vy8ScFax+0lExksfh4tx1TmIavOZG/XznjmU6CXI7WqIk5ZbA==\n-----END PUBLIC KEY-----\n" + } + ], + "events": [ + { + "schemaVersion": "1.0.0", + "eventId": "evt_000001", + "ts": "2026-11-27T10:00:01.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "lifecycle", + "action": "session_start", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "seq": 0, + "prevHash": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "eventHash": "sha256:61a2e4780e81043d3b4b2bd9e8cf1a266c1756242c3788da5f19d240b2250646" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000002", + "ts": "2026-11-27T10:00:02.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "model_call", + "action": "demo-model", + "surface": { + "plane": "model", + "adapter": "gateway", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:cf07194ee232eb531e15f690000d19846dea69cf05504782658afcfacb9228a2", + "outputHash": "sha256:21606b5837ee49171e56cff2afe21083fb4dfe5c15c79b54695c2dc335181c89", + "cost": { + "currency": "USD", + "total": 0.0042, + "model": "demo-model", + "provider": "demo-provider" + }, + "seq": 1, + "prevHash": "sha256:61a2e4780e81043d3b4b2bd9e8cf1a266c1756242c3788da5f19d240b2250646", + "eventHash": "sha256:99dd638341abe5439d882b1719e93a82a51ddab80f28179a40389ce281944e5f" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000003", + "ts": "2026-11-27T10:00:03.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "tool_call", + "action": "lookup_order", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:ece993e999d79e7f2345161a5a98ff209e1eea031bcfc566602a9546443aeee1", + "seq": 2, + "prevHash": "sha256:99dd638341abe5439d882b1719e93a82a51ddab80f28179a40389ce281944e5f", + "eventHash": "sha256:af8b114633bf70c1943c2faea5433763050acca03583a839fb5ea919939356f7" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000004", + "ts": "2026-11-27T10:00:04.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "policy_decision", + "action": "issue_refund", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "policy": { + "decision": "allow", + "policyId": "refund-limit", + "policyVersion": "1", + "engine": "auditant-cedar/1", + "reasons": [ + "amount 40 is under the limit 100" + ] + }, + "seq": 3, + "prevHash": "sha256:af8b114633bf70c1943c2faea5433763050acca03583a839fb5ea919939356f7", + "eventHash": "sha256:ad9cccd9b1980fe99dc6f2fdfedf4db33521864fef7699745e399b56a4a121f3" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000005", + "ts": "2026-11-27T10:00:05.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "tool_call", + "action": "issue_refund", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:12e3e612f21a311079bbb13dd00eee0268a9c12379c3025b96e3755a2b2bc484", + "seq": 4, + "prevHash": "sha256:ad9cccd9b1980fe99dc6f2fdfedf4db33521864fef7699745e399b56a4a121f3", + "eventHash": "sha256:e72be112ef933b698f23aadd9b1bb6e4f71b29252d81fa4b6a75039aa56a47b8" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000006", + "ts": "2026-11-27T10:00:06.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "model_call", + "action": "demo-model", + "surface": { + "plane": "model", + "adapter": "gateway", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:259a648c7737779497c41b77a45b5f7449eaa5d7f36a96cb92e5341678c54f4c", + "outputHash": "sha256:86a7e131e4b36059db897ed1422cb404787508b538229d1d8fb220d5ec71fbfc", + "cost": { + "currency": "USD", + "total": 0.0031, + "model": "demo-model", + "provider": "demo-provider" + }, + "seq": 5, + "prevHash": "sha256:e72be112ef933b698f23aadd9b1bb6e4f71b29252d81fa4b6a75039aa56a47b8", + "eventHash": "sha256:7388cddcf3cf4dceb4eac3fa48dc364063991e01f66396706e7968eb03042f9f" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000007", + "ts": "2026-11-27T10:00:07.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "tool_call", + "action": "send_receipt", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:03fd3de7634a49868d83fff628b0ade7fe99f344d5ce74d94471f281c6ffe6d9", + "seq": 6, + "prevHash": "sha256:7388cddcf3cf4dceb4eac3fa48dc364063991e01f66396706e7968eb03042f9f", + "eventHash": "sha256:486374eeeefa611181bc622511ff5b1d2772ef6237999f58ec9e2b8277ea7f44" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000008", + "ts": "2026-11-27T10:00:08.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "lifecycle", + "action": "session_end", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "seq": 7, + "prevHash": "sha256:486374eeeefa611181bc622511ff5b1d2772ef6237999f58ec9e2b8277ea7f44", + "eventHash": "sha256:e5fd47a8611893e36485c60596575b50b66923c31fecc0f8e714124c68e15c30" + } + ], + "checkpoints": [ + { + "checkpoint": { + "origin": "auditant.dev/demo_org/prod", + "treeSize": 4, + "headHash": "sha256:ad9cccd9b1980fe99dc6f2fdfedf4db33521864fef7699745e399b56a4a121f3", + "timestamp": "2026-11-27T10:05:00.000Z" + }, + "body": "auditant.dev/demo_org/prod\n4\nrZzM2bGYD+mdxvL9/t9NszUhhk/vdpl0XjmbVqShIfM=\n", + "keyId": "auditant-fbd28f98423e", + "signature": "MEUCIQDXdwinWyOGpinCwlf4YdL2LnKMHiS3HqybNbWlSODEVQIgVp8+9xd6ySAt49i0SL4KMrIgYFy6Z8VsuDIMpeRs2Xs=" + }, + { + "checkpoint": { + "origin": "auditant.dev/demo_org/prod", + "treeSize": 8, + "headHash": "sha256:e5fd47a8611893e36485c60596575b50b66923c31fecc0f8e714124c68e15c30", + "timestamp": "2026-11-27T10:05:00.000Z" + }, + "body": "auditant.dev/demo_org/prod\n8\n5f1HqGEYk+NkhcYFlldbULZpI8Mf7MD45xQSTGjhXDA=\n", + "keyId": "auditant-fbd28f98423e", + "signature": "MEYCIQCxhqd1zWMyJgwPu51PacXgbYRuTGUFD0Mqqa+gM5LWhAIhAMzMFhVfRopMu4iPvaz3b9nZXXlc0OSOUWYuJvHXuiw0" + } + ] +} diff --git a/integrations/auditant-evidence-bundle/fixtures/auditant-ranged.json b/integrations/auditant-evidence-bundle/fixtures/auditant-ranged.json new file mode 100644 index 00000000..031f2799 --- /dev/null +++ b/integrations/auditant-evidence-bundle/fixtures/auditant-ranged.json @@ -0,0 +1,150 @@ +{ + "bundleVersion": "1.0.0", + "logId": "demo_org/prod", + "from": "2026-11-27T00:00:00.000Z", + "to": "2026-11-27T23:59:59.999Z", + "exportedAt": "2026-11-27T10:05:00.000Z", + "publicKeys": [ + { + "keyId": "auditant-fbd28f98423e", + "pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE82vl8qkypFk1t7PcswTy3PDikZgM\n8RRp1hFv0vy8ScFax+0lExksfh4tx1TmIavOZG/XznjmU6CXI7WqIk5ZbA==\n-----END PUBLIC KEY-----\n" + } + ], + "events": [ + { + "schemaVersion": "1.0.0", + "eventId": "evt_000005", + "ts": "2026-11-27T10:00:05.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "tool_call", + "action": "issue_refund", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:12e3e612f21a311079bbb13dd00eee0268a9c12379c3025b96e3755a2b2bc484", + "seq": 4, + "prevHash": "sha256:ad9cccd9b1980fe99dc6f2fdfedf4db33521864fef7699745e399b56a4a121f3", + "eventHash": "sha256:e72be112ef933b698f23aadd9b1bb6e4f71b29252d81fa4b6a75039aa56a47b8" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000006", + "ts": "2026-11-27T10:00:06.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "model_call", + "action": "demo-model", + "surface": { + "plane": "model", + "adapter": "gateway", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:259a648c7737779497c41b77a45b5f7449eaa5d7f36a96cb92e5341678c54f4c", + "outputHash": "sha256:86a7e131e4b36059db897ed1422cb404787508b538229d1d8fb220d5ec71fbfc", + "cost": { + "currency": "USD", + "total": 0.0031, + "model": "demo-model", + "provider": "demo-provider" + }, + "seq": 5, + "prevHash": "sha256:e72be112ef933b698f23aadd9b1bb6e4f71b29252d81fa4b6a75039aa56a47b8", + "eventHash": "sha256:7388cddcf3cf4dceb4eac3fa48dc364063991e01f66396706e7968eb03042f9f" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000007", + "ts": "2026-11-27T10:00:07.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "tool_call", + "action": "send_receipt", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:03fd3de7634a49868d83fff628b0ade7fe99f344d5ce74d94471f281c6ffe6d9", + "seq": 6, + "prevHash": "sha256:7388cddcf3cf4dceb4eac3fa48dc364063991e01f66396706e7968eb03042f9f", + "eventHash": "sha256:486374eeeefa611181bc622511ff5b1d2772ef6237999f58ec9e2b8277ea7f44" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000008", + "ts": "2026-11-27T10:00:08.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "lifecycle", + "action": "session_end", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "seq": 7, + "prevHash": "sha256:486374eeeefa611181bc622511ff5b1d2772ef6237999f58ec9e2b8277ea7f44", + "eventHash": "sha256:e5fd47a8611893e36485c60596575b50b66923c31fecc0f8e714124c68e15c30" + } + ], + "checkpoints": [ + { + "checkpoint": { + "origin": "auditant.dev/demo_org/prod", + "treeSize": 4, + "headHash": "sha256:ad9cccd9b1980fe99dc6f2fdfedf4db33521864fef7699745e399b56a4a121f3", + "timestamp": "2026-11-27T10:05:00.000Z" + }, + "body": "auditant.dev/demo_org/prod\n4\nrZzM2bGYD+mdxvL9/t9NszUhhk/vdpl0XjmbVqShIfM=\n", + "keyId": "auditant-fbd28f98423e", + "signature": "MEUCIQDXdwinWyOGpinCwlf4YdL2LnKMHiS3HqybNbWlSODEVQIgVp8+9xd6ySAt49i0SL4KMrIgYFy6Z8VsuDIMpeRs2Xs=" + }, + { + "checkpoint": { + "origin": "auditant.dev/demo_org/prod", + "treeSize": 8, + "headHash": "sha256:e5fd47a8611893e36485c60596575b50b66923c31fecc0f8e714124c68e15c30", + "timestamp": "2026-11-27T10:05:00.000Z" + }, + "body": "auditant.dev/demo_org/prod\n8\n5f1HqGEYk+NkhcYFlldbULZpI8Mf7MD45xQSTGjhXDA=\n", + "keyId": "auditant-fbd28f98423e", + "signature": "MEYCIQCxhqd1zWMyJgwPu51PacXgbYRuTGUFD0Mqqa+gM5LWhAIhAMzMFhVfRopMu4iPvaz3b9nZXXlc0OSOUWYuJvHXuiw0" + } + ], + "startHead": { + "logId": "demo_org/prod", + "treeSize": 4, + "headHash": "sha256:ad9cccd9b1980fe99dc6f2fdfedf4db33521864fef7699745e399b56a4a121f3" + } +} diff --git a/integrations/auditant-evidence-bundle/fixtures/auditant-two-models.json b/integrations/auditant-evidence-bundle/fixtures/auditant-two-models.json new file mode 100644 index 00000000..73da5d77 --- /dev/null +++ b/integrations/auditant-evidence-bundle/fixtures/auditant-two-models.json @@ -0,0 +1,248 @@ +{ + "bundleVersion": "1.0.0", + "logId": "demo_org/prod", + "from": "2026-11-27T00:00:00.000Z", + "to": "2026-11-27T23:59:59.999Z", + "exportedAt": "2026-11-27T10:05:00.000Z", + "publicKeys": [ + { + "keyId": "auditant-fbd28f98423e", + "pem": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE82vl8qkypFk1t7PcswTy3PDikZgM\n8RRp1hFv0vy8ScFax+0lExksfh4tx1TmIavOZG/XznjmU6CXI7WqIk5ZbA==\n-----END PUBLIC KEY-----\n" + } + ], + "events": [ + { + "schemaVersion": "1.0.0", + "eventId": "evt_000001", + "ts": "2026-11-27T10:00:01.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "lifecycle", + "action": "session_start", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "seq": 0, + "prevHash": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "eventHash": "sha256:61a2e4780e81043d3b4b2bd9e8cf1a266c1756242c3788da5f19d240b2250646" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000002", + "ts": "2026-11-27T10:00:02.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "model_call", + "action": "demo-model", + "surface": { + "plane": "model", + "adapter": "gateway", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:cf07194ee232eb531e15f690000d19846dea69cf05504782658afcfacb9228a2", + "outputHash": "sha256:21606b5837ee49171e56cff2afe21083fb4dfe5c15c79b54695c2dc335181c89", + "cost": { + "currency": "USD", + "total": 0.0042, + "model": "demo-model", + "provider": "demo-provider" + }, + "seq": 1, + "prevHash": "sha256:61a2e4780e81043d3b4b2bd9e8cf1a266c1756242c3788da5f19d240b2250646", + "eventHash": "sha256:99dd638341abe5439d882b1719e93a82a51ddab80f28179a40389ce281944e5f" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000003", + "ts": "2026-11-27T10:00:03.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "tool_call", + "action": "lookup_order", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:ece993e999d79e7f2345161a5a98ff209e1eea031bcfc566602a9546443aeee1", + "seq": 2, + "prevHash": "sha256:99dd638341abe5439d882b1719e93a82a51ddab80f28179a40389ce281944e5f", + "eventHash": "sha256:af8b114633bf70c1943c2faea5433763050acca03583a839fb5ea919939356f7" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000004", + "ts": "2026-11-27T10:00:04.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "policy_decision", + "action": "issue_refund", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "policy": { + "decision": "allow", + "policyId": "refund-limit", + "policyVersion": "1", + "engine": "auditant-cedar/1", + "reasons": [ + "amount 40 is under the limit 100" + ] + }, + "seq": 3, + "prevHash": "sha256:af8b114633bf70c1943c2faea5433763050acca03583a839fb5ea919939356f7", + "eventHash": "sha256:ad9cccd9b1980fe99dc6f2fdfedf4db33521864fef7699745e399b56a4a121f3" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000005", + "ts": "2026-11-27T10:00:05.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "tool_call", + "action": "issue_refund", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:12e3e612f21a311079bbb13dd00eee0268a9c12379c3025b96e3755a2b2bc484", + "seq": 4, + "prevHash": "sha256:ad9cccd9b1980fe99dc6f2fdfedf4db33521864fef7699745e399b56a4a121f3", + "eventHash": "sha256:e72be112ef933b698f23aadd9b1bb6e4f71b29252d81fa4b6a75039aa56a47b8" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000006", + "ts": "2026-11-27T10:00:06.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "model_call", + "action": "other-model", + "surface": { + "plane": "model", + "adapter": "gateway", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:259a648c7737779497c41b77a45b5f7449eaa5d7f36a96cb92e5341678c54f4c", + "outputHash": "sha256:86a7e131e4b36059db897ed1422cb404787508b538229d1d8fb220d5ec71fbfc", + "cost": { + "currency": "USD", + "total": 0.0031, + "model": "other-model", + "provider": "demo-provider" + }, + "seq": 5, + "prevHash": "sha256:e72be112ef933b698f23aadd9b1bb6e4f71b29252d81fa4b6a75039aa56a47b8", + "eventHash": "sha256:a2ae4c1c9955801777a98e6501ab862439ee76a6cfb69dab0007e91da2c14291" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000007", + "ts": "2026-11-27T10:00:07.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "tool_call", + "action": "send_receipt", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "inputHash": "sha256:03fd3de7634a49868d83fff628b0ade7fe99f344d5ce74d94471f281c6ffe6d9", + "seq": 6, + "prevHash": "sha256:a2ae4c1c9955801777a98e6501ab862439ee76a6cfb69dab0007e91da2c14291", + "eventHash": "sha256:16a1a13fd6d9ca583eb60fd7964f8a069a57b3c15131d68237cbf923774e8a6a" + }, + { + "schemaVersion": "1.0.0", + "eventId": "evt_000008", + "ts": "2026-11-27T10:00:08.000Z", + "logId": "demo_org/prod", + "actor": { + "kind": "agent", + "id": "refund-agent", + "version": "0.3.1", + "mode": "autonomous" + }, + "sessionId": "sess_fixture", + "actionType": "lifecycle", + "action": "session_end", + "surface": { + "plane": "action", + "adapter": "sdk", + "modality": "text" + }, + "outcome": "ok", + "seq": 7, + "prevHash": "sha256:16a1a13fd6d9ca583eb60fd7964f8a069a57b3c15131d68237cbf923774e8a6a", + "eventHash": "sha256:411938a52b86dd8fec5f0b16d0c7f5730f53cd80437c26e4480622370e93dbe9" + } + ], + "checkpoints": [ + { + "checkpoint": { + "origin": "auditant.dev/demo_org/prod", + "treeSize": 8, + "headHash": "sha256:411938a52b86dd8fec5f0b16d0c7f5730f53cd80437c26e4480622370e93dbe9", + "timestamp": "2026-11-27T10:05:00.000Z" + }, + "body": "auditant.dev/demo_org/prod\n8\nQRk4pSuG3Y/sXwsW0Mf1cw9TzYBDfCbkSAYiNw6T2+k=\n", + "keyId": "auditant-fbd28f98423e", + "signature": "MEUCIQD4NDGb9yscchDgd+TePYVM0HfB+reaHMtmo44khdK0rQIgacyvYFZrfogVCMCwg7x8anOnST2x0KD4xgWPbOIXceY=" + } + ] +} diff --git a/integrations/auditant-evidence-bundle/integration.yaml b/integrations/auditant-evidence-bundle/integration.yaml new file mode 100644 index 00000000..53b80737 --- /dev/null +++ b/integrations/auditant-evidence-bundle/integration.yaml @@ -0,0 +1,28 @@ +name: Auditant evidence bundle +vendor: Auditant +integrates_with: + - trace +description: >- + Re-verifies an Auditant evidence bundle's hash chain and every signed checkpoint offline, then emits a software-only TRACE log-import Trust Record. +maintainer: + github: 4ugusta +repository: https://github.com/agentrust-io/integrations +homepage: https://auditant.co +license: Apache-2.0 +tier: community +marketplace: + display_name: Auditant + category: Evidence & receipts + mark: AU + keywords: + - audit-trail + - hash-chain + - checkpoint + - log-import + - evidence +trace_roles: + - record-producer +trace_conformance_level: 0 +tested_against: + agentrust-trace: "0.11.0" + agentrust-trace-tests: "0.6.2" diff --git a/integrations/auditant-evidence-bundle/pyproject.toml b/integrations/auditant-evidence-bundle/pyproject.toml new file mode 100644 index 00000000..4bbe056a --- /dev/null +++ b/integrations/auditant-evidence-bundle/pyproject.toml @@ -0,0 +1,29 @@ +[build-system] +requires = ["setuptools>=77", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "auditant-agentrust-integration" +version = "0.2.0" +requires-python = ">=3.11" +dependencies = [ + "agentrust-trace==0.11.0", + "agentrust-trace-adapters==0.2.0", + "cryptography>=42", + "rfc8785>=0.1.4", +] + +[project.optional-dependencies] +test = [ + "pytest==9.1.1", + "agentrust-trace-tests==0.6.2", +] + +[project.scripts] +auditant-trace = "auditant_trace:main" + +[tool.setuptools] +py-modules = ["auditant_trace"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/integrations/auditant-evidence-bundle/tests/test_auditant_trace.py b/integrations/auditant-evidence-bundle/tests/test_auditant_trace.py new file mode 100644 index 00000000..5cb68e08 --- /dev/null +++ b/integrations/auditant-evidence-bundle/tests/test_auditant_trace.py @@ -0,0 +1,431 @@ +from __future__ import annotations + +import base64 +import copy +import hashlib +import json +import sys +from pathlib import Path +from typing import Any + +import pytest +import rfc8785 +from agentrust_trace_adapters import MissingEvidence +from agentrust_trace_adapters.builder import software_measurement +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from agentrust_trace.models import TrustRecord +from agentrust_trace.sign import generate_key, key_to_jwk, sign_record, verify_record + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT)) + +import auditant_trace as at # noqa: E402 + +# Bundles made by Auditant's own TypeScript core, not by the code under test (fixtures/README.md). +FIXTURES = ROOT / "fixtures" +FULL = (FIXTURES / "auditant-full.json").read_bytes() +RANGED = (FIXTURES / "auditant-ranged.json").read_bytes() +TWO_MODELS = (FIXTURES / "auditant-two-models.json").read_bytes() + +SUBJECT = "spiffe://example.org/agent/refund-agent" +POLICY = b'permit(principal, action == Action::"issue_refund", resource) when { context.amount <= 100 };\n' +WORKLOAD = "sha256:" + hashlib.sha256(b"refund-agent image").hexdigest() +KEY = generate_key() + + +def _record(raw: bytes, **kw: Any) -> dict[str, Any]: + kw.setdefault("subject", SUBJECT) + kw.setdefault("policy_bundle", POLICY) + kw.setdefault("enforcement_mode", "advisory") + kw.setdefault("workload_digest", WORKLOAD) + kw.setdefault("data_class", "internal") + kw.setdefault("jwk", key_to_jwk(KEY)) + return at.build_trust_record(raw, **kw) + + +def _mutate(raw: bytes, fn) -> bytes: + bundle = json.loads(raw) + fn(bundle) + return json.dumps(bundle).encode() + + +def _refused(raw: bytes, needle: str, **kw: Any) -> list[str]: + with pytest.raises(at.BundleNotVerified) as exc: + _record(raw, **kw) + assert any(needle in r for r in exc.value.reasons), exc.value.reasons + return exc.value.reasons + + +def _test_key() -> tuple[ec.EllipticCurvePrivateKey, str]: + key = ec.generate_private_key(ec.SECP256R1()) + pem = key.public_key().public_bytes( + serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo + ).decode() + return key, pem + + +def _signed(cp: dict[str, Any], key: ec.EllipticCurvePrivateKey, key_id: str, body: str | None = None) -> dict: + body = at.checkpoint_body(cp) if body is None else body + sig = base64.b64encode(key.sign(body.encode(), ec.ECDSA(hashes.SHA256()))).decode() + return {"checkpoint": cp, "body": body, "keyId": key_id, "signature": sig} + + +# ── the fixtures verify ───────────────────────────────────────────────────── + + +@pytest.mark.parametrize("raw,events", [(FULL, 8), (RANGED, 4), (TWO_MODELS, 8)]) +def test_auditant_bundles_verify(raw: bytes, events: int) -> None: + check = at.check_bundle(json.loads(raw)) + assert check.ok, check.reasons + assert check.events == events + assert check.anchored_through_size == 8 + assert check.anchored_event_id == "evt_000008" + + +def test_record_is_a_valid_signed_level0_record() -> None: + signed = sign_record(_record(FULL), KEY) + TrustRecord.model_validate(signed) + verify_record(signed, KEY.public_key()) + assert signed["runtime"]["platform"] == "software-only" + assert signed["appraisal"]["status"] == "none" + assert signed["build_provenance"] == {"slsa_level": 0, "digest": WORKLOAD} + + +# ── TRACE field semantics ─────────────────────────────────────────────────── + + +def test_subject_comes_from_the_operator_not_the_log() -> None: + assert _record(FULL)["subject"] == SUBJECT + with pytest.raises(ValueError, match="SPIFFE URI or a DID"): + _record(FULL, subject="refund-agent") + + +def test_origin_names_auditant_and_the_anchored_event() -> None: + origin = _record(FULL)["origin"] + assert origin == {"kind": "log-import", "producer": "https://auditant.co", "source_event_id": "evt_000008"} + + +def test_policy_bundle_hash_is_the_policy_bytes() -> None: + policy = _record(FULL)["policy"] + assert policy["bundle_hash"] == "sha256:" + hashlib.sha256(POLICY).hexdigest() + with pytest.raises(MissingEvidence): + _record(FULL, policy_bundle=b"") + + +def test_transcript_hash_is_the_tool_call_events() -> None: + bundle = json.loads(FULL) + tool_calls = [e for e in bundle["events"] if e["actionType"] == "tool_call"] + transcript = _record(FULL)["tool_transcript"] + assert transcript["hash"] == "sha256:" + hashlib.sha256(rfc8785.dumps(tool_calls)).hexdigest() + assert transcript["hash"] != "sha256:" + hashlib.sha256(FULL).hexdigest() + assert transcript["call_count"] == 3 + + +def test_measurement_is_a_software_commitment_not_the_checkpoint() -> None: + record = _record(FULL) + assert record["runtime"]["measurement"] == software_measurement( + "https://auditant.co", SUBJECT, record["policy"]["bundle_hash"] + ) + body = at.check_bundle(json.loads(FULL)).anchoring_body + assert record["runtime"]["measurement"] != "sha256:" + hashlib.sha256(body.encode()).hexdigest() + + +def test_workload_digest_is_required() -> None: + with pytest.raises(MissingEvidence): + _record(FULL, workload_digest=None) + + +def test_enforcement_mode_has_no_default_and_declared_is_refused_after_decisions() -> None: + with pytest.raises(TypeError): + at.build_trust_record( # type: ignore[call-arg] + FULL, subject=SUBJECT, policy_bundle=POLICY, workload_digest=WORKLOAD, + data_class="internal", jwk=key_to_jwk(KEY), + ) + with pytest.raises(ValueError): + _record(FULL, enforcement_mode="strict") + with pytest.raises(ValueError, match="policy decision"): + _record(FULL, enforcement_mode="declared") + + +# ── model identity ────────────────────────────────────────────────────────── + + +def test_one_model_is_taken_from_the_bundle() -> None: + assert _record(FULL)["model"] == {"provider": "demo-provider", "model_id": "demo-model"} + + +def test_several_models_need_a_choice_from_the_bundle() -> None: + with pytest.raises(ValueError, match="names 2 models"): + _record(TWO_MODELS) + with pytest.raises(ValueError, match="names 2 models"): + _record(TWO_MODELS, model_provider="demo-provider") + chosen = _record(TWO_MODELS, model_provider="demo-provider", model_id="other-model") + assert chosen["model"] == {"provider": "demo-provider", "model_id": "other-model"} + assert _record(TWO_MODELS, model_id="other-model")["model"]["provider"] == "demo-provider" + + +@pytest.mark.parametrize( + "provider,model_id", + [ + ("demo-provider", "never-called"), + ("other-provider", "demo-model"), + ("other-provider", None), + (None, "never-called"), + ], +) +def test_explicit_model_must_appear_in_the_bundle(provider, model_id) -> None: + with pytest.raises(ValueError, match="is not a model the bundle"): + _record(FULL, model_provider=provider, model_id=model_id) + + +def test_a_model_call_without_a_named_model_is_missing_evidence() -> None: + bundle = json.loads(FULL) + next(e for e in bundle["events"] if e["actionType"] == "model_call").pop("cost") + with pytest.raises(MissingEvidence, match="does not name its provider"): + at.models_in_bundle(bundle) + + +# ── tampering ─────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize( + "fn,needle", + [ + (lambda b: b["events"][2].update(outcome="error"), "content altered at 2"), + (lambda b: b["events"].pop(3), "sequence gap"), + (lambda b: b["events"].reverse(), "sequence gap"), + (lambda b: b["events"].pop(), "no verified checkpoint covers the last event"), + (lambda b: b["events"][0].update(prevHash="sha256:" + "1" * 64), "broken link at 0"), + (lambda b: b.update(publicKeys=[]), "which the bundle does not list"), + (lambda b: b.update(bundleVersion="9.9.9"), "unsupported bundleVersion"), + (lambda b: b.update(checkpoints=[]), "no verified checkpoint covers the last event"), + ], +) +def test_tampered_bundle_yields_no_record(fn, needle: str) -> None: + _refused(_mutate(FULL, fn), needle) + + +def test_ranged_export_must_link_to_its_start_head() -> None: + _refused( + _mutate(RANGED, lambda b: b["startHead"].update(headHash="sha256:" + "2" * 64)), + "broken link at 4", + ) + + +@pytest.mark.parametrize("n", [1, 3]) +def test_deleting_the_first_events_is_caught(n: int) -> None: + raw = _mutate(FULL, lambda b: b["events"].__delitem__(slice(0, n))) + _refused(raw, "no verified checkpoint signs the head it starts from") + + +def test_an_excerpt_pinned_by_a_checkpoint_verifies_but_yields_no_record() -> None: + excerpt = _mutate(FULL, lambda b: b["events"].__delitem__(slice(0, 4))) + assert at.check_bundle(json.loads(excerpt)).ok + _refused(excerpt, "starts at seq 4, not 0") + assert at.check_bundle(json.loads(RANGED)).ok + _refused(RANGED, "starts at seq 4, not 0") + + +def test_a_ranged_export_needs_a_signed_start() -> None: + raw = _mutate(RANGED, lambda b: b["checkpoints"].pop(0)) + _refused(raw, "no verified checkpoint signs the head it starts from") + + +def test_a_start_head_at_zero_must_be_genesis() -> None: + raw = _mutate(FULL, lambda b: b.update(startHead={"treeSize": 0, "headHash": "sha256:" + "1" * 64})) + _refused(raw, "startHead at tree size 0 is not the genesis hash") + + +# ── checkpoints fail closed ───────────────────────────────────────────────── + + +def test_a_failed_checkpoint_fails_the_bundle_even_when_another_anchors_it() -> None: + def forge_first(b: dict) -> None: + sig = base64.b64decode(b["checkpoints"][0]["signature"]) + b["checkpoints"][0]["signature"] = base64.b64encode(sig[:-1] + bytes([sig[-1] ^ 1])).decode() + + reasons = _refused(_mutate(FULL, forge_first), "checkpoint 0 (tree size 4)") + assert not any("checkpoint 1" in r for r in reasons), reasons + + +def test_an_extra_checkpoint_under_an_unknown_key_fails_the_bundle() -> None: + def add(b: dict) -> None: + extra = copy.deepcopy(b["checkpoints"][1]) + extra["keyId"] = "auditant-unknown" + b["checkpoints"].append(extra) + + _refused(_mutate(FULL, add), "'auditant-unknown', which the bundle does not list") + + +def test_a_validly_signed_checkpoint_that_contradicts_the_chain_fails() -> None: + key, pem = _test_key() + + def add(b: dict) -> None: + cp = {"origin": "auditant.dev/demo_org/prod", "treeSize": 4, "headHash": "sha256:" + "3" * 64, + "timestamp": "2026-11-27T10:05:00.000Z"} + b["publicKeys"].append({"keyId": "second", "pem": pem}) + b["checkpoints"].append(_signed(cp, key, "second")) + + _refused(_mutate(FULL, add), "contradicts the chain") + + +def test_a_checkpoint_for_another_log_fails() -> None: + key, pem = _test_key() + + def add(b: dict) -> None: + cp = dict(b["checkpoints"][1]["checkpoint"], origin="auditant.dev/someone_else/prod") + b["publicKeys"].append({"keyId": "second", "pem": pem}) + b["checkpoints"].append(_signed(cp, key, "second")) + + _refused(_mutate(FULL, add), "is not this log's") + + +def test_pinned_keys_cover_every_checkpoint() -> None: + bundle = json.loads(FULL) + key_id, pem = bundle["publicKeys"][0]["keyId"], bundle["publicKeys"][0]["pem"] + assert _record(FULL, pinned_keys={key_id: pem}) + _, other = _test_key() + _refused(FULL, "is not a pinned key", pinned_keys={key_id: other}) + + key, second_pem = _test_key() + + def add(b: dict) -> None: + b["publicKeys"].append({"keyId": "second", "pem": second_pem}) + b["checkpoints"].append(_signed(dict(b["checkpoints"][1]["checkpoint"]), key, "second")) + + raw = _mutate(FULL, add) + assert at.check_bundle(json.loads(raw)).ok # unpinned, both checkpoints verify + _refused(raw, "'second' is not a pinned key", pinned_keys={key_id: pem}) + + +# ── strict encodings and input handling ───────────────────────────────────── + + +def _non_canonical(b64: str) -> str: + """Same bytes, different text: set the unused low bits of the last data character.""" + alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + pad = len(b64) - len(b64.rstrip("=")) + assert pad, "a no-padding string has no unused bits" + i = len(b64) - pad - 1 + return b64[:i] + alphabet[alphabet.index(b64[i]) | 1] + b64[i + 1 :] + + +@pytest.mark.parametrize( + "fn", + [ + lambda s: _non_canonical(s), + lambda s: s.rstrip("="), + lambda s: s[:10] + "\n" + s[10:], + lambda s: s.replace("+", "-").replace("/", "_") if ("+" in s or "/" in s) else "*" + s[1:], + ], + ids=["unused-bits", "no-padding", "newline", "urlsafe-alphabet"], +) +def test_signature_base64_must_be_canonical(fn) -> None: + bundle = json.loads(FULL) + # A DER signature is 70 to 72 bytes; take one whose base64 is padded, so it has unused bits. + i = next(n for n, cp in enumerate(bundle["checkpoints"]) if cp["signature"].endswith("=")) + sig = bundle["checkpoints"][i]["signature"] + altered = fn(sig) + assert altered != sig + bundle["checkpoints"][i]["signature"] = altered + _refused(json.dumps(bundle).encode(), f"checkpoint {i} (tree size {4 * (i + 1)}): signature is unreadable") + + +def test_a_signed_body_with_non_canonical_base64_fails() -> None: + key, pem = _test_key() + + def add(b: dict) -> None: + cp = b["checkpoints"][1]["checkpoint"] + lines = at.checkpoint_body(cp).split("\n") + lines[2] = _non_canonical(lines[2]) + b["publicKeys"].append({"keyId": "second", "pem": pem}) + b["checkpoints"].append(_signed(dict(cp), key, "second", body="\n".join(lines))) + + _refused(_mutate(FULL, add), "fields do not match the signed body") + + +@pytest.mark.parametrize( + "fn,needle", + [ + (lambda b: b["checkpoints"][1]["checkpoint"].update(treeSize=True), "treeSize is not a positive integer"), + (lambda b: b["events"][0].update(seq=False), "events[0].seq is not a non-negative integer"), + (lambda b: b["checkpoints"][1]["checkpoint"].update(treeSize=8.0), "treeSize is not a positive integer"), + (lambda b: b["events"][1].pop("eventHash"), "events[1].eventHash is not a sha256 digest"), + (lambda b: b["events"].__setitem__(2, "event"), "events[2] is not an object"), + (lambda b: b.update(events={"0": {}}), "events is missing, empty or not a list"), + (lambda b: b.update(publicKeys={"k": "pem"}), "publicKeys is missing or not a list"), + (lambda b: b["publicKeys"].append(dict(b["publicKeys"][0])), "more than once"), + (lambda b: b["checkpoints"][0].pop("body"), "checkpoints[0].body is not a string"), + (lambda b: b["checkpoints"].append("cp"), "checkpoints[2] is not a signed checkpoint object"), + (lambda b: b.update(startHead=[]), "startHead needs"), + (lambda b: b.pop("logId"), "logId is missing"), + (lambda b: b["events"][7].pop("eventId"), "events[7].eventId is not a non-empty string"), + (lambda b: b["events"][7].update(eventId=5), "events[7].eventId is not a non-empty string"), + ], +) +def test_malformed_structure_is_reported_not_raised(fn, needle: str) -> None: + bundle = json.loads(FULL) + fn(bundle) + check = at.check_bundle(bundle) # must not raise + assert not check.ok and any(needle in r for r in check.reasons), check.reasons + _refused(json.dumps(bundle).encode(), needle) + + +@pytest.mark.parametrize( + "raw,needle", + [ + (b"[]", "not an object"), + (b"null", "not an object"), + (b'"bundle"', "not an object"), + (b"{not json", "not valid JSON"), + (b"\xff\xfe", "not valid JSON"), + (b'{"logId": "a", "logId": "b"}', "duplicate JSON key 'logId'"), + (b"[" * 200_000, "nests too deeply"), + (b'{"a":' * 200_000, "nests too deeply"), + ], +) +def test_bad_bytes_are_refused(raw: bytes, needle: str) -> None: + _refused(raw, needle) + + +def test_an_unreadable_listed_key_fails_closed() -> None: + _refused( + _mutate(FULL, lambda b: b["publicKeys"][0].update(pem="-----BEGIN PUBLIC KEY-----\nAAAA\n-----END PUBLIC KEY-----\n")), + "is unreadable", + ) + + +# ── the CLI ───────────────────────────────────────────────────────────────── + + +def test_cli_writes_a_record_only_for_a_verified_bundle(tmp_path: Path) -> None: + policy = tmp_path / "policy.cedar" + policy.write_bytes(POLICY) + key_pem = KEY.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption() + ) + signing = tmp_path / "signing.pem" + signing.write_bytes(key_pem) + args = ["--subject", SUBJECT, "--policy-bundle", str(policy), "--enforcement-mode", "advisory", + "--workload-digest", WORKLOAD, "--data-class", "internal", "--signing-key", str(signing)] + + good, out = tmp_path / "good.json", tmp_path / "good.trace.json" + good.write_bytes(FULL) + assert at.main([str(good), "--out", str(out), *args]) == 0 + TrustRecord.model_validate(json.loads(out.read_text())) + + bad, none = tmp_path / "bad.json", tmp_path / "bad.trace.json" + bad.write_bytes(_mutate(FULL, lambda b: b["events"][2].update(outcome="error"))) + assert at.main([str(bad), "--out", str(none), *args]) == 2 + assert not none.exists() + + assert at.main([str(good), "--out", str(none), *args[:5], "declared", *args[6:]]) == 2 + assert not none.exists() + + missing = str(tmp_path / "missing.json") + assert at.main([missing, "--out", str(none), *args]) == 2 + assert at.main([str(good), "--out", str(none), *args, "--pin-key", f"k={missing}"]) == 2 + assert at.main([str(good), "--out", str(none), *args, "--pin-key", "no-equals-sign"]) == 2 + assert not none.exists() diff --git a/marketplace/catalog.json b/marketplace/catalog.json index 5bb380b2..be24e740 100644 --- a/marketplace/catalog.json +++ b/marketplace/catalog.json @@ -1,6 +1,6 @@ { "catalog_version": 1, - "count": 51, + "count": 52, "integrations": [ { "name": "Claude Code", @@ -273,6 +273,30 @@ "case-law" ] }, + { + "name": "Auditant", + "package_name": "Auditant evidence bundle", + "vendor": "Auditant", + "description": "Re-verifies an Auditant evidence bundle's hash chain and every signed checkpoint offline, then emits a software-only TRACE log-import Trust Record.", + "path": "integrations/auditant-evidence-bundle", + "url": "https://github.com/agentrust-io/integrations/tree/main/integrations/auditant-evidence-bundle", + "homepage": "https://auditant.co", + "repository": "https://github.com/agentrust-io/integrations", + "tier": "community", + "stack": [ + "TRACE" + ], + "category": "Evidence & receipts", + "mark": "AU", + "featured": null, + "keywords": [ + "audit-trail", + "hash-chain", + "checkpoint", + "log-import", + "evidence" + ] + }, { "name": "Azure Secure Key Release", "package_name": "WCM Azure Secure Key Release", diff --git a/packages/agentrust-trace-adapters/docs/openshell-bundle-candidate.md b/packages/agentrust-trace-adapters/docs/openshell-bundle-candidate.md index 27d6d574..aba54deb 100644 --- a/packages/agentrust-trace-adapters/docs/openshell-bundle-candidate.md +++ b/packages/agentrust-trace-adapters/docs/openshell-bundle-candidate.md @@ -1,7 +1,7 @@ # OpenShell bundle verifier: candidate v1 Unreleased consumer-side proposal for -[NVIDIA/OpenShell #2745](https://github.com/NVIDIA/OpenShell/issues/2745). +[ai-openshell/openshell #2745](https://github.com/ai-openshell/openshell/issues/2745). The field layout below is proposed for producer review. It is not a published OpenShell export format. Tests and the example use synthetic events and ephemeral software keys. They do not run OpenShell or use hardware evidence.