mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-06 21:04:21 +01:00
opencode 1.19.4 sends the Agent tab's index chunked, where 1.18.35 sent a Content-Length, and the relay injected its phone layer only into a document with a length: with 1.19.4 the tab lost it on a phone (both versions behind a copy of this relay, 2026-10-22). A chunked document is read up to one byte past INJECT_LIMIT before anything is sent, and gets the layer when its last chunk came within and it holds something: one cut short is refused with a 502 as a short one with a length was, one past the limit streams untouched, what was read first, and an empty one as it came. The tests read every Cache-Control the relay sends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
799 lines
39 KiB
Python
799 lines
39 KiB
Python
"""Offline tests for agent_relay.py: a fake opencode server (Basic auth, plain,
|
|
chunked, server-sent events, WebSocket echo) behind the relay, and the pure
|
|
helpers. No browser, no network beyond loopback."""
|
|
import base64
|
|
import hashlib
|
|
import http.client
|
|
import http.server
|
|
import json
|
|
import os
|
|
import socket
|
|
import socketserver
|
|
import struct
|
|
import sys
|
|
import threading
|
|
import time
|
|
import unittest
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
import agent_relay as ar # noqa: E402
|
|
|
|
GOOD_AUTH = "Basic " + base64.b64encode(b"cockpit:secret").decode()
|
|
SPA_DOC = b"<!doctype html><html><head><title>Oc</title></head><body><div id=root></div></body></html>"
|
|
|
|
|
|
def html_of(n: int) -> bytes:
|
|
"""An HTML document of exactly n bytes, with a head the phone layer can go into."""
|
|
head, tail = b"<html><head><title>Big</title></head><body>", b"</body></html>"
|
|
return head + b"x" * (n - len(head) - len(tail)) + tail
|
|
WS_GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
|
RELEASE = threading.Event() # lets the SSE handler send its second event
|
|
SEEN: list = [] # requests as the upstream saw them
|
|
|
|
|
|
def opencode_origin_ok(origin, host) -> bool:
|
|
"""opencode's rule for its terminal (isAllowedRequestOrigin, packages/server/src/cors.ts,
|
|
1.19.0, no --cors list): no Origin, an Origin naming the Host the request was sent to, or
|
|
a loopback page. Any other origin is refused, both for the connect ticket and, from
|
|
1.19.0, for the WebSocket itself."""
|
|
if not origin:
|
|
return True
|
|
if host and urllib.parse.urlsplit(origin).netloc == host:
|
|
return True
|
|
return origin.startswith(("http://localhost:", "http://127.0.0.1:"))
|
|
|
|
|
|
class FakeOpencode(http.server.BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def _json(self, obj, code=200, extra=()):
|
|
body = json.dumps(obj).encode()
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
for k, v in extra:
|
|
self.send_header(k, v)
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def _auth(self) -> bool:
|
|
if self.headers.get("Authorization") == GOOD_AUTH:
|
|
return True
|
|
self.send_response(401)
|
|
self.send_header("WWW-Authenticate", 'Basic realm="Secure Area"')
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
return False
|
|
|
|
def do_GET(self):
|
|
SEEN.append({"method": "GET", "path": self.path, "headers": dict(self.headers.items())})
|
|
if not self._auth():
|
|
return
|
|
if self.headers.get("Upgrade", "").lower() == "websocket":
|
|
return self.websocket()
|
|
path = self.path.split("?", 1)[0]
|
|
if path == "/echo":
|
|
return self._json({"method": "GET", "path": self.path, "headers": dict(self.headers.items())})
|
|
if path == "/len":
|
|
body = bytes(range(256)) * 800 # 204,800 bytes with a Content-Length
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/octet-stream")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.send_header("ETag", '"abc"')
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
if path == "/chunked":
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/plain")
|
|
self.send_header("Transfer-Encoding", "chunked")
|
|
self.end_headers()
|
|
for piece in (b"alpha-", b"beta-", b"gamma"):
|
|
self.wfile.write(b"%x\r\n%s\r\n" % (len(piece), piece))
|
|
self.wfile.write(b"0\r\n\r\n")
|
|
return
|
|
if path == "/sse":
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream")
|
|
self.send_header("Transfer-Encoding", "chunked")
|
|
self.end_headers()
|
|
first = b"data: one\n\n"
|
|
self.wfile.write(b"%x\r\n%s\r\n" % (len(first), first))
|
|
self.wfile.flush()
|
|
RELEASE.wait(timeout=10)
|
|
second = b"data: two\n\n"
|
|
self.wfile.write(b"%x\r\n%s\r\n" % (len(second), second))
|
|
self.wfile.write(b"0\r\n\r\n")
|
|
return
|
|
if path in ("/cutlen", "/cuthtml"):
|
|
# promises a body and dies halfway through it, as opencode does when it
|
|
# restarts mid-answer
|
|
html = path == "/cuthtml"
|
|
body = (b"<html><body>" + b"a" * 2988) if html else bytes(10000)
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/html" if html else "application/javascript")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body[:len(body) // 2])
|
|
self.wfile.flush()
|
|
self.close_connection = True
|
|
self.connection.shutdown(socket.SHUT_RDWR)
|
|
return
|
|
if path == "/nobody":
|
|
self.send_response(204)
|
|
self.end_headers()
|
|
return
|
|
if path == "/spa":
|
|
doc = SPA_DOC
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/html")
|
|
self.send_header("Content-Length", str(len(doc)))
|
|
self.send_header("Cache-Control", "max-age=600")
|
|
self.end_headers()
|
|
self.wfile.write(doc)
|
|
return
|
|
if path == "/emptychunkspa":
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/html")
|
|
self.send_header("Transfer-Encoding", "chunked")
|
|
self.end_headers()
|
|
self.wfile.write(b"0\r\n\r\n")
|
|
return
|
|
if path in ("/chunkspa", "/cutchunkspa", "/sizedchunkspa"):
|
|
# the index the way opencode 1.19.4 sends it: chunked, no Content-Length; cut
|
|
# after its first piece, or of a given size in 64 KiB pieces
|
|
if path == "/sizedchunkspa":
|
|
doc = html_of(int(urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query)["n"][0]))
|
|
pieces = [doc[i:i + 65536] for i in range(0, len(doc), 65536)]
|
|
else:
|
|
pieces = [SPA_DOC[:20], SPA_DOC[20:50], SPA_DOC[50:]]
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/html")
|
|
self.send_header("Transfer-Encoding", "chunked")
|
|
self.send_header("Cache-Control", "max-age=600")
|
|
self.end_headers()
|
|
for i, piece in enumerate(pieces):
|
|
self.wfile.write(b"%x\r\n%s\r\n" % (len(piece), piece))
|
|
if path == "/cutchunkspa":
|
|
self.wfile.flush()
|
|
self.close_connection = True
|
|
self.connection.shutdown(socket.SHUT_RDWR)
|
|
return
|
|
self.wfile.write(b"0\r\n\r\n")
|
|
return
|
|
if path == "/gzspa":
|
|
import gzip
|
|
doc = gzip.compress(SPA_DOC)
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/html")
|
|
self.send_header("Content-Encoding", "gzip")
|
|
self.send_header("Content-Length", str(len(doc)))
|
|
self.end_headers()
|
|
self.wfile.write(doc)
|
|
return
|
|
if path == "/cookie":
|
|
return self._json({"ok": True}, extra=(("Set-Cookie", "cockpit=evil; Path=/"),
|
|
("Set-Cookie", "theme=dark; Path=/")))
|
|
if path == "/global/health":
|
|
return self._json({"healthy": True, "version": "9.9.9"})
|
|
if path == "/config":
|
|
return self._json({"permission": {"*": "allow"}, "model": "x/y"})
|
|
self._json({"error": "not found"}, 404)
|
|
|
|
def do_HEAD(self):
|
|
SEEN.append({"method": "HEAD", "path": self.path, "headers": dict(self.headers.items())})
|
|
if not self._auth():
|
|
return
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/octet-stream")
|
|
self.send_header("Content-Length", "204800")
|
|
self.end_headers()
|
|
|
|
def do_POST(self):
|
|
length = int(self.headers.get("Content-Length") or 0)
|
|
body = self.rfile.read(length)
|
|
SEEN.append({"method": "POST", "path": self.path, "headers": dict(self.headers.items()), "len": length})
|
|
if not self._auth():
|
|
return
|
|
path = self.path.split("?", 1)[0]
|
|
if path.startswith("/pty/") and path.endswith("/connect-token"):
|
|
if (self.headers.get("x-opencode-ticket") != "1"
|
|
or not opencode_origin_ok(self.headers.get("Origin"), self.headers.get("Host"))):
|
|
return self._json({"_tag": "PtyForbiddenError"}, 403)
|
|
return self._json({"ticket": "t"})
|
|
self._json({"len": len(body), "sha256": hashlib.sha256(body).hexdigest(),
|
|
"ctype": self.headers.get("Content-Type")})
|
|
|
|
def websocket(self):
|
|
if self.path.startswith("/pty/") and not opencode_origin_ok(self.headers.get("Origin"),
|
|
self.headers.get("Host")):
|
|
self.send_response(403)
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
self.close_connection = True
|
|
return
|
|
key = self.headers["Sec-WebSocket-Key"].encode()
|
|
accept = base64.b64encode(hashlib.sha1(key + WS_GUID).digest()).decode()
|
|
self.wfile.write(b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"
|
|
b"Connection: Upgrade\r\nSec-WebSocket-Accept: " + accept.encode() + b"\r\n\r\n")
|
|
self.wfile.flush()
|
|
self.close_connection = True
|
|
# echo text frames until a close frame arrives
|
|
while True:
|
|
opcode, payload = ws_read(self.rfile)
|
|
if opcode == 8:
|
|
self.wfile.write(ws_frame(b"", opcode=8))
|
|
self.wfile.flush()
|
|
return
|
|
self.wfile.write(ws_frame(b"echo:" + payload))
|
|
self.wfile.flush()
|
|
|
|
|
|
def ws_frame(payload: bytes, opcode: int = 1, mask: bool = False) -> bytes:
|
|
head = bytes([0x80 | opcode])
|
|
n = len(payload)
|
|
if n < 126:
|
|
head += bytes([(0x80 if mask else 0) | n])
|
|
else:
|
|
head += bytes([(0x80 if mask else 0) | 126]) + struct.pack("!H", n)
|
|
if mask:
|
|
key = os.urandom(4)
|
|
return head + key + bytes(b ^ key[i % 4] for i, b in enumerate(payload))
|
|
return head + payload
|
|
|
|
|
|
def ws_read(fp) -> tuple[int, bytes]:
|
|
b0, b1 = fp.read(2)
|
|
opcode, masked, n = b0 & 0x0F, b1 & 0x80, b1 & 0x7F
|
|
if n == 126:
|
|
n = struct.unpack("!H", fp.read(2))[0]
|
|
key = fp.read(4) if masked else None
|
|
data = fp.read(n)
|
|
if masked:
|
|
data = bytes(b ^ key[i % 4] for i, b in enumerate(data))
|
|
return opcode, data
|
|
|
|
|
|
class Upstream(socketserver.ThreadingMixIn, http.server.HTTPServer):
|
|
daemon_threads = True
|
|
allow_reuse_address = True
|
|
|
|
|
|
class RelayTests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.up = Upstream(("127.0.0.1", 0), FakeOpencode)
|
|
threading.Thread(target=cls.up.serve_forever, daemon=True).start()
|
|
cls.creds = ("cockpit", "secret")
|
|
cfg = ar.RelayConfig(upstream=("127.0.0.1", cls.up.server_port),
|
|
credentials=lambda: cls.creds,
|
|
is_authed=lambda cookie: "cockpit=good" in (cookie or ""),
|
|
cockpit_port=30090)
|
|
cls.cfg = cfg
|
|
cls.relay = ar.serve(cfg, "127.0.0.1", 0)
|
|
threading.Thread(target=cls.relay.serve_forever, daemon=True).start()
|
|
cls.port = cls.relay.server_port
|
|
cls.base = f"http://127.0.0.1:{cls.port}"
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.relay.shutdown(); cls.relay.server_close()
|
|
cls.up.shutdown(); cls.up.server_close()
|
|
|
|
def setUp(self):
|
|
SEEN.clear()
|
|
RELEASE.clear()
|
|
type(self).creds = ("cockpit", "secret")
|
|
|
|
def get(self, path, headers=None, method="GET", data=None):
|
|
req = urllib.request.Request(self.base + path, method=method, data=data,
|
|
headers={"Cookie": "cockpit=good", **(headers or {})})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
return r.status, dict(r.headers.items()), r.read()
|
|
except urllib.error.HTTPError as e:
|
|
with e:
|
|
return e.code, dict(e.headers.items()), e.read()
|
|
|
|
def cache_controls(self, path):
|
|
"""Every Cache-Control the relay sends for a page: get() keeps one value of a header
|
|
sent twice, so an upstream policy passed beside the relay's own went unseen (found in
|
|
review, 2026-10-22)."""
|
|
req = urllib.request.Request(self.base + path, headers={"Cookie": "cockpit=good", "Accept": "text/html"})
|
|
with urllib.request.urlopen(req, timeout=10) as r:
|
|
r.read()
|
|
return r.headers.get_all("Cache-Control")
|
|
|
|
# ---- an answer opencode cuts short ----
|
|
def test_a_cut_fixed_length_answer_ends_the_browsers_connection(self):
|
|
"""The relay forwarded the Content-Length, stopped at opencode's early end, and
|
|
kept the keep-alive connection: the browser waited on it for bytes that would
|
|
never come, one of its six connections to the origin (found in review,
|
|
2026-09-24). It is closed now, which is how a browser learns of the cut."""
|
|
c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=8)
|
|
t0 = time.time()
|
|
try:
|
|
c.request("GET", "/cutlen", headers={"Cookie": "cockpit=good"})
|
|
r = c.getresponse()
|
|
self.assertEqual(r.status, 200)
|
|
with self.assertRaises(http.client.IncompleteRead):
|
|
r.read()
|
|
finally:
|
|
c.close()
|
|
self.assertLess(time.time() - t0, 4, "the browser was left waiting for the rest")
|
|
|
|
def test_a_cut_html_document_is_not_served_as_whole(self):
|
|
"""The document is read whole before the phone layer is injected, so a short one
|
|
became a complete-looking page with the tail of the app missing."""
|
|
code, _, body = self.get("/cuthtml", headers={"Accept": "text/html"})
|
|
self.assertEqual(code, 502)
|
|
self.assertIn("cut its answer short", json.loads(body)["error"])
|
|
|
|
# ---- gate ----
|
|
def test_no_session_is_401_json(self):
|
|
code, hdr, body = self.get("/echo", headers={"Cookie": "cockpit=forged"})
|
|
self.assertEqual(code, 401)
|
|
self.assertEqual(json.loads(body)["error"], "cockpit session required")
|
|
self.assertEqual(SEEN, [], "nothing reaches opencode without a session")
|
|
|
|
def test_no_session_navigation_gets_the_sign_in_page(self):
|
|
code, hdr, body = self.get("/", headers={"Cookie": "", "Accept": "text/html,*/*"})
|
|
self.assertEqual(code, 401)
|
|
self.assertIn("text/html", hdr["Content-Type"])
|
|
self.assertIn(b"http://127.0.0.1:30090/", body)
|
|
self.assertIn("frame-ancestors", hdr["Content-Security-Policy"])
|
|
|
|
def test_foreign_origin_is_403_even_with_a_session(self):
|
|
code, _, _ = self.get("/echo", headers={"Origin": "http://evil.example"})
|
|
self.assertEqual(code, 403)
|
|
code, _, _ = self.get("/echo", headers={"Origin": "null"})
|
|
self.assertEqual(code, 403)
|
|
code, _, _ = self.get("/echo", headers={"Origin": f"http://127.0.0.1:{self.port}"})
|
|
self.assertEqual(code, 200)
|
|
|
|
def test_manifest_passes_without_a_session_but_not_other_paths(self):
|
|
code, _, _ = self.get("/site.webmanifest", headers={"Cookie": ""})
|
|
self.assertEqual(code, 404, "reached the fake upstream (which has no manifest) with the credentials")
|
|
self.assertEqual({k.lower(): v for k, v in SEEN[-1]["headers"].items()}["authorization"], GOOD_AUTH)
|
|
code, _, _ = self.get("/site.webmanifest?x=1", headers={"Cookie": ""})
|
|
self.assertEqual(code, 404)
|
|
code, _, _ = self.get("/site.webmanifest", headers={"Cookie": ""}, method="POST", data=b"{}")
|
|
self.assertEqual(code, 401, "only GET is public")
|
|
code, _, _ = self.get("/site.webmanifest/../session", headers={"Cookie": ""})
|
|
self.assertEqual(code, 401)
|
|
|
|
def test_missing_credentials_is_503(self):
|
|
type(self).creds = None
|
|
code, _, body = self.get("/echo")
|
|
self.assertEqual(code, 503)
|
|
self.assertIn("credentials", json.loads(body)["error"])
|
|
|
|
def test_upstream_down_is_502(self):
|
|
with socket.socket() as dead:
|
|
dead.bind(("127.0.0.1", 0))
|
|
port = dead.getsockname()[1]
|
|
cfg = ar.RelayConfig(upstream=("127.0.0.1", port), credentials=lambda: ("a", "b"),
|
|
is_authed=lambda c: True, cockpit_port=30090)
|
|
srv = ar.serve(cfg, "127.0.0.1", 0)
|
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
try:
|
|
req = urllib.request.Request(f"http://127.0.0.1:{srv.server_port}/x")
|
|
with self.assertRaises(urllib.error.HTTPError) as cm:
|
|
urllib.request.urlopen(req, timeout=10)
|
|
self.assertEqual(cm.exception.code, 502)
|
|
self.assertIn("opencode-web.service", json.loads(cm.exception.read())["error"])
|
|
finally:
|
|
srv.shutdown(); srv.server_close()
|
|
|
|
# ---- mobile layer injection ----
|
|
def test_inject_mobile_helper(self):
|
|
out = ar.inject_mobile(SPA_DOC)
|
|
self.assertTrue(out.startswith(SPA_DOC[:out.index(b'<link')]))
|
|
self.assertIn(b'<link rel="stylesheet" href="/__cockpit/agent-mobile.css">', out)
|
|
self.assertLess(out.index(b"agent-mobile.js"), out.index(b"</head>"),
|
|
"the script lands inside head, before opencode's module")
|
|
self.assertEqual(ar.inject_mobile(out), out, "double injection never happens")
|
|
self.assertIn(ar.MOBILE_TAGS, ar.inject_mobile(b"<html>no head here</html>"),
|
|
"a document without </head> still gets the layer, appended")
|
|
|
|
def test_wants_html_rewrite_pure(self):
|
|
yes = dict(content_type="text/html", content_encoding=None, chunked=False, length=2884)
|
|
self.assertTrue(ar.wants_html_rewrite("GET", 200, **yes))
|
|
self.assertTrue(ar.wants_html_rewrite("GET", 200, content_type="text/html; charset=utf-8",
|
|
content_encoding="identity", chunked=False, length=10))
|
|
self.assertTrue(ar.wants_html_rewrite("GET", 200, content_type="text/html", content_encoding=None,
|
|
chunked=True, length=None),
|
|
"chunked: read up to the ceiling, injected only if whole within it")
|
|
for why, kw in {"POST": dict(command="POST"), "redirect": dict(status=304),
|
|
"json": dict(content_type="application/json"), "gzip": dict(content_encoding="gzip"),
|
|
"chunked gzip": dict(chunked=True, length=None, content_encoding="gzip"),
|
|
"chunked json": dict(chunked=True, length=None, content_type="application/json"),
|
|
"ends when the connection closes": dict(length=None),
|
|
"huge": dict(length=10 * 1024 * 1024)}.items():
|
|
args = {"content_type": "text/html", "content_encoding": None, "chunked": False, "length": 2884}
|
|
args.update(kw)
|
|
self.assertFalse(ar.wants_html_rewrite(args.pop("command", "GET"), args.pop("status", 200), **args), why)
|
|
|
|
def test_injected_assets_served_by_the_relay_itself(self):
|
|
code, hdr, body = self.get("/__cockpit/agent-mobile.css")
|
|
self.assertEqual(code, 200)
|
|
self.assertIn("text/css", hdr["Content-Type"])
|
|
self.assertIn(b"safe-area-inset-bottom", body, "the phone's home-indicator fix is in there")
|
|
self.assertIn(b"max-width: 767px", body, "opencode's own mobile breakpoint")
|
|
code, hdr, body = self.get("/__cockpit/agent-mobile.js")
|
|
self.assertEqual(code, 200)
|
|
self.assertIn("javascript", hdr["Content-Type"])
|
|
self.assertIn(b"spark.lastSession", body)
|
|
code, _, _ = self.get("/__cockpit/agent-mobile.css", headers={"Cookie": ""})
|
|
self.assertEqual(code, 401, "the cockpit session gates even our own files")
|
|
|
|
def test_served_document_gets_the_mobile_layer(self):
|
|
code, hdr, body = self.get("/spa", headers={"Accept": "text/html"})
|
|
self.assertEqual(code, 200)
|
|
self.assertIn(b"/__cockpit/agent-mobile.css", body)
|
|
self.assertIn(b"<title>Oc</title>", body, "the document itself passes untouched")
|
|
self.assertEqual(int(hdr["Content-Length"]), len(body), "the length is recomputed after injection")
|
|
self.assertEqual(self.cache_controls("/spa"), ["no-cache"],
|
|
"Safari must revalidate, never serve the un-injected document from its cache")
|
|
|
|
def test_gzipped_document_streams_untouched(self):
|
|
code, hdr, body = self.get("/gzspa", headers={"Accept": "text/html"})
|
|
self.assertEqual(code, 200)
|
|
self.assertEqual(hdr["Content-Encoding"], "gzip")
|
|
self.assertNotIn(b"/__cockpit/agent-mobile.", body, "compressed bytes are forwarded byte-exact")
|
|
import gzip
|
|
self.assertEqual(gzip.decompress(body), SPA_DOC)
|
|
|
|
def test_a_chunked_document_gets_the_mobile_layer(self):
|
|
"""opencode 1.19.4 sends its index chunked, where 1.18.35 sent it with a
|
|
Content-Length: the relay streamed it untouched, and the Agent tab lost its phone
|
|
layer (both versions behind a copy of this relay, 2026-10-22)."""
|
|
code, hdr, body = self.get("/chunkspa", headers={"Accept": "text/html"})
|
|
self.assertEqual(code, 200)
|
|
self.assertEqual(body, ar.inject_mobile(SPA_DOC))
|
|
self.assertEqual(int(hdr["Content-Length"]), len(body), "sent whole, with its new length")
|
|
self.assertNotIn("Transfer-Encoding", hdr)
|
|
self.assertEqual(self.cache_controls("/chunkspa"), ["no-cache"],
|
|
"Safari must revalidate, never serve the un-injected document from its cache")
|
|
|
|
def test_a_cut_chunked_document_is_not_served_as_whole(self):
|
|
"""A chunked document that stops before its last chunk is cut, as a short one with a
|
|
length is: the browser gets the 502 it can reload from, not a page missing its end."""
|
|
code, _, body = self.get("/cutchunkspa", headers={"Accept": "text/html"})
|
|
self.assertEqual(code, 502)
|
|
self.assertIn("cut its answer short", json.loads(body)["error"])
|
|
|
|
def test_a_chunked_document_past_the_ceiling_streams_untouched(self):
|
|
"""Up to INJECT_LIMIT a chunked document gets the layer; one byte past it, it streams
|
|
as it came, byte-exact and with the upstream's own cache policy."""
|
|
n = ar.INJECT_LIMIT
|
|
code, hdr, body = self.get(f"/sizedchunkspa?n={n}", headers={"Accept": "text/html"})
|
|
self.assertEqual(code, 200)
|
|
self.assertEqual(body, ar.inject_mobile(html_of(n)))
|
|
self.assertEqual(self.cache_controls(f"/sizedchunkspa?n={n}"), ["no-cache"])
|
|
code, hdr, body = self.get(f"/sizedchunkspa?n={n + 1}", headers={"Accept": "text/html"})
|
|
self.assertEqual(code, 200)
|
|
self.assertEqual(body, html_of(n + 1), "nothing injected, nothing lost")
|
|
self.assertEqual(hdr.get("Transfer-Encoding"), "chunked")
|
|
self.assertEqual(self.cache_controls(f"/sizedchunkspa?n={n + 1}"), ["max-age=600"])
|
|
|
|
def test_an_empty_chunked_document_stays_empty(self):
|
|
"""A length must be above 0 for the layer, and a chunked document with nothing in it
|
|
is no different: it reaches the browser as empty as it came."""
|
|
code, hdr, body = self.get("/emptychunkspa", headers={"Accept": "text/html"})
|
|
self.assertEqual(code, 200)
|
|
self.assertEqual(body, b"")
|
|
|
|
# ---- header hygiene ----
|
|
def test_request_headers_are_rewritten(self):
|
|
code, _, body = self.get("/echo?a=1&b=%2Fx", headers={
|
|
"Authorization": "Bearer stolen", "Referer": "http://127.0.0.1:30090/#agent",
|
|
"X-Custom": "kept", "Accept-Encoding": "gzip"})
|
|
self.assertEqual(code, 200)
|
|
seen = json.loads(body)
|
|
self.assertEqual(seen["path"], "/echo?a=1&b=%2Fx", "path and query pass verbatim")
|
|
h = {k.lower(): v for k, v in seen["headers"].items()}
|
|
self.assertEqual(h["authorization"], GOOD_AUTH, "the relay's credentials, not the client's")
|
|
self.assertNotIn("cookie", h, "the cockpit session never reaches opencode")
|
|
self.assertNotIn("referer", h)
|
|
self.assertEqual(h["host"], f"127.0.0.1:{self.up.server_port}")
|
|
self.assertEqual(h["x-custom"], "kept")
|
|
self.assertEqual(h["accept-encoding"], "gzip")
|
|
self.assertEqual(h["connection"], "close")
|
|
|
|
def test_response_headers_and_cookie_filter(self):
|
|
code, hdr, _ = self.get("/cookie")
|
|
self.assertEqual(code, 200)
|
|
cookies = [v for k, v in hdr.items() if k.lower() == "set-cookie"]
|
|
self.assertEqual(len(cookies), 1, "a cookie named like the session is dropped, others pass")
|
|
self.assertTrue(cookies[0].startswith("theme=dark"))
|
|
self.assertEqual(hdr["Content-Security-Policy"], "frame-ancestors 'self' http://127.0.0.1:30090")
|
|
self.assertEqual(hdr["X-Content-Type-Options"], "nosniff")
|
|
self.assertEqual(hdr["Referrer-Policy"], "no-referrer")
|
|
self.assertTrue(hdr["Server"].startswith("SparkCockpitRelay/"))
|
|
|
|
# ---- bodies and framing ----
|
|
def test_post_body_is_forwarded_byte_exact(self):
|
|
blob = os.urandom(1024 * 1024 + 17)
|
|
code, _, body = self.get("/session", method="POST", data=blob,
|
|
headers={"Content-Type": "application/octet-stream"})
|
|
self.assertEqual(code, 200)
|
|
out = json.loads(body)
|
|
self.assertEqual(out["len"], len(blob))
|
|
self.assertEqual(out["sha256"], hashlib.sha256(blob).hexdigest())
|
|
self.assertEqual(out["ctype"], "application/octet-stream")
|
|
|
|
def test_oversize_body_is_413_before_reading_it(self):
|
|
conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
|
|
conn.putrequest("POST", "/session")
|
|
conn.putheader("Cookie", "cockpit=good")
|
|
conn.putheader("Content-Length", str(ar.MAX_BODY + 1))
|
|
conn.endheaders()
|
|
resp = conn.getresponse()
|
|
self.assertEqual(resp.status, 413)
|
|
self.assertEqual(resp.getheader("Connection"), "close")
|
|
conn.close()
|
|
self.assertEqual(SEEN, [])
|
|
|
|
def test_content_length_body_passes_whole(self):
|
|
code, hdr, body = self.get("/len")
|
|
self.assertEqual(code, 200)
|
|
self.assertEqual(hdr["Content-Length"], "204800")
|
|
self.assertEqual(body, bytes(range(256)) * 800)
|
|
self.assertEqual(hdr["ETag"], '"abc"')
|
|
|
|
def test_chunked_body_is_rechunked_whole(self):
|
|
code, hdr, body = self.get("/chunked")
|
|
self.assertEqual(code, 200)
|
|
self.assertEqual(body, b"alpha-beta-gamma")
|
|
self.assertEqual(hdr.get("Transfer-Encoding"), "chunked")
|
|
self.assertNotIn("Content-Length", hdr)
|
|
|
|
def test_204_and_head_carry_no_body(self):
|
|
code, hdr, body = self.get("/nobody")
|
|
self.assertEqual(code, 204)
|
|
self.assertEqual(body, b"")
|
|
conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
|
|
conn.request("HEAD", "/len", headers={"Cookie": "cockpit=good"})
|
|
resp = conn.getresponse()
|
|
self.assertEqual(resp.status, 200)
|
|
self.assertEqual(resp.getheader("Content-Length"), "204800")
|
|
self.assertEqual(resp.read(), b"")
|
|
# the connection is still usable: framing was exact
|
|
conn.request("GET", "/nobody", headers={"Cookie": "cockpit=good"})
|
|
self.assertEqual(conn.getresponse().status, 204)
|
|
conn.close()
|
|
|
|
def test_keep_alive_serves_several_requests_on_one_connection(self):
|
|
conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
|
|
for path, expect in (("/len", bytes(range(256)) * 800), ("/chunked", b"alpha-beta-gamma"),
|
|
("/len", bytes(range(256)) * 800)):
|
|
conn.request("GET", path, headers={"Cookie": "cockpit=good"})
|
|
resp = conn.getresponse()
|
|
self.assertEqual(resp.status, 200)
|
|
self.assertEqual(resp.read(), expect)
|
|
conn.close()
|
|
|
|
def test_http10_client_gets_close_delimited_body(self):
|
|
s = socket.create_connection(("127.0.0.1", self.port), timeout=10)
|
|
s.sendall(b"GET /chunked HTTP/1.0\r\nHost: x\r\nCookie: cockpit=good\r\n\r\n")
|
|
raw = b""
|
|
while True:
|
|
piece = s.recv(65536)
|
|
if not piece:
|
|
break
|
|
raw += piece
|
|
s.close()
|
|
head, body = raw.split(b"\r\n\r\n", 1)
|
|
# the status line names the server's protocol (1.1, as any server does); what a
|
|
# 1.0 client needs is no chunked framing and a body ended by the close
|
|
self.assertTrue(head.startswith(b"HTTP/1.1 200") or head.startswith(b"HTTP/1.0 200"), head[:40])
|
|
self.assertNotIn(b"Transfer-Encoding", head)
|
|
self.assertEqual(body, b"alpha-beta-gamma")
|
|
|
|
def test_server_sent_events_stream_as_they_are_emitted(self):
|
|
conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
|
|
conn.request("GET", "/sse", headers={"Cookie": "cockpit=good", "Accept": "text/event-stream"})
|
|
resp = conn.getresponse()
|
|
self.assertEqual(resp.status, 200)
|
|
self.assertEqual(resp.getheader("Content-Type"), "text/event-stream")
|
|
t0 = time.time()
|
|
first = resp.read1(1024)
|
|
self.assertEqual(first, b"data: one\n\n", "the first event arrives before the second exists")
|
|
self.assertLess(time.time() - t0, 5.0)
|
|
RELEASE.set()
|
|
rest = b""
|
|
while True:
|
|
piece = resp.read1(1024)
|
|
if not piece:
|
|
break
|
|
rest += piece
|
|
self.assertEqual(rest, b"data: two\n\n")
|
|
conn.close()
|
|
|
|
# ---- WebSocket ----
|
|
def test_websocket_is_tunneled_with_the_credentials(self):
|
|
s = socket.create_connection(("127.0.0.1", self.port), timeout=10)
|
|
key = base64.b64encode(os.urandom(16)).decode()
|
|
s.sendall((f"GET /pty/1/connect?ticket=t HTTP/1.1\r\nHost: 127.0.0.1:{self.port}\r\n"
|
|
f"Origin: http://127.0.0.1:{self.port}\r\nCookie: cockpit=good\r\n"
|
|
f"Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n"
|
|
"Sec-WebSocket-Version: 13\r\n\r\n").encode())
|
|
head = b""
|
|
while b"\r\n\r\n" not in head:
|
|
head += s.recv(4096)
|
|
self.assertTrue(head.startswith(b"HTTP/1.1 101"), head)
|
|
accept = base64.b64encode(hashlib.sha1(key.encode() + WS_GUID).digest()).decode()
|
|
self.assertIn(b"Sec-WebSocket-Accept: " + accept.encode(), head)
|
|
s.sendall(ws_frame(b"ping", mask=True))
|
|
fp = s.makefile("rb")
|
|
opcode, data = ws_read(fp)
|
|
self.assertEqual((opcode, data), (1, b"echo:ping"))
|
|
s.sendall(ws_frame(b"", opcode=8, mask=True))
|
|
self.assertEqual(ws_read(fp)[0], 8, "the close frame comes back through the tunnel")
|
|
fp.close()
|
|
s.close()
|
|
h = {k.lower(): v for k, v in SEEN[-1]["headers"].items()}
|
|
self.assertEqual(h["authorization"], GOOD_AUTH)
|
|
self.assertNotIn("cookie", h)
|
|
self.assertEqual(h["upgrade"], "websocket")
|
|
|
|
# ---- the terminal, opened from another machine (the tailnet address) ----
|
|
def test_a_remote_browser_gets_its_terminal_ticket(self):
|
|
remote = f"100.64.0.1:{self.port}"
|
|
code, _, body = self.get("/pty/1/connect-token", method="POST", data=b"", headers={
|
|
"Host": remote, "Origin": f"http://{remote}", "x-opencode-ticket": "1"})
|
|
self.assertEqual((code, json.loads(body)), (200, {"ticket": "t"}))
|
|
h = {k.lower(): v for k, v in SEEN[-1]["headers"].items()}
|
|
self.assertEqual(h["origin"], f"http://127.0.0.1:{self.up.server_port}",
|
|
"opencode is shown its own page's origin, the one it serves to")
|
|
|
|
def test_a_remote_browser_opens_the_terminal(self):
|
|
remote = f"100.64.0.1:{self.port}"
|
|
s = socket.create_connection(("127.0.0.1", self.port), timeout=10)
|
|
s.sendall((f"GET /pty/1/connect?ticket=t HTTP/1.1\r\nHost: {remote}\r\n"
|
|
f"Origin: http://{remote}\r\nCookie: cockpit=good\r\n"
|
|
"Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: eA==\r\n"
|
|
"Sec-WebSocket-Version: 13\r\n\r\n").encode())
|
|
fp = s.makefile("rb")
|
|
head = b""
|
|
while not head.endswith(b"\r\n\r\n"):
|
|
line = fp.readline()
|
|
if not line:
|
|
break
|
|
head += line
|
|
if head.startswith(b"HTTP/1.1 101"):
|
|
s.sendall(ws_frame(b"", opcode=8, mask=True))
|
|
self.assertEqual(ws_read(fp)[0], 8)
|
|
fp.close()
|
|
s.close()
|
|
self.assertTrue(head.startswith(b"HTTP/1.1 101"), head[:40])
|
|
h = {k.lower(): v for k, v in SEEN[-1]["headers"].items()}
|
|
self.assertEqual(h["origin"], f"http://127.0.0.1:{self.up.server_port}")
|
|
|
|
def test_a_foreign_page_still_gets_no_terminal(self):
|
|
remote = f"100.64.0.1:{self.port}"
|
|
code, _, _ = self.get("/pty/1/connect-token", method="POST", data=b"", headers={
|
|
"Host": remote, "Origin": "http://evil.example", "x-opencode-ticket": "1"})
|
|
self.assertEqual(code, 403)
|
|
self.assertEqual(SEEN, [], "refused by the relay, before opencode")
|
|
|
|
def test_websocket_without_session_is_refused_before_upstream(self):
|
|
s = socket.create_connection(("127.0.0.1", self.port), timeout=10)
|
|
s.sendall((f"GET /pty/1/connect HTTP/1.1\r\nHost: 127.0.0.1:{self.port}\r\n"
|
|
"Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: x\r\n\r\n").encode())
|
|
head = s.recv(4096)
|
|
s.close()
|
|
self.assertTrue(head.startswith(b"HTTP/1.1 401"), head[:40])
|
|
self.assertEqual(SEEN, [])
|
|
|
|
def test_upstream_json_and_permission_mode(self):
|
|
self.assertEqual(ar.upstream_json(self.cfg, "/config")["permission"], {"*": "allow"})
|
|
self.assertIsNone(ar.upstream_json(self.cfg, "/missing"), "a non-200 answer is None, never an exception")
|
|
type(self).creds = None
|
|
self.assertIsNone(ar.upstream_json(self.cfg, "/config"))
|
|
self.assertTrue(ar.permission_is_auto("allow"))
|
|
self.assertTrue(ar.permission_is_auto({"*": "allow", "edit": "deny"}))
|
|
self.assertFalse(ar.permission_is_auto({"*": "ask", "bash": "allow"}))
|
|
self.assertFalse(ar.permission_is_auto(None))
|
|
self.assertFalse(ar.permission_is_auto("ask"))
|
|
|
|
# ---- health probe ----
|
|
def test_health_uses_the_credentials(self):
|
|
self.assertEqual(ar.health(self.cfg), {"healthy": True, "version": "9.9.9"})
|
|
type(self).creds = ("cockpit", "wrong")
|
|
out = ar.health(self.cfg)
|
|
self.assertFalse(out["healthy"])
|
|
self.assertIn("refused", out["error"])
|
|
|
|
|
|
class PureHelpers(unittest.TestCase):
|
|
def test_host_name(self):
|
|
self.assertEqual(ar.host_name("100.64.0.1:30090"), "100.64.0.1")
|
|
self.assertEqual(ar.host_name("spark.tail.ts.net"), "spark.tail.ts.net")
|
|
self.assertEqual(ar.host_name("[::1]:30090"), "[::1]")
|
|
self.assertEqual(ar.host_name(None), "")
|
|
# A bare IPv6 literal has no port to strip (a port needs brackets),
|
|
# but it must come back bracketed: callers build http://{name}:{port}
|
|
# URLs, and http://::1:30090/ is malformed. Found by hypothesis as
|
|
# '::' failing test_host_name_never_returns_a_port.
|
|
self.assertEqual(ar.host_name("::"), "[::]")
|
|
self.assertEqual(ar.host_name("::1"), "[::1]")
|
|
self.assertEqual(ar.host_name("fe80::1"), "[fe80::1]")
|
|
|
|
def test_origin_allowed(self):
|
|
self.assertTrue(ar.origin_allowed(None, "h:1"))
|
|
self.assertTrue(ar.origin_allowed("http://H:1", "h:1"))
|
|
self.assertTrue(ar.origin_allowed("https://h:1", "h:1"))
|
|
self.assertFalse(ar.origin_allowed("http://h:2", "h:1"))
|
|
self.assertFalse(ar.origin_allowed("null", "h:1"))
|
|
self.assertFalse(ar.origin_allowed("http://h:1", None))
|
|
|
|
def test_read_credentials(self):
|
|
import tempfile
|
|
with tempfile.TemporaryDirectory() as d:
|
|
f = Path(d) / "env"
|
|
f.write_text('# comment\nOPENCODE_SERVER_USERNAME="cockpit"\nOPENCODE_SERVER_PASSWORD=\'p w\'\n')
|
|
self.assertEqual(ar.read_credentials(f), ("cockpit", "p w"))
|
|
f.write_text("OPENCODE_SERVER_PASSWORD=only\n")
|
|
self.assertEqual(ar.read_credentials(f), ("opencode", "only"))
|
|
f.write_text("OPENCODE_SERVER_USERNAME=u\n")
|
|
self.assertIsNone(ar.read_credentials(f), "no password means no credentials")
|
|
self.assertIsNone(ar.read_credentials(Path(d) / "missing"))
|
|
|
|
def test_forward_request_headers(self):
|
|
out = dict(ar.forward_request_headers(
|
|
[("Host", "a"), ("Cookie", "c"), ("Authorization", "z"), ("Transfer-Encoding", "chunked"),
|
|
("Content-Length", "3"), ("Accept", "*/*"), ("Sec-WebSocket-Key", "k")], "127.0.0.1:4096", "Basic x"))
|
|
self.assertEqual(out["Host"], "127.0.0.1:4096")
|
|
self.assertEqual(out["Authorization"], "Basic x")
|
|
self.assertEqual(out["Connection"], "close")
|
|
self.assertEqual(out["Accept"], "*/*")
|
|
self.assertEqual(out["Sec-WebSocket-Key"], "k")
|
|
for gone in ("Cookie", "Transfer-Encoding", "Content-Length"):
|
|
self.assertNotIn(gone, out)
|
|
ws = dict(ar.forward_request_headers([], "u:1", "Basic x", websocket=True))
|
|
self.assertEqual((ws["Connection"], ws["Upgrade"]), ("Upgrade", "websocket"))
|
|
self.assertNotIn("Origin", out, "no origin is made up for a request that named none")
|
|
remote = ar.forward_request_headers([("Origin", "http://100.64.0.1:30091"), ("origin", "http://x")],
|
|
"127.0.0.1:4096", "Basic x")
|
|
self.assertEqual([v for k, v in remote if k.lower() == "origin"], ["http://127.0.0.1:4096"])
|
|
|
|
def test_frame_policy_and_upstream_split(self):
|
|
self.assertEqual(ar.frame_policy("100.64.0.1:30091", 30090), "frame-ancestors 'self' http://100.64.0.1:30090")
|
|
self.assertEqual(ar.frame_policy("[::1]:30091", 1), "frame-ancestors 'self' http://[::1]:1")
|
|
self.assertEqual(ar.split_upstream("http://127.0.0.1:4096"), ("127.0.0.1", 4096))
|
|
self.assertEqual(ar.split_upstream("127.0.0.1:5000"), ("127.0.0.1", 5000))
|
|
|
|
def test_tailscale_ipv4_and_resolve_bind(self):
|
|
class R:
|
|
def __init__(self, out):
|
|
self.stdout = out
|
|
iface = "8: tailscale0 inet 100.114.54.60/32 scope global tailscale0\\ valid_lft forever\n"
|
|
self.assertEqual(ar.tailscale_ipv4(lambda *a, **k: R(iface)), "100.114.54.60")
|
|
calls = []
|
|
def run(argv, **k):
|
|
calls.append(argv[0])
|
|
return R("" if argv[0] == "ip" else "100.99.1.2\nfd7a:115c::1\n")
|
|
self.assertEqual(ar.tailscale_ipv4(run), "100.99.1.2")
|
|
self.assertEqual(calls, ["ip", "tailscale"], "interface first, CLI as fallback")
|
|
self.assertIsNone(ar.tailscale_ipv4(lambda *a, **k: R("")))
|
|
def boom(*a, **k):
|
|
raise OSError("no such binary")
|
|
self.assertIsNone(ar.tailscale_ipv4(boom))
|
|
self.assertIsNone(ar.tailscale_ipv4(lambda *a, **k: R("inet 192.168.1.5/24")), "a LAN address is not a tailnet one")
|
|
self.assertEqual(ar.resolve_bind("127.0.0.1"), "127.0.0.1")
|
|
self.assertEqual(ar.resolve_bind(" tailscale ", lambda *a, **k: R("100.64.0.9")), "100.64.0.9")
|
|
self.assertIsNone(ar.resolve_bind(""))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main(verbosity=1)
|