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: object

Resolves verified APIKeyClaims to an eager-loaded Principal[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_id or fail closed on storage errors.

Returns:

Resolved user principal, InvalidCredentials if missing/inactive, or VerificationUnavailable.

class app.domain.accounts.security.AppAuthorizationResolver[source]#

Bases: object

Zero-I/O AuthorizationResolver expanding global and additive hierarchical team roles.

async resolve(principal: Principal[m.User]) → AuthorizationSnapshot | InvalidCredentials | VerificationUnavailable[source]#

Compute an immutable AuthorizationSnapshot purely from eager-loaded User attributes.

Returns:

Computed AuthorizationSnapshot, InvalidCredentials if user is missing, or VerificationUnavailable.

class app.domain.accounts.security.ApplicationAccessRouter(*args: Any, **kwargs: Any)[source]#

Bases: Router

Router 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.

__init__(*args: Any, **kwargs: Any) → None[source]#

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: object

SecurityEventSink writing redacted security telemetry to AuditLog.

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.

__init__(alchemy_config: SQLAlchemyAsyncConfig, *, strict: bool = False) → None[source]#

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.

async emit(event: SecurityEvent) → None[source]#

Persist one sanitized SecurityEvent record into audit_log.

Raises:

SQLAlchemyError – If persistence fails and the sink was initialized with strict=True.

class app.domain.accounts.security.SQLAlchemyAPIKeyStore(alchemy_config: SQLAlchemyAsyncConfig)[source]#

Bases: object

APIKeyStore on Advanced Alchemy services storing only peppered digests, prefixes, and rotation lineage.

Initialize the API key store.

__init__(alchemy_config: SQLAlchemyAsyncConfig) → None[source]#

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 None if not found.

async create(record: APIKeyState) → None[source]#

Persist a new digest-only API key record.

Raises:

ValueError – If key_id already exists, or subject_id is 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_id is 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 None if 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 None if key_id does not exist.

async record(*, key_id: str, used_at: datetime) → None[source]#

Persist one coalesced API-key usage timestamp.

async record_usage(updates: dict[str, datetime]) → None[source]#

Batch-update last_used_at timestamps for verified API keys.

class app.domain.accounts.security.SQLAlchemyMFALoginChallengeService(alchemy_config: SQLAlchemyAsyncConfig)[source]#

Bases: object

Adapter implementing MFALoginChallengeStore with 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.

async put(challenge: MFALoginChallenge) → None[source]#

Persist a single-use MFA login challenge, rejecting a non-UUID account_id with ValueError.

async consume(challenge_digest: bytes, *, account_id: str, security_epoch: int, now: datetime) → MFALoginChallenge | None[source]#

Burn the challenge and return it only if account, epoch, and expiry match.

Returns:

Consumed MFALoginChallenge when all checks pass, otherwise None.

class app.domain.accounts.security.SQLAlchemyMFAService(alchemy_config: SQLAlchemyAsyncConfig)[source]#

Bases: object

Adapter implementing MFAStore for encrypted TOTP factors and peppered recovery code digests.

Initialize the MFA store.

__init__(alchemy_config: SQLAlchemyAsyncConfig) → None[source]#

Initialize the MFA store.

async create_totp_enrollment(enrollment: PendingTOTPEnrollment) → None[source]#

Persist a pending encrypted TOTP enrollment, rejecting a non-UUID account_id with ValueError.

async get_totp_enrollment(enrollment_id: str) → PendingTOTPEnrollment | None[source]#

Load a pending TOTP enrollment by identifier.

Returns:

Matching pending enrollment, or None if 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, or None if 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, or None if 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, or None if 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:

True if the counter advanced, False otherwise.

async replace_recovery_codes(account_id: str, codes: tuple[RecoveryCodeDigest, ...], *, now: datetime) → None[source]#

Replace all recovery code digests for an account in one transaction.

async consume_recovery_code(account_id: str, digest: bytes, *, now: datetime) → bool[source]#

Consume one matching unused recovery code digest.

Returns:

True if a matching unused recovery code was consumed, False otherwise.

class app.domain.accounts.security.SQLAlchemyOAuthAccountStore(alchemy_config: SQLAlchemyAsyncConfig, protector: OAuthTransactionProtector)[source]#

Bases: object

OAuthAccountStore adapter 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.

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 AccountLinkError raised by OAuthAccountService.link.

Returns:

Persisted LinkedProviderAccount record.

Raises:

OAuthAccountError – If account_id is 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 AccountLinkError raised by OAuthServices.login.

Returns:

OAuthLoginOutcome containing 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, or None if 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 LinkedProviderAccount record.

Raises:

AccountLinkError – If identifiers are invalid or no matching linked account exists.

Atomically unlink an owned OAuth identity while protecting the user’s final login method.

Returns:

UnlinkOutcome describing 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:

StoredProviderTokens with version metadata, or None if 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:

True if tokens were replaced, False on missing row or version mismatch.

async discard_tokens(provider_account_id: str, *, expected_version: int | None = None) → bool[source]#

Remove retained encrypted tokens for a linked OAuth account.

Returns:

True if tokens were cleared, False on missing row or version mismatch.

async stage_revocation_retry(failure: OAuthRevocationFailure, tokens: ProviderTokenSet, *, expected_version: int) → bool[source]#

Persist encrypted tokens for retry after an upstream revocation error.

Returns:

True if staged tokens were persisted, False on missing row or version mismatch.

class app.domain.accounts.security.SQLAlchemyOAuthTransactionStore(alchemy_config: SQLAlchemyAsyncConfig, protector: OAuthTransactionProtector)[source]#

Bases: object

OAuthTransactionStore adapter 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 OAuthTransaction with decrypted secrets, or None if unmatched or expired.

class app.domain.accounts.security.SQLAlchemyPasskeyStore(alchemy_config: SQLAlchemyAsyncConfig)[source]#

Bases: object

Adapter implementing both PasskeyStore and WebAuthnChallengeStore on 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:

True if stored, False if account_id is 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 None if 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, or CONFLICT).

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 None if not found.

