okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b36e8a02
main
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 17listener that would also accept remote traffic; 182. every request carries the owner's 256-bit control token, compared in constant time, which the 19client 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 21per-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 57On 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 59otherwise exceed; when even the private-directory form is too long the address falls back to a 60short ``/tmp`` path that only this user can traverse. 61""" 62if 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. 65return f"tcp:127.0.0.1:0" 66import hashlib 67digest = hashlib .sha256 (f" { runtime_dir } \0 { name } " .encode ()).hexdigest ()[:16 ] 68candidate = runtime_dir / f" { digest } .sock" 69if len (str (candidate ).encode ())<= 90 : 70return str (candidate ) 71return f"/tmp/strata- { os . getuid () } - { digest } .sock" 72 73 74class Listener : 75"""An accepting endpoint for the owner's private channel. 76 77Use as a context manager. ``accept()`` returns a connected socket, or ``None`` on timeout so the 78owner can service its other work between polls. 79""" 80 81def __init__ (self ,address :str ,* ,timeout :float = 1.0 )-> None : 82self .requested = address 83self .address = address 84self ._sock :socket .socket | None = None 85self ._timeout = timeout 86self ._bound = False 87 88def bind (self )-> str : 89if WINDOWS : 90sock = 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. 93sock .bind (("127.0.0.1" ,0 )) 94self .address = f"tcp:127.0.0.1: { sock . getsockname ()[ 1 ] } " 95else : 96path = Path (self .requested ) 97if 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. 100path .unlink () 101sock = socket .socket (socket .AF_UNIX ,socket .SOCK_STREAM ) 102sock .bind (str (path )) 103os .chmod (path ,0o600 ) 104sock .listen (5 ) 105sock .settimeout (self ._timeout ) 106self ._sock = sock 107self ._bound = True 108return self .address 109 110def accept (self )-> socket .socket | None : 111if self ._sock is None : 112raise TransportError ("the listener is not bound" ) 113try : 114conn ,_ = self ._sock .accept () 115except socket .timeout : 116return None 117except OSError as e : 118if e .errno in (errno .EINTR ,errno .EAGAIN ): 119return None 120raise 121return conn 122 123def close (self )-> None : 124if self ._sock is not None : 125try : 126self ._sock .close () 127finally : 128self ._sock = None 129if not WINDOWS and self ._bound : 130# Remove the path so a later owner can bind it; ignore a racing removal. 131try : 132Path (self .requested ).unlink () 133except OSError : 134pass 135self ._bound = False 136 137def __enter__ (self )-> "Listener" : 138self .bind () 139return self 140 141def __exit__ (self ,* exc :object )-> None : 142self .close () 143 144 145def connect (address :str ,* ,timeout :float = 5.0 )-> socket .socket : 146"""Connect to an owner's private channel.""" 147sock = socket .socket (socket .AF_INET if WINDOWS else socket .AF_UNIX ,socket .SOCK_STREAM ) 148sock .settimeout (timeout ) 149try : 150if WINDOWS : 151_ ,host ,port = address .split (":" ,2 ) 152sock .connect ((host ,int (port ))) 153else : 154sock .connect (address ) 155except OSError : 156sock .close () 157raise 158return sock 159 160 161def check_state_file (path :Path )-> None : 162"""Validate that a state file is one this user may trust. 163 164Refuses anything that is not a regular file, is not owned by this user, or is group/world 165accessible. This is what stops another account from pointing a client at its own listener. 166""" 167st = path .lstat () 168if stat .S_ISLNK (st .st_mode ): 169raise TransportError ("the runtime state file is a symlink" ) 170if not stat .S_ISREG (st .st_mode ): 171raise TransportError ("the runtime state file is not a regular file" ) 172if st .st_size > 16 * 1024 : 173raise TransportError ("the runtime state file is implausibly large" ) 174if hasattr (os ,"getuid" )and st .st_uid != os .getuid (): 175raise TransportError ("the runtime state file is owned by another user" ) 176if WINDOWS : 177# NTFS has no mode bits: the promise is a protected ACL naming this user only. 178from strata_control .private_files import is_private 179if not is_private (path ): 180raise TransportError ("the runtime state file is readable by other users" ) 181elif st .st_mode & 0o077 : 182raise TransportError ("the runtime state file is readable by other users" )