okami.mom/strata

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

Niko1221Merge main 7726f80cb (local, 11-10 14:08) into f-own-int714ff8242

main
22.8 KiB425 linesraw
1"""serve/test_security.py - the Host check (DNS rebinding) and the Origin check for requests without an API key,
2against the mock engine (no GPU, no pack).
3
4    python -m unittest serve.test_security -v
5"""
6from __future__ import annotations
7
8import contextlib
9import errno
10import http.client
11import io
12import json
13import socket
14import sys
15import unittest
16from http.server import BaseHTTPRequestHandler
17from pathlib import Path
18from unittest import mock
19
20sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
21from serve.frontend import ChatTemplate  # noqa: E402
22from serve.server import (ByteTokenizer, MockEngine, Server, Service, allowed_hosts_of, host_allowed,  # noqa: E402
23                          host_name, host_names_for, origin_allowed, serve)
24
25ROOT = Path(__file__).resolve().parents[1]
26LOCAL = {"localhost", "127.0.0.1", "::1"}
27
28
29class HostNames(unittest.TestCase):
30    def test_host_name(self):
31        self.assertEqual(host_name("Example.COM:8080"), "example.com")
32        self.assertEqual(host_name("localhost"), "localhost")
33        self.assertEqual(host_name("[::1]:8095"), "::1")
34        self.assertEqual(host_name("[::1]"), "::1")
35        self.assertEqual(host_name("strata.example.com."), "strata.example.com")
36        for bad in ("", "a:b", "[::1", "[::1]x", "a b", "evil.com/x"):
37            self.assertEqual(host_name(bad), "", bad)
38
39    def test_allowed_hosts_of(self):
40        self.assertEqual(allowed_hosts_of(None), [])
41        self.assertEqual(allowed_hosts_of("Strata.Example.com"), ["strata.example.com"])
42        self.assertEqual(allowed_hosts_of(["https://a.example.com:8443/x", ".example.org", "*"], "box, nas.lan "),
43                         ["a.example.com", ".example.org", "*", "box", "nas.lan"])
44        for bad in (["bad name"], 5, [3], "http://"):
45            with self.assertRaises(ValueError):
46                allowed_hosts_of(bad)
47
48    def test_names_from_the_bind_address(self):
49        with mock.patch("serve.server.lan_addresses", return_value=["192.168.1.20"]):
50            self.assertEqual(host_names_for("127.0.0.1"), LOCAL)                 # this PC only: nothing else
51            self.assertEqual(host_names_for("localhost"), LOCAL)
52            names = host_names_for("0.0.0.0")                                    # other devices too
53            self.assertIn(socket.gethostname().lower(), names)
54            self.assertIn(socket.gethostname().lower() + ".local", names)
55            self.assertIn("192.168.1.20", names)
56            self.assertIn("10.0.0.7", host_names_for("10.0.0.7"))
57            names = host_names_for("127.0.0.1", ["strata.example.com", "*"], ["https://chat.example.net"])
58            self.assertTrue({"strata.example.com", "chat.example.net"} <= names)
59            self.assertNotIn("*", names)
60
61
62class ListenAddress(unittest.TestCase):
63    def test_bind_does_not_look_up_a_host_name(self):
64        """http.server's own server_bind asks socket.getfqdn for the address: on a Mac whose reverse lookup stalls (GitHub's macOS runner:
65        35 s for the first lookup of every new process) a start listened that much later. No network answer may delay a start."""
66        with mock.patch.object(socket, "getfqdn", side_effect=AssertionError("server_bind looked up a host name")), \
67                mock.patch.object(socket, "gethostbyaddr", side_effect=AssertionError("server_bind looked up a host name")):
68            with Server(("127.0.0.1", 0), BaseHTTPRequestHandler) as s:
69                self.assertNotEqual(s.server_address[1], 0)
70
71    def test_bind_sets_server_name_to_the_address_and_server_port(self):
72        # (http.server set server_name to the looked-up name, "localhost" for 127.0.0.1; no Strata code reads it)
73        with Server(("127.0.0.1", 0), BaseHTTPRequestHandler) as s:
74            self.assertEqual((s.server_name, s.server_port), ("127.0.0.1", s.server_address[1]))
75            self.assertGreater(s.server_port, 0)
76
77    def test_ipv4_address_family(self):
78        with Server(("127.0.0.1", 0), BaseHTTPRequestHandler, bind_and_activate=False) as s:
79            self.assertEqual(s.address_family, socket.AF_INET)
80
81    @unittest.skipUnless(socket.has_ipv6, "IPv6 is not available")
82    def test_ipv6_loopback(self):
83        for host in ("::1", "2001:db8::7"):
84            try:
85                with Server((host, 0), BaseHTTPRequestHandler, bind_and_activate=False) as s:
86                    self.assertEqual(s.address_family, socket.AF_INET6)
87            except OSError as e:
88                self.skipTest(f"IPv6 socket is not available: {e}")
89        tok = ByteTokenizer()
90        svc = Service(MockEngine(tok, "</think>\n\nok", max_context=4096), tok,
91                      ChatTemplate(ROOT / "serve/chat_template.jinja"))
92        try:
93            httpd = serve(svc, host="::", port=0)
94        except OSError as e:
95            self.skipTest(f"IPv6 loopback is not available: {e}")
96        try:
97            self.assertEqual(httpd.address_family, socket.AF_INET6)
98            c = http.client.HTTPConnection("::1", httpd.server_address[1], timeout=10)
99            try:
100                try:
101                    c.connect()
102                except OSError as e:
103                    # a box whose loopback has no ::1 (IPv6 off for lo: Boston) can listen on :: but not reach ::1
104                    if e.errno in (errno.EADDRNOTAVAIL, errno.ENETUNREACH, errno.EAFNOSUPPORT):
105                        self.skipTest(f"no IPv6 loopback address (::1) on this computer: {e}")
106                    raise
107                c.request("GET", "/health")
108                r = c.getresponse()
109                self.assertEqual(r.status, 200)
110                r.read()
111            finally:
112                c.close()
113        finally:
114            httpd.shutdown()
115            httpd.server_close()
116
117
118class HostCheck(unittest.TestCase):
119    def test_accepted(self):
120        for host in ("localhost:8095", "LOCALHOST", "127.0.0.1:1", "[::1]:8095", "192.168.1.20:8095", "[fe80::1]",
121                     "app.localhost:8095", None, "", "box:8095", "a.example.org", "example.org:443"):
122            self.assertTrue(host_allowed(host, LOCAL | {"box", ".example.org"}), host)
123
124    def test_refused(self):
125        # a rebinding page sends its own name; lookalikes of allowed names stay out
126        for host in ("evil.example.com", "evil.example.com:8095", "localhost.evil.com", "127.0.0.1.nip.io",
127                     "box.evil.com", "xexample.org", "bad host", "a:b:c:d:e:f:g:h:i"):
128            self.assertFalse(host_allowed(host, LOCAL | {"box", ".example.org"}), host)
129
130    def test_any_host(self):
131        self.assertTrue(host_allowed("evil.example.com", LOCAL, any_host=True))
132
133
134class OriginCheck(unittest.TestCase):
135    def test_accepted(self):
136        names = LOCAL | {"box"}
137        self.assertTrue(origin_allowed("http://127.0.0.1:8095", "127.0.0.1:8095", names))      # Strata's own page
138        self.assertTrue(origin_allowed("http://192.168.1.20:8095", "192.168.1.20:8095", names))  # ... by LAN IP
139        self.assertTrue(origin_allowed("http://localhost:3000", "127.0.0.1:8095", names))      # a local app
140        self.assertTrue(origin_allowed("http://[::1]:3000/", "127.0.0.1:8095", names))
141        self.assertTrue(origin_allowed("https://box", "127.0.0.1:8095", names))
142        self.assertTrue(origin_allowed("https://chat.example.com", "x", names, ["https://chat.example.com"]))
143        self.assertTrue(origin_allowed("https://any.example.com", "x", names, ["*"]))           # cors_origins ["*"]
144        # browser extensions and desktop apps: no web site can send another scheme than http(s) (or "null")
145        for origin in ("chrome-extension://abcdef", "moz-extension://1234-5678", "app://."):
146            self.assertTrue(origin_allowed(origin, "127.0.0.1:8095", names), origin)
147
148    def test_refused(self):
149        names = LOCAL | {"box"}
150        for origin in ("http://evil.example.com", "http://1.2.3.4", "http://192.168.1.99:8095", "null", "",
151                       "http://localhost.evil.com", "https://box.evil.com", "://x"):
152            self.assertFalse(origin_allowed(origin, "127.0.0.1:8095", names, ["https://chat.example.com"]), origin)
153
154
155class OverHttp(unittest.TestCase):
156    """The checks in the running server, as a browser and as curl/the SDKs send their requests."""
157
158    def setUp(self):
159        tok = ByteTokenizer()
160        self.svc = Service(MockEngine(tok, "</think>\n\nok", max_context=4096), tok,
161                           ChatTemplate(ROOT / "serve/chat_template.jinja"))
162        self.httpd = None
163
164    def start(self, **attrs):
165        for k, v in attrs.items():
166            setattr(self.svc, k, v)
167        self.httpd = serve(self.svc, port=0)
168        self.port = self.httpd.server_address[1]
169
170    def tearDown(self):
171        if self.httpd:
172            self.httpd.shutdown()
173            self.httpd.server_close()
174
175    def req(self, method, path, body=None, headers=None, host=None):
176        """(status, JSON, what the server printed); `host` replaces the Host header http.client sends."""
177        c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
178        h = dict(headers or {})
179        if host is not None:
180            h["Host"] = host
181        data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode()
182        out = io.StringIO()
183        try:
184            with contextlib.redirect_stdout(out):
185                c.request(method, path, body=data, headers=h)
186                r = c.getresponse()
187                raw = r.read()
188            return r.status, json.loads(raw) if raw[:1] in (b"{", b"[") else raw, out.getvalue()
189        finally:
190            c.close()
191
192    def chat_body(self):
193        return {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 64}
194
195    # --- Host
196    def test_rebinding_name_is_refused_everywhere(self):
197        self.start()
198        for method, path in (("GET", "/status"), ("GET", "/metrics"), ("GET", "/"), ("GET", "/health"),
199                             ("POST", "/settings"), ("POST", "/v1/chat/completions"), ("OPTIONS", "/v1/models")):
200            code, body, log = self.req(method, path, {} if method == "POST" else None,
201                                       {"Content-Type": "application/json"}, host=f"evil.example.com:{self.port}")
202            self.assertEqual(code, 403, path)
203            if method != "OPTIONS":
204                self.assertIn("allowed_hosts", body["error"]["message"])
205            self.assertEqual(log.count("\n"), 1, path)                          # one log line each
206            self.assertIn("evil.example.com", log)
207
208    def test_local_names_and_ips_pass(self):
209        self.start()
210        for host in (f"127.0.0.1:{self.port}", f"localhost:{self.port}", f"[::1]:{self.port}",
211                     f"192.168.1.20:{self.port}"):
212            self.assertEqual(self.req("GET", "/status", host=host)[0], 200, host)
213
214    def test_no_host_header_passes(self):
215        self.start()
216        with socket.create_connection(("127.0.0.1", self.port), timeout=10) as s:      # an HTTP/1.0 client
217            s.sendall(b"GET /health HTTP/1.0\r\n\r\n")
218            raw = b""
219            while chunk := s.recv(65536):
220                raw += chunk
221        self.assertTrue(raw.startswith(b"HTTP/1.0 200"), raw[:40])
222
223    def test_allowed_hosts_and_wildcard(self):
224        self.start(allowed_hosts=["strata.example.com", ".home.arpa"])
225        self.assertEqual(self.req("GET", "/status", host="strata.example.com")[0], 200)
226        self.assertEqual(self.req("GET", "/status", host="nas.home.arpa:8095")[0], 200)
227        self.assertEqual(self.req("GET", "/status", host="evil.example.com")[0], 403)
228        self.svc.allowed_hosts = ["*"]
229        self.assertEqual(self.req("GET", "/status", host="evil.example.com")[0], 200)
230
231    def test_refusal_names_both_ways_out(self):
232        self.start()
233        message = self.req("GET", "/status", host="evil.example.com")[1]["error"]["message"]
234        self.assertIn("allowed_hosts", message)
235        self.assertIn("api_key", message)
236
237    def test_with_a_key_the_host_check_is_off(self):
238        # a rebinding page cannot authenticate; tunnels and proxies that pass their own name on keep working
239        self.start(api_key="s3cret")
240        tunnel = "random-words.trycloudflare.com"
241        self.assertEqual(self.req("GET", "/status", host=tunnel)[0], 401)
242        self.assertEqual(self.req("GET", "/status", headers={"Authorization": "Bearer s3cret"}, host=tunnel)[0], 200)
243        self.assertEqual(self.req("GET", "/health", host=tunnel)[0], 200)
244        code, _, log = self.req("POST", "/v1/chat/completions", self.chat_body(),
245                                {"Content-Type": "application/json", "Authorization": "Bearer s3cret"}, host=tunnel)
246        self.assertEqual(code, 200)
247        self.assertNotIn("refused", log)
248
249    def test_a_trusted_origin_s_host_is_allowed(self):
250        self.start(trusted_origins=["https://strata.example.com"])
251        self.assertEqual(self.req("GET", "/status", host="strata.example.com")[0], 200)
252
253    # --- Origin on /v1 without an API key
254    def test_curl_and_sdks_without_origin(self):
255        self.start()
256        for ctype in ("application/json", "text/plain", None):              # curl -d sends a form type
257            code, body, _ = self.req("POST", "/v1/chat/completions", self.chat_body(),
258                                     {"Content-Type": ctype} if ctype else {})
259            self.assertEqual(code, 200, ctype)
260            self.assertEqual(body["choices"][0]["message"]["content"], "ok")
261
262    def test_cross_site_page_is_refused(self):
263        self.start()
264        for path in ("/v1/chat/completions", "/v1/messages", "/v1/messages/count_tokens"):
265            for ctype in ("text/plain", "application/json"):
266                code, body, log = self.req("POST", path, self.chat_body(),
267                                           {"Content-Type": ctype, "Origin": "http://evil.example.com"})
268                self.assertEqual(code, 403, (path, ctype))
269                self.assertIn("api_key", body["error"]["message"])
270                self.assertIn("evil.example.com", log)
271        self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(),
272                                  {"Content-Type": "text/plain", "Origin": "null"})[0], 403)
273
274    def test_own_and_local_pages_pass(self):
275        self.start()
276        json_type = {"Content-Type": "application/json"}
277        for origin in (f"http://127.0.0.1:{self.port}", "http://localhost:3000", "chrome-extension://abcdef"):
278            self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(),
279                                      {**json_type, "Origin": origin})[0], 200, origin)
280        # a browser page sends JSON; text/plain from a page is the cross-site "simple request" shape
281        self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(),
282                                  {"Content-Type": "text/plain", "Origin": f"http://127.0.0.1:{self.port}"})[0], 415)
283
284    def test_configured_origins_pass(self):
285        self.start(cors_origins=["https://chat.example.com"], trusted_origins=["https://strata.example.com"],
286                   allowed_hosts=["webui.lan"])
287        for origin in ("https://chat.example.com", "https://strata.example.com", "http://webui.lan:3000"):
288            self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(),
289                                      {"Content-Type": "application/json", "Origin": origin})[0], 200, origin)
290
291    def test_with_a_key_the_key_decides(self):
292        self.start(api_key="s3cret")
293        headers = {"Content-Type": "text/plain", "Origin": "http://evil.example.com"}
294        self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), headers)[0], 401)
295        self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(),
296                                  {**headers, "Authorization": "Bearer s3cret"})[0], 200)
297
298    def test_terminal_telemetry_requires_the_existing_key(self):
299        self.start(api_key="s3cret")
300        self.assertEqual(self.req("GET", "/v1/telemetry")[0], 401)
301        code, body, _ = self.req("GET", "/v1/telemetry", headers={"Authorization": "Bearer s3cret"})
302        self.assertEqual(code, 200)
303        self.assertEqual(body["schema_version"], 1)
304        self.assertNotIn("input", json.dumps(body))
305
306    def test_read_only_telemetry_key_does_not_authorize_inference_or_management(self):
307        self.start(api_key="inference-secret", telemetry_key="read-secret")
308        header = {"Authorization": "Bearer read-secret"}
309        self.assertEqual(self.req("GET", "/v1/telemetry", headers=header)[0], 200)
310        self.assertEqual(self.req("GET", "/metrics", headers=header)[0], 401)
311        self.assertEqual(self.req("GET", "/v1/models", headers=header)[0], 401)
312        self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(),
313                                  {**header, "Content-Type": "application/json"})[0], 401)
314        self.assertEqual(self.req("POST", "/unload", {},
315                                  {**header, "Content-Type": "application/json"})[0], 401)
316
317    def test_read_only_key_gets_bounded_redacted_request_activity(self):
318        self.start(api_key="inference-secret", telemetry_key="read-secret")
319        prompt = "DO_NOT_LEAK_PROMPT_ACTIVITY"
320        request = {**self.chat_body(), "messages": [{"role": "user", "content": prompt}]}
321        self.assertEqual(self.req("POST", "/v1/chat/completions", request,
322                                  {"Authorization": "Bearer inference-secret",
323                                   "Content-Type": "application/json"})[0], 200)
324        code, body, _ = self.req("GET", "/v1/telemetry",
325                                 headers={"Authorization": "Bearer read-secret"})
326        self.assertEqual(code, 200)
327        activity = body["activity"]
328        self.assertEqual(activity["last_seq"], len(activity["events"]))
329        self.assertLessEqual(len(activity["events"]), 32)
330        self.assertEqual(activity["events"][0]["event"], "queued")
331        self.assertEqual(activity["events"][-1]["event"], "finished")
332        self.assertEqual([e["seq"] for e in activity["events"]],
333                         list(range(1, activity["last_seq"] + 1)))
334        self.assertEqual(len({e["request_id"] for e in activity["events"]}), 1)
335        serialized = json.dumps(activity)
336        for secret in (prompt, "inference-secret", "read-secret", "</think>"):
337            self.assertNotIn(secret, serialized)
338        with self.svc.status_lock:
339            for i in range(140):
340                self.svc._terminal_event_locked(f"{i:012x}", "queued")
341        bounded = self.req("GET", "/v1/telemetry",
342                           headers={"Authorization": "Bearer read-secret"})[1]["activity"]
343        self.assertEqual(len(self.svc.terminal_events), 128)
344        self.assertEqual(len(bounded["events"]), 32)
345        self.assertEqual(bounded["events"][-1]["seq"], bounded["last_seq"])
346
347    # --- /unload and /load
348    def test_control_body_arrives_before_the_operation_and_reply(self):
349        self.start()
350        for body, expected in ((b"{}", 200), (b"{", 400)):
351            c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5)
352            try:
353                with mock.patch.object(self.svc, "unload", return_value="unloaded") as unload:
354                    c.putrequest("POST", "/unload")
355                    c.putheader("Content-Type", "application/json")
356                    c.putheader("Content-Length", "2")
357                    c.endheaders()
358                    c.sock.settimeout(0.1)
359                    with self.assertRaises(socket.timeout):
360                        c.sock.recv(1)
361                    unload.assert_not_called()
362                    c.sock.settimeout(5)
363                    c.send(body)
364                    if len(body) < 2:
365                        c.sock.shutdown(socket.SHUT_WR)
366                    r = c.getresponse()
367                    self.assertEqual(r.status, expected)
368                    r.read()
369                    self.assertEqual(unload.call_count, int(expected == 200))
370            finally:
371                c.close()
372
373    def test_unload_and_load_need_json_from_the_own_page(self):
374        self.start()
375        form = {"Content-Type": "application/x-www-form-urlencoded"}
376        for path in ("/unload", "/load"):
377            self.assertEqual(self.req("POST", path, b"a=1", form)[0], 415, path)
378            self.assertEqual(self.req("POST", path, b"", {})[0], 415, path)
379            self.assertEqual(self.req("POST", path, {}, {"Content-Type": "application/json",
380                                                         "Origin": "http://evil.example.com"})[0], 403, path)
381        self.assertEqual(self.req("POST", "/unload", {}, {"Content-Type": "application/json"})[0], 200)
382        self.assertEqual(self.req("POST", "/load", {}, {"Content-Type": "application/json",
383                                                        "Origin": f"http://127.0.0.1:{self.port}"})[0], 200)
384
385    # --- /slots/0?action=save|restore (session files)
386    def test_slots_need_json_from_the_own_page(self):
387        self.start()
388        body = {"filename": "a.bin"}
389        for action in ("save", "restore"):
390            path = f"/slots/0?action={action}"
391            self.assertEqual(self.req("POST", path, b"filename=a.bin",
392                                      {"Content-Type": "application/x-www-form-urlencoded"})[0], 415, path)
393            self.assertEqual(self.req("POST", path, body, {"Content-Type": "text/plain"})[0], 415, path)
394            for origin in ("http://evil.example.com", "null"):
395                self.assertEqual(self.req("POST", path, body, {"Content-Type": "application/json",
396                                                               "Origin": origin})[0], 403, (path, origin))
397            # JSON without an Origin (curl, scripts) or from the own page reaches the slot API: off here, so 501
398            self.assertEqual(self.req("POST", path, body, {"Content-Type": "application/json"})[0], 501, path)
399            self.assertEqual(self.req("POST", path, body, {"Content-Type": "application/json",
400                                                           "Origin": f"http://127.0.0.1:{self.port}"})[0], 501, path)
401        self.assertEqual(self.req("POST", "/slots/0?action=save", body, {"Content-Type": "application/json"},
402                                  host="rebind.example.com")[0], 403)
403
404
405class NoApiKey(unittest.TestCase):
406    """A key is recommended on a network, never required (owner decision 2026-10-20)."""
407
408    def test_none_means_no_key_on_purpose(self):
409        from serve.server import explicit_no_key
410        for v in ("none", " None ", "NONE"):
411            self.assertTrue(explicit_no_key(v))
412        for v in ("", None, "sk-none", ["none"], "none,x"):
413            self.assertFalse(explicit_no_key(v))
414
415    def test_the_warning_is_plain(self):
416        from serve.server import open_server_warning
417        w = open_server_warning(8080)
418        self.assertIn("anyone who can reach port 8080 can use the model", w)
419        self.assertNotIn("tools", w)
420        self.assertIn("and its tools", open_server_warning(8080, tools=True))
421        self.assertIn("public internet", open_server_warning(8080, public=True))
422
423
424if __name__ == "__main__":
425    unittest.main()