mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-06 21:04:21 +01:00
460 lines
25 KiB
Python
460 lines
25 KiB
Python
#!/usr/bin/env python3
|
|
"""The cockpit and the agent relay answer wherever a person opens them, and nowhere else.
|
|
|
|
On the box's own display, the cockpit opened by http://localhost:30090 and its Agent tab was a grey panel: the relay
|
|
listened on the tailnet address alone, and the page framed a port nothing answered on (2026-11-30). A cockpit given
|
|
the tailnet address, as install.sh gives it, refused localhost whole, and ended at each start until Tailscale was up.
|
|
|
|
Both listen on the box's loopback beside the address they are given, each address with a state of its own, and the
|
|
relay tells the page that asks whose it is. What must not move: no other address of the network, no page but the
|
|
cockpit's that reads the relay or frames it, nothing of opencode without the session."""
|
|
import http.client
|
|
import http.server
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
import random
|
|
import re
|
|
import shutil
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
HERE = Path(__file__).resolve()
|
|
DASH = HERE.parents[1]
|
|
REPO = HERE.parents[2]
|
|
sys.path.insert(0, str(DASH))
|
|
sys.path.insert(0, str(REPO / "tests"))
|
|
import agent_relay as ar # noqa: E402
|
|
import localports # noqa: E402
|
|
|
|
CLOSED = "http://127.0.0.1:1"
|
|
PROBE = "/__cockpit/relay" # as agent.js asks it
|
|
|
|
|
|
class Quiet(http.server.BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
seen: list = []
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def do_GET(self):
|
|
type(self).seen.append(self.path)
|
|
out = b'{"ok": true}'
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(out)))
|
|
self.end_headers()
|
|
self.wfile.write(out)
|
|
|
|
|
|
def make(addr, port):
|
|
return (ar.RelayServer6 if ":" in addr else ar.RelayServer)((addr, port), Quiet)
|
|
|
|
|
|
def get(port, path="/", headers=None, host="127.0.0.1", method="GET"):
|
|
c = http.client.HTTPConnection(host, port, timeout=10)
|
|
try:
|
|
c.request(method, path, headers=headers or {})
|
|
r = c.getresponse()
|
|
return r.status, r.headers, r.read()
|
|
finally:
|
|
c.close()
|
|
|
|
|
|
class OneListenerPerAddress(unittest.TestCase):
|
|
def listener(self, resolve, port=0, missing="no address yet", factory=make):
|
|
ln = ar.Listener(factory, port, resolve, missing)
|
|
self.addCleanup(ln.close)
|
|
return ln
|
|
|
|
def test_where_a_server_given_one_address_listens(self):
|
|
was = ar.address_here
|
|
self.addCleanup(setattr, ar, "address_here", was)
|
|
for six in (True, False): # the box's loopback has its IPv6 address, or the box has no IPv6
|
|
ar.address_here = lambda a: six if a == "::1" else was(a)
|
|
for given, want in (("tailscale", ["127.0.0.1", "tailscale"]), ("100.64.0.7", ["127.0.0.1", "100.64.0.7"]),
|
|
("192.168.1.10", ["127.0.0.1", "192.168.1.10"]), ("127.0.0.1", ["127.0.0.1"]),
|
|
("localhost", ["127.0.0.1"]), ("0.0.0.0", ["0.0.0.0"]), ("", [""]),
|
|
# the tailnet and a LAN, the relay's two (decision 1623)
|
|
("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"]), ("::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):
|
|
self.assertEqual(ar.listen_on(given), (["::1"] if six else []) + want)
|
|
|
|
def test_the_loopbacks_ipv6_address_is_served_apart(self):
|
|
if not ar.address_here("::1"):
|
|
self.skipTest("this box has no IPv6 loopback")
|
|
ln = self.listener(lambda: "::1")
|
|
self.assertTrue(ln.sync())
|
|
self.assertEqual(get(ln.server.server_port, host="::1")[0], 200)
|
|
with self.assertRaises(OSError): # and nothing of IPv4's with it
|
|
get(ln.server.server_port, host="127.0.0.1")
|
|
self.assertFalse(ar.address_here("2001:db8::7"))
|
|
self.assertEqual((ar.literal("::1"), ar.literal("127.0.0.1")), ("[::1]", "127.0.0.1"))
|
|
|
|
def test_the_loopback_answers_while_the_other_address_is_not_there(self):
|
|
now = {"addr": None}
|
|
loop, net = self.listener(lambda: "127.0.0.1"), self.listener(lambda: now["addr"])
|
|
said, lines = {}, []
|
|
self.assertFalse(ar.sync_all([loop, net], said, lines.append))
|
|
self.assertEqual(get(loop.server.server_port)[0], 200)
|
|
self.assertEqual((net.state["listening"], net.state["error"]), (False, "no address yet"))
|
|
self.assertFalse(ar.sync_all([loop, net], said, lines.append))
|
|
self.assertEqual(lines, ["listening on 127.0.0.1:0", "no address yet; retrying"], "what did not change is said once")
|
|
now["addr"] = "127.0.0.2" # Tailscale came up
|
|
self.assertTrue(ar.sync_all([loop, net], said, lines.append))
|
|
self.assertEqual(get(net.server.server_port, host="127.0.0.2")[0], 200)
|
|
self.assertEqual(lines[-1], "listening on 127.0.0.2:0")
|
|
|
|
def test_an_address_that_changed_is_followed(self):
|
|
now, here = {"addr": "127.0.0.2"}, {"127.0.0.2", "127.0.0.3"}
|
|
net, was = self.listener(lambda: now["addr"]), ar.address_here
|
|
self.addCleanup(setattr, ar, "address_here", was)
|
|
ar.address_here = lambda a: a in here
|
|
self.assertTrue(net.sync())
|
|
old = net.server.server_port
|
|
here.discard("127.0.0.2")
|
|
now["addr"] = "127.0.0.3" # another tailnet, another lease
|
|
self.assertTrue(net.sync())
|
|
self.assertEqual(net.state["addr"], "127.0.0.3")
|
|
self.assertEqual(get(net.server.server_port, host="127.0.0.3")[0], 200)
|
|
with self.assertRaises(OSError):
|
|
get(old, host="127.0.0.2")
|
|
|
|
def test_an_address_away_for_a_moment_is_heard_the_moment_it_is_back(self):
|
|
# tailscaled restarted by an update: the socket closed and bound again cost the tailnet up to 30 s
|
|
now, here = {"addr": "127.0.0.2"}, {"127.0.0.2"}
|
|
net, was = self.listener(lambda: now["addr"]), ar.address_here
|
|
self.addCleanup(setattr, ar, "address_here", was)
|
|
ar.address_here = lambda a: a in here
|
|
self.assertTrue(net.sync())
|
|
server = net.server
|
|
here.clear()
|
|
for gone in (None, "127.0.0.2"): # tailscale names none, an address given as such stays the same
|
|
now["addr"] = gone
|
|
self.assertFalse(net.sync())
|
|
self.assertEqual((net.state["listening"], net.state["error"]), (False, "127.0.0.2 is not an address of this box now"))
|
|
self.assertEqual(get(server.server_port, host="127.0.0.2")[0], 200, "the socket was closed")
|
|
here.add("127.0.0.2")
|
|
self.assertTrue(net.sync())
|
|
self.assertTrue(net.state["listening"] and net.server is server and net.state["error"] is None)
|
|
|
|
def test_whether_an_address_is_the_boxs(self):
|
|
self.assertTrue(ar.address_here("127.0.0.1"))
|
|
self.assertTrue(ar.address_here("0.0.0.0"))
|
|
self.assertFalse(ar.address_here("192.0.2.7"), "an address of the documentation range no box has")
|
|
|
|
def test_a_port_another_program_holds_is_said_and_taken_when_it_is_free(self):
|
|
port = localports.held(self)
|
|
ln = self.listener(lambda: "127.0.0.1", port, factory=lambda a, p: ar.RelayServer((a, p), Quiet))
|
|
self.assertFalse(ln.sync())
|
|
self.assertIn(f"cannot bind 127.0.0.1:{port}: ", ln.state["error"])
|
|
ln.port = 0
|
|
self.assertTrue(ln.sync())
|
|
self.assertIsNone(ln.state["error"])
|
|
|
|
def test_a_listener_that_stopped_is_bound_again(self):
|
|
ln = self.listener(lambda: "127.0.0.1")
|
|
ln.sync()
|
|
ln.server.shutdown()
|
|
for _ in range(50):
|
|
if not ln.state["listening"]:
|
|
break
|
|
time.sleep(0.05)
|
|
self.assertEqual((ln.state["listening"], ln.state["error"]), (False, "it stopped listening"))
|
|
self.assertTrue(ln.sync())
|
|
self.assertEqual(get(ln.server.server_port)[0], 200)
|
|
|
|
def test_how_often_it_looks(self):
|
|
up = {"yes": False}
|
|
ln = self.listener(lambda: "127.0.0.1" if up["yes"] else None)
|
|
waits = []
|
|
|
|
def pause(s):
|
|
waits.append(round(s, 2))
|
|
up["yes"] = len(waits) >= 6
|
|
if len(waits) == 8:
|
|
raise StopIteration
|
|
with self.assertRaises(StopIteration):
|
|
ar.keep_listening([ln], say=lambda line: None, pause=pause)
|
|
self.assertEqual(waits[:6], [7.5, 11.25, 16.88, 25.31, 30.0, 30.0])
|
|
self.assertEqual(waits[6:], [5.0, 5.0])
|
|
|
|
|
|
class WhoTheRelayIs(unittest.TestCase):
|
|
"""GET /__cockpit/relay: the one answer the cockpit's page may read from the relay, before it frames it."""
|
|
|
|
def setUp(self):
|
|
Quiet.seen = []
|
|
self.up = make("127.0.0.1", 0)
|
|
self.at: list = []
|
|
cfg = ar.RelayConfig(upstream=("127.0.0.1", self.up.server_port), credentials=lambda: ("u", "p"),
|
|
is_authed=lambda c: "cockpit=good" in (c or ""), cockpit_port=30090, ident="this-one",
|
|
seen_at=lambda: self.at)
|
|
self.relay = ar.serve(cfg, "127.0.0.1", 0)
|
|
for s in (self.up, self.relay):
|
|
threading.Thread(target=s.serve_forever, daemon=True).start()
|
|
self.addCleanup(s.server_close)
|
|
self.addCleanup(s.shutdown)
|
|
self.port = self.relay.server_port
|
|
|
|
def ask(self, origin=None, cookie=None, path=PROBE, **kw):
|
|
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}))
|
|
self.assertEqual(hd["Cache-Control"], "no-store")
|
|
self.assertIsNone(hd["Access-Control-Allow-Origin"])
|
|
self.assertEqual(json.loads(self.ask(cookie="cockpit=good")[2])["session"], True)
|
|
self.assertEqual(json.loads(self.ask(cookie="cockpit=forged")[2])["session"], False)
|
|
self.assertEqual(Quiet.seen, [], "opencode is never asked")
|
|
|
|
def test_only_the_cockpits_own_pages_read_it(self):
|
|
self.at[:] = ["127.0.0.1:8090", "spark.example", "spark.example:443"]
|
|
for origin in ("http://127.0.0.1:30090", "http://127.0.0.1:8090", "https://127.0.0.1:8090"):
|
|
with self.subTest(origin=origin):
|
|
st, hd, _ = self.ask(origin)
|
|
self.assertEqual((st, hd["Access-Control-Allow-Origin"], hd["Access-Control-Allow-Credentials"], hd["Vary"]),
|
|
(200, origin, "true", "Origin"))
|
|
# another program's page on this host, another host the cockpit was seen at, anyone else, a sandboxed frame
|
|
for origin in ("http://127.0.0.1:8888", "http://spark.example", "http://evil.example", "http://evil.example:30090",
|
|
"null", "http://127.0.0.1:30090.evil.example"):
|
|
with self.subTest(origin=origin):
|
|
st, hd, _ = self.ask(origin, cookie="cockpit=good")
|
|
self.assertEqual((st, hd["Access-Control-Allow-Origin"]), (403, None))
|
|
|
|
def test_no_other_answer_is_readable_from_the_page(self):
|
|
for path in ("/", "/api/config", PROBE + "/x", "/__cockpit/agent-mobile.js"):
|
|
with self.subTest(path=path):
|
|
st, hd, _ = self.ask("http://127.0.0.1:30090", "cockpit=good", path)
|
|
self.assertEqual((st, hd["Access-Control-Allow-Origin"]), (403, None))
|
|
self.assertEqual(self.ask(method="POST", cookie=None)[0], 401, "the question is a GET")
|
|
self.assertEqual(Quiet.seen, [])
|
|
|
|
def test_the_cockpit_frames_it_where_it_was_opened_and_no_one_else(self):
|
|
self.assertEqual(self.ask()[1]["Content-Security-Policy"], "frame-ancestors 'self' http://127.0.0.1:30090")
|
|
self.at[:] = ["localhost:8090", "127.0.0.1:8090", "127.0.0.1:30090"]
|
|
self.assertEqual(self.ask()[1]["Content-Security-Policy"],
|
|
"frame-ancestors 'self' http://127.0.0.1:30090 http://127.0.0.1:8090 https://127.0.0.1:8090 https://127.0.0.1:30090")
|
|
self.assertEqual(ar.frame_policy("[::1]:30091", 1, ["[::1]:8090"]),
|
|
"frame-ancestors 'self' http://[::1]:1 http://[::1]:8090 https://[::1]:8090")
|
|
|
|
def test_the_sign_in_page_leaves_the_frame(self):
|
|
# shown in the frame once the session has ended, its link opened the cockpit inside it, which no page frames
|
|
_, _, body = get(self.port, "/", {"Accept": "text/html"})
|
|
self.assertIn(b'target="_top"', body)
|
|
|
|
|
|
class TheCockpitSaysHowThePageCameIn(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
env, path = dict(os.environ), list(sys.path)
|
|
cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(env), sys.path.__setitem__(slice(None), path)))
|
|
cls.tmp = Path(tempfile.mkdtemp(prefix="agent-everywhere-"))
|
|
cls.addClassCleanup(shutil.rmtree, cls.tmp, True)
|
|
(cls.tmp / "api-key").write_text("test-key-not-a-real-one\n")
|
|
os.environ.update(COCKPIT_DRY_RUN="1", COCKPIT_CONFIG_DIR=str(cls.tmp), COCKPIT_REPO_DIR=str(REPO), COCKPIT_PORT="30090",
|
|
COCKPIT_AGENT_PORT="30091", COCKPIT_AUTOHEAL="0", COCKPIT_UPDATE_CHECK="0", HOME=str(cls.tmp),
|
|
COCKPIT_ENGINE=CLOSED, COCKPIT_PROXY=CLOSED, COCKPIT_IMAGE=CLOSED, COCKPIT_IMAGE_H3=CLOSED,
|
|
COCKPIT_VIDEO=CLOSED, COCKPIT_TRANSCRIBE=CLOSED)
|
|
spec = importlib.util.spec_from_file_location("cockpit_everywhere_under_test", DASH / "cockpit.py")
|
|
cls.cp = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(cls.cp)
|
|
cls.srv = cls.cp.Server(("127.0.0.1", 0), cls.cp.Handler)
|
|
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
|
|
cls.addClassCleanup(cls.srv.server_close)
|
|
cls.addClassCleanup(cls.srv.shutdown)
|
|
cls.port = cls.srv.server_port
|
|
|
|
def setUp(self):
|
|
self.cp.SEEN_AT.clear()
|
|
self.cookie = "cockpit=" + self.cp.make_token("sess")
|
|
|
|
def ask(self, path="/api/state", host="localhost:30090", cookie=True, **extra):
|
|
return get(self.port, path, {"Host": host, **({"Cookie": self.cookie} if cookie else {}), **extra})
|
|
|
|
def test_the_state_says_where_the_request_arrived(self):
|
|
st, _, body = self.ask()
|
|
state = json.loads(body)
|
|
self.assertEqual(st, 200)
|
|
self.assertEqual(next(iter(state)), "here", "before the collectors the page draws with it")
|
|
here = state["here"]["data"]
|
|
self.assertEqual((here["local"], here["peer"], here["proxied"]), ("127.0.0.1", "127.0.0.1", False))
|
|
self.assertTrue(json.loads(self.ask(**{"X-Forwarded-Proto": "https"})[2])["here"]["data"]["proxied"])
|
|
|
|
def test_the_stream_says_it_once(self):
|
|
s = socket.create_connection(("127.0.0.1", self.port), timeout=15)
|
|
self.addCleanup(s.close)
|
|
s.sendall(f"GET /api/stream?changes=1 HTTP/1.1\r\nHost: x\r\nCookie: {self.cookie}\r\n\r\n".encode())
|
|
raw, frames, end = b"", [], time.time() + 12
|
|
while len(frames) < 2 and time.time() < end:
|
|
raw += s.recv(65536)
|
|
frames = [f for f in raw.split(b"\r\n\r\n", 1)[-1].split(b"\n\n") if f.startswith(b"data: ")]
|
|
frames = frames if raw.endswith(b"\n\n") else frames[:-1]
|
|
first, second = (json.loads(f[6:]) for f in frames[:2])
|
|
self.assertEqual(first["here"]["data"]["local"], "127.0.0.1")
|
|
self.assertNotIn("here", second)
|
|
|
|
def test_the_page_may_frame_and_ask_the_relay_of_its_own_host_only(self):
|
|
def policy(host):
|
|
csp = dict(d.strip().split(" ", 1) for d in self.ask(host=host)[1]["Content-Security-Policy"].split(";"))
|
|
self.assertEqual(csp["connect-src"], "'self' " + csp["frame-src"])
|
|
self.assertEqual(csp["frame-ancestors"], "'none'")
|
|
return csp["frame-src"]
|
|
self.assertEqual(policy("localhost:30090"), "http://localhost:30091 https://localhost:30091")
|
|
self.assertEqual(policy("100.64.0.7:30090"), "http://100.64.0.7:30091 https://100.64.0.7:30091")
|
|
# a tunnel or a proxy that moved the cockpit's port: the relay's own, then the one after the page's
|
|
self.assertEqual(policy("localhost:8090"), "http://localhost:30091 https://localhost:30091 http://localhost:8091 https://localhost:8091")
|
|
self.assertEqual(policy("spark.example"), "http://spark.example:30091 https://spark.example:30091 http://spark.example:81 "
|
|
"https://spark.example:81 http://spark.example:444 https://spark.example:444")
|
|
self.assertEqual(policy("[::1]:30090"), "http://[::1]:30091 https://[::1]:30091")
|
|
for odd in ("a b; script-src *", "x;y", "", "evil.example:30090 http://elsewhere"):
|
|
with self.subTest(host=odd):
|
|
self.assertTrue(policy(odd).startswith("http://127.0.0.1:30091 "), "nothing of a host no browser sends")
|
|
|
|
def test_only_a_signed_in_request_tells_where_the_cockpit_is_opened(self):
|
|
self.ask(host="evil.example:30090", cookie=False)
|
|
self.assertEqual(self.cp.seen_at(), [])
|
|
for host in ("LOCALHOST:8090", "localhost:8090", "a b", "x;y"):
|
|
self.ask(host=host)
|
|
self.assertEqual(self.cp.seen_at(), ["localhost:8090"])
|
|
for i in range(60):
|
|
self.cp.saw_at(f"localhost:{2000 + i}")
|
|
self.assertEqual(len(self.cp.seen_at()), self.cp.SEEN_AT_MAX)
|
|
self.assertEqual(self.cp.seen_at()[-1], "localhost:2059", "the oldest goes first")
|
|
|
|
def test_another_host_name_gets_nothing_without_a_session(self):
|
|
# DNS rebinding: a page of evil.example whose name now leads to 127.0.0.1 is same-origin with the cockpit, and
|
|
# the browser has no cockpit cookie for that name
|
|
for path in ("/api/state", "/api/stream", "/api/actions", "/api/logs/qwen38-flash"):
|
|
with self.subTest(path=path):
|
|
self.assertEqual(self.ask(path, host="evil.example:30090", cookie=False)[0], 401)
|
|
|
|
def test_the_relay_it_builds_names_itself_as_the_state_does(self):
|
|
cfg = self.cp.agent_config()
|
|
self.assertEqual((cfg.ident, cfg.seen_at()), (self.cp.RELAY_ID, self.cp.seen_at()))
|
|
self.assertEqual(self.cp.relay_state()["id"], self.cp.RELAY_ID)
|
|
self.assertGreaterEqual(len(self.cp.RELAY_ID), 16)
|
|
|
|
def test_the_relays_state_is_each_address_then_all_of_them(self):
|
|
class L:
|
|
def __init__(self, addr, listening, error=None):
|
|
self.state = {"addr": addr, "listening": listening, "error": error, "since": None}
|
|
was = list(self.cp.AGENT_LISTENERS)
|
|
self.addCleanup(lambda: self.cp.AGENT_LISTENERS.__setitem__(slice(None), was))
|
|
for rows, want in (([], (False, None, None)),
|
|
([L("127.0.0.1", True), L("100.64.0.7", True)], (True, "100.64.0.7", None)),
|
|
([L("127.0.0.1", True), L(None, False, "no address")], (True, "127.0.0.1", "no address")),
|
|
([L("127.0.0.1", False, "taken"), L("100.64.0.7", True)], (True, "100.64.0.7", "taken"))):
|
|
self.cp.AGENT_LISTENERS[:] = rows
|
|
st = self.cp.relay_state()
|
|
self.assertEqual((st["listening"], st["bind"], st["error"]), want)
|
|
self.assertEqual(len(st["listeners"]), len(rows))
|
|
|
|
|
|
class ACockpitAsItStarts(unittest.TestCase):
|
|
"""The process itself, dry run: where it and its relay listen, and that a missing address does not end it."""
|
|
|
|
def start(self, bind, agent_bind, held_on=None):
|
|
low = int(Path("/proc/sys/net/ipv4/ip_local_port_range").read_text().split()[0])
|
|
for _ in range(4):
|
|
taken = {a[1] for a in localports._listening().values()} # the box's own cockpit, drawn once (2026-11-30)
|
|
port, relay = random.sample([p for p in range(low - 12000, low - 1) if p not in taken], 2)
|
|
if held_on:
|
|
try:
|
|
s = socket.socket()
|
|
s.bind((held_on, port))
|
|
s.listen()
|
|
except OSError:
|
|
s.close()
|
|
continue
|
|
self.addCleanup(s.close)
|
|
tmp = Path(tempfile.mkdtemp(prefix="cockpit-start-"))
|
|
self.addCleanup(shutil.rmtree, tmp, True)
|
|
(tmp / "api-key").write_text("test-key-not-a-real-one\n")
|
|
(tmp / "bin").mkdir()
|
|
for cmd in ("docker", "systemctl", "journalctl", "nvidia-smi", "sudo", "git", "tailscale", "opencode", "ip"):
|
|
(tmp / "bin" / cmd).write_text("#!/bin/sh\nexit 1\n")
|
|
(tmp / "bin" / cmd).chmod(0o755)
|
|
log = open(tmp / "log", "w+")
|
|
self.addCleanup(log.close)
|
|
p = subprocess.Popen([sys.executable, str(DASH / "cockpit.py")], stdout=log, stderr=log, env={
|
|
**os.environ, "PYTHONUNBUFFERED": "1", "COCKPIT_DRY_RUN": "1", "COCKPIT_CONFIG_DIR": str(tmp), "HOME": str(tmp),
|
|
"COCKPIT_REPO_DIR": str(REPO), "COCKPIT_SYSTEMD_DIR": str(tmp), "COCKPIT_PORT": str(port), "COCKPIT_BIND": bind,
|
|
"COCKPIT_AGENT_PORT": str(relay), "COCKPIT_AGENT_BIND": agent_bind, "COCKPIT_AGENT_UPSTREAM": CLOSED,
|
|
"COCKPIT_AUTOHEAL": "0", "COCKPIT_AUTOFIT": "0", "COCKPIT_UPDATE_CHECK": "0", "COCKPIT_ENGINE": CLOSED,
|
|
"COCKPIT_PROXY": CLOSED, "COCKPIT_IMAGE": CLOSED, "COCKPIT_IMAGE_H3": CLOSED, "COCKPIT_VIDEO": CLOSED,
|
|
"COCKPIT_TRANSCRIBE": CLOSED, "PATH": f"{tmp}/bin:{os.environ['PATH']}"})
|
|
self.addCleanup(localports._end, p)
|
|
return p, port, relay, (lambda: (log.flush(), Path(log.name).read_text())[1])
|
|
self.fail("no pair of ports in four tries")
|
|
|
|
def answers(self, host, port, path, within=20.0):
|
|
end = time.time() + within
|
|
while time.time() < end:
|
|
try:
|
|
return get(port, path, host=host)[0]
|
|
except OSError:
|
|
time.sleep(0.2)
|
|
return None
|
|
|
|
def says(self, log, words, within=20.0):
|
|
"""The words come to its log: each address is bound by a thread of its own, in no order."""
|
|
end = time.time() + within
|
|
while words not in log() and time.time() < end:
|
|
time.sleep(0.1)
|
|
self.assertIn(words, log())
|
|
|
|
def test_a_cockpit_on_one_address_answers_on_the_box_too_and_nowhere_else(self):
|
|
p, port, relay, log = self.start("127.0.0.2", "127.0.0.3")
|
|
self.assertEqual(self.answers("127.0.0.1", port, "/api/health"), 200, log())
|
|
self.assertEqual(self.answers("127.0.0.2", port, "/api/health"), 200, log())
|
|
self.assertEqual(self.answers("127.0.0.1", relay, "/x"), 401, log())
|
|
self.assertEqual(self.answers("127.0.0.3", relay, "/x"), 401, log())
|
|
listens = sorted(a for a in localports._listening().values() if a[1] in (port, relay))
|
|
want = [("0100007F", port), ("0200007F", port), ("0100007F", relay), ("0300007F", relay)]
|
|
if ar.address_here("::1"):
|
|
want += [("0" * 24 + "01000000", port), ("0" * 24 + "01000000", relay)]
|
|
self.assertEqual(self.answers("::1", port, "/api/health"), 200, log())
|
|
self.assertEqual(self.answers("::1", relay, "/x"), 401, log())
|
|
self.assertEqual(listens, sorted(want), "the address each is given, and the box's own loopback: no other")
|
|
|
|
def test_an_address_the_box_has_not_yet_does_not_end_it(self):
|
|
p, port, relay, log = self.start("192.0.2.7", "tailscale")
|
|
self.assertEqual(self.answers("127.0.0.1", port, "/api/health"), 200, log())
|
|
self.assertEqual(self.answers("127.0.0.1", relay, "/x"), 401, log())
|
|
self.assertIsNone(p.poll(), log())
|
|
self.says(log, f"cockpit: cannot bind 192.0.2.7:{port}: ")
|
|
self.says(log, "agent relay: no address for 'tailscale' yet")
|
|
|
|
def test_a_port_taken_everywhere_ends_it_as_before(self):
|
|
p, port, relay, log = self.start("127.0.0.1", "127.0.0.1", held_on="127.0.0.1")
|
|
self.assertEqual(p.wait(timeout=30), 1, log())
|
|
self.assertIn(f"cockpit: cannot bind 127.0.0.1:{port}: ", log())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=2)
|