Fastro - The Benav Labs FastAPI boilerplate Changelog¶
Introduction¶
The Changelog documents all notable changes to the Fastro FastAPI boilerplate, organized by version. For releases before v0.18.0, see GitHub releases.
For the full narrative on each release — rationale, decisions, migration guide — see the corresponding GitHub release page.
Unreleased¶
Changed¶
virtualenv21.14.13 andfilelock4.2.4, for eighteen advisories published against the versions the lock held. Both arrive throughpre-commit, which lives in thedevextra, so the image installs neither and a deployment is unaffected: the advisories are about the environments a hook runs in and the lock files it takes, on the machines that run the hooks.pre-commit run --all-filespasses on the new versions.
0.20.0 - October 25, 2026 - Composable Features¶
Every feature in the boilerplate can now be removed: its routes, models, settings, admin views,
seeders and tests come out together, and the project still imports, lints, type-checks and passes
the remaining tests. tools/removal_drill.py proves it for nine presets, and CI runs them as a
matrix. The round that followed fixed what a re-review of the refactor found.
Added¶
- crudauth's account routes, mounted under
/api/v1/auth:POST /change-password(verifies the current password, then revokes the account's other sessions) andGET /me.set-passwordis deliberately not mounted, so an account that signs in with a provider still has no password. src/wiring/, the composition root.app.py,settings.py,hooks.py,models.pyandadmin.pylist what this project selected;backend/scripts/seeders.pyandbackend/tests/wiring.pydo the same for seeders and fixtures. See Composable Features.- Contribution shapes in
infrastructure/composition.py:RouterMount,Lifecycle,PermissionSource,RateLimitResolver,TierDeleteGuard,TierDeleteRelease,ReadinessCheck. tools/removal_drill.py— builds the repository without each feature and runs six checks (the app imports, every module imports, ruff, mypy, tests, and a migration baseline that applies to an empty database) per preset.scripts/cleanup_api_key_json.py— a one-off repair for API key rows holding what no code can read: apermissionsvalue that isn't a list of names (a JSON null, or the object an older version stored) becomes an empty scope, and ausage_limitsvalue keeps the windows the limiter counts and loses the rest.- A test over the documentation's code samples —
tests/unit/test_docs_imports.pyresolves everyfrom src…and relative import in apythonblock underdocs/againstbackend/srcand fails on a name that isn't there, so a sample that can't be pasted into a project fails the suite. GET /health/ready— answers503while a dependency the project selected is unreachable: the database, and the cache, the login lockout's Redis, the session store and the task broker for the features it has. Checks run together, each with a two-second timeout; the report is reused for a couple of seconds, and two checks pointed at one server are asked once.GET /healthstays a liveness probe that touches nothing.- Retries for background tasks. The worker loads Taskiq's
SimpleRetryMiddleware, so a task labelledretry_on_error=Trueis retried;TASKIQ_DEFAULT_RETRY_COUNT(default 3) is how many times it runs in all, the first attempt included, and0turns retries off. A task that doesn't ask for retries still runs once. - A scheduler for background tasks, as its own entry point:
taskiq scheduler src.infrastructure.taskiq.scheduler:schedulerruns the schedules tasks declare in aschedulelabel, over Taskiq'sLabelScheduleSourceand the broker and task importsworker.pyalready set up.bp deploy generatewrites aschedulerservice next to the worker — and writes neither for a project without the taskiq feature. Exactly one scheduler may run: each one fires every schedule it finds. - The removal drill migrates. Every preset now autogenerates its baseline against the models the project kept and applies it to an empty database, so a feature that can be removed stays one Alembic can describe.
- crudauth 0.8.2. The account routes come from it. 0.8 keeps every session id and CSRF token
under an HMAC of its value keyed with
SECRET_KEY, so read access to the session store yields nothing that can sign in, and ends the session a browser presented when that browser signs in again — a copied cookie dies at the account's next login. See Breaking Changes. The release also carries the fixes the email flows and OAuth need: an inactive account is sent no recovery mail and its outstanding links are refused (0.7.5), an OAuth sign-in refuses an inactive account before linking or claiming it (0.7.4), andrepo.gated_register_fields()names the privileged fields an app's own signup schema must not offer (0.7.2) — a test holds this project'sUserCreateto that. - The
@cachekey covers the query string and the caller. A cached response used to be keyed byprefix:resource_idalone, so two pages of one listing shared an entry and an authenticated route could serve one caller's response to another. The key is nowprefix[:resource_id][:q=sorted query][:u=caller]; a route whose response is the same for everybody opts out withper_caller=False, and one that keeps the default but resolves no caller is not cached at all. An empty answer ([],{},"") is now stored and served instead of reading as a miss, and a write invalidates the entry for its resource rather than one keyed by its own query string, and a cache it cannot reach is logged and stepped over instead of answering500.GET /api/v1/rate-limits/ships cached, with its writes clearing every page; it takes the decorator fromwiring/cache.py, which hands a project without the cache feature one that caches nothing. - A role management API under
/api/v1/roles, with the rbac feature: list, read, create, rename and delete roles, replace what a role carries, and assign or unassign it. Each route is gated by its ownrole.*permission and runs the delegation checks, so a caller can neither grant a permission nor assign a role carrying one that they don't hold themselves — including emptying or relabelling a role stronger than they are, or changing the roles of an account that is a superuser or holds something they don't, which is the rule auser.updateholder is already held to. A refused delegation answers403and writes nothing; an unregistered permission name answers422without echoing it.GET /api/v1/users/{user_id}/rolesreads an account's roles. - An API-keys guide, API Keys: creating and scoping a
key, calling with
X-API-Key, what a key holds and what it cannot do, the usage limits and the rows every request writes, revoking and rotating, how a key is stored and why that storage is a plain digest, and how to declare the header in the OpenAPI document if a project wants it in/docs. The authentication overview keeps the two commands and points at it. - Usage limits on an API key, enforced per key.
usage_limitstakes a request count per window —requests_per_minute,requests_per_hour,requests_per_day— counted per key id through the limiter behind the login lockout, so several workers share one count on a sharedRATE_LIMITER_BACKEND. A filled window answers429withRetry-Afterfrom the transport, which covers every route a key can reach rather than only the throttled ones, and counting fails open so an unreachable limiter can't take the API down. A key with no limits is not counted. - A usage row per key-authenticated request. One
KeyUsagerow carrying the path, the method, the status the client actually got, the elapsed milliseconds, the address and the user agent, written as a background task after the response so no request waits for it. Refusals are recorded too — the429s from a key's own limit, and the500s from a route that raised; a session request records nothing. The api_keys feature contributes the middleware through the wiring's installers, so a project without the feature records nothing and has no middleware. last_used_ipbesidelast_used_at, both stamped by that same background task rather than while the request is being authenticated, which now writes nothing at all. They carry the address the trusted-proxy boundary resolved, as the login lockout does, so the key and its usage rows name the client and not the proxy in front of it.- A key holds its owner's permissions, narrowed to its scope. A key-authenticated request holds
what its owner holds — every
PermissionSource, and for a superuser every registered permission — intersected with the key's own scope, so the scope only ever narrows: a permission the owner loses disappears from the key, and a key scoped to nothing holds nothing beyond identity.GET /api/v1/permissions/mereports the narrowed set. A credential carrying a scope is never a superuser, because the flag grants what no scope can name: the transport cancels it on the principal and records the account's flag in the credential's metadata, where only the narrowing reads it. So every consumer gets it right without remembering —require_permissions, the superuser-only routes, the delegation checks behind the role routes (which now compare against what the credential holds rather than reloading the owner's grants), and the ownership checks behind editing an account or reading its tier and rate limits. - A key's scope may name only permissions its creator holds.
POST /api/v1/api-keys/, and aPATCHthat widens a scope, answer403when the scope names something the calling session doesn't hold, and write nothing. An unscoped key needs no permission at all. - A device list.
GET /api/v1/auth/sessionsreports every session an account holds — device, IP, when it signed in, when it was last active, and which one is the caller's — andDELETE /api/v1/auth/sessions/{handle}signs one of them out. Both come from crudauth's session-management router, both take a session principal and nothing else, and a session is named by its handle rather than its id, so the listing is safe to render. A handle belonging to another account answers404. SESSION_BACKEND=databaseandRATE_LIMITER_BACKEND=database, which keep sessions, CSRF tokens, the one-time tokens behind the email flows, the OAuth state and the rate-limit counters in two tables of the project's own database —crudauth_storeandcrudauth_counters— so several workers share them with no Redis to run. The counters matter as much as the sessions: withmemory, each of N workers counts login failures on its own and an attacker gets N times the attempts. Either setting on its own builds the store, and each keeps its own backend, so sessions on Redis with counters in the database is a valid pair. The tables are declared on the project'sBase.metadata, soCREATE_TABLES_ON_STARTUPcreates them andalembic revision --autogeneratewrites them beside the project's own; selecting the backend is a schema change and wants one migration.SESSION_ABSOLUTE_TIMEOUT_HOURS, the most a session may live from sign-in however active it stays, for a project that wants a periodic re-login. Unset by default, so the idleSESSION_TIMEOUT_MINUTESstays the only timeout; a value below one hour is refused when the app starts. A session past the cap is removed and its next request answers401.- An
X-API-Keytransport, with the api_keys feature: a request carrying a valid key is authenticated as the key's owner, withtransport="apikey"on the principal, no CSRF token required and no cookie in the answer. A key that is unknown, malformed, revoked, expired or whose owner a soft delete has taken out answers401— on a route that answers anonymous callers too, since a credential that is present and wrong is not an absent one. The session transport is tried first, so a request carrying both is its session.src/wiring/transports.pyregisters it, so a project without the feature has no second transport, and the drill generates that file. - Session-only routes.
POST /api/v1/auth/change-password,POST /api/v1/auth/email/change-request,POST /api/v1/auth/logout,POST /api/v1/auth/logout-alland every/api/v1/api-keys/route take a session principal and nothing else, so a key can neither escalate through them nor manage keys.DELETE /api/v1/users/{username}takes one too, so a key cannot close the account that issued it.POST /api/v1/auth/refresh-csrfalready read the cookie directly, so a key has never reached it. A password change still revokes only sessions: a key carries no password, and is revoked on its own. - Admin-panel views for the RBAC tables, with rbac and admin: roles, the grants that make
them up, and who holds them. The role listing shows the permissions each role carries, the grant
form offers only names the registry knows, and the holder listing, its count and its account
picker leave out accounts a soft delete has taken out. The panel signs in with the
ADMIN_*credentials, which already setis_superuseron anybody, so the API's delegation checks have no weaker operator to hold back there. GET /api/v1/permissionslists every registered permission grouped by resource, andGET /api/v1/permissions/melists what the caller effectively holds — from everyPermissionSourcethe project wired, every registered permission for a superuser, and never a grant whose name the registry no longer knows. Both come with the rbac feature.- GitHub sign-in, beside Google. A provider is wired when both of its settings are set
(
OAUTH_GITHUB_CLIENT_ID/OAUTH_GITHUB_CLIENT_SECRET), so a project can run either, both or neither, and the settings that used to be read by nothing now wire up the routes. An address GitHub has not verified is refused with?error=email_unverifiedand creates no account. - A provider-only account can set its first password through the reset link, which proves the
address first;
POST /set-passwordstays unmounted, since a borrowed session must not be able to put a password on such an account. - The account recovery flows, mounted from crudauth under
/api/v1/auth: email verification (email/verify-request,email/verify-confirm), password reset (password/reset-request,password/reset-confirm) and a confirmed email change (email/change-request,email/change-confirm). The request routes answer the same for an address with no account, a token is single-use, a completed reset ends every session the account had, a confirmed change notifies the old address, and an inactive account — a soft-deleted one included — is sent nothing and has its outstanding links refused.FRONTEND_URLis where the links point (your own pages, which POST the token to the matching confirm route); production refuses an empty orlocalhostvalue. - A sender for the account emails.
EMAIL_BACKENDpicks it:consolelogs each message with its link and sends nothing (the default, so a fresh project needs no mail server),smtpdelivers overEMAIL_SMTP_*with the server's certificate verified. With the taskiq feature present the wiring hands delivery to theemail:sendtask, so no request waits on the mail server; without it the request sends directly.EMAIL_BACKEND=smtpwithoutEMAIL_SMTP_HOSTis refused when the app starts, on either path, and production refusesconsole: it would log working reset links. FORWARDED_ALLOW_IPSis now documented, and the generated nginx stack puts the containers on a fixed subnet and trusts forwarded headers only from it (bp deploy generate nginx --internal-subnet …).LOG_FORMATnow decides the formatter, with each environment's format as the default.
Changed¶
- The admin panel's login lockout has a key space of its own. It counted failures on the API
login's policy, against the identifier
admin-panel:<address>, and crudauth keys that half of the lockout on whatever string arrives as a username: sevenPOST /api/v1/auth/logincalls withusername=admin-panel:<address>locked the real operator at that address out of the panel, with the correct password. Behind a wrongTRUSTED_PROXY_HOPS, where every admin shares the proxy's address, one caller locked all of them out. The panel now counts on aLockoutPolicyof its own, over a limiter backend built under theadmin-panel:rl:prefix, so nothing the API writes can reach it. The thresholds are still theLOGIN_*settings, and panel failures still lock the panel. - The admin panel's login has a budget every address shares. Failures were counted per address
only, against the single
ADMIN_PASSWORD, so a caller changing address guessed at it without limit: each new address arrived with a full budget of its own. A second lockout now counts every failure the panel refuses, whatever address sent it, against five timesLOGIN_MAX_ATTEMPTSin the same window (25 with the defaults), under theadmin-panel:rl:all:prefix. Past it the panel refuses every address forLOGIN_LOCKOUT_BASE_SECONDS, and since the failures keep counting for the rest of the window, the first attempt after that lock ends locks it again for twice as long, up toLOGIN_LOCKOUT_MAX_SECONDS; the rounds are kept for an hour and that hour starts again with every lockout. So about 26 attempts can keep the panel shut for close to an hour, and every retry while it is shut, the operator's own included, makes it longer. That is the trade for a password that can be guessed at 25 times a window, and one more reason to keep the panel off the public internet; the panel's guide says how to clear the counters and open it again. A login that succeeds gives back the one attempt it made and leaves the failures that came from elsewhere counted. - The admin panel refuses an unsafe method from another site. sqladmin carries no CSRF token,
so
SameSite=Laxwas the whole defence: a sibling subdomain, or script on a same-site frontend, could post to the panel with the operator's cookie and get a302and the row it asked for.SameOriginOnlynow stands in front of the panel's session and answers403toPOST,PUT,PATCHandDELETE, and to aGETof an action route (/{identity}/action/{slug}, where sqladmin serves every@action), unlessSec-Fetch-Sitesayssame-originornone, orOriginnames the host the request arrived at. The admin cookie isSameSite=Strictas well, so it travels on nothing another site starts; a link into the panel from elsewhere lands on the login page, and opening it from the address bar signs you back in.Strictdoes not cover a sibling subdomain, which is the same site to a browser, so the guard is what stands betweenother.example.comand an action link. A request carrying neither header is allowed, so curl and scripts keep working: no site can make a browser send a request with no origin. - The two RBAC listings export their cells as text.
UserRoleAdminandRolePermissionAdmincarried noTextCsvExportMixin, and sqladmin exports every view unless the view says otherwise, soGET /admin/user-role/export/csvwrote a role named=1+1and an account labelled=HYPERLINK("http://x","y")into the file as they stood, for a spreadsheet to run on opening. Both views carry the mixin now and statecan_export = Truerather than inheriting it, and a test sweepsADMIN_VIEWSso a view that exports without the mixin ahead ofModelViewfails the suite instead of shipping. - An admin session is bounded by the login that created it. The cookie's
Max-Agewas the only bound, and Starlette starts that clock again whenever something writes to the session, which a flashed message does, so an operator who kept working kept a session alive indefinitely. Nothing tied a session to the credentials either: changingADMIN_PASSWORDleft a stolen cookie working until it expired. A session now carries the time it was issued and a fingerprint ofADMIN_USERNAME:ADMIN_PASSWORD, derived with scrypt and salted withSECRET_KEY, and the panel refuses it eight hours after that login however active it has been, or as soon as either credential changes, which is the panel's only way of revoking a session. The work factor is what the cookie makes necessary: it is readable by whoever holds it, so a fast hash of a password an operator chose would be one a word list could be run against by anybody who also had the key. The derivation is made as the panel is built and kept for as long as the credentials it was made from, so no request waits for it. A refused session is cleared, so the browser stops sending it. Sessions from before this version carry neither field and are refused, so every operator signs in once after it is deployed. - Signing out of the panel takes a
POST. sqladmin serves logout onGETand links to it from every page, so anything that made the operator's browser fetch/admin/logoutsigned them out, withSameSite=Laxsending the cookie along. The route answers aGETwith a one-button form now and clears the session only on that form'sPOST, which the guard above holds to the panel's own origin. The sidebar link still leads there; a bookmark reaches the form rather than signing anybody out. A panel built on an sqladmin that serves no route by that name refuses to start, rather than leaving aGETthat signs out. - A refused panel login is recorded. The panel logged
Admin login failed, which named neither the caller nor what was tried, andAdmin login locked out for 300s, which named no caller either; neither reached the audit lines a refused API login writes through crudauth'son_login_failedandon_lockouthooks. The panel writes those same lines now, naming the door it refused at:login refused at the admin panel: 'admin' from 203.0.113.7 (curl/8.4.0); invalid_credentials, andlogin locked out at the admin panel (every address) for 300s, from …where the shared budget is what ran out. A username the panel has no account for is kept out of the line, as one the API has no account for already was. The lines crudauth's hooks write now namethe login api, so a log holding both says which door each refusal arrived at. - The image carries
backend/scripts. It copiedsrc,migrations,alembic.iniand the tests, so every documented command that runs a script inside a container answeredNo module named 'scripts':docker compose exec api python -m scripts.setup_initial_datafrom the first-run guide, and thecleanup_api_key_jsonandcanonicalize_emailsrepairs an upgrade needs. The base stage copies the directory now, so the dev, migrate and prod stages all have it. The documentation gives both forms for the two repairs, since the container's working directory is/app/srcwhile the scripts sit at/app/scripts:python -m scripts.<name>in there, anduv run --no-sync python scripts/<name>.pyfrombackend/on the host. crudauth_storeandcrudauth_countersare part of the schema, whatever the backends say. They were declared onBase.metadataonly whereSESSION_BACKENDorRATE_LIMITER_BACKENDnameddatabase, so the schema depended on a runtime choice two ways: a baseline generated with the default backends held neither table, leaving a later move toSESSION_BACKEND=databasewith nowhere to write; and autogenerating with the default against a database-backed deployment wrote a revision that dropped both. Both tables are now declared whenever the accounts feature is present, which adds two empty tables to a project that keeps its sessions in Redis, anddatabase_storestill staysNoneuntil a setting selects it. A deployment already on migrations picks the two tables up in its nextalembic revision --autogenerate, which creates them: that revision is additive and harmless, and only has to be applied before switching either setting todatabase.- The production validator stops describing a Redis connection for a limiter that isn't on
Redis. It listed
RATE_LIMITER_REDIS_*wheneverRATE_LIMITER_ENABLEDwas true, so a project counting in memory (and now in the database) was warned about a Redis it never opened. It now readsRATE_LIMITER_BACKEND. POST /api/v1/auth/logoutruns through crudauth'scomplete_logoutinstead of revoking the session and clearing the cookies by hand. The answer is unchanged, and the route still takes a session principal and nothing else, but every configured transport's cookies are now cleared and theon_after_logouthook runs, naming the ended session by its handle. The hand-written version ran no hook, so anAuthHooks(on_after_logout=…)an app registered saw every logout but this one.- API keys are hashed with SHA-256, as
sha256$<digest>of the key. A key is 384 bits fromsecrets.token_urlsafe(48), not a password, so a salted work factor bought nothing and cost a scrypt derivation per request — which anyone holding a key prefix, and listings show them, could make the server pay on junk. A request now finds its row through one indexed lookup onkey_hash. A key stored with the oldscrypt$…hash still authenticates, through the prefix lookup and the same verification as before, and its row is rewritten as a digest on that first use. Until that happens, every request carrying its prefix costs a derivation, not only the ones its owner makes. - Emails are stored canonically (lowercased, as crudauth looks them up), on signup, on update and
in the admin panel.
UserService.get_by_emailcanonicalises its lookup, so seeding a superuser with a mixed-caseADMIN_EMAILis idempotent. - Tier rate limits match the route template the request hit (
/api/v1/users/{username}), not the concrete path, and soft-deleted rows no longer apply. - Page sizes are bounded: every listing takes
pageanditems_per_pagefrom one shared dependency, capped at 100, and sorts with an id tie-break. - An API key's
expires_atmust carry a UTC offset. - API-key routes answer through schemas — creating a key no longer returns its hash.
- An explicit
nullfor a column the row requires is refused with422; the guarded names come from the model, so a new column can't be forgotten. - Creating tables imports every model first, so
scripts/create_tables.pyandscripts/setup_initial_data.pycreate the whole schema. get_logger()names the logger after its caller's module, so per-module levels and the structuredmodulefield work.- Structured log lines escape quoted values, so client text can't forge a field.
- The admin panel's session cookie is its own middleware, scoped to the panel's own mount
(
ADMIN_BASE_URL, plus whateverroot_paththe request arrived through),Secureoutside local and development, and valid for 8 hours. Changing a user's address in the panel clearsemail_verified. - The secret-key check measures placeholders, hand-written words, repeated blocks (whole or with
a remainder), ordered runs, walks across neighbouring keyboard keys, and words anyone would
recognise, each against a share of the whole value, plus an entropy floor. No key was refused in 100,000
samples of each of
token_hex(16),token_hex(32),token_urlsafe(24)andtoken_urlsafe(32), while"12345678" * 4,qwertyuiopasdfghjklzxcvbnm123456,1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik,,"monkey" * 5 + "12",hunter2hunter2hunter2hunter2hunter22,Summer2026!Summer2026!Summer2026!!,MyCompanyApiSigningKeyForProd2026andthisismysupersecurekeyforthisappnever do. - The API metadata defaults are empty, so a generated project's OpenAPI document carries no
contact, licence or URL it didn't configure, and emits a licence
identifierorurl, never both. - The database name, the RabbitMQ vhost and every Redis URL are escaped or refused rather than rendered raw.
- CI lints and type-checks
backend/scriptsandbackend/migrations, type-checkstools, pins Python on the sync step, and runs the removal drills. - The generated local stack publishes Postgres and Redis on
127.0.0.1only, and the Taskiq Redis result backend stores results as JSON instead of pickles. GET /health/readygates on the dependencies a request needs. The wiring lists them inCRITICAL_READINESS_CHECKS(the database, and the login lockout's Redis and the session store with accounts) andINFORMATIONAL_READINESS_CHECKS(the cache and the task broker). A critical check that fails answers503; an informational one is logged and leaves the answer200.- The readiness body carries the overall status only, and probes that arrive together share one run of the checks. Which dependency answered what goes to the log, written by the probe that ran them.
ADMIN_BASE_URLdecides where the panel is mounted, and the admin session cookie is scoped to the path each request arrived through, prefix included (--root-path /svcgives/svc/admin). Moving the panel, or serving the app under a prefix, no longer leaves every admin request bouncing back to the login form.- The removal drill rebuilds the wiring this repository commits. The generator produces the real
router order and the same imports, and a test regenerates
src/wiring/,scripts/seeders.pyandtests/wiring.pyfor the features a project carries and compares the trees, so generator drift fails the suite rather than going unnoticed. The drill's mypy step now coverssrc scripts migrations tests, as CI does. - A rate limit's
pathis validated as the route template it has to match. The pattern is anchored at both ends, so a trailing newline or space is refused; Starlette's converters ({id:int},{id:uuid},{p:path},str,float) are accepted, as are templates with literal text around the placeholder (/items/{id}.json,/v{version}/items); an unknown converter and two placeholders in one segment are refused. The documented paths now carry the trailing slash the listing routes declare (/api/v1/users/). - The generated nginx vhost replaces
X-Forwarded-Forwith the address it saw ($remote_addr), rather than appending to whatever the client sent, and--internal-subnetis refused unless it names a network address of/8or smaller for IPv4, or/48or smaller for IPv6 - a wildcard, a/0, or a value with host bits set no longer reaches the compose file. The subnet is quoted in the generated YAML. - The input that used to answer
500now answers422.pageis capped at2**31 - 1, so the offset stays a number the database can read; an API key's id is bounded to the range itsIntegercolumn covers; anexpires_atwhose offset moves it past the dates a datetime can hold is refused; and text that is not valid Unicode - a lone surrogate in a password orcurrent_password- is refused before it reaches a hash or a write. A NUL character is refused the same way now. Postgres refuses the whole statement carrying one (invalid byte sequence for encoding "UTF8": 0x00), soPOST /auth/loginwithusername=a%00b, a signup whose name holds one, andGET /users/%00all answered 500 with a traceback, the first two to anybody. The guard covers this project's own request bodies, its URLs and its login form: the write schemas refuse a NUL at any depth, including inside a dict key;NulCharacterMiddlewareanswers before the router for a path or a query carrying one; and the login form is refused before the identifier reaches a query.tests/unit/interfaces/test_request_text.pysweeps the routes so a new body cannot forget the guard. crudauth's own bodies take their fields as plainstr, and a lone surrogate in one answered 500 to anybody:{"token": "\ud800"}onemail/verify-confirm,email/change-confirmorpassword/reset-confirmreachedjwt.decode, which encodes the token as UTF-8 and raises, and anew_passwordcarrying one reached the hash. Every crudauth route this project mounts now carriesbody_a_database_can_hold, which refuses a lone surrogate or a NUL anywhere in a JSON body, keys included, and answers 422 naming the field. It reads the content type the wayfastapi.routingdoes, so anapplication/merge-patch+jsonbody is read as JSON as well, and a body with no content type reaches no field while routes keepstrict_content_type. Only a JSON escape can carry a lone surrogate, since percent-decoding replaces one, so a path, a query and a form cannot. - A soft-deleted tier keeps its soft-deleted users.
TierService.deleteno longer clearsuser.tier_idon rows a soft delete had already removed - onlypermanent_deletedoes, where the foreign key requires it - and a soft-deleted user no longer blocks either delete. A soft-deleted rate limit no longer blocks a tier delete either; a permanent delete removes those rows throughTIER_DELETE_RELEASES, a new contribution point insrc/wiring/hooks.pyfor whatever a feature keeps for a tier. - The admin panel really refuses a deleted tier. sqladmin hands the form's selection over as a primary key, so the old check never fired: the panel now loads the tier and refuses a soft-deleted one, the picker lists only live tiers, and the Tiers listing counts what it shows.
- A soft-deleted tier or rate limit no longer reaches
GET /api/v1/users/{username}/rate-limits. Both joins exclude deleted rows, and a user left pointing at a deleted tier reports no tier and no limits instead of the deleted one's. - The readiness checks name their servers more carefully. Two checks pointed at one server are
asked once whatever database index or password follows the port; a cache in the process
(
CACHE_BACKEND=memory) names no server at all; the memcached check asks on a connection of its own and closes it, rather than handing the app's pool back a connection with an unread reply; a report answers only for the checks it was taken for; and a check whose target can't be named is still asked, with the failure logged. - The seed scripts run on their own.
python scripts/create_first_superuser.pyandpython scripts/create_first_tier.pyimport the models before touching the ORM, and report a failure as one line with exit code1- admin settings that don't describe an account, a password the policy refuses, a taken username, or a database they can't reach. The message for a takenADMIN_EMAILnames the setting rather than the address. - Creating an API key answers with its own schema. The response carries the row as the read
schema reports it plus the full key, with
key_metadataandlast_used_ipexcluded;GET /api/v1/api-keys/{id}still reports both. - Another user's public profile carries the display fields only.
GET /api/v1/users/{username}answers withid,name,usernameandprofile_image_url; the fields features add to the read schemas, such astier_id, stay on/users/me, on/users/{username}/tierfor the owner or a superuser, and on the superuser endpoints. - The admin panel's CSV export writes formula-like cells as text. Text starting with
=,+,-,@, a tab or a carriage return is prefixed with an apostrophe, so a name typed at signup can't become a formula in a spreadsheet. Numbers, dates andNoneare written unchanged. - Failed statements report their SQL without their values. The engine is built with
hide_parameters=True, and the catch-all handler logs the method, path and support id without the exception text, so a failing insert no longer writes a password hash to the log. An email address longer than the column (50 characters) answers422instead of500. - The guarded
/openapi.jsonserves the schema the app builds. In staging, or in production with docs enabled, it was rebuilt from the title, version and description alone, so the contact, licence, summary, terms of service and tags never reached a reader. Both paths now callapp.openapi(). - A log line can't be forged from client text. Every character
str.splitlines()ends a line on — CR, LF,\x0b,\x0c,\x1c–\x1e,\x85,U+2028,U+2029— and every other control character, ANSI escapes included, is written out as an escape: in thestructuredfields, in thesimpleanddetailedmessages, and in thejsondocument, where\x85,U+2028andU+2029used to be written raw. Asimpleordetailedtraceback stays readable over several lines, each of them indented, so nothing after a record's first line starts at column 0. Printable text, accents and symbols included, is left as it is. LOG_FORMATnames the console format only, and is validated when the settings load: a value no formatter implements is refused by name instead of raising from the formatter the first time anything logged. A log file keeps its environment's format, which is what a collector reading it expects.- The guarded docs follow the mount the request arrived through. Behind
--root-path /svcthe gated Swagger and ReDoc pages asked for/openapi.json, which answers404there; they now ask for/svc/openapi.json, and the schema names/svcas its server, as the ungated docs already did. bp env gen-secretdraws again when the app's own rules would refuse the key. Run inside a project, it checks each draw againstis_weak_secret_key: one hex key in 12.6 million runs through eight consecutive digits, which production refuses at startup. Run outside a project, where those rules aren't there to ask, it prints the first draw as before.- A resource that already exists answers
409.ResourceExistsErrormapped to fastcrud'sDuplicateValueException, which is a422, while the routes that raise it declare409: the signup route, the profile update and the rate-limit rename. The mapping now uses aConflictExceptionof this project's own, and the messages are unchanged. - The admin panel's login is throttled. Failures are counted in a lockout of the panel's own,
against the client address and the identifier
admin-panel:<address>, and a locked address is refused before its password is compared. One address therefore has separate budgets at the two doors, and nothing sent to/api/v1/auth/logincan lock the panel; the cost is that the panel is no longer slowed by an address already failing at the API's door. The address comes fromget_client_ip(request, TRUSTED_PROXY_HOPS), so behind a proxy the caller is counted rather than the proxy. - The login lockout's thresholds are stated, not inherited.
LOGIN_MAX_ATTEMPTS=5,LOGIN_ATTEMPT_WINDOW_SECONDS=900,LOGIN_LOCKOUT_BASE_SECONDS=300andLOGIN_LOCKOUT_MAX_SECONDS=3600reach crudauth as aLockoutConfig. The window was crudauth's own default of 60 seconds, which five tries a minute never trip; counting over fifteen minutes is what makes a paced attack accumulate, and a first lockout of five minutes makes resuming cost more. - The pre-commit hooks run what CI runs.
docformatter,blacken-docsandmdformatare gone:ruff-formatowns formatting, and the two documentation hooks damaged what they touched —mdformatstrips the indentation MkDocs content tabs need, andblacken-docsrewrote a sample's keyword arguments into a different statement. The manualunit_testhook runspytest tests/unitinstead of the whole suite, and a root[tool.ruff.lint.isort]withknown-first-party = ["src", "scripts"]makes ruff run frombackend/over../toolssort imports the way the run in CI does. - The documentation and
.env.exampledescribe what the code does. Settings that never existed are gone (DATABASE_ECHO,DATABASE_POOL_SIZE);OAUTH_GITHUB_*says that nothing reads it; the CORS text says that a*origin drops credentials rather than carrying cookies; the admin pages say the session cookie is signed and that the edit form has no password field; the pagination page shows the sharedPageDep/ItemsPerPageDepbounds instead of ale=1000that no route has; the Docker page describes the stackbp deploy generate localwrites (api,worker,postgres,redis) instead of a hand-written one namingappanddb; the testing page namesbackend/tests, sayspytest -m unitselects nothing until you mark tests, and says CI does run the integration tests; the--no-syncflag is explained as skipping uv's implicit sync rather than saving the dev tools from removal; and the client-cache page no longer claimsCACHE_ENABLEDgates the middleware. - Thirty broken imports in the documentation's samples now name what they import:
require_permissionscomes fromauth.authorization, the cache functions fromcache.providerand the decorator fromcache.decorator,default_brokerfromtaskiq.brokersandDBSessionfromtaskiq.deps,Basefromdatabase.session, andregister_permissions/discover_permissionsfrominfrastructure.permissions. The task-discovery sample points at the worker entry point instead of the deliberately import-free package__init__, anddatabase/models.mddescribes the two walkers that find models and permissions instead of a hand-written list that no longer exists. - The API-key read schemas describe a row, not a request.
APIKeyReadandKeyUsageReadno longer inherit the create rules — the name's length, the expiry's offset, the HTTP method, the status-code range — so a row an earlier version wrote is readable instead of answering500. What a caller may send is unchanged, and the fields in each response are the same. create_applicationrefuseslifespan=together withlifecycles=with aTypeError. The passed lifespan used to win silently, leaving every feature the wiring listed unstarted.- The API process opens the task broker. The taskiq feature contributes a
Lifecyclethat the wiring lists, so the broker starts with the app and closes on shutdown. WithTASKIQ_BROKER_TYPE=rabbitmq,.kiq()from a request used to raiseSendTaskErrorfrom taskiq'sNoStartupError, because nothing had runbroker.startup()in that process. A broker that is unreachable at startup doesn't stop the app: it logs a warning, serves, and reconnects in the background. - The RabbitMQ broker is built with no argument the library doesn't take.
queue_name="default"is not anAioPikaBrokerparameter in taskiq-aio-pika 0.6.0, so it was forwarded to the AMQP connection while the queue kept the library's own name. The queue a worker reads is unchanged (taskiq); the Redis broker'squeue_name="default"is a real parameter and stays as it is. - Readiness covers a RabbitMQ broker. The
task_brokercheck reads the live state of the connection the app's lifespan holds — ready while it is up, unavailable while it is being opened or reconnected after an outage — and names the broker it reports on either way. It stays informational, so a broker outage never answers503. API_PREFIXnow moves the whole API. The OAuth routes and theno-storecache header are derived from it instead of writing/apiout, and a prefix the router cannot mount (v2,/,/api/, empty) is refused by name when the settings load rather than raising anAssertionErrorat import.scripts/setup_initial_data.pycreates tables only where the project creates its own. It calledcreate_tables()in every environment, so the documented first-deploy step wrote the schema behind alembic's back, and a baseline applied afterwards failed withDuplicateTableError: relation "roles" already exists. WithCREATE_TABLES_ON_STARTUPoff it now seeds rows and says it created none, so it can be run after the migrations rather than instead of them. It also refuses to seed into a database that has no schema, naming what is missing and saying to runalembic upgrade headfirst, rather than failing inside a seeder.- A documented upgrade path for databases that already have tables.
Migrations
spells out stamping the baseline's own revision id —
headwould mark the revisions after it applied without running them — thenalembic upgrade headfor everything after the baseline, thenalembic check, which autogenerates and so refuses withTarget database is not up to date.while anything is pending. It also gives the order a deployment moving off auto-created tables runs: the repair scripts, the baseline, the stamp, later revisions, the check, then the seeding script. - The documented way to generate a baseline now produces one. The recipe ran
alembic revision --autogenerateagainst whatever.envpointed at, which in a dev setup is the databaseCREATE_TABLES_ON_STARTUPalready built withcreate_all: autogenerate compares the models with that database, finds no difference, and writes a revision whoseupgrade()ispass. Applying it leaves a production database empty. The recipe now makes a throwaway database and names it on the command line, and says whyPOSTGRES_SERVER=postgresout of.env.examplecannot work from your shell.bp deploy generate's printed steps point at the page instead of repeating the bare command. alembic upgraderefuses to run with no revisions. It used to createalembic_version, exit0, and leave a database with no schema, which is what a fresh production deploy got:CREATE_TABLES_ON_STARTUPis off there, so the API then failed every request. The message names the one command that has to run on an empty history,alembic revision --autogenerate -m baseline, which is let through.- A
schemareadiness check, critical.GET /health/readyanswers503unless the database carries the schema this code was written against, and the log line says what it found. Reachability alone reported an unmigrated database as ready, so a deploy that never ran its migrations took traffic and failed every request that read a row. Where the project has migrations the check compares the database's revision with their head, which also catches a database that has every table and is missing a column; where it has none, or whereCREATE_TABLES_ON_STARTUPbuilt the schema, it compares the declared tables with the existing ones. It names no server, so it is asked rather than mirrored from thedatabasecheck, and the production image now carriesmigrations/andalembic.iniso it can read them. -
A key is refused once its owner's account has been recovered.
user.token_versionis a new column, and crudauth's bump of it now takes effect: it was a no-op while the model had no such column, so nothing marked an account as recovered. crudauth bumps it when a password is changed, a reset is completed, or an OAuth provider claims the account.api_keys.owner_token_versionrecords the generation a key was minted under, and theX-API-Keytransport answers401for a key from an older one, so a key minted from a stolen session dies when the owner resets their password, and a key minted under someone else's address dies when they claim it. Ending sessions still leaves keys working, since a key holds none.The same column reaches sessions, which crudauth records with the generation they were created under: a session from before a reset, a password change or a provider claim is now refused by that check as well, on top of the explicit revocation crudauth already did at each of those points. Both columns default to
0, so accounts and keys that exist today match until the first recovery. -FRESH_SIGN_IN_SECONDS, and closing an account asks for one.DELETE /api/v1/users/{username}refuses a session that signed in longer ago than the window with403 Sign in again to continue., so a cookie someone else is holding cannot close the account on its own. Unset, closing an account asks nothing, and crudauth's/set-passwordand MFA-enrolment routes, where a project mounts them, keep crudauth's own 10-minute default; setting it applies one window to all of them, and a value below one second is refused at startup.FreshSessionPrincipalDepputs the same gate on a route of your own. Only a session knows when it signed in, so no other credential is ever fresh. - A refused sign-in is recorded. crudauth'son_login_failedandon_lockouthooks are registered withrecord_a_refused_loginandrecord_a_lockout(infrastructure/auth/audit.py), so every refused password login writes oneWARNINGwith the reason (invalid_credentialsorinactive, which the401does not distinguish), the client addressTRUSTED_PROXY_HOPSresolves and the user agent — and a lockout writes how long it refuses for. An identifier is written out only where an account has it: what arrives in the username field may be a typo, a probe, someone else's address or a password typed one box too high. The lockout line names no identifier, since nothing resolves one before it refuses. A project that would rather write an audit table replaces those two functions. - An OAuth sign-in keeps what the provider owns in step.refresh_the_provider_profile(infrastructure/auth/oauth_profile.py) is registered as crudauth'son_oauth_loginhook, so every sign-in that reaches an active account stampsoauth_updated_at— which nothing wrote on a returning sign-in before — and takes the provider's picture intoprofile_image_urlwhile the account still carries the placeholder avatar it was created with. An avatar or display name the account set is never overwritten.DEFAULT_PROFILE_IMAGE_URLinmodules/user/constants.pyis now the one place that placeholder is written. - A guide to migrating passwords,docs/user-guide/authentication/migrating-passwords.md: why a hash another library wrote with plain bcrypt never matches crudauth's own check (it bcrypts a base64 SHA-256 digest of the password), howlegacy_verifiersaccepts those hashes at login and rewrites each one as its owner signs in, what a verifier must refuse so a leaked unsalted digest can't be typed as a password, that the password policy does not apply to an imported hash, and how to finish and then drop the migration.tests/integration/auth/test_legacy_passwords.pyholds the sign-in, the rehash and the wrong-password refusal the page describes. - A section on running a second crudauth app beside this API, under Sessions: what two apps collide over when they share one Redis database or onecrudauth_store— the per-user session index, which is keyed by user id rather than by the HMAC the session records are under, so each app's device list,logout-alland session cap reach the other's sessions for the same id, and with a sharedSECRET_KEYa cookie from one app signs in to the other; the cookie names overwriting each other in a browser; and the lockout counters merging — withstorage_prefix,csrf_storage_prefix,cookie_name,csrf_cookie_nameand the limiter's prefix against each. It also records thatrate_limit_prefixcannot be combined with therate_limiter=this project passes, so a prefix belongs inbuild_rate_limiter, and that the shipped sqladmin panel is not such an app: itsadmin_sessioncookie andadmin-panel:<address>lockout identifier already stand apart. - An observability guide,docs/user-guide/observability.md: the signals the project already emits (JSON logs, the support id on a failed request, the refused-login audit lines, readiness per dependency, thekey_usagerows) and the two gaps tracing fills — no request id on a log line and no latency per route. Then a recipe for Logfire that stays off untilLOGFIRE_TOKENis set (send_to_logfire="if-token-present"), wired throughINSTALLERSinsrc/wiring/app.py, with the worker configured separately because it never imports that module; what not to export (captured headers carry the session cookie andX-API-Key; statement and parameter capture carry addresses, hashes and session ids; pattern scrubbing cannot know an identifier is a username; the probes are noise); sampling; and what the same recipe looks like against a plain OpenTelemetry collector. - An emptyDOCS_URL,REDOC_URLorOPENAPI_URLswitches that page off, which is what the production checklist and the development guide have always said it does. The empty string was passed to FastAPI as a path, so outside production the app refused to start at all withPrefix and path cannot be both empty; in production it worked only because the environment already forces all three off. The same block registered the three paths a second time where FastAPI was already serving them, so/docs,/redocand/openapi.jsoneach had two routes in local and development; the gated router is now built only where it is the one serving. - A generated compose stack takes the database credentials from the environment file. Thepostgresservice mappedPOSTGRES_USER,POSTGRES_PASSWORDandPOSTGRES_DBthrough${VAR:-postgres}in itsenvironmentblock. Compose interpolates those from the shell or a root.env, never from theenv_filethe service also names, andenvironmentoverridesenv_file, so a password set inbackend/.env, which is where every page says to set it, was replaced inside the container by the literalpostgres: the database initialised with the well-known default and the API could not connect with the password it had been given. The three names are the ones the official image already reads, so the block is gone andenv_filesupplies them; the readiness probe readsPOSTGRES_USERinside the container rather than through compose, so a project that renames the user is still probed correctly.local,prodandnginxwere all affected: regenerate withbp deploy generate <mode>, and recreate the database volume if it was initialised with the default password. - Every dependency carrying a published advisory moved to a patched release: aiohttp 3.14.5, anyio 4.15.1, certifi 2026.10.23, Mako 1.4.3, multidict 7.2.1, pydantic-settings 2.16.1, PyJWT 2.15.1, python-multipart 0.0.32, sqladmin 0.32.0, starlette 1.10.0 and urllib3 2.8.0, which is what the lock resolves on every Python the project supports and what the image installs. The floors this project declares moved with them where the package is one of its own dependencies (sqladmin>=0.28.0,pydantic-settings>=2.14.2), andanyio>=4.15.1andstarlette>=1.3.1are declared for the first time, since the task groups, middleware, requests and responses the project imports come from them rather than through FastAPI. sqladmin takes arequestinexport_dataas of 0.28, which the CSV export mixin accepts and passes on, and which the floor is set to: on 0.27 the mixin's own call would have raisedTypeError. The export tests call it the way sqladmin's endpoint does, and a parameter it gains that the mixin does not fails them.
Removed¶
KeyTypeandKeyStatus, two API-key enums nothing read.KeyTypenamed access levels (public,private,admin,service,webhook) that no column stored and no route gated on;KeyStatusnamed a lifecycle (active,suspended,revoked, …) that the routes express withis_activeandexpires_at. A key's scope is what decides what it may do.HTTPMethodstays: the usage schema validates against it. See Breaking Changes.- The
key_permissionstable and its vocabulary: theKeyPermissionmodel, theKeyPermissionResource/KeyPermissionActionenums, the fourKeyPermission*schemas,APIKeyWithPermissions,crud_key_permissionsandAPIKeyService._check_permission. An API key's scope isAPIKey.permissionsalone. See Breaking Changes. CSRFException, which nothing raised.TaskRegistry/register_task(infrastructure/taskiq/registry.py), a second task registry nothing wrote to.default_broker.get_all_tasks()is the one taskiq keeps.- Settings nothing read:
LOG_CORRELATION_ID,LOG_INCLUDE_STACKTRACE,LOG_PERFORMANCE_METRICS,LOG_SQL_QUERIES,LOG_STRUCTURED_CONTEXT,DEFAULT_CACHE_EXPIRATION,TASKIQ_WORKER_CONCURRENCY,TASKIQ_MAX_TASKS_PER_WORKER,POSTGRES_SYNC_PREFIX,PRODUCTION_SECURITY_STRICT_MODE,TASKIQ_ENABLED. handle_exception: routes let domain errors propagate to the global handler.- The legacy OpenAPI identity settings
CONTACT_NAME,CONTACT_EMAILandLICENSE_NAME, which theAPI_CONTACT_*andAPI_LICENSE_*settings replace. - The
envoption in the pytest config, which needed a plugin the project doesn't install. - The
check-docstring-firstpre-commit hook, which refused 40 of this project's files. A module-level name documented with an attribute docstring under it reads to the hook as a second module docstring, and that is how every constant here is documented, so running it needed an exclude list the length of the project.pre-commit run --all-filespasses again.
Breaking Changes¶
- The admin panel is off until a project asks for it.
ADMIN_ENABLEDdefaults tofalsewhere it defaulted totrue, and the panel is not mounted at all whenADMIN_USERNAMEorADMIN_PASSWORDis empty: the startup log says which one is missing. A deployment that reached/adminwithout settingADMIN_ENABLEDhas to set it, along with both credentials, and gets a404until it does. Mounted without credentials, the panel served a login form that nothing could pass, to anyone who asked for it. POST /api/v1/auth/refresh-csrfis nowPOST /api/v1/auth/csrf/refresh, andPOST /api/v1/auth/logout-allanswers{"detail": …, "revoked": N}where it answered{"message": …, "terminated_count": N}. Both routes now come from crudauth's session-management router, with the device list, rather than being written here: the CSRF refresh gained a self-heal (a token that is still valid comes back unchanged) and a per-address rate limit, andlogout-allkeeps itskeep_currentquery. A client calling the old path gets404.- Two new columns need a migration:
user.token_versionandapi_keys.owner_token_version. Both carry a server default of0, so the nextalembic revision --autogenerateadds them without touching existing rows, and every account and key starts in the same generation. Apply the migration before deploying this version: the models select both columns, so without them every request that loads an account or a key fails. - Minting an API key needs a verified address.
POST /api/v1/api-keys/answers403until the account has confirmed its email, because an unverified address may belong to somebody else: it is what lets an attacker register under a victim's address, mint a key, and keep API access after the victim claims the account through a provider. Accounts that signed in with a provider are verified already; a password signup confirms throughPOST /api/v1/auth/email/verify-request. A deployment with unverified accounts that hold no keys yet should expect those users to verify before they can mint one. KeyTypeandKeyStatusare no longer importable fromsrc.modules.api_keys. Neither was read anywhere: a project using them for its own bookkeeping should copy the enum it wants into its own module.- An API key's
usage_limitsmay name only a window the limiter counts. The column took any JSON object, so{"requests_per_fortnight": 10}stored cleanly and enforced nothing. It now takesrequests_per_minute,requests_per_hourandrequests_per_day, each a positive whole number of requests, and anything else answers422. A limit already stored under another name keeps reading back as it is and counts for nothing — the way a stored permission the registry no longer knows grants nothing.python scripts/cleanup_api_key_json.pynow rewrites those rows too: it keeps the windows the limiter counts and drops the rest, so a repaired row holds exactly what is enforced. - An unknown
SESSION_BACKENDis refused when the app starts. A value crudauth has no store for —memcached, say, left over from before sessions moved to crudauth — used to fall through to memory sessions, which start fine and then lose every session on each deploy and share none between workers. The app now fails at startup, naming the values it supports. - Upgrading signs every user out once. crudauth 0.8 looks a session up under an HMAC of its id
keyed with
SECRET_KEY; sessions written by 0.7 are stored under the raw id and are no longer found, so every signed-in user logs in again after the deploy. From now on, changingSECRET_KEYdoes the same. Nothing else here is affected:/set-passwordand MFA, which 0.8.1 put behind a fresh sign-in, are not mounted by this project. -
An API key's scope is a list of registry permission names.
APIKey.permissionsheld a free-form JSON object, and a second copy of a key's scope lived inkey_permissionsrows keyed by a vocabulary of their own (conversations,credits,user_profile,*, …) that no route could check. Both are gone:permissionsis now alist[str]of registered permission names — the same names a role carries andrequire_permissionsgates on — validated on create and update, where an unregistered name answers422.GET/POST/PATCH /api/v1/api-keys/all speak the list; a client sending the old object gets422.Nothing translates the old vocabulary, since none of its values is a registered permission. Run
python scripts/cleanup_api_key_json.pyonce after upgrading: it empties everypermissionsvalue that isn't a JSON array, so those keys are unscoped and keep working for identity, and rescope them with the names your project registers. A row left holding an object makes the owner's listing answer500.A deployment that already has a
key_permissionstable still has it: the model is gone, so the nextalembic revision --autogeneratedrops the table and every scope stored in it. Run the cleanup script and rescope the keys that need it before serving from the new revision.APIKeyService.validate_api_keyno longer takesresourceandaction— it matches a key to a live row and reports its owner and its scope.APIKeyValidationRequestlost the same two fields. -PATCH /api/v1/users/{username}no longer takesemail(or thecurrent_passwordthat gated it); both now answer422. An account moves its address throughPOST /api/v1/auth/email/change-request, which confirms the new address and notifies the old one, and an administrator can still correct one from the admin panel, whose form carries the field. The password-gated direct change is gone, with itsEmailChangeNeedsPasswordError/ProviderAccountEmailChangeErrorand the budget it counted against. -CREATE_TABLES_ON_STARTUPis off outside local and development, and production refusestruewith a startup error. A production deploy that relied onBase.metadata.create_allrunning on boot has to generate the baseline against an empty database as Migrations describes, review it, commit it, and apply it before the API starts — the generated compose stack has amigrateservice for exactly that. Nothing waits on that service any more either: rundocker compose --profile migrate run --rm migrateand only thendocker compose up -d. - Changing your own email address now requires the account's current password in thePATCH /api/v1/users/{username}body (current_password), and answers403without it. Every change that needs the password counts against the same budget asPOST /api/v1/auth/change-password, correct passwords included: 5 per hour per account, then429. So an account can change its address at most five times an hour. An account with no usable password (provider sign-in only) can't change its address at all. A superuser changing someone else's address is unchanged: no password, no limit. The address change still clearsemail_verified, which is what made a stolen session enough to take an account over through a provider login. - The caller-resolving dependency aliases moved frominfrastructure/dependencies.pytoinfrastructure/auth/deps.py:CurrentUserDep,CurrentSuperUserDep,OptionalUserDep,CurrentPrincipalDep,CurrentPermissionsDep,OAuth2FormDep.AsyncSessionDepstays. - An emptyCORS_ORIGINSnow allows no cross-origin request, where it used to mean "any origin". A*origin never gets credentials, and is refused outright in production. - Rate-limit rows that name a concrete path stop matching. Rewrite them as the route template the router declares (/api/v1/users/{username}); a row for/api/v1/users/42will never apply. -items_per_pageabove 100 answers422on every listing, including the API-key usage history, which allowed 1000, andpageabove2147483647answers422as well. - An API key's id outside1..2147483647answers422, where the request used to reach the database and fail there. - A credential the API throttle cannot resolve now spends the budget its address would have spent carrying none. A junkX-API-Keyor bearer token used to answer401as often as it was sent, unmetered, while the same requests without a header were throttled after the limit. - A signup no longer says whether an address is registered.POST /api/v1/users/answered409 Conflictfor a taken email, so anybody could ask it which addresses hold accounts, one request at a time, while the password-reset and verification routes were careful to answer uniformly. It now answers201with a fixed message whether the address was free or not, creates nothing in the second case, and tells the account that holds the address that somebody tried to sign up with it (crudauth'snotify_existing_account, which is what its own register route does). A mail server that is down does not change the answer. The created profile is no longer in the response: a body carrying it would say the address was free, so a client that readresponse.json()["id"]has to read the account fromGET /api/v1/users/{username}after signing in. A taken username still answers409: a username is public, a profile URL reveals it, and a signup form has to be able to say so. A race decided by the database answers by the index that refused the row, read from the name asyncpg puts on the error, so a lost race for an address is uniform too. The clock says nothing either: the password is hashed before either credential is looked up, since bcrypt is the slowest thing a signup does, and the notice to an existing owner runs as a background task, so neither path waits on a mail server. - With the taskiq feature, a recovery request no longer takes longer when the address exists.password/reset-request, the verification request and the email-change request send only where the address has an account, and the sender was awaited in the request: the publish to the broker on one path and nothing at all on the other, which a caller could time to find out who is registered. With a broker that was down the difference was the wholeBROKER_CONNECT_SECONDS, and the SMTP fallback on top. The sender now hands the message to a task of its own and returns, so both paths answer in the time it takes to make one. The shutdown waitsDRAIN_SECONDSfor what was handed over before closing the broker, so a deploy does not drop a message on its way to the queue, and logs how many it gave up on where a mail server never answered. A delivery that fails in the handover is logged too, where before it was swallowed by the caller. - A project without the taskiq feature hands the delivery over as well. crudauth awaited the configured sender in the request there, so a recovery request for a registered address still cost the mail server's time while one for an unknown address answered at once. The sender it is wired to is now wrapped inHandingOverSender, which hands the delivery to a task of its own and returns, and the project carries a lifecycle that drains what was handed over at shutdown. The handover itself moved out of the taskiq feature toinfrastructure/handover.py, so a project with no queue still has it; the two shutdowns wait for what each may take, one delivery here and the queue leg on top of it with a worker. - A confirmed email change now ends every session the account had.email/change-confirmmoved the address and left the sessions running, so whoever confirmed the change kept one the previous owner's password no longer reaches, and the notice to the old address was all that owner got. The address is what recovers an account, and a completed password reset already ends every session, so this is treated as the same kind of change. The confirmation is a link clicked from the new mailbox and carries no session, so there is none to keep and the one that asked for the change goes with the rest: the owner signs in again, as their new address. API keys are untouched, since nothing about an address moves the generation they were minted under. - Two writes to one role no longer race.POST /roles/{id}/users/{user}looked for the assignment and then inserted it, so two at once answered201and500: the loser's insert hit the primary key ofuser_roles.PUT /roles/{id}/permissionswas quieter and worse. Each replacement deletes what the role carries and inserts its own, and neither saw the other, so the role came out carrying the permissions of both requests, one set of them from a caller who had asked for the other. An assignment landing as the role was deleted answered500from the foreign key, and a deletion landing as a stronger account was given the role took it away from an account the caller could not reach. Every write path now takes the role's row first (SELECT … FOR UPDATE), so two writes to one role queue instead. A write that finds the role gone answers404, and an account a soft delete took out answers404rather than500. The account the write is about is held as well,FOR NO KEY UPDATE, because the stronger-account checks read what it holds: a superuser handing that account a role the caller cannot reach used to land between the check and the write, leaving the caller having changed the roles of an account stronger than themselves, and the admin panel deleting the account used to leave the assignment answering for a row that was there when it was checked. Both wait for the write now: the assignment answers201, and the panel's delete lands after it and takes it with the account. Taking a role away, or replacing what it carries, holds the rows of its holdersFOR SHAREfor the same reason, so two of those still run at once while an assignment to one of the holders waits. A role's row is always taken before an account's. What waits is every write to the account's own row — a profile edit, the bookkeeping a sign-in writes — for as long as the role transaction takes, and every holder's row while a role is taken away; a row that only names the account, an API key or a usage row, waits for none of it. - A tier limits a path with one rate-limit rule. Nothing stopped a second row for the sametier_idandpath, and the limit a caller got was whichever row the lookup read first, so two rows saying10and1000for/api/v1/users/made the limit a toss-up that could land differently after a restart.rate_limitsnow carriesuq_rate_limits_tier_path, a unique index over(tier_id, path)for the rows a soft delete has not taken out, so a path whose rule was deleted is free to configure again.PATCH /api/v1/rate-limits/{name}answers409where the new path is one the tier already limits, andRateLimitService.createthe same, including where another request got there first. A rule for a tier deleted between the check and the insert answers404for the tier rather than a conflict: which constraint refused the row is read off the driver's error, by the same reader the signup race uses (modules/common/collisions.py). A database that already holds two rows for one tier and path cannot create the index: Migrations has the query that finds them. - The tracing recipe no longer breaks the drill's own test. Observability had the reader add the Logfire installer toINSTALLERSinsrc/wiring/app.py, which the removal drill generates:tests/unit/test_removal_drill.pycompares what the generator writes with what the project committed, so following the guide left that test failing. The installer now goes where the app is composed,src/interfaces/main.py, which nothing regenerates, asinstallers=(*INSTALLERS, tracing_install). Making observability a removable feature, with its ownFEATURESentry and its contribution to the generator, is still the other way round and the guide still says so. - The text a caller can leave for other people to read is bounded. A profile image URL had a shape to match and no length, so a 2 MB one was stored and then served to every signed-in account that read the profile; it is now held to 2048 characters, the length a URL is held to elsewhere, and an OAuth provider's picture is left out rather than written where it is longer. The column carries that length as well (String(2048)), so the admin panel, which writes the model rather than the schema, is held to it too and its form says so; a database holding a longer URL has to shorten it before the revision that adds the length applies, and Migrations has the query that finds one. Aredirect_toon a recovery request had no length either, and it is signed into the token the emailed link carries, so a megabyte of path was a megabyte of link in somebody's mailbox: the crudauth routes now carrya_redirect_a_link_can_carrybeside the body guard, and one longer than 2048 characters answers422. The OAuth routes carry it too: there the destination arrives as?redirect_to=, bounded only by the server's request line, and waits in the state store until the callback. A usage row keeps the first 512 characters of the user agent the request sent, where it kept whatever the header held. Rows already stored keep what they hold: the read schemas describe a row rather than policing it. - An account's deletion can no longer be blocked by registering the name it would take. The anonymized row tookdel_<id>_<seconds % 10000>, a name insideUSERNAME_PATTERNand drawn from 10,000 values: anybody who knew an account's id could sign up for that range and leave every GDPR deletion of it answering500from the username index, since the anonymization is the write that renames the row. The name is nowdeleted-<id>-<12 hex>, whose hyphens no signup or rename can produce, and a name held anyway is tried again with fresh hex up toANONYMIZATION_ATTEMPTStimes, where the username index is what refused the write. A deletion that still finds no free name answers500rather than logging a completion over a row it left as it was. - A queued account email carries no readable recovery link.email:sendwas enqueued with the recipient, the subject, the rendered body and the link, so every verification and password-reset token sat in Redis or RabbitMQ in the clear until a worker picked it up, and in any backup or export of that queue afterwards. The message is now sealed with Fernet under a key taken fromSECRET_KEYand opened in the worker, so the queue holds one opaque string; a payload nothing sealed, or one changed since, is refused rather than delivered, and a message this worker cannot open is logged once and dropped rather than retried, since no retry will open it. The seal carries the time it was made and is opened against the lifetime of the link inside it, so a message that waited out its link, after an outage say, is dropped as well: the recipient would otherwise get a page saying only that the link has expired. The key is derived for this one use, so a feature that reaches forSECRET_KEYlater cannot arrive at the same one.cryptographyis declared as a dependency of its own, having arrived throughcrudauth[all]until now. Drain the queue before deploying this, since a message enqueued by the previous version carries six arguments the new task does not take, and before changingSECRET_KEYfrom now on, since a message sealed under the old key is mail nobody receives. - Readiness tells two checks on one host apart when they reach it as different users. The probe asks each server once and mirrors that answer onto the rest, and a server was its scheme, host and port alone. So a cache pointed at the limiter's Redis with the wrong password was reported ready, mirrored from the limiter that got in:GET /health/readyanswered200for a dependency no request could reach. The credentials are part of what identifies a server now, as a digest rather than in the clear, and only the database a Redis URL names is still dropped, since two databases of one server answer together. The derivation carries a work factor and is read once per pair of credentials, so what identifies a server is nothing a word list could be run against. - The production validator refuses four more things, and staging is checked at all. It acceptedSESSION_BACKEND=memory(each process keeping its own sessions, so a restart signs everybody out and a sibling worker knows none of them),RATE_LIMITER_BACKEND=memory(every limit multiplied by the worker count: that backend carries the login lockout, the account-change budgets and an API key's windows, whatever the ratelimit feature is doing), RabbitMQ'sguest/guest(anybody who reaches the broker can enqueue a task the worker runs), and anhttp://FRONTEND_URL(every recovery link carrying its token in the clear). All four are refused in production. Staging ran no checks at all, so it accepted the defaultSECRET_KEY, the console mail backend andCREATE_TABLES_ON_STARTUP=true; those three are refused there as well, since staging answers on the internet and often against a copy of production's data. The rest stays production's, so staging can still run on one worker with a throwaway database password. - A project with no accounts is no longer refused production over the email settings.EMAIL_BACKENDandFRONTEND_URLlive in the core settings, so a core-only project readsconsoleandhttp://localhost:3000the same as any other, and the production validator refused to start over a backend nothing delivers through and an address nothing builds a link from. Both checks now run only where the accounts feature is present, which is what gives a project an account to email. Every other check is unchanged, the secret key and the schema-on-boot refusals included. - A retry can wait, withTASKIQ_RETRY_DELAY_SECONDS. Retries were immediate and nothing else was on offer: a task tripped up by a dependency that is down for a minute spent all three of its attempts in the first milliseconds, and the queue's ownSmartRetryMiddlewaredelays nothing on a Redis broker, which ignores thedelaylabel. Set the seconds and each retry is written to aListRedisScheduleSourceinstead, waits that long, waits longer with each attempt up toRETRY_MAX_DELAY_SECONDS, and carries jitter so a queue of them does not come back in step. The scheduler is what enqueues them when they are due, so a project that sets a delay runs one next to its worker; at0, the default, nothing changes and no scheduler is needed. A delay set withTASKIQ_BROKER_TYPE=rabbitmqis refused where the broker is configured, since there is no Redis to hold the retry in. - An account email the broker will not take is delivered in the request rather than lost.QueuedSenderenqueued and nothing caught the failure, and crudauth delivers every account email best-effort: it logs what a channel raises and answers the same either way, so with the broker down a password reset answered200and no link was ever sent. The enqueue is now tried first and delivery falls back to the request, through the same sender the worker would have used, with a warning naming the kind of mail. A request that falls back waits for the mail server, which is what the message is worth. Reaching that fallback takes an enqueue that fails rather than one that hangs, so the Redis broker is built with thesocket_connect_timeoutredis-py leaves unset, and the call is givenBROKER_CONNECT_SECONDSof its own, which covers a broker that connects and then stalls and a RabbitMQ connection that is reconnecting. The socket's read timeout stays unset on purpose: the worker waits for its next job in abrpopwith no timeout of its own, so a socket that stopped waiting would raise out of the listener on the first idle minute. A message that lands just as the sender's time runs out is delivered as well as queued and read twice, which beats a recovery link nobody is sent. - A task's result expires after an hour instead of being kept for good. The Redis result backend was built with no expiry, so every result it ever wrote stayed in the database the queue itself runs on:TTLon a result key answered-1, and the only way to reclaim the space was to delete the keys by hand. Results are written withresult_ex_timenow,RESULT_KEPT_SECONDS, so one nothing came back for leaves on its own. A result is still there to be awaited for an hour after the task ran, which is far longer than thewait_resultthe docs describe. - A cached entry is keyed by what the route declares, escaped, and by the credential that asked. The query went into the key as it came, joined with the same&and=it was being split on, so?items_per_page%3D20%26page=1is one parameter whose name reads back as the two it spells: a request for anything at all was stored under the entry a real request for that page is served from. The query part is nowurlencodeof the parameters the route declares, sorted, so a value holding a delimiter cannot spell another request and a parameter the route never reads stores no entry of its own. Three more things the key got wrong: a listing with noresource_id_nameinferred one from the first int argument, which waspage, so the id part held a page number; the caller was looked for in whatever argument happened to carry auser_id; and a credential that carries a scope shared its owner's entries, so a response made for a session could be served to an API key that holds less. A per-caller route now names its caller withcaller_from=and raisesValueErrorwhere it is declared if it does not, the argument it names must hold aPrincipal(an account read any other way says nothing about which credential asked, and leaves the route uncached), nothing is inferred, and a scoped credential is keyed apart from the account and from its other scopes. The declared parameters are read from the route rather than from the arguments it was called with, so an alias, a parameter a dependency reads and the fields of a query model are all part of the key, and a request with no route to read keeps every parameter it carried rather than none.resource_id_type,infer_resource_idandCacheIdentificationInferenceErrorare gone with the inference. The shippedrate_limitslisting changes key shape, so its entries are read afresh once after this deploys. A write still clears only the entry of the caller that wrote, which Cache Strategies now spells out. - A credential that carries a scope needsuser.updateto edit its owner's own profile. Ownership was checked before the scope was consulted, so an API key scoped to nothing at all, or to reading, couldPATCH /api/v1/users/{username}for the account that minted it and change its name or its username. A key made for reading is not a licence to rename the account behind it, so a scoped credential now holdsuser.updateas well or reaches no profile at all, its owner's included. A session is unchanged: an account editing its own profile needs no permission. The other self-service routes already refuse a key outright. Worth knowing before a403surprises anybody: a scope names only permissions its owner holds, and the rbac feature is this project's only source of one, so with rbac an owner needs a role carryinguser.update, and with no permission source at all only a superuser's keys can edit a profile. - A key stored as scrypt moves over in a write of its own, not in the request's transaction. The rewrite set the new hash on the row the request's session was tracking and committed that session, which is the one the route writes through: a route that failed afterwards could not roll back, and whatever it had written so far was committed by a write it never asked for. Authenticating now reads through that session and nothing else, and the digest goes through a session of its own, guarded on the hash that was verified, so of two requests racing with one key exactly one row moves over. A rewrite that fails is logged and leaves the key as valid as it was, with the next request it carries trying again. - A key stored as scrypt is derived against only while a request could authenticate with it. The lookup behind the old hash took every row carrying the presented prefix and ascrypt$hash and ran the derivation against each, revoked and expired rows included. Such a row is never used again, so it holds that hash for good, and a key's prefix is in its owner's listing: whoever held one could make the server derive on junk, as often as they liked, for as long as a single row like that survived. The lookup now reads only rows that are active and unexpired, so revoking a key or letting it expire ends what it costs.uv run --no-sync python scripts/revoke_scrypt_api_keys.pynames the keys still stored that way, and--revokedeactivates them. A revoked or expired key of that kind now answersInvalid API keyrather than being rewritten as a digest and then refused as inactive. - A key's windows are counted shortest first, so a refused request keeps its longer budgets. The windows were counted in the order the limits were written in, which is the client's order, so a key carrying{"requests_per_day": 10, "requests_per_minute": 1}spent a day's worth of quota on nine refusals inside a minute: ten requests, one answered, and the day exhausted. The shortest window is now counted first and refuses before any longer one is touched, whatever order the limits were stored in. A refusal reads the longer windows it spent nothing in, soRetry-Afternames the time until the last window the key is still full in rolls rather than the window that refused it: a key that has spent its day is no longer sent back a minute later, once a minute, until the day rolls. - A key held at its limit records one refused request a window, not all of them. Every429a key's ownusage_limitsanswered used to write a usage row and stamplast_used_at, which made a refused request the most expensive one a key could make: five requests against{"requests_per_minute": 1}left five rows and five updates. The first refusal each window answers is still recorded, so an owner can still see a key being throttled, and the rest cost the limiter alone.last_used_atis the time the request arrived rather than the time its write landed, and a key stamped later than that keeps what it has, so of two requests whose writes land out of order the key names the later one, its address included. The stamp and the row are also written separately now, so one of them failing no longer takes the other with it. - Key usage rows are kept forKEY_USAGE_RETENTION_DAYSdays, 90 by default, and pruned after that. One row per key-authenticated request carries the caller's address and user agent, and nothing used to delete any of them.0keeps every row. With the taskiq feature the prune is a scheduled task (api_keys:prune_usage, 03:00 UTC, so it needs a scheduler running); without it,scripts/prune_key_usage.pydoes the same from a system cron. The analyticsdaysis read down to the retained window, and the user summary'stotal_requestsandtotal_cost_microcentsare totals over that window rather than over a key's life, so a project billing from these rows has to aggregate them before they are pruned.key_usagegained an index oncreated_atfor the cutoff. -src/modules/api_keys/__init__.pyexports nothing any more. Import from the submodules (.models,.schemas,.service,.retention,.settings), as the tier module already does: the feature's settings mixin is imported while the settings compose, and a package init that reaches app code closes that circle. -key_metadatais capped at 16 levels of nesting and 8 KB stored, on a create and on aPATCH, and anything past either answers422. A value nested deeper was accepted and then made every validated read of that key answer500(the listing, the single key and the summary), with no way to edit the row back through the API; a 5 MB value was accepted as well. The depth is read without recursion and before anything serializes the value, since serializing is what used to raise. -scripts/unlock_account.pyclears the login lockout one account is held in. The per-identifier half of the lockout counts failures from every address and applies before the password is checked, so anybody who knows a username can keep that account out, and nothing but time cleared it. The script takes a username or an address, clears the count, the lock and the escalation rounds under both of the account's identifiers, and leaves the counters of the addresses those failures came from alone. It reads the lock back afterwards and exits non-zero while the limiter still holds it or cannot be reached, so a run that reports success is one the account can sign in after. Login lockout documents the trade-off. -POST /api/v1/auth/email/change-requestnow counts against the account's change-password budget, 5 an hour and shared withPOST /api/v1/auth/change-password, correct passwords included. crudauth caps that route per client address only, and the password it checks feeds no lockout, so a session holder could guess an account's password from one address after another: three answers per address, then a fresh three from the next. An account whose budget is spent now gets429there and nothing is checked or sent. - A broker that accepts connections and says nothing no longer holds up startup. The RabbitMQ broker now hands aio-pika aBROKER_CONNECT_SECONDSconnect timeout (infrastructure/taskiq/constants.py, 5 seconds), so such an attempt fails and the app falls into its retry loop instead of waiting on the handshake. A blackholed host used to block startup for over two minutes and a silent one indefinitely, and until startup finished not evenGET /healthanswered. A worker builds the same broker, so its own startup is bounded by the same timeout. - A role carrying a permission the registry no longer knows can be edited again. Its stored names went into the delegation check as they were, and that check refuses an unregistered name before it short-circuits for a superuser, so a role stranded by a removed feature answered403onPATCH, onPUT /api/v1/roles/{role_id}/permissionsand onDELETE, to every caller, a superuser included. The check now reads only the names the registry still knows, as role assignment already did, and aPUTdrops the stale ones. A name the request itself asks for is still refused with422. - Deleting or emptying a role answers403while an account stronger than the caller holds it. Both routes used to check only the permissions the role carries, so a caller who was refusedDELETE /api/v1/roles/{role_id}/users/{user_id}for an account could take the same permissions away from it by deleting the role, or by emptying it withPUT /api/v1/roles/{role_id}/permissions. Each holder is now held to the rule the assign routes already applied: not a superuser, and holding nothing the caller doesn't. An account a soft delete has taken out is not a holder for this, since its grants reach nobody while its assignment rows stay behind. Superusers reach every role as before, without the lookup. - A key whose row holds a column no schema can read answers401, where every request it made used to answer500: a scope an older version stored as an object, or apermissionsorusage_limitsholding a JSON null. The refusal is logged as a warning naming the key. The owner's listing still answers500for that row, sopython scripts/cleanup_api_key_json.pyis still how the row is repaired. - A forwarded address a usage row cannot hold no longer answers500. WithTRUSTED_PROXY_HOPSset, anX-Forwarded-Forentry longer than an address, or one that is not an address at all, used to fail the usage row's validation after the handler had committed its work: the client got a plain500and no row was written. A key's usage row and itslast_used_ipnow hold the resolved address when it is one and nothing when it is not, and a row the usage schema refuses is logged and dropped rather than raised. - A signup that loses a race for an address answers409, where the second request used to reach the unique index and answer500. An address stored before it was canonicalised is a conflict too, rather than a500nobody could sign up past. (Both answer the fixed signup confirmation from the entry below, rather than a conflict, since no answer says whether an address is taken.) - A role id, an account id in a role path and atier_idoutside1..2147483647answer422, where the request used to reach the database and fail there with a500. A rate limit'slimitandperiodare bounded the same way, on a create and on aPATCH. - Anexpires_atthat cannot be expressed in UTC answers422, and so does string input that is not valid Unicode. - API key rows that hold a JSON null need one repair run. A version before this one storednullinpermissionsorusage_limitswhen a request sent it, and every validated read of such a row — the listing, the single key, a patch, the summary — now answers500. Runpython scripts/cleanup_api_key_json.pyfrombackend/once after upgrading; it sets those columns to{}wherever they hold a null, reports how many rows it touched, and is safe to run again. - One account per address, case-insensitively.Usernow declaresix_user_email_lower, a unique index overlower(email), so two rows can no longer hold the same address in different case — including through the admin panel, which writes through SQLAlchemy rather than the signup schema. A database written by an older version may hold such a pair, and creating the index on it fails: runpython scripts/canonicalize_emails.pyfrombackend/first. It rewrites every address into the trimmed, lowercased form every lookup uses and adds the index, or, while two accounts hold one address, names them and changes nothing. Safe to run again. - The legacy OpenAPI identity settings are gone. RenameCONTACT_NAME,CONTACT_EMAILandLICENSE_NAMEin your environment toAPI_CONTACT_NAME,API_CONTACT_EMAILandAPI_LICENSE_NAME; the old names are now read by nothing, so a project that keeps them publishes no contact and no licence. - The template's identity is no longer the default.VERSIONdefaults to0.1.0instead of the boilerplate's own release, andAPP_DESCRIPTIONdefaults to empty instead of the boilerplate's feature list, so a generated project's OpenAPI document describes itself or says nothing. SetVERSIONandAPP_DESCRIPTION(orAPI_VERSIONandAPI_DESCRIPTION) to your own values. - A duplicate signup answers409, not422.POST /api/v1/users/with a taken email or username answers409 Conflictwith the same body it used to send ("A user with this email or username already exists."), which is what the route always declared. A client that treats422as "already registered" has to read409as well. The same applies to the profile update and to renaming a rate limit onto a taken name. (A taken address no longer answers at all: see the entry below.) - An emptyAPI_PREFIXno longer serves the API from the root.API_PREFIX=used to mount the routes at/v1/...; it is now refused at startup, together with any prefix that does not start with/or that ends with/. Set a prefix such as/api. - A naiveexpires_aton an API key answers422. Send an offset (2030-01-01T00:00:00+00:00). - Emails are stored lowercased, and rows written before this change are not found. The uniqueness check and every lookup use the canonical form, while the unique index stays case-sensitive, so a legacyLegacy@Example.comrow is invisible to them: a signup aslegacy@example.comsucceeds and creates a second account, a Google sign-in creates another one, and the owner of the legacy row can sign in by username but not by email. Lowercasing existing rows, and a unique index onlower(email), is a data-migration decision and not part of this change. - EveryAPI_*document setting defaults to empty:API_TITLE,API_SUMMARY,API_DESCRIPTION,API_VERSION,API_TERMS_OF_SERVICE,API_CONTACT_NAME,API_CONTACT_EMAIL,API_CONTACT_URL,API_LICENSE_NAME,API_LICENSE_IDENTIFIERandAPI_LICENSE_URL. Set them to put your own identity in the OpenAPI document.API_TITLE,API_DESCRIPTIONandAPI_VERSIONfall back toAPP_NAME,APP_DESCRIPTIONandVERSION, so the document always carries a title and a version — those two have non-empty defaults — and a description only once one of the pair is set. The summary, terms of service, contact and licence fields are left out of the document while they are empty. -HTTPExceptionand friends import frominfrastructure/http_exceptions.py(wasinfrastructure/auth/http_exceptions.py). - The settings listed under Removed are gone. An.envthat still sets them is ignored; nothing read them. -POSTGRES_DBmay not contain/,?,#or@. SQLAlchemy reads the name literally, so such a name would have connected somewhere else; setDATABASE_URLinstead. -GET /health/readyanswers{"status": "ready"}or{"status": "not ready"}and no longer lists the dependencies. A dashboard that readdependenciesfrom the body reads the log instead; the probe that runs the checks names whatever it found unreachable. -READINESS_CHECKSis now two tuples,CRITICAL_READINESS_CHECKSandINFORMATIONAL_READINESS_CHECKS(src/wiring/hooks.py). A project that added its own check lists it in whichever group fits. A cache or broker outage no longer answers503, so an alert that watched/health/readyfor one needs to watch the log line or the reported dependencies instead. - Task results are stored as JSON, not pickles. The Redis result backend no longer unpickles what it reads, so a result key written by an older worker can't be read back. Drain the queue and clear the result keys before deploying both sides. - A stricterSECRET_KEYcheck can stop a production deploy that used to start. A key that repeats a block, walks the keyboard, or reads as ordinary words is now refused, where before only whole repeats and placeholders were. Generate one withbp env gen-secret(orpython -c 'import secrets; print(secrets.token_urlsafe(32))') and roll it before deploying - rotatingSECRET_KEYinvalidates existing sessions and admin logins. - Operators are signed out of the admin panel once. Its session cookie is now scoped to the panel's mount instead of/, so the cookie a browser already holds is not sent to the new path. Signing in again is all it takes. - Logger names changed.get_logger()walked one frame too far, so a module-levellogger = get_logger()came out namedimportlib._bootstrap— the import machinery — rather than the module that asked for it. Every logger is now named after its own module. Per-logger configuration (a level, a filter, a handler keyed by name) has to name the module, and themodulefield of astructuredorjsonline carries it. -TASKIQ_RABBITMQ_VHOSTis written literally, not pre-escaped. The value is escaped when the broker URL is built, so%2Fnow names a vhost called%2F(amqp://…:5672/%252F). Write/for the default vhost, or the name itself (tasks); a leading slash is dropped either way. - Regenerate an nginx stack (bp deploy generate nginx) to get theX-Forwarded-Forchange. Until then a client can send its ownX-Forwarded-For, and uvicorn - trusting the compose network - reports it asrequest.client. - Regenerate a local stack (bp deploy generate local) to publish Postgres and Redis on127.0.0.1only. An existingdocker-compose.ymlkeeps offering a password-less database to everyone on the network. -POST /api/v1/api-keys/no longer returnskey_metadataorlast_used_ip. Read them fromGET /api/v1/api-keys/{id}; a key that has just been created has nolast_used_ipanyway. -GET /api/v1/users/{username}no longer returnstier_id. A user's tier is now visible only to that user, through/users/meorGET /api/v1/users/{username}/tier, and to superusers, who can read any user's tier through the same route. A client that read another user's tier from their profile can no longer see it.
Full release notes: https://github.com/benavlabs/FastAPI-boilerplate/releases/tag/v0.20.0 Full changelog: https://github.com/benavlabs/FastAPI-boilerplate/compare/v0.19.0...v0.20.0
0.19.0 - June 23, 2026 - The crudauth Migration¶
Three changes since v0.18.0: route dependency injection moved to centralized Annotated[...] type aliases (#261), the app metadata (APP_NAME / APP_DESCRIPTION / VERSION) became environment-configurable, and — the headline — the vendored authentication stack was replaced with the crudauth library.
The crudauth migration. The vendored authentication stack — the in-tree SessionManager, its storage backends, the OAuth provider framework, and the token/password utilities — has been replaced with crudauth. The boilerplate now keeps only the wiring: a single auth = CRUDAuth(...) singleton in infrastructure/auth/setup.py, the FastAPI dependencies that wrap it, the OAuth building blocks, and the route handlers. Session validation, CSRF, login lockout, and session storage all live in the library.
Annotated type-alias DI (#261, by @emiliano-gandini-outeda). Route signatures moved from inline Depends(...) to centralized Annotated[..., Depends(...)] aliases in infrastructure/dependencies.py, with per-module dependencies.py files holding the service aliases for user, tier, rate_limit, and api_keys.
This is a breaking change for anyone importing from the old auth modules or relying on the removed settings. See Breaking Changes below for the migration.
Added¶
crudauthlibrary integration by @igorbenavauth = CRUDAuth(...)composition root ininfrastructure/auth/setup.py; the app lifespan callsauth.initialize()/auth.shutdown()- New
Principal-based dependenciesget_current_principal/get_optional_principalalongside the dict-returningget_current_user/get_optional_user/get_current_superuser TRUSTED_PROXY_HOPSsetting (default0) — number of trusted reverse proxies in front of the app, used by crudauth to resolve the real client IP for login lockout. Set1behind a single nginx/Caddy.User.is_activeproperty — derived fromnot is_deleted; crudauth reads it during login so soft-deleted users can't authenticate.- Annotated type-alias dependency injection (#261) by @emiliano-gandini-outeda — centralized
Annotated[..., Depends(...)]aliases ininfrastructure/dependencies.pyand per-moduledependencies.py(user,tier,rate_limit,api_keys) with service aliases; route signatures migrated to use them.
Changed¶
- Auth dependencies now import from
infrastructure.auth.dependencies(wasinfrastructure.auth.session.dependencies). get_password_hash/verify_passwordnow comefrom crudauth(wasinfrastructure.auth.utils).- Login lockout now returns
429 Too Many Requestswith aRetry-Afterheader (was a generic401). It is throttled internally by crudauth (escalating per-IP / per-identifier), not via env vars. - OAuth providers are now configured through crudauth's built-in OAuth router in
infrastructure/auth/setup.pyrather than hand-rolled callback wiring. Google remains wired. APP_NAME,APP_DESCRIPTION, andVERSIONare now environment-configurable (read viaconfig(...); previously hardcoded)./check-authnow answers anonymous callers with{"authenticated": false}instead of raising401(#261).
Removed¶
- The vendored session stack:
SessionManager, the memory/redis/memcached session backends, session storage/schemas/dependencies, and the user-agent parsing helpers. - The in-tree OAuth package (provider framework, factory,
providers/google.py,providers/github.py, services) andauth/utils.py/auth/constants.py. - The memcached session backend — sessions now support only
redisandmemory. (The general cache and rate limiter still support memcached.) - The GitHub OAuth provider file. The
Usermodel keeps itsgithub_id/oauth_providercolumns, so the data model still anticipates GitHub, but no provider or routes ship. - Settings
ALGORITHM,ACCESS_TOKEN_EXPIRE_MINUTES,REFRESH_TOKEN_EXPIRE_DAYS,SESSION_COOKIE_MAX_AGE,LOGIN_MAX_ATTEMPTS, andLOGIN_WINDOW_MINUTES. - The dependency aliases
SessionManagerDep,CurrentSessionDataDep,OptionalSessionDataDep,GoogleOAuthProviderDep, andOAuthStateStorageDep.
Breaking Changes¶
- Imports moved. Replace
from ...infrastructure.auth.session.dependencies import ...withfrom ...infrastructure.auth.dependencies import ..., and importget_password_hash/verify_passwordfromcrudauth. - Removed settings. Delete
ALGORITHM,ACCESS_TOKEN_EXPIRE_MINUTES,REFRESH_TOKEN_EXPIRE_DAYS,SESSION_COOKIE_MAX_AGE,LOGIN_MAX_ATTEMPTS, andLOGIN_WINDOW_MINUTESfrom your environment — they no longer exist. AddTRUSTED_PROXY_HOPSif you run behind a proxy. - Login lockout response changed from
401to429+Retry-After; update any client that special-cased the old status/message. SESSION_BACKEND=memcachedis no longer valid — switch toredisormemory.SessionManagerand friends are gone. Code that called the session manager directly (e.g. listing a user's sessions) must move to crudauth's session APIs.
Full release notes: https://github.com/benavlabs/FastAPI-boilerplate/releases/tag/v0.19.0 Full changelog: https://github.com/benavlabs/FastAPI-boilerplate/compare/v0.18.0...v0.19.0
0.18.0 - May 24, 2026 - The Pluggable Restructure¶
This is the release we promised in v0.17.0; the one that tears the layout apart and rebuilds it as a real plugin system. If you've been pinned to v0.17.0 waiting for it, this is your moment.
A heads-up before we go further: the diff is enormous; v0.17.0 → v0.18.0 is not the kind of upgrade you run git pull for. The Python package moved, auth changed completely, workers changed, the admin panel changed, there's a new CLI in a new workspace member. We didn't do this lightly.
Why this release is so different¶
We didn't iterate on the v0.17.0 codebase to get here. We rebased the project on the fastroai-template structure.
fastroai-template is the production-tested template we use internally (and sell) for AI SaaS products. It's been running real apps for months and the structural choices (three-layer architecture, vertical-slice modules, server-side sessions, SQLAdmin, Taskiq, swappable infrastructure) have proven themselves under load. Reinventing all of that for FastAPI-boilerplate would have meant another six months of polish; rebasing meant we could ship the good parts on day one.
The trade-off is that fastroai-template carries a lot of stuff this boilerplate's audience doesn't necessarily need: a Stripe integration, subscription/credits/entitlements modeling, AI agent orchestration, usage tracking with cost calculation, OAuth-specific provisioning for SaaS, an Astro frontend. Excellent for an AI SaaS starter, wrong for a general FastAPI boilerplate.
So this release is fastroai-template minus the SaaS/AI parts, plus a plugin system that fastroai-template doesn't have. What's left is the structural skeleton; the parts that any FastAPI app needs and that we've watched hold up in real use:
- The three-layer split (
interfaces/,infrastructure/,modules/) - Vertical-slice modules (
user/,tier/,api_keys/,rate_limit/) - Server-side sessions + CSRF, OAuth (Google wired, GitHub scaffolded)
- SQLAdmin, Taskiq, swappable cache/session/rate-limit backends
- The production security validator that refuses to boot with insecure defaults
The new part, the one fastroai-template doesn't have, is bp — a plugin-aware CLI. fastroai-template ships everything in-tree because that's appropriate for an AI SaaS starter. FastAPI-boilerplate's whole pitch is "use what you need, drop what you don't", and that pitch only works if dropping things and adding things are first-class operations. The bp.commands and bp.features entry points are how external Python packages contribute new commands and feature generators without touching the core. Build a Stripe plugin, a Prometheus plugin, a CRUD-generator plugin, they all ship as separate packages.
If you can stay on v0.17.0, consider it¶
For brand-new projects, v0.18.0 is the better starting point. For existing apps with significant custom code on v0.17.0, the honest answer is: the migration path is "copy your business logic into the new structure", not a sed-style find-and-replace. If your fork has diverged from v0.17.0 in non-trivial ways, pinning to v0.17.0 may be the right call. We'll keep v0.17.0 around as a tag forever.
For the full migration guide and per-section detail, see the full release notes on GitHub.
Added¶
- Three-layer architecture by @igorbenav
backend/src/{interfaces,infrastructure,modules}/split- Vertical-slice modules: each domain owns its full vertical (
models,schemas,crud,service,routes,enums) -
Modules shipped:
user,tier,api_keys,rate_limit,common -
uv workspace split by @igorbenav
- Workspace root with two members:
backend/(deployable) andcli/(developer tool) - Single shared
.venv; prod Dockerfile only copiesbackend/src/ -
Install with
uv sync --all-packages --all-extrasfrom the repo root -
bpCLI with plugin extension points by @igorbenav bp.commands— external Typer sub-apps mount under the rootbp.features— external feature generators with manifest + plan + rollback- In-tree commands:
bp deploy generate {local,prod,nginx},bp env gen-secret,bp env validate -
Built-in
deployfeature with Jinja templates for compose + nginx -
OAuth provider framework by @igorbenav, @LucasQR
- Google end-to-end (callback creates session, sets cookie)
- GitHub scaffolded with the same provider/factory shape
-
Documentation at
docs/user-guide/authentication/ -
API keys module by @igorbenav
- Named keys with permissions and usage limits
- Per-call usage recording for analytics
- scrypt hashing with per-row salt (CodeQL strong-KDF compliant)
-
Lookup via indexed
key_prefixcolumn with constant-time verify -
Production security validator by @igorbenav
- Startup gate that refuses to boot prod with insecure defaults
- Checks
SECRET_KEY, DB credentials, CORS policy, session flags, debug mode, admin credentials and Redis passwords -
bp env validateruns the same checks against any config -
Server-side sessions by @igorbenav
- Opaque session IDs in
HttpOnlycookies - Backed by Redis (default), Memcached, or in-memory
- CSRF enforced by default for state-changing endpoints
-
Documentation at
docs/user-guide/authentication/sessions.md -
Swappable infrastructure backends by @igorbenav
- Cache, rate limit, session storage all behind ABCs in
*/base.py - Concrete backends in
*/backends/{redis,memcached,memory}.py -
Env-selectable:
SESSION_BACKEND,CACHE_BACKEND,RATE_LIMITER_BACKEND -
Multi-stage Dockerfile by @igorbenav
dev/migrate/prodstages from a singlebackend/Dockerfile- Uses
uv exportagainst the lockfile for reproducible builds with hash verification -
Pinned uv version (
0.9.9) for build reproducibility -
Python 3.14 dependency compatibility by @carlosplanchon
-
Dependency bumps that compile and run on Python 3.14
-
CI workflows for the workspace by @igorbenav
tests.yml,linting.yml,type-checking.yml,docs.ymlcovering both members- Least-privilege
permissions: contents: readon all workflows (docs.ymladditionally haspages: writeandid-token: write)
Changed¶
- JWT → server-side sessions by @igorbenav
- JWT access tokens, refresh tokens, and the
token_blacklisttable removed -
API surface is cookie-based now; clients sending
Authorization: Bearerare rejected -
CRUDAdmin → SQLAdmin by @igorbenav
- Custom admin panel replaced with SQLAdmin
DataclassModelMixinadded forMappedAsDataclassmodel compatibility-
Env:
CRUD_ADMIN_*removed; useADMIN_ENABLED(uses mainSECRET_KEY) -
ARQ → Taskiq by @igorbenav
- Async-native worker stack with Redis or RabbitMQ broker
- Worker command:
taskiq worker infrastructure.taskiq.worker:default_broker -
DBSessiondependency injection in tasks -
MkDocs → Zensical by @igorbenav
- Docs site generator swapped; configured via
zensical.toml - Local:
uvx zensical serve; build:uvx zensical build -
Deploy via
.github/workflows/docs.ymlto GitHub Pages -
Settings layout by @igorbenav
- Composed setting groups (
AuthSettings,CacheSettings,RateLimiterSettings, etc.) ininfrastructure/config/settings.py get_settings()returns the composedSettingsinstance- Most env var names stable; a few moved between groups
Security¶
- Dropped
python-jose/ecdsaby @igorbenav - Removed unused
fastsecuredep, which was pulling inpython-joseandecdsa - Addresses the Minerva timing attack on P-256 in python-ecdsa (the project explicitly won't fix it; switching to
cryptographywas the upstream recommendation) -
bcryptis now a direct dependency (was transitive viafastsecure) -
Bumped
idnato 3.16 by @igorbenav -
Fixes CVE-2024-3651 bypass for crafted inputs to
idna.encode() -
Bumped
sqladminto 0.26.0 by @igorbenav -
Fixes the
ajax_lookupauthorization bypass -
scrypt for API key hashing by @igorbenav
- Per-row salt, format
scrypt$N$r$p$salt$derived - Compliance with CodeQL's strong-KDF allowlist
-
Constant-time verify via
hmac.compare_digest -
Workflow permissions tightened by @igorbenav
- All CI workflows now declare explicit
permissions:blocks - Read-only on test/lint/type-check; targeted writes only where needed
Improved¶
- Full documentation rewrite by @igorbenav, @LucasQR, @emiliano-gandini-outeda
- Every page under
docs/user-guide/rewritten for the new structure - New
docs/cli/section:index.md,commands.md,plugins.md - New
docs/user-guide/authentication/sessions.md -
README slimmed but still self-contained
-
Lint enforcement:
PLC0415by @igorbenav - No deferred imports anywhere — all imports at module top
-
Surfaced and resolved a circular import in session storage by extracting
AbstractSessionStoragetoauth/session/base.py -
README polish by @carlosplanchon
- Installation scripts moved out of Gists into the repo
- DeepWiki documentation link added
Removed¶
src/app/layout — replaced bybackend/src/{interfaces,infrastructure,modules}/- JWT auth +
token_blacklisttable — replaced by server-side sessions - CRUDAdmin views — replaced by SQLAdmin
- ARQ workers — replaced by Taskiq
- Deployment scripts (
setup.py,scripts/{local_with_uvicorn,gunicorn_managing_uvicorn_workers,production_with_nginx}/) — replaced bybp deploy generate mkdocs.yml— replaced byzensical.toml- Demo
postsmodule — pure demo code, not needed backend/uv.lock— stale duplicate of workspaceuv.lock
Breaking Changes¶
⚠️ Eight breaking changes. The migration path for forks with significant custom code is "copy your business logic into the new structure" — there is no sed-style find-and-replace.
| Change | Impact | Migration |
|---|---|---|
src/app/ layout removed |
Imports break at import time | Manual restructure into modules/<name>/ |
| JWT removed | Authorization: Bearer clients rejected |
Switch clients to cookie auth |
| CRUDAdmin → SQLAdmin | Custom admin views need porting | Port to ModelView shape |
| ARQ → Taskiq | Workers need re-registration | Rewrite tasks as @broker.task async functions |
| API key hash format | Existing keys won't validate | Users must regenerate |
| Settings composition | Env var names mostly stable; a few moved | Diff .env.example |
| Sync command | cd backend && uv sync --extra dev produces broken venv |
Use uv sync --all-packages --all-extras from repo root |
| Deployment scaffolder | ./setup.py local removed |
uv run --no-sync bp deploy generate {local,prod,nginx} |
For brand-new projects, v0.18.0 is the better starting point. For existing apps with significant custom code on v0.17.0, pinning to v0.17.0 may be the right call — that tag stays supported.
New Co-Maintainers¶
- @carlosplanchon and @emiliano-gandini-outeda are now officially helping maintain and improve the boilerplate.
Full release notes: https://github.com/benavlabs/FastAPI-boilerplate/releases/tag/v0.18.0 Full changelog: https://github.com/benavlabs/FastAPI-boilerplate/compare/v0.17.0...v0.18.0