# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-laundering-exfiltration-path-across-multi-hop-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-taint-laundering-exfiltration-path-across-multi-hop-tool-calls.warrant.json
# Markdown SHA-256:   7bb65b5780abdfbee79e9c44c16ca73c27e180a6bb840e3555da656ea70d7a80
# Code AST SHA-256:   42c6c640d8d393c82958449ed074273871ebb28624bee16f55d46b39788914d7
# Verified Classes:   TaintLaunderingError, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when an egress call's argument derives from an untrusted source
    through a non-content-preserving tool without an audited declassification."""


@dataclass(frozen=True)
class ToolCall:
    call_id: str
    tool: str
    inputs: tuple[str, ...]          # call_ids of upstream calls
    output_taint: frozenset[str]     # labels attached to this call's output
    content_preserving: bool         # True only if provably output ⊆ input


CONTENT_PRESERVING = {"parse_json", "regex_fixed", "hash", "count"}
EGRESS_SINKS = {"http_post", "send_message", "write_file", "dns_lookup"}


def _upstream_taint(call: ToolCall, by_id: dict[str, ToolCall]) -> frozenset[str]:
    taint: set[str] = set()
    for cid in call.inputs:
        upstream = by_id[cid]
        taint |= upstream.output_taint
        taint |= _upstream_taint(upstream, by_id)
    return frozenset(taint)


def assert_egress_safe(call: ToolCall, by_id: dict[str, ToolCall]) -> None:
    if call.tool not in EGRESS_SINKS:
        return

    derived = _upstream_taint(call, by_id)
    if "untrusted" not in derived:
        return

    # Walk the derivation path: every node carrying untrusted taint must be
    # content-preserving, or an explicit declassification must be recorded.
    for cid in call.inputs:
        node = by_id[cid]
        if "untrusted" in node.output_taint and not node.content_preserving:
            raise TaintLaunderingError(
                f"egress blocked: call {call.call_id} ({call.tool}) derives from "
                f"untrusted source via non-content-preserving tool "
                f"{node.tool} ({node.call_id}); taint was laundered, not removed"
            )

    # Even if all intermediate nodes look clean, a decreasing-taint path with a
    # tainted root is a laundering signature.
    if "untrusted" in derived and "untrusted" not in call.output_taint:
        raise TaintLaunderingError(
            f"egress blocked: call {call.call_id} has untrusted derivation but "
            f"untainted argument; monotone-non-decreasing taint invariant violated"
        )


def audit_trace(calls: Iterable[ToolCall]) -> list[str]:
    by_id = {c.call_id: c for c in calls}
    violations: list[str] = []
    for call in by_id.values():
        try:
            assert_egress_safe(call, by_id)
        except TaintLaunderingError as exc:
            violations.append(str(exc))
    return violations
