# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-chained-attestation-whose-intermediate-issuer-has-rotated-its-signing-key-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-chained-attestation-whose-intermediate-issuer-has-rotated-its-signing-key-mid-chain.warrant.json
# Markdown SHA-256:   920ffec6ea7b937f9b246152da75626f63eea7bb79dff291c5bb11020d686b08
# Code AST SHA-256:   170c3c5d76f216aa2559c5684612d6b949ff97aaf3a3611070566b76cab6900c
# Verified Classes:   KeyAuthorityUnresolvable, HistoricalKey, ChainLink
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class KeyAuthorityUnresolvable(RuntimeError):
    """Raised when a chain link's signing key cannot be proven authoritative
    for the link's issuance time. Fail closed; do not fall back to a live key."""
    pass


@dataclass
class HistoricalKey:
    kid: str
    issuer: str
    not_before: float
    not_after: float


@dataclass
class ChainLink:
    kid: str
    issuer: str
    iat: float
    signature_valid_under: str  # kid the signature actually verifies against


def verify_chain(
    chain: list[ChainLink],
    key_history: dict[str, list[HistoricalKey]],
    clock_skew: float = 30.0,
    now: Optional[float] = None,
) -> bool:
    """Validate a multi-hop attestation chain with iat-pinned key authority.

    Invariant: every link must resolve to a key whose validity window contains
    the link's iat. Matching on issuer identity alone is rejected.
    """
    now = now if now is not None else time.time()

    for idx, link in enumerate(chain):
        if link.iat > now + clock_skew:
            raise KeyAuthorityUnresolvable(
                f"link {idx}: iat {link.iat} is in the future beyond skew; "
                f"backdating with a rotated key is not permitted"
            )

        candidates = key_history.get(link.issuer, [])
        authoritative = [
            k for k in candidates
            if k.kid == link.kid and k.not_before <= link.iat <= k.not_after
        ]

        if not authoritative:
            # Distinguish "key exists but not for this time" from "no such key".
            any_kid = any(k.kid == link.kid for k in candidates)
            reason = (
                "key retired and no historical window covers iat"
                if any_kid else "kid never published by issuer"
            )
            raise KeyAuthorityUnresolvable(
                f"link {idx}: cannot establish authority of kid={link.kid} "
                f"under issuer={link.issuer} at iat={link.iat}: {reason}. "
                f"Refusing to fall back to live key (identity-aliasing hazard)."
            )

        # The signature must verify under the key that was authoritative at iat,
        # not under whatever key the issuer currently advertises.
        if link.signature_valid_under != link.kid:
            raise KeyAuthorityUnresolvable(
                f"link {idx}: signature verifies under {link.signature_valid_under} "
                f"but link claims kid={link.kid}; key-identity mismatch"
            )

    return True
