# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-hardware-attested-identity-chain-as-invalid-the-moment-its-own-tee-measurement-diverges-from-the-creden.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-hardware-attested-identity-chain-as-invalid-the-moment-its-own-tee-measurement-diverges-from-the-creden.warrant.json
# Markdown SHA-256:   13f07ae3eecc8781eecabb0255be3871c41b8811a90956b726f96aad8e979ae3
# Code AST SHA-256:   1b420f919fc101e88e16de628a5dcbb45e965a1eb174de47152b4c4cdbabcab8
# Verified Classes:   MeasurementDivergenceError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class MeasurementDivergenceError(RuntimeError):
    """Raised when a live TEE quote's measurement diverges from the
    measurement committed in the credential's cnf binding. This is a
    positive signal of runtime drift, not an absence of evidence."""
    pass


def verify_attested_identity(vc: dict, quote: dict, challenge: dict,
                             trusted_root: bytes) -> bool:
    # 1. Issuer signature + chain to trusted root.
    if not verify_chain(vc["proof"], trusted_root):
        raise MeasurementDivergenceError("issuer chain invalid")

    # 2. Freshness: challenge issued by this verifier, within window.
    if quote["nonce"] != challenge["nonce"] or not within_window(challenge):
        raise MeasurementDivergenceError("stale or foreign nonce")

    # 3. report_data must bind the cnf key to this challenge.
    if quote["report_data"] != bind(challenge["nonce"], vc["cnf"]["kid"]):
        raise MeasurementDivergenceError("report_data does not bind cnf key")

    # 4. THE GUARD: live measurement must equal the committed measurement.
    committed = vc["cnf"]["attestation"]["measurement"]
    live = quote["measurement"]
    if live != committed:
        # Every other check passed. Key continuity holds; image continuity
        # does NOT. Hard reject; do not degrade to warning.
        raise MeasurementDivergenceError(
            f"measurement drift: committed={committed} live={live}"
        )

    # 5. Revocation.
    if is_revoked(vc["cnf"]["kid"]):
        raise MeasurementDivergenceError("cnf key revoked")

    return True
