# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-its-attestation-key-before-the-credential-is-sealed-or-the-signature-verifies-against-a-key-the-agent-no-longer-holds.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-its-attestation-key-before-the-credential-is-sealed-or-the-signature-verifies-against-a-key-the-agent-no-longer-holds.warrant.json
# Markdown SHA-256:   4fd8b76fcfbe8e89cda38179ccc2480e4b2225641f6d5199eec5039b57b03636
# Code AST SHA-256:   103fa39315c92d10888601c857007be4a19c511d0c0d43a078b9eb22fdce809a
# Verified Classes:   AttestationBindingError, KeyMaterialUnavailable
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import hmac


class AttestationBindingError(RuntimeError):
    """Raised when a cached credential's subject key is not controlled by the live agent."""


class KeyMaterialUnavailable(AttestationBindingError):
    """The agent cannot produce proof-of-possession for the bound subject key."""


def _sign(key_material: bytes, challenge: bytes) -> bytes:
    return hmac.new(key_material, challenge, hashlib.sha256).digest()


def assert_binding_held(credential: dict, live_keys: dict[str, bytes], challenge: bytes) -> None:
    """
    Enforce the binding invariant before presenting a credential.

    credential: sealed VC dict with 'credentialSubject': {'id': did}, 'verificationMethod': did
    live_keys:  map of did -> private key material currently held by this process
    challenge:  fresh verifier nonce the agent must sign to prove possession
    """
    subject_did = credential.get("credentialSubject", {}).get("id")
    if not subject_did:
        raise AttestationBindingError("credential has no credentialSubject.id to bind against")

    vm = credential.get("verificationMethod")
    if vm != subject_did:
        raise AttestationBindingError(
            f"verificationMethod {vm!r} does not match subject {subject_did!r}; "
            "credential sealed against a key the subject does not name"
        )

    key = live_keys.get(subject_did)
    if key is None:
        raise KeyMaterialUnavailable(
            f"no live key for bound subject {subject_did!r}: "
            "key was ephemeral or rotated after sealing; credential is orphaned"
        )

    # Prove possession now, not at the verifier's convenience.
    proof = _sign(key, challenge)
    if not hmac.compare_digest(proof, _sign(key, challenge)):
        raise AttestationBindingError("proof-of-possession self-check failed")
    # If we reach here, the agent can back the credential it is about to present.


def resume_with_credentials(checkpoint: dict, cached_credentials: list[dict], challenge: bytes) -> list[dict]:
    """
    Cold-start resume path. Drops any credential whose binding cannot be proven.
    Re-attestation must be triggered for the dropped set by the caller.
    """
    live_keys = checkpoint.get("key_material")
    if not live_keys:
        raise KeyMaterialUnavailable(
            "checkpoint carries no key material; every cached credential is unusable"
        )

    usable = []
    for cred in cached_credentials:
        try:
            assert_binding_held(cred, live_keys, challenge)
        except KeyMaterialUnavailable:
            # Do NOT fall back to artifact-only use. Drop and re-attest.
            continue
        usable.append(cred)
    return usable
