# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-token-resurrection-across-mcp-egress-allowlist-renegotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-token-resurrection-across-mcp-egress-allowlist-renegotiation.warrant.json
# Markdown SHA-256:   78228f4d8f428b25b2c89aac3871178b1dd11f22635d04739629a00f839db300
# Code AST SHA-256:   20b93b541cbe177790efc8050505918fe825617de1c4304730fcb95081d68200
# Verified Classes:   CapabilityResurrectionError, CapabilityToken, EgressPolicy, EgressProxy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class CapabilityResurrectionError(RuntimeError):
    """Raised when a stale-generation capability token would authorize egress."""


@dataclass(frozen=True)
class CapabilityToken:
    resource: str          # exact FQDN, never a suffix
    audience: str
    allowlist_gen: int
    expires_at: float
    token_id: str


@dataclass
class EgressPolicy:
    allowlist_gen: int = 7
    allowed_hosts: set = field(default_factory=set)

    def mutate(self, add: Optional[str] = None, remove: Optional[str] = None) -> int:
        # Any mutation is a revocation event: advance the generation.
        if add:
            self.allowed_hosts.add(add)
        if remove:
            self.allowed_hosts.discard(remove)
        self.allowlist_gen += 1
        return self.allowlist_gen


class EgressProxy:
    def __init__(self, policy: EgressPolicy):
        self.policy = policy

    def check(self, token: CapabilityToken, dest_host: str) -> None:
        if time.time() > token.expires_at:
            raise CapabilityResurrectionError(
                f"token {token.token_id} expired"
            )
        if token.allowlist_gen != self.policy.allowlist_gen:
            # The core invariant: stale generation is dead, full stop.
            raise CapabilityResurrectionError(
                f"token {token.token_id} bound to gen {token.allowlist_gen}, "
                f"policy at gen {self.policy.allowlist_gen}; renegotiate"
            )
        if token.resource != dest_host:
            # Exact-host match only. No suffix logic.
            raise CapabilityResurrectionError(
                f"token scoped to {token.resource!r}, requested {dest_host!r}"
            )
        if dest_host not in self.policy.allowed_hosts:
            raise CapabilityResurrectionError(
                f"{dest_host} not in allowlist gen {self.policy.allowlist_gen}"
            )


def demo_resurrection_blocked() -> None:
    policy = EgressPolicy(allowed_hosts={"api.vendor-x.com"})
    token = CapabilityToken(
        resource="api.vendor-x.com",
        audience="egress",
        allowlist_gen=policy.allowlist_gen,
        expires_at=time.time() + 86400,
        token_id="cap-001",
    )
    proxy = EgressProxy(policy)

    # Operator narrows allowlist at 11:02 — generation advances.
    policy.mutate(remove="api.vendor-x.com")

    # Operator adds a mirror at 14:40 — generation advances again.
    policy.mutate(add="api.vendor-x.net")

    # Agent polls at 15:00 with the old token against the mirror.
    try:
        proxy.check(token, "api.vendor-x.net")
    except CapabilityResurrectionError as e:
        # Expected: stale generation blocks the resurrection.
        print(f"blocked: {e}")
    else:
        raise CapabilityResurrectionError(
            "INVARIANT VIOLATED: stale token authorized egress to mirror host"
        )


if __name__ == "__main__":
    demo_resurrection_blocked()
