# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-attestation-warrant-replay-across-enclave-restarts-in-confidential-cross-org-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-attestation-warrant-replay-across-enclave-restarts-in-confidential-cross-org-agent-handoffs.warrant.json
# Markdown SHA-256:   3aaa6a70aa199b99e7683a115947283940867a787e2a325f67127da6a7bce6d3
# Code AST SHA-256:   5c51e5fd82d3a1fd0409d43a8a411f027a88ca452d37d6892ca51e635dc3a704
# Verified Classes:   AttestationWarrantBindingError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class AttestationWarrantBindingError(RuntimeError):
    """Raised when a handoff bundle's attestation quote and delegated warrant
    are not bound to the same enclave instance key."""
    pass


def verify_handoff_bundle(bundle, policy, seen_nonces):
    quote = bundle.quote
    warrant = bundle.warrant

    if not quote.verify_chain(policy.trusted_roots):
        raise AttestationWarrantBindingError("quote does not chain to trusted root")
    if quote.measurement not in policy.allowlist:
        raise AttestationWarrantBindingError(
            f"measurement {quote.measurement!r} not in policy allowlist"
        )
    if quote.nonce in seen_nonces:
        raise AttestationWarrantBindingError(
            f"quote nonce {quote.nonce!r} already seen (replay)"
        )
    if not warrant.verify_signature(policy.issuer_root):
        raise AttestationWarrantBindingError("warrant signature invalid")
    if warrant.is_expired():
        raise AttestationWarrantBindingError("warrant expired")

    # The binding invariant: quote report-data commits to the live instance key,
    # and the warrant must have been signed over that exact key.
    quote_instance_key = quote.extract_instance_key()   # from report_data hash
    warrant_subject_key = warrant.subject_key
    if quote_instance_key != warrant_subject_key:
        raise AttestationWarrantBindingError(
            "instance-key mismatch: quote attests "
            f"{quote_instance_key!r} but warrant was issued to "
            f"{warrant_subject_key!r} (stale warrant after enclave restart)"
        )

    seen_nonces.add(quote.nonce)
    return True
