This commit is contained in:
1 parent
51e0a4217b
commit
ab3a6a19fb
5 files changed
+1094
-35
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],
|
||||
|
||||
Reference in new issue
Block a user