Files
CollabTable/shared/packages/python-backend/README.md
T
Gabriel20xxandClaude Haiku 5.5 362cee26fd
Security / Secrets (gitleaks) (push) Successful in 1m1s
Security / Dependencies (Trivy) (push) Successful in 51s
Security / Code (Semgrep) (push) Successful in 1m29s
Docker / Docker Build & Push (push) Successful in 5m28s
Sync shared snapshot from 8701874
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-21 00:23:35 +01:00

267 lines
13 KiB
Markdown

# `gabriel20xx-shared-backend`
Shared Python backend infrastructure for services using `asyncpg`:
- validated `DATABASE_URL` and pool settings;
- one async pool owner with startup retry, ping, and graceful shutdown;
- bcrypt password helpers (`verify_and_upgrade_password_async` returns a current-scheme hash for a login to store) 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"
```
Database startup uses `DB_INIT_RETRY_INTERVAL_MS` (default `5000`, minimum
`250`) and `DB_INIT_RETRY_MAX_ATTEMPTS` (default `0`, retry indefinitely). Only
transient connection errors are retried; bad credentials or a missing database
fail at once.
`authproxy.build_auth_router` limits login attempts (10 per account and 200 per
client address per 15 minutes) and TOTP verify/disable attempts (5 per user), in
process memory, and answers `429` beyond that. The client address is the TCP
peer; `X-Forwarded-For` is read only from peers inside `TRUSTED_PROXIES` (a
comma-separated list of CIDR ranges or IP addresses, empty by default; the
`trusted_proxies` argument overrides it, and an invalid list raises
`ValueError` at startup). The same address reaches AuthGuard as
`X-Forwarded-For` through `authclient.forwarded_client_ip`, which AuthGuard reads
only from peers in its own `TRUSTED_PROXIES`.
`AuthStore` refuses an empty password hash and a username containing `@`
(`EmptyPasswordHashError`, `InvalidUsernameError` in `shared_backend.auth`),
refuses `set_totp_secret` while TOTP is enabled (`TotpAlreadyEnabledError`), and
makes usernames unique ignoring case when no clashing pair already exists.
`hash_password` refuses a password longer than 72 bytes, the most bcrypt reads.
## `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 fastapi.responses import JSONResponse
from shared_backend import AuthClient, CoreConfigInfo, CoreConfigStore, handle_core_services_push
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:
@app.put("/api/core-services/internal")
async def push_core_services(request):
status, body = handle_core_services_push(
core_config, SECRET, request.headers.get("X-Internal-Auth"), await request.body()
)
return JSONResponse(body, status_code=status)
```
`handle_core_services_push` is the framework-neutral body of the route. It returns
`(status, body)`, so any framework can send it, and it does the checks in this order:
- `X-Internal-Auth` must equal SECRET, compared in constant time, or the response is
401 `{"error": "internal service authentication required"}`. A SECRET that is not usable
(see below) gets 401 for every caller.
- A body over 4096 bytes, or one that is not a JSON object, gets 400
`{"error": "invalid JSON body"}`.
- A non-empty `omniLoggerUrl`, `authGuardUrl` or `carrierNodeUrl(s)` that is not an http or
https URL with a host gets 400 `{"error": "core service URL must be an http or https URL with a host"}`.
- Otherwise it returns 200 `{"ok": true}`. The response never includes the ingest token.
Other fields are ignored.
The store keeps the last non-empty value of each field, so a partial push never clears a stored
one. OmniLogger's URL and this service's ingest token (`CoreConfigInfo.omni_logger_url` and
`omni_logger_ingest_token`) are not used by the store's AuthGuard or CarrierNode logic. A
log shipper follows them through `follow_omnilogger`:
```python
shipper = Shipper.from_env("myservice") or Shipper(base_url="", ingest_token="", service="myservice")
follow_omnilogger(core_config, shipper) # once, at startup; later pushes call shipper.set_credentials
```
`follow_omnilogger` calls `shipper.set_credentials(url, token)` after a push, but only once
both values are stored, so a token-only push never disables or re-points the shipper.
Don't seed the store with `OMNILOGGER_*` values from the environment. Those belong to the
shipper, and seeding them would make a token-only push re-point it.
`internal_secret_matches` also refuses a SECRET shorter than `MIN_INTERNAL_SECRET_LENGTH`
(16 characters) or equal to an example placeholder (`EXAMPLE_INTERNAL_SECRETS`), so every
internal route gated by it rejects all callers until the secret is set properly. Call
`internal_secret_usable(SECRET)` at startup to log a warning for that case.
## `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.
## `logshipper`: mirroring logs to OmniLogger
`shared_backend.logshipper` is the Python counterpart of `shared/backend/logshipper`
(Go): it sends log entries to the workspace's central OmniLogger, and it is additive.
A service keeps its console logging as it is and adds an `OmniLoggerHandler` beside
its existing handlers, so each record also reaches OmniLogger:
```python
import logging
from shared_backend import OmniLoggerHandler, Shipper
shipper = Shipper.from_env("myservice", level="info") # None unless both env vars are set
if shipper is not None:
logging.getLogger().addHandler(OmniLoggerHandler(shipper))
...
if shipper is not None:
shipper.close() # on graceful shutdown; also runs at interpreter exit
```
`from_env` reads `OMNILOGGER_URL` and `OMNILOGGER_INGEST_TOKEN` and returns `None` when
either is unset or empty, so a disabled service makes no network calls and logs
exactly as before. The `level` argument is the threshold (`debug`, `info`, `warn`,
`error`, `critical`, or `silent`); it defaults to `info`.
`set_credentials(base_url, token)` changes where entries are sent, and the ingest token
used, while the service runs. It is thread-safe and takes effect from the next flush, and
the background thread keeps running. An empty base URL or token disables shipping: entries
are no longer buffered, anything already buffered is dropped, and console output is
unchanged. `Shipper(base_url="", ingest_token="", service=...)` builds a disabled shipper
up front, so a push from ProjectConfigurator can enable it later (see `coreconfig` above).
The handler maps `DEBUG`, `INFO`, `WARNING`, `ERROR` and `CRITICAL` to `debug`, `info`,
`warn`, `error` and `critical`. Entries are batched in a daemon thread and sent every 2
seconds, or as soon as 100 are buffered, with a 5-second HTTP timeout and bearer auth.
The buffer holds 2000 entries and drops new ones when full. Failures and drops are
reported on stderr at most once a minute and never raise into the caller.
Entries are clamped before buffering, because OmniLogger rejects a whole batch when
one entry breaks a limit. A message over 8192 bytes is cut on a character boundary
and given a ` [truncated]` suffix. A context over 16384 bytes, or one containing a NUL,
becomes `{"context_dropped":true}`. A NUL in a message is written as the text `\u0000`.
Batches are split to stay within 1000 entries and under 2 MiB per request. `Shipper`
never prints, so the service's own console output is unchanged.