# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-a-tool-re-serializes-injected-content-across-an-information-flow-label-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-when-a-tool-re-serializes-injected-content-across-an-information-flow-label-boundary.warrant.json
# Markdown SHA-256:   07844f265f9b4e4bd7aa9994b63261e3519b47d44dc381a5359eeb36ef34f3e9
# Code AST SHA-256:   5f0e785620f38320ce8caaeef5b49eff696ba0e4e068774313cf920400ca95bf
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a tool boundary returns content whose taint label
    is not a superset of the join of its inputs, with no audited
    declassification proof attached."""
    pass


def propagate_across_tool_boundary(
    input_labels: set[str],
    tool_output: dict,
    declassification_proof: dict | None = None,
) -> set[str]:
    """Enforce the monotonic-join invariant at a tool boundary.

    input_labels: labels present on the arguments passed to the tool.
    tool_output:  must contain 'content' and 'label_set'.
                  'label_set' is the taint the tool claims for its output.
    declassification_proof: optional dict with keys
                  {'sanitizer', 'independent_of'} asserting the output was
                  derived only from untainted regions.
    """
    required = set(input_labels)
    claimed = set(tool_output.get("label_set", []))

    # Soundness check: output taint must cover input taint unless a
    # declassification proof is supplied AND names the removed labels.
    missing = required - claimed
    if missing:
        if declassification_proof is None:
            raise TaintLaunderingError(
                f"Tool boundary dropped taint {sorted(missing)} with no "
                f"declassification proof; output label_set={sorted(claimed)}. "
                f"Treating as laundering, not as clean."
            )
        proven = set(declassification_proof.get("independent_of", []))
        if not missing.issubset(proven):
            raise TaintLaunderingError(
                f"Declassification proof does not cover dropped labels "
                f"{sorted(missing - proven)}; proof only covers {sorted(proven)}."
            )

    # Unknown-field closure: any metadata the serializer discarded is
    # treated as taint-bearing by default.
    if tool_output.get("dropped_unknown_fields"):
        claimed |= required

    return claimed


def guarded_tool_call(tool, args, arg_labels):
    out = tool(args)
    if "label_set" not in out:
        # A tool that returns content without a label is a laundering
        # surface by construction; refuse rather than guess.
        raise TaintLaunderingError(
            f"Tool {getattr(tool, '__name__', tool)!r} returned content "
            f"without a label_set; cannot verify monotonic join."
        )
    return out["content"], propagate_across_tool_boundary(
        arg_labels, out, out.get("declassification_proof")
    )
