# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-silently-outlived-its-issuer-s-trust-root-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-capability-token-has-silently-outlived-its-issuer-s-trust-root-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   3096c50f5a8403af0333ee73375c68414ee9b8353dac12d064657bb1d568efe1
# Code AST SHA-256:   d57746b828d7d3457d78cd5d7d009b74c454beb7e31321036027caa651378f0f
# Verified Classes:   StaleTrustRootError, CapabilityToken, IssuerTrustView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleTrustRootError(RuntimeError):
    """Raised when a capability token's signing-key epoch cannot be proven current."""


@dataclass(frozen=True)
class CapabilityToken:
    issuer: str
    signing_key_epoch: int      # epoch of the key that signed this token
    issued_at: float            # token.iat
    expires_at: float           # token.exp
    scope: str


@dataclass(frozen=True)
class IssuerTrustView:
    issuer: str
    live_key_epoch: int         # highest epoch the issuer currently considers live
    fetched_at: float           # when the verifier last re-anchored
    revocation_epoch: int       # issuer's revocation-list epoch at fetch time


def verify_capability(
    token: CapabilityToken,
    cached_view: IssuerTrustView,
    *,
    now: float,
    max_staleness: float,
    clock_skew: float,
    refetch,  # callable(issuer) -> IssuerTrustView | None
) -> bool:
    if now > token.expires_at:
        raise StaleTrustRootError("token expired")

    # The verifier must re-anchor if its view is older than the staleness bound.
    view = cached_view
    if now - view.fetched_at > max_staleness:
        fresh = refetch(token.issuer)
        if fresh is None:
            # Fail closed: a stale cache is exactly the blind spot.
            raise StaleTrustRootError(
                f"cannot re-anchor trust root for {token.issuer}; refusing stale cache"
            )
        view = fresh

    # The token's signing-key epoch must be provably live in the current view.
    if token.signing_key_epoch < view.revocation_epoch:
        raise StaleTrustRootError(
            f"token signed by revoked epoch {token.signing_key_epoch} "
            f"(issuer revocation epoch {view.revocation_epoch})"
        )
    if token.signing_key_epoch > view.live_key_epoch:
        raise StaleTrustRootError(
            f"token epoch {token.signing_key_epoch} unknown to verifier "
            f"(live epoch {view.live_key_epoch})"
        )

    # Clock-skew band: if issuance and rotation are indistinguishable, treat
    # the token as post-rotation and require a fresh anchor.
    if abs(token.issued_at - view.fetched_at) <= clock_skew:
        fresh = refetch(token.issuer)
        if fresh is None or fresh.revocation_epoch != view.revocation_epoch:
            raise StaleTrustRootError(
                "issuance within clock-skew band of rotation; cannot order events"
            )

    return True
