# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-attestation-key-rotation-that-silently-invalidates-a-peer-s-mtls-warrant-mid-swarm.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-attestation-key-rotation-that-silently-invalidates-a-peer-s-mtls-warrant-mid-swarm.warrant.json
# Markdown SHA-256:   f86e9011a756bd8c96ca0ba14d19ff4d63ed296b95a74417570a1670edea1972
# Code AST SHA-256:   ee8ff480564170c3a8d92baddbc22386ef3dd74089cc802e81b8097fdbc1c0af
# Verified Classes:   WarrantBindingError, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WarrantBindingError(RuntimeError):
    """Raised when a peer's handshake key does not match the key bound in its warrant."""
    pass


@dataclass
class Warrant:
    subject: str
    capability: str
    attestation_pubkey_hash: str  # signed claim over the attesting key
    expires_at: float


def verify_warrant_binding(warrant: Warrant, handshake_pubkey: bytes, now: float) -> None:
    if now >= warrant.expires_at:
        raise WarrantBindingError(
            f"warrant for {warrant.subject} expired at {warrant.expires_at}"
        )

    presented_hash = hashlib.sha256(handshake_pubkey).hexdigest()
    if presented_hash != warrant.attestation_pubkey_hash:
        # This is the rotation-orphan case: cert chain and subject are valid,
        # but the key that completed the handshake is not the key the warrant
        # was granted over. Capability must NOT be honored.
        raise WarrantBindingError(
            f"attestation key mismatch for {warrant.subject}: "
            f"warrant binds {warrant.attestation_pubkey_hash[:12]}…, "
            f"handshake presented {presented_hash[:12]}… — "
            f"warrant is stale, re-attestation required"
        )


def authorize_ledger_write(warrant: Warrant, handshake_pubkey: bytes, now: float) -> bool:
    verify_warrant_binding(warrant, handshake_pubkey, now)
    return warrant.capability == "executor.may_write_ledger"
