Async (asyncpg-consistent with the rest of this package), stdlib-only HTTP via urllib + asyncio.to_thread (no new dependency for one GET call). Framework-agnostic by design: read the two real consumers (HordeWorker's aiohttp webui, Heretic's FastAPI app) and they don't share a framework, so token_from_request/resolve_user work over plain headers/cookies mappings rather than shipping a framework adapter. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
158 lines
6.3 KiB
Python
158 lines
6.3 KiB
Python
import io
|
|
import json
|
|
import unittest
|
|
import urllib.error
|
|
from unittest.mock import patch
|
|
|
|
from shared_backend.authclient import (
|
|
AuthClient,
|
|
AuthClientError,
|
|
AuthGuardUser,
|
|
InvalidSessionError,
|
|
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) -> None:
|
|
self.status = status
|
|
self._body = json.dumps(payload).encode("utf-8")
|
|
|
|
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=None,
|
|
fp=io.BytesIO(body),
|
|
)
|
|
|
|
|
|
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 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()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|