# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-laundering-when-a-tainted-value-survives-a-sandbox-syscall-boundary-intact.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-laundering-when-a-tainted-value-survives-a-sandbox-syscall-boundary-intact.warrant.json
# Markdown SHA-256:   8b16e11c12983d32a23c313a85333d2c5386107da4a0ea8e3d986152f58f9bea
# Code AST SHA-256:   b4fc01db7df605633fcf0180193a9c8f7258ba259f786f153a825f61e62ee004
# Verified Classes:   CapabilityLaunderingError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CapabilityLaunderingError(RuntimeError):
    """Raised when a tainted value reaches a capability-gated sink
    without a surviving provenance label, or when scope is evaluated
    on non-canonical form."""
    pass


TAINT_SENSITIVE_SINKS = {
    "open", "openat", "openat2",
    "execve", "execveat",
    "connect", "sendto",
}


def mediate_syscall(syscall: str, args: dict, capability_scope: str) -> None:
    """
    Mediation entry point. Enforces the composite invariant:
    no tainted value may reach a capability-gated sink without
    an in-band label, and scope must be evaluated on canonical form.
    """
    if syscall not in TAINT_SENSITIVE_SINKS:
        # Unclassified syscall reaching a sink is a policy gap.
        if _reaches_sink(syscall):
            raise CapabilityLaunderingError(
                f"unclassified syscall {syscall!r} reaches a taint-sensitive sink; "
                f"policy enumeration is incomplete"
            )
        return

    target = args.get("target")
    if target is None:
        raise CapabilityLaunderingError(
            f"sink {syscall!r} invoked without a target argument"
        )

    # Invariant 1: label continuity across the serialization boundary.
    label = args.get("__provenance_label__")
    if label is None:
        raise CapabilityLaunderingError(
            f"sink {syscall!r} target={target!r} carries no in-band provenance label; "
            f"label was dropped at the tool-wrapper serialization boundary"
        )

    # Invariant 2: scope must be evaluated on canonical form.
    canonical = _canonicalize(target)
    if not _scope_matches(capability_scope, canonical):
        raise CapabilityLaunderingError(
            f"sink {syscall!r} target={target!r} canonical={canonical!r} "
            f"escapes capability scope {capability_scope!r}; "
            f"scope was evaluated on non-canonical form or resolution "
            f"occurred after scope check"
        )

    # Invariant 3: tainted values may not reach the sink at all.
    if label.startswith("untrusted_"):
        raise CapabilityLaunderingError(
            f"sink {syscall!r} target={canonical!r} reached by value with "
            f"provenance label {label!r}; composite invariant violated"
        )


def _reaches_sink(syscall: str) -> bool:
    # Conservative: any syscall not explicitly cleared is assumed to reach a sink.
    return True


def _canonicalize(path: str) -> str:
    import os
    return os.path.realpath(path)


def _scope_matches(scope: str, canonical: str) -> bool:
    import os
    scope_root = os.path.realpath(scope.rstrip("*").rstrip("/"))
    return canonical == scope_root or canonical.startswith(scope_root + os.sep)
