# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-because-a-dynamic-information-flow-label-survived-a-boundary-the-agent-did-not-re-validate.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tool-result-because-a-dynamic-information-flow-label-survived-a-boundary-the-agent-did-not-re-validate.warrant.json
# Markdown SHA-256:   0de66ad6005ad737691393e691ff85bef53e975fa550af0d2976d20c369bef3e
# Code AST SHA-256:   2b4b50acc4d226fcce19bbb6062261788aa66302602a0dc51ad846b6cf1acf44
# Verified Classes:   LabelLaunderingError, AuthorityEscalationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class LabelLaunderingError(RuntimeError):
    """Raised when a taint label fails to survive a tool boundary intact."""
    pass


class AuthorityEscalationError(RuntimeError):
    """Raised when a label's authority is widened without explicit declassification."""
    pass


def revalidate_at_sink(value: dict, sink_class: str) -> dict:
    """Re-validate the label on the immediately preceding hop before a privileged sink.

    Fail-closed: a missing label is treated as maximal taint, not as trust.
    """
    label = value.get("label")
    if label is None:
        # Boundary dropped the label: this is the laundering condition.
        raise LabelLaunderingError(
            f"value reached sink '{sink_class}' with no label; "
            "treating as maximal taint and quarantining"
        )

    provenance = label.get("provenance")
    authority = label.get("authority")

    if provenance is None or authority is None:
        raise LabelLaunderingError(
            f"incomplete label {label!r} at sink '{sink_class}'"
        )

    # Authority may only narrow across a boundary, never widen.
    permitted = {"read_only": {"read"}, "internal_write": {"read", "write"}}
    if sink_class not in permitted.get(authority, set()):
        # A read_only value feeding a write sink: do not auto-promote.
        raise AuthorityEscalationError(
            f"authority '{authority}' does not permit sink '{sink_class}'; "
            "quarantine and require explicit declassification"
        )

    return value


def dispatch_tool_call(tool: dict, payload: dict) -> dict:
    """Dispatch with a label-required schema; reject unlabeled input at the boundary."""
    schema = tool.get("input_schema", {})
    if "label" not in schema.get("required", []):
        raise LabelLaunderingError(
            f"tool '{tool['name']}' schema does not require a label field; "
            "this is a laundering surface and must be rejected"
        )
    if "label" not in payload:
        raise LabelLaunderingError(
            f"payload to '{tool['name']}' missing label; fail-closed"
        )
    return tool["fn"](revalidate_at_sink(payload, tool["sink_class"]))
