diff --git a/dashboard/agent_relay.py b/dashboard/agent_relay.py index 932e7c10..33b12182 100644 --- a/dashboard/agent_relay.py +++ b/dashboard/agent_relay.py @@ -948,6 +948,7 @@ def listen_on(configured: str) -> list[str]: one, for http://[::1]: before the others, as the last one is the address it was given.""" given = [LOOPBACK if a == "localhost" else a for a in (x.strip() for x in configured.split(",")) if a] or [""] every = [a for a in given if a in EVERY_INTERFACE] + given = [a for a in given if a != LOOPBACK6] return ([LOOPBACK6] if address_here(LOOPBACK6) else []) + (every[:1] or list(dict.fromkeys([LOOPBACK, *given]))) diff --git a/dashboard/cockpit.py b/dashboard/cockpit.py index 38df8f45..1d216b9b 100644 --- a/dashboard/cockpit.py +++ b/dashboard/cockpit.py @@ -4786,9 +4786,9 @@ def engine_table() -> dict: def proxy_unit_env() -> tuple[str, dict, bool]: - """The proxy's unit as systemd runs it: what it shows, the three names the cockpit reads of its environment (the - interface, the certificate, the file of client keys: nothing else of it leaves this function, which holds keys), and - whether a file it takes its environment from could not be read.""" + """The proxy's unit as systemd runs it: what it shows, which holds its keys and is for this process alone, the three names + the cockpit reads of its environment (the interface, the certificate, the file of client keys), and whether a file it + takes its environment from could not be read.""" show = run(["systemctl", "show", "qwen38-keepalive.service", "-p", "ExecStart", "-p", "Environment", "-p", "EnvironmentFiles"], timeout=5) or "" names = r"(? str: except (OSError, ValueError) as e: raise NoClientKey(f"{knows}, and the cockpit cannot read them ({type(e).__name__})") from None mine = next((k for k, label in (keys.items() if isinstance(keys, dict) else ()) - if isinstance(label, str) and label.strip().lower() == "cockpit" and k.strip()), None) + if isinstance(label, str) and label.strip().lower() == "cockpit" and re.fullmatch(r"[!-~]+", k)), None) if mine is None: raise NoClientKey(f'{knows}, and none of them is the cockpit\'s: add one to it, labelled "cockpit" ' '({"": "cockpit"}), then sudo systemctl restart qwen38-keepalive') @@ -9102,13 +9102,43 @@ class Handler(http.server.BaseHTTPRequestHandler): return json.dumps({"here": here, **STATE}) # ---- routes ---- + def from_another_site(self) -> bool: + """Whether a browser says this request comes from another site's page: one open in the same browser locked the + cockpit's own login out for a minute with five tries of its own, again and again (2026-12-01). Sec-Fetch-Site says + it, which no page can write; a browser sends none over plain HTTP to another address than its own loopback, where + its Origin has to be the host it asked (review of v1.60.0). No client but a browser sends either.""" + site = self.headers.get("Sec-Fetch-Site") + if site is not None: + return site == "cross-site" + return not ar.origin_allowed(self.headers.get("Origin"), self.headers.get("Host")) + + def sent_on_to_localhost(self, path: str) -> bool: + """A page asked at http://[::1] is the same cockpit's at localhost: a content policy has no name for an IPv6 address, + so nothing of the Agent view opens under it.""" + host = (self.headers.get("Host") or "").lower() + if not host.startswith("[::1]") or path not in ("/", "/login"): + return False + self.send_response(302) + self.send_header("Location", f"http://localhost{host[5:]}{path}") + self.send_header("Content-Length", "0") + self.end_headers() + return True + 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": - return self.send_json({"ok": True, "version": VERSION}) + out = {"ok": True, "version": VERSION} + asked = self.headers.get("X-Alzeo-Prove") or "" + if self.client_address[0] in (ar.LOOPBACK, ar.LOOPBACK6) and re.fullmatch(r"[0-9a-f]{32}", asked): + # to this box's proxy, which sends this box's key to its cockpit alone: a tunnel to another box's may hold + # the port (review of v1.60.0) + out["proof"] = hmac.new(api_key().encode(), b"alzeo cockpit " + asked.encode(), "sha256").hexdigest() + return self.send_json(out) + if self.sent_on_to_localhost(path): + return None if path == "/login" or path == "/favicon.ico" or path.startswith("/static/"): return self.serve_static(path) if not self.authed(): @@ -9290,12 +9320,10 @@ class Handler(http.server.BaseHTTPRequestHandler): self.close_connection = True self.send_json({"error": "auth"}, 401) return self._linger() - if path == "/api/login" and self.headers.get("Sec-Fetch-Site") == "cross-site": - # a page of another site open in the same browser: its five tries locked the cockpit's own login out for a - # minute, again and again (2026-12-01). The browser says it itself, and a page cannot: no client but a browser - # sends it. + if path == "/api/login" and self.from_another_site(): self.close_connection = True - self.send_json({"error": "a login from another site's page is refused"}, 403) + self.send_json({"error": "a login from another site's page is refused (a proxy in front has to pass the Host header " + "as it came)"}, 403) return self._linger() raw = self.rfile.read(length) if length else b"" if path == "/api/login": diff --git a/dashboard/static/js/agent.js b/dashboard/static/js/agent.js index 3e68fbaa..90a73a8d 100644 --- a/dashboard/static/js/agent.js +++ b/dashboard/static/js/agent.js @@ -131,7 +131,7 @@ function agentWhy(){ if (hears(local)) return [`The agent's relay listens on ${local}:${R}, and this browser gets no answer from it: a firewall, or an access rule of the tailnet, lets port ${P} through and not ${R}.`, [{say: `Let TCP port ${R} through as ${P} is. With ufw, on the box:`, cmd: `sudo ufw allow ${R}/tcp`}, over(host), screen]]; const onBox = here.peer === here.local; - return [`The agent runs commands on the box, so its relay answers only on ${agentAnd(up.filter(a => a !== '::1'))}, and you opened the cockpit at ${host === local ? host : `${host} (${local})`}. docs/cockpit.md says how to give it another address.`, + return [`The agent runs commands on the box, so its relay answers only on ${agentAnd(up.some(a => a !== '::1') ? up.filter(a => a !== '::1') : up)}, and you opened the cockpit at ${host === local ? host : `${host} (${local})`}. docs/cockpit.md says how to give it another address.`, [...(onBox ? [{say: 'You are on the box itself. Here, by localhost:', href: url('localhost')}] : []), ...nets, ...(onBox ? [] : [over(host), screen])]]; } function mountAgent(){ diff --git a/dashboard/static/js/base.js b/dashboard/static/js/base.js index c689487b..73e9dc5a 100644 --- a/dashboard/static/js/base.js +++ b/dashboard/static/js/base.js @@ -1627,7 +1627,7 @@ function renderBanners(state, errors){ else if (ocf && !ocf.ok) add('warn', 'opencode asks for more than this engine can hold.', `${ocf.why}: opencode declares ${fmtN(ocf.asked)} tokens, and ${ocf.served} can serve ${fmtN(ocf.limit)}. A session would break when the proxy refuses the prompt. Settings has "Fit the limits to this engine".`); // An address the cockpit was given and this box does not have (Tailscale down, or its address changed since the // install): the page opens here, and nobody reaches it from there, which nothing said. - const deaf = ((F.here || {}).listeners || []).find(l => !l.listening && l.addr !== '127.0.0.1'); + const deaf = ((F.here || {}).listeners || []).find(l => !l.listening && l.addr !== '127.0.0.1' && l.addr !== '::1'); if (deaf) add('warn', `The cockpit does not answer on ${deaf.addr}.`, `${cap1(deaf.error || '')}. It tries again by itself. If that address changed for good, give the cockpit the new one, on the box:`, `cd ${(F.config || {}).repo_dir || '~/dgx-spark-qwen38'} && DASH_BIND="$(${isTailnet(deaf.addr) ? 'tailscale ip -4 | head -1' : "hostname -I | awk '{print $1}'"})" dashboard/install-dashboard.sh`); diff --git a/dashboard/tests/test_agent_door_page.py b/dashboard/tests/test_agent_door_page.py index 4d98a4b0..b03f8339 100644 --- a/dashboard/tests/test_agent_door_page.py +++ b/dashboard/tests/test_agent_door_page.py @@ -278,7 +278,7 @@ class TheCockpitsOwnAddress(unittest.TestCase): self.assertIn(f'cd /opt/alzeo && DASH_BIND="$({how})" dashboard/install-dashboard.sh', r) def test_none_when_it_answers_or_when_the_loopback_alone_is_taken(self): - for rows in ("[L('127.0.0.1'), L('100.64.0.7')]", "[L('127.0.0.1', 'taken'), L('100.64.0.7')]", "[]"): + for rows in ("[L('127.0.0.1'), L('100.64.0.7')]", "[L('127.0.0.1', 'taken'), L('100.64.0.7')]", "[L('::1', 'taken'), L('127.0.0.1'), L('100.64.0.7')]", "[]"): with self.subTest(rows=rows): r = run(self, "feed({config: {periods: {}}, here: HERE('127.0.0.1', '127.0.0.1', {listeners: %s})}); report($('banners').textContent);" % rows) self.assertNotIn("does not answer on", r) diff --git a/dashboard/tests/test_agent_everywhere.py b/dashboard/tests/test_agent_everywhere.py index 97a99fd0..1c86b20c 100644 --- a/dashboard/tests/test_agent_everywhere.py +++ b/dashboard/tests/test_agent_everywhere.py @@ -86,7 +86,7 @@ class OneListenerPerAddress(unittest.TestCase): ("tailscale,192.168.1.10", ["127.0.0.1", "tailscale", "192.168.1.10"]), ("tailscale, 192.168.1.10,tailscale", ["127.0.0.1", "tailscale", "192.168.1.10"]), ("127.0.0.1,192.168.1.10", ["127.0.0.1", "192.168.1.10"]), ("localhost,tailscale", ["127.0.0.1", "tailscale"]), - ("192.168.1.10,0.0.0.0", ["0.0.0.0"]), + ("192.168.1.10,0.0.0.0", ["0.0.0.0"]), ("::1", ["127.0.0.1"]), ("::1,192.168.1.10", ["127.0.0.1", "192.168.1.10"]), # nothing between two commas is nothing: read as every interface, it opened the relay on them all ("tailscale,", ["127.0.0.1", "tailscale"]), (",,192.168.1.10, ", ["127.0.0.1", "192.168.1.10"])): with self.subTest(given=given, six=six): diff --git a/dashboard/tests/test_cockpit_http.py b/dashboard/tests/test_cockpit_http.py index d6e2a73f..26418daf 100644 --- a/dashboard/tests/test_cockpit_http.py +++ b/dashboard/tests/test_cockpit_http.py @@ -20,6 +20,7 @@ What is asserted, in the order an attacker would try it: * one job at a time, and the audit log records the exact argv """ import base64 +import hmac import http.client import importlib.util import json @@ -339,13 +340,48 @@ class Login(Base): for key in ("wrong", API_KEY): for _ in range(7): st, hdrs, data = self.req("POST", "/api/login", {"key": key}, headers={"Sec-Fetch-Site": "cross-site"}) - self.assertEqual((st, json.loads(data)["error"]), (403, "a login from another site's page is refused")) + self.assertEqual(st, 403) + self.assertIn("a login from another site's page is refused", json.loads(data)["error"]) self.assertNotIn("Set-Cookie", hdrs) for site in ("same-origin", "same-site", "none", None): st, hdrs, _ = self.req("POST", "/api/login", {"key": API_KEY}, headers={"Sec-Fetch-Site": site} if site else {}) self.assertEqual(st, 200, site) self.assertIn("Set-Cookie", hdrs) + def test_nor_over_plain_http_where_a_browser_says_its_origin_alone(self): + # a browser sends no Sec-Fetch header to a tailnet or a LAN address over plain HTTP, the cockpit's own case (review + # of v1.60.0): its Origin has to be the host it asked + host = f"192.168.1.20:{self.port}" + for origin in ("http://evil.example", "https://evil.example", "null", f"http://192.168.1.21:{self.port}", "http://192.168.1.20"): + for _ in range(7): + st, hdrs, data = self.req("POST", "/api/login", {"key": "wrong"}, headers={"Origin": origin, "Host": host}) + self.assertEqual(st, 403, origin) + self.assertIn("another site's page", json.loads(data)["error"]) + for headers in ({"Origin": f"http://{host}", "Host": host}, {"Host": host}, + {"Origin": "https://box.tail1234.ts.net", "Host": "box.tail1234.ts.net"}, + # the browser's own word first: a proxy that speaks TLS and writes its own Host + {"Origin": "https://cockpit.example", "Host": "127.0.0.1:30090", "Sec-Fetch-Site": "same-origin"}): + st, hdrs, _ = self.req("POST", "/api/login", {"key": API_KEY}, headers=headers) + self.assertEqual(st, 200, headers) + self.assertIn("Set-Cookie", hdrs) + + def test_it_proves_to_this_boxs_proxy_that_it_is_its_cockpit(self): + nonce = "0123456789abcdef" * 2 + st, _, data = self.req("GET", "/api/health", headers={"X-Alzeo-Prove": nonce}) + want = hmac.new(API_KEY.encode(), b"alzeo cockpit " + nonce.encode(), "sha256").hexdigest() + self.assertEqual((st, json.loads(data).get("proof")), (200, want)) + for headers in ({}, {"X-Alzeo-Prove": "short"}, {"X-Alzeo-Prove": nonce.upper()}, {"X-Alzeo-Prove": nonce + "0"}): + st, _, data = self.req("GET", "/api/health", headers=headers) + self.assertEqual((st, "proof" in json.loads(data)), (200, False), headers) + + def test_an_ipv6_address_in_the_bar_is_sent_on_to_localhost(self): + # a content policy has no name for one: nothing of the Agent view opened under it (review of v1.60.0) + for path in ("/", "/login"): + st, hdrs, _ = self.req("GET", path, headers={"Host": "[::1]:30090"}) + self.assertEqual((st, hdrs.get("Location")), (302, f"http://localhost:30090{path}")) + self.assertEqual(self.req("GET", "/login", headers={"Host": "localhost:30090"})[0], 200) + self.assertEqual(self.req("GET", "/api/health", headers={"Host": "[::1]:30090"})[0], 200) + def test_a_failure_is_audited(self): self.req("POST", "/api/login", {"key": "wrong"}) log = self.tmp / "cockpit-audit.log" diff --git a/docs/cockpit.md b/docs/cockpit.md index 265069ab..e0e3b487 100644 --- a/docs/cockpit.md +++ b/docs/cockpit.md @@ -668,7 +668,7 @@ host the cockpit was opened by leads to the relay too: | an SSH tunnel or NVIDIA Sync | opens when the tunnel carries port 30091 too, on 30091 or on the port after the cockpit's | | a proxy that speaks TLS (`tailscale serve`, Caddy, nginx) | opens when it carries the relay too, over https, on port 30091 or on the port after the page's (444 after 443) | | the LAN address or the `.local` name, with the relay on the tailnet | says so, with what opens it: the tailnet address, the SSH command, the box's own screen | -| `[::1]` on the box's own screen | opens (the cockpit and the relay serve the loopback's IPv6 address, where the box has one) | +| `[::1]` on the box's own screen | opens as `localhost`, where the cockpit sends on: a page's content policy has no name for an IPv6 address | | another IPv6 literal | nothing: but for `::1`, the cockpit and the relay serve IPv4 only | Since v1.59.1 the view frames nothing it has not reached: it asks the relay who it is diff --git a/keepalive-proxy.py b/keepalive-proxy.py index 1718254c..dbc61151 100755 --- a/keepalive-proxy.py +++ b/keepalive-proxy.py @@ -4630,6 +4630,13 @@ def _cockpit_get(path): key = _door_key() if not key: raise OSError("this box cannot read its own key") + # it proves first that it holds this box's key: what answers on the loopback may be a tunnel to another box's + # cockpit, and this key would have gone there (review of v1.60.0) + nonce = os.urandom(16).hex() + with _cockpit_opener().open(urllib.request.Request(base + "/api/health", headers={"X-Alzeo-Prove": nonce}), timeout=5) as r: + proof = json.loads(r.read(1 << 16).decode()).get("proof") + if not hmac.compare_digest(str(proof).encode(), hmac.new(key.encode(), b"alzeo cockpit " + nonce.encode(), "sha256").hexdigest().encode()): + raise OSError("what answers on its port does not prove it is this box's cockpit") req = urllib.request.Request(base + "/api/login", data=json.dumps({"key": key}).encode(), headers={"Content-Type": "application/json"}, method="POST") with _cockpit_opener().open(req, timeout=5) as r: diff --git a/tests/pairbox.py b/tests/pairbox.py index 78274968..c4d4861f 100644 --- a/tests/pairbox.py +++ b/tests/pairbox.py @@ -8,6 +8,7 @@ tests/test_proxy_pair_one_model.py and tests/test_proxy_pair_one_model_inprocess """ import atexit import hashlib +import hmac import http.client import http.server import importlib.util @@ -397,9 +398,12 @@ COCKPIT_STATE = {"machine": {"data": {"mem": {"MemTotal": 121 * GIB, "MemAvailab class FakeCockpit(http.server.BaseHTTPRequestHandler): - """A cockpit as the proxy meets it: /api/login with a box's key sets a session cookie, /api/state needs it.""" + """A cockpit as the proxy meets it: /api/login with a box's key sets a session cookie, /api/state needs it, /api/health + proves the key it holds, its box's: the one in the home its path names first (each box's proxy asks under its own).""" protocol_version = "HTTP/1.1" keys = {KEY_1, KEY_2} + homes: dict = {} + proves = KEY_1 # with no home in the path; None: another box's, which proves nothing logins: list = [] sessions: set = set() states: list = [] # one per /api/state read @@ -417,7 +421,15 @@ class FakeCockpit(http.server.BaseHTTPRequestHandler): self.end_headers() self.wfile.write(out) + def of_a_box(self): + box, _, rest = self.path[1:].partition("/") + if box not in FakeCockpit.homes: + return FakeCockpit.proves + self.path = "/" + rest + return (FakeCockpit.homes[box] / ".config" / "qwen38" / "api-key").read_text().strip() + def do_POST(self): + self.of_a_box() body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}") if self.path == "/api/login" and body.get("key") in FakeCockpit.keys: tok = f"tok{len(FakeCockpit.logins)}" @@ -427,6 +439,10 @@ class FakeCockpit(http.server.BaseHTTPRequestHandler): self.reply(403, {"error": "bad key"}) def do_GET(self): + key = self.of_a_box() + if self.path == "/api/health": + asked = b"alzeo cockpit " + (self.headers.get("X-Alzeo-Prove") or "").encode() + return self.reply(200, {"ok": True, **({"proof": hmac.new(key.encode(), asked, "sha256").hexdigest()} if key else {})}) if (self.headers.get("Cookie") or "").removeprefix("cockpit=") not in FakeCockpit.sessions: return self.reply(401, {"error": "auth"}) if self.path == "/api/state": @@ -661,13 +677,18 @@ class PairFixture: cls.tearDownClass() raise + @classmethod + def cockpit_of(cls, home): + FakeCockpit.homes[home.name] = home + return f"{cls.cockpit_url}/{home.name}" + @classmethod def start_inproc(cls, home, engine): cls.saved_env = dict(os.environ) os.environ.update({"PAIR_CHECKPOINT": TEST_REV, **cls.ENTRY_ENV, "HOME": str(home), "PROXY_BIND": "127.0.0.1", "PAIR_TTL_S": str(PAIR_TTL), "PAIR_PORT": "0", - "QWEN38_COCKPIT_URL": cls.cockpit_url, + "QWEN38_COCKPIT_URL": cls.cockpit_of(home), "UPSTREAM": f"http://127.0.0.1:{engine.server_address[1]}", "PROMPT_CEILING_TOKENS": "0", "FLASH_PROMPT_CEILING_TOKENS": "0"}) for k in ("QWEN38_CLIENT_KEYS_FILE", "QWEN38_UPSTREAM_API_KEY", "PROXY_HOLD_UNITS", "QWEN38_PAIR_FILE", @@ -702,7 +723,7 @@ class PairFixture: @classmethod def start_proxy(cls, home, engine, label, **extra): env = {"PATH": os.environ["PATH"], "HOME": str(home), "PROXY_BIND": "127.0.0.1", "PAIR_PORT": "0", - "QWEN38_COCKPIT_URL": cls.cockpit_url, "UPSTREAM": f"http://127.0.0.1:{engine.server_address[1]}", + "QWEN38_COCKPIT_URL": cls.cockpit_of(home), "UPSTREAM": f"http://127.0.0.1:{engine.server_address[1]}", "PROMPT_CEILING_TOKENS": "0", "FLASH_PROMPT_CEILING_TOKENS": "0", "PAIR_CHECKPOINT": TEST_REV, **extra} with open(cls.tmp / f"{label}.journal", "ab") as journal: # the child keeps its own copy proc, port = localports.spawn(lambda port: subprocess.Popen( diff --git a/tests/test_proxy_pair.py b/tests/test_proxy_pair.py index 17f36aca..53cfae18 100644 --- a/tests/test_proxy_pair.py +++ b/tests/test_proxy_pair.py @@ -2658,6 +2658,33 @@ class ThePairsPieces(unittest.TestCase): self.assertTrue(gone["cockpit"], gone) self.assertEqual(len(FakeCockpit.logins), 2) + def test_its_key_goes_to_its_own_cockpit_alone(self): + """On the loopback: where an ssh tunnel to the other box's cockpit may hold the port, which got this box's key and + counted it as a failed login (review of v1.60.0).""" + srv = Engine(("127.0.0.1", 0), FakeCockpit) + threading.Thread(target=srv.serve_forever, daemon=True).start() + self.addCleanup(srv.server_close) + self.addCleanup(srv.shutdown) + saved, url = self.mod.UPSTREAM_API_KEY, os.environ.get("QWEN38_COCKPIT_URL") + + def back(): + self.mod.UPSTREAM_API_KEY, FakeCockpit.proves, self.mod._COCKPIT["cookie"] = saved, KEY_1, None + os.environ.pop("QWEN38_COCKPIT_URL", None) + if url is not None: + os.environ["QWEN38_COCKPIT_URL"] = url + self.addCleanup(back) + self.mod.UPSTREAM_API_KEY = KEY_1 + os.environ["QWEN38_COCKPIT_URL"] = f"http://127.0.0.1:{srv.server_address[1]}" + for other in (KEY_2, None): + FakeCockpit.proves, self.mod._COCKPIT["cookie"] = other, None + FakeCockpit.logins.clear() + with self.assertRaisesRegex(OSError, "does not prove it is this box's cockpit"): + self.mod._cockpit_get("/api/state") + self.assertEqual(FakeCockpit.logins, [], "this box's key went to what holds the port") + FakeCockpit.proves = KEY_1 + self.mod._cockpit_get("/api/state") + self.assertEqual(FakeCockpit.logins, [KEY_1]) + def test_the_cockpit_is_found_on_the_boxs_own_loopback_at_its_units_port(self): # whatever address it was given besides: since v1.59.1 it answers there too. Asked at the tailnet address its unit # names, it was not found while Tailscale was down, and the pair's tile said nothing (2026-12-01)