# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-mid-handshake-identity-expiry-when-a-short-lived-workload-token-rotates-between-attestation-and-the-first-rpc.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-mid-handshake-identity-expiry-when-a-short-lived-workload-token-rotates-between-attestation-and-the-first-rpc.warrant.json
# Markdown SHA-256:   3b4e65f2be104512cf832fc87df2427455fffd364bb547619600a0352c908df8
# Code AST SHA-256:   233c6ac292336b38b5cc5790bc68a7ac5562c15603471ca4effc2b2287c88608
# Verified Classes:   IdentityDiscontinuity, ContinuityProofInvalid, SessionRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass, field
from typing import Optional


class IdentityDiscontinuity(RuntimeError):
    """Raised when a session's peer identity changes without a valid continuity proof."""
    pass


class ContinuityProofInvalid(IdentityDiscontinuity):
    """Raised when a rotation is claimed but the pre-rotation key did not sign it."""
    pass


@dataclass
class SessionRecord:
    session_id: str
    # Ordered list of (pubkey_fingerprint, continuity_sig_from_prev_or_None)
    key_chain: list = field(default_factory=list)
    baton_token: Optional[str] = None

    @property
    def current_key(self) -> str:
        return self.key_chain[-1][0]


def _fingerprint(pubkey: bytes) -> str:
    return hashlib.sha256(pubkey).hexdigest()


def _verify_continuity(
    old_privkey_signer,
    old_pubkey: bytes,
    new_pubkey: bytes,
    session_id: str,
    rotation_ts: int,
    signature: bytes,
) -> bool:
    """The pre-rotation key must sign the succession tuple."""
    msg = b"|".join([
        old_pubkey,
        new_pubkey,
        session_id.encode(),
        str(rotation_ts).encode(),
    ])
    expected = old_privkey_signer(msg)
    return hmac.compare_digest(expected, signature)


def admit_connection(
    session: SessionRecord,
    presented_pubkey: bytes,
    continuity_sig: Optional[bytes],
    rotation_ts: Optional[int],
) -> None:
    """
    Called on every new connection bound to an existing session.
    Mutates session.key_chain on proven rotation; raises otherwise.
    """
    presented_fp = _fingerprint(presented_pubkey)
    if presented_fp == session.current_key:
        return  # no rotation, fast path

    # Key changed. This is the decision boundary.
    if continuity_sig is None or rotation_ts is None:
        raise IdentityDiscontinuity(
            f"session {session.session_id}: peer key rotated to {presented_fp[:12]} "
            f"without continuity proof; refusing to advance pinned identity"
        )

    old_fp = session.current_key
    # The verifier must reconstruct the old pubkey from its chain to check the sig.
    old_pubkey = session.key_chain[-1][2]  # stored alongside fp in real impl
    if not _verify_continuity(
        old_privkey_signer=_signer_for(old_fp),
        old_pubkey=old_pubkey,
        new_pubkey=presented_pubkey,
        session_id=session.session_id,
        rotation_ts=rotation_ts,
        signature=continuity_sig,
    ):
        raise ContinuityProofInvalid(
            f"session {session.session_id}: rotation {old_fp[:12]} -> {presented_fp[:12]} "
            f"carries invalid continuity signature; treating as impersonation"
        )

    session.key_chain.append((presented_fp, continuity_sig, presented_pubkey))
    # baton_token survives rotation because it is session-bound, not identity-bound


def _signer_for(fingerprint: str):
    # Placeholder: in production this resolves to the verifier's held copy of
    # the peer's pre-rotation public key and performs signature verification.
    raise NotImplementedError("wire to key store")
