Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: an API key with spaces or characters outside ASCII matches; a blank key is refused at start (#956)
BGonnermann4bc3b4ef45c5
diff --git a/serve/server.py b/serve/server.pyindex f969d99ec..7b89f858a 100644--- a/serve/server.py+++ b/serve/server.py@@ -3840,7 +3840,7 @@ def make_handler(svc: Service):return Trueauth = self.headers.get("Authorization", "")given = auth[7:].strip() if auth.lower().startswith("bearer ") else self.headers.get("x-api-key", "")- if hmac.compare_digest(given.encode(), svc.api_key.encode()): # #213: constant-time+ if key_matches(given, svc.api_key):return Trueself._json(401, {"error": {"type": "authentication_error", "message": "missing or wrong API key"}})return False@@ -4722,6 +4722,30 @@ def host_allowed(host, names, any_host=False) -> bool:or _name_in(name, names))+def api_key_of(value) -> str:+ """The key as a client can send it (#725). An HTTP header loses the spaces and line ends around its value, so a+ key kept with them (a config file or an environment file with CRLF line ends, a quoted " key ") matched no+ request: every client got 401 with the right key. A value that is only such characters raises ValueError, it+ never means "no key" (#213)."""+ key = "" if value is None else str(value)+ if key and not key.strip():+ raise ValueError("an API key was given but it is empty")+ return key.strip()+++def key_matches(given: str, key: str) -> bool:+ """given: a header's value as http.server read it, each byte one character. A key with characters outside ASCII+ arrives as UTF-8 from most clients and as Latin-1 from some; the right key passes in both forms (#725: the+ bytes were re-encoded before, so a UTF-8 key never matched). Constant-time (#213)."""+ raw = given.encode("latin-1", "replace")+ ok = hmac.compare_digest(raw, key.encode())+ try:+ ok |= hmac.compare_digest(raw, key.encode("latin-1"))+ except UnicodeEncodeError:+ pass+ return ok++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 therequest's own Host), a page on one of the names this server answers to (any port), or an origin the config lists@@ -5010,7 +5034,11 @@ def main() -> int:print("[strata] an API key was given but it is empty: set a key, or leave --api-key / STRATA_API_KEY out",file=sys.stderr)return 2- svc.api_key = a.api_key or cfg.get("api_key", "")+ try:+ svc.api_key = api_key_of(a.api_key or cfg.get("api_key", ""))+ except ValueError as e:+ print(f'[strata] {e}: set a key, or leave --api-key / STRATA_API_KEY / "api_key" out', file=sys.stderr)+ return 2svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True)svc.trusted_origins = origins_of(cfg.get("trusted_origins"), "trusted_origins", wildcard=False)try:diff --git a/serve/test_server.py b/serve/test_server.pyindex c53280bbd..10053f8ee 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -22,7 +22,8 @@ from unittest import mocksys.path.insert(0, str(Path(__file__).resolve().parents[1]))from serve.frontend import ChatTemplate, literal_tags, mark_think_literals, unmark_think_literals # noqa: E402from serve.server import (CTX_SLACK, ByteTokenizer, EngineDied, GpuBusy, MockEngine, PP_DONE_TAIL, Service, # noqa: E402- StrataEngine, engine_args, layer_split_value, prompt_progress, prompt_tokens_seen,+ StrataEngine, api_key_of, engine_args, key_matches, layer_split_value, prompt_progress,+ prompt_tokens_seen,request_timings, serve, start_failure_hint)from types import SimpleNamespace # noqa: E402@@ -846,6 +847,53 @@ class StatusNeedsTheKey(unittest.TestCase):httpd.server_close()+class ApiKeyForms(unittest.TestCase):+ """#725: a key no client could send (spaces or a line end around it), and a key outside ASCII."""++ def test_the_key_loses_what_a_header_cannot_carry(self):+ self.assertEqual(api_key_of(" s3cret "), "s3cret")+ self.assertEqual(api_key_of("s3cret\r\n"), "s3cret")+ self.assertEqual(api_key_of("two words"), "two words")+ self.assertEqual(api_key_of(12345), "12345") # a number in the config file+ self.assertEqual(api_key_of(""), "")+ self.assertEqual(api_key_of(None), "")++ def test_a_blank_key_is_an_error_not_no_key(self):+ for blank in (" ", "\r\n", "\t "):+ with self.assertRaises(ValueError):+ api_key_of(blank)++ def test_a_key_outside_ascii_matches_as_utf8_and_as_latin1(self):+ def as_read(key, enc): # what http.server hands the handler+ return key.encode(enc).decode("latin-1")+ self.assertTrue(key_matches("s3cret", "s3cret"))+ self.assertFalse(key_matches("s3cret ", "s3cret"))+ self.assertFalse(key_matches("", "s3cret"))+ self.assertTrue(key_matches(as_read("clé", "utf-8"), "clé"))+ self.assertTrue(key_matches(as_read("clé", "latin-1"), "clé"))+ self.assertTrue(key_matches(as_read("ключ", "utf-8"), "ключ"))+ self.assertFalse(key_matches(as_read("ключ", "utf-8"), "ключx"))++ def test_a_utf8_key_over_http(self):+ tok = ByteTokenizer()+ svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ svc.api_key = "ключ"+ httpd = serve(svc, port=0)+ base = f"http://127.0.0.1:{httpd.server_address[1]}/status"+ try:+ sent = ("Bearer " + svc.api_key).encode().decode("latin-1") # UTF-8 bytes, as curl and the web app send+ with urllib.request.urlopen(urllib.request.Request(base, headers={"Authorization": sent}), timeout=10) as r:+ self.assertEqual(r.status, 200)+ with self.assertRaises(urllib.error.HTTPError) as e:+ urllib.request.urlopen(urllib.request.Request(base, headers={"Authorization": "Bearer ???"}),+ timeout=10)+ self.assertEqual(e.exception.code, 401)+ e.exception.close()+ finally:+ httpd.shutdown()+ httpd.server_close()++class ToolCallTerminators(unittest.TestCase):"""#210: a value that contains </parameter> or </tool_call> (a file documenting the call format) is kept whole."""CONTENT = ("Close each value with </parameter> and the call with </function></tool_call>.\n"