# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-warrant-replay-across-trust-brokered-federation-boundaries-when-brokered-tokens-outlive-the-delegating-agent-s-aut.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-warrant-replay-across-trust-brokered-federation-boundaries-when-brokered-tokens-outlive-the-delegating-agent-s-aut.warrant.json
# Markdown SHA-256:   0d431e056a9258ec89c6687a54a3a36ba0d5d4d4f18f096f04b22e447cf32d74
# Code AST SHA-256:   5f2b6b89d9956aa9ca4b51f83d25d45493baf48f429b1bc19628a3b7988d4973
# Verified Classes:   WarrantLineageError, Warrant, FederationLedger
# Defensive Guards:   12 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class WarrantLineageError(RuntimeError):
    """Raised when a brokered warrant's delegator authority cannot be
    confirmed live at presentation time, or when a re-delegation would
    launder a revoked ancestor out of the verifier's view."""


@dataclass
class Warrant:
    warrant_id: str
    delegator: str
    scope: str
    issued_at: float
    exp: float
    parent_id: Optional[str] = None
    chain: tuple = field(default_factory=tuple)  # (root, ..., delegator)


class FederationLedger:
    """Broker-side lineage ledger: every mint records parent, every
    revocation walks descendants. This is the invariant that bounds the
    revocation shadow to zero for brokered chains."""

    def __init__(self) -> None:
        self._warrants: dict[str, Warrant] = {}
        self._revoked: set[str] = set()
        self._children: dict[str, set[str]] = {}

    def mint(
        self,
        warrant_id: str,
        delegator: str,
        scope: str,
        exp: float,
        parent_id: Optional[str] = None,
        delegator_live: bool = True,
    ) -> Warrant:
        if not delegator_live:
            raise WarrantLineageError(
                f"refusing to mint {warrant_id}: delegator {delegator} not live"
            )
        if parent_id is not None:
            parent = self._warrants.get(parent_id)
            if parent is None:
                raise WarrantLineageError(
                    f"refusing to mint {warrant_id}: unknown parent {parent_id}"
                )
            if parent_id in self._revoked:
                raise WarrantLineageError(
                    f"refusing to mint {warrant_id}: parent {parent_id} revoked"
                )
            if not _scope_subset(scope, parent.scope):
                raise WarrantLineageError(
                    f"scope escalation: {scope} not subset of {parent.scope}"
                )
            chain = parent.chain + (delegator,)
        else:
            chain = (delegator,)

        w = Warrant(
            warrant_id=warrant_id,
            delegator=delegator,
            scope=scope,
            issued_at=time.time(),
            exp=exp,
            parent_id=parent_id,
            chain=chain,
        )
        self._warrants[warrant_id] = w
        if parent_id is not None:
            self._children.setdefault(parent_id, set()).add(warrant_id)
        return w

    def revoke(self, warrant_id: str) -> set[str]:
        """Revoke a warrant and every descendant. Returns the full set of
        withdrawn IDs so verifiers can update their CRL."""
        if warrant_id not in self._warrants:
            raise WarrantLineageError(f"cannot revoke unknown warrant {warrant_id}")
        withdrawn: set[str] = set()
        stack = [warrant_id]
        while stack:
            wid = stack.pop()
            if wid in self._revoked:
                continue
            self._revoked.add(wid)
            withdrawn.add(wid)
            stack.extend(self._children.get(wid, ()))
        return withdrawn

    def verify(self, warrant_id: str, now: Optional[float] = None) -> None:
        """Verifier-side check. Fails closed on any lineage or liveness gap."""
        now = time.time() if now is None else now
        w = self._warrants.get(warrant_id)
        if w is None:
            raise WarrantLineageError(f"unknown warrant {warrant_id}")
        if now > w.exp:
            raise WarrantLineageError(f"warrant {warrant_id} expired at {w.exp}")
        if warrant_id in self._revoked:
            raise WarrantLineageError(f"warrant {warrant_id} revoked")
        # Walk the chain: every ancestor must be present and unrevoked.
        cursor = w.parent_id
        while cursor is not None:
            if cursor in self._revoked:
                raise WarrantLineageError(
                    f"warrant {warrant_id} has revoked ancestor {cursor}"
                )
            ancestor = self._warrants.get(cursor)
            if ancestor is None:
                raise WarrantLineageError(
                    f"warrant {warrant_id} has missing ancestor {cursor}"
                )
            cursor = ancestor.parent_id


def _scope_subset(child: str, parent: str) -> bool:
    """Attenuation must be monotone: child scope is a subset of parent."""
    c = set(child.split(":"))
    p = set(parent.split(":"))
    return c.issubset(p)


def demonstrate_failure() -> None:
    ledger = FederationLedger()
    # t=0: root grant for A/planner, then attenuate to A/executor.
    ledger.mint("G_root", "A/planner", "resource:C:read", exp=time.time() + 3600)
    w1 = ledger.mint(
        "W_1", "A/executor", "audit:submit",
        exp=time.time() + 900, parent_id="G_root",
    )
    # t=120: root revoked; lineage walk withdraws W_1 too.
    withdrawn = ledger.revoke("G_root")
    if "W_1" not in withdrawn:
        raise WarrantLineageError("lineage walk missed descendant W_1")
    # t=300: A/executor presents W_1 to B/auditor -> must fail closed.
    try:
        ledger.verify(w1.warrant_id)
    except WarrantLineageError as exc:
        print(f"correctly rejected: {exc}")
        return
    raise WarrantLineageError(
        "invariant violated: revoked-ancestor warrant verified as live"
    )


if __name__ == "__main__":
    demonstrate_failure()