async put(challenge: WebAuthnChallenge) → None[source]#

Persist a single-use WebAuthn ceremony challenge.

async consume(challenge_digest: bytes, *, binding_digest: bytes, purpose: str, now: datetime) → WebAuthnChallenge | None[source]#

Atomically burn the WebAuthn challenge and return it only if binding, purpose, and expiry match.

Returns:

Consumed WebAuthnChallenge when all checks pass, otherwise None.

class app.domain.accounts.security.SQLAlchemySecurityBackend(alchemy_config: SQLAlchemyAsyncConfig, *, clock: Callable[[], datetime] | None = None, notification_handler: Callable[[NotificationCommand], Awaitable[None]] | None = None)[source]#

Bases: object

Adapter implementing the LocalAuth account, 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, or None if 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, or None if 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_sensitive columns.

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:

True if the password hash was updated, False otherwise.

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:

PasswordChangeOutcome indicating CHANGED, CONFLICT, or NOT_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 LoginMethod entries for account_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:

RevokeLoginMethodOutcome indicating REVOKED, NOT_FOUND, or FINAL_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 CREATED leaves the database untouched, as does the ValueError that PurposeTokenService.issue raises for a colliding verification token identifier.

Returns:

RegistrationOutcome with 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_id surfaces as the ValueError raised by PurposeTokenService.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:

VerificationOutcome with 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:

PasswordResetOutcome with 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_id or a colliding session_id surfaces as the ValueError raised by UserSessionService.start.

Returns:

Persisted UserAuthSession record.

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 UserAuthSession records for account_id.

async touch(session_id: str, *, now: datetime) → UserAuthSession | None[source]#

Advance last_seen_at on a session that is active both at now and on the backend’s clock.

Returns:

Updated UserAuthSession, or None if 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:

True if an active session was revoked, False otherwise.

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_id surfaces as the ValueError raised by UserSessionService.start.

Returns:

Persisted successor UserAuthSession, or None if 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.authenticate which fails closed with VerificationUnavailable.

Returns:

ResolvedUserAuthSession if session and user are active, otherwise None.

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, InvalidCredentials if not found/expired, or VerificationUnavailable.

