fix(hub): runner runs operator rows in the operator's shell and closes them only when the host check passes
A hub-run operator row ran under bash -c with PATH=/usr/bin:/bin, so a command that works in the operator's terminal (aliases, PATH additions) failed there, and exit 0 closed the row whatever its check, because the hub cannot read the host's repos, PATH and installed dirs. The runner now runs the signed text as $SHELL -ic <text> in the signed directory, like operator.py run (SHELL, else the runner uid's login shell). After exit 0 it runs operator.py checked <slug> the same way and reports checked true, false or null; the hub calls ran without --check-failed only when checked is true, so a row whose check fails on the host stays open with a message like run's.
operator.py: new checked <slug> (exit 0 pass, 1 fail, 2 unknown slug) and ran --check-failed; holds() shares the check with run. jobs.py accepts the optional checked field and drops the old usage-error fallback to done. The runner unit passes --operator with the installed operator.py; without it, or with an older hub or runner on either side, checked stays null and the row stays open (fails closed).
Rebased onto master from its lane base 2754568 with a 3-way apply: all 10 files clean, the staged stat equal to the patch's own (+206/-64), nothing of master reverted.
Tests: test_operator.py ran once on the staged tree (operator-approved run): 52 passed, 61 subtests passed. test_hub_executors and test_hub_console cover checked() and the ran/--check-failed calls; written, not run: the full suite runs once on master after all bundles (operator order). A probe of /bin/bash -ic without a tty, as systemd starts the runner, passes the exit code through (7); the rc file's 56-line banner lands at the head and falls out of the runner's last-lines output tail.
Security: MEDUSA over the staged tree on master: 100, 9 of 10 files covered, 0 open findings, every hit accepted earlier (RH005 after a skeptic review and the operator's accept). The systemd unit is outside MEDUSA's coverage; its one change appends --operator <installed operator.py>.
🎯 Fix: 90 %
💥 Break: 4 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 86
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
20b1500b80
commit
a4f7017691
10 files changed
+209
-67
No files matched your search
+7
-2
@@ -19,6 +19,8 @@ from hub_support import (
|
||||
GIT_ENV,
|
||||
HOST_STATE,
|
||||
HUB,
|
||||
LOGIN_SHELL,
|
||||
OPERATOR,
|
||||
OPTIONS,
|
||||
PAGE,
|
||||
RASCI,
|
||||
@@ -53,8 +55,11 @@ class HubCase(unittest.TestCase):
|
||||
self.offices = base / "state" / "offices"
|
||||
self.approvers = base / "config" / "approvers.json"
|
||||
self.replay = base / "replay"
|
||||
self.shell = base / "login-shell"
|
||||
for path in (self.pages, self.state, self.outside, self.projects, self.tree_file.parent, self.timers, self.kept):
|
||||
path.mkdir()
|
||||
self.shell.write_text(LOGIN_SHELL, encoding="utf-8")
|
||||
self.shell.chmod(0o755)
|
||||
silence = mock.patch.object(server.Handler, "log_message")
|
||||
silence.start()
|
||||
self.addCleanup(silence.stop)
|
||||
@@ -198,8 +203,8 @@ class HubCase(unittest.TestCase):
|
||||
def run_runner(self, register: bool = True, council: Path | None = None) -> None:
|
||||
trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "runner.json")]
|
||||
flags = ["--rasci", str(RASCI), "--council", str(council or self.council)] if register else []
|
||||
command = [sys.executable, str(RUNNER), "--port", str(self.port), "--interval", "0.1", *trust, *flags, "--once"]
|
||||
done = subprocess.run(command, capture_output=True, text=True, timeout=60, check=False)
|
||||
command = [sys.executable, str(RUNNER), "--port", str(self.port), "--interval", "0.1", *trust, *flags, "--operator", str(OPERATOR), "--once"]
|
||||
done = subprocess.run(command, capture_output=True, text=True, timeout=60, check=False, env={**os.environ, "SHELL": str(self.shell), "AGENTS_COUNCIL_ROOT": str(council or self.council)})
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
|
||||
def settle(self, check: Callable[[], bool]) -> None:
|
||||
|
||||
@@ -24,6 +24,8 @@ CLIENT = HUB / "client" / "permission_hook.py"
|
||||
RUNNER = HUB / "client" / "runner.py"
|
||||
APPROVAL = HUB / "client" / "approval.py"
|
||||
RASCI = REPO_ROOT / "skills" / "kvb-org-rasci" / "scripts" / "rasci.py"
|
||||
OPERATOR = REPO_ROOT / "skills" / "kvb-org-operator" / "scripts" / "operator.py"
|
||||
LOGIN_SHELL = '#!/bin/sh\n[ "$1" = -ic ] || exit 97\nexec /bin/sh -c "$2"\n'
|
||||
SPEC = importlib.util.spec_from_file_location("kvb_orchestrator_server", HUB / "server.py")
|
||||
server = importlib.util.module_from_spec(SPEC)
|
||||
sys.modules[SPEC.name] = server
|
||||
|
||||
+22
-21
@@ -107,47 +107,48 @@ class TestHubConsole(HubCase):
|
||||
fields = {"task": "operator/greet", "command": COMMAND, "directory": str(self.outside), "sha256": DIGEST, "status": "running", "proof": None}
|
||||
jobs = [
|
||||
self.httpd.hub.jobs.add({**fields, **extra, "code": None, "output": "", "created_ts": time.time(), "started": time.time(), "finished": None, "dismissed": False})
|
||||
for extra in ({}, {}, {}, {}, {}, {"kind": "gate", "argv": []})
|
||||
for extra in ({}, {}, {}, {}, {}, {}, {}, {"kind": "gate", "argv": []})
|
||||
]
|
||||
reports = (
|
||||
{"output": "token-42\n", "code": 0, "refused": False}, {"output": "token-42\n", "code": 3, "refused": False},
|
||||
{"output": "token-42\n", "code": 0, "refused": False, "checked": True}, {"output": "", "code": 0, "refused": False, "checked": False},
|
||||
{"output": "", "code": 0, "refused": False}, {"output": "token-42\n", "code": 3, "refused": False},
|
||||
{"output": "", "code": -9, "refused": False}, {"output": "", "code": 130, "refused": False},
|
||||
{"output": "token-42\n", "code": None, "refused": True}, {"output": "", "code": 1, "refused": False},
|
||||
)
|
||||
answers = [self.runner(f"/api/runner/{job['id']}/report", report) for job, report in zip(jobs, reports)]
|
||||
self.assertEqual([(status, body["status"], len(body["runs"])) for status, body in answers], [
|
||||
(200, "done", 1), (200, "failed", 1), (200, "failed", 1), (200, "failed", 1), (200, "refused", 0), (200, "failed", 0),
|
||||
(200, "done", 1), (200, "done", 1), (200, "done", 1), (200, "failed", 1), (200, "failed", 1), (200, "failed", 1), (200, "refused", 0), (200, "failed", 0),
|
||||
])
|
||||
shown = ["greet", f"--command={COMMAND}", f"--dir={self.outside}"]
|
||||
self.assertEqual(self.scripts.calls, [
|
||||
(skill_scripts.OPERATOR_SCRIPT, ["ran", *shown]),
|
||||
(skill_scripts.OPERATOR_SCRIPT, ["ran", *shown, "--check-failed"]),
|
||||
(skill_scripts.OPERATOR_SCRIPT, ["ran", *shown, "--check-failed"]),
|
||||
(skill_scripts.OPERATOR_SCRIPT, ["failed", *shown, "--why", "exit 3"]),
|
||||
(skill_scripts.OPERATOR_SCRIPT, ["failed", *shown, "--why", "killed by signal 9"]),
|
||||
(skill_scripts.OPERATOR_SCRIPT, ["failed", *shown, "--why", "exit 130"]),
|
||||
])
|
||||
self.assertNotIn("token-42", json.dumps(self.scripts.calls))
|
||||
|
||||
def test_an_older_installed_operator_without_ran_still_closes_the_row_through_done(self):
|
||||
def test_a_ran_the_installed_operator_refuses_never_falls_back_to_done(self):
|
||||
self.register("queued")
|
||||
fields = {"task": "operator/greet", "command": COMMAND, "directory": str(self.outside), "sha256": DIGEST, "status": "running", "proof": None}
|
||||
jobs = [
|
||||
self.httpd.hub.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": time.time(), "finished": None, "dismissed": False})
|
||||
for _ in range(2)
|
||||
]
|
||||
self.scripts.code = 2
|
||||
done = self.runner(f"/api/runner/{jobs[0]['id']}/report", {"output": "", "code": 0, "refused": False})[1]
|
||||
failed = self.runner(f"/api/runner/{jobs[1]['id']}/report", {"output": "", "code": 1, "refused": False})[1]
|
||||
shown = ["greet", f"--command={COMMAND}", f"--dir={self.outside}"]
|
||||
self.assertEqual(self.scripts.calls, [
|
||||
(skill_scripts.OPERATOR_SCRIPT, ["ran", *shown]),
|
||||
(skill_scripts.OPERATOR_SCRIPT, ["done", "greet"]),
|
||||
(skill_scripts.OPERATOR_SCRIPT, ["failed", *shown, "--why", "exit 1"]),
|
||||
])
|
||||
self.assertEqual((len(done["runs"]), len(failed["runs"])), (2, 1))
|
||||
self.scripts.code = 1
|
||||
job = self.httpd.hub.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": time.time(), "finished": None, "dismissed": False})
|
||||
self.runner(f"/api/runner/{job['id']}/report", {"output": "", "code": 0, "refused": False})
|
||||
self.assertEqual(self.scripts.calls[-1], (skill_scripts.OPERATOR_SCRIPT, ["ran", *shown]))
|
||||
self.scripts.code = 2
|
||||
done = self.runner(f"/api/runner/{job['id']}/report", {"output": "", "code": 0, "refused": False, "checked": False})[1]
|
||||
shown = ["greet", f"--command={COMMAND}", f"--dir={self.outside}"]
|
||||
self.assertEqual(self.scripts.calls, [(skill_scripts.OPERATOR_SCRIPT, ["ran", *shown, "--check-failed"])])
|
||||
self.assertEqual(len(done["runs"]), 1)
|
||||
|
||||
def test_a_report_with_a_checked_other_than_true_false_or_null_is_refused(self):
|
||||
self.register("queued")
|
||||
fields = {"task": "operator/greet", "command": COMMAND, "directory": str(self.outside), "sha256": DIGEST, "status": "running", "proof": None}
|
||||
job = self.httpd.hub.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": time.time(), "finished": None, "dismissed": False})
|
||||
for checked in ("yes", 1, [True]):
|
||||
with self.subTest(checked=checked):
|
||||
self.assertEqual(self.runner(f"/api/runner/{job['id']}/report", {"output": "", "code": 0, "refused": False, "checked": checked})[0], 400)
|
||||
self.assertEqual(self.runner(f"/api/runner/{job['id']}/report", {"output": "", "code": 0, "refused": False, "checked": None})[1]["status"], "done")
|
||||
self.assertEqual(self.scripts.calls[-1][1][-1], "--check-failed")
|
||||
|
||||
def test_jobs_from_before_the_console_stay_out_of_the_inbox(self):
|
||||
self.register("done")
|
||||
|
||||
@@ -107,22 +107,54 @@ class TestHubExecutors(HubCase):
|
||||
self.approvers.unlink()
|
||||
job = {"task": "operator/greet", "command": command, "directory": str(self.outside), "proof": proof}
|
||||
self.assertIn("no key is pinned", runner.refusal(job, self.trust("other"), time.time()))
|
||||
reports = []
|
||||
self.assertEqual(runner.execute({"command": "exit 3", "directory": str(self.outside)}, reports.append), 3)
|
||||
reports, host = [], runner.Host(shell=str(self.shell), operator=None, council=None)
|
||||
self.assertEqual(runner.execute({"command": "exit 3", "directory": str(self.outside)}, host, reports.append), 3)
|
||||
self.assertEqual(reports[-1], {"output": "", "code": 3, "refused": False})
|
||||
self.assertEqual(runner.execute({"command": "true", "directory": str(self.outside)}, host, reports.append), 0)
|
||||
self.assertEqual(reports[-1], {"output": "", "code": 0, "refused": False, "checked": None})
|
||||
self.assertEqual(runner.execute({"command": "true", "directory": str(self.outside)}, host._replace(shell=str(self.outside)), reports.append), 127)
|
||||
|
||||
def test_the_runner_keeps_a_row_open_whose_check_fails_on_the_host_after_exit_0(self):
|
||||
command = "echo pushed"
|
||||
register = {"operator/push": {"title": command, "workdir": str(self.outside), "description": "push", "check": f"absent:{self.outside}", "status": "queued", "roles": {}}}
|
||||
self.write_council({"rasci.json": register})
|
||||
digest = hashlib.sha256(command.encode()).hexdigest()
|
||||
signer = self.pin()
|
||||
push = [self.entry("operator", "operator/push", "", digest)]
|
||||
with mock.patch.object(batches, "UNDO", 0.05):
|
||||
self.assertEqual(self.approve(push, self.signed(push, signer))[0], 202)
|
||||
self.settle(lambda: self.runner_jobs() != [])
|
||||
self.run_runner()
|
||||
job = self.snapshot()["jobs"][-1]
|
||||
self.assertEqual((job["status"], job["code"], job["output"]), ("done", 0, "pushed\n"))
|
||||
self.assertEqual(self.scripts.calls[-1], (skill_scripts.OPERATOR_SCRIPT, ["ran", "push", f"--command={command}", f"--dir={self.outside}", "--check-failed"]))
|
||||
host = runner.Host(shell=str(self.shell), operator=hub_support.OPERATOR, council=self.council)
|
||||
self.assertIs(runner.checked({"task": "operator/push"}, host), False)
|
||||
self.assertIsNone(runner.checked({"task": "operator/missing"}, host))
|
||||
self.assertIsNone(runner.checked({"task": "operator/push"}, host._replace(shell=str(self.outside / "no-shell"))))
|
||||
marking = self.outside / "marking-shell"
|
||||
marking.write_text('#!/bin/sh\ntouch "$0.ran"\n', encoding="utf-8")
|
||||
marking.chmod(0o700)
|
||||
for task in ("operator/x\\'\"; id #", "operator/Push", "review/push", "push", None):
|
||||
with self.subTest(task=task):
|
||||
self.assertIsNone(runner.checked({"task": task}, host._replace(shell=str(marking))))
|
||||
self.assertFalse(marking.with_name("marking-shell.ran").exists())
|
||||
self.write_council({"rasci.json": {"operator/push": {**register["operator/push"], "check": "manual"}}})
|
||||
self.assertIs(runner.checked({"task": "operator/push"}, host), True)
|
||||
|
||||
def test_the_runner_closes_the_output_pipe_on_every_path(self):
|
||||
popen, spawned = subprocess.Popen, []
|
||||
job = {"command": "echo hi; sleep 0.3", "directory": str(self.outside)}
|
||||
host = runner.Host(shell=str(self.shell), operator=None, council=None)
|
||||
|
||||
def spawn(*args: object, **kwargs: object) -> subprocess.Popen:
|
||||
spawned.append(popen(*args, **kwargs))
|
||||
return spawned[-1]
|
||||
|
||||
with mock.patch.object(subprocess, "Popen", spawn), mock.patch.object(runner, "BEAT", 0.05):
|
||||
self.assertEqual(runner.execute(job, [].append), 0)
|
||||
self.assertEqual(runner.execute(job, host, [].append), 0)
|
||||
self.assertTrue(spawned[0].stdout.closed)
|
||||
self.assertRaises(RuntimeError, runner.execute, job, mock.Mock(side_effect=RuntimeError("the hub is gone")))
|
||||
self.assertRaises(RuntimeError, runner.execute, job, host, mock.Mock(side_effect=RuntimeError("the hub is gone")))
|
||||
self.settle(lambda: spawned[1].stdout.closed)
|
||||
self.assertEqual(spawned[1].wait(10), 0)
|
||||
|
||||
|
||||
+15
-1
@@ -1016,6 +1016,20 @@ class TestOperator(unittest.TestCase):
|
||||
with self.subTest(args=args):
|
||||
self.assertEqual(self._as(None, *args).returncode, 2)
|
||||
|
||||
def test_checked_answers_the_host_check_and_ran_with_check_failed_keeps_the_row_open(self):
|
||||
self._add("open", self.base, "true", "r", f"absent:{self.base}")
|
||||
self._add("gone", self.base, "true", "r", f"absent:{self.base / 'nothing'}")
|
||||
self._add("man", self.base, "true", "r", "manual")
|
||||
codes = {slug: self._as(None, "checked", slug).returncode for slug in ("open", "gone", "man", "missing")}
|
||||
self.assertEqual(codes, {"open": 1, "gone": 0, "man": 0, "missing": 2})
|
||||
shown = ("--command", "true", "--dir", str(self.base))
|
||||
kept = self._as(None, "ran", "open", *shown, "--check-failed")
|
||||
self.assertEqual(kept.returncode, 0, kept.stderr)
|
||||
self.assertIn(f"but absent:{self.base} does not pass yet; the row stays open", kept.stdout)
|
||||
self.assertIn("operator/open", self._open())
|
||||
self.assertEqual(self._as(None, "ran", "open", *shown).returncode, 0)
|
||||
self.assertNotIn("operator/open", self._open())
|
||||
|
||||
def test_the_hub_runner_calls_the_stored_session_with_ran_and_failed_even_when_its_channel_says_post(self):
|
||||
radio = REPO_ROOT / "skills" / "kvb-org-radio" / "scripts" / "radio.py"
|
||||
chosen = subprocess.run([sys.executable, str(radio), "feedback", "set", "post"], capture_output=True, text=True, env=self.env, check=False)
|
||||
@@ -1031,7 +1045,7 @@ class TestOperator(unittest.TestCase):
|
||||
"from kvb_orchestrator.jobs import Jobs\n"
|
||||
"from kvb_orchestrator.skill_scripts import Scripts\n"
|
||||
"hub = types.SimpleNamespace(scripts=Scripts(Path(sys.argv[2]), Path(sys.argv[3]), Path(sys.argv[4])))\n"
|
||||
"print(json.dumps([Jobs.close_row(hub, job, status, code) for job, status, code in json.loads(sys.argv[5])]))\n"
|
||||
"print(json.dumps([Jobs.close_row(hub, job, status, code, True) for job, status, code in json.loads(sys.argv[5])]))\n"
|
||||
)
|
||||
jobs = [
|
||||
[{"task": "operator/go", "command": "true", "directory": str(self.base)}, "done", 0],
|
||||
|
||||
Reference in new issue
Block a user