Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
fix(security): validate everything collectors report, limit enrollment, safer defaults
karloks20051fb8e52e0665
diff --git a/.env.example b/.env.exampleindex d3ab6ab..4ef6182 100644--- a/.env.example+++ b/.env.example@@ -5,7 +5,7 @@ GEMINI_API_KEY=AGENT_MODEL=models/gemini-3.5-flash# Allow anyone to create an account. When false, only the first account can be-# created. Defaults: true in docker-compose.yml, false in docker-compose.server.yml.+# created (false is the default, in every compose file).# ALLOW_REGISTRATION=false# Optional: receives JSON alerts for critical daily-checkup findings.diff --git a/README.md b/README.mdindex 1274327..01aae57 100644--- a/README.md+++ b/README.md@@ -189,7 +189,7 @@ protection. In short:Backend (Python 3.12) and frontend (Node 20) can run without Docker; see [Development](docs/development.md).```bash-source venv/bin/activate && pip install -r requirements-dev.txt && pytest # backend, about a minute and a half+source venv/bin/activate && pip install -r requirements-dev.txt && pytest # backend, about two minutescd src/frontend && node --test # chart helpers, nothing to install```diff --git a/SECURITY.md b/SECURITY.mdindex 4781e2d..95981a8 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -82,8 +82,10 @@ stats) and nothing more through Docker.already have access to the database (local development, recovering a lost login). It reads theemail and password from `SEED_ADMIN_EMAIL` / `SEED_ADMIN_PASSWORD` or prompts for them, never printsthe password, and applies the same 16-character rule. It has no built-in account or password.-- **Registration stays off.** `ALLOW_REGISTRATION` defaults to `false` in `docker-compose.server.yml`,- so after the first account nobody else can sign up.+- **Registration stays off.** `ALLOW_REGISTRATION` defaults to `false` everywhere (in the backend and in+ both compose files), so after the first account nobody else can sign up. If you turn it on, the backend+ prints a SECURITY WARNING at every start, because anyone who can reach the dashboard can then create an+ account and read every server, container and incident.## Passwords and cross-site requests@@ -170,6 +172,13 @@ the public side at all.- **Re-pairing an existing machine needs explicit confirmation.** If a new request matches themachine ID of a server you already have, approving it replaces that server's credentials and signsits collector out. The dashboard warns and asks, and the API refuses without `replace: true`.+- **The enrollment key is the exception, and it is watched.** A collector installed with the enrollment key+ (for scripted installs) gets its existing server back, with a new token, when its machine ID is already+ known, which is what makes reinstalling easy. Because that key is long-lived, using it is rate limited+ (per address and per key), the number of servers is capped (`MAX_SERVERS`, default 200), and replacing an+ existing server's credentials is recorded: it appears in the server's System row, in the audit log, and+ opens a **warning** for an hour, with advice to rotate the key if you didn't do it. Treat the key like a+ password and rotate it under *Connect a server → Advanced* if a host that holds it is compromised.- **No code comes from the dashboard.** The dashboard no longer serves `collector.py`. Remotehosts install the collector and the Docker proxy from container images you publish (the "Publishimages" workflow builds them for a version tag, signs them with cosign and prints their digests).@@ -187,10 +196,20 @@ What this still depends on:admin still has to approve them; ingest additionally needs a server's token.- Rotating a collector token means re-adding that server.-## Container data is untrusted+## Data from collectors is untrusted-A compromised collector controls everything it reports about containers, so the backend never trusts-it: each record is reduced to known fields of the right type (text made printable and capped, numbers+A compromised collector controls everything it reports, so the backend never trusts any of it. For the host+itself, every number is range-checked (percentages 0 to 100, loads, sizes and counters within sane limits; NaN,+infinity, text and booleans become "unknown"), so one bad value can't make pages fail for everyone. Server+descriptions (hostname, address, operating system, core count, memory) are checked too, and a hostname that+another server already uses is ignored, so one collector can't pose as another. Only the stack's own collector,+which reaches the backend through the gate's internal listener, can claim to be the dashboard's machine. At most+64 filesystems are accepted per check-in, check-ins must be spaced by a quarter of the check interval+(refused with 429 otherwise, and checked only after the token is verified, so nobody else can use up a+server's slot), and the alerts list on the dashboard shows at most ten per server, so one noisy server can't+push everyone else's off it.++For containers, each record is reduced to known fields of the right type (text made printable and capped, numbersrange-checked, timestamps parsed strictly, image IDs matched against `sha256:` plus 64 hex characters),and anything unexpected becomes "unknown", which never raises an incident. At most 500 containers areaccepted per check-in, names are capped at 128 characters so they can't break incident keys, anddiff --git a/TESTS.md b/TESTS.mdindex a6d3bbd..d40675d 100644--- a/TESTS.md+++ b/TESTS.md@@ -4,8 +4,8 @@ Vexion ships with an automated test suite. This page explains how to run it, whacovers (and what it doesn't), and what every single test is for, so you can decidewhether a failure matters before you upgrade or change your setup.-- **798 test cases** from 469 test functions, plus 16 small tests of the chart helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).-- **About a minute and a half** to run. No Docker, PostgreSQL, Redis, network or root access needed.+- **1035 test cases** from 523 test functions, plus 16 small tests of the chart helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).+- **About two minutes** to run. No Docker, PostgreSQL, Redis, network or root access needed.- **Safe to run next to a live install.** The tests use a throwaway in-memory databaseand fakes; they never touch your running containers or your data. (Two collectortests read this machine's `/proc` and root filesystem, read-only.)@@ -124,7 +124,7 @@ docker compose logs --tail 20 collector # "Sent host metrics and N contai| File | Cases | Protects ||---|---|---|-| [`test_account_security.py`](#test_account_securitypy) | 121 | Two-factor sign-in, recovery codes, encrypted secrets, sessions you can review and end, and password change. |+| [`test_account_security.py`](#test_account_securitypy) | 130 | Two-factor sign-in, recovery codes, encrypted secrets, sessions you can review and end, password change, and the password check before turning two-factor on. || [`test_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. |@@ -137,9 +137,12 @@ docker compose logs --tail 20 collector # "Sent host metrics and N contai| [`test_dashboard_host.py`](#test_dashboard_hostpy) | 8 | The "this machine" logic, history charts, container list and incident counts. || [`test_docker_proxy.py`](#test_docker_proxypy) | 111 | The read-only Docker proxy: what it allows, refuses and hides. || [`test_enrollment.py`](#test_enrollmentpy) | 10 | Enrollment keys, collector credentials and offline-server detection. |+| [`test_enrollment_limits.py`](#test_enrollment_limitspy) | 12 | Limits on the enrollment key: rate limits, the server cap, and a warning when credentials are replaced. || [`test_health_checks.py`](#test_health_checkspy) | 4 | The assistant's fixed health checks and the critical-only webhook. || [`test_history.py`](#test_historypy) | 36 | The history API behind long-range charts: which level of detail answers each range, point limits, gaps, and agreement with the raw samples. || [`test_indexes.py`](#test_indexespy) | 9 | The database indexes on the metrics tables: only the ones queries use, none duplicated. |+| [`test_ingest_validation.py`](#test_ingest_validationpy) | 178 | What collectors report is checked and bounded: numbers, names, filesystems, spacing of check-ins. |+| [`test_input_limits.py`](#test_input_limitspy) | 38 | Size and shape limits on request bodies, the audit-log endpoint, and safe defaults. || [`test_network_checks.py`](#test_network_checkspy) | 94 | The host's real network totals, listening-port inventory, optional internet check, firewall fingerprints, and the validation of all of it. || [`test_pending_collectors.py`](#test_pending_collectorspy) | 28 | Adding servers: approval, join tokens, strict mode, re-pairing safety. || [`test_rollups.py`](#test_rollupspy) | 31 | Summarised history: hourly, daily, weekly and monthly rollups, catching up, gaps, and purging only what has been summarised. |@@ -235,6 +238,15 @@ out of their own install.| `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_a_normal_session_must_give_the_password_to_set_up_two_factor` | From a normal session, starting two-factor setup without the password, or with a wrong one, is refused (401) and nothing is created. |+| `test_the_right_password_starts_the_setup_from_a_normal_session` | The right password starts the setup. |+| `test_a_stolen_session_cannot_lock_the_owner_out_by_enrolling_its_own_authenticator` | Someone with only the session cookie can't enrol their own authenticator, and the owner can still sign in. |+| `test_wrong_passwords_while_setting_up_count_toward_the_two_factor_lockout` | Wrong passwords during setup count towards the shared lockout. |+| `test_the_forced_first_enrolment_does_not_ask_for_the_password_again` | An admin who just signed in and must enrol isn't asked for the password again. |+| `test_turning_two_factor_off_gives_this_session_a_new_id` | Turning two-factor off gives the current session a new ID and ends the old one. |+| `test_a_successful_sign_in_does_not_reset_the_address_counter` | Signing in to your own account doesn't give more guesses against someone else's: only the one allowed guess is left. |+| `test_signing_in_successfully_does_not_use_up_the_addresss_allowance` | People behind one address can all sign in, 15 times in a row, without being locked out. |+| `test_a_successful_sign_in_still_resets_that_accounts_own_counter` | A successful sign-in clears that account's own counter. |### test_admin.py@@ -473,9 +485,9 @@ tested hardest (91 cases). If any of these fail, do not run the proxy until it i| Test | What it checks ||---|---|-| `test_the_four_read_requests_are_allowed` *(6 inputs)* | The exact requests the collector needs (list containers, inspect one, one stats snapshot, and the quick one-shot stats form) are allowed. |+| `test_the_four_read_requests_are_allowed` *(5 inputs)* | The exact requests the collector needs (list containers, inspect one, one stats snapshot, and the quick one-shot stats form) are allowed. || `test_only_get_is_allowed` *(8 inputs)* | Every method except GET (POST, PUT, DELETE, PATCH, HEAD, OPTIONS, lowercase `get`, CONNECT) is refused. |-| `test_everything_else_is_refused` *(63 inputs)* | Everything outside the allow-list is refused: other endpoints (`/info`, images, exec, start, kill, export, archive, logs), extra or changed query strings, path traversal, encoded or padded paths, injected line breaks, odd container IDs. |+| `test_everything_else_is_refused` *(81 inputs)* | Everything outside the allow-list is refused: other endpoints (`/info`, images, exec, start, kill, export, archive, logs), extra or changed query strings, path traversal, encoded or padded paths, injected line breaks, odd container IDs. || `test_inspect_output_drops_environment_and_everything_unneeded` | The container description is cut down to the needed fields (including exit code, out-of-memory flag, finish time and image ID); environment variables (often secrets), mounts, labels, host configuration and Docker's free-text error message never leave the proxy. || `test_list_and_stats_output_are_cut_down` | The same filtering applies to the container list and stats. || `test_unexpected_upstream_shapes_do_not_crash_the_filters` *(7 inputs)* | Strange or malformed answers from Docker don't crash the proxy. |@@ -503,6 +515,25 @@ tested hardest (91 cases). If any of these fail, do not run the proxy until it i| `test_collector_enrolls_and_saves_when_no_credentials` | Without credentials, the collector enrolls, saves its token, and the file is readable only by its owner (mode 600). || `test_machine_id_read_from_host_root` | The collector identifies the machine from the host's `/etc/machine-id`. |+### test_enrollment_limits.py++The enrollment key can re-issue a server's credentials, so its use is limited and visible.++| Test | What it checks |+|---|---|+| `test_enrolling_with_a_known_machine_id_still_works_but_signs_the_old_collector_out` | Re-enrolling a known machine gives its server a new token and the old token stops working. |+| `test_replacing_credentials_leaves_an_event_and_an_audit_entry` | The replacement is written to the server's events and to the audit log. |+| `test_the_replacement_opens_a_warning_that_clears_by_itself` | A warning opens at the server's next check-in and resolves once the event is old. |+| `test_a_brand_new_machine_is_not_a_replacement` | A new machine creates a server and no warning. |+| `test_the_hostname_is_made_printable_and_bounded` | Control characters in the hostname become `?`, and one over 255 characters is refused. |+| `test_one_address_can_only_enroll_so_often` | The 31st enrollment from one address in an hour gets 429. |+| `test_wrong_keys_count_against_the_limit_too` | Wrong keys count against the limit, so keys can't be tried freely. |+| `test_another_address_has_its_own_allowance` | Another address isn't affected by the first one's limit. |+| `test_the_key_itself_has_a_limit_across_addresses` | One key can only be used so often in total, whichever addresses it comes from. |+| `test_a_redis_outage_does_not_block_enrolling` | With Redis down, enrolling still works. |+| `test_a_full_install_refuses_new_servers_but_still_serves_the_ones_it_has` | At the server limit new machines are refused (409) but existing ones can re-enroll. |+| `test_the_cap_applies_to_adding_by_hand_and_to_approving_requests` | The server limit also applies to adding a server by hand and to approving a request. |+### test_health_checks.py| Test | What it checks |@@ -555,6 +586,53 @@ The indexes on the metrics tables. The live migration is checked by hand against| `test_deleting_a_server_and_purging_old_rows_can_both_use_an_index` *(4 inputs)* | Every metrics table keeps an index starting with `server_id` (deleting a server cascades through it) and one on `time` alone (the hourly purge). || `test_a_primary_key_is_never_indexed_a_second_time` *(4 inputs)* | No table gets a redundant index on its own `id`. |+### test_ingest_validation.py++Nothing a collector reports is trusted: numbers, names and filesystems are checked, check-ins are spaced, and one bad collector can't break pages for everyone.++| Test | What it checks |+|---|---|+| `test_a_check_in_with_infinity_does_not_break_the_pages_for_everyone` | A check-in containing `Infinity`, `-Infinity` or `NaN` is accepted but stored as unknown, and the overview, history, heatmap and fleet pages keep working for everyone. |+| `test_every_host_number_outside_its_range_or_of_the_wrong_type_is_stored_as_unknown` *(117 inputs)* | Each host number (every field, each bad value: too big, negative, text, boolean, null, list, object, a number too large for a float) is stored as unknown. |+| `test_sensible_numbers_are_stored_exactly` | Normal values are stored unchanged. |+| `test_counters_too_big_for_the_database_are_unknown_instead_of_an_error` *(8 inputs)* | Counters beyond what the database column holds, or negative, become unknown instead of an error. |+| `test_the_summaries_survive_whatever_was_reported` | Absurd values never reach the summaries, so summarising can't be broken by a collector. |+| `test_a_server_description_is_kept_only_if_it_is_sensible` | A valid hostname, address, operating system, core count and memory size are saved (control characters become `?`). |+| `test_a_bad_server_description_leaves_what_was_known` *(18 inputs)* | A bad core count, memory size, address or hostname leaves the earlier value in place. |+| `test_long_names_are_cut_to_what_fits` | Over-long hostnames and operating system names are cut to 255 characters. |+| `test_a_collector_cannot_take_another_servers_name` | A hostname another server already uses (in any letter case) is ignored. |+| `test_only_a_collector_on_the_internal_listener_can_claim_to_be_the_dashboards_machine` | Over the VPN listener a collector can't take the dashboard machine's place; the stack's own collector can. |+| `test_in_the_development_stack_the_claim_is_accepted_as_before` | With a single listener (development) the claim still works. |+| `test_at_most_sixty_four_filesystems_are_stored_per_check_in` | 3000 reported filesystems become 64 stored rows. |+| `test_a_filesystem_is_stored_once_and_only_with_known_good_fields` | Duplicates are dropped, and fields a collector shouldn't set (`id`, `server_id`, `time`, extras) are ignored. |+| `test_filesystem_records_that_are_not_usable_are_skipped` *(9 inputs)* | Relative paths, empty names, wrong types and non-objects are skipped; valid ones around them are kept. |+| `test_filesystem_numbers_outside_their_range_are_unknown` *(8 inputs)* | Bad sizes and percentages for a filesystem become unknown. |+| `test_mount_names_are_made_printable_and_bounded` | Long names and control characters are cut and replaced. |+| `test_a_check_in_that_follows_the_last_one_too_closely_is_refused` | A second check-in a moment after the first gets 429 with `Retry-After`; another server is unaffected. |+| `test_the_next_check_in_is_accepted_when_the_slot_has_passed` | Once the spacing has passed, check-ins work again. |+| `test_the_spacing_is_never_shorter_than_the_minimum` | Even with a 15-second interval the spacing is at least 5 seconds. |+| `test_someone_without_the_token_cannot_use_up_a_servers_slot` | A request with a wrong token is refused (401) without using up the real collector's slot. |+| `test_a_redis_outage_does_not_stop_check_ins` | If Redis is down the limit is skipped and monitoring continues. |+| `test_one_server_with_a_flood_of_alerts_cannot_hide_everyone_elses` | 100 alerts from one server show at most 10, so another server's single alert stays visible; the total count stays true. |+| `test_one_query_never_reads_more_raw_rows_than_the_backstop` | A history query stops at the row cap. |++### test_input_limits.py++Request bodies have sizes and shapes, and the defaults are the safe ones.++| Test | What it checks |+|---|---|+| `test_a_sensible_log_entry_is_stored_under_the_dashboard_source` | A normal log entry is stored and its source is always `dashboard`, even if the request says otherwise. |+| `test_nobody_can_write_entries_that_look_like_they_came_from_another_part_of_the_system` | Entries claiming to come from `auth` or `admin` are stored as `dashboard`. |+| `test_log_entries_outside_the_limits_are_refused_and_nothing_is_stored` *(14 inputs)* | Too long, too many, wrong type, unknown level or an odd event type: refused (422) and nothing stored. |+| `test_a_megabyte_message_is_refused` | A one-megabyte message is refused. |+| `test_writing_log_entries_is_rate_limited_per_user` | The 121st entry in an hour gets 429. |+| `test_log_entries_need_a_session` | Without a session, 401. |+| `test_oversized_fields_in_other_bodies_are_refused_before_any_work_is_done` *(16 inputs)* | Over-long fields in chat, conversations, sign-in, registration, enrollment, collector registration and adding servers are refused (422). |+| `test_registration_is_closed_unless_someone_opens_it` | Registration, API documentation and CORS origins default to closed and empty, and registration opens only when asked. |+| `test_the_api_documentation_is_not_served_to_anonymous_visitors` | `/docs`, `/redoc` and `/openapi.json` return 404. |+| `test_an_open_registration_is_called_out_in_the_log` | With registration open and accounts existing, the startup log gets a SECURITY WARNING; not on a fresh install. |+### test_network_checks.pyNetwork checks: the host's real traffic totals, which ports it listens on, whether it candiff --git a/collector-compose.yml b/collector-compose.ymlindex 8059a56..8113193 100644--- a/collector-compose.yml+++ b/collector-compose.yml@@ -1,5 +1,5 @@-# Collector-only stack, an alternative to the one-line `docker run` shown on the-# dashboard (Connect a server). Set HOMELAB_API_URL (e.g. in a .env next to+# Collector-only stack that builds the images locally, an alternative to the signed images the compose+# command from the dashboard (Connect a server) installs. Set HOMELAB_API_URL (e.g. in a .env next to# this file) and run:# docker compose -f collector-compose.yml up -d --build# The server then appears on the dashboard under "New servers detected"; clickdiff --git a/compose.yml b/compose.ymlindex 954dfd7..36cf7eb 100644--- a/compose.yml+++ b/compose.yml@@ -44,10 +44,15 @@ services:AGENT_MODEL: ${AGENT_MODEL:-models/gemini-3.5-flash}# Set to true when the dashboard is served over HTTPS.SESSION_COOKIE_SECURE: ${SESSION_COOKIE_SECURE:-false}- ALLOW_REGISTRATION: ${ALLOW_REGISTRATION:-true}+ ALLOW_REGISTRATION: ${ALLOW_REGISTRATION:-false}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:-}+ # Limits on what collectors can do. A check-in must come at least this share of the check interval after the+ # previous one (0 switches it off); the install holds at most MAX_SERVERS; /docs is off unless enabled.+ INGEST_MIN_SPACING_RATIO: ${INGEST_MIN_SPACING_RATIO:-0.25}+ MAX_SERVERS: ${MAX_SERVERS:-200}+ ENABLE_API_DOCS: ${ENABLE_API_DOCS:-false}# Setup token for the very first account. Empty: one is generated and printed in the backend log.ADMIN_BOOTSTRAP_TOKEN: ${ADMIN_BOOTSTRAP_TOKEN:-}# How long a token from "Connect a server" stays valid, in seconds.diff --git a/docker-compose.server.yml b/docker-compose.server.ymlindex 1694b53..0da07a0 100644--- a/docker-compose.server.yml+++ b/docker-compose.server.yml@@ -59,6 +59,11 @@ 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:-}+ # Limits on what collectors can do. A check-in must come at least this share of the check interval after the+ # previous one (0 switches it off); the install holds at most MAX_SERVERS; /docs is off unless enabled.+ INGEST_MIN_SPACING_RATIO: ${INGEST_MIN_SPACING_RATIO:-0.25}+ MAX_SERVERS: ${MAX_SERVERS:-200}+ ENABLE_API_DOCS: ${ENABLE_API_DOCS:-false}# Setup token for the very first account. Empty: one is generated and printed in the backend log.ADMIN_BOOTSTRAP_TOKEN: ${ADMIN_BOOTSTRAP_TOKEN:-}# How long a token from "Connect a server" stays valid, in seconds.diff --git a/docker/nginx.conf b/docker/nginx.confindex 04ba626..b9b73be 100644--- a/docker/nginx.conf+++ b/docker/nginx.conf@@ -30,6 +30,7 @@ server {proxy_http_version 1.1;proxy_set_header Host $http_host;proxy_set_header X-Forwarded-For $remote_addr;+ proxy_set_header X-Collector-Via "";proxy_set_header X-Forwarded-Host $host;proxy_read_timeout 120s;client_max_body_size 5m;diff --git a/docs/accounts.md b/docs/accounts.mdindex 35873e9..47d90e2 100644--- a/docs/accounts.md+++ b/docs/accounts.md@@ -4,8 +4,9 @@- The first account created is the **admin**. It needs the install's **setuptoken** (printed in the backend log at start, or `ADMIN_BOOTSTRAP_TOKEN`). Later- accounts are regular users (and on the server file, registration closes after- the first account).+ accounts are regular users. Registration is closed after the first account unless you set+ `ALLOW_REGISTRATION=true` (the backend then prints a security warning at every start, because anyone+ who can reach the dashboard could create an account).- **Passwords must be at least 16 characters** (and at most 72 bytes). A few randomwords make a good passphrase. The rule applies to new accounts; existingaccounts keep working with their current password.@@ -39,7 +40,8 @@ as Google Authenticator, Aegis or a password manager).Back this key up with your other secrets. **If you lose it, authenticator codesstop 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+2. **Turn it on** under Account → Two-factor sign-in. From a normal session it first asks for your+ password again (the forced first enrolment of an admin doesn't). You get a setup key and an`otpauth://` link to paste into your authenticator app (no QR code yet), confirmwith 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 bediff --git a/docs/alerts.md b/docs/alerts.mdindex 7937373..7bdf5eb 100644--- a/docs/alerts.md+++ b/docs/alerts.md@@ -38,6 +38,7 @@ stops firing.| Kernel fault flags (machine check, bad page, oops, warning, soft lockup) | – | warning, clears on reboot || Clock not synchronised | 3 check-ins in a row | warning || Reboot required | – | info |+| Server credentials replaced through the enrollment key | stays open 60 minutes | warning |New listening ports and firewall changes are noticed the same way, by comparing withwhat the previous check-in saw. The first report is a silent baseline, an unreadablediff --git a/docs/api.md b/docs/api.mdindex bd07b2e..962ccc3 100644--- a/docs/api.md+++ b/docs/api.md@@ -9,7 +9,7 @@ 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. |+| `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. Starting setup from a normal session needs `{"password": ...}`; the forced first enrolment doesn't. || `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. |@@ -34,7 +34,7 @@ All paths are relative to `/api` when going through the frontend/nginx.| `POST /monitoring/collectors/enroll` | enrollment key | Join without approval. || `POST /monitoring/metrics/ingest` | collector token | Collector reports host, container and system metrics. || `GET /conversations`, `POST /conversations`, `DELETE /conversations/{id}`, `POST /agent/chat` | session | Homie assistant chats. |-| `GET /logs`, `POST /logs`, `GET /dashboard/summary` | session | Audit log and summary counts. |+| `GET /logs`, `POST /logs`, `GET /dashboard/summary` | session | Audit log and summary counts. `POST /logs` adds an entry to your own log (level from a fixed list, message up to 2000 characters, at most 120 an hour); its source is always `dashboard`. |The four collector endpoints above exist only on the collector gate in the serverstack (the public listener answers 404); the development stack serves them on thediff --git a/docs/configuration.md b/docs/configuration.mdindex fdf4a45..3d5723f 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -12,7 +12,10 @@| `ADMIN_ALERT_WEBHOOK_URL` | empty | Receives JSON alerts for critical `daily_checkup` findings. || `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. |+| `ALLOW_REGISTRATION` | `false` | Let anyone create an account. When `false` (the default), only the first account can be created. Turning it on prints a security warning at every start. |+| `MAX_SERVERS` | `200` | The most servers the install holds, however they are added (enrollment key, approval or by hand). |+| `INGEST_MIN_SPACING_RATIO` | `0.25` | A check-in must arrive at least this share of the server's check interval (and never sooner than 5 seconds) after the previous one, or it is refused with 429. `0` switches the limit off. |+| `ENABLE_API_DOCS` | `false` | Serves the interactive API documentation at `/api/docs`. Leave off on a public install. || `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. |diff --git a/docs/deployment.md b/docs/deployment.mdindex 81ed7c3..2296788 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -126,9 +126,14 @@ compose project). Collectors started from `collector-compose.yml` need## Without Traefik-- **Caddy (automatic Let's Encrypt):** with `compose.yml`, set- `DOMAIN`, `SESSION_COOKIE_SECURE=true` and `FRONTEND_BIND=127.0.0.1` in- `.env`, open ports 80/443, and run `docker compose --profile https up -d --build`.+- **Another reverse proxy (nginx, Caddy, HAProxy, ...):** use the **server stack** (`docker-compose.server.yml`),+ not the development stack, and point your proxy at its dashboard port (`127.0.0.1:5173` by default; the+ Traefik labels are simply unused). The server stack is the one that keeps the collector endpoints off the+ public side, registration closed and the session cookie HTTPS-only. Terminate HTTPS in your proxy and have it+ send `X-Forwarded-For`.+- **Caddy profile (`--profile https`, development stack): private use only.** It publishes the development+ stack's single listener, which serves the collector endpoints on the same address as the dashboard, so it+ is not suitable for a dashboard that is open to the internet. Use it on a LAN or behind a VPN.- **Private, over a VPN:** install Tailscale, WireGuard or OpenVPN on the serverand your devices, run `docker compose up -d --build`, and use `http://<vpn-ip>:5173`(collectors: `http://<vpn-ip>:5173/api`). Nothing is exposed publicly. This usesdiff --git a/docs/development.md b/docs/development.mdindex 3c2a493..ab9353f 100644--- a/docs/development.md+++ b/docs/development.md@@ -44,7 +44,7 @@ pip install -r requirements-dev.txt # the app's requirements plus pytestpytest```-No Docker, PostgreSQL or Redis is needed; the suite takes about a minute and a half. The chart+No Docker, PostgreSQL or Redis is needed; the suite takes about two minutes. The charthelpers have their own tests that need only Node 20 or newer: `cd src/frontend && node --test`. See[TESTS.md](../TESTS.md) for how the tests work, what they don't cover, and what everytest is for.diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 555f57a..33b7b03 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -27,3 +27,7 @@| Lost the authenticator and the recovery codes | Run `docker compose exec backend python src/backend/reset_2fa.py <email>` on the host, then sign in with the password and set it up again. || Authenticator codes stopped working after a restore or `.env` change | `SECRETS_KEY` changed or was lost, so the stored secret can't be decrypted. Restore the old key (rotation: `new,old`), or use a recovery code and the reset command. || Server marked offline | It missed 3 check-ins in a row. Check the machine, its collector log and its route to the dashboard. The incident resolves on the next report. |+| A collector log says "Check-ins are arriving faster than this server's interval allows" (HTTP 429) | The collector reports more often than a quarter of the server's check interval. It retries by itself; check that only one collector uses that server's token, or adjust `INGEST_MIN_SPACING_RATIO`. |+| "This install already has the most servers it allows" | `MAX_SERVERS` (default 200) is reached. Remove servers you no longer need, or raise it in `.env`. |+| A warning "The credentials of <server> were replaced" | Someone used the enrollment key on a machine whose ID is already known, which signs the previous collector out. Expected after you reinstall that machine with the key; if it wasn't you, rotate the key under *Connect a server → Advanced* and inspect the machine. |+| "Enter your current password to set up two-factor." | Turning on two-factor from a normal session asks for your password again. Type it in the field that appears. |diff --git a/example.env b/example.envindex 38318bf..63393a1 100644--- a/example.env+++ b/example.env@@ -77,6 +77,20 @@ SESSION_TTL_SECONDS=86400# the same domain.SESSION_COOKIE_NAME=homie_session+# =============================================================================+# Limits (the defaults suit most installs)+# =============================================================================++# The most servers this install will hold, however they are added.+# MAX_SERVERS=200++# A check-in must arrive at least this share of the server's check interval after the previous one;+# faster ones are refused (429). 0 switches the limit off.+# INGEST_MIN_SPACING_RATIO=0.25++# Serves the interactive API documentation at /api/docs. Leave off on a public install.+# ENABLE_API_DOCS=false+# Setup token for the very first account (the one that becomes the admin).# Leave it commented: the backend then makes one up and prints it in its log# ("docker compose logs backend | grep 'setup token'") until the first account exists.diff --git a/src/agent/docker_proxy.py b/src/agent/docker_proxy.pyindex 8137b89..8ed7445 100644--- a/src/agent/docker_proxy.py+++ b/src/agent/docker_proxy.py@@ -37,7 +37,7 @@ UPSTREAM_TIMEOUT_SECONDS = 10_ID = r"[0-9a-f]{12,64}"# Matched against the whole request target, query string included.-_LIST = re.compile(r"/containers/json(\?all=1)?")+_LIST = re.compile(r"/containers/json\?all=1")_INSPECT = re.compile(rf"/containers/{_ID}/json")_STATS = re.compile(rf"/containers/{_ID}/stats\?stream=false(&one-shot=true)?")diff --git a/src/backend/config.py b/src/backend/config.pyindex e314a7f..d8d98fe 100644--- a/src/backend/config.py+++ b/src/backend/config.py@@ -15,15 +15,18 @@ SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "86400"))AGENT_MODEL = os.getenv("AGENT_MODEL", "models/gemini-3.5-flash")SESSION_COOKIE_NAME = os.getenv("SESSION_COOKIE_NAME", "homie_session")SESSION_COOKIE_SECURE = os.getenv("SESSION_COOKIE_SECURE", "false").lower() == "true"-# When false, only the first account can be created (so a fresh install can still be set up).-ALLOW_REGISTRATION = os.getenv("ALLOW_REGISTRATION", "true").lower() == "true"+# When false (the default), only the first account can be created, so a fresh install can still be set up and+# nobody else can sign themselves up. Set to true only if everyone who can reach the dashboard may get an account.+ALLOW_REGISTRATION = os.getenv("ALLOW_REGISTRATION", "false").lower() == "true"+# Interactive API documentation (/docs, /openapi.json). Off unless asked for.+ENABLE_API_DOCS = os.getenv("ENABLE_API_DOCS", "false").lower() == "true"LOGIN_RATE_LIMIT = int(os.getenv("LOGIN_RATE_LIMIT", "5"))LOGIN_RATE_WINDOW_SECONDS = int(os.getenv("LOGIN_RATE_WINDOW_SECONDS", "60"))REGISTER_RATE_LIMIT = int(os.getenv("REGISTER_RATE_LIMIT", "3"))REGISTER_RATE_WINDOW_SECONDS = int(os.getenv("REGISTER_RATE_WINDOW_SECONDS", "3600"))CORS_ORIGINS = [origin.strip()- for origin in os.getenv("CORS_ORIGINS", "http://localhost:5173,http://localhost:5174,http://localhost:5175,http://localhost:5176").split(",")+ for origin in os.getenv("CORS_ORIGINS", "").split(",")if origin.strip()]@@ -37,6 +40,14 @@ COLLECTOR_IMAGE = os.getenv("COLLECTOR_IMAGE", "").strip()DOCKER_PROXY_IMAGE = os.getenv("DOCKER_PROXY_IMAGE", "").strip()JOIN_TOKEN_TTL_SECONDS = int(os.getenv("JOIN_TOKEN_TTL_SECONDS", "900"))+# A collector that reports much more often than its check interval is broken or hostile: it fills the database+# and the history queries. A check-in must arrive at least this share of the interval after the previous one+# (and never sooner than the minimum below). Set the ratio to 0 to switch the limit off.+INGEST_MIN_SPACING_RATIO = float(os.getenv("INGEST_MIN_SPACING_RATIO", "0.25"))+INGEST_MIN_SPACING_SECONDS = int(os.getenv("INGEST_MIN_SPACING_SECONDS", "5"))+# The most servers an install will hold, whichever way they are added (enrollment, approval or by hand).+MAX_SERVERS = int(os.getenv("MAX_SERVERS", "200"))+# Creating the first account (which becomes the admin) needs a setup token, so nobody else can claim a# fresh install. Leave unset to have one generated and printed in the backend log at every start until# the first account exists; set it to choose your own.diff --git a/src/backend/history.py b/src/backend/history.pyindex ef19774..4ca05e3 100644--- a/src/backend/history.py+++ b/src/backend/history.py@@ -27,6 +27,8 @@ RANGES: dict[str, timedelta | None] = {SOURCE = {"1h": DETAILED, "6h": DETAILED, "24h": DETAILED, "7d": DETAILED,"30d": rollups.HOUR, "90d": rollups.WEEK, "1y": rollups.WEEK, "all": rollups.MONTH}MAX_POINTS = 500+# A backstop: with check-ins spaced by the ingest limit, one series stays well below this in seven days.+MAX_RAW_ROWS = 150_000NATURAL_SECONDS = {rollups.HOUR: 3600, rollups.DAY: 86400, rollups.WEEK: 7 * 86400, rollups.MONTH: 31 * 86400}# Bucket sizes a chart can be given; the smallest that keeps a range within MAX_POINTS is used.NICE_STEPS = (15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 14400, 21600, 43200, 86400, 7 * 86400)@@ -156,7 +158,7 @@ def _raw_items(db, spec: Series, wanted, server_id, key, since: datetime, until:columns = [getattr(spec.raw, spec.metrics[name].raw) for name in wanted]if spec.has_down:columns.append(spec.raw.status)- query = select(spec.raw.time, *columns).where(*_where(spec, "raw", server_id, key), spec.raw.time >= since, spec.raw.time < until).order_by(spec.raw.time)+ query = select(spec.raw.time, *columns).where(*_where(spec, "raw", server_id, key), spec.raw.time >= since, spec.raw.time < until).order_by(spec.raw.time).limit(MAX_RAW_ROWS)return [(rollups._utc(row[0]), _raw_agg(spec, wanted, row)) for row in db.execute(query)]diff --git a/src/backend/main.py b/src/backend/main.pyindex 01112e8..12f509d 100644--- a/src/backend/main.py+++ b/src/backend/main.py@@ -1,5 +1,6 @@from __future__ import annotations+import ipaddressimport jsonimport mathimport re@@ -18,7 +19,7 @@ from fastapi import Cookie, Depends, FastAPI, Header, HTTPException, Query, Requfrom fastapi import Path as PathParamfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, PlainTextResponse-from pydantic import BaseModel, EmailStr, Field+from pydantic import BaseModel, EmailStr, Field, field_validatorfrom sqlalchemy import case, func, inspect, textfrom .alerts import CONTAINER_RULE_PREFIX, CRITICAL, SERVER_OFFLINE_RULE, SEVERITIES, active_rule_keys, raise_alert, resolve_alerts, sync_alerts@@ -45,27 +46,31 @@ from .config import (COLLECTOR_PUBLIC_URL,DOCKER_PROXY_IMAGE,JOIN_TOKEN_TTL_SECONDS,+ ENABLE_API_DOCS,+ INGEST_MIN_SPACING_RATIO,+ INGEST_MIN_SPACING_SECONDS,+ MAX_SERVERS,CORS_ORIGINS,SESSION_COOKIE_NAME,SESSION_COOKIE_SECURE,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_limit, enforce_login_limit, enforce_register_limit, reset_limits+from .rate_limit import enforce_ip_limit, enforce_limit, enforce_login_limit, enforce_register_limit, refund_attempt, reset_limitsfrom ..agent.service import delete_agent_conversation, send_agent_messageclass RegisterRequest(BaseModel):- name: str+ name: str = Field(max_length=255)email: EmailStr- password: str+ password: str = Field(max_length=1024)# Only needed for the very first account; see ensure_bootstrap_token.- bootstrap_token: str | None = None+ bootstrap_token: str | None = Field(default=None, max_length=200)class LoginRequest(BaseModel):email: EmailStr- password: str+ password: str = Field(max_length=1024)class TwoFactorLoginRequest(BaseModel):@@ -77,6 +82,10 @@ class CodeRequest(BaseModel):code: str = Field(max_length=64)+class SetupRequest(BaseModel):+ password: str | None = Field(default=None, max_length=1024)++class ReauthRequest(BaseModel):password: str = Field(max_length=1024)code: str = Field(max_length=64)@@ -88,32 +97,49 @@ class PasswordChangeRequest(BaseModel):class AgentChatRequest(BaseModel):- conversation_id: str- message: str+ conversation_id: str = Field(max_length=255)+ message: str = Field(max_length=8000)class ConversationRequest(BaseModel):- conversation_id: str- title: str = "New chat"+ conversation_id: str = Field(max_length=255)+ title: str = Field(default="New chat", max_length=255)+++class LogCreateRequest(BaseModel):+ """An entry the dashboard adds to the user's own audit log. The source is always the dashboard, so nobody can+ write entries that look like they came from sign-in or administration."""++ level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"+ message: str = Field(default="New event", max_length=2000)+ task_title: str | None = Field(default=None, max_length=255)+ steps: list[Annotated[str, Field(max_length=1000)]] = Field(default_factory=list, max_length=50)+ conversation_id: str | None = Field(default=None, max_length=255)+ event_type: str | None = Field(default=None, max_length=50, pattern=r"^[a-z0-9_\-]*$")++ @field_validator("level", mode="before")+ @classmethod+ def _upper_case_level(cls, value):+ return value.upper() if isinstance(value, str) else valueclass ServerRequest(BaseModel):- hostname: str- ip_address: str | None = None+ hostname: str = Field(max_length=255)+ ip_address: str | None = Field(default=None, max_length=64)check_interval_seconds: int = 60class EnrollRequest(BaseModel):- enroll_key: str- hostname: str- machine_id: str | None = None+ enroll_key: str = Field(max_length=200)+ hostname: str = Field(max_length=255)+ machine_id: str | None = Field(default=None, max_length=64)class CollectorRegisterRequest(BaseModel):- hostname: str- machine_id: str | None = None- os_info: str | None = None- join_token: str | None = None+ hostname: str = Field(max_length=255)+ machine_id: str | None = Field(default=None, max_length=64)+ os_info: str | None = Field(default=None, max_length=255)+ join_token: str | None = Field(default=None, max_length=200)class ApproveRequest(BaseModel):@@ -161,7 +187,8 @@ def agent_error_message(exc: Exception) -> str:redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)-app = FastAPI(title="Homelab Agent API")+# The interactive API documentation is a map of every endpoint, so it is off unless ENABLE_API_DOCS=true.+app = FastAPI(title="Homelab Agent API", docs_url="/docs" if ENABLE_API_DOCS else None, redoc_url=None, openapi_url="/openapi.json" if ENABLE_API_DOCS else None)UNSAFE_METHODS = {"POST", "PUT", "PATCH", "DELETE"}@@ -203,6 +230,14 @@ app.add_middleware()+def registration_warning(db) -> str | None:+ """A warning for the log when anyone who can reach the dashboard may create an account."""+ if ALLOW_REGISTRATION and db.query(User).count() > 0:+ return ("SECURITY WARNING: ALLOW_REGISTRATION is true, so anyone who can reach the dashboard can create an account and see "+ "every server, container and incident. Set ALLOW_REGISTRATION=false unless that is what you want.")+ return None++@app.on_event("startup")def startup_event():Base.metadata.create_all(bind=engine)@@ -274,6 +309,8 @@ def startup_event():if require_admin_two_factor(db) and not secrets_box.available():print("SECURITY WARNING: two-factor is required for administrators, but SECRETS_KEY is missing or invalid, so it is NOT being enforced. ""Generate a key with `python -m src.backend.secrets_box` and set SECRETS_KEY in .env.", flush=True)+ if warning := registration_warning(db):+ print(warning, 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)@@ -414,7 +451,10 @@ def auth_login(payload: LoginRequest, request: Request, response: Response, db=Dexcept ValueError as exc:raise HTTPException(status_code=401, detail=str(exc)) from exc- reset_limits(redis_client, *limit_keys)+ # This email's counter is cleared. The address's counter only gets this one successful attempt back: clearing it+ # would let anyone with an account of their own reset the limit between guesses at someone else's password.+ reset_limits(redis_client, limit_keys[1])+ refund_attempt(redis_client, limit_keys[0])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)}@@ -504,12 +544,16 @@ def two_factor_status(session_id: Annotated[str | None, Cookie(alias=SESSION_COO@app.post("/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)+def two_factor_setup(payload: SetupRequest | None = None, 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 docs/accounts.md (Two-factor sign-in).")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.")+ if session.get("stage") != STAGE_ENROLLMENT:+ # Turning two-factor on from a normal session needs the password again. Otherwise a stolen session could+ # enrol its own authenticator, which signs out the real owner and locks them out.+ _confirm_password(db, user, payload.password if payload else None)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.@@ -545,6 +589,14 @@ def two_factor_enable(payload: CodeRequest, request: Request, response: Responsereturn {"recovery_codes": codes, "setup_required": False}+def _confirm_password(db, user: User, password: str | None) -> None:+ """Ask for the current password again before a sensitive change. Wrong tries share the two-factor lockout."""+ if not password or 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 or missing password was given while setting up two-factor", source="auth")+ raise HTTPException(status_code=401, detail="Enter your current password to set up two-factor.")++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.")@@ -561,7 +613,7 @@ def _reauthenticate(db, user: User, password: str, code: str) -> None:@app.post("/auth/2fa/disable")-def two_factor_disable(payload: ReauthRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):+def two_factor_disable(payload: ReauthRequest, 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)if not user.totp_enabled:raise HTTPException(status_code=409, detail="Two-factor is not turned on.")@@ -571,7 +623,11 @@ def two_factor_disable(payload: ReauthRequest, session_id: Annotated[str | None,user.totp_enabled, user.totp_secret_enc, user.totp_last_step = False, None, Nonedb.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"])+ # A fresh session ID for this one too, and every other session ends.+ 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="WARNING", message=f"Two-factor was turned off ({revoked} other sessions signed out)", source="auth")return {"status": "ok"}@@ -807,6 +863,22 @@ def agent_config(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NOVERVIEW_ALERT_LIMIT = 50+OVERVIEW_ALERTS_PER_SERVER = 10+OVERVIEW_ALERT_SCAN = 1000+++def _spread_alerts(alerts: list) -> list:+ """The most severe alerts first, but at most a few per server, so one server with a flood of alerts can't push+ everybody else's off the list. The alert count shown elsewhere is still the true total."""+ per_server: dict[int, int] = {}+ chosen = []+ for alert in alerts:+ per_server[alert.server_id] = per_server.get(alert.server_id, 0) + 1+ if per_server[alert.server_id] <= OVERVIEW_ALERTS_PER_SERVER:+ chosen.append(alert)+ if len(chosen) >= OVERVIEW_ALERT_LIMIT:+ break+ return chosenSYSTEM_EVENTS_SHOWN = 10@@ -909,7 +981,7 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_Cactive_alerts = db.query(IncidentAlert).filter(IncidentAlert.status == "active")# Most severe first, then newest.severity_rank = case({severity: rank for rank, severity in enumerate(reversed(SEVERITIES))}, value=IncidentAlert.severity, else_=len(SEVERITIES))- alerts = active_alerts.order_by(severity_rank, IncidentAlert.created_at.desc()).limit(OVERVIEW_ALERT_LIMIT).all()+ alerts = _spread_alerts(active_alerts.order_by(severity_rank, IncidentAlert.created_at.desc()).limit(OVERVIEW_ALERT_SCAN).all())hostnames = {server.id: server.hostname for server in servers}thresholds = get_alert_thresholds(db)pending = visible_pending_collectors(db) if _is_admin(db, user["id"]) else []@@ -1148,18 +1220,23 @@ def revoke_enrollment_key(session_id: Annotated[str | None, Cookie(alias=SESSION@app.post("/monitoring/collectors/enroll", dependencies=[Depends(require_collector_listener)])-def enroll_collector(payload: EnrollRequest, db=Depends(get_db)):+def enroll_collector(payload: EnrollRequest, db=Depends(get_db), request: Request = None):"""Register (or re-register) a collector using the owner's enrollment key.Servers are matched on machine_id, so a collector that lost its saved- credentials gets its existing server back with a fresh token.+ credentials gets its existing server back with a fresh token. That makes the key powerful, so every use is+ rate limited, the number of servers is capped, and replacing an existing server's credentials is recorded+ as an event (it opens a warning), so it can't happen unnoticed."""+ client_ip = _client_ip(request) if request else "unknown"+ _soft_limit(scope="enroll-ip", subject=client_ip, limit=ENROLL_RATE_LIMIT, window_seconds=ENROLL_RATE_WINDOW_SECONDS)key = db.query(EnrollmentKey).filter(EnrollmentKey.key_hash == _hash_secret(payload.enroll_key.strip())).first()if not key:raise HTTPException(status_code=401, detail="Enrollment key is invalid or has been rotated.")if not _is_admin(db, key.owner_id):raise HTTPException(status_code=403, detail="Enrollment key belongs to an account that can no longer add servers.")- hostname = payload.hostname.strip()[:255]+ _soft_limit(scope="enroll-key", subject=key.id, limit=ENROLL_RATE_LIMIT * 2, window_seconds=ENROLL_RATE_WINDOW_SECONDS)+ hostname = _printable(payload.hostname, 255)machine_id = (payload.machine_id or "").strip()[:64] or Noneif not hostname:raise HTTPException(status_code=400, detail="Hostname is required.")@@ -1167,11 +1244,19 @@ def enroll_collector(payload: EnrollRequest, db=Depends(get_db)):server = Noneif machine_id:server = db.query(Server).filter(Server.machine_id == machine_id).first()+ replaced = server is not Noneif not server:+ _ensure_server_capacity(db)server = Server(owner_id=key.owner_id, hostname=hostname, machine_id=machine_id)db.add(server)+ db.flush()token = secrets.token_urlsafe(32)server.collector_token_hash = _hash_secret(token)+ if replaced:+ now = datetime.now(timezone.utc)+ detail = f"This server's credentials were replaced through the enrollment key (request from {_printable(client_ip, 64)}). Its previous collector can no longer report."+ db.add(SystemEvent(server_id=server.id, time=now, kind=CREDENTIALS_REPLACED_KIND, detail=detail[:512], event_key=f"credentials:{now.isoformat()}"))+ record_audit_log(db, user_id=key.owner_id, level="warning", message=f"Enrollment key replaced the credentials of server {server.id} ({server.hostname}) from {_printable(client_ip, 64)}", source="enrollment", event_type="credentials_replaced")db.commit()db.refresh(server)return {"server_id": server.id, "collector_token": token, "check_interval_seconds": server.check_interval_seconds}@@ -1291,6 +1376,7 @@ def approve_pending_collector(pending_id: int, payload: ApproveRequest | None =# Approving mints new credentials for that server and locks out its current collector, so never do it silently.raise HTTPException(status_code=409, detail=f"This machine matches the existing server {server.hostname}. Approving replaces that server's credentials and signs its current collector out. Confirm to continue.")if not server:+ _ensure_server_capacity(db)server = Server(owner_id=user["id"], hostname=pending.hostname, machine_id=pending.machine_id, ip_address=pending.ip_address, os_info=pending.os_info)db.add(server)db.flush()@@ -1409,6 +1495,7 @@ def add_monitored_server(payload: ServerRequest, session_id: Annotated[str | Nonuser = _require_admin(session_id, db)if not payload.hostname.strip() or not 15 <= payload.check_interval_seconds <= 86400:raise HTTPException(status_code=400, detail="Hostname is required and interval must be between 15 and 86400 seconds.")+ _ensure_server_capacity(db)token = secrets.token_urlsafe(32)token_hash = hashlib.sha256(token.encode()).hexdigest()server = Server(owner_id=user["id"], hostname=payload.hostname.strip()[:255], ip_address=payload.ip_address, check_interval_seconds=payload.check_interval_seconds, collector_token_hash=token_hash)@@ -1482,6 +1569,128 @@ def _whole_number(value, low: int, high: int) -> int | None:return value if isinstance(value, int) and not isinstance(value, bool) and low <= value <= high else None+def _finite_number(value, low: float, high: float) -> float | None:+ """A real number inside [low, high], or None for anything else: text, booleans, NaN, infinity, out of range."""+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ return None+ try:+ number = float(value)+ except OverflowError: # an integer too large for a float+ return None+ return number if math.isfinite(number) and low <= number <= high else None+++# What a collector may report for the host, as (lowest, highest). Anything outside becomes unknown (None).+HOST_NUMBER_LIMITS = {+ "cpu_utilization_pct": (0, 100), "ram_pct": (0, 100), "swap_pct": (0, 100), "disk_usage_pct": (0, 100), "disk_inodes_pct": (0, 100),+ "load_1m": (0, 1e6), "load_5m": (0, 1e6), "load_15m": (0, 1e6),+ "ram_used_gb": (0, 1e9), "ram_available_gb": (0, 1e9),+ "net_bytes_sent_mb": (0, 1e12), "net_bytes_recv_mb": (0, 1e12), "system_uptime_seconds": (0, 1e10),+}+MAX_MOUNTS_PER_CHECKIN = 64+INT_MAX = 2**31 - 1 # the database's INTEGER columns+++def _clean_host_numbers(fields: dict) -> None:+ """Range-check every number a collector reported about the host. A single NaN or Infinity stored here would+ make every page that reads the latest sample fail for every user, so nothing unchecked is stored."""+ for key, (low, high) in HOST_NUMBER_LIMITS.items():+ if key in fields:+ fields[key] = _finite_number(fields[key], low, high)+++def _clean_mount(raw) -> dict | None:+ """One filesystem record reduced to known fields of the right type and size, or None if unusable."""+ if not isinstance(raw, dict) or not isinstance(raw.get("mount"), str):+ return None+ mount = _printable(raw["mount"], 255)+ if not mount.startswith("/"):+ return None+ fs_type = raw.get("fs_type")+ return {+ "mount": mount, "fs_type": (_printable(fs_type, 64) or None) if isinstance(fs_type, str) else None,+ "total_gb": _finite_number(raw.get("total_gb"), 0, 1e9), "used_gb": _finite_number(raw.get("used_gb"), 0, 1e9),+ "used_pct": _finite_number(raw.get("used_pct"), 0, 100), "inodes_pct": _finite_number(raw.get("inodes_pct"), 0, 100),+ }+++def _clean_mounts(raw) -> list[dict]:+ """At most MAX_MOUNTS_PER_CHECKIN valid, distinct filesystems."""+ seen: set[str] = set()+ cleaned = []+ for item in raw if isinstance(raw, list) else []:+ mount = _clean_mount(item)+ if mount and mount["mount"] not in seen:+ seen.add(mount["mount"])+ cleaned.append(mount)+ if len(cleaned) >= MAX_MOUNTS_PER_CHECKIN:+ break+ return cleaned+++def _apply_server_fields(db, server: Server, reported: dict) -> None:+ """Copy the descriptive fields a collector reports onto its server, each checked, never trusted.++ A hostname that another server already uses is ignored, so one collector can't pose as another machine in+ alert titles.+ """+ hostname = reported.get("hostname")+ if isinstance(hostname, str) and (name := _printable(hostname, 255)):+ taken = db.query(Server.id).filter(func.lower(Server.hostname) == name.lower(), Server.id != server.id).first()+ if not taken:+ server.hostname = name+ address = reported.get("ip_address")+ if isinstance(address, str):+ try:+ server.ip_address = str(ipaddress.ip_address(address.strip()))+ except ValueError:+ pass+ os_info = reported.get("os_info")+ if isinstance(os_info, str) and (text := _printable(os_info, 255)):+ server.os_info = text+ if (cores := _whole_number(reported.get("cpu_cores"), 1, 4096)) is not None:+ server.cpu_cores = cores+ if (ram := _finite_number(reported.get("total_ram_gb"), 0, 1e6)) is not None:+ server.total_ram_gb = ram+++ENROLL_RATE_LIMIT = 30+ENROLL_RATE_WINDOW_SECONDS = 3600+CREDENTIALS_REPLACED_KIND = "credentials_replaced"+++def _soft_limit(*, scope: str, subject, limit: int, window_seconds: int) -> None:+ """Count an attempt and refuse with 429 past the limit. Doesn't get in the way if Redis itself is down."""+ try:+ enforce_limit(redis_client, scope=scope, subject=subject, limit=limit, window_seconds=window_seconds)+ except HTTPException as exc:+ if exc.status_code == 429:+ raise+ # 503 means the counter itself is unavailable (Redis down); that must not stop servers from enrolling+ except Exception:+ return+++def _ensure_server_capacity(db) -> None:+ """Refuse to add yet another server once the install holds MAX_SERVERS, however it is being added."""+ if (db.query(func.count(Server.id)).scalar() or 0) >= MAX_SERVERS:+ raise HTTPException(status_code=409, detail=f"This install already has the most servers it allows ({MAX_SERVERS}). Remove one first, or raise MAX_SERVERS.")+++def _enforce_ingest_spacing(server: Server) -> None:+ """Refuse a check-in that follows the previous one too closely. Runs after authentication, so only the+ server's own collector can use up its slot."""+ if INGEST_MIN_SPACING_RATIO <= 0:+ return+ spacing = max(INGEST_MIN_SPACING_SECONDS, int(server.check_interval_seconds * INGEST_MIN_SPACING_RATIO))+ try:+ allowed = redis_client.set(f"homelab:ingest:{server.id}", "1", nx=True, ex=spacing)+ except Exception: # losing the limit during a Redis outage is better than losing the monitoring+ return+ if not allowed:+ raise HTTPException(status_code=429, detail="Check-ins are arriving faster than this server's interval allows.", headers={"Retry-After": str(spacing)})++def _clean_container(raw, now: datetime) -> dict | None:"""One container record reduced to known fields of the right type and size, or None if unusable.@@ -1580,6 +1789,9 @@ def _clean_system_fields(fields: dict) -> None:for key, kind in (("oom_kill_total", int), ("kernel_tainted", int), ("ntp_synced", bool), ("reboot_required", bool)):if key in fields and not (isinstance(fields[key], kind) and (kind is bool or not isinstance(fields[key], bool))):fields[key] = None+ for key in ("oom_kill_total", "kernel_tainted"):+ if key in fields:+ fields[key] = _whole_number(fields[key], 0, INT_MAX)if "last_shutdown" in fields and fields["last_shutdown"] not in {"clean", "unclean", "unknown"}:fields["last_shutdown"] = Noneif "docker_status" in fields and fields["docker_status"] not in DOCKER_STATUSES:@@ -1599,7 +1811,7 @@ def _clean_system_fields(fields: dict) -> None:@app.post("/monitoring/metrics/ingest", dependencies=[Depends(require_collector_listener)])-def ingest_metrics(payload: MetricsIngestRequest, authorization: Annotated[str | None, Header()] = None, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):+def ingest_metrics(payload: MetricsIngestRequest, authorization: Annotated[str | None, Header()] = None, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db), request: Request = None):server = db.query(Server).filter(Server.id == payload.server_id).first()if not server:raise HTTPException(status_code=404, detail="Server not found.")@@ -1609,16 +1821,18 @@ def ingest_metrics(payload: MetricsIngestRequest, authorization: Annotated[str |passelse:_require_admin(session_id, db)- for field in ("hostname", "ip_address", "os_info", "cpu_cores", "total_ram_gb"):- if field in payload.server and payload.server[field] is not None:- setattr(server, field, payload.server[field])- # Only one server can be the dashboard's own machine; the latest collector to claim it wins.- server.is_dashboard_host = payload.server.get("dashboard_host") is True+ _enforce_ingest_spacing(server)+ _apply_server_fields(db, server, payload.server)+ # Only the stack's own collector, which reaches the backend through the gate's internal listener, may claim to+ # be the dashboard's machine; a collector coming in over the VPN can't take that place. (With a single+ # listener, in the development stack, there is no way to tell, so the claim is accepted.)+ server.is_dashboard_host = payload.server.get("dashboard_host") is True and _collector_via(request) in ("internal", "")if server.is_dashboard_host:db.query(Server).filter(Server.id != server.id, Server.is_dashboard_host.is_(True)).update({"is_dashboard_host": False}, synchronize_session=False)now = datetime.now(timezone.utc)host_fields = {k: v for k, v in payload.host.items() if k in HostMetric.__table__.columns.keys() and k not in {"id", "server_id", "time"}}_clean_system_fields(host_fields)+ _clean_host_numbers(host_fields)previous = db.query(HostMetric).filter(HostMetric.server_id == server.id).order_by(HostMetric.time.desc(), HostMetric.id.desc()).first()# Only a collector that found the system helper sends its events; then they replace the OOM counter.helper_active = isinstance(payload.host.get("helper_events"), list)@@ -1629,11 +1843,8 @@ def ingest_metrics(payload: MetricsIngestRequest, authorization: Annotated[str |if host_fields.get("boot_id") and host_fields.get("last_shutdown") in REBOOT_DETAILS:db.query(SystemEvent).filter(SystemEvent.server_id == server.id, SystemEvent.event_key == f"{REBOOT_KEY_PREFIX}{host_fields['boot_id']}").update({"detail": REBOOT_DETAILS[host_fields["last_shutdown"]]}, synchronize_session=False)db.add(HostMetric(server_id=server.id, time=now, **host_fields))- mounts = payload.host.get("mounts")- for mount in mounts if isinstance(mounts, list) else []:- if isinstance(mount, dict) and isinstance(mount.get("mount"), str) and mount["mount"]:- allowed = {k: v for k, v in mount.items() if k in MountMetric.__table__.columns.keys() and k not in {"id", "server_id", "time"}}- db.add(MountMetric(server_id=server.id, time=now, **allowed))+ for mount in _clean_mounts(payload.host.get("mounts")):+ db.add(MountMetric(server_id=server.id, time=now, **mount))containers = [clean for clean in (_clean_container(raw, now) for raw in payload.containers[:MAX_CONTAINERS_PER_CHECKIN]) if clean]# Compare with the previous check-in before this one's rows exist.previous_containers = latest_containers(db, server.id, previous.time) if previous else []@@ -1745,26 +1956,30 @@ def delete_conversation(conversation_id: str, session_id: Annotated[str | None,return {"status": "deleted"}+LOG_WRITE_LIMIT = 120++@app.post("/logs")def create_log(- payload: dict,+ payload: LogCreateRequest,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.")+ enforce_limit(redis_client, scope="logs-user", subject=user["id"], limit=LOG_WRITE_LIMIT, window_seconds=3600)return record_audit_log(db,user_id=user["id"],- level=str(payload.get("level", "INFO")).upper(),- message=str(payload.get("message", "New event")),- source=str(payload.get("source", "dashboard")),- task_title=str(payload.get("task_title") or payload.get("message", "New task")),- steps=[str(step) for step in payload.get("steps", []) if str(step).strip()],- conversation_id=payload.get("conversation_id"),- event_type=payload.get("event_type"),+ level=payload.level,+ message=payload.message,+ source="dashboard",+ task_title=payload.task_title or payload.message[:255],+ steps=[step for step in payload.steps if step.strip()],+ conversation_id=payload.conversation_id,+ event_type=payload.event_type or None,)diff --git a/src/backend/rate_limit.py b/src/backend/rate_limit.pyindex ce09cf4..99feb58 100644--- a/src/backend/rate_limit.py+++ b/src/backend/rate_limit.py@@ -56,6 +56,16 @@ def enforce_limit(redis_client, *, scope: str, subject: str, limit: int, window_return key+def refund_attempt(redis_client, key: str) -> None:+ """Give back one attempt, for an attempt that turned out to be fine. Unlike a reset this can't be used to+ clear the failures that came before it: the count of wrong guesses in the window stays as it was."""+ try:+ if redis_client.decr(key) < 0:+ redis_client.incr(key)+ except Exception:+ pass++def reset_limits(redis_client, *keys: str) -> None:try:redis_client.delete(*keys)diff --git a/src/backend/rules.py b/src/backend/rules.pyindex dc76b40..9db41ad 100644--- a/src/backend/rules.py+++ b/src/backend/rules.py@@ -277,6 +277,12 @@ def system_rules(db, server, thresholds: dict, now: datetime, active_keys: frozeCRITICAL if len(oom) >= 3 else WARNING, f"{host} is killing processes to free memory",f"The kernel OOM killer fired {len(oom)} time(s) in the last {thresholds['event_window_minutes']} minutes ({'; '.join(dict.fromkeys(event.detail for event in oom[:3]))}). Check which containers or processes are using the most memory.",)+ if replaced := [event for event in events if event.kind == "credentials_replaced"]:+ firing[f"{SYSTEM_RULE_PREFIX}credentials"] = (+ WARNING, f"The credentials of {host} were replaced",+ f"At {replaced[0].time:%Y-%m-%d %H:%M} UTC the enrollment key was used to give this server new credentials, which signed its previous collector out. "+ "That is expected when you reinstalled it with the key. If you did not, treat the enrollment key as compromised: rotate it under Connect a server → Advanced, and check the machine.",+ )if faults := taint_faults(latest.kernel_tainted):# The taint flags stay set until the next boot, so this alert clears on reboot.firing[f"{SYSTEM_RULE_PREFIX}kernel"] = (WARNING, f"Kernel on {host} reported faults", f"The kernel has flagged: {', '.join(faults)}. Check dmesg on the host for details; the flag clears after a reboot.")diff --git a/src/frontend/src/App.jsx b/src/frontend/src/App.jsxindex a17e05e..2005346 100644--- a/src/frontend/src/App.jsx+++ b/src/frontend/src/App.jsx@@ -733,8 +733,8 @@ function ContainerSection({ server, open, onToggle }) {}const TAINT_FAULT_BITS = [4, 5, 7, 9, 14]-const SYSTEM_EVENT_LABELS = { reboot: 'Reboot', oom_kill: 'OOM kill', kernel_fault: 'Kernel fault', kernel_error: 'Kernel error' }-const SYSTEM_EVENT_CLASSES = { reboot: 'text-sky-300', oom_kill: 'text-amber-300', kernel_fault: 'text-red-300', kernel_error: 'text-amber-300' }+const SYSTEM_EVENT_LABELS = { reboot: 'Reboot', oom_kill: 'OOM kill', kernel_fault: 'Kernel fault', kernel_error: 'Kernel error', credentials_replaced: 'Credentials replaced' }+const SYSTEM_EVENT_CLASSES = { reboot: 'text-sky-300', oom_kill: 'text-amber-300', kernel_fault: 'text-red-300', kernel_error: 'text-amber-300', credentials_replaced: 'text-amber-300' }const CHIP_CLASSES = { ok: 'text-emerald-300', warn: 'text-amber-300', info: 'text-sky-300', unknown: 'text-[#7f8589]' }function formatAgo(value) {@@ -2345,7 +2345,16 @@ function TwoFactorSection({ status, reload, onEnrolled }) {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 [askPassword, setAskPassword] = useState(false)+ const [setupPassword, setSetupPassword] = useState('')+ // A session that has just signed in (the forced first enrolment) needs no password; a normal one must give it again.+ const start = () => {+ if (!status.setup_required && !askPassword) { setAskPassword(true); return }+ return run(async () => {+ setSetup(await apiRequest('/auth/2fa/setup', { method: 'POST', body: JSON.stringify(status.setup_required ? {} : { password: setupPassword }) }))+ setSetupPassword(''); setAskPassword(false)+ })+ }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('')@@ -2367,7 +2376,15 @@ function TwoFactorSection({ status, reload, 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 && askPassword && (+ <form onSubmit={(event) => { event.preventDefault(); start() }} className="flex flex-wrap items-center gap-2">+ <input type="password" autoComplete="current-password" autoFocus aria-label="Your current password" placeholder="Your current password" value={setupPassword} onChange={(event) => setSetupPassword(event.target.value)} className="min-h-10 w-64 max-w-full rounded-xl border border-white/10 bg-[#111417] px-3 text-sm text-white" />+ <button type="submit" disabled={busy || !setupPassword} className="rounded-xl bg-white px-4 py-2 text-sm font-medium text-slate-950 disabled:opacity-50">Continue</button>+ <button type="button" onClick={() => { setAskPassword(false); setSetupPassword('') }} className="text-xs text-[#9aa0a6] hover:text-white">Cancel</button>+ <span className="w-full text-xs text-[#7f8589]">Asked again because turning on two-factor is a sensitive change.</span>+ </form>+ )}+ {!setup && !askPassword && <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]">diff --git a/tests/conftest.py b/tests/conftest.pynew file mode 100644index 0000000..8d4c9fe--- /dev/null+++ b/tests/conftest.py@@ -0,0 +1,15 @@+"""Settings shared by every test."""+import os++os.environ.setdefault("DATABASE_URL", "sqlite://")+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")++import pytest++from src.backend import main++[email protected](autouse=True)+def _no_ingest_spacing(monkeypatch):+ """Tests send check-ins back to back, so the minimum spacing between check-ins is off unless a test turns it on."""+ monkeypatch.setattr(main, "INGEST_MIN_SPACING_RATIO", 0)diff --git a/tests/fakes.py b/tests/fakes.pyindex 72d10e4..e0701e7 100644--- a/tests/fakes.py+++ b/tests/fakes.py@@ -9,7 +9,9 @@ class FakeRedis:self.ttls: dict[str, int] = {}# strings and counters- def set(self, key, value, ex=None, **kwargs):+ def set(self, key, value, ex=None, nx=False, **kwargs):+ if nx and key in self.store:+ return Noneself.store[key] = valueif ex is not None:self.ttls[key] = ex@@ -25,6 +27,10 @@ class FakeRedis:self.ttls.pop(key, None)return removed+ def decr(self, key):+ self.store[key] = int(self.store.get(key, 0)) - 1+ return self.store[key]+def incr(self, key):self.store[key] = int(self.store.get(key, 0)) + 1return self.store[key]diff --git a/tests/test_account_security.py b/tests/test_account_security.pyindex 9922b3f..7ce99b9 100644--- a/tests/test_account_security.py+++ b/tests/test_account_security.py@@ -260,7 +260,7 @@ def _signed_in(email="[email protected]"):def _enroll(app, client):- secret = client.post("/auth/2fa/setup").json()["secret"]+ secret = client.post("/auth/2fa/setup", json={"password": PASSWORD}).json()["secret"]response = client.post("/auth/2fa/enable", json={"code": totp.code_at(secret, app.clock["now"])})assert response.status_code == 200, response.textreturn secret, response.json()["recovery_codes"]@@ -334,7 +334,7 @@ def test_when_no_key_is_configured_two_factor_is_not_enforced_and_cannot_be_set_assert _login(client).json()["setup_required"] is Falseassert client.get("/monitoring/overview").status_code == 200assert client.get("/auth/2fa/status").json()["available"] is False- assert client.post("/auth/2fa/setup").status_code == 503+ assert client.post("/auth/2fa/setup", json={"password": PASSWORD}).status_code == 503def test_the_policy_can_be_turned_off_and_defaults_to_on(app):@@ -378,7 +378,7 @@ def test_enrolling_upgrades_the_session_and_rotates_its_id(app):def test_a_wrong_code_does_not_enable_two_factor(app):client = _signed_in()- client.post("/auth/2fa/setup")+ client.post("/auth/2fa/setup", json={"password": PASSWORD})user_before = app.db.get(User, 1).totp_enabledresponse = client.post("/auth/2fa/enable", json={"code": "000000"})@@ -449,7 +449,7 @@ def test_a_code_cannot_be_replayed(app):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"]+ secret = client.post("/auth/2fa/setup", json={"password": PASSWORD}).json()["secret"]code = totp.code_at(secret, app.clock["now"])client.post("/auth/2fa/enable", json={"code": code})@@ -562,13 +562,13 @@ 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+ assert client.post("/auth/2fa/setup", json={"password": PASSWORD}).status_code == 409 and client.post("/auth/2fa/enable", json={"code": "123456"}).status_code == 409def 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"]+ first = client.post("/auth/2fa/setup", json={"password": PASSWORD}).json()["secret"]+ second = client.post("/auth/2fa/setup", json={"password": PASSWORD}).json()["secret"]assert first != secondassert client.post("/auth/2fa/enable", json={"code": totp.code_at(first, app.clock["now"])}).status_code == 400@@ -788,3 +788,90 @@ 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+++# --- turning two-factor on from a normal session needs the password again ---------------------------------++def test_a_normal_session_must_give_the_password_to_set_up_two_factor(app):+ client = _signed_in("[email protected]")++ for body in (None, {}, {"password": None}, {"password": ""}, {"password": "wrong-password-entirely"}):+ response = client.post("/auth/2fa/setup", json=body) if body is not None else client.post("/auth/2fa/setup")+ assert response.status_code == 401, body+ user = app.db.get(User, 2)+ app.db.refresh(user)+ assert user.totp_secret_enc is None and user.totp_enabled is False # nothing was created+ assert any("wrong or missing password" in message for message in _audit(app))+++def test_the_right_password_starts_the_setup_from_a_normal_session(app):+ client = _signed_in("[email protected]")++ response = client.post("/auth/2fa/setup", json={"password": PASSWORD})++ assert response.status_code == 200 and len(response.json()["secret"]) == 32+++def test_a_stolen_session_cannot_lock_the_owner_out_by_enrolling_its_own_authenticator(app):+ thief = _signed_in("[email protected]") # has the session cookie but not the password++ assert thief.post("/auth/2fa/setup").status_code == 401+ assert thief.post("/auth/2fa/enable", json={"code": "123456"}).status_code == 400+ owner = TestClient(main.app)+ assert _login(owner, "[email protected]").json().get("status") != "two_factor_required" # the owner can still sign in with the password alone+++def test_wrong_passwords_while_setting_up_count_toward_the_two_factor_lockout(app):+ client = _signed_in("[email protected]")+ codes = [client.post("/auth/2fa/setup", json={"password": "nope-nope-nope-nope"}).status_code for _ in range(main.TWO_FACTOR_ATTEMPTS + 2)]++ assert codes[:main.TWO_FACTOR_ATTEMPTS] == [401] * main.TWO_FACTOR_ATTEMPTS and codes[-1] == 429+++def test_the_forced_first_enrolment_does_not_ask_for_the_password_again(app):+ client = _signed_in("[email protected]") # an administrator who must enrol: the session just passed the password++ assert client.get("/auth/me").json()["user"]["setup_required"] is True+ assert client.post("/auth/2fa/setup").status_code == 200+++# --- smaller hardening ----------------------------------------------------------------------------------++def test_turning_two_factor_off_gives_this_session_a_new_id(app):+ member = _signed_in("[email protected]")+ secret, _ = _enroll(app, member)+ before = member.cookies.get(COOKIE)++ assert member.post("/auth/2fa/disable", json={"password": PASSWORD, "code": _code(app, secret, 30)}).status_code == 200++ after = member.cookies.get(COOKIE)+ assert after and after != before+ assert main.redis_client.get(f"homelab:session:{before}") is None and member.get("/auth/me").status_code == 200+++def test_a_successful_sign_in_does_not_reset_the_address_counter(app):+ """Someone with an account of their own must not be able to reset the limit between guesses at another account."""+ attacker = TestClient(main.app)+ for _ in range(main.LOGIN_RATE_LIMIT - 1):+ assert _login(attacker, "[email protected]", "a-wrong-password-for-the-admin").status_code == 401+ assert _login(attacker, "[email protected]").status_code == 200 # their own account, from the same address++ # signing in did not buy more guesses: only the one allowed guess is left, then the address is locked out+ assert _login(attacker, "[email protected]", "the-last-allowed-guess-attempt").status_code == 401+ assert _login(attacker, "[email protected]", "another-wrong-password-attempt").status_code == 429+++def test_signing_in_successfully_does_not_use_up_the_addresss_allowance(app):+ """People behind one shared address can all sign in without locking each other out."""+ for _ in range(main.LOGIN_RATE_LIMIT * 3):+ assert _login(TestClient(main.app), "[email protected]").status_code == 200+++def test_a_successful_sign_in_still_resets_that_accounts_own_counter(app):+ client = TestClient(main.app)+ for _ in range(main.LOGIN_RATE_LIMIT - 2):+ _login(client, "[email protected]", "wrong-password-for-the-member")+ assert _login(client, "[email protected]").status_code == 200++ keys = [key for key in main.redis_client.keys("*") if "login-email" in key and "member" in key]+ assert keys == []diff --git a/tests/test_auth_backend.py b/tests/test_auth_backend.pyindex 56f3961..5df101d 100644--- a/tests/test_auth_backend.py+++ b/tests/test_auth_backend.py@@ -168,7 +168,7 @@ def test_configured_token_is_used_and_not_printed(monkeypatch):assert main._bootstrap_token_valid(session, "my-own-setup-token")[email protected]("bad", [None, "", " ", "hlb_wrong", "x" * 1000])[email protected]("bad", [None, "", " ", "hlb_wrong", "x" * 200]) # 200 is the longest the request model accepts (longer is refused before it gets here)def test_first_account_is_refused_without_the_right_token(monkeypatch, bad):main, session = _fresh(monkeypatch)main.ensure_bootstrap_token(session)diff --git a/tests/test_docker_proxy.py b/tests/test_docker_proxy.pyindex d47591f..3cafd81 100644--- a/tests/test_docker_proxy.py+++ b/tests/test_docker_proxy.py@@ -40,7 +40,7 @@ def _fresh_collector_state():# --- routing: the allow-list ---------------------------------------------------------------@pytest.mark.parametrize("target", [- "/containers/json", "/containers/json?all=1", f"/containers/{CID}/json", f"/containers/{CID}/stats?stream=false", f"/containers/{CID[:12]}/json",+ "/containers/json?all=1", f"/containers/{CID}/json", f"/containers/{CID}/stats?stream=false", f"/containers/{CID[:12]}/json",f"/containers/{CID}/stats?stream=false&one-shot=true",])def test_the_four_read_requests_are_allowed(target):@@ -49,11 +49,12 @@ def test_the_four_read_requests_are_allowed(target):@pytest.mark.parametrize("method", ["POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "get", "CONNECT"])def test_only_get_is_allowed(method):- assert proxy.route(method, "/containers/json") is None+ assert proxy.route(method, "/containers/json?all=1") is None@pytest.mark.parametrize("target", [# other endpoints, including the ones that read container contents or start things+ "/containers/json", # only the full list the collector asks for (?all=1) is allowed"/", "/version", "/info", "/images/json", "/volumes", "/networks", "/system/df", "/events", "/_ping", "/containers", "/containers/",f"/containers/{CID}/export", f"/containers/{CID}/archive?path=/etc/passwd", f"/containers/{CID}/logs", f"/containers/{CID}/top",f"/containers/{CID}/attach", f"/containers/{CID}/exec", f"/containers/{CID}/start", f"/containers/{CID}/kill", f"/containers/{CID}/changes",@@ -196,7 +197,7 @@ def test_upstream_failures_become_a_generic_502(stack):daemon.shutdown()daemon.server_close()- assert _raw(port, "GET", "/containers/json")[0] == 502+ assert _raw(port, "GET", "/containers/json?all=1")[0] == 502def test_oversized_upstream_answers_are_rejected(stack, monkeypatch):diff --git a/tests/test_enrollment_limits.py b/tests/test_enrollment_limits.pynew file mode 100644index 0000000..3c448d1--- /dev/null+++ b/tests/test_enrollment_limits.py@@ -0,0 +1,176 @@+"""The enrollment key is powerful (it can re-issue a server's credentials), so its use is rate limited, the number+of servers is capped, and replacing credentials is never silent."""+import json+import os+from datetime import datetime, timedelta, timezone++os.environ.setdefault("DATABASE_URL", "sqlite://")+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")++import pytest+from fastapi.testclient import TestClient+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker+from sqlalchemy.pool import StaticPool++from src.backend import main+from src.backend.models import AuditLog, Base, EnrollmentKey, IncidentAlert, PendingCollector, Server, SystemEvent, User+from tests.fakes import FakeRedis++KEY = "enroll-key-secret"+++def app(monkeypatch):+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)+ Base.metadata.create_all(engine)+ Session = sessionmaker(bind=engine)+ with Session() as seed:+ seed.add(User(id=1, name="Owner", email="[email protected]", password_hash="x", role="admin", is_active=True))+ seed.add(EnrollmentKey(owner_id=1, key_hash=main._hash_secret(KEY)))+ seed.add(Server(id=2, owner_id=1, hostname="existing", check_interval_seconds=60, collector_token_hash=main._hash_secret("old-token"), machine_id="machine-existing"))+ seed.commit()++ def get_db():+ session = Session()+ try:+ yield session+ finally:+ session.close()++ main.app.dependency_overrides[main.get_db] = get_db+ monkeypatch.setattr(main, "redis_client", FakeRedis())+ client = TestClient(main.app, raise_server_exceptions=False)+ client.Session = Session+ yield client+ main.app.dependency_overrides.clear()+++def enroll(client, machine_id="machine-new", hostname="new-box", key=KEY):+ return client.post("/monitoring/collectors/enroll", json={"enroll_key": key, "hostname": hostname, "machine_id": machine_id})+++def ingest(client, server_id, token):+ return client.post("/monitoring/metrics/ingest", content=json.dumps({"server_id": server_id, "host": {"cpu_utilization_pct": 3}}), headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"})+++# --- replacing credentials is never silent --------------------------------------------------------------++def test_enrolling_with_a_known_machine_id_still_works_but_signs_the_old_collector_out(app):+ response = enroll(app, "machine-existing", "whatever")++ body = response.json()+ assert response.status_code == 200 and body["server_id"] == 2 and body["collector_token"] != "old-token"+ assert ingest(app, 2, "old-token").status_code == 401+ assert ingest(app, 2, body["collector_token"]).status_code == 200+++def test_replacing_credentials_leaves_an_event_and_an_audit_entry(app):+ enroll(app, "machine-existing")++ with app.Session() as db:+ [event] = db.query(SystemEvent).filter_by(kind="credentials_replaced").all()+ assert event.server_id == 2 and "replaced" in event.detail and "enrollment key" in event.detail+ audit = db.query(AuditLog).filter_by(source="enrollment").one()+ assert audit.level == "WARNING" and "server 2" in audit.message+++def test_the_replacement_opens_a_warning_that_clears_by_itself(app):+ token = enroll(app, "machine-existing").json()["collector_token"]+ ingest(app, 2, token)++ with app.Session() as db:+ alert = db.query(IncidentAlert).filter_by(server_id=2, rule_key="system:credentials", status="active").one()+ assert alert.severity == "WARNING" and "enrollment key" in alert.description+ db.query(SystemEvent).update({SystemEvent.time: datetime.now(timezone.utc) - timedelta(hours=3)})+ db.commit()+ ingest(app, 2, token)+ with app.Session() as db:+ assert db.query(IncidentAlert).filter_by(rule_key="system:credentials", status="active").count() == 0+++def test_a_brand_new_machine_is_not_a_replacement(app):+ body = enroll(app).json()++ with app.Session() as db:+ assert db.query(SystemEvent).filter_by(kind="credentials_replaced").count() == 0+ assert db.query(AuditLog).filter_by(source="enrollment").count() == 0+ assert db.get(Server, body["server_id"]).hostname == "new-box"+++def test_the_hostname_is_made_printable_and_bounded(app):+ body = enroll(app, hostname="x" * 250 + "\x00\x07").json()++ with app.Session() as db:+ assert db.get(Server, body["server_id"]).hostname == "x" * 250 + "??" # control characters become "?"+ assert enroll(app, "machine-long", hostname="h" * 256).status_code == 422 # longer than a hostname can be: refused outright+++# --- rate limits ----------------------------------------------------------------------------------------++def test_one_address_can_only_enroll_so_often(app):+ codes = [enroll(app, f"machine-{i}", f"box{i}").status_code for i in range(main.ENROLL_RATE_LIMIT + 3)]++ assert codes[:main.ENROLL_RATE_LIMIT] == [200] * main.ENROLL_RATE_LIMIT and codes[main.ENROLL_RATE_LIMIT:] == [429] * 3+++def test_wrong_keys_count_against_the_limit_too(app):+ for i in range(main.ENROLL_RATE_LIMIT):+ assert enroll(app, f"m{i}", key="not-the-key").status_code == 401++ assert enroll(app, "later").status_code == 429+++def test_another_address_has_its_own_allowance(app):+ for i in range(main.ENROLL_RATE_LIMIT + 1):+ enroll(app, f"machine-{i}")+ other = TestClient(main.app, client=("203.0.113.9", 50000), raise_server_exceptions=False)++ assert enroll(other, "from-elsewhere").status_code == 200+++def test_the_key_itself_has_a_limit_across_addresses(app):+ limit = main.ENROLL_RATE_LIMIT * 2+ for i in range(limit):+ client = TestClient(main.app, client=(f"198.51.100.{i % 250 + 1}", 40000 + i), raise_server_exceptions=False)+ assert enroll(client, f"machine-{i}", f"box{i}").status_code == 200++ last = TestClient(main.app, client=("192.0.2.77", 1), raise_server_exceptions=False)+ assert enroll(last, "one-too-many").status_code == 429+++def test_a_redis_outage_does_not_block_enrolling(app, monkeypatch):+ class Down:+ def __getattr__(self, name):+ raise ConnectionError("redis is down")++ monkeypatch.setattr(main, "redis_client", Down())++ assert enroll(app).status_code == 200+++# --- how many servers ------------------------------------------------------------------------------------++def test_a_full_install_refuses_new_servers_but_still_serves_the_ones_it_has(app, monkeypatch):+ monkeypatch.setattr(main, "MAX_SERVERS", 2)+ assert enroll(app, "machine-a").status_code == 200 # the second server++ refused = enroll(app, "machine-b")++ assert refused.status_code == 409 and "most servers" in refused.json()["detail"]+ assert enroll(app, "machine-existing").status_code == 200 # an existing server can still be re-enrolled+ with app.Session() as db:+ assert db.query(Server).count() == 2+++def test_the_cap_applies_to_adding_by_hand_and_to_approving_requests(app, monkeypatch):+ monkeypatch.setattr(main, "MAX_SERVERS", 1)+ monkeypatch.setattr(main, "_require_admin", lambda session_id, db: {"id": 1, "role": "admin"})++ assert app.post("/monitoring/servers", json={"hostname": "manual", "check_interval_seconds": 60}).status_code == 409+ with app.Session() as db:+ pending = PendingCollector(hostname="waiting", machine_id="machine-waiting", status="pending", poll_secret_hash="x", pairing_code="ABCD2345")+ db.add(pending)+ db.commit()+ pending_id = pending.id+ assert app.post(f"/monitoring/pending-collectors/{pending_id}/approve", json={}).status_code == 409diff --git a/tests/test_ingest_validation.py b/tests/test_ingest_validation.pynew file mode 100644index 0000000..f8a35ed--- /dev/null+++ b/tests/test_ingest_validation.py@@ -0,0 +1,286 @@+"""What a collector reports is never trusted: numbers, names and filesystems are checked before they are stored,+and a collector can't flood the database or take another server's place."""+import json+import os+from datetime import datetime, timedelta, timezone++os.environ.setdefault("DATABASE_URL", "sqlite://")+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")++import pytest+from fastapi.testclient import TestClient+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker+from sqlalchemy.pool import StaticPool++from src.backend import history, main, rollups+from src.backend.models import Base, HostMetric, IncidentAlert, MountMetric, Server, User+from tests.fakes import FakeRedis++TOKENS = {1: "token-one", 2: "token-two"}+++def app(monkeypatch):+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)+ Base.metadata.create_all(engine)+ Session = sessionmaker(bind=engine)+ with Session() as seed:+ seed.add(User(id=1, name="Owner", email="[email protected]", password_hash="x", role="admin", is_active=True))+ for server_id, name in ((1, "alpha"), (2, "bravo")):+ seed.add(Server(id=server_id, owner_id=1, hostname=name, check_interval_seconds=60, collector_token_hash=main._hash_secret(TOKENS[server_id]), machine_id=f"machine-{server_id}"))+ seed.commit()++ def get_db():+ session = Session()+ try:+ yield session+ finally:+ session.close()++ main.app.dependency_overrides[main.get_db] = get_db+ monkeypatch.setattr(main, "redis_client", FakeRedis())+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: {"id": 1, "role": "admin"})+ client = TestClient(main.app, raise_server_exceptions=False)+ client.Session = Session+ yield client+ main.app.dependency_overrides.clear()+++def ingest(client, server_id, body, token=None, headers=None):+ payload = body if isinstance(body, str) else json.dumps({"server_id": server_id, **body})+ return client.post("/monitoring/metrics/ingest", content=payload, headers={"Authorization": f"Bearer {token or TOKENS[server_id]}", "Content-Type": "application/json", **(headers or {})})+++def latest(client, server_id=1):+ with client.Session() as db:+ return db.query(HostMetric).filter_by(server_id=server_id).order_by(HostMetric.id.desc()).first()+++def server(client, server_id=1):+ with client.Session() as db:+ return db.get(Server, server_id)+++# --- numbers --------------------------------------------------------------------------------------++def test_a_check_in_with_infinity_does_not_break_the_pages_for_everyone(app):+ ingest(app, 1, '{"server_id": 1, "host": {"cpu_utilization_pct": 12.5}}')++ response = ingest(app, 1, '{"server_id": 1, "host": {"ram_pct": Infinity, "load_1m": -Infinity, "swap_pct": NaN}}')++ assert response.status_code == 200+ assert latest(app).ram_pct is None and latest(app).load_1m is None and latest(app).swap_pct is None+ for path in ("/monitoring/overview", "/monitoring/servers/1/history?range=1h&metrics=ram", "/monitoring/servers/1/history?minutes=30", "/stats/servers/1/heatmap", "/stats/fleet?range=24h"):+ assert app.get(path).status_code == 200, path++[email protected]("key", sorted(main.HOST_NUMBER_LIMITS))[email protected]("bad", ["1e308", "-1", "2e12", "\"12\"", "true", "null", "[1]", "{\"a\": 1}", "1" + "0" * 400])+def test_every_host_number_outside_its_range_or_of_the_wrong_type_is_stored_as_unknown(app, key, bad):+ response = ingest(app, 1, '{"server_id": 1, "host": {"%s": %s}}' % (key, bad))++ assert response.status_code == 200+ assert getattr(latest(app), key) is None+++def test_sensible_numbers_are_stored_exactly(app):+ ingest(app, 1, {"host": {"cpu_utilization_pct": 41.5, "load_1m": 0.52, "ram_pct": 63.25, "ram_used_gb": 12.5, "disk_usage_pct": 100, "net_bytes_sent_mb": 123456.789, "system_uptime_seconds": 86400.5}})++ row = latest(app)+ assert (row.cpu_utilization_pct, row.load_1m, row.ram_pct, row.ram_used_gb, row.disk_usage_pct, row.net_bytes_sent_mb, row.system_uptime_seconds) == (41.5, 0.52, 63.25, 12.5, 100.0, 123456.789, 86400.5)++[email protected]("key", ["oom_kill_total", "kernel_tainted"])[email protected]("bad", [2**31, 2**40, -1, 10**30])+def test_counters_too_big_for_the_database_are_unknown_instead_of_an_error(app, key, bad):+ response = ingest(app, 1, {"host": {key: bad}})++ assert response.status_code == 200 and getattr(latest(app), key) is None+++def test_the_summaries_survive_whatever_was_reported(app):+ for body in ('{"server_id": 1, "host": {"cpu_utilization_pct": 1e200}}', '{"server_id": 1, "host": {"cpu_utilization_pct": 1e200}}', '{"server_id": 1, "host": {"cpu_utilization_pct": 50}}'):+ ingest(app, 1, body)+ with app.Session() as db:+ db.query(HostMetric).update({HostMetric.time: datetime.now(timezone.utc) - timedelta(days=2)})+ db.commit()+ rollups.run_rollups(db)+ assert [row.avg_cpu for row in db.query(rollups.HostRollup).filter_by(tier="hour")] == [50.0] # the absurd values were never stored+++# --- names and descriptions of the server -----------------------------------------------------------++def test_a_server_description_is_kept_only_if_it_is_sensible(app):+ ingest(app, 1, {"server": {"hostname": "alpha-new\x00\x07", "ip_address": "10.0.0.5", "os_info": "Debian 13\n(trixie)", "cpu_cores": 8, "total_ram_gb": 31.4}, "host": {}})++ row = server(app)+ assert (row.hostname, row.ip_address, row.os_info, row.cpu_cores, row.total_ram_gb) == ("alpha-new??", "10.0.0.5", "Debian 13?(trixie)", 8, 31.4)++[email protected]("reported", [+ {"cpu_cores": -5}, {"cpu_cores": 0}, {"cpu_cores": 10**9}, {"cpu_cores": True}, {"cpu_cores": "8"}, {"cpu_cores": 4.5},+ {"total_ram_gb": -1}, {"total_ram_gb": 1e30}, {"total_ram_gb": "lots"}, {"total_ram_gb": True},+ {"ip_address": "not an address"}, {"ip_address": 12345}, {"ip_address": "999.1.1.1"}, {"hostname": ""}, {"hostname": " "}, {"hostname": 12}, {"hostname": None}, {"os_info": 5},+])+def test_a_bad_server_description_leaves_what_was_known(app, reported):+ before = server(app)+ keep = (before.hostname, before.ip_address, before.os_info, before.cpu_cores, before.total_ram_gb)++ assert ingest(app, 1, {"server": reported, "host": {}}).status_code == 200++ after = server(app)+ assert (after.hostname, after.ip_address, after.os_info, after.cpu_cores, after.total_ram_gb) == keep+++def test_long_names_are_cut_to_what_fits(app):+ ingest(app, 1, {"server": {"hostname": "h" * 5000, "os_info": "o" * 5000}, "host": {}})++ row = server(app)+ assert len(row.hostname) == 255 and len(row.os_info) == 255+++def test_a_collector_cannot_take_another_servers_name(app):+ ingest(app, 1, {"server": {"hostname": "BRAVO"}, "host": {}}) # bravo is server 2's name, whatever the case++ assert server(app, 1).hostname == "alpha"+++def test_only_a_collector_on_the_internal_listener_can_claim_to_be_the_dashboards_machine(app, monkeypatch):+ monkeypatch.setattr(main, "COLLECTOR_ACCESS", "strict")+ ingest(app, 2, {"server": {"dashboard_host": True}, "host": {}}, headers={"X-Collector-Via": "internal"})+ assert server(app, 2).is_dashboard_host is True++ ingest(app, 1, {"server": {"dashboard_host": True}, "host": {}}, headers={"X-Collector-Via": "vpn"}) # a remote collector++ assert server(app, 1).is_dashboard_host is False and server(app, 2).is_dashboard_host is True+++def test_in_the_development_stack_the_claim_is_accepted_as_before(app):+ ingest(app, 1, {"server": {"dashboard_host": True}, "host": {}})++ assert server(app, 1).is_dashboard_host is True+++# --- filesystems -------------------------------------------------------------------------------------++def mounts(client, server_id=1):+ with client.Session() as db:+ return db.query(MountMetric).filter_by(server_id=server_id).order_by(MountMetric.id).all()+++def test_at_most_sixty_four_filesystems_are_stored_per_check_in(app):+ many = [{"mount": f"/m{i}", "used_pct": 99.0, "total_gb": 10, "used_gb": 9.9} for i in range(3000)]++ assert ingest(app, 1, {"host": {"mounts": many}}).status_code == 200++ assert len(mounts(app)) == main.MAX_MOUNTS_PER_CHECKIN == 64+++def test_a_filesystem_is_stored_once_and_only_with_known_good_fields(app):+ ingest(app, 1, {"host": {"mounts": [+ {"mount": "/data", "fs_type": "ext4", "total_gb": 100, "used_gb": 40, "used_pct": 40, "inodes_pct": 5, "id": 999, "server_id": 2, "time": "2001-01-01T00:00:00", "extra": "x"},+ {"mount": "/data", "used_pct": 1},+ ]}})++ [row] = mounts(app)+ assert (row.mount, row.fs_type, row.total_gb, row.used_pct, row.server_id) == ("/data", "ext4", 100.0, 40.0, 1) and row.id != 999 and row.time.year != 2001+ assert mounts(app, 2) == []++[email protected]("mount", [{"mount": "relative/path"}, {"mount": ""}, {"mount": 5}, {"mount": None}, {"nothing": 1}, "text", 7, None, ["/x"]])+def test_filesystem_records_that_are_not_usable_are_skipped(app, mount):+ assert ingest(app, 1, {"host": {"mounts": [mount, {"mount": "/ok", "used_pct": 1}]}}).status_code == 200++ assert [row.mount for row in mounts(app)] == ["/ok"]++[email protected]("bad", ["1e308", "-1", "101", "\"x\"", "true", "null", "Infinity", "NaN"])+def test_filesystem_numbers_outside_their_range_are_unknown(app, bad):+ ingest(app, 1, '{"server_id": 1, "host": {"mounts": [{"mount": "/data", "used_pct": %s, "inodes_pct": %s, "total_gb": %s, "used_gb": %s}]}}' % (bad, bad, bad, bad))++ [row] = mounts(app)+ assert (row.used_pct, row.inodes_pct) == (None, None)+ assert (row.total_gb, row.used_gb) == ((101.0, 101.0) if bad == "101" else (None, None)) # 101 is a fine size in GB, only a bad percentage+++def test_mount_names_are_made_printable_and_bounded(app):+ ingest(app, 1, {"host": {"mounts": [{"mount": "/" + "d" * 600 + "\x00", "fs_type": "t" * 300}]}})++ [row] = mounts(app)+ assert len(row.mount) == 255 and len(row.fs_type) == 64 and "\x00" not in row.mount+++# --- how often, and how many --------------------------------------------------------------------------++def spaced(monkeypatch):+ monkeypatch.setattr(main, "INGEST_MIN_SPACING_RATIO", 0.25)+++def test_a_check_in_that_follows_the_last_one_too_closely_is_refused(app, spaced):+ assert ingest(app, 1, {"host": {}}).status_code == 200++ again = ingest(app, 1, {"host": {}})++ assert again.status_code == 429 and again.headers["Retry-After"] == "15" # a quarter of the 60 s interval+ assert ingest(app, 2, {"host": {}}).status_code == 200 # another server has its own slot+++def test_the_next_check_in_is_accepted_when_the_slot_has_passed(app, spaced):+ ingest(app, 1, {"host": {}})+ main.redis_client.delete("homelab:ingest:1") # the key expires after the spacing++ assert ingest(app, 1, {"host": {}}).status_code == 200+++def test_the_spacing_is_never_shorter_than_the_minimum(app, spaced):+ with app.Session() as db:+ db.get(Server, 1).check_interval_seconds = 15+ db.commit()+ ingest(app, 1, {"host": {}})++ assert ingest(app, 1, {"host": {}}).headers["Retry-After"] == "5"+++def test_someone_without_the_token_cannot_use_up_a_servers_slot(app, spaced, monkeypatch):+ monkeypatch.setattr(main, "_require_admin", lambda session_id, db: (_ for _ in ()).throw(main.HTTPException(status_code=401, detail="no")))++ assert ingest(app, 1, {"host": {}}, token="wrong").status_code == 401++ assert ingest(app, 1, {"host": {}}).status_code == 200 # the real collector is not held up+++def test_a_redis_outage_does_not_stop_check_ins(app, spaced, monkeypatch):+ class Down:+ def set(self, *args, **kwargs):+ raise ConnectionError("redis is down")++ monkeypatch.setattr(main, "redis_client", Down())++ assert ingest(app, 1, {"host": {}}).status_code == 200 and ingest(app, 1, {"host": {}}).status_code == 200+++def test_one_server_with_a_flood_of_alerts_cannot_hide_everyone_elses(app):+ with app.Session() as db:+ db.add_all(IncidentAlert(server_id=1, severity="CRITICAL", title=f"flood {i}", description="d", rule_key=f"host:disk:/m{i}", status="active") for i in range(100))+ db.add(IncidentAlert(server_id=2, severity="WARNING", title="the real problem", description="d", rule_key="host:memory", status="active"))+ db.commit()++ overview = app.get("/monitoring/overview").json()++ titles = [alert["title"] for alert in overview["alerts"]]+ assert "the real problem" in titles and sum(1 for alert in overview["alerts"] if alert["server_id"] == 1) == main.OVERVIEW_ALERTS_PER_SERVER+ assert overview["alert_count"] == 101 # the true total is still shown+++def test_one_query_never_reads_more_raw_rows_than_the_backstop(app, monkeypatch):+ with app.Session() as db:+ now = datetime.now(timezone.utc)+ db.add_all(HostMetric(server_id=1, time=now - timedelta(minutes=i), cpu_utilization_pct=1.0) for i in range(500))+ db.commit()+ monkeypatch.setattr(history, "MAX_RAW_ROWS", 100)++ result = history.history(db, history.HOST, 1, None, "24h", ("cpu",), 60)++ assert sum(point["samples"] for point in result["points"]) == 100diff --git a/tests/test_input_limits.py b/tests/test_input_limits.pynew file mode 100644index 0000000..627a333--- /dev/null+++ b/tests/test_input_limits.py@@ -0,0 +1,148 @@+"""Request bodies have sizes and shapes: nothing is stored or processed just because someone sent it."""+import os++os.environ.setdefault("DATABASE_URL", "sqlite://")+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")++import pytest+from fastapi.testclient import TestClient+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker+from sqlalchemy.pool import StaticPool++from src.backend import main+from src.backend.models import AuditLog, Base, User+from tests.fakes import FakeRedis+++def app(monkeypatch):+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)+ Base.metadata.create_all(engine)+ Session = sessionmaker(bind=engine)+ with Session() as seed:+ seed.add(User(id=1, name="Member", email="[email protected]", password_hash="x", role="user", is_active=True))+ seed.commit()++ def get_db():+ session = Session()+ try:+ yield session+ finally:+ session.close()++ main.app.dependency_overrides[main.get_db] = get_db+ monkeypatch.setattr(main, "redis_client", FakeRedis())+ monkeypatch.setattr(main, "get_user_from_session", lambda redis_client, session_id: {"id": 1, "role": "user"} if session_id else None)+ client = TestClient(main.app, raise_server_exceptions=False, cookies={main.SESSION_COOKIE_NAME: "a-session"})+ client.Session = Session+ yield client+ main.app.dependency_overrides.clear()+++def entries(client):+ with client.Session() as db:+ return db.query(AuditLog).filter(AuditLog.source == "dashboard").all()+++# --- POST /logs ---------------------------------------------------------------------------------------++def test_a_sensible_log_entry_is_stored_under_the_dashboard_source(app):+ response = app.post("/logs", json={"level": "warning", "message": "Opened the report", "steps": ["one", " ", "two"], "event_type": "report_opened", "source": "auth"})++ assert response.status_code == 200+ [entry] = entries(app)+ assert (entry.level, entry.message, entry.source, entry.event_type) == ("WARNING", "Opened the report", "dashboard", "report_opened")+++def test_nobody_can_write_entries_that_look_like_they_came_from_another_part_of_the_system(app):+ app.post("/logs", json={"message": "Admin changed the thresholds", "source": "admin", "event_type": "admin"})+ app.post("/logs", json={"message": "x", "source": "auth"})++ assert {entry.source for entry in entries(app)} == {"dashboard"}++[email protected]("body", [+ {"message": "x" * 2001}, {"task_title": "t" * 256}, {"steps": ["s"] * 51}, {"steps": ["s" * 1001]}, {"steps": "not a list"}, {"steps": [1, 2]},+ {"level": "SURPRISE"}, {"level": 5}, {"event_type": "has spaces"}, {"event_type": "Upper"}, {"event_type": "e" * 51}, {"conversation_id": "c" * 256},+ {"message": ["a", "list"]}, {"message": None},+])+def test_log_entries_outside_the_limits_are_refused_and_nothing_is_stored(app, body):+ assert app.post("/logs", json=body).status_code == 422+ assert entries(app) == []+++def test_a_megabyte_message_is_refused(app):+ assert app.post("/logs", json={"message": "m" * 1_000_000}).status_code == 422+++def test_writing_log_entries_is_rate_limited_per_user(app):+ codes = [app.post("/logs", json={"message": f"entry {i}"}).status_code for i in range(main.LOG_WRITE_LIMIT + 2)]++ assert codes[:main.LOG_WRITE_LIMIT] == [200] * main.LOG_WRITE_LIMIT and codes[-2:] == [429, 429]+++def test_log_entries_need_a_session(app):+ app.cookies.clear()++ assert app.post("/logs", json={"message": "x"}).status_code == 401+++# --- other bodies ---------------------------------------------------------------------------------------+[email protected]("path, body", [+ ("/agent/chat", {"conversation_id": "c" * 256, "message": "hi"}),+ ("/agent/chat", {"conversation_id": "c", "message": "m" * 8001}),+ ("/conversations", {"conversation_id": "c" * 256}),+ ("/conversations", {"conversation_id": "c", "title": "t" * 256}),+ ("/auth/login", {"email": "[email protected]", "password": "p" * 1025}),+ ("/auth/register", {"name": "n" * 256, "email": "[email protected]", "password": "p" * 20}),+ ("/auth/register", {"name": "n", "email": "[email protected]", "password": "p" * 1025}),+ ("/auth/register", {"name": "n", "email": "[email protected]", "password": "p" * 20, "bootstrap_token": "t" * 201}),+ ("/monitoring/collectors/enroll", {"enroll_key": "k" * 201, "hostname": "h"}),+ ("/monitoring/collectors/enroll", {"enroll_key": "k", "hostname": "h" * 256}),+ ("/monitoring/collectors/enroll", {"enroll_key": "k", "hostname": "h", "machine_id": "m" * 65}),+ ("/monitoring/collectors/register", {"hostname": "h" * 256}),+ ("/monitoring/collectors/register", {"hostname": "h", "os_info": "o" * 256}),+ ("/monitoring/collectors/register", {"hostname": "h", "join_token": "j" * 201}),+ ("/monitoring/servers", {"hostname": "h" * 256}),+ ("/monitoring/servers", {"hostname": "h", "ip_address": "1" * 65}),+])+def test_oversized_fields_in_other_bodies_are_refused_before_any_work_is_done(app, path, body):+ assert app.post(path, json=body).status_code == 422+++# --- safer defaults and smaller leaks ---------------------------------------------------------------------++def test_registration_is_closed_unless_someone_opens_it(monkeypatch):+ import importlib++ from src.backend import config++ monkeypatch.delenv("ALLOW_REGISTRATION", raising=False)+ monkeypatch.delenv("ENABLE_API_DOCS", raising=False)+ monkeypatch.delenv("CORS_ORIGINS", raising=False)+ reloaded = importlib.reload(config)+ try:+ assert reloaded.ALLOW_REGISTRATION is False and reloaded.ENABLE_API_DOCS is False and reloaded.CORS_ORIGINS == []+ monkeypatch.setenv("ALLOW_REGISTRATION", "true")+ assert importlib.reload(config).ALLOW_REGISTRATION is True+ finally:+ monkeypatch.delenv("ALLOW_REGISTRATION", raising=False)+ importlib.reload(config)+++def test_the_api_documentation_is_not_served_to_anonymous_visitors(app):+ for path in ("/docs", "/openapi.json", "/redoc"):+ assert app.get(path).status_code == 404, path+++def test_an_open_registration_is_called_out_in_the_log(app, monkeypatch):+ with app.Session() as db:+ monkeypatch.setattr(main, "ALLOW_REGISTRATION", False)+ assert main.registration_warning(db) is None+ monkeypatch.setattr(main, "ALLOW_REGISTRATION", True)+ assert "SECURITY WARNING" in main.registration_warning(db) and "ALLOW_REGISTRATION=false" in main.registration_warning(db)+ db.query(User).delete()+ db.commit()+ assert main.registration_warning(db) is None # a fresh install has nobody to protect yetdiff --git a/tests/test_pending_collectors.py b/tests/test_pending_collectors.pyindex 6580b1c..320b61f 100644--- a/tests/test_pending_collectors.py+++ b/tests/test_pending_collectors.py@@ -260,7 +260,7 @@ def test_vpn_listener_refuses_registration_without_a_token(db, strict):assert db.query(PendingCollector).count() == 0[email protected]("bad", ["", "hlj_nonsense", "x" * 500])[email protected]("bad", ["", "hlj_nonsense", "x" * 200]) # 200 is the longest the request model acceptsdef test_wrong_tokens_are_refused(db, strict, bad):_mint(db)with pytest.raises(HTTPException) as exc: