# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-taint-an-egress-approved-argument-the-laundering-hazard-at-taint-aware-egress-policy-enforcement-points.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-taint-an-egress-approved-argument-the-laundering-hazard-at-taint-aware-egress-policy-enforcement-points.warrant.json
# Markdown SHA-256:   dc88b75ce2ffaca48e9bb22fd0a38f12714cbca53ba0c93dd9a31cb779f0bfcf
# Code AST SHA-256:   e5854ad6282016b620367d5f06551ea3352410d70f8ca24691d85eb490d16f03
# Verified Classes:   TaintLaunderingError, AllowlistEntry, ProvenanceLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

Taint = Literal["trusted", "internal", "untrusted"]
_RANK = {"trusted": 0, "internal": 1, "untrusted": 2}


class TaintLaunderingError(RuntimeError):
    """Raised when an egress emission would lower the provenance label of a contributing value
    without an explicit, audited declassification annotation."""


@dataclass(frozen=True)
class AllowlistEntry:
    tool: str
    path: str
    pattern: str
    declassifies: bool = False
    justification: str = ""


@dataclass
class ProvenanceLedger:
    # value_id -> (taint, set of contributing source ids)
    labels: dict[str, tuple[Taint, frozenset[str]]] = field(default_factory=dict)

    def join(self, value_ids: list[str]) -> tuple[Taint, frozenset[str]]:
        taint: Taint = "trusted"
        sources: set[str] = set()
        for vid in value_ids:
            if vid not in self.labels:
                # Unknown provenance must be treated as untrusted, never as trusted.
                return "untrusted", frozenset({f"unknown:{vid}"})
            t, srcs = self.labels[vid]
            if _RANK[t] > _RANK[taint]:
                taint = t
            sources |= srcs
        return taint, frozenset(sources)


def enforce_egress(
    ledger: ProvenanceLedger,
    entry: AllowlistEntry,
    emitted_value_id: str,
    input_value_ids: list[str],
    surface_matches: bool,
) -> Taint:
    """Return the label to stamp on the emission, or raise TaintLaunderingError.

    Invariant enforced: emitted_label = lub(input_labels) unless the allowlist entry
    explicitly and justifiably declassifies.
    """
    input_taint, sources = ledger.join(input_value_ids)
    if not surface_matches:
        raise TaintLaunderingError(
            f"surface pattern mismatch for {entry.tool}:{entry.path}"
        )
    if input_taint == "untrusted" and not entry.declassifies:
        raise TaintLaunderingError(
            f"taint laundering blocked: {entry.tool}:{entry.path} would emit "
            f"untrusted provenance {sorted(sources)} without declassification annotation"
        )
    if entry.declassifies and not entry.justification:
        raise TaintLaunderingError(
            f"declassification at {entry.tool}:{entry.path} lacks justification"
        )
    return input_taint  # never downgrade; caller may only raise, not lower
