# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-inherit-a-poisoned-warrant-when-taint-graph-sink-analysis-marks-the-payload-clean.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-inherit-a-poisoned-warrant-when-taint-graph-sink-analysis-marks-the-payload-clean.warrant.json
# Markdown SHA-256:   96d856827534bf5a094162b8960e0a43aebfb85782dee9b44a61b5df45e6503f
# Code AST SHA-256:   c733a38f5166290d6bdd2f6c12aa2944bae49b4431003644e48e4cd029350edd
# Verified Classes:   TaintWarrantError, Artifact
# Defensive Guards:   4 fail-closed invariants (zero external deps)

"""Sink gate that refuses to trust a schema-conforming artifact's label alone."""

from dataclasses import dataclass, field
from typing import Any


class TaintWarrantError(RuntimeError):
    """Raised when a sink is asked to act on a warrant that attests to shape, not value."""


@dataclass
class Artifact:
    payload: dict[str, Any]
    label: str                      # "trusted" | "untrusted"
    warrant_kind: str               # "schema" | "provenance-join"
    source_labels: frozenset[str] = field(default_factory=frozenset)


ALLOWED_ENDPOINTS = frozenset({"https://internal.example/report"})
FORBIDDEN_KEYS = frozenset({"debug", "verbose", "trace"})


def sink_gate(artifact: Artifact) -> dict[str, Any]:
    # Invariant 1: a schema warrant is never sufficient to authorize a sink.
    if artifact.warrant_kind == "schema":
        raise TaintWarrantError(
            f"refusing sink: warrant attests to schema shape only, not value provenance "
            f"(label={artifact.label!r})"
        )

    # Invariant 2: provenance-join warrant must carry no untrusted ancestor.
    if "untrusted" in artifact.source_labels:
        raise TaintWarrantError(
            f"refusing sink: artifact has untrusted ancestor {artifact.source_labels!r}"
        )

    # Invariant 3: value-level gating, independent of label.
    for key in artifact.payload:
        if key in FORBIDDEN_KEYS:
            raise TaintWarrantError(f"refusing sink: forbidden key {key!r} in payload")

    endpoint = artifact.payload.get("endpoint")
    if endpoint is not None and endpoint not in ALLOWED_ENDPOINTS:
        raise TaintWarrantError(f"refusing sink: endpoint {endpoint!r} not allowlisted")

    return artifact.payload


# The injected plan from the trace: schema-legal, label="trusted", but smuggled.
poisoned = Artifact(
    payload={"debug": True, "endpoint": "https://attacker.example/collect"},
    label="trusted",
    warrant_kind="schema",
)

try:
    sink_gate(poisoned)
except TaintWarrantError as exc:
    print(f"blocked: {exc}")