class app.domain.accounts.security.SQLAlchemyStepUpService(alchemy_config: SQLAlchemyAsyncConfig)[source]#

Bases: object

Adapter implementing StepUpStore for single-use step-up authentication grants.

Initialize the step-up grant store.

__init__(alchemy_config: SQLAlchemyAsyncConfig) → None[source]#

Initialize the step-up grant store.

async put(record: StepUpGrantState) → None[source]#

Persist a short-lived step-up grant.

async consume(grant_digest: bytes, *, principal_id: str, security_epoch: int, purpose: str, transport_digest: bytes, now: datetime) → StepUpGrantState | None[source]#

Spend a step-up grant matching every binding and expiry check.

Returns:

Consumed StepUpGrantState when valid, otherwise None.

class app.domain.accounts.security.SelfSubjectPredicate(parameter: str = 'user_id')[source]#

Bases: AuthorizationPredicate

Authorization predicate granting access when a path parameter matches the authenticated principal ID.

Initialize the predicate targeting the named path parameter.

__init__(parameter: str = 'user_id') → None[source]#

Initialize the predicate targeting the named path parameter.

decide(connection: ASGIConnection[Any, Any, Any, Any]) → AuthorizationDecision[source]#

Evaluate whether the authenticated principal matches the path parameter value.

Returns:

Grant decision when IDs match, otherwise an unauthenticated or forbidden denial.

app.domain.accounts.security.build_api_key_service(store: SQLAlchemyAPIKeyStore, pepper: bytes, *, prefix: str = 'lsk') → APIKeyService[source]#

Construct an APIKeyService backed by SQLAlchemyAPIKeyStore.

Returns:

Configured APIKeyService instance.

app.domain.accounts.security.build_csrf_config(settings: Settings) → CSRFConfig[source]#

Build Litestar’s native CSRF configuration using an HKDF-derived secret.

Returns:

Configured CSRFConfig instance.

app.domain.accounts.security.build_notification_handler(queue_service: QueueService | None = None) → Callable[[NotificationCommand], Awaitable[None]][source]#

Create a LocalAuth notification callback enqueueing canonical email.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 AESGCMOAuthTransactionProtector using an HKDF-derived 32-byte key.

Returns:

Configured AESGCMOAuthTransactionProtector instance.

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 StoreRateLimiter over Advanced Alchemy’s SQLAlchemyStore.

Parameters:
  • alchemy_config – Shared Advanced Alchemy async configuration.

  • policies – Optional per-operation rate-limit budgets; defaults to litestar-security policies.

  • clock – Optional UTC clock callable for deterministic testing.

Returns:

Configured RateLimiter backed by the app_store table.

app.domain.accounts.security.build_secret_protector(settings: Settings, *, key_version: str = 'v1', retained_keys: Sequence[SecretProtectorKey] = ()) → AESGCMSecretProtector[source]#

Build an AESGCMSecretProtector backed by an HKDF-derived 32-byte key.

Returns:

Configured AESGCMSecretProtector instance.

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 SecurityConfig instance.

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 SQLAlchemyStore instance 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 code member is REAUTHENTICATION_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 ProviderTokenSet instance.

app.domain.accounts.security.oauth_account_aad(provider: str, subject: str) → bytes[source]#

Build canonical AEAD associated data for persisted UserOAuthAccount tokens.

Returns:

UTF-8 encoded associated data bytes binding provider and subject.

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 code member is APPLICATION_ACCESS_REQUIRED.

app.domain.accounts.security.requires_team_role(*roles: str) → AuthorizationPredicate[source]#

Require either global superuser role or one of the specified roles on path team_id.

Returns:

Composite authorization predicate enforcing the team role requirement.

app.domain.accounts.security.sanitize_event_details(payload: Any) → Any[source]#

Recursively redact sensitive keys from structured audit metadata.

Returns:

Copy of payload with sensitive values and byte sequences redacted.

app.domain.accounts.security.serialize_oauth_tokens(tokens: ProviderTokenSet) → bytes[source]#

Serialize a ProviderTokenSet into canonical JSON bytes for AEAD encryption.

Returns:

UTF-8 encoded JSON bytes representing the token set.