# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-taint-tracks-a-secret-into-a-tool-call-whose-schema-permits-lossy-re-encoding.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-taint-tracks-a-secret-into-a-tool-call-whose-schema-permits-lossy-re-encoding.warrant.json
# Markdown SHA-256:   68fe3f57a0dc9505dba3b0b88081bee6359a5fa4e25b8104821e5b1933462e84
# Code AST SHA-256:   586c83bc2905c30f2b883f9def763d4668444bf41b2ea812e065395612ad1c17
# Verified Classes:   TaintEgressViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintEgressViolation(RuntimeError):
    """Raised when a labeled value reaches an egress sink through a lossy re-encoding
    that defeats byte-identity matching. Signals that the guard must fall back to
    provenance-class allowlisting, not that the call is merely suspicious."""
    pass


def authorize_egress(arg_value: str, arg_label: str | None, sink: str,
                     allowlist: dict[str, set[str]],
                     closure_matcher) -> None:
    # Primary control: provenance-class allowlist. Does not depend on byte match.
    if arg_label is not None:
        permitted_sinks = allowlist.get(arg_label, set())
        if sink not in permitted_sinks:
            raise TaintEgressViolation(
                f"provenance class {arg_label!r} not allowlisted for sink {sink!r}; "
                f"blocked regardless of byte identity"
            )

    # Secondary control: closure matcher over the transformation set.
    # Fires on prefix, split-field reconstruction, line-wrapped base64, etc.
    hit = closure_matcher(arg_value)
    if hit is not None:
        raise TaintEgressViolation(
            f"sink {sink!r} received derived form of labeled value "
            f"(matched transformation {hit!r}); egress blocked"
        )


def guarded_tool_call(tool_name: str, args: dict, arg_labels: dict[str, str | None],
                      allowlist: dict[str, set[str]], closure_matcher) -> None:
    for field, value in args.items():
        if not isinstance(value, str):
            continue
        authorize_egress(
            arg_value=value,
            arg_label=arg_labels.get(field),
            sink=f"{tool_name}.{field}",
            allowlist=allowlist,
            closure_matcher=closure_matcher,
        )
