# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cross-issuer-attestation-chain-when-the-leaf-credential-s-aud-claim-is-valid-but-the-issuer-s-jwks-rotatio.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cross-issuer-attestation-chain-when-the-leaf-credential-s-aud-claim-is-valid-but-the-issuer-s-jwks-rotatio.warrant.json
# Markdown SHA-256:   b9e858b03da133a9883eac9dff23b45f5b04864a131a92d7b2eab186e47bf35e
# Code AST SHA-256:   25335fc5c5fdaefe000901979bde06f42dd22b078732f5bf8b9e087ad9725f14
# Verified Classes:   TemporalAuthorityError, KeyRecord, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class TemporalAuthorityError(RuntimeError):
    """Raised when a credential's signing key was not authorized at the credential's iat."""
    pass


@dataclass(frozen=True)
class KeyRecord:
    kid: str
    nbf: float          # epoch seconds; key authorized-not-before
    exp: float          # epoch seconds; key authorized-not-after
    public_key: object


@dataclass(frozen=True)
class Warrant:
    iss: str
    aud: str
    iat: float
    exp: float
    kid: str
    signature: bytes
    payload: bytes


def verify_cross_issuer(
    warrant: Warrant,
    jwks: dict[str, KeyRecord],
    cache_observed_at: float,
    cache_stale_at: float,
    trusted_issuers: set[str],
    self_id: str,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    if warrant.iss not in trusted_issuers:
        raise TemporalAuthorityError(f"untrusted issuer {warrant.iss}")
    if warrant.aud != self_id:
        raise TemporalAuthorityError(f"audience mismatch: {warrant.aud} != {self_id}")
    if not (cache_observed_at <= now < cache_stale_at):
        raise TemporalAuthorityError("JWKS cache stale; refusing offline verification")

    key = jwks.get(warrant.kid)
    if key is None:
        raise TemporalAuthorityError(f"kid {warrant.kid} absent from JWKS")

    # Signature check omitted for brevity; assume it passed upstream.
    # The critical, non-obvious clause: anchor key authority to warrant.iat,
    # NOT to now, and NOT merely to key presence.
    if not (key.nbf <= warrant.iat < key.exp):
        raise TemporalAuthorityError(
            f"key {key.kid} authority window [{key.nbf},{key.exp}) "
            f"does not cover warrant.iat={warrant.iat}"
        )

    if warrant.exp <= now:
        raise TemporalAuthorityError(f"warrant expired at {warrant.exp}")
