sessions/dev/tests/test_sessions_ctl.py
agent 1b3172bd50 Add repos from the page, answer actions in place, Expo-style redesign
Add repository:
- New remote verb `add-repo KEY OWNER/NAME`. Off unless config.toml has
  [repo_add] (base_url + owners). Only listed owners; the dev box builds
  the URL itself, checks it with `git ls-remote` (bot access), then
  appends to [repos] under the lock. No URL crosses the SSH link.
- `repos` also reports where adding is allowed, so the page shows the
  form only when it's on and rejects other hosts before calling SSH.
- set_toml_string inserts after the section's last key, not after
  trailing blank lines / the next section's comments.

Responsiveness:
- web/static/app.js (progressive enhancement; every form still works
  without JS): forms go via fetch and get a JSON answer instead of
  POST-redirect-GET; buttons/cards show the change immediately; the
  list refreshes itself (15 s, 3 s while something is starting).
- `repos` is cached for 5 min (refreshed on add-repo), so a page view
  is one SSH call instead of two.
- `list` reads all unit states with one `systemctl show` instead of one
  per session: 676 -> 374 ms on the dev box with 21 sessions.
- Static assets are content-hashed and cached immutably.

Design: slate greys, hairline borders, black primary action, tinted
status badges, monospace repo/branch, two columns on desktop, stacked
on phones, light and dark.

Docs: README security model, AGENTS.md (JS convention, add-repo
invariant), config.example.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MCUMXh8zZConC75Mptbeou
2026-11-10 22:17:37 +00:00

402 lines
18 KiB
Python

