# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-identity-warrant-collapse-when-a-gateway-flattens-a2a-task-envelopes-into-mcp-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-identity-warrant-collapse-when-a-gateway-flattens-a2a-task-envelopes-into-mcp-tool-calls.warrant.json
# Markdown SHA-256:   39755788e11003f3cf160f03481181533cb05e557c5bfc11cf1bba4a97d0355b
# Code AST SHA-256:   0fb6edb8976d62ef65f3712d94d1b29e0499023ef3cdcfe5fedc3ed04701bbc8
# Verified Classes:   WarrantCollapseError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass


class WarrantCollapseError(RuntimeError):
    """Raised when a translated call's principal does not match the terminal
    subject of the warrant chain the caller claims to have delegated through.
    A verifying call from an ancestor principal is the signature of collapse."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: frozenset
    parent_hash: str | None  # hash of parent warrant, None at root
    sig: bytes


def _chain_hash(chain: list[Warrant]) -> str:
    h = hashlib.sha256()
    for w in chain:
        h.update(w.issuer.encode())
        h.update(w.subject.encode())
        h.update(b"|".join(sorted(w.scope)))
        h.update((w.parent_hash or "").encode())
        h.update(w.sig)
    return h.hexdigest()


def verify_translated_call(
    *,
    outbound_chain: list[Warrant],
    outbound_chain_hash: str,
    wire_principal: str,
    wire_chain_hash: str | None,
    requested_scope: frozenset,
    trust_root: dict[str, bytes],
) -> frozenset:
    # 1. Caller-side binding: the callee must see the same chain the caller sent.
    if wire_chain_hash is None:
        # Gateway flattened. We cannot verify the chain. Fail closed unless the
        # outbound chain was length-one (flattening is valid only at depth 1).
        if len(outbound_chain) != 1:
            raise WarrantCollapseError(
                f"gateway dropped warrant chain (len={len(outbound_chain)}); "
                f"effective scope unverifiable, refusing"
            )
        chain = outbound_chain
    else:
        if not hmac.compare_digest(wire_chain_hash, outbound_chain_hash):
            raise WarrantCollapseError(
                "warrant chain hash mismatch: gateway altered the delegation chain"
            )
        chain = outbound_chain

    # 2. Verify every signature against the trust root.
    for w in chain:
        expected = trust_root.get(w.issuer)
        if expected is None or not hmac.compare_digest(expected, w.sig):
            raise WarrantCollapseError(f"unverifiable warrant from issuer {w.issuer}")

    # 3. Terminal-subject check: the principal on the wire MUST be the
    #    terminal subject, not an ancestor. This is the collapse detector.
    terminal_subject = chain[-1].subject
    if wire_principal != terminal_subject:
        raise WarrantCollapseError(
            f"principal substitution: wire principal={wire_principal!r} "
            f"but terminal subject={terminal_subject!r}; "
            f"ancestor authority cannot be exercised on behalf of a narrowed delegate"
        )

    # 4. Effective authority is the intersection of all scopes in the chain.
    effective = frozenset.intersection(*(w.scope for w in chain))
    if not requested_scope.issubset(effective):
        raise WarrantCollapseError(
            f"requested {sorted(requested_scope)} exceeds effective "
            f"intersection {sorted(effective)}"
        )
    return effective
