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
9.3 KiB245 linesraw
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):
34    def test_unix_address_fits_the_sun_path_limit(self):
35        """A long home directory must not produce an address the kernel rejects."""
36        long_dir = Path("/Users/someone-with-a-very-long-account-name/Documents/deepseek-harness/state")
37        addr = ot.address_for(long_dir, "default")
38        self.assertLessEqual(len(addr.encode()), 90)
39        if ot.WINDOWS:
40            self.assertTrue(addr.startswith("tcp:"))
41        else:
42            self.assertTrue(addr.endswith(".sock"))
43
44    @unittest.skipIf(ot.WINDOWS, "the Windows address is a placeholder; the listener picks the port")
45    def test_address_is_stable_for_the_same_inputs(self):
46        d = Path("/tmp/strata-runtime")
47        self.assertEqual(ot.address_for(d, "default"), ot.address_for(d, "default"))
48        self.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):
53    def setUp(self):
54        self.tmp = Path(tempfile.mkdtemp(prefix="strata-transport-"))
55
56    def tearDown(self):
57        import shutil
58        shutil.rmtree(self.tmp, ignore_errors=True)
59
60    def test_round_trip_and_private_permissions(self):
61        addr = ot.address_for(self.tmp, "default")
62        with ot.Listener(addr, timeout=2) as listener:
63            mode = stat.S_IMODE(os.stat(listener.address).st_mode)
64            self.assertEqual(mode, 0o600, "the owner socket must not be reachable by other users")
65
66            received: list[bytes] = []
67
68            def server():
69                conn = listener.accept()
70                assert conn is not None, "the listener timed out"
71                with conn:
72                    received.append(conn.recv(4096))
73
74            t = threading.Thread(target=server)
75            t.start()
76            with ot.connect(listener.address, timeout=2) as client:
77                client.sendall(json.dumps({"hello": "owner"}).encode() + b"\n")
78            t.join(timeout=5)
79            self.assertEqual([json.loads(received[0])], [{"hello": "owner"}])
80
81    def test_the_socket_path_is_removed_on_close(self):
82        addr = ot.address_for(self.tmp, "default")
83        listener = ot.Listener(addr)
84        listener.bind()
85        self.assertTrue(Path(listener.address).exists())
86        listener.close()
87        self.assertFalse(Path(listener.address).exists(),
88                         "a stale socket path would block the next owner from binding")
89
90    def test_accept_returns_none_on_timeout_rather_than_raising(self):
91        """The owner polls, so a quiet channel must not look like an error."""
92        addr = ot.address_for(self.tmp, "default")
93        with ot.Listener(addr, timeout=0.2) as listener:
94            self.assertIsNone(listener.accept())
95
96    def test_connect_to_a_dead_address_raises_oserror(self):
97        addr = ot.address_for(self.tmp, "nothing-here")
98        with self.assertRaises(OSError):
99            ot.connect(addr, timeout=1)
100
101
102class TestLoopbackTransport(unittest.TestCase):
103    """The Windows branch, exercised on every platform.
104
105    This is the same code Windows runs; only the socket family differs, and `socket.AF_INET` works
106    everywhere. Testing it here means the transport is verified rather than deferred.
107    """
108
109    def setUp(self):
110        self.tmp = Path(tempfile.mkdtemp(prefix="strata-transport-tcp-"))
111
112    def tearDown(self):
113        import shutil
114        shutil.rmtree(self.tmp, ignore_errors=True)
115
116    def _bind_loopback(self) -> ot.Listener:
117        """Bind the way the Windows branch does, regardless of host platform."""
118        original = ot.WINDOWS
119        ot.WINDOWS = True
120        try:
121            listener = ot.Listener("tcp:127.0.0.1:0", timeout=2)
122            listener.bind()
123            return listener
124        finally:
125            ot.WINDOWS = original
126
127    def test_loopback_binds_and_round_trips(self):
128        listener = self._bind_loopback()
129        try:
130            self.assertTrue(listener.address.startswith("tcp:127.0.0.1:"),
131                            "the owner must never bind a wildcard address")
132            port = int(listener.address.rsplit(":", 1)[1])
133            self.assertGreater(port, 0)
134            got: list[bytes] = []
135
136            def server():
137                conn = listener.accept()
138                assert conn is not None
139                with conn:
140                    got.append(conn.recv(1024))
141
142            t = threading.Thread(target=server)
143            t.start()
144            original = ot.WINDOWS
145            ot.WINDOWS = True
146            try:
147                with ot.connect(listener.address, timeout=2) as client:
148                    client.sendall(b"token-check\n")
149            finally:
150                ot.WINDOWS = original
151            t.join(timeout=5)
152            self.assertEqual(got, [b"token-check\n"])
153        finally:
154            listener.close()
155
156    def test_two_owners_cannot_share_the_port(self):
157        """A second owner must fail to bind rather than silently share the channel."""
158        listener = self._bind_loopback()
159        try:
160            port = int(listener.address.rsplit(":", 1)[1])
161            clash = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
162            try:
163                clash.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.
166                self.fail("a second listener bound the owner's port")
167            except OSError:
168                pass
169            finally:
170                clash.close()
171        finally:
172            listener.close()
173
174    def test_it_binds_loopback_only(self):
175        """The listener must not be reachable from another interface."""
176        listener = self._bind_loopback()
177        try:
178            port = 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.
181            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
182            s.settimeout(0.5)
183            try:
184                with self.assertRaises(OSError):
185                    s.connect(("203.0.113.1", port))
186            finally:
187                s.close()
188        finally:
189            listener.close()
190
191
192class TestStateFileValidation(unittest.TestCase):
193    """A client must refuse a state file it cannot trust."""
194
195    def setUp(self):
196        self.tmp = Path(tempfile.mkdtemp(prefix="strata-state-"))
197        self.path = self.tmp / "default.json"
198        self.path.write_text('{"token": "x"}')
199        restrict_to_current_user(self.path)
200
201    def tearDown(self):
202        import shutil
203        shutil.rmtree(self.tmp, ignore_errors=True)
204
205    def test_a_private_regular_file_is_accepted(self):
206        ot.check_state_file(self.path)
207
208    @unittest.skipUnless(ot.WINDOWS, "NTFS ACLs")
209    def test_a_state_file_with_an_inherited_acl_is_refused(self):
210        other = self.tmp / "inherited.json"
211        other.write_text("{}")  # a fresh file inherits the directory's entries (SYSTEM, Administrators)
212        with self.assertRaises(ot.TransportError):
213            ot.check_state_file(other)
214
215    @unittest.skipIf(ot.WINDOWS, "POSIX permission bits")
216    def test_a_world_readable_state_file_is_refused(self):
217        os.chmod(self.path, 0o644)
218        with self.assertRaises(ot.TransportError):
219            ot.check_state_file(self.path)
220
221    @unittest.skipIf(ot.WINDOWS, "POSIX symlinks")
222    def test_a_symlink_is_refused(self):
223        link = self.tmp / "link.json"
224        link.symlink_to(self.path)
225        with self.assertRaises(ot.TransportError):
226            ot.check_state_file(link)
227
228    def test_a_directory_is_refused(self):
229        with self.assertRaises(ot.TransportError):
230            ot.check_state_file(self.tmp)
231
232    def test_an_implausibly_large_state_file_is_refused(self):
233        big = self.tmp / "big.json"
234        big.write_bytes(b"x" * (17 * 1024))
235        os.chmod(big, 0o600)
236        with self.assertRaises(ot.TransportError):
237            ot.check_state_file(big)
238
239    def test_a_missing_file_raises_oserror(self):
240        with self.assertRaises(OSError):
241            ot.check_state_file(self.tmp / "nope.json")
242
243
244if __name__ == "__main__":
245    unittest.main()