# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-identity-attestation-from-surviving-key-rotation-without-re-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-identity-attestation-from-surviving-key-rotation-without-re-authorization.warrant.json
# Markdown SHA-256:   a507aa209569629d493c3122bf6c1901b83e84b6bd7aa39e176afcf335f4ffb1
# Code AST SHA-256:   36fc6832584c6bb55a882062fb65e0c662912d941be640d08089b87fd5c99ee1
# Verified Classes:   AttestationBindingError, AttestationQuote, AuthorizationDecision
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationBindingError(RuntimeError):
    """Raised when an authorization decision does not bind to the currently attested key."""
    pass


@dataclass(frozen=True)
class AttestationQuote:
    principal_id: str
    key_digest: str          # sha256 of the attested public key
    pcr_measurements: dict   # posture at attestation time


@dataclass(frozen=True)
class AuthorizationDecision:
    principal_id: str
    key_digest: str          # digest of the key the decision was made about
    posture_digest: str


def _digest_posture(pcrs: dict) -> str:
    h = hashlib.sha256()
    for name in sorted(pcrs):
        h.update(name.encode())
        h.update(pcrs[name].encode())
    return h.hexdigest()


def authorize_request(quote: AttestationQuote,
                      decision: AuthorizationDecision) -> None:
    # Invariant 1: decision must be about the same principal.
    if decision.principal_id != quote.principal_id:
        raise AttestationBindingError(
            f"principal mismatch: decision={decision.principal_id!r} "
            f"quote={quote.principal_id!r}"
        )

    # Invariant 2 (the non-obvious one): decision must be about the SAME KEY
    # that is currently attested. Rotation severs this silently otherwise.
    if decision.key_digest != quote.key_digest:
        raise AttestationBindingError(
            "authorization decision bound to stale key after rotation: "
            f"decision_key={decision.key_digest[:12]} "
            f"attested_key={quote.key_digest[:12]}; "
            "force full re-authorization"
        )

    # Invariant 3: posture at decision time must match posture now.
    if decision.posture_digest != _digest_posture(quote.pcr_measurements):
        raise AttestationBindingError(
            "posture drift since authorization decision; re-authorize"
        )
    # All invariants hold: the decision is provably about the attested key.
