# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-dynamic-information-flow-taint-labels-across-tool-call-boundaries-but-silently-launders-them-at-the-schema-co.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-dynamic-information-flow-taint-labels-across-tool-call-boundaries-but-silently-launders-them-at-the-schema-co.warrant.json
# Markdown SHA-256:   ee87978b9f22b1e33834c77084e1e2a1f442cc230fda4229eb91d551047b26aa
# Code AST SHA-256:   4d1e874dcd2518df6fbef54b00152af7b027d7a65f2ba184f83226b128866fcd
# Verified Classes:   Integrity, Label, TaintLaunderingError, OpaqueBoundaryError, Endorsement
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum
from typing import Any


class Integrity(IntEnum):
    UNTRUSTED = 0
    DERIVED = 1
    TRUSTED = 2


@dataclass(frozen=True)
class Label:
    source_id: str
    integrity: Integrity


class TaintLaunderingError(RuntimeError):
    """Raised when a propagation rule raises integrity class without a registered endorsement."""


class OpaqueBoundaryError(RuntimeError):
    """Raised when an opaque tool (internal model/service) accepts tainted arguments."""


@dataclass(frozen=True)
class Endorsement:
    justification: str
    reviewer: str


def propagate(
    rule_name: str,
    inputs: list[Label],
    output_integrity: Integrity,
    endorsement: Endorsement | None = None,
) -> Label:
    """Apply a propagation rule, enforcing the monotonicity invariant.

    A rule may only raise integrity class above the input join if it carries an
    explicit Endorsement. This makes laundering a hard error rather than a
    silent policy bypass.
    """
    if not inputs:
        raise TaintLaunderingError(f"rule {rule_name!r} has no input labels")
    input_join = max(l.integrity for l in inputs)
    if output_integrity > input_join and endorsement is None:
        raise TaintLaunderingError(
            f"rule {rule_name!r} raises integrity {input_join.name} -> "
            f"{output_integrity.name} without a registered endorsement; "
            f"this is laundering, not propagation"
        )
    source = inputs[0].source_id
    return Label(source_id=source, integrity=output_integrity)


def invoke_opaque_tool(
    tool_name: str,
    args: list[Label],
    opaque: bool,
    allow_tainted: bool = False,
) -> Label:
    """Invoke a tool that crosses an internal model/service boundary.

    Opaque tools drop labels at their internal boundary, so their output must be
    conservatively re-labeled to the input join, and they must not accept tainted
    arguments unless explicitly allowlisted.
    """
    if opaque and not allow_tainted:
        tainted = [a for a in args if a.integrity <= Integrity.DERIVED]
        if tainted:
            raise OpaqueBoundaryError(
                f"opaque tool {tool_name!r} received tainted arg "
                f"(integrity={tainted[0].integrity.name}); labels would be "
                f"dropped at its internal boundary"
            )
    input_join = max((a.integrity for a in args), default=Integrity.UNTRUSTED)
    return Label(source_id=f"opaque:{tool_name}", integrity=input_join)


def run_extract_field(doc: Label) -> Label:
    # The historical bug: "scalar extraction => DERIVED" with no endorsement.
    # Correct behavior: reject the upgrade unless an Endorsement is supplied.
    return propagate(
        rule_name="extract_field/scalar",
        inputs=[doc],
        output_integrity=Integrity.DERIVED,
        endorsement=None,  # schema-conformance is NOT a valid justification
    )


if __name__ == "__main__":
    untrusted_doc = Label(source_id="fetch_url:doc", integrity=Integrity.UNTRUSTED)
    try:
        run_extract_field(untrusted_doc)
    except TaintLaunderingError as e:
        print(f"blocked at propagation: {e}")

    try:
        invoke_opaque_tool(
            tool_name="lookup_account",
            args=[Label(source_id="extract_field", integrity=Integrity.DERIVED)],
            opaque=True,
        )
    except OpaqueBoundaryError as e:
        print(f"blocked at opaque boundary: {e}")
