# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-tee-quote-to-a-task-context-it-did-not-originate.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attests-a-tee-quote-to-a-task-context-it-did-not-originate.warrant.json
# Markdown SHA-256:   85a296e4862fbb8a93dfd47be4a88c1e0592909010444daaa04b0e29d8b88b06
# Code AST SHA-256:   2320d9cb77fa00fabd6a43bfa2962782772add52dc8cfac8aaa4586ec4321039
# Verified Classes:   AttestationBindingError, Quote, RequestContext
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class AttestationBindingError(RuntimeError):
    """Raised when a TEE quote fails per-task binding invariants."""


@dataclass
class Quote:
    report_data: bytes          # 64 bytes: [0:32]=task_hash, [32:64]=enclave_pubkey
    measurement: str
    timestamp: float
    signature_valid: bool


@dataclass
class RequestContext:
    task_id: str
    attempt_nonce: bytes        # MUST be fresh per attempt, including retries
    transcript_head: bytes
    issued_at: float
    deadline: float


ALLOWED_MEASUREMENTS = {"mrenclave:abc123..."}


def verify_quote(
    quote: Quote,
    ctx: RequestContext,
    envelope_signing_key: bytes,
    now: float | None = None,
) -> None:
    now = now if now is not None else time.time()

    if not quote.signature_valid:
        raise AttestationBindingError("quote signature does not chain to vendor root")

    if quote.measurement not in ALLOWED_MEASUREMENTS:
        raise AttestationBindingError(
            f"measurement {quote.measurement!r} not in allowlist"
        )

    task_hash = hashlib.sha256(ctx.task_id.encode()).digest()
    if quote.report_data[0:32] != task_hash:
        raise AttestationBindingError("report_data task hash does not match task_id")

    # Per-attempt nonce: catches replay across retries of the same task.
    if quote.report_data[32:48] != ctx.attempt_nonce[:16]:
        raise AttestationBindingError(
            "report_data nonce does not match this attempt's nonce "
            "(replayed or task-scoped nonce)"
        )

    attested_key = quote.report_data[48:64]
    if attested_key != envelope_signing_key:
        raise AttestationBindingError(
            "envelope signing key is not the key bound in report_data; "
            "attested enclave and executor are decoupled"
        )

    if not (ctx.issued_at <= quote.timestamp <= ctx.deadline):
        raise AttestationBindingError(
            "quote timestamp outside request-anchored window"
        )

    if quote.report_data[16:32] != ctx.transcript_head[:16]:
        raise AttestationBindingError(
            "transcript head mismatch: attested view diverges from verifier"
        )
