diff --git a/AGENTS.md b/AGENTS.md index f6682b4..b0b021a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,18 +8,13 @@ model" before changing anything that touches the SSH boundary. - `dev/` runs on the **dev box**: `sessions_ctl.py` (installed as `~/.local/bin/sessions-ctl`), systemd user units, `install.sh`. - `web/` runs on **prod** in a rootless Podman container: `app.py`, - `Containerfile`. `compose.yaml` at the root is what prod's panel deploys. - Configured only through env vars; `sessions-ctl keygen` prints them. + `Containerfile`, Quadlet unit `sessions-web.container`. ## Stack and conventions - Python ≥ 3.11, **standard library only** on both sides. No pip install, so there's no supply chain to audit. Keep it that way unless there's a strong reason. - The web page has **no JavaScript**. Plain forms, POST, then a redirect. -- `sessions-ctl` prints exactly one JSON object (except `keygen`: KEY=VALUE - lines on stdout, human note on stderr); exit 0/1/2. -- The web app has no login: Authelia (Caddy forward_auth) in front of it is - the login. It must keep refusing requests without the auth header, and - refusing cross-site POSTs. +- `sessions-ctl` always prints exactly one JSON object; exit 0/1/2. - The dev port for local work on the web app is **8470**, bound to 127.0.0.1. Preview via `ssh -p 14922 -L 8470:localhost:8470 `. @@ -27,10 +22,8 @@ model" before changing anything that touches the SSH boundary. 1. Nothing received over SSH reaches a shell or Claude. No "initial prompt" feature, no free-text arguments. New remote verbs need validation *and* a test in `dev/tests/test_sessions_ctl.py`. -2. Local-only verbs (`delete`, `refresh-access`, `keygen`, `_launch`) stay out - of `REMOTE_VERBS`. -6. The private key is never written to disk on the dev box outside a temp dir - in `XDG_RUNTIME_DIR` (RAM), which `keygen` removes. +2. Local-only verbs (`delete`, `refresh-access`, `_launch`) stay out of + `REMOTE_VERBS`. 3. `refresh-access` never writes an empty `from=`, and never touches lines other than the one ending in ` sessions-manager`. 4. The session unit keeps `DBUS_SESSION_BUS_ADDRESS` pointed at nothing. @@ -45,7 +38,5 @@ python3 -m unittest discover -s web/tests ``` To test end to end on the dev box, add a throwaway key with `from="127.0.0.1",restrict,command=".../sessions-ctl --remote" … sessions-selftest`, -run the container with `--network host`, `SESSIONS_DEV_HOST=127.0.0.1` and the -key as `SESSIONS_SSH_KEY_B64`, send requests with a `Remote-User` header, then -remove the key line again. Never run the real `keygen` from an agent session: -its output is a private key and would end up in the transcript. +run the container with `--network host` and `SESSIONS_DEV_HOST=127.0.0.1`, +then remove the key line again. diff --git a/README.md b/README.md index eeaa517..7257274 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ without SSHing in yourself. Each session runs `claude` with **Remote Control**, you then talk to it from the Claude app or the "Open in Claude" link. ``` - phone/browser ──HTTPS──▶ prod: Caddy + Authelia ──▶ sessions-web (container, 127.0.0.1:) + phone/browser ──HTTPS──▶ prod: reverse proxy ──▶ sessions-web (container, 127.0.0.1:8470) │ ssh, key locked to one command ▼ dev box: sessions-ctl --remote ──▶ systemd: claude-session@ @@ -17,8 +17,8 @@ you then talk to it from the Claude app or the "Open in Claude" link. |---|---|---| | [`dev/sessions_ctl.py`](dev/sessions_ctl.py) | dev box, `~/.local/bin/sessions-ctl` | CLI + SSH forced command. Stdlib Python ≥ 3.11 | | [`dev/systemd/`](dev/systemd) | dev box, `~/.config/systemd/user/` | one unit per session; hourly key-IP refresh | -| [`web/app.py`](web/app.py) | prod, container | session list + buttons; stdlib, no JS, no login of its own | -| [`compose.yaml`](compose.yaml) | prod, panel | how the panel builds and runs the container | +| [`web/app.py`](web/app.py) | prod, container | login page + session list; stdlib, no JS | +| [`web/sessions-web.container`](web/sessions-web.container) | prod, Quadlet | runs the container under systemd, restarts at boot | ## Security model @@ -43,20 +43,13 @@ from="",restrict,command="…/sessions-ctl --remote" ssh-ed2551 prompt". Instructions go through Remote Control, which is guarded by your claude.ai account, not by prod. So the worst a hijacked prod can do is start sessions up to `max_running`, or stop them. -- **The web app has no login of its own; Authelia is the login.** It serves - only requests carrying `Remote-User`, which Caddy's `forward_auth` sets from - Authelia (overwriting anything the client sent). With the header missing it - answers 403. That's a tripwire in case the route ever loses forward_auth, - not the protection itself. `SESSIONS_ALLOWED_USERS` can narrow it to named - users. Authelia's policy for the domain should be `two_factor`. It is by - default on prod. -- Cross-site POSTs are refused by checking `Sec-Fetch-Site`/`Origin`, so no - CSRF secret is needed. The page has a strict CSP and no JavaScript. The dev - box host key is pinned (`StrictHostKeyChecking yes`). -- The container is configured only by environment variables, including the - SSH key (one base64 line). At start it writes the key to a 0600 file on its - `/tmp` tmpfs. It runs rootless with a read-only root filesystem and all - capabilities dropped, published only on `127.0.0.1`. +- The web app: scrypt password hash, HMAC-signed `HttpOnly; Secure; + SameSite=Strict` cookie, CSRF token on every POST, 5 failed logins per IP / + 20 overall per 15 min, strict CSP, no JavaScript. It pins the dev box host + key (`StrictHostKeyChecking yes`). +- The container is rootless, has a read-only root filesystem and drops all + capabilities. It publishes only to `127.0.0.1`. Secrets are Podman secrets, + not files beside the unit. - Every remote call is logged on the dev box: `journalctl -t sessions-ctl`. **Folder trust:** Claude Code asks "do you trust this folder?" on first launch @@ -94,74 +87,77 @@ Claude Code field. If a Claude Code update breaks it, the session shows ```sh git clone ssh://git@git.reudy.net:14922/reudy-net/sessions.git && cd sessions ./dev/install.sh # idempotent; re-run after every pull -$EDITOR ~/.config/sessions/config.toml # [repos] allowlist, [ssh_access] allow_from_host -sessions-ctl keygen # add --rotate to replace an existing key +$EDITOR ~/.config/sessions/config.toml # [repos] allowlist + [ssh_access] +./dev/install.sh # writes the authorized_keys line +sessions-ctl health ``` -`keygen` makes the key pair prod uses. It generates it in RAM, writes the -public half to the config and `authorized_keys` (replacing the old -`sessions-manager` line), and prints the five environment variables for prod -to stdout, with a note on stderr. The private key is then deleted from this -box, so the printed copy is the only one. Paste it, then clear the terminal. -If it's lost, run `keygen --rotate` and paste again. - Requires linger (`sudo loginctl enable-linger agent`); `install.sh` warns if it's off. -## Deploy on prod (panel) +## Install: prod -The repo root has a `compose.yaml`, so the panel can build and run it: - -1. **New app** in the panel from the Forgejo repo `reudy-net/sessions`, branch `main`. -2. **Environment**: paste the five lines `sessions-ctl keygen` printed. Optional: - `SESSIONS_ALLOWED_USERS=reudy`. -3. **Route**: e.g. `sessions.reudy.net` → service `web`, port `8470`, with - **Authelia on**. From the CLI: - `panelctl init sessions "sessions.reudy.net|127.0.0.1:18470||web:8470" true` -4. **Deploy.** The container log should say - `sessions-web on 0.0.0.0:8470 → agent@:14922 …`. -5. Open `https://sessions.reudy.net`, sign in through Authelia, and you should - see the session list. An error there comes from the dev box (see - Troubleshooting). - -**Reboots:** the container has `restart: unless-stopped`. Rootless Podman only -honours that at boot if the user's `podman-restart.service` is enabled -(`systemctl --user is-enabled podman-restart` as the panel user). That applies -to every panel app, so it belongs in the NixOS config. - -### Without the panel - -Any container runtime works. Put the five variables in a `chmod 600` env -file and run: +As the rootless user that will run the container. Replace `~/.ssh/` with +the private half of the key that is in the dev box's config. ```sh -podman build -t localhost/sessions-web web/ -podman run -d --name sessions-web --restart unless-stopped \ - --env-file ~/.config/sessions-web/env -p 127.0.0.1:8470:8470 \ - --read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges \ - localhost/sessions-web +git clone ssh://git@git.reudy.net:14922/reudy-net/sessions.git && cd sessions +podman build -t localhost/sessions-web:latest web/ + +# 1. Secrets (nothing is echoed; each command reads from a file or a hidden prompt) +podman secret create sessions-ssh-key ~/.ssh/ +head -c 48 /dev/urandom | base64 -w0 | podman secret create sessions-web-secret - +read -rsp 'Web password (12+ chars): ' PW; echo +printf '%s\n' "$PW" | podman run --rm -i localhost/sessions-web:latest python3 /app/app.py hash-password --stdin \ + | podman secret create sessions-password-hash - ; unset PW + +# 2. Non-secret config + the dev box's pinned host key +install -d -m 700 ~/.config/sessions-web +install -m 600 web/env.example ~/.config/sessions-web/env +install -m 644 web/known_hosts.dev-box ~/.config/sessions-web/known_hosts + +# 3. Check that the key works from this machine before involving the container +ssh -i ~/.ssh/ -p 14922 -o UserKnownHostsFile=web/known_hosts.dev-box agent@2.28.100.223 health + +# 4. Run under systemd (starts at boot only with linger on for this user) +install -D -m 644 web/sessions-web.container ~/.config/containers/systemd/sessions-web.container +systemctl --user daemon-reload +systemctl --user start sessions-web +curl -s http://127.0.0.1:8470/healthz # → ok ``` -Then put it behind `forward_auth` in Caddy: +### Reverse proxy +The container listens on `127.0.0.1:8470` only. Put it behind the proxy that already +terminates TLS on prod, for example at `sessions.reudy.net`. The proxy must set +`X-Forwarded-For` for the rate limiter (`SESSIONS_TRUST_PROXY=1`). + +Caddy: ``` sessions.reudy.net { - forward_auth 127.0.0.1:9091 { - uri /api/authz/forward-auth - copy_headers Remote-User Remote-Groups Remote-Email Remote-Name - } reverse_proxy 127.0.0.1:8470 } ``` +nginx: +``` +location / { + proxy_pass http://127.0.0.1:8470; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; +} +``` + +### Updating prod +```sh +git pull && podman build -t localhost/sessions-web:latest web/ && systemctl --user restart sessions-web +``` ## Troubleshooting | Symptom | Check | |---|---| -| "forbidden: this page must be served behind Authelia" | The route has no forward_auth, or the user isn't in `SESSIONS_ALLOWED_USERS` | -| Container exits with "configuration error" | One of the env values was pasted incompletely. Run `sessions-ctl keygen --rotate` again and paste all five lines | -| Page says "dev box unreachable: Permission denied" | Prod's outgoing IP isn't the one `reudy.net` resolves to, or the env holds an old key. On the dev box, `sudo journalctl -u ssh -n 20` shows the source IP. `sessions-ctl refresh-access` shows what `from=` holds | -| "Host key verification failed" | The dev box's host key changed. Check that the change is expected, then update `SESSIONS_DEV_HOST_KEY`. Never turn off checking | +| Page says "dev box unreachable: Permission denied" | Prod's outgoing IP isn't the one `reudy.net` resolves to. On the dev box, `sudo journalctl -u ssh -n 20` shows the source IP. `sessions-ctl refresh-access` shows what `from=` holds | +| "Host key verification failed" | The dev box's host key changed. Update `known_hosts.dev-box` deliberately; never turn off checking | | Session `failed` | `journalctl --user -u claude-session@NAME -n 50`. After 5 crashes in 10 min systemd gives up; fix the cause, then Start again | | "stuck on the folder-trust prompt" | `tmux -L claude-NAME attach`, accept, detach. Then the trust field has moved in a Claude Code update, so fix `trust_workspace()` | | No "Open in Claude" link | The link is read from the pane once Remote Control is up; refresh after a few seconds | diff --git a/compose.yaml b/compose.yaml deleted file mode 100644 index 6687499..0000000 --- a/compose.yaml +++ /dev/null @@ -1,20 +0,0 @@ -# Deployed on prod by the panel (reudy-net/panel): it builds this, injects the -# app's environment variables, and publishes web:8470 on 127.0.0.1 for the -# route, which must have Authelia turned on. The variables come from running -# `sessions-ctl keygen` on the dev box — see README "Deploy on prod". -services: - web: - build: ./web - image: localhost/sessions-web:latest - restart: unless-stopped - read_only: true - tmpfs: - - /tmp - cap_drop: - - ALL - security_opt: - - no-new-privileges:true - healthcheck: - test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8470/healthz', timeout=4)"] - interval: 60s - timeout: 5s diff --git a/dev/config.example.toml b/dev/config.example.toml index 6740691..8ee8db2 100644 --- a/dev/config.example.toml +++ b/dev/config.example.toml @@ -21,10 +21,5 @@ 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. 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 +# The public half of the key the web app container uses. +public_key = "ssh-ed25519 AAAA… comment" diff --git a/dev/install.sh b/dev/install.sh index 0cbf501..6cb9354 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 run: sessions-ctl keygen" + echo "created $cfg_dir/config.toml — edit [repos] and [ssh_access], then re-run." 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 "no key for prod yet — run: sessions-ctl keygen" + echo "ssh_access.public_key not set yet — skipping authorized_keys." fi echo "installed. try: sessions-ctl health" diff --git a/dev/sessions_ctl.py b/dev/sessions_ctl.py index 29a839c..fa479cc 100755 --- a/dev/sessions_ctl.py +++ b/dev/sessions_ctl.py @@ -18,16 +18,13 @@ 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 one JSON object on stdout (except `keygen`, which prints an env -block to copy). Exit codes: 0 ok, 1 error, 2 usage. +Output is always one JSON object on stdout. 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 @@ -50,7 +47,6 @@ 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 @@ -78,8 +74,7 @@ class UserError(Exception): # ---------------------------------------------------------------- config/state -def load_config(path: Path | None = None) -> dict: - path = path or CONFIG_PATH # looked up at call time, so tests can repoint it +def load_config(path: Path = CONFIG_PATH) -> dict: cfg = dict(DEFAULTS) if path.exists(): with path.open("rb") as f: @@ -404,80 +399,6 @@ 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 @@ -528,7 +449,6 @@ VERBS = { "health": cmd_health, "delete": cmd_delete, "refresh-access": cmd_refresh_access, - "keygen": cmd_keygen, "_launch": cmd_launch, } @@ -564,12 +484,7 @@ 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:]) - 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})) + 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 99718db..675362d 100644 --- a/dev/tests/test_sessions_ctl.py +++ b/dev/tests/test_sessions_ctl.py @@ -126,73 +126,5 @@ 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() diff --git a/web/Containerfile b/web/Containerfile index e91b354..9971be6 100644 --- a/web/Containerfile +++ b/web/Containerfile @@ -1,5 +1,5 @@ # sessions-web: the prod half of the session manager. -# Configured entirely by environment variables (see app.py); no mounts needed. +# Build: podman build -t localhost/sessions-web:latest web/ FROM docker.io/library/python:3.13-slim RUN apt-get update \ @@ -9,6 +9,8 @@ RUN apt-get update \ WORKDIR /app COPY app.py /app/app.py +# Mount points must already exist: the container runs with a read-only root. +RUN touch /app/ssh_key /app/known_hosts USER 10001 ENV PYTHONUNBUFFERED=1 SESSIONS_LISTEN=0.0.0.0:8470 diff --git a/web/app.py b/web/app.py index 8284338..b2a01da 100644 --- a/web/app.py +++ b/web/app.py @@ -1,91 +1,137 @@ #!/usr/bin/env python3 -"""sessions-web — a small page for starting Claude sessions on the dev box. +"""sessions-web — a small password-protected page for starting Claude sessions. -Runs on prod in a container, behind Authelia (Caddy forward_auth). It has no -login of its own: it serves only requests that carry the user header Authelia -sets, and it never touches Claude itself — every action is one -`ssh dev-box ` call to sessions-ctl, which the dev box pins to a -forced command. Standard library only; no JavaScript on the page. +Runs on prod (in a container). It never touches Claude itself: every action is +one `ssh dev-box ` call to sessions-ctl, which the dev box pins to +a forced command. Standard library only; no JavaScript on the page. -Configuration (environment; every value is one line, so the panel can set it). -`sessions-ctl keygen` on the dev box prints the first five ready to paste: +Configuration (environment): SESSIONS_DEV_HOST dev box address (required) SESSIONS_DEV_PORT default 14922 SESSIONS_DEV_USER default agent - SESSIONS_DEV_HOST_KEY dev box SSH host key, "ssh-ed25519 AAAA…" (required) - SESSIONS_SSH_KEY_B64 base64 of the OpenSSH private key (required) - SESSIONS_AUTH_HEADER header the proxy sets after login (default Remote-User) - SESSIONS_ALLOWED_USERS optional comma-separated usernames; empty = any - user Authelia lets through + SESSIONS_SSH_KEY private key file (default /app/ssh_key) + SESSIONS_KNOWN_HOSTS pinned host key file (default /app/known_hosts) + SESSIONS_PASSWORD_HASH output of `app.py hash-password` (required) + SESSIONS_SECRET >= 32 random chars for signing cookies (required) SESSIONS_LISTEN default 0.0.0.0:8470 (inside the container) + SESSIONS_COOKIE_SECURE 1 (default) = cookie only over HTTPS; 0 for local tests + SESSIONS_TRUST_PROXY 1 = take the client IP from X-Forwarded-For (only + when a reverse proxy you control sets it) """ from __future__ import annotations import base64 -import binascii +import getpass +import hashlib +import hmac import html import json import os -import re +import secrets import shlex import signal import subprocess import sys -import tempfile +import threading +import time import urllib.parse from http import HTTPStatus +from http.cookies import SimpleCookie from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +COOKIE = "sessions_auth" +SESSION_TTL = 12 * 3600 NAME_CHARS = set("abcdefghijklmnopqrstuvwxyz0123456789-") -HOST_KEY_RE = re.compile(r"^(ssh-ed25519|ecdsa-sha2-nistp256|ssh-rsa) [A-Za-z0-9+/=]+$") -# ---------------------------------------------------------------- config +# ---------------------------------------------------------------- passwords -class ConfigError(Exception): - pass +def hash_password(password: str, *, n: int = 2**15, r: int = 8, p: int = 1) -> str: + salt = secrets.token_bytes(16) + dk = hashlib.scrypt(password.encode(), salt=salt, n=n, r=r, p=p, maxmem=64 * 1024 * 1024) + return "scrypt${}${}${}${}${}".format(n, r, p, base64.b64encode(salt).decode(), base64.b64encode(dk).decode()) -def materialise_ssh_files(env: dict, directory: str) -> tuple[str, str]: - """Write the private key and a known_hosts file from env into `directory`. - - ssh wants files; the panel (and `podman run -e`) gives us single-line env - values. `directory` is a private (0700) temp dir on the container's /tmp. - """ +def verify_password(password: str, encoded: str) -> bool: try: - key = base64.b64decode(env.get("SESSIONS_SSH_KEY_B64", "").strip(), validate=True) - except (binascii.Error, ValueError): - raise ConfigError("SESSIONS_SSH_KEY_B64 is not valid base64") - if not key.startswith(b"-----BEGIN OPENSSH PRIVATE KEY-----"): - raise ConfigError("SESSIONS_SSH_KEY_B64 does not decode to an OpenSSH private key") - host_key = env.get("SESSIONS_DEV_HOST_KEY", "").strip() - if not HOST_KEY_RE.fullmatch(host_key): - raise ConfigError('SESSIONS_DEV_HOST_KEY must look like "ssh-ed25519 AAAA…"') + algo, n, r, p, salt, dk = encoded.split("$") + if algo != "scrypt": + return False + got = hashlib.scrypt(password.encode(), salt=base64.b64decode(salt), n=int(n), r=int(r), p=int(p), maxmem=64 * 1024 * 1024) + return hmac.compare_digest(got, base64.b64decode(dk)) + except (ValueError, TypeError): + return False - key_path = os.path.join(directory, "id") - fd = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) - with os.fdopen(fd, "wb") as f: - f.write(key if key.endswith(b"\n") else key + b"\n") - host, port = env["SESSIONS_DEV_HOST"], env.get("SESSIONS_DEV_PORT", "14922") - known = os.path.join(directory, "known_hosts") - with open(known, "w") as f: - f.write(f"[{host}]:{port} {host_key}\n") - return key_path, known +# ---------------------------------------------------------------- cookies + + +def sign(secret: bytes, payload: dict) -> str: + body = base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).decode() + mac = hmac.new(secret, body.encode(), hashlib.sha256).hexdigest() + return f"{body}.{mac}" + + +def unsign(secret: bytes, token: str, now: float | None = None) -> dict | None: + try: + body, mac = token.rsplit(".", 1) + except ValueError: + return None + if not hmac.compare_digest(mac, hmac.new(secret, body.encode(), hashlib.sha256).hexdigest()): + return None + try: + payload = json.loads(base64.urlsafe_b64decode(body)) + except ValueError: + return None + if payload.get("exp", 0) < (now or time.time()): + return None + return payload + + +def csrf_token(secret: bytes, sid: str) -> str: + return hmac.new(secret, f"csrf:{sid}".encode(), hashlib.sha256).hexdigest() + + +# ---------------------------------------------------------------- rate limit + + +class RateLimiter: + """Failed logins: at most `per_ip` per window per client, `total` overall.""" + + def __init__(self, per_ip: int = 5, total: int = 20, window: int = 900): + self.per_ip, self.total, self.window = per_ip, total, window + self.fails: dict[str, list[float]] = {} + self.lock = threading.Lock() + + def _prune(self, now: float) -> None: + for ip in list(self.fails): + self.fails[ip] = [t for t in self.fails[ip] if now - t < self.window] + if not self.fails[ip]: + del self.fails[ip] + + def blocked(self, ip: str, now: float | None = None) -> bool: + now = now or time.time() + with self.lock: + self._prune(now) + return len(self.fails.get(ip, [])) >= self.per_ip or sum(map(len, self.fails.values())) >= self.total + + def fail(self, ip: str, now: float | None = None) -> None: + with self.lock: + self.fails.setdefault(ip, []).append(now or time.time()) # ---------------------------------------------------------------- dev box link class DevBox: - def __init__(self, env: dict, key_path: str, known_hosts: str): + def __init__(self, env: dict): self.host = env["SESSIONS_DEV_HOST"] self.port = env.get("SESSIONS_DEV_PORT", "14922") self.user = env.get("SESSIONS_DEV_USER", "agent") - self.key = key_path - self.known_hosts = known_hosts + self.key = env.get("SESSIONS_SSH_KEY", "/app/ssh_key") + self.known_hosts = env.get("SESSIONS_KNOWN_HOSTS", "/app/known_hosts") def argv(self, *args: str) -> list[str]: for a in args: # belt and braces: the dev box validates too @@ -124,28 +170,6 @@ class DevBox: return {"ok": False, "error": f"dev box unreachable: {err[:200]}"} -# ---------------------------------------------------------------- request checks - - -def same_origin(headers, host: str) -> bool: - """Reject cross-site POSTs without needing a CSRF secret. - - Browsers send Sec-Fetch-Site and/or Origin on every POST. Either must say - the request came from this site; a request with neither is refused. - """ - site = headers.get("Sec-Fetch-Site") - if site is not None: - return site == "same-origin" - origin = headers.get("Origin") - if origin: - return urllib.parse.urlsplit(origin).netloc == host - return False - - -def allowed_user(user: str, allowed: set[str]) -> bool: - return bool(user) and (not allowed or user in allowed) - - # ---------------------------------------------------------------- HTML CSS = """ @@ -181,8 +205,18 @@ def e(v) -> str: return html.escape(str(v if v is not None else "")) -def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes: - parts = [f'

