Skip to content

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++

#321 follow-up: CORS only on /v1/* for configured origins; no own-page bypass for proxy headers

Niko1221a8d5a16c3565
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index 8b9f75e25..2454069f2 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -447,7 +447,12 @@ print(r.choices[0].message.content)
- **From the internet.** Put a tunnel in front of it, for example [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/do-more-with-tunnels/trycloudflare/):
`cloudflared tunnel --url http://127.0.0.1:8080`. **Set a key first**, or anyone with the link can use your PC:
add `"api_key": "some-long-secret"` to `strata-<model>.json` (or set the `STRATA_API_KEY` environment variable);
- clients then send it as their API key.
+ clients then send it as their API key. Streamed answers carry `X-Accel-Buffering: no`, so nginx-style proxies pass
+ each token on at once. The web app's settings and MCP tools only answer Strata's own page: when you open it through
+ a proxy or tunnel whose address differs, add that address, e.g. `"trusted_origins": ["https://strata.example.com"]`.
+- **From web apps in a browser (CORS).** Off by default. `"cors_origins": ["https://chat.example.com"]` lets pages of
+ those origins call `/v1/*` from the browser (Open WebUI's direct connections, browser extensions); `["*"]` lets any
+ page do it - only sensible with an API key. It never opens `/settings`, `/unload` or the MCP tools.
**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 353fca917..5c5fbd10a 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -673,6 +673,12 @@ class Service:
self.fifo = threading.Lock()
self.embeddings = threading.local() # the current request's image embeddings file (GENI)
self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key)
+ # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that
+ # matters); empty = no CORS headers at all, as before
+ self.cors_origins: list[str] = []
+ # #321: origins that count as Strata's own page for /settings and MCP tools, e.g. the web app reached through a
+ # reverse proxy or tunnel whose Host differs ("https://strata.example.com"); never a wildcard
+ self.trusted_origins: list[str] = []
self.status = {"busy": False, "queued": 0} # GET /status: what the model is doing right now
self.rate = collections.deque(maxlen=32) # (time, generated) samples for the live tok/s window
self.history = collections.deque(maxlen=500) # the last finished requests, newest last (GET /metrics)
@@ -1524,20 +1530,39 @@ def make_handler(svc: Service):
def log_message(self, fmt, *args):
pass
+ def _cors(self):
+ """#321: CORS headers for an API path (/v1/*) and an origin the config lists in cors_origins - nothing
+ otherwise, so a browser keeps every other page away from the API, /settings, /unload and the MCP tools."""
+ if not svc.cors_origins or not self.path.split("?")[0].startswith("/v1/"):
+ return
+ origin = (self.headers.get("Origin") or "").rstrip("/")
+ if "*" in svc.cors_origins:
+ allow = "*"
+ elif origin and origin in svc.cors_origins:
+ allow = origin
+ self.send_header("Vary", "Origin")
+ else:
+ return
+ self.send_header("Access-Control-Allow-Origin", allow)
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
+ # the headers the preflight asks for (SDKs add their own; "*" does not cover Authorization)
+ asked = self.headers.get("Access-Control-Request-Headers")
+ self.send_header("Access-Control-Allow-Headers",
+ asked or "Authorization, Content-Type, x-api-key, anthropic-version, anthropic-beta")
+ self.send_header("Access-Control-Max-Age", "600")
+
def do_OPTIONS(self):
+ # a CORS preflight: no credentials come with it, so no API key; the headers only for cors_origins
self.send_response(204)
- self.send_header("Access-Control-Allow-Origin", "*")
- self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
- self.send_header("Access-Control-Allow-Headers", "*")
+ self._cors()
+ self.send_header("Content-Length", "0")
self.end_headers()
def _json(self, code, obj):
body = json.dumps(obj, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
- self.send_header("Access-Control-Allow-Origin", "*")
- self.send_header("Access-Control-Allow-Headers", "*")
- self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
+ self._cors()
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
@@ -1721,14 +1746,15 @@ def make_handler(svc: Service):
if not self.headers.get("Content-Type", "").startswith("application/json"):
self._json(415, {"error": {"message": "send application/json"}})
return False
- origin = self.headers.get("Origin")
- if origin:
- origin_host = origin.split("://", 1)[-1].split("/")[0]
- host = self.headers.get("X-Forwarded-Host") or self.headers.get("Host", "")
- if origin_host != host and origin_host.split(":")[0] != host.split(":")[0]:
- if not (self.headers.get("CF-Ray") or self.headers.get("X-Forwarded-For") or self.headers.get("CF-Connecting-IP")):
- self._json(403, {"error": {"message": f"{what} only from Strata's own page"}})
- return False
+ # The Origin must be this server's own address (host and port), or an origin the config trusts
+ # (trusted_origins: the web app behind a reverse proxy or tunnel). Headers a proxy adds (X-Forwarded-*,
+ # CF-Ray, CF-Connecting-IP) prove nothing about the page that sent the request, so they open nothing.
+ origin = (self.headers.get("Origin") or "").rstrip("/")
+ if origin and origin.split("://", 1)[-1] != self.headers.get("Host", "") and \
+ origin not in svc.trusted_origins:
+ self._json(403, {"error": {"message": f"{what} only from Strata's own page (or an origin in the "
+ f"config's trusted_origins)"}})
+ return False
return True
def _settings(self):
@@ -1750,9 +1776,8 @@ def make_handler(svc: Service):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
- self.send_header("X-Accel-Buffering", "no")
- self.send_header("Access-Control-Allow-Origin", "*")
- self.send_header("Access-Control-Allow-Headers", "*")
+ self.send_header("X-Accel-Buffering", "no") # nginx and similar proxies pass each event at once
+ self._cors()
self.end_headers()
def _openai(self, req):
@@ -1894,6 +1919,28 @@ def serve(svc: Service, host="127.0.0.1", port=8095) -> ThreadingHTTPServer:
return httpd
+def origins_of(value, key: str, wildcard: bool) -> list[str]:
+ """#321: a config's origin list ("https://chat.example.com" or a list of them) - scheme://host[:port], no path;
+ "*" only where `wildcard` allows it. A wrong entry stops the start rather than opening less or more than meant."""
+ if value is None or value == "" or value == []:
+ return []
+ items = [value] if isinstance(value, str) else value
+ if not isinstance(items, list) or not all(isinstance(x, str) for x in items):
+ raise SystemExit(f"[strata] {key}: expected an origin or a list of origins")
+ out = []
+ for x in items:
+ x = x.strip().rstrip("/")
+ if x == "*" and wildcard:
+ out.append(x)
+ continue
+ scheme, sep, rest = x.partition("://")
+ if scheme not in ("http", "https") or not sep or not rest or "/" in rest or "*" in rest:
+ raise SystemExit(f"[strata] {key}: {x!r} is not an origin like https://chat.example.com"
+ + ("" if wildcard else " (no wildcards here)"))
+ out.append(x)
+ return out
+
+
SHARED_KEYS = ("reasoning_effort", "temperature", "top_p", "top_k", "seed", "max_tokens", "experimental_speed_projection")
@@ -2092,6 +2139,12 @@ def main() -> int:
file=sys.stderr)
return 2
svc.api_key = a.api_key or cfg.get("api_key", "")
+ svc.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)
+ if svc.cors_origins:
+ print(f"[strata] CORS on /v1/* for {', '.join(svc.cors_origins)}"
+ + ("" if svc.api_key or "*" not in svc.cors_origins else
+ " - WARNING: any web page may use the model (no API key)"), flush=True)
svc.idle_unload_s = a.idle_unload if a.idle_unload is not None else float(cfg.get("idle_unload_s") or 0)
svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \
int(cfg.get("min_free_vram_mib") or 0)
diff --git a/serve/test_server.py b/serve/test_server.py
index 0f2816469..2f364631a 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -811,15 +811,28 @@ class SharedSettings(unittest.TestCase):
finally:
self.svc.api_key = ""
- def test_reverse_proxy_origin_allowed(self):
- # A tunnel or reverse-proxy with matching X-Forwarded-Host
- code, _ = self.req("/settings", {"defaults": {"temperature": 1}},
- {"Origin": "https://proxy.example.com", "X-Forwarded-Host": "proxy.example.com"})
- self.assertEqual(code, 200)
- # Cloudflare Tunnel passing CF-Ray
- code, _ = self.req("/settings", {"defaults": {"temperature": 1}},
- {"Origin": "https://random-name.trycloudflare.com", "CF-Ray": "1234567890"})
- self.assertEqual(code, 200)
+ def test_proxy_headers_do_not_make_a_page_strata_s_own(self):
+ # #321: X-Forwarded-*, CF-Ray or CF-Connecting-IP say nothing about the page that sent the request - any web
+ # page behind any proxy would otherwise change the settings (or run MCP tools)
+ for extra in ({"X-Forwarded-Host": "proxy.example.com"}, {"CF-Ray": "1234567890"},
+ {"X-Forwarded-For": "203.0.113.9"}, {"CF-Connecting-IP": "203.0.113.9"}):
+ code, _ = self.req("/settings", {"defaults": {"temperature": 1}},
+ {"Origin": "https://proxy.example.com", **extra})
+ self.assertEqual(code, 403, extra)
+ # another port on the same host is another site (a local dev server's page)
+ code, _ = self.req("/settings", {"defaults": {"temperature": 1}}, {"Origin": "http://127.0.0.1:1"})
+ self.assertEqual(code, 403)
+
+ def test_a_trusted_origin_is_strata_s_own_page(self):
+ # the web app behind a reverse proxy or tunnel: the config's trusted_origins
+ self.svc.trusted_origins = ["https://strata.example.com"]
+ try:
+ code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://strata.example.com"})
+ self.assertEqual(code, 200)
+ code, _ = self.req("/settings", {"defaults": {}}, {"Origin": "https://evil.example.com"})
+ self.assertEqual(code, 403)
+ finally:
+ self.svc.trusted_origins = []
class WebApp(unittest.TestCase):
@@ -1014,17 +1027,57 @@ class UsageAndStatus(unittest.TestCase):
return [json.loads(line[6:]) for line in raw.decode().splitlines()
if line.startswith("data: {")]
- def test_cors_preflight_options(self):
- req = urllib.request.Request(self.base + "/v1/chat/completions", method="OPTIONS")
+ def preflight(self, path, origin="https://chat.example.com"):
+ req = urllib.request.Request(self.base + path, method="OPTIONS",
+ headers={"Origin": origin, "Access-Control-Request-Method": "POST",
+ "Access-Control-Request-Headers": "authorization, content-type"})
with urllib.request.urlopen(req, timeout=10) as r:
- self.assertEqual(r.status, 204)
- self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "*")
- self.assertIn("OPTIONS", r.headers.get("Access-Control-Allow-Methods", ""))
+ return r.status, r.headers
+
+ def test_cors_is_off_by_default(self):
+ # #321: OPTIONS is answered, but without cors_origins no page of another origin is let in
+ status, h = self.preflight("/v1/chat/completions")
+ self.assertEqual(status, 204)
+ self.assertIsNone(h.get("Access-Control-Allow-Origin"))
+ with urllib.request.urlopen(self.base + "/health", timeout=10) as r:
+ self.assertIsNone(r.headers.get("Access-Control-Allow-Origin"))
+
+ def test_cors_for_the_configured_origins_on_the_api_only(self):
+ self.svc.cors_origins = ["https://chat.example.com"]
+ try:
+ status, h = self.preflight("/v1/chat/completions")
+ self.assertEqual((status, h.get("Access-Control-Allow-Origin")), (204, "https://chat.example.com"))
+ self.assertIn("OPTIONS", h.get("Access-Control-Allow-Methods", ""))
+ self.assertIn("authorization", h.get("Access-Control-Allow-Headers", ""))
+ self.assertIsNone(self.preflight("/v1/chat/completions", "https://evil.example.com")[1]
+ .get("Access-Control-Allow-Origin"))
+ # never on the app's own endpoints (/settings, /unload, ...)
+ self.assertIsNone(self.preflight("/settings")[1].get("Access-Control-Allow-Origin"))
+ req = urllib.request.Request(self.base + "/v1/models", headers={"Origin": "https://chat.example.com"})
+ with urllib.request.urlopen(req, timeout=10) as r:
+ self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "https://chat.example.com")
+ self.svc.cors_origins = ["*"]
+ self.assertEqual(self.preflight("/v1/messages", "https://any.example.com")[1]
+ .get("Access-Control-Allow-Origin"), "*")
+ finally:
+ self.svc.cors_origins = []
- def test_cors_headers(self):
- req = urllib.request.Request(self.base + "/health")
- with urllib.request.urlopen(req, timeout=10) as r:
- self.assertEqual(r.headers.get("Access-Control-Allow-Origin"), "*")
+ def test_sse_is_not_buffered_by_proxies(self):
+ req = urllib.request.Request(self.base + "/v1/chat/completions", headers={"Content-Type": "application/json"},
+ data=json.dumps({"model": "m", "stream": True,
+ "messages": [{"role": "user", "content": "hi"}]}).encode())
+ with urllib.request.urlopen(req, timeout=30) as r:
+ self.assertEqual(r.headers.get("X-Accel-Buffering"), "no")
+ r.read()
+
+ def test_origin_lists_are_checked(self):
+ from serve.server import origins_of
+ self.assertEqual(origins_of(None, "k", True), [])
+ self.assertEqual(origins_of("https://a.example.com/", "k", False), ["https://a.example.com"])
+ self.assertEqual(origins_of(["*", "http://localhost:3000"], "k", True), ["*", "http://localhost:3000"])
+ for bad in ("*", "a.example.com", "https://a.example.com/path", "https://*.example.com", 5):
+ with self.assertRaises(SystemExit):
+ origins_of(bad, "k", False)
def test_openai(self):
b = self.chat("/v1/chat/completions")