diff --git a/AGENTS.md b/AGENTS.md index b0b021a..f6682b4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,13 +8,18 @@ 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`, Quadlet unit `sessions-web.container`. + `Containerfile`. `compose.yaml` at the root is what prod's panel deploys. + Configured only through env vars; `sessions-ctl keygen` prints them. ## 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` always prints exactly one JSON object; exit 0/1/2. +- `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. - 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 `. @@ -22,8 +27,10 @@ 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`, `_launch`) stay out of - `REMOTE_VERBS`. +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. 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. @@ -38,5 +45,7 @@ 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` and `SESSIONS_DEV_HOST=127.0.0.1`, -then remove the key line again. +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. diff --git a/README.md b/README.md index 7257274..eeaa517 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: reverse proxy ──▶ sessions-web (container, 127.0.0.1:8470) + phone/browser ──HTTPS──▶ prod: Caddy + Authelia ──▶ sessions-web (container, 127.0.0.1:) │ 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 | 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 | +| [`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 | ## Security model @@ -43,13 +43,20 @@ 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: 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. +- **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`. - 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 @@ -87,77 +94,74 @@ 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] -./dev/install.sh # writes the authorized_keys line -sessions-ctl health +$EDITOR ~/.config/sessions/config.toml # [repos] allowlist, [ssh_access] allow_from_host +sessions-ctl keygen # add --rotate to replace an existing key ``` +`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. -## Install: prod +## Deploy on prod (panel) -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. +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: ```sh -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 +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 ``` -### Reverse proxy +Then put it behind `forward_auth` in Caddy: -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 | |---|---| -| 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 | +| "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 | | 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 new file mode 100644 index 0000000..6687499 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,20 @@ +# 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/web/Containerfile b/web/Containerfile index 9971be6..e91b354 100644 --- a/web/Containerfile +++ b/web/Containerfile @@ -1,5 +1,5 @@ # sessions-web: the prod half of the session manager. -# Build: podman build -t localhost/sessions-web:latest web/ +# Configured entirely by environment variables (see app.py); no mounts needed. FROM docker.io/library/python:3.13-slim RUN apt-get update \ @@ -9,8 +9,6 @@ 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 b2a01da..8284338 100644 --- a/web/app.py +++ b/web/app.py @@ -1,137 +1,91 @@ #!/usr/bin/env python3 -"""sessions-web — a small password-protected page for starting Claude sessions. +"""sessions-web — a small page for starting Claude sessions on the dev box. -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. +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. -Configuration (environment): +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: SESSIONS_DEV_HOST dev box address (required) SESSIONS_DEV_PORT default 14922 SESSIONS_DEV_USER default agent - 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_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_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 getpass -import hashlib -import hmac +import binascii import html import json import os -import secrets +import re import shlex import signal import subprocess import sys -import threading -import time +import tempfile 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+/=]+$") -# ---------------------------------------------------------------- passwords +# ---------------------------------------------------------------- config -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()) +class ConfigError(Exception): + pass -def verify_password(password: str, encoded: str) -> bool: +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. + """ try: - 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 = 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…"') + 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") -# ---------------------------------------------------------------- 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()) + 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 # ---------------------------------------------------------------- dev box link class DevBox: - def __init__(self, env: dict): + def __init__(self, env: dict, key_path: str, known_hosts: str): self.host = env["SESSIONS_DEV_HOST"] self.port = env.get("SESSIONS_DEV_PORT", "14922") self.user = env.get("SESSIONS_DEV_USER", "agent") - self.key = env.get("SESSIONS_SSH_KEY", "/app/ssh_key") - self.known_hosts = env.get("SESSIONS_KNOWN_HOSTS", "/app/known_hosts") + self.key = key_path + self.known_hosts = known_hosts def argv(self, *args: str) -> list[str]: for a in args: # belt and braces: the dev box validates too @@ -170,6 +124,28 @@ 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 = """ @@ -205,18 +181,8 @@ def e(v) -> str: return html.escape(str(v if v is not None else "")) -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'
'] +def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes: + parts = [f'

Sessions

{e(user)}
'] if flash: parts.append(f'
{e(flash[1])}
') if not listing.get("ok"): @@ -236,12 +202,11 @@ def dashboard(listing: dict, repos: dict, csrf: 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

- @@ -254,15 +219,10 @@ def dashboard(listing: dict, repos: dict, csrf: str, flash: tuple[str, str] | No class App: - 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 __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 make_handler(app: App): @@ -270,14 +230,11 @@ def make_handler(app: App): server_version = "sessions-web" sys_version = "" - # -- 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 user(self) -> str: + return (self.headers.get(app.auth_header) or "").strip() def log_message(self, fmt, *args): - sys.stderr.write(f"{self.client_ip()} {fmt % args}\n") + sys.stderr.write(f"{self.user() or '-'} {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) @@ -293,19 +250,17 @@ def make_handler(app: App): if self.command != "HEAD": self.wfile.write(body) - 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) + def refuse_unauthenticated(self) -> bool: + """Fail closed if the request didn't come through Authelia. - 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 + 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 form(self) -> dict: n = int(self.headers.get("Content-Length") or 0) @@ -313,7 +268,6 @@ 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() @@ -321,15 +275,12 @@ 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: @@ -338,27 +289,15 @@ 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, csrf_token(app.secret, sess["sid"]), flash)) + self.send(200, dashboard(listing, repos, self.user(), 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(): @@ -370,40 +309,34 @@ 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.redirect("/?" + urllib.parse.urlencode({key: msg})) + self.send(HTTPStatus.SEE_OTHER, headers={"Location": "/?" + 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_PASSWORD_HASH", "SESSIONS_SECRET") if not env.get(k)] + missing = [k for k in ("SESSIONS_DEV_HOST", "SESSIONS_DEV_HOST_KEY", "SESSIONS_SSH_KEY_B64") if not env.get(k)] if missing: - print(f"missing configuration: {', '.join(missing)}", file=sys.stderr) + print(f"missing configuration: {', '.join(missing)} (run `sessions-ctl keygen` on the dev box)", file=sys.stderr) return 1 - app = App(env) + 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)) 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)) - print(f"sessions-web listening on {host}:{port}, dev box {app.dev.user}@{app.dev.host}:{app.dev.port}", file=sys.stderr) + 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) server.serve_forever() return 0 diff --git a/web/env.example b/web/env.example deleted file mode 100644 index 008ce0e..0000000 --- a/web/env.example +++ /dev/null @@ -1,8 +0,0 @@ -# ~/.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 deleted file mode 100644 index 531c10f..0000000 --- a/web/known_hosts.dev-box +++ /dev/null @@ -1 +0,0 @@ -[2.28.100.223]:14922 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEdLIHPjrkeUPfw1CDcIHC2Yydl39X46GBjmn6vqd+6E diff --git a/web/sessions-web.container b/web/sessions-web.container deleted file mode 100644 index 092164f..0000000 --- a/web/sessions-web.container +++ /dev/null @@ -1,34 +0,0 @@ -# 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 af23661..9f333d7 100644 --- a/web/tests/test_app.py +++ b/web/tests/test_app.py @@ -1,6 +1,10 @@ """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 @@ -8,64 +12,60 @@ _spec = importlib.util.spec_from_file_location("app", Path(__file__).parents[1] app = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(app) -SECRET = b"x" * 32 +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 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)) +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_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)) + 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 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") +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_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)) + 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"}) + 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_rejects_odd_arguments(self): @@ -81,8 +81,9 @@ class Rendering(unittest.TestCase): "name": "