"""HTTP client for a centralized AuthGuard instance (see the AuthGuard project, 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 "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. 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 here. Framework-agnostic vs. framework-specific: this package's own README says "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 import asyncio import ipaddress import json import urllib.error import urllib.request from dataclasses import dataclass, field from typing import Any, Mapping DEFAULT_COOKIE_NAME = "auth_session" DEFAULT_TIMEOUT = 5.0 _BEARER_PREFIX = "Bearer " def _normalize_base_url(base_url: str) -> str: trimmed = str(base_url or "").strip().rstrip("/") if not trimmed: return trimmed if trimmed.lower().startswith(("http://", "https://")): return trimmed return f"http://{trimmed}" if _is_private_host(trimmed) else f"https://{trimmed}" def _is_private_host(hostport: str) -> bool: """Reports whether hostport (a bare "host" or "host:port", no scheme) names a loopback, RFC1918/RFC4193 private, or link-local address, or a ".local" mDNS name -- the kind of host a plain-HTTP AuthGuard is typically reachable at on a local network, as opposed to a public hostname expected to terminate TLS itself. Never performs DNS resolution: only literal IPs and the "localhost"/".local" names are recognized, so a real public hostname that merely happens to resolve to a private address still defaults to https. """ host = hostport if host.startswith("["): end = host.find("]") if end != -1: host = host[1:end] elif host.count(":") == 1: host = host.split(":", 1)[0] host = host.strip().lower() if host == "localhost" or host.endswith(".local"): return True try: ip = ipaddress.ip_address(host) except ValueError: return False return ip.is_loopback or ip.is_private or ip.is_link_local class InvalidSessionError(Exception): """Raised by validate() / resolve_user() when AuthGuard reports the token/cookie as not currently valid (expired, unknown, or missing).""" def __init__(self, message: str = "authclient: invalid or missing session") -> None: super().__init__(message) class AuthClientError(Exception): """Raised for a transport or decoding failure talking to AuthGuard -- kept distinct from InvalidSessionError so callers can tell "AuthGuard is unreachable/misbehaving" apart from "this visitor is unauthenticated" if they want to log or alert differently. Either way, callers should still 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 fields returned by GET /api/session/validate (and the Go/Node User types) -- deliberately not the local shared_backend.auth.AuthUser dataclass, which carries columns (email, password_hash, timestamps) that only exist for this package's own local Postgres-backed auth.""" id: int username: str 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.""" def __init__( self, base_url: str, *, cookie_name: str = DEFAULT_COOKIE_NAME, timeout: float = DEFAULT_TIMEOUT, ) -> None: """base_url is AuthGuard's base URL, e.g. "https://auth.example.com" (no trailing slash required). May be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080") -- the scheme is then inferred from the host: a loopback, RFC1918/RFC4193 private, or link-local address, or a ".local" name, defaults to "http://" (a plain-HTTP AuthGuard on a local network is the common case for those), anything else defaults to "https://". An explicit "http://" or "https://" is always left as-is, overriding the inference. cookie_name is the cookie token_from_request looks for when there is no Authorization header; it must match AuthGuard's SessionCookieName. timeout is the request timeout in seconds for the underlying blocking HTTP call.""" self.base_url = _normalize_base_url(base_url) 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 when AuthGuard reports the session as not valid (or token is empty/missing -- checked locally, without a network call), and AuthClientError for any transport/decoding failure.""" if not self.base_url: raise AuthClientError("authclient: client has no base URL") trimmed = (token or "").strip() if not trimmed: raise InvalidSessionError() return await asyncio.to_thread(self._validate_sync, trimmed) def _validate_sync(self, token: str) -> AuthGuardUser: request = urllib.request.Request( f"{self.base_url}/api/session/validate", headers={"Authorization": f"{_BEARER_PREFIX}{token}"}, ) try: with urllib.request.urlopen(request, timeout=self.timeout) as response: status = response.status body = response.read() except urllib.error.HTTPError as exc: # A non-2xx status still carries a body (AuthGuard's {"valid": # false, ...} JSON, typically on a 401); read it the same way a # normal response would be before falling through to decoding. status = exc.code body = exc.read() 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 try: payload = json.loads(body) if not isinstance(payload, dict): raise TypeError(f"expected a JSON object, got {type(payload).__name__}") except (ValueError, TypeError, UnicodeDecodeError) as exc: if status == 401: raise InvalidSessionError() from exc raise AuthClientError(f"authclient: decode AuthGuard response: {exc}") from exc if status != 200 or not payload.get("valid"): raise InvalidSessionError() return AuthGuardUser( id=int(payload.get("user_id") or 0), username=str(payload.get("username") or ""), 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], cookies: Mapping[str, str] | None = None, *, cookie_name: str = DEFAULT_COOKIE_NAME, ) -> str: """Extracts a session token the same way the Go and Node authclient versions do: an `Authorization: Bearer ` header first, falling back to a cookie named cookie_name. Returns "" if neither is present. Framework-agnostic by design (see the module docstring): pass whatever your framework's request object exposes as headers/cookies mappings, e.g. aiohttp's `request.headers` / `request.cookies`, or FastAPI's/ Starlette's `request.headers` / `request.cookies`. headers is looked up case-insensitively when the mapping supports it (both frameworks' header types do); a plain dict must already use the "Authorization" key. """ header = headers.get("Authorization") or headers.get("authorization") or "" if header.startswith(_BEARER_PREFIX): token = header[len(_BEARER_PREFIX) :].strip() if token: return token if cookies: token = (cookies.get(cookie_name) or "").strip() if token: return token return "" async def resolve_user( client: AuthClient, headers: Mapping[str, str], cookies: Mapping[str, str] | None = None, ) -> AuthGuardUser: """Extracts a token from headers/cookies with token_from_request (using client.cookie_name) and validates it against AuthGuard, returning the resolved user or raising InvalidSessionError / AuthClientError exactly like validate() does. This is the framework-agnostic building block every consumer wires into its own request pipeline, failing closed (401) on any exception from this call. For example, in an aiohttp `@web.middleware`: try: request["user"] = await resolve_user(auth_client, request.headers, request.cookies) except Exception: raise web.HTTPUnauthorized(reason="authentication required") Or as a FastAPI dependency: async def require_session(request: Request) -> AuthGuardUser: try: return await resolve_user(auth_client, request.headers, request.cookies) except Exception as exc: raise HTTPException(status_code=401, detail="authentication required") from exc """ token = token_from_request(headers, cookies, cookie_name=client.cookie_name) return await client.validate(token)