# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-egress-filtering-as-a-stateful-invariant-rather-than-a-per-request-check.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-egress-filtering-as-a-stateful-invariant-rather-than-a-per-request-check.warrant.json
# Markdown SHA-256:   fb446d2bce81ef17dfb52293bd1b3bf06a3cc2ae5a313b20bb50ecfc5dbf082e
# Code AST SHA-256:   ea20a186c5a786428352e3fda3bd9f0ee980ccad4313e801acb115ebb75b8824
# Verified Classes:   EgressInvariantViolation, PinnedPeer
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import ipaddress
import ssl
from dataclasses import dataclass


class EgressInvariantViolation(RuntimeError):
    """Raised when a request would cross the egress trust boundary unsafely."""


@dataclass(frozen=True)
class PinnedPeer:
    resolved_ip: str
    sni: str
    spki_sha256: str
    token_audience: str


def authorize_hop(
    *,
    hostname: str,
    resolved_ip: str,
    sni: str,
    peer_spki_sha256: str,
    token_audience: str,
    allowlist: dict[str, PinnedPeer],
    is_redirect: bool,
    prior_peer: PinnedPeer | None,
) -> PinnedPeer:
    # A redirect is a new decision, never a transparent continuation.
    if is_redirect and prior_peer is None:
        raise EgressInvariantViolation(
            "redirect encountered without a prior authorized peer; refusing to dial"
        )

    # Reject link-local / loopback / private ranges before any name logic.
    ip = ipaddress.ip_address(resolved_ip)
    if ip.is_link_local or ip.is_loopback or ip.is_private or ip.is_reserved:
        raise EgressInvariantViolation(
            f"resolved peer {resolved_ip} is in a non-routable or metadata range"
        )

    entry = allowlist.get(hostname)
    if entry is None:
        raise EgressInvariantViolation(f"host {hostname} not on egress allowlist")

    # Name match is insufficient: bind resolved IP, SNI, cert pin, and audience.
    if str(ip) != entry.resolved_ip:
        raise EgressInvariantViolation(
            f"DNS answer {resolved_ip} != pinned {entry.resolved_ip} for {hostname} "
            "(possible rebinding)"
        )
    if sni != entry.sni:
        raise EgressInvariantViolation(f"SNI {sni} != pinned {entry.sni}")
    if peer_spki_sha256 != entry.spki_sha256:
        raise EgressInvariantViolation(
            f"certificate SPKI mismatch for {hostname}; refusing to attach token"
        )
    if token_audience != entry.token_audience:
        raise EgressInvariantViolation(
            f"token audience {token_audience} not scoped to {entry.token_audience}"
        )

    return entry


def emit_request(
    *,
    hostname: str,
    resolved_ip: str,
    sni: str,
    peer_spki_sha256: str,
    token_audience: str,
    allowlist: dict[str, PinnedPeer],
    is_redirect: bool,
    prior_peer: PinnedPeer | None,
    pool_key: tuple[str, str, int, str] | None,
) -> None:
    # A denied or re-decided peer invalidates any pooled socket keyed to it.
    if pool_key is not None and prior_peer is not None:
        expected = (prior_peer.sni, prior_peer.resolved_ip, 443, prior_peer.sni)
        if pool_key != expected:
            raise EgressInvariantViolation(
                f"pool key {pool_key} does not match authorized peer identity"
            )

    authorize_hop(
        hostname=hostname,
        resolved_ip=resolved_ip,
        sni=sni,
        peer_spki_sha256=peer_spki_sha256,
        token_audience=token_audience,
        allowlist=allowlist,
        is_redirect=is_redirect,
        prior_peer=prior_peer,
    )
    # Only after full identity binding may bytes (and the token) be emitted.
