# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hardware-rooted-attestation-keys-from-silently-decoupling-from-the-capability-tokens-they-are-supposed-to-bind.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hardware-rooted-attestation-keys-from-silently-decoupling-from-the-capability-tokens-they-are-supposed-to-bind.warrant.json
# Markdown SHA-256:   d494c92e3cf575f858a3c9d1d3c443dd5c3a93b29b02acb1d3d9c5810cf7959e
# Code AST SHA-256:   eea97a5756a3df24a21ebc5630802a507e69ed6c79ef2bf78166630ad50241f3
# Verified Classes:   UnboundCapabilityToken, Quote, CapabilityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class UnboundCapabilityToken(RuntimeError):
    """Raised when a token cannot be bound to a fresh hardware quote."""
    pass


@dataclass(frozen=True)
class Quote:
    key_id: str
    nonce: bytes
    generation_counter: int
    issued_at: float


@dataclass(frozen=True)
class CapabilityToken:
    kid: str
    mint_nonce: bytes
    mint_generation: int
    ttl_seconds: float
    minted_at: float


def verify_binding(
    token: CapabilityToken,
    quote: Quote | None,
    now: float,
) -> None:
    # Freshness of the token itself.
    if now - token.minted_at > token.ttl_seconds:
        raise UnboundCapabilityToken(
            f"token for kid={token.kid} expired at t={token.minted_at + token.ttl_seconds:.3f}"
        )

    # No quote observed for this token's nonce: the token is unbound.
    # A cached quote for the same kid is NOT acceptable here.
    if quote is None:
        raise UnboundCapabilityToken(
            f"no quote observed for nonce={token.mint_nonce.hex()} kid={token.kid}"
        )

    if quote.key_id != token.kid:
        raise UnboundCapabilityToken(
            f"quote key_id={quote.key_id} does not match token kid={token.kid}"
        )

    if quote.nonce != token.mint_nonce:
        raise UnboundCapabilityToken(
            f"quote nonce={quote.nonce.hex()} does not match token mint_nonce={token.mint_nonce.hex()}"
        )

    # Enclave generation must not lag the token's mint generation.
    # A token minted from a restored checkpoint after key rotation will
    # carry mint_generation <= quote.generation_counter only if the mint
    # path bumped the counter on resume; otherwise it is superseded.
    if quote.generation_counter < token.mint_generation:
        raise UnboundCapabilityToken(
            f"quote generation={quote.generation_counter} precedes "
            f"token mint_generation={token.mint_generation} for kid={token.kid}"
        )


def honor_tool_call(
    token: CapabilityToken,
    quote: Quote | None,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now
    verify_binding(token, quote, now)
    # Proceed to execute the tool call under the now-verified identity.
