# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stale-delegated-warrants-from-resurrecting-revoked-agent-identity-across-federated-trust-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stale-delegated-warrants-from-resurrecting-revoked-agent-identity-across-federated-trust-boundaries.warrant.json
# Markdown SHA-256:   6570fec87d119366e8c831243dd74e065e42349252af4d092680d0fad88fe6ff
# Code AST SHA-256:   b22cf801b1f08accaa7aad53b01383286f19b4c1c949f0c811b62f573f37a939
# Verified Classes:   WarrantResurrectionError, Warrant, KeyRegistry
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class WarrantResurrectionError(RuntimeError):
    """Raised when a warrant validates but names a superseded/revoked key."""
    pass


@dataclass
class Warrant:
    subject: str
    key_id: str
    capability: str
    minted_at: float
    expires_at: float
    delegation_chain: tuple = ()


@dataclass
class KeyRegistry:
    # subject -> (current_key_id, rotated_at)
    current: dict = field(default_factory=dict)
    revoked_key_ids: set = field(default_factory=set)

    def resolve_current_key(self, subject: str) -> str:
        entry = self.current.get(subject)
        if entry is None:
            raise WarrantResurrectionError(f"no key registered for subject {subject!r}")
        return entry[0]


def authorize(
    warrant: Warrant,
    presented_key_id: str,
    registry: KeyRegistry,
    now: float | None = None,
    max_registry_skew_s: float = 30.0,
) -> bool:
    now = time.time() if now is None else now

    # 1. Temporal validity of the warrant itself.
    if not (warrant.minted_at <= now < warrant.expires_at):
        raise WarrantResurrectionError(
            f"warrant for {warrant.subject!r} outside validity window"
        )

    # 2. Subject binding must match the presented key.
    if warrant.key_id != presented_key_id:
        raise WarrantResurrectionError(
            f"presented key {presented_key_id!r} does not match warrant binding "
            f"{warrant.key_id!r}"
        )

    # 3. THE MISSING CONJUNCT: key-currency resolution at verification time.
    if presented_key_id in registry.revoked_key_ids:
        raise WarrantResurrectionError(
            f"key {presented_key_id!r} for subject {warrant.subject!r} is revoked; "
            f"warrant is a stale delegation and must not authorize"
        )
    current_key = registry.resolve_current_key(warrant.subject)
    if current_key != presented_key_id:
        raise WarrantResurrectionError(
            f"key {presented_key_id!r} is superseded by {current_key!r} for "
            f"subject {warrant.subject!r}; re-mint required"
        )

    # 4. Delegation-chain revocation must be resolved at the last hop.
    for hop_key in warrant.delegation_chain:
        if hop_key in registry.revoked_key_ids:
            raise WarrantResurrectionError(
                f"delegation hop {hop_key!r} revoked in chain for "
                f"{warrant.subject!r}"
            )

    return True


def demo_resurrection():
    reg = KeyRegistry()
    reg.current["agent:worker-7"] = ("key-v1", 0.0)
    t0 = 1_000_000.0
    w = Warrant(
        subject="agent:worker-7",
        key_id="key-v1",
        capability="write",
        minted_at=t0,
        expires_at=t0 + 6 * 3600,
        delegation_chain=("delegate:mid-3",),
    )
    # Rotation: v1 revoked, v2 current.
    reg.revoked_key_ids.add("key-v1")
    reg.current["agent:worker-7"] = ("key-v2", t0 + 1800)

    # Attacker replays the old warrant with the revoked key.
    try:
        authorize(w, presented_key_id="key-v1", registry=reg, now=t0 + 2700)
    except WarrantResurrectionError as e:
        print(f"BLOCKED (correct): {e}")

    # Legitimate holder with rotated key presents a fresh warrant.
    w2 = Warrant(
        subject="agent:worker-7",
        key_id="key-v2",
        capability="write",
        minted_at=t0 + 1800,
        expires_at=t0 + 1800 + 3600,
        delegation_chain=("delegate:mid-3",),
    )
    assert authorize(w2, presented_key_id="key-v2", registry=reg, now=t0 + 2700)
    print("ALLOWED (correct): rotated key with fresh warrant")


if __name__ == "__main__":
    demo_resurrection()