Sessions

{e(user)}
'] +def login_page(error: str = "") -> bytes: + flash = f'
{e(error)}
' if error else "" + return page("Sessions · sign in", f""" +

Sessions

{flash} +
+ +
""") + + +def dashboard(listing: dict, repos: dict, csrf: str, flash: tuple[str, str] | None) -> bytes: + parts = ['

Sessions

' + f'
'] if flash: parts.append(f'
{e(flash[1])}
') if not listing.get("ok"): @@ -202,11 +236,12 @@ def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | No {e(s["state"])}
{e(s["repo"])} · {e(s["branch"])} · since {e(s["created_at"][:16].replace("T", " "))}{restarts}
{warn}
{link}
- +
""") options = "".join(f'' for r in repos.get("repos", [])) parts.append(f"""

New session

+ @@ -219,10 +254,15 @@ def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | No class App: - def __init__(self, env: dict, dev: DevBox): - self.dev = dev - self.auth_header = env.get("SESSIONS_AUTH_HEADER", "Remote-User") - self.allowed_users = {u.strip() for u in env.get("SESSIONS_ALLOWED_USERS", "").split(",") if u.strip()} + def __init__(self, env: dict): + self.password_hash = env["SESSIONS_PASSWORD_HASH"].strip() + self.secret = env["SESSIONS_SECRET"].strip().encode() + if len(self.secret) < 32: + raise SystemExit("SESSIONS_SECRET must be at least 32 characters") + self.cookie_secure = env.get("SESSIONS_COOKIE_SECURE", "1") == "1" + self.trust_proxy = env.get("SESSIONS_TRUST_PROXY", "0") == "1" + self.dev = DevBox(env) + self.limiter = RateLimiter() def make_handler(app: App): @@ -230,11 +270,14 @@ def make_handler(app: App): server_version = "sessions-web" sys_version = "" - def user(self) -> str: - return (self.headers.get(app.auth_header) or "").strip() + # -- plumbing + def client_ip(self) -> str: + if app.trust_proxy and self.headers.get("X-Forwarded-For"): + return self.headers["X-Forwarded-For"].split(",")[-1].strip() + return self.client_address[0] def log_message(self, fmt, *args): - sys.stderr.write(f"{self.user() or '-'} {fmt % args}\n") + sys.stderr.write(f"{self.client_ip()} {fmt % args}\n") def send(self, status: int, body: bytes = b"", ctype: str = "text/html; charset=utf-8", headers: dict | None = None): self.send_response(status) @@ -250,17 +293,19 @@ def make_handler(app: App): if self.command != "HEAD": self.wfile.write(body) - def refuse_unauthenticated(self) -> bool: - """Fail closed if the request didn't come through Authelia. + def redirect(self, to: str, cookie: str | None = None): + headers = {"Location": to} + if cookie is not None: + headers["Set-Cookie"] = cookie + self.send(HTTPStatus.SEE_OTHER, headers=headers) - Behind Caddy's forward_auth the header is always set by Authelia - (copy_headers overwrites whatever the client sent). If it's - missing, the route has lost its forward_auth — don't serve. - """ - if allowed_user(self.user(), app.allowed_users): - return False - self.send(403, b"forbidden: this page must be served behind Authelia\n", "text/plain") - return True + def cookie_header(self, value: str, max_age: int) -> str: + secure = "; Secure" if app.cookie_secure else "" + return f"{COOKIE}={value}; Max-Age={max_age}; Path=/; HttpOnly; SameSite=Strict{secure}" + + def auth(self) -> dict | None: + jar = SimpleCookie(self.headers.get("Cookie", "")) + return unsign(app.secret, jar[COOKIE].value) if COOKIE in jar else None def form(self) -> dict: n = int(self.headers.get("Content-Length") or 0) @@ -268,6 +313,7 @@ def make_handler(app: App): return {} return {k: v[0] for k, v in urllib.parse.parse_qs(self.rfile.read(n).decode(errors="replace")).items()} + # -- routes def do_HEAD(self): self.do_GET() @@ -275,12 +321,15 @@ def make_handler(app: App): path = urllib.parse.urlsplit(self.path).path if path == "/healthz": return self.send(200, b"ok\n", "text/plain") - if self.refuse_unauthenticated(): - return if path == "/app.css": return self.send(200, CSS.encode(), "text/css") + if path == "/login": + return self.send(200, login_page()) if path != "/": return self.send(404, b"not found\n", "text/plain") + sess = self.auth() + if not sess: + return self.redirect("/login") flash = None q = urllib.parse.parse_qs(urllib.parse.urlsplit(self.path).query) if "ok" in q: @@ -289,15 +338,27 @@ def make_handler(app: App): flash = ("err", q["err"][0][:300]) listing = app.dev.call("list") repos = app.dev.call("repos") if listing.get("ok") else {} - self.send(200, dashboard(listing, repos, self.user(), flash)) + self.send(200, dashboard(listing, repos, csrf_token(app.secret, sess["sid"]), flash)) def do_POST(self): - if self.refuse_unauthenticated(): - return - if not same_origin(self.headers, self.headers.get("Host", "")): - return self.send(403, b"forbidden: cross-site request\n", "text/plain") path = urllib.parse.urlsplit(self.path).path f = self.form() + if path == "/login": + ip = self.client_ip() + if app.limiter.blocked(ip): + return self.send(429, login_page("Too many attempts. Try again in 15 minutes.")) + if not verify_password(f.get("password", ""), app.password_hash): + app.limiter.fail(ip) + self.log_message("login failed") + return self.send(401, login_page("Wrong password.")) + token = sign(app.secret, {"sid": secrets.token_urlsafe(16), "exp": int(time.time()) + SESSION_TTL}) + return self.redirect("/", self.cookie_header(token, SESSION_TTL)) + + sess = self.auth() + if not sess or not hmac.compare_digest(f.get("csrf", ""), csrf_token(app.secret, sess["sid"])): + return self.send(403, b"forbidden\n", "text/plain") + if path == "/logout": + return self.redirect("/login", self.cookie_header("", 0)) if path == "/create": args = [f.get("name", "").strip(), f.get("repo", "")] if f.get("base", "").strip(): @@ -309,34 +370,40 @@ def make_handler(app: App): done = {"/start": "started", "/stop": "stopped"}[path] + f" {f.get('name', '')}" else: return self.send(404, b"not found\n", "text/plain") - self.log_message("%s %s -> %s", path, f.get("name", ""), "ok" if r.get("ok") else r.get("error")) key, msg = ("ok", done) if r.get("ok") else ("err", r.get("error", "failed")) - self.send(HTTPStatus.SEE_OTHER, headers={"Location": "/?" + urllib.parse.urlencode({key: msg})}) + self.redirect("/?" + urllib.parse.urlencode({key: msg})) return Handler def main(argv: list[str]) -> int: + if argv[:1] == ["hash-password"]: + # --stdin: read the password from a pipe (see README) so that no prompt + # text can end up in the output that is piped into `podman secret create`. + if argv[1:] == ["--stdin"]: + pw = sys.stdin.readline().rstrip("\n") + else: + pw = getpass.getpass("New password: ") + if getpass.getpass("Again: ") != pw: + print("passwords differ", file=sys.stderr) + return 1 + if len(pw) < 12: + print("use at least 12 characters", file=sys.stderr) + return 1 + sys.stdout.write(hash_password(pw)) + return 0 env = dict(os.environ) - missing = [k for k in ("SESSIONS_DEV_HOST", "SESSIONS_DEV_HOST_KEY", "SESSIONS_SSH_KEY_B64") if not env.get(k)] + missing = [k for k in ("SESSIONS_DEV_HOST", "SESSIONS_PASSWORD_HASH", "SESSIONS_SECRET") if not env.get(k)] if missing: - print(f"missing configuration: {', '.join(missing)} (run `sessions-ctl keygen` on the dev box)", file=sys.stderr) + print(f"missing configuration: {', '.join(missing)}", file=sys.stderr) return 1 - workdir = tempfile.mkdtemp(prefix="sessions-web-") # 0700, on the container's /tmp tmpfs - try: - key_path, known = materialise_ssh_files(env, workdir) - except ConfigError as err: - print(f"configuration error: {err}", file=sys.stderr) - return 1 - app = App(env, DevBox(env, key_path, known)) + app = App(env) host, _, port = env.get("SESSIONS_LISTEN", "0.0.0.0:8470").rpartition(":") server = ThreadingHTTPServer((host, int(port)), make_handler(app)) # As PID 1 in a container Python gets no default SIGTERM handling, so # `podman stop` would hang for 10 s and then SIGKILL. Exit cleanly instead. signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) - who = ", ".join(sorted(app.allowed_users)) or "any user Authelia admits" - print(f"sessions-web on {host}:{port} → {app.dev.user}@{app.dev.host}:{app.dev.port}; " - f"auth header {app.auth_header}; allowed: {who}", file=sys.stderr) + print(f"sessions-web listening on {host}:{port}, dev box {app.dev.user}@{app.dev.host}:{app.dev.port}", file=sys.stderr) server.serve_forever() return 0 diff --git a/web/env.example b/web/env.example new file mode 100644 index 0000000..008ce0e --- /dev/null +++ b/web/env.example @@ -0,0 +1,8 @@ +# ~/.config/sessions-web/env on prod — non-secret settings only (chmod 600 anyway). +# Secrets (SSH key, cookie secret, password hash) are podman secrets; see README. +SESSIONS_DEV_HOST=2.28.100.223 +SESSIONS_DEV_PORT=14922 +SESSIONS_DEV_USER=agent +# The reverse proxy in front sets X-Forwarded-For; trust it for rate limiting. +SESSIONS_TRUST_PROXY=1 +SESSIONS_COOKIE_SECURE=1 diff --git a/web/known_hosts.dev-box b/web/known_hosts.dev-box new file mode 100644 index 0000000..531c10f --- /dev/null +++ b/web/known_hosts.dev-box @@ -0,0 +1 @@ +[2.28.100.223]:14922 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEdLIHPjrkeUPfw1CDcIHC2Yydl39X46GBjmn6vqd+6E diff --git a/web/sessions-web.container b/web/sessions-web.container new file mode 100644 index 0000000..092164f --- /dev/null +++ b/web/sessions-web.container @@ -0,0 +1,34 @@ +# Podman Quadlet unit for prod. Install as the (rootless) user that runs it: +# ~/.config/containers/systemd/sessions-web.container +# then: systemctl --user daemon-reload && systemctl --user start sessions-web +# Starts at boot only if that user has linger (sudo loginctl enable-linger ). +[Unit] +Description=sessions-web (Claude session manager UI) +After=network-online.target +Wants=network-online.target + +[Container] +Image=localhost/sessions-web:latest +ContainerName=sessions-web +# Loopback only — the reverse proxy on this host is the only way in. +PublishPort=127.0.0.1:8470:8470 +EnvironmentFile=%h/.config/sessions-web/env +# Secrets live in podman's secret store, not in files next to this unit. +Secret=sessions-ssh-key,type=mount,target=/app/ssh_key,mode=0400,uid=10001 +Secret=sessions-web-secret,type=env,target=SESSIONS_SECRET +Secret=sessions-password-hash,type=env,target=SESSIONS_PASSWORD_HASH +Volume=%h/.config/sessions-web/known_hosts:/app/known_hosts:ro,Z +ReadOnly=true +Tmpfs=/tmp +Tmpfs=/home/app +HealthCmd=python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8470/healthz', timeout=4)" +HealthInterval=60s +DropCapability=ALL +NoNewPrivileges=true + +[Service] +Restart=always +RestartSec=5 + +[Install] +WantedBy=default.target diff --git a/web/tests/test_app.py b/web/tests/test_app.py index 9f333d7..af23661 100644 --- a/web/tests/test_app.py +++ b/web/tests/test_app.py @@ -1,10 +1,6 @@ """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 @@ -12,60 +8,64 @@ _spec = importlib.util.spec_from_file_location("app", Path(__file__).parents[1] 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(), -} +SECRET = b"x" * 32 -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") +class Passwords(unittest.TestCase): + def test_roundtrip(self): + h = app.hash_password("correct horse battery", n=2**10) + self.assertTrue(app.verify_password("correct horse battery", h)) + self.assertFalse(app.verify_password("wrong", h)) - 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) + def test_garbage_hash_is_false_not_crash(self): + for h in ("", "plain", "scrypt$x$y$z$a$b", "md5$1$2$3$4$5"): + self.assertFalse(app.verify_password("pw", h)) -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)) +class Cookies(unittest.TestCase): + def test_sign_unsign(self): + tok = app.sign(SECRET, {"sid": "abc", "exp": 2_000_000_000}) + self.assertEqual(app.unsign(SECRET, tok)["sid"], "abc") - 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"})) + def test_tampered_or_expired(self): + tok = app.sign(SECRET, {"sid": "abc", "exp": 2_000_000_000}) + body, mac = tok.rsplit(".", 1) + forged = app.sign(b"y" * 32, {"sid": "abc", "exp": 2_000_000_000}) + self.assertIsNone(app.unsign(SECRET, forged)) + self.assertIsNone(app.unsign(SECRET, body + "." + "0" * 64)) + self.assertIsNone(app.unsign(SECRET, "nodot")) + old = app.sign(SECRET, {"sid": "abc", "exp": 100}) + self.assertIsNone(app.unsign(SECRET, old)) + + def test_csrf_bound_to_session(self): + self.assertNotEqual(app.csrf_token(SECRET, "a"), app.csrf_token(SECRET, "b")) + + +class Limiter(unittest.TestCase): + def test_per_ip_and_window(self): + rl = app.RateLimiter(per_ip=2, total=10, window=100) + rl.fail("1.1.1.1", now=0) + self.assertFalse(rl.blocked("1.1.1.1", now=1)) + rl.fail("1.1.1.1", now=1) + self.assertTrue(rl.blocked("1.1.1.1", now=2)) + self.assertFalse(rl.blocked("2.2.2.2", now=2)) + self.assertFalse(rl.blocked("1.1.1.1", now=200)) + + def test_global_cap(self): + rl = app.RateLimiter(per_ip=5, total=3, window=100) + for i in range(3): + rl.fail(f"10.0.0.{i}", now=0) + self.assertTrue(rl.blocked("9.9.9.9", now=1)) class SshArgv(unittest.TestCase): def setUp(self): - self.dev = app.DevBox({"SESSIONS_DEV_HOST": "dev.example"}, "/k", "/kh") + self.dev = app.DevBox({"SESSIONS_DEV_HOST": "dev.example"}) 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_rejects_odd_arguments(self): @@ -81,9 +81,8 @@ class Rendering(unittest.TestCase): "name": "