# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-egress-taint-laundering-through-capability-scoped-tool-composition-and-why-per-call-policy-checks-cannot-see-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-egress-taint-laundering-through-capability-scoped-tool-composition-and-why-per-call-policy-checks-cannot-see-it.warrant.json
# Markdown SHA-256:   7b2156bea627fdbf55bd09f944cda328c38efba8d27d8128ccd5272c416481bd
# Code AST SHA-256:   844e3f4ad5dccefdf692bd35e212e0454e9689f1c2d209993fa54ed6cbda6053
# Verified Classes:   TaintLaunderingError, ProvenanceEnvelope, ToolScope, PolicyEngine
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a value's taint set collapses across a call boundary
    without an explicit declassify warrant, indicating egress-taint
    laundering through capability-scoped tool composition."""


@dataclass
class ProvenanceEnvelope:
    value: Any
    taint: frozenset[str]
    envelope_id: str
    # Stable identity minted at return time; survives re-serialization.

    def canonical_bytes(self) -> bytes:
        return json.dumps(self.value, sort_keys=True, separators=(",", ":")).encode()


@dataclass
class ToolScope:
    name: str
    egress_scope: str            # e.g. "public", "secret"
    propagates_taint: bool       # False => taint-opaque (echo-capable)
    output_declared_scope: str


@dataclass
class PolicyEngine:
    provenance: dict[str, ProvenanceEnvelope] = field(default_factory=dict)
    declassify_warrants: set[str] = field(default_factory=set)

    def register(self, env: ProvenanceEnvelope) -> None:
        self.provenance[env.envelope_id] = env

    def _resolve_taint(self, arg: Any) -> frozenset[str]:
        # Resolve taint by envelope ID if the arg is an envelope, else by
        # content hash. A miss returns "unknown", never "clean".
        if isinstance(arg, ProvenanceEnvelope):
            return arg.taint
        h = hashlib.sha256(
            json.dumps(arg, sort_keys=True, separators=(",", ":")).encode()
        ).hexdigest()
        for env in self.provenance.values():
            if hashlib.sha256(env.canonical_bytes()).hexdigest() == h:
                return env.taint
        return frozenset({"taint-unknown"})

    def check_call(self, tool: ToolScope, args: list[Any], result: Any) -> ProvenanceEnvelope:
        input_taint = frozenset().union(*(self._resolve_taint(a) for a in args)) if args else frozenset()

        # Invariant 1: taint-opaque tools cannot receive tainted input
        # without a declassify warrant.
        if not tool.propagates_taint and input_taint - {"public"}:
            if tool.name not in self.declassify_warrants:
                raise TaintLaunderingError(
                    f"tool {tool.name!r} is taint-opaque but received "
                    f"taint {sorted(input_taint)} without declassify warrant"
                )

        # Invariant 2: egress scope must dominate input taint.
        if tool.egress_scope == "public" and input_taint - {"public"}:
            raise TaintLaunderingError(
                f"egress scope 'public' for {tool.name!r} cannot carry "
                f"taint {sorted(input_taint)} to a public sink"
            )

        # Invariant 3: output taint is the union of input taint and declared
        # output scope. A declared-clean output that echoes tainted input
        # must inherit the taint, not shed it.
        output_taint = input_taint | {tool.output_declared_scope}
        if tool.propagates_taint:
            output_taint = output_taint | self._resolve_taint(result)
        env = ProvenanceEnvelope(
            value=result,
            taint=frozenset(output_taint),
            envelope_id=hashlib.sha256(
                (tool.name + json.dumps(result, sort_keys=True, default=str)).encode()
            ).hexdigest(),
        )
        self.register(env)
        return env


def run_chain(engine: PolicyEngine, tools: dict[str, ToolScope]) -> None:
    # Step 1: vault read returns a secret-tainted value.
    secret = ProvenanceEnvelope(
        value={"token": "sk-live-abc"},
        taint=frozenset({"secret"}),
        envelope_id="env-vault-1",
    )
    engine.register(secret)

    # Step 2: agent re-serializes the token to satisfy a validator's type
    # expectation. The re-serialized string is a *new* value; content-hash
    # lookup will miss, and the engine resolves taint as 'taint-unknown'.
    reserialized = json.loads(json.dumps(secret.value["token"]))
    validator = tools["format.validate"]
    echo_env = engine.check_call(validator, [reserialized], {"valid": True, "echo": reserialized})

    # Step 3: agent posts the echo to a public webhook. The echo carries
    # 'taint-unknown' + 'public' + 'secret' (via union), so the public
    # sink check must reject it.
    sink = tools["http.post"]
    try:
        engine.check_call(sink, [echo_env], {"status": 200})
    except TaintLaunderingError as exc:
        raise TaintLaunderingError(
            "chain-level egress violation: tainted value reached public sink "
            "via taint-opaque validator; per-call checks passed but chain "
            "invariant failed"
        ) from exc


if __name__ == "__main__":
    engine = PolicyEngine()
    tools = {
        "format.validate": ToolScope(
            name="format.validate",
            egress_scope="public",
            propagates_taint=False,       # echo-capable: must be taint-opaque
            output_declared_scope="public",
        ),
        "http.post": ToolScope(
            name="http.post",
            egress_scope="public",
            propagates_taint=True,
            output_declared_scope="public",
        ),
    }
    run_chain(engine, tools)
