# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-call-s-argument-provenance-not-its-argument-value-as-the-sandbox-authorization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-call-s-argument-provenance-not-its-argument-value-as-the-sandbox-authorization-boundary.warrant.json
# Markdown SHA-256:   1dcc103affeea4df926bce013f28a56645d2f60c61b2666264b0bd6ca1516d55
# Code AST SHA-256:   ea9ad106214ad895498ae0dc895c39d9a83c6d46fa140f110eadf4b8cc0a51cb
# Verified Classes:   TaintViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintViolation(RuntimeError):
    """Raised when an egress tool call carries untrusted-derived provenance."""
    pass


TRUSTED = frozenset({"trusted:operator"})
UNTRUSTED_PREFIX = "untrusted:"


def is_untrusted(label: str) -> bool:
    return label.startswith(UNTRUSTED_PREFIX)


def authorize_tool_call(
    tool_name: str,
    arg_taint_set: frozenset[str],
    sink_class: str,  # "egress" | "read"
    value_check_passed: bool,
) -> str:
    """Return 'authorize' | 'authorize_re_taint' | 'deny_escalate'.

    Invariant: unknown provenance is treated as untrusted for egress sinks.
    """
    if not arg_taint_set:
        # Unattributable argument: fail closed for egress.
        if sink_class == "egress":
            raise TaintViolation(
                f"tool={tool_name!r} emitted an argument with unknown provenance; "
                "egress sinks require attributable trusted provenance"
            )
        return "authorize_re_taint"

    has_untrusted = any(is_untrusted(lbl) for lbl in arg_taint_set)

    if not has_untrusted:
        if not value_check_passed:
            raise TaintViolation(
                f"tool={tool_name!r} trusted argument failed value check"
            )
        return "authorize"

    if sink_class == "egress":
        # Do not silently allow; require out-of-band operator confirmation.
        raise TaintViolation(
            f"tool={tool_name!r} egress blocked: argument tainted by "
            f"{sorted(l for l in arg_taint_set if is_untrusted(l))}; "
            "operator confirmation token required"
        )

    # Read with untrusted-derived argument: permit, but propagate taint.
    return "authorize_re_taint"


def propagate_read_output(output_taint: frozenset[str]) -> frozenset[str]:
    """Re-taint read outputs so the taint survives to the next hop."""
    derived = frozenset({f"{UNTRUSTED_PREFIX}derived"})
    return output_taint | derived
