2026-09-13 21:27:54 +02:00
|
|
|
import unittest
|
|
|
|
|
|
|
|
|
|
from fastapi import FastAPI, Request
|
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
|
|
|
|
|
|
from shared_backend import authproxy as ap
|
2026-10-19 07:48:07 +00:00
|
|
|
from shared_backend.authclient import (
|
|
|
|
|
DEFAULT_COOKIE_NAME,
|
|
|
|
|
APIError,
|
|
|
|
|
AuthClient,
|
|
|
|
|
PublicUser,
|
|
|
|
|
SessionResult,
|
2026-10-19 21:46:52 +00:00
|
|
|
_forwarded_client_ip,
|
2026-10-19 07:48:07 +00:00
|
|
|
)
|
2026-09-13 21:27:54 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
2026-09-16 23:58:00 +02:00
|
|
|
def _build_app(
|
|
|
|
|
store: ap.ProxyStore,
|
|
|
|
|
client: AuthClient | None = None,
|
|
|
|
|
*,
|
|
|
|
|
internal_secret: str | None = None,
|
2026-10-19 21:46:52 +00:00
|
|
|
local_profile_without_authguard: bool = False,
|
|
|
|
|
trusted_proxies: str = "",
|
2026-09-16 23:58:00 +02:00
|
|
|
) -> FastAPI:
|
2026-09-13 21:27:54 +02:00
|
|
|
def get_client(request: Request) -> AuthClient | None:
|
|
|
|
|
return client
|
|
|
|
|
|
|
|
|
|
def get_store(request: Request) -> ap.ProxyStore:
|
|
|
|
|
return store
|
|
|
|
|
|
|
|
|
|
app = FastAPI()
|
2026-09-16 23:58:00 +02:00
|
|
|
app.include_router(
|
2026-10-19 21:46:52 +00:00
|
|
|
ap.build_auth_router(
|
|
|
|
|
get_client,
|
|
|
|
|
get_store,
|
|
|
|
|
internal_secret=internal_secret,
|
|
|
|
|
local_profile_without_authguard=local_profile_without_authguard,
|
|
|
|
|
trusted_proxies=trusted_proxies,
|
|
|
|
|
),
|
2026-09-16 23:58:00 +02:00
|
|
|
prefix="/api/auth",
|
|
|
|
|
)
|
2026-09-13 21:27:54 +02:00
|
|
|
return app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class AuthDisabledModeTests(unittest.TestCase):
|
2026-10-19 21:46:52 +00:00
|
|
|
"""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
|
2026-09-13 21:27:54 +02:00
|
|
|
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:
|
2026-10-19 21:46:52 +00:00
|
|
|
self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
|
2026-09-13 21:27:54 +02:00
|
|
|
|
|
|
|
|
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()
|
2026-09-16 23:58:00 +02:00
|
|
|
self.assertEqual(body["user"]["username"], "Admin")
|
2026-09-13 21:27:54 +02:00
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
2026-10-19 21:46:52 +00:00
|
|
|
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})
|
|
|
|
|
|
|
|
|
|
|
2026-09-13 21:27:54 +02:00
|
|
|
class AccessSettingsTests(unittest.TestCase):
|
2026-10-19 07:48:07 +00:00
|
|
|
def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
|
2026-09-13 21:27:54 +02:00
|
|
|
store = _FakeStore(login_required=True)
|
2026-10-19 07:48:07 +00:00
|
|
|
client = TestClient(_build_app(store, _RoleClient()))
|
2026-09-13 21:27:54 +02:00
|
|
|
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
2026-10-19 07:48:07 +00:00
|
|
|
|
|
|
|
|
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")
|
2026-09-13 21:27:54 +02:00
|
|
|
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})
|
|
|
|
|
|
2026-10-19 07:48:07 +00:00
|
|
|
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})
|
2026-10-19 21:46:52 +00:00
|
|
|
self.assertEqual(response.status_code, 500)
|
2026-10-19 07:48:07 +00:00
|
|
|
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
|
|
|
|
|
2026-09-16 23:58:00 +02:00
|
|
|
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
|
|
|
|
store = _FakeStore(login_required=True)
|
2026-09-18 13:11:49 +02:00
|
|
|
client = TestClient(
|
|
|
|
|
_build_app(store, _FakeClient(setup_required=False), internal_secret="secret")
|
|
|
|
|
)
|
2026-09-16 23:58:00 +02:00
|
|
|
|
|
|
|
|
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")
|
|
|
|
|
|
2026-09-13 21:27:54 +02:00
|
|
|
|
|
|
|
|
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"]
|
|
|
|
|
|
|
|
|
|
|
2026-10-19 07:48:07 +00:00
|
|
|
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])
|
|
|
|
|
|
|
|
|
|
|
2026-09-13 21:27:54 +02:00
|
|
|
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"])
|
|
|
|
|
|
|
|
|
|
|
2026-10-19 21:46:52 +00:00
|
|
|
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")
|
|
|
|
|
|
|
|
|
|
|
2026-09-13 21:27:54 +02:00
|
|
|
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:
|
2026-10-19 21:46:52 +00:00
|
|
|
self.client = TestClient(_build_app(_FakeStore(), local_profile_without_authguard=True))
|
2026-09-13 21:27:54 +02:00
|
|
|
|
|
|
|
|
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()
|