# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-warrant-authority-when-an-mcp-to-a2a-bridge-re-signs-a-delegated-call.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-warrant-authority-when-an-mcp-to-a2a-bridge-re-signs-a-delegated-call.warrant.json
# Markdown SHA-256:   55c0838d77ac598b17fdf5b69fb2f290dae694ad8266422a765985dbe339d4ee
# Code AST SHA-256:   e0b5f44a9ad0e6e251467adc9ae9fe43f3406168e5285cdd7b2fbba6fac3e8df
# Verified Classes:   WarrantBridgeError, Warrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantBridgeError(RuntimeError):
    """Raised when an MCP-to-A2A bridge cannot preserve delegation authority."""


@dataclass
class Warrant:
    issuer: str
    subject: str
    audience: str
    scope: frozenset[str]
    expires_at: float
    chain: Optional[tuple["Warrant", ...]] = None  # embedded inbound delegation
    bridge_mode: str = "forwarded"  # "forwarded" | "resigned_with_chain"


def bridge_warrant(
    inbound: Warrant,
    callee_audience: str,
    gateway_id: str,
    gateway_ttl: float,
    now: float,
    callee_verifies_chain: bool,
) -> Warrant:
    # Condition 1: can we forward unchanged?
    if inbound.audience == callee_audience:
        return inbound  # forwarded; chain preserved by construction

    # Forwarding blocked by audience mismatch. Re-signing is the only path,
    # but it is only legal if the callee will verify the embedded chain.
    if not callee_verifies_chain:
        raise WarrantBridgeError(
            f"audience mismatch ({inbound.audience!r} != {callee_audience!r}) "
            f"and callee does not verify delegation chains; refusing to mint "
            f"a leaf-only warrant for subject {inbound.subject!r}"
        )

    # Condition 4: expiry monotonicity — never outlive the inbound delegation.
    clamped_exp = min(inbound.expires_at, now + gateway_ttl)
    if clamped_exp <= now:
        raise WarrantBridgeError(
            f"inbound warrant for {inbound.subject!r} already expired at "
            f"{inbound.expires_at}; gateway session must not extend it"
        )

    # Condition 2 + 3: embed chain, narrow scope only (here: inherit exactly,
    # never widen). A real bridge would intersect with the requested scope.
    return Warrant(
        issuer=gateway_id,
        subject=inbound.subject,
        audience=callee_audience,
        scope=inbound.scope,          # subset of inbound.scope — never invented
        expires_at=clamped_exp,
        chain=(inbound,),
        bridge_mode="resigned_with_chain",
    )


def verify_at_callee(w: Warrant, required_scope: str, now: float) -> None:
    if now >= w.expires_at:
        raise WarrantBridgeError(f"warrant expired at {w.expires_at}")
    if required_scope not in w.scope:
        raise WarrantBridgeError(
            f"scope {required_scope!r} not granted to {w.subject!r}"
        )
    if w.bridge_mode == "resigned_with_chain":
        if not w.chain:
            raise WarrantBridgeError("re-signed warrant missing delegation chain")
        # Walk the chain to a home-root-issued leaf; scope and expiry must be
        # non-increasing at every hop.
        prev = w
        for hop in w.chain:
            if not hop.scope.issuperset(prev.scope):
                raise WarrantBridgeError("scope widened across delegation hop")
            if hop.expires_at > prev.expires_at:
                raise WarrantBridgeError("expiry extended across delegation hop")
            prev = hop
