# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-re-derivation-step-that-resets-information-flow-labels.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-re-derivation-step-that-resets-information-flow-labels.warrant.json
# Markdown SHA-256:   19d5209d864877111075ad070aeb76c3819379d509cbc80a00473ea7c1c92155
# Code AST SHA-256:   91d1a2d8594a191e01a95123cb76749daa5b480160edd33ebbc389847d5b07cd
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a sink receives a model-authored literal that was generated
    in a context window containing live tainted handles, without passing a
    declassification gate. Provenance-only IFC cannot catch this; the gate must."""


def guard_sink_call(
    tool_name: str,
    arguments: dict,
    live_tainted_handles: set[str],
    declassification_tokens: dict[str, str],
    high_entropy_threshold: float = 3.5,
) -> None:
    """Enforce the re-derivation invariant at a sink boundary.

    A literal argument is acceptable only if either:
      (a) no tainted handle was live in the generating context, or
      (b) the literal carries a declassification token bound to this exact
          value, granted by an audit that saw the live tainted sources.
    High-entropy literals (URLs, account numbers, base64 blobs) are always
    gated because they are the exfiltration carriers.
    """
    if not live_tainted_handles:
        return  # no laundering edge possible

    for arg_name, value in arguments.items():
        if not isinstance(value, str):
            continue  # handles are resolved elsewhere; only literals here
        entropy = _shannon_entropy(value)
        token = declassification_tokens.get(value)
        if token is None:
            raise TaintLaunderingError(
                f"sink {tool_name!r} arg {arg_name!r} is a model-authored literal "
                f"(entropy={entropy:.2f}) generated alongside tainted handles "
                f"{sorted(live_tainted_handles)}; no declassification token bound "
                f"to this value. Re-fetch via handle or run semantic audit."
            )
        if not _token_audit_saw_sources(token, live_tainted_handles):
            raise TaintLaunderingError(
                f"declassification token for {arg_name!r} was granted by an audit "
                f"that did not observe all live tainted sources "
                f"{sorted(live_tainted_handles)}; token is stale."
            )
        if entropy >= high_entropy_threshold and not _token_is_high_entropy_cleared(token):
            raise TaintLaunderingError(
                f"high-entropy literal in {arg_name!r} (entropy={entropy:.2f}) "
                f"requires high-entropy clearance on its declassification token."
            )


def _shannon_entropy(s: str) -> float:
    import math
    if not s:
        return 0.0
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    n = len(s)
    return -sum((c / n) * math.log2(c / n) for c in counts.values())


def _token_audit_saw_sources(token: str, sources: set[str]) -> bool:
    # Stub: real implementation checks the audit record bound to the token.
    return bool(token) and bool(sources)


def _token_is_high_entropy_cleared(token: str) -> bool:
    # Stub: real implementation checks the token's clearance scope.
    return token.startswith("he:")
