# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-keeps-a-rotated-aaif-credential-past-its-warrant-revocation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-keeps-a-rotated-aaif-credential-past-its-warrant-revocation-epoch.warrant.json
# Markdown SHA-256:   841918aa1334f940dadb0aba80e50fce9521981655d4b5f2eae3f8174997cb83
# Code AST SHA-256:   4bcac0978c75aab22bd34ce126f6d018a0f2b5dc090633fb9a798c88ba6b131e
# Verified Classes:   WarrantRevocationAmbiguity, KeyRing, RevocationList
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class WarrantRevocationAmbiguity(RuntimeError):
    """Raised when a verifier cannot establish a trusted, current revocation state
    for a presented AAIF warrant and would otherwise fall back to stale trust."""


@dataclass
class KeyRing:
    current_kid: str
    valid_kids: set[str] = field(default_factory=set)


@dataclass
class RevocationList:
    version: int
    signing_kid: str
    revoked: set[str]
    published_at: float
    ttl: float

    def expired(self, now: float) -> bool:
        return (now - self.published_at) > self.ttl


def verify_warrant(
    warrant_id: str,
    warrant_signing_kid: str,
    keyring: KeyRing,
    wl: RevocationList,
    now: float,
) -> str:
    # 1. Credential surface: warrant signature must reference a live key.
    if warrant_signing_kid not in keyring.valid_kids:
        raise WarrantRevocationAmbiguity(
            f"warrant {warrant_id}: signing kid {warrant_signing_kid} not in JWKS"
        )

    # 2. Revocation surface: the WRL we hold must be signed by a live key.
    if wl.signing_kid not in keyring.valid_kids:
        raise WarrantRevocationAmbiguity(
            f"warrant {warrant_id}: WRL v{wl.version} signed by untrusted kid "
            f"{wl.signing_kid}"
        )

    # 3. The phase-lock invariant: if we gate on current-kid, a non-current-signed
    #    WRL is NOT a license to fall back to a cached older WRL. Defer instead.
    if wl.signing_kid != keyring.current_kid:
        raise WarrantRevocationAmbiguity(
            f"warrant {warrant_id}: WRL v{wl.version} signed by non-current kid "
            f"{wl.signing_kid} (current={keyring.current_kid}); "
            f"revocation state is ambiguous under key rotation — defer, do not fall back"
        )

    # 4. Freshness: a trusted-but-expired WRL is still not authoritative.
    if wl.expired(now):
        raise WarrantRevocationAmbiguity(
            f"warrant {warrant_id}: WRL v{wl.version} expired at "
            f"{wl.published_at + wl.ttl:.0f}"
        )

    if warrant_id in wl.revoked:
        return "reject:revoked"
    return "accept"


# Replay of the observed failure: rotation at t=24h leaves v88 old-key-signed,
# verifier gated on current-kid, cached v85 is expired-but-trusted.
if __name__ == "__main__":
    now = 30 * 3600
    ring = KeyRing(current_kid="a-0611", valid_kids={"a-0610", "a-0611"})
    wl_v88 = RevocationList(88, "a-0610", {"W-4471"}, published_at=20 * 3600, ttl=12 * 3600)
    try:
        print(verify_warrant("W-4471", "a-0610", ring, wl_v88, now))
    except WarrantRevocationAmbiguity as e:
        print(f"DEFER (correct): {e}")
