Skip to main content

Module auth

Module auth 

Source
Expand description

Authentication & authorization.

Three pieces:

  • users.rs — user records, password hashing, login
  • sessions.rs — DB-backed sessions with expiry cleanup
  • permissions.rs — granular permissions + groups

A user belongs to zero or more groups. Permissions come from two sources: (a) direct assignments on the user, (b) inherited from the user’s groups. The permission string is <app>.<action>_<model> — e.g. posts.change_post.

Modules§

emergency
Emergency-recovery primitives — the framework-side surface called by the rustio-admin user <op> CLI commands.
guards
Authority guards — server-side enforcement of the rank model.

Structs§

DefaultPasswordPolicy
Length-only password policy. Default min_len is 10 — the secure-by-default baseline R1 ships with: long enough to defeat trivial guessing under Argon2id + per-IP rate-limiting (NIST SP 800-63B’s recommended length floor is 8, with longer being preferable), short enough not to drive operators toward sticky- note workarounds. Production / regulated deployments are encouraged to override to 12+ via crate::admin::Admin::password_policy; high-sensitivity deployments may want 16+ paired with an organisational complexity rule or breach blocklist.
DefaultRecoveryPolicy
Length-only / rate-limit-only baseline policy. Public fields plus chainable with_* setters so projects that want to tweak one knob don’t need to author a full trait impl.
Identity
The identity attached to a request by the auth middleware. Kept cheap to clone because we pass it into handler bodies.
InvalidationOutcome
Outcome of an invalidate_sessions call. Used by the audit pipeline to write one row per affected session and by the caller to decide whether to clear the user’s cookie.
LoginThrottle
Auto-throttle parameters for the login flow (DESIGN_R2_ORGANISATIONAL.md §3.3 + §12 locked decisions).
Permission
Session
One session row, reconstructed from rustio_sessions. Returned by list_active_for_user for the active-sessions UI.
StoredUser
Superuser
Marker type used by the admin’s authorize macro for fast-paths on admins.
UserProfile
Read-only view of a user, used by the built-in admin profile page. Excludes password_hash deliberately. Construct via load_user_profile.

Enums§

MfaPolicy
Framework-wide MFA enforcement policy.
PasswordPolicyError
Reasons a candidate password fails policy validation.
PermissionError
Role
SessionInvalidationReason
Why a session is being invalidated. Drives both the audit action_type and decisions about whether to clear remembered MFA or mint a replacement session.
SessionTarget
Which sessions an invalidate_sessions call targets.
SessionTrust
Trust level a session has acquired. The login flow mints SessionTrust::Authenticated; the future re-auth wall promotes to SessionTrust::Elevated; a successful TOTP step on this session lifts to SessionTrust::MfaVerified.

Constants§

DEFAULT_GROUP_NAMES
The three structural permission groups every fresh database is seeded with (PR 2.2 / DESIGN_PERMISSIONS.md).
SESSION_COOKIE
The cookie name we look for and set. Constant so middleware and handlers stay in sync.

Traits§

PasswordPolicy
Validates a candidate password against project-defined rules.
RecoveryPolicy
Tunables for the R1 recovery flow: token TTL, rate-limit shape, strict-mailer boot guard, and public-site-URL derivation.

Functions§

add_user_to_group
check_permission
Ask “does this identity have permission X?”.
create_group
Idempotent. A second call with the same name returns the existing group’s id; the stored description is preserved (first-write-wins). Mirrors the permission_id upsert idiom in this module.
create_session
create_user
current_session_id
Resolve the cookie token to its session_id (active sessions only). Used by the active-sessions UI to mark which row is the current device, and by UserExceptCurrent callers.
delete_session
Hard-delete a session row by cookie token. Retained as a pre-0.4.0 compatibility shim — internal callers are migrating to invalidate_sessions, which soft-revokes via revoked_at and keeps the row available for the audit trail. New code MUST NOT call this directly; only the expired-row sweeper and the read-path stale-cleanup branch are allowed callers, both of which are inside this module.
find_user_by_email
grant_model_to_default_groups
Per-model permission grants for the seeded default groups (PR 2.2 / DESIGN_PERMISSIONS.md). Called by crate::admin::Admin::seed_permissions after the four CRUD permissions are registered for <app>.<singular>. Each grant is idempotent (grant_to_group uses ON CONFLICT DO NOTHING); missing groups (because seed_default_groups was skipped by the user-defined-groups guard) cause silent no-ops, not errors.
grant_to_group
grant_to_user
hash_password
identity_from_session
init_permission_tables
init_session_tables
init_tables
Initialise every auth-related table. Safe to call on every boot.
init_user_tables
invalidate_sessions
Centralised session invalidation — the single legitimate writer of rustio_sessions.revoked_at.
list_active_for_user
List a user’s currently-active sessions, ordered by last_seen descending so the active-sessions UI surfaces the most recently used row first. Excludes revoked + expired rows.
load_user_profile
Load a user by id for display purposes. Returns Ok(None) for a missing id (callers map to 404). Returns Err only on a real DB failure or a corrupted role string. Never reads password_hash.
login
Verify credentials and create a session. Returns the session token to set in the cookie. A deliberately vague error on failure — we don’t want to leak whether the email was valid.
logout_session
Convenience wrapper for the existing logout flow. Routes through invalidate_sessions with SessionTarget::Single and SessionInvalidationReason::Logout.
migrate_user_schema
Idempotent schema upgrade for the 5-tier role hierarchy + demo + profile columns. Safe to call repeatedly; safe on a fresh DB and on a legacy 'admin'-roled DB.
permissions_for_user
All permission names belonging to the given user — direct + via groups — unioned into one set. Cached for 60s.
protected_roles
Roles the framework refuses to lose its last active member of.
purge_expired_sessions
Delete all expired sessions. Intended to be called periodically from a background task (see background::spawn_session_sweeper).
register_model_permissions
For an admin model named posts, register the canonical four permissions: add_post, change_post, delete_post, view_post. Idempotent.
remove_user_from_group
seed_default_groups
Seed the three structural permission groups on a fresh database.
session_token_from_cookie
set_password
Re-hash and write a new password for user_id. Stamps both password_changed_at and updated_at to the same NOW()password_changed_at is the doctrine-7 surface (“Password last changed: 2 days ago”) that the active-sessions UI reads; the existing updated_at continues to track row-level edits.
update_user_role
verdict_for_orphan_role
Pure verdict for the orphan check, factored out so it can be unit-tested without a Db. The async wrapper would_orphan_role supplies active_count and target_is_protected from SQL.
verify_password
would_orphan_developersDeprecated
Legacy alias preserved so external callers keep compiling. Prefer would_orphan_protected which generalises across every role in super::role::protected_roles.
would_orphan_protected
Walk every entry in super::role::protected_roles and return the first protected role whose membership would be orphaned by the proposed change. None means the change is safe.
would_orphan_role
Would the proposed change leave the system with zero active members of protected_role?

Type Aliases§

SharedPasswordPolicy
Type-erased shared password-policy reference, mirroring crate::email::SharedMailer. The framework’s Admin holds one of these; defaults to Arc::new(DefaultPasswordPolicy::new()) until a project overrides via Admin::password_policy(Arc::new(...)).
SharedRecoveryPolicy
Type-erased shared recovery-policy reference, mirroring SharedPasswordPolicy / crate::email::SharedMailer.