# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-value-that-has-passed-through-a-tool-call-boundary-rather-than-trusting-the-label-that-sur.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-tainted-value-that-has-passed-through-a-tool-call-boundary-rather-than-trusting-the-label-that-sur.warrant.json
# Markdown SHA-256:   1d92911707b52ef94d66fff81b886931180079ed32214f9baaa5bdb60aea61ed
# Code AST SHA-256:   7d57cce05d17269c529384a7ec32efd09f4f637b058612fdda8b3b9a16f53ffc
# Verified Classes:   TaintBoundaryViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import hmac


class TaintBoundaryViolation(RuntimeError):
    """Raised when a taint label crossing a tool boundary cannot be trusted."""


TRUSTED_TOOL_REGISTRY = {
    "fetch_doc": "untrusted",   # external content
    "write_file": "trusted",    # privileged sink
}


def _mac(secret: bytes, payload: bytes, label: str, tool_id: str, nonce: str) -> str:
    msg = b"|".join([payload, label.encode(), tool_id.encode(), nonce.encode()])
    return hmac.new(secret, msg, hashlib.sha256).hexdigest()


def resolve_effective_label(
    secret: bytes,
    tool_id: str,
    payload: bytes,
    asserted_label: dict | None,
) -> str:
    """
    Compute the label the receiver will actually honor.

    Rules:
      - Registry-derived trust class is the floor; asserted label may only
        raise taint, never lower it.
      - An asserted label claiming *less* taint than the registry floor, or
        failing MAC verification, is a boundary violation.
    """
    floor = TRUSTED_TOOL_REGISTRY.get(tool_id)
    if floor is None:
        raise TaintBoundaryViolation(f"tool {tool_id!r} not in trust registry")

    if asserted_label is None:
        return floor

    claimed = asserted_label.get("integrity")
    nonce = asserted_label.get("nonce", "")
    mac = asserted_label.get("mac", "")
    expected = _mac(secret, payload, claimed or "", tool_id, nonce)

    if not hmac.compare_digest(mac, expected):
        # Replayed or forged label: downgrade to floor, do not trust claim.
        raise TaintBoundaryViolation(
            f"taint label MAC mismatch for tool {tool_id!r} "
            f"(claimed={claimed!r}, nonce={nonce!r}) — possible replay"
        )

    # Monotonic join: asserted may only increase taint relative to floor.
    order = {"trusted": 0, "untrusted": 1}
    if order.get(claimed, 1) < order[floor]:
        raise TaintBoundaryViolation(
            f"label laundering attempt: floor={floor!r} claimed={claimed!r}"
        )

    return claimed


def dispatch_tool_call(secret: bytes, tool_id: str, payload: bytes, raw_args: dict) -> str:
    # Strip any model-authored taint field before it can be replayed.
    raw_args.pop("taint", None)
    asserted = raw_args.get("_taint_envelope")
    try:
        return resolve_effective_label(secret, tool_id, payload, asserted)
    except TaintBoundaryViolation:
        # Quarantine path: emit boundary event, force untrusted, continue.
        return "untrusted"
