# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-revocation-when-provenance-labels-are-forged-by-the-very-tool-output-that-carries-them.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-revocation-when-provenance-labels-are-forged-by-the-very-tool-output-that-carries-them.warrant.json
# Markdown SHA-256:   6c18d2ccbb5fdd7bff054bc0f66d6ac02f88cc2c25f501594d7fac778428a23d
# Code AST SHA-256:   d77108c48341853093835747f47c15a18974e43c908b2f4267ad61b4d7e55bf0
# Verified Classes:   ProvenanceLaunderingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceLaunderingError(RuntimeError):
    """Raised when a segment's taint label was derived from its own content,
    or when a side-effecting capability is authorized by a segment whose
    provenance was produced under degraded (content-derived) labeling."""


TRUSTED_SOURCES = {"system", "user"}


def authorize_capability(
    capability: str,
    authorizing_segment: dict,
    degraded_provenance: bool,
) -> None:
    """Gate a side-effecting capability on the authorizing segment's label.

    Invariant: a label is only usable if it was assigned by a component
    that never read the segment's content. If the assembler was in
    degraded mode (envelopes dropped, fallback labeler active), every
    label is content-derived and therefore advisory.
    """
    side_effecting = capability in {"send_email", "write_file", "http_post"}
    if not side_effecting:
        return

    source = authorizing_segment.get("source")
    taint = authorizing_segment.get("taint")
    label_origin = authorizing_segment.get("label_origin", "unknown")

    # Missing envelope => taint by default; never recover from content.
    if source is None or taint is None:
        raise ProvenanceLaunderingError(
            f"capability {capability!r} authorized by unlabeled segment; "
            "missing envelope implies taint=true and cannot be recovered"
        )

    # A label whose origin is content-derived is not a trust boundary.
    if label_origin == "content_derived":
        raise ProvenanceLaunderingError(
            f"capability {capability!r} authorized by content-derived label "
            f"(source={source!r}); labeler must be blind to payload"
        )

    if degraded_provenance:
        raise ProvenanceLaunderingError(
            f"capability {capability!r} requested while provenance is degraded; "
            "require out-of-band confirmation instead of a context segment"
        )

    if taint is True or source not in TRUSTED_SOURCES:
        raise ProvenanceLaunderingError(
            f"capability {capability!r} not authorized: "
            f"source={source!r} taint={taint!r}"
        )
