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): close the hardening leftovers from the first security review
Karlo Kajba Šimanić63b4308e75c1
diff --git a/TESTS.md b/TESTS.mdindex 7d7fa94..0eac091 100644--- a/TESTS.md+++ b/TESTS.md@@ -4,7 +4,7 @@ Infradeck ships with an automated test suite. This page explains how to run it,covers (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.-- **1409 test cases** from 762 test functions, plus 38 small tests of the frontend helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).+- **1418 test cases** from 770 test functions, plus 38 small tests of the frontend helpers (see [Frontend helper tests](#frontend-helper-tests)) (some functions run once per input).- **About two minutes** to run. No Docker, PostgreSQL, Redis, network or root access needed.- **Safe to run next to a live install.** The tests use a throwaway in-memory databaseand fakes; they never touch your running containers or your data. (Two collector@@ -135,7 +135,7 @@ side and the backend's side in one file, because the feature only works when bot| `tests/monitoring/` | What is watched and how it turns into incidents: the alert engine and its rules, system, container and network checks, the system helper and the container details. || `tests/history/` | Long-term history: rollups, the history API, statistics and the database indexes behind them. || `tests/assistant/` | The AI assistant: its fixed health checks, error messages and conversations. |-| `tests/security/` | Tests written from security reviews that cut across areas: request size limits and the second review's findings. |+| `tests/security/` | Tests written from security reviews that cut across areas: request size limits, the second review's findings and the nginx security headers. |`tests/conftest.py` (settings every test shares) and `tests/fakes.py` (the fake Redis) stay at the top.The chart helper tests for the frontend are separate, in `src/frontend/tests/`.@@ -144,7 +144,7 @@ The chart helper tests for the frontend are separate, in `src/frontend/tests/`.| File | Cases | Protects ||---|---|---|-| [`test_account_security.py`](#test_account_securitypy) | 136 | Two-factor sign-in, recovery codes, encrypted secrets, sessions you can review and end, password change, and the password check before turning two-factor on. |+| [`test_account_security.py`](#test_account_securitypy) | 146 | 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) | 5 | Helpful, non-leaking error messages from the AI assistant. || [`test_agent_service.py`](#test_agent_servicepy) | 9 | The assistant can only run the fixed read-only checks; the OpenAI provider and conversation history. |@@ -158,7 +158,7 @@ The chart helper tests for the frontend are separate, in `src/frontend/tests/`.| [`test_conversations.py`](#test_conversationspy) | 1 | Deleting one assistant conversation leaves the others alone. || [`test_container_checks.py`](#test_container_checkspy) | 126 | Docker health, container exit codes, inventory and image changes, memory-leak trends, and the validation of everything a collector sends about containers. || [`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_docker_proxy.py`](#test_docker_proxypy) | 119 | The read-only Docker proxy: what it allows, refuses and hides, and how it limits its own clients. || [`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. |@@ -167,6 +167,7 @@ The chart helper tests for the frontend are separate, in `src/frontend/tests/`.| [`test_migrations.py`](#test_migrationspy) | 5 | Database migrations: new and pre-migration databases both end at the latest revision with the models' schema. || [`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_nginx_headers.py`](#test_nginx_headerspy) | 4 | The development and server nginx send the same security headers, HSTS only on the server one. || [`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. |@@ -245,6 +246,9 @@ out of their own install.| `test_when_no_key_is_configured_two_factor_is_not_enforced_and_cannot_be_set_up` | Without a key the "require 2FA" policy isn't enforced (no lock-out) and setup says why it can't proceed. || `test_the_policy_can_be_turned_off_and_defaults_to_on` | "Require two-factor for admins" is on by default and an admin can switch it off. || `test_admins_can_change_the_policy_and_it_is_audited` | Policy changes are admin-only and recorded in the log. |+| `test_switching_the_admin_policy_on_signs_out_admins_without_two_factor` | Switching the admin policy on ends the sessions of admins who haven't set two-factor up, so they sign in again and land on the setup; members stay signed in. The sign-out is recorded in the log. |+| `test_admins_who_already_use_two_factor_stay_signed_in_when_the_policy_is_switched_on` | Admins who already use two-factor keep their sessions. |+| `test_requiring_two_factor_of_everyone_signs_out_users_without_it` | Requiring two-factor of everyone does the same for members. || `test_the_policy_only_applies_to_administrators` | Members are never forced to enrol. || `test_an_admin_without_two_factor_gets_a_limited_session_when_it_is_required` | An admin who hasn't enrolled can sign in, but only to set up two-factor. || `test_enrolling_upgrades_the_session_and_rotates_its_id` | Finishing enrolment turns the limited session into a full one with a new ID. |@@ -597,6 +601,8 @@ tested hardest (91 cases). If any of these fail, do not run the proxy until it i| `test_oversized_upstream_answers_are_rejected` | A huge answer from Docker is rejected instead of being passed on. || `test_proxy_socket_is_not_world_accessible_and_replaces_a_stale_one` | The proxy's socket file is created with owner and group access only, and a leftover socket from a crash is replaced. || `test_collector_still_supports_the_plain_socket_path` | The collector still works without Docker access (it just reports no containers). |+| `test_a_stalled_client_is_dropped` | A client that connects and sends nothing is disconnected after the timeout instead of holding the connection open. |+| `test_connections_beyond_the_limit_are_closed_until_a_slot_frees` | Connections beyond the limit are closed at once, and served again as soon as an earlier one ends. |### test_enrollment.py@@ -744,6 +750,17 @@ Request bodies have sizes and shapes, and the defaults are the safe ones.| `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_nginx_headers.py++The development nginx (`docker/nginx.conf`) and the server nginx (`docker/nginx.strict.conf`) are separate files+with the same intent. These tests catch a security header changed in one but not the other.++| Test | What it checks |+|---|---|+| `test_both_send_the_same_security_headers` | Both files send the same security headers with the same values, apart from HSTS. |+| `test_only_the_server_nginx_sends_hsts` | HSTS is sent by the server nginx (behind HTTPS) and not by the development one (plain HTTP). |+| `test_no_location_drops_the_server_wide_headers` *(2 inputs)* | No `location` block has its own `add_header`, which would silently drop the server-wide headers there. |+### test_network_checks.pyNetwork checks: the host's real traffic totals, which ports it listens on, whether it candiff --git a/docker/Caddyfile b/docker/Caddyfileindex 51b2dcf..a00aff5 100644--- a/docker/Caddyfile+++ b/docker/Caddyfile@@ -2,5 +2,8 @@# The domain's DNS must point at this server and ports 80/443 must be open.{$DOMAIN} {encode zstd gzip+ # Same value as docker/nginx.strict.conf. No includeSubDomains, since other apps on your domain may not be+ # HTTPS-only.+ header Strict-Transport-Security "max-age=15552000"reverse_proxy frontend:80}diff --git a/src/backend/main.py b/src/backend/main.pyindex e89b7cf..ac583a4 100644--- a/src/backend/main.py+++ b/src/backend/main.py@@ -552,6 +552,16 @@ def two_factor_required_for(db, role: str) -> bool:return require_two_factor_for_everyone(db) or (role == "admin" and require_admin_two_factor(db))+def end_sessions_without_two_factor(db) -> int:+ """After a two-factor rule is switched on: signs out every account it now applies to that hasn't set two-factor+ up, so they sign in again under the rule (and land on the setup). Returns how many sessions ended."""+ ended = 0+ for account in db.query(User).filter(User.totp_enabled.is_(False)):+ if two_factor_required_for(db, account.role):+ ended += revoke_other_sessions(redis_client, account.id, None)+ return ended++DISABLED_RULES_KEY = "disabled_rules"@@ -610,6 +620,7 @@ def get_admin_settings(session_id: Annotated[str | None, Cookie(alias=SESSION_COdef update_admin_settings(payload: AdminSettingsRequest, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):user = _require_admin(session_id, db)changes = []+ two_factor_tightened = Falsedays = payload.history_retention_daysif days is not None and days != retention.history_days(db):if days not in retention.HISTORY_CHOICES:@@ -618,6 +629,7 @@ def update_admin_settings(payload: AdminSettingsRequest, session_id: Annotated[schanges.append(f"Changed history retention to {retention.describe(days)}")if payload.require_2fa_for_admins is not None and payload.require_2fa_for_admins != require_admin_two_factor(db):_set_setting(db, REQUIRE_ADMIN_2FA_KEY, "true" if payload.require_2fa_for_admins else "false")+ two_factor_tightened |= payload.require_2fa_for_adminschanges.append(f"{'Required' if payload.require_2fa_for_admins else 'Stopped requiring'} two-factor for administrators")if payload.instance_name is not None:name = _printable(payload.instance_name, MAX_INSTANCE_NAME)@@ -628,6 +640,7 @@ def update_admin_settings(payload: AdminSettingsRequest, session_id: Annotated[schanges.append(f"Renamed this install to {name}" if name else "Reset this install's name to the default")if payload.require_2fa_for_everyone is not None and payload.require_2fa_for_everyone != require_two_factor_for_everyone(db):_set_setting(db, REQUIRE_2FA_EVERYONE_KEY, "true" if payload.require_2fa_for_everyone else "false")+ two_factor_tightened |= payload.require_2fa_for_everyonechanges.append(f"{'Required' if payload.require_2fa_for_everyone else 'Stopped requiring'} two-factor for everyone")if payload.disabled_rules is not None:known = {row["kind"] for row in RULE_ROWS}@@ -684,6 +697,10 @@ def update_admin_settings(payload: AdminSettingsRequest, session_id: Annotated[s_set_setting(db, MOUNT_THRESHOLDS_KEY, json.dumps(mount_thresholds))changes.append("Changed per-mount disk thresholds: " + (", ".join(f"{mount}={limits['disk_warning_pct']:g}/{limits['disk_critical_pct']:g}" for mount, limits in mount_thresholds.items()) or "none"))db.commit()+ if two_factor_tightened:+ ended = end_sessions_without_two_factor(db)+ if ended:+ changes.append(f"Signed out {ended} session{'s' if ended != 1 else ''} of accounts that must now set up two-factor")for change in changes:record_audit_log(db, user_id=user["id"], level="INFO", message=change, source="admin")return _admin_settings(db)diff --git a/src/collector/docker_proxy.py b/src/collector/docker_proxy.pyindex 96b552a..c504eca 100644--- a/src/collector/docker_proxy.py+++ b/src/collector/docker_proxy.py@@ -28,6 +28,7 @@ import osimport reimport socketimport socketserver+import threadingfrom http.server import BaseHTTPRequestHandlerfrom pathlib import Pathfrom typing import Any, Callable@@ -41,6 +42,10 @@ SOCKET_PATH = os.getenv("DOCKER_SOCKET_PATH", "/var/run/docker.sock")LISTEN_PATH = os.getenv("INFRADECK_DOCKER_PROXY_SOCKET", "/run/docker-proxy/docker.sock")MAX_RESPONSE_BYTES = 8 * 1024 * 1024UPSTREAM_TIMEOUT_SECONDS = 10+# A stalled client is dropped after this long without sending anything, and only this many connections are served+# at once (the collector sends one request at a time), so no client can tie the proxy up.+CLIENT_TIMEOUT_SECONDS = 30+MAX_CONNECTIONS = 16_ID = r"[0-9a-f]{12,64}"# Matched against the whole request target, query string included.@@ -144,6 +149,7 @@ class _UnixHTTPConnection(http.client.HTTPConnection):class ProxyHandler(BaseHTTPRequestHandler):server_version = "infradeck-docker-proxy"socket_path = SOCKET_PATH+ timeout = CLIENT_TIMEOUT_SECONDSdef _send(self, status: int, body: bytes = b"", content_type: str = "text/plain") -> None:self.send_response(status)@@ -186,6 +192,27 @@ class ProxyHandler(BaseHTTPRequestHandler):class _Server(socketserver.ThreadingUnixStreamServer):daemon_threads = True+ def __init__(self, *args: Any, **kwargs: Any):+ super().__init__(*args, **kwargs)+ self.slots = threading.BoundedSemaphore(MAX_CONNECTIONS)++ def process_request(self, request: Any, client_address: Any) -> None:+ """Closes a connection beyond MAX_CONNECTIONS straight away instead of starting a thread for it."""+ if not self.slots.acquire(blocking=False):+ self.shutdown_request(request)+ return+ try:+ super().process_request(request, client_address)+ except BaseException:+ self.slots.release()+ raise++ def process_request_thread(self, request: Any, client_address: Any) -> None:+ try:+ super().process_request_thread(request, client_address)+ finally:+ self.slots.release()+def make_server(listen_path: str = LISTEN_PATH, socket_path: str = SOCKET_PATH) -> socketserver.ThreadingUnixStreamServer:"""Listen on a Unix socket only readable and writable by its owner (and group)."""diff --git a/tests/accounts/test_account_security.py b/tests/accounts/test_account_security.pyindex e942e84..d5c77bd 100644--- a/tests/accounts/test_account_security.py+++ b/tests/accounts/test_account_security.py@@ -365,6 +365,44 @@ def test_admins_can_change_the_policy_and_it_is_audited(app, monkeypatch):assert any("Stopped requiring two-factor" in row.message for row in app.db.query(AuditLog))+def _policy(app, monkeypatch, **change):+ monkeypatch.setattr(main, "_require_admin", lambda session_id, db: {"id": 1})+ return main.update_admin_settings(main.AdminSettingsRequest(**change), session_id="s", db=app.db)+++def test_switching_the_admin_policy_on_signs_out_admins_without_two_factor(app, monkeypatch):+ app.db.add(AppSetting(key=main.REQUIRE_ADMIN_2FA_KEY, value="false"))+ app.db.commit()+ admin, member = _signed_in(), _signed_in("[email protected]")++ _policy(app, monkeypatch, require_2fa_for_admins=True)++ assert admin.get("/monitoring/overview").status_code == 401+ assert member.get("/monitoring/overview").status_code == 200+ assert _login(TestClient(main.app)).json()["setup_required"] is True+ assert any(row.message == "Signed out 1 session of accounts that must now set up two-factor" for row in app.db.query(AuditLog))+++def test_admins_who_already_use_two_factor_stay_signed_in_when_the_policy_is_switched_on(app, monkeypatch):+ admin = _signed_in()+ _enroll(app, admin)+ _policy(app, monkeypatch, require_2fa_for_admins=False)++ _policy(app, monkeypatch, require_2fa_for_admins=True)++ assert admin.get("/monitoring/overview").status_code == 200+ assert not any(row.message.startswith("Signed out") for row in app.db.query(AuditLog))+++def test_requiring_two_factor_of_everyone_signs_out_users_without_it(app, monkeypatch):+ member = _signed_in("[email protected]")++ _policy(app, monkeypatch, require_2fa_for_everyone=True)++ assert member.get("/monitoring/overview").status_code == 401+ assert _login(TestClient(main.app), "[email protected]").json()["setup_required"] is True++def test_enrolling_upgrades_the_session_and_rotates_its_id(app):client = _signed_in()limited_cookie = client.cookies.get(COOKIE)diff --git a/tests/collectors/test_docker_proxy.py b/tests/collectors/test_docker_proxy.pyindex 99d5f57..f0a2769 100644--- a/tests/collectors/test_docker_proxy.py+++ b/tests/collectors/test_docker_proxy.py@@ -1,7 +1,9 @@import http.clientimport json+import socketimport socketserverimport threading+import timefrom http.server import BaseHTTPRequestHandlerimport pytest@@ -244,3 +246,55 @@ def test_proxy_socket_is_not_world_accessible_and_replaces_a_stale_one(tmp_path)def test_collector_still_supports_the_plain_socket_path(tmp_path):assert collector.collect_containers(str(tmp_path / "missing.sock")) == []+++def bare_proxy(tmp_path):+ """A proxy with no Docker daemon behind it, for tests of how it treats its own clients."""+ def start():+ listen_path = str(tmp_path / "proxy" / "docker.sock")+ server = proxy.make_server(listen_path, str(tmp_path / "unused"))+ threading.Thread(target=server.serve_forever, daemon=True).start()+ servers.append(server)+ return listen_path+ servers = []+ yield start+ for server in servers:+ server.shutdown()+ server.server_close()+++def _connect(listen_path):+ client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ client.settimeout(5)+ client.connect(listen_path)+ return client+++def test_a_stalled_client_is_dropped(bare_proxy, monkeypatch):+ monkeypatch.setattr(proxy.ProxyHandler, "timeout", 0.2)+ client = _connect(bare_proxy())+ try:+ assert client.recv(1) == b"" # closed by the proxy, not by the 5 s timeout here+ finally:+ client.close()+++def test_connections_beyond_the_limit_are_closed_until_a_slot_frees(bare_proxy, monkeypatch):+ monkeypatch.setattr(proxy, "MAX_CONNECTIONS", 1)+ listen_path = bare_proxy()+ holder = _connect(listen_path)+ try:+ with pytest.raises((http.client.RemoteDisconnected, ConnectionError)):+ _raw(listen_path, "GET", "/containers/json?all=1")+ finally:+ holder.close()++ deadline = time.monotonic() + 5+ while True:+ try:+ assert _raw(listen_path, "GET", "/containers/json?all=1")[0] == 502 # served again; no daemon behind it+ break+ except (http.client.RemoteDisconnected, ConnectionError):+ assert time.monotonic() < deadline+ time.sleep(0.05)diff --git a/tests/security/test_nginx_headers.py b/tests/security/test_nginx_headers.pynew file mode 100644index 0000000..dd8e864--- /dev/null+++ b/tests/security/test_nginx_headers.py@@ -0,0 +1,42 @@+"""The development nginx (docker/nginx.conf, baked into the frontend image) and the server nginx+(docker/nginx.strict.conf, mounted by docker-compose.server.yml) are two files with the same intent. These tests+catch a security header added to, changed in or dropped from one of them but not the other."""+import re+from pathlib import Path++import pytest++DOCKER = Path(__file__).resolve().parents[2] / "docker"+DEVELOPMENT, SERVER = DOCKER / "nginx.conf", DOCKER / "nginx.strict.conf"+# Sent only by the server nginx: it sits behind an HTTPS reverse proxy, the development one serves plain HTTP.+HTTPS_ONLY = {"Strict-Transport-Security"}+HEADER = re.compile(r'^\s*add_header\s+(\S+)\s+"([^"]*)"\s+always;', re.MULTILINE)+++def _headers(path: Path) -> dict[str, str]:+ return dict(HEADER.findall(path.read_text()))+++def _location_blocks(path: Path) -> list[str]:+ """The text of every location block (they hold no nested blocks in these files)."""+ return re.findall(r"location\s[^{]*\{([^}]*)\}", path.read_text())+++def test_both_send_the_same_security_headers():+ development, server = _headers(DEVELOPMENT), _headers(SERVER)++ assert development, "no add_header lines found; did the file format change?"+ assert {name: value for name, value in server.items() if name not in HTTPS_ONLY} == development+++def test_only_the_server_nginx_sends_hsts():+ assert HTTPS_ONLY <= set(_headers(SERVER))+ assert not HTTPS_ONLY & set(_headers(DEVELOPMENT))++[email protected]("path", [DEVELOPMENT, SERVER], ids=lambda path: path.name)+def test_no_location_drops_the_server_wide_headers(path):+ """An add_header inside a location replaces every add_header from the server block for that location."""+ blocks = _location_blocks(path)++ assert blocks and not any("add_header" in block for block in blocks)