sessions/dev/tests/test_sessions_ctl.py
agent 0738171f1e Archive sessions, allow spaces in names, stop tripping the SSH rate limit
Connection refused: the dev box's UFW `limit` rule refuses the 6th new
SSH connection from one address within 30 s. Every page view made two
calls (list, repos) and every button one more, so stopping two sessions
and refreshing hit it (kernel log: "UFW LIMIT BLOCK" from prod's IP).
The web app now multiplexes all calls over one connection
(ControlMaster=auto, ControlPersist=120), with the socket in its private
temp dir. compose.yaml gets `init: true` so the backgrounded master is
reaped; the app warns if it runs as PID 1.

Spaces in names: `create` now takes a title (letters, digits, '-',
single spaces, <= 48 chars). The slug used for the directory, branch,
unit and tmux socket is derived from it; the title is shown on the page
and passed to claude as --name. A plain slug still maps to itself.

Archive: new remote verbs `archive` (stop + flag, keeps checkout and
conversation) and `unarchive` (back to the list, still stopped). An
archived session refuses `start`. The page lists archived sessions in a
collapsible section. `list` re-reads state under the lock before saving
a Remote Control URL so it can't undo a concurrent archive.

Also: name/branch validation used re.match with `$`, which accepts a
trailing newline; it now uses fullmatch.

Tested end to end with a throwaway 127.0.0.1 key and the real container:
24 remote calls went over 1 TCP connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rog8S9b5qKaw6nUicxXLkM
2026-10-06 09:42:40 +00:00

288 lines
13 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')
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()