# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-mark-a-tainted-tool-call-argument-the-retrieval-to-invocation-taint-boundary-in-indirect-prompt-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-mark-a-tainted-tool-call-argument-the-retrieval-to-invocation-taint-boundary-in-indirect-prompt-injection.warrant.json
# Markdown SHA-256:   c15c64e76c9d3c011754506b986347c1aae0fd0b886c4872eca24b1844168679
# Code AST SHA-256:   fd7f048253dcd2d271790702a67f6de7eb474f471cfd7eafdefe90988e66ef85
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a tool-call argument field would be invoked as clean
    despite tracing to untrusted retrieved content, or when provenance
    is indeterminate and the runtime attempts to proceed anyway."""
    pass


UNTRUSTED = "untrusted"
TRUSTED = "trusted"
UNKNOWN = "unknown"

# Encodings the taint analyzer can decode. Anything outside this set
# forces the field to UNKNOWN (fail-closed), never to TRUSTED.
SUPPORTED_ENCODINGS = {"identity", "base64", "percent", "json_escape"}


def field_taint(field_value: str, sources: list[dict], encoding: str) -> str:
    """Return TRUSTED, UNTRUSTED, or UNKNOWN for one argument field.

    sources: [{"label": TRUSTED|UNTRUSTED, "decoded_text": str}, ...]
    """
    if encoding not in SUPPORTED_ENCODINGS:
        return UNKNOWN
    if not sources:
        return UNKNOWN  # no provenance recorded -> cannot claim clean
    for src in sources:
        if src["label"] == UNTRUSTED and src["decoded_text"] and (
            src["decoded_text"] in field_value
            or _encoded_overlap(src["decoded_text"], field_value, encoding)
        ):
            return UNTRUSTED
    if any(s["label"] == UNKNOWN for s in sources):
        return UNKNOWN
    return TRUSTED


def _encoded_overlap(needle: str, haystack: str, encoding: str) -> bool:
    # Placeholder for base64/percent/json_escape decode-and-compare.
    # Must return True if any supported decode of haystack contains needle.
    return False


def authorize_invocation(tool: str, args: dict, sources: list[dict],
                         encoding: str = "identity") -> dict:
    """Gate a tool invocation. Returns per-field taint report or raises."""
    report = {}
    for name, value in args.items():
        t = field_taint(str(value), sources, encoding)
        report[name] = t
        if t == UNKNOWN and tool in CONTROL_FIELD_TOOLS:
            raise TaintLaunderingError(
                f"{tool}.{name}: provenance indeterminate; refusing to invoke "
                f"a control field as clean (fail-closed)."
            )
    tainted_controls = [
        n for n, t in report.items()
        if t == UNTRUSTED and n in CONTROL_FIELDS
    ]
    if tainted_controls:
        raise TaintLaunderingError(
            f"{tool}: tainted control field(s) {tainted_controls}; "
            f"invocation blocked pending review."
        )
    return report


CONTROL_FIELDS = {"url", "endpoint", "recipient", "path", "command", "host"}
CONTROL_FIELD_TOOLS = {"http_post", "send_email", "exec", "write_file"}
