# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tee-attestation-quote-as-bound-to-a-specific-tool-invocation-rather-than-to-the-enclave-that-produced-i.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tee-attestation-quote-as-bound-to-a-specific-tool-invocation-rather-than-to-the-enclave-that-produced-i.warrant.json
# Markdown SHA-256:   f4c83970b3288e2eb557cc35fe41778b7c50ff9f140f4621b0dcd527fbdddd4c
# Code AST SHA-256:   35840061c3dceca243aacb1908a0b4e657d8c5f05895a8fad54d66f2d559750b
# Verified Classes:   AttestationBindingError, Quote, Invocation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationBindingError(RuntimeError):
    """Raised when a TEE quote is valid as enclave identity but not as
    a warrant for the specific tool invocation being authorized."""
    pass


@dataclass(frozen=True)
class Quote:
    measurement: str
    report_data: str   # hex digest committed by the enclave
    nonce: str


@dataclass(frozen=True)
class Invocation:
    tool_id: str
    schema_hash: str
    canonical_args: str
    input_digest: str


def expected_report_data(inv: Invocation, nonce: str) -> str:
    payload = "|".join([
        inv.tool_id,
        inv.schema_hash,
        inv.canonical_args,
        inv.input_digest,
        nonce,
    ])
    return hashlib.sha256(payload.encode()).hexdigest()


def authorize_invocation(
    quote: Quote,
    inv: Invocation,
    pinned_measurement: str,
    consumed_nonces: set[str],
    relying_schema_hash: str,
) -> None:
    if quote.measurement != pinned_measurement:
        raise AttestationBindingError(
            f"measurement {quote.measurement!r} != pinned {pinned_measurement!r}; "
            "quote is authentic but about a different enclave image"
        )
    if quote.nonce in consumed_nonces:
        raise AttestationBindingError(
            f"nonce {quote.nonce!r} already consumed; attestation does not cover "
            "a second invocation"
        )
    if inv.schema_hash != relying_schema_hash:
        raise AttestationBindingError(
            f"schema drift: enclave attests {inv.schema_hash!r} but relying agent "
            f"serialized under {relying_schema_hash!r}; argument semantics disagree"
        )
    expected = expected_report_data(inv, quote.nonce)
    if quote.report_data != expected:
        raise AttestationBindingError(
            "quote binds a nonce but not the frozen invocation; "
            f"expected report_data {expected!r}, got {quote.report_data!r}"
        )
    consumed_nonces.add(quote.nonce)


def run_settlement_pipeline(
    quote: Quote,
    inv: Invocation,
    pinned_measurement: str,
    consumed_nonces: set[str],
    relying_schema_hash: str,
) -> str:
    authorize_invocation(
        quote, inv, pinned_measurement, consumed_nonces, relying_schema_hash
    )
    return f"executed {inv.tool_id} under attested warrant"


if __name__ == "__main__":
    inv = Invocation(
        tool_id="settle_invoice",
        schema_hash="sha256:abc123",
        canonical_args='{"amount":100,"currency":"USD"}',
        input_digest="sha256:input0001",
    )
    nonce = "nonce-7f3a"
    good_quote = Quote(
        measurement="MR_B_v2",
        report_data=expected_report_data(inv, nonce),
        nonce=nonce,
    )
    # Valid frozen-plan attestation:
    print(run_settlement_pipeline(good_quote, inv, "MR_B_v2", set(), "sha256:abc123"))

    # Failure: quote binds only the nonce, not the invocation.
    nonce_only_quote = Quote(
        measurement="MR_B_v2",
        report_data=hashlib.sha256(nonce.encode()).hexdigest(),
        nonce=nonce,
    )
    try:
        run_settlement_pipeline(nonce_only_quote, inv, "MR_B_v2", set(), "sha256:abc123")
    except AttestationBindingError as e:
        print(f"rejected: {e}")
