Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
feat(auth): default-deny baseline requiring a session on every non-exempt route
karloks20053ab929573397
diff --git a/src/backend/main.py b/src/backend/main.pyindex 12ac014..1762bfd 100644--- a/src/backend/main.py+++ b/src/backend/main.py@@ -238,8 +238,31 @@ def agent_error_message(exc: Exception) -> str:redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)# Jobs for the agent worker are published after the commit that opened or escalated an incident (see src/agent/jobs.py).agent_jobs.redis_getter = lambda: redis_client+# Default-deny baseline (Option B, #154): every route requires a valid session unless its path is exempt — the+# sign-in/registration pages, the token-authenticated collector endpoints, and the API docs. Handlers keep their own+# checks (role, ownership, the user object); this only makes "a new endpoint forgot its auth" fail closed, not open.+SESSION_EXEMPT_PATHS = {+ "/", "/health", "/auth/config", "/auth/invite", "/auth/register", "/auth/login", "/auth/login/2fa", "/auth/logout",+ # These accept the limited enrolment session (two-factor setup, profile) and enforce it themselves with+ # _account_session(allow_limited=True); the baseline, which only knows full sessions, would wrongly block them.+ "/auth/me", "/auth/2fa/status", "/auth/2fa/setup", "/auth/2fa/enable",+ "/monitoring/collectors/register", "/monitoring/collectors/register/poll", "/monitoring/collectors/enroll",+ "/monitoring/metrics/ingest", "/monitoring/metrics/checks",+ "/openapi.json", "/docs", "/docs/oauth2-redirect",+}+++def require_session(request: Request, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)) -> None:+ """Runs before every handler. For a path that isn't exempt it demands a valid session (or API token), raising 401+ otherwise; the handler then re-checks and reads the user. _current_user also accepts API tokens, so read tokens+ keep working. Exempt paths authenticate themselves (a sign-in step, a collector token) or are public."""+ if request.url.path not in SESSION_EXEMPT_PATHS:+ _current_user(session_id, db)++# The interactive API documentation is a map of every endpoint, so it is off unless ENABLE_API_DOCS=true.-app = FastAPI(title="Infradeck API", docs_url="/docs" if ENABLE_API_DOCS else None, redoc_url=None, openapi_url="/openapi.json" if ENABLE_API_DOCS else None)+app = FastAPI(title="Infradeck API", docs_url="/docs" if ENABLE_API_DOCS else None, redoc_url=None, openapi_url="/openapi.json" if ENABLE_API_DOCS else None,+ dependencies=[Depends(require_session)])UNSAFE_METHODS = {"POST", "PUT", "PATCH", "DELETE"}diff --git a/tests/collectors/test_enrollment_limits.py b/tests/collectors/test_enrollment_limits.pyindex 3c448d1..1342c7b 100644--- a/tests/collectors/test_enrollment_limits.py+++ b/tests/collectors/test_enrollment_limits.py@@ -165,6 +165,7 @@ def test_a_full_install_refuses_new_servers_but_still_serves_the_ones_it_has(appdef test_the_cap_applies_to_adding_by_hand_and_to_approving_requests(app, monkeypatch):monkeypatch.setattr(main, "MAX_SERVERS", 1)+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: {"id": 1, "role": "admin"})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 == 409diff --git a/tests/security/test_endpoints_require_auth.py b/tests/security/test_endpoints_require_auth.pyindex d20c355..ce0d5f2 100644--- a/tests/security/test_endpoints_require_auth.py+++ b/tests/security/test_endpoints_require_auth.py@@ -91,3 +91,28 @@ def test_the_public_list_only_names_routes_that_exist():everything = set(_routes())missing = [entry for entry in PUBLIC if entry not in everything]assert not missing, f"PUBLIC names routes that no longer exist: {missing}"+++def test_public_routes_are_session_exempt():+ # A route the security policy treats as public must also be exempt from the baseline, or it would be blocked.+ for _method, path in PUBLIC:+ assert path in main.SESSION_EXEMPT_PATHS, f"{path} is public but not in SESSION_EXEMPT_PATHS"+++def test_the_baseline_gate_blocks_non_exempt_paths_without_a_session(monkeypatch):+ # require_session is the default-deny gate (Option B): with no session it raises on a non-exempt path and+ # passes on an exempt one, before any handler runs.+ from types import SimpleNamespace++ from fastapi import HTTPException++ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)+ Base.metadata.create_all(engine)+ monkeypatch.setattr(main, "redis_client", FakeRedis()) # empty: nobody has a session+ with sessionmaker(bind=engine)() as db:+ request = SimpleNamespace(url=SimpleNamespace(path="/availability"))+ with pytest.raises(HTTPException) as caught:+ main.require_session(request, session_id=None, db=db)+ assert caught.value.status_code in (401, 403)+ # an exempt path is let through without a session+ main.require_session(SimpleNamespace(url=SimpleNamespace(path="/health")), session_id=None, db=db)