# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-its-hardware-bound-attestation-key-silently-rotated-beneath-a-live-short-lived-token.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-its-hardware-bound-attestation-key-silently-rotated-beneath-a-live-short-lived-token.warrant.json
# Markdown SHA-256:   f4c6f15bf9236416ab4aa24f72cb6bd9f1543591ec26349b19774d8374e4860e
# Code AST SHA-256:   f598ee3f4a0b5c9d719e4bebb338373bcc80ccd97f72b0afc18ea438b95d70e1
# Verified Classes:   AttestationKeyRotated, Token, Keystore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AttestationKeyRotated(RuntimeError):
    """Raised when the keystore's current key no longer matches the token's cnf.jkt."""
    pass


@dataclass
class Token:
    jkt: str          # JWK thumbprint named in cnf claim
    exp: float        # wall-clock expiry
    generation: int   # keystore generation at mint time


class Keystore:
    """Hardware-backed keystore that can rotate keys without process restart."""
    def __init__(self):
        self._generation = 1
        self._pubkey = b"K1-pub"

    def current_thumbprint(self) -> str:
        return hashlib.sha256(self._pubkey).hexdigest()

    def generation(self) -> int:
        return self._generation

    def rotate(self):  # firmware update / vTPM re-instantiation
        self._generation += 1
        self._pubkey = b"K2-pub"

    def sign(self, nonce: bytes) -> bytes:
        # NOTE: signs with whatever key is current; never errors on rotation
        return hashlib.sha256(self._pubkey + nonce).digest()


def sign_proof_of_possession(ks: Keystore, token: Token, nonce: bytes, now: float) -> bytes:
    if now >= token.exp:
        raise AttestationKeyRotated(f"token expired at {token.exp}, now={now}")
    if ks.generation() != token.generation:
        raise AttestationKeyRotated(
            f"keystore generation advanced {token.generation}->{ks.generation()}; "
            "token cnf.jkt is stale, re-attest required"
        )
    if ks.current_thumbprint() != token.jkt:
        raise AttestationKeyRotated(
            f"current key thumbprint {ks.current_thumbprint()[:12]} != "
            f"token jkt {token.jkt[:12]}"
        )
    return ks.sign(nonce)


def run_tool_step(ks: Keystore, token: Token, now: float) -> bytes:
    # Fail-closed: a rotation is terminal for this token, not retryable.
    return sign_proof_of_possession(ks, token, b"handshake-nonce", now)


if __name__ == "__main__":
    ks = Keystore()
    tok = Token(jkt=ks.current_thumbprint(), exp=1000.0, generation=ks.generation())
    run_tool_step(ks, tok, now=500.0)          # ok
    ks.rotate()                                 # silent hardware key rotation
    try:
        run_tool_step(ks, tok, now=506.0)       # would have silently mis-signed before
    except AttestationKeyRotated as e:
        print("re-attest or abort:", e)
