# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-least-privilege-attenuation-when-a-delegation-chain-is-revoked-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-least-privilege-attenuation-when-a-delegation-chain-is-revoked-mid-flight.warrant.json
# Markdown SHA-256:   c3db24ded3931670a16e6f3156d8499bb1dd36a7ed1186c6c332464319b61851
# Code AST SHA-256:   3b15d408eac55a4832c0801ca9d80e5709fbe1a09c2bf6d75cadd6a7e01605a8
# Verified Classes:   OrphanedCapabilityError, Capability, RevocationService
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class OrphanedCapabilityError(RuntimeError):
    """Raised when a capability's signed root binding cannot be resolved to a live root epoch.

    This is the fail-closed guard for the re-mint delegation regime: a token whose
    root_id/root_epoch is missing, unsigned, or points at a revoked/stale epoch is
    treated as revoked, regardless of its own signature and TTL.
    """


@dataclass(frozen=True)
class Capability:
    cap_id: str
    scope: frozenset[str]
    ttl_remaining_s: int
    issuer: str
    signature_ok: bool
    root_id: Optional[str]        # must be a SIGNED claim, not audit-only metadata
    root_epoch: Optional[int]     # epoch of the root at mint time


class RevocationService:
    def __init__(self, revoked_roots: dict[str, int]):
        # root_id -> epoch at which it was revoked (monotonic counter)
        self._revoked_roots = revoked_roots
        self._current_epoch = 0

    def current_epoch(self) -> int:
        return self._current_epoch

    def bump_epoch(self) -> int:
        self._current_epoch += 1
        return self._current_epoch

    def revoke_root(self, root_id: str) -> None:
        self._revoked_roots[root_id] = self.bump_epoch()


def verify_capability(cap: Capability, revocations: RevocationService) -> None:
    """Verify a leaf capability, enforcing BOTH attenuation and revocation continuity.

    Attenuation (scope subset) is assumed checked upstream at mint time.
    This function enforces the invariant that is violated by re-minting:
    the signed root binding must resolve to a live root epoch.
    """
    if not cap.signature_ok:
        raise OrphanedCapabilityError(f"cap {cap.cap_id}: bad signature")

    if cap.ttl_remaining_s <= 0:
        raise OrphanedCapabilityError(f"cap {cap.cap_id}: expired")

    # The seam: an audit-only parent_id would leave root_id None here.
    if cap.root_id is None or cap.root_epoch is None:
        raise OrphanedCapabilityError(
            f"cap {cap.cap_id}: no signed root binding; cannot prove revocation continuity. "
            f"Fail closed — treat as orphaned/revoked."
        )

    revoked_at = revocations._revoked_roots.get(cap.root_id)
    if revoked_at is not None and cap.root_epoch <= revoked_at:
        raise OrphanedCapabilityError(
            f"cap {cap.cap_id}: root {cap.root_id} revoked at epoch {revoked_at}, "
            f"token bound to epoch {cap.root_epoch}. Reject."
        )

    # Only reachable if root is live and token epoch postdates any revocation.
    return None


def demonstrate_orphan() -> None:
    rev = RevocationService(revoked_roots={})
    # C2 re-minted by W with audit-only parent linkage: root_id is None.
    orphan = Capability(
        cap_id="C2", scope=frozenset({"read:repo"}), ttl_remaining_s=180,
        issuer="W", signature_ok=True, root_id=None, root_epoch=None,
    )
    rev.revoke_root("C0")
    try:
        verify_capability(orphan, rev)
    except OrphanedCapabilityError as e:
        print(f"contained: {e}")


if __name__ == "__main__":
    demonstrate_orphan()