"""Unit tests for the parts of sessions-ctl that guard the SSH boundary.
Run: python3 -m unittest discover -s dev/tests
"""
import importlib.util
import json
import tempfile
import unittest
from pathlib import Path
_spec = importlib.util.spec_from_file_location("sessions_ctl", Path(__file__).parents[1] / "sessions_ctl.py")
sc = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(sc)
KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPAP6gemgKZVguFi6Diif+dBbMAZQupimeV9OQuUotlw vps-manual"
class RemoteParsing(unittest.TestCase):
def test_allowed_verbs_pass(self):
self.assertEqual(sc.parse_remote("create fix-login papure main"), ["create", "fix-login", "papure", "main"])
self.assertEqual(sc.parse_remote("list"), ["list"])
def test_local_only_verbs_rejected(self):
for cmd in ("delete x --yes --force", "refresh-access", "_launch x"):
with self.assertRaises(sc.UserError, msg=cmd):
sc.parse_remote(cmd)
def test_no_command_means_no_shell(self):
for cmd in (None, "", " "):
with self.assertRaises(sc.UserError):
sc.parse_remote(cmd)
def test_shell_metacharacters_are_just_text(self):
# "list;" is not a verb; nothing is ever handed to a shell.
for cmd in ("list; rm -rf ~", "bash -i", "$(id)", "list 'unterminated"):
with self.assertRaises(sc.UserError, msg=cmd):
sc.parse_remote(cmd)
def test_injection_in_arguments_fails_validation(self):
argv = sc.parse_remote("status '$(id)'")
with self.assertRaises(sc.UserError):
sc.validate_name(argv[1])
class Validation(unittest.TestCase):
def test_names(self):
for ok in ("a", "fix-login", "x" * 32, "9lives"):
sc.validate_name(ok)
for bad in ("", "-x", "X", "a_b", "a/b", "..", "x" * 33, "a b", "--force"):
with self.assertRaises(sc.UserError, msg=bad):
sc.validate_name(bad)
def test_branches(self):
for ok in ("main", "feature/x-1", "v1.2"):
sc.validate_branch(ok)
for bad in ("-b", "--upload-pack=x", "a..b", "x.lock", "a/", "a b", "~x"):
with self.assertRaises(sc.UserError, msg=bad):
sc.validate_branch(bad)
def test_arity(self):
with self.assertRaises(sc.UserError):
sc.cmd_repos({"repos": {}}, ["extra"])
def test_trailing_newline_rejected(self):
# re.match + "$" would accept "a\n"; sessions-ctl must use fullmatch.
for f, v in ((sc.validate_name, "a\n"), (sc.validate_branch, "main\n"), (sc.name_from_title, "Fix\n")):
with self.assertRaises(sc.UserError, msg=repr(v)):
f(v)
def test_titles(self):
self.assertEqual(sc.name_from_title("Fix login bug"), ("fix-login-bug", "Fix login bug"))
self.assertEqual(sc.name_from_title("fix-login"), ("fix-login", "fix-login"))
self.assertEqual(sc.name_from_title("a - b"), ("a-b", "a - b"))
self.assertEqual(sc.name_from_title("X" * 48)[0], "x" * 32)
for bad in ("", " a", "a ", "a b", "X" * 49, "a_b", "-a", "a\tb", "a;b", "$(id)", "---", "'a'"):
with self.assertRaises(sc.UserError, msg=bad):
sc.name_from_title(bad)
def test_title_survives_the_ssh_round_trip(self):
import shlex
self.assertEqual(sc.parse_remote(shlex.join(["create", "Fix login bug", "papure"])),
["create", "Fix login bug", "papure"])
class Archive(unittest.TestCase):
"""archive/unarchive with systemd stubbed out and state in a temp dir."""
def setUp(self):
from unittest import mock
d = tempfile.TemporaryDirectory()
self.addCleanup(d.cleanup)
self.calls = []
self.active = set()
def systemctl(*args, check=True):
self.calls.append(args)
if args[:2] == ("disable", "--now"):
self.active.discard(args[2])
elif args[:2] == ("enable", "--now"):
self.active.add(args[2])
def unit_state(name):
on = sc.UNIT.format(name) in self.active
return {"active": "active" if on else "inactive", "sub": "", "enabled": on, "restarts": 0}
for target, value in (("STATE_DIR", Path(d.name)), ("systemctl", systemctl), ("unit_state", unit_state)):
p = mock.patch.object(sc, target, value)
p.start()
self.addCleanup(p.stop)
sc.write_state({"name": "s1", "title": "S 1", "repo": "r", "branch": "session/s1",
"workspace": "/nonexistent", "uuid": "u", "created_at": "2026-10-06T00:00:00+00:00"})
self.active.add(sc.UNIT.format("s1"))
self.cfg = {"max_running": 2}
def test_archive_stops_and_flags(self):
view = sc.cmd_archive(self.cfg, ["s1"])["session"]
self.assertIn(("disable", "--now", "claude-session@s1.service"), self.calls)
self.assertTrue(view["archived"])
self.assertEqual(view["state"], "inactive")
self.assertEqual(view["title"], "S 1")
self.assertTrue(sc.read_state("s1")["archived"])
def test_archived_cannot_start_until_unarchived(self):
sc.cmd_archive(self.cfg, ["s1"])
with self.assertRaises(sc.UserError):
sc.cmd_start(self.cfg, ["s1"])
view = sc.cmd_unarchive(self.cfg, ["s1"])["session"]
self.assertFalse(view["archived"])
self.assertEqual(view["state"], "inactive") # unarchive doesn't start it
sc.cmd_start(self.cfg, ["s1"])
self.assertEqual(sc.unit_state("s1")["active"], "active")
def test_validates_name(self):
for verb in (sc.cmd_archive, sc.cmd_unarchive):
for bad in ("../x", "$(id)", "nope"):
with self.assertRaises(sc.UserError, msg=bad):
verb(self.cfg, [bad])
with self.assertRaises(sc.UserError):
verb(self.cfg, ["s1", "extra"])
def test_remote_verbs(self):
self.assertEqual(sc.parse_remote("archive s1"), ["archive", "s1"])
self.assertEqual(sc.parse_remote("unarchive s1"), ["unarchive", "s1"])
class AuthorizedKeys(unittest.TestCase):
def test_line_shape(self):
line = sc.authorized_line(KEY, ["37.205.10.63"], "/home/agent/.local/bin/sessions-ctl")
self.assertEqual(
line,
'from="37.205.10.63",restrict,command="/home/agent/.local/bin/sessions-ctl --remote" '
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPAP6gemgKZVguFi6Diif+dBbMAZQupimeV9OQuUotlw sessions-manager",
)
def test_rejects_bad_key_and_ip(self):
with self.assertRaises(sc.UserError):
sc.authorized_line('ssh-ed25519 AAAA" ,command="sh', ["1.2.3.4"], "/x")
with self.assertRaises(sc.UserError):
sc.authorized_line(KEY, ['1.2.3.4",command="sh'], "/x")
def test_replace_keeps_other_lines(self):
other = "ssh-ed25519 AAAAother admin@laptop"
first = sc.replace_marked_line(other + "\n", "L1 sessions-manager")
self.assertEqual(first, other + "\nL1 sessions-manager\n")
second = sc.replace_marked_line(first, "L2 sessions-manager")
self.assertEqual(second, other + "\nL2 sessions-manager\n")
self.assertEqual(sc.replace_marked_line(second, "L2 sessions-manager"), second) # idempotent
class Trust(unittest.TestCase):
def test_trust_and_untrust_preserve_other_keys(self):
with tempfile.TemporaryDirectory() as d:
cj = Path(d) / ".claude.json"
cj.write_text(json.dumps({"oauthAccount": {"x": 1}, "projects": {"/a": {"hasTrustDialogAccepted": True}}}))
cj.chmod(0o600)
sc.trust_workspace(Path("/w/s1"), cj)
data = json.loads(cj.read_text())
self.assertTrue(data["projects"]["/w/s1"]["hasTrustDialogAccepted"])
self.assertEqual(data["oauthAccount"], {"x": 1})
self.assertEqual(cj.stat().st_mode & 0o777, 0o600)
sc.untrust_workspace(Path("/w/s1"), cj)
self.assertEqual(json.loads(cj.read_text())["projects"], {"/a": {"hasTrustDialogAccepted": True}})
class ClaudeArgs(unittest.TestCase):
def test_new_then_resume(self):
state = {"name": "s1", "uuid": "11111111-2222-3333-4444-555555555555"}
with tempfile.TemporaryDirectory() as d:
projects = Path(d)
first = sc.claude_args(state, "dev-box", projects)
self.assertEqual(first[-2:], ["--session-id", state["uuid"]])
self.assertIn("dev-box-s1", first)
self.assertIn("--dangerously-skip-permissions", first)
(projects / "-home-agent-sessions-s1").mkdir()
(projects / "-home-agent-sessions-s1" / f"{state['uuid']}.jsonl").write_text("")
resumed = sc.claude_args(state, "dev-box", projects)
self.assertEqual(resumed[-2:], ["--resume", state["uuid"]])
self.assertIn("--dangerously-skip-permissions", resumed)
def test_title_is_the_claude_name(self):
args = sc.claude_args({"name": "s1", "title": "Fix login bug", "uuid": "u"}, "dev-box", Path("/nonexistent"))
self.assertEqual(args[args.index("--name") + 1], "Fix login bug")
self.assertEqual(args[args.index("--remote-control") + 1], "dev-box-s1")
class MainContract(unittest.TestCase):
def test_remote_without_command_prints_json_error(self):
import contextlib, io, os
buf = io.StringIO()
os.environ.pop("SSH_ORIGINAL_COMMAND", None)
with contextlib.redirect_stdout(buf):
rc = sc.main(["--remote"])
self.assertEqual(rc, 1)
self.assertFalse(json.loads(buf.getvalue())["ok"])
class TomlEdit(unittest.TestCase):
BASE = 'max_running = 2\n\n[repos]\na = "x"\n\n[ssh_access]\nallow_from_host = "reudy.net"\npublic_key = "old"\n'
def test_replaces_in_place(self):
out = sc.set_toml_string(self.BASE, "ssh_access", "public_key", "ssh-ed25519 AAAAnew c")
self.assertIn('public_key = "ssh-ed25519 AAAAnew c"', out)
self.assertNotIn('"old"', out)
self.assertEqual(out.count("public_key"), 1)
self.assertIn('a = "x"', out)
def test_adds_key_or_section(self):
no_key = self.BASE.replace('public_key = "old"\n', "")
self.assertIn('public_key = "k"', sc.set_toml_string(no_key, "ssh_access", "public_key", "k"))
out = sc.set_toml_string('max_running = 2\n', "ssh_access", "public_key", "k")
self.assertTrue(out.endswith('[ssh_access]\npublic_key = "k"\n'))
def test_same_key_in_other_section_untouched(self):
text = '[other]\npublic_key = "keep"\n[ssh_access]\npublic_key = "old"\n'
out = sc.set_toml_string(text, "ssh_access", "public_key", "new")
self.assertIn('public_key = "keep"', out)
self.assertIn('public_key = "new"', out)
def test_rejects_quotes(self):
with self.assertRaises(sc.UserError):
sc.set_toml_string("", "s", "k", 'a" \nx = "y')
def test_new_key_goes_after_last_key_not_into_next_sections_comments(self):
text = '[repos]\na = "x"\n\n# about ssh\n[ssh_access]\nk = "v"\n'
out = sc.set_toml_string(text, "repos", "b", "y")
self.assertEqual(out, '[repos]\na = "x"\nb = "y"\n\n# about ssh\n[ssh_access]\nk = "v"\n')
self.assertEqual(sc.set_toml_string("[repos]\n# none yet\n", "repos", "b", "y"), '[repos]\nb = "y"\n# none yet\n')
class UnitStates(unittest.TestCase):
def test_one_call_matched_by_id(self):
from unittest import mock
out = ("Id=claude-session@b.service\nActiveState=active\nSubState=running\nUnitFileState=enabled\nNRestarts=2\n\n"
"Id=claude-session@a.service\nActiveState=inactive\nSubState=dead\nUnitFileState=disabled\nNRestarts=0\n")
calls = []
def systemctl(*args, check=True):
calls.append(args)
return mock.Mock(stdout=out)
with mock.patch.object(sc, "systemctl", systemctl):
states = sc.unit_states(["a", "b", "c"])
self.assertEqual(len(calls), 1)
self.assertEqual(states["a"]["active"], "inactive")
self.assertEqual(states["b"], {"active": "active", "sub": "running", "enabled": True, "restarts": 2})
self.assertEqual(states["c"]["active"], "unknown") # missing block: unknown, not someone else's state
with mock.patch.object(sc, "systemctl", systemctl):
self.assertEqual(sc.unit_states([]), {})
self.assertEqual(len(calls), 1)
class AddRepo(unittest.TestCase):
"""add-repo with git and the config file in a temp dir."""
BASE = "ssh://git@git.example:14922/"
def setUp(self):
from unittest import mock
d = tempfile.TemporaryDirectory()
self.addCleanup(d.cleanup)
self.cfg_path = Path(d.name) / "config.toml"
self.cfg_path.write_text(
'max_running = 2\n\n[repos]\nold = "ssh://git@git.example:14922/team/Old.git"\n\n'
f'[repo_add]\nbase_url = "{self.BASE}"\nowners = ["team"]\n\n[ssh_access]\nallow_from_host = "x"\n')
self.cfg_path.chmod(0o600)
self.git = []
self.git_rc = 0
def run(cmd, **kw):
self.git.append(cmd)
return mock.Mock(returncode=self.git_rc, stdout="", stderr="")
for target, value in (("CONFIG_PATH", self.cfg_path), ("STATE_DIR", Path(d.name) / "state")):
p = mock.patch.object(sc, target, value)
p.start()
self.addCleanup(p.stop)
p = mock.patch.object(sc.subprocess, "run", run)
p.start()
self.addCleanup(p.stop)
def add(self, *args):
return sc.cmd_add_repo(sc.load_config(self.cfg_path), list(args))
def test_adds_and_keeps_the_rest(self):
import os, stat
before = self.cfg_path.read_text()
out = self.add("elorasmus", "team/elorasmus")
self.assertEqual(out["repos"], ["elorasmus", "old"])
self.assertEqual(self.git, [["git", "ls-remote", "--", f"{self.BASE}team/elorasmus.git", "HEAD"]])
after = self.cfg_path.read_text()
self.assertEqual(after, before.replace('Old.git"\n', f'Old.git"\nelorasmus = "{self.BASE}team/elorasmus.git"\n'))
self.assertEqual(stat.S_IMODE(os.stat(self.cfg_path).st_mode), 0o600)
self.assertEqual(sc.cmd_repos(sc.load_config(self.cfg_path), [])["add"],
{"base_url": self.BASE, "owners": ["team"]})
def test_strips_dot_git(self):
self.add("x", "team/x.git")
self.assertIn(f'x = "{self.BASE}team/x.git"', self.cfg_path.read_text())
def test_rejects_before_touching_git_or_config(self):
before = self.cfg_path.read_text()
bad = [
("Bad", "team/x"), ("x", "other/x"), ("x", "team"), ("x", "team/"), ("x", "team/a/b"),
("x", "team/../x"), ("x", "team/-x"), ("x", "team/x y"), ("x", "team/x\n"), ("x", "../team/x"),
("old", "team/new"), # key taken
("again", "team/old"), # URL already listed (case-insensitive)
]
for args in bad:
with self.assertRaises(sc.UserError, msg=args):
self.add(*args)
with self.assertRaises(sc.UserError):
self.add("x")
self.assertEqual(self.git, [])
self.assertEqual(self.cfg_path.read_text(), before)
def test_unreachable_repo_is_not_added(self):
before = self.cfg_path.read_text()
self.git_rc = 128
with self.assertRaises(sc.UserError):
self.add("x", "team/x")
self.assertEqual(self.cfg_path.read_text(), before)
def test_off_without_repo_add_section(self):
cfg = sc.load_config(self.cfg_path)
cfg["repo_add"] = {}
with self.assertRaises(sc.UserError):
sc.cmd_add_repo(cfg, ["x", "team/x"])
self.assertNotIn("add", sc.cmd_repos(cfg, []))
cfg["repo_add"] = {"base_url": "file:///tmp/", "owners": ["team"]}
with self.assertRaises(sc.UserError):
sc.cmd_add_repo(cfg, ["x", "team/x"])
def test_is_a_remote_verb(self):
self.assertEqual(sc.parse_remote("add-repo x team/x"), ["add-repo", "x", "team/x"])
class Keygen(unittest.TestCase):
def test_keygen_end_to_end_in_temp_dirs(self):
import base64, os
from unittest import mock
with tempfile.TemporaryDirectory() as d:
d = Path(d)
cfg = d / "config.toml"
cfg.write_text('[ssh_access]\nallow_from_host = "reudy.net"\npublic_key = "ssh-ed25519 AAAAold vps-manual"\n')
ak = d / "authorized_keys"
ak.write_text("ssh-ed25519 AAAAmine me@laptop\n" + 'from="1.1.1.1",restrict ssh-ed25519 AAAAold sessions-manager\n')
hk = d / "host.pub"
hk.write_text("ssh-ed25519 AAAAhostkey root@box\n")
with mock.patch.object(sc, "CONFIG_PATH", cfg), mock.patch.object(sc, "AUTHORIZED_KEYS", ak), \
mock.patch.object(sc, "HOST_KEY_PATH", str(hk)), mock.patch.object(sc, "resolve", lambda h: ["37.205.10.63"]), \
mock.patch.dict(os.environ, {"XDG_RUNTIME_DIR": str(d)}):
with self.assertRaises(sc.UserError): # existing key needs --rotate
sc.cmd_keygen(sc.load_config(cfg), [])
r = sc.cmd_keygen(sc.load_config(cfg), ["--rotate"])
env = dict(line.split("=", 1) for line in r["text"].splitlines())
self.assertEqual(set(env), {"SESSIONS_DEV_HOST", "SESSIONS_DEV_PORT", "SESSIONS_DEV_USER",
"SESSIONS_DEV_HOST_KEY", "SESSIONS_SSH_KEY_B64"})
self.assertEqual(env["SESSIONS_DEV_HOST_KEY"], "ssh-ed25519 AAAAhostkey")
priv = base64.b64decode(env["SESSIONS_SSH_KEY_B64"], validate=True)
self.assertTrue(priv.startswith(b"-----BEGIN OPENSSH PRIVATE KEY-----"))
# public half landed in config and authorized_keys; old key gone; other keys kept
new_pub = sc.load_config(cfg)["ssh_access"]["public_key"]
self.assertTrue(new_pub.startswith("ssh-ed25519 ") and "AAAAold" not in new_pub)
keys = ak.read_text()
self.assertIn("me@laptop", keys)
self.assertNotIn("AAAAold", keys)
self.assertIn(new_pub.split()[1], keys)
self.assertIn('from="37.205.10.63"', keys)
# nothing private left behind in the runtime dir
self.assertEqual([p.name for p in d.iterdir() if p.name.startswith("sessions-keygen-")], [])
def test_keygen_is_local_only(self):
with self.assertRaises(sc.UserError):
sc.parse_remote("keygen --rotate")
if __name__ == "__main__":
unittest.main()