reinhardt-auth
Authentication and authorization system for Reinhardt framework.
Overview
Comprehensive authentication and authorization system inspired by Django and Django REST Framework. Provides JWT tokens, permission classes, user models, and password hashing with Argon2.
Installation
Add reinhardt to your Cargo.toml:
[]
= { = "0.1.0-alpha.1", = ["auth"] }
# Or use a preset:
# reinhardt = { version = "0.1.0-alpha.1", features = ["standard"] } # Recommended
# reinhardt = { version = "0.1.0-alpha.1", features = ["full"] } # All features
Then import authentication features:
use ;
use ;
use ;
Note: Authentication features are included in the standard and full feature presets.
Implemented ✓
Core Authentication
JWT (JSON Web Token) Authentication
- Claims Management:
Claimsstruct with user identification, expiration, and issue times - Token Generation: Automatic 24-hour expiration by default
- Token Verification: Built-in expiration checking and signature validation
- Encode/Decode: Full JWT token encoding and decoding support
use ;
use Duration;
let jwt_auth = new;
let token = jwt_auth.generate_token.unwrap;
let claims = jwt_auth.verify_token.unwrap;
HTTP Basic Authentication
- BasicAuthentication: HTTP Basic auth backend with user management
- Base64 Encoding/Decoding: Standard HTTP Basic auth header parsing
- User Registration: Add users with username/password pairs
- Request Authentication: Extract and verify credentials from Authorization headers
use ;
let mut auth = new;
auth.add_user;
// Request with Basic auth header will be authenticated
let result = auth.authenticate.unwrap;
User Management
User Trait
- Core User Interface: Unified trait for authenticated and anonymous users
- User Identification:
id(),username(),get_username()methods - Authentication Status:
is_authenticated(),is_active(),is_admin()checks - Django Compatibility: Methods compatible with Django's user interface
User Implementations
- SimpleUser: Fully-featured user with UUID, username, email, active/admin flags
- AnonymousUser: Zero-sized type representing unauthenticated visitors
- Serialization Support: Serde integration for SimpleUser
use ;
use Uuid;
let user = SimpleUser ;
assert!;
assert!;
Django-Style User Models
BaseUser Trait (AbstractBaseUser equivalent)
- Minimal Authentication Interface: Minimal set of fields for user authentication
- Automatic Password Hashing: Argon2id hashing by default, fully customizable
- Associated Type Default:
type Hasher: PasswordHasher + Default = Argon2Hasher - Password Management:
set_password(): Automatically hashes with configured hashercheck_password(): Verifies password against hashset_unusable_password(): Marks password as unusable (for OAuth-only accounts)has_usable_password(): Checks if user can log in with password
- Session Authentication:
get_session_auth_hash()for session invalidation on password change - Username Normalization: NFKC Unicode normalization to prevent homograph attacks
- Django Compatibility: Method names and behavior match Django's AbstractBaseUser
use BaseUser;
use Uuid;
use Utc;
use ;
let mut user = MyUser ;
// Password is automatically hashed with Argon2id
user.set_password.unwrap;
assert!;
FullUser Trait (AbstractUser equivalent)
- Complete User Model: Extends BaseUser with additional fields
- User Profile Fields:
username(): Unique username for loginemail(): Email addressfirst_name()/last_name(): User's nameis_staff(): Can access admin interfaceis_superuser(): Has all permissionsdate_joined(): Account creation timestamp
- Helper Methods:
get_full_name(): Combines first and last nameget_short_name(): Returns first name only
- Django Compatibility: Matches Django's AbstractUser interface
use ;
use Uuid;
use Utc;
let mut user = DefaultUser ;
assert_eq!;
assert_eq!;
PermissionsMixin Trait
- Authorization Interface: Permission and group management
- Permission Checking:
has_perm(perm): Check if user has specific permissionhas_module_perms(app_label): Check if user has any permission for appget_all_permissions(): Get all user and group permissions
- Superuser Bypass: Superusers automatically pass all permission checks
- Group Support: Users can belong to multiple groups
- Django Compatibility: Permission format
"app_label.permission_name"
use ;
use Uuid;
use Utc;
let user = DefaultUser ;
assert!;
assert!;
DefaultUser Struct
- Ready-to-Use Implementation: Combines BaseUser, FullUser, and PermissionsMixin
- Database Model:
#[derive(Model)]for ORM integration - Table Name:
auth_user(Django-compatible) - All Fields Included: Username, email, names, passwords, permissions, groups, flags, timestamps
- Zero Configuration: Works out of the box with automatic Argon2id hashing
use ;
use HashMap;
# block_on
BaseUserManager Trait
- User Creation Interface:
create_user()andcreate_superuser()methods - Async Support: Full async/await integration
- Extra Fields: Accept arbitrary extra data via HashMap
- Email Normalization:
normalize_email()static method - Django Compatibility: Matches Django's UserManager interface
DefaultUserManager
- In-Memory Implementation: Built-in manager for DefaultUser
- Thread-Safe: Uses
Arc<RwLock<HashMap>>for concurrent access - User Lookup:
get_by_id()andget_by_username()methods - Demonstration Purpose: For testing and prototyping (use ORM-based manager in production)
Password Security
Password Hashing
- PasswordHasher Trait: Composable password hashing interface
- Argon2Hasher: Production-ready Argon2id implementation (recommended)
- Hash Generation: Secure salt generation using OS random number generator
- Password Verification: Constant-time comparison for security
use ;
let hasher = new;
let hash = hasher.hash.unwrap;
assert!;
Authentication Backends
AuthBackend Trait
- Composable Architecture: Support for multiple authentication strategies
- Async Support: Full async/await integration with
async_trait - User Authentication:
authenticate(username, password)method - User Lookup:
get_user(user_id)for session restoration
Composite Authentication
- CompositeAuthBackend: Chain multiple authentication backends
- Fallback Support: Try backends in order until one succeeds
- Flexible Configuration: Add backends dynamically at runtime
use CompositeAuthBackend;
let mut composite = new;
composite.add_backend;
composite.add_backend;
// Will try database first, then LDAP
let user = composite.authenticate.await;
Permission System
Permission Trait
- Permission Interface: Async
has_permission()method with context - PermissionContext: Request-aware context with authentication flags
- Composable Permissions: Build complex permission logic
Built-in Permission Classes
- AllowAny: Allow all requests without authentication
- IsAuthenticated: Require authenticated user
- IsAdminUser: Require authenticated admin user
- IsActiveUser: Require authenticated and active user
- IsAuthenticatedOrReadOnly: Authenticated for write, read-only for anonymous users
use ;
let permission = IsAuthenticated;
let context = PermissionContext ;
assert!;
Error Handling
AuthenticationError
- InvalidCredentials: Wrong username or password
- UserNotFound: User does not exist
- SessionExpired: Session has expired
- InvalidToken: Token is malformed or invalid
- Unknown: Generic error with custom message
AuthenticationBackend Trait
- Unified Error Handling: All backends use
AuthenticationError - Standard Error Trait: Implements
std::error::Error - Display Implementation: User-friendly error messages
Session-Based Authentication
SessionAuthentication
- Session Management:
Sessionstruct with HashMap-based data storage - SessionStore Trait: Async interface for session persistence
load(): Retrieve session by IDsave(): Persist session datadelete(): Remove session
- InMemorySessionStore: Built-in in-memory session storage
- SessionId: Type-safe session identifier wrapper
- Cookie Integration: Secure session cookie handling
use ;
use InMemorySessionBackend;
let session_backend = new;
let auth = new;
// Authenticate user from request (checks session cookie)
let user = auth.authenticate.await?;
// Get user by ID
if let Some = auth.get_user.await?
Multi-Factor Authentication (MFA)
TOTP-Based MFA
- MFAAuthentication: Time-based one-time password (TOTP) authentication
- Secret Management: Secure per-user secret storage
- QR Code Generation: Generate TOTP URLs for authenticator apps (Google Authenticator, Authy)
- Code Verification: Verify TOTP codes with configurable time window
- Registration Flow: User enrollment with secret generation
- Time Window: Configurable tolerance for time skew (default: 1 time step)
use MFAAuthentication;
let mfa = new;
// Register user for MFA
let totp_url = mfa.register_user.await?;
// User scans QR code generated from totp_url
// Verify code during login
let code = "123456"; // from user's authenticator app
assert!;
OAuth2 Support
OAuth2 Authentication
- OAuth2Authentication: Full OAuth2 provider implementation
- Grant Types: Authorization Code, Client Credentials, Refresh Token, Implicit
- Application Management:
OAuth2Applicationwith client credentials - Token Management:
OAuth2Tokenwith access and refresh tokens - Authorization Flow:
- Authorization code generation and validation
- Token exchange (code → access token)
- Token refresh with refresh tokens
- OAuth2TokenStore Trait: Persistent token storage interface
- InMemoryTokenStore: Built-in in-memory token storage
use ;
let store = new;
let oauth2 = new;
// Register OAuth2 application
oauth2.register_application.await?;
// Authorization code flow
let code = oauth2.generate_authorization_code.await?;
let token = oauth2.exchange_code.await?;
// Use access token
let claims = oauth2.verify_token.await?;
Token Blacklist & Rotation
Token Blacklist
- TokenBlacklist Trait: Interface for token invalidation
- BlacklistReason: Categorized revocation reasons
Logout: User-initiated logoutCompromised: Security incidentManualRevoke: Admin revocationRotated: Automatic token rotation
- InMemoryBlacklist: Built-in in-memory blacklist storage
- Cleanup: Automatic removal of expired blacklist entries
- Statistics: Usage tracking and monitoring
Token Rotation
- TokenRotationManager: Automatic refresh token rotation
- RefreshTokenStore Trait: Persistent refresh token storage
- Rotation Flow: Invalidate old token when issuing new one
- Security: Prevents refresh token reuse attacks
- InMemoryRefreshStore: Built-in in-memory refresh token storage
use ;
// Token blacklist
let blacklist = new;
use ;
let expires_at = now + hours;
blacklist.blacklist.await?;
assert!;
// Token rotation
let refresh_store = new;
let rotation_manager = new;
let new_token = rotation_manager.rotate_token.await?;
Remote User Authentication
Header-Based Authentication
- RemoteUserAuthentication: Authenticate via trusted HTTP headers
- Reverse Proxy Integration: Support for authentication proxies (nginx, Apache, etc.)
- Header Configuration: Configurable header name (default:
REMOTE_USER) - Header Validation: Verify header presence and format
- Automatic Logout: Optional force logout when header is missing
- SSO Support: Single sign-on integration
use RemoteUserAuthentication;
// Standard configuration
let auth = new;
// With force logout
let auth = new.force_logout_if_no_header;
// Authenticate from request
let user = auth.authenticate.await?;
Usage Examples
Complete Authentication Flow
use ;
// 1. Set up JWT authentication
let jwt_auth = new;
// 2. Set up Basic authentication with a user
let mut basic_auth = new;
basic_auth.add_user;
// 3. Authenticate user and generate JWT
let user = basic_auth.authenticate.unwrap.unwrap;
let token = jwt_auth.generate_token.unwrap;
// 4. Verify token on subsequent requests
let claims = jwt_auth.verify_token.unwrap;
// 5. Check permissions
let permission = IsAuthenticated;
let context = PermissionContext ;
if permission.has_permission.await
Custom Authentication Backend
use ;
use async_trait;
use HashMap;
sessions
Features
Implemented ✓
Core Session Backend
- SessionBackend Trait - Async trait defining session storage operations (load, save, delete, exists)
- SessionError - Error types for session operations (cache errors, serialization errors)
- Generic Session Storage - Type-safe session data storage with
serdesupport
Cache-Based Backends
- InMemorySessionBackend - In-memory session storage using
InMemoryCache- Fast, volatile storage (sessions lost on restart)
- TTL (Time-To-Live) support for automatic expiration
- Suitable for development and single-instance deployments
- CacheSessionBackend - Generic cache-based session backend
- Works with any
Cachetrait implementation - Supports external cache systems (Redis, Memcached, etc.)
- Configurable TTL for session expiration
- Horizontal scalability for distributed systems
- Works with any
Dependency Injection Support
- Integration with
reinhardt-difor dependency injection - Session backend registration and resolution
High-Level Session API
- Session struct - Django-style session object with dictionary-like interface
- Type-safe with generic backend parameter
B: SessionBackend - Dictionary-like methods:
get(),set(),delete(),contains_key() - Session iteration methods:
keys(),values(),items() - Manual session clearing:
clear() - Manual modification tracking:
mark_modified(),mark_unmodified() - Session modification tracking:
is_modified(),is_accessed() - Session key management:
get_or_create_key(),generate_key() - Session lifecycle:
flush()(clear and new key),cycle_key()(keep data, new key) - Automatic persistence:
save()method with TTL support (default: 3600 seconds) - Comprehensive doctests and unit tests (36 total tests)
- Type-safe with generic backend parameter
Storage Backends
- DatabaseSessionBackend (feature:
database) - Persistent session storage in database- Session model with expiration timestamps
- Automatic session cleanup with
cleanup_expired() - SQLite, PostgreSQL, and MySQL support via sqlx
- Table creation with
create_table() - Indexed expiration dates for efficient cleanup
- 9 comprehensive tests
- FileSessionBackend (feature:
file) - File-based session storage- Session files stored in configurable directory (default:
/tmp/reinhardt_sessions) - File locking using
fs2for concurrent access safety - JSON serialization with TTL support
- Automatic expired session cleanup on access
- 11 comprehensive tests
- Session files stored in configurable directory (default:
- CookieSessionBackend (feature:
cookie) - Encrypted session data in cookies- AES-256-GCM encryption for session data
- HMAC-SHA256 signing for tamper detection
- Automatic size limitation checking (4KB max)
- Secure client-side storage
- 11 comprehensive tests
HTTP Middleware
- SessionMiddleware (feature:
middleware) - HTTP middleware for session management- Automatic session loading from cookies
- Automatic session saving on response
- Cookie configuration: name, path, domain
- Security settings: secure, httponly, samesite
- TTL and max-age support
- HttpSessionConfig - Comprehensive middleware configuration
- SameSite enum - Cookie SameSite attribute (Strict, Lax, None)
Session Management Features
- Session expiration and cleanup - Implemented via
cleanup_expired()in DatabaseSessionBackend - Session key rotation - Implemented via
cycle_key()andflush()in Session API - Cross-site request forgery (CSRF) protection integration - CSRF module available
- Session serialization formats - JSON via serde_json, MessagePack, CBOR, Bincode
- Session storage migration tools - Migration module available
Session Serialization Formats
- JSON (always available) - Human-readable, widely compatible via
serde_json - MessagePack (feature:
messagepack) - Compact binary format, cross-platform viarmp-serde - CBOR (feature:
cbor) - RFC 7049 compliant binary format viaciborium - Bincode (feature:
bincode) - Fastest for Rust-to-Rust communication
Session Compression
- CompressedSessionBackend (feature:
compression) - Automatic compression wrapper- Threshold-based compression (default: 512 bytes, configurable)
- Only compresses data exceeding threshold to avoid overhead
- Zstd compression (feature:
compression-zstd) - Best balance of speed and ratio - Gzip compression (feature:
compression-gzip) - Wide compatibility - Brotli compression (feature:
compression-brotli) - Best compression ratio
Session Replication
- ReplicatedSessionBackend (feature:
replication) - High availability with multi-backend replication- AsyncReplication - Eventual consistency, highest throughput
- SyncReplication - Strong consistency, both backends updated in parallel
- AcknowledgedReplication - Primary first, then secondary with acknowledgment
- Configurable retry attempts and delays for failure handling
Session Analytics
- InstrumentedSessionBackend - Automatic session event tracking wrapper
- LoggerAnalytics - Tracing-based logging (always available)
- PrometheusAnalytics (feature:
analytics-prometheus) - Prometheus metrics exportsession_created_total- Total sessions createdsession_accessed_total- Total session accessessession_access_latency_seconds- Access latency histogramsession_size_bytes- Session data size histogramsession_deleted_total- Deletions by reason (explicit, expired, flushed)session_expired_total- Total expired sessions
Multi-Tenant Session Isolation
- TenantSessionBackend (feature:
tenant) - Tenant-specific session namespacing- Prefix-based keying:
tenant:{tenant_id}:session:{session_id} - Configurable key prefix pattern
- Maximum sessions per tenant limit
- Strict isolation mode for security
- TenantSessionOperations trait:
list_sessions(),count_sessions(),delete_all_sessions()
- Prefix-based keying:
License
Licensed under the BSD 3-Clause License.