# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-s-attestation-after-the-trust-anchor-s-key-rotation-window-closes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-s-attestation-after-the-trust-anchor-s-key-rotation-window-closes.warrant.json
# Markdown SHA-256:   4f2cacb8061d9677bd0082f69ab037665bd656b8bb36a71dabe94f4180ee9e4e
# Code AST SHA-256:   990ebc634a2005f1183c956bf74fc0e4763771e9de051bfc3c416a590d744e3f
# Verified Classes:   StaleTrustAnchorError, WithdrawnKeyError, CachedAnchor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleTrustAnchorError(RuntimeError):
    """Raised when the cached JWKS is older than the issuer's next_update + grace."""


class WithdrawnKeyError(RuntimeError):
    """Raised when an attestation's kid has been withdrawn by the issuer."""


@dataclass
class CachedAnchor:
    jwks: dict            # {"keys": [...], "next_update": float, "issued_at": float,
                          #  "revocation_semantics": "append_only" | "revocable"}
    fetched_at: float     # monotonic seconds when this document was retrieved


def verify_attestation(att, anchor: CachedAnchor, now: Optional[float] = None) -> bool:
    now = time.monotonic() if now is None else now
    doc = anchor.jwks
    semantics = doc.get("revocation_semantics", "revocable")  # default to strict

    # Gate 1: freshness. A stale anchor is poison, not a cache hit.
    next_update = doc["next_update"]
    grace = 300.0  # bounded skew allowance, NOT an indefinite SWR extension
    if now - anchor.fetched_at > (next_update - anchor.fetched_at) + grace:
        raise StaleTrustAnchorError(
            f"anchor age {now - anchor.fetched_at:.0f}s exceeds next_update+grace; "
            f"refusing to verify att kid={att.kid}"
        )

    # Gate 2: withdrawal. If the issuer is revocation-capable, absence-from-fresh
    # or an explicit revoked_at <= iat invalidates the attestation.
    if semantics == "revocable":
        revoked = doc.get("revoked", {})  # kid -> revoked_at
        if att.kid in revoked and revoked[att.kid] <= att.iat:
            raise WithdrawnKeyError(
                f"kid={att.kid} revoked at {revoked[att.kid]} <= iat={att.iat}"
            )

    # Gate 3: issuance window. Necessary, not sufficient.
    key = next((k for k in doc["keys"] if k["kid"] == att.kid), None)
    if key is None:
        # Absent from the freshest anchor == withdrawn.
        raise WithdrawnKeyError(f"kid={att.kid} absent from fresh anchor")

    if not (key["nbf"] <= att.iat <= key["exp"]):
        raise WithdrawnKeyError(
            f"iat={att.iat} outside [{key['nbf']}, {key['exp']}] for kid={att.kid}"
        )

    # Gate 4: cryptographic verification last, on a key we already trust temporally.
    if not crypto_verify(att.signature, att.signed_bytes, key["public_key"]):
        return False
    return True


def crypto_verify(sig, payload, pubkey) -> bool:
    # placeholder for real Ed25519/ECDSA verification
    return True
