This commit is contained in:
1 parent
9a6ec940f7
commit
fd32419371
114 files changed
+21997
-96
No files matched your search
@@ -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)
|
||||
Reference in new issue
Block a user