# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-sever-a-tainted-value-s-provenance-when-prompt-injection-crosses-a-tool-call-return-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-sever-a-tainted-value-s-provenance-when-prompt-injection-crosses-a-tool-call-return-boundary.warrant.json
# Markdown SHA-256:   876cc86f724f5a1fc2bf89d1ef1a935edd5f18546c17501c21b8d5a70f617dd0
# Code AST SHA-256:   7c096f08649a22e2ed42d50ed079e53eb2113d8442d4a93ab0bf90806f9be4ff
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a side-effecting tool argument derives from untrusted content
    but the call was classified as model-generated/trusted."""
    pass


TRUST_ORDER = {"trusted": 0, "internal": 1, "untrusted:external": 2}
SIDE_EFFECTING = {"create_task", "send_email", "issue_payment", "transfer_funds"}
FREE_FORM_FIELDS = {"note", "body", "query", "amount", "recipient", "assignee"}


def min_trust(labels):
    if not labels:
        return "untrusted:external"  # no provenance => assume worst
    return max(labels, key=lambda l: TRUST_ORDER[l])


def authorize_tool_call(call, context_taint, derivation_map):
    """
    call: {"name": str, "args": {field: value}}
    context_taint: set of trust labels currently live in context
    derivation_map: {arg_value_hash: [source_labels]} produced by the tracker
    """
    if call["name"] not in SIDE_EFFECTING:
        return True

    for field, value in call["args"].items():
        if field not in FREE_FORM_FIELDS:
            continue
        sources = derivation_map.get(hash_value(value))
        if sources is None:
            # No derivation edge recorded. The framework cannot prove the value
            # is untainted, so it must assume the worst label in context.
            effective = min_trust(list(context_taint))
            if TRUST_ORDER[effective] > TRUST_ORDER["internal"]:
                raise ProvenanceLaunderingError(
                    f"arg {field!r}={value!r} has no derivation edge; "
                    f"context taint={effective}; refusing side-effecting call "
                    f"{call['name']!r}"
                )
            continue
        effective = min_trust(sources)
        if TRUST_ORDER[effective] > TRUST_ORDER["internal"]:
            raise ProvenanceLaunderingError(
                f"arg {field!r}={value!r} derives from {sources}; "
                f"effective trust={effective}; refusing {call['name']!r}"
            )
    return True


def hash_value(v):
    # Framework-side stable hash of the exact emitted string; the tracker
    # must record the same hash when it observes the model output.
    return hash(str(v))
