# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-label-after-tool-output-re-entry-rather-than-clear-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-provenance-label-after-tool-output-re-entry-rather-than-clear-it.warrant.json
# Markdown SHA-256:   cda659860fe68dfbfc7d798267d803c996a76e74e2c2d13b2074b788fa485686
# Code AST SHA-256:   d737b551e184b988a71979088b0082145b1a3ca4eb71b019fb5fc75b489b4c48
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a span's trust is set from channel identity rather than carried lineage."""
    pass


TRUSTED = "trusted"
UNKNOWN = "unknown:origin"
TAINTED = "tainted"


def resolve_reentry_label(
    envelope_provenance: str | None,
    sender_is_trusted_peer: bool,
    is_function_of_tainted_bytes: bool,
    rederived_attestation: bool,
) -> str:
    # Absence of provenance is never evidence of cleanliness.
    if envelope_provenance is None:
        label = UNKNOWN
    else:
        label = envelope_provenance

    # Channel trust may authorize the sender, never the payload.
    if sender_is_trusted_peer and label == UNKNOWN:
        raise ProvenanceLaunderingError(
            "trusted-peer identity used to upgrade an unlabeled span; "
            "sender trust cannot substitute for data lineage"
        )

    # Transport of tainted bytes preserves taint regardless of channel.
    if is_function_of_tainted_bytes:
        if label == TRUSTED:
            raise ProvenanceLaunderingError(
                "span is a function of tainted bytes but arrived labeled trusted"
            )
        return TAINTED

    # Clearing requires explicit content-verified re-derivation attestation.
    if label == TRUSTED and not rederived_attestation:
        raise ProvenanceLaunderingError(
            "span labeled trusted without re-derivation attestation"
        )

    return label


def gate_privileged_action(label: str, requires_reauth: bool) -> None:
    if label == TAINTED or requires_reauth:
        raise ProvenanceLaunderingError(
            f"privileged action blocked: span label={label!r}, "
            f"requires_reauth={requires_reauth}"
        )
