# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-capability-warrant-when-a-peer-s-attestation-ttl-expires-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-capability-warrant-when-a-peer-s-attestation-ttl-expires-mid-handoff.warrant.json
# Markdown SHA-256:   1994105fa6c1dad6c4b388bff4bf78be5eeafaa6dd182f21ccdcf4d2fe548b65
# Code AST SHA-256:   1795730a30453d2f0525e4daf4568866874683240ba618d37bf8c584d0316dfa
# Verified Classes:   StaleWarrantError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when a privileged action is attempted under a warrant whose
    temporal validity has lapsed at the moment of execution, or when
    re-verification is indeterminate and the caller would otherwise
    fail open on a cached grant."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    issuer: str
    scopes: frozenset
    issued_at: float
    not_after: float
    nonce: str
    signature: str


def verify_signature(w: Warrant, issuer_key: str) -> bool:
    # Stand-in for real asymmetric verification; must be deterministic.
    return w.signature == f"{issuer_key}:{w.nonce}"


def fetch_current_warrant(issuer: str, nonce: str):
    """Returns the issuer's current view of the warrant, or None if the
    issuer has GC'd it (which is itself a signal of expiry)."""
    # In production this is a network call that may 404 or time out.
    return None


def authorize_action(
    cached: Warrant,
    action_scope: str,
    issuer_key: str,
    clock_skew_tolerance: float = 30.0,
) -> None:
    now = time.time()

    # 1. Signature is necessary but never sufficient.
    if not verify_signature(cached, issuer_key):
        raise StaleWarrantError(
            f"signature invalid for warrant {cached.nonce}"
        )

    # 2. Temporal re-check AT ACTION TIME, not receipt time.
    if now >= cached.not_after:
        raise StaleWarrantError(
            f"warrant {cached.nonce} expired at {cached.not_after:.0f}, "
            f"action attempted at {now:.0f} under scope {action_scope!r}"
        )

    # 3. Clock-skew bound: a warrant issued "in the future" relative to
    #    local time is untrustworthy and must not be honored.
    if cached.issued_at - now > clock_skew_tolerance:
        raise StaleWarrantError(
            f"warrant {cached.nonce} issued_at {cached.issued_at:.0f} "
            f"exceeds local now {now:.0f} by more than skew tolerance"
        )

    # 4. Scope containment at action granularity.
    if action_scope not in cached.scopes:
        raise StaleWarrantError(
            f"scope {action_scope!r} not granted by warrant {cached.nonce}"
        )

    # 5. Re-verify against issuer; fail CLOSED on indeterminate.
    current = fetch_current_warrant(cached.issuer, cached.nonce)
    if current is None:
        # Issuer GC'd the warrant or is unreachable. Do NOT proceed on
        # the cached copy — this is the fail-open trap.
        raise StaleWarrantError(
            f"warrant {cached.nonce} no longer resolvable at issuer "
            f"{cached.issuer!r}; refusing action under stale grant"
        )
    if current.not_after != cached.not_after:
        raise StaleWarrantError(
            f"warrant {cached.nonce} validity window mutated at issuer"
        )
