Files
shared/packages/python-backend/tests/test_authclient.py
T
Gabriel20xx 22887fef03 ci: expand CI checks and make consumer sync opt-in
- Add Go, npm, Python, and Java validation to CI
- Run Go tests against PostgreSQL
- Record performance fixes in the report
2026-10-19 21:14:31 +00:00

540 lines
23 KiB
Python

import io
import json
import unittest
import urllib.error
from email.message import Message
from unittest.mock import patch
from shared_backend.authclient import (
APIError,
AuthClient,
AuthClientError,
AuthGuardUser,
InvalidSessionError,
ManagedUser,
PublicUser,
forwarded_client_ip,
resolve_user,
token_from_request,
)
class _FakeResponse:
"""Minimal stand-in for the context manager urllib.request.urlopen returns."""
def __init__(self, status: int, payload: dict, cookies: list[str] | None = None) -> None:
self.status = status
self._body = json.dumps(payload).encode("utf-8")
self.headers = Message()
for cookie in cookies or []:
self.headers.add_header("Set-Cookie", cookie)
def __enter__(self) -> "_FakeResponse":
return self
def __exit__(self, *exc_info) -> bool:
return False
def read(self) -> bytes:
return self._body
def _fake_http_error(status: int, payload: dict) -> urllib.error.HTTPError:
body = json.dumps(payload).encode("utf-8")
return urllib.error.HTTPError(
url="http://authguard.example/api/session/validate",
code=status,
msg="error",
hdrs=Message(),
fp=io.BytesIO(body),
)
class AuthClientForwardedClientIpTests(unittest.IsolatedAsyncioTestCase):
"""forwarded_client_ip makes credential calls carry the end user's address (S-009)."""
async def _login_request(self, address):
client = AuthClient("https://authguard.example")
payload = {"user": {"id": 1, "username": "a", "email": "", "role": "user"}}
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_FakeResponse(200, payload),
) as urlopen:
if address is None:
await client.login("a", "secret-password")
else:
with forwarded_client_ip(address):
await client.login("a", "secret-password")
return urlopen.call_args.args[0]
async def test_the_address_is_sent_as_x_forwarded_for(self) -> None:
request = await self._login_request("203.0.113.9")
self.assertEqual(request.get_header("X-forwarded-for"), "203.0.113.9")
async def test_no_header_is_sent_outside_the_block(self) -> None:
request = await self._login_request(None)
self.assertIsNone(request.get_header("X-forwarded-for"))
async def test_a_value_that_is_not_an_ip_address_is_dropped(self) -> None:
for value in ("203.0.113.9\r\nX-Evil: 1", "not-an-ip", ""):
request = await self._login_request(value)
self.assertIsNone(request.get_header("X-forwarded-for"), repr(value))
class AuthClientBaseUrlTests(unittest.TestCase):
def test_bare_public_host_assumes_https(self) -> None:
self.assertEqual(AuthClient("auth.example.com").base_url, "https://auth.example.com")
self.assertEqual(
AuthClient("auth.example.com:8080").base_url, "https://auth.example.com:8080"
)
def test_bare_private_host_assumes_http(self) -> None:
self.assertEqual(AuthClient("192.168.1.50:8080").base_url, "http://192.168.1.50:8080")
self.assertEqual(AuthClient("10.1.2.3:8080").base_url, "http://10.1.2.3:8080")
self.assertEqual(AuthClient("172.20.0.5:8080").base_url, "http://172.20.0.5:8080")
self.assertEqual(AuthClient("127.0.0.1:8080").base_url, "http://127.0.0.1:8080")
self.assertEqual(AuthClient("169.254.1.1:8080").base_url, "http://169.254.1.1:8080")
self.assertEqual(AuthClient("localhost:8080").base_url, "http://localhost:8080")
self.assertEqual(AuthClient("authguard.local:8080").base_url, "http://authguard.local:8080")
self.assertEqual(AuthClient("[::1]:8080").base_url, "http://[::1]:8080")
self.assertEqual(AuthClient("[fd00::1]:8080").base_url, "http://[fd00::1]:8080")
def test_172_range_outside_private_block_assumes_https(self) -> None:
self.assertEqual(AuthClient("172.32.0.5:8080").base_url, "https://172.32.0.5:8080")
def test_explicit_scheme_left_alone(self) -> None:
self.assertEqual(AuthClient("http://auth.example.com").base_url, "http://auth.example.com")
self.assertEqual(
AuthClient("https://auth.example.com").base_url, "https://auth.example.com"
)
self.assertEqual(AuthClient("HTTP://auth.example.com").base_url, "HTTP://auth.example.com")
self.assertEqual(
AuthClient("https://192.168.1.50:8080").base_url, "https://192.168.1.50:8080"
)
def test_trailing_slash_stripped_before_scheme_check(self) -> None:
self.assertEqual(AuthClient("auth.example.com/").base_url, "https://auth.example.com")
def test_whitespace_trimmed_and_empty_stays_empty(self) -> None:
self.assertEqual(AuthClient(" auth.example.com ").base_url, "https://auth.example.com")
self.assertEqual(AuthClient("").base_url, "")
class AuthClientValidateTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.client = AuthClient("https://authguard.example")
async def test_valid_session_resolves_user(self) -> None:
payload = {"valid": True, "user_id": 42, "username": "alice", "role": "admin"}
response = _FakeResponse(200, payload)
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
user = await self.client.validate("a-token")
self.assertEqual(user, AuthGuardUser(id=42, username="alice", role="admin"))
urlopen.assert_called_once()
request = urlopen.call_args.args[0]
self.assertEqual(request.get_header("Authorization"), "Bearer a-token")
async def test_empty_token_raises_without_network_call(self) -> None:
with patch("shared_backend.authclient.urllib.request.urlopen") as urlopen:
with self.assertRaises(InvalidSessionError):
await self.client.validate("")
with self.assertRaises(InvalidSessionError):
await self.client.validate(" ")
urlopen.assert_not_called()
async def test_missing_base_url_raises_client_error_without_network_call(self) -> None:
client = AuthClient(" ")
with patch("shared_backend.authclient.urllib.request.urlopen") as urlopen:
with self.assertRaises(AuthClientError):
await client.validate("a-token")
urlopen.assert_not_called()
async def test_authguard_reports_invalid_raises_invalid_session_error(self) -> None:
response = _FakeResponse(200, {"valid": False})
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
with self.assertRaises(InvalidSessionError):
await self.client.validate("a-token")
async def test_authguard_401_raises_invalid_session_error(self) -> None:
error = _fake_http_error(401, {"valid": False})
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=error):
with self.assertRaises(InvalidSessionError):
await self.client.validate("a-token")
async def test_transport_error_propagates_as_auth_client_error(self) -> None:
transport_error = urllib.error.URLError("connection refused")
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=transport_error):
with self.assertRaises(AuthClientError) as ctx:
await self.client.validate("a-token")
# Distinct from InvalidSessionError - a service outage is not the same
# as "this visitor is unauthenticated".
self.assertNotIsInstance(ctx.exception, InvalidSessionError)
self.assertIs(ctx.exception.__cause__, transport_error)
async def test_decode_failure_propagates_as_auth_client_error(self) -> None:
class _BadResponse(_FakeResponse):
def read(self) -> bytes:
return b"not json"
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_BadResponse(200, {}),
):
with self.assertRaises(AuthClientError):
await self.client.validate("a-token")
class AuthClientValidationCacheTests(unittest.IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.client = AuthClient("https://authguard.example")
payload = {"valid": True, "user_id": 42, "username": "alice", "role": "admin"}
self.valid = _FakeResponse(200, payload)
async def test_repeated_validate_reuses_the_answer(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
) as urlopen:
first = await self.client.validate("a-token")
second = await self.client.validate("a-token")
self.assertEqual(first, second)
urlopen.assert_called_once()
async def test_invalid_session_is_cached_too(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen",
return_value=_FakeResponse(401, {"valid": False}),
) as urlopen:
with self.assertRaises(InvalidSessionError):
await self.client.validate("bad-token")
with self.assertRaises(InvalidSessionError):
await self.client.validate("bad-token")
urlopen.assert_called_once()
async def test_logout_drops_the_cached_answer(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen",
side_effect=[self.valid, _FakeResponse(200, {}), _FakeResponse(401, {"valid": False})],
) as urlopen:
await self.client.validate("a-token")
await self.client.logout("a-token")
with self.assertRaises(InvalidSessionError):
await self.client.validate("a-token")
self.assertEqual(urlopen.call_count, 3)
async def test_set_base_url_clears_the_cache(self) -> None:
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=self.valid
) as urlopen:
await self.client.validate("a-token")
self.client.set_base_url("https://authguard2.example")
await self.client.validate("a-token")
self.assertEqual(urlopen.call_count, 2)
class TokenFromRequestTests(unittest.TestCase):
def test_prefers_authorization_header_over_cookie(self) -> None:
headers = {"Authorization": "Bearer header-token"}
cookies = {"auth_session": "cookie-token"}
self.assertEqual(token_from_request(headers, cookies), "header-token")
def test_falls_back_to_cookie_when_no_header(self) -> None:
self.assertEqual(
token_from_request({}, {"auth_session": "cookie-token"}),
"cookie-token",
)
def test_uses_configured_cookie_name(self) -> None:
self.assertEqual(
token_from_request({}, {"session": "cookie-token"}, cookie_name="session"),
"cookie-token",
)
def test_returns_empty_string_when_neither_present(self) -> None:
self.assertEqual(token_from_request({}, {}), "")
def test_ignores_non_bearer_authorization_header(self) -> None:
headers = {"Authorization": "Basic dXNlcjpwYXNz"}
cookies = {"auth_session": "cookie-token"}
self.assertEqual(token_from_request(headers, cookies), "cookie-token")
class ResolveUserTests(unittest.IsolatedAsyncioTestCase):
async def test_resolves_user_from_header(self) -> None:
client = AuthClient("https://authguard.example")
payload = {"valid": True, "user_id": 7, "username": "bob", "role": "user"}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
user = await resolve_user(client, {"Authorization": "Bearer a-token"}, {})
self.assertEqual(user, AuthGuardUser(id=7, username="bob", role="user"))
async def test_no_token_anywhere_raises_invalid_session_without_network_call(self) -> None:
client = AuthClient("https://authguard.example")
with patch("shared_backend.authclient.urllib.request.urlopen") as urlopen:
with self.assertRaises(InvalidSessionError):
await resolve_user(client, {}, {})
urlopen.assert_not_called()
class AuthClientProxyMethodTests(unittest.IsolatedAsyncioTestCase):
"""Covers the register/login/.../setup_status surface: the additional
methods a service that runs its own login/admin screens proxied to
AuthGuard needs, beyond the original validate()-only surface."""
def setUp(self) -> None:
self.client = AuthClient("https://authguard.example")
async def test_setup_status_true_and_false(self) -> None:
for setup_required in (True, False):
response = _FakeResponse(200, {"setup_required": setup_required})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
result = await self.client.setup_status()
self.assertEqual(result, setup_required)
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "GET")
self.assertTrue(request.full_url.endswith("/api/setup-status"))
async def test_register_returns_user_and_forwards_cookies(self) -> None:
payload = {
"user": {
"id": 1,
"username": "root",
"email": "root@example.com",
"role": "superadmin",
"totp_enabled": False,
}
}
response = _FakeResponse(201, payload, cookies=["auth_session=abc; HttpOnly"])
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
result = await self.client.register(
"root", "root@example.com", "correct horse battery staple"
)
self.assertEqual(
result.user,
PublicUser(
id=1,
username="root",
email="root@example.com",
role="superadmin",
totp_enabled=False,
),
)
self.assertEqual(result.cookies, ["auth_session=abc; HttpOnly"])
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "POST")
sent = json.loads(request.data)
self.assertEqual(
sent,
{
"username": "root",
"email": "root@example.com",
"password": "correct horse battery staple",
},
)
async def test_login_success(self) -> None:
payload = {
"user": {
"id": 2,
"username": "alice",
"email": "alice@example.com",
"role": "user",
"totp_enabled": True,
}
}
response = _FakeResponse(200, payload, cookies=["auth_session=xyz"])
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
result = await self.client.login("alice", "correct horse battery staple", "123456")
self.assertEqual(result.user.username, "alice")
self.assertTrue(result.user.totp_enabled)
self.assertEqual(result.cookies, ["auth_session=xyz"])
async def test_login_totp_required_raises_api_error_with_flag(self) -> None:
error = _fake_http_error(
401, {"error": "two-factor authentication code required", "totp_required": True}
)
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=error):
with self.assertRaises(APIError) as ctx:
await self.client.login("alice", "correct horse battery staple")
self.assertEqual(ctx.exception.status_code, 401)
self.assertTrue(ctx.exception.totp_required)
async def test_login_invalid_credentials_raises_api_error_without_totp_flag(self) -> None:
error = _fake_http_error(401, {"error": "invalid username/email or password"})
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=error):
with self.assertRaises(APIError) as ctx:
await self.client.login("alice", "wrong password")
self.assertFalse(ctx.exception.totp_required)
self.assertEqual(ctx.exception.message, "invalid username/email or password")
async def test_logout_returns_clearing_cookies(self) -> None:
response = _FakeResponse(200, {"ok": True}, cookies=["auth_session=; Max-Age=0"])
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
cookies = await self.client.logout("a-token")
self.assertEqual(cookies, ["auth_session=; Max-Age=0"])
request = urlopen.call_args.args[0]
self.assertEqual(request.get_header("Authorization"), "Bearer a-token")
async def test_me_resolves_public_user(self) -> None:
payload = {
"user": {
"id": 3,
"username": "bob",
"email": "bob@example.com",
"role": "admin",
"totp_enabled": False,
}
}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
user = await self.client.me("a-token")
self.assertEqual(user.id, 3)
self.assertEqual(user.role, "admin")
async def test_totp_enable_returns_secret(self) -> None:
payload = {"secret": "SECRET", "otpauth_url": "otpauth://...", "enabled": False}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
result = await self.client.totp_enable("a-token")
self.assertEqual(result.secret, "SECRET")
self.assertFalse(result.enabled)
async def test_totp_verify_and_disable_send_token(self) -> None:
response = _FakeResponse(200, {"enabled": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.totp_verify("a-token", "123456")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {"token": "123456"})
response = _FakeResponse(200, {"enabled": False})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.totp_disable("a-token", "654321")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {"token": "654321"})
async def test_request_password_reset_targets_superadmin_by_default(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.request_password_reset()
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {})
async def test_confirm_password_reset_sends_code_and_password(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.confirm_password_reset("ABCD1234", "a brand new passphrase")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertEqual(sent, {"code": "ABCD1234", "password": "a brand new passphrase"})
async def test_list_managed_users(self) -> None:
payload = {
"users": [
{
"id": 1,
"username": "root",
"email": "root@example.com",
"role": "superadmin",
"created_at": "2026-01-01T00:00:00Z",
},
{
"id": 2,
"username": "bob",
"email": "bob@example.com",
"role": "user",
"created_at": "2026-01-02T00:00:00Z",
},
]
}
response = _FakeResponse(200, payload)
with patch("shared_backend.authclient.urllib.request.urlopen", return_value=response):
users = await self.client.list_managed_users("a-token")
self.assertEqual(len(users), 2)
self.assertEqual(
users[0],
ManagedUser(
id=1,
username="root",
email="root@example.com",
role="superadmin",
created_at="2026-01-01T00:00:00Z",
),
)
async def test_create_managed_user_omits_role_when_not_given(self) -> None:
payload = {
"user": {
"id": 4,
"username": "carol",
"email": "carol@example.com",
"role": "user",
"created_at": "",
}
}
response = _FakeResponse(201, payload)
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
created = await self.client.create_managed_user(
"a-token",
username="carol",
email="carol@example.com",
password="correct horse battery staple",
)
self.assertEqual(created.username, "carol")
sent = json.loads(urlopen.call_args.args[0].data)
self.assertNotIn("role", sent)
async def test_update_managed_user_only_sends_provided_fields(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.update_managed_user("a-token", 5, email="new@example.com")
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "PUT")
self.assertTrue(request.full_url.endswith("/api/admin/users/5"))
sent = json.loads(request.data)
self.assertEqual(sent, {"email": "new@example.com"})
async def test_delete_managed_user(self) -> None:
response = _FakeResponse(200, {"ok": True})
with patch(
"shared_backend.authclient.urllib.request.urlopen", return_value=response
) as urlopen:
await self.client.delete_managed_user("a-token", 6)
request = urlopen.call_args.args[0]
self.assertEqual(request.get_method(), "DELETE")
self.assertTrue(request.full_url.endswith("/api/admin/users/6"))
async def test_transport_error_raises_auth_client_error_not_api_error(self) -> None:
transport_error = urllib.error.URLError("connection refused")
with patch("shared_backend.authclient.urllib.request.urlopen", side_effect=transport_error):
with self.assertRaises(AuthClientError) as ctx:
await self.client.setup_status()
self.assertNotIsInstance(ctx.exception, APIError)
if __name__ == "__main__":
unittest.main()