# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-scope-widening-in-mcp-delegation-chains-when-revocation-races-a-cached-capability-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-scope-widening-in-mcp-delegation-chains-when-revocation-races-a-cached-capability-grant.warrant.json
# Markdown SHA-256:   c2e5e1f83426d7788c477dae9c476df64e5390e50dd15df2de47fe2517f2241c
# Code AST SHA-256:   02f36f2bc5db4e8115181a63c35860600779c6566470efcc1662d6d64ce1e9bf
# Verified Classes:   StaleRootAuthorityError, Grant, RootLivenessOracle
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class StaleRootAuthorityError(RuntimeError):
    """Raised when a delegated grant cannot prove live root authority within Δ."""
    pass


@dataclass
class Grant:
    grant_id: str
    parent_id: Optional[str]
    scope: frozenset
    signature_chain_valid: bool
    minted_at: float
    ttl: float
    revoked_at: Optional[float] = None


@dataclass
class RootLivenessOracle:
    """Authoritative source of root liveness. Must be consulted within Δ."""
    revoked_ids: set = field(default_factory=set)

    def root_alive(self, root_id: str, now: float) -> Optional[bool]:
        # Returns True/False, or None if unreachable (unknown liveness).
        return root_id not in self.revoked_ids


MAX_STALENESS_DELTA = 5.0  # seconds; must be < min hop TTL


def authorize_use(
    grant: Grant,
    root_id: str,
    oracle: RootLivenessOracle,
    now: float,
    last_root_check: Optional[float],
) -> None:
    # 1. Structural checks (local, cheap).
    if not grant.signature_chain_valid:
        raise StaleRootAuthorityError(f"{grant.grant_id}: broken signature chain")
    if now - grant.minted_at > grant.ttl:
        raise StaleRootAuthorityError(f"{grant.grant_id}: grant TTL expired")
    if grant.revoked_at is not None and grant.revoked_at <= now:
        raise StaleRootAuthorityError(f"{grant.grant_id}: locally revoked")

    # 2. Root liveness within Δ. Narrow scope does NOT substitute for this.
    if last_root_check is None or (now - last_root_check) > MAX_STALENESS_DELTA:
        alive = oracle.root_alive(root_id, now)
        if alive is None:
            # Unknown liveness => deny, even for a single-file scope.
            raise StaleRootAuthorityError(
                f"{grant.grant_id}: root liveness unknown; scope={sorted(grant.scope)} "
                f"is attenuated but unproven — deny by default"
            )
        if alive is False:
            raise StaleRootAuthorityError(
                f"{grant.grant_id}: root {root_id} revoked; attenuation cannot resurrect authority"
            )
    # else: recent liveness proof within Δ, proceed.
