Files
shared/packages/python-backend/README.md
T
Gabriel20xxandClaude Sonnet 5 dcfdb3d7af Make AuthGuard integration decouple from knowing the URL at startup
Every language's AuthGuard client/service used "no URL at construction"
to mean "auth disabled forever" - a live SetBaseUrl/setBaseUrl push from
ProjectConfigurator could only ever retarget an *already-enabled* client,
never turn one on for the first time. That made AUTHGUARD_URL a de-facto
required env var everywhere, even though ProjectConfigurator can push it
live after startup.

- Go: shared/backend/auth's New/NewWithStore now default to a "pending"
  Service (still enabled, fails closed until a URL arrives) instead of
  disabled when authGuardURL is empty; add an explicit Disabled() option
  for the genuine standalone/local-dev opt-out.
- Python/Node/Java: add setBaseUrl/set_base_url to each AuthClient so a
  client built with an empty base URL can be retargeted in place once a
  URL is pushed, the same as the Go client already supported.
- Python/Node: add a coreconfig module (Info/Store), the framework-agnostic
  equivalent of shared/backend/coreconfig (Go), for services in those
  languages to receive ProjectConfigurator's core-services push at all.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-14 09:35:45 +02:00

156 lines
6.9 KiB
Markdown

# `gabriel20xx-shared-backend`
Shared Python backend infrastructure for services using `asyncpg`:
- validated `DATABASE_URL` and pool settings;
- 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;
- 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
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)])
...
```
`auth_client.set_base_url(url)` retargets an existing client's AuthGuard
base URL in place — the natural callback for `coreconfig.Store.on_update`
(see below), so a live `authGuardUrl` push from ProjectConfigurator takes
effect on the client's very next call with no restart. This also means a
service no longer needs to know its AuthGuard URL at construction time: a
client built with `AuthClient("")` is usable right away (it just fails
closed, with a clear error, until a real URL arrives), so a service that
gets its `AUTHGUARD_URL` from ProjectConfigurator's push doesn't need the
env var set at all — see `coreconfig` below.
## `coreconfig`: receiving AuthGuard's/CarrierNode's URL(s) from ProjectConfigurator
`shared_backend.coreconfig` is the Python equivalent of
`shared/backend/coreconfig` (Go): a small, framework-agnostic `Store` that
holds AuthGuard's and CarrierNode's current base URL(s), seeded from
whatever fallback (e.g. this service's own env vars, or nothing at all) you
give it, and updated live whenever ProjectConfigurator pushes a fresh
`PUT /api/core-services/internal`. A service wires the actual route itself:
```python
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore
auth_client = AuthClient("") # pending: no URL yet, still safe to use
core_config = CoreConfigStore(CoreConfigInfo(auth_guard_url=""))
core_config.on_update(lambda info: auth_client.set_base_url(info.auth_guard_url))
# in your framework's route for PUT /api/core-services/internal:
async def push_core_services(request):
if request.headers.get("X-Internal-Auth") != INTERNAL_SERVICE_SECRET:
raise HTTPException(status_code=401)
body = await request.json()
info = core_config.set(CoreConfigInfo.from_json(body))
return {"ok": True, "info": info.to_json()}
```
## `authproxy`: a ready-to-mount FastAPI router (optional)
Wiring up `authclient` still leaves each service reimplementing the same
~800-1000 lines of status/setup/login/logout/TOTP/admin-user-CRUD
boilerplate around it — three projects in this workspace independently did
exactly that before `shared_backend.authproxy` was extracted from them.
Unlike the rest of this package, `authproxy` is a deliberate, narrow
exception to "HTTP framework adapters stay in each service": it hard-depends
on FastAPI and Pydantic, and is only pulled in if you install the optional
`fastapi` extra:
```bash
pip install "gabriel20xx-shared-backend[fastapi]"
```
A service implements a small `ProxyStore` (two independent, genuinely
local concerns: a one-time "has this deployment's setup screen been
completed" claim flag, and optionally a "require login" toggle) and calls
`build_auth_router` once to get a fully-formed `APIRouter`:
```python
from shared_backend.authclient import AuthClient
from shared_backend.authproxy import ProxyStore, build_auth_router
class MyStore(ProxyStore):
async def login_required(self) -> bool: return True
async def set_login_required(self, required: bool) -> None: pass
async def is_setup_claimed(self) -> bool: ... # your own table
async def try_claim_setup(self) -> bool: ... # your own table
async def unclaim_setup(self) -> None: ... # your own table
def get_client(request):
return request.app.state.auth_client # AuthClient | None, or None in auth-disabled mode
def get_store(request):
return request.app.state.auth_store
app.include_router(
build_auth_router(get_client, get_store, legacy_cookie_name="myproject_session"),
prefix="/api/auth",
)
```
This mounts `/status`, `/me` (GET/PUT), `/admin-needed`, `/setup`, `/login`,
`/logout`, `/access` (GET/PUT, the login-required toggle), `/users`
(GET/POST), `/users/{id}` (PUT/PATCH/DELETE), and `/totp/status|initiate|verify|disable`
— the same URL paths and JSON response shapes as `shared/backend/auth`
(Go)'s `Service`, so a project migrating onto this module gets the same
standardized wire format that Go consumers of that engine already have.