# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-at-the-sink-boundary-rather-than-trust-the-label-carried-in-the-tool-call-payload.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-taint-at-the-sink-boundary-rather-than-trust-the-label-carried-in-the-tool-call-payload.warrant.json
# Markdown SHA-256:   76e1e5a6da2f405a1f9a48f9a854c2644cd526c1bf731a0c7dd0cc0f1956a82a
# Code AST SHA-256:   705ddfba121ba355fc3228cde6977284f4813cc8c18ea9dfd150d0eacdf43f3e
# Verified Classes:   TaintEgressBlocked, ProvenanceLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintEgressBlocked(RuntimeError):
    """Raised when a sink argument's derived lineage taints an egress call."""
    pass


@dataclass
class ProvenanceLedger:
    # content_hash -> (shingle_set, label)
    _blobs: dict = field(default_factory=dict)

    @staticmethod
    def _shingles(text: str, n: int = 8) -> set:
        toks = text.split()
        return {tuple(toks[i:i + n]) for i in range(max(0, len(toks) - n + 1))}

    def register_untrusted(self, blob: str) -> str:
        h = hashlib.sha256(blob.encode()).hexdigest()
        self._blobs[h] = (self._shingles(blob), "untrusted")
        return h

    def derived_taint(self, value: str, threshold: float = 0.30) -> str:
        """Re-derive taint from byte lineage, ignoring any declared label."""
        vs = self._shingles(value)
        if not vs:
            return "trusted"
        for _, (bs, label) in self._blobs.items():
            if not bs:
                continue
            overlap = len(vs & bs) / len(vs | bs)
            if overlap >= threshold:
                return label
        return "trusted"


def enforce_sink(
    ledger: ProvenanceLedger,
    sink_name: str,
    args: dict,
    declared_label: str,
    egress_sinks=("send_email", "http_post", "write_file", "exec"),
) -> None:
    if sink_name not in egress_sinks:
        return
    for key, value in args.items():
        if not isinstance(value, str):
            continue
        derived = ledger.derived_taint(value)
        # OR the derived taint with the declared label; derived wins.
        if derived == "untrusted" or declared_label == "untrusted":
            raise TaintEgressBlocked(
                f"sink={sink_name} arg={key} declared={declared_label} "
                f"derived={derived}: untrusted lineage at egress boundary"
            )
