# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-across-mcp-tool-server-boundaries-when-a-capability-scoped-syscall-returns-data-whose-provenance-labe.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-across-mcp-tool-server-boundaries-when-a-capability-scoped-syscall-returns-data-whose-provenance-labe.warrant.json
# Markdown SHA-256:   665614a7b66818ffa8dbd0b33a6ddc9a7edc4eec12d95b4f7dc041034d1d0b26
# Code AST SHA-256:   7b3e7466fa2ce28041566902e4cc8583c7650d7ac625c2ae1920b71ab8f1aa2e
# Verified Classes:   Taint, TaintLaunderingError, ScopedObject, CallTrace, ServerScope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Taint(IntEnum):
    CLEAN = 0
    USER_INPUT = 1
    UNTRUSTED_WEB = 2
    SECRET = 3


def join(*labels: Taint) -> Taint:
    return max(labels, default=Taint.CLEAN)


class TaintLaunderingError(RuntimeError):
    """Raised when a result's declared taint is weaker than the observed data flow."""


@dataclass
class ScopedObject:
    path: str
    taint: Taint = Taint.CLEAN


@dataclass
class CallTrace:
    """Syscall trace for one MCP call, as observed by the sandbox (not self-reported)."""
    arg_taint: Taint
    objects_read: list[ScopedObject] = field(default_factory=list)
    objects_written: list[ScopedObject] = field(default_factory=list)


@dataclass
class ServerScope:
    objects: dict[str, ScopedObject] = field(default_factory=dict)

    def obj(self, path: str) -> ScopedObject:
        return self.objects.setdefault(path, ScopedObject(path))


def execute_call(scope: ServerScope, trace: CallTrace, declared_result_taint: Taint) -> Taint:
    """
    Apply the provenance-join invariant. On write, objects inherit the call's arg taint.
    On read, the result must carry at least the join of arg taint and read-object taint.
    """
    # 1. Join taint onto every object written during this call.
    for o in trace.objects_written:
        o.taint = join(o.taint, trace.arg_taint)

    # 2. Compute the mandatory lower bound for the result from observed reads.
    observed = join(trace.arg_taint, *(o.taint for o in trace.objects_read))

    # 3. Reject any result whose declared label is weaker than observed flow.
    if declared_result_taint < observed:
        raise TaintLaunderingError(
            f"result declared {declared_result_taint.name} but observed flow is "
            f"{observed.name} via reads of {[o.path for o in trace.objects_read]}"
        )
    return declared_result_taint


def demo_laundering_trace() -> None:
    scope = ServerScope()
    scratch = scope.obj("/var/scratch/staged.json")

    # Call 1: untrusted_web write into scoped object. Result is status-only (CLEAN).
    execute_call(
        scope,
        CallTrace(arg_taint=Taint.UNTRUSTED_WEB, objects_written=[scratch]),
        declared_result_taint=Taint.CLEAN,
    )
    assert scratch.taint == Taint.UNTRUSTED_WEB

    # Call 2: clean-labeled args, but the server reads the tainted object.
    # A runtime that only joins argument taint would accept CLEAN here.
    execute_call(
        scope,
        CallTrace(arg_taint=Taint.USER_INPUT, objects_read=[scratch]),
        declared_result_taint=Taint.USER_INPUT,  # laundering attempt: should fail
    )
