okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
7.6 KiB182 linesraw
1"""Owner transport: the private channel between a Strata Control owner and its clients.
2
3There is exactly one owner per installation. Clients attach to it over a channel that must be
4reachable only by the same user, and the design differs per platform for a concrete reason:
5
6**POSIX (macOS, Linux)** uses an ``AF_UNIX`` stream socket inside the owner's private runtime
7directory (mode ``0700``), with the socket itself at ``0600``. Access control is the filesystem's:
8another user cannot open the path. This is the implementation the terminal layer already used and it
9is preserved unchanged here.
10
11**Windows** cannot create a named pipe from the Python standard library — there is no
12``socket.AF_UNIX`` that carries a security descriptor, and ``CreateNamedPipe`` is not exposed. The
13transport is therefore a **loopback TCP listener owned by the owner process**, protected by three
14things rather than by a pipe ACL:
15
161. it binds ``127.0.0.1`` only, never ``0.0.0.0``, and it never enables a wildcard or IPv6-any
17   listener that would also accept remote traffic;
182. every request carries the owner's 256-bit control token, compared in constant time, which the
19   client reads from a state file in the owner's private directory (``0700``, owner-only);
203. a connection that fails the token check is dropped immediately and counts toward a small
21   per-owner failure budget, so the port cannot be used as a token oracle.
22
23A local TCP port is reachable by other users on the same machine *if* they can guess it and *if*
24they have the token. That is a weaker guarantee than a pipe ACL, and it is recorded as such: on
25Windows the security of the owner channel rests on the token, exactly as it does for a Jupyter
26server or any other loopback-authenticated service. A native ``CreateNamedPipe`` implementation with
27``SDDL`` restricting the pipe to the owner is a scoped improvement, not a prerequisite, and
28``history/docs/work/IMPLEMENTATION_STATUS.md`` tracks it as the honest difference between the platforms.
29
30This module is deliberately small: it provides the two operations the runtime needs (listen,
31connect), plus the addressing helpers. It owns no policy, no identity and no lifecycle.
32"""
33
34from __future__ import annotations
35
36import errno
37import os
38import socket
39import stat
40import sys
41from pathlib import Path
42
43#: The largest single message either side will read. Both the state file and the socket protocol
44#: assume it, so it lives here with the transport rather than with either caller.
45MAX_MESSAGE = 64 * 1024
46
47WINDOWS = sys.platform == "win32"
48
49
50class TransportError(OSError):
51    """The channel could not be established, with the reason the caller should report."""
52
53
54def address_for(runtime_dir: Path, name: str) -> str:
55    """The address a client connects to, stored in the owner's state file.
56
57    On POSIX this is the socket path. The digest keeps it inside the ``AF_UNIX`` length limit
58    (``sun_path`` is about 104 bytes on macOS and 108 on Linux), which a long home directory would
59    otherwise exceed; when even the private-directory form is too long the address falls back to a
60    short ``/tmp`` path that only this user can traverse.
61    """
62    if WINDOWS:
63        # The port is chosen by the listener and written into the state file; the address here is
64        # only a placeholder that the caller always overwrites with the real one.
65        return f"tcp:127.0.0.1:0"
66    import hashlib
67    digest = hashlib.sha256(f"{runtime_dir}\0{name}".encode()).hexdigest()[:16]
68    candidate = runtime_dir / f"{digest}.sock"
69    if len(str(candidate).encode()) <= 90:
70        return str(candidate)
71    return f"/tmp/strata-{os.getuid()}-{digest}.sock"
72
73
74class Listener:
75    """An accepting endpoint for the owner's private channel.
76
77    Use as a context manager. ``accept()`` returns a connected socket, or ``None`` on timeout so the
78    owner can service its other work between polls.
79    """
80
81    def __init__(self, address: str, *, timeout: float = 1.0) -> None:
82        self.requested = address
83        self.address = address
84        self._sock: socket.socket | None = None
85        self._timeout = timeout
86        self._bound = False
87
88    def bind(self) -> str:
89        if WINDOWS:
90            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
91            # Loopback only, and no SO_REUSEADDR: a second owner must fail to bind rather than
92            # silently share the port with the first.
93            sock.bind(("127.0.0.1", 0))
94            self.address = f"tcp:127.0.0.1:{sock.getsockname()[1]}"
95        else:
96            path = Path(self.requested)
97            if path.exists():
98                # A leftover socket from a crashed owner. Only unlink when nothing is listening,
99                # which is exactly what the caller's stale check established before calling bind.
100                path.unlink()
101            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
102            sock.bind(str(path))
103            os.chmod(path, 0o600)
104        sock.listen(5)
105        sock.settimeout(self._timeout)
106        self._sock = sock
107        self._bound = True
108        return self.address
109
110    def accept(self) -> socket.socket | None:
111        if self._sock is None:
112            raise TransportError("the listener is not bound")
113        try:
114            conn, _ = self._sock.accept()
115        except socket.timeout:
116            return None
117        except OSError as e:
118            if e.errno in (errno.EINTR, errno.EAGAIN):
119                return None
120            raise
121        return conn
122
123    def close(self) -> None:
124        if self._sock is not None:
125            try:
126                self._sock.close()
127            finally:
128                self._sock = None
129        if not WINDOWS and self._bound:
130            # Remove the path so a later owner can bind it; ignore a racing removal.
131            try:
132                Path(self.requested).unlink()
133            except OSError:
134                pass
135        self._bound = False
136
137    def __enter__(self) -> "Listener":
138        self.bind()
139        return self
140
141    def __exit__(self, *exc: object) -> None:
142        self.close()
143
144
145def connect(address: str, *, timeout: float = 5.0) -> socket.socket:
146    """Connect to an owner's private channel."""
147    sock = socket.socket(socket.AF_INET if WINDOWS else socket.AF_UNIX, socket.SOCK_STREAM)
148    sock.settimeout(timeout)
149    try:
150        if WINDOWS:
151            _, host, port = address.split(":", 2)
152            sock.connect((host, int(port)))
153        else:
154            sock.connect(address)
155    except OSError:
156        sock.close()
157        raise
158    return sock
159
160
161def check_state_file(path: Path) -> None:
162    """Validate that a state file is one this user may trust.
163
164    Refuses anything that is not a regular file, is not owned by this user, or is group/world
165    accessible. This is what stops another account from pointing a client at its own listener.
166    """
167    st = path.lstat()
168    if stat.S_ISLNK(st.st_mode):
169        raise TransportError("the runtime state file is a symlink")
170    if not stat.S_ISREG(st.st_mode):
171        raise TransportError("the runtime state file is not a regular file")
172    if st.st_size > 16 * 1024:
173        raise TransportError("the runtime state file is implausibly large")
174    if hasattr(os, "getuid") and st.st_uid != os.getuid():
175        raise TransportError("the runtime state file is owned by another user")
176    if WINDOWS:
177        # NTFS has no mode bits: the promise is a protected ACL naming this user only.
178        from strata_control.private_files import is_private
179        if not is_private(path):
180            raise TransportError("the runtime state file is readable by other users")
181    elif st.st_mode & 0o077:
182        raise TransportError("the runtime state file is readable by other users")