# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-mistakes-a-sanitized-tool-argument-for-a-de-tainted-one-during-prompt-injection-driven-exfiltration-attempts.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-mistakes-a-sanitized-tool-argument-for-a-de-tainted-one-during-prompt-injection-driven-exfiltration-attempts.warrant.json
# Markdown SHA-256:   8f7e9930b443483309c3ab58789671be9899106476b42cdc52190cf4849b5489
# Code AST SHA-256:   ecb625d2a6c222a7390aa513bfb8a57cadd7494492d309948c3181467f444a73
# Verified Classes:   TaintLaunderingError, Provenance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a tool argument's provenance root is untrusted despite a clean-looking literal."""
    pass

from dataclasses import dataclass, field
from typing import Optional
from urllib.parse import urlsplit, urljoin

TRUSTED_ROOTS = {"user_instruction"}
TRUSTED_HOSTS = {"docs.internal.example"}

@dataclass
class Provenance:
    root: str
    nodes: tuple = field(default_factory=tuple)
    def is_trusted(self) -> bool:
        return self.root in TRUSTED_ROOTS and not self.nodes

def build_arg(base: Provenance, fragment: Provenance, joined: str) -> tuple[str, Provenance]:
    # Derived strings inherit the union of operands' untrusted nodes; trust is never transitive.
    nodes = tuple(set(base.nodes) | set(fragment.nodes))
    root = base.root if base.root == fragment.root else "mixed"
    if fragment.root not in TRUSTED_ROOTS:
        nodes = nodes + (fragment.root,)
    return joined, Provenance(root=root, nodes=nodes)

def resolve_and_check(url: str, prov: Provenance, fetcher_parser=urlsplit) -> str:
    parts = fetcher_parser(url)
    host = parts.hostname  # executor's parser, not the taint layer's
    if prov.nodes or prov.root not in TRUSTED_ROOTS:
        raise TaintLaunderingError(
            f"argument {url!r} has untrusted provenance nodes {prov.nodes!r}"
        )
    if host not in TRUSTED_HOSTS:
        raise TaintLaunderingError(
            f"argument {url!r} resolves to non-allowlisted host {host!r} under executor parser"
        )
    return url

def safe_fetch(base_url: str, base_prov: Provenance, injected_path: str) -> str:
    injected_prov = Provenance(root="untrusted_document", nodes=("injection",))
    joined = urljoin(base_url, injected_path)
    _, derived_prov = build_arg(base_prov, injected_prov, joined)
    # The repair loop's reformulation is still tainted; refuse, do not retry.
    return resolve_and_check(joined, derived_prov)
