xtr-security
The security bundle for xtr applications: the family facade and the container wiring that configures it.
Why?
The security family is four libraries — xtr-security-core,
xtr-security-http, xtr-security-csrf and
xtr-password-hasher — each usable on its own. Wiring them together
by hand is a lot of moving parts: a token storage per request, voters gathered into a decision
manager, a user provider and a password hasher, and, per firewall, an authenticator over its own
event dispatcher, an access map, an entry point and the OpenAPI scheme it shows.
This package is the one bundle of the family. An application lists SecurityBundle, writes one
SecurityConfig, and the container owns the rest.
- 🔥 Firewalls as configuration — a slice of the request space, how it authenticates, and
the rules it enforces, in one frozen value.
- 🧩 Open at the seams — a third-party bundle adds a kind of authenticator, token handler or
user provider through the factory registries, without this package knowing it.
- 🪪 The FastAPI surface stays FastAPI's —
IsGranted and CurrentUser are dependencies
and decorators; the firewall itself runs as a subscriber over the kernel lifecycle's events,
before routing, and a route documents its security with the framework's own params.
- 🔒 Scoped to the request — the token storage, the authorization checker and the
Security
facade are per-request; concurrent requests never share them.
Install
uv add xtr-security # the bundle, wiring core, http, csrf and the password hasher
uv add xtr-console # beside it: debug:firewall and security:hash-password
uv add "xtr-security-http[oidc]" # + verifying third-party OIDC issuers' tokens
Requires Python 3.14.4+. The core, http-edge and password-hasher libraries come with the package;
xtr-console, installed beside it, adds the commands. The forgery-token library
comes with the package too — the bundle builds its manager itself where a firewall asks for a
token — and so does the rate limiter, whose factories a throttled
firewall's attempts count under. The oidc extra of
xtr-security-http adds joserfc and httpx; the bundle registers the OIDC
token handler, the userinfo handler and the OIDC login factories only when that extra is
installed. Self-issued JSON Web Tokens are a
separate package, xtr-security-jwt, which depends on this one and
registers itself through the extension points.
Quick start
Write a token handler that turns a bearer token into a user, configure a firewall that uses it,
and secure the routes — no JSON Web Tokens needed.
# app/security_handler.py
from xtr_dependency_injection import as_service
from xtr_security_core import InMemoryUser
from xtr_security_http import UserBadge
from xtr_security_http.access_token.access_token_handler_interface import (
AccessTokenHandlerInterface,
)
from xtr_security_http.exception import InvalidAccessTokenError
@as_service
class MyTokenHandler(AccessTokenHandlerInterface):
async def get_user_badge_from(self, access_token: str) -> UserBadge:
if access_token != "s3cret":
raise InvalidAccessTokenError("Unknown token.")
return UserBadge("alice", user_loader=lambda i: InMemoryUser(i, roles=["ROLE_USER"]))
# app/config/packages/security.py
from xtr_dependency_injection import configure
from xtr_security.bundle import (
AccessControlConfig,
AccessTokenConfig,
FirewallConfig,
SecurityConfig,
ServiceTokenHandlerConfig,
)
from app.security_handler import MyTokenHandler
@configure
def security() -> SecurityConfig:
return SecurityConfig(
firewalls={
"api": FirewallConfig(
pattern=r"^/api",
authenticators=(
AccessTokenConfig(
token_handler=ServiceTokenHandlerConfig(MyTokenHandler),
realm="api",
),
),
),
},
access_control=(AccessControlConfig(path=r"^/api", attribute="IS_AUTHENTICATED"),),
)
# app/web.py
from typing import Annotated
from fastapi import FastAPI
from xtr_dependency_injection import Kernel
from xtr_http_kernel import setup
from xtr_security_core.user.user_interface import UserInterface
from xtr_security_http import CurrentUser, IsGranted
from app.bundles import BUNDLES
app = FastAPI()
@app.get("/api/me")
async def me(user: Annotated[UserInterface, CurrentUser()]) -> dict[str, str]:
return {"user": user.get_user_identifier()}
@app.get("/api/books")
async def books() -> list[str]: ...
@app.delete("/api/books/{isbn}")
@IsGranted("ROLE_ADMIN")
async def delete_book(isbn: str) -> None: ...
kernel = Kernel("app")
setup(app, kernel)
$ curl -i localhost:8000/api/me
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api"
$ curl -i -H 'Authorization: Bearer s3cret' localhost:8000/api/me
HTTP/1.1 200 OK
{"user":"alice"}
Configure
SecurityConfig is a frozen dataclass buildable with no arguments; every field has a default,
so the zero-config path is no firewalls and the affirmative decision strategy.
| Field |
Default |
What it is |
firewalls |
{} |
The firewalls, keyed by name, matched in order — first match wins |
providers |
{} |
The user providers, keyed by the name firewalls refer to |
password_hashers |
{} |
The hasher each user class, "module:Class" string or name is hashed by |
role_hierarchy |
{} |
The roles each role reaches, expanding a token's roles |
access_control |
() |
The access-control rules, tried in order |
access_decision_manager |
affirmative |
How the voters' answers become one decision |
http_port |
80 |
The port plain http answers on, spelled out in a channel redirect when it is not the default |
https_port |
443 |
The port https answers on, spelled out in a channel redirect when it is not the default |
expose_security_errors |
NONE |
How much of an authentication failure reaches the client |
trace_votes |
None |
Announce every vote as an event and log every decision; None follows kernel.debug |
authenticator_factories |
built-ins |
The factories that build firewalls' authenticators |
token_handler_factories |
built-ins |
The factories that build access-token handlers |
user_provider_factories |
built-ins |
The factories that build user providers |
The built-ins the zero-config path carries: eight authenticator factories — access token,
form login, HTTP basic, JSON login, login link, remember me, remote user and X509 — joined by a
ninth, the OIDC login, only when the oidc extra is installed; two token-handler factories —
a service handler and the OAuth2 introspection one — joined by the OIDC and userinfo ones under
the same extra; and three user-provider factories — in-memory, chain and service. Nothing
else registers unconfigured: no firewall, no rule, no voter beyond the built-ins.
Firewalls
FirewallConfig claims a slice of the request space and says how it authenticates: