# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-attestation-key-mid-delegation-the-orphaned-warrant-window-in-zero-trust-agent-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-attestation-key-mid-delegation-the-orphaned-warrant-window-in-zero-trust-agent-chains.warrant.json
# Markdown SHA-256:   66d493ac3498077f0fdd788240bec6c0ae1fed1d4800179d1fdec0ca13029038
# Code AST SHA-256:   5854bd460b96a957f8677e006334635fa55597fc80e77e2b51997f6f37dcae89
# Verified Classes:   OrphanedWarrantError, Attestation, RotationEvent, Warrant, RotationLedger, Verifier
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class OrphanedWarrantError(RuntimeError):
    """Raised when a warrant's confirmation digest no longer matches the
    presenter's live attestation, or when an intervening rotation crossed a
    capability-class boundary that the warrant was not scoped against."""


@dataclass(frozen=True)
class Attestation:
    logical_id: str
    measurement_digest: str          # hash over measured code + pubkey
    capability_class: str            # e.g. "fs:ro,tools:read"
    issued_at: float


@dataclass(frozen=True)
class RotationEvent:
    logical_id: str
    from_digest: str
    to_digest: str
    from_class: str
    to_class: str
    at: float

    @property
    def scope_affecting(self) -> bool:
        return self.from_class != self.to_class


@dataclass
class Warrant:
    subject_logical_id: str
    cnf_digest: str                  # MUST be a measurement digest
    cnf_class: str
    minted_at: float
    ttl: float
    signature_valid: bool = True

    def expired(self, now: float) -> bool:
        return now > self.minted_at + self.ttl


class RotationLedger:
    def __init__(self) -> None:
        self._events: list[RotationEvent] = []

    def record(self, ev: RotationEvent) -> None:
        self._events.append(ev)

    def events_in(self, logical_id: str, lo: float, hi: float) -> list[RotationEvent]:
        return [
            e for e in self._events
            if e.logical_id == logical_id and lo < e.at <= hi
        ]


class Verifier:
    """Fails closed on any identity discontinuity inside the warrant window."""

    def __init__(self, ledger: RotationLedger) -> None:
        self.ledger = ledger

    def exercise(
        self,
        warrant: Warrant,
        presenter: Attestation,
        now: Optional[float] = None,
    ) -> None:
        now = time.time() if now is None else now

        if not warrant.signature_valid:
            raise OrphanedWarrantError("warrant signature invalid")
        if warrant.expired(now):
            raise OrphanedWarrantError("warrant expired")

        # Clause 1: measurement equality. No logical-ID fallback permitted.
        if presenter.measurement_digest != warrant.cnf_digest:
            raise OrphanedWarrantError(
                f"cnf digest mismatch: warrant={warrant.cnf_digest[:12]} "
                f"presenter={presenter.measurement_digest[:12]} "
                f"(rotation occurred inside warrant window; re-mint required)"
            )

        # Clause 2: no scope-affecting rotation inside (minted_at, now].
        rotations = self.ledger.events_in(
            warrant.subject_logical_id, warrant.minted_at, now
        )
        for ev in rotations:
            if ev.scope_affecting:
                raise OrphanedWarrantError(
                    f"scope-affecting rotation at {ev.at:.0f}: "
                    f"{ev.from_class!r} -> {ev.to_class!r}; "
                    f"warrant scoped against {warrant.cnf_class!r} is stale by discontinuity"
                )


def demo() -> None:
    ledger = RotationLedger()
    t0 = 1_000_000.0

    old = Attestation("agent-B", hashlib.sha256(b"B@t0").hexdigest(), "fs:ro,tools:read", t0)
    new = Attestation("agent-B", hashlib.sha256(b"B@t1").hexdigest(), "fs:rw,tools:read", t0 + 90)

    ledger.record(RotationEvent(
        logical_id="agent-B",
        from_digest=old.measurement_digest,
        to_digest=new.measurement_digest,
        from_class=old.capability_class,
        to_class=new.capability_class,      # scope-affecting: ro -> rw
        at=t0 + 90,
    ))

    w = Warrant(
        subject_logical_id="agent-B",
        cnf_digest=old.measurement_digest,
        cnf_class=old.capability_class,
        minted_at=t0,
        ttl=240.0,
    )

    v = Verifier(ledger)
    # Presenter is still the OLD instance: passes clause 1, but ledger shows a
    # scope-affecting rotation inside the window -> must fail closed.
    try:
        v.exercise(w, old, now=t0 + 150)
    except OrphanedWarrantError as e:
        print("rejected (old presenter):", e)

    # Presenter is the NEW instance: fails clause 1 outright.
    try:
        v.exercise(w, new, now=t0 + 150)
    except OrphanedWarrantError as e:
        print("rejected (new presenter):", e)


if __name__ == "__main__":
    demo()
