0.15 storage and creation migration
0.15 changes verification storage to enforce one-time use under concurrent requests. Upgrade every application worker together after migrating persistent storage. Do not mix old workers, which use read/update/delete, with 0.15 atomic verification writers. Back up the database and stop authentication writers while migrating.
Required custom-adapter contract
VerificationStore now requires:
async def attempt_verification(
self,
identifier: str,
purpose: VerificationPurpose,
value_hash: str,
*,
now: datetime,
max_attempts: int | None = None,
consume: bool = True,
) -> VerificationAttempt: ...
VerificationAttempt is exported from fastauth.storage.base. Its fields are:
status:accepted,invalid,expired,exhausted, orabsentattempt_count: the failed-attempt count at this decisionverification: an independentVerificationsnapshot on acceptance, otherwiseNone
Verification.consumed_at is an optional UTC datetime. Consumed and exhausted
challenges are invisible to get_verification and get_active_verification.
The expiry boundary is expires_at <= now. A positive max_attempts applies to
both valid and invalid guesses; a challenge already at its cap cannot succeed.
A wrong guess increments the counter exactly once and burns the challenge when
it reaches the cap. consume=False performs the same atomic checks and failed
attempt accounting but leaves a correct challenge available for later consumption.
max_attempts=None is used for high-entropy opaque links. An invalid guess then
increments the counter but does not impose an OTP-style attempt cap.
create_verification must atomically replace the current challenge for the
(identifier, purpose) pair. There must be at most one current record, including
consumed records. Issuance, attempts, expiry checks, and supersession must share
the same backend atomic boundary. Old challenges cannot become valid after the
newest challenge is consumed or expired. Do not implement replacement as
delete_verifications_for_identifier() followed by an independent insert.
The latest completed issuance wins; simultaneous email delivery order is not an
ordering guarantee. Issuance does not guarantee email delivery.
Use a backend atomic operation or transaction. A Python lock on each database
client does not coordinate separate workers. There is no safe fallback to the
old read/modify/write protocol. FastAuth rejects adapters that omit the method
or inherit the unsupported BaseDatabaseAdapter default. Structural capability
checks cannot prove atomicity: adapter authors must execute the conformance tests
against their backend with concurrent independent clients.
This mandatory capability and changed current-challenge semantics are an explicit
security exception to the usual deprecation window in API_STABILITY.md.
Preserving the old fallback would preserve double consumption and lost attempts.
Legacy read/update/delete adapter methods remain available for maintenance, but
must not be used to implement authentication decisions or to restore consumed
state. Verification IDs are opaque; Mongo may reuse the same storage ID when
replacing a challenge. Do not retain an old ID to perform delayed deletion.
First-party implementations
- Memory: one asyncio lock covers issuance and the entire attempt decision
- PostgreSQL: a unique
(identifier, purpose)key, upsert issuance, and a transaction withSELECT ... FOR UPDATEaround the decision and update - MongoDB: a unique
(identifier, purpose)index, upsert issuance, and onefind_one_and_updateaggregation pipeline for each attempt. This works on standalone MongoDB; verification does not require replica-set transactions
All link-based verification, password reset, email change, account deletion, OTP sign-in, OTP verification, OTP reset, OTP email change, and OTP pre-check paths use the same atomic adapter decision. After a challenge is consumed, subsequent mutation/delivery failures do not make it reusable: request a new challenge. Invalid new passwords are validated before consuming reset challenges.
MongoDB preflight and offline migration
The Python counter field on RateLimitDoc is now hits, leaving Beanie's
RateLimitDoc.count() collection-counting method available. Its BSON alias
remains count, so existing rate-limit records need no migration. Domain
RateLimit.count and the adapter API are unchanged. Code that reads the
counter directly from a Beanie document should use document.hits.
New databases receive a unique partial username index covering string values only. Multiple documents with missing or null usernames can coexist; duplicate non-null usernames remain rejected. The previous unique+sparse index included explicit null values and must be replaced.
init_beanie_documents checks for incompatible legacy indexes and fails with an
explicit migration instruction. It does not silently drop indexes or select a
historical challenge for you. With writers stopped, use the same database and
collection affixes as your application:
from fastauth.storage.beanie import (
migrate_mongo_storage_v015,
preflight_mongo_storage_v015,
)
result = await migrate_mongo_storage_v015(
database,
collection_prefix="", # match your deployed configuration
collection_suffix="",
)
await preflight_mongo_storage_v015(database)
The migration:
- Builds
users_username_strings_uniquewithpartialFilterExpression={"username": {"$type": "string"}}. Existing duplicate string usernames fail index creation before any legacy username index is dropped - Drops incompatible legacy unique username indexes after the replacement exists
- Retains only the newest verification for each identifier/purpose, ordered by
created_atthen_id, including expired/consumed rows. Older outstanding links and OTPs are intentionally invalidated - Builds
verifications_current_uniqueand initializes missingconsumed_atfields
The result reports removed username indexes and the number of superseded verification rows deleted. Re-running is safe with writers stopped. Resolve any duplicate real usernames explicitly before retrying. A failed attempt can have partially completed these steps; keep writers stopped until preflight and initialization succeed. Existing legacy hash indexes can remain; they do not replace the new unique pair index. Mongo's TTL deletion remains maintenance, never the authorization expiry check.
PostgreSQL migration
The tracked schema migration 5, atomic current verification challenges, adds
consumed_at, removes superseded verification records while retaining the newest
record per pair, and installs the unique pair index. Apply the normal adapter
migration workflow, or run with migration mode check after your deployment has
applied migrations. This migration follows the release's policy/session migration
4. New and existing installations must reach the current schema version.
Existing old links/OTPs other than the newest per pair are intentionally invalidated. The migration executes within the adapter migration transaction. Backups are the recovery mechanism; downgrading application binaries does not restore deleted challenges. Ordinary user, account, and session data is not removed by migration 5.
User and credential creation
Signup and trusted provisioning validate and hash passwords before user/account
writes. OTP auto-registration shares the same user/account persistence helper.
An account write failure triggers deletion of the newly owned user and its
associated state. Cancellation is deferred until the short persistence/cleanup
section completes, then propagated. Mongo allocates the new ObjectId before its
insert await so a lost insert acknowledgement can be compensated by the owned ID.
Custom adapters must likewise expose the owned ID on the input user before an
insert can complete or fail ambiguously, and must implement delete_user cleanup.
Duplicate-identity errors never trigger deletion of an existing user's data.
AFTER_CREATE observes a stored user with a usable account. Once those writes
commit, a later session, hook, refresh, or notification failure does not delete the
identity; the user can sign in or request a new OTP. Signup success events remain
after session creation, so a failed session response is not a successful signup
event. Trusted provisioning emits UserCreated after its after-create hook.
Hooks and event delivery do not constitute a database transaction.
Compensation is not a distributed transaction: process termination or a database outage that also prevents cleanup can require operator reconciliation. Cleanup failure is surfaced rather than reported as success. Configure database timeouts; cancellation must not abandon the consistency section midway through a write. No atomic multi-collection Mongo transaction or new replica-set requirement is implied by this recovery contract.
Optional compare-and-swap password rehash
PasswordRehashStore is a separate optional runtime-checkable protocol:
async def replace_account_password(
self,
account_id: str,
*,
expected_hash: str,
new_hash: str,
) -> bool: ...
It updates only the password and timestamp if the stored hash still equals
expected_hash. A concurrent password reset must win over stale rehash work.
All first-party adapters implement the atomic comparison. Custom adapters may
omit it and skip automatic rehash; successful authentication must not use an
unconditional whole-account update as a rehash fallback. Use
PasswordRehashAdapterContract from fastauth.testing for conformance.
Memory adapter isolation
Reads, lists, and create/update return values are independent deep snapshots. Changing an input or returned model, including nested metadata, no longer changes stored state until an explicit successful update. This aligns Memory behavior with persistent adapters and prevents rejected hooks from changing state through shared Python object references.
Release verification
The adapter and quickstart fixtures accept FASTAUTH_TEST_MONGO_URL and
FASTAUTH_TEST_POSTGRES_URL for disposable real databases. Otherwise they launch
MongoDB 7 and PostgreSQL 16 containers. Never point these fixtures at a production
database: test fixtures delete test databases and create/drop test tables.
Set FASTAUTH_REQUIRE_DATABASES=1 for release verification. Missing Docker or
another database setup error then fails the suite instead of marking it skipped.
The Docker-backed CI job sets this flag. Require an executed, zero-skip backend
job; Memory tests and mocked database calls do not establish Mongo/PostgreSQL
concurrency or migration correctness.
Protected user activation
UserStatusStore is a separate capability for privileged activation changes:
Ordinary update_user must preserve the currently stored active field even
when the supplied model has a different value. A stale profile update must never
undo a suspension. Implement this in the atomic database mutation itself, not by
reading current status and later replacing the whole document. All three
first-party adapters enforce that separation. The policy setter requires this
capability and must not fall back to an ordinary whole-row update. Use
UserStatusAdapterContract and CreationAdapterContract from fastauth.testing
for the protected-status and compensating-creation backend release gates.