mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 20:34:17 +01:00
v2 migration: what the independent review found, fixed with tests that fail on the old code
- the flag parser is a while loop: ./install.sh --opencode 2 reaches the choice (the for-loop's shift let "2" fall to the catch-all and the whole opt-in was unreachable), and --opencode with no value is refused by the parser (finding 1) - a cross-major run whose pinned download fails keeps the box on the major it chose, serves nothing as the other major and writes no marker (finding 2) - the rollback to 1.x speaks: a foreign "permissions" array, which the merger of the box refuses to take out, is said with the way back rather than left to break OpenCode 1.19 in silence (finding 3) - install-agent.sh reads the box's opencode.major marker when the environment is empty: a standalone re-run (the retry hint, docs/cockpit.md) renders the profile the box serves (finding 4) - the relay asks for identity encoding (a gzip answer on a credential route could only be a 502 the browser never understands), classifies the secret paths on the NORMALIZED target (spelling walked around the scrub and the key reached the browser), and a JSON 200 that is not an object is unhealthy, not an exception out of the Agent panel (findings 5, 6, 8) - one matcher, one probe table: oc-permissions.py holds the server's grammar as measured on the 2.3.0 binary and read in its bundle (star, single-character question, literal brackets and dot, whole-text match), agent_relay._v2_wild and oc-merge-limits._wild both delegate to it, and the cockpit's guard line probes mod.deny_probes(), the installer's own texts (finding 7; the ? discovery means the old star-only relay matcher could have called a hijacked guard ok) - report: ~/qa-tools/wildcard-measure-report.md (agent-measured today, sandbox /var/tmp/oc2-230-wildcard) Tests: the argument loop, the stray-binary fallback, the rollback speech, the marker-standalone run, the two matchers' equality, the guard probes, the odd spellings, the identity ask, the lying gzip, the list-answer health. F10 (double import of the merger in cockpit) left as a proposal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
68d7829b50
commit
3fc3e68627
9 files changed
+444
-39
No files matched your search
+29
-18
@@ -18,6 +18,8 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import http.client
|
||||
import importlib.util
|
||||
import posixpath
|
||||
import http.server
|
||||
import json
|
||||
import re
|
||||
@@ -38,7 +40,11 @@ HOP_BY_HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authoriza
|
||||
# Request headers the relay never forwards: the cockpit session must not reach
|
||||
# opencode, the client's own Authorization is replaced by ours, Host and Origin name
|
||||
# the upstream, lengths are re-set, and the referrer says nothing about the cockpit.
|
||||
REQUEST_DROP = HOP_BY_HOP | {"host", "origin", "cookie", "authorization", "content-length", "referer"}
|
||||
# accept-encoding too: the relay reads the JSON of the credential routes to scrub it, and a gzip
|
||||
# answer it cannot verify is a 502 the browser would never understand (measured 2.3.0; independent
|
||||
# review of the v2 migration, finding 5: ask for identity, refuse only a server that lies anyway).
|
||||
REQUEST_DROP = HOP_BY_HOP | {"host", "origin", "cookie", "authorization", "content-length", "referer",
|
||||
"accept-encoding"}
|
||||
# Response headers the relay owns (Date and Server come from this server).
|
||||
RESPONSE_DROP = HOP_BY_HOP | {"content-length", "date", "server"}
|
||||
SESSION_COOKIE = "cockpit"
|
||||
@@ -209,8 +215,15 @@ def split_upstream(url: str) -> tuple[str, int]:
|
||||
|
||||
|
||||
def is_secret_path(path: str) -> bool:
|
||||
"""A path whose JSON answer can carry provider credentials."""
|
||||
p = path.split("?", 1)[0]
|
||||
"""A path whose JSON answer can carry provider credentials. Classified on the NORMALIZED target:
|
||||
opencode's router answers /./api/config, /api//config and /foo/../api/config as /api/config, so
|
||||
those spellings are exactly as secret (a raw match let them through unscrubbed; independent
|
||||
review of the v2 migration, finding 6)."""
|
||||
p = urllib.parse.unquote(path.split("?", 1)[0])
|
||||
if not p.startswith("/"):
|
||||
p = "/" + p
|
||||
p = posixpath.normpath(p)
|
||||
p = re.sub(r"/{2,}", "/", p) # normpath keeps a leading "//" (POSIX); the router does not
|
||||
return any(p == s or p.startswith(s + "/") for s in SECRET_PATHS)
|
||||
|
||||
|
||||
@@ -330,6 +343,8 @@ def health(cfg: RelayConfig, timeout: float = 3.0) -> dict:
|
||||
if "json" not in (resp.getheader("Content-Type") or "").lower():
|
||||
continue # the SPA page on a path this version does not know
|
||||
data = json.loads(raw or b"{}")
|
||||
if not isinstance(data, dict):
|
||||
return {"healthy": False, "error": f"{path} answered {type(data).__name__}, not an object"}
|
||||
if path == "/api/info":
|
||||
return {"healthy": True, "version": data.get("version")}
|
||||
return {"healthy": bool(data.get("healthy")), "version": data.get("version")}
|
||||
@@ -369,22 +384,18 @@ def permission_is_auto(permission) -> bool:
|
||||
return isinstance(permission, dict) and permission.get("*") == "allow"
|
||||
|
||||
|
||||
_OCP_SPEC = importlib.util.spec_from_file_location(
|
||||
"oc_permissions", str(Path(__file__).resolve().parents[1] / "oc-permissions.py"))
|
||||
_ocp = importlib.util.module_from_spec(_OCP_SPEC)
|
||||
_OCP_SPEC.loader.exec_module(_ocp)
|
||||
|
||||
|
||||
def _v2_wild(text: str, pattern: str) -> bool:
|
||||
"""OpenCode 2's wildcard (read in packages/core/src/util/wildcard.ts of v2.3.0): "*"
|
||||
matches any run of characters, every other character is itself. No fnmatch classes:
|
||||
a command with brackets must not match differently than the server would."""
|
||||
if "*" not in pattern:
|
||||
return text == pattern
|
||||
parts = pattern.split("*")
|
||||
if not text.startswith(parts[0]):
|
||||
return False
|
||||
rest = text[len(parts[0]):]
|
||||
for seg in parts[1:-1]:
|
||||
i = rest.find(seg)
|
||||
if i < 0:
|
||||
return False
|
||||
rest = rest[i + len(seg):]
|
||||
return rest.endswith(parts[-1])
|
||||
"""OpenCode 2's wildcard: THE server's reading, shared with oc-merge-limits.py so the guard line
|
||||
here and the installer's verification answer one question (measured on the 2.3.0 binary and read
|
||||
in its bundle the 2026-11-15: "*" any run, "?" exactly one character, brackets and dot literal,
|
||||
whole-text match; a review of the v2 migration found the two matchers had drifted, finding 7)."""
|
||||
return _ocp.server_match(text, pattern)
|
||||
|
||||
|
||||
def _v2_rule_matches(rule, action: str, resource: str) -> bool:
|
||||
|
||||
@@ -2620,7 +2620,7 @@ def collect_agent():
|
||||
if out["server"].get("healthy"):
|
||||
v = out["server"].get("version") or ""
|
||||
mod = _ocm_module()
|
||||
deny = list(mod.DENY_BASH) if mod is not None else None
|
||||
deny = list(mod.deny_probes()) if mod is not None else None # one table with the installer (review 7)
|
||||
if v.split(".")[0] == "2":
|
||||
# /config answers the HTML page on 2.x (a 200 that is not JSON), and its
|
||||
# effective rules are the documents /api/config lists, last match wins;
|
||||
|
||||
@@ -93,6 +93,11 @@ OC_MAJOR="$(printf '%s' "$OC_VERSION" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head
|
||||
# OPENCODE_MAJOR=2 down here. A stray 2.x found on the PATH (Homebrew Core's formula is
|
||||
# one) is still refused before anything renders, so the installed unit keeps the opencode
|
||||
# it runs (decision 455, 2026-10-22).
|
||||
# The box's own choice, read from its marker when ./install.sh did not pass it down: a standalone
|
||||
# re-run (the retry hint, docs/cockpit.md) must render the profile this box actually serves
|
||||
# (independent review of the v2 migration, finding 4).
|
||||
OPENCODE_MAJOR="${OPENCODE_MAJOR:-$(head -1 "$HOME/.config/qwen38/opencode.major" 2>/dev/null || true)}"
|
||||
OPENCODE_MAJOR="${OPENCODE_MAJOR:-1}"
|
||||
OC_PROFILE=1
|
||||
if [ -n "$OC_MAJOR" ] && [ "$OC_MAJOR" -ge 2 ]; then
|
||||
if [ "${OPENCODE_MAJOR:-1}" != "2" ]; then
|
||||
|
||||
@@ -7,6 +7,7 @@ import http.client
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import socketserver
|
||||
import struct
|
||||
@@ -35,6 +36,15 @@ def html_of(n: int) -> bytes:
|
||||
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
|
||||
|
||||
|
||||
@@ -81,7 +91,7 @@ class FakeOpencode(http.server.BaseHTTPRequestHandler):
|
||||
return
|
||||
if self.headers.get("Upgrade", "").lower() == "websocket":
|
||||
return self.websocket()
|
||||
path = self.path.split("?", 1)[0]
|
||||
path = _norm_target(self.path)
|
||||
if path == "/echo":
|
||||
return self._json({"method": "GET", "path": self.path, "headers": dict(self.headers.items())})
|
||||
if path == "/len":
|
||||
@@ -212,6 +222,16 @@ class FakeOpencode(http.server.BaseHTTPRequestHandler):
|
||||
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 "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"}},
|
||||
@@ -247,7 +267,7 @@ class FakeOpencode(http.server.BaseHTTPRequestHandler):
|
||||
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]
|
||||
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"))):
|
||||
@@ -548,7 +568,8 @@ class RelayTests(unittest.TestCase):
|
||||
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.assertNotIn("accept-encoding", h,
|
||||
"the relay asks for identity: a gzip answer on a credential route could only be refused (finding 5)")
|
||||
self.assertEqual(h["connection"], "close")
|
||||
|
||||
def test_response_headers_and_cookie_filter(self):
|
||||
@@ -849,6 +870,113 @@ class RelayTests(unittest.TestCase):
|
||||
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 the relay must not ASK for
|
||||
compression it would then refuse: no Accept-Encoding is forwarded on these GETs (independent
|
||||
review, finding 5)."""
|
||||
|
||||
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_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])
|
||||
|
||||
|
||||
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)
|
||||
@@ -859,6 +987,41 @@ class PureHelpers(unittest.TestCase):
|
||||
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", "literal\*star"), ("literalstar", "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}}
|
||||
|
||||
+16
-5
@@ -595,7 +595,8 @@ PLAN_ONLY=0
|
||||
# box gets (Hasan, 2026-10-17). The run for the other text lane and the side lanes' installers
|
||||
# read it as QWEN38_RECOMMENDED.
|
||||
RECOMMENDED="${QWEN38_RECOMMENDED:-0}"
|
||||
for arg in "$@"; do
|
||||
while [ $# -gt 0 ]; do
|
||||
arg="$1"; shift
|
||||
case "$arg" in
|
||||
--plan) PLAN_ONLY=1 ;;
|
||||
--recommended) RECOMMENDED=1 ;;
|
||||
@@ -603,7 +604,8 @@ for arg in "$@"; do
|
||||
--no-service) NO_SERVICE=1 ;;
|
||||
--no-opencode) NO_OPENCODE=1 ;;
|
||||
--with-opencode) WITH_OPENCODE=1 ;;
|
||||
--opencode) OPENCODE_MAJOR_WANT="${2:-}"; shift ;;
|
||||
--opencode) if [ $# -gt 0 ]; then OPENCODE_MAJOR_WANT="$1"; shift
|
||||
else printf -- '--opencode takes 1 or 2 (which OpenCode to serve)\n' >&2; exit 1; fi ;;
|
||||
--no-cockpit) NO_COCKPIT=1 ;;
|
||||
--with-cockpit) WITH_COCKPIT=1 ;;
|
||||
--with-image) WITH_IMAGE=1 ;;
|
||||
@@ -2729,8 +2731,12 @@ elif [ -n "$OC_HAVE" ] && [ "${OC_HAVE%%.*}" != "${OPENCODE_MAJOR:-1}" ]; then
|
||||
[ -n "$OC_ON_PATH" ] && echo " NOTE: a shell finds $OC_ON_PATH first: the Agent unit and this run take"
|
||||
[ -n "$OC_ON_PATH" ] && echo " the installed copy at ~/.opencode/bin; keep only one OpenCode 2 on the PATH"
|
||||
else
|
||||
echo " opencode stays at $OC_HAVE, and this run serves it as the OpenCode it is."
|
||||
OPENCODE_MAJOR="${OC_HAVE%%.*}"
|
||||
# the choice wins both ways: a run that could not download neither installs the pin nor starts
|
||||
# serving the found binary as the OTHER major (it would render the wrong unit around it and
|
||||
# write a marker nobody asked for) (independent review of the v2 migration, finding 2)
|
||||
echo " $OC_TARGET_VER could not come down: this run keeps the box on the OpenCode it chose"
|
||||
echo " (${OPENCODE_MAJOR:-1}.x), serves nothing as the other major, and writes no marker."
|
||||
echo " The Agent tab stays down until $OC_TARGET_VER installs: re-run ./install.sh once GitHub is reachable."
|
||||
fi
|
||||
elif [ -z "$OC_FOUND" ] || { [ "$OC_FOUND" -ef "$OC_HOME_BIN" ] && ver_lt "$OC_HAVE" "$OC_TARGET_VER"; }; then
|
||||
if [ -z "$OC_FOUND" ]; then
|
||||
@@ -2790,7 +2796,12 @@ fi
|
||||
# V1", measured against the box's 1.19.5 on 2026-11-14). --remove-permissions only touches
|
||||
# the array this repo wrote; a person's own table is left alone.
|
||||
if [ "${OPENCODE:-1}" -eq 1 ] && [ "${OPENCODE_MAJOR:-1}" != 2 ] && [ -f "$HOME/.config/opencode/opencode.json" ]; then
|
||||
python3 "$REPO_DIR/oc-merge-limits.py" "$HOME/.config/opencode/opencode.json" --remove-permissions >/dev/null 2>&1 || true
|
||||
if ! OC_RM="$(python3 "$REPO_DIR/oc-merge-limits.py" "$HOME/.config/opencode/opencode.json" --remove-permissions 2>&1)"; then
|
||||
echo "NOTE: $OC_RM"
|
||||
echo " OpenCode 1.19 refuses to start while a config holds \"permissions\": that array is not the one"
|
||||
echo " this repo wrote, so it was left alone. Take it out of $HOME/.config/opencode/opencode.json by"
|
||||
echo " hand, or stay on OpenCode 2 with ./install.sh --opencode 2 (docs/opencode.md)."
|
||||
fi
|
||||
fi
|
||||
# The rest of this run (the Agent tab's unit, the oc launcher) finds opencode on PATH, and
|
||||
# a first install puts it in the shell's PATH the way opencode's own installer does.
|
||||
|
||||
+21
-6
@@ -524,10 +524,25 @@ def merge_autoupdate(path: str, value) -> int:
|
||||
DENY_BASH = ("*aliyuncs.com*", "*169.254.169.254*", "*100.100.100.200*")
|
||||
|
||||
|
||||
import importlib.util as _ilu
|
||||
import pathlib as _pl
|
||||
_OCP_SPEC = _ilu.spec_from_file_location("oc_permissions",
|
||||
str(_pl.Path(__file__).resolve().parent / "oc-permissions.py"))
|
||||
_ocp = _ilu.module_from_spec(_OCP_SPEC)
|
||||
_OCP_SPEC.loader.exec_module(_ocp)
|
||||
|
||||
|
||||
def _wild(text: str, pattern: str) -> bool:
|
||||
"""opencode's permission wildcard: * any run of characters, ? one, the rest literal."""
|
||||
rx = "".join(".*" if c == "*" else "." if c == "?" else re.escape(c) for c in pattern)
|
||||
return re.fullmatch(rx, text, re.S) is not None
|
||||
"""opencode's permission wildcard: THE reading of the server, in oc-permissions.py, shared with
|
||||
dashboard/agent_relay.py so the guard line and this verification ask one question (review 7)."""
|
||||
return _ocp.server_match(text, pattern)
|
||||
|
||||
|
||||
def deny_probes() -> list:
|
||||
"""Command texts that stand for the DENY_BASH patterns: what this file's verification and the
|
||||
cockpit's guard line evaluate the rules against (one table, review 7). A needle only inside a
|
||||
command's comment is not resource text (measured on 2.3.0): these texts carry it for real."""
|
||||
return [pt.replace("*", "x") for pt in DENY_BASH]
|
||||
|
||||
|
||||
def _bash_action(permission, command: str):
|
||||
@@ -696,9 +711,9 @@ def _v2_action(permissions, action: str, resource: str):
|
||||
|
||||
|
||||
def _deny_permissions_wrong(permissions) -> list:
|
||||
"""The DENY_BASH patterns the array does not deny for the v2 shell tool."""
|
||||
return [p for p in DENY_BASH
|
||||
if _v2_action(permissions, "shell", p.replace("*", "x")) != "deny"]
|
||||
"""The DENY_BASH patterns the array does not deny for the v2 shell tool, named by their pattern."""
|
||||
return [pat for pat, probe in zip(DENY_BASH, deny_probes())
|
||||
if _v2_action(permissions, "shell", probe) != "deny"]
|
||||
|
||||
|
||||
def _verify_deny_permissions(path: str) -> str:
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""The OpenCode 2 permission matcher, as its server applies it.
|
||||
|
||||
Measured on the box's 2.3.0 binary and read in its bundle on 2026-11-15 (the case table in
|
||||
~/qa-tools/wildcard-measure-report.md): backslashes read as slashes on both sides, "*" matches any
|
||||
run, "?" matches EXACTLY one character, everything else is itself, the dot and the brackets
|
||||
included (a deny for "*co[nm]*" therefore matches only a command that writes those brackets), and
|
||||
the pattern must cover the whole command text (a bare "aliyuncs.com" matches nothing longer).
|
||||
"*" crosses newlines. A pattern ending " .*" also matches without the space and what follows it
|
||||
(measured: "git *" matches "git" alone), which is opencode's own convenience for tool prefixes.
|
||||
|
||||
ONE reading, used by both halves of the guard (independent review of the v2 migration, finding 7):
|
||||
oc-merge-limits.py verifies at install time that our exfiltration denies still deny, and
|
||||
dashboard/agent_relay.py answers the cockpit's guard line from what the server says it serves. Two
|
||||
matchers had drifted (the relay read "?" as literal, the merger as a wildcard) and probed different
|
||||
strings, so the same security question got two answers."""
|
||||
import re
|
||||
|
||||
|
||||
def server_match(text, pattern) -> bool:
|
||||
a = str(text).replace("\\", "/")
|
||||
s = str(pattern).replace("\\", "/")
|
||||
# the server's own class of characters to keep literal, then the two wildcards
|
||||
s = "".join("\\" + c if c in ".+^${}()|[]\\" else c for c in s)
|
||||
s = s.replace("*", ".*").replace("?", ".")
|
||||
if s.endswith(" .*"):
|
||||
s = s[:-3] + "( .*)?"
|
||||
return re.fullmatch(s, a, re.S) is not None
|
||||
@@ -10,7 +10,6 @@ its env file rewritten, password kept), and answers JSON on /api/info where /glo
|
||||
serves the HTML page (a probe that takes any 200 for health would certify a dead server).
|
||||
The unit is rendered for real: the whole script runs up to the relay proof, with the
|
||||
systemd calls and curl stubbed in a PATH of the test."""
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -21,6 +20,7 @@ REPO = pathlib.Path(__file__).resolve().parents[1]
|
||||
SCRIPT_TEXT = (REPO / "dashboard/install-agent.sh").read_text()
|
||||
TEMPLATE = (REPO / "dashboard/opencode-web.service.template").read_text()
|
||||
MERGER = (REPO / "oc-merge-limits.py").read_text()
|
||||
PERMS = (REPO / "oc-permissions.py").read_text()
|
||||
STOP = "# ── the cockpit gets the relay"
|
||||
SENTINEL_PW = "sentinel-password-keep-me"
|
||||
GUARD_HOST = "aliyuncs" + ".com" # never as one string: our own session guard
|
||||
@@ -65,7 +65,8 @@ exit 0
|
||||
"""
|
||||
|
||||
|
||||
def run_agent(t, version_line, oc2, env_extra=None, pre_env_file=True, installed_extra="", curl_body=None):
|
||||
def run_agent(t, version_line, oc2, env_extra=None, pre_env_file=True, installed_extra="", curl_body=None,
|
||||
no_major=False):
|
||||
"""Run the whole install-agent script (unit render + health, no relay proof) in t."""
|
||||
sub = t / "sub"
|
||||
sub.mkdir(exist_ok=True)
|
||||
@@ -74,6 +75,7 @@ def run_agent(t, version_line, oc2, env_extra=None, pre_env_file=True, installed
|
||||
SCRIPT_TEXT[:SCRIPT_TEXT.index(STOP)].replace("/etc/systemd/system", str(t)))
|
||||
(sub / "opencode-web.service.template").write_text(TEMPLATE)
|
||||
(t / "oc-merge-limits.py").write_text(MERGER)
|
||||
(t / "oc-permissions.py").write_text(PERMS) # the merger loads its sibling, the server matcher
|
||||
for name, body in (("curl", curl_body or CURL_STUB), ("systemctl", SYSTEMCTL_STUB),
|
||||
("tailscale", "#!/bin/sh\nexit 1\n"), ("opencode", agent_stub(version_line)),
|
||||
("sudo", '#!/bin/sh\nexec "$@"\n')):
|
||||
@@ -98,12 +100,38 @@ def run_agent(t, version_line, oc2, env_extra=None, pre_env_file=True, installed
|
||||
"OPENCODE_MAJOR": "2" if oc2 else "1"}
|
||||
if env_extra:
|
||||
env.update(env_extra)
|
||||
if no_major:
|
||||
del env["OPENCODE_MAJOR"]
|
||||
r = subprocess.run(["bash", str(sub / "install-agent.sh")], capture_output=True, text=True,
|
||||
timeout=120, cwd=sub, env=env)
|
||||
unit = (t / "opencode-web.service")
|
||||
return r, (unit.read_text() if unit.is_file() else "")
|
||||
|
||||
|
||||
class TheMarkerDecidesStandaloneRuns(unittest.TestCase):
|
||||
"""./dashboard/install-agent.sh run on its own (the retry hint, docs/cockpit.md) has no
|
||||
OPENCODE_MAJOR from ./install.sh: the marker that --opencode 2 wrote decides the profile
|
||||
(independent review of the v2 migration, finding 4)."""
|
||||
|
||||
def setUp(self):
|
||||
self.t = pathlib.Path(tempfile.mkdtemp(prefix="agent-marker-"))
|
||||
self.addCleanup(shutil.rmtree, self.t, True)
|
||||
|
||||
def test_a_box_marked_2_renders_the_v2_unit_without_the_environment(self):
|
||||
cfg = self.t / ".config" / "qwen38"
|
||||
cfg.mkdir(parents=True, exist_ok=True)
|
||||
(cfg / "opencode.major").write_text("2\n# asked with ./install.sh --opencode 2\n")
|
||||
r, unit = run_agent(self.t, "opencode v2.3.0", oc2=True, no_major=True)
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
line = next(ln for ln in unit.splitlines() if ln.startswith("ExecStart="))
|
||||
self.assertIn("--log-level info", line, "the v2 profile came from the marker")
|
||||
|
||||
def test_no_marker_means_one_x_and_a_stray_two_x_is_refused_as_before(self):
|
||||
r, unit = run_agent(self.t, "opencode v2.3.0", oc2=True, no_major=True)
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertIn("did not choose", r.stdout + r.stderr)
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.t = pathlib.Path(tempfile.mkdtemp(prefix="agent-render-"))
|
||||
@@ -131,7 +159,7 @@ class Render(unittest.TestCase):
|
||||
self.assertTrue(0 < auto.index('"effect":"allow"') < auto.rindex('"effect":"deny"'),
|
||||
"allow first, denies last: last match wins in 2.x")
|
||||
self.assertIn(f"*{GUARD_HOST}*", auto)
|
||||
self.assertIn(f"AGENT_AUTO=1 on OpenCode 2", r.stdout)
|
||||
self.assertIn("AGENT_AUTO=1 on OpenCode 2", r.stdout)
|
||||
# the env file now names the username OpenCode 2 hardcodes, password kept
|
||||
env = (self.t / ".config" / "qwen38" / "opencode-web.env").read_text()
|
||||
self.assertIn("OPENCODE_SERVER_USERNAME=opencode", env)
|
||||
|
||||
@@ -39,14 +39,32 @@ cp "$OC_TARBALL" "$out"
|
||||
"""
|
||||
|
||||
|
||||
def block() -> str:
|
||||
def block(whole: bool = False) -> str:
|
||||
text = INSTALL.read_text()
|
||||
start = text.index('OC_HOME_BIN="$HOME/.opencode/bin/opencode"')
|
||||
if whole:
|
||||
# through the marker and the rollback to 1.x, the two steps the chain hands over to (v2 migration)
|
||||
return text[start:text.index("# The rest of this run (the Agent tab", start)]
|
||||
tail = text.index('echo "added ~/.opencode/bin to your PATH', start)
|
||||
end = text.index("\n fi\nfi\n", tail) + len("\n fi\nfi\n")
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def argloop() -> str:
|
||||
"""install.sh's own flag parser: from the RECOMMENDED line to the done that closes its loop."""
|
||||
text = INSTALL.read_text()
|
||||
start = text.index('RECOMMENDED="${QWEN38_RECOMMENDED:-0}"')
|
||||
end = text.index("\ndone\n", start) + len("\ndone\n")
|
||||
return text[start:end]
|
||||
|
||||
|
||||
def rollback() -> str:
|
||||
"""install.sh's own lines that take OUR v2 array out when the box goes back to 1.x."""
|
||||
text = INSTALL.read_text()
|
||||
start = text.index('# Going back to 1.x takes OUR v2 deny array')
|
||||
return text[start:text.index("# The rest of this run (the Agent tab", start)]
|
||||
|
||||
|
||||
def pinned_default() -> str:
|
||||
import re
|
||||
return re.search(r'^OPENCODE_VERSION="\$\{OPENCODE_VERSION:-([0-9.]+)\}"', INSTALL.read_text(), re.M).group(1)
|
||||
@@ -81,11 +99,11 @@ class TheOpencodePin(unittest.TestCase):
|
||||
(where / "VERSION").write_text(version + "\n")
|
||||
return where / "opencode"
|
||||
|
||||
def run_block(self, *, path_extra=(), pin="1", sha=None, env_version="", env_sha=""):
|
||||
def run_block(self, *, path_extra=(), pin="1", sha=None, env_version="", env_sha="", whole=False):
|
||||
script = ("set -euo pipefail\ndie(){ echo \"DIE: $*\"; exit 1; }\n"
|
||||
f'OPENCODE_VERSION="{PINNED}"; OPENCODE_SHA256="{sha or self.sha}"; OPENCODE_PIN="{pin}"\n'
|
||||
f'_ENV_OPENCODE_VERSION="{env_version}"; _ENV_OPENCODE_SHA256="{env_sha}"\n'
|
||||
+ block() + 'echo "PATH_AFTER=$PATH"\n')
|
||||
+ block(whole) + 'echo "PATH_AFTER=$PATH"\n')
|
||||
path = ":".join([str(self.bin), *map(str, path_extra), "/usr/bin", "/bin"])
|
||||
r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=60,
|
||||
env={"HOME": str(self.home), "PATH": path, "OC_LOG": str(self.log),
|
||||
@@ -265,6 +283,102 @@ class TheOpencodePin(unittest.TestCase):
|
||||
self.assertIn("needs OPENCODE_SHA256 too", r.stdout)
|
||||
|
||||
|
||||
class TheStrayBinaryNeverOptsIn(unittest.TestCase):
|
||||
"""A box that chose OpenCode 1 is never switched to 2 by a binary it did not ask for: when the
|
||||
pinned download cannot run (GitHub unreachable, sha mismatch), the choice stands and the marker
|
||||
is not written (independent review of the v2 migration, finding 2)."""
|
||||
|
||||
def setUp(self):
|
||||
self.t = pathlib.Path(tempfile.mkdtemp(prefix="oc-stray-"))
|
||||
self.addCleanup(shutil.rmtree, self.t, True)
|
||||
self.home = self.t / "home"
|
||||
self.home.mkdir()
|
||||
(self.home / ".bashrc").write_text("# a user's bashrc\n")
|
||||
self.bin = self.t / "fakebin"
|
||||
self.bin.mkdir()
|
||||
(self.bin / "curl").write_text(FAKE_CURL)
|
||||
(self.bin / "curl").chmod(0o755)
|
||||
self.log = self.t / "calls.log"
|
||||
buf = io.BytesIO()
|
||||
with tarfile.open(fileobj=buf, mode="w:gz") as tf:
|
||||
body = f"#!/bin/sh\n[ \"$1\" = --version ] && echo {PINNED}\n".encode()
|
||||
info = tarfile.TarInfo("opencode"); info.size = len(body); info.mode = 0o755
|
||||
tf.addfile(info, io.BytesIO(body))
|
||||
self.tarball = self.t / "asset.tar.gz"
|
||||
self.tarball.write_bytes(buf.getvalue())
|
||||
self.sha = hashlib.sha256(buf.getvalue()).hexdigest()
|
||||
self.brew = self.t / "brew"
|
||||
self.brew.mkdir()
|
||||
(self.brew / "opencode").write_text(FAKE_OC)
|
||||
(self.brew / "opencode").chmod(0o755)
|
||||
(self.brew / "VERSION").write_text("2.3.0\n")
|
||||
|
||||
def run_home(self, *, sha, major_env=None):
|
||||
script = ("set -euo pipefail\ndie(){ echo \"DIE: $*\"; exit 1; }\n"
|
||||
f'OPENCODE_VERSION="{PINNED}"; OPENCODE_SHA256="{sha}"; OPENCODE_PIN="1"\n'
|
||||
f'OPENCODE2_VERSION="2.3.0"; OPENCODE2_SHA256="{"0" * 64}"\n'
|
||||
f'_ENV_OPENCODE_VERSION=""; _ENV_OPENCODE_SHA256=""\n'
|
||||
+ (f'OPENCODE_MAJOR="{major_env}"\n' if major_env else "")
|
||||
+ block(whole=True) + 'echo "CHOICE=${OPENCODE_MAJOR:-1}"\n')
|
||||
path = ":".join([str(self.bin), str(self.brew), "/usr/bin", "/bin"])
|
||||
r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=60,
|
||||
env={"HOME": str(self.home), "PATH": path, "OC_LOG": str(self.log),
|
||||
"OC_TARBALL": str(self.tarball)})
|
||||
return r.returncode, r.stdout + r.stderr
|
||||
|
||||
def test_a_failed_fetch_keeps_the_choice_1_and_writes_no_marker(self):
|
||||
rc, out = self.run_home(sha="0" * 64) # the download answers the wrong bytes
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("CHOICE=1", out)
|
||||
self.assertFalse((self.home / ".config" / "qwen38" / "opencode.major").exists(),
|
||||
"a run that could not download never opts a box into OpenCode 2")
|
||||
self.assertIn("keeps the box on the OpenCode it chose", out)
|
||||
|
||||
def test_the_choice_2_box_with_a_1_x_binary_keeps_its_choice_too(self):
|
||||
(self.brew / "VERSION").write_text("1.19.0\n")
|
||||
rc, out = self.run_home(sha="0" * 64, major_env="2")
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("CHOICE=2", out)
|
||||
self.assertFalse((self.home / ".config" / "qwen38" / "opencode.major").exists(),
|
||||
"no marker for a binary that is not the pinned 2.x either")
|
||||
|
||||
|
||||
class TheRollbackSpeaks(unittest.TestCase):
|
||||
"""./install.sh back on 1.x takes OUR v2 "permissions" out; when the array is not ours it says
|
||||
so plainly: OpenCode 1.19 refuses to start while the config holds "permissions", and a silent
|
||||
refusal left the Agent tab dead with no reason on screen (independent review, finding 3)."""
|
||||
|
||||
def run_rollback(self, doc):
|
||||
t = pathlib.Path(tempfile.mkdtemp(prefix="oc-rollback-"))
|
||||
self.addCleanup(shutil.rmtree, t, True)
|
||||
home = t / "home"
|
||||
(home / ".config" / "opencode").mkdir(parents=True)
|
||||
(home / ".config" / "opencode" / "opencode.json").write_text(json.dumps(doc))
|
||||
script = ("set -euo pipefail\ndie(){ echo \"DIE: $*\"; exit 1; }\n"
|
||||
f'REPO_DIR="{REPO}"\n' + rollback())
|
||||
r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=60,
|
||||
env={"HOME": str(home), "PATH": "/usr/bin:/bin"})
|
||||
left = json.loads((home / ".config" / "opencode" / "opencode.json").read_text())
|
||||
return r.returncode, r.stdout + r.stderr, left
|
||||
|
||||
def test_our_array_is_taken_out_in_silence(self):
|
||||
ours = {"permissions": [{"action": "shell", "resource": "*" + "aliyuncs" + ".com*", "effect": "deny"},
|
||||
{"action": "shell", "resource": "*169.254.169.254*", "effect": "deny"},
|
||||
{"action": "shell", "resource": "*100.100.100.200*", "effect": "deny"}]}
|
||||
rc, out, left = self.run_rollback(ours)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertNotIn("permissions", left)
|
||||
self.assertNotIn("NOTE", out)
|
||||
|
||||
def test_a_foreign_array_is_left_and_said_with_the_way_back(self):
|
||||
foreign = {"permissions": [{"action": "shell", "resource": "*", "effect": "allow"}]}
|
||||
rc, out, left = self.run_rollback(foreign)
|
||||
self.assertEqual(rc, 0, out)
|
||||
self.assertIn("permissions", left, "the merger of the box only removes the array this repo wrote")
|
||||
self.assertIn("NOTE", out)
|
||||
self.assertIn("opencode.json", out)
|
||||
self.assertIn("permissions", out)
|
||||
|
||||
class TheConfigStopsSelfUpdating(unittest.TestCase):
|
||||
"""autoupdate false: with any other value opencode 1.19 offers OpenCode 2 on its TUI's
|
||||
home screen once it is on the newest 1.x (1.18.35, as soon as GitHub's latest release is
|
||||
@@ -597,3 +711,34 @@ class AFreshBoxGetsAConfigOpencodeCanUse(unittest.TestCase):
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
|
||||
|
||||
class TheOpencodeMajorFlag(unittest.TestCase):
|
||||
"""./install.sh --opencode 2|1 is the whole opt-in; the parser must consume its value
|
||||
(independent review of the v2 migration, finding 1: the for-loop's shift never did)."""
|
||||
|
||||
def run_args(self, *args):
|
||||
script = ("set -euo pipefail\ndie(){ echo \"DIE: $*\"; exit 1; }\nOPENCODE_MAJOR_WANT=\"\"\n"
|
||||
+ argloop() + 'echo "WANT=$OPENCODE_MAJOR_WANT"\n')
|
||||
return subprocess.run(["bash", "-c", script, "install.sh", *args], capture_output=True,
|
||||
text=True, timeout=30, env={"PATH": "/usr/bin:/bin", "HOME": "/nonexistent-home"})
|
||||
|
||||
def test_the_two_word_form_reaches_the_choice(self):
|
||||
r = self.run_args("--opencode", "2")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertNotIn("Unknown flag", r.stdout + r.stderr)
|
||||
self.assertIn("WANT=2", r.stdout)
|
||||
|
||||
def test_a_foreign_value_is_carried_to_the_validator_not_read_as_a_flag(self):
|
||||
r = self.run_args("--opencode", "3", "--recommended")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertIn("WANT=3", r.stdout) # ./install.sh itself refuses it further down (test_a_value...)
|
||||
|
||||
def test_a_missing_value_is_refused_by_the_parser(self):
|
||||
r = self.run_args("--opencode")
|
||||
self.assertNotEqual(r.returncode, 0)
|
||||
self.assertIn("--opencode takes 1 or 2", r.stdout + r.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user