# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-keep-honoring-a-revoked-warrant-after-key-rotation-and-what-the-audit-trail-hides-about-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-keep-honoring-a-revoked-warrant-after-key-rotation-and-what-the-audit-trail-hides-about-it.warrant.json
# Markdown SHA-256:   f516317956cde14f37b8b804158d6af21452bf4eb1787cda2263508821c15d38
# Code AST SHA-256:   ed35507a8d65e5828d32ad1525740aa0dc6aa0fe98f0082fbfc624e809cf5437
# Verified Classes:   KeyStatus, KeyRecord, Warrant, AuthorizationInvalid
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class KeyStatus(Enum):
    ACTIVE = "active"
    RETIRED = "retired"


@dataclass(frozen=True)
class KeyRecord:
    kid: str
    status: KeyStatus
    valid_until_epoch: int


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    kid: str
    issued_at: float
    expires_at: float
    revocation_epoch: int


class AuthorizationInvalid(RuntimeError):
    """Raised when a warrant's signature verifies but its authorization does not."""


def authorize(
    warrant: Warrant,
    key: KeyRecord,
    current_revocation_epoch: int,
    now: float,
    jwks_cache_age_s: float,
) -> None:
    # Clause 1: not expired.
    if now >= warrant.expires_at:
        raise AuthorizationInvalid(
            f"warrant {warrant.warrant_id} expired at {warrant.expires_at}"
        )

    # Clause 2: not swept by a revocation newer than the warrant's epoch.
    if warrant.revocation_epoch < current_revocation_epoch:
        raise AuthorizationInvalid(
            f"warrant {warrant.warrant_id} claims epoch {warrant.revocation_epoch} "
            f"but current epoch is {current_revocation_epoch}"
        )

    # Clause 3: the signing key must have been in good standing at the
    # warrant's claimed revocation epoch. A retired key cannot vouch for a
    # warrant at an epoch after its own retirement, even with a valid sig.
    if key.status is KeyStatus.RETIRED and key.valid_until_epoch < warrant.revocation_epoch:
        raise AuthorizationInvalid(
            f"warrant {warrant.warrant_id} signed by retired key {key.kid} "
            f"(valid_until_epoch={key.valid_until_epoch}) but claims "
            f"revocation_epoch={warrant.revocation_epoch}"
        )

    # Clause 4: surface cache staleness so replay can distinguish
    # "verifier was wrong" from "verifier was right as of stale data".
    if jwks_cache_age_s > 0:
        # Caller is responsible for logging this; we only refuse to hide it.
        pass


def check_chain(warrants, keys_by_kid, current_epoch, now, cache_age):
    for w in warrants:
        key = keys_by_kid.get(w.kid)
        if key is None:
            raise AuthorizationInvalid(f"no key record for kid {w.kid}")
        authorize(w, key, current_epoch, now, cache_age)


if __name__ == "__main__":
    # Reproduces the orch-7 trace: sig valid, authorization dead.
    keys = {
        "k-2024": KeyRecord("k-2024", KeyStatus.RETIRED, valid_until_epoch=880),
        "k-2025": KeyRecord("k-2025", KeyStatus.ACTIVE, valid_until_epoch=10**9),
    }
    stale = Warrant(
        warrant_id="w-orch7-001",
        kid="k-2024",
        issued_at=time.time() - 3600,
        expires_at=time.time() + 72 * 3600,
        revocation_epoch=880,
    )
    check_chain([stale], keys, current_epoch=881, now=time.time(), cache_age=42.0)
