# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-bound-to-a-tpm-backed-workload-identity-still-fail-mcp-peer-authentication-after-a-live-migration.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-bound-to-a-tpm-backed-workload-identity-still-fail-mcp-peer-authentication-after-a-live-migration.warrant.json
# Markdown SHA-256:   3f70119ccdce5be504b2078b8de0c4991f2702387bba100de15d49a2c1f71f0a
# Code AST SHA-256:   eed5ad36b78587ee635eb16137171794f5d54f6dc5b01ce5ecf5e059c510156e
# Verified Classes:   AttestationEpochMismatch, StaleNonceError, UntrustedPlatformKeyError, SubjectMeasurementEpochError, Warrant, PeerTrustConfig
# Defensive Guards:   6 fail-closed invariants (zero external deps)

"""Peer-side MCP attestation warrant verifier.

Enforces the epoch-triple invariant: a composite warrant is accepted only if
the quote nonce, workload-token subject, and pinned platform key all belong to
the same execution epoch. Signature validity alone is insufficient.
"""

from __future__ import annotations

import time
from dataclasses import dataclass


class AttestationEpochMismatch(RuntimeError):
    """Raised when a warrant is structurally valid but spans execution epochs."""


class StaleNonceError(AttestationEpochMismatch):
    """Quote nonce does not match the peer-issued handshake nonce."""


class UntrustedPlatformKeyError(AttestationEpochMismatch):
    """Binding assertion signed by a key outside the peer's pinned set."""


class SubjectMeasurementEpochError(AttestationEpochMismatch):
    """SVID was minted before the current vTPM execution epoch began."""


@dataclass(frozen=True)
class Warrant:
    quote_nonce: bytes
    quote_pcr_digest: bytes
    quote_vtpm_reset_count: int
    quote_generated_at: float
    svid_subject: str
    svid_issued_at: float
    binding_assertion: bytes
    binding_assertion_signer_fingerprint: str
    claimed_platform_key_id: str  # untrusted; never used for resolution


@dataclass(frozen=True)
class PeerTrustConfig:
    pinned_platform_key_fingerprints: frozenset[str]
    nonce_freshness_window_s: float = 60.0
    expected_subject: str = "spiffe://corp/mcp/orders"


def verify_warrant(
    warrant: Warrant,
    peer_nonce: bytes,
    nonce_issued_at: float,
    trust: PeerTrustConfig,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # 1. Nonce epoch: the quote must be for THIS handshake, not a cached one.
    if warrant.quote_nonce != peer_nonce:
        raise StaleNonceError(
            f"quote nonce {warrant.quote_nonce.hex()[:8]} != peer-issued "
            f"{peer_nonce.hex()[:8]}; server re-presented a cached warrant"
        )
    if now - nonce_issued_at > trust.nonce_freshness_window_s:
        raise StaleNonceError(
            f"nonce issued {now - nonce_issued_at:.1f}s ago exceeds "
            f"{trust.nonce_freshness_window_s}s window"
        )

    # 2. Platform-key pinning: resolve from peer config, NOT from the warrant.
    if warrant.binding_assertion_signer_fingerprint not in trust.pinned_platform_key_fingerprints:
        raise UntrustedPlatformKeyError(
            f"binding assertion signed by {warrant.binding_assertion_signer_fingerprint}, "
            f"not in pinned set; server claimed platform_key_id="
            f"{warrant.claimed_platform_key_id!r} (ignored)"
        )

    # 3. Subject-measurement co-epoch: SVID must postdate the current epoch.
    if warrant.svid_subject != trust.expected_subject:
        raise SubjectMeasurementEpochError(
            f"SVID subject {warrant.svid_subject!r} != expected "
            f"{trust.expected_subject!r}"
        )
    if warrant.svid_issued_at < warrant.quote_generated_at - _epoch_skew_allowance(warrant):
        raise SubjectMeasurementEpochError(
            f"SVID iat={warrant.svid_issued_at:.0f} predates quote epoch "
            f"(reset_count={warrant.quote_vtpm_reset_count}); "
            f"token and measurement from different epochs"
        )


def _epoch_skew_allowance(warrant: Warrant) -> float:
    # Small allowance for clock skew within a single epoch; a vTPM reset
    # transition implies a new epoch and zero allowance.
    return 2.0 if warrant.quote_vtpm_reset_count == 0 else 0.0


def handle_initialize(warrant: Warrant, peer_nonce: bytes, nonce_issued_at: float,
                      trust: PeerTrustConfig) -> str:
    try:
        verify_warrant(warrant, peer_nonce, nonce_issued_at, trust)
    except AttestationEpochMismatch as exc:
        # Force full re-handshake; never upgrade a degraded warrant.
        raise AttestationEpochMismatch(
            f"rejecting MCP initialize: {type(exc).__name__}: {exc}; "
            f"require fresh quote + regenerated binding assertion"
        ) from exc
    return "authenticated"
