# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-taint-propagation-across-a-tool-call-boundary-when-the-exfiltration-channel-is-a-permitted-untainted-sink.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-taint-propagation-across-a-tool-call-boundary-when-the-exfiltration-channel-is-a-permitted-untainted-sink.warrant.json
# Markdown SHA-256:   23b0a4b91b7f532aa325c4a3746b5af2ddea5e1609921c3c6d7415382192b8c2
# Code AST SHA-256:   882dd83bfc821e4167342d6bb7d2d0c1205a81290ce16ec167ddd4dba2be29c7
# Verified Classes:   ImplicitFlowTaintError, Label, SinkCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ImplicitFlowTaintError(RuntimeError):
    """Raised when a sink is reached via implicit (control/shape/timing) flow from tainted data."""
    pass


@dataclass
class Label:
    tainted: bool = False
    sources: tuple[str, ...] = field(default_factory=tuple)

    def join(self, other: "Label") -> "Label":
        return Label(
            tainted=self.tainted or other.tainted,
            sources=tuple(dict.fromkeys(self.sources + other.sources)),
        )


TAINTED = Label(tainted=True, sources=("untrusted_doc",))
CLEAN = Label()


@dataclass
class SinkCall:
    sink: str
    args: dict[str, Any]
    arg_labels: dict[str, Label]
    control_label: Label          # taint of the predicate(s) guarding this call
    shape_label: Label            # taint of any length/cardinality/timing derived from data
    observable: bool = True


def check_sink(call: SinkCall) -> None:
    """Deny if any observable dimension of the sink depends on tainted state."""
    if not call.observable:
        return
    for name, lbl in call.arg_labels.items():
        if lbl.tainted:
            raise ImplicitFlowTaintError(
                f"sink {call.sink!r}: argument {name!r} carries tainted value from {lbl.sources}"
            )
    if call.control_label.tainted:
        raise ImplicitFlowTaintError(
            f"sink {call.sink!r}: invocation is control-dependent on tainted predicate "
            f"from {call.control_label.sources}; value-level taint check is insufficient"
        )
    if call.shape_label.tainted:
        raise ImplicitFlowTaintError(
            f"sink {call.sink!r}: observable shape (length/timing/cardinality) derived from "
            f"tainted data {call.shape_label.sources}"
        )


def guarded_post(body: str, control: Label, shape: Label) -> None:
    # body is a clean literal, but the *choice* of literal was made by branching on taint.
    call = SinkCall(
        sink="http_post",
        args={"body": body},
        arg_labels={"body": CLEAN},
        control_label=control,
        shape_label=shape,
    )
    check_sink(call)


def exfiltrate_one_bit(secret: str, guess: str) -> None:
    # Classic implicit-flow leak: clean literal, tainted control dependence.
    payload = "yes" if secret[0] == guess else "no"
    guarded_post(payload, control=TAINTED, shape=CLEAN)


def exfiltrate_via_length(secret: str) -> None:
    # Clean literal, but length of padded body encodes the secret's length.
    pad = "x" * len(secret)
    guarded_post("report" + pad, control=CLEAN, shape=TAINTED)


if __name__ == "__main__":
    for fn in (lambda: exfiltrate_one_bit("a1b2", "a"),
               lambda: exfiltrate_via_length("a1b2")):
        try:
            fn()
        except ImplicitFlowTaintError as e:
            print("DENIED:", e)
