# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-warrant-whose-audience-constraint-was-satisfied-only-at-the-leaf-and-silently-widened-at-each-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-warrant-whose-audience-constraint-was-satisfied-only-at-the-leaf-and-silently-widened-at-each-hop.warrant.json
# Markdown SHA-256:   3d97fee395f61c457cdef6ff0ef1a9286d325ab334cf9fe2a4dac0f382643d52
# Code AST SHA-256:   7e635edd45202a9d3c6285bbf84119cfd6da336b34eeb7a931c112348f9ed052
# Verified Classes:   WarrantChainError, Warrant, Agent
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class WarrantChainError(RuntimeError):
    """Raised when an audience-restricted warrant violates the per-hop
    delegation invariant: aud must equal the current holder's identity,
    and each hop must extend the act chain via a fresh exchange."""


@dataclass
class Warrant:
    aud: str                      # audience the token is valid for
    act: list[str]                # delegation chain, oldest actor first
    capability: str               # e.g. "exec_v2"
    signature: str = ""           # IdP signature over (aud, act, capability)

    def fingerprint(self) -> str:
        material = f"{self.aud}|{','.join(self.act)}|{self.capability}"
        return hashlib.sha256(material.encode()).hexdigest()


@dataclass
class Agent:
    identity: str                 # AAIF-bound SPIFFE ID, e.g. "agent://planner"
    mtls_peer: str = ""           # identity proven by the mTLS handshake

    def verify_inbound(self, w: Warrant) -> None:
        # mTLS proves the channel peer; audience must prove *this* agent.
        if self.mtls_peer != self.identity:
            raise WarrantChainError(
                f"mTLS peer {self.mtls_peer!r} does not match bound identity "
                f"{self.identity!r}"
            )
        if w.aud != self.identity:
            # The only sound response to aud != self at an interior node
            # is to refuse to forward; exchange, don't passthrough.
            raise WarrantChainError(
                f"audience mismatch at {self.identity}: token aud={w.aud!r} "
                f"names a downstream party; refusing passthrough"
            )

    def exchange(self, inbound: Warrant, next_hop: str, capability: str) -> Warrant:
        # Precondition: inbound.aud == self.identity (checked by verify_inbound).
        self.verify_inbound(inbound)
        if capability != inbound.capability:
            # An intermediary may not mutate capability while forwarding a
            # warrant that still validates on aud alone.
            raise WarrantChainError(
                f"capability downgrade at {self.identity}: "
                f"{inbound.capability!r} -> {capability!r} is not a valid exchange"
            )
        new_act = inbound.act + [self.identity]
        return Warrant(aud=next_hop, act=new_act, capability=capability)


def terminal_verify(w: Warrant, self_id: str, expected_hops: int) -> None:
    if w.aud != self_id:
        raise WarrantChainError(
            f"terminal {self_id} received token for {w.aud!r}"
        )
    if len(w.act) != expected_hops:
        # Transport path length k implies act length k+1 (origin + k hops).
        # A shorter act chain means an intermediary forwarded without exchanging.
        raise WarrantChainError(
            f"delegation chain length {len(w.act)} != expected {expected_hops}; "
            f"an intermediary forwarded a token without a fresh exchange"
        )


# --- failure trace: the passthrough that shipped ---
O = Agent("agent://orchestrator", mtls_peer="agent://orchestrator")
P = Agent("agent://planner", mtls_peer="agent://planner")
E = Agent("agent://executor", mtls_peer="agent://executor")

warrant_from_O = Warrant(
    aud="agent://executor", act=["agent://orchestrator"], capability="exec_v2"
)

# P verifies inbound against itself: aud is executor, not planner.
try:
    P.verify_inbound(warrant_from_O)
except WarrantChainError as exc:
    print("passthrough rejected:", exc)

# Correct path: P exchanges, minting a fresh token bound to E with P in act.
warrant_for_E = P.exchange(warrant_from_O, next_hop="agent://executor", capability="exec_v2")
terminal_verify(warrant_for_E, self_id="agent://executor", expected_hops=2)
print("valid chain:", warrant_for_E.act, "->", warrant_for_E.aud)

# The silent-downgrade variant: P tries to exchange but mutates capability.
try:
    P.exchange(warrant_from_O, next_hop="agent://executor", capability="exec_v1")
except WarrantChainError as exc:
    print("capability downgrade rejected:", exc)
