Files
alzeo/tests/test_uninstall_opencode.py
T
Hasan BasbunarandClaude Fable 5.2 cf7c07798a opencode guard: the report's hosts are denied to webfetch too, on both majors
Since v1.40.4 the box's opencode configs deny a shell command naming an Alibaba Cloud host or a
cloud metadata address. On 2026-11-21 the same kind of request left this box as a webfetch tool
call, twice, which no shell rule sees (decision 1561). The same three patterns are now written
for the webfetch tool.

1.x: a block "webfetch*" after "bash*" at the end of "permission" (the plain key "webfetch"
cannot hold an object: 1.19.5 refuses the config), and "*webfetch" after "*bash" in the unit's
OPENCODE_PERMISSION. A block already last and intact is not rewritten, so a box of an earlier
release gets "webfetch*" after its "bash*" and nothing else of its file moves. A block the person
set to one action is theirs: "deny" stands while no key after it speaks for the tool again,
anything else is said (rc 1) and the other block is written still.

2.x: three webfetch rules after the three shell ones, in "permissions" and in the unit's
OPENCODE_CONFIG_CONTENT. A box that served 2.x on v1.56.0 gets the three new rules once; the
rollback to 1.x and the uninstall recognise both shapes of the array, and an empty array is the
person's, not ours.

The unit's values stay this repo's rules alone. On OpenCode 2 the unit's allow overrides every
deny rule of the person's own configs (the content merges after every file): the install's note
said "unless your config has one after it", which no file can have, and now says what happens.

Measured on the real binaries against a scripted endpoint asking for a webfetch whose URL names
aliyuncs.com and points at 127.0.0.1: 1.19.5 and 1.19.6 fetch it with no rule and refuse it with
"webfetch*" and with "*webfetch"; 2.3.2 fetches it under the wildcard allow alone and answers
permission.rejected with the rule after it. Tests red on the old code, green now.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 15:45:10 +01:00

220 lines
13 KiB
Python

