# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-anchor-its-identity-when-a-short-lived-credential-outlives-the-attestation-evidence-that-minted-it.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-anchor-its-identity-when-a-short-lived-credential-outlives-the-attestation-evidence-that-minted-it.warrant.json
# Markdown SHA-256:   ea9190961747f6feebeb4e668bef5b6f16565068353be950df71365a3751369f
# Code AST SHA-256:   6e58c8b89d7179b460fee7bb9105339205f1ee4df93df7016a549bd9d9f6a453
# Verified Classes:   EvidenceStaleError, Evidence, Credential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class EvidenceStaleError(RuntimeError):
    """Raised when a credential's attestation evidence has lapsed before the credential expired."""
    pass


@dataclass(frozen=True)
class Evidence:
    digest: str
    subject_measurement: str
    valid_until: float  # epoch seconds


@dataclass(frozen=True)
class Credential:
    evidence_digest: str
    subject_measurement: str
    not_after: float  # epoch seconds


def rotation_deadline(cred: Credential, ev: Evidence) -> float:
    """The instance must re-anchor at the earlier of token expiry and evidence expiry.

    Keying rotation on cred.not_after alone is the skew bug: when the mint service
    issues a token that outlives its evidence, the evidence clock is the binding one.
    """
    if cred.evidence_digest != ev.digest:
        raise EvidenceStaleError(
            f"credential evidence digest {cred.evidence_digest!r} does not match "
            f"presented evidence {ev.digest!r}; cannot compute rotation deadline"
        )
    if cred.subject_measurement != ev.subject_measurement:
        raise EvidenceStaleError(
            "credential subject measurement does not match evidence subject; "
            "identity has drifted from its attestation anchor"
        )
    return min(cred.not_after, ev.valid_until)


def assert_action_authorized(cred: Credential, ev: Evidence, now: float) -> None:
    """Verify-time re-anchor: a signature-valid token is not sufficient if its evidence lapsed."""
    if cred.evidence_digest != ev.digest:
        raise EvidenceStaleError("evidence digest mismatch at verify time")
    if ev.valid_until < now:
        raise EvidenceStaleError(
            f"evidence lapsed at {ev.valid_until:.3f} but action attempted at {now:.3f}; "
            f"credential not_after={cred.not_after:.3f} outlived its evidence — re-attest before acting"
        )
    if cred.not_after < now:
        raise EvidenceStaleError("credential expired")
    # Action is anchored: token live AND evidence fresh AND subject matches.


def handoff(cred: Credential, ev: Evidence, peer_now: float) -> Credential:
    """A peer must re-fetch evidence, never trust a bundle carried in episodic memory."""
    # Simulate the peer re-fetching evidence rather than using a cached copy.
    refreshed = Evidence(digest=ev.digest, subject_measurement=ev.subject_measurement,
                         valid_until=ev.valid_until)
    assert_action_authorized(cred, refreshed, peer_now)
    return cred


if __name__ == "__main__":
    now = time.time()
    ev = Evidence(digest="sha256:aaif-quote-7f3", subject_measurement="mrtm:planner-v9",
                  valid_until=now + 300)
    cred = Credential(evidence_digest="sha256:aaif-quote-7f3",
                      subject_measurement="mrtm:planner-v9", not_after=now + 900)

    # Rotation deadline correctly binds to the evidence clock, not the token clock.
    assert rotation_deadline(cred, ev) == ev.valid_until

    # Within the freshness window the action is anchored.
    assert_action_authorized(cred, ev, now + 100)

    # At t+400 the token is still cryptographically live but evidence has lapsed.
    assert_action_authorized(cred, ev, now + 400)  # raises EvidenceStaleError
