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
104/// Primary authentication framework — start here.
105///
106/// Contains [`AuthFramework`], the main entry point for most applications.
107/// Access grouped operations via [`AuthFramework::users`], [`AuthFramework::tokens`],
108/// [`AuthFramework::sessions`], etc.
109pub mod auth;
110
111/// Advanced component-oriented framework.
112///
113/// Use [`ModularAuthFramework`](auth_modular::AuthFramework) only when you need
114/// direct access to individual manager instances (user, session, MFA) for custom
115/// composition. Most applications should use [`auth::AuthFramework`] instead.
116pub mod auth_modular;
117
118/// Grouped operation facades over [`AuthFramework`].
119///
120/// Light reference wrappers (e.g. [`UserOperations`], [`TokenOperations`]) returned
121/// by the accessor methods on `AuthFramework`. Not usually imported directly —
122/// use `auth.users()`, `auth.tokens()`, etc.
123pub mod auth_operations;
124
125/// Supporting authentication data types.
126///
127/// Credentials, metadata, and MFA primitives used as inputs to the core
128/// framework. Import specific types rather than the module wildcard.
129pub mod authentication;
130
131/// Domain-specific newtypes (`Roles`, `Scopes`, `Permissions`, etc.).
132pub mod types;
133
134/// Error types and the crate-wide [`Result`](errors::Result) alias.
135pub mod errors;
136
137/// Authentication method implementations (JWT, OAuth2, API keys, passwords, SAML).
138pub mod methods;
139
140/// Permission and role definitions for access control.
141pub mod permissions;
142
143/// Token creation, validation, rotation, and JWKS support.
144pub mod tokens;
145
146// ────────────────────────────────────────────────────────────────────────────
147// Configuration
148// ────────────────────────────────────────────────────────────────────────────
149
150/// Configuration types and management.
151///
152/// - [`AuthConfig`](config::AuthConfig) — main config struct (use [`AuthConfig::new()`]
153/// for fluent setters or [`AuthConfig::builder()`] for the full builder).
154/// - [`ConfigManager`](config::ConfigManager) — layered config from files + env.
155/// - [`AppConfig`](config::AppConfig) — simple app-owned config values.
156pub mod config;
157
158// ────────────────────────────────────────────────────────────────────────────
159// Storage & persistence
160// ────────────────────────────────────────────────────────────────────────────
161
162/// Storage backends and the [`AuthStorage`](storage::AuthStorage) trait.
163///
164/// See the trait documentation for available backends (Memory, PostgreSQL,
165/// MySQL, Redis, SQLite, Encrypted) and guidance on writing custom backends.
166pub mod storage;
167
168// ────────────────────────────────────────────────────────────────────────────
169// Security
170// ────────────────────────────────────────────────────────────────────────────
171
172/// Audit logging of authentication and authorization events.
173pub mod audit;
174
175/// Role-based and attribute-based access control (RBAC/ABAC).
176pub mod authorization;
177#[cfg(feature = "role-system")]
178pub mod authorization_enhanced;
179/// Security utilities: rate limiting, DoS protection, IP blocking, and JWT hardening.
180pub mod security;
181
182// ────────────────────────────────────────────────────────────────────────────
183// Session & distributed state
184// ────────────────────────────────────────────────────────────────────────────
185
186/// Session lifecycle, device fingerprinting, and risk scoring.
187pub mod session;
188
189/// Distributed authentication: cross-node token validation and cluster coordination.
190pub mod distributed;
191
192// ────────────────────────────────────────────────────────────────────────────
193// Server-side protocol implementations
194// ────────────────────────────────────────────────────────────────────────────
195
196/// Server-side OAuth 2.0 / OIDC / FAPI protocol implementations.
197pub mod server;
198
199// oauth2_server and oauth2_enhanced_storage now live under server::oauth.
200pub use server::oauth::oauth2_enhanced_storage;
201pub use server::oauth::oauth2_server;
202
203/// OAuth 2.0 client type definitions (RFC 6749 §2.1).
204pub mod client;
205
206// ────────────────────────────────────────────────────────────────────────────
207// Integrations, providers & transport
208// ────────────────────────────────────────────────────────────────────────────
209
210/// OAuth 2.0 provider configuration and PKCE helpers.
211pub mod providers;
212
213/// Helpers for extracting user profiles from tokens and provider responses.
214pub mod profile_utils;
215
216/// Multi-tenant support for native multi-tenant deployments.
217pub mod tenant;
218
219/// User context and session enrichment.
220pub mod user_context;
221
222// ────────────────────────────────────────────────────────────────────────────
223// Monitoring, analytics & operations
224// ────────────────────────────────────────────────────────────────────────────
225
226/// Monitoring, health checks, and performance metrics.
227pub mod monitoring;
228
229/// Analytics collection and reporting.
230pub mod analytics;
231
232/// Deployment, scaling, and infrastructure management.
233pub mod deployment;
234
235/// Threat intelligence feeds and IP reputation services.
236pub mod threat_intelligence;
237
238// ────────────────────────────────────────────────────────────────────────────
239// Migration & maintenance
240// ────────────────────────────────────────────────────────────────────────────
241
242/// Schema migration utilities for role-system v1.0 integration.
243pub mod migration;
244
245/// SQL migration scripts for database backends.
246pub mod migrations;
247
248/// Backup, restore, and reset utilities.
249pub mod maintenance;
250
251// ────────────────────────────────────────────────────────────────────────────
252// Developer tools
253// ────────────────────────────────────────────────────────────────────────────
254
255/// Ergonomic builders and prelude for better developer experience.
256pub mod builders;
257
258/// Convenience re-exports for common types — `use auth_framework::prelude::*`.
259pub mod prelude;
260
261/// Internal utility functions.
262pub mod utils;
263
264/// Test helpers and mock implementations for downstream testing.
265pub mod testing;
266
267/// Protocol-level types shared across OAuth, OIDC, and SAML flows.
268pub mod protocols;
269
270/// Command-line interface utilities.
271pub mod cli;
272
273// ────────────────────────────────────────────────────────────────────────────
274// Feature-gated optional modules
275// ────────────────────────────────────────────────────────────────────────────
276
277#[cfg(feature = "enhanced-observability")]
278pub mod observability;
279
280#[cfg(feature = "event-sourcing")]
281pub mod architecture;
282
283// SDK generation for multiple languages
284#[cfg(feature = "enhanced-rbac")]
285pub mod sdks;
286
287// ────────────────────────────────────────────────────────────────────────────
288// Web framework integrations
289// ────────────────────────────────────────────────────────────────────────────
290
291/// Ready-made middleware and extractors for popular web frameworks.
292///
293/// Enable the appropriate feature flag to pull in the integration you need:
294///
295/// | Feature | Module |
296/// |---------|--------|
297/// | `axum-integration` | [`integrations::axum`] |
298/// | `actix-integration` | [`integrations::actix_web`] |
299/// | `warp-integration` | [`integrations::warp`] |
300pub mod integrations {
301 #[cfg(feature = "axum-integration")]
302 pub mod axum;
303
304 #[cfg(feature = "actix-integration")]
305 pub mod actix_web;
306
307 #[cfg(feature = "warp-integration")]
308 pub mod warp;
309}
310
311// ────────────────────────────────────────────────────────────────────────────
312// Re-exports — public API surface
313// ────────────────────────────────────────────────────────────────────────────
314
315// Re-exports - Main modular auth framework components
316pub use crate::auth::{
317 AdminOperations, AuditOperations, AuthFramework, AuthResult, AuthStats,
318 AuthorizationOperations, MaintenanceOperations, MfaOperations, MonitoringOperations,
319 SessionOperations, TokenOperations, UserInfo, UserOperations,
320};
321
322/// Deprecated alias — use [`UserInfo`] directly.
323#[deprecated(
324 since = "0.5.0",
325 note = "Use `UserInfo` directly — the `Core` prefix is redundant"
326)]
327pub type CoreUserInfo = UserInfo;
328pub use crate::auth_modular::AuthFramework as ModularAuthFramework;
329pub use crate::maintenance::{
330 BackupReport, MaintenanceSnapshot, MigrationFileReport, ResetReport, RestoreReport,
331 SnapshotManifest,
332};
333pub use authentication::credentials::Credential;
334pub use config::app_config::ConfigBuilder as AppConfigBuilder;
335pub use config::config_manager::{
336 AuthFrameworkSettings, ConfigBuilder as LayeredConfigBuilder, ConfigManager,
337};
338pub use config::{AuthConfig, AuthConfigBuilder, CorsConfig, app_config::AppConfig};
339pub use errors::{AuthError, Result};
340pub use methods::{
341 ApiKeyMethod, AuthMethod, JwtMethod, MethodResult, OAuth2Method, PasswordMethod,
342};
343
344// REST API Server exports
345#[cfg(feature = "api-server")]
346pub use api::{ApiError, ApiResponse, ApiServer, ApiState};
347
348// SAML support (feature-gated)
349#[cfg(feature = "saml")]
350pub use methods::saml;
351
352// PKCE support functions
353pub use providers::generate_pkce;
354
355pub use permissions::{Permission, PermissionChecker, Role};
356pub use profile_utils::{ExtractProfile, TokenToProfile};
357pub use providers::{
358 DeviceAuthorizationResponse, OAuthProvider, OAuthProviderConfig, ProviderProfile,
359};
360pub use tokens::AuthToken;
361
362// WS-Security 1.1 and WS-Trust — enterprise XML security protocols.
363// Hidden from root docs; access via `auth_framework::protocols::ws_security` / `ws_trust`.
364#[doc(hidden)]
365pub use protocols::ws_security::{
366 UsernameToken, WsSecurityClient, WsSecurityConfig, WsSecurityHeader,
367};
368#[doc(hidden)]
369pub use protocols::ws_trust::RequestSecurityToken;
370
371// Server-side OIDC types.
372//
373// Note: the OIDC spec defines its own `UserInfo` struct (the /userinfo endpoint
374// response). It is re-exported here as `OidcUserInfo` to avoid collision with
375// the framework-level [`UserInfo`] (the internal user record).
376pub use server::oidc::{
377 Address, AuthorizationValidationResult, IdTokenClaims, Jwk, JwkSet, LogoutResponse,
378 OidcAuthorizationRequest, OidcConfig, OidcDiscoveryDocument, OidcProvider, SubjectType,
379 UserInfo as OidcUserInfo,
380};
381
382// Phase 2: Logout & Security Ecosystem specifications (advanced OIDC logout protocols).
383// Hidden from root docs; access via `auth_framework::server::oidc::oidc_backchannel_logout`
384// and `auth_framework::server::oidc::oidc_frontchannel_logout`.
385#[doc(hidden)]
386pub use server::oidc::oidc_backchannel_logout::{
387 BackChannelLogoutConfig, BackChannelLogoutManager, BackChannelLogoutRequest,
388 BackChannelLogoutResponse, LogoutEvents, LogoutTokenClaims, NotificationResult,
389 RpBackChannelConfig,
390};
391#[doc(hidden)]
392pub use server::oidc::oidc_frontchannel_logout::{
393 FailedNotification, FrontChannelLogoutConfig, FrontChannelLogoutManager,
394 FrontChannelLogoutRequest, FrontChannelLogoutResponse, RpFrontChannelConfig,
395};
396#[doc(hidden)]
397pub use server::oidc::oidc_rp_initiated_logout::{
398 ClientLogoutConfig, LogoutNotificationTarget, RpInitiatedLogoutConfig,
399 RpInitiatedLogoutManager, RpInitiatedLogoutRequest, RpInitiatedLogoutResponse,
400};
401
402// OAuth2 server types and configurations
403pub use oauth2_server::{
404 AuthorizationRequest, GrantType, OAuth2Config, OAuth2Server, ResponseType, TokenRequest,
405 TokenResponse,
406};
407
408// Server configuration types — ClientType and ClientConfig come from the canonical `client` module.
409pub use client::{ClientConfig, ClientConfigBuilder, ClientType};
410pub use server::{ClientRegistrationRequest, WorkingServerConfig};
411
412/// Deprecated alias for [`ClientRegistrationRequest`].
413#[deprecated(since = "0.5.0", note = "Use `ClientRegistrationRequest` instead")]
414pub type ServerClientRegistrationRequest =
415 server::core::client_registration::ClientRegistrationRequest;
416
417// Advanced server modules and RFC implementations.
418// Hidden from top-level docs/autocomplete to avoid cluttering the onboarding path;
419// access via `auth_framework::server::*` for advanced use.
420#[doc(hidden)]
421pub use server::DpopManager;
422#[doc(hidden)]
423pub use server::MetadataProvider;
424#[doc(hidden)]
425pub use server::OAuth2Server as ServerOAuth2Server;
426#[doc(hidden)]
427pub use server::PARManager;
428#[doc(hidden)]
429pub use server::PrivateKeyJwtManager;
430#[doc(hidden)]
431pub use server::TokenIntrospectionService;
432
433// Security and authentication module re-exports
434pub use audit::{AuditEvent, AuditEventType, AuditLogger, EventOutcome, RiskLevel};
435/// Deprecated alias for `authentication::mfa::MfaManager`. Use `auth_modular` MFA operations instead.
436#[deprecated(
437 since = "0.5.0",
438 note = "Use `AuthFramework::mfa()` accessor or `auth_modular::MfaManager` instead"
439)]
440pub use authentication::mfa::MfaManager as LegacyMfaManager;
441pub use authentication::mfa::{MfaMethodType, TotpProvider};
442pub use authorization::{
443 AbacPermission as AuthzPermission, AbacRole as AuthzRole, AccessCondition, AuthorizationEngine,
444};
445pub use security::secure_jwt::{SecureJwtClaims, SecureJwtConfig, SecureJwtValidator};
446pub use security::secure_mfa::SecureMfaService;
447pub use security::secure_session::{
448 DeviceFingerprint, SecureSession, SecureSessionConfig, SecureSessionManager, SecurityFlags,
449};
450pub use security::secure_utils::{SecureComparison, SecureRandomGen};
451/// Deprecated alias for [`SessionManager`]. Use `SessionManager` directly.
452#[deprecated(since = "0.5.0", note = "Use `SessionManager` instead")]
453pub use session::manager::SessionManager as LegacySessionManager;
454pub use session::manager::{DeviceInfo, Session, SessionConfig, SessionManager, SessionState};
455pub use utils::rate_limit::RateLimiter;
456
457// Multi-tenant support
458pub use tenant::{TenantContext, TenantId, TenantMetadata, TenantRegistry, TenantRegistryBuilder};
459
460// Monitoring and metrics
461pub use monitoring::{
462 HealthCheckResult, HealthStatus, MetricDataPoint, MetricType, MonitoringConfig,
463 MonitoringManager, PerformanceMetrics, SecurityEvent, SecurityEventSeverity, SecurityEventType,
464};
465
466// Session coordination stats from auth module
467pub use auth::SessionCoordinationStats;
468
469// Re-export testing utilities when available
470#[cfg(test)]
471pub use testing::{MockAuthMethod, MockStorage}; // Removed helpers temporarily
472
473// Re-export test infrastructure for bulletproof testing
474#[cfg(test)]
475pub use testing::{
476 test_infrastructure::{TestEnvironmentGuard, test_data},
477 utilities::*,
478};