#!/usr/bin/env python3
"""uninstall.sh --yes must not leave opencode unable to start.
The providers install.sh writes read the API key through a {file:} reference, and
opencode refuses to start at all, every provider included, while one points at a file
that is gone ("bad file reference", opencode 1.18.32, reference box 2026-09-23). --yes
deletes that file, and since v1.18.4 every fresh box gets such a config. These run the
uninstaller's own lines, as written, in a throwaway HOME."""
import json
import re
import os
import pathlib
import shutil
import subprocess
import tempfile
import unittest
REPO = pathlib.Path(__file__).resolve().parents[1]
UNINSTALL = REPO / "uninstall.sh"
def purge_block() -> str:
text = UNINSTALL.read_text()
start = text.index('if [ "$PURGE_CONFIG" -eq 1 ]; then\n # opencode refuses')
end = text.index("\nfi\n", text.index("they answer again after ./install.sh", start)) + 4
return text[start:end]
# what --deny-bash puts in the copy: the rules under their own key (oc-merge-limits.py deny_permission)
RULES = {"bash*": {"*aliyuncs.com*": "deny", "*169.254.169.254*": "deny", "*100.100.100.200*": "deny"},
"webfetch*": {"*aliyuncs.com*": "deny", "*169.254.169.254*": "deny", "*100.100.100.200*": "deny"}}
def box(key):
return {"npm": "@ai-sdk/openai-compatible",
"options": {"baseURL": "http://127.0.0.1:30001/v1", "apiKey": "{file:" + key + "}"},
"models": {"qwen3.8-27b": {"limit": {"context": 1000, "input": 1000, "output": 100}}}}
class UninstallLeavesOpencodeStartable(unittest.TestCase):
def run_it(self, user_cfg, purge):
home = pathlib.Path(tempfile.mkdtemp(prefix="un-oc-"))
cfg = home / ".config" / "qwen38"
cfg.mkdir(parents=True)
(cfg / "api-key").write_text("k\n")
oc = home / ".config" / "opencode" / "opencode.json"
if user_cfg is not None:
oc.parent.mkdir(parents=True)
oc.write_text(user_cfg(str(cfg / "api-key")))
cfgs = " ".join(f'"{oc.parent / n}"' for n in ("config.json", "opencode.json", "opencode.jsonc"))
script = (f'set -euo pipefail\nPURGE_CONFIG={purge}; CONFIG_DIR="{cfg}"; OC_USER_CFGS=({cfgs}); '
f'REPO_DIR="{REPO}"\n' + purge_block())
r = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=60,
env={"HOME": str(home), "PATH": "/usr/bin:/bin"})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
return r.stdout + r.stderr, home, cfg, oc
def test_the_copy_install_sh_made_goes_with_the_key(self):
mine = lambda k: json.dumps({"$schema": "https://opencode.ai/config.json", "autoupdate": "notify",
"provider": {"qwen38": box(k)}, "model": "qwen38/qwen3.8-27b",
"small_model": "qwen38/qwen3.8-27b"}, indent=2)
out, home, cfg, oc = self.run_it(mine, purge=1)
self.assertFalse(cfg.exists())
self.assertFalse(oc.exists())
self.assertIn("held only this box's providers (qwen38): moved to", out)
self.assertEqual(len(list(oc.parent.glob("opencode.json.bak-*"))), 1, "no backup was kept")
def test_the_copy_with_the_rules_goes_with_the_key_too(self):
# v1.40.4 puts the bash rules in the copy: it stayed, its provider gone and autoupdate off for good
# (found in review, 2026-10-29). Rules of the user's own keep the file.
for rules, gone in ((RULES, True), ({"bash*": {**RULES["bash*"], "rm -rf *": "deny"}}, False)):
with self.subTest(gone=gone):
mine = lambda k: json.dumps({"$schema": "https://opencode.ai/config.json", "autoupdate": False,
"provider": {"qwen38": box(k)}, "model": "qwen38/qwen3.8-27b",
"permission": rules}, indent=2)
out, home, cfg, oc = self.run_it(mine, purge=1)
self.assertEqual(oc.exists(), not gone, out)
if gone:
self.assertIn("held only this box's providers (qwen38): moved to", out)
else:
self.assertEqual(json.loads(oc.read_text())["permission"], rules)
def test_the_copy_a_v2_install_made_goes_with_the_key_too(self):
# review of v1.56.0, finding 3: a fresh OpenCode 2 install copies the generated config, with
# its v2 keys (permissions, policies, share, websearch, update), as the user's global config;
# the purge did not count those keys as ours, so the copy stayed, emptied of its provider.
# A value the user changed keeps the file.
import importlib.util
spec = importlib.util.spec_from_file_location("ocm", REPO / "oc-merge-limits.py")
ocm = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ocm)
# the values the purge counts as ours are the ones install.sh writes in the generated v2 config
install = (REPO / "install.sh").read_text()
for line in ('doc["policies"] = [{"action": "provider.use", "resource": "opencode", "effect": "deny"}]',
'doc["share"] = "disabled"', 'doc["websearch"] = False', 'doc["update"] = "disable"'):
self.assertIn(line, install, "install.sh and the purge must agree on the v2 keys")
for websearch, gone in ((False, True), (True, False)):
with self.subTest(gone=gone):
mine = lambda k: json.dumps({
"$schema": "https://opencode.ai/config.json", "provider": {"qwen38": box(k)},
"compaction": {"keep": {"tokens": 135000}, "background": True},
"model": "qwen38/qwen3.8-27b", "small_model": "qwen38/qwen3.8-27b",
"permission": RULES, "permissions": ocm.deny_permissions_v2(),
"policies": [{"action": "provider.use", "resource": "opencode", "effect": "deny"}],
"share": "disabled", "websearch": websearch, "update": "disable"}, indent=2)
out, home, cfg, oc = self.run_it(mine, purge=1)
self.assertEqual(oc.exists(), not gone, out)
if gone:
self.assertIn("held only this box's providers (qwen38): moved to", out)
else:
self.assertIs(json.loads(oc.read_text())["websearch"], True)
def test_the_copy_of_a_release_before_v157_goes_with_the_key_too(self):
# up to v1.56.0 the copy held the shell rules alone ("bash*" in 1.x, three shell rules in 2.x): a box
# uninstalled with this release's script, without an install of it in between, still holds that
# shape, and it is still this repo's copy, not the person's
import importlib.util
spec = importlib.util.spec_from_file_location("ocm", REPO / "oc-merge-limits.py")
ocm = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ocm)
shell_only = {"bash*": dict.fromkeys(ocm.DENY_BASH, "deny")}
for extra in ({"permission": shell_only},
{"permission": shell_only, "permissions": ocm.deny_permissions_v2_before_v157()}):
with self.subTest(keys=sorted(extra)):
mine = lambda k: json.dumps({"$schema": "https://opencode.ai/config.json", "autoupdate": False,
"provider": {"qwen38": box(k)}, "model": "qwen38/qwen3.8-27b",
**extra}, indent=2)
out, home, cfg, oc = self.run_it(mine, purge=1)
self.assertFalse(oc.exists(), out)
self.assertIn("held only this box's providers (qwen38): moved to", out)
def test_a_users_own_config_keeps_everything_but_the_box(self):
theirs = lambda k: json.dumps({"model": "qwen38/qwen3.8-27b", "plugin": ["x.js"],
"provider": {"qwen38": box(k), "anthropic": {}}})
out, home, cfg, oc = self.run_it(theirs, purge=1)
self.assertFalse(cfg.exists())
self.assertEqual(json.loads(oc.read_text()), {"plugin": ["x.js"], "provider": {"anthropic": {}}})
self.assertIn("removed the qwen38 provider", out)
def test_kept_config_says_the_providers_wait_for_a_reinstall(self):
theirs = lambda k: json.dumps({"provider": {"qwen38": box(k)}})
out, home, cfg, oc = self.run_it(theirs, purge=0)
self.assertTrue((cfg / "api-key").exists())
self.assertIn('"qwen38"', oc.read_text())
self.assertIn("still lists this box's providers", out)
def test_a_block_pasted_into_opencodes_own_jsonc_goes_too(self):
# opencode writes opencode.jsonc itself on its first start, so that is where a
# user following "merge the qwen38 block" may well have put it.
home = pathlib.Path(tempfile.mkdtemp(prefix="un-oc-"))
cfg = home / ".config" / "qwen38"
cfg.mkdir(parents=True)
(cfg / "api-key").write_text("k\n")
jsonc = home / ".config" / "opencode" / "opencode.jsonc"
jsonc.parent.mkdir(parents=True)
jsonc.write_text('{\n // mine\n "provider": {"qwen38": ' + json.dumps(box(str(cfg / "api-key")))
+ ', "x": {}}\n}\n')
cfgs = " ".join(f'"{jsonc.parent / n}"' for n in ("config.json", "opencode.json", "opencode.jsonc"))
r = subprocess.run(["bash", "-c", f'set -euo pipefail\nPURGE_CONFIG=1; CONFIG_DIR="{cfg}"; '
f'OC_USER_CFGS=({cfgs}); REPO_DIR="{REPO}"\n' + purge_block()],
capture_output=True, text=True, env={"HOME": str(home), "PATH": "/usr/bin:/bin"})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertNotIn("qwen38", jsonc.read_text())
self.assertIn("// mine", jsonc.read_text())
def test_a_cache_the_container_wrote_as_root_is_removed_quietly(self):
# A directory the user cannot write stands for the root-owned compile cache: the
# plain rm fails on it, and the fallback (a fake sudo here) removes the rest.
home = pathlib.Path(tempfile.mkdtemp(prefix="un-cache-"))
cfg = home / ".config" / "qwen38"
locked = cfg / "sglang-cache" / "inductor" / "yl"
locked.mkdir(parents=True)
(locked / "c.py").write_text("x")
locked.chmod(0o555)
fake = home / "bin"
fake.mkdir()
(fake / "sudo").write_text('#!/bin/sh\necho "sudo $*" >> "$HOME/sudo.log"\n'
'chmod -R u+w "$4" && exec "$@"\n')
(fake / "sudo").chmod(0o755)
cfgs = " ".join(f'"{home / ".config" / "opencode" / n}"' for n in ("config.json", "opencode.json", "opencode.jsonc"))
r = subprocess.run(["bash", "-c", f'set -euo pipefail\nPURGE_CONFIG=1; CONFIG_DIR="{cfg}"; '
f'OC_USER_CFGS=({cfgs}); REPO_DIR="{REPO}"\n' + purge_block()],
capture_output=True, text=True, env={"HOME": str(home), "PATH": f"{fake}:/usr/bin:/bin"})
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertFalse(cfg.exists())
self.assertNotIn("Permission", r.stdout + r.stderr)
self.assertEqual((home / "sudo.log").read_text(), f"sudo rm -rf --one-file-system {cfg}\n")
def test_no_opencode_config_is_no_opencode_line(self):
out, home, cfg, oc = self.run_it(None, purge=1)
self.assertEqual(out.strip(), "config removed.")
@unittest.skipUnless(shutil.which("opencode") or os.path.exists(os.path.expanduser("~/.opencode/bin/opencode")),
"needs a real opencode to show it starts")
def test_the_real_opencode_starts_after_the_purge(self):
theirs = lambda k: json.dumps({"provider": {"qwen38": box(k), "other": {"npm": "@ai-sdk/openai-compatible",
"options": {"baseURL": "http://127.0.0.1:9/v1"}, "models": {"m": {}}}}})
out, home, cfg, oc = self.run_it(theirs, purge=1)
binary = shutil.which("opencode") or os.path.expanduser("~/.opencode/bin/opencode")
# OpenCode 2 (the default since v1.56.0) takes no provider after `models` and prints its help
# for one; it lists every model, other/m among them. Without --standalone it starts its managed
# background service (`opencode serve --service`), which outlives the test and holds its port
# (measured on 2.3.2 the 2026-11-22); --standalone runs a server that ends with the command
# asked in the throwaway HOME too: OpenCode 2 writes its log file under HOME even for --version
# (measured on 2.3.2 the 2026-11-23), and asked with the suite's own HOME it left that file there:
# on a box that serves OpenCode 2, "The offline suite touches nothing outside itself" failed (the
# release CI of v1.56.0, on the reference box)
ver = subprocess.run([binary, "--version"], capture_output=True, text=True, timeout=60,
cwd=str(home), env={"HOME": str(home), "PATH": "/usr/bin:/bin"}).stdout
major = (re.findall(r"(\d+)\.\d+\.\d+", ver) or ["1"])[-1]
args = [binary, "models", "--standalone"] if major == "2" else [binary, "models", "other"]
r = subprocess.run(args, capture_output=True, text=True, timeout=120,
cwd=str(home), env={"HOME": str(home), "PATH": "/usr/bin:/bin"})
self.assertNotIn("bad file reference", r.stdout + r.stderr)
self.assertIn("other/m", r.stdout, r.stdout + r.stderr)
if __name__ == "__main__":
unittest.main(verbosity=2)