diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 2c6621c7..53974cba 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -405,7 +405,8 @@ server, three server options (all off by default; also as keys in `strata-.json` or `STRATA_ALLOWED_HOSTS=strata.example.com` (comma-separated); `".example.com"` allows that name and every name below it, and `["*"]` turns the check off. The hosts of `trusted_origins` count as allowed. Requests without a `Host` header (HTTP/1.0 clients) pass. +- **Web pages without an API key.** Without `api_key`, a `POST` to `/v1/*` that carries an `Origin` header (a + browser page sent it) is answered only for Strata's own page, pages on `localhost` or an allowed host name (any + port), the origins in `trusted_origins` or `cors_origins`, and browser extensions and desktop apps + (`chrome-extension://`, `moz-extension://`, `app://`: no web site can send those), and only with a JSON body; any + other page, and `Origin: null`, gets **403**. Clients that send no `Origin` (curl, the OpenAI and Anthropic SDKs, + other servers) are not affected. With + an API key, the key decides. `POST /unload` and `POST /load` take `Content-Type: application/json` from Strata's + own page (or no `Origin`), like `/settings`. **Conversation cache.** A request that continues a chat reads only the part after what the engine already holds: the live session, or one of the checkpoints it keeps in RAM (up to 6, ~118 MB each, taken at the start of each new diff --git a/serve/server.py b/serve/server.py index 4fc94a9e..68f048d7 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1987,6 +1987,27 @@ def make_handler(svc: Service): f"the STRATA_ALLOWED_HOSTS environment variable"}}) return False + def _foreign_page(self) -> bool: + """Without an API key, a /v1 POST from a browser page of another site (any site can POST text/plain + there without a CORS preflight) would burn GPU time: an Origin header must name an allowed page, and + then the body must be JSON. No Origin (curl, the SDKs, other servers): any content type, as before.""" + origin = self.headers.get("Origin") + if svc.api_key or not origin: + return False + if not origin_allowed(origin, self.headers.get("Host"), svc.host_names, + [*svc.trusted_origins, *svc.cors_origins]): + print(f"[strata] refused an API request from the web page {origin!r} (no API key; add its host to " + f"\"allowed_hosts\" or its origin to \"cors_origins\" in the config)", flush=True) + self._json(403, {"error": {"type": "forbidden", "message": + f"web pages of {origin} may not use this server without an API key; set \"api_key\", " + f"or add the page's host to \"allowed_hosts\" (or its origin to \"cors_origins\") " + f"in the config"}}) + return True + if not self.headers.get("Content-Type", "").startswith("application/json"): + self._json(415, {"error": {"message": "send application/json"}}) + return True + return False + def _watch_client(self, cancel: threading.Event) -> None: """#430 #431: cancel the request as soon as its client hangs up. A non-streamed request writes nothing until it ends, and a streamed one only a keep-alive per prompt chunk (and the first write after a hang-up @@ -2190,9 +2211,14 @@ def make_handler(svc: Service): if not self._authorized(): return path = self.path.split("?")[0].rstrip("/") # issue #55: Claude Code posts /v1/messages?beta=true + if path.startswith("/v1/") and self._foreign_page(): + return if path == "/settings": self._settings() return + # JSON from Strata's own page only, as /settings: else a plain form POST from any site unloads the model + if path in ("/unload", "/load") and not self._own_page("the model can be loaded or unloaded"): + return if path == "/unload": # give the GPU back now (between requests) try: r = svc.unload() @@ -2613,6 +2639,26 @@ def host_allowed(host, names, any_host=False) -> bool: or _name_in(name, names)) +def origin_allowed(origin: str, host, names, origins=()) -> bool: + """A browser page's Origin that may use the model without an API key: this server's own page (the Origin is the + request's own Host), a page on one of the names this server answers to (any port), or an origin the config lists + (trusted_origins, cors_origins). Unlike the Host check no IP passes on trust: a page served from any other IP is + another site. "null" (a sandboxed frame, a file:// page) does not pass: any site can send it. An origin of another + scheme (chrome-extension://, moz-extension://, an Electron app's app://) does: no web site can send one.""" + origin = (origin or "").strip().rstrip("/") + if origin in origins or "*" in origins: # cors_origins ["*"]: the config lets every page in + return True + scheme, sep, rest = origin.lower().partition("://") + if not sep or not scheme: + return False + if scheme not in ("http", "https"): + return True + if host and rest == host.strip().lower(): + return True + name = host_name(rest) + return bool(name) and (name in LOOPBACK_NAMES or name.endswith(".localhost") or _name_in(name, names)) + + def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer: svc.host_names = host_names_for(host, svc.allowed_hosts, svc.trusted_origins) svc.start_telemetry() diff --git a/serve/test_security.py b/serve/test_security.py index 2e137495..f79b6b9e 100644 --- a/serve/test_security.py +++ b/serve/test_security.py @@ -1,4 +1,5 @@ -"""serve/test_security.py - the Host check (DNS rebinding), against the mock engine (no GPU, no pack). +"""serve/test_security.py - the Host check (DNS rebinding) and the Origin check for requests without an API key, +against the mock engine (no GPU, no pack). python -m unittest serve.test_security -v """ @@ -17,7 +18,7 @@ from unittest import mock sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from serve.frontend import ChatTemplate # noqa: E402 from serve.server import (ByteTokenizer, MockEngine, Service, allowed_hosts_of, host_allowed, # noqa: E402 - host_name, host_names_for, serve) + host_name, host_names_for, origin_allowed, serve) ROOT = Path(__file__).resolve().parents[1] LOCAL = {"localhost", "127.0.0.1", "::1"} @@ -72,6 +73,27 @@ class HostCheck(unittest.TestCase): self.assertTrue(host_allowed("evil.example.com", LOCAL, any_host=True)) +class OriginCheck(unittest.TestCase): + def test_accepted(self): + names = LOCAL | {"box"} + self.assertTrue(origin_allowed("http://127.0.0.1:8095", "127.0.0.1:8095", names)) # Strata's own page + self.assertTrue(origin_allowed("http://192.168.1.20:8095", "192.168.1.20:8095", names)) # ... by LAN IP + self.assertTrue(origin_allowed("http://localhost:3000", "127.0.0.1:8095", names)) # a local app + self.assertTrue(origin_allowed("http://[::1]:3000/", "127.0.0.1:8095", names)) + self.assertTrue(origin_allowed("https://box", "127.0.0.1:8095", names)) + self.assertTrue(origin_allowed("https://chat.example.com", "x", names, ["https://chat.example.com"])) + self.assertTrue(origin_allowed("https://any.example.com", "x", names, ["*"])) # cors_origins ["*"] + # browser extensions and desktop apps: no web site can send another scheme than http(s) (or "null") + for origin in ("chrome-extension://abcdef", "moz-extension://1234-5678", "app://."): + self.assertTrue(origin_allowed(origin, "127.0.0.1:8095", names), origin) + + def test_refused(self): + names = LOCAL | {"box"} + for origin in ("http://evil.example.com", "http://1.2.3.4", "http://192.168.1.99:8095", "null", "", + "http://localhost.evil.com", "https://box.evil.com", "://x"): + self.assertFalse(origin_allowed(origin, "127.0.0.1:8095", names, ["https://chat.example.com"]), origin) + + class OverHttp(unittest.TestCase): """The checks in the running server, as a browser and as curl/the SDKs send their requests.""" @@ -152,6 +174,64 @@ class OverHttp(unittest.TestCase): self.start(trusted_origins=["https://strata.example.com"]) self.assertEqual(self.req("GET", "/status", host="strata.example.com")[0], 200) + # --- Origin on /v1 without an API key + def test_curl_and_sdks_without_origin(self): + self.start() + for ctype in ("application/json", "text/plain", None): # curl -d sends a form type + code, body, _ = self.req("POST", "/v1/chat/completions", self.chat_body(), + {"Content-Type": ctype} if ctype else {}) + self.assertEqual(code, 200, ctype) + self.assertEqual(body["choices"][0]["message"]["content"], "ok") + + def test_cross_site_page_is_refused(self): + self.start() + for path in ("/v1/chat/completions", "/v1/messages", "/v1/messages/count_tokens"): + for ctype in ("text/plain", "application/json"): + code, body, log = self.req("POST", path, self.chat_body(), + {"Content-Type": ctype, "Origin": "http://evil.example.com"}) + self.assertEqual(code, 403, (path, ctype)) + self.assertIn("api_key", body["error"]["message"]) + self.assertIn("evil.example.com", log) + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {"Content-Type": "text/plain", "Origin": "null"})[0], 403) + + def test_own_and_local_pages_pass(self): + self.start() + json_type = {"Content-Type": "application/json"} + for origin in (f"http://127.0.0.1:{self.port}", "http://localhost:3000", "chrome-extension://abcdef"): + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {**json_type, "Origin": origin})[0], 200, origin) + # a browser page sends JSON; text/plain from a page is the cross-site "simple request" shape + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {"Content-Type": "text/plain", "Origin": f"http://127.0.0.1:{self.port}"})[0], 415) + + def test_configured_origins_pass(self): + self.start(cors_origins=["https://chat.example.com"], trusted_origins=["https://strata.example.com"], + allowed_hosts=["webui.lan"]) + for origin in ("https://chat.example.com", "https://strata.example.com", "http://webui.lan:3000"): + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {"Content-Type": "application/json", "Origin": origin})[0], 200, origin) + + def test_with_a_key_the_key_decides(self): + self.start(api_key="s3cret") + headers = {"Content-Type": "text/plain", "Origin": "http://evil.example.com"} + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), headers)[0], 401) + self.assertEqual(self.req("POST", "/v1/chat/completions", self.chat_body(), + {**headers, "Authorization": "Bearer s3cret"})[0], 200) + + # --- /unload and /load + def test_unload_and_load_need_json_from_the_own_page(self): + self.start() + form = {"Content-Type": "application/x-www-form-urlencoded"} + for path in ("/unload", "/load"): + self.assertEqual(self.req("POST", path, b"a=1", form)[0], 415, path) + self.assertEqual(self.req("POST", path, b"", {})[0], 415, path) + self.assertEqual(self.req("POST", path, {}, {"Content-Type": "application/json", + "Origin": "http://evil.example.com"})[0], 403, path) + self.assertEqual(self.req("POST", "/unload", {}, {"Content-Type": "application/json"})[0], 200) + self.assertEqual(self.req("POST", "/load", {}, {"Content-Type": "application/json", + "Origin": f"http://127.0.0.1:{self.port}"})[0], 200) + if __name__ == "__main__": unittest.main()