Skip to content

Releases

v0.8.2

Choose a tag to compare

@igorbenav igorbenav released this 07 Oct 19:30
dd7333f

Release v0.8.2 - SQLite Fix for Python 3.11

Date: 2026-10-07

A fix for the database store on SQLite under Python 3.11. Nothing else changes.


Fixed

If you run DatabaseStore on SQLite with Python 3.11, opening an email link a second time could make every write to the database fail for a few seconds with "database is locked", logins included. A second open is common: a double click, or a mail scanner fetching the link before the user does. This affected verification, password reset and email change links.

The cause was a lost claim on the link going through a duplicate-key error. SQLAlchemy 2.0's aiosqlite adapter leaves the failed statement's cursor open, and on Python 3.11 that cursor kept the connection holding SQLite's lock until it was garbage collected. The claim now uses INSERT OR IGNORE on SQLite, so losing it raises nothing.

PostgreSQL, MySQL and MariaDB weren't affected, and neither were Python 3.10, 3.12 and 3.13.


Upgrading

pip install -U crudauth

Nothing to change in your code.


Full Changelog: v0.8.1...v0.8.2

Docs: https://benavlabs.github.io/crudauth

v0.8.1

Choose a tag to compare

@igorbenav igorbenav released this 07 Oct 18:55
fed97e3

Release v0.8.1 - No Redis? Use Your Database

Date: 2026-10-07

Running several workers on PostgreSQL, MySQL, MariaDB or SQLite, and no Redis? CRUDAuth can now keep all of its server-side state in your database, so a login made on one worker is good on every other one, and login lockout counts failures across all of them. Nothing changes if you don't use it.

This release also fixes a security gap for OAuth-only accounts, gives your hooks the provider profile on every OAuth sign-in, and adds what an app needs to run beside another CRUDAuth app.


Database storage

from sqlalchemy.ext.asyncio import async_sessionmaker
from crudauth import CRUDAuth, DatabaseStore

store = DatabaseStore(async_sessionmaker(engine, expire_on_commit=False))
auth = CRUDAuth(session=get_session, user_model=User, SECRET_KEY="change-me", database_store=store)

Sessions, CSRF tokens, one-time email tokens, OAuth state, the MFA store and the login lockout counters all go into two tables, crudauth_store and crudauth_counters. The counters matter as much as the sessions: if they stay in memory, each of four workers counts failures separately and an attacker gets four times the attempts.

Create the tables with await store.create_tables() in development. In production, put them in a migration: pass your own metadata and Alembic autogenerates them with the rest of your schema.

store = DatabaseStore(sessions, metadata=Base.metadata)

store_table= and counter_table= rename the tables. The store can use a different database from your app's. It opens a short session per operation and never holds a connection between them.

Expired rows read as absent immediately. Every 1,000 writes, the store deletes about as many expired rows, so cleanup keeps up without any single request doing a large delete. A failed cleanup is logged and doesn't fail the write. To run cleanup on a schedule instead, pass purge_every=0 and call await store.purge_expired(). Expiry uses your application's clock, so keep your workers' clocks in sync.

Concurrent updates to one session both land, a one-time token is claimed once, an OAuth state is consumed once, and every failed login is counted, on every supported database. This is tested against PostgreSQL 16, MySQL 8.0, MariaDB 11.4 and SQLite back to 3.22. SQLite allows one writer at a time, so use it on a single host and PostgreSQL or MySQL for many workers.

Keys compare exactly, case and trailing spaces included, and keys of any length fit. On MySQL and MariaDB, a deadlock between concurrent writes is retried instead of returning an error. SQLite without RETURNING (Debian bullseye, Ubuntu 20.04) works too.


Security: OAuth-only accounts need a recent sign-in to add a credential

An account that signs in only through OAuth has no password to re-enter. Until now, MFA setup and /set-password asked it for nothing, so a stolen session cookie could enroll the attacker's authenticator, or set a password and use it to take over the account.

Both routes now require such an account to have signed in within the last 10 minutes on the session making the request, or to hold an active sudo elevation. Otherwise they return 403, and your frontend should send the user through the provider again.

