# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-capability-sandbox-s-egress-allowlist-silently-authorizes-a-tool-call-whose-arguments-were-rewritten-after-policy-e.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-capability-sandbox-s-egress-allowlist-silently-authorizes-a-tool-call-whose-arguments-were-rewritten-after-policy-e.warrant.json
# Markdown SHA-256:   2db6fb90db3ebea826021ab8692608c79c78525af5da6a1792c40f62212e2d41
# Code AST SHA-256:   9cb06694d77a38b04230d32079862adef961bc1eaf6fed38d60fc39f608014b4
# Verified Classes:   EgressCheckToUseGap, AuthorizedDestination, DispatchTarget
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import ipaddress
from dataclasses import dataclass
from typing import Optional


class EgressCheckToUseGap(RuntimeError):
    """Raised when the address the socket will dial diverges from the address policy authorized."""
    pass


@dataclass(frozen=True)
class AuthorizedDestination:
    scheme: str
    canonical_host: str
    resolved_ip: ipaddress.IPv4Address | ipaddress.IPv6Address
    port: int


@dataclass(frozen=True)
class DispatchTarget:
    scheme: str
    canonical_host: str
    resolved_ip: ipaddress.IPv4Address | ipaddress.IPv6Address
    port: int


def canonicalize_host(raw_host: str) -> str:
    # Strip userinfo confusion: only the segment after the last '@' is the host.
    host = raw_host.rsplit("@", 1)[-1]
    # Strip trailing root label and case-fold.
    host = host.rstrip(".").lower()
    return host


def authorize(
    allowlist: frozenset[str],
    scheme: str,
    raw_url_authority: str,
    port: int,
    resolver,
) -> AuthorizedDestination:
    host = canonicalize_host(raw_url_authority)
    if host not in allowlist:
        raise EgressCheckToUseGap(
            f"host {host!r} not in egress allowlist {sorted(allowlist)!r}"
        )
    # Resolve ONCE, here, and pin the address. This is the authorization unit.
    resolved_ip = resolver(host)
    return AuthorizedDestination(
        scheme=scheme,
        canonical_host=host,
        resolved_ip=resolved_ip,
        port=port,
    )


def dispatch(
    authorized: AuthorizedDestination,
    target: DispatchTarget,
    resolver,
) -> None:
    # The connection layer must dial the pinned IP, never re-resolve the name.
    if target.resolved_ip != authorized.resolved_ip:
        raise EgressCheckToUseGap(
            "resolved address diverged from authorized address: "
            f"authorized={authorized.resolved_ip} target={target.resolved_ip}"
        )
    if target.canonical_host != authorized.canonical_host:
        raise EgressCheckToUseGap(
            "canonical host diverged from authorized host: "
            f"authorized={authorized.canonical_host!r} target={target.canonical_host!r}"
        )
    if (target.scheme, target.port) != (authorized.scheme, authorized.port):
        raise EgressCheckToUseGap(
            "scheme/port diverged from authorization: "
            f"authorized={authorized.scheme}:{authorized.port} "
            f"target={target.scheme}:{target.port}"
        )
    # ... open socket to target.resolved_ip directly; do not consult DNS again ...
