Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /terrene-foundation_kailash-py /src /kailash /trust /pact /audit.py
| # Copyright 2026 Terrene Foundation | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """PACT governance audit -- maps PACT actions to EATP Audit Anchors. | |
| Records all governance-layer decisions (access grants/denials, envelope | |
| changes, clearance modifications) into the audit chain for compliance | |
| review and forensic analysis. | |
| Per thesis Section 5.7 normative mapping, every governance action maps | |
| to one of 10 PactAuditAction types, which are recorded as EATP Audit | |
| Anchors with structured details. | |
| AuditChain provides a tamper-evident linked chain of AuditAnchor records | |
| with thread-safe append and integrity verification. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import hmac as hmac_mod | |
| import json | |
| import logging | |
| import threading | |
| from datetime import UTC, datetime | |
| from enum import Enum | |
| from typing import Any | |
| from uuid import uuid4 | |
| from kailash.trust._canonical import canonical_scalars | |
| from kailash.trust._jcs import jcs_subject_hash | |
| from kailash.trust.pact.config import VerificationLevel | |
| from kailash.trust.pact.exceptions import PactError | |
| logger = logging.getLogger(__name__) | |
| SCHEMA_VERSION_V2 = "v2.2" | |
| """Grandfathered audit-anchor pre-image schema — no ``subject_hash`` segment. | |
| The default for every anchor that does NOT bind an external subject. Its | |
| signing pre-image is byte-identical to the pre-2026-07 anchor form, so existing | |
| chains verify unchanged (issue #1590). | |
| """ | |
| SCHEMA_VERSION_V3 = "v3" | |
| """EATP v3 audit-anchor schema — binds an external subject via ``subject_hash``. | |
| Set automatically when a ``subject`` is anchored. A true RFC 8785 (JCS) digest | |
| of the subject (``sha256:<hex>``) is appended to the signing pre-image; the | |
| ``schema_version`` discriminator itself is EXCLUDED from the pre-image and is | |
| fail-closed — stripping it on a with-subject anchor forces v2.2-shape | |
| reconstruction, so the recomputed hash diverges and verification rejects the | |
| record (issue #1590 — the EATP v3 keystone). | |
| """ | |
| GENESIS_HASH = "0" * 64 | |
| """Canonical genesis sentinel for audit-chain fingerprints. | |
| Used as `previous_hash` when hashing the first entry in any audit chain. | |
| MUST match across all Kailash SDKs (Python + Rust) per EATP D6 and the | |
| cross-SDK fingerprint contract — see `rules/event-payload-classification.md` | |
| MUST Rule 2. Matches existing blockchain convention (bitcoin, ethereum) and | |
| shares the byte shape of a real SHA-256 hex digest so verifiers need no | |
| option/enum branching. | |
| Change history: | |
| 2026-04-20: replaced the prior ``'genesis'`` literal. Breaking change — | |
| existing chains rooted at ``'genesis'`` will no longer verify. | |
| """ | |
| __all__ = [ | |
| "GENESIS_HASH", | |
| "SCHEMA_VERSION_V2", | |
| "SCHEMA_VERSION_V3", | |
| "PactAuditAction", | |
| "create_pact_audit_details", | |
| "AuditAnchor", | |
| "AuditChain", | |
| "TieredAuditDispatcher", | |
| ] | |
| class PactAuditAction(str, Enum): | |
| """PACT governance action types for EATP audit anchors. | |
| Per thesis Section 5.7 normative mapping. Each action type maps | |
| to a specific governance operation that must be recorded in the | |
| audit chain. | |
| """ | |
| ENVELOPE_CREATED = "envelope_created" | |
| ENVELOPE_MODIFIED = "envelope_modified" | |
| CLEARANCE_GRANTED = "clearance_granted" | |
| CLEARANCE_REVOKED = "clearance_revoked" | |
| BARRIER_ENFORCED = "barrier_enforced" | |
| KSP_CREATED = "ksp_created" | |
| KSP_REVOKED = "ksp_revoked" | |
| BRIDGE_APPROVED = "bridge_approved" | |
| BRIDGE_ESTABLISHED = "bridge_established" | |
| BRIDGE_REVOKED = "bridge_revoked" | |
| ADDRESS_COMPUTED = "address_computed" | |
| VACANCY_DESIGNATED = "vacancy_designated" | |
| VACANCY_SUSPENDED = "vacancy_suspended" | |
| BRIDGE_CONSENT = "bridge_consent" | |
| BRIDGE_REJECTED = "bridge_rejected" | |
| CLEARANCE_TRANSITIONED = "clearance_transitioned" | |
| PLAN_SUSPENDED = "plan_suspended" | |
| PLAN_RESUMED = "plan_resumed" | |
| RESUME_CONDITION_UPDATED = "resume_condition_updated" | |
| def create_pact_audit_details( | |
| action: PactAuditAction, | |
| *, | |
| role_address: str = "", | |
| target_address: str = "", | |
| reason: str = "", | |
| step_failed: int | None = None, | |
| **extra: Any, | |
| ) -> dict[str, Any]: | |
| """Create audit details dict for a PACT governance action. | |
| Produces a structured details dictionary suitable for inclusion in an | |
| EATP AuditAnchor's metadata field. Optional fields are only included | |
| when they have non-empty/non-None values to keep audit records clean. | |
| Args: | |
| action: The PactAuditAction being recorded. | |
| role_address: The D/T/R address of the role performing the action. | |
| target_address: The D/T/R address of the target (if applicable). | |
| reason: Human-readable reason for the action. | |
| step_failed: For BARRIER_ENFORCED, which access enforcement step | |
| (1-5) denied access. | |
| **extra: Additional key-value pairs to include in the details dict. | |
| Returns: | |
| A dict with structured audit details. Always includes pact_action | |
| and role_address. Other fields are included only when non-empty. | |
| """ | |
| details: dict[str, Any] = { | |
| "pact_action": action.value, | |
| "role_address": role_address, | |
| } | |
| if target_address: | |
| details["target_address"] = target_address | |
| if reason: | |
| details["reason"] = reason | |
| if step_failed is not None: | |
| details["step_failed"] = step_failed | |
| details.update(extra) | |
| return details | |
| # --------------------------------------------------------------------------- | |
| # AuditAnchor — a single tamper-evident record | |
| # --------------------------------------------------------------------------- | |
| class AuditAnchor: | |
| """A single tamper-evident record in the governance audit chain. | |
| Each anchor contains a hash of its content plus the hash of the previous | |
| anchor, forming an integrity chain that can be verified for tampering. | |
| Attributes: | |
| anchor_id: Unique anchor identifier. | |
| sequence: Position in the chain (0-based). | |
| previous_hash: Hash of the previous anchor (None for genesis). | |
| agent_id: Agent that performed the action. | |
| action: The action that was performed. | |
| verification_level: PACT VerificationLevel for this action. | |
| envelope_id: Constraint envelope that was evaluated (if any). | |
| result: Action outcome. | |
| metadata: Additional structured details. | |
| timestamp: When the action occurred. | |
| content_hash: SHA-256 hash of this anchor's content (set by seal()). | |
| """ | |
| __slots__ = ( | |
| "anchor_id", | |
| "sequence", | |
| "previous_hash", | |
| "agent_id", | |
| "action", | |
| "verification_level", | |
| "envelope_id", | |
| "result", | |
| "metadata", | |
| "timestamp", | |
| "content_hash", | |
| "subject", | |
| "schema_version", | |
| ) | |
| def __init__( | |
| self, | |
| *, | |
| anchor_id: str = "", | |
| sequence: int = 0, | |
| previous_hash: str | None = None, | |
| agent_id: str = "", | |
| action: str = "", | |
| verification_level: VerificationLevel = VerificationLevel.HELD, | |
| envelope_id: str | None = None, | |
| result: str = "", | |
| metadata: dict[str, Any] | None = None, | |
| timestamp: datetime | None = None, | |
| content_hash: str = "", | |
| subject: Any | None = None, | |
| schema_version: str | None = None, | |
| ) -> None: | |
| self.anchor_id = anchor_id or f"anc-{uuid4().hex[:8]}" | |
| self.sequence = sequence | |
| self.previous_hash = previous_hash | |
| self.agent_id = agent_id | |
| self.action = action | |
| self.verification_level = verification_level | |
| self.envelope_id = envelope_id | |
| self.result = result | |
| self.metadata = metadata or {} | |
| # Timestamp MUST be timezone-aware. A naive datetime serializes with | |
| # NO offset, so its canonical pre-image drops the +00:00 field and | |
| # hash-diverges from an offset-bearing peer (kailash-rs always emits | |
| # +00:00). Construction is strict (reject naive — a programming error), | |
| # mirroring TraceEvent.__post_init__. A non-UTC offset is normalized to | |
| # UTC so the canonical pre-image always renders +00:00 for the same | |
| # instant. (Issue #1401. Deserialization of historical records is the | |
| # lenient counterpart — see from_dict.) | |
| if timestamp is None: | |
| self.timestamp = datetime.now(UTC) | |
| elif timestamp.tzinfo is None: | |
| raise ValueError( | |
| "AuditAnchor.timestamp must be timezone-aware (UTC). " | |
| "Got a naive datetime — use datetime.now(UTC) or " | |
| "datetime.fromisoformat with an explicit offset." | |
| ) | |
| else: | |
| self.timestamp = timestamp.astimezone(UTC) | |
| self.content_hash = content_hash | |
| # EATP v3 (issue #1590): an external subject anchored on this record. | |
| # ``subject`` is any JSON-native / typed-scalar value; when present the | |
| # anchor is v3 and its RFC-8785 (JCS) ``subject_hash`` is bound into the | |
| # signing pre-image. ``schema_version`` is the DISCRIMINATOR that drives | |
| # pre-image reconstruction; it is EXCLUDED from the pre-image itself. | |
| # | |
| # Derivation: an explicit ``schema_version`` (from ``from_dict``) is | |
| # honored verbatim so a DOWNGRADED record — subject present, but | |
| # ``schema_version`` stripped to v2.2 — reconstructs the v2.2 pre-image | |
| # (no ``subject_hash``) and fails hash verification (fail-closed). When | |
| # not explicit, a subject implies v3; its absence implies v2.2. No | |
| # combination raises here: verification, not construction, is the gate, | |
| # so every anomalous (subject, schema_version) pairing fails CLOSED via | |
| # a hash mismatch rather than an exception inside the verify ladder. | |
| self.subject = subject | |
| if schema_version is not None: | |
| self.schema_version = schema_version | |
| elif subject is not None: | |
| self.schema_version = SCHEMA_VERSION_V3 | |
| else: | |
| self.schema_version = SCHEMA_VERSION_V2 | |
| def _subject_hash(self) -> str: | |
| """Return the RFC 8785 (JCS) ``subject_hash`` for this anchor's subject. | |
| ``sha256:<hex>`` of the JCS canonicalization of ``self.subject``. Only | |
| meaningful for a v3 anchor (``schema_version == SCHEMA_VERSION_V3``); a | |
| ``None`` subject canonicalizes to ``"null"`` deterministically. | |
| """ | |
| return jcs_subject_hash(self.subject) | |
| def _canonical_input(self) -> str: | |
| """Build the canonical pre-image string that ``compute_hash`` hashes. | |
| This is the SINGLE production source of the canonical-input bytes; | |
| ``compute_hash`` hashes its output and the regression tests assert | |
| against it directly (no test-side re-implementation — issue #1404). | |
| Canonical input format (cross-SDK contract, see kailash-rs#449 §2): | |
| {anchor_id}:{sequence}:{previous_hash}:{agent_id}:{action}: | |
| {verification_level}:{envelope_id_or_empty}:{result}: | |
| {iso8601_utc_with_+00:00}[:{metadata_json_sorted_compact}] | |
| * Timestamp: ``isoformat(timespec="microseconds")`` — ALWAYS six | |
| fractional-second digits and an explicit ``+00:00`` offset. Bare | |
| ``isoformat()`` elides the fraction when ``microsecond == 0`` but | |
| emits six digits otherwise, so a whole-second anchor and a peer SDK | |
| that always emits six digits would hash-diverge (issue #1400, the | |
| same fix TraceEvent.to_dict already carries). ``__init__`` / | |
| ``from_dict`` guarantee ``self.timestamp`` is UTC-aware so the offset | |
| is always ``+00:00`` (issue #1401). | |
| * Metadata: routed through ``canonical_scalars`` (the shared | |
| typed-scalar whitelist) then ``json.dumps`` with compact separators | |
| + ``ensure_ascii=True`` + ``allow_nan=False`` (a ``NaN`` / ``Infinity`` | |
| metadata value raises ``ValueError``, matching ``serialize_for_signing`` | |
| and RFC-8259). NO ``default=str`` — a ``Decimal`` / ``UUID`` / | |
| ``datetime`` / ``set`` in metadata is encoded deterministically, never | |
| via implementation-defined ``str()`` (issue #1405 / #1403). A | |
| non-JSON-native, non-whitelisted value raises ``TypeError`` rather than | |
| silently stringifying. Empty metadata omits the suffix entirely (no | |
| trailing ``:``). | |
| DELIBERATE ASYMMETRY: a ``datetime`` VALUE inside metadata renders via | |
| ``canonical_scalars`` as a plain ``isoformat()`` (so a whole-second | |
| metadata datetime emits NO fractional part), whereas the anchor's OWN | |
| top-level ``timestamp`` always gets six fractional digits (above). | |
| Metadata datetimes follow the established ``serialize_for_signing`` | |
| signing-family contract (bare ``isoformat()``, issue #959) — changing | |
| them to fixed-width would break every existing trust-plane signature. | |
| A peer SDK MUST therefore render metadata datetimes with bare | |
| ``isoformat()`` to stay byte-equal (cross-SDK confirmation tracked with | |
| the kailash-rs#449 lockstep). Pinned by the ``U6`` whole-second | |
| metadata-datetime vector in ``test-vectors/audit-chain-canonical.json``. | |
| """ | |
| content = ( | |
| f"{self.anchor_id}:{self.sequence}:{self.previous_hash or GENESIS_HASH}:" | |
| f"{self.agent_id}:{self.action}:{self.verification_level.value}:" | |
| f"{self.envelope_id or ''}:{self.result}:" | |
| f"{self.timestamp.isoformat(timespec='microseconds')}" | |
| ) | |
| if self.metadata: | |
| meta_str = json.dumps( | |
| canonical_scalars(self.metadata), | |
| sort_keys=True, | |
| separators=(",", ":"), | |
| ensure_ascii=True, | |
| allow_nan=False, | |
| ) | |
| content += f":{meta_str}" | |
| # EATP v3 (issue #1590): the subject binding is appended ONLY for a v3 | |
| # anchor, keyed on the ``schema_version`` DISCRIMINATOR (NOT on | |
| # ``self.subject is not None``). This is the fail-closed hinge: stripping | |
| # ``schema_version`` (v3 → v2.2) on a with-subject record drops this | |
| # segment, so the recomputed hash diverges from the stored one and | |
| # verification rejects the record. A v2.2 anchor never appends the | |
| # segment, so its pre-image is BYTE-IDENTICAL to the pre-EATP-v3 form. | |
| # The ``subject_hash`` uses the true RFC 8785 (JCS) encoder — distinct | |
| # from the v2.2 ``json.dumps(sort_keys=True)`` metadata form above, which | |
| # is grandfathered cross-SDK byte-pinned and untouched here. | |
| if self.schema_version == SCHEMA_VERSION_V3: | |
| content += f":subject_hash={self._subject_hash()}" | |
| return content | |
| def compute_hash(self) -> str: | |
| """Compute the SHA-256 content hash for this anchor. | |
| Hashes the canonical pre-image built by :meth:`_canonical_input`. | |
| """ | |
| return hashlib.sha256(self._canonical_input().encode()).hexdigest() | |
| def seal(self) -> None: | |
| """Seal this anchor by computing and storing its content hash.""" | |
| self.content_hash = self.compute_hash() | |
| def is_sealed(self) -> bool: | |
| return bool(self.content_hash) | |
| def verify_integrity(self) -> bool: | |
| """Verify this anchor's hash matches its content.""" | |
| if not self.is_sealed: | |
| return False | |
| return hmac_mod.compare_digest(self.content_hash, self.compute_hash()) | |
| def _compute_hash_legacy(self) -> str: | |
| """Recompute the content hash under the pre-2026-04-20 contract. | |
| Used ONLY for forensic disambiguation in ``verify_chain_integrity`` | |
| to distinguish legacy-rooted chains (pre-GENESIS_HASH migration) | |
| from real tampering. Legacy form: ``'genesis'`` literal as the | |
| first-anchor sentinel AND default ``json.dumps`` separators (with | |
| spaces) for metadata canonicalization. | |
| An anchor whose stored ``content_hash`` matches this legacy form | |
| is a pre-migration chain that requires re-sealing, NOT a tampered | |
| record. | |
| """ | |
| content = ( | |
| f"{self.anchor_id}:{self.sequence}:{self.previous_hash or 'genesis'}:" | |
| f"{self.agent_id}:{self.action}:{self.verification_level.value}:" | |
| f"{self.envelope_id or ''}:{self.result}:{self.timestamp.isoformat()}" | |
| ) | |
| if self.metadata: | |
| meta_str = json.dumps(self.metadata, sort_keys=True, default=str) | |
| content += f":{meta_str}" | |
| return hashlib.sha256(content.encode()).hexdigest() | |
| def _compute_hash_prefix_format(self) -> str: | |
| """Recompute the content hash under the 2026-04-20 .. 2026-06-20 contract. | |
| Used ONLY for forensic disambiguation in ``verify_chain_integrity`` to | |
| distinguish chains sealed AFTER the GENESIS_HASH migration but BEFORE | |
| the 2026-06-20 canonical-conformance fix (issue #1400/#1405) from real | |
| tampering. That prefix format used the ``GENESIS_HASH`` sentinel (so it | |
| is NOT a pre-2026-04-20 legacy chain) BUT still carried the two pre-fix | |
| byte differences: | |
| * bare ``isoformat()`` — fractional second elided when ``microsecond`` | |
| is 0 (the issue #1400 bug, now fixed to ``timespec="microseconds"``); | |
| * metadata ``json.dumps(..., default=str)`` — implementation-defined | |
| ``str()`` on typed scalars (the issue #1405 bug, now routed through | |
| ``canonical_scalars``). | |
| An anchor whose stored ``content_hash`` matches this recompute is a | |
| pre-2026-06-20 chain that requires re-sealing, NOT a tampered record. | |
| This is the sibling of :meth:`_compute_hash_legacy` for the newer | |
| format boundary; it is deliberately byte-verbatim with the pre-fix | |
| ``_canonical_input`` so it reproduces historically-sealed bytes exactly. | |
| KNOWN LIMITATION (narrow): this reproducer renders ``self.timestamp``, | |
| which ``__init__`` / ``from_dict`` have already normalized to UTC. A | |
| pre-fix anchor sealed with an EXPLICIT naive or non-UTC timestamp had its | |
| original-offset bytes (no offset / ``+08:00``) hashed; after load-time | |
| normalization those original bytes are unrecoverable, so such an anchor | |
| matches NEITHER this reproducer NOR :meth:`_compute_hash_legacy` and | |
| reads as ``content hash mismatch (tampered?)`` rather than a re-seal | |
| advisory. The common pre-fix population (the ``datetime.now(UTC)`` | |
| default path) IS recognized correctly; only anchors EXPLICITLY | |
| constructed with a naive/non-UTC timestamp (the very class issue #1401 | |
| deprecates) fall here, and re-seal is the correct disposition for them | |
| regardless of the label. Pinned by | |
| ``TestPreFixNaiveNonUtcLimitation`` in | |
| ``tests/regression/test_issue_1400_audit_chain_canonical_conformance.py``. | |
| """ | |
| content = ( | |
| f"{self.anchor_id}:{self.sequence}:{self.previous_hash or GENESIS_HASH}:" | |
| f"{self.agent_id}:{self.action}:{self.verification_level.value}:" | |
| f"{self.envelope_id or ''}:{self.result}:{self.timestamp.isoformat()}" | |
| ) | |
| if self.metadata: | |
| meta_str = json.dumps( | |
| self.metadata, | |
| sort_keys=True, | |
| separators=(",", ":"), | |
| default=str, | |
| ensure_ascii=True, | |
| ) | |
| content += f":{meta_str}" | |
| return hashlib.sha256(content.encode()).hexdigest() | |
| def to_dict(self) -> dict[str, Any]: | |
| """Serialize to a JSON-compatible dictionary. | |
| The EATP v3 fields (``schema_version``, ``subject``, ``subject_hash``) | |
| are emitted ONLY for a v3 anchor (issue #1590). A v2.2 anchor omits them | |
| entirely, so its serialized form is BYTE-IDENTICAL to the pre-EATP-v3 | |
| shape — every existing conformance vector and on-disk record round-trips | |
| unchanged. ``subject_hash`` is informational transparency for external | |
| verifiers; on verify it is RE-DERIVED from ``subject`` (never trusted | |
| from the stored value), so a tampered ``subject`` fails the hash check. | |
| The stored ``subject`` is normalized through ``canonical_scalars`` — the | |
| SAME normalizer ``jcs_subject_hash`` already applies before hashing — so | |
| a typed-scalar subject (``datetime`` / ``UUID`` / ``Decimal`` / ``bytes`` | |
| / ``Enum`` / dataclass) serializes cleanly through ``json.dumps`` instead | |
| of raising ``TypeError: Object of type X is not JSON serializable``. This | |
| is BYTE-SAFE for ``subject_hash``: ``canonical_scalars`` is idempotent | |
| and ``subject_hash`` is derived from ``canonical_scalars(subject)`` on | |
| BOTH sides, so normalizing the STORED form changes NEITHER the emitted | |
| ``subject_hash`` NOR the ``content_hash`` (the pre-image is untouched), | |
| and a ``from_dict`` round-trip re-derives the identical ``subject_hash`` | |
| (``verify_integrity`` still passes). For a JSON-native subject the | |
| normalization is a value-preserving no-op, so every existing golden | |
| vector's ``expected_canonical_json`` is unchanged. | |
| """ | |
| result: dict[str, Any] = { | |
| "anchor_id": self.anchor_id, | |
| "sequence": self.sequence, | |
| "previous_hash": self.previous_hash, | |
| "agent_id": self.agent_id, | |
| "action": self.action, | |
| "verification_level": self.verification_level.value, | |
| "envelope_id": self.envelope_id, | |
| "result": self.result, | |
| "metadata": self.metadata, | |
| "timestamp": self.timestamp.isoformat(timespec="microseconds"), | |
| "content_hash": self.content_hash, | |
| } | |
| if self.schema_version == SCHEMA_VERSION_V3: | |
| result["schema_version"] = self.schema_version | |
| result["subject"] = canonical_scalars(self.subject) | |
| result["subject_hash"] = self._subject_hash() | |
| return result | |
| def from_dict(cls, data: dict[str, Any]) -> AuditAnchor: | |
| """Deserialize from a dictionary. | |
| ``schema_version`` and ``subject`` are read verbatim (issue #1590). A | |
| record MISSING ``schema_version`` defaults EXPLICITLY to v2.2 — passed | |
| as a concrete value, NOT ``None`` — so a with-subject record whose | |
| ``schema_version`` was STRIPPED reconstructs as v2.2 (dropping the | |
| ``subject_hash`` segment) and fails hash verification (fail-closed). | |
| This EXPLICIT default is load-bearing: passing ``None`` would let | |
| ``__init__``'s "a subject implies v3" convenience RE-DERIVE v3 from the | |
| still-present ``subject``, silently undoing the downgrade the stripped | |
| discriminator is supposed to force. The stored ``subject_hash`` is NOT | |
| consumed: the pre-image re-derives it from ``subject`` on demand. | |
| """ | |
| ts = data.get("timestamp") | |
| if isinstance(ts, str): | |
| ts = datetime.fromisoformat(ts) | |
| if isinstance(ts, datetime) and ts.tzinfo is None: | |
| # Lenient on read (issue #1401): a historical record may have been | |
| # persisted with a naive timestamp (pre-fix to_dict emitted whatever | |
| # tz the anchor held). Normalize naive→UTC so AuditChain.from_dict | |
| # can LOAD it instead of fail-closed raising — contrast __init__, | |
| # which REJECTS naive on NEW construction. Re-sealing under the | |
| # fixed canonical format then re-anchors it with an explicit +00:00. | |
| ts = ts.replace(tzinfo=UTC) | |
| return cls( | |
| anchor_id=data.get("anchor_id", ""), | |
| sequence=data.get("sequence", 0), | |
| previous_hash=data.get("previous_hash"), | |
| agent_id=data.get("agent_id", ""), | |
| action=data.get("action", ""), | |
| verification_level=VerificationLevel( | |
| data.get("verification_level", "HELD") | |
| ), | |
| envelope_id=data.get("envelope_id"), | |
| result=data.get("result", ""), | |
| metadata=data.get("metadata", {}), | |
| timestamp=ts, | |
| content_hash=data.get("content_hash", ""), | |
| subject=data.get("subject"), | |
| # EXPLICIT v2.2 default on an absent key (NOT None) — see docstring: | |
| # a stripped discriminator MUST force v2.2 reconstruction, and a | |
| # None here would let __init__ re-derive v3 from the subject. | |
| schema_version=data.get("schema_version", SCHEMA_VERSION_V2), | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # AuditChain — an ordered chain of audit anchors | |
| # --------------------------------------------------------------------------- | |
| class AuditChain: | |
| """An ordered chain of audit anchors with integrity verification. | |
| Thread-safe: append() acquires an internal lock to prevent hash chain | |
| corruption from concurrent appends. | |
| Args: | |
| chain_id: Unique identifier for this audit chain. | |
| """ | |
| _MAX_ANCHORS = 10_000 | |
| def __init__(self, chain_id: str, *, max_anchors: int = _MAX_ANCHORS) -> None: | |
| self.chain_id = chain_id | |
| self.anchors: list[AuditAnchor] = [] | |
| self._max_anchors = max_anchors | |
| self._chain_lock = threading.Lock() | |
| def length(self) -> int: | |
| return len(self.anchors) | |
| def latest(self) -> AuditAnchor | None: | |
| return self.anchors[-1] if self.anchors else None | |
| def append( | |
| self, | |
| agent_id: str, | |
| action: str, | |
| verification_level: VerificationLevel, | |
| *, | |
| envelope_id: str | None = None, | |
| result: str = "", | |
| metadata: dict[str, Any] | None = None, | |
| subject: Any | None = None, | |
| ) -> AuditAnchor: | |
| """Create and append a new sealed anchor. | |
| Thread-safe: acquires the chain lock to ensure correct sequence | |
| numbering and hash linkage. | |
| Args: | |
| agent_id: The agent performing the action. | |
| action: The action being recorded. | |
| verification_level: The PACT verification level. | |
| envelope_id: Optional constraint envelope ID. | |
| result: Action outcome. | |
| metadata: Additional details. | |
| subject: Optional external governed subject (issue #1590). When | |
| provided, the anchor is sealed as an EATP v3 record: a true | |
| RFC 8785 (JCS) ``subject_hash`` of ``subject`` is bound into the | |
| signing pre-image. When ``None`` (the default), the anchor is a | |
| v2.2 record whose pre-image is byte-identical to the historical | |
| form. | |
| Returns: | |
| The newly created and sealed AuditAnchor. | |
| """ | |
| with self._chain_lock: | |
| sequence = len(self.anchors) | |
| previous_hash = self.anchors[-1].content_hash if self.anchors else None | |
| anchor = AuditAnchor( | |
| anchor_id=f"{self.chain_id}-{sequence}", | |
| sequence=sequence, | |
| previous_hash=previous_hash, | |
| agent_id=agent_id, | |
| action=action, | |
| verification_level=verification_level, | |
| envelope_id=envelope_id, | |
| result=result, | |
| metadata=metadata or {}, | |
| subject=subject, | |
| ) | |
| anchor.seal() | |
| self.anchors.append(anchor) | |
| # Evict oldest 10% when at capacity (bounded collection) | |
| if len(self.anchors) > self._max_anchors: | |
| evict_count = max(1, self._max_anchors // 10) | |
| self.anchors = self.anchors[evict_count:] | |
| return anchor | |
| def verify_chain_integrity(self) -> tuple[bool, list[str]]: | |
| """Walk the chain and verify every anchor's integrity. | |
| Returns: | |
| (is_valid, list of error messages). Empty list means valid. | |
| """ | |
| errors: list[str] = [] | |
| for i, anchor in enumerate(self.anchors): | |
| if anchor.sequence != i: | |
| errors.append( | |
| f"Anchor {i}: sequence mismatch (expected {i}, got {anchor.sequence})" | |
| ) | |
| if not anchor.verify_integrity(): | |
| # The stored content_hash does not match the CURRENT canonical | |
| # format. The current-format rung (``compute_hash`` → | |
| # ``_canonical_input``) is SCHEMA_VERSION-AWARE (issue #1590): it | |
| # reconstructs the v2.2 pre-image for a v2.2 anchor AND the | |
| # v3-with-``subject_hash`` pre-image for a v3 anchor, so a | |
| # LEGITIMATE v3 anchor verifies on this rung and never falls | |
| # through to the historical reproducers below (it does NOT read | |
| # as tampered). A v3 record whose ``schema_version`` was STRIPPED | |
| # reconstructs as v2.2 here, mismatches, and is correctly | |
| # REJECTED (fail-closed) — it matches none of the ladder rungs. | |
| # Before calling any mismatch tampering, try the two historical | |
| # format recomputes — a match means the chain pre-dates a | |
| # canonical-format migration and needs re-sealing, NOT a | |
| # forensic incident. Ladder (newest → oldest): current | |
| # (schema-aware v2.2/v3; already failed above) → pre-2026-06-20 | |
| # prefix format (whole-second timestamp and/or a default=str | |
| # scalar in metadata) → pre-2026-04-20 legacy genesis | |
| # sentinel → tampered. | |
| if anchor.is_sealed and hmac_mod.compare_digest( | |
| anchor.content_hash, anchor._compute_hash_prefix_format() | |
| ): | |
| errors.append( | |
| f"Anchor {i}: pre-2026-06-20 canonical format detected " | |
| f"(whole-second timestamp and/or default=str typed-scalar " | |
| f"metadata) — chain pre-dates the canonical-conformance fix " | |
| f"(issue #1400/#1405). Re-seal required: re-invoke " | |
| f"AuditAnchor.seal() across every anchor in the chain. " | |
| f"This is NOT tampering." | |
| ) | |
| elif anchor.is_sealed and hmac_mod.compare_digest( | |
| anchor.content_hash, anchor._compute_hash_legacy() | |
| ): | |
| errors.append( | |
| f"Anchor {i}: legacy genesis sentinel detected — chain " | |
| f"pre-dates 2026-04-20 canonical alignment (kailash-rs#449). " | |
| f"Re-seal required: re-invoke AuditAnchor.seal() across every " | |
| f"anchor in the chain. This is NOT tampering." | |
| ) | |
| else: | |
| errors.append(f"Anchor {i}: content hash mismatch (tampered?)") | |
| if i == 0: | |
| if anchor.previous_hash is not None: | |
| errors.append( | |
| "Anchor 0: genesis anchor should have no previous_hash" | |
| ) | |
| else: | |
| expected_prev = self.anchors[i - 1].content_hash | |
| if anchor.previous_hash is None or not hmac_mod.compare_digest( | |
| anchor.previous_hash, expected_prev | |
| ): | |
| errors.append( | |
| f"Anchor {i}: previous_hash doesn't match anchor {i - 1}" | |
| ) | |
| return len(errors) == 0, errors | |
| def filter_by_agent(self, agent_id: str) -> list[AuditAnchor]: | |
| """Get all anchors for a specific agent.""" | |
| return [a for a in self.anchors if a.agent_id == agent_id] | |
| def filter_by_level(self, level: VerificationLevel) -> list[AuditAnchor]: | |
| """Get all anchors at a specific verification level.""" | |
| return [a for a in self.anchors if a.verification_level == level] | |
| def to_dict(self) -> dict[str, Any]: | |
| """Serialize the entire chain.""" | |
| return { | |
| "chain_id": self.chain_id, | |
| "anchors": [a.to_dict() for a in self.anchors], | |
| } | |
| def from_dict(cls, data: dict[str, Any]) -> AuditChain: | |
| """Deserialize from a dictionary and verify integrity (P-H10). | |
| After reconstruction, verifies the hash chain integrity. | |
| Raises PactError if the chain is corrupted. | |
| """ | |
| chain = cls(chain_id=data.get("chain_id", "")) | |
| for anchor_data in data.get("anchors", []): | |
| chain.anchors.append(AuditAnchor.from_dict(anchor_data)) | |
| # Verify integrity after reconstruction (P-H10 fix) | |
| if chain.anchors: | |
| valid, errors = chain.verify_chain_integrity() | |
| if not valid: | |
| logger.warning( | |
| "AuditChain '%s' integrity check failed after from_dict: %s", | |
| chain.chain_id, | |
| errors, | |
| ) | |
| # Honor the documented contract: a corrupted audit chain MUST | |
| # raise, never silently return as valid. Fail-closed — accepting | |
| # a tampered/corrupted chain at the deserialization boundary | |
| # defeats the tamper-evidence guarantee the audit chain exists | |
| # to provide. BUT surface the per-anchor errors in the message | |
| # (not only details) AND distinguish a benign pre-canonical-fix | |
| # chain — every error is a re-seal advisory ("NOT tampering") — | |
| # from possible tampering, so the operator gets actionable | |
| # re-seal guidance instead of an opaque "failed verification". | |
| reseal_only = bool(errors) and all("NOT tampering" in e for e in errors) | |
| summary = ( | |
| "requires re-seal — pre-canonical-fix format detected " | |
| "(NOT tampering)" | |
| if reseal_only | |
| else "failed integrity verification (possible tampering)" | |
| ) | |
| raise PactError( | |
| f"AuditChain '{chain.chain_id}' {summary} after " | |
| f"deserialization: {errors}", | |
| details={ | |
| "chain_id": chain.chain_id, | |
| "errors": errors, | |
| "reseal_only": reseal_only, | |
| }, | |
| ) | |
| return chain | |
| # --------------------------------------------------------------------------- | |
| # TieredAuditDispatcher -- gradient-aligned persistence tiers (PACT-08) | |
| # --------------------------------------------------------------------------- | |
| # Tier buffer bound: maximum FLAGGED anchors buffered before forced flush. | |
| _MAX_SESSION_BUFFER = 10_000 | |
| class TieredAuditDispatcher: | |
| """Routes audit anchors to storage tiers based on verification level. | |
| The three tiers align with the PACT verification gradient: | |
| * **Tier 1 (ephemeral)** -- ``AUTO_APPROVED`` actions are written only to | |
| the in-memory ``AuditChain``. Cheap, fast, lost on process restart. | |
| * **Tier 2 (session-buffered)** -- ``FLAGGED`` actions are buffered in | |
| memory and flushed to the durable store at session end via | |
| ``flush_session()``. Balances cost with auditability. | |
| * **Tier 3 (synchronous durable)** -- ``HELD`` and ``BLOCKED`` actions are | |
| written synchronously to both the ephemeral chain AND the durable store. | |
| These represent governance denials or holds that MUST survive restarts. | |
| Thread safety: the dispatcher acquires ``_lock`` around the session buffer. | |
| The ephemeral ``AuditChain`` and durable store each have their own locks. | |
| Args: | |
| ephemeral: The in-memory ``AuditChain`` for all tiers. | |
| durable: An ``InMemoryAuditStore`` (or any store exposing | |
| ``create_event`` / ``append``). When ``None``, Tier 2 and 3 | |
| behave identically to Tier 1 (ephemeral-only). | |
| """ | |
| def __init__( | |
| self, | |
| ephemeral: AuditChain, | |
| durable: Any | None = None, | |
| ) -> None: | |
| self._ephemeral = ephemeral | |
| self._durable = durable | |
| self._session_buffer: list[AuditAnchor] = [] | |
| self._lock = threading.Lock() | |
| def ephemeral(self) -> AuditChain: | |
| """The underlying ephemeral audit chain.""" | |
| return self._ephemeral | |
| def session_buffer_size(self) -> int: | |
| """Number of FLAGGED anchors currently buffered.""" | |
| with self._lock: | |
| return len(self._session_buffer) | |
| def dispatch( | |
| self, | |
| anchor: AuditAnchor, | |
| level: VerificationLevel, | |
| ) -> None: | |
| """Route an anchor to the appropriate persistence tier. | |
| Args: | |
| anchor: The sealed ``AuditAnchor`` to dispatch. | |
| level: The ``VerificationLevel`` that determines the tier. | |
| """ | |
| if level in (VerificationLevel.HELD, VerificationLevel.BLOCKED): | |
| # Tier 3: synchronous durable write + ephemeral | |
| if self._durable is not None: | |
| event = self._anchor_to_event(anchor) | |
| try: | |
| # InMemoryAuditStore.append is async, but for synchronous | |
| # governance paths we need a sync wrapper. We use the | |
| # store's internal deque directly if available, otherwise | |
| # fall back to create+append via an event loop. | |
| import asyncio | |
| try: | |
| loop = asyncio.get_running_loop() | |
| except RuntimeError: | |
| loop = None | |
| if loop is not None and loop.is_running(): | |
| # Already in an async context -- schedule as task | |
| loop.create_task(self._durable.append(event)) | |
| else: | |
| asyncio.run(self._durable.append(event)) | |
| except Exception: | |
| logger.exception( | |
| "TieredAuditDispatcher: durable write failed for " | |
| "HELD/BLOCKED anchor %s -- ephemeral-only", | |
| anchor.anchor_id, | |
| ) | |
| self._ephemeral.append( | |
| agent_id=anchor.agent_id, | |
| action=anchor.action, | |
| verification_level=level, | |
| envelope_id=anchor.envelope_id, | |
| result=anchor.result, | |
| metadata=anchor.metadata, | |
| ) | |
| elif level == VerificationLevel.FLAGGED: | |
| # Tier 2: buffer for session-end persistence + ephemeral | |
| with self._lock: | |
| self._session_buffer.append(anchor) | |
| # Bounded: evict oldest 10% at capacity | |
| if len(self._session_buffer) > _MAX_SESSION_BUFFER: | |
| evict = max(1, _MAX_SESSION_BUFFER // 10) | |
| self._session_buffer = self._session_buffer[evict:] | |
| self._ephemeral.append( | |
| agent_id=anchor.agent_id, | |
| action=anchor.action, | |
| verification_level=level, | |
| envelope_id=anchor.envelope_id, | |
| result=anchor.result, | |
| metadata=anchor.metadata, | |
| ) | |
| else: | |
| # Tier 1: ephemeral only (AUTO_APPROVED) | |
| self._ephemeral.append( | |
| agent_id=anchor.agent_id, | |
| action=anchor.action, | |
| verification_level=level, | |
| envelope_id=anchor.envelope_id, | |
| result=anchor.result, | |
| metadata=anchor.metadata, | |
| ) | |
| def flush_session(self) -> int: | |
| """Persist Tier 2 (FLAGGED) anchors to the durable store. | |
| Returns the number of anchors flushed. Clears the session buffer | |
| regardless of whether the durable store is configured (so the buffer | |
| does not grow unbounded in ephemeral-only mode). | |
| Returns: | |
| Number of anchors flushed to durable storage. | |
| """ | |
| with self._lock: | |
| to_flush = list(self._session_buffer) | |
| self._session_buffer.clear() | |
| if not to_flush or self._durable is None: | |
| return 0 | |
| flushed = 0 | |
| for anchor in to_flush: | |
| event = self._anchor_to_event(anchor) | |
| try: | |
| import asyncio | |
| try: | |
| loop = asyncio.get_running_loop() | |
| except RuntimeError: | |
| loop = None | |
| if loop is not None and loop.is_running(): | |
| loop.create_task(self._durable.append(event)) | |
| else: | |
| asyncio.run(self._durable.append(event)) | |
| flushed += 1 | |
| except Exception: | |
| logger.exception( | |
| "TieredAuditDispatcher: flush failed for anchor %s", | |
| anchor.anchor_id, | |
| ) | |
| return flushed | |
| def _anchor_to_event(self, anchor: AuditAnchor) -> Any: | |
| """Convert a PACT AuditAnchor to a canonical AuditEvent. | |
| Uses the durable store's ``create_event`` factory to build a | |
| properly hash-chained event from the anchor's fields. | |
| Returns: | |
| An ``AuditEvent`` instance ready for ``store.append()``. | |
| """ | |
| if self._durable is None: | |
| raise RuntimeError("Cannot convert anchor to event without a durable store") | |
| return self._durable.create_event( | |
| actor=anchor.agent_id, | |
| action=anchor.action, | |
| resource=anchor.envelope_id or "", | |
| outcome=anchor.result or "success", | |
| metadata={ | |
| **anchor.metadata, | |
| "verification_level": anchor.verification_level.value, | |
| "pact_anchor_id": anchor.anchor_id, | |
| }, | |
| ) | |
Xet Storage Details
- Size:
- 42 kB
- Xet hash:
- c40e1cdaa0d7a496883a9f823fd2969906ce463e400df42f0b8a88b8c43aeb53
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.