# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-audit-warrant-when-a-federated-agent-re-signs-the-delegation-chain-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-audit-warrant-when-a-federated-agent-re-signs-the-delegation-chain-mid-execution.warrant.json
# Markdown SHA-256:   b30368c3c1f71d6d3ceab0f5751917ea1b8d81840693f71b563bd9e410de1e9f
# Code AST SHA-256:   92ab438cb3c74642bc436d91d8f6c235ba04caf66de9deeff39bf0c8a2725f56
# Verified Classes:   WarrantProvenanceError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class WarrantProvenanceError(RuntimeError):
    """Raised when a federated delegation chain cannot be linked back to the
    originating org's attestation of the human principal."""
    pass


@dataclass
class Warrant:
    payload: dict          # signed claims
    signer_org: str        # org whose key signed this warrant
    signature: bytes
    # For re-signed envelopes only: hash of the upstream warrant this
    # envelope claims to delegate from. Must be INSIDE the signed payload.
    upstream_hash: Optional[str] = None


def _canonical_hash(w: Warrant) -> str:
    # Hash covers payload + signer + signature: the full upstream attestation.
    h = hashlib.sha256()
    h.update(repr(sorted(w.payload.items())).encode())
    h.update(w.signer_org.encode())
    h.update(w.signature)
    return h.hexdigest()


def verify_federated_chain(
    leaf: Warrant,
    upstream: Warrant,
    trusted_keys: dict,          # org -> verify(sig, payload) -> bool
    originating_org: str,
) -> str:
    """Return the attested principal, or raise if the chain is unlinkable.

    Invariant: the principal used for audit MUST come from the originating
    org's warrant, never from a peer re-signing.
    """
    # 1. Leaf must be validly signed by its own org.
    if not trusted_keys[leaf.signer_org](leaf.signature, leaf.payload):
        raise WarrantProvenanceError(
            f"leaf warrant signature invalid under {leaf.signer_org}"
        )

    # 2. Leaf must embed the upstream hash INSIDE its signed payload.
    embedded = leaf.payload.get("upstream_hash")
    if embedded is None:
        raise WarrantProvenanceError(
            "leaf warrant omits upstream_hash; peer re-signed without a "
            "back-reference, chain is unlinkable"
        )

    # 3. The embedded hash must match the actual upstream warrant.
    if embedded != _canonical_hash(upstream):
        raise WarrantProvenanceError(
            "upstream_hash mismatch: leaf does not delegate from this warrant"
        )

    # 4. Upstream must be attested by the originating org, not the peer.
    if upstream.signer_org != originating_org:
        raise WarrantProvenanceError(
            f"upstream signed by {upstream.signer_org}, expected "
            f"originating org {originating_org}"
        )
    if not trusted_keys[originating_org](upstream.signature, upstream.payload):
        raise WarrantProvenanceError(
            "upstream warrant not validly signed by originating org"
        )

    # 5. Principal MUST be read from upstream, never from the leaf.
    if leaf.payload.get("principal") != upstream.payload.get("principal"):
        raise WarrantProvenanceError(
            "principal mismatch between leaf and upstream: peer re-signed "
            "the principal field, audit attestation is lost"
        )

    return upstream.payload["principal"]


def audit_record(leaf: Warrant, upstream: Warrant, trusted_keys: dict,
                 originating_org: str) -> dict:
    principal = verify_federated_chain(
        leaf, upstream, trusted_keys, originating_org
    )
    return {
        "attested_principal": principal,
        "attesting_org": originating_org,   # not leaf.signer_org
        "leaf_signer": leaf.signer_org,
        "chain_link": leaf.payload["upstream_hash"],
    }
