Run sessions-web behind Authelia, configured only by env vars

Drop the app's own login (password hash, signed cookies, CSRF tokens, rate
limiting): Authelia via Caddy forward_auth is the login. The app refuses any
request without the Remote-User header (optionally limited to
SESSIONS_ALLOWED_USERS) and any cross-site POST (Sec-Fetch-Site / Origin).

The SSH key and the dev box host key now come from environment variables
printed by `sessions-ctl keygen`, so the container needs no secrets store or
mounts. Add compose.yaml so prod's panel can build and deploy it; remove the
Quadlet unit and the files it needed. README covers the panel deploy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KKYfRST9cTJYae3f7Jf3ac
This commit is contained in:
agent 2026-09-30 14:39:56 +00:00
parent ca66db3aeb
commit b55ea07c96
9 changed files with 254 additions and 332 deletions

View file

@ -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 <verb> <args>` 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 <verb> <args>` 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'<div class="flash err">{e(error)}</div>' if error else ""
return page("Sessions · sign in", f"""
<header><h1>Sessions</h1></header>{flash}
<form method="post" action="/login" class="card">
<label for="pw">Password</label><input id="pw" name="password" type="password" autocomplete="current-password" autofocus required>
<div class="actions"><button class="primary">Sign in</button></div></form>""")
def dashboard(listing: dict, repos: dict, csrf: str, flash: tuple[str, str] | None) -> bytes:
parts = ['<header><h1>Sessions</h1><form method="post" action="/logout" class="inline">'
f'<input type="hidden" name="csrf" value="{e(csrf)}"><button>Sign out</button></form></header>']
def dashboard(listing: dict, repos: dict, user: str, flash: tuple[str, str] | None) -> bytes:
parts = [f'<header><h1>Sessions</h1><span class="meta">{e(user)}</span></header>']
if flash:
parts.append(f'<div class="flash {e(flash[0])}">{e(flash[1])}</div>')
if not listing.get("ok"):
@ -236,12 +202,11 @@ def dashboard(listing: dict, repos: dict, csrf: str, flash: tuple[str, str] | No
<span class="pill {e(s["state"])}">{e(s["state"])}</span></div>
<div class="meta">{e(s["repo"])} · {e(s["branch"])} · since {e(s["created_at"][:16].replace("T", " "))}{restarts}</div>{warn}
<div class="actions">{link}<form method="post" action="/{verb}" class="inline">
<input type="hidden" name="csrf" value="{e(csrf)}"><input type="hidden" name="name" value="{e(s["name"])}">
<input type="hidden" name="name" value="{e(s["name"])}">
<button>{verb.title()}</button></form></div></div>""")
options = "".join(f'<option value="{e(r)}">{e(r)}</option>' for r in repos.get("repos", []))
parts.append(f"""<h2>New session</h2><form method="post" action="/create" class="card">
<input type="hidden" name="csrf" value="{e(csrf)}">
<label for="name">Name</label><input id="name" name="name" required pattern="[a-z0-9][a-z0-9\\-]{{0,31}}" placeholder="fix-login" autocapitalize="none" autocomplete="off">
<label for="repo">Repository</label><select id="repo" name="repo" required>{options}</select>
<label for="base">Start from branch (optional)</label><input id="base" name="base" placeholder="default branch" autocapitalize="none" autocomplete="off">
@ -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