# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-delegated-declassification-envelopes-when-the-approving-agent-inherits-the-requester-s-taint.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-delegated-declassification-envelopes-when-the-approving-agent-inherits-the-requester-s-taint.warrant.json
# Markdown SHA-256:   80dbdfd24132b602b849ccdbf7e2aea8384ae0422887ac941949016747e7744e
# Code AST SHA-256:   7a1cb6804ff2e8c1200227cba2f45ee46a7313fda5621696b11cd11258b41a87
# Verified Classes:   TaintLaunderingError, Envelope, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a declassification warrant's authority exceeds its context purity."""


# Label lattice: lower index = less tainted. Join = max by index.
LABELS = ["PUBLIC", "INTERNAL", "SECRET"]
_RANK = {lbl: i for i, lbl in enumerate(LABELS)}


def join(a: str, b: str) -> str:
    return a if _RANK[a] >= _RANK[b] else b


@dataclass(frozen=True)
class Envelope:
    payload: str
    taint: str
    context_taint: str  # join of everything the *holder* has read


@dataclass(frozen=True)
class Warrant:
    source: str
    target: str
    approver: str
    approver_context_taint: str  # C2: computed by transport, not asserted
    sig: str = ""

    @property
    def taint(self) -> str:
        # The warrant is only as clean as the context that produced it.
        return self.approver_context_taint


def make_warrant(
    req: Envelope, approver_id: str, approver_read_taint: str
) -> Warrant:
    if _RANK[approver_read_taint] > _RANK[req.taint]:
        # Approver read something *more* tainted than the envelope claims.
        raise TaintLaunderingError(
            f"approver {approver_id} context taint {approver_read_taint} "
            f"exceeds envelope taint {req.taint}; warrant would be unsound"
        )
    return Warrant(
        source=req.taint,
        target="PUBLIC",
        approver=approver_id,
        approver_context_taint=approver_read_taint,
    )


def apply_declassification(env: Envelope, w: Warrant, target: str) -> Envelope:
    # C1: source label must match the envelope's actual taint.
    if w.source != env.taint:
        raise TaintLaunderingError(
            f"warrant source {w.source} != envelope taint {env.taint}"
        )
    # C3: the warrant itself must be clean enough to authorize the target.
    if _RANK[w.taint] > _RANK[target]:
        raise TaintLaunderingError(
            f"warrant taint {w.taint} cannot authorize relabel to {target}; "
            f"approver {w.approver} read tainted context — restage via "
            f"metadata-only approval or an intermediate label"
        )
    # Relabel is monotone downward only within warrant authority.
    if _RANK[target] > _RANK[env.taint]:
        raise TaintLaunderingError(
            f"relabel {env.taint}->{target} is an upward move; not a declassification"
        )
    return Envelope(payload=env.payload, taint=target, context_taint=env.context_taint)


# --- reproduction of the observed failure, now caught -------------------------
secret_env = Envelope(payload="summary: customer 4417 called...", taint="SECRET",
                      context_taint="SECRET")
# Approver read the payload to judge "no PII" -> its context is SECRET-tainted.
w = make_warrant(secret_env, approver_id="auditor", approver_read_taint="SECRET")
try:
    apply_declassification(secret_env, w, target="PUBLIC")
except TaintLaunderingError as e:
    print("blocked:", e)
    # Correct remediation: metadata-only approval keeps approver context clean.
    w2 = make_warrant(secret_env, approver_id="auditor", approver_read_taint="PUBLIC")
    # Still blocked: a PUBLIC-context approver cannot authorize SECRET->PUBLIC
    # on semantic grounds; it can only do so via policy metadata, which is a
    # separate warrant type. Staged path: SECRET->INTERNAL then INTERNAL->PUBLIC.
    try:
        apply_declassification(secret_env, w2, target="PUBLIC")
    except TaintLaunderingError as e2:
        print("staged path required:", e2)
