Extend Go/Python/Node authclient with the full AuthGuard API surface
Previously each authclient only supported GET /api/session/validate - the "just gate requests behind a valid session" case. A service that runs its own login/register/admin-user-management screens proxied to AuthGuard (GameStream's pattern, now also used by InfiniteVideo and OutdoorGames) needs much more: register, login, logout, me, totp_enable/verify/disable, password-reset request/confirm, and managed-user list/create/update/delete. The Go client already had this full surface from GameStream's original migration; Python and Node only had validate(), so both gained the same method set as Go, mirroring its behavior and JSON wire shapes exactly (register/login/logout return the raw Set-Cookie values to forward, totp_required surfaces on a 401 from login, etc). Also adds a SetupStatus/ setup_status/setupStatus method (GET /api/setup-status) so a service's own first-launch flow can tell whether AuthGuard already has an account before showing its own account-creation form, and adds totp_enabled to the Go client's PublicUser (AuthGuard has reported it for a while; the client just hadn't picked it up). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
db733a6bf4
commit
f5a20b72af
7 files changed
+1169
-42
No files matched your search
@@ -3,39 +3,47 @@ a sibling of this shared/python-backend package) instead of embedding this
|
||||
package's own asyncpg-backed AuthStore against a service's private database.
|
||||
|
||||
A service that switches to AuthGuard trades "its own local user table" for
|
||||
"one HTTP call per request to AuthGuard's GET /api/session/validate",
|
||||
gaining a single shared identity across every project that does the same.
|
||||
This module is additive: it does not change how shared_backend.auth works,
|
||||
and no project in this workspace is wired up to use it yet -- that migration
|
||||
is a deliberate per-project decision. Mirrors
|
||||
shared/backend/authclient/client.go and
|
||||
shared/packages/node-backend/src/authclient.js (the Go and Node
|
||||
"HTTP calls to AuthGuard's API", gaining a single shared identity across
|
||||
every project that does the same. This module is additive: it does not
|
||||
change how shared_backend.auth works. Mirrors shared/backend/authclient/client.go
|
||||
and shared/packages/node-backend/src/authclient.js (the Go and Node
|
||||
equivalents) -- keep all three in sync if any changes shape.
|
||||
|
||||
Two kinds of consumer, two parts of this module:
|
||||
|
||||
- A service that only needs to gate requests behind "is this a valid
|
||||
AuthGuard session" (HordeWorker, Heretic) uses `AuthClient.validate` /
|
||||
`token_from_request` / `resolve_user`, calling only GET
|
||||
/api/session/validate. This is the original, minimal surface of this
|
||||
module.
|
||||
- A service that runs its own login/register/admin-user-management screens
|
||||
proxied to AuthGuard (mirroring shared/backend/authclient/client.go's
|
||||
full method set -- see e.g. Original/GameStream/backend/cmd/gamestreamd/auth.go
|
||||
for the reference Go implementation of this pattern) uses the additional
|
||||
methods below: register, login, logout, me, totp_*, *_password_reset,
|
||||
*_managed_user(s), setup_status.
|
||||
|
||||
Sync vs. async: every other I/O-bound module in this package (auth.py,
|
||||
postgres.py) is async, built on asyncpg, because a service using this
|
||||
package already runs its own request handling on an async event loop. A
|
||||
per-request session check is exactly the kind of call such a handler would
|
||||
`await`, so `AuthClient.validate` is async too, for the same reason the Go
|
||||
and Node versions are async/Promise-based: so it composes with the rest of
|
||||
an async request path instead of blocking it. This package's dependency
|
||||
list (asyncpg, bcrypt) has no async HTTP client, and adding one (aiohttp,
|
||||
httpx) just for a single small GET request is more than this needs. Instead,
|
||||
the actual HTTP call is a plain blocking `urllib.request.urlopen`, run off
|
||||
package already runs its own request handling on an async event loop. Every
|
||||
method here is `async` for the same reason. This package's dependency list
|
||||
(asyncpg, bcrypt) has no async HTTP client, and adding one (aiohttp, httpx)
|
||||
just for occasional small JSON requests is more than this needs. Instead,
|
||||
the actual HTTP calls are plain blocking `urllib.request.urlopen`, run off
|
||||
the event loop via `asyncio.to_thread` -- stdlib-only, and the awkwardness
|
||||
of raw async stdlib sockets/TLS/redirects is not worth it for one endpoint.
|
||||
of raw async stdlib sockets/TLS/redirects is not worth it here.
|
||||
|
||||
Framework-agnostic vs. framework-specific: this package's own README says
|
||||
"HTTP framework adapters stay in each service", and the two real prospective
|
||||
consumers of this module do not even share a framework -- HordeWorker's
|
||||
webui/server.py is aiohttp.web, Heretic's src/heretic/api/app.py is FastAPI.
|
||||
So there is no single framework to special-case here. Instead of a
|
||||
decorator/dependency tied to one framework, this module exposes
|
||||
`token_from_request`/`resolve_user` as plain functions over headers/cookies
|
||||
mappings (which is all `aiohttp.web.Request` and FastAPI/Starlette's
|
||||
`Request` both expose), and each service wires those into its own
|
||||
framework's idiom (an aiohttp `@web.middleware`, a FastAPI `Depends`, etc.)
|
||||
the same way it already owns its own routing.
|
||||
"HTTP framework adapters stay in each service". `token_from_request`/
|
||||
`resolve_user` are plain functions over headers/cookies mappings (which is
|
||||
all `aiohttp.web.Request` and FastAPI/Starlette's `Request` both expose),
|
||||
and each service wires those into its own framework's idiom (an aiohttp
|
||||
`@web.middleware`, a FastAPI `Depends`, etc.) the same way it already owns
|
||||
its own routing. The register/login/logout methods return the raw
|
||||
Set-Cookie header values AuthGuard's response carried rather than trying to
|
||||
set them on a framework-specific response object -- see SessionResult --
|
||||
for the same reason: each service's own route handler already owns the
|
||||
concrete Response object and knows how to attach headers to it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -44,8 +52,8 @@ import asyncio
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from typing import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Mapping
|
||||
|
||||
DEFAULT_COOKIE_NAME = "auth_session"
|
||||
DEFAULT_TIMEOUT = 5.0
|
||||
@@ -69,6 +77,26 @@ class AuthClientError(Exception):
|
||||
fail closed (401) on both."""
|
||||
|
||||
|
||||
class APIError(AuthClientError):
|
||||
"""Raised when AuthGuard responds with a non-2xx status to one of the
|
||||
register/login/.../setup_status methods below (not raised by validate(),
|
||||
which uses InvalidSessionError for its one specific non-2xx case).
|
||||
Mirrors Go's *authclient.APIError -- carries the status code and (when
|
||||
AuthGuard's JSON body decoded successfully) its {"error": "..."}
|
||||
message, so a caller can map it back onto its own service's response
|
||||
shape/status code rather than exposing AuthGuard's wording verbatim."""
|
||||
|
||||
def __init__(self, status_code: int, message: str, *, totp_required: bool = False) -> None:
|
||||
self.status_code = status_code
|
||||
self.message = message
|
||||
# Mirrors AuthGuard's {"totp_required": true} flag on a 401 from
|
||||
# POST /api/login that means "credentials were correct, but this
|
||||
# account has two-factor auth enabled and no (or an incorrect) code
|
||||
# was supplied" -- distinct from a plain invalid-credentials 401.
|
||||
self.totp_required = totp_required
|
||||
super().__init__(f"authclient: authguard responded {status_code}: {message}")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AuthGuardUser:
|
||||
"""The account AuthGuard resolved for a validated session. Mirrors the
|
||||
@@ -82,6 +110,55 @@ class AuthGuardUser:
|
||||
role: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PublicUser:
|
||||
"""The account object AuthGuard returns from POST /api/register,
|
||||
POST /api/login, and GET /api/me. Mirrors AuthGuard's publicUser (see
|
||||
internal/httpapi/server.go's toPublicUser) -- includes totp_enabled,
|
||||
which AuthGuardUser (from /api/session/validate) does not carry."""
|
||||
|
||||
id: int
|
||||
username: str
|
||||
email: str
|
||||
role: str
|
||||
totp_enabled: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ManagedUser:
|
||||
"""One row of GET /api/admin/users, and the payload returned by
|
||||
create_managed_user. Additionally carries created_at, which PublicUser
|
||||
does not."""
|
||||
|
||||
id: int
|
||||
username: str
|
||||
email: str
|
||||
role: str
|
||||
created_at: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SessionResult:
|
||||
"""Returned by register() and login(): the account AuthGuard resolved,
|
||||
plus the raw Set-Cookie header value(s) its response carried. A caller
|
||||
forwards these onto its own framework's response object, e.g. in
|
||||
FastAPI: `for cookie in result.cookies: response.headers.append("set-cookie", cookie)`."""
|
||||
|
||||
user: PublicUser
|
||||
cookies: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class TOTPEnableResult:
|
||||
"""Returned by totp_enable(): a freshly provisioned, not yet active TOTP
|
||||
secret and its otpauth:// URI for a QR code / authenticator app. Confirm
|
||||
it with totp_verify()."""
|
||||
|
||||
secret: str
|
||||
otpauth_url: str
|
||||
enabled: bool = False
|
||||
|
||||
|
||||
class AuthClient:
|
||||
"""Calls a centralized AuthGuard instance over HTTP."""
|
||||
|
||||
@@ -101,6 +178,8 @@ class AuthClient:
|
||||
self.cookie_name = cookie_name
|
||||
self.timeout = timeout
|
||||
|
||||
# --- session validation (the original, minimal surface) ----------------
|
||||
|
||||
async def validate(self, token: str) -> AuthGuardUser:
|
||||
"""Calls AuthGuard's GET /api/session/validate with token as a Bearer
|
||||
credential and returns the resolved user. Raises InvalidSessionError
|
||||
@@ -152,6 +231,244 @@ class AuthClient:
|
||||
role=str(payload.get("role") or ""),
|
||||
)
|
||||
|
||||
# --- shared request/response plumbing for everything below -------------
|
||||
|
||||
async def _call(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
token: str = "",
|
||||
body: Any = None,
|
||||
) -> tuple[dict[str, Any], list[str]]:
|
||||
"""Runs one JSON request/response round trip against AuthGuard, off
|
||||
the event loop. Returns the decoded JSON body (an empty dict for a
|
||||
2xx response with no body) and the raw Set-Cookie header value(s)
|
||||
the response carried. Raises APIError for a non-2xx response,
|
||||
AuthClientError for a transport/decoding failure -- mirroring Go's
|
||||
Client.call exactly, just spread across two return values instead
|
||||
of one (Go, request, out any)."""
|
||||
if not self.base_url:
|
||||
raise AuthClientError("authclient: client has no base URL")
|
||||
return await asyncio.to_thread(self._call_sync, method, path, token, body)
|
||||
|
||||
def _call_sync(
|
||||
self, method: str, path: str, token: str, body: Any
|
||||
) -> tuple[dict[str, Any], list[str]]:
|
||||
data = None
|
||||
headers: dict[str, str] = {}
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
if token:
|
||||
headers["Authorization"] = f"{_BEARER_PREFIX}{token}"
|
||||
|
||||
request = urllib.request.Request(
|
||||
f"{self.base_url}{path}", data=data, headers=headers, method=method
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
||||
status = response.status
|
||||
raw = response.read()
|
||||
cookies = response.headers.get_all("Set-Cookie") or []
|
||||
except urllib.error.HTTPError as exc:
|
||||
status = exc.code
|
||||
raw = exc.read()
|
||||
cookies = []
|
||||
except urllib.error.URLError as exc:
|
||||
raise AuthClientError(f"authclient: call AuthGuard: {exc}") from exc
|
||||
except OSError as exc:
|
||||
raise AuthClientError(f"authclient: call AuthGuard: {exc}") from exc
|
||||
|
||||
payload: dict[str, Any] = {}
|
||||
if raw:
|
||||
try:
|
||||
decoded = json.loads(raw)
|
||||
if isinstance(decoded, dict):
|
||||
payload = decoded
|
||||
except (ValueError, TypeError, UnicodeDecodeError) as exc:
|
||||
if not (200 <= status < 300):
|
||||
raise APIError(status, f"request failed ({status})") from exc
|
||||
raise AuthClientError(f"authclient: decode AuthGuard response: {exc}") from exc
|
||||
|
||||
if not (200 <= status < 300):
|
||||
message = str(payload.get("error") or f"request failed ({status})")
|
||||
raise APIError(status, message, totp_required=bool(payload.get("totp_required")))
|
||||
|
||||
return payload, list(cookies)
|
||||
|
||||
@staticmethod
|
||||
def _public_user(payload: dict[str, Any]) -> PublicUser:
|
||||
user = payload.get("user") or {}
|
||||
return PublicUser(
|
||||
id=int(user.get("id") or 0),
|
||||
username=str(user.get("username") or ""),
|
||||
email=str(user.get("email") or ""),
|
||||
role=str(user.get("role") or ""),
|
||||
totp_enabled=bool(user.get("totp_enabled")),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _managed_user(user: dict[str, Any]) -> ManagedUser:
|
||||
return ManagedUser(
|
||||
id=int(user.get("id") or 0),
|
||||
username=str(user.get("username") or ""),
|
||||
email=str(user.get("email") or ""),
|
||||
role=str(user.get("role") or ""),
|
||||
created_at=str(user.get("created_at") or ""),
|
||||
)
|
||||
|
||||
# --- setup / registration ------------------------------------------------
|
||||
|
||||
async def setup_status(self) -> bool:
|
||||
"""Calls GET /api/setup-status, an unauthenticated endpoint that
|
||||
reports whether AuthGuard has any account at all. Accounts are
|
||||
centralized in AuthGuard, so a caller with its own "first launch,
|
||||
create the initial admin" flow should consult this first: when it
|
||||
returns False, some account already exists (possibly created by a
|
||||
different project, or directly against AuthGuard), and the caller
|
||||
should show its ordinary login screen instead of its own
|
||||
account-creation form."""
|
||||
payload, _ = await self._call("GET", "/api/setup-status")
|
||||
return bool(payload.get("setup_required"))
|
||||
|
||||
async def register(self, username: str, email: str, password: str) -> SessionResult:
|
||||
"""Calls POST /api/register, creating a new AuthGuard account and
|
||||
starting a session for it."""
|
||||
payload, cookies = await self._call(
|
||||
"POST",
|
||||
"/api/register",
|
||||
body={"username": username, "email": email, "password": password},
|
||||
)
|
||||
return SessionResult(user=self._public_user(payload), cookies=cookies)
|
||||
|
||||
async def login(
|
||||
self, username_or_email: str, password: str, totp_token: str = ""
|
||||
) -> SessionResult:
|
||||
"""Calls POST /api/login. totp_token may be empty; AuthGuard raises
|
||||
an APIError with totp_required set when the account has two-factor
|
||||
auth enabled and no valid code was supplied."""
|
||||
body: dict[str, str] = {"username_or_email": username_or_email, "password": password}
|
||||
if totp_token:
|
||||
body["totp_token"] = totp_token
|
||||
payload, cookies = await self._call("POST", "/api/login", body=body)
|
||||
return SessionResult(user=self._public_user(payload), cookies=cookies)
|
||||
|
||||
async def logout(self, token: str) -> list[str]:
|
||||
"""Calls POST /api/logout, deleting the session identified by token
|
||||
server-side. Returns the (cookie-clearing) Set-Cookie header
|
||||
value(s) AuthGuard's response carried."""
|
||||
_, cookies = await self._call("POST", "/api/logout", token=token)
|
||||
return cookies
|
||||
|
||||
async def me(self, token: str) -> PublicUser:
|
||||
"""Calls GET /api/me, resolving token to its account."""
|
||||
payload, _ = await self._call("GET", "/api/me", token=token)
|
||||
return self._public_user(payload)
|
||||
|
||||
# --- TOTP ------------------------------------------------------------------
|
||||
|
||||
async def totp_enable(self, token: str) -> TOTPEnableResult:
|
||||
"""Calls POST /api/totp/enable, provisioning (or re-provisioning) a
|
||||
pending TOTP secret for token's account. The secret is not active
|
||||
until totp_verify confirms a generated code."""
|
||||
payload, _ = await self._call("POST", "/api/totp/enable", token=token)
|
||||
return TOTPEnableResult(
|
||||
secret=str(payload.get("secret") or ""),
|
||||
otpauth_url=str(payload.get("otpauth_url") or ""),
|
||||
enabled=bool(payload.get("enabled")),
|
||||
)
|
||||
|
||||
async def totp_verify(self, token: str, code: str) -> None:
|
||||
"""Calls POST /api/totp/verify, confirming code against the pending
|
||||
secret totp_enable provisioned and activating two-factor auth."""
|
||||
await self._call("POST", "/api/totp/verify", token=token, body={"token": code})
|
||||
|
||||
async def totp_disable(self, token: str, code: str) -> None:
|
||||
"""Calls POST /api/totp/disable, turning two-factor auth off for
|
||||
token's account. AuthGuard requires code to be one last valid TOTP
|
||||
code as proof of possession."""
|
||||
await self._call("POST", "/api/totp/disable", token=token, body={"token": code})
|
||||
|
||||
# --- password reset ("break glass", console-only -- see AuthGuard's README) --
|
||||
|
||||
async def request_password_reset(self, username_or_email: str = "") -> None:
|
||||
"""Calls POST /api/password-reset/request. AuthGuard prints a
|
||||
one-time code to its own process console; only an operator with
|
||||
access to that console can relay it onward. Sent with no
|
||||
username_or_email, the target is AuthGuard's superadmin account --
|
||||
AuthGuard's own web UI is the intended place to drive this, not an
|
||||
individual project (see AuthGuard's README's "Web UI" section)."""
|
||||
body = {"username_or_email": username_or_email} if username_or_email else {}
|
||||
await self._call("POST", "/api/password-reset/request", body=body)
|
||||
|
||||
async def confirm_password_reset(self, code: str, new_password: str) -> None:
|
||||
"""Calls POST /api/password-reset/confirm with the code an operator
|
||||
relayed out-of-band and a new password, and invalidates every
|
||||
existing session for that account."""
|
||||
await self._call(
|
||||
"POST",
|
||||
"/api/password-reset/confirm",
|
||||
body={"code": code, "password": new_password},
|
||||
)
|
||||
|
||||
# --- admin user management --------------------------------------------------
|
||||
|
||||
async def list_managed_users(self, token: str) -> list[ManagedUser]:
|
||||
"""Calls GET /api/admin/users. token's account must satisfy
|
||||
AuthGuard's CanManageUsers check (admin or superadmin), or this
|
||||
raises an APIError with status_code 401/403."""
|
||||
payload, _ = await self._call("GET", "/api/admin/users", token=token)
|
||||
return [self._managed_user(u) for u in payload.get("users") or []]
|
||||
|
||||
async def create_managed_user(
|
||||
self,
|
||||
token: str,
|
||||
*,
|
||||
username: str,
|
||||
email: str,
|
||||
password: str,
|
||||
role: str | None = None,
|
||||
) -> ManagedUser:
|
||||
"""Calls POST /api/admin/users. Only a superadmin actor may set role
|
||||
to anything other than "user"; anyone else's requested role is
|
||||
silently ignored by AuthGuard."""
|
||||
body: dict[str, Any] = {"username": username, "email": email, "password": password}
|
||||
if role is not None:
|
||||
body["role"] = role
|
||||
payload, _ = await self._call("POST", "/api/admin/users", token=token, body=body)
|
||||
return self._managed_user(payload.get("user") or {})
|
||||
|
||||
async def update_managed_user(
|
||||
self,
|
||||
token: str,
|
||||
user_id: int,
|
||||
*,
|
||||
username: str | None = None,
|
||||
email: str | None = None,
|
||||
password: str | None = None,
|
||||
role: str | None = None,
|
||||
) -> None:
|
||||
"""Calls PUT /api/admin/users/{id}. A None field means "leave
|
||||
unchanged" (AuthGuard applies only non-empty fields); role is only
|
||||
honored per AuthGuard's own authorization rules (only a superadmin
|
||||
actor, and never onto/away from a superadmin target) -- this client
|
||||
does not re-implement or pre-validate those rules."""
|
||||
body: dict[str, Any] = {}
|
||||
if username is not None:
|
||||
body["username"] = username
|
||||
if email is not None:
|
||||
body["email"] = email
|
||||
if password is not None:
|
||||
body["password"] = password
|
||||
if role is not None:
|
||||
body["role"] = role
|
||||
await self._call("PUT", f"/api/admin/users/{user_id}", token=token, body=body)
|
||||
|
||||
async def delete_managed_user(self, token: str, user_id: int) -> None:
|
||||
"""Calls DELETE /api/admin/users/{id}."""
|
||||
await self._call("DELETE", f"/api/admin/users/{user_id}", token=token)
|
||||
|
||||
|
||||
def token_from_request(
|
||||
headers: Mapping[str, str],
|
||||
|
||||
@@ -6,10 +6,13 @@ from email.message import Message
|
||||
from unittest.mock import patch
|
||||
|
||||
from shared_backend.authclient import (
|
||||
APIError,
|
||||
AuthClient,
|
||||
AuthClientError,
|
||||
AuthGuardUser,
|
||||
InvalidSessionError,
|
||||
ManagedUser,
|
||||
PublicUser,
|
||||
resolve_user,
|
||||
token_from_request,
|
||||
)
|
||||
@@ -18,9 +21,12 @@ from shared_backend.authclient import (
|
||||
class _FakeResponse:
|
||||
"""Minimal stand-in for the context manager urllib.request.urlopen returns."""
|
||||
|
||||
def __init__(self, status: int, payload: dict) -> None:
|
||||
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
|
||||
@@ -154,5 +160,258 @@ class ResolveUserTests(unittest.IsolatedAsyncioTestCase):
|
||||
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()
|
||||
Reference in new issue
Block a user