Skip to content

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.

feat(auth): two-factor sign-in, encrypted secrets, sessions and password change

karloks200590476bc6dcb3
diff --git a/README.md b/README.md
index 9925787..bc58996 100644
--- a/README.md
+++ b/README.md
@@ -535,6 +535,10 @@ standard-library Python.
- **Passwords must be at least 16 characters** (and at most 72 bytes). A few random
words make a good passphrase. The rule applies to new accounts; existing
accounts keep working with their current password.
+- **Account page** (sidebar → Account), for every user: change your password (needs
+ the current one; signs out your other devices), turn on **two-factor sign-in**,
+ and review or end your sessions (**Sign out everywhere else**). See
+ [Two-factor sign-in](#two-factor-sign-in).
- Everyone signed in can see all servers, containers and incidents.
- Only admins can add, approve, dismiss or delete servers, change check
intervals, manage the enrollment key and open the **Admin** page.
@@ -544,6 +548,43 @@ standard-library Python.
chat with the assistant on or off. The other sections on the page show
placeholder data and aren't saved yet.
+### Two-factor sign-in
+
+Two-factor uses a one-time code from any authenticator app (TOTP, the same standard
+as Google Authenticator, Aegis or a password manager).
+
+1. **Create a key once.** Secrets are stored encrypted, so the stack needs a key.
+ Generate one and put it in `.env` as `SECRETS_KEY` (see `example.env`):
+
+ ```bash
+ docker compose run --rm --no-deps backend python -m src.backend.secrets_box
+ ```
+
+ Back this key up with your other secrets. **If you lose it, authenticator codes
+ stop working** (recovery codes still do, and so does the reset command below).
+ To rotate it, put the new key first and keep the old one after a comma.
+2. **Turn it on** under Account → Two-factor sign-in. You get a setup key and an
+ `otpauth://` link to paste into your authenticator app (no QR code yet), confirm
+ with a code, and are shown **10 recovery codes once**. Each works one time.
+3. **Signing in** then asks for the code after the password. A recovery code can be
+ typed instead.
+
+**Admins must use it by default.** *Admin → Users → Require two-factor for admins* is
+**on**. An admin without two-factor can still sign in, but only to the Account page
+until they finish setting it up, so nobody is locked out. A member's two-factor is
+optional. The setting is only enforced when `SECRETS_KEY` is set; without it the
+backend prints a warning at start and the policy does nothing.
+
+**Locked out?** An admin who lost both the authenticator and the recovery codes can
+reset an account from the host:
+
+```bash
+docker compose exec backend python src/backend/reset_2fa.py [email protected]
+```
+
+It turns two-factor off for that account and signs it out everywhere. With the
+policy on, the account is asked to set up two-factor again at its next sign-in.
+
## Configuration
### Stack (`.env` next to the Compose file)
@@ -557,6 +598,7 @@ standard-library Python.
| `SESSION_COOKIE_SECURE` | `false` (dev), `true` (server file) | Send the login cookie over HTTPS only. |
| `SESSION_TTL_SECONDS` | `86400` | Session lifetime. |
| `ALLOW_REGISTRATION` | `true` (dev), `false` (server file) | Let anyone create an account. When `false`, only the first account can be created. |
+| `SECRETS_KEY` | empty | Key that encrypts two-factor secrets. Required for two-factor sign-in and for the "require two-factor for admins" policy to be enforced. Generate with `python -m src.backend.secrets_box`; comma-separated keys allow rotation. |
| `ADMIN_BOOTSTRAP_TOKEN` | generated at start | Setup token for the first account. Leave empty to have one generated and printed in the backend log until the first account exists. |
| `FRONTEND_BIND` | `0.0.0.0` (dev), `127.0.0.1` (server file) | Interface for the dashboard's plain-HTTP port. |
| `FRONTEND_PORT` | `5173` | Dashboard port on the host. |
@@ -627,7 +669,9 @@ from the backend's response to each report.
admin, then an admin's click. Re-pairing a machine that matches an existing
server needs explicit confirmation.
- **Fresh installs can't be claimed.** The first account needs a setup token.
-- **Accounts.** Passwords must be at least 16 characters. Every logged-in account
+- **Accounts.** Passwords must be at least 16 characters. Two-factor sign-in
+ (authenticator app plus single-use recovery codes) is available to everyone and
+ **required for admins by default**; secrets are encrypted with your `SECRETS_KEY`. Every logged-in account
can see all monitoring data and use the assistant (your Gemini key) unless an
admin turns chat off. Only admins can add, approve or remove servers. With
`ALLOW_REGISTRATION=false` (the default in `docker-compose.server.yml`) only the
@@ -773,6 +817,11 @@ All paths are relative to `/api` when going through the frontend/nginx.
|---|---|---|
| `GET /health` | – | Database and Redis status. |
| `POST /auth/register`, `POST /auth/login`, `POST /auth/logout`, `GET /auth/me` | session cookie | Accounts and sessions. |
+| `POST /auth/login/2fa` | pending login token | Second step of sign-in: authenticator or recovery code. |
+| `GET /auth/2fa/status`, `POST /auth/2fa/setup`, `POST /auth/2fa/enable` | session (also the limited setup session) | Two-factor status, start and confirm setup. |
+| `POST /auth/2fa/disable`, `POST /auth/2fa/recovery-codes` | session + password + code | Turn two-factor off; replace the recovery codes. |
+| `POST /auth/password` | session + current password | Change password; signs out other sessions. |
+| `GET /auth/sessions`, `POST /auth/sessions/revoke-others`, `DELETE /auth/sessions/{id}` | session | List and end your own sessions. |
| `GET /auth/config` | – | Whether registration is open and whether the first account still needs a setup token. |
| `GET /monitoring/overview` | session | Servers (latest metrics, filesystems, containers from the latest check-in, open incident count), pending servers (admins), active incidents and disk thresholds. |
| `GET /monitoring/servers/{id}/history` | session | CPU, memory and root disk samples (`?minutes=`, default 30, max 1440). |
@@ -784,7 +833,7 @@ All paths are relative to `/api` when going through the frontend/nginx.
| `POST /monitoring/join-tokens` | admin | Create the single-use join token for **Connect a server** (shown once). |
| `GET /monitoring/install-info` | admin | The collector address and images the panel uses. |
| `GET` / `POST` / `DELETE /monitoring/enrollment-key` | admin | Show status / create or rotate / revoke the enrollment key. |
-| `GET` / `PUT /admin/settings` | admin | Metrics retention, chat on/off, alert thresholds and per-mount disk thresholds. |
+| `GET` / `PUT /admin/settings` | admin | Metrics retention, chat on/off, require two-factor for admins, alert thresholds and per-mount disk thresholds. |
| `GET /agent/config` | session | Whether chat with the assistant is enabled. |
| `POST /monitoring/collectors/register` | join token (rate limited) | Collector asks to join; returns a poll secret and pairing code. |
| `POST /monitoring/collectors/register/poll` | poll secret | Collector checks approval; returns its token once approved. |
diff --git a/SECURITY.md b/SECURITY.md
index 3c41f04..d2755d9 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -100,6 +100,41 @@ stats) and nothing more through Docker.
If something between the browser and nginx rewrites the `Host` header, add your dashboard's URL to
`CORS_ORIGINS` (for example `https://dashboard.example.com`).
+## Two-factor sign-in and sessions
+
+- **TOTP and recovery codes.** Admins must use two-factor by default (*Admin → Users*). Codes are
+ standard 6-digit TOTP (RFC 6238) and accepted one 30-second period either side. A code can be used
+ once; replaying it, even inside its window, is refused. Ten recovery codes (80 bits each) are shown
+ once, stored only as SHA-256 hashes, and each works a single time.
+- **No session before the second step.** After a correct password the server returns only a short-lived
+ (5 minute) single-use token. A session and cookie exist only after a correct code. Wrong codes get one
+ generic answer and are counted per account (5 per 5 minutes, shared by every attempt, so starting the
+ password step again doesn't reset it) and per address.
+- **Secrets are encrypted.** The TOTP secret is stored encrypted (Fernet) with `SECRETS_KEY` from `.env`.
+ Without a valid key nothing is ever stored in plain text, two-factor can't be set up, and the
+ "require for admins" policy is *not enforced* (the backend prints a warning at start), so a missing
+ key can't lock anyone out. Losing the key makes authenticator codes unusable; recovery codes and the
+ reset command still work.
+- **Enrolment can't lock you out.** An admin without two-factor, while the policy is on, gets a limited
+ session that can reach only their profile, the two-factor setup and logout. Every other endpoint
+ refuses it by default.
+- **Sessions.** Session IDs are random and never shown to the browser's page; the Account page lists
+ sessions under separate public IDs. Changing the password or turning two-factor on or off signs out
+ the other sessions and issues a new session ID for the current one. A session ID isn't reused after a
+ privilege change.
+- **Reset.** `python src/backend/reset_2fa.py <email>`, run in the backend container, turns two-factor
+ off for an account and signs it out everywhere. It needs access to the host, which is the point.
+
+Known limits:
+
+- Anyone who knows an account's password can make five wrong code guesses per five minutes, which locks
+ that account's code step for the rest of the window (the same trade-off as the email lockout).
+- Sessions that existed before this feature was installed aren't in the per-user list; they expire at
+ the normal 24 hours (or on logout) and can't be ended from the Account page.
+- TOTP only. There are no passkeys or hardware keys yet, and the setup shows a key and link, not a QR code.
+- Recovery codes protect against a lost phone, not a lost `SECRETS_KEY` combined with a lost phone and
+ lost recovery codes; the host-side reset covers that.
+
## HTTP security headers
The frontend's nginx sends these on every response: a Content-Security-Policy that allows only the
diff --git a/TESTS.md b/TESTS.md
index e2aa4b4..37176c5 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, wha
covers (and what it doesn't), and what every single test is for, so you can decide
whether a failure matters before you upgrade or change your setup.
-- **507 test cases** from 292 test functions (some functions run once per input).
+- **628 test cases** from 366 test functions (some functions run once per input).
- **About 15 to 20 seconds** 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 database
and fakes; they never touch your running containers or your data. (Two collector
@@ -66,7 +66,7 @@ Each test builds just what it needs and checks one behaviour:
- **A fresh in-memory SQLite database** per test (`DATABASE_URL=sqlite://`, set by the
tests themselves). Your PostgreSQL is never used.
-- **A fake Redis.** The code is told Redis is "there", but nothing connects to one.
+- **A fake Redis** (`tests/fakes.py`). The code is told Redis is "there", but nothing connects to one.
- **Faked system access.** Tests that read `/proc`, mounted filesystems, the Docker
API, the kernel log or `wtmp` point the collector at temporary files or stubs, so
results don't depend on the machine running them.
@@ -84,7 +84,9 @@ Because of this, the same tests pass on a laptop, a VPS or a Raspberry Pi.
Being clear about the limits matters, especially for a security-focused project:
- **The web interface** (React) has no automated tests. Build errors show up when you
- run `docker compose up -d --build`; look at the dashboard after upgrading.
+ run `docker compose up -d --build`; look at the dashboard after upgrading. This
+ includes the Account page and the two-factor prompts: the endpoints behind them are
+ tested, the screens are not.
- **Your deployment**: Compose files, Traefik labels, nginx configuration, your VPN,
firewall rules and the collector gate are not exercised by the suite. They were
checked by hand against a running stack when written, not by an automated test.
@@ -118,6 +120,7 @@ docker compose logs --tail 20 collector # "Sent host metrics and N contai
| File | Cases | Protects |
|---|---|---|
+| [`test_account_security.py`](#test_account_securitypy) | 121 | Two-factor sign-in, recovery codes, encrypted secrets, sessions you can review and end, and password change. |
| [`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. |
@@ -142,6 +145,88 @@ docker compose logs --tail 20 collector # "Sent host metrics and N contai
Each table row is one test function. Where a function is marked *(N inputs)* it runs
once per input, which is why the totals above are larger than the number of rows.
+### test_account_security.py
+
+Two-factor sign-in, recovery codes, encrypted secrets, sessions and password change.
+If these fail, an account could be easier to take over, or an admin could be locked
+out of their own install.
+
+| Test | What it checks |
+|---|---|
+| `test_codes_match_the_rfc_6238_reference_vectors` *(6 inputs)* | The one-time code generator gives the exact answers published in the TOTP standard (RFC 6238), so it will match any authenticator app. |
+| `test_a_code_is_accepted_in_its_own_period_and_one_either_side_but_not_further` | A code works in its own 30-second period and one either side (clock drift), not further away. |
+| `test_a_code_cannot_be_used_twice_or_after_a_newer_one` | A code that was already used, or an older one, is refused. |
+| `test_malformed_codes_are_rejected` *(12 inputs)* | Empty, short, long, non-numeric, huge and non-string codes are refused without errors. |
+| `test_spaces_and_a_hyphen_in_a_typed_code_are_ignored` | `123 456` and `123-456` are accepted as `123456`. |
+| `test_new_secrets_are_random_and_authenticator_friendly` | Every secret is different and uses the base32 letters authenticator apps expect. |
+| `test_the_otpauth_link_names_the_account_and_issuer_safely` | The link you paste into an authenticator carries the account and "Vexion", with odd characters escaped. |
+| `test_recovery_codes_are_random_formatted_and_normalised` | Ten distinct recovery codes in `XXXX-XXXX-XXXX-XXXX` form; typing them in lower case or without hyphens still matches. |
+| `test_things_that_are_not_recovery_codes_are_refused` *(7 inputs)* | Wrong length, wrong characters and non-strings are not treated as recovery codes. |
+| `test_secrets_are_encrypted_and_round_trip` | A secret is encrypted with `SECRETS_KEY` and decrypts back; the stored text doesn't contain it. |
+| `test_without_a_key_nothing_can_be_stored` | With no `SECRETS_KEY`, nothing is stored (never in plain text). |
+| `test_an_invalid_key_is_refused_not_used` *(6 inputs)* | A malformed key is treated as no key at all. |
+| `test_a_wrong_key_or_tampered_value_cannot_be_decrypted` | Another key, or an edited stored value, fails to decrypt instead of returning garbage. |
+| `test_keys_can_be_rotated_by_listing_the_new_one_first` | Listing a new key first encrypts with it while values made with the old key still open. |
+| `test_session_ids_are_long_random_and_distinct` | Session IDs are long, random and never repeat. |
+| `test_a_session_is_indexed_under_its_user_and_shows_only_public_ids` | Each user's sessions are listed under opaque public IDs; the real session ID never appears. |
+| `test_expired_sessions_drop_out_of_the_list` | Sessions that expired no longer show up. |
+| `test_one_session_can_be_revoked_without_touching_the_others` | Ending one session leaves the user's others signed in. |
+| `test_a_user_cannot_revoke_or_see_someone_elses_session` | Another user's session can neither be seen nor ended. |
+| `test_malformed_public_ids_are_never_looked_up` *(8 inputs)* | Odd session identifiers are rejected before touching Redis. |
+| `test_all_other_sessions_can_be_revoked_keeping_the_current_one` | "Sign out everywhere else" keeps only the current session. |
+| `test_logging_out_removes_the_session_from_the_index` | Logging out also removes the session from the list. |
+| `test_logging_out_a_session_that_already_expired_is_still_fine` | Logging out with an expired session doesn't fail. |
+| `test_sessions_created_before_stages_existed_count_as_full` | Sessions from before this feature stay working as normal sessions. |
+| `test_limited_sessions_are_refused_unless_a_caller_opts_in` | A limited (set-up-only) session is refused by default; only the two-factor setup endpoints opt in. |
+| `test_every_route_that_needs_a_session_refuses_a_limited_one` | Sweeps every route that needs a sign-in and checks each refuses a limited session, except the short allowed list. |
+| `test_a_limited_session_is_refused_everywhere_except_the_two_factor_setup` | A limited session can reach only its own profile, two-factor setup and logout. |
+| `test_a_limited_session_cannot_disable_regenerate_or_change_the_password` | A limited session can't turn off two-factor, make new recovery codes or change the password. |
+| `test_signing_in_with_two_factor_needs_both_steps_and_creates_no_session_before_the_second` | After the password alone there is no cookie and no session; only a correct code creates one. |
+| `test_a_wrong_or_malformed_code_is_refused_with_one_generic_message` | Every kind of wrong code gets the same "Invalid code." answer. |
+| `test_a_wrong_code_during_sign_in_is_audited_without_the_code` | Failed codes are logged without recording what was typed. |
+| `test_a_pending_login_is_destroyed_after_five_wrong_codes` | Five wrong codes end that sign-in attempt; the right code no longer helps. |
+| `test_a_successful_second_step_resets_the_failure_count` | A good code clears the attempt count. |
+| `test_a_pending_login_token_is_single_use_and_unknown_tokens_are_refused` | A login token works once; invented ones are refused. |
+| `test_an_expired_pending_login_cannot_be_completed` | If the code isn't entered within five minutes, the password step has to be repeated. |
+| `test_guessing_across_many_pending_logins_locks_the_account_for_a_while` | Restarting the password step doesn't reset the guess count; five wrong codes in five minutes lock the account's code step. |
+| `test_the_per_address_limit_on_code_attempts_applies_too` | One IP address can't guess codes for many accounts. |
+| `test_hostile_second_step_bodies_are_rejected_before_any_work` *(7 inputs)* | Missing, oversized or wrong-typed fields are rejected right away. |
+| `test_unknown_emails_cost_the_same_work_as_wrong_passwords` | Sign-in does the same password work for unknown emails, so timing doesn't reveal which accounts exist. |
+| `test_a_member_signs_in_with_just_a_password` | Members without two-factor sign in as before. |
+| `test_the_code_from_the_enrollment_step_cannot_be_reused_to_sign_in` | The code used to switch two-factor on can't be used again straight away to sign in. |
+| `test_a_wrong_code_does_not_enable_two_factor` | A wrong confirmation code leaves two-factor off. |
+| `test_enabling_without_starting_setup_is_refused` | Confirming a code without first requesting a secret is refused. |
+| `test_setting_up_again_before_confirming_replaces_the_pending_secret` | Starting setup twice gives a new secret; the abandoned one is useless. |
+| `test_setup_is_refused_while_two_factor_is_already_on` | You can't replace a working secret without turning two-factor off first. |
+| `test_the_secret_is_stored_encrypted_and_recovery_codes_only_as_hashes` | In the database the secret is encrypted and recovery codes are hashes; neither is readable. |
+| `test_secrets_never_appear_in_api_responses` | After setup is done, no response includes the secret or the recovery codes again. |
+| `test_recovery_codes_work_once_and_the_count_drops` | A recovery code signs you in once; the remaining count goes down. |
+| `test_regenerating_recovery_codes_replaces_the_old_ones` | Making new codes (needs password and a code) invalidates all old ones. |
+| `test_turning_two_factor_off_needs_the_password_and_a_code_and_ends_other_sessions` | Turning two-factor off needs the password plus a code, and signs out other sessions. |
+| `test_if_the_key_is_lost_totp_codes_stop_working_but_recovery_codes_still_do` | If `SECRETS_KEY` is lost, authenticator codes fail but recovery codes still get you in. |
+| `test_when_no_key_is_configured_two_factor_is_not_enforced_and_cannot_be_set_up` | Without a key the "require 2FA" policy isn't enforced (no lock-out) and setup says why it can't proceed. |
+| `test_the_policy_can_be_turned_off_and_defaults_to_on` | "Require two-factor for admins" is on by default and an admin can switch it off. |
+| `test_admins_can_change_the_policy_and_it_is_audited` | Policy changes are admin-only and recorded in the log. |
+| `test_the_policy_only_applies_to_administrators` | Members are never forced to enrol. |
+| `test_an_admin_without_two_factor_gets_a_limited_session_when_it_is_required` | An admin who hasn't enrolled can sign in, but only to set up two-factor. |
+| `test_enrolling_upgrades_the_session_and_rotates_its_id` | Finishing enrolment turns the limited session into a full one with a new ID. |
+| `test_the_first_account_on_a_fresh_install_must_enrol_when_the_policy_is_on` | The first admin lands on the two-factor setup straight after registering. |
+| `test_an_admin_cannot_turn_two_factor_off_while_the_policy_requires_it` | While the policy is on, an admin can't disable their own two-factor. |
+| `test_a_members_two_factor_is_optional_but_available` | A member can turn two-factor on and off. |
+| `test_a_reset_admin_is_asked_to_enrol_again_when_it_is_required` | After a command-line reset, the admin signs in with the password and is asked to enrol again. |
+| `test_resetting_two_factor_from_the_command_line_helper` | The reset command clears the secret and recovery codes and signs the account out everywhere. |
+| `test_the_reset_script_asks_for_exactly_one_email` | The reset command refuses missing or extra arguments. |
+| `test_bad_password_changes_are_refused_and_change_nothing` *(5 inputs)* | Wrong current password, short, over-long or unchanged new passwords are refused and nothing changes. |
+| `test_changing_the_password_signs_out_other_sessions_and_rotates_this_one` | After a password change, other devices are signed out and this one gets a new session ID. |
+| `test_password_change_attempts_are_rate_limited` | Repeated password-change attempts are rate limited. |
+| `test_the_account_page_lists_sessions_and_can_end_them` | The sessions list shows device, address and time, and ending one works. |
+| `test_sign_out_everywhere_else_keeps_only_this_session` | The endpoint behind "Sign out everywhere else" keeps the current session only. |
+| `test_ending_the_current_session_through_the_list_clears_the_cookie` | Ending your own session from the list signs you out and clears the cookie. |
+| `test_logout_ends_the_session_everywhere_and_the_cookie_is_cleared` | Logging out deletes the session on the server as well as the cookie. |
+| `test_malformed_session_ids_in_the_url_are_not_found` *(4 inputs)* | Odd identifiers in the session URL get "not found". |
+| `test_one_user_cannot_end_another_users_session_by_guessing_its_id` | Even a valid public ID can only be ended by the account that owns it. |
+| `test_cross_site_requests_to_the_new_endpoints_are_refused` | All the new state-changing endpoints reject requests from another site. |
+
### test_admin.py
Roles and permissions. If these fail, someone might be able to do something they
@@ -198,7 +283,7 @@ Accounts, passwords, first-run protection and the cross-site check.
| Test | What it checks |
|---|---|
| `test_register_user_creates_record_and_hashes_password` | Registering stores the account and a bcrypt hash, never the password itself. |
-| `test_authenticate_user_returns_session_for_valid_credentials` | Signing in with the right email and password returns a session. |
+| `test_valid_credentials_identify_the_user_and_open_a_session` | The right email and password identify the account and a session can then be opened for it. |
| `test_record_audit_log_persists_database_entries` | Audit-log entries, including assistant events with steps and conversation IDs, are saved. |
| `test_registration_closed_still_allows_first_account` | With registration switched off, the first account can still be created on an empty install; once an account exists, registration closes and a stranger is refused (403). |
| `test_registration_open_by_default` | Registration is open when `ALLOW_REGISTRATION` is true. |
diff --git a/compose.yml b/compose.yml
index 517f4c8..6e36e93 100644
--- a/compose.yml
+++ b/compose.yml
@@ -46,6 +46,8 @@ services:
SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false}
ALLOW_REGISTRATION: ${ALLOW_REGISTRATION:-true}
CORS_ORIGINS: ${CORS_ORIGINS:-http://localhost:5173}
+ # Key that encrypts stored secrets such as two-factor secrets (generate: docker compose run --rm backend python -m src.backend.secrets_box).
+ SECRETS_KEY: ${SECRETS_KEY:-}
# Connect a server panel: images remote hosts install, and the address they reach this dashboard at.
COLLECTOR_IMAGE: ${COLLECTOR_IMAGE:-}
DOCKER_PROXY_IMAGE: ${DOCKER_PROXY_IMAGE:-}
diff --git a/docker-compose.server.yml b/docker-compose.server.yml
index 464cbb2..acece3c 100644
--- a/docker-compose.server.yml
+++ b/docker-compose.server.yml
@@ -59,6 +59,8 @@ services:
REGISTER_RATE_LIMIT: ${REGISTER_RATE_LIMIT:-3}
REGISTER_RATE_WINDOW_SECONDS: ${REGISTER_RATE_WINDOW_SECONDS:-3600}
ADMIN_ALERT_WEBHOOK_URL: ${ADMIN_ALERT_WEBHOOK_URL:-}
+ # Key that encrypts stored secrets such as two-factor secrets (generate: docker compose run --rm backend python -m src.backend.secrets_box).
+ SECRETS_KEY: ${SECRETS_KEY:-}
# Collector endpoints answer only through the collector-gate container (VPN or internal).
COLLECTOR_ACCESS: strict
# Shown in the Connect a server panel: your VPN address for the gate, and pinned images.
diff --git a/example.env b/example.env
index 2f8440c..a16950b 100644
--- a/example.env
+++ b/example.env
@@ -35,6 +35,16 @@ TRAEFIK_ROUTER=homelab
# https:// and no trailing slash. Leave commented to use the default.
# CORS_ORIGINS=https://<your-domain>
+# =============================================================================
+# Secrets at rest (needed for two-factor sign-in)
+# =============================================================================
+
+# Key that encrypts secrets the app must read back, such as two-factor secrets. Without it two-factor
+# can't be set up and is not enforced. Keep it out of backups of the database. Generate one with:
+# docker compose run --rm backend python -m src.backend.secrets_box
+# To rotate, put the new key first and keep the old one after a comma: SECRETS_KEY=<new>,<old>
+SECRETS_KEY=
+
# =============================================================================
# AI chat (optional)
# =============================================================================
diff --git a/requirements.txt b/requirements.txt
index f9f3b80..0df689c 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,4 +1,5 @@
bcrypt
+cryptography
email-validator
fastapi
google-genai
diff --git a/src/backend/auth.py b/src/backend/auth.py
index edb0174..9bba51a 100644
--- a/src/backend/auth.py
+++ b/src/backend/auth.py
@@ -1,10 +1,24 @@
import json
-import uuid
+import re
+import secrets
+from datetime import datetime, timezone
import bcrypt
+from sqlalchemy import or_
+from . import secrets_box, totp
from .config import SESSION_TTL_SECONDS
-from .models import AuditLog, User
+from .models import AuditLog, RecoveryCode, User
+
+# A "full" session can use everything. An "enrollment" session is what an admin gets when two-factor is
+# required but not yet set up: it can only reach the two-factor setup and is refused everywhere else.
+STAGE_FULL = "full"
+STAGE_ENROLLMENT = "enrollment"
+PENDING_TWO_FACTOR_TTL_SECONDS = 300
+MAX_PENDING_ATTEMPTS = 5
+_PUBLIC_ID = re.compile(r"[0-9a-f]{16}")
+# Checked against when the account doesn't exist, so that unknown emails cost the same time as wrong passwords.
+_DUMMY_PASSWORD_HASH = bcrypt.hashpw(b"not-a-real-password", bcrypt.gensalt())
def _serialize_user(user: User):
return {
@@ -36,6 +50,140 @@ def _delete_session(redis_client, session_id: str):
redis_client.delete(key)
+def _user_sessions_key(user_id: int) -> str:
+ return f"homelab:user-sessions:{user_id}"
+
+
+def _pending_key(token: str) -> str:
+ return f"homelab:2fa-pending:{token}"
+
+
+def _printable(text: str | None, limit: int) -> str | None:
+ cleaned = "".join(char if char.isprintable() else "?" for char in (text or "").strip())[:limit].strip()
+ return cleaned or None
+
+
+def create_session(redis_client, user: User, *, stage: str = STAGE_FULL, ip: str | None = None, user_agent: str | None = None) -> tuple[str, str]:
+ """Open a session and index it under its user. Returns (session_id, public_id).
+
+ The session ID is the secret in the cookie and is never shown to a client. The public ID is a separate
+ random value used only to list and revoke a user's own sessions.
+ """
+ session_id, public_id = secrets.token_urlsafe(32), secrets.token_hex(8)
+ _store_session(redis_client, session_id, {
+ "user_id": user.id, "email": user.email, "name": user.name, "role": user.role, "stage": stage, "public_id": public_id,
+ "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.expire(index, SESSION_TTL_SECONDS)
+ return session_id, public_id
+
+
+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)
+ if not raw:
+ return None
+ try:
+ data = json.loads(raw)
+ except (TypeError, ValueError):
+ return None
+ return {
+ "id": data.get("user_id"), "name": data.get("name"), "email": data.get("email"), "role": data.get("role"),
+ "stage": data.get("stage", STAGE_FULL), "public_id": data.get("public_id"),
+ "created_at": data.get("created_at"), "ip": data.get("ip"), "user_agent": data.get("user_agent"),
+ }
+
+
+def get_user_from_session(redis_client, session_id: str | None, *, allow_limited: bool = False):
+ """The signed-in user, or None. Limited (enrollment) sessions are refused unless the caller opts in."""
+ session = get_session(redis_client, session_id)
+ if not session or (session["stage"] != STAGE_FULL and not allow_limited):
+ return None
+ return session
+
+
+def delete_session(redis_client, session_id: str | None) -> bool:
+ """End a session and remove it from its user's index."""
+ session = get_session(redis_client, session_id)
+ if not session:
+ return False
+ if session["public_id"] and session["id"] is not None:
+ redis_client.hdel(_user_sessions_key(session["id"]), session["public_id"])
+ _delete_session(redis_client, session_id)
+ return True
+
+
+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)
+ if not session or session["id"] != user_id or session["public_id"] != public_id:
+ redis_client.hdel(index, public_id)
+ continue
+ sessions.append({"id": public_id, "created_at": session["created_at"], "ip": session["ip"], "user_agent": session["user_agent"],
+ "current": public_id == current_public_id, "limited": session["stage"] != STAGE_FULL})
+ return sorted(sessions, key=lambda item: item["created_at"] or "", reverse=True)
+
+
+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)
+ 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)
+
+
+def revoke_other_sessions(redis_client, user_id: int, keep_public_id: str | None) -> int:
+ """Sign out every session of the user except the one with ``keep_public_id`` (all of them if None)."""
+ revoked = 0
+ for public_id in list(redis_client.hgetall(_user_sessions_key(user_id))):
+ if public_id != keep_public_id and revoke_user_session(redis_client, user_id, public_id):
+ revoked += 1
+ return revoked
+
+
+def create_pending_two_factor(redis_client, user_id: int) -> str:
+ """The short-lived token that carries a login between the password step and the code step."""
+ token = secrets.token_urlsafe(32)
+ redis_client.set(_pending_key(token), json.dumps({"user_id": user_id}), ex=PENDING_TWO_FACTOR_TTL_SECONDS)
+ return token
+
+
+def read_pending_two_factor(redis_client, token) -> int | None:
+ if not isinstance(token, str) or not 20 <= len(token) <= 100:
+ return None
+ raw = redis_client.get(_pending_key(token))
+ try:
+ return int(json.loads(raw)["user_id"]) if raw else None
+ except (TypeError, ValueError, KeyError):
+ return 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}"
+ attempts = redis_client.incr(key)
+ if attempts == 1:
+ redis_client.expire(key, PENDING_TWO_FACTOR_TTL_SECONDS)
+ if attempts > MAX_PENDING_ATTEMPTS:
+ delete_pending_two_factor(redis_client, token)
+ return False
+ return True
+
+
+def delete_pending_two_factor(redis_client, token: str) -> None:
+ redis_client.delete(_pending_key(token), f"homelab:2fa-attempts:{token}")
+
+
def record_audit_log(
db,
*,
@@ -130,7 +278,8 @@ def validate_password(password: str) -> None:
raise ValueError(f"Password must be at most {PASSWORD_MAX_BYTES} bytes long.")
-def register_user(db, redis_client, *, name: str, email: str, password: str):
+def register_user(db, redis_client, *, name: str, email: str, password: str, admin_requires_two_factor: bool = False,
+ ip: str | None = None, user_agent: str | None = None):
normalized_name = name.strip()
normalized_email = email.strip().lower()
@@ -160,62 +309,82 @@ def register_user(db, redis_client, *, name: str, email: str, password: str):
record_audit_log(db, user_id=user.id, level="INFO", message="New account registered", source="auth")
- session_id = str(uuid.uuid4())
- _store_session(
- redis_client,
- session_id,
- {"user_id": user.id, "email": user.email, "name": user.name, "role": user.role},
- )
+ stage = STAGE_ENROLLMENT if user.role == "admin" and admin_requires_two_factor else STAGE_FULL
+ session_id, _public_id = create_session(redis_client, user, stage=stage, ip=ip, user_agent=user_agent)
- return {"session_id": session_id, "user": _serialize_user(user)}
+ return {"session_id": session_id, "user": _serialize_user(user), "setup_required": stage == STAGE_ENROLLMENT}
-def authenticate_user(db, redis_client, *, email: str, password: str):
- normalized_email = email.strip().lower()
- user = db.query(User).filter(User.email == normalized_email).first()
+def verify_password(user: User, password: str) -> bool:
+ # Anything over bcrypt's limit can't be a valid password here; bcrypt would raise with a different message.
+ if not isinstance(password, str) or len(password.encode("utf-8")) > PASSWORD_MAX_BYTES:
+ return False
+ return bcrypt.checkpw(password.encode("utf-8"), user.password_hash.encode("utf-8"))
+
+def verify_credentials(db, *, email: str, password: str) -> User:
+ """The active account for a correct email and password. Raises one generic error for every kind of failure."""
+ user = db.query(User).filter(User.email == email.strip().lower()).first()
if not user or not user.is_active:
+ # Do the same work as for a wrong password so the response time doesn't reveal which emails exist.
+ bcrypt.checkpw(b"not-a-real-password", _DUMMY_PASSWORD_HASH)
raise ValueError("Invalid email or password.")
-
- # Anything over bcrypt's limit can't be a valid password here; bcrypt would raise with a different message.
- if len(password.encode("utf-8")) > PASSWORD_MAX_BYTES or not bcrypt.checkpw(password.encode("utf-8"), user.password_hash.encode("utf-8")):
+ if not verify_password(user, password):
raise ValueError("Invalid email or password.")
+ return user
+
+
+def hash_password(password: str) -> str:
+ return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
+
+
+def verify_second_factor(db, user: User, code) -> str | None:
+ """"totp" or "recovery" if the code is valid for this user, else None. A valid code is consumed.
+
+ TOTP codes must belong to a time step newer than the last accepted one (no replay) and the update is done
+ atomically, so two simultaneous attempts with the same code can't both succeed. Recovery codes work once.
+ Raises secrets_box.SecretsUnavailable if the stored secret can't be decrypted.
+ """
+ if totp.normalize_code(code) is not None:
+ if not user.totp_enabled or not user.totp_secret_enc:
+ return None
+ step = totp.verify(secrets_box.decrypt(user.totp_secret_enc), code, user.totp_last_step)
+ if step is None:
+ return None
+ claimed = db.query(User).filter(User.id == user.id, or_(User.totp_last_step.is_(None), User.totp_last_step < step)).update({"totp_last_step": step}, synchronize_session=False)
+ db.flush()
+ if claimed != 1:
+ return None
+ user.totp_last_step = step
+ return "totp"
+ normalized = totp.normalize_recovery_code(code)
+ if normalized is None:
+ return None
+ used = db.query(RecoveryCode).filter(RecoveryCode.user_id == user.id, RecoveryCode.code_hash == totp.hash_recovery_code(normalized), RecoveryCode.used_at.is_(None)).update({"used_at": datetime.now(timezone.utc)}, synchronize_session=False)
+ db.flush()
+ return "recovery" if used == 1 else None
- record_audit_log(db, user_id=user.id, level="INFO", message="User signed in", source="auth")
-
- session_id = str(uuid.uuid4())
- _store_session(
- redis_client,
- session_id,
- {"user_id": user.id, "email": user.email, "name": user.name, "role": user.role},
- )
- return {"session_id": session_id, "user": _serialize_user(user)}
+def recovery_codes_left(db, user: User) -> int:
+ return db.query(RecoveryCode).filter(RecoveryCode.user_id == user.id, RecoveryCode.used_at.is_(None)).count()
-def get_user_from_session(redis_client, session_id: str | None):
- if not session_id:
- return None
+def issue_recovery_codes(db, user: User) -> list[str]:
+ """Replace the user's recovery codes with a fresh set and return the plain codes, which are never stored."""
+ db.query(RecoveryCode).filter(RecoveryCode.user_id == user.id).delete(synchronize_session=False)
+ codes = totp.generate_recovery_codes()
+ db.add_all([RecoveryCode(user_id=user.id, code_hash=totp.hash_recovery_code(code)) for code in codes])
+ return codes
- raw = _read_session(redis_client, session_id)
- if not raw:
- return None
- try:
- data = json.loads(raw)
- except (TypeError, ValueError):
- return None
-
- return {
- "id": data.get("user_id"),
- "name": data.get("name"),
- "email": data.get("email"),
- "role": data.get("role"),
- }
+def reset_two_factor(db, redis_client, user: User) -> None:
+ """Turn two-factor off for an account and sign it out everywhere (the command-line recovery path)."""
+ user.totp_enabled, user.totp_secret_enc, user.totp_last_step = False, None, None
+ db.query(RecoveryCode).filter(RecoveryCode.user_id == user.id).delete(synchronize_session=False)
+ db.commit()
+ revoke_other_sessions(redis_client, user.id, None)
+ record_audit_log(db, user_id=user.id, level="WARNING", message="Two-factor was reset from the command line", source="auth")
def logout_user(redis_client, session_id: str | None):
- if not session_id:
- return False
- _delete_session(redis_client, session_id)
- return True
+ return delete_session(redis_client, session_id)
diff --git a/src/backend/main.py b/src/backend/main.py
index b6686c2..78d61f1 100644
--- a/src/backend/main.py
+++ b/src/backend/main.py
@@ -17,13 +17,18 @@ import redis
from fastapi import Cookie, Depends, FastAPI, Header, HTTPException, Query, Request, Response, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, PlainTextResponse
-from pydantic import BaseModel, EmailStr
+from pydantic import BaseModel, EmailStr, Field
from sqlalchemy import case, func, inspect, text
from .alerts import CONTAINER_RULE_PREFIX, CRITICAL, SERVER_OFFLINE_RULE, SEVERITIES, active_rule_keys, raise_alert, resolve_alerts, sync_alerts
-from .auth import authenticate_user, get_recent_logs, get_user_from_session, logout_user, record_audit_log, register_user
+from . import secrets_box, totp
+from .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,
+ register_user, revoke_other_sessions, revoke_user_session, validate_password, verify_credentials, verify_password, verify_second_factor,
+)
from .db import SessionLocal, check_database, get_db
-from .models import AppSetting, AuditLog, Base, ChatMessage, ContainerMetric, Conversation, EnrollmentKey, FirewallState, HostMetric, IncidentAlert, JoinToken, ListenerState, MountMetric, PendingCollector, Server, SystemEvent, User
+from .models import AppSetting, AuditLog, Base, ChatMessage, ContainerMetric, Conversation, EnrollmentKey, FirewallState, HostMetric, IncidentAlert, JoinToken, ListenerState, MountMetric, PendingCollector, RecoveryCode, Server, SystemEvent, User
from .db import engine
from .config import (
@@ -45,7 +50,7 @@ from .config import (
SESSION_TTL_SECONDS,
)
from .rules import DEFAULT_THRESHOLDS, HOST_RULE_PREFIX, container_rules, host_rules, validate_thresholds, detect_system_events, system_rules, SYSTEM_RULE_PREFIX, validate_mount_thresholds, validate_helper_events, REBOOT_DETAILS, REBOOT_KEY_PREFIX, detect_container_events, memory_trend_rules, CONTAINER_EVENT_KINDS, MAX_CONTAINER_EVENTS_PER_CHECKIN, MAX_CONTAINER_EVENTS_PER_HOUR, TREND_RULE_PREFIX, NETWORK_EVENT_KINDS, NETWORK_RULE_PREFIX, MAX_NETWORK_EVENTS_PER_CHECKIN, MAX_NETWORK_EVENTS_PER_HOUR, INTERNET_STATUSES, LISTENER_SCOPES, FIREWALL_LABELS, detect_listener_changes, detect_firewall_changes, network_rules, validate_listeners, validate_firewall
-from .rate_limit import enforce_ip_limit, enforce_login_limit, enforce_register_limit, reset_limits
+from .rate_limit import enforce_ip_limit, enforce_limit, enforce_login_limit, enforce_register_limit, reset_limits
from ..agent.service import delete_agent_conversation, send_agent_message
@@ -62,6 +67,25 @@ class LoginRequest(BaseModel):
password: str
+class TwoFactorLoginRequest(BaseModel):
+ pending_token: str = Field(max_length=100)
+ code: str = Field(max_length=64)
+
+
+class CodeRequest(BaseModel):
+ code: str = Field(max_length=64)
+
+
+class ReauthRequest(BaseModel):
+ password: str = Field(max_length=1024)
+ code: str = Field(max_length=64)
+
+
+class PasswordChangeRequest(BaseModel):
+ current_password: str = Field(max_length=1024)
+ new_password: str = Field(max_length=1024)
+
+
class AgentChatRequest(BaseModel):
conversation_id: str
message: str
@@ -100,6 +124,7 @@ class AdminSettingsRequest(BaseModel):
# Both optional so the admin page can save one setting at a time.
metrics_retention_days: int | None = None
agent_chat_enabled: bool | None = None
+ require_2fa_for_admins: bool | None = None
alert_thresholds: dict | None = None
# Replaces all per-mount disk overrides: {mount: {disk_warning_pct, disk_critical_pct}}.
mount_thresholds: dict | None = None
@@ -204,6 +229,8 @@ def startup_event():
connection.execute(text("ALTER TABLE system_events ADD COLUMN IF NOT EXISTS event_key VARCHAR(128)"))
connection.execute(text("ALTER TABLE pending_collectors ADD COLUMN IF NOT EXISTS join_token_id INTEGER REFERENCES join_tokens(id) ON DELETE SET NULL"))
connection.execute(text("CREATE INDEX IF NOT EXISTS ix_system_events_event_key ON system_events (event_key)"))
+ for column, column_type in (("totp_secret_enc", "TEXT"), ("totp_enabled", "BOOLEAN NOT NULL DEFAULT FALSE"), ("totp_last_step", "INTEGER"), ("password_changed_at", "TIMESTAMP WITH TIME ZONE")):
+ connection.execute(text(f"ALTER TABLE users ADD COLUMN IF NOT EXISTS {column} {column_type}"))
connection.execute(text("ALTER TABLE incident_alerts ADD COLUMN IF NOT EXISTS rule_key VARCHAR(255)"))
connection.execute(text("ALTER TABLE incident_alerts ADD COLUMN IF NOT EXISTS resolved_at TIMESTAMP WITH TIME ZONE"))
connection.execute(text("CREATE INDEX IF NOT EXISTS ix_incident_alerts_rule_key ON incident_alerts (rule_key)"))
@@ -227,6 +254,9 @@ def startup_event():
db = SessionLocal()
try:
ensure_admin_exists(db)
+ 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)
setup_token = ensure_bootstrap_token(db)
if setup_token:
print(f"First-run setup token: {setup_token} (needed to create the first account; shown again at every start until it exists)", flush=True)
@@ -311,23 +341,46 @@ def auth_register(payload: RegisterRequest, request: Request, response: Response
name=payload.name,
email=str(payload.email),
password=payload.password,
+ admin_requires_two_factor=two_factor_enforced(db),
+ ip=_client_ip(request),
+ user_agent=request.headers.get("user-agent"),
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if first_account:
ensure_bootstrap_token(db) # an account exists now: this removes the token
+ _set_session_cookie(response, result.pop("session_id"))
+ return result
+
+
+def _set_session_cookie(response: Response, session_id: str) -> None:
response.set_cookie(
key=SESSION_COOKIE_NAME,
- value=result["session_id"],
+ value=session_id,
max_age=SESSION_TTL_SECONDS,
httponly=True,
secure=SESSION_COOKIE_SECURE,
samesite="lax",
path="/",
)
- result.pop("session_id", None)
- return result
+
+
+def _user_payload(user: User, **extra) -> dict:
+ return {"id": user.id, "name": user.name, "email": user.email, "role": user.role, "is_active": user.is_active, **extra}
+
+
+def _complete_login(db, request: Request, response: Response, user: User, how: str = "") -> dict:
+ """Open the session after every required step has passed.
+
+ An administrator without two-factor, while it is required, gets an enrollment session: it can reach
+ the two-factor setup and nothing else until setup is done.
+ """
+ stage = STAGE_ENROLLMENT if user.role == "admin" and not user.totp_enabled and two_factor_enforced(db) else STAGE_FULL
+ session_id, _public_id = create_session(redis_client, user, stage=stage, ip=_client_ip(request), user_agent=request.headers.get("user-agent"))
+ _set_session_cookie(response, session_id)
+ record_audit_log(db, user_id=user.id, level="INFO", message=f"User signed in{how}", source="auth")
+ return {"user": _user_payload(user), "setup_required": stage == STAGE_ENROLLMENT}
@app.post("/auth/login")
@@ -340,43 +393,74 @@ def auth_login(payload: LoginRequest, request: Request, response: Response, db=D
window_seconds=LOGIN_RATE_WINDOW_SECONDS,
)
try:
- result = authenticate_user(
- db,
- redis_client,
- email=str(payload.email),
- password=payload.password,
- )
+ user = verify_credentials(db, email=str(payload.email), password=payload.password)
except ValueError as exc:
raise HTTPException(status_code=401, detail=str(exc)) from exc
reset_limits(redis_client, *limit_keys)
+ if user.totp_enabled:
+ # No session exists until the second step passes; this token only carries the login between the steps.
+ return {"status": "two_factor_required", "pending_token": create_pending_two_factor(redis_client, user.id)}
+ return _complete_login(db, request, response, user)
- response.set_cookie(
- key=SESSION_COOKIE_NAME,
- value=result["session_id"],
- max_age=SESSION_TTL_SECONDS,
- httponly=True,
- secure=SESSION_COOKIE_SECURE,
- samesite="lax",
- path="/",
- )
- result.pop("session_id", None)
+
+def _second_factor_or_error(db, user: User, code: str) -> str:
+ """Verify a code for the user, with the shared brute-force limit. Raises 401 (or 429/503); returns "totp" or "recovery"."""
+ limit_key = enforce_limit(redis_client, scope="2fa-user", subject=user.id, limit=TWO_FACTOR_ATTEMPTS, window_seconds=TWO_FACTOR_WINDOW_SECONDS)
+ try:
+ method = verify_second_factor(db, user, code)
+ except secrets_box.SecretsUnavailable as exc:
+ raise HTTPException(status_code=503, detail="Two-factor codes can't be checked on this server right now (a SECRETS_KEY problem). A recovery code still works.") from exc
+ if method is None:
+ record_audit_log(db, user_id=user.id, level="WARNING", message="A wrong two-factor code was entered", source="auth")
+ raise HTTPException(status_code=401, detail="Invalid code.")
+ reset_limits(redis_client, limit_key)
+ return method
+
+
[email protected]("/auth/login/2fa")
+def auth_login_two_factor(payload: TwoFactorLoginRequest, request: Request, response: Response, db=Depends(get_db)):
+ enforce_ip_limit(redis_client, scope="2fa-ip", ip_address=_client_ip(request), limit=20, window_seconds=TWO_FACTOR_WINDOW_SECONDS)
+ expired = HTTPException(status_code=401, detail="Sign-in expired. Please sign in again.")
+ user_id = read_pending_two_factor(redis_client, payload.pending_token)
+ if user_id is None:
+ raise expired
+ if not count_pending_attempt(redis_client, payload.pending_token):
+ raise HTTPException(status_code=401, detail="Too many wrong codes. Please sign in again.")
+ user = db.get(User, user_id)
+ if not user or not user.is_active or not user.totp_enabled:
+ raise expired
+ method = _second_factor_or_error(db, user, payload.code)
+ db.commit() # the code that was just accepted is now spent
+ delete_pending_two_factor(redis_client, payload.pending_token)
+ if method == "recovery":
+ record_audit_log(db, user_id=user.id, level="WARNING", message="A two-factor recovery code was used to sign in", source="auth")
+ result = _complete_login(db, request, response, user, " with two-factor")
+ result["recovery_codes_left"] = recovery_codes_left(db, user)
return result
+def _account_session(session_id, db, *, allow_limited: bool = False) -> tuple[dict, User]:
+ """The caller's session and account for the account endpoints. Enrollment sessions only where allowed."""
+ session = get_session(redis_client, session_id)
+ if not session:
+ raise HTTPException(status_code=401, detail="Session is invalid or expired.")
+ if session["stage"] != STAGE_FULL and not allow_limited:
+ raise HTTPException(status_code=403, detail="Finish setting up two-factor first.")
+ user = db.get(User, session["id"])
+ if not user or not user.is_active:
+ raise HTTPException(status_code=401, detail="Session is invalid or expired.")
+ return session, user
+
+
@app.get("/auth/me")
def auth_me(
session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None,
db=Depends(get_db),
):
- user = get_user_from_session(redis_client, session_id)
- if not user:
- raise HTTPException(status_code=401, detail="Session is invalid or expired.")
- # Read role and status from the database so admin changes apply without a new login.
- account = db.query(User).filter(User.id == user["id"]).first()
- if not account or not account.is_active:
- raise HTTPException(status_code=401, detail="Session is invalid or expired.")
- return {"user": {**user, "name": account.name, "email": account.email, "role": account.role}}
+ session, account = _account_session(session_id, db, allow_limited=True)
+ # Role and status come from the database so admin changes apply without a new login.
+ return {"user": _user_payload(account, setup_required=session["stage"] != STAGE_FULL, two_factor_enabled=account.totp_enabled)}
@app.post("/auth/logout")
@@ -384,14 +468,161 @@ def auth_logout(
response: Response,
session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None,
):
- if logout_user(redis_client, session_id):
- response.delete_cookie(key=SESSION_COOKIE_NAME, path="/")
- return {"status": "ok"}
- raise HTTPException(status_code=400, detail="No session id supplied.")
+ if not session_id:
+ raise HTTPException(status_code=400, detail="No session id supplied.")
+ delete_session(redis_client, session_id)
+ response.delete_cookie(key=SESSION_COOKIE_NAME, path="/")
+ return {"status": "ok"}
+
+
[email protected]("/auth/2fa/status")
+def two_factor_status(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db, allow_limited=True)
+ return {
+ "enabled": user.totp_enabled, "available": secrets_box.available(),
+ "required": user.role == "admin" and two_factor_enforced(db),
+ "recovery_codes_left": recovery_codes_left(db, user) if user.totp_enabled else 0,
+ "setup_required": session["stage"] != STAGE_FULL,
+ }
+
+
[email protected]("/auth/2fa/setup")
+def two_factor_setup(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ _session, user = _account_session(session_id, db, allow_limited=True)
+ if not secrets_box.available():
+ raise HTTPException(status_code=503, detail="Two-factor needs SECRETS_KEY to be configured on the server. See the README.")
+ if user.totp_enabled:
+ raise HTTPException(status_code=409, detail="Two-factor is already turned on. Turn it off first to set it up again.")
+ enforce_limit(redis_client, scope="2fa-setup", subject=user.id, limit=10, window_seconds=3600)
+ secret = totp.new_secret()
+ # Stored encrypted and inactive until a code from the app has been confirmed.
+ user.totp_secret_enc, user.totp_last_step = secrets_box.encrypt(secret), None
+ db.commit()
+ return {"secret": secret, "otpauth_uri": totp.otpauth_uri(secret, user.email)}
+
[email protected]("/auth/2fa/enable")
+def two_factor_enable(payload: CodeRequest, request: Request, response: Response, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db, allow_limited=True)
+ if user.totp_enabled:
+ raise HTTPException(status_code=409, detail="Two-factor is already turned on.")
+ if not user.totp_secret_enc:
+ raise HTTPException(status_code=400, detail="Start the setup first.")
+ limit_key = enforce_limit(redis_client, scope="2fa-user", subject=user.id, limit=TWO_FACTOR_ATTEMPTS, window_seconds=TWO_FACTOR_WINDOW_SECONDS)
+ try:
+ step = totp.verify(secrets_box.decrypt(user.totp_secret_enc), payload.code)
+ except secrets_box.SecretsUnavailable as exc:
+ raise HTTPException(status_code=503, detail="Two-factor can't be set up on this server right now (a SECRETS_KEY problem).") from exc
+ if step is None:
+ raise HTTPException(status_code=400, detail="That code is not valid. Check the clock on your phone and try again.")
+ reset_limits(redis_client, limit_key)
+ user.totp_enabled, user.totp_last_step = True, step
+ codes = issue_recovery_codes(db, user)
+ db.commit()
+ record_audit_log(db, user_id=user.id, level="INFO", message="Two-factor was turned on", source="auth")
+ # A fresh session ID: this is the moment an enrollment session becomes a full one, and other sessions end.
+ new_session_id, new_public_id = create_session(redis_client, user, stage=STAGE_FULL, ip=_client_ip(request), user_agent=request.headers.get("user-agent"))
+ delete_session(redis_client, session_id)
+ revoke_other_sessions(redis_client, user.id, new_public_id)
+ _set_session_cookie(response, new_session_id)
+ return {"recovery_codes": codes, "setup_required": False}
+
+
+def _reauthenticate(db, user: User, password: str, code: str) -> None:
+ """Password plus a second-factor code, for changes to the two-factor setup. One generic error for either being wrong."""
+ wrong = HTTPException(status_code=401, detail="The password or the code is not correct.")
+ if not verify_password(user, password):
+ enforce_limit(redis_client, scope="2fa-user", subject=user.id, limit=TWO_FACTOR_ATTEMPTS, window_seconds=TWO_FACTOR_WINDOW_SECONDS)
+ record_audit_log(db, user_id=user.id, level="WARNING", message="A wrong password was entered while changing two-factor", source="auth")
+ raise wrong
+ try:
+ _second_factor_or_error(db, user, code)
+ except HTTPException as exc:
+ if exc.status_code == 401:
+ raise wrong from exc
+ raise
+
+
[email protected]("/auth/2fa/disable")
+def two_factor_disable(payload: ReauthRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ if not user.totp_enabled:
+ raise HTTPException(status_code=409, detail="Two-factor is not turned on.")
+ if user.role == "admin" and two_factor_enforced(db):
+ raise HTTPException(status_code=403, detail="Two-factor is required for administrators on this server.")
+ _reauthenticate(db, user, payload.password, payload.code)
+ user.totp_enabled, user.totp_secret_enc, user.totp_last_step = False, None, None
+ db.query(RecoveryCode).filter(RecoveryCode.user_id == user.id).delete(synchronize_session=False)
+ db.commit()
+ revoked = revoke_other_sessions(redis_client, user.id, session["public_id"])
+ record_audit_log(db, user_id=user.id, level="WARNING", message=f"Two-factor was turned off ({revoked} other sessions signed out)", source="auth")
+ return {"status": "ok"}
+
+
[email protected]("/auth/2fa/recovery-codes")
+def two_factor_new_recovery_codes(payload: ReauthRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ _session, user = _account_session(session_id, db)
+ if not user.totp_enabled:
+ raise HTTPException(status_code=409, detail="Two-factor is not turned on.")
+ _reauthenticate(db, user, payload.password, payload.code)
+ codes = issue_recovery_codes(db, user)
+ db.commit()
+ record_audit_log(db, user_id=user.id, level="INFO", message="Two-factor recovery codes were regenerated", source="auth")
+ return {"recovery_codes": codes}
+
+
[email protected]("/auth/password")
+def change_password(payload: PasswordChangeRequest, request: Request, response: Response, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ enforce_limit(redis_client, scope="pw-change", subject=user.id, limit=5, window_seconds=600)
+ if not verify_password(user, payload.current_password):
+ record_audit_log(db, user_id=user.id, level="WARNING", message="A wrong current password was entered while changing the password", source="auth")
+ raise HTTPException(status_code=400, detail="The current password is not correct.")
+ try:
+ validate_password(payload.new_password)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if payload.new_password == payload.current_password:
+ raise HTTPException(status_code=400, detail="The new password must be different from the current one.")
+ user.password_hash, user.password_changed_at = hash_password(payload.new_password), datetime.now(timezone.utc)
+ db.commit()
+ # A fresh session ID for this browser, and every other session ends: whoever had the old password is out.
+ new_session_id, new_public_id = create_session(redis_client, user, stage=STAGE_FULL, ip=_client_ip(request), user_agent=request.headers.get("user-agent"))
+ delete_session(redis_client, session_id)
+ revoked = revoke_other_sessions(redis_client, user.id, new_public_id)
+ _set_session_cookie(response, new_session_id)
+ record_audit_log(db, user_id=user.id, level="INFO", message=f"Password was changed ({revoked} other sessions signed out)", source="auth")
+ return {"status": "ok", "other_sessions_signed_out": revoked}
+
+
[email protected]("/auth/sessions")
+def auth_sessions(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ return {"sessions": list_user_sessions(redis_client, user.id, session["public_id"])}
+
+
[email protected]("/auth/sessions/revoke-others")
+def auth_revoke_other_sessions(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ revoked = revoke_other_sessions(redis_client, user.id, session["public_id"])
+ record_audit_log(db, user_id=user.id, level="INFO", message=f"Signed out {revoked} other sessions", source="auth")
+ return {"signed_out": revoked}
+
+
[email protected]("/auth/sessions/{public_id}")
+def auth_revoke_session(public_id: str, response: Response, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):
+ session, user = _account_session(session_id, db)
+ if not revoke_user_session(redis_client, user.id, public_id):
+ raise HTTPException(status_code=404, detail="Session not found.")
+ if public_id == session["public_id"]:
+ response.delete_cookie(key=SESSION_COOKIE_NAME, path="/")
+ return {"status": "ok"}
def _current_user(session_id, db):
+ session = get_session(redis_client, session_id)
+ if session and session["stage"] != STAGE_FULL:
+ raise HTTPException(status_code=403, detail="Finish setting up two-factor first.")
user = get_user_from_session(redis_client, session_id)
if not user:
raise HTTPException(status_code=401, detail="Session is invalid or expired.")
@@ -428,6 +659,9 @@ MAX_METRICS_RETENTION_DAYS = 3650
AGENT_CHAT_ENABLED_KEY = "agent_chat_enabled"
+REQUIRE_ADMIN_2FA_KEY = "require_admin_2fa"
+TWO_FACTOR_ATTEMPTS = 5
+TWO_FACTOR_WINDOW_SECONDS = 300
ALERT_THRESHOLDS_KEY = "alert_thresholds"
MOUNT_THRESHOLDS_KEY = "mount_thresholds"
@@ -448,6 +682,17 @@ def get_metrics_retention_days(db) -> int:
return DEFAULT_METRICS_RETENTION_DAYS
+def require_admin_two_factor(db) -> bool:
+ """The admin setting: on unless an admin has turned it off."""
+ setting = db.get(AppSetting, REQUIRE_ADMIN_2FA_KEY)
+ return setting is None or setting.value == "true"
+
+
+def two_factor_enforced(db) -> bool:
+ """Whether admins are actually required to use two-factor: the setting is on and enrolment is possible (a key is configured)."""
+ return require_admin_two_factor(db) and secrets_box.available()
+
+
def is_agent_chat_enabled(db) -> bool:
setting = db.get(AppSetting, AGENT_CHAT_ENABLED_KEY)
return setting is None or setting.value == "true"
@@ -473,7 +718,7 @@ def get_mount_thresholds(db) -> dict:
def _admin_settings(db) -> dict:
- return {"metrics_retention_days": get_metrics_retention_days(db), "agent_chat_enabled": is_agent_chat_enabled(db), "alert_thresholds": get_alert_thresholds(db), "mount_thresholds": get_mount_thresholds(db)}
+ return {"metrics_retention_days": get_metrics_retention_days(db), "agent_chat_enabled": is_agent_chat_enabled(db), "alert_thresholds": get_alert_thresholds(db), "mount_thresholds": get_mount_thresholds(db), "require_2fa_for_admins": require_admin_two_factor(db), "secrets_configured": secrets_box.available()}
def purge_old_metrics(db, now: datetime | None = None) -> int:
@@ -503,6 +748,9 @@ def update_admin_settings(payload: AdminSettingsRequest, session_id: Annotated[s
raise HTTPException(status_code=400, detail=f"Retention must be between {MIN_METRICS_RETENTION_DAYS} and {MAX_METRICS_RETENTION_DAYS} days.")
_set_setting(db, METRICS_RETENTION_KEY, str(days))
changes.append(f"Changed metrics retention to {days} days")
+ if payload.require_2fa_for_admins is not None and payload.require_2fa_for_admins != require_admin_two_factor(db):
+ _set_setting(db, REQUIRE_ADMIN_2FA_KEY, "true" if payload.require_2fa_for_admins else "false")
+ changes.append(f"{'Required' if payload.require_2fa_for_admins else 'Stopped requiring'} two-factor for administrators")
if payload.agent_chat_enabled is not None:
_set_setting(db, AGENT_CHAT_ENABLED_KEY, "true" if payload.agent_chat_enabled else "false")
changes.append(f"{'Enabled' if payload.agent_chat_enabled else 'Disabled'} chat with the agent")
diff --git a/src/backend/models.py b/src/backend/models.py
index 974da86..95052d7 100644
--- a/src/backend/models.py
+++ b/src/backend/models.py
@@ -18,6 +18,12 @@ class User(Base):
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
role: Mapped[str] = mapped_column(String(50), default="user", nullable=False)
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
+ # Two-factor sign-in: the TOTP secret is stored encrypted (see secrets_box); it only counts once totp_enabled is set.
+ totp_secret_enc: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ totp_enabled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
+ # The newest time step already accepted, so an intercepted code can't be replayed.
+ totp_last_step: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
+ password_changed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=lambda: datetime.now(timezone.utc),
@@ -31,6 +37,18 @@ class User(Base):
)
+class RecoveryCode(Base):
+ """A single-use two-factor recovery code, stored only as a hash."""
+
+ __tablename__ = "recovery_codes"
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True, nullable=False)
+ code_hash: Mapped[str] = mapped_column(String(64), unique=True, nullable=False)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)
+ used_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
+
+
class AppSetting(Base):
"""Admin-editable settings stored as key/value pairs."""
diff --git a/src/backend/rate_limit.py b/src/backend/rate_limit.py
index 8e96942..ce09cf4 100644
--- a/src/backend/rate_limit.py
+++ b/src/backend/rate_limit.py
@@ -49,6 +49,13 @@ def enforce_ip_limit(redis_client, *, scope: str, ip_address: str, limit: int, w
return key
+def enforce_limit(redis_client, *, scope: str, subject: str, limit: int, window_seconds: int) -> str:
+ """Count an attempt for any subject (a user ID, a token) and refuse with 429 once the limit is passed."""
+ key = _key(scope, str(subject))
+ _record_attempt(redis_client, key, limit, window_seconds)
+ return key
+
+
def reset_limits(redis_client, *keys: str) -> None:
try:
redis_client.delete(*keys)
diff --git a/src/backend/reset_2fa.py b/src/backend/reset_2fa.py
new file mode 100644
index 0000000..2e999c3
--- /dev/null
+++ b/src/backend/reset_2fa.py
@@ -0,0 +1,44 @@
+"""Turns off two-factor sign-in for one account and signs it out everywhere.
+
+For an administrator who has lost both their authenticator and their recovery codes. It needs access to
+the database and Redis (so run it inside the backend container) and prints no secrets:
+
+ docker compose exec backend python src/backend/reset_2fa.py [email protected]
+
+The account can sign in with its password afterwards and, if two-factor is required for administrators,
+is asked to set it up again.
+"""
+import os
+import sys
+
+# Dodaj roditeljski direktorij (src/) u Python path kako bi 'backend' postao dostupan paket
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
+
+import redis
+
+from backend.auth import reset_two_factor
+from backend.config import REDIS_URL
+from backend.db import SessionLocal
+from backend.models import User
+
+
+def main(argv):
+ if len(argv) != 2 or not argv[1].strip():
+ print("Usage: python src/backend/reset_2fa.py <email>")
+ return 2
+ email = argv[1].strip().lower()
+ db = SessionLocal()
+ try:
+ user = db.query(User).filter(User.email == email).first()
+ if not user:
+ print(f"No account with the email '{email}'.")
+ return 1
+ reset_two_factor(db, redis.Redis.from_url(REDIS_URL, decode_responses=True), user)
+ print(f"Two-factor was turned off for '{email}' and the account was signed out everywhere.")
+ return 0
+ finally:
+ db.close()
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))
diff --git a/src/backend/secrets_box.py b/src/backend/secrets_box.py
new file mode 100644
index 0000000..c9534e1
--- /dev/null
+++ b/src/backend/secrets_box.py
@@ -0,0 +1,57 @@
+"""Encryption at rest for secrets the app must be able to read back (TOTP secrets, later notification tokens).
+
+The key comes from the SECRETS_KEY environment variable, never from the database, so a stolen database
+or backup does not reveal the secrets. Several comma-separated keys are accepted for rotation: the first
+one encrypts, all of them decrypt. If no valid key is configured nothing is ever stored in plain text:
+callers get SecretsUnavailable and must refuse the feature.
+
+Generate a key with: python -m src.backend.secrets_box
+"""
+from __future__ import annotations
+
+import os
+
+from cryptography.fernet import Fernet, InvalidToken, MultiFernet
+
+
+class SecretsUnavailable(RuntimeError):
+ """No usable key is configured, or a stored value can't be decrypted with the configured keys."""
+
+
+def _fernet() -> MultiFernet:
+ keys = [key.strip() for key in os.getenv("SECRETS_KEY", "").split(",") if key.strip()]
+ if not keys:
+ raise SecretsUnavailable("SECRETS_KEY is not configured.")
+ try:
+ return MultiFernet([Fernet(key) for key in keys])
+ except (ValueError, TypeError) as exc:
+ raise SecretsUnavailable("SECRETS_KEY is not a valid key.") from exc
+
+
+def available() -> bool:
+ """True if a valid key is configured."""
+ try:
+ _fernet()
+ except SecretsUnavailable:
+ return False
+ return True
+
+
+def encrypt(plaintext: str) -> str:
+ return _fernet().encrypt(plaintext.encode("utf-8")).decode("ascii")
+
+
+def decrypt(token: str) -> str:
+ try:
+ return _fernet().decrypt(token.encode("ascii")).decode("utf-8")
+ except (InvalidToken, UnicodeError, ValueError) as exc:
+ # A wrong key and a tampered value look the same, and neither reveals anything.
+ raise SecretsUnavailable("The stored secret can't be decrypted with the configured SECRETS_KEY.") from exc
+
+
+def generate_key() -> str:
+ return Fernet.generate_key().decode("ascii")
+
+
+if __name__ == "__main__":
+ print(generate_key())
diff --git a/src/backend/totp.py b/src/backend/totp.py
new file mode 100644
index 0000000..3bb0e04
--- /dev/null
+++ b/src/backend/totp.py
@@ -0,0 +1,96 @@
+"""Time-based one-time passwords (RFC 6238) and recovery codes, using only the standard library."""
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import secrets
+import struct
+import time
+from urllib.parse import quote
+
+PERIOD_SECONDS = 30
+DIGITS = 6
+# Codes from the previous and next period are accepted to tolerate a little clock drift.
+WINDOW_STEPS = 1
+RECOVERY_CODE_COUNT = 10
+_RECOVERY_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # no 0/O/1/I
+RECOVERY_CODE_LENGTH = 16 # 32 symbols ** 16 = 80 bits
+
+
+def _now() -> float:
+ return time.time()
+
+
+def new_secret() -> str:
+ """A random 160-bit secret in the base32 form authenticator apps expect."""
+ return base64.b32encode(secrets.token_bytes(20)).decode("ascii").rstrip("=")
+
+
+def _code_for_step(secret: str, step: int) -> str:
+ key = base64.b32decode(secret + "=" * (-len(secret) % 8), casefold=True)
+ digest = hmac.new(key, struct.pack(">Q", step), hashlib.sha1).digest()
+ offset = digest[-1] & 0x0F
+ number = (struct.unpack(">I", digest[offset:offset + 4])[0] & 0x7FFFFFFF) % 10**DIGITS
+ return f"{number:0{DIGITS}d}"
+
+
+def code_at(secret: str, timestamp: float) -> str:
+ return _code_for_step(secret, int(timestamp // PERIOD_SECONDS))
+
+
+def normalize_code(code) -> str | None:
+ """The six digits of a code typed with optional spaces or a hyphen, or None if it isn't one."""
+ if not isinstance(code, str):
+ return None
+ cleaned = code.replace(" ", "").replace("-", "")
+ return cleaned if len(cleaned) == DIGITS and cleaned.isascii() and cleaned.isdigit() else None
+
+
+def verify(secret: str, code, last_step: int | None = None, now: float | None = None) -> int | None:
+ """The time step the code belongs to if it is valid and newer than ``last_step``, else None.
+
+ Requiring a step newer than the last accepted one stops an intercepted code being used twice.
+ All steps in the window are always compared, in constant time.
+ """
+ cleaned = normalize_code(code)
+ if cleaned is None:
+ return None
+ current = int((_now() if now is None else now) // PERIOD_SECONDS)
+ matched: int | None = None
+ for step in range(current - WINDOW_STEPS, current + WINDOW_STEPS + 1):
+ if hmac.compare_digest(_code_for_step(secret, step), cleaned):
+ matched = step
+ if matched is None or (last_step is not None and matched <= last_step):
+ return None
+ return matched
+
+
+def otpauth_uri(secret: str, account: str, issuer: str = "Vexion") -> str:
+ label = quote(f"{issuer}:{account}", safe="")
+ return f"otpauth://totp/{label}?secret={secret}&issuer={quote(issuer, safe='')}&algorithm=SHA1&digits={DIGITS}&period={PERIOD_SECONDS}"
+
+
+def generate_recovery_codes(count: int = RECOVERY_CODE_COUNT) -> list[str]:
+ """Single-use codes formatted XXXX-XXXX-XXXX-XXXX."""
+ codes = []
+ for _ in range(count):
+ raw = "".join(secrets.choice(_RECOVERY_ALPHABET) for _ in range(RECOVERY_CODE_LENGTH))
+ codes.append("-".join(raw[i:i + 4] for i in range(0, RECOVERY_CODE_LENGTH, 4)))
+ return codes
+
+
+def normalize_recovery_code(code) -> str | None:
+ """The 16 symbols of a recovery code typed with any case, spaces or hyphens, or None if it isn't one."""
+ if not isinstance(code, str):
+ return None
+ cleaned = code.replace(" ", "").replace("-", "").upper()
+ return cleaned if len(cleaned) == RECOVERY_CODE_LENGTH and all(char in _RECOVERY_ALPHABET for char in cleaned) else None
+
+
+def hash_recovery_code(code: str) -> str:
+ """Recovery codes carry 80 bits of randomness, so a plain SHA-256 is enough to protect them at rest."""
+ normalized = normalize_recovery_code(code)
+ if normalized is None:
+ raise ValueError("Not a recovery code.")
+ return hashlib.sha256(normalized.encode("ascii")).hexdigest()
diff --git a/src/frontend/src/App.jsx b/src/frontend/src/App.jsx
index bd33e41..f929159 100644
--- a/src/frontend/src/App.jsx
+++ b/src/frontend/src/App.jsx
@@ -47,6 +47,7 @@ function parseAgentMessage(text) {
const navigation = [
{ label: 'Dashboard', to: '/', icon: '▣' },
{ label: 'Agent', to: '/agent', icon: '◷' },
+ { label: 'Account', to: '/account', icon: '◉' },
{ label: 'Admin', to: '/admin', icon: '⚙', adminOnly: true },
]
@@ -318,8 +319,16 @@ function LoginPage({ onLogin }) {
const { enabled: registrationEnabled } = useRegistrationEnabled()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
+ const [pendingToken, setPendingToken] = useState(null)
+ const [code, setCode] = useState('')
const [error, setError] = useState('')
+ const finish = (data) => {
+ const setupRequired = Boolean(data.setup_required)
+ onLogin({ id: data.user.id, name: data.user.name, email: data.user.email, role: data.user.role, setup_required: setupRequired })
+ navigate(setupRequired ? '/account' : '/')
+ }
+
const handleSubmit = async (event) => {
event.preventDefault()
setError('')
@@ -329,19 +338,57 @@ function LoginPage({ onLogin }) {
method: 'POST',
body: JSON.stringify({ email, password }),
})
-
- onLogin({
- id: data.user.id,
- name: data.user.name,
- email: data.user.email,
- role: data.user.role,
- })
- navigate('/')
+ if (data.status === 'two_factor_required') {
+ setPassword('')
+ setPendingToken(data.pending_token)
+ return
+ }
+ finish(data)
} catch (requestError) {
setError(requestError.message || 'Invalid email or password.')
}
}
+ const handleCode = async (event) => {
+ event.preventDefault()
+ setError('')
+ try {
+ finish(await apiRequest('/auth/login/2fa', { method: 'POST', body: JSON.stringify({ pending_token: pendingToken, code: code.trim() }) }))
+ } catch (requestError) {
+ setError(requestError.message || 'Invalid code.')
+ // An expired or used-up sign-in can't be retried; start again from the password.
+ if (requestError.status === 401 && /sign in again|expired/i.test(requestError.message || '')) { setPendingToken(null); setCode('') }
+ }
+ }
+
+ if (pendingToken) {
+ return (
+ <AuthCard title="Two-factor" subtitle="Second step">
+ <form onSubmit={handleCode} className="space-y-4">
+ <p className="text-sm text-[#bcbcbc]">Enter the 6-digit code from your authenticator app, or one of your recovery codes.</p>
+ <label className="block">
+ <span className="mb-2 block text-sm text-[#bcbcbc]">Code</span>
+ <input
+ type="text"
+ inputMode="text"
+ autoComplete="one-time-code"
+ autoFocus
+ maxLength={32}
+ value={code}
+ onChange={(event) => setCode(event.target.value)}
+ className="w-full rounded-2xl border border-neutral-700 bg-neutral-900/70 px-4 py-3 font-mono text-lg tracking-widest text-white outline-none transition focus:border-emerald-400"
+ placeholder="123456"
+ required
+ />
+ </label>
+ {error && <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300">{error}</div>}
+ <button type="submit" className="flex w-full items-center justify-center rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-3 font-medium text-slate-950 transition hover:brightness-110">Verify</button>
+ <button type="button" onClick={() => { setPendingToken(null); setCode(''); setError('') }} className="w-full py-2 text-sm text-[#9aa0a6] hover:text-white">Back to sign in</button>
+ </form>
+ </AuthCard>
+ )
+ }
+
return (
<AuthCard title="Login" subtitle="Secure access" footerText={registrationEnabled ? 'Need an account?' : null} footerLink="/register" footerLinkText="Register here">
<form onSubmit={handleSubmit} className="space-y-4">
@@ -427,8 +474,9 @@ function RegisterPage({ onRegister }) {
name: data.user.name,
email: data.user.email,
role: data.user.role,
+ setup_required: Boolean(data.setup_required),
})
- navigate('/')
+ navigate(data.setup_required ? '/account' : '/')
} catch (requestError) {
setError(requestError.message || 'Unable to create account right now.')
}
@@ -1653,9 +1701,45 @@ function SaveButton() {
)
}
+function TwoFactorPolicySetting() {
+ const [state, setState] = useState(null)
+ const [saving, setSaving] = useState(false)
+ const [message, setMessage] = useState(null)
+
+ useEffect(() => {
+ apiRequest('/admin/settings', { method: 'GET' })
+ .then((data) => setState({ required: data.require_2fa_for_admins, configured: data.secrets_configured }))
+ .catch((error) => setMessage({ ok: false, text: error.message || 'Could not load the setting.' }))
+ }, [])
+
+ const change = async (next) => {
+ setSaving(true)
+ setMessage(null)
+ try {
+ const data = await apiRequest('/admin/settings', { method: 'PUT', body: JSON.stringify({ require_2fa_for_admins: next }) })
+ setState({ required: data.require_2fa_for_admins, configured: data.secrets_configured })
+ setMessage({ ok: true, text: data.require_2fa_for_admins ? 'Administrators must now use two-factor. Those without it are asked to set it up at their next sign-in.' : 'Two-factor is optional for administrators.' })
+ } catch (error) {
+ setMessage({ ok: false, text: error.message || 'Could not save the setting.' })
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ return (
+ <AdminSection title="Two-factor" description="Protects sign-in with a code from an authenticator app, on top of the password.">
+ <Toggle label="Require two-factor for administrators" description="An administrator without it can only reach the two-factor setup until it is done." checked={state?.required ?? false} onChange={change} disabled={state === null || saving} />
+ {state && !state.configured && <p className="mt-3 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-xs text-amber-200">SECRETS_KEY is not set on the server, so two-factor can't be set up and this is <strong>not being enforced</strong> yet. Set it in <code>.env</code> (see the README, Secrets at rest) and restart.</p>}
+ {message && <p className={`mt-3 text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
+ </AdminSection>
+ )
+}
+
function AdminUsersTab() {
return (
<div className="space-y-5">
+ <TwoFactorPolicySetting />
+
<AdminSection title="Registration" description="Controls whether new people can create an account.">
<Toggle label="Allow registration" description="When off, only the first account can be created. Replaces ALLOW_REGISTRATION in .env." />
</AdminSection>
@@ -2160,10 +2244,221 @@ function RequireAuth({ user, children }) {
if (!user) {
return <Navigate to="/login" replace state={{ from: location.pathname }} />
}
+ // An administrator who still has to set up two-factor can only use the account page.
+ if (user.setup_required && location.pathname !== '/account') {
+ return <Navigate to="/account" replace />
+ }
return children
}
+function SecretsBox({ children }) {
+ return <div className="rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 p-4">{children}</div>
+}
+
+function PasswordSection() {
+ const [form, setForm] = useState({ current: '', next: '', repeat: '' })
+ const [message, setMessage] = useState(null)
+ const [busy, setBusy] = useState(false)
+ const set = (key) => (event) => setForm((current) => ({ ...current, [key]: event.target.value }))
+
+ const submit = async (event) => {
+ event.preventDefault()
+ setMessage(null)
+ if (form.next.length < MIN_PASSWORD_LENGTH) return setMessage({ ok: false, text: `The new password must be at least ${MIN_PASSWORD_LENGTH} characters.` })
+ if (form.next !== form.repeat) return setMessage({ ok: false, text: 'The two new passwords do not match.' })
+ setBusy(true)
+ try {
+ const data = await apiRequest('/auth/password', { method: 'POST', body: JSON.stringify({ current_password: form.current, new_password: form.next }) })
+ setForm({ current: '', next: '', repeat: '' })
+ setMessage({ ok: true, text: `Password changed. ${data.other_sessions_signed_out} other ${data.other_sessions_signed_out === 1 ? 'session was' : 'sessions were'} signed out.` })
+ } catch (error) {
+ setMessage({ ok: false, text: error.message || 'Could not change the password.' })
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+ <AdminSection title="Password" description={`At least ${MIN_PASSWORD_LENGTH} characters; a few random words make a good passphrase. Changing it signs you out everywhere else.`}>
+ <form onSubmit={submit} className="max-w-md space-y-3">
+ <input type="password" autoComplete="current-password" aria-label="Current password" placeholder="Current password" value={form.current} onChange={set('current')} className={inputClass} required />
+ <input type="password" autoComplete="new-password" aria-label="New password" placeholder={`New password (${MIN_PASSWORD_LENGTH}+ characters)`} value={form.next} onChange={set('next')} className={inputClass} required />
+ <input type="password" autoComplete="new-password" aria-label="Repeat the new password" placeholder="Repeat the new password" value={form.repeat} onChange={set('repeat')} className={inputClass} required />
+ <button type="submit" disabled={busy} className="rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-2.5 text-sm font-medium text-[#0b0b0b] disabled:opacity-50">{busy ? 'Changing…' : 'Change password'}</button>
+ {message && <p className={`text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
+ </form>
+ </AdminSection>
+ )
+}
+
+function RecoveryCodesPanel({ codes, onDone, doneLabel }) {
+ const [saved, setSaved] = useState(false)
+ const [copied, setCopied] = useState(false)
+ const copy = async () => {
+ try { await navigator.clipboard.writeText(codes.join('\n')); setCopied(true); setTimeout(() => setCopied(false), 1500) } catch { setCopied(false) }
+ }
+ return (
+ <SecretsBox>
+ <div className="text-sm font-medium text-white">Save your recovery codes</div>
+ <p className="mt-1 text-xs text-[#9aa0a6]">Each code works once if you lose your authenticator. They are shown only now; store them somewhere safe, such as a password manager.</p>
+ <ul className="mt-3 grid grid-cols-1 gap-1.5 font-mono text-sm text-[#cfcfcf] sm:grid-cols-2">{codes.map((code) => <li key={code} className="rounded-lg bg-white/5 px-3 py-1.5">{code}</li>)}</ul>
+ <div className="mt-3 flex flex-wrap items-center gap-3">
+ <button type="button" onClick={copy} className={secondaryButtonClass}>{copied ? 'Copied' : 'Copy codes'}</button>
+ <label className="inline-flex items-center gap-2 text-xs text-[#bcbcbc]"><input type="checkbox" checked={saved} onChange={(event) => setSaved(event.target.checked)} className="h-4 w-4" />I have saved these codes</label>
+ <button type="button" disabled={!saved} onClick={onDone} className="rounded-xl bg-white px-3 py-1.5 text-xs font-medium text-slate-950 disabled:opacity-40">{doneLabel}</button>
+ </div>
+ </SecretsBox>
+ )
+}
+
+function TwoFactorSection({ status, reload, onEnrolled }) {
+ const [setup, setSetup] = useState(null)
+ const [code, setCode] = useState('')
+ const [codes, setCodes] = useState(null)
+ const [form, setForm] = useState({ password: '', code: '' })
+ const [action, setAction] = useState(null)
+ const [message, setMessage] = useState(null)
+ const [busy, setBusy] = useState(false)
+
+ const run = async (work) => {
+ setBusy(true)
+ setMessage(null)
+ try { await work() } catch (error) { setMessage({ ok: false, text: error.message || 'Something went wrong.' }) } finally { setBusy(false) }
+ }
+ const start = () => run(async () => setSetup(await apiRequest('/auth/2fa/setup', { method: 'POST' })))
+ const enable = (event) => { event.preventDefault(); run(async () => {
+ const data = await apiRequest('/auth/2fa/enable', { method: 'POST', body: JSON.stringify({ code: code.trim() }) })
+ setCodes(data.recovery_codes); setSetup(null); setCode('')
+ await reload()
+ }) }
+ const reauth = (path, onData) => (event) => { event.preventDefault(); run(async () => {
+ const data = await apiRequest(path, { method: 'POST', body: JSON.stringify({ password: form.password, code: form.code.trim() }) })
+ setForm({ password: '', code: '' }); setAction(null); onData(data)
+ await reload()
+ }) }
+ const secretText = setup ? setup.secret.match(/.{1,4}/g).join(' ') : ''
+
+ return (
+ <AdminSection title="Two-factor sign-in" description="A 6-digit code from an authenticator app (such as Aegis, Authy or Google Authenticator) is asked for after your password.">
+ {!status.available && <p className="rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">Two-factor can't be set up because the server has no <code>SECRETS_KEY</code>. An administrator needs to set one in <code>.env</code> (see the README, Secrets at rest).</p>}
+
+ {status.available && codes && <RecoveryCodesPanel codes={codes} doneLabel={status.setup_required || onEnrolled ? 'Continue' : 'Done'} onDone={() => { setCodes(null); if (onEnrolled) onEnrolled() }} />}
+
+ {status.available && !codes && !status.enabled && (
+ <div className="space-y-3">
+ {status.required && <p className="text-sm text-amber-200">Two-factor is required for administrators on this server.</p>}
+ {!setup && <button type="button" onClick={start} disabled={busy} className="rounded-2xl bg-linear-to-r from-white to-[#cfcfcf] px-4 py-2.5 text-sm font-medium text-[#0b0b0b] disabled:opacity-50">Set up two-factor</button>}
+ {setup && (
+ <SecretsBox>
+ <ol className="list-decimal space-y-3 pl-5 text-sm text-[#bcbcbc]">
+ <li>In your authenticator app, add an account and enter this key (time-based, 6 digits):
+ <div className="mt-2 break-all rounded-lg bg-white/5 px-3 py-2 font-mono text-base tracking-wider text-white select-all">{secretText}</div>
+ <a href={setup.otpauth_uri} className="mt-1 inline-block text-xs text-emerald-300 underline">or open it in an authenticator app on this device</a>
+ </li>
+ <li>Enter the code the app shows now to confirm:
+ <form onSubmit={enable} className="mt-2 flex flex-wrap items-center gap-2">
+ <input type="text" inputMode="numeric" autoComplete="one-time-code" maxLength={8} aria-label="Code from the authenticator app" placeholder="123456" value={code} onChange={(event) => setCode(event.target.value)} className={`${inputClass} w-40 font-mono tracking-widest`} required />
+ <button type="submit" disabled={busy} className="rounded-xl bg-white px-4 py-2 text-sm font-medium text-slate-950 disabled:opacity-50">Turn on</button>
+ </form>
+ </li>
+ </ol>
+ </SecretsBox>
+ )}
+ </div>
+ )}
+
+ {status.available && !codes && status.enabled && (
+ <div className="space-y-3">
+ <p className="text-sm text-emerald-300">Two-factor is on. <span className="text-[#9aa0a6]">{status.recovery_codes_left} recovery {status.recovery_codes_left === 1 ? 'code' : 'codes'} left.</span></p>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" onClick={() => setAction(action === 'codes' ? null : 'codes')} className={secondaryButtonClass}>New recovery codes</button>
+ {!status.required && <button type="button" onClick={() => setAction(action === 'off' ? null : 'off')} className="min-h-10 sm:min-h-0 rounded-xl border border-red-400/30 bg-red-500/5 px-3 py-1.5 text-xs text-red-300 hover:bg-red-500/10">Turn off</button>}
+ </div>
+ {status.required && <p className="text-xs text-[#7f8589]">It can't be turned off while it is required for administrators.</p>}
+ {action && (
+ <form onSubmit={action === 'off' ? reauth('/auth/2fa/disable', () => setMessage({ ok: true, text: 'Two-factor is off. Your other sessions were signed out.' })) : reauth('/auth/2fa/recovery-codes', (data) => setCodes(data.recovery_codes))} className="max-w-md space-y-2">
+ <p className="text-xs text-[#9aa0a6]">Confirm with your password and a current code (or a recovery code).</p>
+ <input type="password" autoComplete="current-password" aria-label="Password" placeholder="Password" value={form.password} onChange={(event) => setForm((current) => ({ ...current, password: event.target.value }))} className={inputClass} required />
+ <input type="text" autoComplete="one-time-code" aria-label="Code" placeholder="Code" maxLength={32} value={form.code} onChange={(event) => setForm((current) => ({ ...current, code: event.target.value }))} className={`${inputClass} font-mono`} required />
+ <button type="submit" disabled={busy} className="rounded-xl bg-white px-4 py-2 text-sm font-medium text-slate-950 disabled:opacity-50">{action === 'off' ? 'Turn off two-factor' : 'Generate new codes'}</button>
+ </form>
+ )}
+ </div>
+ )}
+ {message && <p className={`mt-3 text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
+ </AdminSection>
+ )
+}
+
+function SessionsSection() {
+ const [sessions, setSessions] = useState(null)
+ const [message, setMessage] = useState(null)
+ const load = () => apiRequest('/auth/sessions', { method: 'GET' }).then((data) => setSessions(data.sessions)).catch((error) => setMessage({ ok: false, text: error.message || 'Could not load the sessions.' }))
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useEffect(() => { load() }, [])
+
+ const end = async (id) => {
+ setMessage(null)
+ try { await apiRequest(`/auth/sessions/${id}`, { method: 'DELETE' }); await load() } catch (error) { setMessage({ ok: false, text: error.message || 'Could not sign that session out.' }) }
+ }
+ const endOthers = async () => {
+ setMessage(null)
+ try {
+ const data = await apiRequest('/auth/sessions/revoke-others', { method: 'POST' })
+ setMessage({ ok: true, text: `Signed out ${data.signed_out} other ${data.signed_out === 1 ? 'session' : 'sessions'}.` })
+ await load()
+ } catch (error) { setMessage({ ok: false, text: error.message || 'Could not sign the other sessions out.' }) }
+ }
+
+ return (
+ <AdminSection title="Where you're signed in" description="Sign out any session you don't recognise." action={sessions?.length > 1 ? <button type="button" onClick={endOthers} className={secondaryButtonClass}>Sign out all others</button> : null}>
+ {sessions === null ? <p className="text-sm text-[#9aa0a6]">Loading…</p> : (
+ <ul className="space-y-2">{sessions.map((session) => (
+ <li key={session.id} className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-[#1f2326] bg-[#0d1013]/60 px-4 py-3 text-sm">
+ <div className="min-w-0">
+ <div className="truncate text-white">{session.user_agent || 'Unknown browser'}{session.current && <span className="ml-2 rounded-full bg-emerald-400/15 px-2 py-0.5 text-[10px] font-semibold tracking-wider text-emerald-300">THIS SESSION</span>}</div>
+ <div className="text-xs text-[#9aa0a6]">{session.ip || 'unknown address'} · signed in {session.created_at ? formatDateTime(session.created_at) : 'earlier'}</div>
+ </div>
+ {!session.current && <button type="button" onClick={() => end(session.id)} className={secondaryButtonClass}>Sign out</button>}
+ </li>
+ ))}</ul>
+ )}
+ <p className="mt-3 text-xs text-[#7f8589]">Sessions that started before this feature was added don't appear here and expire on their own within a day.</p>
+ {message && <p className={`mt-3 text-xs ${message.ok ? 'text-emerald-300' : 'text-amber-200'}`}>{message.text}</p>}
+ </AdminSection>
+ )
+}
+
+function AccountPage({ user, onLogout, onUserChange }) {
+ const navigate = useNavigate()
+ const [status, setStatus] = useState(null)
+ const [error, setError] = useState('')
+ // Remember that this visit began as a required setup, so Continue leads on to the dashboard once it is done.
+ const wasRequired = useRef(false)
+ if (status?.setup_required) wasRequired.current = true
+ const reload = () => apiRequest('/auth/2fa/status', { method: 'GET' }).then((data) => { setStatus(data); onUserChange({ setup_required: data.setup_required, two_factor_enabled: data.enabled }) }).catch((requestError) => setError(requestError.message || 'Could not load your account.'))
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useEffect(() => { reload() }, [])
+
+ return (
+ <AppShell user={user} onLogout={onLogout}>
+ <div className="flex flex-col gap-5">
+ <header className="glass-panel rounded-[28px] p-5 md:p-6">
+ <div className="text-xs uppercase tracking-[0.22em] text-[#9aa0a6]">Your account</div>
+ <h1 className="mt-1 text-3xl font-semibold text-white">Account</h1>
+ <p className="mt-2 text-sm text-[#9aa0a6]">{user.name} · {user.email} · {user.role}</p>
+ {status?.setup_required && <div className="mt-4 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">Two-factor is required for administrators. Set it up below to continue to the dashboard.</div>}
+ {error && <div className="mt-4 rounded-xl border border-amber-400/30 bg-amber-400/5 p-3 text-sm text-amber-200">{error}</div>}
+ </header>
+ {status && <TwoFactorSection status={status} reload={reload} onEnrolled={wasRequired.current ? () => navigate('/') : null} />}
+ {status && !status.setup_required && <PasswordSection />}
+ {status && !status.setup_required && <SessionsSection />}
+ </div>
+ </AppShell>
+ )
+}
+
function App() {
const [user, setUser] = useState(() => getStoredUser())
const [users, setUsers] = useState(() => getStoredUsers())
@@ -2232,6 +2527,14 @@ function App() {
</RequireAuth>
}
/>
+ <Route
+ path="/account"
+ element={
+ <RequireAuth user={user}>
+ <AccountPage user={user} onLogout={handleLogout} onUserChange={(patch) => setUser((current) => (current ? { ...current, ...patch } : current))} />
+ </RequireAuth>
+ }
+ />
<Route path="/reports" element={<RequireAuth user={user}><Navigate to="/agent" replace /></RequireAuth>} />
<Route path="/logs" element={<RequireAuth user={user}><Navigate to="/agent" replace /></RequireAuth>} />
<Route
diff --git a/tests/fakes.py b/tests/fakes.py
new file mode 100644
index 0000000..72d10e4
--- /dev/null
+++ b/tests/fakes.py
@@ -0,0 +1,79 @@
+"""A small in-memory stand-in for the Redis commands the backend uses, shared by the tests."""
+import fnmatch
+
+
+class FakeRedis:
+ def __init__(self):
+ self.store: dict = {}
+ self.hashes: dict[str, dict] = {}
+ self.ttls: dict[str, int] = {}
+
+ # strings and counters
+ def set(self, key, value, ex=None, **kwargs):
+ self.store[key] = value
+ if ex is not None:
+ self.ttls[key] = ex
+ return True
+
+ def get(self, key):
+ return self.store.get(key)
+
+ def delete(self, *keys):
+ removed = 0
+ for key in keys:
+ removed += int(self.store.pop(key, None) is not None) + int(self.hashes.pop(key, None) is not None)
+ self.ttls.pop(key, None)
+ return removed
+
+ def incr(self, key):
+ self.store[key] = int(self.store.get(key, 0)) + 1
+ return self.store[key]
+
+ def expire(self, key, seconds):
+ self.ttls[key] = seconds
+ return True
+
+ def ttl(self, key):
+ return self.ttls.get(key, -1)
+
+ def keys(self, pattern="*"):
+ return [key for key in list(self.store) + list(self.hashes) if fnmatch.fnmatch(key, pattern)]
+
+ # hashes
+ def hset(self, key, field, value):
+ self.hashes.setdefault(key, {})[field] = value
+ return 1
+
+ def hget(self, key, field):
+ return self.hashes.get(key, {}).get(field)
+
+ def hgetall(self, key):
+ return dict(self.hashes.get(key, {}))
+
+ def hdel(self, key, *fields):
+ entry = self.hashes.get(key, {})
+ return sum(int(entry.pop(field, None) is not None) for field in fields)
+
+ # the rate limiter pipelines an increment with an expiry
+ def pipeline(self):
+ parent = self
+
+ class Pipeline:
+ def __init__(self):
+ self.calls = []
+
+ def incr(self, key):
+ self.calls.append(("incr", key))
+ return self
+
+ def expire(self, key, seconds):
+ self.calls.append(("expire", key, seconds))
+ return self
+
+ def execute(self):
+ results = []
+ for call in self.calls:
+ results.append(parent.incr(call[1]) if call[0] == "incr" else parent.expire(call[1], call[2]))
+ return results
+
+ return Pipeline()
diff --git a/tests/test_account_security.py b/tests/test_account_security.py
new file mode 100644
index 0000000..9922b3f
--- /dev/null
+++ b/tests/test_account_security.py
@@ -0,0 +1,790 @@
+import base64
+import os
+from types import SimpleNamespace
+
+os.environ.setdefault("DATABASE_URL", "sqlite://")
+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")
+
+import bcrypt
+import pytest
+from cryptography.fernet import Fernet
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.pool import StaticPool
+from starlette.testclient import TestClient
+
+from src.backend import auth, main, secrets_box, totp
+from src.backend.models import AppSetting, AuditLog, Base, RecoveryCode, User
+from tests.fakes import FakeRedis
+
+PASSWORD = "correct-horse-battery-staple"
+NEW_PASSWORD = "another-long-passphrase-here"
+CLOCK = 1_800_000_000
+COOKIE = "homie_session"
+
+
+# --- TOTP (RFC 6238) --------------------------------------------------------------------------------
+
+RFC_SECRET = base64.b32encode(b"12345678901234567890").decode().rstrip("=")
+
+
[email protected]("timestamp, expected", [(59, "287082"), (1111111109, "081804"), (1111111111, "050471"), (1234567890, "005924"), (2000000000, "279037"), (20000000000, "353130")])
+def test_codes_match_the_rfc_6238_reference_vectors(timestamp, expected):
+ assert totp.code_at(RFC_SECRET, timestamp) == expected
+
+
+def test_a_code_is_accepted_in_its_own_period_and_one_either_side_but_not_further():
+ now = 1_800_000_015
+ for offset, accepted in ((-90, False), (-60, False), (-30, True), (0, True), (30, True), (60, False), (90, False)):
+ assert (totp.verify(RFC_SECRET, totp.code_at(RFC_SECRET, now + offset), now=now) is not None) is accepted, offset
+
+
+def test_a_code_cannot_be_used_twice_or_after_a_newer_one():
+ now = 1_800_000_015
+ step = totp.verify(RFC_SECRET, totp.code_at(RFC_SECRET, now), now=now)
+
+ assert totp.verify(RFC_SECRET, totp.code_at(RFC_SECRET, now), last_step=step, now=now) is None
+ assert totp.verify(RFC_SECRET, totp.code_at(RFC_SECRET, now - 30), last_step=step, now=now) is None
+ assert totp.verify(RFC_SECRET, totp.code_at(RFC_SECRET, now + 30), last_step=step, now=now) == step + 1
+
+
[email protected]("bad", ["", "12345", "1234567", "abcdef", "12 34 5", "١٢٣٤٥٦", "123456\x00", None, 123456, ["123456"], {"c": 1}, "123456"])
+def test_malformed_codes_are_rejected(bad):
+ assert totp.verify(RFC_SECRET, bad, now=1_800_000_015) is None
+
+
+def test_spaces_and_a_hyphen_in_a_typed_code_are_ignored():
+ code = totp.code_at(RFC_SECRET, 1_800_000_015)
+ assert totp.verify(RFC_SECRET, f"{code[:3]} {code[3:]}", now=1_800_000_015) is not None
+ assert totp.verify(RFC_SECRET, f"{code[:3]}-{code[3:]}", now=1_800_000_015) is not None
+
+
+def test_new_secrets_are_random_and_authenticator_friendly():
+ first, second = totp.new_secret(), totp.new_secret()
+ assert first != second and len(first) == 32 and set(first) <= set("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567")
+ assert totp.code_at(first, 1_800_000_000).isdigit()
+
+
+def test_the_otpauth_link_names_the_account_and_issuer_safely():
+ uri = totp.otpauth_uri("ABCDEFGH", "[email protected]&x=1")
+ assert uri.startswith("otpauth://totp/Vexion%3Aa%2Bb%40example.com%26x%3D1?secret=ABCDEFGH&issuer=Vexion") and "&x=1&" not in uri
+
+
+def test_recovery_codes_are_random_formatted_and_normalised():
+ codes = totp.generate_recovery_codes()
+ assert len(codes) == len(set(codes)) == 10 and all(len(code) == 19 and code.count("-") == 3 for code in codes)
+ assert totp.normalize_recovery_code(codes[0].lower().replace("-", " ")) == codes[0].replace("-", "")
+ assert totp.hash_recovery_code(codes[0]) == totp.hash_recovery_code(codes[0].lower()) != totp.hash_recovery_code(codes[1])
+
+
[email protected]("bad", ["", "short", "A" * 17, "0O1I-0O1I-0O1I-0O1I", None, 5, "ABCD-EFGH-JKLM-NPQ!"])
+def test_things_that_are_not_recovery_codes_are_refused(bad):
+ assert totp.normalize_recovery_code(bad) is None
+
+
+# --- encrypted secrets ------------------------------------------------------------------------------
+
+def test_secrets_are_encrypted_and_round_trip(monkeypatch):
+ monkeypatch.setenv("SECRETS_KEY", secrets_box.generate_key())
+ token = secrets_box.encrypt("JBSWY3DPEHPK3PXP")
+ assert "JBSWY3DPEHPK3PXP" not in token and secrets_box.decrypt(token) == "JBSWY3DPEHPK3PXP"
+ assert secrets_box.encrypt("JBSWY3DPEHPK3PXP") != token # fresh randomness each time
+
+
+def test_without_a_key_nothing_can_be_stored(monkeypatch):
+ monkeypatch.delenv("SECRETS_KEY", raising=False)
+ assert secrets_box.available() is False
+ with pytest.raises(secrets_box.SecretsUnavailable):
+ secrets_box.encrypt("x")
+
+
[email protected]("bad_key", ["", " ", "not-a-key", "short", "x" * 44, ","])
+def test_an_invalid_key_is_refused_not_used(monkeypatch, bad_key):
+ monkeypatch.setenv("SECRETS_KEY", bad_key)
+ assert secrets_box.available() is False
+
+
+def test_a_wrong_key_or_tampered_value_cannot_be_decrypted(monkeypatch):
+ monkeypatch.setenv("SECRETS_KEY", secrets_box.generate_key())
+ token = secrets_box.encrypt("secret")
+ monkeypatch.setenv("SECRETS_KEY", secrets_box.generate_key())
+ with pytest.raises(secrets_box.SecretsUnavailable):
+ secrets_box.decrypt(token)
+ monkeypatch.setenv("SECRETS_KEY", secrets_box.generate_key())
+ tampered = secrets_box.encrypt("secret")[:-4] + "AAAA"
+ for bad in (tampered, "garbage", "", "é"):
+ with pytest.raises(secrets_box.SecretsUnavailable):
+ secrets_box.decrypt(bad)
+
+
+def test_keys_can_be_rotated_by_listing_the_new_one_first(monkeypatch):
+ old, new = secrets_box.generate_key(), secrets_box.generate_key()
+ monkeypatch.setenv("SECRETS_KEY", old)
+ token = secrets_box.encrypt("secret")
+ monkeypatch.setenv("SECRETS_KEY", f"{new},{old}")
+
+ assert secrets_box.decrypt(token) == "secret"
+ fresh = secrets_box.encrypt("secret")
+ assert Fernet(new).decrypt(fresh.encode()) == b"secret" # new values use the first key
+ monkeypatch.setenv("SECRETS_KEY", new)
+ assert secrets_box.decrypt(fresh) == "secret"
+
+
+# --- sessions ---------------------------------------------------------------------------------------
+
+def _user(user_id=1, role="admin"):
+ return User(id=user_id, name="N", email=f"u{user_id}@example.com", password_hash="x", role=role)
+
+
+def test_a_session_is_indexed_under_its_user_and_shows_only_public_ids():
+ redis = FakeRedis()
+ session_id, public_id = auth.create_session(redis, _user(), ip="203.0.113.7", user_agent="Mozilla/5.0 \x1b[31mEvil" + "x" * 500)
+
+ listed = auth.list_user_sessions(redis, 1, public_id)
+
+ assert len(listed) == 1 and listed[0]["id"] == public_id and listed[0]["current"] is True and listed[0]["ip"] == "203.0.113.7"
+ assert session_id not in repr(listed) and "\x1b" not in listed[0]["user_agent"] and len(listed[0]["user_agent"]) <= 120
+
+
+def test_session_ids_are_long_random_and_distinct():
+ redis = FakeRedis()
+ ids = {auth.create_session(redis, _user())[0] for _ in range(20)}
+ assert len(ids) == 20 and all(len(session_id) >= 43 for session_id in ids)
+
+
+def test_one_session_can_be_revoked_without_touching_the_others():
+ redis = FakeRedis()
+ first, first_public = auth.create_session(redis, _user())
+ second, second_public = auth.create_session(redis, _user())
+
+ assert auth.revoke_user_session(redis, 1, second_public) is True
+ assert auth.get_user_from_session(redis, second) is None and auth.get_user_from_session(redis, first) is not None
+ assert [item["id"] for item in auth.list_user_sessions(redis, 1, first_public)] == [first_public]
+
+
+def test_all_other_sessions_can_be_revoked_keeping_the_current_one():
+ redis = FakeRedis()
+ keep, keep_public = auth.create_session(redis, _user())
+ others = [auth.create_session(redis, _user())[0] for _ in range(3)]
+
+ assert auth.revoke_other_sessions(redis, 1, keep_public) == 3
+ assert auth.get_user_from_session(redis, keep) is not None and all(auth.get_user_from_session(redis, other) is None for other in others)
+
+
+def test_a_user_cannot_revoke_or_see_someone_elses_session():
+ redis = FakeRedis()
+ victim, victim_public = auth.create_session(redis, _user(2, "user"))
+ _mine, _ = auth.create_session(redis, _user(1))
+
+ assert auth.revoke_user_session(redis, 1, victim_public) is False
+ assert auth.get_user_from_session(redis, victim) is not None and auth.list_user_sessions(redis, 1, None)[0]["id"] != victim_public
+ # even a corrupted index entry pointing at another user's session is ignored and cleaned up
+ redis.hset(auth._user_sessions_key(1), "0123456789abcdef", victim)
+ assert all(item["id"] != victim_public for item in auth.list_user_sessions(redis, 1, None))
+ assert auth.revoke_user_session(redis, 1, "0123456789abcdef") is False and auth.get_user_from_session(redis, victim) is not None
+
+
[email protected]("bad", ["", "short", "../etc/passwd", "g" * 16, "0123456789abcdeF", "0" * 17, None, 5])
+def test_malformed_public_ids_are_never_looked_up(bad):
+ assert auth.revoke_user_session(FakeRedis(), 1, bad) is False
+
+
+def test_expired_sessions_drop_out_of_the_list():
+ redis = FakeRedis()
+ session_id, public_id = auth.create_session(redis, _user())
+ redis.delete(auth._session_key(session_id)) # what Redis does when the lifetime ends
+
+ assert auth.list_user_sessions(redis, 1, None) == [] and redis.hgetall(auth._user_sessions_key(1)) == {}
+
+
+def test_logging_out_removes_the_session_from_the_index():
+ redis = FakeRedis()
+ session_id, _ = auth.create_session(redis, _user())
+
+ assert auth.delete_session(redis, session_id) is True and auth.list_user_sessions(redis, 1, None) == []
+ assert auth.delete_session(redis, session_id) is False and auth.delete_session(redis, None) is False
+
+
+def test_limited_sessions_are_refused_unless_a_caller_opts_in():
+ redis = FakeRedis()
+ session_id, _ = auth.create_session(redis, _user(), stage=auth.STAGE_ENROLLMENT)
+
+ assert auth.get_user_from_session(redis, session_id) is None
+ assert auth.get_user_from_session(redis, session_id, allow_limited=True)["stage"] == auth.STAGE_ENROLLMENT
+
+
+def test_sessions_created_before_stages_existed_count_as_full():
+ import json
+ redis = FakeRedis()
+ redis.set(auth._session_key("legacy"), json.dumps({"user_id": 1, "email": "[email protected]", "name": "A", "role": "admin"}))
+
+ assert auth.get_user_from_session(redis, "legacy")["stage"] == auth.STAGE_FULL
+
+
+# --- the app over HTTP ------------------------------------------------------------------------------
+
[email protected](autouse=True)
+def fast_bcrypt(monkeypatch):
+ real = bcrypt.gensalt
+ monkeypatch.setattr(bcrypt, "gensalt", lambda rounds=12, prefix=b"2b": real(rounds=4, prefix=prefix))
+
+
+def app(monkeypatch):
+ monkeypatch.setenv("SECRETS_KEY", secrets_box.generate_key())
+ redis, clock = FakeRedis(), {"now": CLOCK}
+ monkeypatch.setattr(main, "redis_client", redis)
+ monkeypatch.setattr(main, "SESSION_COOKIE_SECURE", False) # the test client speaks plain HTTP, whatever .env says
+ monkeypatch.setattr(totp, "_now", lambda: clock["now"])
+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
+ Base.metadata.create_all(engine)
+ db = sessionmaker(bind=engine)()
+ password_hash = auth.hash_password(PASSWORD)
+ db.add_all([User(id=1, name="Admin", email="[email protected]", password_hash=password_hash, role="admin"),
+ User(id=2, name="Member", email="[email protected]", password_hash=password_hash, role="user")])
+ db.commit()
+ main.app.dependency_overrides[main.get_db] = lambda: db
+ yield SimpleNamespace(db=db, redis=redis, clock=clock)
+ main.app.dependency_overrides.clear()
+
+
+def _login(client, email="[email protected]", password=PASSWORD):
+ return client.post("/auth/login", json={"email": email, "password": password})
+
+
+def _signed_in(email="[email protected]"):
+ client = TestClient(main.app)
+ response = _login(client, email)
+ assert response.status_code == 200, response.text
+ return client
+
+
+def _enroll(app, client):
+ secret = client.post("/auth/2fa/setup").json()["secret"]
+ response = client.post("/auth/2fa/enable", json={"code": totp.code_at(secret, app.clock["now"])})
+ assert response.status_code == 200, response.text
+ return secret, response.json()["recovery_codes"]
+
+
+def _code(app, secret, advance=0):
+ app.clock["now"] += advance
+ return totp.code_at(secret, app.clock["now"])
+
+
+def _second_step(client, app, secret, code=None, advance=30, email="[email protected]"):
+ """Sign in with a password and return the response of the second step."""
+ first = _login(client, email).json()
+ assert first["status"] == "two_factor_required"
+ return client.post("/auth/login/2fa", json={"pending_token": first["pending_token"], "code": code or _code(app, secret, advance)})
+
+
+def _audit(app):
+ return [row.message for row in app.db.query(AuditLog).filter(AuditLog.source == "auth").order_by(AuditLog.id)]
+
+
+def test_a_member_signs_in_with_just_a_password(app):
+ client = TestClient(main.app)
+ response = _login(client, "[email protected]")
+
+ assert response.status_code == 200 and response.json()["setup_required"] is False and COOKIE in client.cookies
+ assert client.get("/monitoring/overview").status_code == 200
+
+
+def test_an_admin_without_two_factor_gets_a_limited_session_when_it_is_required(app):
+ client = TestClient(main.app)
+ response = _login(client)
+
+ assert response.json()["setup_required"] is True
+ assert client.get("/auth/me").json()["user"]["setup_required"] is True
+
+
+def test_a_limited_session_is_refused_everywhere_except_the_two_factor_setup(app):
+ client = _signed_in()
+ password_body = {"current_password": PASSWORD, "new_password": NEW_PASSWORD}
+ for method, path, body in (("get", "/monitoring/overview", None), ("get", "/admin/settings", None), ("get", "/auth/sessions", None), ("get", "/agent/config", None),
+ ("get", "/dashboard/summary", None), ("post", "/auth/password", password_body), ("delete", "/monitoring/servers/1", None),
+ ("post", "/monitoring/join-tokens", None), ("get", "/monitoring/enrollment-key", None), ("get", "/conversations", None),
+ ("get", "/logs", None), ("post", "/auth/sessions/revoke-others", None)):
+ response = client.request(method.upper(), path, json=body) if body else getattr(client, method)(path)
+ assert response.status_code in (401, 403), (path, response.status_code)
+ for path in ("/auth/me", "/auth/2fa/status"):
+ assert client.get(path).status_code == 200, path
+
+
+def test_every_route_that_needs_a_session_refuses_a_limited_one(app):
+ allowed = {"/auth/me", "/auth/2fa/status", "/auth/2fa/setup", "/auth/2fa/enable", "/auth/logout", "/health", "/auth/config", "/auth/login", "/auth/login/2fa", "/auth/register",
+ "/monitoring/collectors/register", "/monitoring/collectors/register/poll", "/monitoring/collectors/enroll", "/monitoring/metrics/ingest", "/"}
+ client = _signed_in()
+ leaked = []
+ for route in main.app.routes:
+ path = getattr(route, "path", None)
+ if not path or path in allowed or path.startswith(("/docs", "/redoc", "/openapi")):
+ continue
+ for method in sorted(set(route.methods or []) & {"GET", "DELETE", "PATCH", "PUT", "POST"}):
+ response = client.request(method, path.replace("{", "").replace("}", "").replace("server_id", "1").replace("pending_id", "1").replace("container_id", "x").replace("conversation_id", "x").replace("public_id", "0123456789abcdef"), json={})
+ if response.status_code < 300:
+ leaked.append((method, path, response.status_code))
+ assert leaked == []
+
+
+def test_when_no_key_is_configured_two_factor_is_not_enforced_and_cannot_be_set_up(app, monkeypatch):
+ monkeypatch.delenv("SECRETS_KEY", raising=False)
+ client = TestClient(main.app)
+
+ assert _login(client).json()["setup_required"] is False
+ assert client.get("/monitoring/overview").status_code == 200
+ assert client.get("/auth/2fa/status").json()["available"] is False
+ assert client.post("/auth/2fa/setup").status_code == 503
+
+
+def test_the_policy_can_be_turned_off_and_defaults_to_on(app):
+ assert main.require_admin_two_factor(app.db) is True and main.two_factor_enforced(app.db) is True
+ app.db.add(AppSetting(key=main.REQUIRE_ADMIN_2FA_KEY, value="false"))
+ app.db.commit()
+
+ assert main.require_admin_two_factor(app.db) is False and main.two_factor_enforced(app.db) is False
+ assert _login(TestClient(main.app)).json()["setup_required"] is False
+
+
+def test_the_policy_only_applies_to_administrators(app):
+ app.db.add(AppSetting(key=main.REQUIRE_ADMIN_2FA_KEY, value="true"))
+ app.db.commit()
+
+ assert _login(TestClient(main.app), "[email protected]").json()["setup_required"] is False
+
+
+def test_admins_can_change_the_policy_and_it_is_audited(app, monkeypatch):
+ monkeypatch.setattr(main, "_require_admin", lambda session_id, db: {"id": 1})
+ assert main.get_admin_settings(session_id="s", db=app.db)["require_2fa_for_admins"] is True
+
+ result = main.update_admin_settings(main.AdminSettingsRequest(require_2fa_for_admins=False), session_id="s", db=app.db)
+
+ assert result["require_2fa_for_admins"] is False and result["secrets_configured"] is True
+ assert any("Stopped requiring two-factor" in row.message for row in app.db.query(AuditLog))
+
+
+def test_enrolling_upgrades_the_session_and_rotates_its_id(app):
+ client = _signed_in()
+ limited_cookie = client.cookies.get(COOKIE)
+
+ secret, codes = _enroll(app, client)
+
+ assert client.cookies.get(COOKIE) != limited_cookie and len(codes) == 10
+ assert client.get("/monitoring/overview").status_code == 200
+ old = TestClient(main.app)
+ old.cookies.set(COOKIE, limited_cookie)
+ assert old.get("/auth/me").status_code == 401 # the limited session no longer exists
+
+
+def test_a_wrong_code_does_not_enable_two_factor(app):
+ client = _signed_in()
+ client.post("/auth/2fa/setup")
+ user_before = app.db.get(User, 1).totp_enabled
+
+ response = client.post("/auth/2fa/enable", json={"code": "000000"})
+
+ assert response.status_code == 400 and user_before is False and app.db.get(User, 1).totp_enabled is False
+ assert client.get("/monitoring/overview").status_code == 403
+
+
+def test_enabling_without_starting_setup_is_refused(app):
+ assert _signed_in().post("/auth/2fa/enable", json={"code": "123456"}).status_code == 400
+
+
+def test_the_secret_is_stored_encrypted_and_recovery_codes_only_as_hashes(app):
+ client = _signed_in()
+ secret, codes = _enroll(app, client)
+
+ user = app.db.get(User, 1)
+ assert secret not in user.totp_secret_enc and secrets_box.decrypt(user.totp_secret_enc) == secret
+ stored = {row.code_hash for row in app.db.query(RecoveryCode)}
+ assert len(stored) == 10 and not any(code.replace("-", "") in " ".join(stored) for code in codes)
+ assert stored == {totp.hash_recovery_code(code) for code in codes}
+
+
+def test_secrets_never_appear_in_api_responses(app):
+ client = _signed_in()
+ secret, _ = _enroll(app, client)
+ stored = app.db.get(User, 1).totp_secret_enc
+
+ for path in ("/auth/me", "/auth/2fa/status", "/auth/sessions", "/admin/settings"):
+ body = client.get(path).text
+ assert secret not in body and stored not in body and "totp_secret" not in body, path
+
+
+def test_signing_in_with_two_factor_needs_both_steps_and_creates_no_session_before_the_second(app):
+ secret, _ = _enroll(app, _signed_in())
+ client = TestClient(main.app)
+ first = _login(client)
+
+ assert first.json()["status"] == "two_factor_required" and COOKIE not in client.cookies and "user" not in first.json()
+ assert client.get("/auth/me").status_code == 401 and client.get("/monitoring/overview").status_code == 401
+ app.clock["now"] += 30
+ done = client.post("/auth/login/2fa", json={"pending_token": first.json()["pending_token"], "code": totp.code_at(secret, app.clock["now"])})
+ assert done.status_code == 200 and client.get("/monitoring/overview").status_code == 200
+
+
+def test_a_wrong_or_malformed_code_is_refused_with_one_generic_message(app):
+ secret, _ = _enroll(app, _signed_in())
+ client = TestClient(main.app)
+ messages = set()
+ for code in ("000000", "12345", "abcdef", "١٢٣٤٥٦", "ABCD-EFGH-JKLM-NPQR"):
+ token = _login(client).json()["pending_token"]
+ response = client.post("/auth/login/2fa", json={"pending_token": token, "code": code})
+ assert response.status_code == 401
+ messages.add(response.json()["detail"])
+
+ assert messages == {"Invalid code."} and COOKIE not in client.cookies
+
+
+def test_a_code_cannot_be_replayed(app):
+ secret, _ = _enroll(app, _signed_in())
+ app.clock["now"] += 30
+ code = totp.code_at(secret, app.clock["now"])
+
+ assert _second_step(TestClient(main.app), app, secret, code=code, advance=0).status_code == 200
+ assert _second_step(TestClient(main.app), app, secret, code=code, advance=0).status_code == 401
+ assert _second_step(TestClient(main.app), app, secret, advance=30).status_code == 200 # the next period works
+
+
+def test_the_code_from_the_enrollment_step_cannot_be_reused_to_sign_in(app):
+ client = _signed_in()
+ secret = client.post("/auth/2fa/setup").json()["secret"]
+ code = totp.code_at(secret, app.clock["now"])
+ client.post("/auth/2fa/enable", json={"code": code})
+
+ assert _second_step(TestClient(main.app), app, secret, code=code, advance=0).status_code == 401
+
+
+def test_recovery_codes_work_once_and_the_count_drops(app):
+ _secret, codes = _enroll(app, _signed_in())
+ client = TestClient(main.app)
+
+ first = client.post("/auth/login/2fa", json={"pending_token": _login(client).json()["pending_token"], "code": codes[0].lower()})
+ assert first.status_code == 200 and first.json()["recovery_codes_left"] == 9
+ again = client.post("/auth/login/2fa", json={"pending_token": _login(client).json()["pending_token"], "code": codes[0]})
+ assert again.status_code == 401
+ assert any("recovery code was used" in message for message in _audit(app))
+
+
+def test_a_pending_login_token_is_single_use_and_unknown_tokens_are_refused(app):
+ secret, _ = _enroll(app, _signed_in())
+ client = TestClient(main.app)
+ token = _login(client).json()["pending_token"]
+ app.clock["now"] += 30
+ code = totp.code_at(secret, app.clock["now"])
+
+ assert client.post("/auth/login/2fa", json={"pending_token": token, "code": code}).status_code == 200
+ app.clock["now"] += 30
+ assert client.post("/auth/login/2fa", json={"pending_token": token, "code": totp.code_at(secret, app.clock["now"])}).status_code == 401
+ for bad in ("", "x", "a" * 43, "../../x", "a" * 500):
+ assert client.post("/auth/login/2fa", json={"pending_token": bad, "code": code}).status_code in (401, 422), bad
+
+
+def test_an_expired_pending_login_cannot_be_completed(app):
+ secret, _ = _enroll(app, _signed_in())
+ client = TestClient(main.app)
+ token = _login(client).json()["pending_token"]
+ app.redis.delete(auth._pending_key(token)) # what Redis does when the five minutes are over
+
+ assert client.post("/auth/login/2fa", json={"pending_token": token, "code": _code(app, secret, 30)}).status_code == 401
+
+
+def test_a_pending_login_is_destroyed_after_five_wrong_codes(app):
+ secret, _ = _enroll(app, _signed_in())
+ client = TestClient(main.app)
+ token = _login(client).json()["pending_token"]
+
+ statuses = [client.post("/auth/login/2fa", json={"pending_token": token, "code": "000000"}).status_code for _ in range(6)]
+ right = client.post("/auth/login/2fa", json={"pending_token": token, "code": _code(app, secret, 30)})
+
+ assert statuses == [401, 401, 401, 401, 401, 401] and right.status_code == 401 and COOKIE not in client.cookies
+
+
+def test_guessing_across_many_pending_logins_locks_the_account_for_a_while(app):
+ secret, _ = _enroll(app, _signed_in())
+ client = TestClient(main.app)
+ statuses = []
+ for _ in range(7):
+ token = _login(client).json()["pending_token"]
+ statuses.append(client.post("/auth/login/2fa", json={"pending_token": token, "code": "000000"}).status_code)
+
+ assert statuses[:5] == [401] * 5 and statuses[5:] == [429, 429]
+ token = _login(client).json()["pending_token"]
+ assert client.post("/auth/login/2fa", json={"pending_token": token, "code": _code(app, secret, 30)}).status_code == 429 # even the right code, until the window ends
+
+
+def test_a_successful_second_step_resets_the_failure_count(app):
+ secret, _ = _enroll(app, _signed_in())
+ client = TestClient(main.app)
+ for _ in range(3):
+ client.post("/auth/login/2fa", json={"pending_token": _login(client).json()["pending_token"], "code": "000000"})
+ assert _second_step(client, app, secret).status_code == 200
+ for _ in range(4):
+ assert client.post("/auth/login/2fa", json={"pending_token": _login(client).json()["pending_token"], "code": "000000"}).status_code == 401
+
+
+def test_the_per_address_limit_on_code_attempts_applies_too(app):
+ client = TestClient(main.app)
+ statuses = {client.post("/auth/login/2fa", json={"pending_token": "a" * 43, "code": "000000"}).status_code for _ in range(25)}
+
+ assert 429 in statuses
+
+
+def test_unknown_emails_cost_the_same_work_as_wrong_passwords(app, monkeypatch):
+ calls = []
+ real = bcrypt.checkpw
+ monkeypatch.setattr(bcrypt, "checkpw", lambda *args: calls.append(1) or real(*args))
+ client = TestClient(main.app)
+
+ unknown = _login(client, "[email protected]", PASSWORD)
+ wrong = _login(client, "[email protected]", "wrong-password-entirely")
+
+ assert unknown.status_code == wrong.status_code == 401 and unknown.json() == wrong.json() and len(calls) == 2
+
+
[email protected]("body", [{"pending_token": "a" * 43, "code": 123456}, {"pending_token": "a" * 43, "code": None}, {"pending_token": "a" * 43, "code": ["1"]},
+ {"pending_token": "a" * 43, "code": "1" * 65}, {"pending_token": "a" * 101, "code": "123456"}, {"pending_token": 5, "code": "123456"}, {}])
+def test_hostile_second_step_bodies_are_rejected_before_any_work(app, body):
+ assert TestClient(main.app).post("/auth/login/2fa", json=body).status_code == 422
+
+
+def test_a_members_two_factor_is_optional_but_available(app):
+ client = _signed_in("[email protected]")
+ status = client.get("/auth/2fa/status").json()
+ assert status == {"enabled": False, "available": True, "required": False, "recovery_codes_left": 0, "setup_required": False}
+
+ _enroll(app, client)
+ assert client.get("/auth/2fa/status").json()["enabled"] is True and client.get("/auth/2fa/status").json()["recovery_codes_left"] == 10
+
+
+def test_setup_is_refused_while_two_factor_is_already_on(app):
+ client = _signed_in()
+ _enroll(app, client)
+
+ assert client.post("/auth/2fa/setup").status_code == 409 and client.post("/auth/2fa/enable", json={"code": "123456"}).status_code == 409
+
+
+def test_setting_up_again_before_confirming_replaces_the_pending_secret(app):
+ client = _signed_in()
+ first = client.post("/auth/2fa/setup").json()["secret"]
+ second = client.post("/auth/2fa/setup").json()["secret"]
+
+ assert first != second
+ assert client.post("/auth/2fa/enable", json={"code": totp.code_at(first, app.clock["now"])}).status_code == 400
+
+
+def test_turning_two_factor_off_needs_the_password_and_a_code_and_ends_other_sessions(app):
+ member = _signed_in("[email protected]")
+ secret, _ = _enroll(app, member)
+ other = TestClient(main.app)
+ assert _second_step(other, app, secret, email="[email protected]").status_code == 200
+
+ wrong_password = member.post("/auth/2fa/disable", json={"password": "wrong", "code": _code(app, secret, 30)})
+ wrong_code = member.post("/auth/2fa/disable", json={"password": PASSWORD, "code": "000000"})
+ assert wrong_password.status_code == wrong_code.status_code == 401 and wrong_password.json() == wrong_code.json()
+ assert app.db.get(User, 2).totp_enabled is True
+
+ done = member.post("/auth/2fa/disable", json={"password": PASSWORD, "code": _code(app, secret, 30)})
+ assert done.status_code == 200 and app.db.get(User, 2).totp_enabled is False and app.db.get(User, 2).totp_secret_enc is None
+ assert app.db.query(RecoveryCode).filter(RecoveryCode.user_id == 2).count() == 0
+ assert other.get("/auth/me").status_code == 401 and member.get("/auth/me").status_code == 200
+ assert _login(TestClient(main.app), "[email protected]").json()["user"]["email"] == "[email protected]" # single step again
+
+
+def test_an_admin_cannot_turn_two_factor_off_while_the_policy_requires_it(app):
+ client = _signed_in()
+ secret, _ = _enroll(app, client)
+
+ response = client.post("/auth/2fa/disable", json={"password": PASSWORD, "code": _code(app, secret, 30)})
+
+ assert response.status_code == 403 and app.db.get(User, 1).totp_enabled is True
+
+
+def test_a_limited_session_cannot_disable_regenerate_or_change_the_password(app):
+ client = _signed_in()
+ for path, body in (("/auth/2fa/disable", {"password": PASSWORD, "code": "123456"}), ("/auth/2fa/recovery-codes", {"password": PASSWORD, "code": "123456"}),
+ ("/auth/password", {"current_password": PASSWORD, "new_password": NEW_PASSWORD})):
+ assert client.post(path, json=body).status_code == 403, path
+
+
+def test_regenerating_recovery_codes_replaces_the_old_ones(app):
+ client = _signed_in("[email protected]")
+ secret, old_codes = _enroll(app, client)
+
+ assert client.post("/auth/2fa/recovery-codes", json={"password": "wrong", "code": _code(app, secret, 30)}).status_code == 401
+ response = client.post("/auth/2fa/recovery-codes", json={"password": PASSWORD, "code": _code(app, secret, 30)})
+ new_codes = response.json()["recovery_codes"]
+
+ assert response.status_code == 200 and len(new_codes) == 10 and not set(new_codes) & set(old_codes)
+ other = TestClient(main.app)
+ assert other.post("/auth/login/2fa", json={"pending_token": _login(other, "[email protected]").json()["pending_token"], "code": old_codes[0]}).status_code == 401
+ assert other.post("/auth/login/2fa", json={"pending_token": _login(other, "[email protected]").json()["pending_token"], "code": new_codes[0]}).status_code == 200
+
+
+def test_if_the_key_is_lost_totp_codes_stop_working_but_recovery_codes_still_do(app, monkeypatch):
+ _secret, codes = _enroll(app, _signed_in("[email protected]"))
+ monkeypatch.setenv("SECRETS_KEY", secrets_box.generate_key()) # a different key from now on
+ client = TestClient(main.app)
+
+ token = _login(client, "[email protected]").json()["pending_token"]
+ assert client.post("/auth/login/2fa", json={"pending_token": token, "code": "123456"}).status_code == 503
+ token = _login(client, "[email protected]").json()["pending_token"]
+ assert client.post("/auth/login/2fa", json={"pending_token": token, "code": codes[0]}).status_code == 200
+
+
+def test_a_wrong_code_during_sign_in_is_audited_without_the_code(app):
+ _enroll(app, _signed_in())
+ client = TestClient(main.app)
+ client.post("/auth/login/2fa", json={"pending_token": _login(client).json()["pending_token"], "code": "135790"})
+
+ messages = _audit(app)
+ assert "A wrong two-factor code was entered" in messages and not any("135790" in message for message in messages)
+
+
+def test_changing_the_password_signs_out_other_sessions_and_rotates_this_one(app):
+ client = _signed_in("[email protected]")
+ other = _signed_in("[email protected]")
+ old_cookie = client.cookies.get(COOKIE)
+
+ response = client.post("/auth/password", json={"current_password": PASSWORD, "new_password": NEW_PASSWORD})
+
+ assert response.status_code == 200 and response.json()["other_sessions_signed_out"] == 1
+ assert client.cookies.get(COOKIE) != old_cookie and client.get("/auth/me").status_code == 200
+ assert other.get("/auth/me").status_code == 401
+ stale = TestClient(main.app)
+ stale.cookies.set(COOKIE, old_cookie)
+ assert stale.get("/auth/me").status_code == 401
+ assert _login(TestClient(main.app), "[email protected]", PASSWORD).status_code == 401
+ assert _login(TestClient(main.app), "[email protected]", NEW_PASSWORD).status_code == 200
+ assert app.db.get(User, 2).password_changed_at is not None and any("Password was changed" in message for message in _audit(app))
+
+
[email protected]("current, new, status", [
+ ("wrong-current-password", NEW_PASSWORD, 400),
+ (PASSWORD, "short", 400),
+ (PASSWORD, "p" * 73, 400),
+ (PASSWORD, PASSWORD, 400),
+ (PASSWORD, "", 400),
+])
+def test_bad_password_changes_are_refused_and_change_nothing(app, current, new, status):
+ client = _signed_in("[email protected]")
+ before = app.db.get(User, 2).password_hash
+
+ response = client.post("/auth/password", json={"current_password": current, "new_password": new})
+
+ assert response.status_code == status and app.db.get(User, 2).password_hash == before
+ assert _login(TestClient(main.app), "[email protected]", PASSWORD).status_code == 200
+
+
+def test_password_change_attempts_are_rate_limited(app):
+ client = _signed_in("[email protected]")
+ statuses = [client.post("/auth/password", json={"current_password": "wrong-current-password", "new_password": NEW_PASSWORD}).status_code for _ in range(7)]
+
+ assert statuses[:5] == [400] * 5 and statuses[5:] == [429, 429]
+ assert client.post("/auth/password", json={"current_password": PASSWORD, "new_password": NEW_PASSWORD}).status_code == 429
+
+
+def test_the_account_page_lists_sessions_and_can_end_them(app):
+ mine, other = _signed_in("[email protected]"), _signed_in("[email protected]")
+ listed = mine.get("/auth/sessions").json()["sessions"]
+ assert len(listed) == 2 and sum(item["current"] for item in listed) == 1
+ assert COOKIE not in repr(listed) and mine.cookies.get(COOKIE) not in repr(listed) and other.cookies.get(COOKIE) not in repr(listed)
+
+ theirs = next(item["id"] for item in listed if not item["current"])
+ assert mine.delete(f"/auth/sessions/{theirs}").status_code == 200 and other.get("/auth/me").status_code == 401
+ assert mine.delete(f"/auth/sessions/{theirs}").status_code == 404
+
+
+def test_ending_the_current_session_through_the_list_clears_the_cookie(app):
+ client = _signed_in("[email protected]")
+ current = next(item["id"] for item in client.get("/auth/sessions").json()["sessions"] if item["current"])
+
+ assert client.delete(f"/auth/sessions/{current}").status_code == 200 and client.get("/auth/me").status_code == 401
+
+
+def test_sign_out_everywhere_else_keeps_only_this_session(app):
+ mine = _signed_in("[email protected]")
+ others = [_signed_in("[email protected]") for _ in range(3)]
+
+ assert mine.post("/auth/sessions/revoke-others").json() == {"signed_out": 3}
+ assert mine.get("/auth/me").status_code == 200 and all(other.get("/auth/me").status_code == 401 for other in others)
+
+
+def test_one_user_cannot_end_another_users_session_by_guessing_its_id(app):
+ admin_client = _signed_in("[email protected]")
+ member = _signed_in("[email protected]")
+ admin_public = next(item["id"] for item in admin_client.get("/auth/sessions").json()["sessions"] if False) if False else None
+ member_public = next(item["id"] for item in member.get("/auth/sessions").json()["sessions"])
+
+ # an admin in a full session (after enrolling) still can't use a member's id
+ secret, _ = _enroll(app, admin_client)
+ assert admin_client.delete(f"/auth/sessions/{member_public}").status_code == 404 and member.get("/auth/me").status_code == 200
+
+
[email protected]("path", ["/auth/sessions/short", "/auth/sessions/..%2F..%2Fetc", "/auth/sessions/" + "g" * 16, "/auth/sessions/" + "0" * 40])
+def test_malformed_session_ids_in_the_url_are_not_found(app, path):
+ assert _signed_in("[email protected]").delete(path).status_code in (404, 405, 422)
+
+
+def test_logout_ends_the_session_everywhere_and_the_cookie_is_cleared(app):
+ client = _signed_in("[email protected]")
+ cookie = client.cookies.get(COOKIE)
+
+ assert client.post("/auth/logout").status_code == 200 and client.get("/auth/me").status_code == 401
+ assert app.redis.hgetall(auth._user_sessions_key(2)) == {} and app.redis.get(auth._session_key(cookie)) is None
+
+
+def test_logging_out_a_session_that_already_expired_is_still_fine(app):
+ client = TestClient(main.app)
+ client.cookies.set(COOKIE, "an-expired-session-id")
+ assert client.post("/auth/logout").status_code == 200
+
+
+def test_the_first_account_on_a_fresh_install_must_enrol_when_the_policy_is_on(app):
+ app.db.query(User).delete()
+ app.db.commit()
+ token = main.ensure_bootstrap_token(app.db)
+ client = TestClient(main.app)
+
+ response = client.post("/auth/register", json={"name": "Owner", "email": "[email protected]", "password": PASSWORD, "bootstrap_token": token})
+
+ assert response.status_code == 200 and response.json()["setup_required"] is True
+ assert client.get("/monitoring/overview").status_code == 403 and client.get("/auth/me").json()["user"]["role"] == "admin"
+
+
+def test_cross_site_requests_to_the_new_endpoints_are_refused(app):
+ client = _signed_in("[email protected]")
+ for path, body in (("/auth/password", {"current_password": PASSWORD, "new_password": NEW_PASSWORD}), ("/auth/2fa/setup", {}), ("/auth/sessions/revoke-others", {})):
+ assert client.post(path, json=body, headers={"Origin": "https://evil.example"}).status_code == 403, path
+ assert app.db.get(User, 2).password_changed_at is None
+
+
+def test_resetting_two_factor_from_the_command_line_helper(app):
+ member = _signed_in("[email protected]")
+ secret, _ = _enroll(app, member)
+ other = TestClient(main.app)
+ assert _second_step(other, app, secret, email="[email protected]").status_code == 200
+
+ auth.reset_two_factor(app.db, app.redis, app.db.get(User, 2))
+
+ user = app.db.get(User, 2)
+ assert (user.totp_enabled, user.totp_secret_enc, user.totp_last_step) == (False, None, None)
+ assert app.db.query(RecoveryCode).filter(RecoveryCode.user_id == 2).count() == 0
+ assert member.get("/auth/me").status_code == 401 and other.get("/auth/me").status_code == 401
+ assert "Two-factor was reset from the command line" in _audit(app)
+ assert "user" in _login(TestClient(main.app), "[email protected]").json()
+
+
+def test_a_reset_admin_is_asked_to_enrol_again_when_it_is_required(app):
+ client = _signed_in()
+ _enroll(app, client)
+ auth.reset_two_factor(app.db, app.redis, app.db.get(User, 1))
+
+ assert _login(TestClient(main.app)).json()["setup_required"] is True
+
+
+def test_the_reset_script_asks_for_exactly_one_email():
+ script = os.path.join(os.path.dirname(__file__), "..", "src", "backend", "reset_2fa.py")
+ source = open(script).read()
+ assert "reset_two_factor" in source and "len(argv) != 2" in source
diff --git a/tests/test_admin.py b/tests/test_admin.py
index d70c21b..ff07a05 100644
--- a/tests/test_admin.py
+++ b/tests/test_admin.py
@@ -11,20 +11,10 @@ from sqlalchemy.orm import sessionmaker
from src.backend import main, rules
from src.backend.auth import register_user
+from tests.fakes import FakeRedis
from src.backend.models import AppSetting, Base, ContainerMetric, HostMetric, PendingCollector, Server, User
-class FakeRedis:
- def __init__(self):
- self.store = {}
-
- def set(self, key, value, ex=None):
- self.store[key] = value
-
- def get(self, key):
- return self.store.get(key)
-
-
@pytest.fixture
def db():
engine = create_engine("sqlite://")
@@ -164,7 +154,7 @@ def test_admin_can_turn_agent_chat_off_and_on(fleet, monkeypatch):
result = main.update_admin_settings(main.AdminSettingsRequest(agent_chat_enabled=False), session_id="s", db=fleet)
- assert result == {"metrics_retention_days": main.DEFAULT_METRICS_RETENTION_DAYS, "agent_chat_enabled": False, "alert_thresholds": rules.DEFAULT_THRESHOLDS, "mount_thresholds": {}}
+ assert result == {"metrics_retention_days": main.DEFAULT_METRICS_RETENTION_DAYS, "agent_chat_enabled": False, "alert_thresholds": rules.DEFAULT_THRESHOLDS, "mount_thresholds": {}, "require_2fa_for_admins": True, "secrets_configured": False}
_login_as(monkeypatch, 2)
assert main.agent_config(session_id="s", db=fleet) == {"chat_enabled": False}
diff --git a/tests/test_auth_backend.py b/tests/test_auth_backend.py
index 2c4b13d..56f3961 100644
--- a/tests/test_auth_backend.py
+++ b/tests/test_auth_backend.py
@@ -7,26 +7,11 @@ import bcrypt
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
-from src.backend.auth import authenticate_user, record_audit_log, register_user
+from src.backend.auth import create_session, record_audit_log, register_user, verify_credentials
+from tests.fakes import FakeRedis
from src.backend.models import AuditLog, Base, User
-class FakeRedis:
- def __init__(self):
- self.store = {}
-
- def set(self, key, value, ex=None):
- self.store[key] = value
- return True
-
- def get(self, key):
- return self.store.get(key)
-
- def delete(self, key):
- self.store.pop(key, None)
- return True
-
-
def test_register_user_creates_record_and_hashes_password():
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
@@ -48,30 +33,17 @@ def test_register_user_creates_record_and_hashes_password():
assert session.query(User).first().password_hash != "correct-horse-battery-staple"
-def test_authenticate_user_returns_session_for_valid_credentials():
+def test_valid_credentials_identify_the_user_and_open_a_session():
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
- Session = sessionmaker(bind=engine)
- session = Session()
+ session = sessionmaker(bind=engine)()
redis = FakeRedis()
- register_user(
- db=session,
- redis_client=redis,
- name="Grace Hopper",
- password="correct-horse-battery-staple",
- )
-
- result = authenticate_user(
- db=session,
- redis_client=redis,
- password="correct-horse-battery-staple",
- )
+ register_user(db=session, redis_client=redis, name="Grace Hopper", email="[email protected]", password="correct-horse-battery-staple")
+ user = verify_credentials(session, email="[email protected]", password="correct-horse-battery-staple")
+ session_id, public_id = create_session(redis, user)
- assert result["user"]["email"] == "[email protected]"
- assert result["session_id"]
+ assert user.email == "[email protected]" and session_id and public_id
def test_record_audit_log_persists_database_entries():
@@ -164,32 +136,14 @@ def _fresh(monkeypatch, token=""):
monkeypatch.setattr(main, "ALLOW_REGISTRATION", False)
monkeypatch.setattr(main, "ADMIN_BOOTSTRAP_TOKEN", token)
monkeypatch.setattr(main, "enforce_register_limit", lambda *a, **k: None)
- monkeypatch.setattr(main, "redis_client", FakeRedisForRegister())
+ monkeypatch.setattr(main, "redis_client", FakeRedis())
return main, session
-class FakeRedisForRegister:
- def __init__(self):
- self.store = {}
-
- def setex(self, key, ttl, value):
- self.store[key] = value
-
- def set(self, key, value, *a, **k):
- self.store[key] = value
-
- def get(self, key):
- return self.store.get(key)
-
- def delete(self, *keys):
- for key in keys:
- self.store.pop(key, None)
-
-
def _register(main, session, token, email="[email protected]"):
from types import SimpleNamespace
from fastapi import Response
- request = SimpleNamespace(client=SimpleNamespace(host="1.2.3.4"))
+ request = SimpleNamespace(client=SimpleNamespace(host="1.2.3.4"), headers={})
return main.auth_register(main.RegisterRequest(name="Owner", email=email, password="correct-horse-battery-staple", bootstrap_token=token), request=request, response=Response(), db=session)
@@ -293,7 +247,7 @@ def test_existing_accounts_with_short_passwords_can_still_sign_in():
session.add(User(name="Old", email="[email protected]", password_hash=bcrypt.hashpw(b"old6pw", bcrypt.gensalt()).decode(), role="admin"))
session.commit()
- assert authenticate_user(session, FakeRedis(), email="[email protected]", password="old6pw")["user"]["email"] == "[email protected]"
+ assert verify_credentials(session, email="[email protected]", password="old6pw").email == "[email protected]"
def test_an_overlong_password_at_login_is_just_invalid_not_an_error_with_internals():
@@ -304,7 +258,7 @@ def test_an_overlong_password_at_login_is_just_invalid_not_an_error_with_interna
session.commit()
with pytest.raises(ValueError) as exc:
- authenticate_user(session, FakeRedis(), email="[email protected]", password="x" * 200)
+ verify_credentials(session, email="[email protected]", password="x" * 200)
assert str(exc.value) == "Invalid email or password."