# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-federated-agent-identity-attestation-when-its-hardware-backed-key-rotates-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-federated-agent-identity-attestation-when-its-hardware-backed-key-rotates-mid-session.warrant.json
# Markdown SHA-256:   2bfabc531f8b47008a8440196b2f4a345fb076b84e9993c5c942b3af158f8ce2
# Code AST SHA-256:   f88a2349e726f0c128ecb30a4d392965e3620aa9e008e8d15ed3d6dd3a831991
# Verified Classes:   KeyRotationUnattestedError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class KeyRotationUnattestedError(RuntimeError):
    """Raised when an agent's hardware-backed key has rotated but no
    rotation proof chains the new key to the issuer's attested identity.
    This is NOT a signature failure and NOT a compromise signal; it is a
    lifecycle gap that must be resolved by re-issuance, not retry."""


def verify_federated_presentation(vc, quote, rotation_proof, issuer_trust_anchor):
    # 1. Credential signature is necessary but not sufficient.
    if not vc.verify_signature(issuer_trust_anchor):
        raise KeyRotationUnattestedError(
            "VC signature invalid against issuer trust anchor"
        )

    # 2. Attestation must verify against the platform endorsement root.
    if not quote.verify_endorsement_chain():
        raise KeyRotationUnattestedError(
            "attestation quote does not chain to endorsement root"
        )

    vc_key = vc.credential_subject.public_key
    attested_key = quote.attested_key  # NOT quote.ak; the signing key

    # 3. The binding check: the only place divergence is visible.
    if attested_key == vc_key:
        return "bound"

    # 4. Mismatch. Accept only with a valid rotation proof covering
    #    old->new for this subject, chained to the same endorsement root.
    if rotation_proof is None:
        raise KeyRotationUnattestedError(
            f"attested key {attested_key.fingerprint()} != VC key "
            f"{vc_key.fingerprint()}; no rotation proof present"
        )

    if not rotation_proof.verify(
        old_key=vc_key,
        new_key=attested_key,
        subject=vc.credential_subject.id,
        endorsement_root=quote.endorsement_root,
    ):
        raise KeyRotationUnattestedError(
            "rotation proof present but does not cover this subject/key pair"
        )

    # Legal rotation: accept, but require re-issuance within one refresh window.
    return "rotation_continuity_pending_reissue"
