Merge branch 'f-138-sec' into f-138-prs

This commit is contained in:
Niko1221 committed 2026-10-03 02:21:36 +02:00
commit f3efd59298
5 files changed
+453 -10

No files matched your search

+23 -1
View File
@@ -405,7 +405,8 @@ server, three server options (all off by default; also as keys in `strata-<model
| `--min-free-vram-mib 11000` | `"min_free_vram_mib": 11000` | load an unloaded model only when that much VRAM is free (it waits up to 15 s for memory being given back), else answer **503** "the GPU is in use by another program" instead of starting into what a game left (with several GPUs it checks the first one) |
| `--before-load "cmd"` | `"before_load": "cmd"` or `["cmd", "arg"]` | a command run before the model is loaded again, e.g. one that unloads another server's model |
`POST /unload` unloads it now (`409` while a request is running) and `POST /load` loads it ahead of a request;
`POST /unload` unloads it now (`409` while a request is running) and `POST /load` loads it ahead of a request (both
with `Content-Type: application/json`, e.g. `curl -X POST -H "Content-Type: application/json" localhost:8080/unload`);
`/health` says `"loaded"`, `/v1/models` lists it as `unloaded` (like llama.cpp's router), `/props` sets
`is_sleeping` and the Monitor shows the state. Unloading ends the engine process - and the image encoder, when images
are on; it is started again first, as at a start - so their VRAM and RAM go straight back. The model files stay in
@@ -539,9 +540,30 @@ print(r.choices[0].message.content)
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"]`.
With the key set, any `Host` name reaches the server (see Host names below).
- **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.
- **Host names (DNS rebinding).** A web page of another site can point its own name at `127.0.0.1` and then reach
this server as if it were its own, so without an API key the server answers only requests whose `Host` is a name
it knows (with a key the check is off: such a page cannot send the key, and tunnels and proxies that pass their
own name on keep working):
`localhost` (and `*.localhost`), any IP address (`127.0.0.1`, `[::1]`, `192.168.x.x`, ...), the address it
listens on and, when it listens beyond this PC (`0.0.0.0` or a LAN address), this PC's name (`mypc`, `mypc.local`)
and `host.docker.internal`; any port. Others get **403** naming the setting, and the server window prints one line
for each. Reach it under another name (a reverse proxy that keeps the name, a tunnel, a DNS name on your network,
another container's name for it)? Add the name: `"allowed_hosts": ["strata.example.com"]` in
`strata-<model>.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 (so does setting `api_key`). 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
+10 -8
View File
@@ -11,12 +11,14 @@ The installer recommends one for your PC; this page explains the choice. Back to
| Your RAM | Take | Why |
| --- | --- | --- |
| **32 GB** | **Coder** | it fits 32 GB, and it is made for code (with a 24 GB card, Q2_0 and IQ2_XS run too: [low-RAM mode](#a-big-graphics-card-and-little-ram)) |
| **32 GB** | **Coder** | it fits 32 GB; best at code, weaker at everything else ([why](#coder)). With a 24 GB card, Q2_0 and IQ2_XS run too ([low-RAM mode](#a-big-graphics-card-and-little-ram)) and are the better pick for general use |
| **48 GB** | **IQ2_XS** (or Q2_0, the fastest) | the larger sizes do not fit |
| **64 GB** | **IQ2_XS** (recommended), or IQ3_XXS / IQ3_S | every size fits (IQ3_S with little else open) |
| **96 GB or more** | **IQ3_S**, or [Unsloth's 4-bit](#unsloth-ud-q4_k_xl-experimental) (experimental) | room for the largest sizes |
Not sure? Take **IQ2_XS** - or the **Coder** if you mainly write code, or have 32-48 GB of RAM.
Not sure? Take **IQ2_XS**. The **Coder** is the one that fits a 32 GB PC, but it keeps only 256 of the 512 experts,
chosen on code data, so it is weaker outside code and in languages other than English. For general use, or whenever
your RAM allows, take a full model (Q2_0, IQ2_XS or IQ3_S).
## How fast is each size
@@ -91,12 +93,12 @@ The original, in all four sizes. With images, and with the
### Coder
**[Coder](https://huggingface.co/ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-Coder-GGUF)** - ISTA-DASLab's coding version:
half of the experts removed, keeping the ones that code, tool use and images need (91% of the full model's SWE-bench
Verified score, 99% of LiveCodeBench, by its authors). One size (IQ1_M: its experts stored like IQ3_S): shard 1 is
**29.6 GB**, so it fits a PC with **32 GB of RAM**, runs 262K context on 64 GB, and reads long prompts the fastest of
all. It is weaker outside code, and that includes Chinese and other CJK text (#438: Chinese answers came out wrong
or looping where English was fine). For general chat or CJK text, take a size that keeps every expert: Q2_0,
IQ2_XS or IQ3_S.
it keeps 256 of each layer's 512 experts, chosen on code (with agentic and image) data, and drops the rest (91% of
the full model's SWE-bench Verified score, 99% of LiveCodeBench, by its authors). One size (IQ1_M: its experts stored
like IQ3_S): shard 1 is **29.6 GB**, so it fits a PC with **32 GB of RAM**, runs 262K context on 64 GB, and reads long
prompts the fastest of all. With half the experts gone it is weaker outside code and in languages other than
English, Chinese and other CJK text included (#438: Chinese answers came out wrong or looping where English was
fine). For general use, or whenever your RAM allows, take a size that keeps every expert: Q2_0, IQ2_XS or IQ3_S.
More: [details](DETAILS.md#or-the-coder-half-the-experts-for-code).
```
+164
View File
@@ -61,6 +61,7 @@ IMAGE_PAD = "<|image_pad|>"
VISION_START = "<|vision_start|>"
# #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it)
REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n</think>\n\n"
LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")
CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here
# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first
# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.
@@ -960,6 +961,10 @@ class Service:
# #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] = []
# DNS rebinding: extra Host names this server answers to (the config's allowed_hosts, $STRATA_ALLOWED_HOSTS;
# "*" = any), and every name it answers to, which serve() works out from the address it listens on
self.allowed_hosts: list[str] = []
self.host_names: set[str] = set(LOOPBACK_NAMES)
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
# #332: the API request monitor (/api-monitor) keeps the last 100 requests' prompts and answers in memory,
@@ -1973,6 +1978,46 @@ def make_handler(svc: Service):
def log_message(self, fmt, *args):
pass
def parse_request(self):
"""Without an API key, every request (any method) first passes the Host check: DNS rebinding protection
(host_allowed). With a key a rebinding page cannot authenticate, so the check is skipped: tunnels and
proxies that pass their own name on keep working."""
if not super().parse_request():
return False
host = self.headers.get("Host")
if svc.api_key or host_allowed(host, svc.host_names, "*" in svc.allowed_hosts):
return True
print(f"[strata] refused a request for Host {host!r} from {self.client_address[0]}: not a name this server "
f"answers to (add it to \"allowed_hosts\" in the config or STRATA_ALLOWED_HOSTS, or set an API key)",
flush=True)
self._json(403, {"error": {"type": "forbidden", "message":
f"Host {host!r} is not allowed (DNS rebinding protection). Reaching Strata under this "
f"name on purpose? Add it to \"allowed_hosts\" in the config (strata-<model>.json) or to "
f"the STRATA_ALLOWED_HOSTS environment variable, or set an API key (\"api_key\"), which "
f"turns this check off"}})
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
@@ -2176,9 +2221,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()
@@ -2513,7 +2563,114 @@ def lan_addresses() -> list[str]:
return ([first] if ok(first) else []) + sorted(ip for ip in ips if ok(ip) and ip != first)
def host_name(value) -> str:
"""The name in a Host header (or an origin's host[:port]): "Example.com:8080" -> "example.com",
"[::1]:8095" -> "::1"; "" when it is malformed."""
v = (value or "").strip().lower()
if v.startswith("["):
name, sep, rest = v[1:].partition("]")
return name if sep and (not rest or (rest[:1] == ":" and rest[1:].isdigit())) else ""
if v.count(":") == 1:
v, port = v.split(":")
if not port.isdigit():
return ""
elif ":" in v: # a bare IPv6 address (a config entry)
return v
v = v.rstrip(".")
return v if v and all(c.isalnum() or c in "-._" for c in v) else ""
def _is_ip(name: str) -> bool:
import ipaddress
try:
ipaddress.ip_address(name)
return True
except ValueError:
return False
def _name_in(name: str, names) -> bool:
"""`name` is one of `names`, or below an entry that starts with a dot (".example.com")."""
return name in names or any(n.startswith(".") and (name.endswith(n) or name == n[1:]) for n in names)
def allowed_hosts_of(value, env: str = "") -> list[str]:
"""The config's allowed_hosts (a name or a list) plus $STRATA_ALLOWED_HOSTS (comma-separated): host names, "*" or
".example.com" (it and every name below it). A scheme, port or path is dropped ("https://a.example.com:8443/"
-> "a.example.com"); a wrong entry stops the start (ValueError)."""
items = [] if value in (None, "") else [value] if isinstance(value, str) else value
if not isinstance(items, list) or not all(isinstance(x, str) for x in items):
raise ValueError("allowed_hosts: expected a host name or a list of them")
out = []
for raw in items + [x for x in env.split(",") if x.strip()]:
x = raw.strip().lower()
if x == "*":
out.append(x)
continue
x = x.split("://", 1)[-1].split("/", 1)[0]
dot = x.startswith(".")
name = host_name(x[1:] if dot else x)
if not name:
raise ValueError(f"allowed_hosts: {raw!r} is not a host name like strata.example.com")
out.append("." + name if dot else name)
return list(dict.fromkeys(out))
def host_names_for(bind_host: str, allowed_hosts=(), trusted_origins=()) -> set[str]:
"""Every name this server answers to besides an IP address: localhost, the address it listens on, the config's
allowed_hosts and trusted_origins' hosts, and - listening beyond this PC (0.0.0.0 or a LAN address) - this PC's
name and LAN addresses (the LAN addresses matter for the Origin check, which takes no IP on trust)."""
names = set(LOOPBACK_NAMES)
bind = host_name(bind_host)
if bind and bind not in ("0.0.0.0", "::"):
names.add(bind)
if bind not in LOOPBACK_NAMES:
try:
pc = socket.gethostname().lower()
names.update((pc, pc + ".local"))
except OSError:
pass
names.update(("host.docker.internal", *lan_addresses()))
names.update(x for x in allowed_hosts if x != "*")
names.update(filter(None, (host_name(o.split("://", 1)[-1]) for o in trusted_origins)))
return names
def host_allowed(host, names, any_host=False) -> bool:
"""DNS rebinding: a web page of another site whose name its DNS points at 127.0.0.1 reaches this server as the
same origin, so the browser lets it read every answer. Its requests carry that site's name in Host, so only
the names this server answers to pass. An IP address passes (a page served from an IP is that IP's own page;
rebinding needs a name), as does "*.localhost" (browsers never ask DNS for it) and a request without a Host
header (HTTP/1.0 clients; browsers always send one)."""
if any_host or not (host or "").strip():
return True
name = host_name(host)
return bool(name) and (_is_ip(name) or name == "localhost" or name.endswith(".localhost")
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()
httpd = Server((host, port), make_handler(svc))
threading.Thread(target=httpd.serve_forever, daemon=True).start()
@@ -2762,6 +2919,13 @@ def main() -> int:
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)
try:
svc.allowed_hosts = allowed_hosts_of(cfg.get("allowed_hosts"), os.environ.get("STRATA_ALLOWED_HOSTS", ""))
except ValueError as e:
raise SystemExit(f"[strata] config {e}")
if svc.allowed_hosts:
print("[strata] Host check off: any name reaches this server (allowed_hosts \"*\")" if "*" in svc.allowed_hosts
else f"[strata] also answers to the host names {', '.join(svc.allowed_hosts)} (allowed_hosts)", flush=True)
svc.api_monitor = a.api_monitor or cfg.get("api_monitor") is True
if svc.api_monitor:
print("[strata] API request monitor on (/api-monitor): the last 100 requests' prompts and answers are kept in "
+255
View File
@@ -0,0 +1,255 @@
"""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
"""
from __future__ import annotations
import contextlib
import http.client
import io
import json
import socket
import sys
import unittest
from pathlib import Path
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, origin_allowed, serve)
ROOT = Path(__file__).resolve().parents[1]
LOCAL = {"localhost", "127.0.0.1", "::1"}
class HostNames(unittest.TestCase):
def test_host_name(self):
self.assertEqual(host_name("Example.COM:8080"), "example.com")
self.assertEqual(host_name("localhost"), "localhost")
self.assertEqual(host_name("[::1]:8095"), "::1")
self.assertEqual(host_name("[::1]"), "::1")
self.assertEqual(host_name("strata.example.com."), "strata.example.com")
for bad in ("", "a:b", "[::1", "[::1]x", "a b", "evil.com/x"):
self.assertEqual(host_name(bad), "", bad)
def test_allowed_hosts_of(self):
self.assertEqual(allowed_hosts_of(None), [])
self.assertEqual(allowed_hosts_of("Strata.Example.com"), ["strata.example.com"])
self.assertEqual(allowed_hosts_of(["https://a.example.com:8443/x", ".example.org", "*"], "box, nas.lan "),
["a.example.com", ".example.org", "*", "box", "nas.lan"])
for bad in (["bad name"], 5, [3], "http://"):
with self.assertRaises(ValueError):
allowed_hosts_of(bad)
def test_names_from_the_bind_address(self):
with mock.patch("serve.server.lan_addresses", return_value=["192.168.1.20"]):
self.assertEqual(host_names_for("127.0.0.1"), LOCAL) # this PC only: nothing else
self.assertEqual(host_names_for("localhost"), LOCAL)
names = host_names_for("0.0.0.0") # other devices too
self.assertIn(socket.gethostname().lower(), names)
self.assertIn(socket.gethostname().lower() + ".local", names)
self.assertIn("192.168.1.20", names)
self.assertIn("10.0.0.7", host_names_for("10.0.0.7"))
names = host_names_for("127.0.0.1", ["strata.example.com", "*"], ["https://chat.example.net"])
self.assertTrue({"strata.example.com", "chat.example.net"} <= names)
self.assertNotIn("*", names)
class HostCheck(unittest.TestCase):
def test_accepted(self):
for host in ("localhost:8095", "LOCALHOST", "127.0.0.1:1", "[::1]:8095", "192.168.1.20:8095", "[fe80::1]",
"app.localhost:8095", None, "", "box:8095", "a.example.org", "example.org:443"):
self.assertTrue(host_allowed(host, LOCAL | {"box", ".example.org"}), host)
def test_refused(self):
# a rebinding page sends its own name; lookalikes of allowed names stay out
for host in ("evil.example.com", "evil.example.com:8095", "localhost.evil.com", "127.0.0.1.nip.io",
"box.evil.com", "xexample.org", "bad host", "a:b:c:d:e:f:g:h:i"):
self.assertFalse(host_allowed(host, LOCAL | {"box", ".example.org"}), host)
def test_any_host(self):
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."""
def setUp(self):
tok = ByteTokenizer()
self.svc = Service(MockEngine(tok, "</think>\n\nok", max_context=4096), tok,
ChatTemplate(ROOT / "serve/chat_template.jinja"))
self.httpd = None
def start(self, **attrs):
for k, v in attrs.items():
setattr(self.svc, k, v)
self.httpd = serve(self.svc, port=0)
self.port = self.httpd.server_address[1]
def tearDown(self):
if self.httpd:
self.httpd.shutdown()
self.httpd.server_close()
def req(self, method, path, body=None, headers=None, host=None):
"""(status, JSON, what the server printed); `host` replaces the Host header http.client sends."""
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=30)
h = dict(headers or {})
if host is not None:
h["Host"] = host
data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode()
out = io.StringIO()
try:
with contextlib.redirect_stdout(out):
c.request(method, path, body=data, headers=h)
r = c.getresponse()
raw = r.read()
return r.status, json.loads(raw) if raw[:1] in (b"{", b"[") else raw, out.getvalue()
finally:
c.close()
def chat_body(self):
return {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 64}
# --- Host
def test_rebinding_name_is_refused_everywhere(self):
self.start()
for method, path in (("GET", "/status"), ("GET", "/metrics"), ("GET", "/"), ("GET", "/health"),
("POST", "/settings"), ("POST", "/v1/chat/completions"), ("OPTIONS", "/v1/models")):
code, body, log = self.req(method, path, {} if method == "POST" else None,
{"Content-Type": "application/json"}, host=f"evil.example.com:{self.port}")
self.assertEqual(code, 403, path)
if method != "OPTIONS":
self.assertIn("allowed_hosts", body["error"]["message"])
self.assertEqual(log.count("\n"), 1, path) # one log line each
self.assertIn("evil.example.com", log)
def test_local_names_and_ips_pass(self):
self.start()
for host in (f"127.0.0.1:{self.port}", f"localhost:{self.port}", f"[::1]:{self.port}",
f"192.168.1.20:{self.port}"):
self.assertEqual(self.req("GET", "/status", host=host)[0], 200, host)
def test_no_host_header_passes(self):
self.start()
with socket.create_connection(("127.0.0.1", self.port), timeout=10) as s: # an HTTP/1.0 client
s.sendall(b"GET /health HTTP/1.0\r\n\r\n")
raw = b""
while chunk := s.recv(65536):
raw += chunk
self.assertTrue(raw.startswith(b"HTTP/1.0 200"), raw[:40])
def test_allowed_hosts_and_wildcard(self):
self.start(allowed_hosts=["strata.example.com", ".home.arpa"])
self.assertEqual(self.req("GET", "/status", host="strata.example.com")[0], 200)
self.assertEqual(self.req("GET", "/status", host="nas.home.arpa:8095")[0], 200)
self.assertEqual(self.req("GET", "/status", host="evil.example.com")[0], 403)
self.svc.allowed_hosts = ["*"]
self.assertEqual(self.req("GET", "/status", host="evil.example.com")[0], 200)
def test_refusal_names_both_ways_out(self):
self.start()
message = self.req("GET", "/status", host="evil.example.com")[1]["error"]["message"]
self.assertIn("allowed_hosts", message)
self.assertIn("api_key", message)
def test_with_a_key_the_host_check_is_off(self):
# a rebinding page cannot authenticate; tunnels and proxies that pass their own name on keep working
self.start(api_key="s3cret")
tunnel = "random-words.trycloudflare.com"
self.assertEqual(self.req("GET", "/status", host=tunnel)[0], 401)
self.assertEqual(self.req("GET", "/status", headers={"Authorization": "Bearer s3cret"}, host=tunnel)[0], 200)
self.assertEqual(self.req("GET", "/health", host=tunnel)[0], 200)
code, _, log = self.req("POST", "/v1/chat/completions", self.chat_body(),
{"Content-Type": "application/json", "Authorization": "Bearer s3cret"}, host=tunnel)
self.assertEqual(code, 200)
self.assertNotIn("refused", log)
def test_a_trusted_origin_s_host_is_allowed(self):
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()
+1 -1
View File
@@ -680,7 +680,7 @@ class ClientHangUp(unittest.TestCase):
body = json.dumps({"model": "x", "max_tokens": 20, "stream": stream,
"messages": [{"role": "user", "content": "a long prompt"}]}).encode()
c = so.create_connection(("127.0.0.1", self.port))
c.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n"
c.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Type: application/json\r\n"
b"Content-Length: " + str(len(body)).encode() + b"\r\n\r\n" + body)
time.sleep(1.0)
c.close()