mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-06 21:04:21 +01:00
The v2 migration put accept-encoding in REQUEST_DROP, so the relay never forwarded it on any request: a box that never passes --opencode lost gzip on every route, which is not "nothing changes" for a v1 box. The drop is now per request (forward_request_headers secret=...): on /api/config, /api/provider, /api/model and /api/credential the relay asks for identity, because it reads the JSON of the answer to scrub it and a gzip answer it cannot verify is a 502; everywhere else the client's Accept-Encoding passes, as it did before the v2 migration. Blind review of 2026-11-20, D6. Tests: test_accept_encoding_passes_on_every_other_route (new), test_request_headers_are_rewritten and test_forward_request_headers (updated) fail on the old code under the CI's invocation (cwd=dashboard, python3 tests/test_agent_relay.py); test_no_accept_encoding_reaches_opencode still proves the drop on the secret routes. Generated by Mistral Vibe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1245 lines
63 KiB
Python
1245 lines
63 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 re
|
|
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
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tests"))
|
|
import localports # 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
|
|
def _norm_target(target: str) -> str:
|
|
"""opencode's router answers the normalized path; so does this fake upstream, so an oddly spelled
|
|
request really reaches the credentials route (finding 6)."""
|
|
import posixpath
|
|
p = urllib.parse.unquote(target.split("?", 1)[0])
|
|
p = posixpath.normpath(p) if p.startswith("/") else "/" + posixpath.normpath(p)
|
|
return re.sub(r"/{2,}", "/", p)
|
|
|
|
|
|
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 = _norm_target(self.path)
|
|
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 == "/api/info":
|
|
mode = getattr(type(self), "INFO_MODE", "404")
|
|
if mode == "404":
|
|
return self._json({"error": "not found"}, 404)
|
|
if mode == "html": # OpenCode 2 answers its page on paths it does not know
|
|
body = SPA_DOC
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/html")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
return self._json({"version": "2.3.0", "pid": 4242, "capabilities": {"persistentPty": True}})
|
|
if path == "/global/health":
|
|
mode = getattr(type(self), "GH_MODE", "json")
|
|
if mode == "html":
|
|
body = SPA_DOC
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/html")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
if mode == "404":
|
|
return self._json({"error": "not found"}, 404)
|
|
return self._json({"healthy": True, "version": "9.9.9"})
|
|
if path == "/config":
|
|
return self._json({"permission": {"*": "allow"}, "model": "x/y"})
|
|
if path == "/api/config" and "page=1" in (self.path.partition("?")[2] if "?" in self.path else ""):
|
|
body = b"<!doctype html><title>the page</title>" # 1.x answers a page route as a page (measured /model)
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/html")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
if path == "/api/config" and "enc=1" in (self.path.partition("?")[2] if "?" in self.path else ""):
|
|
import gzip
|
|
raw = gzip.compress(b'{"apiKey": "sk-live"}')
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Encoding", "gzip")
|
|
self.send_header("Content-Length", str(len(raw)))
|
|
self.end_headers()
|
|
self.wfile.write(raw)
|
|
return
|
|
if path == "/api/config":
|
|
return self._json({"info": {"providers": {"local": {
|
|
"options": {"apiKey": "sk-live", "headers": {"Authorization": "Bearer sk-live"}},
|
|
"models": {"m": {"name": "m", "value": "keepme"}}}}}, "apiKey": "sk-live"})
|
|
if path == "/api/credential":
|
|
return self._json([{"name": "gh", "value": "sk-live", "token": "tok-live", "note": "ok"}])
|
|
if path == "/api/provider":
|
|
return self._json([{"id": "local", "apiKey": "sk-live"}])
|
|
if path == "/api/model":
|
|
return self._json({"data": [{"id": "m", "apiKey": "sk-live"}]})
|
|
if path == "/api/config/bad":
|
|
body = b'{"apiKey": "sk-live"}'
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/plain")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
return
|
|
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 = _norm_target(self.path)
|
|
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"})
|
|
if path in ("/api/config", "/api/provider", "/api/model", "/api/credential"):
|
|
# the answer of a POST on a secret route carries the key too (blind review
|
|
# 2026-11-20, D5); enc=1 answers it gzipped, which the relay must refuse
|
|
if "enc=1" in (self.path.partition("?")[2] if "?" in self.path else ""):
|
|
import gzip
|
|
raw = gzip.compress(b'{"apiKey": "sk-live"}')
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Encoding", "gzip")
|
|
self.send_header("Content-Length", str(len(raw)))
|
|
self.end_headers()
|
|
self.wfile.write(raw)
|
|
return
|
|
return self._json({"info": {"providers": {"local": {
|
|
"options": {"apiKey": "sk-live", "headers": {"Authorization": "Bearer sk-live"}}}}},
|
|
"apiKey": "sk-live"})
|
|
self._json({"len": len(body), "sha256": hashlib.sha256(body).hexdigest(),
|
|
"ctype": self.headers.get("Content-Type")})
|
|
|
|
do_DELETE = do_PUT = do_PATCH = do_POST
|
|
|
|
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):
|
|
port = localports.held(self) # nothing listens there, and no other program can
|
|
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",
|
|
"dropped only on the credential routes, where the scrub reads the answer; "
|
|
"everywhere else it passes, as before the v2 migration (D6)")
|
|
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("AlzeoCockpitRelay/"))
|
|
|
|
# ---- 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"))
|
|
|
|
# ---- credentials in OpenCode 2's config answers ----
|
|
def test_is_secret_path(self):
|
|
for p in ("/config", "/config?x=1", "/config/providers", "/provider/local",
|
|
"/api/config", "/api/config?x=1", "/api/config/shell", "/api/provider",
|
|
"/api/provider/local", "/api/model", "/api/model/x",
|
|
"/api/credential", "/api/credential/x",
|
|
"/api/experimental/config", "/api/integration"):
|
|
self.assertTrue(ar.is_secret_path(p), p)
|
|
for p in ("/configfoo", "/api/configuration", "/api/session", "/api/agent",
|
|
"/api/models", "/global/health", "/"):
|
|
self.assertFalse(ar.is_secret_path(p), p)
|
|
|
|
def test_scrub_secrets_keeps_the_shape(self):
|
|
doc = {"info": {"providers": {"local": {
|
|
"options": {"apiKey": "sk-live", "api_key": "sk-live",
|
|
"headers": {"Authorization": "Bearer sk-live", "X-Trace": "ok"}},
|
|
"secret": {"nested": "sk-live"}, "models": {"m": {"token": "sk-live"}}}}},
|
|
"list": [{"password": "sk-live", "keep": 1}], "keep": "visible"}
|
|
out = ar.scrub_secrets(doc)
|
|
self.assertEqual(out["keep"], "visible")
|
|
o = out["info"]["providers"]["local"]["options"]
|
|
self.assertEqual(o["apiKey"], "***")
|
|
self.assertEqual(o["api_key"], "***")
|
|
self.assertEqual(o["headers"]["Authorization"], "***")
|
|
self.assertEqual(o["headers"]["X-Trace"], "ok")
|
|
self.assertEqual(out["info"]["providers"]["local"]["secret"], "***")
|
|
self.assertEqual(out["info"]["providers"]["local"]["models"]["m"]["token"], "***")
|
|
self.assertEqual(out["list"], [{"password": "***", "keep": 1}])
|
|
|
|
def test_a_secret_bearing_answer_is_scrubbed_before_the_browser(self):
|
|
for path in ("/api/config", "/api/provider", "/api/model"):
|
|
code, hdr, body = self.get(path)
|
|
self.assertEqual(code, 200, path)
|
|
self.assertNotIn(b"sk-live", body, path)
|
|
self.assertIn(b"***", body, path)
|
|
self.assertEqual(hdr.get("Cache-Control"), "no-store", path)
|
|
self.assertEqual(int(hdr["Content-Length"]), len(body), path)
|
|
self.assertNotIn("Transfer-Encoding", hdr, path)
|
|
|
|
def test_a_secret_bearing_answer_that_is_not_json_is_refused(self):
|
|
code, _, body = self.get("/api/config/bad")
|
|
self.assertEqual(code, 502)
|
|
self.assertNotIn(b"sk-live", body)
|
|
self.assertIn("not relayed", json.loads(body)["error"])
|
|
|
|
def test_credential_values_are_scrubbed_before_the_browser(self):
|
|
# OpenCode 2 lists stored credentials "including its secret value" (2026-11-14)
|
|
code, hdr, body = self.get("/api/credential")
|
|
self.assertEqual(code, 200)
|
|
self.assertNotIn(b"sk-live", body)
|
|
self.assertNotIn(b"tok-live", body)
|
|
self.assertIn(b"***", body)
|
|
self.assertEqual(json.loads(body)[0]["note"], "ok", "the shape is kept")
|
|
self.assertEqual(hdr.get("Cache-Control"), "no-store")
|
|
|
|
def test_value_is_only_scrubbed_where_it_carries_a_credential(self):
|
|
# "value" is a plain member of models and costs: scrubbing it everywhere would
|
|
# lie to the SPA about its own shapes
|
|
code, _, body = self.get("/api/config")
|
|
self.assertEqual(code, 200)
|
|
self.assertIn(b"keepme", body, "value kept where it is not a credential")
|
|
self.assertNotIn(b"sk-live", body)
|
|
|
|
# ---- 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"])
|
|
|
|
def test_health_reads_the_v2_info(self):
|
|
FakeOpencode.INFO_MODE = "json"
|
|
try:
|
|
self.assertEqual(ar.health(self.cfg), {"healthy": True, "version": "2.3.0"})
|
|
finally:
|
|
del FakeOpencode.INFO_MODE
|
|
|
|
def test_health_the_page_on_global_health_is_not_health(self):
|
|
# OpenCode 2 answers its SPA page on every path it does not know (issue #55704,
|
|
# measured on 2.3.0 the 2026-11-14): the truth is /api/info, a 200 page is nothing.
|
|
FakeOpencode.INFO_MODE = "json"
|
|
FakeOpencode.GH_MODE = "html"
|
|
try:
|
|
self.assertEqual(ar.health(self.cfg), {"healthy": True, "version": "2.3.0"})
|
|
finally:
|
|
del FakeOpencode.INFO_MODE
|
|
del FakeOpencode.GH_MODE
|
|
|
|
def test_health_pages_answer_nothing(self):
|
|
FakeOpencode.INFO_MODE = "html"
|
|
FakeOpencode.GH_MODE = "html"
|
|
try:
|
|
out = ar.health(self.cfg)
|
|
self.assertFalse(out["healthy"])
|
|
self.assertIn("no JSON", out["error"])
|
|
finally:
|
|
del FakeOpencode.INFO_MODE
|
|
del FakeOpencode.GH_MODE
|
|
|
|
|
|
|
|
def make_relay(handler=None, creds=("cockpit", "secret")):
|
|
"""One relay in front of one fake opencode, as RelayTests builds them, for a single test."""
|
|
up = Upstream(("127.0.0.1", 0), handler or FakeOpencode)
|
|
threading.Thread(target=up.serve_forever, daemon=True).start()
|
|
cfg = ar.RelayConfig(upstream=("127.0.0.1", up.server_port), credentials=lambda: creds,
|
|
is_authed=lambda cookie: "cockpit=good" in (cookie or ""), cockpit_port=30090)
|
|
relay = ar.serve(cfg, "127.0.0.1", 0)
|
|
threading.Thread(target=relay.serve_forever, daemon=True).start()
|
|
return up, relay
|
|
|
|
|
|
class TheScrubCannotBeSpelledAround(unittest.TestCase):
|
|
"""A browser (or a script injected in the tab) spelling /api/config oddly must not walk around
|
|
the credential scrub: classify on the NORMALIZED target, the one opencode's router answers
|
|
(independent review of the v2 migration, finding 6)."""
|
|
|
|
SPELLINGS = ("/api//config", "/./api/config", "/foo/../api/config", "/%2e%2e/api/config",
|
|
"//api/config")
|
|
|
|
def _raw_get(self, port, path):
|
|
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
|
|
try:
|
|
conn.putrequest("GET", path, skip_host=True)
|
|
conn.putheader("Host", "127.0.0.1")
|
|
conn.putheader("Cookie", "cockpit=good")
|
|
conn.endheaders()
|
|
resp = conn.getresponse()
|
|
return resp.status, resp.read()
|
|
finally:
|
|
conn.close()
|
|
|
|
def test_is_secret_path_reads_the_normalized_target(self):
|
|
for p in self.SPELLINGS:
|
|
with self.subTest(path=p):
|
|
self.assertTrue(ar.is_secret_path(p), p)
|
|
|
|
def test_an_oddly_spelled_config_answer_still_reaches_the_browser_scrubbed(self):
|
|
up, relay = make_relay()
|
|
self.addCleanup(relay.shutdown)
|
|
self.addCleanup(up.shutdown)
|
|
for p in self.SPELLINGS:
|
|
with self.subTest(path=p):
|
|
SEEN.clear()
|
|
code, body = self._raw_get(relay.server_port, p)
|
|
self.assertEqual(code, 200)
|
|
self.assertNotIn(b"sk-live", body, "the answer came from the credentials route")
|
|
|
|
|
|
class TheRelayAsksForIdentity(unittest.TestCase):
|
|
"""The scrub reads JSON; a gzip answer it cannot verify is a 502. So on the credential
|
|
routes the relay must not ASK for compression it would then refuse: no Accept-Encoding is
|
|
forwarded there (independent review, finding 5). On every other route the client's
|
|
Accept-Encoding passes, as it did before the v2 migration, so a box that never passes
|
|
--opencode sees no change at the relay (blind review of 2026-11-20, D6)."""
|
|
|
|
def _get(self, port, path, headers=None):
|
|
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
|
|
try:
|
|
conn.putrequest("GET", path, skip_host=True)
|
|
conn.putheader("Host", "127.0.0.1")
|
|
conn.putheader("Cookie", "cockpit=good")
|
|
for k, v in (headers or {}).items():
|
|
conn.putheader(k, v)
|
|
conn.endheaders()
|
|
resp = conn.getresponse()
|
|
return resp.status, resp.read()
|
|
finally:
|
|
conn.close()
|
|
|
|
def test_no_accept_encoding_reaches_opencode(self):
|
|
up, relay = make_relay()
|
|
self.addCleanup(relay.shutdown)
|
|
self.addCleanup(up.shutdown)
|
|
SEEN.clear()
|
|
code, body = self._get(relay.server_port, "/api/config", headers={"Accept-Encoding": "gzip, br"})
|
|
self.assertEqual(code, 200)
|
|
self.assertNotIn(b"sk-live", body)
|
|
seen = next(r for r in SEEN if r["path"] == "/api/config")
|
|
self.assertNotIn("accept-encoding", {k.lower() for k in seen["headers"]})
|
|
|
|
def test_accept_encoding_passes_on_every_other_route(self):
|
|
up, relay = make_relay()
|
|
self.addCleanup(relay.shutdown)
|
|
self.addCleanup(up.shutdown)
|
|
SEEN.clear()
|
|
code, body = self._get(relay.server_port, "/echo", headers={"Accept-Encoding": "gzip, br"})
|
|
self.assertEqual(code, 200, body[:120])
|
|
seen = next(r for r in SEEN if r["path"] == "/echo")
|
|
self.assertEqual(seen["headers"].get("Accept-Encoding"), "gzip, br",
|
|
"only the credential routes ask for identity (D6)")
|
|
|
|
def test_a_lying_gzip_answer_is_refused_not_forwarded(self):
|
|
up, relay = make_relay()
|
|
self.addCleanup(relay.shutdown)
|
|
self.addCleanup(up.shutdown)
|
|
code, body = self._get(relay.server_port, "/api/config?enc=1")
|
|
self.assertEqual(code, 502, body[:120])
|
|
|
|
def test_a_page_on_a_secret_path_passes_and_an_oversized_json_is_refused(self):
|
|
# 1.x's /model answers the SPA page (measured 2026-11-15 on the box): a page is not a key,
|
|
# it passes. A JSON answer beyond the scrub limit is refused, never relayed unread.
|
|
up, relay = make_relay()
|
|
self.addCleanup(relay.shutdown)
|
|
self.addCleanup(up.shutdown)
|
|
code, body = self._get(relay.server_port, "/api/config?page=1")
|
|
self.assertEqual(code, 200)
|
|
self.assertIn(b"the page", body)
|
|
was = ar.SCRUB_LIMIT
|
|
ar.SCRUB_LIMIT = 16
|
|
try:
|
|
code, body = self._get(relay.server_port, "/api/config")
|
|
self.assertEqual(code, 502, body[:120])
|
|
self.assertIn(b"scrub limit", body)
|
|
finally:
|
|
ar.SCRUB_LIMIT = was
|
|
|
|
|
|
class TheScrubCoversEveryMethod(unittest.TestCase):
|
|
"""A POST, PUT, PATCH or DELETE on a secret route is scrubbed exactly like a GET: a script
|
|
injected in the tab can post, and the answer of a POST is not less secret. A compressed
|
|
answer on such a route is refused, fail closed, whatever the method (blind review of
|
|
2026-11-20, D5)."""
|
|
|
|
def _req(self, port, method, path, data=b""):
|
|
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
|
|
try:
|
|
conn.putrequest(method, path, skip_host=True)
|
|
conn.putheader("Host", "127.0.0.1")
|
|
conn.putheader("Cookie", "cockpit=good")
|
|
conn.putheader("Content-Length", str(len(data)))
|
|
conn.endheaders(data if data else None)
|
|
resp = conn.getresponse()
|
|
return resp.status, resp.read()
|
|
finally:
|
|
conn.close()
|
|
|
|
def test_a_post_on_a_secret_route_is_scrubbed(self):
|
|
up, relay = make_relay()
|
|
self.addCleanup(relay.shutdown)
|
|
self.addCleanup(up.shutdown)
|
|
for method, path, data in (("POST", "/api/config", b"{}"),
|
|
("POST", "/api/provider", b"{}"),
|
|
("PUT", "/api/model", b"{}"),
|
|
("DELETE", "/api/credential", b"")):
|
|
with self.subTest(method=method, path=path):
|
|
code, body = self._req(relay.server_port, method, path, data)
|
|
self.assertEqual(code, 200, body[:120])
|
|
self.assertNotIn(b"sk-live", body, "the answer of a non-GET is scrubbed too")
|
|
self.assertIn(b"***", body, "the shape is kept")
|
|
|
|
def test_a_lying_gzip_answer_to_a_post_is_refused(self):
|
|
up, relay = make_relay()
|
|
self.addCleanup(relay.shutdown)
|
|
self.addCleanup(up.shutdown)
|
|
code, body = self._req(relay.server_port, "POST", "/api/config?enc=1", b"{}")
|
|
self.assertEqual(code, 502, body[:120])
|
|
self.assertIn(b"not relayed", body)
|
|
|
|
|
|
class TheHealthProbeTrustsNothing(unittest.TestCase):
|
|
"""A 200 application/json that is not an object is not health: the probe answers like every
|
|
other failure instead of raising out of the Agent panel (independent review, finding 8)."""
|
|
|
|
def test_a_json_list_is_unhealthy_not_an_exception(self):
|
|
up = Upstream(("127.0.0.1", 0), type("L", (http.server.BaseHTTPRequestHandler,), {
|
|
"log_message": lambda self, *a: None,
|
|
"do_GET": lambda self: (self.send_response(200),
|
|
self.send_header("Content-Type", "application/json"),
|
|
self.end_headers(), self.wfile.write(b"[]"))[-1]}))
|
|
threading.Thread(target=up.serve_forever, daemon=True).start()
|
|
self.addCleanup(up.shutdown)
|
|
self.addCleanup(up.server_close)
|
|
cfg = ar.RelayConfig(upstream=("127.0.0.1", up.server_port),
|
|
credentials=lambda: ("opencode", "pw"), is_authed=lambda c: True,
|
|
cockpit_port=30090)
|
|
got = ar.health(cfg) # must not raise (finding 8)
|
|
self.assertFalse(got.get("healthy"))
|
|
self.assertNotIn("version", got or {})
|
|
|
|
class PureHelpers(unittest.TestCase):
|
|
def test_v2_wild_no_fnmatch_classes(self):
|
|
# OpenCode 2's "*" only: brackets must match literally (read in wildcard.ts of 2.3.0)
|
|
self.assertFalse(ar._v2_wild("echo b", "echo [abc]"))
|
|
self.assertTrue(ar._v2_wild("echo [abc]", "echo [abc]"))
|
|
self.assertTrue(ar._v2_wild("curl https://a.example/x", "*a.example*"))
|
|
self.assertFalse(ar._v2_wild("curl https://b.example/x", "*a.example*"))
|
|
self.assertFalse(ar._v2_wild("ECHO", "echo"), "matching is case-sensitive on Linux")
|
|
self.assertTrue(ar._v2_wild("anything", "*"))
|
|
|
|
def test_the_two_matchers_ask_the_same_question(self):
|
|
# the guard line (relay) and the installer's verification (oc-merge-limits) answer one
|
|
# security question about the same rules: one grammar (finding 7)
|
|
import importlib.util
|
|
spec = importlib.util.spec_from_file_location(
|
|
"ocml", Path(ar.__file__).resolve().parents[1] / "oc-merge-limits.py")
|
|
ocml = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(ocml)
|
|
for text, pattern in (("curl https://oss-cn-hangzhou.aliyuncs.com/x", "*aliyuncs.com*"),
|
|
("echo 169.254.169.254", "*169.254.169.254*"),
|
|
("a?b", "a?b"), ("axb", "a?b"), ("axxb", "a?b"),
|
|
("literal star", r"literal\*star"), ("literalstar", r"literal\*star"),
|
|
("", "*"), ("x", "")):
|
|
with self.subTest(text=text, pattern=pattern):
|
|
self.assertEqual(ar._v2_wild(text, pattern), ocml._wild(text, pattern))
|
|
|
|
def test_the_guard_line_probes_what_the_installer_probes(self):
|
|
# a later allow written with a ? wildcard must not read as safe to the cockpit while the
|
|
# installer calls it wrong (finding 7): same probes, one table
|
|
import importlib.util
|
|
spec = importlib.util.spec_from_file_location(
|
|
"ocml", Path(ar.__file__).resolve().parents[1] / "oc-merge-limits.py")
|
|
ocml = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(ocml)
|
|
probes = ocml.deny_probes()
|
|
self.assertEqual(probes, [p.replace("*", "x") for p in ocml.DENY_BASH])
|
|
ours = [{"action": "shell", "resource": p, "effect": "deny"} for p in ocml.DENY_BASH]
|
|
doc = {"type": "document", "info": {"permissions": [
|
|
{"action": "*", "resource": "*", "effect": "allow"}, *ours,
|
|
{"action": "shell", "resource": "*aliyuncs.co?*", "effect": "allow"}]}}
|
|
st = ar.config_docs_auto_state([doc], probes)
|
|
self.assertFalse(st["deny_ok"], "the ? allow (co + one character) re-opens what the deny closed")
|
|
st = ar.config_docs_auto_state([doc], ocml.DENY_BASH)
|
|
self.assertFalse(st["deny_ok"], "probing the raw pattern too must not call it safe either")
|
|
|
|
def test_config_docs_auto_state(self):
|
|
d = lambda perms, path="/f.json": {"type": "document", "path": path,
|
|
"info": {"permissions": perms}}
|
|
guard = [{"action": "shell", "resource": "*a.example*", "effect": "deny"}]
|
|
# the unit's injected content (the document with no path) allows all, its own
|
|
# denies come last: auto, and the guard holds
|
|
entries = [d(guard, path="/f.json"),
|
|
d([{"action": "*", "resource": "*", "effect": "allow"}] + guard, path=None)]
|
|
self.assertEqual(ar.config_docs_auto_state(entries, ["*a.example*"]),
|
|
{"auto": True, "deny_ok": True})
|
|
# allow * without our denies after it: the guard was overridden
|
|
self.assertEqual(ar.config_docs_auto_state(
|
|
[d([{"action": "*", "resource": "*", "effect": "allow"}], path=None)],
|
|
["*a.example*"]), {"auto": True, "deny_ok": False})
|
|
# a later rule allowing the guarded host wins over ours (last match): not deny_ok
|
|
self.assertEqual(ar.config_docs_auto_state(
|
|
[d([{"action": "*", "resource": "*", "effect": "allow"}] + guard
|
|
+ [{"action": "shell", "resource": "*a.example*", "effect": "allow"}], path=None)],
|
|
["*a.example*"]), {"auto": True, "deny_ok": False})
|
|
# nothing matching a shell call: the server default is ask, so not auto
|
|
self.assertEqual(ar.config_docs_auto_state([d(guard)], ["*a.example*"]),
|
|
{"auto": False, "deny_ok": True})
|
|
# directory entries (no info) are skipped, unknown effects never match
|
|
self.assertEqual(ar.config_docs_auto_state(
|
|
[{"type": "directory", "path": "/x"}, d(guard),
|
|
d([{"action": "shell", "resource": "*", "effect": "yes-please"}])],
|
|
["*a.example*"]), {"auto": False, "deny_ok": True})
|
|
for bad in ([], None, ["x"], [d("not-a-list")], [{"type": "document", "info": 3}]):
|
|
self.assertIsNone(ar.config_docs_auto_state(bad, []), bad)
|
|
# no pattern to check (the guard's module could not be read): nothing proves the guards, so deny_ok is None,
|
|
# never True; auto is still read
|
|
for none in (None, []):
|
|
self.assertEqual(ar.config_docs_auto_state([d(guard)], none), {"auto": False, "deny_ok": None})
|
|
|
|
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"))
|
|
ae = dict(ar.forward_request_headers([("Accept-Encoding", "gzip")], "u:1", "Basic x"))
|
|
self.assertEqual(ae["Accept-Encoding"], "gzip", "forwarded by default, as before the v2 migration")
|
|
aes = dict(ar.forward_request_headers([("Accept-Encoding", "gzip")], "u:1", "Basic x", secret=True))
|
|
self.assertNotIn("Accept-Encoding", aes, "dropped where the relay reads the answer to scrub it")
|
|
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
|
|
# 100.100 to 100.119, the regex's branch the reference box's own address is in, with an address no box has
|
|
iface = "8: tailscale0 inet 100.101.0.7/32 scope global tailscale0\\ valid_lft forever\n"
|
|
self.assertEqual(ar.tailscale_ipv4(lambda *a, **k: R(iface)), "100.101.0.7")
|
|
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)
|