# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-downgraded-attestation-chain-when-a-hardware-backed-agent-identity-is-re-issued-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-downgraded-attestation-chain-when-a-hardware-backed-agent-identity-is-re-issued-mid-handshake.warrant.json
# Markdown SHA-256:   8237c78f266e95024e8c39a563c5e180b6321d5cf6702e660221b66240309c9e
# Code AST SHA-256:   58cffdbed81587088733addc103c675806b381fed79657b98002773c1910904c
# Verified Classes:   AttestationContinuityError, AttestationTuple, ReKeyProof
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttestationContinuityError(RuntimeError):
    """Raised when a session's attested identity tuple changes without a valid re-key proof."""
    pass


@dataclass(frozen=True)
class AttestationTuple:
    subject_key: str          # e.g. SPKI hash of the hardware-backed key
    endorsement_key: str      # EK identity of the backing hardware
    measurement: str          # PCR digest / enclave measurement
    issuance_serial: int      # monotonic issuance counter from the issuer


@dataclass(frozen=True)
class ReKeyProof:
    old_subject_key: str
    new_subject_key: str
    signature_by_old_key: bytes
    issuer_countersignature: bytes


def verify_message_continuity(
    session_tuple: AttestationTuple,
    presented_tuple: AttestationTuple,
    rekey_proof: Optional[ReKeyProof],
    verify_sig,
    verify_countersig,
) -> AttestationTuple:
    """
    Enforce the session continuity invariant. Returns the (possibly updated)
    session tuple on success; raises AttestationContinuityError otherwise.
    """
    if presented_tuple == session_tuple:
        return session_tuple

    # Measurement must never change within a session, regardless of key.
    if presented_tuple.measurement != session_tuple.measurement:
        raise AttestationContinuityError(
            f"measurement changed within session: "
            f"{session_tuple.measurement} -> {presented_tuple.measurement}"
        )

    # Hardware identity change requires a full re-handshake, not a re-key.
    if presented_tuple.endorsement_key != session_tuple.endorsement_key:
        raise AttestationContinuityError(
            "endorsement key changed; full re-handshake required"
        )

    # Subject key changed: require an attested re-key proof linking old -> new.
    if presented_tuple.subject_key != session_tuple.subject_key:
        if rekey_proof is None:
            raise AttestationContinuityError(
                f"subject key changed {session_tuple.subject_key} -> "
                f"{presented_tuple.subject_key} with no re-key proof; "
                f"silent downgrade candidate"
            )
        if rekey_proof.old_subject_key != session_tuple.subject_key:
            raise AttestationContinuityError(
                "re-key proof does not reference the session's outgoing key"
            )
        if rekey_proof.new_subject_key != presented_tuple.subject_key:
            raise AttestationContinuityError(
                "re-key proof does not reference the presented incoming key"
            )
        if not verify_sig(
            rekey_proof.old_subject_key,
            rekey_proof.new_subject_key,
            rekey_proof.signature_by_old_key,
        ):
            raise AttestationContinuityError(
                "re-key proof signature by outgoing key failed"
            )
        if not verify_countersig(
            rekey_proof.old_subject_key,
            rekey_proof.new_subject_key,
            rekey_proof.issuer_countersignature,
        ):
            raise AttestationContinuityError(
                "re-key proof issuer countersignature failed"
            )

    # Issuance serial must be strictly monotonic and gap-free.
    if presented_tuple.issuance_serial != session_tuple.issuance_serial + 1:
        raise AttestationContinuityError(
            f"issuance serial gap: {session_tuple.issuance_serial} -> "
            f"{presented_tuple.issuance_serial}"
        )

    return presented_tuple
