# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-valid-looking-capability-token-at-the-moment-of-delegation-chain-re-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-valid-looking-capability-token-at-the-moment-of-delegation-chain-re-verification.warrant.json
# Markdown SHA-256:   9895b941dbee6fa10b27b960a9f2186874cafefc7656f009d867e7d275ebce7b
# Code AST SHA-256:   c26aba767a15922091dd565bbb982ef8aa810c4029acb87c578ad0d4afd1fdbe
# Verified Classes:   DelegationAuthorityWithdrawn, ChainWideningDetected, CapabilityToken, RootDocument
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class DelegationAuthorityWithdrawn(RuntimeError):
    """Raised when a capability token's signature is valid but the signing
    verification method is no longer authorized in the live delegation root."""
    pass


class ChainWideningDetected(RuntimeError):
    """Raised when any hop's scope is not a subset of its parent's scope."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    token_hash: str
    issuer_did: str
    signing_key_id: str          # e.g. "#key-1"
    scope: frozenset[str]
    parent_scope: Optional[frozenset[str]]
    max_revocation_age_s: int


@dataclass(frozen=True)
class RootDocument:
    did: str
    version: str                 # changes on any rotation / controller edit
    delegation_keys: frozenset[str]
    cache_max_age_s: int


def verify_at_use_time(
    token: CapabilityToken,
    live_root: RootDocument,
    cached_verdict: Optional[tuple[str, str]],  # (token_hash, root_version)
    requested_scope: str,
    operation_is_destructive: bool,
    resolution_ok: bool,
) -> bool:
    # 1. Scope containment (token-local, cheap, always first).
    if token.parent_scope is not None and not token.scope.issubset(token.parent_scope):
        raise ChainWideningDetected(
            f"hop scope {sorted(token.scope)} is not a subset of parent "
            f"{sorted(token.parent_scope)}; refusing to clamp"
        )
    if requested_scope not in token.scope:
        return False

    # 2. Resolution must have succeeded for destructive ops.
    if not resolution_ok:
        if operation_is_destructive:
            raise DelegationAuthorityWithdrawn(
                f"cannot resolve {token.issuer_did} at use time; "
                f"failing closed for destructive scope {requested_scope!r}"
            )
        return False  # read-only fail-open only if token explicitly allows; default deny

    # 3. Live delegation-root liveness — the boundary condition.
    if live_root.did != token.issuer_did:
        raise DelegationAuthorityWithdrawn(
            f"root document DID {live_root.did} does not match token issuer "
            f"{token.issuer_did}"
        )
    if token.signing_key_id not in live_root.delegation_keys:
        raise DelegationAuthorityWithdrawn(
            f"signing key {token.signing_key_id} is no longer in the live "
            f"delegation set of {live_root.did} (version {live_root.version}); "
            f"token is a valid signature over withdrawn authority"
        )

    # 4. Verdict cache is only valid for the root version it was computed against.
    if cached_verdict is not None:
        cached_hash, cached_root_version = cached_verdict
        if cached_hash == token.token_hash and cached_root_version == live_root.version:
            return True
        # root version changed -> cached verdict is stale regardless of TTL

    # 5. Revocation freshness bound must come from the token, not the verifier.
    if live_root.cache_max_age_s > token.max_revocation_age_s:
        raise DelegationAuthorityWithdrawn(
            f"root cache age {live_root.cache_max_age_s}s exceeds token "
            f"max_revocation_age {token.max_revocation_age_s}s; cannot confirm freshness"
        )

    return True
