# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-hardware-attestation-quote-whose-nonce-binds-to-a-stale-credential-subject-the-verifiable-credential-hardware-key-r.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-hardware-attestation-quote-whose-nonce-binds-to-a-stale-credential-subject-the-verifiable-credential-hardware-key-r.warrant.json
# Markdown SHA-256:   838af9ee16b1c1b0586be54611fb51823e687c8aa58187a9277c66c65e1212dd
# Code AST SHA-256:   040f7cf8c082440886ecfc948ef8552e6bf5133e45c1b3f8f32d84644b21e8dc
# Verified Classes:   AttestationBindingError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class AttestationBindingError(RuntimeError):
    """Raised when a hardware quote and a verifiable credential do not bind to the same key."""
    pass


def verify_agent_attestation(quote, vc, did_doc, challenge) -> bool:
    # 1. Freshness: nonce must be bound to the credential, not just the session.
    expected_nonce = hash_nonce(challenge, vc.id, vc.proof.verification_method)
    if quote.nonce != expected_nonce:
        raise AttestationBindingError(
            f"nonce not bound to credential {vc.id}; possible replay or rebinding gap"
        )

    # 2. Resolve the key named by the VC's proof method.
    vm = did_doc.get_verification_method(vc.proof.verification_method)
    if vm is None or vm.deactivated:
        raise AttestationBindingError(
            f"verificationMethod {vc.proof.verification_method} missing or deactivated"
        )

    # 3. Three-way key equality: quote key == VC-named key == credentialSubject key_binding.
    if quote.attested_key_id != vm.public_key_multibase:
        raise AttestationBindingError(
            "hardware quote key does not match VC verificationMethod "
            f"({quote.attested_key_id} != {vm.public_key_multibase}); "
            "stale subject binding after key rotation"
        )
    if vc.credential_subject.get("key_binding") != vm.public_key_multibase:
        raise AttestationBindingError(
            "credentialSubject.key_binding does not match resolved key; "
            "credential predates current key registration"
        )

    # 4. Temporal ordering: VC must postdate key registration.
    if vc.issuance_date < vm.registered_at:
        raise AttestationBindingError(
            "VC issued before verificationMethod registration; "
            "cannot attest a key the credential did not commit to"
        )

    return True
