# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-taint-labels-at-every-capability-enforcement-point-rather-than-trusting-the-label-carried-in-the-forw.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-taint-labels-at-every-capability-enforcement-point-rather-than-trusting-the-label-carried-in-the-forw.warrant.json
# Markdown SHA-256:   eb35cf88fb8247b92e387c5b61aab912d8f137a93e5ce90490cef29065c8bdca
# Code AST SHA-256:   dd910fbd6307419d53c2840c0d510e07015201c061ac92d3d4f3edccc1e92187
# Verified Classes:   TaintBindingViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintBindingViolation(RuntimeError):
    """Raised when a PEP is asked to honor a taint label that is not bound to the received payload."""


def enforce_capability(envelope: dict, payload: bytes, lineage: dict | None, trusted_issuers: set[str]) -> str:
    """
    Decide the effective taint at a policy enforcement point.

    Invariant: honor the carried label ONLY if it is cryptographically bound to
    this exact payload and signed by a trusted issuer. Otherwise re-derive from
    lineage, or fail closed to 'untrusted'.
    """
    carried = envelope.get("taint")
    proof = envelope.get("taint_proof")

    if carried is not None and proof is not None:
        issuer = proof.get("issuer")
        bound_hash = proof.get("payload_hash")
        if issuer not in trusted_issuers:
            raise TaintBindingViolation(
                f"taint label '{carried}' signed by untrusted issuer '{issuer}'"
            )
        if bound_hash != _sha256(payload):
            raise TaintBindingViolation(
                "taint proof does not bind to the received payload; label is stale or transplanted"
            )
        return carried  # verified fast path

    # No verifiable binding: the carried label (if any) is an unverified assertion.
    if lineage is not None:
        return _derive_taint_from_lineage(lineage)

    # No lineage available: fail closed. Absence of a label is NOT cleanliness.
    if carried is not None:
        raise TaintBindingViolation(
            f"unbound taint label '{carried}' present with no lineage; refusing to honor"
        )
    return "untrusted"


def _sha256(b: bytes) -> str:
    import hashlib
    return hashlib.sha256(b).hexdigest()


def _derive_taint_from_lineage(lineage: dict) -> str:
    sources = lineage.get("sources", [])
    if any(s.get("trust") != "trusted" for s in sources) or not sources:
        return "untrusted"
    return "trusted"