auth = CRUDAuth(..., fresh_sign_in_seconds=600)  # the default; 0 closes both routes to these accounts

Accounts with a password are unaffected and still confirm it with the password. To apply the same check to your own routes, use await auth.signed_in_recently(principal).


Provider profile on every OAuth sign-in

The new on_oauth_login hook receives the provider's profile and the request's database session on every OAuth sign-in, for new and existing accounts. Use it for provider data that changes, such as a GitHub username:

async def keep_github_login(user, info, *, db, created, context):
    if info.provider == "github":
        await db.execute(update(User).where(User.id == user["id"]).values(github_login=info.username))
        await db.commit()

auth = CRUDAuth(..., hooks=AuthHooks(on_oauth_login=keep_github_login))

Running beside another CRUDAuth app

  • await session_transport.complete_logout(request, response, db) does what POST /logout does, for a logout route of your own. The logout hook now receives the ended session's handle.
  • CRUDAuth(rate_limit_prefix="admin:rl:") separates an app's lockout counters from another app's on the same Redis or database, so failures in one don't lock the user out of the other.
  • auth.mfa_router returns only the /mfa routes.

Fixed

  • In 0.8.0, SessionTransport(storage=...) combined with email or OAuth failed at startup with Unknown session backend: 'custom'.
  • A hook that rolled back its database work, as the hooks guide recommends on failure, turned a successful registration, OAuth sign-in or recovery-code login into a 500. crudauth now reloads the user after such a hook, and rolls back the uncommitted work of a hook that raises.

Upgrading

pip install -U crudauth

If your frontend offers "set a password" or two-factor setup to OAuth-only users well after they signed in, handle the new 403 by sending them through the provider again, or raise fresh_sign_in_seconds. /set-password with a bearer token is now refused for these accounts.

To use database storage, pass a DatabaseStore as shown above and create its two tables. MySQL needs 8.0.17 or later, MariaDB 10.2 or later.


Full Changelog: v0.8.0...v0.8.1

Dependencies: unchanged. Install your own database driver: asyncpg, aiomysql or aiosqlite.

Docs: https://benavlabs.github.io/crudauth

v0.8.0

Choose a tag to compare

@igorbenav igorbenav released this 06 Oct 20:07
93e94f7

Release v0.8.0 - Bring Your Users, Share Your Redis

Date: 2026-10-06

Everything an app needs to move its users onto CRUDAuth from auth it wrote itself, and to run
beside another CRUDAuth app: old password hashes that still sign in, sessions namespaced per app,
sessions kept in a store you supply, and hooks for the logins that fail. Sessions are also stored
more safely and can be capped from sign-in.

One breaking change to plan for: deploying 0.8.0 signs every user out once.


Old passwords keep working

Moving users from another system used to mean a password reset for everyone, because CRUDAuth
can't verify a hash another library wrote. Now you tell it how:

from crudauth.utils import verify_plain_bcrypt

auth = CRUDAuth(..., legacy_verifiers=[verify_plain_bcrypt])

When CRUDAuth's own check fails at login, each verifier runs; a match signs the user in and
replaces their stored hash with a CRUDAuth one. Once everyone has signed in since the move, drop
the option. A verifier is any (plain_password, hashed_password) -> bool, so argon2, PBKDF2 or a
framework's own format needs only its check. They run for unknown users too, against a dummy hash,
so a wrong password takes the same time whether or not the account exists.


Two CRUDAuth apps, one Redis

An admin panel mounted beside your app, both on CRUDAuth, used to share one cookie name and one key
space: a session from one app resolved in the other. Give one of them its own:

SessionTransport(
    cookie_name="admin_session",
    csrf_cookie_name="admin_csrf",
    storage_prefix="admin:session:",
    csrf_storage_prefix="admin:csrf:",
)

Your own session store

Keep sessions in a database table, Memcached or anything else that implements
AbstractSessionStorage:

SessionTransport(storage=my_sessions, csrf_storage=my_csrf_tokens)

Hooks for refused logins

