auth_framework/lib.rs
1#![deny(clippy::unwrap_used)]
2
3/*!
4# Auth Framework
5
6A comprehensive authentication and authorization framework for Rust applications.
7
8This crate provides a unified interface for various authentication methods,
9token management, permission checking, and secure credential handling with
10a focus on distributed systems.
11
12## API Orientation
13
14- Use [`AuthFramework`] as the default entry point for most applications.
15- Use [`ModularAuthFramework`] only when you explicitly want manager-level
16 composition and lifecycle control.
17- Use [`prelude`] when you want ergonomic imports for application code.
18- Use [`AppConfigBuilder`] for simple application-owned configuration values.
19- Use [`LayeredConfigBuilder`] and [`ConfigManager`] when you need layered
20 configuration from files and environment variables.
21
22## Features
23
24- Multiple authentication methods (OAuth, API keys, JWT, etc.)
25- Token issuance, validation, and refresh with RSA and HMAC signing
26- RSA key format support: PKCS#1 and PKCS#8 formats auto-detected
27- Role-based access control integration
28- Permission checking and enforcement
29- Secure credential storage
30- Authentication middleware for web frameworks
31- Distributed authentication with cross-node validation
32- Single sign-on capabilities
33- Multi-factor authentication support
34- Audit logging of authentication events
35- Rate limiting and brute force protection
36- Session management
37- Password hashing and validation
38- Customizable authentication flows
39
40## Quick Start
41
42```rust,no_run
43use auth_framework::prelude::*;
44
45#[tokio::main]
46async fn main() -> Result<(), Box<dyn std::error::Error>> {
47 // Build configuration. JWT secret must be at least 32 characters.
48 let config = AuthConfig::new()
49 .token_lifetime(std::time::Duration::from_secs(3600))
50 .secret(std::env::var("JWT_SECRET")
51 .unwrap_or_else(|_| "replace-with-a-32-char-random-secret!!".to_string()));
52
53 let mut auth = AuthFramework::new(config);
54 auth.initialize().await?;
55
56 // Register a user.
57 let user_id = auth.users().register("alice", "alice@example.com", "s3cr3t!").await?;
58
59 // Issue a token via the grouped token accessor.
60 let token = auth.tokens().create(&user_id, &["read"], "jwt", None).await?;
61
62 // Validate and authorize.
63 if auth.tokens().validate(&token).await? {
64 if auth.authorization().check(&token, "read", "documents").await? {
65 println!("Alice may read documents.");
66 }
67 }
68
69 Ok(())
70}
71```
72
73See [`prelude`] for the full set of re-exported types, and the accessor groups
74[`AuthFramework::users`], [`AuthFramework::sessions`], [`AuthFramework::tokens`],
75[`AuthFramework::authorization`], [`AuthFramework::mfa`], [`AuthFramework::monitoring`],
76[`AuthFramework::audit`], and [`AuthFramework::admin`] for organized entry points
77into each capability area.
78
79## Security Considerations
80
81- Always use HTTPS in production
82- Use strong, unique secrets for token signing
83- Enable rate limiting to prevent brute force attacks
84- Regularly rotate secrets and keys
85- Monitor authentication events for suspicious activity
86- Follow the principle of least privilege for permissions
87
88See the [Security Policy](https://github.com/ciresnave/auth-framework/blob/main/SECURITY.md)
89for comprehensive security guidelines.
90*/
91
92// REST API Server
93#[cfg(feature = "api-server")]
94pub mod api;
95
96// Admin interface (conditional on admin-binary feature)
97#[cfg(feature = "admin-binary")]
98pub mod admin;
99
100// ────────────────────────────────────────────────────────────────────────────
101// Core framework modules
102// ────────────────────────────────────────────────────────────────────────────
103
104pub(crate) mod account_state;
105/// Primary authentication framework — start here.
106///
107/// Contains [`AuthFramework`], the main entry point for most applications.
108/// Access grouped operations via [`AuthFramework::users`], [`AuthFramework::tokens`],
109/// [`AuthFramework::sessions`], etc.
110pub mod auth;
111
112/// Advanced component-oriented framework.
113///
114/// Use [`ModularAuthFramework`](auth_modular::AuthFramework) only when you need
115/// direct access to individual manager instances (user, session, MFA) for custom
116/// composition. Most applications should use [`auth::AuthFramework`] instead.
117pub mod auth_modular;
118
119/// Grouped operation facades over [`AuthFramework`].
120///
121/// Light reference wrappers (e.g. [`UserOperations`], [`TokenOperations`]) returned
122/// by the accessor methods on `AuthFramework`. Not usually imported directly —
123/// use `auth.users()`, `auth.tokens()`, etc.
124pub mod auth_operations;
125
126/// Supporting authentication data types.
127///
128/// Credentials, metadata, and MFA primitives used as inputs to the core
129/// framework. Import specific types rather than the module wildcard.
130pub mod authentication;
131
132/// Domain-specific newtypes (`Roles`, `Scopes`, `Permissions`, etc.).
133pub mod types;
134
135/// Error types and the crate-wide [`Result`](errors::Result) alias.
136pub mod errors;
137
138/// Authentication method implementations (JWT, OAuth2, API keys, passwords, SAML).
139pub mod methods;
140
141/// Permission and role definitions for access control.
142pub mod permissions;
143
144/// Token creation, validation, rotation, and JWKS support.
145pub mod tokens;
146
147// ────────────────────────────────────────────────────────────────────────────
148// Configuration
149// ────────────────────────────────────────────────────────────────────────────
150
151/// Configuration types and management.
152///
153/// - [`AuthConfig`](config::AuthConfig) — main config struct (use [`AuthConfig::new()`]
154/// for fluent setters or [`AuthConfig::builder()`] for the full builder).
155/// - [`ConfigManager`](config::ConfigManager) — layered config from files + env.
156/// - [`AppConfig`](config::AppConfig) — simple app-owned config values.
157pub mod config;
158
159// ────────────────────────────────────────────────────────────────────────────
160// Storage & persistence
161// ────────────────────────────────────────────────────────────────────────────
162
163/// Storage backends and the [`AuthStorage`](storage::AuthStorage) trait.
164///
165/// See the trait documentation for available backends (Memory, PostgreSQL,
166/// Redis, SQLite, Encrypted) and guidance on writing custom backends.
167pub mod storage;
168
169// ────────────────────────────────────────────────────────────────────────────
170// Security
171// ────────────────────────────────────────────────────────────────────────────
172
173/// Audit logging of authentication and authorization events.
174pub mod audit;
175
176/// Role-based and attribute-based access control (RBAC/ABAC).
177pub mod authorization;
178#[cfg(feature = "role-system")]
179pub mod authorization_enhanced;
180/// Security utilities: rate limiting, DoS protection, IP blocking, and JWT hardening.
181pub mod security;
182
183// ────────────────────────────────────────────────────────────────────────────
184// Session & distributed state
185// ────────────────────────────────────────────────────────────────────────────
186
187/// Session lifecycle, device fingerprinting, and risk scoring.
188pub mod session;
189
190/// Distributed authentication: cross-node token validation and cluster coordination.
191pub mod distributed;
192
193// ────────────────────────────────────────────────────────────────────────────
194// Server-side protocol implementations
195// ────────────────────────────────────────────────────────────────────────────
196
197/// Server-side OAuth 2.0 / OIDC / FAPI protocol implementations.
198pub mod server;
199
200// oauth2_server and oauth2_enhanced_storage now live under server::oauth.
201pub use server::oauth::oauth2_enhanced_storage;
202pub use server::oauth::oauth2_server;
203
204/// OAuth 2.0 client type definitions (RFC 6749 §2.1).
205pub mod client;
206
207// ────────────────────────────────────────────────────────────────────────────
208// Integrations, providers & transport
209// ────────────────────────────────────────────────────────────────────────────
210
211/// OAuth 2.0 provider configuration and PKCE helpers.
212pub mod providers;
213
214/// Helpers for extracting user profiles from tokens and provider responses.
215pub mod profile_utils;
216
217/// Multi-tenant support for native multi-tenant deployments.
218pub mod tenant;
219
220/// User context and session enrichment.
221pub mod user_context;
222
223// ────────────────────────────────────────────────────────────────────────────
224// Monitoring, analytics & operations
225// ────────────────────────────────────────────────────────────────────────────
226
227/// Monitoring, health checks, and performance metrics.
228pub mod monitoring;
229
230/// Analytics collection and reporting.
231pub mod analytics;
232
233/// Deployment, scaling, and infrastructure management.
234pub mod deployment;
235
236/// Threat intelligence feeds and IP reputation services.
237pub mod threat_intelligence;
238
239// ────────────────────────────────────────────────────────────────────────────
240// Migration & maintenance
241// ────────────────────────────────────────────────────────────────────────────
242
243/// Schema migration utilities for role-system v1.0 integration.
244pub mod migration;
245
246/// SQL migration scripts for database backends.
247pub mod migrations;
248
249/// Backup, restore, and reset utilities.
250pub mod maintenance;
251
252// ────────────────────────────────────────────────────────────────────────────
253// Developer tools
254// ────────────────────────────────────────────────────────────────────────────
255
256/// Ergonomic builders and prelude for better developer experience.
257pub mod builders;
258
259/// Convenience re-exports for common types — `use auth_framework::prelude::*`.
260pub mod prelude;
261
262/// Internal utility functions.
263pub mod utils;
264
265/// Test helpers and mock implementations for downstream testing.
266pub mod testing;
267
268/// Protocol-level types shared across OAuth, OIDC, and SAML flows.
269pub mod protocols;
270
271/// Command-line interface utilities.
272pub mod cli;
273
274// ────────────────────────────────────────────────────────────────────────────
275// Feature-gated optional modules
276// ────────────────────────────────────────────────────────────────────────────
277
278#[cfg(feature = "enhanced-observability")]
279pub mod observability;
280
281#[cfg(feature = "event-sourcing")]
282pub mod architecture;
283
284// SDK generation for multiple languages
285#[cfg(feature = "enhanced-rbac")]
286pub mod sdks;
287
288// ────────────────────────────────────────────────────────────────────────────
289// Web framework integrations
290// ────────────────────────────────────────────────────────────────────────────
291
292/// Ready-made middleware and extractors for popular web frameworks.
293///
294/// Enable the appropriate feature flag to pull in the integration you need:
295///
296/// | Feature | Module |
297/// |---------|--------|
298/// | `axum-integration` | [`integrations::axum`] |
299/// | `actix-integration` | [`integrations::actix_web`] |
300/// | `warp-integration` | [`integrations::warp`] |
301pub mod integrations {
302 #[cfg(feature = "axum-integration")]
303 pub mod axum;
304
305 #[cfg(feature = "actix-integration")]
306 pub mod actix_web;
307
308 #[cfg(feature = "warp-integration")]
309 pub mod warp;
310}
311
312// ────────────────────────────────────────────────────────────────────────────
313// Re-exports — public API surface
314// ────────────────────────────────────────────────────────────────────────────
315
316// Re-exports - Main modular auth framework components
317pub use crate::auth::{
318 AdminOperations, AuditOperations, AuthFramework, AuthResult, AuthStats,
319 AuthorizationOperations, MaintenanceOperations, MfaOperations, MonitoringOperations,
320 SessionOperations, TokenOperations, UserInfo, UserOperations,
321};
322
323/// Deprecated alias — use [`UserInfo`] directly.
324#[deprecated(
325 since = "0.5.0",
326 note = "Use `UserInfo` directly — the `Core` prefix is redundant"
327)]
328pub type CoreUserInfo = UserInfo;
329pub use crate::auth_modular::AuthFramework as ModularAuthFramework;
330pub use crate::maintenance::{
331 BackupReport, MaintenanceSnapshot, MigrationFileReport, ResetReport, RestoreReport,
332 SnapshotManifest,
333};
334pub use authentication::credentials::Credential;
335pub use config::app_config::ConfigBuilder as AppConfigBuilder;
336pub use config::config_manager::{
337 ApiServerSettings, AuthFrameworkSettings, ConfigBuilder as LayeredConfigBuilder, ConfigManager,
338};
339pub use config::{AuthConfig, AuthConfigBuilder, CorsConfig, app_config::AppConfig};
340pub use errors::{AuthError, Result};
341pub use methods::{
342 ApiKeyMethod, AuthMethod, JwtMethod, MethodResult, OAuth2Method, PasswordMethod,
343};
344
345// REST API Server exports
346#[cfg(feature = "api-server")]
347pub use api::{ApiError, ApiResponse, ApiServer, ApiState};
348
349// SAML support (feature-gated)
350#[cfg(feature = "saml")]
351pub use methods::saml;
352
353// PKCE support functions
354pub use providers::generate_pkce;
355
356pub use permissions::{Permission, PermissionChecker, Role};
357pub use profile_utils::{ExtractProfile, TokenToProfile};
358pub use providers::{
359 DeviceAuthorizationResponse, OAuthProvider, OAuthProviderConfig, ProviderProfile,
360};
361pub use tokens::AuthToken;
362
363// WS-Security 1.1 and WS-Trust — enterprise XML security protocols.
364// Hidden from root docs; access via `auth_framework::protocols::ws_security` / `ws_trust`.
365#[doc(hidden)]
366pub use protocols::ws_security::{
367 UsernameToken, WsSecurityClient, WsSecurityConfig, WsSecurityHeader,
368};
369#[doc(hidden)]
370pub use protocols::ws_trust::RequestSecurityToken;
371
372// Server-side OIDC types.
373//
374// Note: the OIDC spec defines its own `UserInfo` struct (the /userinfo endpoint
375// response). It is re-exported here as `OidcUserInfo` to avoid collision with
376// the framework-level [`UserInfo`] (the internal user record).
377pub use server::oidc::{
378 Address, AuthorizationValidationResult, IdTokenClaims, Jwk, JwkSet, LogoutResponse,
379 OidcAuthorizationRequest, OidcConfig, OidcDiscoveryDocument, OidcProvider, SubjectType,
380 UserInfo as OidcUserInfo,
381};
382
383// Phase 2: Logout & Security Ecosystem specifications (advanced OIDC logout protocols).
384// Hidden from root docs; access via `auth_framework::server::oidc::oidc_backchannel_logout`
385// and `auth_framework::server::oidc::oidc_frontchannel_logout`.
386#[doc(hidden)]
387pub use server::oidc::oidc_backchannel_logout::{
388 BackChannelLogoutConfig, BackChannelLogoutManager, BackChannelLogoutRequest,
389 BackChannelLogoutResponse, LogoutEvents, LogoutTokenClaims, NotificationResult,
390 RpBackChannelConfig,
391};
392#[doc(hidden)]
393pub use server::oidc::oidc_frontchannel_logout::{
394 FailedNotification, FrontChannelLogoutConfig, FrontChannelLogoutManager,
395 FrontChannelLogoutRequest, FrontChannelLogoutResponse, RpFrontChannelConfig,
396};
397#[doc(hidden)]
398pub use server::oidc::oidc_rp_initiated_logout::{
399 ClientLogoutConfig, LogoutNotificationTarget, RpInitiatedLogoutConfig,
400 RpInitiatedLogoutManager, RpInitiatedLogoutRequest, RpInitiatedLogoutResponse,
401};
402
403// OAuth2 server types and configurations
404pub use oauth2_server::{
405 AuthorizationRequest, GrantType, OAuth2Config, OAuth2Server, ResponseType, TokenRequest,
406 TokenResponse,
407};
408
409// Server configuration types — ClientType and ClientConfig come from the canonical `client` module.
410pub use client::{ClientConfig, ClientConfigBuilder, ClientType};
411pub use server::{ClientRegistrationRequest, WorkingServerConfig};
412
413/// Deprecated alias for [`ClientRegistrationRequest`].
414#[deprecated(since = "0.5.0", note = "Use `ClientRegistrationRequest` instead")]
415pub type ServerClientRegistrationRequest =
416 server::core::client_registration::ClientRegistrationRequest;
417
418// Advanced server modules and RFC implementations.
419// Hidden from top-level docs/autocomplete to avoid cluttering the onboarding path;
420// access via `auth_framework::server::*` for advanced use.
421#[doc(hidden)]
422pub use server::DpopManager;
423#[doc(hidden)]
424pub use server::MetadataProvider;
425#[doc(hidden)]
426pub use server::OAuth2Server as ServerOAuth2Server;
427#[doc(hidden)]
428pub use server::PARManager;
429#[doc(hidden)]
430pub use server::PrivateKeyJwtManager;
431#[doc(hidden)]
432pub use server::TokenIntrospectionService;
433
434// Security and authentication module re-exports
435pub use audit::{AuditEvent, AuditEventType, AuditLogger, EventOutcome, RiskLevel};
436/// Deprecated alias for `authentication::mfa::MfaManager`. Use `auth_modular` MFA operations instead.
437#[deprecated(
438 since = "0.5.0",
439 note = "Use `AuthFramework::mfa()` accessor or `auth_modular::MfaManager` instead"
440)]
441pub use authentication::mfa::MfaManager as LegacyMfaManager;
442pub use authentication::mfa::{MfaMethodType, TotpProvider};
443pub use authorization::{
444 AbacPermission as AuthzPermission, AbacRole as AuthzRole, AccessCondition, AuthorizationEngine,
445};
446pub use security::secure_jwt::{SecureJwtClaims, SecureJwtConfig, SecureJwtValidator};
447pub use security::secure_mfa::SecureMfaService;
448pub use security::secure_session::{
449 DeviceFingerprint, SecureSession, SecureSessionConfig, SecureSessionManager, SecurityFlags,
450};
451pub use security::secure_utils::{SecureComparison, SecureRandomGen};
452/// Deprecated alias for [`SessionManager`]. Use `SessionManager` directly.
453#[deprecated(since = "0.5.0", note = "Use `SessionManager` instead")]
454pub use session::manager::SessionManager as LegacySessionManager;
455pub use session::manager::{DeviceInfo, Session, SessionConfig, SessionManager, SessionState};
456pub use utils::rate_limit::RateLimiter;
457
458// Multi-tenant support
459pub use tenant::{TenantContext, TenantId, TenantMetadata, TenantRegistry, TenantRegistryBuilder};
460
461// Monitoring and metrics
462pub use monitoring::{
463 HealthCheckResult, HealthStatus, MetricDataPoint, MetricType, MonitoringConfig,
464 MonitoringManager, PerformanceMetrics, SecurityEvent, SecurityEventSeverity, SecurityEventType,
465};
466
467// Session coordination stats from auth module
468pub use auth::SessionCoordinationStats;
469
470// Re-export testing utilities when available
471#[cfg(test)]
472pub use testing::{MockAuthMethod, MockStorage}; // Removed helpers temporarily
473
474// Re-export test infrastructure for bulletproof testing
475#[cfg(test)]
476pub use testing::{
477 test_infrastructure::{TestEnvironmentGuard, test_data},
478 utilities::*,
479};