serve: add CORS preflight (OPTIONS), reverse-proxy header support, and X-Accel-Buffering for SSE

- Implement do_OPTIONS (204 No Content) and add Access-Control-Allow-* headers to allow web-based clients (Open WebUI, LibreChat, browser extensions) to query endpoints.
- Update _own_page to recognize reverse proxies and tunnels (Cloudflare Tunnel, Tailscale Funnel, Nginx) via X-Forwarded-Host, CF-Ray, and forwarded headers, preventing 403 CSRF false-positives when serving remotely.
- Add X-Accel-Buffering: no to SSE streaming responses to prevent reverse proxies from buffering real-time token generation.
- Add unit tests in serve/test_server.py covering CORS preflight, CORS headers, and reverse proxy origin checks.

Co-authored-by: Gemini <gemini@google.com>
This commit is contained in:
BlitzenCatsandGemini authored and Niko1221 committed 2026-10-01 08:22:10 +02:00
1 parent ca85ebdee2
commit 392e32c46b
2 files changed
+42 -3

No files matched your search

+20 -3
View File
@@ -1524,10 +1524,20 @@ def make_handler(svc: Service):
def log_message(self, fmt, *args):
pass
def do_OPTIONS(self):
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.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.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
@@ -1712,9 +1722,13 @@ def make_handler(svc: Service):
self._json(415, {"error": {"message": "send application/json"}})
return False
origin = self.headers.get("Origin")
if origin and origin.split("://", 1)[-1] != self.headers.get("Host", ""):
self._json(403, {"error": {"message": f"{what} only from Strata's own page"}})
return False
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
return True
def _settings(self):
@@ -1736,6 +1750,9 @@ 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.end_headers()
def _openai(self, req):
+22
View File
@@ -811,6 +811,16 @@ 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)
class WebApp(unittest.TestCase):
"""The web app (PR #22's dashboard idea, rebuilt): its page and files, and GET /metrics."""
@@ -1004,6 +1014,18 @@ 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")
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", ""))
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_openai(self):
b = self.chat("/v1/chat/completions")
u, t = b["usage"], b["timings"]