Files
shared/packages/python-backend/tests/test_authproxy.py
T

564 lines
23 KiB
Python

import unittest
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from shared_backend import authproxy as ap
from shared_backend.authclient import (
DEFAULT_COOKIE_NAME,
APIError,
AuthClient,
PublicUser,
SessionResult,
_forwarded_client_ip,
)
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,
local_profile_without_authguard: bool = False,
trusted_proxies: str = "",
) -> 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,
local_profile_without_authguard=local_profile_without_authguard,
trusted_proxies=trusted_proxies,
),
prefix="/api/auth",
)
return app
class AuthDisabledModeTests(unittest.TestCase):
"""client=None (AUTHGUARD_URL unset) with the local-mode opt-in - every
route reports the fixed placeholder superadmin identity and nothing is
gated. Without the opt-in the same deployment fails closed; see
UnconfiguredAuthGuardTests. 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(), local_profile_without_authguard=True))
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 UnconfiguredAuthGuardTests(unittest.TestCase):
"""client=None without local_profile_without_authguard: a missing
AUTHGUARD_URL must not turn guarded routes into the local superadmin."""
def setUp(self) -> None:
self.client = TestClient(
_build_app(_FakeStore(login_required=True)), raise_server_exceptions=False
)
def test_guarded_routes_fail_closed(self) -> None:
self.assertEqual(self.client.get("/api/auth/status").status_code, 500)
self.assertEqual(self.client.get("/api/auth/me").status_code, 500)
self.assertEqual(self.client.get("/api/auth/users").status_code, 500)
self.assertEqual(self.client.post("/api/auth/logout").status_code, 500)
def test_login_flag_read_is_still_public(self) -> None:
self.assertEqual(self.client.get("/api/auth/access").json(), {"loginRequired": True})
class AccessSettingsTests(unittest.TestCase):
def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store, _RoleClient()))
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 401)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 403)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
client.cookies.set(DEFAULT_COOKIE_NAME, "admin-token")
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_anonymous_put_is_refused_when_authguard_is_not_configured(self) -> None:
store = _FakeStore(login_required=True)
client = TestClient(_build_app(store))
response = client.put("/api/auth/access", json={"loginRequired": False})
self.assertEqual(response.status_code, 500)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
def test_internal_update_refuses_a_short_or_placeholder_secret(self) -> None:
for secret in ("short", "change-me-to-a-long-random-value"):
with self.subTest(secret=secret):
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, 401)
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
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="internal-test-secret"
)
)
response = client.put(
"/api/auth/access/internal",
headers={"X-Internal-Auth": "internal-test-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 _RoleClient(_FakeClient):
"""Resolves two fixed session tokens to an administrator and an ordinary user."""
async def me(self, token: str) -> PublicUser:
roles = {"admin-token": "superadmin", "user-token": "user"}
if token not in roles:
raise APIError(401, "unauthenticated")
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
class _ProfileClient(_RoleClient):
def __init__(self, *, totp_enabled: bool = False) -> None:
super().__init__()
self.totp_enabled = totp_enabled
self.login_calls: list[tuple[str, str, str]] = []
self.update_calls: list[dict[str, object]] = []
async def me(self, token: str) -> PublicUser:
if token != "admin-token":
raise APIError(401, "unauthenticated")
return PublicUser(
id=1,
username="admin",
email="admin@example.com",
role="superadmin",
totp_enabled=self.totp_enabled,
)
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
self.login_calls.append((username_or_email, password, totp_token))
if password != "current-password":
raise APIError(401, "invalid credentials")
return SessionResult(
user=PublicUser(id=1, username="admin", email="admin@example.com", role="superadmin"),
cookies=["auth_session=reauth-token; Path=/; HttpOnly"],
)
async def update_managed_user(self, token: str, user_id: int, **kwargs) -> None:
self.update_calls.append({"token": token, "user_id": user_id, **kwargs})
class ProfileReauthenticationTests(unittest.TestCase):
def _put(self, fake: _ProfileClient, body: dict[str, str]):
client = TestClient(_build_app(_FakeStore(), fake))
return client.put(
"/api/auth/me",
headers={"Cookie": f"{DEFAULT_COOKIE_NAME}=admin-token"},
json=body,
)
def test_password_update_requires_current_password_and_totp_when_enabled(self) -> None:
no_totp = _ProfileClient()
response = self._put(
no_totp,
{"username": "admin", "email": "admin@example.com", "password": "new-password"},
)
self.assertEqual(response.status_code, 400)
self.assertEqual(no_totp.login_calls, [])
totp = _ProfileClient(totp_enabled=True)
response = self._put(
totp,
{
"username": "admin",
"email": "admin@example.com",
"password": "new-password",
"currentPassword": "current-password",
},
)
self.assertEqual(response.status_code, 400)
self.assertEqual(totp.login_calls, [])
def test_password_update_reauthenticates_and_cleans_up_temporary_session(self) -> None:
fake = _ProfileClient(totp_enabled=True)
response = self._put(
fake,
{
"username": "admin",
"email": "admin@example.com",
"password": "new-password",
"currentPassword": "current-password",
"totpToken": "123456",
},
)
self.assertEqual(response.status_code, 200, response.text)
self.assertEqual(fake.login_calls, [("admin", "current-password", "123456")])
self.assertEqual(
fake.update_calls,
[
{
"token": "admin-token",
"user_id": 1,
"username": "admin",
"email": "admin@example.com",
"password": "new-password",
}
],
)
self.assertIn("reauth-token", fake.logged_out)
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 _AddressRecordingClient(_RoleClient):
"""Records the address AuthClient would send as X-Forwarded-For for each credential call, and
counts the calls that reached AuthGuard."""
def __init__(self) -> None:
super().__init__()
self.forwarded: list[str | None] = []
self.login_calls = 0
self.totp_calls = 0
async def login(self, username_or_email: str, password: str, totp_token: str = ""):
self.login_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
return await super().login(username_or_email, password, totp_token)
async def register(self, username: str, email: str, password: str) -> SessionResult:
self.forwarded.append(_forwarded_client_ip.get())
return await super().register(username, email, password)
async def totp_verify(self, token: str, code: str) -> None:
self.totp_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
if code != "123456":
raise APIError(401, "bad code")
async def totp_disable(self, token: str, code: str) -> None:
self.totp_calls += 1
self.forwarded.append(_forwarded_client_ip.get())
raise APIError(401, "bad code")
class AttemptLimitTests(unittest.TestCase):
"""Login and the TOTP routes refuse further attempts with 429 (S-009)."""
def _login(self, client: TestClient, identifier: str = "Victim") -> int:
response = client.post(
"/api/auth/login", json={"identifier": identifier, "password": "wrong"}
)
return response.status_code
def test_login_is_limited_per_account_before_authguard_is_called(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake))
for attempt in range(ap.LOGIN_ACCOUNT_LIMIT):
self.assertEqual(self._login(client), 401, f"attempt {attempt + 1}")
self.assertEqual(self._login(client), 429)
self.assertEqual(self._login(client, "VICTIM"), 429) # the account key ignores case
self.assertEqual(fake.login_calls, ap.LOGIN_ACCOUNT_LIMIT)
self.assertEqual(self._login(client, "someone-else"), 401)
def test_login_is_limited_per_client_address(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake), client=("203.0.113.7", 40000))
statuses = [self._login(client, f"user{i}") for i in range(ap.LOGIN_CLIENT_LIMIT + 1)]
self.assertEqual(statuses[:-1], [401] * ap.LOGIN_CLIENT_LIMIT)
self.assertEqual(statuses[-1], 429)
def test_totp_verify_and_disable_share_a_per_user_limit(self) -> None:
fake = _AddressRecordingClient()
client = TestClient(_build_app(_FakeStore(), fake))
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
for _ in range(ap.TOTP_ATTEMPT_LIMIT - 1):
response = client.post("/api/auth/totp/verify", json={"totpToken": "000000"})
self.assertEqual(response.status_code, 401)
self.assertEqual(
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 401
)
self.assertEqual(
client.post("/api/auth/totp/verify", json={"totpToken": "123456"}).status_code, 429
)
self.assertEqual(
client.post("/api/auth/totp/disable", json={"totpToken": "000000"}).status_code, 429
)
self.assertEqual(fake.totp_calls, ap.TOTP_ATTEMPT_LIMIT)
class ClientAddressForwardingTests(unittest.TestCase):
"""The client address is the TCP peer unless the peer is a trusted proxy (decision 5), and it
reaches AuthGuard as X-Forwarded-For through forwarded_client_ip."""
def _login_address(self, *, peer: str, trusted: str, forwarded: str | None) -> str | None:
fake = _AddressRecordingClient()
client = TestClient(
_build_app(_FakeStore(), fake, trusted_proxies=trusted), client=(peer, 40000)
)
headers = {"X-Forwarded-For": forwarded} if forwarded is not None else {}
response = client.post(
"/api/auth/login",
json={"identifier": "a@b.com", "password": "correct"},
headers=headers,
)
self.assertEqual(response.status_code, 200)
return fake.forwarded[-1]
def test_the_tcp_peer_is_forwarded_without_trusted_proxies(self) -> None:
got = self._login_address(peer="203.0.113.7", trusted="", forwarded="6.6.6.6")
self.assertEqual(got, "203.0.113.7")
def test_a_spoofed_header_from_an_untrusted_peer_is_ignored(self) -> None:
got = self._login_address(peer="203.0.113.7", trusted="10.0.0.0/8", forwarded="6.6.6.6")
self.assertEqual(got, "203.0.113.7")
def test_a_trusted_peer_has_its_header_walked_right_to_left(self) -> None:
got = self._login_address(
peer="10.0.0.2", trusted="10.0.0.0/8", forwarded="6.6.6.6, 198.51.100.9, 10.0.0.1"
)
self.assertEqual(got, "198.51.100.9")
def test_setup_and_totp_forward_the_address_too(self) -> None:
fake = _AddressRecordingClient()
fake.setup_required = True
client = TestClient(_build_app(_FakeStore(), fake), client=("198.51.100.20", 40000))
client.post(
"/api/auth/setup",
json={"username": "admin", "email": "admin@example.com", "password": "password123"},
)
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
client.post("/api/auth/totp/verify", json={"totpToken": "123456"})
client.post("/api/auth/totp/disable", json={"totpToken": "123456"})
self.assertEqual(fake.forwarded, ["198.51.100.20"] * 3)
def test_the_forwarded_address_does_not_leak_outside_the_call(self) -> None:
self._login_address(peer="203.0.113.7", trusted="", forwarded=None)
self.assertIsNone(_forwarded_client_ip.get())
def test_an_invalid_trusted_proxy_list_fails_at_startup(self) -> None:
with self.assertRaises(ValueError):
_build_app(_FakeStore(), trusted_proxies="10.0.0.0/8, not-an-ip")
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(), local_profile_without_authguard=True))
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()