import unittest from fastapi import FastAPI, Request from fastapi.testclient import TestClient from shared_backend import authproxy as ap from shared_backend.authclient import APIError, AuthClient, PublicUser, SessionResult class _FakeStore(ap.ProxyStore): """In-memory ProxyStore covering both flags build_auth_router needs.""" def __init__(self, *, claimed: bool = False, login_required: bool = True) -> None: self.claimed = claimed self._login_required = login_required async def login_required(self) -> bool: return self._login_required async def set_login_required(self, required: bool) -> None: self._login_required = required async def is_setup_claimed(self) -> bool: return self.claimed async def try_claim_setup(self) -> bool: if self.claimed: return False self.claimed = True return True async def unclaim_setup(self) -> None: self.claimed = False def _build_app( store: ap.ProxyStore, client: AuthClient | None = None, *, internal_secret: str | None = None, ) -> FastAPI: def get_client(request: Request) -> AuthClient | None: return client def get_store(request: Request) -> ap.ProxyStore: return store app = FastAPI() app.include_router( ap.build_auth_router(get_client, get_store, internal_secret=internal_secret), prefix="/api/auth", ) return app class AuthDisabledModeTests(unittest.TestCase): """client=None (AUTHGUARD_URL unset) - every route reports the fixed placeholder superadmin identity and nothing is gated. This is also a regression test for a real bug this module had: request/response models declared *inside* build_auth_router, combined with `from __future__ import annotations`, made FastAPI silently misparse every JSON body as a missing query parameter (all these POST/PUT calls would 422 on that bug).""" def setUp(self) -> None: self.client = TestClient(_build_app(_FakeStore())) def test_status_reports_local_superadmin(self) -> None: response = self.client.get("/api/auth/status") self.assertEqual(response.status_code, 200) body = response.json() self.assertTrue(body["authenticated"]) self.assertFalse(body["setupRequired"]) self.assertEqual(body["user"]["role"], "superadmin") self.assertTrue(body["user"]["canManageUsers"]) def test_me_reports_local_superadmin(self) -> None: body = self.client.get("/api/auth/me").json() self.assertEqual(body["user"]["username"], "Admin") def test_setup_succeeds_as_a_no_op(self) -> None: response = self.client.post( "/api/auth/setup", json={"username": "a", "email": "a@b.com", "password": "password123"}, ) self.assertEqual(response.status_code, 201) self.assertEqual(response.json()["user"]["role"], "superadmin") def test_login_succeeds_as_a_no_op(self) -> None: response = self.client.post( "/api/auth/login", json={"identifier": "anyone", "password": "whatever"} ) self.assertEqual(response.status_code, 200) def test_logout_always_ok(self) -> None: self.assertEqual(self.client.post("/api/auth/logout").json(), {"ok": True}) def test_list_users_returns_empty_list_not_an_error(self) -> None: self.assertEqual(self.client.get("/api/auth/users").json(), []) def test_mutating_admin_routes_require_authguard(self) -> None: response = self.client.post( "/api/auth/users", json={"username": "b", "email": "b@c.com", "password": "password123"}, ) self.assertEqual(response.status_code, 409) def test_totp_initiate_requires_authguard(self) -> None: self.assertEqual(self.client.post("/api/auth/totp/initiate").status_code, 409) def test_update_me_requires_authguard(self) -> None: self.assertEqual(self.client.put("/api/auth/me", json={}).status_code, 409) class AccessSettingsTests(unittest.TestCase): def test_get_and_put_round_trip_through_the_store(self) -> None: store = _FakeStore(login_required=True) client = TestClient(_build_app(store)) self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True}) response = client.put("/api/auth/access", json={"loginRequired": False}) self.assertEqual(response.json(), {"loginRequired": False}) self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False}) def test_internal_update_disables_login_and_uses_admin_identity(self) -> None: store = _FakeStore(login_required=True) client = TestClient(_build_app(store, _FakeClient(setup_required=False), internal_secret="secret")) response = client.put( "/api/auth/access/internal", headers={"X-Internal-Auth": "secret"}, json={"loginRequired": False}, ) self.assertEqual(response.status_code, 200) self.assertEqual(response.json(), {"loginRequired": False}) body = client.get("/api/auth/me").json() self.assertFalse(body["authRequired"]) self.assertEqual(body["user"]["username"], "Admin") class _FakeClient(AuthClient): """Overrides just the methods build_auth_router calls, bypassing real HTTP entirely - AuthClient.__init__ never needs a reachable base_url for these tests since nothing here calls the real _call/_validate_sync.""" def __init__(self, *, setup_required: bool = True) -> None: super().__init__("http://authguard.test") self.setup_required = setup_required self.registered: list[tuple[str, str, str]] = [] self.logged_out: list[str] = [] async def setup_status(self) -> bool: return self.setup_required async def register(self, username: str, email: str, password: str) -> SessionResult: self.registered.append((username, email, password)) self.setup_required = False return SessionResult( user=PublicUser(id=1, username=username, email=email, role="superadmin"), cookies=["auth_session=tok1; Path=/"], ) async def login(self, username_or_email: str, password: str, totp_token: str = ""): if password == "wrong": raise APIError(401, "invalid credentials") return SessionResult( user=PublicUser(id=1, username=username_or_email, email="a@b.com", role="user"), cookies=["auth_session=tok1; Path=/"], ) async def me(self, token: str) -> PublicUser: if not token: raise APIError(401, "unauthenticated") return PublicUser(id=1, username="a", email="a@b.com", role="user") async def logout(self, token: str) -> list[str]: self.logged_out.append(token) return ["auth_session=; Path=/; Max-Age=0"] class EnabledModeSetupAndLoginTests(unittest.TestCase): """Exercises the real (client is not None) path, including the setup-claim flag's interaction with the store.""" def test_setup_claims_the_flag_and_registers_against_authguard(self) -> None: store = _FakeStore(claimed=False) fake_client = _FakeClient(setup_required=True) client = TestClient(_build_app(store, fake_client)) response = client.post( "/api/auth/setup", json={"username": "admin", "email": "admin@example.com", "password": "password123"}, ) self.assertEqual(response.status_code, 201) self.assertTrue(store.claimed) self.assertEqual(fake_client.registered, [("admin", "admin@example.com", "password123")]) self.assertIn("set-cookie", response.headers) def test_setup_refuses_a_second_claim(self) -> None: store = _FakeStore(claimed=True) client = TestClient(_build_app(store, _FakeClient())) response = client.post( "/api/auth/setup", json={"username": "admin", "email": "admin@example.com", "password": "password123"}, ) self.assertEqual(response.status_code, 409) def test_setup_unclaims_when_authguard_already_has_an_account(self) -> None: # claimed=False locally, but AuthGuard itself reports no setup is # needed (e.g. another project already created the first account) - # the local claim slot must be released again, not left stuck. store = _FakeStore(claimed=False) client = TestClient(_build_app(store, _FakeClient(setup_required=False))) response = client.post( "/api/auth/setup", json={"username": "admin", "email": "admin@example.com", "password": "password123"}, ) self.assertEqual(response.status_code, 409) self.assertFalse(store.claimed) def test_login_success_forwards_cookies(self) -> None: client = TestClient(_build_app(_FakeStore(), _FakeClient())) response = client.post( "/api/auth/login", json={"identifier": "a@b.com", "password": "correct"} ) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()["user"]["username"], "a@b.com") def test_login_invalid_credentials_surfaces_401(self) -> None: client = TestClient(_build_app(_FakeStore(), _FakeClient())) response = client.post( "/api/auth/login", json={"identifier": "a@b.com", "password": "wrong"} ) self.assertEqual(response.status_code, 401) def test_me_without_session_cookie_reports_no_user(self) -> None: client = TestClient(_build_app(_FakeStore(), _FakeClient())) body = client.get("/api/auth/me").json() self.assertIsNone(body["user"]) class RequestValidationTests(unittest.TestCase): """Every JSON-body route must actually parse its body (see the docstring on AuthDisabledModeTests for the regression this guards against).""" def setUp(self) -> None: self.client = TestClient(_build_app(_FakeStore())) def test_setup_rejects_missing_fields_with_422_not_500(self) -> None: response = self.client.post("/api/auth/setup", json={}) self.assertEqual(response.status_code, 422) def test_login_rejects_missing_password_with_422_not_500(self) -> None: response = self.client.post("/api/auth/login", json={"identifier": "a"}) self.assertEqual(response.status_code, 422) if __name__ == "__main__": unittest.main()