# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-an-a2a-artifact-whose-provenance-chain-verifies-locally-but-whose-signing-key-was-rotated-out-of-the-trust-window-mid-flig.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-an-a2a-artifact-whose-provenance-chain-verifies-locally-but-whose-signing-key-was-rotated-out-of-the-trust-window-mid-flig.warrant.json
# Markdown SHA-256:   4a4c60adb644bcc9fa87a2a52f50e6f784e614629278616173579d63b5c38ce2
# Code AST SHA-256:   5cfcb4e95efe223cecb6969ad9c98bb4f15268de77f0b95a2af10b0779ae3a6c
# Verified Classes:   ProvenanceChainError, UnknownSigningKey, PostRetirementSignature, KeyNotValidAtSigningTime, SignatureTimestampOutOfSkew, NonMonotonicChain, TrustRecord, Hop, ChainVerifier
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceChainError(RuntimeError):
    """Base for all provenance-chain admission failures."""


class UnknownSigningKey(ProvenanceChainError):
    """Key absent from registry and no signed retirement attestation present."""


class PostRetirementSignature(ProvenanceChainError):
    """Hop signed at or after its key's retirement time."""


class KeyNotValidAtSigningTime(ProvenanceChainError):
    """sig_ts falls outside the key's [valid_from, valid_to] interval."""


class SignatureTimestampOutOfSkew(ProvenanceChainError):
    """sig_ts is too far from receiver clock; possible backdating."""


class NonMonotonicChain(ProvenanceChainError):
    """A hop's sig_ts precedes the previous hop's sig_ts."""


@dataclass
class TrustRecord:
    key_id: str
    signer_id: str
    valid_from: float
    valid_to: float
    retired_at: Optional[float] = None  # set on rotation; never delete the record


@dataclass
class Hop:
    signer_id: str
    key_id: str
    sig_ts: float
    digest_sig: bytes = b""


@dataclass
class ChainVerifier:
    registry: dict[str, TrustRecord] = field(default_factory=dict)
    max_skew_s: float = 300.0

    def _lookup(self, key_id: str) -> Optional[TrustRecord]:
        return self.registry.get(key_id)

    def verify_hop(self, hop: Hop, receiver_now: float) -> None:
        rec = self._lookup(hop.key_id)

        if rec is None:
            # Unknown key: reject by default. A signed retirement attestation
            # from the signer org is the ONLY path to admit here.
            raise UnknownSigningKey(
                f"key {hop.key_id} for signer {hop.signer_id} absent from registry; "
                f"quarantine pending signed retirement attestation"
            )

        if rec.signer_id != hop.signer_id:
            raise ProvenanceChainError(
                f"key {hop.key_id} belongs to {rec.signer_id}, not {hop.signer_id}"
            )

        if abs(hop.sig_ts - receiver_now) > self.max_skew_s:
            raise SignatureTimestampOutOfSkew(
                f"hop {hop.key_id} sig_ts={hop.sig_ts} vs now={receiver_now} "
                f"exceeds skew {self.max_skew_s}s"
            )

        if not (rec.valid_from <= hop.sig_ts <= rec.valid_to):
            raise KeyNotValidAtSigningTime(
                f"key {hop.key_id} not valid at sig_ts={hop.sig_ts} "
                f"(window [{rec.valid_from}, {rec.valid_to}])"
            )

        if rec.retired_at is not None and hop.sig_ts >= rec.retired_at:
            raise PostRetirementSignature(
                f"key {hop.key_id} signed at {hop.sig_ts} but retired at {rec.retired_at}"
            )

    def verify_chain(self, chain: list[Hop], receiver_now: float) -> None:
        prev_ts: Optional[float] = None
        for hop in chain:
            if prev_ts is not None and hop.sig_ts < prev_ts:
                raise NonMonotonicChain(
                    f"hop {hop.key_id} sig_ts={hop.sig_ts} precedes prior hop ts={prev_ts}"
                )
            self.verify_hop(hop, receiver_now)
            prev_ts = hop.sig_ts


# --- reproduction of the observed failure ---
now = time.time()
registry = {
    "A/k1": TrustRecord("A/k1", "orgA", now - 3600, now + 3600),
    # B/k7 rotated out: deleted instead of retired -> triggers unknown-key branch
}
chain = [
    Hop("orgA", "A/k1", now - 60),
    Hop("orgB", "B/k7", now - 40),
]

verifier = ChainVerifier(registry=registry)
try:
    verifier.verify_chain(chain, receiver_now=now)
except UnknownSigningKey as e:
    print(f"QUARANTINED: {e}")
    # With retirement-not-deletion, B/k7 would carry retired_at=now-10,
    # and sig_ts=now-40 < retired_at -> hop admitted as late-arriving-valid.
