# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tainted-value-read-as-a-capability-grant-rather-than-a-data-flow-the-join-propagation-hole-in-taint-awa.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tainted-value-read-as-a-capability-grant-rather-than-a-data-flow-the-join-propagation-hole-in-taint-awa.warrant.json
# Markdown SHA-256:   0364a2e0c1f5419dbd72193c38c73bb40b2c9931a10c9e6b42616a5048df117e
# Code AST SHA-256:   b501abb02ff913b974b71177a296bacd309a81f39c54ad5914acb45fb5720360
# Verified Classes:   TaintLaunderingError, ContextProvenance
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a sink call is reached from a tainted context window
    via a model-generated or sanitizer-laundered argument."""
    pass


class ContextProvenance:
    def __init__(self):
        self.tainted_in_context = set()

    def observe(self, source_id: str, tainted: bool):
        if tainted:
            self.tainted_in_context.add(source_id)

    def is_context_tainted(self) -> bool:
        return bool(self.tainted_in_context)


SANITIZER_CONTRACTS = {
    # tool -> set of declared output fields; anything else is undeclared and taint-preserving
    "summarize": {"summary"},  # NOTE: implementation can emit more; contract incomplete
}


def authorize_sink_call(
    tool: str,
    arg_name: str,
    arg_kind: str,  # "direct_ref" | "model_generated" | "sanitizer_output"
    arg_provenance: set,
    ctx: ContextProvenance,
    sanitizer_used: str | None = None,
) -> bool:
    if arg_kind == "direct_ref":
        return not (arg_provenance & ctx.tainted_in_context)

    if arg_kind == "sanitizer_output":
        contract = SANITIZER_CONTRACTS.get(sanitizer_used or "")
        if contract is None or arg_name not in contract:
            # undeclared field or unregistered sanitizer -> laundering node
            raise TaintLaunderingError(
                f"sink {tool}.{arg_name} reached via unsound sanitizer {sanitizer_used!r}; "
                f"contract={contract!r}"
            )
        return not ctx.is_context_tainted()

    if arg_kind == "model_generated":
        if ctx.is_context_tainted():
            # model-generated literal inherits context taint; deny without out-of-band grant
            raise TaintLaunderingError(
                f"sink {tool}.{arg_name} argument generated from tainted context "
                f"{sorted(ctx.tainted_in_context)}; per-argument label is unsound"
            )
        return True

    raise TaintLaunderingError(f"unknown arg_kind {arg_kind!r}")
