# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-value-before-crossing-a-tool-boundary-and-why-dynamic-label-propagation-silently-fails-at-the-serialization.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-value-before-crossing-a-tool-boundary-and-why-dynamic-label-propagation-silently-fails-at-the-serialization.warrant.json
# Markdown SHA-256:   37282762073fc3c35b56632935f2ba1a3619348de3419e81f0461aed8f18b74d
# Code AST SHA-256:   d9992a00757246d52fda19ae76e99b0a57894b28eb464f7c475d1082e7bee55b
# Verified Classes:   TaintLabel, ToolEffect, TaintBoundaryViolation, LabelRegistry, ToolSpec
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class TaintLabel(Enum):
    TRUSTED = 0
    UNTRUSTED = 1


class ToolEffect(Enum):
    READ = 0
    WRITE = 1
    EXTERNAL = 2


class TaintBoundaryViolation(RuntimeError):
    """Raised when a value crosses a serialization edge into an effectful
    tool call carrying (or defaulting to) an UNTRUSTED label that the tool's
    effect class does not permit."""


@dataclass
class LabelRegistry:
    """Content-addressed label store. Survives object-identity churn caused
    by regex extraction, normalization, and JSON round-trips inside the agent.
    """
    key: bytes
    _entries: dict[str, TaintLabel] = field(default_factory=dict)

    def _digest(self, value: str) -> str:
        h = hashlib.blake2b(key=self.key, digest_size=16)
        h.update(value.encode("utf-8"))
        return h.hexdigest()

    def register(self, value: str, label: TaintLabel) -> None:
        d = self._digest(value)
        prior = self._entries.get(d)
        # Labels only ever join upward; never downgrade.
        if prior is None or label.value > prior.value:
            self._entries[d] = label

    def lookup(self, value: str) -> TaintLabel:
        # Default-UNTRUSTED: absence of a label is indistinguishable from a
        # dropped label, so it must be treated as tainted.
        return self._entries.get(self._digest(value), TaintLabel.UNTRUSTED)


@dataclass
class ToolSpec:
    name: str
    effect: ToolEffect
    max_permitted_label: TaintLabel


def serialization_edge_gate(
    args: dict[str, Any],
    spec: ToolSpec,
    registry: LabelRegistry,
) -> dict[str, Any]:
    """Walk the serialized argument tree, resolve labels by content, and
    enforce the tool's effect-class trust threshold before transport."""
    worst = TaintLabel.TRUSTED
    offending: list[tuple[str, str]] = []

    def visit(path: str, node: Any) -> None:
        nonlocal worst
        if isinstance(node, dict):
            for k, v in node.items():
                visit(f"{path}.{k}", v)
        elif isinstance(node, (list, tuple)):
            for i, v in enumerate(node):
                visit(f"{path}[{i}]", v)
        elif isinstance(node, str):
            label = registry.lookup(node)
            if label.value > worst.value:
                worst = label
            if label is TaintLabel.UNTRUSTED:
                offending.append((path, node[:64]))

    visit("$", args)

    if worst.value > spec.max_permitted_label.value:
        raise TaintBoundaryViolation(
            f"tool={spec.name!r} effect={spec.effect.name} "
            f"permits max label {spec.max_permitted_label.name} but "
            f"arguments carry {worst.name}; offending leaves: {offending}"
        )
    return args


# --- demonstration of the boundary failure and its guardrail ---

def run_agent_turn(registry: LabelRegistry) -> None:
    # 1. Untrusted fetch is labeled at the source.
    fetched = "<a href='https://evil.example/redirect'>rollback</a>"
    registry.register(fetched, TaintLabel.UNTRUSTED)

    # 2. Extraction produces a new object; content-addressed registry still
    #    covers it because the extracted substring is registered explicitly.
    extracted = "https://evil.example/redirect"
    registry.register(extracted, TaintLabel.UNTRUSTED)

    # 3. Normalization produces a laundered value with no registry entry.
    #    Default-UNTRUSTED catches it.
    laundered = extracted + "?from=ops"

    spec = ToolSpec(
        name="webhook_register",
        effect=ToolEffect.EXTERNAL,
        max_permitted_label=TaintLabel.TRUSTED,
    )
    serialization_edge_gate({"url": laundered}, spec, registry)  # raises


if __name__ == "__main__":
    run_agent_turn(LabelRegistry(key=b"runtime-held-key"))
