security#
Declarative litestar-security configuration, SQLAlchemy persistence adapters, and authorization resolver.
Declarative litestar-security persistence adapters, resolver, and configuration.
- class app.domain.accounts.security.APIKeyIdentityResolver(alchemy_config: SQLAlchemyAsyncConfig)[source]#
Bases:
objectResolves verified
APIKeyClaimsto an eager-loadedPrincipal[m.User].Initialize the API key identity resolver.
- __init__(alchemy_config: SQLAlchemyAsyncConfig) None[source]#
Initialize the API key identity resolver.
- async resolve(claims: APIKeyClaims | APIKeyState) Principal[User] | InvalidCredentials | VerificationUnavailable[source]#
Load the active user for the key’s
subject_idor fail closed on storage errors.- Returns:
Resolved user principal,
InvalidCredentialsif missing/inactive, orVerificationUnavailable.
- class app.domain.accounts.security.AppAuthorizationResolver[source]#
Bases:
objectZero-I/O
AuthorizationResolverexpanding global and additive hierarchical team roles.- async resolve(principal: Principal[m.User]) AuthorizationSnapshot | InvalidCredentials | VerificationUnavailable[source]#
Compute an immutable
AuthorizationSnapshotpurely from eager-loadedUserattributes.- Returns:
Computed
AuthorizationSnapshot,InvalidCredentialsif user is missing, orVerificationUnavailable.
- class app.domain.accounts.security.ApplicationAccessRouter(*args: Any, **kwargs: Any)[source]#
Bases:
RouterRouter placing the application’s own controllers behind
require_application_access.Route discovery wraps every domain controller in this router, which keeps the guard off routes the security configuration excludes, such as static files.
Initialize the router with the application-access guard ahead of any guards passed in.
- class app.domain.accounts.security.AuditSecurityEventSink(alchemy_config: SQLAlchemyAsyncConfig, *, strict: bool = False)[source]#
Bases:
objectSecurityEventSinkwriting redacted security telemetry toAuditLog.Initialize the audit event sink.
- Parameters:
alchemy_config – Shared Advanced Alchemy async configuration.
strict – Whether to re-raise database write errors instead of logging and suppressing.
- class app.domain.accounts.security.SQLAlchemyAPIKeyStore(alchemy_config: SQLAlchemyAsyncConfig)[source]#
Bases:
objectAPIKeyStoreon Advanced Alchemy services storing only peppered digests, prefixes, and rotation lineage.Initialize the API key store.
- async get(key_id: str) APIKeyState | None[source]#
Load one API key state record by opaque
key_id.- Returns:
Matching key state, or
Noneif not found.
- async create(record: APIKeyState) None[source]#
Persist a new digest-only API key record.
- Raises:
ValueError – If
key_idalready exists, orsubject_idis not a valid UUID or names no account.
- async rotate(*, current_key_id: str, replacement: APIKeyState, overlap_until: datetime | None, now: datetime) None[source]#
Atomically mark the current key rotated with bounded overlap and persist its successor.
- Raises:
ValueError – If
replacement.subject_idis invalid or rotation conflicts with current state.IntegrityError – If the database fails for a reason other than a violated constraint.
- async revoke(*, key_id: str, now: datetime) None[source]#
Stop an existing API key from working now, ending any rotation overlap it still has.
- Raises:
ValueError – If no API key matches
key_id.
- async list_for_user(user_id: UUID) list[m.APIKey][source]#
List all API keys owned by a user ordered newest first.
- Returns:
API keys belonging to
user_id.
- async get_for_user(user_id: UUID, key_id: str) m.APIKey | None[source]#
Fetch one API key owned by
user_id.- Returns:
Matching API key, or
Noneif not found.
- async update_metadata(key_id: str, *, name: str, key_prefix: str) APIKey | None[source]#
Update human-readable name and display prefix on an existing key.
- Returns:
Updated API key, or
Noneifkey_iddoes not exist.
- class app.domain.accounts.security.SQLAlchemyMFALoginChallengeService(alchemy_config: SQLAlchemyAsyncConfig)[source]#
Bases:
objectAdapter implementing
MFALoginChallengeStorewith burn-on-consume and burn-on-mismatch.Initialize the MFA login challenge store.
- __init__(alchemy_config: SQLAlchemyAsyncConfig) None[source]#
Initialize the MFA login challenge store.
- class app.domain.accounts.security.SQLAlchemyMFAService(alchemy_config: SQLAlchemyAsyncConfig)[source]#
Bases:
objectAdapter implementing
MFAStorefor encrypted TOTP factors and peppered recovery code digests.Initialize the MFA store.
- async create_totp_enrollment(enrollment: PendingTOTPEnrollment) None[source]#
Persist a pending encrypted TOTP enrollment, rejecting a non-UUID
account_idwithValueError.
- async get_totp_enrollment(enrollment_id: str) PendingTOTPEnrollment | None[source]#
Load a pending TOTP enrollment by identifier.
- Returns:
Matching pending enrollment, or
Noneif not found.
- async activate_totp(account_id: str, enrollment_id: str, *, accepted_counter: int, login_method: LoginMethod, event: SecurityEvent, now: datetime) TOTPMethod | None[source]#
Confirm a pending TOTP enrollment, its login method, and its audit event in one transaction.
- Returns:
Activated
TOTPMethod, orNoneif missing, expired, or already confirmed.
- async activate_totp_with_recovery_codes(account_id: str, enrollment_id: str, *, accepted_counter: int, codes: tuple[RecoveryCodeDigest, ...], login_method: LoginMethod, event: SecurityEvent, now: datetime) TOTPMethod | None[source]#
Confirm a pending TOTP enrollment and replace the account’s recovery codes in one transaction.
- Returns:
Activated
TOTPMethod, orNoneif missing, expired, or already confirmed.
- async get_totp_method(account_id: str, method_id: str) TOTPMethod | None[source]#
Load an active TOTP method owned by the specified account.
- Returns:
Confirmed
TOTPMethod, orNoneif not found.
- async advance_totp_counter(method_id: str, *, accepted_counter: int, now: datetime) bool[source]#
Advance a TOTP method’s counter only when strictly greater than the previous value.
- Returns:
Trueif the counter advanced,Falseotherwise.
- class app.domain.accounts.security.SQLAlchemyOAuthAccountStore(alchemy_config: SQLAlchemyAsyncConfig, protector: OAuthTransactionProtector)[source]#
Bases:
objectOAuthAccountStoreadapter persisting linked OAuth identities and encrypted provider tokens.Initialize the OAuth account store with an AEAD protector.
- __init__(alchemy_config: SQLAlchemyAsyncConfig, protector: OAuthTransactionProtector) None[source]#
Initialize the OAuth account store with an AEAD protector.
- async link(account_id: str, identity: ProviderIdentity, grant: ProviderGrant, tokens: ProviderTokenSet, *, retain_tokens: bool = False, now: datetime) LinkedProviderAccount[source]#
Link an external OAuth identity to an existing user account.
An identity that belongs to another user, or a provider the user already linked, surfaces as the
AccountLinkErrorraised byOAuthAccountService.link.- Returns:
Persisted
LinkedProviderAccountrecord.- Raises:
OAuthAccountError – If
account_idis not a valid UUID.
- async login(identity: ProviderIdentity, grant: ProviderGrant, tokens: ProviderTokenSet, *, provision_unknown: bool, retain_tokens: bool, now: datetime) OAuthLoginOutcome[source]#
Authenticate or optionally provision a user via an external OAuth identity.
An unlinked identity that may not be provisioned, or whose email is already registered, surfaces as the
AccountLinkErrorraised byOAuthServices.login.- Returns:
OAuthLoginOutcomecontaining the linked account and provisioning flag.
- async resolve_provider_account(account_id: str, provider: str) LinkedProviderAccount | None[source]#
Resolve an account’s linked OAuth identity for the named provider.
- Returns:
Matching
LinkedProviderAccount, orNoneif not linked.
- async upgrade(account_id: str, provider_account_id: str, identity: ProviderIdentity, grant: ProviderGrant, tokens: ProviderTokenSet, *, retain_tokens: bool, now: datetime) LinkedProviderAccount[source]#
Upgrade scopes and optionally replace retained tokens on an existing OAuth link.
- Returns:
Updated
LinkedProviderAccountrecord.- Raises:
AccountLinkError – If identifiers are invalid or no matching linked account exists.
- async unlink(account_id: str, provider: str, provider_account_id: str, *, require_remaining: bool, now: datetime) UnlinkOutcome[source]#
Atomically unlink an owned OAuth identity while protecting the user’s final login method.
- Returns:
UnlinkOutcomedescribing whether the link was removed, missing, or blocked as the final method.
- async get_tokens(provider_account_id: str, *, now: datetime) StoredProviderTokens | None[source]#
Decrypt and return retained OAuth tokens for a linked account.
- Returns:
StoredProviderTokenswith version metadata, orNoneif unavailable.
- async replace_tokens(provider_account_id: str, *, expected_version: int, tokens: ProviderTokenSet, now: datetime) bool[source]#
Optimistically replace encrypted provider tokens when version matches.
- Returns:
Trueif tokens were replaced,Falseon missing row or version mismatch.
- class app.domain.accounts.security.SQLAlchemyOAuthTransactionStore(alchemy_config: SQLAlchemyAsyncConfig, protector: OAuthTransactionProtector)[source]#
Bases:
objectOAuthTransactionStoreadapter keeping PKCE verifiers and nonces encrypted with AES-GCM.Initialize the OAuth transaction store with an AEAD protector.
- __init__(alchemy_config: SQLAlchemyAsyncConfig, protector: OAuthTransactionProtector) None[source]#
Initialize the OAuth transaction store with an AEAD protector.
- async create(transaction: OAuthTransaction) None[source]#
Encrypt PKCE/nonce secrets and persist a single-use OAuth transaction.
- async consume(*, state_digest: bytes, binding_digest: bytes, provider: str, now: datetime) OAuthTransaction | None[source]#
Consume a matching unexpired OAuth transaction atomically without burning mismatched callbacks.
- Returns:
Consumed
OAuthTransactionwith decrypted secrets, orNoneif unmatched or expired.
- class app.domain.accounts.security.SQLAlchemyPasskeyStore(alchemy_config: SQLAlchemyAsyncConfig)[source]#
Bases:
objectAdapter implementing both
PasskeyStoreandWebAuthnChallengeStoreon Advanced Alchemy services.Initialize the passkey and WebAuthn challenge store.
- __init__(alchemy_config: SQLAlchemyAsyncConfig) None[source]#
Initialize the passkey and WebAuthn challenge store.
- async add_credential(credential: PasskeyCredential, *, login_method: LoginMethod, event: SecurityEvent) bool[source]#
Persist a new passkey credential, its login method, and its audit event in one transaction.
- Returns:
Trueif stored,Falseifaccount_idis invalid or the credential already exists.- Raises:
IntegrityError – If the database fails for a reason other than a violated constraint.
- async get_credential(credential_id: bytes) PasskeyCredential | None[source]#
Load one passkey credential by raw credential identifier bytes.
- Returns:
Matching passkey credential, or
Noneif not found.
- async list_credentials(account_id: str) tuple[PasskeyCredential, ...][source]#
List all passkey credentials owned by an account.
- Returns:
Tuple of passkey credentials registered to
account_id.
- async record_assertion(credential_id: bytes, *, expected_version: int, sign_count: int, backup_eligible: bool, backup_state: bool, clone_risk: bool, now: datetime) PasskeyAssertionStatus[source]#
Optimistically update credential sign count, version, and clone-risk flag.
- Returns:
Assertion recording status (
RECORDED,CLONE_RISK, orCONFLICT).
- async rename_credential(account_id: str, credential_id: bytes, display_name: str) PasskeyCredential | None[source]#
Rename a passkey credential owned by the specified account.
- Returns:
Updated passkey credential, or
Noneif not found.
- class app.domain.accounts.security.SQLAlchemySecurityBackend(alchemy_config: SQLAlchemyAsyncConfig, *, clock: Callable[[], datetime] | None = None, notification_handler: Callable[[NotificationCommand], Awaitable[None]] | None = None)[source]#
Bases:
objectAdapter implementing the
LocalAuthaccount, token, login method, and session ports on services.Initialize the backend with an Advanced Alchemy config and optional notification callback.
- __init__(alchemy_config: SQLAlchemyAsyncConfig, *, clock: Callable[[], datetime] | None = None, notification_handler: Callable[[NotificationCommand], Awaitable[None]] | None = None) None[source]#
Initialize the backend with an Advanced Alchemy config and optional notification callback.
- async find_for_login(normalized_identifier: str) LocalAccountState[User] | None[source]#
Locate an account by normalized email address with authorization relationships eager-loaded.
- Returns:
Matching
LocalAccountState, orNoneif not found.
- async get_by_id(account_id: str) LocalAccountState[User] | None[source]#
Load an account by UUID string with authorization relationships eager-loaded.
- Returns:
Matching
LocalAccountState, orNoneif not found or invalid UUID.
- async current_epoch(account_id: str) int | None[source]#
Return the current security epoch for the given user account.
- async get_password_state(account_id: str) PasswordCredentialState | None[source]#
Return the password credential snapshot, undeferring
security_sensitivecolumns.
- async compare_and_replace_password(account_id: str, expected_hash: str, password_hash: str, *, event: SecurityEvent) bool[source]#
Atomically compare-and-swap a stored password hash and record its audit event.
- Returns:
Trueif the password hash was updated,Falseotherwise.
- async replace_password_and_bump_epoch(account_id: str, password_hash: str, *, expected_epoch: int, event: SecurityEvent) PasswordChangeOutcome[source]#
Atomically replace a password hash, advance
security_epoch, and record the audit event.- Returns:
PasswordChangeOutcomeindicatingCHANGED,CONFLICT, orNOT_FOUND.
- async list_methods(account_id: str) tuple[LoginMethod, ...][source]#
List an account’s login methods: recorded ones, its password, confirmed MFA factors, and passkeys.
- Returns:
Tuple of viable
LoginMethodentries foraccount_id.
- async register_login_method(account_id: str, method: LoginMethod, *, event: SecurityEvent) None[source]#
Persist a login method record for an account together with its audit event.
- async revoke_login_method(account_id: str, method_id: str, *, require_remaining: bool = True, event: SecurityEvent) RevokeLoginMethodOutcome[source]#
Revoke one login method with its MFA factor or passkey and record the audit event atomically.
The account stays locked for the transaction, so concurrent revocations cannot each remove a different method and leave the account without any.
- Returns:
RevokeLoginMethodOutcomeindicatingREVOKED,NOT_FOUND, orFINAL_METHOD.
- async register(command: RegistrationCommand, password_hash: str, *, invitation_digest: bytes | None, verification: PurposeTokenDelivery | None, now: datetime, event: SecurityEvent) RegistrationOutcome[User][source]#
Provision an account, consume its invitation, store its verification token, and record the audit event.
Everything commits together; any outcome other than
CREATEDleaves the database untouched, as does theValueErrorthatPurposeTokenService.issueraises for a colliding verification token identifier.- Returns:
RegistrationOutcomewith status and created account state when successful.
- async issue(issue: TokenIssue, notification: NotificationCommand, *, event: SecurityEvent) None[source]#
Persist a single-use purpose token digest with its audit event, then dispatch its notification.
A colliding
issue.token_idsurfaces as theValueErrorraised byPurposeTokenService.issue.
- async issue_absent() None[source]#
Perform a constant-interface no-op when issuing for a non-existent account.
- async consume_and_verify(token_id: str, digest: bytes, *, now: datetime, event: SecurityEvent) VerificationOutcome[source]#
Atomically consume a verification token, mark its account verified, and record the audit event.
- Returns:
VerificationOutcomewith consumption status and updated account metadata.
- async consume_and_reset(token_id: str, digest: bytes, new_password_hash: str, *, now: datetime, event: SecurityEvent) PasswordResetOutcome[source]#
Atomically consume a recovery token, replace the password, bump the epoch, and record the audit event.
- Returns:
PasswordResetOutcomewith reset status and next security epoch.
- async create(command: CreateSessionCommand, *, event: SecurityEvent) UserAuthSession[source]#
Persist a new authenticated browser session together with its audit event.
A non-UUID
command.account_idor a collidingsession_idsurfaces as theValueErrorraised byUserSessionService.start.- Returns:
Persisted
UserAuthSessionrecord.
- async get(session_id: str) UserAuthSession | None[source]#
Return an active, unexpired session record or
None.
- async list_for_account(account_id: str) tuple[UserAuthSession, ...][source]#
List active, unexpired sessions for one user account.
- Returns:
Tuple of active
UserAuthSessionrecords foraccount_id.
- async touch(session_id: str, *, now: datetime) UserAuthSession | None[source]#
Advance
last_seen_aton a session that is active both atnowand on the backend’s clock.- Returns:
Updated
UserAuthSession, orNoneif the session is missing, revoked, or expired.
- async revoke_session_for_account(account_id: str, session_id: str, *, event: SecurityEvent) bool[source]#
Revoke one session owned by the given account and record the audit event.
- Returns:
Trueif an active session was revoked,Falseotherwise.
- async revoke_sessions_for_account(account_id: str, *, event: SecurityEvent) int[source]#
Revoke all active sessions owned by the given account and record the audit event.
- Returns:
Number of sessions revoked.
- async revoke_other_sessions(account_id: str, session_id: str, *, event: SecurityEvent) int[source]#
Revoke all active sessions for an account except the specified current session.
- Returns:
Number of sessions revoked.
- async rebind(prior_session_id: str, command: CreateSessionCommand, *, event: SecurityEvent) UserAuthSession | None[source]#
Atomically replace a prior active session with a successor session and record the audit event.
A colliding replacement
session_idsurfaces as theValueErrorraised byUserSessionService.start.- Returns:
Persisted successor
UserAuthSession, orNoneif the prior session is inactive or invalid.
- async resolve_user_auth_session(session_id: str, account_id: str, *, now: datetime) ResolvedUserAuthSession[User] | None[source]#
Resolve an active session and its eager-loaded user in one query.
Database errors propagate to
NativeSessionAuth.authenticatewhich fails closed withVerificationUnavailable.- Returns:
ResolvedUserAuthSessionif session and user are active, otherwiseNone.
- async resolve_session(session_id: str, account_id: str, *, now: datetime | None = None) ResolvedUserAuthSession[User] | InvalidCredentials | VerificationUnavailable[source]#
Fail-closed session lookup converting storage errors to
VerificationUnavailable.- Returns:
Resolved session,
InvalidCredentialsif not found/expired, orVerificationUnavailable.
- class app.domain.accounts.security.SQLAlchemyStepUpService(alchemy_config: SQLAlchemyAsyncConfig)[source]#
Bases:
objectAdapter implementing
StepUpStorefor single-use step-up authentication grants.Initialize the step-up grant store.
- class app.domain.accounts.security.SelfSubjectPredicate(parameter: str = 'user_id')[source]#
Bases:
AuthorizationPredicateAuthorization predicate granting access when a path parameter matches the authenticated principal ID.
Initialize the predicate targeting the named path parameter.
- app.domain.accounts.security.build_api_key_service(store: SQLAlchemyAPIKeyStore, pepper: bytes, *, prefix: str = 'lsk') APIKeyService[source]#
Construct an
APIKeyServicebacked bySQLAlchemyAPIKeyStore.- Returns:
Configured
APIKeyServiceinstance.
- app.domain.accounts.security.build_csrf_config(settings: Settings) CSRFConfig[source]#
Build Litestar’s native CSRF configuration using an HKDF-derived secret.
- Returns:
Configured
CSRFConfiginstance.
- app.domain.accounts.security.build_notification_handler(queue_service: QueueService | None = None) Callable[[NotificationCommand], Awaitable[None]][source]#
Create a
LocalAuthnotification callback enqueueing canonicalemail.send_*queue tasks.- Returns:
Async notification callback accepting a
NotificationCommand.
- app.domain.accounts.security.build_oauth_protector(settings: Settings, *, key_version: str = 'v1', retained_keys: Sequence[OAuthTransactionProtectorKey] = ()) AESGCMOAuthTransactionProtector[source]#
Build an
AESGCMOAuthTransactionProtectorusing an HKDF-derived 32-byte key.- Returns:
Configured
AESGCMOAuthTransactionProtectorinstance.
- app.domain.accounts.security.build_rate_limiter(alchemy_config: SQLAlchemyAsyncConfig, *, policies: Mapping[str, RateLimitPolicy] | None = None, clock: Callable[[], datetime] | None = None) RateLimiter[source]#
Construct a database-backed
StoreRateLimiterover Advanced Alchemy’sSQLAlchemyStore.- Parameters:
alchemy_config – Shared Advanced Alchemy async configuration.
policies – Optional per-operation rate-limit budgets; defaults to
litestar-securitypolicies.clock – Optional UTC clock callable for deterministic testing.
- Returns:
Configured
RateLimiterbacked by theapp_storetable.
- app.domain.accounts.security.build_secret_protector(settings: Settings, *, key_version: str = 'v1', retained_keys: Sequence[SecretProtectorKey] = ()) AESGCMSecretProtector[source]#
Build an
AESGCMSecretProtectorbacked by an HKDF-derived 32-byte key.- Returns:
Configured
AESGCMSecretProtectorinstance.
- app.domain.accounts.security.build_security_config(settings: Settings, alchemy_config: SQLAlchemyAsyncConfig, *, queue_service: QueueService | None = None) SecurityConfig[m.User][source]#
Assemble the complete declarative
SecurityConfig[m.User]for the application.- Returns:
Fully configured
SecurityConfiginstance.
- app.domain.accounts.security.build_session_middleware(settings: Settings) DefineMiddleware[source]#
Build Litestar’s native server-side session middleware backed by
SQLAlchemyStore.- Returns:
Configured server-side session middleware definition.
- app.domain.accounts.security.build_session_store(alchemy_config: SQLAlchemyAsyncConfig) SQLAlchemyStore[SQLAlchemyAsyncConfig][source]#
Build the SQLAlchemy-backed Litestar server-side session store on
m.AppStore.- Returns:
Configured
SQLAlchemyStoreinstance for session storage.
- async app.domain.accounts.security.confirm_authentication(request: Request[Any, Any, Any], user: m.User, current_password: str | None) None[source]#
Admit a sensitive action after a recent sign-in or a re-verified current password.
A denial for a missing password reaches the client as a problem-details body whose top-level
codemember isREAUTHENTICATION_REQUIRED, so clients can prompt for the password and retry.- Parameters:
request – Request whose session evidence and client address are evaluated.
user – Authenticated account performing the action.
current_password – Current password re-confirming a sign-in older than
RECENT_AUTHENTICATION_WINDOW.
- Raises:
PermissionDeniedException – If the sign-in is not recent and the current password is missing or wrong.
TooManyRequestsException – If the account or client has exhausted its password verification attempts.
ServiceUnavailableException – If the password cannot be verified.
- app.domain.accounts.security.deserialize_oauth_tokens(raw: bytes) ProviderTokenSet[source]#
Deserialize canonical JSON bytes back into a
ProviderTokenSet.- Returns:
Reconstructed
ProviderTokenSetinstance.
- app.domain.accounts.security.oauth_account_aad(provider: str, subject: str) bytes[source]#
Build canonical AEAD associated data for persisted
UserOAuthAccounttokens.- Returns:
UTF-8 encoded associated data bytes binding
providerandsubject.
- app.domain.accounts.security.require_application_access(connection: ASGIConnection[Any, Any, Any, Any], route_handler: BaseRouteHandler) None[source]#
Deny signed-in principals that hold neither the default access role nor
superuser.Anonymous connections pass, because each route’s authentication policy decides whether they are admitted. Signing out stays available so an account without access can end its session.
- Raises:
PermissionDeniedException – If the principal is signed in without the default access role. The client sees a problem-details body whose top-level
codemember isAPPLICATION_ACCESS_REQUIRED.
- app.domain.accounts.security.requires_team_role(*roles: str) AuthorizationPredicate[source]#
Require either global
superuserrole or one of the specified roles on pathteam_id.- Returns:
Composite authorization predicate enforcing the team role requirement.