# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-capability-token-replay-window-collapse-when-delegated-warrants-outlive-the-signing-key-s-rotation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-capability-token-replay-window-collapse-when-delegated-warrants-outlive-the-signing-key-s-rotation-epoch.warrant.json
# Markdown SHA-256:   00b38dfe4277ca425a492a559800253b31392f96c596c52e66c1a9ffc205c579
# Code AST SHA-256:   7d7d6d04c2434f58ec13260e623a928648707fe99e0559a0a6ffe3becfac589d
# Verified Classes:   StaleAuthorityWindowError, ReplayUnpinnedError, KeyResolution, DelegatedCapabilityToken, AAIFVerifier
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAuthorityWindowError(RuntimeError):
    """Raised when a delegated capability token would be honored under a
    signing key whose resolution is older than the issuer's declared
    rotation period, collapsing the token-validity / key-authority windows."""
    pass


class ReplayUnpinnedError(RuntimeError):
    """Raised when an authorization decision is recorded without a pinned
    key-set version, making the decision non-replayable by an auditor."""
    pass


@dataclass(frozen=True)
class KeyResolution:
    key_id: str
    epoch_end: float          # issuer's authority end for this key
    resolved_at: float        # when the verifier fetched this key
    jwks_version: str         # pinned snapshot identifier


@dataclass(frozen=True)
class DelegatedCapabilityToken:
    signing_key_id: str
    not_before: float
    not_after: float
    scope: frozenset


class AAIFVerifier:
    def __init__(self, max_key_age: float):
        # max_key_age MUST be < the issuer's minimum rotation period.
        if max_key_age <= 0:
            raise ValueError("max_key_age must be positive")
        self.max_key_age = max_key_age

    def verify(
        self,
        token: DelegatedCapabilityToken,
        resolution: KeyResolution,
        requested_scope: frozenset,
        now: float,
    ) -> dict:
        # 1. Temporal validity of the token itself.
        if not (token.not_before <= now <= token.not_after):
            raise StaleAuthorityWindowError(
                f"token outside temporal validity at {now}"
            )

        # 2. Key-resolution freshness: the load-bearing invariant.
        age = now - resolution.resolved_at
        if age > self.max_key_age:
            raise StaleAuthorityWindowError(
                f"signing key {resolution.key_id} resolved {age:.1f}s ago, "
                f"exceeds max_key_age={self.max_key_age:.1f}s; "
                f"authority cannot be confirmed current"
            )

        # 3. Epoch-bounded authority: the key must still hold authority at
        #    verification time, per the issuer's current manifest.
        if now > resolution.epoch_end:
            raise StaleAuthorityWindowError(
                f"signing key {resolution.key_id} authority ended at "
                f"{resolution.epoch_end}, verification at {now}; "
                f"token.not_after={token.not_after} exceeds key epoch"
            )

        # 4. Scope containment.
        if not requested_scope.issubset(token.scope):
            raise StaleAuthorityWindowError(
                f"requested scope {requested_scope} not within {token.scope}"
            )

        # 5. Pin the key-set version so the decision is replayable.
        if not resolution.jwks_version:
            raise ReplayUnpinnedError(
                "authorization decision recorded without a pinned "
                "jwks_version; audit replay would resolve a different key set"
            )

        # Effective authority is clamped to the tighter of token and key.
        effective_end = min(token.not_after, resolution.epoch_end)
        return {
            "admitted": True,
            "effective_not_after": effective_end,
            "jwks_version": resolution.jwks_version,
            "clamped": effective_end < token.not_after,
        }


# --- demonstration of the collapse window ---
def _demo() -> None:
    now = 1_000_000.0
    token = DelegatedCapabilityToken(
        signing_key_id="key_v1",
        not_before=now - 60,
        not_after=now + 6 * 3600,   # 6h token
        scope=frozenset({"filesystem:read"}),
    )
    # Key rotated at now+90m; verifier resolved it 30m ago.
    resolution = KeyResolution(
        key_id="key_v1",
        epoch_end=now + 90 * 60,
        resolved_at=now - 30 * 60,
        jwks_version="jwks-2025-06-13T00:00Z",
    )
    verifier = AAIFVerifier(max_key_age=3600.0)

    # At t=3h the token is still temporally valid, but the key's authority
    # ended at t+90m. This must raise, not admit.
    try:
        verifier.verify(token, resolution, frozenset({"filesystem:read"}), now + 3 * 3600)
    except StaleAuthorityWindowError as e:
        print(f"collapse window detected: {e}")


if __name__ == "__main__":
    _demo()
