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- [`ModularAuthFramework`] is deprecated (removed in `0.7.0`); for manager-level
16 composition and lifecycle control name [`auth_modular::AuthFramework`] by path.
17- Use [`prelude`] when you want ergonomic imports for application code.
18- [`AppConfigBuilder`] is deprecated (removed in `0.7.0`); use [`LayeredConfigBuilder`].
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 [`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/// 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/// How a client's secret is kept in its `oauth2_client:{id}` record (shared by the HTTP API and
207/// the library registry).
208pub(crate) mod client_secret;
209
210// ────────────────────────────────────────────────────────────────────────────
211// Integrations, providers & transport
212// ────────────────────────────────────────────────────────────────────────────
213
214/// OAuth 2.0 provider configuration and PKCE helpers.
215pub mod providers;
216
217/// Helpers for extracting user profiles from tokens and provider responses.
218pub mod profile_utils;
219
220/// Multi-tenant support for native multi-tenant deployments.
221pub mod tenant;
222
223/// User context and session enrichment.
224pub mod user_context;
225
226// ────────────────────────────────────────────────────────────────────────────
227// Monitoring, analytics & operations
228// ────────────────────────────────────────────────────────────────────────────
229
230/// Monitoring, health checks, and performance metrics.
231pub mod monitoring;
232
233/// Analytics collection and reporting.
234pub mod analytics;
235
236/// Deployment, scaling, and infrastructure management.
237pub mod deployment;
238
239/// Threat intelligence feeds and IP reputation services.
240pub mod threat_intelligence;
241
242// ────────────────────────────────────────────────────────────────────────────
243// Migration & maintenance
244// ────────────────────────────────────────────────────────────────────────────
245
246/// Schema migration utilities for role-system v1.0 integration.
247pub mod migration;
248
249/// SQL migration scripts for database backends.
250pub mod migrations;
251
252/// Backup, restore, and reset utilities.
253pub mod maintenance;
254
255// ────────────────────────────────────────────────────────────────────────────
256// Developer tools
257// ────────────────────────────────────────────────────────────────────────────
258
259/// Ergonomic builders and prelude for better developer experience.
260pub mod builders;
261
262/// Convenience re-exports for common types — `use auth_framework::prelude::*`.
263pub mod prelude;
264
265/// Internal utility functions.
266pub mod utils;
267
268/// Test helpers and mock implementations for downstream testing.
269pub mod testing;
270
271/// Protocol-level types shared across OAuth, OIDC, and SAML flows.
272pub mod protocols;
273
274/// Command-line interface utilities.
275pub mod cli;
276
277// ────────────────────────────────────────────────────────────────────────────
278// Feature-gated optional modules
279// ────────────────────────────────────────────────────────────────────────────
280
281#[cfg(feature = "enhanced-observability")]
282pub mod observability;
283
284#[cfg(feature = "event-sourcing")]
285pub mod architecture;
286
287// SDK generation for multiple languages
288#[cfg(feature = "enhanced-rbac")]
289pub mod sdks;
290
291// ────────────────────────────────────────────────────────────────────────────
292// Web framework integrations
293// ────────────────────────────────────────────────────────────────────────────
294
295/// Ready-made middleware and extractors for popular web frameworks.
296///
297/// Enable the appropriate feature flag to pull in the integration you need:
298///
299/// | Feature | Module |
300/// |---------|--------|
301/// | `axum-integration` | [`integrations::axum`] |
302/// | `actix-integration` | [`integrations::actix_web`] |
303/// | `warp-integration` | [`integrations::warp`] |
304pub mod integrations {
305 #[cfg(feature = "axum-integration")]
306 pub mod axum;
307
308 #[cfg(feature = "actix-integration")]
309 pub mod actix_web;
310
311 #[cfg(feature = "warp-integration")]
312 pub mod warp;
313}
314
315// ────────────────────────────────────────────────────────────────────────────
316// Re-exports — public API surface
317// ────────────────────────────────────────────────────────────────────────────
318
319// Re-exports - Main modular auth framework components
320pub use crate::auth::{
321 AdminOperations, AuditOperations, AuthFramework, AuthResult, AuthStats,
322 AuthorizationOperations, MaintenanceOperations, MfaOperations, MonitoringOperations,
323 SessionOperations, TokenOperations, UserInfo, UserOperations,
324};
325
326/// Deprecated alias — use [`UserInfo`] directly.
327#[deprecated(
328 since = "0.5.0",
329 note = "Use `UserInfo` directly — the `Core` prefix is redundant"
330)]
331pub type CoreUserInfo = UserInfo;
332/// Deprecated alias of [`auth_modular::AuthFramework`]; removed in `0.7.0`.
333///
334/// Use [`AuthFramework`] (see `COMPATIBILITY.md`), or name
335/// `auth_framework::auth_modular::AuthFramework` by path if you need
336/// manager-level access.
337///
338/// ```compile_fail
339/// #![deny(deprecated)]
340/// use auth_framework::ModularAuthFramework;
341/// fn takes(_: Option<ModularAuthFramework>) {}
342/// ```
343///
344/// The same code compiles once the warning is allowed (control):
345///
346/// ```
347/// #![allow(deprecated)]
348/// use auth_framework::ModularAuthFramework;
349/// fn takes(_: Option<ModularAuthFramework>) {}
350/// ```
351#[deprecated(
352 since = "0.6.0",
353 note = "removed in 0.7.0: use `AuthFramework`, or `auth_framework::auth_modular::AuthFramework` by path"
354)]
355pub type ModularAuthFramework = crate::auth_modular::AuthFramework;
356pub use crate::maintenance::{
357 BackupReport, MaintenanceSnapshot, MigrationFileReport, ResetReport, RestoreReport,
358 SnapshotManifest,
359};
360pub use authentication::credentials::Credential;
361/// Deprecated alias of [`config::app_config::ConfigBuilder`]; removed in `0.7.0`.
362///
363/// Use [`LayeredConfigBuilder`] (see `COMPATIBILITY.md`).
364///
365/// ```compile_fail
366/// #![deny(deprecated)]
367/// use auth_framework::AppConfigBuilder;
368/// fn takes(_: Option<AppConfigBuilder>) {}
369/// ```
370///
371/// The same code compiles once the warning is allowed (control):
372///
373/// ```
374/// #![allow(deprecated)]
375/// use auth_framework::AppConfigBuilder;
376/// fn takes(_: Option<AppConfigBuilder>) {}
377/// ```
378#[deprecated(since = "0.6.0", note = "removed in 0.7.0: use `LayeredConfigBuilder`")]
379pub type AppConfigBuilder = config::app_config::ConfigBuilder;
380pub use config::config_manager::{
381 ApiServerSettings, AuthFrameworkSettings, ConfigBuilder as LayeredConfigBuilder, ConfigManager,
382};
383pub use config::{AuthConfig, AuthConfigBuilder, CorsConfig, app_config::AppConfig};
384pub use errors::{AuthError, Result};
385pub use methods::{
386 ApiKeyMethod, AuthMethod, JwtMethod, MethodResult, OAuth2Method, PasswordMethod,
387};
388
389// REST API Server exports
390#[cfg(feature = "api-server")]
391pub use api::{ApiError, ApiResponse, ApiServer, ApiState};
392
393// SAML support (feature-gated)
394#[cfg(feature = "saml")]
395pub use methods::saml;
396
397// PKCE support functions
398pub use providers::generate_pkce;
399
400pub use permissions::{Permission, PermissionChecker, Role};
401pub use profile_utils::{ExtractProfile, TokenToProfile};
402pub use providers::{
403 DeviceAuthorizationResponse, OAuthProvider, OAuthProviderConfig, ProviderProfile,
404};
405pub use tokens::AuthToken;
406
407// WS-Security 1.1 and WS-Trust — enterprise XML security protocols.
408// Hidden from root docs; access via `auth_framework::protocols::ws_security` / `ws_trust`.
409#[doc(hidden)]
410pub use protocols::ws_security::{
411 UsernameToken, WsSecurityClient, WsSecurityConfig, WsSecurityHeader,
412};
413#[doc(hidden)]
414pub use protocols::ws_trust::RequestSecurityToken;
415
416// Server-side OIDC types.
417//
418// Note: the OIDC spec defines its own `UserInfo` struct (the /userinfo endpoint
419// response). It is re-exported here as `OidcUserInfo` to avoid collision with
420// the framework-level [`UserInfo`] (the internal user record).
421pub use server::oidc::{
422 Address, AuthorizationValidationResult, IdTokenClaims, Jwk, JwkSet, LogoutResponse,
423 OidcAuthorizationRequest, OidcConfig, OidcDiscoveryDocument, OidcProvider, SubjectType,
424 UserInfo as OidcUserInfo,
425};
426
427// Phase 2: Logout & Security Ecosystem specifications (advanced OIDC logout protocols).
428// Hidden from root docs; access via `auth_framework::server::oidc::oidc_backchannel_logout`
429// and `auth_framework::server::oidc::oidc_frontchannel_logout`.
430#[doc(hidden)]
431pub use server::oidc::oidc_backchannel_logout::{
432 BackChannelLogoutConfig, BackChannelLogoutManager, BackChannelLogoutRequest,
433 BackChannelLogoutResponse, LogoutEvents, LogoutTokenClaims, NotificationResult,
434 RpBackChannelConfig,
435};
436#[doc(hidden)]
437pub use server::oidc::oidc_frontchannel_logout::{
438 FailedNotification, FrontChannelLogoutConfig, FrontChannelLogoutManager,
439 FrontChannelLogoutRequest, FrontChannelLogoutResponse, RpFrontChannelConfig,
440};
441#[doc(hidden)]
442pub use server::oidc::oidc_rp_initiated_logout::{
443 ClientLogoutConfig, LogoutNotificationTarget, RpInitiatedLogoutConfig,
444 RpInitiatedLogoutManager, RpInitiatedLogoutRequest, RpInitiatedLogoutResponse,
445};
446
447// OAuth2 server types and configurations
448pub use oauth2_server::{
449 AuthorizationRequest, GrantType, OAuth2Config, OAuth2Server, ResponseType, TokenRequest,
450 TokenResponse,
451};
452
453// Server configuration types — ClientType and ClientConfig come from the canonical `client` module.
454pub use client::{ClientConfig, ClientConfigBuilder, ClientType};
455pub use server::{ClientRegistrationRequest, WorkingServerConfig};
456
457/// Deprecated alias for [`ClientRegistrationRequest`].
458#[deprecated(since = "0.5.0", note = "Use `ClientRegistrationRequest` instead")]
459pub type ServerClientRegistrationRequest =
460 server::core::client_registration::ClientRegistrationRequest;
461
462// Advanced server modules and RFC implementations.
463// Hidden from top-level docs/autocomplete to avoid cluttering the onboarding path;
464// access via `auth_framework::server::*` for advanced use.
465#[doc(hidden)]
466pub use server::DpopManager;
467#[doc(hidden)]
468pub use server::MetadataProvider;
469#[doc(hidden)]
470pub use server::OAuth2Server as ServerOAuth2Server;
471#[doc(hidden)]
472pub use server::PARManager;
473#[doc(hidden)]
474pub use server::PrivateKeyJwtManager;
475
476// Security and authentication module re-exports
477pub use audit::{AuditEvent, AuditEventType, AuditLogger, EventOutcome, RiskLevel};
478/// Deprecated alias for `authentication::mfa::MfaManager`. Use `auth_modular` MFA operations instead.
479#[deprecated(
480 since = "0.5.0",
481 note = "Use `AuthFramework::mfa()` accessor or `auth_modular::MfaManager` instead"
482)]
483pub use authentication::mfa::MfaManager as LegacyMfaManager;
484pub use authentication::mfa::{MfaMethodType, TotpProvider};
485pub use authorization::{
486 AbacPermission as AuthzPermission, AbacRole as AuthzRole, AccessCondition, AuthorizationEngine,
487};
488pub use security::secure_jwt::{SecureJwtClaims, SecureJwtConfig, SecureJwtValidator};
489pub use security::secure_mfa::SecureMfaService;
490pub use security::secure_session::{
491 DeviceFingerprint, SecureSession, SecureSessionConfig, SecureSessionManager, SecurityFlags,
492};
493pub use security::secure_utils::{SecureComparison, SecureRandomGen};
494/// Deprecated alias for [`SessionManager`]. Use `SessionManager` directly.
495#[deprecated(since = "0.5.0", note = "Use `SessionManager` instead")]
496pub use session::manager::SessionManager as LegacySessionManager;
497pub use session::manager::{DeviceInfo, Session, SessionConfig, SessionManager, SessionState};
498pub use utils::rate_limit::RateLimiter;
499
500// Multi-tenant support
501pub use tenant::{TenantContext, TenantId, TenantMetadata, TenantRegistry, TenantRegistryBuilder};
502
503// Monitoring and metrics
504pub use monitoring::{
505 HealthCheckResult, HealthStatus, MetricDataPoint, MetricType, MonitoringConfig,
506 MonitoringManager, PerformanceMetrics, SecurityEvent, SecurityEventSeverity, SecurityEventType,
507};
508
509// Session coordination stats from auth module
510pub use auth::SessionCoordinationStats;
511
512// Re-export testing utilities when available
513#[cfg(test)]
514pub use testing::{MockAuthMethod, MockStorage}; // Removed helpers temporarily
515
516// Re-export test infrastructure for bulletproof testing
517#[cfg(test)]
518pub use testing::{
519 test_infrastructure::{TestEnvironmentGuard, test_data},
520 utilities::*,
521};