mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
proxy, cockpit: what an independent review found in this version, each with its test
A key header of 64 KB of "\n" was read in 8.7 s under the interpreter's lock, with no key, every stream of the box still: it is refused at once. The red banner of a start that barely moves is no longer drawn again at each reading, its Stop with it. The words of a box with no lane name what starts one, and a start's length by lane. llama-server's own /chat/completions gets a chat keepalive. The relay's sign-in page names where this browser reaches the cockpit, through a tunnel or TLS. A body the cockpit does not read is never its connection's next request. A chunked body shows its size in Traffic. The other box of a pair is told before a silent stream is cut, and binds nothing for it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d1c153b8c6
commit
4e22e96e44
12 files changed
+133
-9
No files matched your search
@@ -178,6 +178,11 @@ at, on the same host name; the same origins, and no other port of that host, may
|
||||
the relay. The page asks it without the session first, so that the session goes to no
|
||||
other program on that port.
|
||||
|
||||
A browser keeps a cookie for a host name, not for a port. Reached through a tunnel as
|
||||
`localhost`, the cockpit's session cookie is also sent to any other server that browser
|
||||
opens on `localhost` of that computer: sign out when the tunnel is done on a computer
|
||||
where others run programs, or reach the box by its tailnet name.
|
||||
|
||||
**The pair port (`keepalive-proxy.py`, :30002, only while the box is paired)**
|
||||
is the proxy itself, for the other box of a pair (`pair.py`, docs/pair.md). It
|
||||
speaks TLS 1.3 only and demands a client certificate: the chain must end at a
|
||||
|
||||
@@ -557,7 +557,12 @@ def make_handler(cfg: RelayConfig) -> type[http.server.BaseHTTPRequestHandler]:
|
||||
self.close_connection = True
|
||||
wants_page = self.command == "GET" and "text/html" in (self.headers.get("Accept") or "")
|
||||
if wants_page and code == 401:
|
||||
cockpit = f"http://{host_name(self.headers.get('Host')) or '127.0.0.1'}:{cfg.cockpit_port}/"
|
||||
# where this browser was last answered by the cockpit on this name (a tunnel or a proxy shows it on another
|
||||
# port, or over TLS), else its own port
|
||||
name = (host_name(self.headers.get("Host")) or "127.0.0.1").lower()
|
||||
at = next((a for a in reversed(cfg.seen_at()) if host_name(a) == name), f"{name}:{cfg.cockpit_port}")
|
||||
tls = (self.headers.get("X-Forwarded-Proto") or "").strip().lower() == "https"
|
||||
cockpit = f"http{'s' if tls else ''}://{at}/"
|
||||
payload = SIGN_IN_PAGE.format(cockpit=cockpit).encode()
|
||||
ctype = "text/html; charset=utf-8"
|
||||
else:
|
||||
|
||||
@@ -8933,6 +8933,8 @@ class Handler(http.server.BaseHTTPRequestHandler):
|
||||
|
||||
# ---- routes ----
|
||||
def do_GET(self):
|
||||
if (self.headers.get("Content-Length") or "0").strip() != "0" or self.headers.get("Transfer-Encoding"):
|
||||
self.close_connection = True # a body nothing here reads: never this connection's next request
|
||||
path, _, query = self.path.partition("?")
|
||||
fresh = "refresh=1" in query
|
||||
if path == "/api/health":
|
||||
@@ -9086,6 +9088,10 @@ class Handler(http.server.BaseHTTPRequestHandler):
|
||||
# reference box, 2026-09-24), and running out of unified memory is a power
|
||||
# cycle on this machine. A value int() refused killed the handler thread with
|
||||
# no answer at all.
|
||||
if self.headers.get("Transfer-Encoding"):
|
||||
self.close_connection = True
|
||||
self.send_json({"error": "a body is sent with its Content-Length here"}, 411)
|
||||
return self._linger()
|
||||
declared = (self.headers.get("Content-Length") or "0").strip()
|
||||
if not (declared.isascii() and declared.isdigit()):
|
||||
self.close_connection = True
|
||||
|
||||
@@ -751,7 +751,7 @@ const EXPLAIN = {
|
||||
if (p.verb === 'restart') return `systemd restarts ${lane}; it answers again in ${readyIn(p.unit)}.`;
|
||||
return `systemd starts ${lane}: it loads its weights and answers in ${readyIn(p.unit)}. Follow the boot in the dock and on the Now view.`;
|
||||
},
|
||||
boot_off: p => `systemd no longer starts ${LANE_NAME[p.unit]} with the box. It stays as it is now, serving or stopped, and after the next boot no lane serves until one is loaded, here or with switch-model.sh.`,
|
||||
boot_off: p => `systemd no longer starts ${LANE_NAME[p.unit]} with the box. It stays as it is now, serving or stopped, and after the next boot no lane serves until one is loaded here, or started on the box.`,
|
||||
switch: p => (TARGET_NOTE[p.target] ? TARGET_NOTE[p.target] + '\n\n' : '') +
|
||||
`switch-model.sh verifies the checkpoint, makes this lane the one enabled at boot and ${TARGET_UNIT(p.target) === VIDEO_UNIT || TARGET_UNIT(p.target) === IMAGE_H3_UNIT ? 'changes nothing else'
|
||||
: TARGET_UNIT(p.target) === TRANSCRIBE_UNIT ? 'fetches what its GGUF files lack and puts in its unit for them: the proxy and opencode, text clients, stay as they are'
|
||||
@@ -1569,11 +1569,13 @@ function renderBanners(state, errors){
|
||||
`The container ${o.container} serves, but its unit is not running, so no other engine may start and a reboot will not bring it back. Start it from Lanes to replace it, or remove it:`, `docker rm -f ${o.container}`));
|
||||
if (errors.lifecycle) add('warn', 'Engine state unknown.', 'The lifecycle collector failed: ' + String(errors.lifecycle).slice(0, 120));
|
||||
// drawn only when it changed: a live region re-read twice a second is noise
|
||||
const sig = JSON.stringify(want.map(w => [w[0], w[1], !!w[3], w[4] || null, (w[5] || []).map(a => a[0])]));
|
||||
// (and of a list, how many: its words hold watts and MHz, and a button drawn again at each reading is one nobody presses)
|
||||
const sig = JSON.stringify(want.map(w => [w[0], w[1], !!w[3], (w[4] || []).length, (w[5] || []).map(a => a[0])]));
|
||||
if (box.dataset.sig === sig){
|
||||
[...box.children].forEach((b, i) => {
|
||||
const t = b.querySelector('.t'); if (t) setText(t, want[i][2]);
|
||||
const c = b.querySelector('.bcmd .cmd'); if (c) setText(c, want[i][3]);
|
||||
b.querySelectorAll('.blist li').forEach((li, k) => setText(li, want[i][4][k]));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import importlib.util
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
@@ -190,6 +191,15 @@ class WhoTheRelayIs(unittest.TestCase):
|
||||
h = {k: v for k, v in (("Origin", origin), ("Cookie", cookie)) if v}
|
||||
return get(self.port, path, h, **kw)
|
||||
|
||||
def test_its_sign_in_page_names_where_this_browser_reaches_the_cockpit(self):
|
||||
def link(host, **more):
|
||||
return re.search(rb'<a href="([^"]+)"', get(self.port, "/x", {"Host": host, "Accept": "text/html", **more})[2])[1].decode()
|
||||
self.assertEqual(link(f"localhost:{self.port}"), "http://localhost:30090/")
|
||||
self.at[:] = ["localhost:31090", "box.ts.net"] # through a tunnel, and behind tailscale serve
|
||||
self.assertEqual(link(f"localhost:{self.port}"), "http://localhost:31090/")
|
||||
self.assertEqual(link("box.ts.net:30091", **{"X-Forwarded-Proto": "https"}), "https://box.ts.net/")
|
||||
self.assertEqual(link("other.lan:30091"), "http://other.lan:30090/")
|
||||
|
||||
def test_it_names_itself_and_says_whether_the_session_reached_it(self):
|
||||
st, hd, body = self.ask()
|
||||
self.assertEqual((st, json.loads(body)), (200, {"relay": "this-one", "session": False}))
|
||||
|
||||
@@ -50,6 +50,22 @@ class AStartSaysWhereItIs(unittest.TestCase):
|
||||
for txt in r:
|
||||
self.assertNotRegex(txt, r"about 0 s left|about -|NaN|undefined|null")
|
||||
|
||||
def test_its_buttons_stay_while_its_facts_change(self):
|
||||
"""The list of causes holds watts and MHz: the banner was drawn again at each reading, and its Stop with it, focus and
|
||||
all, in the one case it is for (found in review, 2026-11-30)."""
|
||||
r = run(self, r"""
|
||||
box(start('loading-weights', 453, STILL));
|
||||
const stop = () => [...$('banners').querySelectorAll('button')].find(b => /Stop/.test(b.textContent));
|
||||
const first = stop(), was = txt('banners');
|
||||
const next = JSON.parse(JSON.stringify(STILL)); next.causes[0] = next.causes[0].replace('942', '937').replace('5 W', '6 W');
|
||||
box(start('loading-weights', 456, next));
|
||||
report({same: first === stop(), there: !!first, was, now: txt('banners')});""")
|
||||
self.assertTrue(r["there"])
|
||||
self.assertTrue(r["same"], "the same button")
|
||||
self.assertIn("942 MHz", r["was"])
|
||||
self.assertIn("937 MHz", r["now"])
|
||||
self.assertNotIn("942 MHz", r["now"])
|
||||
|
||||
def test_before_its_usual_time_it_says_what_is_left_and_of_how_many_starts(self):
|
||||
r = run(self, "box(start('loading-weights', 60, W())); report(said());")
|
||||
for place in ("card", "bay", "capsule", "act"):
|
||||
|
||||
@@ -279,6 +279,37 @@ class InputsThatEndedTheHandler(Base):
|
||||
self.assertTrue(head.startswith(b"HTTP/1.1 403"), head[:60])
|
||||
self.assertEqual(sum(len(v) for v in self.cp.LOGIN_FAILS.values()), 1, "the attempt was not counted")
|
||||
|
||||
def test_a_body_nothing_reads_is_never_the_next_request(self):
|
||||
"""A GET's body was read as a request of its own by the same connection, with a proxy in front (found in review,
|
||||
2026-11-30)."""
|
||||
port = self.serve(self.cp.Server, self.cp.Handler)
|
||||
hidden = b"GET /api/health HTTP/1.1\r\nHost: x\r\n\r\n"
|
||||
for head in (b"GET /api/health HTTP/1.1\r\nHost: x\r\nContent-Length: %d\r\n\r\n" % len(hidden),
|
||||
b"GET /api/health HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n",
|
||||
b"POST /api/login HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n"):
|
||||
s = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||
self.addCleanup(s.close)
|
||||
s.sendall(head + hidden)
|
||||
got = b""
|
||||
while True:
|
||||
try:
|
||||
c = s.recv(4096)
|
||||
except ConnectionResetError:
|
||||
break
|
||||
if not c:
|
||||
break
|
||||
got += c
|
||||
self.assertEqual(got.count(b"HTTP/1.1 "), 1, head[:40])
|
||||
if head.startswith(b"POST"):
|
||||
self.assertIn(b" 411 ", got[:20])
|
||||
# and a plain GET keeps its connection
|
||||
s = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||
self.addCleanup(s.close)
|
||||
for _ in range(2):
|
||||
s.sendall(hidden)
|
||||
got = s.recv(4096)
|
||||
self.assertTrue(got.startswith(b"HTTP/1.1 200"), got[:40])
|
||||
|
||||
def test_a_nul_in_a_static_path_is_a_404(self):
|
||||
port = self.serve(self.cp.Server, self.cp.Handler)
|
||||
head = self.raw(port, b"GET /static/app\x00.js HTTP/1.1\r\nHost: x\r\n\r\n")
|
||||
|
||||
+24
-6
@@ -832,13 +832,13 @@ def engine_gone():
|
||||
units = _HOLD_SEEN["units"] if HOLD_UNITS else None
|
||||
if units:
|
||||
return (f"{', '.join(units)} is starting, loading or restarting, which takes minutes "
|
||||
"(about 9 at most on a DGX Spark)"), "30"
|
||||
"(under one to 17 on a DGX Spark, by the lane)"), "30"
|
||||
if units is not None:
|
||||
# v6.63: no lane at all, and it read "stopped, restarting or still loading", with a Retry-After
|
||||
# for what comes back by nobody's doing but the operator's: opencode wrote it again every 30 s
|
||||
# (2.3.2), and the OpenAI SDK waited 60 s before it showed it (3.60.0, 2026-11-30)
|
||||
return ("No lane serves on this box: start one in the cockpit, Lanes, or with ./switch-model.sh and "
|
||||
"the lane's name"), None
|
||||
return ("No lane serves on this box: start one in the cockpit, Lanes, or on the box with sudo systemctl "
|
||||
"start and the lane's unit (qwen38-sglang for the 27B)"), None
|
||||
return "It is stopped, restarting or still loading (a restart takes minutes, about 9 on a DGX Spark)", "30"
|
||||
|
||||
|
||||
@@ -1426,7 +1426,12 @@ def key_refusal(headers, key):
|
||||
return ("this port needs the box's API key, and the request carries none. Send it as Authorization: "
|
||||
f"Bearer <key>, or as x-api-key: <key>. {KEY_WHERE}")
|
||||
bare = value[6:] if value[:6].lower() == "bearer" else value
|
||||
bare = re.sub(r"(?:\\[nrt])+$", "", bare.strip(" \t\"'`<>")).strip(" \t\"'`<>")
|
||||
# no longer than the key in what a person wraps it in: the pattern's cost is the square of what it reads, and a header
|
||||
# goes to 64 KiB (8.7 s with the interpreter's lock held, every stream still, found in review, 2026-11-30)
|
||||
if len(bare) <= len(key) + 64:
|
||||
bare = re.sub(r"(?:\\[nrt])+$", "", bare.strip(" \t\"'`<>")).strip(" \t\"'`<>")
|
||||
else:
|
||||
bare = ""
|
||||
if hmac.compare_digest(bare.encode("utf-8", "replace"), key.encode("utf-8", "replace")):
|
||||
return ("the key is this box's, but the header around it is not. Send exactly Authorization: Bearer <key>: "
|
||||
"one space, no quotes, nothing after it")
|
||||
@@ -6005,7 +6010,7 @@ def sse_error_openai(msg, kind="corrupted_output", code=None):
|
||||
KA_ANTHROPIC = b'event: ping\ndata: {"type": "ping"}\n\n'
|
||||
KA_COMMENT = b": keepalive\n\n"
|
||||
KA_RESPONSES = b'event: keepalive\ndata: {"type":"keepalive"}\n\n'
|
||||
KA_CHAT_ROUTES = ("/v1/chat/completions", "/invocations")
|
||||
KA_CHAT_ROUTES = ("/v1/chat/completions", "/chat/completions", "/invocations") # the second, llama-server's own
|
||||
|
||||
|
||||
def ka_openai(model="keepalive", text=False):
|
||||
@@ -6797,6 +6802,7 @@ class H(BaseHTTPRequestHandler):
|
||||
if anthropic:
|
||||
self._finish()
|
||||
return
|
||||
self._say_ended_by_order() # to the other box of a pair, which reads a bare cut as its engine's death
|
||||
self.close_connection = True
|
||||
try: self.connection.shutdown(socket.SHUT_RDWR)
|
||||
except Exception: pass
|
||||
@@ -6817,10 +6823,17 @@ class H(BaseHTTPRequestHandler):
|
||||
except Exception: pass
|
||||
|
||||
# ---- relay -------------------------------------------------------------
|
||||
def _say_arrow(self, n):
|
||||
"""The journal's line of a request that came, once: the cockpit's Traffic reads its size there."""
|
||||
arrow, self._arrow = getattr(self, "_arrow", None), None
|
||||
if arrow:
|
||||
log(f"{arrow}{n}b")
|
||||
|
||||
def _done(self, outcome, quiet=False):
|
||||
"""The request's outcome, and its journal line unless quiet: the tile's reads every 5 s, written on both
|
||||
boxes, pushed a paired box's real requests out of the 800 lines the cockpit reads in about 34 minutes
|
||||
(found in review, 2026-11-03)."""
|
||||
self._say_arrow(0)
|
||||
self._ended = True
|
||||
_gen_discard(self)
|
||||
with _GEN_LOCK:
|
||||
@@ -7944,7 +7957,9 @@ class H(BaseHTTPRequestHandler):
|
||||
"outside printable ASCII, and is refused"}}).encode())
|
||||
self._done("400 suspect path"); return
|
||||
self._label_peer()
|
||||
log(f"{self._peer} -> {self.command} {self.path.split('?')[0]} body={n0}b")
|
||||
self._arrow = f"{self._peer} -> {self.command} {self.path.split('?')[0]} body="
|
||||
if not with_body or self.headers.get("Transfer-Encoding") is None:
|
||||
self._say_arrow(n0) # one in chunks says its size once it is read
|
||||
# v6.47: a stop is this request's own, on a connection that serves several too
|
||||
self._stop_why = None; self._stop_floor = True; self._relay_q = None
|
||||
self._relaying_whole = False # set once a non-streamed answer is relayed whole (stop_generations)
|
||||
@@ -8007,6 +8022,7 @@ class H(BaseHTTPRequestHandler):
|
||||
try:
|
||||
body = self._read_chunked(cap) if chunked else self._read_body(n)
|
||||
except _BadBody as e:
|
||||
self._say_arrow(0)
|
||||
status, why = e.args
|
||||
if not status:
|
||||
log(f"{self._peer} the caller left before its chunked body arrived whole")
|
||||
@@ -8029,6 +8045,7 @@ class H(BaseHTTPRequestHandler):
|
||||
self._over_budget(n or getattr(self, "_body_reserved", 0)); return
|
||||
if chunked:
|
||||
n = len(body)
|
||||
self._say_arrow(n)
|
||||
self._body_read = True
|
||||
if body is not None and len(body) < n:
|
||||
# The caller closed before its body arrived whole: what came is no request, and
|
||||
@@ -9811,6 +9828,7 @@ class H(BaseHTTPRequestHandler):
|
||||
status, why = 501, f"Transfer-Encoding {te[:40]!r} is not read here: send the body chunked, or with a Content-Length"
|
||||
else:
|
||||
return False
|
||||
self._say_arrow(0)
|
||||
log(f"{self._peer} REFUSED a body framed as {te[:40]!r}: {why}")
|
||||
self._plain(status, {"Content-Type": "application/json"},
|
||||
json.dumps({"error": {"type": "invalid_request", "message": f"keepalive-proxy: {why}"}}).encode())
|
||||
|
||||
@@ -122,6 +122,9 @@ class AChunkedBodyReachesTheEngineWhole(Base):
|
||||
|
||||
def test_one_chunk(self):
|
||||
self.reaches(self.chunks(RAW))
|
||||
self.assertEqual(sum(f"-> POST /v1/chat/completions body={len(RAW)}b" in ln for ln in self.journal), 1,
|
||||
"the cockpit's Traffic reads its size there")
|
||||
self.assertEqual(sum("-> POST" in ln for ln in self.journal), 1)
|
||||
|
||||
def test_many_chunks_cut_anywhere(self):
|
||||
self.reaches(self.chunks(*[RAW[i:i + 1] for i in range(len(RAW))]))
|
||||
@@ -207,6 +210,7 @@ class ABodyFramedWrongIsRefused(Base):
|
||||
self.assertIn(status, (0, 400))
|
||||
self.assertEqual(Engine.seen, [])
|
||||
self.assertTrue([ln for ln in self.journal if "CLIENT GONE before its body" in ln or "REFUSED" in ln], self.journal)
|
||||
self.assertEqual(sum("-> POST" in ln for ln in self.journal), 1, self.journal)
|
||||
|
||||
def test_the_key_is_asked_before_a_chunk_is_read(self):
|
||||
for key in (None, "another"):
|
||||
|
||||
@@ -112,6 +112,7 @@ class NoLane(Base):
|
||||
def test_none_serves_and_none_comes(self):
|
||||
msg, retry = self.reading(("inactive", "failed"))
|
||||
self.assertIn("No lane serves on this box: start one in the cockpit, Lanes", msg)
|
||||
self.assertNotIn("switch-model.sh", msg, "which starts nothing")
|
||||
self.assertIsNone(retry, "no wait brings it back")
|
||||
|
||||
def test_one_is_on_its_way(self):
|
||||
|
||||
@@ -293,6 +293,20 @@ class EachRouteHasItsOwnKeepalive(Base):
|
||||
first = next(i for i, r in enumerate(recs) if b"hello" in r)
|
||||
self.assertEqual(set(recs[:first]), {b'event: keepalive\ndata: {"type":"keepalive"}\n\n'}, agent)
|
||||
|
||||
def test_llama_servers_own_chat_route_gets_a_chat_chunk(self):
|
||||
self.assertEqual(self.mod.keepalive_for("/chat/completions", "m"), self.mod.ka_openai("m"))
|
||||
|
||||
def test_the_other_box_of_a_pair_is_told_before_the_cut_of_a_silent_stream(self):
|
||||
"""A bare cut reads there as the death of this box's engine, and bound the request for 10 minutes."""
|
||||
said = []
|
||||
h = self.mod.H.__new__(self.mod.H)
|
||||
h.path = "/v1/chat/completions"
|
||||
h._chunk = lambda b: said.append("error" if b"upstream_silent" in b else b)
|
||||
h._say_ended_by_order = lambda: said.append("ended")
|
||||
h.connection = type("C", (), {"shutdown": lambda self, how: said.append("cut")})()
|
||||
h._end_silent(3600)
|
||||
self.assertEqual(said, ["error", "ended", "cut"])
|
||||
|
||||
def test_a_route_with_a_shape_of_its_own_gets_comments(self):
|
||||
recs = self.sse_records(self.ask(self.SILENT, path="/generate", stream=True))
|
||||
self.assertIn(b": keepalive\n\n", recs)
|
||||
|
||||
@@ -166,6 +166,18 @@ class ARefusalSaysWhatToSend(Base):
|
||||
self.assertEqual(Engine.seen, [])
|
||||
return json.loads(body)
|
||||
|
||||
def test_a_long_value_is_refused_at_once(self):
|
||||
"""Its reading cost the square of its length under the interpreter's lock: 64 KB of "\\n" sent with no key held
|
||||
every stream of the box for 8.7 s (found in review, 2026-11-30)."""
|
||||
for value in ("Bearer " + "\\n" * 30_000 + "x", "Bearer " + "\\n" * 30_000, "'" * 60_000, "Bearer " + " " * 60_000 + "x"):
|
||||
for name in ("Authorization", "x-api-key"):
|
||||
t0 = time.monotonic()
|
||||
why = self.mod.key_refusal({name: value}, KEY)
|
||||
self.assertLess(time.monotonic() - t0, 0.2, value[:20])
|
||||
self.assertNotIn(KEY, why)
|
||||
# what a person wraps it in is still read
|
||||
self.assertIn("the key is this box's", self.mod.key_refusal({"Authorization": f'Bearer "{KEY}"\\n'}, KEY))
|
||||
|
||||
def test_no_key(self):
|
||||
msg = self.refusal()["error"]["message"]
|
||||
for words in ("carries none", "Authorization: Bearer <key>", "x-api-key", "~/.config/qwen38/api-key"):
|
||||
|
||||
Reference in new issue
Block a user