# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-path-scoped-mcp-filesystem-tools-from-escaping-confinement-through-symlink-resolution-and-toctou-races.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-path-scoped-mcp-filesystem-tools-from-escaping-confinement-through-symlink-resolution-and-toctou-races.warrant.json
# Markdown SHA-256:   7220c318f065fa1c054263b3e35b9aef3e2b0fe7c43f5984060b2ced2781770c
# Code AST SHA-256:   c1d78888ab5a2543201f2d3790fd09f3efc80403c35409a59edf90f05d666a8c
# Verified Classes:   ConfinementViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import os

class ConfinementViolation(RuntimeError):
    """Raised when a filesystem operation would resolve outside the capability root."""

def open_confined(root: str, rel: str) -> int:
    # Resolve the root once; it is the trust anchor.
    real_root = os.path.realpath(root)
    # Resolve the requested path fully, including every symlink component.
    candidate = os.path.realpath(os.path.join(real_root, rel))
    # Containment test on resolved identity, with separator to block sibling-prefix escape.
    if candidate != real_root and not candidate.startswith(real_root + os.sep):
        raise ConfinementViolation(
            f"resolved path {candidate!r} escapes root {real_root!r}"
        )
    # Bind the check to the handle: O_NOFOLLOW refuses a leaf symlink swapped in
    # between realpath() and open(), closing the TOCTOU window.
    try:
        fd = os.open(candidate, os.O_RDONLY | os.O_NOFOLLOW)
    except OSError as e:
        raise ConfinementViolation(
            f"open refused for {candidate!r}: leaf mutated or symlinked ({e})"
        ) from e
    # Residual: a hardlink inside root to an out-of-root inode passes here.
    # Documented; mitigate with a link-count check or a namespace-confined mount.
    return fd
