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
116 lines
5.3 KiB
Python
116 lines
5.3 KiB
Python
"""Unit tests for sessions-web. Run: python3 -m unittest discover -s web/tests"""
|
|
|
|
import base64
|
|
import importlib.util
|
|
import os
|
|
import stat
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
_spec = importlib.util.spec_from_file_location("app", Path(__file__).parents[1] / "app.py")
|
|
app = importlib.util.module_from_spec(_spec)
|
|
_spec.loader.exec_module(app)
|
|
|
|
FAKE_KEY = b"-----BEGIN OPENSSH PRIVATE KEY-----\nAAAAfake\n-----END OPENSSH PRIVATE KEY-----\n"
|
|
ENV = {
|
|
"SESSIONS_DEV_HOST": "2.28.100.223",
|
|
"SESSIONS_DEV_HOST_KEY": "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEdLIHPjrkeUPfw1CDcIHC2Yydl39X46GBjmn6vqd+6E",
|
|
"SESSIONS_SSH_KEY_B64": base64.b64encode(FAKE_KEY).decode(),
|
|
}
|
|
|
|
|
|
class SshFiles(unittest.TestCase):
|
|
def test_writes_private_key_and_pinned_host(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
key, known = app.materialise_ssh_files(ENV, d)
|
|
self.assertEqual(Path(key).read_bytes(), FAKE_KEY)
|
|
self.assertEqual(stat.S_IMODE(os.stat(key).st_mode), 0o600)
|
|
self.assertEqual(Path(known).read_text(), f"[2.28.100.223]:14922 {ENV['SESSIONS_DEV_HOST_KEY']}\n")
|
|
|
|
def test_rejects_bad_values(self):
|
|
bad = [
|
|
{"SESSIONS_SSH_KEY_B64": "not base64!"},
|
|
{"SESSIONS_SSH_KEY_B64": base64.b64encode(b"hello").decode()},
|
|
{"SESSIONS_DEV_HOST_KEY": "ssh-ed25519"},
|
|
{"SESSIONS_DEV_HOST_KEY": "ssh-ed25519 AAAA\n[evil]:22 ssh-ed25519 AAAA"},
|
|
]
|
|
for override in bad:
|
|
with tempfile.TemporaryDirectory() as d, self.assertRaises(app.ConfigError, msg=override):
|
|
app.materialise_ssh_files({**ENV, **override}, d)
|
|
|
|
|
|
class RequestChecks(unittest.TestCase):
|
|
def test_same_origin(self):
|
|
host = "sessions.reudy.net"
|
|
self.assertTrue(app.same_origin({"Sec-Fetch-Site": "same-origin"}, host))
|
|
self.assertFalse(app.same_origin({"Sec-Fetch-Site": "cross-site", "Origin": f"https://{host}"}, host))
|
|
self.assertFalse(app.same_origin({"Sec-Fetch-Site": "same-site"}, host))
|
|
self.assertTrue(app.same_origin({"Origin": f"https://{host}"}, host))
|
|
self.assertFalse(app.same_origin({"Origin": "https://evil.example"}, host))
|
|
self.assertFalse(app.same_origin({}, host))
|
|
|
|
def test_allowed_user(self):
|
|
self.assertFalse(app.allowed_user("", set()))
|
|
self.assertTrue(app.allowed_user("reudy", set()))
|
|
self.assertTrue(app.allowed_user("reudy", {"reudy"}))
|
|
self.assertFalse(app.allowed_user("mallory", {"reudy"}))
|
|
|
|
|
|
class SshArgv(unittest.TestCase):
|
|
def setUp(self):
|
|
self.dev = app.DevBox({"SESSIONS_DEV_HOST": "dev.example"}, "/k", "/kh")
|
|
|
|
def test_shape(self):
|
|
argv = self.dev.argv("create", "fix-login", "papure", "feature/x")
|
|
self.assertEqual(argv[0], "ssh")
|
|
self.assertIn("StrictHostKeyChecking=yes", argv)
|
|
self.assertIn("UserKnownHostsFile=/kh", argv)
|
|
self.assertEqual(argv[-2:], ["--", "create fix-login papure feature/x"])
|
|
|
|
def test_multiplexes_over_one_connection(self):
|
|
argv = self.dev.argv("list")
|
|
self.assertIn("ControlMaster=auto", argv)
|
|
self.assertIn("ControlPath=/cm-%C", argv) # next to the key, in the private temp dir
|
|
|
|
def test_title_with_spaces_is_one_quoted_argument(self):
|
|
self.assertEqual(self.dev.argv("create", "Fix login bug", "papure")[-1], "create 'Fix login bug' papure")
|
|
|
|
def test_rejects_odd_arguments(self):
|
|
for bad in ("", "-oProxyCommand=x", " -x", "$(id)", "a;b", "a\nb", "a\tb", "'a'", "a`b`"):
|
|
with self.assertRaises(ValueError, msg=bad):
|
|
self.dev.argv("status", bad)
|
|
self.assertFalse(self.dev.call("status", "a;b")["ok"])
|
|
|
|
|
|
class Rendering(unittest.TestCase):
|
|
def test_archived_section(self):
|
|
def s(name, archived):
|
|
return {"name": name, "title": name.upper(), "archived": archived, "repo": "r", "branch": "b",
|
|
"created_at": "2026-10-06T00:00:00", "state": "inactive", "enabled": False, "restarts": 0}
|
|
out = app.dashboard({"ok": True, "max_running": 2, "sessions": [s("live", False), s("old", True)]},
|
|
{"repos": []}, "u", None).decode()
|
|
live, archived = out.split("<details>")
|
|
self.assertIn("LIVE", live)
|
|
self.assertIn('action="/archive"', live)
|
|
self.assertNotIn("OLD", live)
|
|
self.assertIn("Archived (1)", archived)
|
|
self.assertIn('action="/unarchive"', archived)
|
|
self.assertNotIn('action="/start"', archived)
|
|
no_archive = app.dashboard({"ok": True, "max_running": 2, "sessions": [s("live", False)]}, {}, "u", None)
|
|
self.assertNotIn(b"<details>", no_archive)
|
|
|
|
def test_escapes_everything(self):
|
|
listing = {"ok": True, "max_running": 2, "sessions": [{
|
|
"name": "<script>", "repo": "r", "branch": "b", "created_at": "2026-09-30T11:00:00",
|
|
"state": "active", "enabled": True, "restarts": 0,
|
|
"remote_control_url": 'https://claude.ai/code/session_x" onclick="x', "needs_attention": None}]}
|
|
out = app.dashboard(listing, {"repos": ["papure"]}, "<u>", ("err", "<b>")).decode()
|
|
self.assertNotIn("<script>", out)
|
|
self.assertNotIn("<u>", out)
|
|
self.assertNotIn('" onclick="', out)
|
|
self.assertIn("<b>", out)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|