# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-delegated-capability-token-from-surviving-its-issuer-s-key-rotation-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-delegated-capability-token-from-surviving-its-issuer-s-key-rotation-mid-flight.warrant.json
# Markdown SHA-256:   b230777890cda4fed3f4534d5d174f528e4fb7b3c1fa312c7f4952fe6192cffc
# Code AST SHA-256:   f42f52ac7e2f2fbfe26416ab7362b51914f9100d1b01227f6643b9fba8334fe9
# Verified Classes:   AnchorStalenessExceededTokenLife, CapabilityToken, TrustAnchor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AnchorStalenessExceededTokenLife(RuntimeError):
    """Raised when the verifier's cached trust anchor for an issuer key is
    older than the token's remaining validity, meaning a rotation between
    anchor refresh and verification would be invisible to the verifier."""
    pass


@dataclass
class CapabilityToken:
    issuer_key_id: str
    issued_at: float
    ttl_seconds: float

    def remaining_ttl(self, now: float) -> float:
        return max(0.0, (self.issued_at + self.ttl_seconds) - now)


@dataclass
class TrustAnchor:
    issuer_key_id: str
    fetched_at: float
    status: str  # "current" | "retired_honored" | "retired_revoked"


def verify_delegated_capability(
    token: CapabilityToken,
    anchor: TrustAnchor,
    now: float,
    max_anchor_age_seconds: float,
) -> None:
    if anchor.issuer_key_id != token.issuer_key_id:
        raise AnchorStalenessExceededTokenLife(
            f"anchor key {anchor.issuer_key_id} does not match token key "
            f"{token.issuer_key_id}; chain cannot resolve"
        )

    if anchor.status == "retired_revoked":
        raise AnchorStalenessExceededTokenLife(
            f"signing key {anchor.issuer_key_id} is retired and revoked; "
            f"every token chained beneath it is invalid regardless of TTL"
        )

    remaining = token.remaining_ttl(now)
    anchor_age = now - anchor.fetched_at

    # The coupling invariant: a stale anchor must not outlive the token's
    # remaining life, or a rotation between fetch and verify is invisible.
    effective_anchor_age = min(anchor_age, max_anchor_age_seconds)
    if effective_anchor_age > remaining:
        raise AnchorStalenessExceededTokenLife(
            f"anchor age {anchor_age:.1f}s (capped {effective_anchor_age:.1f}s) "
            f"exceeds token remaining TTL {remaining:.1f}s for key "
            f"{anchor.issuer_key_id}; force re-fetch or refuse"
        )

    if anchor.status == "retired_honored" and anchor_age > remaining:
        raise AnchorStalenessExceededTokenLife(
            f"key {anchor.issuer_key_id} retired-honored but anchor is stale; "
            f"cannot confirm token predates the retirement boundary"
        )
