# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-re-bound-agent-identity-when-a-delegated-aaif-credential-outlives-the-workload-it-was-minted-for.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-re-bound-agent-identity-when-a-delegated-aaif-credential-outlives-the-workload-it-was-minted-for.warrant.json
# Markdown SHA-256:   f3a27f9ae64ec1126d7abde44697aee73f9925dfda5c6debe4a9d8ac80d8785b
# Code AST SHA-256:   5616de24016b6bbd852cb1561a8619879de52ec9c5e4e139cd2717f1378c8d53
# Verified Classes:   BindingSubstitutionError, KeyOnlyBindingError
# Defensive Guards:   8 fail-closed invariants (zero external deps)

class BindingSubstitutionError(RuntimeError):
    """Raised when a presented AAIF credential's workload binding does not
    correspond to the freshly attested executing workload."""
    pass


class KeyOnlyBindingError(RuntimeError):
    """Raised when a credential carries no workload claim (presence-only
    binding) and has already been consumed, or when single-use enforcement
    is required but no replay set is available."""
    pass


def verify_presentation(cred, proof_of_possession, fresh_attestation, replay_set):
    """
    Enforce the correspondence invariant at credential presentation time.

    cred:                parsed AAIF credential with .cnf, .workload, .exp, .iat
    proof_of_possession: signature over a verifier nonce by the cnf key
    fresh_attestation:   attestation quote captured at presentation time, or None
    replay_set:          set of consumed credential ids for key-only bindings
    """
    # 1. Delegation chain (assumed verified upstream; re-assert here).
    if not cred.chain_valid:
        raise BindingSubstitutionError("delegation chain failed verification")

    # 2. Delegation clock.
    if now() > cred.exp:
        raise BindingSubstitutionError(
            f"credential expired at {cred.exp}, now {now()}"
        )

    # 3. Proof-of-possession of the bound key.
    if not verify_pop(proof_of_possession, cred.cnf, nonce=cred.nonce):
        raise BindingSubstitutionError("proof-of-possession does not match cnf key")

    # 4. Presence-only binding: refuse unless single-use and unconsumed.
    if cred.workload is None:
        if cred.id in replay_set:
            raise KeyOnlyBindingError(
                f"key-only credential {cred.id} already consumed; refusing replay"
            )
        replay_set.add(cred.id)
        return "accepted-key-only-single-use"

    # 5. THE LOAD-BEARING CHECK: executor must match the bound workload.
    if fresh_attestation is None:
        raise BindingSubstitutionError(
            "credential carries a workload claim but no fresh attestation was "
            "supplied; cannot confirm the presenting instance is the bound workload"
        )

    if fresh_attestation.measurement != cred.workload.attest:
        raise BindingSubstitutionError(
            "binding substitution: presented workload measurement "
            f"{fresh_attestation.measurement!r} != bound attestation "
            f"{cred.workload.attest!r} (credential {cred.id})"
        )

    # 6. Attestation must postdate issuance; a stale quote cannot vouch for now.
    if fresh_attestation.issued_at < cred.iat:
        raise BindingSubstitutionError(
            f"attestation issued_at {fresh_attestation.issued_at} predates "
            f"credential issuance {cred.iat}; stale quote"
        )

    return "accepted"


def require_checkpoint_exclusion(snapshot_keys, bound_keys):
    """Runtime invariant: no cnf-bound key may appear in a serialized snapshot."""
    leaked = set(snapshot_keys) & set(bound_keys)
    if leaked:
        raise BindingSubstitutionError(
            f"cnf-bound key material leaked into checkpoint: {leaked}; "
            "restored instances would inherit presentable credentials"
        )
