# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-delegated-authorization-chain-silently-outlive-its-issuer-s-revocation-when-aaif-attestation-is-cached-per-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-delegated-authorization-chain-silently-outlive-its-issuer-s-revocation-when-aaif-attestation-is-cached-per-hop.warrant.json
# Markdown SHA-256:   d662c3a49660d99ef30c6b42255f7eeb8973ac88ceed80ed7b6dad9f29aeed6e
# Code AST SHA-256:   e122b419bf4e3697112d7f672c0f169bf1c20b0f3a37e862d900047e2ee18d80
# Verified Classes:   StaleAttestationChainError, Attestation, DelegatedToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleAttestationChainError(RuntimeError):
    """Raised when a delegated chain's root attestation cannot be proven live
    within the revocation SLA at presentation time."""
    pass


@dataclass
class Attestation:
    key_id: str
    nonce: str
    epoch: int
    valid: Optional[bool]  # None = unknown response shape


@dataclass
class DelegatedToken:
    issuer_key_id: str
    subject: str
    ttl_seconds: int
    embedded_chain: list[Attestation]


REVOCATION_SLA_SECONDS = 60


def validate_chain_at_presentation(
    token: DelegatedToken,
    now: int,
    fetch_root_epoch,
    fetch_attestation,
) -> None:
    if not token.embedded_chain:
        raise StaleAttestationChainError(
            f"token for {token.subject} carries no attestation chain"
        )

    root = token.embedded_chain[0]
    current_epoch = fetch_root_epoch(root.key_id)

    # Freshness proof: the root's epoch must match the issuer's current epoch.
    # A mismatch means the chain was minted against a superseded root.
    if root.epoch != current_epoch:
        raise StaleAttestationChainError(
            f"root attestation epoch {root.epoch} != issuer epoch "
            f"{current_epoch} for key {root.key_id}; chain minted pre-revocation"
        )

    # Re-verify the root against the revocation endpoint, keyed on nonce,
    # not key_id — key_id caches collide across attestation instances.
    live = fetch_attestation(root.key_id, root.nonce)
    if live is None:
        raise StaleAttestationChainError(
            f"revocation endpoint returned no record for nonce {root.nonce}"
        )
    if live.valid is not True:
        # Any non-True (False or None) fails closed. This is the guardrail
        # against the observed schema-mismatch bug.
        raise StaleAttestationChainError(
            f"root attestation {root.nonce} not live: valid={live.valid!r}"
        )

    # Every intermediate hop must be within the revocation SLA of its
    # delegation time; we approximate that by requiring each hop's epoch
    # to be >= root epoch (no hop minted against a pre-revocation root).
    for hop in token.embedded_chain[1:]:
        if hop.epoch < root.epoch:
            raise StaleAttestationChainError(
                f"intermediate hop {hop.key_id} epoch {hop.epoch} "
                f"predates root epoch {root.epoch}"
            )
