okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b36e8a02
main
1"""Owner transport contract tests. 2 3These run on every platform and assert the properties the runtime depends on, rather than asserting 4that a particular syscall was used. The Windows path is exercised on POSIX too: the loopback-TCP 5listener and the state-file validation are ordinary Python and can be tested anywhere, so the 6platform branch is not left unverified until someone has a Windows machine. 7 8What is NOT tested here, and cannot be, is whether a Windows named pipe with an owner-only ACL 9behaves as intended — because that implementation does not exist yet. `history/docs/work/IMPLEMENTATION_STATUS.md` 10records that as the honest difference between the platforms rather than pretending the loopback 11transport is equivalent to it. 12""" 13 14from __future__import annotations 15 16import json 17import os 18import socket 19import stat 20import sys 21import tempfile 22import threading 23import time 24import unittest 25from pathlib import Path 26 27sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 28 29from strata_control import owner_transport as ot # noqa: E402 30from strata_control .private_files import restrict_to_current_user # noqa: E402 31 32 33class TestAddressing (unittest .TestCase ): 34def test_unix_address_fits_the_sun_path_limit (self ): 35"""A long home directory must not produce an address the kernel rejects.""" 36long_dir = Path ("/Users/someone-with-a-very-long-account-name/Documents/deepseek-harness/state" ) 37addr = ot .address_for (long_dir ,"default" ) 38self .assertLessEqual (len (addr .encode ()),90 ) 39if ot .WINDOWS : 40self .assertTrue (addr .startswith ("tcp:" )) 41else : 42self .assertTrue (addr .endswith (".sock" )) 43 44@ unittest . skipIf ( ot . WINDOWS , "the Windows address is a placeholder; the listener picks the port" ) 45def test_address_is_stable_for_the_same_inputs (self ): 46d = Path ("/tmp/strata-runtime" ) 47self .assertEqual (ot .address_for (d ,"default" ),ot .address_for (d ,"default" )) 48self .assertNotEqual (ot .address_for (d ,"default" ),ot .address_for (d ,"other" )) 49 50 51@ unittest . skipIf ( ot . WINDOWS , "POSIX socket binding" ) 52class TestPosixListener (unittest .TestCase ): 53def setUp (self ): 54self .tmp = Path (tempfile .mkdtemp (prefix = "strata-transport-" )) 55 56def tearDown (self ): 57import shutil 58shutil .rmtree (self .tmp ,ignore_errors = True ) 59 60def test_round_trip_and_private_permissions (self ): 61addr = ot .address_for (self .tmp ,"default" ) 62with ot .Listener (addr ,timeout = 2 )as listener : 63mode = stat .S_IMODE (os .stat (listener .address ).st_mode ) 64self .assertEqual (mode ,0o600 ,"the owner socket must not be reachable by other users" ) 65 66received :list [bytes ]= [] 67 68def server (): 69conn = listener .accept () 70assert conn is not None ,"the listener timed out" 71with conn : 72received .append (conn .recv (4096 )) 73 74t = threading .Thread (target = server ) 75t .start () 76with ot .connect (listener .address ,timeout = 2 )as client : 77client .sendall (json .dumps ({"hello" :"owner" }).encode ()+ b"\n" ) 78t .join (timeout = 5 ) 79self .assertEqual ([json .loads (received [0 ])], [{"hello" :"owner" }]) 80 81def test_the_socket_path_is_removed_on_close (self ): 82addr = ot .address_for (self .tmp ,"default" ) 83listener = ot .Listener (addr ) 84listener .bind () 85self .assertTrue (Path (listener .address ).exists ()) 86listener .close () 87self .assertFalse (Path (listener .address ).exists (), 88"a stale socket path would block the next owner from binding" ) 89 90def test_accept_returns_none_on_timeout_rather_than_raising (self ): 91"""The owner polls, so a quiet channel must not look like an error.""" 92addr = ot .address_for (self .tmp ,"default" ) 93with ot .Listener (addr ,timeout = 0.2 )as listener : 94self .assertIsNone (listener .accept ()) 95 96def test_connect_to_a_dead_address_raises_oserror (self ): 97addr = ot .address_for (self .tmp ,"nothing-here" ) 98with self .assertRaises (OSError ): 99ot .connect (addr ,timeout = 1 ) 100 101 102class TestLoopbackTransport (unittest .TestCase ): 103"""The Windows branch, exercised on every platform. 104 105This is the same code Windows runs; only the socket family differs, and `socket.AF_INET` works 106everywhere. Testing it here means the transport is verified rather than deferred. 107""" 108 109def setUp (self ): 110self .tmp = Path (tempfile .mkdtemp (prefix = "strata-transport-tcp-" )) 111 112def tearDown (self ): 113import shutil 114shutil .rmtree (self .tmp ,ignore_errors = True ) 115 116def _bind_loopback (self )-> ot .Listener : 117"""Bind the way the Windows branch does, regardless of host platform.""" 118original = ot .WINDOWS 119ot .WINDOWS = True 120try : 121listener = ot .Listener ("tcp:127.0.0.1:0" ,timeout = 2 ) 122listener .bind () 123return listener 124finally : 125ot .WINDOWS = original 126 127def test_loopback_binds_and_round_trips (self ): 128listener = self ._bind_loopback () 129try : 130self .assertTrue (listener .address .startswith ("tcp:127.0.0.1:" ), 131"the owner must never bind a wildcard address" ) 132port = int (listener .address .rsplit (":" ,1 )[1 ]) 133self .assertGreater (port ,0 ) 134got :list [bytes ]= [] 135 136def server (): 137conn = listener .accept () 138assert conn is not None 139with conn : 140got .append (conn .recv (1024 )) 141 142t = threading .Thread (target = server ) 143t .start () 144original = ot .WINDOWS 145ot .WINDOWS = True 146try : 147with ot .connect (listener .address ,timeout = 2 )as client : 148client .sendall (b"token-check\n" ) 149finally : 150ot .WINDOWS = original 151t .join (timeout = 5 ) 152self .assertEqual (got , [b"token-check\n" ]) 153finally : 154listener .close () 155 156def test_two_owners_cannot_share_the_port (self ): 157"""A second owner must fail to bind rather than silently share the channel.""" 158listener = self ._bind_loopback () 159try : 160port = int (listener .address .rsplit (":" ,1 )[1 ]) 161clash = socket .socket (socket .AF_INET ,socket .SOCK_STREAM ) 162try : 163clash .bind (("127.0.0.1" ,port )) 164# If the platform allows the rebind, the port is not exclusively held, which would 165# let a second owner hijack the channel. Fail loudly. 166self .fail ("a second listener bound the owner's port" ) 167except OSError : 168pass 169finally : 170clash .close () 171finally : 172listener .close () 173 174def test_it_binds_loopback_only (self ): 175"""The listener must not be reachable from another interface.""" 176listener = self ._bind_loopback () 177try : 178port = int (listener .address .rsplit (":" ,1 )[1 ]) 179# Connecting to a non-loopback local address on that port must fail: nothing is bound 180# there. 203.0.113.0/24 is TEST-NET-3 and is never a local address. 181s = socket .socket (socket .AF_INET ,socket .SOCK_STREAM ) 182s .settimeout (0.5 ) 183try : 184with self .assertRaises (OSError ): 185s .connect (("203.0.113.1" ,port )) 186finally : 187s .close () 188finally : 189listener .close () 190 191 192class TestStateFileValidation (unittest .TestCase ): 193"""A client must refuse a state file it cannot trust.""" 194 195def setUp (self ): 196self .tmp = Path (tempfile .mkdtemp (prefix = "strata-state-" )) 197self .path = self .tmp / "default.json" 198self .path .write_text ('{"token": "x"}' ) 199restrict_to_current_user (self .path ) 200 201def tearDown (self ): 202import shutil 203shutil .rmtree (self .tmp ,ignore_errors = True ) 204 205def test_a_private_regular_file_is_accepted (self ): 206ot .check_state_file (self .path ) 207 208@ unittest . skipUnless ( ot . WINDOWS , "NTFS ACLs" ) 209def test_a_state_file_with_an_inherited_acl_is_refused (self ): 210other = self .tmp / "inherited.json" 211other .write_text ("{}" )# a fresh file inherits the directory's entries (SYSTEM, Administrators) 212with self .assertRaises (ot .TransportError ): 213ot .check_state_file (other ) 214 215@ unittest . skipIf ( ot . WINDOWS , "POSIX permission bits" ) 216def test_a_world_readable_state_file_is_refused (self ): 217os .chmod (self .path ,0o644 ) 218with self .assertRaises (ot .TransportError ): 219ot .check_state_file (self .path ) 220 221@ unittest . skipIf ( ot . WINDOWS , "POSIX symlinks" ) 222def test_a_symlink_is_refused (self ): 223link = self .tmp / "link.json" 224link .symlink_to (self .path ) 225with self .assertRaises (ot .TransportError ): 226ot .check_state_file (link ) 227 228def test_a_directory_is_refused (self ): 229with self .assertRaises (ot .TransportError ): 230ot .check_state_file (self .tmp ) 231 232def test_an_implausibly_large_state_file_is_refused (self ): 233big = self .tmp / "big.json" 234big .write_bytes (b"x" * (17 * 1024 )) 235os .chmod (big ,0o600 ) 236with self .assertRaises (ot .TransportError ): 237ot .check_state_file (big ) 238 239def test_a_missing_file_raises_oserror (self ): 240with self .assertRaises (OSError ): 241ot .check_state_file (self .tmp / "nope.json" ) 242 243 244if __name__ == "__main__" : 245unittest .main ()