auth_framework/lib.rs
1/*!
2# Auth Framework
3
4A comprehensive authentication and authorization framework for Rust applications.
5
6This crate provides a unified interface for various authentication methods,
7token management, permission checking, and secure credential handling with
8a focus on distributed systems.
9
10## Features
11
12- Multiple authentication methods (OAuth, API keys, JWT, etc.)
13- Token issuance, validation, and refresh with RSA and HMAC signing
14- RSA key format support: PKCS#1 and PKCS#8 formats auto-detected
15- Role-based access control integration
16- Permission checking and enforcement
17- Secure credential storage
18- Authentication middleware for web frameworks
19- Distributed authentication with cross-node validation
20- Single sign-on capabilities
21- Multi-factor authentication support
22- Audit logging of authentication events
23- Rate limiting and brute force protection
24- Session management
25- Password hashing and validation
26- Customizable authentication flows
27
28## Quick Start
29
30
31```rust,no_run
32use auth_framework::{AuthFramework, AuthConfig, methods::JwtMethod};
33use std::time::Duration;
34
35# #[tokio::main]
36# async fn main() -> Result<(), Box<dyn std::error::Error>> {
37 // Configure the auth framework
38 let config = AuthConfig::new()
39 .token_lifetime(Duration::from_secs(3600))
40 .refresh_token_lifetime(Duration::from_secs(86400 * 7));
41
42 // Create the auth framework
43 let mut auth = AuthFramework::new(config);
44
45 // Register a JWT authentication method
46 let jwt_method = JwtMethod::new()
47 .secret_key("your-secret-key")
48 .issuer("your-service");
49
50 auth.register_method("jwt", auth_framework::methods::AuthMethodEnum::Jwt(jwt_method));
51
52 // Initialize the framework
53 auth.initialize().await?;
54
55 // Create a token
56 let token = auth.create_auth_token(
57 "user123",
58 vec!["read".to_string(), "write".to_string()],
59 "jwt",
60 None,
61 ).await?;
62
63 // Validate the token
64 if auth.validate_token(&token).await? {
65 println!("Token is valid!");
66
67 // Check permissions
68 if auth.check_permission(&token, "read", "documents").await? {
69 println!("User has permission to read documents");
70 }
71 }
72# Ok(())
73# }
74```
75
76## Security Considerations
77
78- Always use HTTPS in production
79- Use strong, unique secrets for token signing
80- Enable rate limiting to prevent brute force attacks
81- Regularly rotate secrets and keys
82- Monitor authentication events for suspicious activity
83- Follow the principle of least privilege for permissions
84
85See the [Security Policy](https://github.com/yourusername/auth-framework/blob/main/SECURITY.md)
86for comprehensive security guidelines.
87*/
88
89// REST API Server - NEW!
90#[cfg(feature = "api-server")]
91pub mod api;
92
93// ## Quick Start
94//
95// ```rust,no_run
96// use auth_framework::{AuthFramework, AuthConfig};
97// use auth_framework::methods::JwtMethod;
98// use std::time::Duration;
99//
100// # #[tokio::main]
101// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
102// // Configure the auth framework
103// let config = AuthConfig::new()
104// .token_lifetime(Duration::from_secs(3600))
105// .refresh_token_lifetime(Duration::from_secs(86400 * 7));
106//
107// // Create the auth framework
108// let mut auth = AuthFramework::new(config);
109//
110// // Register a JWT authentication method
111// let jwt_method = JwtMethod::new()
112// .secret_key("your-secret-key")
113// .issuer("your-service");
114//
115// auth.register_method("jwt", Box::new(jwt_method));
116//
117// // Initialize the framework
118// auth.initialize().await?;
119//
120// // Create a token
121// let token = auth.create_auth_token(
122// "user123",
123// vec!["read".to_string(), "write".to_string()],
124// "jwt",
125// None,
126// ).await?;
127//
128// // Validate the token
129// if auth.validate_token(&token).await? {
130// println!("Token is valid!");
131//
132// // Check permissions
133// if auth.check_permission(&token, "read", "documents").await? {
134// println!("User has permission to read documents");
135// }
136// }
137// # Ok(())
138// # }
139// ```
140//
141// ## Security Considerations
142//
143// - Always use HTTPS in production
144// - Use strong, unique secrets for token signing
145// - Enable rate limiting to prevent brute force attacks
146// - Regularly rotate secrets and keys
147// - Monitor authentication events for suspicious activity
148// - Follow the principle of least privilege for permissions
149//
150// See the [Security Policy](https://github.com/yourusername/auth-framework/blob/main/SECURITY.md)
151// for comprehensive security guidelines.
152
153// Admin interface (conditional on admin-binary feature)
154#[cfg(feature = "admin-binary")]
155pub mod admin;
156
157pub mod auth;
158pub mod auth_modular; // Modular authentication components
159pub mod authentication; // Reorganized authentication modules
160pub mod errors;
161pub mod methods;
162pub mod permissions;
163pub mod profile_utils;
164pub mod providers;
165
166// SDK generation for multiple languages
167#[cfg(feature = "enhanced-rbac")]
168pub mod sdks;
169
170pub mod server;
171pub mod storage;
172pub mod testing; // Reorganized testing modules
173pub mod threat_intelligence; // Automated threat intelligence feed management
174pub mod tokens;
175pub mod utils;
176
177// Migration utilities for role-system v1.0 integration
178pub mod migration;
179
180// Analytics and monitoring for RBAC systems
181pub mod analytics;
182
183// Production deployment automation and monitoring
184pub mod deployment;
185
186// User context and session management
187pub mod user_context;
188
189// Enhanced OAuth2 storage with proper validation
190pub mod oauth2_enhanced_storage;
191
192// OAuth2 server implementation
193// Secure OAuth2 server implementation
194pub mod oauth2_server;
195
196// Consolidated security modules
197pub mod audit;
198pub mod authorization;
199#[cfg(feature = "role-system")]
200pub mod authorization_enhanced;
201pub mod distributed_rate_limiting; // Advanced distributed rate limiting
202pub mod security;
203pub mod session; // Reorganized session modules
204
205// Configuration management
206pub mod config;
207
208// Monitoring and metrics collection
209pub mod monitoring;
210
211// Enhanced observability
212#[cfg(feature = "enhanced-observability")]
213pub mod observability;
214
215// Architecture enhancements
216#[cfg(feature = "event-sourcing")]
217pub mod architecture;
218
219// Web framework integrations
220pub mod integrations {
221 #[cfg(feature = "axum-integration")]
222 pub mod axum;
223
224 #[cfg(feature = "actix-integration")]
225 pub mod actix_web;
226
227 #[cfg(feature = "warp-integration")]
228 pub mod warp;
229}
230
231// Database migrations
232pub mod migrations;
233
234// CLI tools
235pub mod cli;
236
237// Ergonomic builders and prelude for better developer experience
238pub mod builders;
239pub mod prelude;
240
241// WS-Security 1.1 and SAML 2.0 support
242pub mod saml_assertions;
243pub mod ws_security;
244pub mod ws_trust;
245
246// Re-exports - Main modular auth framework components
247pub use crate::auth::{AuthFramework, AuthResult, AuthStats, UserInfo};
248pub use authentication::credentials::Credential;
249pub use config::{
250 AuthConfig,
251 app_config::{AppConfig, ConfigBuilder},
252};
253pub use errors::{AuthError, Result};
254pub use methods::{
255 ApiKeyMethod, AuthMethod, JwtMethod, MethodResult, OAuth2Method, PasswordMethod,
256};
257
258// REST API Server exports
259#[cfg(feature = "api-server")]
260pub use api::{ApiError, ApiResponse, ApiServer, ApiState};
261
262// SAML support (feature-gated)
263#[cfg(feature = "saml")]
264pub use methods::saml;
265
266// PKCE support functions
267pub use providers::generate_pkce;
268
269// WS-Security and WS-Trust support
270pub use permissions::{Permission, PermissionChecker, Role};
271pub use profile_utils::{ExtractProfile, TokenToProfile};
272pub use providers::{DeviceAuthorizationResponse, OAuthProvider, OAuthProviderConfig, UserProfile};
273pub use tokens::AuthToken;
274pub use ws_security::{UsernameToken, WsSecurityClient, WsSecurityConfig, WsSecurityHeader};
275pub use ws_trust::RequestSecurityToken;
276
277// Server-side authentication and authorization - Now working!
278pub use server::oidc::{
279 Address, AuthorizationValidationResult, IdTokenClaims, Jwk, JwkSet, LogoutResponse,
280 OidcAuthorizationRequest, OidcConfig, OidcDiscoveryDocument, OidcProvider, SubjectType,
281 UserInfo as OidcUserInfo,
282};
283
284// Phase 2: Logout & Security Ecosystem specifications
285pub use server::oidc::{
286 oidc_backchannel_logout::{
287 BackChannelLogoutConfig, BackChannelLogoutManager, BackChannelLogoutRequest,
288 BackChannelLogoutResponse, LogoutEvents, LogoutTokenClaims, NotificationResult,
289 RpBackChannelConfig,
290 },
291 oidc_frontchannel_logout::{
292 FailedNotification, FrontChannelLogoutConfig, FrontChannelLogoutManager,
293 FrontChannelLogoutRequest, FrontChannelLogoutResponse, RpFrontChannelConfig,
294 },
295};
296
297// OAuth2 server types and configurations
298pub use oauth2_server::{
299 AuthorizationRequest, GrantType, OAuth2Config, OAuth2Server, ResponseType, TokenRequest,
300 TokenResponse,
301};
302
303// Server configuration types
304pub use server::{
305 ClientRegistrationRequest, ClientType, WorkingServerConfig,
306 core::{
307 client_registration::ClientRegistrationRequest as ServerClientRegistrationRequest,
308 client_registry::ClientType as ServerClientType,
309 },
310};
311
312// Advanced server modules and RFC implementations
313pub use server::{
314 DpopManager, MetadataProvider, OAuth2Server as ServerOAuth2Server, PARManager,
315 PrivateKeyJwtManager, TokenIntrospectionService,
316};
317
318// Security and authentication module re-exports
319pub use audit::{AuditEvent, AuditEventType, AuditLogger, EventOutcome, RiskLevel};
320pub use authentication::mfa::{MfaManager as LegacyMfaManager, MfaMethodType, TotpProvider};
321pub use authorization::{
322 AccessCondition, AuthorizationEngine, Permission as AuthzPermission, Role as AuthzRole,
323};
324pub use security::secure_jwt::{SecureJwtClaims, SecureJwtConfig, SecureJwtValidator};
325pub use security::secure_mfa::SecureMfaService;
326pub use security::secure_session::{
327 DeviceFingerprint, SecureSession, SecureSessionConfig, SecureSessionManager, SecurityFlags,
328 SessionState as SecureSessionState,
329};
330pub use security::secure_utils::{SecureComparison, SecureRandomGen};
331pub use session::manager::{
332 DeviceInfo, Session, SessionConfig, SessionManager as LegacySessionManager, SessionState,
333};
334pub use utils::rate_limit::RateLimiter;
335
336// Monitoring and metrics
337pub use monitoring::{
338 HealthCheckResult, HealthStatus, MetricDataPoint, MetricType, MonitoringConfig,
339 MonitoringManager, PerformanceMetrics, SecurityEvent, SecurityEventSeverity, SecurityEventType,
340};
341
342// Session coordination stats from auth module
343pub use auth::SessionCoordinationStats;
344
345// Re-export testing utilities when available
346#[cfg(any(test, feature = "testing"))]
347pub use testing::{MockAuthMethod, MockStorage}; // Removed helpers temporarily
348
349// Re-export test infrastructure for bulletproof testing
350#[cfg(any(test, feature = "testing"))]
351pub use testing::{
352 test_infrastructure::{TestEnvironmentGuard, test_data},
353 utilities::*,
354};