# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-valid-hardware-attestation-quote-as-insufficient-proof-of-agent-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-valid-hardware-attestation-quote-as-insufficient-proof-of-agent-identity.warrant.json
# Markdown SHA-256:   5cec04c4b164d561508522d320a7293aa0f539bf885d79481dfcce99ff90d819
# Code AST SHA-256:   8a359457f6327074924a149fddd55bdb45d8399593c3d143106725638d2d92d4
# Verified Classes:   AttestationBindingError, WorkloadToken, AttestationQuote
# Defensive Guards:   8 fail-closed invariants (zero external deps)

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


class AttestationBindingError(RuntimeError):
    """Raised when a quote+token pair does not prove instance identity."""


@dataclass
class WorkloadToken:
    subject: str
    issued_at: float
    expires_at: float
    cnf_jkt: Optional[str]        # JWK thumbprint of the agent signing key
    nonce_claim: Optional[str]    # verifier-issued nonce, echoed by STS


@dataclass
class AttestationQuote:
    measurement: str
    nonce: str                    # nonce the quote was bound to
    signing_key_jkt: str          # thumbprint of key proven to be in the TEE


def verify_instance_identity(
    quote: AttestationQuote,
    token: WorkloadToken,
    verifier_nonce: str,
    request_signature_jkt: str,
    measurement_allowlist: dict[str, str],   # measurement -> scope ("broad"|"narrow")
    max_token_lifetime_for_broad: float = 90.0,
    now: Optional[float] = None,
) -> str:
    now = time.time() if now is None else now

    if token.expires_at <= now:
        raise AttestationBindingError("token expired before handshake")
    if quote.nonce != verifier_nonce:
        raise AttestationBindingError(
            "quote nonce was not issued by this verifier; prover-chosen nonce "
            "proves only self-consistency, not freshness to this session"
        )
    if token.nonce_claim != verifier_nonce:
        raise AttestationBindingError(
            "verifier nonce not bound into token; a captured token plus a "
            "fresh quote from any host with the same measurement is replayable"
        )
    if token.cnf_jkt is None:
        raise AttestationBindingError(
            "token carries no key binding (cnf.jkt); principal and signing key "
            "are unlinked, so any key under the allowed measurement can sign as this subject"
        )
    if token.cnf_jkt != quote.signing_key_jkt:
        raise AttestationBindingError(
            "token is bound to a different key than the attested key"
        )
    if request_signature_jkt != token.cnf_jkt:
        raise AttestationBindingError(
            "request was not signed by the key the token names"
        )

    scope = measurement_allowlist.get(quote.measurement)
    if scope is None:
        raise AttestationBindingError("measurement not on allowlist")

    lifetime = token.expires_at - token.issued_at
    if scope == "broad" and lifetime > max_token_lifetime_for_broad:
        raise AttestationBindingError(
            f"broad-measurement token lifetime {lifetime:.0f}s exceeds "
            f"{max_token_lifetime_for_broad:.0f}s; recycle window exceeds token TTL"
        )

    return token.subject


def jwk_thumbprint(pubkey_bytes: bytes) -> str:
    return hashlib.sha256(pubkey_bytes).hexdigest()
