# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-subject-binding-drift-between-its-runtime-attestation-and-its-issued-aaif-verifiable-credential.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-subject-binding-drift-between-its-runtime-attestation-and-its-issued-aaif-verifiable-credential.warrant.json
# Markdown SHA-256:   20f9a39fcdc556858b2e1999c31408e3b09e4e160aa733c44485bd80e79e0745
# Code AST SHA-256:   29dcd1f553c33dd1b4e346de4b28bf94a7d45b05a01e313120f549d38019a6ef
# Verified Classes:   SubjectBindingDrift, BindingAssurance, VerifiableCredential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class SubjectBindingDrift(RuntimeError):
    """Raised when a live runtime attestation no longer matches the VC's cnf claim."""


class BindingAssurance(Enum):
    FRESH = "fresh"
    NONE = "none"
    UNAVAILABLE = "unavailable"


@dataclass(frozen=True)
class VerifiableCredential:
    subject_did: str
    scope: tuple[str, ...]
    cnf_runtime_attestation: str | None  # None => legacy static credential


def fresh_quote(runtime) -> str | None:
    """Return SHA-256 over the live TEE measurement registers, or None if unavailable."""
    measurements = runtime.read_measurement_registers()
    if measurements is None:
        return None
    return hashlib.sha256(measurements).hexdigest()


def assert_subject_binding(vc: VerifiableCredential, runtime) -> BindingAssurance:
    """
    Called immediately after cold start / checkpoint rehydration, BEFORE any
    scope-bearing tool call. Fail-closed on drift.
    """
    if vc.cnf_runtime_attestation is None:
        return BindingAssurance.NONE

    live = fresh_quote(runtime)
    if live is None:
        # No TEE on this host: cannot prove binding. Refuse bound scopes.
        return BindingAssurance.UNAVAILABLE

    if live != vc.cnf_runtime_attestation:
        raise SubjectBindingDrift(
            f"subject-binding drift for {vc.subject_did}: "
            f"cnf={vc.cnf_runtime_attestation[:16]}… live={live[:16]}…; "
            f"refusing scopes {vc.scope}; emit event to orchestrator for re-issuance"
        )
    return BindingAssurance.FRESH


def guarded_tool_call(vc: VerifiableCredential, runtime, required_scope: str, fn, *args):
    assurance = assert_subject_binding(vc, runtime)
    if required_scope not in vc.scope:
        raise SubjectBindingDrift(f"scope {required_scope} not present on VC")
    if required_scope.startswith("scope:filesystem:") and assurance is not BindingAssurance.FRESH:
        raise SubjectBindingDrift(
            f"bound scope {required_scope} requires FRESH binding, got {assurance.value}"
        )
    return fn(*args)
