Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
feat(security): isolate Redis and the collector, require a Redis password, hash session IDs
karloks20051592254417ea
diff --git a/.env.example b/.env.exampleindex 4ef6182..08e0b2e 100644--- a/.env.example+++ b/.env.example@@ -1,5 +1,7 @@-# Copy to .env, set POSTGRES_PASSWORD, then run: docker compose up -d --build+# Copy to .env, set POSTGRES_PASSWORD and REDIS_PASSWORD, then run: docker compose up -d --buildPOSTGRES_PASSWORD=replace-with-a-long-random-password+# Redis holds the login sessions, so it has a password too. Letters and digits only: openssl rand -hex 24+REDIS_PASSWORD=replace-with-another-long-random-password# Optional: required only if you use the Gemini chat feature.GEMINI_API_KEY=AGENT_MODEL=models/gemini-3.5-flashdiff --git a/README.md b/README.mdindex 01aae57..34c6b83 100644--- a/README.md+++ b/README.md@@ -104,8 +104,9 @@ flowchart LRvolume and it answers only container list, inspect and stats.- The optional **system helper** reads the kernel log and `wtmp`, and writes asanitised summary file the collector picks up (profile `system-events`).-- PostgreSQL and Redis have no host ports; they are reachable only inside the- Compose network.+- PostgreSQL and Redis have no host ports and sit on a separate network with no route out, reachable only+ by the backend; Redis needs a password. The collector can reach the gate (or, in development, the backend)+ and nothing else.The development stack (`compose.yml`) keeps a single listener: everything,including the collector endpoints, is reachable through the frontend. The server@@ -116,7 +117,7 @@ stack splits them as described above.Requirements: Docker with Compose v2.```bash-cp .env.example .env # then set POSTGRES_PASSWORD to a long random value+cp .env.example .env # then set POSTGRES_PASSWORD and REDIS_PASSWORD (openssl rand -hex 24)docker compose up -d --build```@@ -146,7 +147,7 @@ need published images; see [Publishing the collector images](docs/deployment.md#The server stack (`docker-compose.server.yml`) publishes the dashboard through an existing **Traefik** andserves the collector endpoints only on a separate listener bound to your **VPN address**. In short:-1. `cp example.env .env`, then set `POSTGRES_PASSWORD`, `DASHBOARD_DOMAIN`, your Traefik names and+1. `cp example.env .env`, then set `POSTGRES_PASSWORD`, `REDIS_PASSWORD`, `DASHBOARD_DOMAIN`, your Traefik names and`COMPOSE_FILE=docker-compose.server.yml` (the last one matters: without it Compose uses the development stack).2. Generate `SECRETS_KEY` (needed for two-factor sign-in) and set `COLLECTOR_BIND` / `COLLECTOR_PUBLIC_URL` for your VPN.3. `docker compose -f docker-compose.server.yml up -d --build`, then register the first account with the setup token from the backend log.diff --git a/SECURITY.md b/SECURITY.mdindex 95981a8..1125288 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -11,7 +11,7 @@ This page says what each component can reach, so you can decide what to run.| Docker proxy | container, uid 0, no capabilities | the Docker socket; a Unix socket shared only with the collector; no network | Allows four read-only requests. See below. || System helper (optional) | container, uid 0 with **one** capability | kernel log, `/var/log/wtmp` (read-only), one output volume | Off by default. Details below. || Collector gate (server stack) | nginx container, no capabilities | the backend; publishes one port on your VPN address | The only way to reach collector endpoints. See below. |-| Backend / frontend / database | containers | each other | Only the frontend port is published. |+| Backend / frontend / database / Redis | containers | each other, over separate networks | Only the frontend port is published. Redis and PostgreSQL are on a network with no route out and are reachable only by the backend. Redis needs a password. |## The optional system helper@@ -256,6 +256,26 @@ The collector's network checks are passive or opt-in, and add no privileges:command **Connect a server** generates (signed, digest-pinned images), and machines set up from`collector-compose.yml` build the images locally.+## Network separation, Redis and login sessions++- **Three networks.** `data` holds PostgreSQL, Redis and the backend and has **no route to the internet**.+ `front` holds the frontend, the collector gate and the backend. `collector` holds the collector and the gate+ only. So the collector, the container that talks to remote hosts and parses their data, can reach the gate+ and nothing else: it can't resolve or connect to Redis or PostgreSQL, and a neighbouring container can't+ either. (Checked on a running stack.) The development stack has the same split, except that its collector+ talks to the backend directly.+- **Redis has a password** (`REDIS_PASSWORD`, required). Without it, anything that could reach Redis could write+ a session for any user, administrator included, with no password or two-factor.+- **Sessions are stored hashed.** Redis holds only the SHA-256 of the cookie value, in the session key, the+ per-user index and the pending-login token. Reading Redis (a backup, a leaked dump) doesn't hand out working+ sessions. Note what this does and doesn't do: hashing protects against *reading* Redis. It does not stop+ someone who can *write* to it, because they can pick a secret and store its hash; the password and the+ network separation are what stop that.+- **Upgrade.** Sessions written in the old format no longer work (everyone signs in once) and are deleted from+ Redis at start, so the old session IDs don't linger there.+- **Still open:** the backend trusts `X-Forwarded-For` from any address that can reach it (`--forwarded-allow-ips`).+ With the separation, only the nginx containers can, but narrowing it further is tracked separately.+## Statistics and history- **Who can see it.** Every signed-in account sees the same statistics as the dashboard, for everydiff --git a/TESTS.md b/TESTS.mdindex d40675d..e365d2d 100644--- a/TESTS.md+++ b/TESTS.md@@ -4,7 +4,7 @@ Vexion ships with an automated test suite. This page explains how to run it, whacovers (and what it doesn't), and what every single test is for, so you can decidewhether a failure matters before you upgrade or change your setup.-- **1035 test cases** from 523 test functions, plus 16 small tests of the chart helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).+- **1041 test cases** from 529 test functions, plus 16 small tests of the chart helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).- **About two minutes** to run. No Docker, PostgreSQL, Redis, network or root access needed.- **Safe to run next to a live install.** The tests use a throwaway in-memory databaseand fakes; they never touch your running containers or your data. (Two collector@@ -124,7 +124,7 @@ docker compose logs --tail 20 collector # "Sent host metrics and N contai| File | Cases | Protects ||---|---|---|-| [`test_account_security.py`](#test_account_securitypy) | 130 | Two-factor sign-in, recovery codes, encrypted secrets, sessions you can review and end, password change, and the password check before turning two-factor on. |+| [`test_account_security.py`](#test_account_securitypy) | 136 | Two-factor sign-in, recovery codes, encrypted secrets, sessions you can review and end, password change, and the password check before turning two-factor on. || [`test_admin.py`](#test_adminpy) | 18 | Who may do what: admin-only actions, roles, retention cleanup, the chat on/off switch. || [`test_agent_errors.py`](#test_agent_errorspy) | 2 | Helpful, non-leaking error messages from the AI assistant. || [`test_agent_service.py`](#test_agent_servicepy) | 2 | The assistant can only run the fixed read-only checks. |@@ -247,6 +247,12 @@ out of their own install.| `test_a_successful_sign_in_does_not_reset_the_address_counter` | Signing in to your own account doesn't give more guesses against someone else's: only the one allowed guess is left. || `test_signing_in_successfully_does_not_use_up_the_addresss_allowance` | People behind one address can all sign in, 15 times in a row, without being locked out. || `test_a_successful_sign_in_still_resets_that_accounts_own_counter` | A successful sign-in clears that account's own counter. |+| `test_redis_never_holds_the_session_cookie_value_or_the_pending_login_token` | After signing in, and after a two-step sign-in has started, the cookie value and the pending-login token appear nowhere in Redis (keys, hash fields or values). |+| `test_the_sessions_index_keeps_digests_not_session_ids` | The per-user session list stores 64-character digests, not session IDs. |+| `test_a_session_stored_under_the_raw_cookie_value_is_not_accepted` | A session planted under the raw cookie value (the old format) is not accepted. |+| `test_listing_and_ending_sessions_still_work_with_digests` | Listing sessions and ending another one still work, and the ended one stops working. |+| `test_old_format_session_data_is_removed_at_start_and_new_data_is_kept` | At start, old-format session, pending-login, attempt and index records are deleted; live sessions are kept. |+| `test_the_cleanup_of_old_session_data_never_stops_the_backend_from_starting` | If Redis fails during that cleanup, nothing is raised. |### test_admin.pydiff --git a/compose.yml b/compose.ymlindex 36cf7eb..61203d7 100644--- a/compose.yml+++ b/compose.yml@@ -4,6 +4,7 @@ services:image: postgres:16-alpinecontainer_name: homelab-postgresrestart: unless-stopped+ networks: [data]environment:POSTGRES_DB: homelabPOSTGRES_USER: homelab@@ -21,11 +22,16 @@ services:image: redis:7-alpinecontainer_name: homelab-redisrestart: unless-stopped- command: ["redis-server", "--appendonly", "yes"]+ networks: [data]+ # Needs a password: Redis holds the login sessions, so nothing that can merely reach it on the network+ # may use it. Generate one with `openssl rand -hex 24` (letters and digits only, so it fits in a URL).+ command: ["sh", "-c", "exec redis-server --appendonly yes --requirepass \"$$REDIS_PASSWORD\""]+ environment:+ REDIS_PASSWORD: ${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env (generate one with openssl rand -hex 24)}volumes:- redis_data:/datahealthcheck:- test: ["CMD", "redis-cli", "ping"]+ test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" --no-auth-warning ping | grep -q PONG"]interval: 10stimeout: 5sretries: 5@@ -37,9 +43,10 @@ services:container_name: homelab-backendimage: homelab-backend:latestrestart: unless-stopped+ networks: [data, front]environment:DATABASE_URL: postgresql+psycopg://homelab:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@postgres:5432/homelab- REDIS_URL: redis://redis:6379/0+ REDIS_URL: redis://:${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env (generate one with openssl rand -hex 24)}@redis:6379/0GEMINI_API_KEY: ${GEMINI_API_KEY:-}AGENT_MODEL: ${AGENT_MODEL:-models/gemini-3.5-flash}# Set to true when the dashboard is served over HTTPS.@@ -85,6 +92,7 @@ services:image: homelab-collector:latestcontainer_name: homelab-collectorrestart: unless-stopped+ networks: [front]environment:HOMELAB_API_URL: http://backend:8000# Marks this collector as the machine running the dashboard (the charts at the top).@@ -165,6 +173,7 @@ services:VITE_API_BASE_URL: /apicontainer_name: homelab-frontendrestart: unless-stopped+ networks: [front]# Serves the dashboard and proxies /api to the backend. Reach it directly over# LAN/VPN, or put the `https` profile's Caddy in front for a public domain.ports:@@ -179,6 +188,7 @@ services:container_name: homelab-caddyprofiles: ["https"]restart: unless-stopped+ networks: [front]environment:DOMAIN: ${DOMAIN:-localhost}ports:@@ -192,6 +202,12 @@ services:depends_on:- frontend+networks:+ # Redis and PostgreSQL are reachable only by the backend; the collector can reach the backend and nothing else.+ data:+ internal: true+ front:+volumes:postgres_data:redis_data:diff --git a/docker-compose.server.yml b/docker-compose.server.ymlindex 0da07a0..a619dc6 100644--- a/docker-compose.server.yml+++ b/docker-compose.server.yml@@ -9,6 +9,7 @@ services:image: postgres:16-alpinecontainer_name: homelab-postgresrestart: unless-stopped+ networks: [data]environment:POSTGRES_DB: homelabPOSTGRES_USER: homelab@@ -26,11 +27,16 @@ services:image: redis:7-alpinecontainer_name: homelab-redisrestart: unless-stopped- command: ["redis-server", "--appendonly", "yes"]+ networks: [data]+ # Needs a password: Redis holds the login sessions, so nothing that can merely reach it on the network+ # may use it. Generate one with `openssl rand -hex 24` (letters and digits only, so it fits in a URL).+ command: ["sh", "-c", "exec redis-server --appendonly yes --requirepass \"$$REDIS_PASSWORD\""]+ environment:+ REDIS_PASSWORD: ${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env (generate one with openssl rand -hex 24)}volumes:- redis_data:/datahealthcheck:- test: ["CMD", "redis-cli", "ping"]+ test: ["CMD-SHELL", "redis-cli -a \"$$REDIS_PASSWORD\" --no-auth-warning ping | grep -q PONG"]interval: 10stimeout: 5sretries: 5@@ -42,9 +48,10 @@ services:container_name: homelab-backendimage: homelab-backend:latestrestart: unless-stopped+ networks: [data, front]environment:DATABASE_URL: postgresql+psycopg://homelab:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@postgres:5432/homelab- REDIS_URL: redis://redis:6379/0+ REDIS_URL: redis://:${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env (generate one with openssl rand -hex 24)}@redis:6379/0GEMINI_API_KEY: ${GEMINI_API_KEY:-}AGENT_MODEL: ${AGENT_MODEL:-models/gemini-3.5-flash}# Served over HTTPS via Traefik, so the login cookie is HTTPS-only.@@ -98,6 +105,7 @@ services:image: homelab-collector:latestcontainer_name: homelab-collectorrestart: unless-stopped+ networks: [collector]environment:# Through the gate's internal listener (not published); the public listener refuses collectors.HOMELAB_API_URL: http://collector-gate:8080/api@@ -139,6 +147,7 @@ services:image: nginx:alpinecontainer_name: homelab-collector-gaterestart: unless-stopped+ networks: [front, collector]ports:- "${COLLECTOR_BIND:-127.0.0.1}:${COLLECTOR_PORT:-8081}:8081"volumes:@@ -216,7 +225,7 @@ services:# Public listener only: collector endpoints are refused here (see the collector-gate service).- ./docker/nginx.strict.conf:/etc/nginx/conf.d/default.conf:ronetworks:- - default+ - front- traefiklabels:- traefik.enable=true@@ -232,6 +241,12 @@ services:condition: service_healthynetworks:+ # Three networks keep each container to what it needs. Redis and PostgreSQL are on `data` only, which has no+ # route out; the collector is on `collector` only and can reach nothing but the gate.+ data:+ internal: true+ front:+ collector:traefik:external: truename: ${TRAEFIK_NETWORK:-traefik_default} # Traefik's Docker network; same value as the label abovediff --git a/docs/configuration.md b/docs/configuration.mdindex 3d5723f..30d8514 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -7,6 +7,7 @@| Variable | Default | Description ||---|---|---|| `POSTGRES_PASSWORD` | *(required)* | PostgreSQL password. |+| `REDIS_PASSWORD` | *(required)* | Redis password. Redis holds the login sessions, so nothing that can merely reach it may use it. Use letters and digits only (`openssl rand -hex 24`) because it is put into a URL. || `GEMINI_API_KEY` | empty | Enables the Homie chat assistant. || `AGENT_MODEL` | `models/gemini-3.5-flash` | Gemini model for the assistant. || `ADMIN_ALERT_WEBHOOK_URL` | empty | Receives JSON alerts for critical `daily_checkup` findings. |diff --git a/docs/deployment.md b/docs/deployment.mdindex 2296788..0e569e9 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -23,6 +23,7 @@ Then set at least these:| Setting | Default | Meaning ||---|---|---|| `POSTGRES_PASSWORD` | *(required)* | A long random password for the bundled database. |+| `REDIS_PASSWORD` | *(required)* | A long random password for Redis, which holds the login sessions. Letters and digits only (`openssl rand -hex 24`). || `DASHBOARD_DOMAIN` | *(required)* | Your domain, without `https://`. Used for the Traefik router. || `TRAEFIK_ENTRYPOINT` | `websecure` | Your Traefik HTTPS entrypoint name. || `TRAEFIK_CERT_RESOLVER` | `letsencrypt` | Your Traefik certificate resolver name. |@@ -116,6 +117,12 @@ frontend, collector, Docker proxy and system helper each have their code builtinto their image, so a service that isn't rebuilt keeps running the old version.The database schema is updated automatically when the backend starts.+**Upgrading from a version that had no `REDIS_PASSWORD`:** add one to `.env` first+(`echo "REDIS_PASSWORD=$(openssl rand -hex 24)" >> .env`), then update as above. Compose refuses to start+without it. This version also separates the containers onto three networks and stores login sessions+only as hashes, so **everyone is signed out once** and signs in again; no data is lost. Back the password+up with your other secrets; if you change it later, Redis is simply restarted with the new one.+Collectors on other machines run the image digest from the command you generated.To update them, publish a new version tag, put the new digests in `.env`, and run afreshly generated command on each machine (or pull the new digests into itsdiff --git a/docs/development.md b/docs/development.mdindex ab9353f..ba1e572 100644--- a/docs/development.md+++ b/docs/development.md@@ -12,7 +12,7 @@ in place of PostgreSQL.```bashpython -m venv venv && source venv/bin/activatepip install -r requirements.txt-docker run -d --name homelab-dev-redis -p 6379:6379 redis:7-alpine # if Redis isn't running+docker run -d --name homelab-dev-redis -p 127.0.0.1:6379:6379 redis:7-alpine # if Redis isn't running (no password: for local development only)DATABASE_URL=sqlite:///./dev.db REDIS_URL=redis://localhost:6379/0 \uvicorn src.backend.main:app --reload --host 0.0.0.0 --port 8060```diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 33b7b03..4cb1f61 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -27,6 +27,8 @@| Lost the authenticator and the recovery codes | Run `docker compose exec backend python src/backend/reset_2fa.py <email>` on the host, then sign in with the password and set it up again. || Authenticator codes stopped working after a restore or `.env` change | `SECRETS_KEY` changed or was lost, so the stored secret can't be decrypted. Restore the old key (rotation: `new,old`), or use a recovery code and the reset command. || Server marked offline | It missed 3 check-ins in a row. Check the machine, its collector log and its route to the dashboard. The incident resolves on the next report. |+| `Set REDIS_PASSWORD in .env` when starting the stack | Add a `REDIS_PASSWORD` to `.env` (`echo "REDIS_PASSWORD=$(openssl rand -hex 24)" >> .env`). Redis holds the login sessions, so it has a password; you are signed out once after adding it. |+| The backend log says `AuthenticationError` or `invalid password` for Redis, or `/health` shows Redis down | `REDIS_PASSWORD` in `.env` doesn't match the password Redis was started with, or contains characters that don't fit in a URL (`@`, `:`, `/`, `%`). Use letters and digits only, and recreate both containers: `docker compose up -d --force-recreate redis backend`. || A collector log says "Check-ins are arriving faster than this server's interval allows" (HTTP 429) | The collector reports more often than a quarter of the server's check interval. It retries by itself; check that only one collector uses that server's token, or adjust `INGEST_MIN_SPACING_RATIO`. || "This install already has the most servers it allows" | `MAX_SERVERS` (default 200) is reached. Remove servers you no longer need, or raise it in `.env`. || A warning "The credentials of <server> were replaced" | Someone used the enrollment key on a machine whose ID is already known, which signs the previous collector out. Expected after you reinstall that machine with the key; if it wasn't you, rotate the key under *Connect a server → Advanced* and inspect the machine. |diff --git a/example.env b/example.envindex 63393a1..72b51a2 100644--- a/example.env+++ b/example.env@@ -17,6 +17,10 @@ COMPOSE_FILE=docker-compose.server.yml# without it. Use a long random string, e.g. the output of: openssl rand -hex 32POSTGRES_PASSWORD=<long-random-password>+# Password for Redis, which holds the login sessions. The stack refuses to start without it. Letters and digits+# only, so it fits in a URL: openssl rand -hex 24+REDIS_PASSWORD=<long-random-password>+# The domain the dashboard is served on (no https://, no slash). Used for the Traefik router# and as the default for CORS_ORIGINS below.DASHBOARD_DOMAIN=<your-domain>diff --git a/src/backend/auth.py b/src/backend/auth.pyindex 9bba51a..1ccd836 100644--- a/src/backend/auth.py+++ b/src/backend/auth.py@@ -1,3 +1,4 @@+import hashlibimport jsonimport reimport secrets@@ -30,24 +31,34 @@ def _serialize_user(user: User):}+def _digest(secret: str) -> str:+ """What Redis stores in place of a secret. The cookie value (and a pending-login token) is only ever kept+ as its SHA-256, so reading Redis (a backup, a leak, another container) doesn't hand out working sessions,+ and writing a key there is useless without knowing a secret that hashes to it."""+ return hashlib.sha256(secret.encode()).hexdigest()+++_DIGEST = re.compile(r"[0-9a-f]{64}")++def _session_key(session_id: str) -> str:- return f"homelab:session:{session_id}"+ return _key_for_digest(_digest(session_id))+++def _key_for_digest(digest: str) -> str:+ return f"homelab:session:{digest}"def _store_session(redis_client, session_id: str, payload: dict):- key = _session_key(session_id)- value = json.dumps(payload)- redis_client.set(key, value, ex=SESSION_TTL_SECONDS)+ redis_client.set(_session_key(session_id), json.dumps(payload), ex=SESSION_TTL_SECONDS)def _read_session(redis_client, session_id: str):- key = _session_key(session_id)- return redis_client.get(key)+ return redis_client.get(_session_key(session_id))def _delete_session(redis_client, session_id: str):- key = _session_key(session_id)- redis_client.delete(key)+ redis_client.delete(_session_key(session_id))def _user_sessions_key(user_id: int) -> str:@@ -55,7 +66,11 @@ def _user_sessions_key(user_id: int) -> str:def _pending_key(token: str) -> str:- return f"homelab:2fa-pending:{token}"+ return f"homelab:2fa-pending:{_digest(token)}"+++def _attempts_key(token: str) -> str:+ return f"homelab:2fa-attempts:{_digest(token)}"def _printable(text: str | None, limit: int) -> str | None:@@ -75,7 +90,7 @@ def create_session(redis_client, user: User, *, stage: str = STAGE_FULL, ip: str"created_at": datetime.now(timezone.utc).isoformat(), "ip": _printable(ip, 64), "user_agent": _printable(user_agent, 120),})index = _user_sessions_key(user.id)- redis_client.hset(index, public_id, session_id)+ redis_client.hset(index, public_id, _digest(session_id))redis_client.expire(index, SESSION_TTL_SECONDS)return session_id, public_id@@ -84,7 +99,14 @@ def get_session(redis_client, session_id: str | None) -> dict | None:"""The session behind a cookie, whatever its stage, or None. Sessions from before stages existed count as full."""if not session_id:return None- raw = _read_session(redis_client, session_id)+ return _session_from_raw(_read_session(redis_client, session_id))+++def _session_by_digest(redis_client, digest) -> dict | None:+ return _session_from_raw(redis_client.get(_key_for_digest(digest))) if isinstance(digest, str) and _DIGEST.fullmatch(digest) else None+++def _session_from_raw(raw) -> dict | None:if not raw:return Nonetry:@@ -120,8 +142,8 @@ def delete_session(redis_client, session_id: str | None) -> bool:def list_user_sessions(redis_client, user_id: int, current_public_id: str | None) -> list[dict]:"""A user's live sessions, newest first, by public ID only. Entries whose session has expired are dropped."""index, sessions = _user_sessions_key(user_id), []- for public_id, session_id in redis_client.hgetall(index).items():- session = get_session(redis_client, session_id)+ for public_id, digest in redis_client.hgetall(index).items():+ session = _session_by_digest(redis_client, digest)if not session or session["id"] != user_id or session["public_id"] != public_id:redis_client.hdel(index, public_id)continue@@ -134,12 +156,14 @@ def revoke_user_session(redis_client, user_id: int, public_id: str) -> bool:"""Sign out one of the user's own sessions by public ID. Anything that isn't theirs is simply not found."""if not isinstance(public_id, str) or not _PUBLIC_ID.fullmatch(public_id):return False- session_id = redis_client.hget(_user_sessions_key(user_id), public_id)- session = get_session(redis_client, session_id)+ digest = redis_client.hget(_user_sessions_key(user_id), public_id)+ session = _session_by_digest(redis_client, digest)if not session or session["id"] != user_id:redis_client.hdel(_user_sessions_key(user_id), public_id)return False- return delete_session(redis_client, session_id)+ redis_client.hdel(_user_sessions_key(user_id), public_id)+ redis_client.delete(_key_for_digest(digest))+ return Truedef revoke_other_sessions(redis_client, user_id: int, keep_public_id: str | None) -> int:@@ -170,7 +194,7 @@ def read_pending_two_factor(redis_client, token) -> int | None:def count_pending_attempt(redis_client, token: str) -> bool:"""Count a try against this pending login; after MAX_PENDING_ATTEMPTS the token is destroyed. False means no more tries."""- key = f"homelab:2fa-attempts:{token}"+ key = _attempts_key(token)attempts = redis_client.incr(key)if attempts == 1:redis_client.expire(key, PENDING_TWO_FACTOR_TTL_SECONDS)@@ -181,7 +205,24 @@ def count_pending_attempt(redis_client, token: str) -> bool:def delete_pending_two_factor(redis_client, token: str) -> None:- redis_client.delete(_pending_key(token), f"homelab:2fa-attempts:{token}")+ redis_client.delete(_pending_key(token), _attempts_key(token))+++def purge_legacy_session_keys(redis_client) -> int:+ """Delete session data written before session IDs were hashed: the keys that still contain a raw session ID or+ pending-login token, and the per-user indexes that point at them. Those sessions stopped working when the+ format changed; this stops their secrets from sitting in Redis until they expire. Returns how many were removed."""+ removed = 0+ try:+ for key in list(redis_client.scan_iter(match="homelab:session:*")) + list(redis_client.scan_iter(match="homelab:2fa-pending:*")) + list(redis_client.scan_iter(match="homelab:2fa-attempts:*")):+ if not _DIGEST.fullmatch(key.rsplit(":", 1)[-1]):+ removed += int(bool(redis_client.delete(key)))+ for key in redis_client.scan_iter(match="homelab:user-sessions:*"):+ if any(not _DIGEST.fullmatch(value) for value in redis_client.hvals(key)):+ removed += int(bool(redis_client.delete(key)))+ except Exception:+ return removed+ return removeddef record_audit_log(diff --git a/src/backend/main.py b/src/backend/main.pyindex 12f509d..c3f8fb3 100644--- a/src/backend/main.py+++ b/src/backend/main.py@@ -23,7 +23,7 @@ from pydantic import BaseModel, EmailStr, Field, field_validatorfrom sqlalchemy import case, func, inspect, textfrom .alerts import CONTAINER_RULE_PREFIX, CRITICAL, SERVER_OFFLINE_RULE, SEVERITIES, active_rule_keys, raise_alert, resolve_alerts, sync_alerts-from . import history as history_service, rollups, secrets_box, stats, totp+from . import auth, history as history_service, rollups, secrets_box, stats, totpfrom .auth import (STAGE_ENROLLMENT, STAGE_FULL, count_pending_attempt, create_pending_two_factor, create_session, delete_pending_two_factor, delete_session, get_recent_logs,get_session, get_user_from_session, hash_password, issue_recovery_codes, list_user_sessions, read_pending_two_factor, recovery_codes_left, record_audit_log,@@ -309,6 +309,8 @@ def startup_event():if require_admin_two_factor(db) and not secrets_box.available():print("SECURITY WARNING: two-factor is required for administrators, but SECRETS_KEY is missing or invalid, so it is NOT being enforced. ""Generate a key with `python -m src.backend.secrets_box` and set SECRETS_KEY in .env.", flush=True)+ if removed := auth.purge_legacy_session_keys(redis_client):+ print(f"Removed {removed} session records written in the old format (sign-ins before this version ended).", flush=True)if warning := registration_warning(db):print(warning, flush=True)setup_token = ensure_bootstrap_token(db)diff --git a/tests/fakes.py b/tests/fakes.pyindex e0701e7..21f28c7 100644--- a/tests/fakes.py+++ b/tests/fakes.py@@ -42,6 +42,12 @@ class FakeRedis:def ttl(self, key):return self.ttls.get(key, -1)+ def scan_iter(self, match="*", **kwargs):+ return iter(self.keys(match))++ def hvals(self, key):+ return list(self.hashes.get(key, {}).values())+def keys(self, pattern="*"):return [key for key in list(self.store) + list(self.hashes) if fnmatch.fnmatch(key, pattern)]diff --git a/tests/test_account_security.py b/tests/test_account_security.pyindex 7ce99b9..ec5b52c 100644--- a/tests/test_account_security.py+++ b/tests/test_account_security.py@@ -1,4 +1,6 @@import base64+import json+import reimport osfrom types import SimpleNamespace@@ -846,7 +848,7 @@ def test_turning_two_factor_off_gives_this_session_a_new_id(app):after = member.cookies.get(COOKIE)assert after and after != before- assert main.redis_client.get(f"homelab:session:{before}") is None and member.get("/auth/me").status_code == 200+ assert main.redis_client.get(auth._session_key(before)) is None and member.get("/auth/me").status_code == 200def test_a_successful_sign_in_does_not_reset_the_address_counter(app):@@ -875,3 +877,77 @@ def test_a_successful_sign_in_still_resets_that_accounts_own_counter(app):keys = [key for key in main.redis_client.keys("*") if "login-email" in key and "member" in key]assert keys == []+++# --- Redis never holds a working session ID -----------------------------------------------------------------++def _everything_in_redis(redis):+ """Every key, hash field and value Redis holds, as text."""+ seen = list(redis.store) + [str(value) for value in redis.store.values()]+ for name, mapping in redis.hashes.items():+ seen += [name] + list(mapping) + [str(value) for value in mapping.values()]+ return seen+++def test_redis_never_holds_the_session_cookie_value_or_the_pending_login_token(app):+ client = _signed_in("[email protected]")+ cookie = client.cookies.get(COOKIE)+ assert client.get("/auth/sessions").status_code == 200 # the list and index are in use too++ assert cookie and not any(cookie in item for item in _everything_in_redis(app.redis))++ secret, _ = _enroll(app, client)+ pending = _login(TestClient(main.app), "[email protected]").json()["pending_token"]+ assert not any(pending in item for item in _everything_in_redis(app.redis))+++def test_the_sessions_index_keeps_digests_not_session_ids(app):+ _signed_in("[email protected]")++ values = app.redis.hvals(auth._user_sessions_key(2))++ assert len(values) == 1 and re.fullmatch(r"[0-9a-f]{64}", values[0])+++def test_a_session_stored_under_the_raw_cookie_value_is_not_accepted(app):+ """What an old-format key (or a guess at one) looks like: the cookie value itself in the key."""+ app.redis.set("homelab:session:planted-cookie-value", json.dumps({"user_id": 1, "email": "[email protected]", "name": "A", "role": "admin", "stage": "full", "public_id": "0" * 16}))+ client = TestClient(main.app, cookies={COOKIE: "planted-cookie-value"})++ assert client.get("/monitoring/overview").status_code == 401+++def test_listing_and_ending_sessions_still_work_with_digests(app):+ first = _signed_in("[email protected]")+ second = _signed_in("[email protected]")++ listed = first.get("/auth/sessions").json()["sessions"]+ other = next(item for item in listed if not item["current"])+ assert len(listed) == 2 and first.delete(f"/auth/sessions/{other['id']}").status_code == 200++ assert second.get("/auth/me").status_code == 401 and first.get("/auth/me").status_code == 200+++def test_old_format_session_data_is_removed_at_start_and_new_data_is_kept(app):+ client = _signed_in("[email protected]")+ old_session, old_pending, old_attempts = "homelab:session:" + "a" * 43, "homelab:2fa-pending:" + "b" * 43, "homelab:2fa-attempts:" + "c" * 43+ for key in (old_session, old_pending, old_attempts):+ app.redis.set(key, "x")+ app.redis.hset("homelab:user-sessions:9", "0123456789abcdef", "raw-session-id-not-a-digest")+ before = len(app.redis.keys("homelab:session:*"))++ removed = auth.purge_legacy_session_keys(app.redis)++ assert removed == 4+ for key in (old_session, old_pending, old_attempts):+ assert app.redis.get(key) is None+ assert app.redis.hgetall("homelab:user-sessions:9") == {}+ assert len(app.redis.keys("homelab:session:*")) == before - 1 and client.get("/auth/me").status_code == 200 # the live session survived+++def test_the_cleanup_of_old_session_data_never_stops_the_backend_from_starting(app):+ class Broken:+ def scan_iter(self, *args, **kwargs):+ raise ConnectionError("redis is down")++ assert auth.purge_legacy_session_keys(Broken()) == 0