Sync shared snapshot from 43d77dd
Docker / Docker Build & Push (push) Successful in 3m34s

This commit is contained in:
Gabriel20xx committed 2026-09-01 08:44:09 +02:00
1 parent 9a6ec940f7
commit fd32419371
114 files changed
+21997 -96

No files matched your search

+54 -1
View File
@@ -6,7 +6,10 @@ Shared Python backend infrastructure for services using `asyncpg`:
- one async pool owner with ping and graceful shutdown;
- bcrypt password and secure session-token helpers;
- short-lived, one-time admin reset codes printed to the server console;
- common account/session persistence for the single-admin or optional multi-user model.
- common account/session persistence for the single-admin or optional multi-user model;
- an `authclient` module for services that adopt AuthGuard, the centralized
identity service, instead of this package's own local Postgres-backed
auth (see below).
HTTP framework adapters stay in each service. Install this package from the
published index or directly from the shared repository with a subdirectory
@@ -15,3 +18,53 @@ install during development:
```bash
pip install "git+https://repos.gfranz.ch/Gabriel20xx/shared@v0.1.0#subdirectory=packages/python-backend"
```
## `authclient`: adopting AuthGuard instead of local auth
`shared_backend.authclient` is how a service trades its own local user table
for one HTTP call per request to a centralized AuthGuard instance's
`GET /api/session/validate`, gaining a single shared identity across every
project that does the same. It mirrors `shared/backend/authclient` (Go) and
`shared/packages/node-backend/src/authclient.js` (Node) — same shape,
translated to Python idioms. It's additive: switching to it is a deliberate
per-project decision, and no project is wired up to it automatically.
`AuthClient.validate` is `async` (stdlib `urllib` under the hood, run off
the event loop via `asyncio.to_thread`, so no new HTTP dependency), for the
same reason the Go/Node versions are async — it composes with an async
request handler instead of blocking it:
```python
from shared_backend import AuthClient, AuthClientError, InvalidSessionError
auth_client = AuthClient("https://authguard.example.com")
try:
user = await auth_client.validate(token) # AuthGuardUser(id, username, role)
except InvalidSessionError:
... # no/expired/unknown session - fail closed (401)
except AuthClientError:
... # AuthGuard unreachable or returned something unexpected - also fail closed
```
`token_from_request(headers, cookies)` extracts a token the same way the
Go/Node versions do — an `Authorization: Bearer <token>` header first,
falling back to a cookie (`auth_session` by default) — and `resolve_user`
combines that with `validate`. Both are plain functions over
headers/cookies mappings, not tied to any web framework (this package's
adapters stay in each service, per the note above); wire them into whatever
your framework's request pipeline looks like, e.g. as a FastAPI dependency:
```python
from fastapi import Depends, HTTPException, Request
from shared_backend.authclient import resolve_user
async def require_session(request: Request):
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
@app.get("/me", dependencies=[Depends(require_session)])
...
```
@@ -14,6 +14,14 @@ from .auth import (
normalize_role,
verify_password,
)
from .authclient import (
AuthClient,
AuthClientError,
AuthGuardUser,
InvalidSessionError,
resolve_user,
token_from_request,
)
from .config import DatabaseConfig, database_url_from_env
from .postgres import Database
from .tokens import hash_token, new_session_token
@@ -22,6 +30,12 @@ from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp
__all__ = [
"AuthStore",
"AuthUser",
"AuthClient",
"AuthClientError",
"AuthGuardUser",
"InvalidSessionError",
"resolve_user",
"token_from_request",
"ROLE_ADMIN",
"ROLE_SUPERADMIN",
"ROLE_USER",
@@ -0,0 +1,213 @@
"""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
"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
equivalents) -- keep all three in sync if any changes shape.
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
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.
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.
"""
from __future__ import annotations
import asyncio
import json
import urllib.error
import urllib.request
from dataclasses import dataclass
from typing import Mapping
DEFAULT_COOKIE_NAME = "auth_session"
DEFAULT_TIMEOUT = 5.0
_BEARER_PREFIX = "Bearer "
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."""
@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
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). 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 = str(base_url or "").strip().rstrip("/")
self.cookie_name = cookie_name
self.timeout = timeout
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 ""),
)
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 <token>` 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)
@@ -0,0 +1,157 @@
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()