sessions/web/tests/test_app.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

248 lines
12 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 class="archive">')
self.assertIn("LIVE", live)
self.assertIn('action="/archive"', live)
self.assertNotIn("OLD", live)
self.assertIn('Archived <span class="count">1</span>', 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 class="archive">', 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("&lt;b&gt;", out)
def test_add_repo_form_only_when_the_dev_box_allows_it(self):
listing = {"ok": True, "max_running": 2, "sessions": []}
self.assertNotIn(b'action="/add-repo"', app.dashboard(listing, {"repos": ["a"]}, "u", None))
on = app.dashboard(listing, {"repos": ["a"], "add": {"base_url": "ssh://git@git.example:14922/",
"owners": ["team"]}}, "u", None).decode()
self.assertIn('action="/add-repo"', on)
self.assertIn("git.example", on)
def test_assets_are_versioned_and_page_has_no_inline_script(self):
out = app.dashboard({"ok": True, "sessions": []}, {}, "u", None).decode()
self.assertIn(f'src="/app.js?v={app.ASSET_VERSION}"', out)
self.assertNotRegex(out, r"<script(?![^>]*\bsrc=)") # CSP has no 'unsafe-inline'
class RepoInput(unittest.TestCase):
BASE = "ssh://git@git.reudy.net:14922/"
def test_accepts_paths_and_urls_on_the_git_host(self):
for text in ("reudy-net/elorasmus", "reudy-net/elorasmus.git", " reudy-net/elorasmus/ ",
"ssh://git@git.reudy.net:14922/reudy-net/elorasmus.git",
"https://git.reudy.net/reudy-net/elorasmus", "https://GIT.reudy.net/reudy-net/elorasmus.git",
"git@git.reudy.net:reudy-net/elorasmus.git"):
self.assertEqual(app.parse_repo_input(text, self.BASE), ("reudy-net", "elorasmus"), text)
def test_rejects_other_hosts_and_odd_paths(self):
for text in ("https://github.com/reudy-net/elorasmus", "git@github.com:reudy-net/x.git",
"elorasmus", "a/b/c", "reudy-net/../x", "reudy-net/x y", "reudy-net/x;id", "",
"file:///etc/passwd", "reudy-net/-x", "reudy-net/x\ny"):
with self.assertRaises(ValueError, msg=text):
app.parse_repo_input(text, self.BASE)
def test_key_from_repo(self):
self.assertEqual(app.key_from_repo("Papure"), "papure")
self.assertEqual(app.key_from_repo("My_App.v2"), "my-app-v2")
self.assertEqual(app.key_from_repo("x" * 40), "x" * 32)
class Server(unittest.TestCase):
"""The real handler on a loopback port, with the dev box faked."""
class FakeDev:
def __init__(self):
self.calls = []
def call(self, *args, timeout=60):
self.calls.append(args)
if args[0] == "list":
return {"ok": True, "max_running": 2, "sessions": []}
if args[0] == "repos":
return {"ok": True, "repos": ["a"], "add": {"base_url": "ssh://git@git.example:1/", "owners": ["team"]}}
if args[0] == "add-repo":
return {"ok": True, "repo": args[1], "repos": ["a", args[1]]}
if args[0] == "stop":
return {"ok": False, "error": "no session named 'x'"}
return {"ok": True}
def setUp(self):
import http.client, threading
self.dev = self.FakeDev()
self.app = app.App({}, self.dev)
self.server = app.ThreadingHTTPServer(("127.0.0.1", 0), app.make_handler(self.app))
threading.Thread(target=self.server.serve_forever, daemon=True).start()
self.addCleanup(self.server.server_close)
self.addCleanup(self.server.shutdown)
self.conn = lambda: http.client.HTTPConnection("127.0.0.1", self.server.server_port, timeout=5)
def request(self, method, path, body=None, **headers):
import urllib.parse
c = self.conn()
data = urllib.parse.urlencode(body).encode() if body is not None else None
hdrs = {"Remote-User": "reudy", "Sec-Fetch-Site": "same-origin", **headers}
if data is not None:
hdrs["Content-Type"] = "application/x-www-form-urlencoded"
c.request(method, path, data, hdrs)
r = c.getresponse()
return r, r.read()
def test_page_and_assets(self):
r, body = self.request("GET", "/")
self.assertEqual(r.status, 200)
csp = r.getheader("Content-Security-Policy")
self.assertIn("script-src 'self'", csp)
self.assertNotIn("unsafe", csp)
for path in ("/app.js", "/app.css"):
r, body = self.request("GET", f"{path}?v={app.ASSET_VERSION}")
self.assertEqual(r.status, 200, path)
self.assertIn("immutable", r.getheader("Cache-Control"))
r, _ = self.request("GET", "/app.js", **{"Remote-User": ""})
self.assertEqual(r.status, 403)
def test_repos_are_cached_between_page_views(self):
self.request("GET", "/")
self.request("GET", "/")
self.assertEqual([c[0] for c in self.dev.calls].count("repos"), 1)
self.assertEqual([c[0] for c in self.dev.calls].count("list"), 2)
def test_json_answers_instead_of_redirect(self):
import json
r, body = self.request("POST", "/start", {"name": "x"}, Accept="application/json")
self.assertEqual(r.status, 200)
self.assertEqual(json.loads(body), {"ok": True, "message": "Started x"})
r, body = self.request("POST", "/stop", {"name": "x"}, Accept="application/json")
self.assertEqual(json.loads(body), {"ok": False, "error": "no session named 'x'"})
r, _ = self.request("POST", "/start", {"name": "x"})
self.assertEqual(r.status, 303) # without JS: post, redirect, get
def test_cross_site_and_unauthenticated_posts_still_refused(self):
r, _ = self.request("POST", "/start", {"name": "x"}, Accept="application/json", **{"Sec-Fetch-Site": "cross-site"})
self.assertEqual(r.status, 403)
r, _ = self.request("POST", "/start", {"name": "x"}, Accept="application/json", **{"Remote-User": ""})
self.assertEqual(r.status, 403)
self.assertEqual(self.dev.calls, [])
def test_add_repo_sends_only_owner_and_name(self):
import json
r, body = self.request("POST", "/add-repo", {"url": "ssh://git@git.example:1/team/My_App.git"},
Accept="application/json")
out = json.loads(body)
self.assertTrue(out["ok"])
self.assertEqual(out["repos"], ["a", "my-app"])
self.assertIn(("add-repo", "my-app", "team/My_App"), self.dev.calls)
# the cache now has the new repo without another `repos` call
self.assertEqual(self.app.repos()["repos"], ["a", "my-app"])
self.assertEqual([c[0] for c in self.dev.calls].count("repos"), 1)
def test_add_repo_rejects_other_hosts_before_calling_the_dev_box(self):
import json
r, body = self.request("POST", "/add-repo", {"url": "https://github.com/team/x"}, Accept="application/json")
self.assertFalse(json.loads(body)["ok"])
self.assertNotIn("add-repo", [c[0] for c in self.dev.calls])
if __name__ == "__main__":
unittest.main()