# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-concatenation-when-a-sandboxed-tool-call-smuggles-protected-bytes-past-a-per-argument-label-check.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-concatenation-when-a-sandboxed-tool-call-smuggles-protected-bytes-past-a-per-argument-label-check.warrant.json
# Markdown SHA-256:   fd1bcdfdce7d9749e99a1805cb76eb69fbcf9fcf90c12b245edb4feb5521f6eb
# Code AST SHA-256:   ea951c9be7e8cd3c9c87ef93358ef905367671a9e988ea70b8b5739d7e3105e8
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import base64
import binascii
import unicodedata
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when an egress payload reconstructs a protected value across span boundaries."""


def _normalize(s: str, tokenizer_merges: dict[str, str]) -> str:
    s = unicodedata.normalize("NFKC", s).lower()
    s = "".join(ch for ch in s if not ch.isspace())
    # Apply the model's BPE merge table so boundary-born tokens are visible.
    for merged, parts in tokenizer_merges.items():
        s = s.replace(parts, merged)
    return s


def _candidate_decodings(s: str) -> Iterable[str]:
    yield s
    for decoder in (base64.b64decode, bytes.fromhex):
        try:
            raw = decoder(s)
            yield raw.decode("utf-8", errors="strict")
        except (binascii.Error, ValueError, UnicodeDecodeError):
            continue


def enforce_egress_closure(
    payload: str,
    protected_values: Iterable[str],
    tokenizer_merges: dict[str, str],
    sink_capability_set: frozenset[str],
    emitter_capability_set: frozenset[str],
) -> None:
    # Content-closure is mandatory only when the sink is strictly more capable.
    if not (sink_capability_set > emitter_capability_set):
        return

    normalized_protected = {
        _normalize(p, tokenizer_merges) for p in protected_values if p
    }
    if not normalized_protected:
        return

    for candidate in _candidate_decodings(payload):
        norm = _normalize(candidate, tokenizer_merges)
        for p in normalized_protected:
            if p in norm:
                raise TaintLaunderingError(
                    f"egress blocked: payload reconstructs protected value "
                    f"(len={len(p)}) at sink with capabilities "
                    f"{sorted(sink_capability_set - emitter_capability_set)}"
                )