AuthHooks(on_login_failed=record_failure, on_lockout=alert_on_lockout)

on_login_failed gets the identifier, the account it named (or None) and whether the password
was wrong or the account disabled: what the response deliberately doesn't tell the caller.
on_lockout gets the identifier and the seconds left. And context.session_handle now names the
session a login created, so an audit log can refer to it without storing a credential.


Safer sessions

  • The store no longer holds session ids or CSRF tokens, only an HMAC of each keyed with your
    SECRET_KEY. Someone who can read your Redis can't sign in with what they read.
  • Signing in again ends the session the browser had. The old cookie stayed valid only for
    whoever had copied it.
  • An optional absolute lifetime: SessionTransport(absolute_timeout_hours=12) ends a session
    12 hours after sign-in, however active it stays.

Upgrading

pip install -U crudauth
  • Every user is signed out once when you deploy, since sessions are now stored under a
    different key. Changing SECRET_KEY has the same effect from now on.
  • Device-list handles change format. auth.sessions.session_handle(session_id) still works
    (it's now an instance method); a handle you stored from 0.7 no longer matches.
  • A second login in the same browser ends the first session.

Full Changelog: v0.7.5...v0.8.0

Dependencies: unchanged.

Docs: https://benavlabs.github.io/crudauth

v0.7.5

Choose a tag to compare

@igorbenav igorbenav released this 06 Oct 03:06
c72e61b

Release v0.7.5 - A Disabled Account Gets No Email Either

Date: 2026-10-06

The follow-up to 0.7.4. That release stopped an OAuth sign-in from changing a disabled account;
this one does the same for the email flows. No breaking changes, and upgrading needs no code
changes.


What was wrong

The email flows never checked is_active. For a disabled account:

  • a password reset request sent a working reset link to its address, and redeeming it set a new
    password, signed out every session and ran your after_password_reset hook;
  • a verification request sent a verification link, and redeeming it marked the address verified;
  • an email-change link sent before the account was disabled could still swap its address.

None of this let anyone sign in, because login already refuses a disabled account. But it changed
accounts you'd disabled to keep as they were, kept emailing the addresses of users you'd deleted,
and fired hooks you may rely on for side effects.


What changed

A disabled account is now treated as one that doesn't exist:

  • It's sent nothing. /password/reset-request and /email/verify-request skip it and answer
    exactly as they do for an unknown address, so the response still reveals nothing.
  • Its links stop working. A reset, verification or email-change link sent before the account
    was disabled is refused at confirm with the usual Invalid or expired token.

If you soft-delete users and expose is_active as a property over your own flag
(return not self.is_deleted), your deleted users get the same treatment.


Upgrading

pip install -U crudauth

Nothing is required.


Full Changelog: v0.7.4...v0.7.5

Dependencies: unchanged.

Docs: https://benavlabs.github.io/crudauth

v0.7.4

Choose a tag to compare

@igorbenav igorbenav released this 06 Oct 02:41
5b79e6f

Release v0.7.4 - A Disabled Account Stays as It Was

Date: 2026-10-05

A small fix to OAuth sign-in on a disabled account. It was always refused, but the account could be
changed before the refusal. Now it isn't touched. No breaking changes, and upgrading needs no code
changes.


What was wrong

When someone signed in with a provider whose email matched a disabled account (is_active false),
CRUDAuth linked the account before noticing it was disabled:

  • the provider id was written onto it;
  • if the account's email had never been verified, the link also claimed it: the password was made
    unusable, MFA was removed, its sessions were ended and the email was marked verified.

Then the callback answered account_inactive and set no session. Nobody got in, but the account
had changed. If you disable accounts to keep them as they were, or soft-delete users and might
restore them, a restored account could come back linked to a stranger's provider identity and
without its password.


What changed

The account is checked before anything is written. A disabled account found by provider id or by
email is refused with account_inactive, exactly as before, and left untouched.

If your app calls auth.oauth.get_or_create_user(info, db) from its own callback, it now raises
OAuthAccountException with code == "account_inactive" for a disabled account, the same way it
already raises for every other refusal, instead of returning the user.


Soft-deleting apps

CRUDAuth reads is_active as an attribute, so you can keep your own flag as the source of truth:

class User(Base, AuthUserMixin):
    is_deleted: Mapped[bool] = mapped_column(default=False)

    @property
    def is_active(self) -> bool:
        return not self.is_deleted

A deleted user then can't sign in by password, session, bearer token or provider, and with this
release a provider sign-in can't modify the deleted row either.


Upgrading

pip install -U crudauth

Nothing is required.


Full Changelog: v0.7.3...v0.7.4

Dependencies: unchanged.

Docs: https://benavlabs.github.io/crudauth

v0.7.3

Choose a tag to compare

@igorbenav igorbenav released this 05 Oct 22:38
f51f520

Release v0.7.3

Date: 2026-10-05

A small release about one thing: where a redirect-mode OAuth callback sends the browser when it has
nowhere better to go. It used to be redirect_base_url, always, now you can say. No breaking
changes, and upgrading needs no code changes.


Why this exists

A redirect-mode callback falls back to a default target in three cases:

  • the sign-in failed, so it redirects with ?error=<code>;
  • the account needs an MFA challenge, so it redirects with #mfa_challenge=...;
  • redirect_to was missing, or unsafe and refused.

That default was redirect_base_url, which is fine for an app served at its root. It isn't for a
single-page app under /app with a landing page at /: a declined Google sign-in landed on the
landing page, which doesn't read ?error. And redirect_base_url can't carry /app, because it
also builds the redirect URI you register with the provider.


The option

auth = CRUDAuth(
    ...,
    redirect_base_url="https://example.com",
    oauth_default_redirect="/app/login",
)

A failure now lands on /app/login?error=<code>, an MFA challenge on
/app/login#mfa_challenge=..., and a sign-in without a safe redirect_to on /app/login. A safe
redirect_to still wins, and the provider redirect URI doesn't change.

It takes a same-origin path or an absolute http(s) URL. Anything else, such as //evil.example
or javascript:..., is refused when CRUDAuth is constructed, so a typo fails at startup rather
than at someone's sign-in. Leave it unset and nothing changes.


Documentation

  • "When the app isn't at the root" in the OAuth guide.
  • The error and MFA sections name the new target.
  • The agent skill references say the same, so an assistant wiring OAuth into an app under a path
    reaches for the option instead of a proxy rewrite.

Upgrading

pip install -U crudauth

Nothing is required. If your app isn't served at the root of redirect_base_url and you've been
forwarding /?error=... to your login page with a proxy rule, replace the rule with
oauth_default_redirect.


Full Changelog: v0.7.2...v0.7.3

Dependencies: unchanged.

Docs: https://benavlabs.github.io/crudauth

v0.7.2

Choose a tag to compare

@igorbenav igorbenav released this 28 Sep 03:36
94e36cc

Release v0.7.2 - Guardrails for Your Own Registration Route

Date: 2026-09-28

A small release about one thing: apps that register users through their own route instead of
CRUDAuth's /register. The allowlist has always protected CRUDAuth's endpoint, but nothing helped
an app audit the schema it wrote itself, and the field that matters most there, email_verified,
is what the OAuth account claim depends on. No breaking changes, and upgrading needs no code
changes.


Why this exists

CRUDAuth's /register keeps email and username, plus whatever you opt into with
register_extra_fields. Everything privileged is dropped unconditionally (is_superuser,
email_verified, the password, the OAuth identifiers, the primary key), and the gate covers a
column_map alias too.

An app with its own signup route gets none of that. If that route accepts email_verified, someone
can register under an address they don't own as already verified. When the owner later signs in
with Google, CRUDAuth finds a verified account with that email and links their provider identity to
it, but skips the claim, because the account looks like it proved itself. The claim is what would
otherwise make the password unusable, clear MFA, bump token_version and terminate the sessions.
So the person who registered first keeps password access to the account its owner now uses. The same
goes for google_id and github_id, which decide which account a provider login resolves to.

This shipped as a real vulnerability in a downstream project
(GHSA-h3fc-96x2-49rx),
which is what prompted the release: the defect wasn't in CRUDAuth, but nothing in CRUDAuth made it
easy to notice either.


The check

UserRepository.gated_register_fields(names) already existed; the sets behind it are now exported
from the package root, so an app can assert its own schema in one line:

from crudauth import REGISTRATION_GATED_FIELDS  # the full set, if you want to read it

def test_signup_accepts_no_privileged_field():
    assert not auth.repo.gated_register_fields(SignUp.model_fields)

It answers with the privileged fields a set of names contains, by logical name and by mapped
column, so a column_map rename can't slip one past. Put it next to your signup tests and a field
added later can't quietly reopen the hole.

A signup schema that's safe to write yourself:

class SignUp(BaseModel):
    model_config = ConfigDict(extra="forbid")

    email: EmailStr
    username: str
    password: str

Nothing privileged declared, extra="forbid" so an attempt is a 422, and build the row from those
fields plus a hash, never from **payload.model_dump(), which carries whatever the schema grew
since.


Documentation

  • "Registering users from your own route" in the registration guide, with the schema, the
    assertion, and why email_verified is the field that turns a careless signup into account
    takeover.
  • The two field sets are described on the UserRepository API page.
  • The same rule is in the agent skill references, so an assistant writing a signup route follows it:
    identity.md carries the schema and the assertion, and oauth.md records that the claim only
    holds while email_verified is server-owned, and that an app doing its own account linking has to
    claim as well.

Upgrading

pip install -U crudauth

Nothing is required. If your app has its own registration route, add the assertion above to its
tests. And if it links OAuth accounts with its own code rather than OAuthAccountService, check
that it claims an unverified account on link.


Full Changelog: v0.7.1...v0.7.2

Dependencies: unchanged.

Docs: https://benavlabs.github.io/crudauth

v0.7.1

Choose a tag to compare

@igorbenav igorbenav released this 19 Sep 04:27
349d71e

Release v0.7.1 - OAuth State Redirects and Rate-Limit Headers on Errors

Date: 2026-09-18

A follow-up to v0.7.0 with two fixes that came out of moving the FastAPI boilerplate onto it. Both
make the library do what 0.7.0 already promised in the normal case. There are no breaking changes,
and upgrading needs no code changes.


A failed OAuth state check in redirect mode goes back to the app

In redirect mode, a failed callback sends the browser back to redirect_base_url with
?error=<code>. The state checks were the one exception: they answered with a JSON 400 on the
API's origin. That covered a callback with no state cookie, a cookie from another sign-in, and a
state that's already used or expired. These are the everyday ways a sign-in fails: the user took
too long, finished it in another browser, or went back and resubmitted.

They now use the same redirect, with a new code:

GET /oauth/google/callback?code=...&state=...
307 Location: https://app.example.com?error=invalid_state

The state cookie is cleared and no session is created. If your app already handles ?error= on its
landing page, add invalid_state there and offer to start the sign-in again. JSON mode still answers
400 Invalid or expired OAuth state.


Rate-limit headers on responses refused after the limiter

rate_limit() counts a request before the rest of the route runs. When something after it raises,
FastAPI builds the response from the exception, and the X-RateLimit-* headers were lost. That
something could be current_user() answering 401, the route raising a 404, or a 422 for a bad
body. A client pacing itself by the headers saw no budget being spent through a run of 401s, and
then got a 429.

Add the new middleware to put the headers on those responses too:

from crudauth.ratelimit import RateLimitHeadersMiddleware

app.add_middleware(RateLimitHeadersMiddleware)

It only fills in headers a response doesn't have, so successful responses and the 429 are
unchanged. A request that no limiter counted gets no headers.

Without the middleware, one thing changes for routes with more than one limiter. The headers now
describe the limiter with the least remaining, since that's the one the client will hit first.
Before, they described whichever limiter ran last.


Upgrading

pip install -U crudauth

Nothing is required. Optionally:

  • Handle ?error=invalid_state on the page redirect_base_url points to.
  • Add RateLimitHeadersMiddleware if clients read the rate-limit headers.

Full Changelog: v0.7.0...v0.7.1

Dependencies: unchanged.

Docs: https://benavlabs.github.io/crudauth

v0.7.0

Choose a tag to compare

@igorbenav igorbenav released this 18 Sep 00:06
8efd18a

Release v0.7.0 - Second Factors and Any Identity Provider

Date: 2026-09-17

v0.7.0 adds a second factor, and an identity provider that isn't Google or GitHub - and then puts every
path that was already here through a security pass. TOTP is opt-in and covers both login routes and
OAuth. Any OpenID Connect provider is configured with its issuer and nothing else. Five hardening
branches went through OAuth account linking, sessions, recovery tokens, password hashing, and rate
limiting.

It's the largest release so far: 24 merged pull requests since v0.6.0. Most apps upgrade by changing
nothing, but there are four breaking changes, all listed below with what to do about them.


Headline changes

TOTP two-factor authentication

auth = CRUDAuth(
    ...,
    mfa=MfaConfig(
        issuer="Acme",                                # shown in the authenticator app
        encryption_key=os.environ["MFA_ENCRYPTION_KEY"],
        required=lambda user: user.is_superuser,      # False | True | a sync/async predicate
    ),
)

Seven routes mount under /mfa: POST /verify, POST /challenge, GET /mfa (status),
POST /totp/setup, POST /totp/confirm, POST /totp/disable and
POST /recovery-codes/regenerate. Codes are RFC 6238, six digits, a 30-second step with ±1 drift,
compared in constant time. Secrets are encrypted at rest with Fernet (pass a
list of keys to rotate; the first encrypts, all decrypt), and recovery codes are stored as SHA-256
hashes and consumed with a compare-and-set so one code can't be spent twice.

Login is where it shows up: /login and /token now answer
{"mfa_required": true, "challenge": "...", "expires_in": 300} for an enrolled account instead of
signing them in, and /mfa/verify finishes the login with whatever the transport would have
returned. The challenge is stored server-side under a hash of its token, bound to the user's
token_version, with a TTL and an attempt cap. A correct password that still needs its second
factor neither counts against the login lockout nor clears it.

oauth=True on MfaConfig also challenges social logins; it's off by default, since the provider
did its own verification. If MFA is required for accounts that can sign in with OAuth, CRUDAuth
warns at startup when oauth=False would let them skip it.

Enrolling needs four columns on the model (totp_secret_encrypted, totp_confirmed_at,
totp_last_step, mfa_recovery_codes) - make_auth_identity(mfa=True) emits them - plus the
crudauth[mfa] extra for cryptography.

Any OpenID Connect provider from its issuer

oauth={
    "keycloak": OAuthCredentials(
        client_id="...", client_secret="...",
        issuer="https://sso.example.com/realms/main",
    ),
}

Keycloak, Zitadel, Authentik, Auth0, Okta, Entra ID: no provider class, no endpoint URLs. The
endpoints come from {issuer}/.well-known/openid-configuration when the app starts, and the dict key
is the provider name, so this one links accounts on keycloak_id and serves
/oauth/keycloak/authorize like any built-in.

Discovery decides where an app sends its users' credentials, so it's checked: the document must
declare the issuer it was fetched from, the issuer must be https (localhost excepted, for
development) and carry no query or fragment, and the document must name the three endpoints. Client
authentication follows what the provider advertises - the secret in the body, or HTTP Basic when
that's all it accepts. email_verified is honored exactly as stated, so a provider that doesn't
claim verification can't auto-link to an existing account.

A public client (PKCE, no secret) no longer sends an empty client_secret, which several IdPs
reject.

Recovery links can bring people back

Someone opens an invitation, has no account, signs up, verifies from their inbox, and lands on a
generic signed-in page. redirect_to on /email/verify-request, /password/reset-request and
/email/change-request fixes that: the destination rides inside the signed token, so the emailed
URL is unchanged and the destination survives the link being opened on a different device than the
one that started the sign-up. The confirm responses hand it back. Same-origin relative paths only,
validated when the token is minted and again when it's redeemed.

A security pass over what was already here

  • OAuth account linking: an unverified local account is claimed rather than silently linked, a
    provider that doesn't report a verified email can't link to an existing account, and the callback
    stopped leaking which addresses exist.
  • Sessions: device lists and revocation work on opaque handles instead of raw session ids,
    sessions are bound to token_version, writes are compare-and-set, logout clears a bearer refresh
    cookie too, and a login the browser marks Sec-Fetch-Site: cross-site is refused.
  • Recovery tokens: bound to the account state they were minted for, so a reset link dies when the
    password or recovery value changes; the previous address is notified on an email change.
  • Passwords: hashing and verification run off the event loop, the unusable-password path is
    timing-equalized, and passwords are NFKC-normalized before hashing.
  • Rate limiting: X-Forwarded-For is read against a trusted-proxy boundary, TTLs are set
    atomically with the counter, clear_all can't be used to wipe a spray, and the lockout is
    configurable through LockoutConfig.

Configuration people asked for

PasswordPolicy enforced on every password path; dynamic rate limits with KeyBy.USER_OR_IP and
per-request resolution; auth.resolve_principal(request) for middleware; injected Redis clients that
stay yours; configurable OAuth paths and a JSON response mode; safe_redirect_path exported for your
own routes; and OAuth-generated usernames bounded to your column width.

The internals were split up

crud_auth.py shed a third of its length: the account and session-management routes, the
rate-limit dependencies, the OAuth path helpers and each transport's own routes moved into their own
modules, utils.py became a package, and route builders take a typed AuthSurface instead of Any.
Every documented import path still works.


Breaking changes

  • EmailFlowService.confirm_recovery_verification / reset_password / confirm_email_change
    return EmailFlowResult(user, redirect_to)
    instead of the user row.
  • DELETE /sessions/{id} takes a session handle, and GET /sessions returns handles rather than
    raw session ids.
  • Internals moved: auth._apply_rate_limit is gone, the per-feature store attributes are one
    registry, SessionInfo is defined in crudauth.transports.session.management, and four transport
    helpers dropped their underscore (SessionTransport.enforce_csrf, BearerTransport.read_refresh,
    clamp_scopes, access_token).
  • AbstractOAuthProvider gained initialize() and _ensure_ready() (no-ops by default) and an
    optional transport= argument.

Migrating from v0.6.0

If you mount auth.router and don't call the services yourself, there is nothing to do. The
routes, their request bodies and their responses are unchanged, except where you opt into a new
feature. No database migration, and no session or token invalidation: session handles are derived
from the session id on the fly, and token_version on a session defaults to unbound, so everyone
stays logged in across the upgrade.

The rest applies only if it describes you.

1. You call the email service directly. Unpack the result:

# before
user = await auth.emails.confirm_recovery_verification(db, token)

# after
user, redirect_to = await auth.emails.confirm_recovery_verification(db, token)
# or: result.user / result.redirect_to

Same for reset_password and confirm_email_change. Code that ignores the return value needs no
change.

2. Your frontend lists or revokes sessions. Each entry's id in GET /sessions is now the
session's public handle - the SHA-256 of the session id - and that's what
DELETE /sessions/{id} takes. The shape of the response is unchanged, but the values are
different, so re-read the list after upgrading rather than reusing anything you stored. A raw
session id is no longer accepted, which is the point: it's the cookie value and must never reach a
page.

3. You enable MFA. Add the four columns (make_auth_identity(mfa=True) emits them, otherwise map
them with column_map=), install crudauth[mfa], and set an encryption_key that differs from
SECRET_KEY (CRUDAuth refuses to start otherwise). Then teach the client that /login and /token
can answer {"mfa_required": true, "challenge": ...}: post that challenge plus the code to
/mfa/verify, which returns what the login would have returned. Accounts that never enroll are
unaffected.

4. You configure an OIDC provider. Discovery is a network call, so it happens in
CRUDAuth.initialize():

@asynccontextmanager
async def lifespan(app):
    await auth.initialize()
    yield
    await auth.shutdown()

That's the same lifespan call a Redis-backed app already makes. Skip it and the provider raises on
first use rather than sending someone to a hostless URL.

5. You wrote a custom transport. Two optional methods let it join the login and MFA flows:
complete_login(request, response, user, options) issues your credential once a login is fully
verified, and sets_cookies() tells the cross-site check whether a login sets a cookie. The default
complete_login raises, which is right for a transport with no login route.

6. You wrote a custom OAuth provider. A subclass that passes its arguments to super().__init__
is unaffected. initialize() is wher...

Read more

v0.6.0

Choose a tag to compare

@igorbenav igorbenav released this 22 Jun 02:46
bc73418

Release v0.6.0 - The Toolbox

Date: 2026-06-21

v0.5.0 added the device-management routes. v0.6.0 turns the rest of CRUDAuth inside out: the hardened
auth flows that used to live only inside the route handlers are now reusable primitives, every wired
service is reachable off auth, and the building blocks are exported from the package root. So you
can hand-roll a login, mint a token in a webhook, or skip the routes entirely without losing the
hardening, or reimplementing it. Everything is additive; nothing breaks.


Headline changes

Reusable password authentication and token issuance

The credential check (escalating lockout, timing-equalized verification, the disabled-account check)
was inlined and duplicated in both /login and /token, and callable from nowhere; token issuance
(scope clamp, token_version epoch) was inlined in /token. Two new primitives fix that:

  • auth.authenticate_password(db, identifier, password, *, request) returns the user on success
    and raises UnauthorizedException / RateLimitException otherwise. /login and /token now
    delegate to it.
  • auth.issue_tokens(user, *, scopes=None) mints the access + refresh pair, clamping scopes to
    grantable_scopes and stamping the epoch. /token issues through it.

So a hand-written login or a token minted outside /token gets exactly what the built-in routes get.
Reach for these instead of the raw functions, which skip the lockout, the clamp, and the epoch, which
is the whole point.

Every wired service reachable off auth

auth.repo / auth.sessions / auth.sudo were already public; now auth.emails (the
EmailFlowService) and auth.oauth (the OAuthAccountService) join them, each None when the
feature isn't configured. Trigger a reset from your own route, or reuse the OAuth linking rules in a
hand-written callback, without touching private attributes.

The building blocks are exported

from crudauth import UserRepository, SessionManager, SudoManager, EmailFlowService, OAuthAccountService and the password helpers get_password_hash, verify_password,
is_unusable_password, make_unusable_password. The raw token-mint functions stay unexported on
purpose, so issue_tokens remains the path that carries the clamp and the epoch.

End-to-end tests against real Postgres

A new tests/e2e/ suite spins up PostgreSQL via testcontainers and drives full journeys (login,
token, refresh, lockout, revocation, device management, recovery) over HTTP. It was the before/after
anchor for the refactor, and it catches dialect issues SQLite hides, like coercing a token's string
sub to an integer primary key. It skips automatically when Docker isn't available.


Breaking changes

None. Two new facade methods, two new accessors, nine new exports, and a new test suite. The /login,
/token, and /refresh handlers were refactored to delegate to the new primitives, but their HTTP
behavior is unchanged, which the Postgres journeys verify.

Tests

ruff and mypy clean (106 files), full suite green (329 passing: 7 new toolbox tests plus 6 new
Postgres e2e journeys), docs build clean. The new primitives are covered by a hand-rolled login over
authenticate_password, issue_tokens minting and scope-clamping, the service accessors, and the
exports; the routes that now delegate are pinned by the e2e journeys end to end.

What's Changed

  • Extract authenticate_password and issue_tokens, add auth.emails / auth.oauth, export the toolbox surface, and add an e2e suite against real Postgres (the building-blocks toolbox)

Full Changelog: v0.5.0...v0.6.0

Dependencies: no new runtime dependencies; the dev group gains testcontainers[postgres] and asyncpg.

Docs: https://benavlabs.github.io/crudauth