# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-tool-s-declared-egress-policy-as-void-because-the-sandbox-resolves-dns-before-the-policy-predicate.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-tool-s-declared-egress-policy-as-void-because-the-sandbox-resolves-dns-before-the-policy-predicate.warrant.json
# Markdown SHA-256:   40a91b95d440a1c9f7afb58a987e13e65366b86c335a2c55ba9c1c3400869e3e
# Code AST SHA-256:   752b24e7012671537d799915f7b6e4c2d9c41a578e2b2d3abf23915c8b52b721
# Verified Classes:   EgressPolicyVoid
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EgressPolicyVoid(RuntimeError):
    """Raised when the sandbox cannot assert the policy subject at connect time."""
    pass


def enforce_egress(manifest: dict, connect: dict) -> str:
    """
    manifest: {"allowed_hosts": [...], "allowed_ips": [...], "transport": "tls"|"plain"}
    connect:  {"sni": str|None, "host_header": str|None, "dst_ip": str}
    Returns the enforcement subject if the decision is sound.
    Raises EgressPolicyVoid if the manifest's host allow-list cannot be enforced.
    """
    allowed_hosts = set(manifest.get("allowed_hosts", []))
    allowed_ips = set(manifest.get("allowed_ips", []))
    transport = manifest.get("transport")

    # The only sound subject is one the untrusted process cannot substitute.
    subject = connect.get("sni") or connect.get("host_header")

    if subject is None:
        # Plaintext or IP-literal connect: no hostname assertion reached the proxy.
        # The hostname allow-list is void. Only an explicit IP allow-list can bind.
        if connect["dst_ip"] in allowed_ips:
            return f"ip:{connect['dst_ip']}"
        raise EgressPolicyVoid(
            f"host allow-list {sorted(allowed_hosts)} is unenforceable: "
            f"connect to {connect['dst_ip']} carried no SNI/Host and no matching "
            f"allowed_ips entry; resolution may have been substituted in-sandbox"
        )

    if subject not in allowed_hosts:
        # Subject is asserted but not permitted.
        raise EgressPolicyVoid(
            f"asserted subject {subject!r} not in allow-list {sorted(allowed_hosts)}"
        )

    if transport != "tls" and connect.get("sni") is None:
        # Host header on plaintext is attacker-controlled; not a sound subject.
        raise EgressPolicyVoid(
            f"plaintext Host {subject!r} is not a trustworthy subject; "
            f"require TLS SNI or an explicit allowed_ips entry"
        )

    return f"host:{subject}"
