# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-egress-scope-erosion-when-a-policy-engine-s-tool-allowlist-and-its-network-egress-filter-are-evaluated-against-differ.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-egress-scope-erosion-when-a-policy-engine-s-tool-allowlist-and-its-network-egress-filter-are-evaluated-against-differ.warrant.json
# Markdown SHA-256:   73cabe13c66457d0823adab98747b6b86770a63d37008f40f222ff4ceed0f88a
# Code AST SHA-256:   8e7c61651fa2119a5b4d6aa18f163b89c6a6c635dcef825712568f92d867b0d5
# Verified Classes:   EgressProjectionMismatch, NormalizedCall
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from urllib.parse import urlsplit


class EgressProjectionMismatch(RuntimeError):
    """Raised when the tool gate and egress gate disagree on the destination."""


@dataclass(frozen=True)
class NormalizedCall:
    tool: str
    host: str
    port: int
    scheme: str


ALLOWED_TOOLS = frozenset({"http_fetch"})
ALLOWED_EGRESS = frozenset({("https", "api.internal.example", 443)})


def normalize_call(tool: str, raw_url: str) -> NormalizedCall:
    # Single canonicalization point. Both gates consume this output.
    try:
        parts = urlsplit(raw_url)
        if not parts.hostname or parts.scheme not in {"http", "https"}:
            raise ValueError("unparseable authority")
        port = parts.port or (443 if parts.scheme == "https" else 80)
        host = parts.hostname.rstrip(".").lower()
    except (ValueError, AttributeError) as exc:
        # Fail closed: ambiguity is denial, never "no decision".
        raise EgressProjectionMismatch(
            f"cannot normalize egress target for {raw_url!r}: {exc}"
        ) from exc
    return NormalizedCall(tool=tool, host=host, port=port, scheme=parts.scheme)


def admit(tool: str, raw_url: str) -> NormalizedCall:
    call = normalize_call(tool, raw_url)
    if call.tool not in ALLOWED_TOOLS:
        raise EgressProjectionMismatch(f"tool {call.tool!r} not in allowlist")
    target = (call.scheme, call.host, call.port)
    if target not in ALLOWED_EGRESS:
        # The dispatcher will use call.host/call.port, not raw_url,
        # so this decision is authoritative over the actual egress.
        raise EgressProjectionMismatch(
            f"egress target {target!r} not in allowlist "
            f"(normalized from {raw_url!r})"
        )
    return call


def dispatch(call: NormalizedCall) -> None:
    # Dispatcher MUST consume the normalized tuple, never raw_url.
    assert call.host == "api.internal.example" and call.port == 443
    # ... perform request against call.host:call.port ...


# The fragment/userinfo differential that defeated the split-parser engine:
try:
    admit("http_fetch", "https://api.internal.example#@169.254.169.254/")
except EgressProjectionMismatch as err:
    print("denied:", err)
