Add registration toggle and password change; genericise deploy

Two things the running instance needed.

**Registration toggle.** Admin -> General, backed by a new settings table
group rather than the environment. LEMBAS_ALLOW_SIGNUP now seeds only the
initial value: once an administrator saves the setting, the stored value
wins. The alternative -- environment always winning -- means a toggle in
the UI silently reverts on the next restart, which is worse than not
offering one. Closing registration also removes the "Create one" link
from the sign-in page, so the link never leads somewhere that refuses.

**Password change**, on the user settings page. Changing a password
revokes every other session and immediately re-issues a cookie for the
current one: if the reason for the change is that somebody else knows
the password, leaving their session alive defeats the point, but signing
the user out of the tab they are standing in is merely rude.

**deploy/ is now host-agnostic.** This repository is public, so the unit
and vhost became templates with __PREFIX__ / __SITE_HOST__ / __APP_PORT__
substituted at install time, and every path, hostname and port moved to
environment variables. REPO_URL defaults to the checkout's own origin so
a fork deploys itself. Machine-specific values belong in private notes,
not here -- CLAUDE.md now says so.

83 tests, ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-07-21 11:14:33 +02:00
parent 0f44e8d24c
commit 9179461bfe
16 changed files with 713 additions and 149 deletions
+4 -2
View File
@@ -20,8 +20,10 @@ LEMBAS_RELOAD=false
# debug | info | warning | error # debug | info | warning | error
LEMBAS_LOG_LEVEL=info LEMBAS_LOG_LEVEL=info
# Allow new accounts to register themselves. The very first account created is # Allow new accounts to register themselves. This is only the INITIAL value:
# always an admin, regardless of this setting. Turn off once your users exist. # once an administrator sets it under Admin -> General, the stored setting wins
# and this variable is ignored. The very first account created is always an
# admin regardless.
LEMBAS_ALLOW_SIGNUP=true LEMBAS_ALLOW_SIGNUP=true
# Default theme for signed-out visitors: moria (dark) or shire (light). # Default theme for signed-out visitors: moria (dark) or shire (light).
+4 -2
View File
@@ -37,7 +37,9 @@ runtime. Clone it, `pip install -e .`, run it.
- **OpenAI connections** — point at OpenAI, LM Studio, vLLM, llama.cpp, - **OpenAI connections** — point at OpenAI, LM Studio, vLLM, llama.cpp,
llama-swap, Ollama or OpenRouter; models are discovered and cached llama-swap, Ollama or OpenRouter; models are discovered and cached
- **Accounts** — first account becomes the administrator, argon2 password - **Accounts** — first account becomes the administrator, argon2 password
hashing, revocable server-side sessions hashing, revocable server-side sessions, self-service password change
- **Admin settings** — open or close registration from the UI, stored in the
database and effective immediately
- **Two themes** — *Moria* (dark) and *Shire* (light), switchable per user - **Two themes** — *Moria* (dark) and *Shire* (light), switchable per user
**Planned** **Planned**
@@ -80,7 +82,7 @@ All variables are prefixed `LEMBAS_` and can live in `.env`. See
| `LEMBAS_SECRET_KEY` | *generated* | Signs sessions and encrypts stored API keys. **Set this.** A generated key changes every restart, signing everyone out and making stored API keys unreadable. | | `LEMBAS_SECRET_KEY` | *generated* | Signs sessions and encrypts stored API keys. **Set this.** A generated key changes every restart, signing everyone out and making stored API keys unreadable. |
| `LEMBAS_DATA_DIR` | `./data` | SQLite database and uploads. | | `LEMBAS_DATA_DIR` | `./data` | SQLite database and uploads. |
| `LEMBAS_HOST` / `LEMBAS_PORT` | `127.0.0.1` / `8080` | Bind address. | | `LEMBAS_HOST` / `LEMBAS_PORT` | `127.0.0.1` / `8080` | Bind address. |
| `LEMBAS_ALLOW_SIGNUP` | `true` | Let new users register themselves. The first account is always an admin regardless. | | `LEMBAS_ALLOW_SIGNUP` | `true` | Whether new users may register themselves — the *initial* value only. Once set under **Admin → General** the stored setting wins. The first account is always an admin regardless. |
| `LEMBAS_DEFAULT_THEME` | `moria` | `moria` (dark) or `shire` (light). | | `LEMBAS_DEFAULT_THEME` | `moria` | `moria` (dark) or `shire` (light). |
| `LEMBAS_SESSION_TTL` | `2592000` | Session lifetime in seconds. | | `LEMBAS_SESSION_TTL` | `2592000` | Session lifetime in seconds. |
| `LEMBAS_REQUEST_TIMEOUT` | `300` | Seconds to wait on an upstream model. | | `LEMBAS_REQUEST_TIMEOUT` | `300` | Seconds to wait on an upstream model. |
+43 -33
View File
@@ -1,51 +1,63 @@
# Deployment # Deployment
Installs LLeMbas as a **system** service behind nginx at `https://chat.lan`. Installs LLeMbas as a **system** service behind nginx with a self-signed
certificate. Written for a systemd + nginx host; tested on Arch.
Written for `gamebox` (Arch), and follows the conventions already used there | | Default |
for llama-swap and comfyui:
| | |
|---|---| |---|---|
| Service user | `lembas` (system account, `nologin`) | | Service user | `lembas` (system account, `nologin`) |
| Home | `/home/lembas`, bind-mounted to `/srv/lembas` | | Home | `/home/lembas` |
| Checkout | `/srv/lembas/app` (git clone of the Gitea remote) | | Install prefix | `/srv/lembas` (bind mount of the home) |
| Virtualenv | `/srv/lembas/venv` | | Checkout | `$PREFIX/app` |
| Database | `/srv/lembas/data/lembas.db` | | Virtualenv | `$PREFIX/venv` |
| Environment | `/srv/lembas/lembas.env` (mode 600) | | Database | `$PREFIX/data/lembas.db` |
| Environment | `$PREFIX/lembas.env` (mode 600) |
| Unit | `/etc/systemd/system/lembas.service` | | Unit | `/etc/systemd/system/lembas.service` |
| Vhost | `/etc/nginx/conf.d/chat.lan.conf`, self-signed cert | | Vhost | `/etc/nginx/conf.d/<host>.conf` |
| Listens | `127.0.0.1:8080` — reachable only through nginx | | Listens on | `127.0.0.1:8080` — reachable only through nginx |
The home lives on `/home` rather than `/var/lib` because the root LV on that The prefix defaults to a bind mount of the service user's home because on many
box is only 50 GB; `/srv/lembas` is the same bind-mount trick as `/srv/llama` machines the root filesystem is small while `/home` is not, and the virtualenv
and `/srv/comfyui`. plus database belong on the larger volume. Set `PREFIX=$HOME_DIR` to skip it.
## First install ## First install
```bash ```bash
./deploy/install.sh SITE_HOST=chat.example ./deploy/install.sh
``` ```
Idempotent — safe to re-run. It creates the user and bind mount, clones the Idempotent — safe to re-run. It creates the user and bind mount, clones the
repo, builds the venv, generates `lembas.env` with a fresh repo, builds the venv, generates `lembas.env` with a fresh `LEMBAS_SECRET_KEY`,
`LEMBAS_SECRET_KEY`, installs the unit and vhost, issues a self-signed cert, installs the unit and vhost, issues a self-signed certificate, adds a
adds a `/etc/hosts` entry, and enables the service. `/etc/hosts` entry if the name does not already resolve, and enables the
service.
Then open <https://chat.lan>, accept the self-signed certificate warning, and Then open `https://<SITE_HOST>`, accept the certificate warning, and create the
create the first account — it becomes the administrator. first account — it becomes the administrator.
Everything is overridable from the environment:
| Variable | Default | |
|---|---|---|
| `SITE_HOST` | `lembas.local` | nginx `server_name` and certificate CN |
| `APP_PORT` | `8080` | loopback port the service binds |
| `SERVICE_USER` | `lembas` | system account to run as |
| `HOME_DIR` | `/home/lembas` | that account's home |
| `PREFIX` | `/srv/lembas` | install root (bind mount of `HOME_DIR`) |
| `REPO_URL` | this checkout's `origin` | so a fork deploys itself |
| `LEMBAS_BRANCH` | `main` | branch to deploy |
## Deploying a change ## Deploying a change
```bash ```bash
git push # from the working copy git push
./deploy/update.sh ./deploy/update.sh
``` ```
`update.sh` fetches, hard-resets `/srv/lembas/app` to `origin/main`, reinstalls `update.sh` fetches, hard-resets the deployment checkout to `origin/main`,
dependencies and restarts the service, then prints what changed. The hard reset reinstalls dependencies and restarts, printing the commits it pulled. The hard
is deliberate: nothing is ever edited in place there, so there is no local work reset is deliberate: nothing is ever edited in place there, so there is no local
to preserve and no merge conflicts to resolve. work to preserve and no conflicts to resolve.
## Operating it ## Operating it
@@ -53,10 +65,9 @@ to preserve and no merge conflicts to resolve.
systemctl status lembas systemctl status lembas
journalctl -u lembas -f journalctl -u lembas -f
sudo -u lembas /srv/lembas/venv/bin/lembas info # paths and counts sudo -u lembas /srv/lembas/venv/bin/lembas info # paths and counts
sudo systemctl restart lembas
``` ```
Configuration lives in `/srv/lembas/lembas.env`. Edit it and restart. Configuration lives in `$PREFIX/lembas.env`. Edit it and restart.
## Notes ## Notes
@@ -70,11 +81,10 @@ delivers it in one lump at the end, which is indistinguishable from streaming
being broken. `proxy_read_timeout` is raised to an hour because a model can being broken. `proxy_read_timeout` is raised to an hour because a model can
think for minutes before the first token. think for minutes before the first token.
**Name resolution.** `chat.lan` is in Pi-hole, but this box queries the router
first and the router's dnsmasq is authoritative for `.lan` without forwarding
those queries on — the same reason `comfy.lan` needs one. `install.sh` adds a
`/etc/hosts` entry, which is harmless if DNS already answers.
**Hardening is deliberately moderate.** `ProtectSystem=full`, not `strict`: the **Hardening is deliberately moderate.** `ProtectSystem=full`, not `strict`: the
agentic features planned for later need to run commands, and a lockdown that agentic features planned for later need to run commands, and a lockdown that
has to be torn out again is worse than one that was never applied. has to be torn out again is worse than one that was never applied.
**Use a real certificate if this is exposed beyond a trusted LAN.** The
self-signed cert exists so the install works with no external dependencies;
point `ssl_certificate` at a real one and nothing else needs to change.
+62 -32
View File
@@ -1,28 +1,52 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Install LLeMbas as a system service behind nginx at https://chat.lan. # Install LLeMbas as a system service behind nginx with a self-signed cert.
# #
# Follows the conventions already used on this box for llama-swap and comfyui: # Creates a dedicated service user, a virtualenv, a systemd unit and an nginx
# a dedicated service user whose home lives on /home (the root LV is only # vhost. Idempotent: safe to re-run. To deploy new code afterwards use
# 50 GB) and is bind-mounted to /srv/<name>, a system unit so it survives # update.sh, which is what a `git push` should be followed by.
# logout, and an nginx vhost with a self-signed cert.
# #
# Idempotent: safe to re-run. To deploy new code afterwards use update.sh, # Everything is configurable from the environment:
# which is what a `git push` should be followed by. #
# SITE_HOST=chat.example ./deploy/install.sh # vhost name
# APP_PORT=8080 # loopback port
# PREFIX=/srv/lembas # install root
# HOME_DIR=/home/lembas # service user's home
# REPO_URL=... # defaults to this checkout's origin
#
# PREFIX defaults to a bind mount of HOME_DIR rather than living directly under
# /srv, because on many machines the root filesystem is small and the venv plus
# database belong on the larger /home volume. Set PREFIX=HOME_DIR to skip that.
set -euo pipefail set -euo pipefail
REPO_URL="${LEMBAS_REPO_URL:-https://git.houmeres.sk/Houmeres/LLeMbas.git}" HERE="$(dirname "$(readlink -f "$0")")"
SITE_HOST="${SITE_HOST:-lembas.local}"
APP_PORT="${APP_PORT:-8080}"
SERVICE_USER="${SERVICE_USER:-lembas}"
HOME_DIR="${HOME_DIR:-/home/lembas}"
PREFIX="${PREFIX:-/srv/lembas}"
BRANCH="${LEMBAS_BRANCH:-main}" BRANCH="${LEMBAS_BRANCH:-main}"
SERVICE_USER=lembas # Default to wherever this checkout came from, so a fork deploys itself.
HOME_DIR=/home/lembas REPO_URL="${REPO_URL:-$(git -C "$HERE" remote get-url origin 2>/dev/null || true)}"
PREFIX=/srv/lembas
APP="$PREFIX/app" APP="$PREFIX/app"
VENV="$PREFIX/venv" VENV="$PREFIX/venv"
ENV_FILE="$PREFIX/lembas.env" ENV_FILE="$PREFIX/lembas.env"
HERE="$(dirname "$(readlink -f "$0")")"
if [[ -z "$REPO_URL" ]]; then
echo "Could not determine REPO_URL. Set it explicitly." >&2
exit 1
fi
echo "== plan =="
echo " host : https://$SITE_HOST -> 127.0.0.1:$APP_PORT"
echo " user : $SERVICE_USER ($HOME_DIR)"
echo " prefix : $PREFIX"
echo " repo : $REPO_URL ($BRANCH)"
echo "== service user ==" echo "== service user =="
# --system: no ageing, no mail spool. Home under /home, not /var/lib, so the # --system: no ageing, no mail spool. Home under /home, not /var/lib, so the
# venv and database sit on the big volume. # venv and database sit on the larger volume.
if ! getent passwd "$SERVICE_USER" >/dev/null; then if ! getent passwd "$SERVICE_USER" >/dev/null; then
sudo useradd --system --create-home --home-dir "$HOME_DIR" \ sudo useradd --system --create-home --home-dir "$HOME_DIR" \
--shell /usr/bin/nologin --comment "LLeMbas" "$SERVICE_USER" --shell /usr/bin/nologin --comment "LLeMbas" "$SERVICE_USER"
@@ -31,12 +55,14 @@ else
fi fi
sudo chmod 755 "$HOME_DIR" sudo chmod 755 "$HOME_DIR"
echo "== /srv/lembas bind-mount onto /home ==" if [[ "$PREFIX" != "$HOME_DIR" ]]; then
echo "== $PREFIX bind-mount onto $HOME_DIR =="
sudo mkdir -p "$PREFIX" sudo mkdir -p "$PREFIX"
grep -q "^$HOME_DIR[[:space:]]" /etc/fstab \ grep -q "^$HOME_DIR[[:space:]]" /etc/fstab \
|| echo "$HOME_DIR $PREFIX none bind 0 0" | sudo tee -a /etc/fstab >/dev/null || echo "$HOME_DIR $PREFIX none bind 0 0" | sudo tee -a /etc/fstab >/dev/null
sudo systemctl daemon-reload sudo systemctl daemon-reload
mountpoint -q "$PREFIX" || sudo mount "$PREFIX" mountpoint -q "$PREFIX" || sudo mount "$PREFIX"
fi
echo "== checkout ==" echo "== checkout =="
if [[ ! -d "$APP/.git" ]]; then if [[ ! -d "$APP/.git" ]]; then
@@ -53,8 +79,8 @@ sudo -u "$SERVICE_USER" "$VENV/bin/pip" install --quiet --upgrade pip
sudo -u "$SERVICE_USER" "$VENV/bin/pip" install --quiet -e "$APP" sudo -u "$SERVICE_USER" "$VENV/bin/pip" install --quiet -e "$APP"
echo "== environment ==" echo "== environment =="
# Generated once and never regenerated: rotating LEMBAS_SECRET_KEY would sign # Generated once and never regenerated: rotating LEMBAS_SECRET_KEY signs every
# every user out and make the stored API keys unreadable. # user out AND makes the stored upstream API keys unreadable.
if [[ ! -f "$ENV_FILE" ]]; then if [[ ! -f "$ENV_FILE" ]]; then
KEY=$("$VENV/bin/python" -c "import secrets; print(secrets.token_urlsafe(48))") KEY=$("$VENV/bin/python" -c "import secrets; print(secrets.token_urlsafe(48))")
sudo tee "$ENV_FILE" >/dev/null <<EOF sudo tee "$ENV_FILE" >/dev/null <<EOF
@@ -63,9 +89,9 @@ if [[ ! -f "$ENV_FILE" ]]; then
# Changing it signs everyone out and makes stored API keys unreadable. # Changing it signs everyone out and makes stored API keys unreadable.
LEMBAS_SECRET_KEY=$KEY LEMBAS_SECRET_KEY=$KEY
LEMBAS_DATA_DIR=$PREFIX/data LEMBAS_DATA_DIR=$PREFIX/data
# Loopback only: reachable through the nginx chat.lan vhost, never direct. # Loopback only: reachable through the nginx vhost, never directly.
LEMBAS_HOST=127.0.0.1 LEMBAS_HOST=127.0.0.1
LEMBAS_PORT=8080 LEMBAS_PORT=$APP_PORT
LEMBAS_LOG_LEVEL=info LEMBAS_LOG_LEVEL=info
LEMBAS_ALLOW_SIGNUP=true LEMBAS_ALLOW_SIGNUP=true
LEMBAS_DEFAULT_THEME=moria LEMBAS_DEFAULT_THEME=moria
@@ -80,30 +106,34 @@ fi
sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 750 "$PREFIX/data" sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 750 "$PREFIX/data"
echo "== systemd unit ==" echo "== systemd unit =="
sudo install -Dm644 "$HERE/lembas.service" /etc/systemd/system/lembas.service sed -e "s|__PREFIX__|$PREFIX|g" -e "s|__SERVICE_USER__|$SERVICE_USER|g" \
"$HERE/lembas.service" | sudo tee /etc/systemd/system/lembas.service >/dev/null
sudo systemctl daemon-reload sudo systemctl daemon-reload
echo "== self-signed cert for chat.lan ==" echo "== self-signed cert for $SITE_HOST =="
sudo mkdir -p /etc/nginx/ssl sudo mkdir -p /etc/nginx/ssl
if [[ ! -f /etc/nginx/ssl/chat.lan.crt ]]; then if [[ ! -f "/etc/nginx/ssl/$SITE_HOST.crt" ]]; then
sudo openssl req -x509 -newkey rsa:2048 -nodes \ sudo openssl req -x509 -newkey rsa:2048 -nodes \
-keyout /etc/nginx/ssl/chat.lan.key -out /etc/nginx/ssl/chat.lan.crt \ -keyout "/etc/nginx/ssl/$SITE_HOST.key" -out "/etc/nginx/ssl/$SITE_HOST.crt" \
-days 3650 -subj "/CN=chat.lan" -addext "subjectAltName=DNS:chat.lan" -days 3650 -subj "/CN=$SITE_HOST" -addext "subjectAltName=DNS:$SITE_HOST"
sudo chmod 600 /etc/nginx/ssl/chat.lan.key sudo chmod 600 "/etc/nginx/ssl/$SITE_HOST.key"
sudo chmod 644 /etc/nginx/ssl/chat.lan.crt sudo chmod 644 "/etc/nginx/ssl/$SITE_HOST.crt"
fi fi
echo "== nginx vhost ==" echo "== nginx vhost =="
sudo install -Dm644 "$HERE/chat.lan.nginx.conf" /etc/nginx/conf.d/chat.lan.conf sed -e "s|__SITE_HOST__|$SITE_HOST|g" -e "s|__APP_PORT__|$APP_PORT|g" \
"$HERE/nginx-vhost.conf" | sudo tee "/etc/nginx/conf.d/$SITE_HOST.conf" >/dev/null
sudo nginx -t sudo nginx -t
sudo systemctl reload nginx sudo systemctl reload nginx
echo "== local name resolution ==" echo "== local name resolution =="
# chat.lan is in Pi-hole, but this box asks the router first and the router's # Only useful when the LAN's DNS does not already answer for this name.
# dnsmasq is authoritative for .lan without forwarding it on -- same reason if ! getent hosts "$SITE_HOST" >/dev/null; then
# comfy.lan needs a hosts entry. Harmless if DNS already resolves it. printf '127.0.0.1\t%s\n::1\t\t%s\n' "$SITE_HOST" "$SITE_HOST" | sudo tee -a /etc/hosts >/dev/null
grep -q 'chat\.lan' /etc/hosts \ echo " added $SITE_HOST to /etc/hosts"
|| printf '127.0.0.1\tchat.lan\n::1\t\tchat.lan\n' | sudo tee -a /etc/hosts >/dev/null else
echo " $SITE_HOST already resolves"
fi
echo "== enable service ==" echo "== enable service =="
sudo systemctl enable --now lembas sudo systemctl enable --now lembas
@@ -111,5 +141,5 @@ sleep 2
sudo systemctl --no-pager --lines=0 status lembas || true sudo systemctl --no-pager --lines=0 status lembas || true
echo echo
echo "LLeMbas is up at https://chat.lan (self-signed cert; accept the warning)" echo "LLeMbas is up at https://$SITE_HOST (self-signed cert; accept the warning)"
echo "Create the first account -- it becomes the administrator." echo "Create the first account -- it becomes the administrator."
+18 -23
View File
@@ -1,48 +1,43 @@
# LLeMbas system service. # LLeMbas system service template.
# #
# Deployed to /etc/systemd/system/lembas.service by deploy/install.sh. # install.sh substitutes __PREFIX__ and __SERVICE_USER__ and writes the result
# to /etc/systemd/system/lembas.service. Edit this file, not the installed copy.
# #
# A system unit, not a user unit, so it survives logout and comes up at boot # A system unit, not a user unit, so it survives logout and comes up at boot
# without anyone signing in -- matching llama-swap and comfyui on this box. # without anyone signing in.
#
# /srv/lembas is a bind mount of /home/lembas: the root LV is only 50 GB and
# the venv plus SQLite database belong on /home, same trick as /srv/llama.
[Unit] [Unit]
Description=LLeMbas - web UI for language models Description=LLeMbas - web UI for language models
Documentation=https://git.houmeres.sk/Houmeres/LLeMbas
After=network-online.target After=network-online.target
Wants=network-online.target Wants=network-online.target
# The unit is useless without the bind mount: the venv and database live there. # The prefix is usually a bind mount; the venv and database live there, so
RequiresMountsFor=/srv/lembas # starting before it is mounted would create an empty database in its place.
# Not a hard dependency. LLeMbas starts fine with the endpoint down and shows a RequiresMountsFor=__PREFIX__
# readable error in the admin UI, which is better than refusing to boot.
After=llama-swap.service
[Service] [Service]
Type=simple Type=simple
User=lembas User=__SERVICE_USER__
Group=lembas Group=__SERVICE_USER__
WorkingDirectory=/srv/lembas/app WorkingDirectory=__PREFIX__/app
EnvironmentFile=/srv/lembas/lembas.env EnvironmentFile=__PREFIX__/lembas.env
ExecStart=/srv/lembas/venv/bin/lembas serve ExecStart=__PREFIX__/venv/bin/lembas serve
Restart=on-failure Restart=on-failure
RestartSec=5 RestartSec=5
# Reachable only through the nginx chat.lan vhost, never directly on the LAN. # The bind address comes from LEMBAS_HOST in the environment file, which the
# The bind address is set by LEMBAS_HOST in the environment file. # installer sets to 127.0.0.1: reachable through nginx, never directly.
# --- Hardening ------------------------------------------------------------- # --- Hardening -------------------------------------------------------------
# Modest rather than maximal: the agentic features planned for later will need # Moderate rather than maximal. The agentic features planned for later need to
# to run commands, so ProtectSystem=strict would only be torn out again. # run commands, and a lockdown that has to be torn out again is worse than one
# that was never applied.
NoNewPrivileges=yes NoNewPrivileges=yes
PrivateTmp=yes PrivateTmp=yes
ProtectSystem=full ProtectSystem=full
ProtectKernelTunables=yes ProtectKernelTunables=yes
ProtectControlGroups=yes ProtectControlGroups=yes
RestrictSUIDSGID=yes RestrictSUIDSGID=yes
# Only /srv/lembas needs to be writable; /home/lembas is the same inode. ReadWritePaths=__PREFIX__
ReadWritePaths=/srv/lembas
LimitNOFILE=65535 LimitNOFILE=65535
[Install] [Install]
@@ -1,12 +1,16 @@
# chat.lan - HTTPS reverse proxy to LLeMbas (127.0.0.1:8080). # nginx vhost template for LLeMbas.
# Deployed to /etc/nginx/conf.d/chat.lan.conf. Self-signed cert (chat.lan).
# #
# Mirrors the comfy.lan and llama.lan vhosts on this box. # install.sh substitutes __SITE_HOST__ and __APP_PORT__ and writes the result to
# /etc/nginx/conf.d/<host>.conf. Edit this file, not the installed copy.
#
# Assumes a self-signed certificate at /etc/nginx/ssl/<host>.{crt,key}, which
# install.sh generates. To use a real certificate, point ssl_certificate at it;
# nothing else here needs to change.
server { server {
listen 80; listen 80;
listen [::]:80; listen [::]:80;
server_name chat.lan; server_name __SITE_HOST__;
return 301 https://$host$request_uri; return 301 https://$host$request_uri;
} }
@@ -14,17 +18,17 @@ server {
listen 443 ssl; listen 443 ssl;
listen [::]:443 ssl; listen [::]:443 ssl;
http2 on; http2 on;
server_name chat.lan; server_name __SITE_HOST__;
ssl_certificate /etc/nginx/ssl/chat.lan.crt; ssl_certificate /etc/nginx/ssl/__SITE_HOST__.crt;
ssl_certificate_key /etc/nginx/ssl/chat.lan.key; ssl_certificate_key /etc/nginx/ssl/__SITE_HOST__.key;
ssl_protocols TLSv1.2 TLSv1.3; ssl_protocols TLSv1.2 TLSv1.3;
# File uploads land here once that feature exists; 0 = no limit. # File uploads land here once that feature exists; 0 = no limit.
client_max_body_size 0; client_max_body_size 0;
location / { location / {
proxy_pass http://127.0.0.1:8080; proxy_pass http://127.0.0.1:__APP_PORT__;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
@@ -32,13 +36,14 @@ server {
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
# Streamed replies are server-sent events. Every one of these matters: # Streamed replies are server-sent events. Every one of these matters:
# with buffering on, nginx holds the whole reply and delivers it in one # with buffering on (the default) nginx holds the whole reply and
# lump at the end, which looks exactly like streaming being broken. # delivers it in one lump at the end, which is indistinguishable from
# streaming being broken.
proxy_buffering off; proxy_buffering off;
proxy_request_buffering off; proxy_request_buffering off;
proxy_cache off; proxy_cache off;
# SSE is plain HTTP/1.1 chunked, so the connection header must not be # SSE is plain HTTP/1.1 chunked, not a websocket upgrade, so the
# the websocket upgrade dance -- it must simply stay open. # connection header must simply be left to keep-alive.
proxy_set_header Connection ""; proxy_set_header Connection "";
# A model can think for minutes before the first token. The default # A model can think for minutes before the first token. The default
@@ -47,9 +52,8 @@ server {
proxy_send_timeout 3600s; proxy_send_timeout 3600s;
} }
# Static assets are immutable per release and never need revalidating.
location /static/ { location /static/ {
proxy_pass http://127.0.0.1:8080; proxy_pass http://127.0.0.1:__APP_PORT__;
proxy_set_header Host $host; proxy_set_header Host $host;
expires 1h; expires 1h;
add_header Cache-Control "public"; add_header Cache-Control "public";
+19 -16
View File
@@ -1,36 +1,39 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Pull the latest LLeMbas and restart the service. # Pull the latest LLeMbas into the deployment and restart the service.
# #
# This is what to run after pushing: it fetches, hard-resets the deployment # Run this after pushing. It fetches, hard-resets the deployment checkout to the
# checkout to the remote branch, reinstalls dependencies if they changed, and # remote branch, reinstalls dependencies if they changed, and restarts. Nothing
# restarts. Nothing is ever edited in place at /srv/lembas/app, so a hard reset # is ever edited in place under the deployment prefix, so a hard reset is safe
# is safe and avoids merge conflicts from a dirty deployment tree. # and avoids merge conflicts from a dirty tree.
set -euo pipefail set -euo pipefail
SERVICE_USER=lembas SERVICE_USER="${SERVICE_USER:-lembas}"
PREFIX=/srv/lembas PREFIX="${PREFIX:-/srv/lembas}"
BRANCH="${LEMBAS_BRANCH:-main}"
APP="$PREFIX/app" APP="$PREFIX/app"
VENV="$PREFIX/venv" VENV="$PREFIX/venv"
BRANCH="${LEMBAS_BRANCH:-main}"
if [[ ! -d "$APP/.git" ]]; then if [[ ! -d "$APP/.git" ]]; then
echo "No deployment at $APP. Run deploy/install.sh first." >&2 echo "No deployment at $APP. Run deploy/install.sh first." >&2
exit 1 exit 1
fi fi
before=$(sudo -u "$SERVICE_USER" git -C "$APP" rev-parse HEAD) git_as() { sudo -u "$SERVICE_USER" git -C "$APP" "$@"; }
before=$(git_as rev-parse HEAD)
echo "== fetching ==" echo "== fetching =="
sudo -u "$SERVICE_USER" git -C "$APP" fetch --quiet origin "$BRANCH" git_as fetch --quiet origin "$BRANCH"
sudo -u "$SERVICE_USER" git -C "$APP" reset --hard --quiet "origin/$BRANCH" git_as reset --hard --quiet "origin/$BRANCH"
after=$(sudo -u "$SERVICE_USER" git -C "$APP" rev-parse HEAD) after=$(git_as rev-parse HEAD)
if [[ "$before" == "$after" ]]; then if [[ "$before" == "$after" ]]; then
echo " already at $(git -C "$APP" rev-parse --short HEAD), nothing to pull" echo " already at ${after:0:7}, nothing to pull"
else else
echo " $(echo "$before" | cut -c1-7) -> $(echo "$after" | cut -c1-7)" echo " ${before:0:7} -> ${after:0:7}"
sudo -u "$SERVICE_USER" git -C "$APP" --no-pager log --oneline "$before..$after" | sed 's/^/ /' git_as --no-pager log --oneline "$before..$after" | sed 's/^/ /'
fi fi
# Cheap and idempotent; catches a dependency added since the last deploy. # Cheap and idempotent; catches a dependency added since the last deploy.
@@ -42,7 +45,7 @@ sudo systemctl restart lembas
sleep 2 sleep 2
if systemctl is-active --quiet lembas; then if systemctl is-active --quiet lembas; then
echo " lembas is running at https://chat.lan" echo " lembas is running"
else else
echo " lembas FAILED to start:" >&2 echo " lembas FAILED to start:" >&2
sudo journalctl -u lembas -n 30 --no-pager >&2 sudo journalctl -u lembas -n 30 --no-pager >&2
+39 -2
View File
@@ -11,7 +11,8 @@ from sqlalchemy import func, select
from sqlalchemy.orm import Session as DBSession from sqlalchemy.orm import Session as DBSession
from lembas.api.deps import AdminUser, Db from lembas.api.deps import AdminUser, Db
from lembas.db.models import Connection, Model from lembas.db.models import Connection, Model, User
from lembas.services import settings_store
from lembas.services.crypto import decrypt, encrypt, mask from lembas.services.crypto import decrypt, encrypt, mask
from lembas.services.llm.openai_client import Endpoint, LLMError, list_models from lembas.services.llm.openai_client import Endpoint, LLMError, list_models
from lembas.web.templating import render from lembas.web.templating import render
@@ -39,7 +40,43 @@ def _connections(db: DBSession) -> list[Connection]:
@router.get("") @router.get("")
async def admin_home(user: AdminUser): async def admin_home(user: AdminUser):
return RedirectResponse("/admin/connections", status_code=status.HTTP_303_SEE_OTHER) return RedirectResponse("/admin/general", status_code=status.HTTP_303_SEE_OTHER)
@router.get("/general")
async def general_page(request: Request, db: Db, user: AdminUser, saved: bool = False):
return render(
request,
"admin/general.html",
{
"values": settings_store.get_group(db),
"saved": saved,
"user_count": db.scalar(select(func.count()).select_from(User)),
},
)
@router.post("/general")
async def save_general(
db: Db,
user: AdminUser,
instance_name: str = Form("LLeMbas"),
allow_signup: bool = Form(False),
) -> Response:
"""Save instance settings.
Unchecked checkboxes are simply absent from a form post, which is why
allow_signup defaults to False here -- that absence *is* the "off" signal.
"""
settings_store.update(
db,
{
"instance_name": instance_name.strip()[:120] or "LLeMbas",
"allow_signup": allow_signup,
},
)
log.info("registration %s by %s", "opened" if allow_signup else "closed", user.email)
return RedirectResponse("/admin/general?saved=1", status_code=status.HTTP_303_SEE_OTHER)
@router.get("/connections") @router.get("/connections")
+33 -17
View File
@@ -13,6 +13,7 @@ from lembas.config import settings
from lembas.db.models import ROLE_ADMIN, ROLE_USER, User from lembas.db.models import ROLE_ADMIN, ROLE_USER, User
from lembas.security.passwords import hash_password, validate_password, verify_password from lembas.security.passwords import hash_password, validate_password, verify_password
from lembas.security.sessions import COOKIE_NAME, create_session, revoke_session from lembas.security.sessions import COOKIE_NAME, create_session, revoke_session
from lembas.services import settings_store
from lembas.web.templating import render from lembas.web.templating import render
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -48,6 +49,19 @@ def _safe_next(raw: str | None) -> str:
return raw return raw
def _login_page(request: Request, db: Db, *, status_code: int = 200, **context):
"""Render the sign-in page.
Always goes through here so `allow_signup` reflects the *stored* setting
rather than the environment default baked in by render(). Otherwise the
"Create one" link would keep appearing after an administrator closed
registration, offering a link that only leads to a refusal.
"""
context.setdefault("next", "/")
context["allow_signup"] = settings_store.signup_allowed(db)
return render(request, "auth/login.html", context, status_code=status_code)
@router.get("/login") @router.get("/login")
async def login_form(request: Request, db: Db, user: CurrentUser, next: str = "/"): async def login_form(request: Request, db: Db, user: CurrentUser, next: str = "/"):
if user is not None: if user is not None:
@@ -57,7 +71,7 @@ async def login_form(request: Request, db: Db, user: CurrentUser, next: str = "/
# cannot possibly satisfy. # cannot possibly satisfy.
if _no_users_yet(db): if _no_users_yet(db):
return RedirectResponse("/auth/register", status_code=status.HTTP_303_SEE_OTHER) return RedirectResponse("/auth/register", status_code=status.HTTP_303_SEE_OTHER)
return render(request, "auth/login.html", {"next": _safe_next(next)}) return _login_page(request, db, next=_safe_next(next))
@router.post("/login") @router.post("/login")
@@ -75,21 +89,23 @@ async def login(
# cannot be used to discover which addresses are registered. # cannot be used to discover which addresses are registered.
if user is None or not verify_password(password, user.password_hash): if user is None or not verify_password(password, user.password_hash):
log.info("failed sign-in for %s", email) log.info("failed sign-in for %s", email)
return render( return _login_page(
request, request,
"auth/login.html", db,
{"error": "That email and password do not match.", "email": email,
"next": _safe_next(next)},
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
error="That email and password do not match.",
email=email,
next=_safe_next(next),
) )
if not user.active: if not user.active:
return render( return _login_page(
request, request,
"auth/login.html", db,
{"error": "This account has been deactivated. Ask an administrator.",
"email": email, "next": _safe_next(next)},
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
error="This account has been deactivated. Ask an administrator.",
email=email,
next=_safe_next(next),
) )
token = create_session( token = create_session(
@@ -108,12 +124,12 @@ async def register_form(request: Request, db: Db, user: CurrentUser):
if user is not None: if user is not None:
return RedirectResponse("/", status_code=status.HTTP_303_SEE_OTHER) return RedirectResponse("/", status_code=status.HTTP_303_SEE_OTHER)
first_run = _no_users_yet(db) first_run = _no_users_yet(db)
if not first_run and not settings.allow_signup: if not first_run and not settings_store.signup_allowed(db):
return render( return _login_page(
request, request,
"auth/login.html", db,
{"error": "Registration is closed. Ask an administrator for an account."},
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
error="Registration is closed. Ask an administrator for an account.",
) )
return render(request, "auth/register.html", {"first_run": first_run}) return render(request, "auth/register.html", {"first_run": first_run})
@@ -127,12 +143,12 @@ async def register(
password: str = Form(...), password: str = Form(...),
): ):
first_run = _no_users_yet(db) first_run = _no_users_yet(db)
if not first_run and not settings.allow_signup: if not first_run and not settings_store.signup_allowed(db):
return render( return _login_page(
request, request,
"auth/login.html", db,
{"error": "Registration is closed. Ask an administrator for an account."},
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
error="Registration is closed. Ask an administrator for an account.",
) )
name = name.strip() name = name.strip()
+11 -1
View File
@@ -97,13 +97,23 @@ async def chat_detail(request: Request, db: Db, user: RequiredUser, chat_id: str
@router.get("/settings") @router.get("/settings")
async def settings_page(request: Request, db: Db, user: RequiredUser): async def settings_page(
request: Request,
db: Db,
user: RequiredUser,
error: str = "",
saved: str = "",
):
# error/saved arrive as query parameters because the password form redirects
# back here: a POST that re-rendered in place would re-submit on refresh.
return render( return render(
request, request,
"settings.html", "settings.html",
{ {
"chat": None, "chat": None,
"models": chat_service.available_models(db), "models": chat_service.available_models(db),
"error": error,
"saved": saved,
**_sidebar_context(db, user), **_sidebar_context(db, user),
}, },
) )
+74 -1
View File
@@ -2,9 +2,17 @@
from __future__ import annotations from __future__ import annotations
from fastapi import APIRouter, Body import logging
from fastapi import APIRouter, Body, Form, Request, status
from fastapi.responses import RedirectResponse, Response
from lembas.api.deps import Db, RequiredUser from lembas.api.deps import Db, RequiredUser
from lembas.config import settings
from lembas.security.passwords import hash_password, validate_password, verify_password
from lembas.security.sessions import COOKIE_NAME, create_session, revoke_all_for_user
log = logging.getLogger(__name__)
router = APIRouter(prefix="/api/preferences", tags=["preferences"]) router = APIRouter(prefix="/api/preferences", tags=["preferences"])
@@ -27,3 +35,68 @@ async def set_theme(db: Db, user: RequiredUser, theme: str = Body(..., embed=Tru
user.settings_json = {**(user.settings_json or {}), "theme": theme} user.settings_json = {**(user.settings_json or {}), "theme": theme}
db.commit() db.commit()
return {"ok": True, "theme": theme} return {"ok": True, "theme": theme}
@router.post("/password")
async def change_password(
request: Request,
db: Db,
user: RequiredUser,
current_password: str = Form(...),
new_password: str = Form(...),
confirm_password: str = Form(...),
) -> Response:
"""Change your own password.
Every other session is revoked on success. If the reason for changing a
password is that someone else knows it, leaving their session alive would
defeat the point.
"""
def back(message: str, ok: bool = False) -> Response:
from urllib.parse import quote
field = "saved" if ok else "error"
return RedirectResponse(
f"/settings?{field}={quote(message)}", status_code=status.HTTP_303_SEE_OTHER
)
if not verify_password(current_password, user.password_hash):
log.info("failed password change for %s: current password wrong", user.email)
return back("Your current password is not correct.")
if new_password != confirm_password:
return back("The new passwords do not match.")
if (problem := validate_password(new_password)) is not None:
return back(problem)
if verify_password(new_password, user.password_hash):
return back("That is already your password.")
user.password_hash = hash_password(new_password)
db.commit()
revoke_all_for_user(db, user)
token = create_session(
db,
user,
user_agent=request.headers.get("user-agent", ""),
ip_address=request.client.host if request.client else "",
)
log.info("password changed for %s; other sessions revoked", user.email)
# revoke_all_for_user killed this session too, so hand back a fresh cookie
# -- otherwise changing your password would sign you out of the tab you are
# standing in.
response = back("Password changed. Any other sessions have been signed out.", ok=True)
response.set_cookie(
COOKIE_NAME,
token,
max_age=settings.session_ttl,
httponly=True,
samesite="lax",
secure=False,
path="/",
)
return response
+63
View File
@@ -0,0 +1,63 @@
"""Instance-wide settings that administrators can change at runtime.
Distinct from ``lembas.config``, which holds deployment configuration read from
the environment at startup. Anything here is editable from the admin UI and
lives in the ``settings`` table.
Environment variables act as the *initial* value only. Once an administrator
sets something in the UI, the stored value wins -- otherwise a toggle in the
interface would silently revert on the next restart, which is worse than not
offering the toggle at all.
"""
from __future__ import annotations
from typing import Any
from sqlalchemy.orm import Session as DBSession
from lembas.config import settings as env_settings
from lembas.db.models import Setting
GENERAL = "general"
def _defaults() -> dict[str, Any]:
return {
"allow_signup": env_settings.allow_signup,
# When on, new accounts land in the `pending` role and cannot sign in
# until an administrator approves them. Reserved for the users pass.
"require_approval": False,
"instance_name": "LLeMbas",
}
def get_group(db: DBSession, key: str = GENERAL) -> dict[str, Any]:
"""Stored settings for a group, with defaults filled in for absent keys."""
values = _defaults() if key == GENERAL else {}
row = db.get(Setting, key)
if row is not None and isinstance(row.value, dict):
values.update(row.value)
return values
def get(db: DBSession, name: str, *, key: str = GENERAL) -> Any:
return get_group(db, key).get(name)
def update(db: DBSession, changes: dict[str, Any], *, key: str = GENERAL) -> dict[str, Any]:
"""Merge changes into a settings group and persist them."""
row = db.get(Setting, key)
if row is None:
row = Setting(key=key, value={})
db.add(row)
# Reassigned rather than mutated: SQLAlchemy only reliably detects a change
# to a JSON column when the whole value is replaced.
row.value = {**(row.value or {}), **changes}
db.commit()
return get_group(db, key)
def signup_allowed(db: DBSession) -> bool:
return bool(get(db, "allow_signup"))
+5 -1
View File
@@ -22,6 +22,10 @@
<nav class="sidebar__scroll" aria-label="Administration"> <nav class="sidebar__scroll" aria-label="Administration">
<div class="nav-group"> <div class="nav-group">
<div class="nav-group__label">Administration</div> <div class="nav-group__label">Administration</div>
<a class="nav-item {{ 'is-active' if section == 'general' }}" href="/admin/general">
{{ icon("gear", "icon--sm") }}
<span class="nav-item__label">General</span>
</a>
<a class="nav-item {{ 'is-active' if section == 'connections' }}" <a class="nav-item {{ 'is-active' if section == 'connections' }}"
href="/admin/connections"> href="/admin/connections">
{{ icon("server", "icon--sm") }} {{ icon("server", "icon--sm") }}
@@ -40,7 +44,7 @@
<span class="nav-item__label">Users &amp; groups</span> <span class="nav-item__label">Users &amp; groups</span>
</span> </span>
<span class="nav-item is-disabled"> <span class="nav-item is-disabled">
{{ icon("gear", "icon--sm") }} {{ icon("sliders", "icon--sm") }}
<span class="nav-item__label">Tools</span> <span class="nav-item__label">Tools</span>
</span> </span>
</div> </div>
@@ -0,0 +1,74 @@
{% extends "admin/_layout.html" %}
{% from "_macros.html" import icon %}
{% set section = "general" %}
{% block title %}General - LLeMbas{% endblock %}
{% block heading %}General{% endblock %}
{% block admin_content %}
<p class="admin-lede">
Instance-wide settings. These are stored in the database and take effect
immediately — no restart, and they survive one.
</p>
{% if saved %}
<div class="alert alert--success">{{ icon("check", "icon--sm") }} <span>Settings saved.</span></div>
{% endif %}
<form method="post" action="/admin/general">
<section class="card">
<h2 class="card__title">Identity</h2>
<div class="field">
<label class="field__label" for="instance-name">Instance name</label>
<input class="input" id="instance-name" name="instance_name"
value="{{ values.instance_name }}" maxlength="120">
<p class="field__hint">Shown in the browser tab and on the sign-in page.</p>
</div>
</section>
<section class="card">
<h2 class="card__title">
Registration
{% if values.allow_signup %}
<span class="badge badge--success">open</span>
{% else %}
<span class="badge badge--danger">closed</span>
{% endif %}
</h2>
<div class="field">
<label class="checkbox">
<input type="checkbox" name="allow_signup" value="true"
{{ 'checked' if values.allow_signup }}>
<span>Anyone who can reach this instance may create an account</span>
</label>
<p class="field__hint">
Turn this off once your users exist. Sign-in is unaffected — existing
accounts keep working, and the "Create one" link disappears from the
sign-in page.
</p>
</div>
{% if values.allow_signup and user_count > 0 %}
<div class="alert alert--warning">
{{ icon("warning", "alert__icon") }}
<div>
<strong>Registration is open.</strong>
<div class="text-sm" style="margin-top: var(--sp-1)">
This instance has {{ user_count }} account{{ '' if user_count == 1 else 's' }}.
Anyone who can reach it can add another, and every account can use your
configured models and API keys.
</div>
</div>
</div>
{% endif %}
<p class="field__hint">
<code>LEMBAS_ALLOW_SIGNUP</code> in the environment sets only the starting
value. Once saved here, this setting wins.
</p>
</section>
<button class="btn btn--primary" type="submit">Save settings</button>
</form>
{% endblock %}
+39
View File
@@ -21,6 +21,17 @@
<div class="admin-scroll"> <div class="admin-scroll">
<div class="admin-page"> <div class="admin-page">
{% if error %}
<div class="alert alert--error" role="alert">
{{ icon("warning", "alert__icon") }} <span>{{ error }}</span>
</div>
{% endif %}
{% if saved %}
<div class="alert alert--success" role="status">
{{ icon("check", "icon--sm") }} <span>{{ saved }}</span>
</div>
{% endif %}
<section class="card"> <section class="card">
<h2 class="card__title">Account</h2> <h2 class="card__title">Account</h2>
<div class="field"> <div class="field">
@@ -55,6 +66,34 @@
</p> </p>
</section> </section>
<section class="card">
<h2 class="card__title">Change password</h2>
<form method="post" action="/api/preferences/password">
<div class="field">
<label class="field__label" for="current-password">Current password</label>
<input class="input" type="password" id="current-password"
name="current_password" required autocomplete="current-password">
</div>
<div class="field">
<label class="field__label" for="new-password">New password</label>
<input class="input" type="password" id="new-password" name="new_password"
required minlength="8" autocomplete="new-password">
<p class="field__hint">At least 8 characters.</p>
</div>
<div class="field">
<label class="field__label" for="confirm-password">Confirm new password</label>
<input class="input" type="password" id="confirm-password"
name="confirm_password" required minlength="8"
autocomplete="new-password">
</div>
<button class="btn btn--primary" type="submit">Change password</button>
<p class="field__hint" style="margin-top: var(--sp-3)">
Every other session is signed out when the password changes. You
stay signed in here.
</p>
</form>
</section>
<section class="card"> <section class="card">
<h2 class="card__title">Session</h2> <h2 class="card__title">Session</h2>
<form method="post" action="/auth/logout"> <form method="post" action="/auth/logout">
+202
View File
@@ -0,0 +1,202 @@
"""Instance settings (registration toggle) and changing your own password."""
from __future__ import annotations
from fastapi.testclient import TestClient
from sqlalchemy import select
from lembas.db.models import Session as SessionRow
from lembas.db.models import User
from lembas.services import settings_store
# --- Registration toggle -----------------------------------------------------
def test_registration_is_open_by_default(client: TestClient, db, registered):
assert settings_store.signup_allowed(db) is True
def test_closing_registration_blocks_new_accounts(client: TestClient, db, registered):
client.post("/admin/general", data={"instance_name": "LLeMbas"}, follow_redirects=False)
assert settings_store.signup_allowed(db) is False
response = client.post(
"/auth/register",
data={"name": "Uninvited", "email": "no@thanks.test", "password": "let-me-in-please"},
follow_redirects=False,
)
assert response.status_code == 403
assert "Registration is closed" in response.text
assert db.scalar(select(User).where(User.email == "no@thanks.test")) is None
def test_closed_registration_hides_the_create_account_link(
client: TestClient, db, registered
):
client.post("/admin/general", data={"instance_name": "LLeMbas"}, follow_redirects=False)
client.post("/auth/logout", follow_redirects=False)
page = client.get("/auth/login")
assert "/auth/register" not in page.text
def test_open_registration_shows_the_link(client: TestClient, db, registered):
client.post(
"/admin/general",
data={"instance_name": "LLeMbas", "allow_signup": "true"},
follow_redirects=False,
)
client.post("/auth/logout", follow_redirects=False)
assert "/auth/register" in client.get("/auth/login").text
def test_existing_users_can_still_sign_in_when_registration_is_closed(
client: TestClient, db, registered
):
client.post("/admin/general", data={"instance_name": "LLeMbas"}, follow_redirects=False)
client.post("/auth/logout", follow_redirects=False)
response = client.post(
"/auth/login",
data={"email": registered["email"], "password": registered["password"]},
follow_redirects=False,
)
assert response.status_code == 303
def test_stored_setting_beats_the_environment_default(client: TestClient, db, registered):
"""A toggle that silently reverted on restart would be worse than none."""
from lembas.config import settings as env_settings
assert env_settings.allow_signup is True
settings_store.update(db, {"allow_signup": False})
assert settings_store.signup_allowed(db) is False
def test_ordinary_users_cannot_change_instance_settings(client: TestClient, db, registered):
client.post("/auth/logout", follow_redirects=False)
client.post(
"/auth/register",
data={"name": "Sam", "email": "sam@shire.test", "password": "potatoes-po-ta-toes"},
follow_redirects=False,
)
assert client.post("/admin/general", data={"instance_name": "Pwned"}).status_code == 403
assert settings_store.get(db, "instance_name") == "LLeMbas"
# --- Password change ---------------------------------------------------------
def test_password_change_works(client: TestClient, db, registered):
response = client.post(
"/api/preferences/password",
data={
"current_password": registered["password"],
"new_password": "a-much-better-password",
"confirm_password": "a-much-better-password",
},
follow_redirects=False,
)
assert response.status_code == 303
assert "saved=" in response.headers["location"]
client.post("/auth/logout", follow_redirects=False)
assert (
client.post(
"/auth/login",
data={"email": registered["email"], "password": "a-much-better-password"},
follow_redirects=False,
).status_code
== 303
)
def test_old_password_stops_working(client: TestClient, db, registered):
client.post(
"/api/preferences/password",
data={
"current_password": registered["password"],
"new_password": "a-much-better-password",
"confirm_password": "a-much-better-password",
},
follow_redirects=False,
)
client.post("/auth/logout", follow_redirects=False)
assert (
client.post(
"/auth/login",
data={"email": registered["email"], "password": registered["password"]},
follow_redirects=False,
).status_code
== 401
)
def test_wrong_current_password_is_refused(client: TestClient, db, registered):
response = client.post(
"/api/preferences/password",
data={
"current_password": "not-my-password",
"new_password": "a-much-better-password",
"confirm_password": "a-much-better-password",
},
follow_redirects=False,
)
assert "error=" in response.headers["location"]
user = db.scalar(select(User).where(User.email == registered["email"]))
db.refresh(user)
from lembas.security.passwords import verify_password
assert verify_password(registered["password"], user.password_hash)
def test_mismatched_confirmation_is_refused(client: TestClient, db, registered):
response = client.post(
"/api/preferences/password",
data={
"current_password": registered["password"],
"new_password": "a-much-better-password",
"confirm_password": "a-different-password",
},
follow_redirects=False,
)
assert "do%20not%20match" in response.headers["location"]
def test_short_new_password_is_refused(client: TestClient, db, registered):
response = client.post(
"/api/preferences/password",
data={
"current_password": registered["password"],
"new_password": "short",
"confirm_password": "short",
},
follow_redirects=False,
)
assert "8%20characters" in response.headers["location"]
def test_other_sessions_are_revoked_but_this_one_survives(client: TestClient, db, registered):
"""If the reason for changing a password is that someone else knows it,
leaving their session alive defeats the point."""
other = TestClient(client.app)
other.post(
"/auth/login",
data={"email": registered["email"], "password": registered["password"]},
follow_redirects=False,
)
assert other.get("/chat", follow_redirects=False).status_code == 200
assert db.scalar(select(SessionRow)) is not None
client.post(
"/api/preferences/password",
data={
"current_password": registered["password"],
"new_password": "a-much-better-password",
"confirm_password": "a-much-better-password",
},
follow_redirects=False,
)
# The other browser is out...
assert other.get("/chat", follow_redirects=False).status_code == 303
# ...and the tab that made the change is still in.
assert client.get("/chat", follow_redirects=False).status_code == 200