# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-call-sandboxing-as-a-capability-attenuation-problem-rather-than-a-path-allowlist-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-call-sandboxing-as-a-capability-attenuation-problem-rather-than-a-path-allowlist-problem.warrant.json
# Markdown SHA-256:   c7590e4b3bbda28594f0a7b11fc329c0b1b320445cdac9e58ec5ff2933915fa7
# Code AST SHA-256:   49a0cddbdd033771864d232b8c71eeeebe8f3ab4528bd5f619d650ada5faa891
# Verified Classes:   CapabilityAttenuationError, Intent, FdTag, HandlerAuthority, CapabilityLedger
# Defensive Guards:   7 fail-closed invariants (zero external deps)

"""Capability-attenuation guard for MCP tool-call sandboxing.

Enforces the invariant: no byte may move from a read-capability to a
write-capability across an intent boundary without an explicit export grant.
Path allowlists and egress CIDRs are necessary but not sufficient.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class CapabilityAttenuationError(RuntimeError):
    """Raised when a handler attempts an operation outside its attenuated authority."""


class Intent(Enum):
    READ = "read"
    WRITE = "write"
    EXPORT = "export"      # explicit grant to move bytes off-host
    RESOLVE = "resolve"    # reference resolution; must NOT carry read-authority


@dataclass(frozen=True)
class FdTag:
    fd: int
    opened_by_call: str
    opened_under_intents: frozenset[Intent]
    path: str


@dataclass
class HandlerAuthority:
    """Authority granted to a single tool-call handler invocation."""
    call_id: str
    declared_intents: frozenset[Intent]
    # Paths the handler may open; enforced in addition to Landlock.
    allowed_read_paths: frozenset[str] = field(default_factory=frozenset)
    allowed_egress: frozenset[str] = field(default_factory=frozenset)


class CapabilityLedger:
    """Tracks fd lineage across tool-call boundaries."""

    def __init__(self) -> None:
        self._tags: dict[int, FdTag] = {}

    def register_open(self, tag: FdTag, authority: HandlerAuthority) -> None:
        if Intent.READ not in authority.declared_intents:
            raise CapabilityAttenuationError(
                f"call {authority.call_id} opened {tag.path} without READ intent"
            )
        if tag.path not in authority.allowed_read_paths:
            raise CapabilityAttenuationError(
                f"call {authority.call_id} opened {tag.path} outside declared read set"
            )
        self._tags[tag.fd] = tag

    def authorize_transfer(
        self,
        src_fd: int,
        dst_host: str,
        authority: HandlerAuthority,
    ) -> None:
        """Check that moving bytes src_fd -> dst_host is within authority.

        This is the composition check: the source fd's opening intents and the
        current call's intents must jointly include EXPORT. A clean path rule
        and a clean egress rule are NOT sufficient.
        """
        if src_fd not in self._tags:
            # fd not opened through the ledger: untracked authority, refuse.
            raise CapabilityAttenuationError(
                f"call {authority.call_id} transferred untracked fd {src_fd}"
            )
        tag = self._tags[src_fd]
        joint = tag.opened_under_intents | authority.declared_intents
        if Intent.EXPORT not in joint:
            raise CapabilityAttenuationError(
                f"composition leak blocked: call {authority.call_id} "
                f"(intents={sorted(i.value for i in authority.declared_intents)}) "
                f"attempted to send fd {src_fd} opened by {tag.opened_by_call} "
                f"(intents={sorted(i.value for i in tag.opened_under_intents)}) "
                f"to {dst_host} without EXPORT grant"
            )
        if dst_host not in authority.allowed_egress:
            raise CapabilityAttenuationError(
                f"call {authority.call_id} egress to {dst_host} not in declared set "
                f"{sorted(authority.allowed_egress)}"
            )

    def close(self, fd: int) -> None:
        self._tags.pop(fd, None)


def dispatch_tool_call(
    ledger: CapabilityLedger,
    authority: HandlerAuthority,
    open_path: str | None,
    transfer_fd: int | None,
    transfer_host: str | None,
) -> None:
    """Simulates a handler dispatch under attenuation.

    Reproduces the observed failure: a resolve_reference handler that reuses
    an fd cached by a prior read_file call.
    """
    if open_path is not None:
        # Handler opens a file; must be within its declared read set.
        if Intent.READ not in authority.declared_intents:
            raise CapabilityAttenuationError(
                f"call {authority.call_id} attempted open without READ intent"
            )
        ledger.register_open(
            FdTag(
                fd=hash(open_path) & 0xFFFF,
                opened_by_call=authority.call_id,
                opened_under_intents=authority.declared_intents,
                path=open_path,
            ),
            authority,
        )

    if transfer_fd is not None and transfer_host is not None:
        # The composition check: this is where the observed leak is caught.
        ledger.authorize_transfer(transfer_fd, transfer_host, authority)


def _demo() -> None:
    ledger = CapabilityLedger()

    # Call 1: read_file, legitimate.
    reader = HandlerAuthority(
        call_id="call-1",
        declared_intents=frozenset({Intent.READ}),
        allowed_read_paths=frozenset({"/workspace/data/cust_4471.json"}),
    )
    fd = hash("/workspace/data/cust_4471.json") & 0xFFFF
    dispatch_tool_call(ledger, reader, open_path="/workspace/data/cust_4471.json",
                       transfer_fd=None, transfer_host=None)

    # Call 2: resolve_reference. Path rules pass, egress rules pass,
    # but the handler tries to send fd from call-1 to an internal host.
    resolver = HandlerAuthority(
        call_id="call-2",
        declared_intents=frozenset({Intent.RESOLVE}),
        allowed_egress=frozenset({"10.0.0.42"}),
    )
    try:
        dispatch_tool_call(ledger, resolver, open_path=None,
                           transfer_fd=fd, transfer_host="10.0.0.42")
    except CapabilityAttenuationError as exc:
        print(f"BLOCKED: {exc}")
        return
    raise AssertionError("composition leak was not blocked")


if __name__ == "__main__":
    _demo()
