sessions/dev/tests/test_sessions_ctl.py
agent ca66db3aeb Add sessions-ctl keygen to create prod's key on the dev box
keygen generates an ed25519 pair in RAM, writes the public half to
config.toml and authorized_keys (replacing the previous sessions-manager
line) and prints the web app's environment - dev host, port, user, pinned
host key and the private key as one base64 line - then deletes the private
key, so the pasted copy is the only one. Refuses to replace an existing key
without --rotate. Local only, never reachable over SSH.

Also make load_config() read CONFIG_PATH at call time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KKYfRST9cTJYae3f7Jf3ac
2026-09-30 14:39:56 +00:00

198 lines
9.1 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"])
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)
(projects / "-home-agent-sessions-s1").mkdir()
(projects / "-home-agent-sessions-s1" / f"{state['uuid']}.jsonl").write_text("")
self.assertEqual(sc.claude_args(state, "dev-box", projects)[-2:], ["--resume", state["uuid"]])
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()