From ca66db3aeb1279084365df588466fb4e477662e2 Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 30 Sep 2026 14:39:56 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01KKYfRST9cTJYae3f7Jf3ac --- dev/config.example.toml | 9 +++- dev/install.sh | 4 +- dev/sessions_ctl.py | 91 ++++++++++++++++++++++++++++++++-- dev/tests/test_sessions_ctl.py | 68 +++++++++++++++++++++++++ 4 files changed, 165 insertions(+), 7 deletions(-) diff --git a/dev/config.example.toml b/dev/config.example.toml index 8ee8db2..6740691 100644 --- a/dev/config.example.toml +++ b/dev/config.example.toml @@ -21,5 +21,10 @@ sessions = "ssh://git@git.reudy.net:14922/reudy-net/sessions.git" # prod's key may only connect from the address(es) this name resolves to. # Re-resolved hourly by sessions-access-refresh.timer. allow_from_host = "reudy.net" -# The public half of the key the web app container uses. -public_key = "ssh-ed25519 AAAA… comment" +# The public half of the key the web app container uses. Written by +# `sessions-ctl keygen`; you don't need to edit it by hand. +# public_key = "ssh-ed25519 AAAA… sessions-web" +# Printed by keygen as SESSIONS_DEV_HOST / SESSIONS_DEV_PORT. By default it's +# the address this box uses to reach the internet, and 14922. +# advertise_host = "2.28.100.223" +# port = 14922 diff --git a/dev/install.sh b/dev/install.sh index 6cb9354..0cbf501 100755 --- a/dev/install.sh +++ b/dev/install.sh @@ -24,7 +24,7 @@ done if [[ ! -e "$cfg_dir/config.toml" ]]; then install -m 600 "$here/config.example.toml" "$cfg_dir/config.toml" - echo "created $cfg_dir/config.toml — edit [repos] and [ssh_access], then re-run." + echo "created $cfg_dir/config.toml — edit [repos] and [ssh_access], then run: sessions-ctl keygen" fi chmod 600 "$cfg_dir/config.toml" @@ -41,6 +41,6 @@ fi if grep -Eq '^public_key = "ssh-[a-z0-9-]+ AAAA[A-Za-z0-9+/=]{20,}' "$cfg_dir/config.toml"; then "$bin/sessions-ctl" refresh-access else - echo "ssh_access.public_key not set yet — skipping authorized_keys." + echo "no key for prod yet — run: sessions-ctl keygen" fi echo "installed. try: sessions-ctl health" diff --git a/dev/sessions_ctl.py b/dev/sessions_ctl.py index fa479cc..29a839c 100755 --- a/dev/sessions_ctl.py +++ b/dev/sessions_ctl.py @@ -18,13 +18,16 @@ Each session is: systemd is the source of truth for "should this run": a session that is enabled starts at boot (the user has linger on) and is restarted if it dies. -Output is always one JSON object on stdout. Exit codes: 0 ok, 1 error, 2 usage. +Output is one JSON object on stdout (except `keygen`, which prints an env +block to copy). Exit codes: 0 ok, 1 error, 2 usage. Standard library only, so it runs with the system python3. """ from __future__ import annotations +import base64 import datetime as dt +import getpass import fcntl import json import os @@ -47,6 +50,7 @@ CLAUDE_JSON = Path(os.environ.get("SESSIONS_CLAUDE_JSON", HOME / ".claude.json") CLAUDE_PROJECTS = HOME / ".claude/projects" AUTHORIZED_KEYS = Path(os.environ.get("SESSIONS_AUTHORIZED_KEYS", HOME / ".ssh/authorized_keys")) SELF_PATH = HOME / ".local/bin/sessions-ctl" +HOST_KEY_PATH = os.environ.get("SESSIONS_HOST_KEY", "/etc/ssh/ssh_host_ed25519_key.pub") UNIT = "claude-session@{}.service" KEY_MARKER = "sessions-manager" # comment that tags the one line we own in authorized_keys @@ -74,7 +78,8 @@ class UserError(Exception): # ---------------------------------------------------------------- config/state -def load_config(path: Path = CONFIG_PATH) -> dict: +def load_config(path: Path | None = None) -> dict: + path = path or CONFIG_PATH # looked up at call time, so tests can repoint it cfg = dict(DEFAULTS) if path.exists(): with path.open("rb") as f: @@ -399,6 +404,80 @@ def cmd_refresh_access(cfg: dict, args: list[str]) -> dict: return {"changed": changed, "from": ips} +def cmd_keygen(cfg: dict, args: list[str]) -> dict: + """Local only. Make the key prod uses and print its env block once. + + The pair is generated in RAM (XDG_RUNTIME_DIR). The public half goes into + config.toml and authorized_keys; the private half is printed as one base64 + line for the container's environment and then deleted, so it exists only + where you paste it. + """ + if [a for a in args if a != "--rotate"]: + raise UserError("usage: sessions-ctl keygen [--rotate]") + if cfg["ssh_access"].get("public_key", "").startswith("ssh-") and "--rotate" not in args: + raise UserError("a key is already configured; `keygen --rotate` replaces it " + "(prod stops working until its environment is updated)") + if not cfg["ssh_access"].get("allow_from_host"): + raise UserError("config: set ssh_access.allow_from_host first") + + tmp = Path(tempfile.mkdtemp(dir=_user_env()["XDG_RUNTIME_DIR"], prefix="sessions-keygen-")) + try: + _run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "sessions-web", "-f", str(tmp / "id")]) + public = (tmp / "id.pub").read_text().strip() + private_b64 = base64.b64encode((tmp / "id").read_bytes()).decode() + finally: + shutil.rmtree(tmp, ignore_errors=True) + + text = CONFIG_PATH.read_text() if CONFIG_PATH.exists() else "" + atomic_write(CONFIG_PATH, set_toml_string(text, "ssh_access", "public_key", public), 0o600) + access = cmd_refresh_access(load_config(), []) + + host_key = " ".join(Path(HOST_KEY_PATH).read_text().split()[:2]) + env_block = "\n".join([ + f"SESSIONS_DEV_HOST={cfg['ssh_access'].get('advertise_host') or public_address()}", + f"SESSIONS_DEV_PORT={cfg['ssh_access'].get('port', 14922)}", + f"SESSIONS_DEV_USER={getpass.getuser()}", + f"SESSIONS_DEV_HOST_KEY={host_key}", + f"SESSIONS_SSH_KEY_B64={private_b64}", + ]) + note = ("Paste these lines into the sessions app's environment on prod (panel -> app -> Environment).\n" + "The private key exists nowhere else now. Clear this screen afterwards (`clear`, and your\n" + "terminal's scrollback). The key only works from: " + ", ".join(access["from"])) + return {"text": env_block, "note": note, "from": access["from"]} + + +def set_toml_string(text: str, section: str, key: str, value: str) -> str: + """Set `key = "value"` inside [section] of a simple TOML file, keeping the rest.""" + if '"' in value or "\\" in value or "\n" in value: + raise UserError("refusing to write an unusual value into config.toml") + lines, out, in_section, done = text.splitlines(), [], False, False + for line in lines: + stripped = line.strip() + if stripped.startswith("["): + if in_section and not done: + out.append(f'{key} = "{value}"') + done = True + in_section = stripped == f"[{section}]" + elif in_section and re.match(rf"^{re.escape(key)}\s*=", stripped): + if not done: + out.append(f'{key} = "{value}"') + done = True + continue + out.append(line) + if not done: + if not in_section: + out += ["", f"[{section}]"] + out.append(f'{key} = "{value}"') + return "\n".join(out) + "\n" + + +def public_address() -> str: + """The source address this box uses to reach the internet (no packet is sent).""" + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + s.connect(("192.0.2.1", 9)) # TEST-NET-1; UDP connect only picks a route + return s.getsockname()[0] + + # ---------------------------------------------------------------- helpers @@ -449,6 +528,7 @@ VERBS = { "health": cmd_health, "delete": cmd_delete, "refresh-access": cmd_refresh_access, + "keygen": cmd_keygen, "_launch": cmd_launch, } @@ -484,7 +564,12 @@ def main(argv: list[str]) -> int: if not argv or argv[0] not in VERBS: raise UserError(f"usage: sessions-ctl {{{'|'.join(v for v in VERBS if not v.startswith('_'))}}} …") result = VERBS[argv[0]](load_config(), argv[1:]) - print(json.dumps({"ok": True, **result})) + if "text" in result and not remote: + print(result["text"]) # keygen: KEY=VALUE lines only, safe to paste as-is + if result.get("note"): + print(result["note"], file=sys.stderr) + else: + print(json.dumps({"ok": True, **result})) return 0 except UserError as e: print(json.dumps({"ok": False, "error": str(e)})) diff --git a/dev/tests/test_sessions_ctl.py b/dev/tests/test_sessions_ctl.py index 675362d..99718db 100644 --- a/dev/tests/test_sessions_ctl.py +++ b/dev/tests/test_sessions_ctl.py @@ -126,5 +126,73 @@ class MainContract(unittest.TestCase): 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()