pulseengine_mcp_auth/
lib.rs

1//! # MCP Authentication and Authorization Framework
2//!
3//! A comprehensive, drop-in security framework for Model Context Protocol (MCP) servers
4//! providing enterprise-grade authentication, authorization, session management, and security monitoring.
5//!
6#![allow(clippy::uninlined_format_args)]
7#![allow(clippy::needless_borrows_for_generic_args)]
8#![allow(clippy::manual_strip)]
9#![allow(clippy::redundant_closure)]
10#![allow(clippy::explicit_auto_deref)]
11#![allow(clippy::inherent_to_string)]
12#![allow(clippy::unwrap_or_default)]
13#![allow(clippy::should_implement_trait)]
14#![allow(clippy::redundant_pattern_matching)]
15#![allow(clippy::ptr_arg)]
16#![allow(clippy::new_without_default)]
17//! ## Quick Start
18//!
19//! ### Simple Development Setup
20//!
21//! ```rust,ignore
22//! use pulseengine_mcp_auth::integration::McpIntegrationHelper;
23//!
24//! #[tokio::main]
25//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
26//!     // Quick development setup - minimal security, maximum convenience
27//!     let framework = McpIntegrationHelper::setup_development("my-server".to_string()).await?;
28//!
29//!     // Process authenticated MCP requests
30//!     let (processed_request, auth_context) = framework
31//!         .process_request(request, Some(&headers))
32//!         .await?;
33//!
34//!     Ok(())
35//! }
36//! ```
37//!
38//! ### Production Setup with Admin Key
39//!
40//! ```rust,ignore
41//! use pulseengine_mcp_auth::integration::McpIntegrationHelper;
42//!
43//! #[tokio::main]
44//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
45//!     // Production setup with admin API key creation
46//!     let (framework, admin_key) = McpIntegrationHelper::setup_production(
47//!         "prod-server".to_string(),
48//!         Some("admin-key".to_string()),
49//!     ).await?;
50//!
51//!     if let Some(key) = admin_key {
52//!         println!("Admin API Key: {}", key.secret);
53//!         // Store this key securely for initial access
54//!     }
55//!
56//!     Ok(())
57//! }
58//! ```
59//!
60//! ### Environment-Based Configuration
61//!
62//! ```rust,ignore
63//! use pulseengine_mcp_auth::integration::AuthFramework;
64//!
65//! // Auto-selects appropriate security profile for environment
66//! let framework = AuthFramework::for_environment(
67//!     "my-server".to_string(),
68//!     std::env::var("ENVIRONMENT").unwrap_or("production".to_string()),
69//! ).await?;
70//! ```
71//!
72//! ## Core Features
73//!
74//! ### 🔐 Multi-Layer Authentication
75//! - **API Keys**: Secure token-based authentication with role-based permissions
76//! - **JWT Tokens**: Stateless session tokens with configurable expiration
77//! - **Session Management**: Server-side session tracking with automatic cleanup
78//! - **Transport Agnostic**: HTTP, WebSocket, Stdio, and custom transport support
79//!
80//! ### 🛡️ Authorization & Permissions
81//! - **Role-Based Access Control (RBAC)**: Admin, Operator, Monitor, Device, Custom roles
82//! - **Fine-Grained Permissions**: Resource and tool-level access control
83//! - **Permission Inheritance**: Hierarchical permission systems
84//! - **Dynamic Permission Checking**: Runtime permission validation
85//!
86//! ### 🔒 Request Security
87//! - **Input Validation**: Request size limits, parameter validation
88//! - **Injection Prevention**: SQL, XSS, Command, and Path Traversal detection
89//! - **Request Sanitization**: Automatic content cleaning and escaping
90//! - **Rate Limiting**: Per-method and per-user rate controls
91//!
92//! ### 🗝️ Credential Management
93//! - **Encrypted Storage**: AES-GCM encryption for host credentials
94//! - **Vault Integration**: Enterprise secret management (Infisical)
95//! - **Credential Rotation**: Automatic credential lifecycle management
96//! - **Host Connection Data**: Secure storage of IP, username, password combinations
97//!
98//! ### 📊 Security Monitoring
99//! - **Real-Time Events**: Authentication, authorization, and security events
100//! - **Metrics Collection**: Performance and security metrics
101//! - **Alerting System**: Configurable security alerts and thresholds
102//! - **Security Dashboard**: Web-based monitoring interface
103//!
104//! ## Security Profiles
105//!
106//! The framework includes 8 predefined security profiles optimized for different environments:
107//!
108//! ```rust,ignore
109//! use pulseengine_mcp_auth::integration::{AuthFramework, SecurityProfile};
110//!
111//! // Development: Minimal security, maximum convenience
112//! let dev = AuthFramework::with_security_profile(
113//!     "dev-server".to_string(),
114//!     SecurityProfile::Development,
115//! ).await?;
116//!
117//! // Production: Maximum security and reliability
118//! let prod = AuthFramework::with_security_profile(
119//!     "prod-server".to_string(),
120//!     SecurityProfile::Production,
121//! ).await?;
122//!
123//! // High Security: Compliance-ready with strict controls
124//! let secure = AuthFramework::with_security_profile(
125//!     "secure-server".to_string(),
126//!     SecurityProfile::HighSecurity,
127//! ).await?;
128//!
129//! // IoT Device: Lightweight for resource-constrained environments
130//! let iot = AuthFramework::with_security_profile(
131//!     "iot-device".to_string(),
132//!     SecurityProfile::IoTDevice,
133//! ).await?;
134//! ```
135//!
136//! ## Authentication Examples
137//!
138//! ### Creating API Keys
139//!
140//! ```rust,ignore
141//! use pulseengine_mcp_auth::models::Role;
142//!
143//! // Create API key with specific permissions
144//! let api_key = framework.create_api_key(
145//!     "client-app".to_string(),                    // Key name
146//!     Role::Operator,                              // Role
147//!     Some(vec![                                   // Custom permissions
148//!         "auth:read".to_string(),
149//!         "session:create".to_string(),
150//!         "credential:read".to_string(),
151//!     ]),
152//!     Some(chrono::Utc::now() + chrono::Duration::days(30)), // Expiration
153//!     Some(vec!["192.168.1.0/24".to_string()]),   // IP whitelist
154//! ).await?;
155//!
156//! println!("API Key: {}", api_key.secret);
157//! ```
158//!
159//! ### Processing Authenticated Requests
160//!
161//! ```rust,ignore
162//! use std::collections::HashMap;
163//! use pulseengine_mcp_auth::integration::RequestHelper;
164//!
165//! // Extract API key from request headers
166//! let mut headers = HashMap::new();
167//! headers.insert("Authorization".to_string(), format!("Bearer {}", api_key));
168//!
169//! // Process request with authentication and security validation
170//! match RequestHelper::process_authenticated_request(&framework, request, Some(&headers)).await {
171//!     Ok((processed_request, Some(auth_context))) => {
172//!         // Request is authenticated and validated
173//!         println!("Authenticated user: {:?}", auth_context.user_id);
174//!
175//!         // Check specific permissions
176//!         RequestHelper::validate_request_permissions(&auth_context, "tools:use")?;
177//!
178//!         // Process the request...
179//!     },
180//!     Ok((_, None)) => {
181//!         // Request is not authenticated
182//!         return Err("Authentication required".into());
183//!     },
184//!     Err(e) => {
185//!         // Security validation failed
186//!         return Err(format!("Security violation: {}", e).into());
187//!     }
188//! }
189//! ```
190//!
191//! ## Credential Management Examples
192//!
193//! ### Storing Host Credentials
194//!
195//! ```rust,ignore
196//! use pulseengine_mcp_auth::integration::CredentialHelper;
197//!
198//! // Store host credentials securely (e.g., for Loxone Miniserver)
199//! let credential_id = CredentialHelper::store_validated_credentials(
200//!     &framework,
201//!     "Loxone Miniserver".to_string(),        // Credential name
202//!     "192.168.1.100".to_string(),            // Host IP
203//!     Some(80),                               // Port
204//!     "admin".to_string(),                    // Username
205//!     "secure_password123".to_string(),       // Password
206//!     &auth_context,                          // Authentication context
207//! ).await?;
208//!
209//! println!("Stored credential: {}", credential_id);
210//! ```
211//!
212//! ### Retrieving Host Credentials
213//!
214//! ```rust,ignore
215//! // Retrieve host credentials for connection
216//! let (host_ip, username, password) = CredentialHelper::get_validated_credentials(
217//!     &framework,
218//!     &credential_id,
219//!     &auth_context,
220//! ).await?;
221//!
222//! // Use credentials to connect to host system
223//! println!("Connecting to {}@{}", username, host_ip);
224//! // establish_connection(host_ip, username, password).await?;
225//! ```
226//!
227//! ## Session Management
228//!
229//! ```rust,ignore
230//! use pulseengine_mcp_auth::integration::SessionHelper;
231//!
232//! // Create session with custom duration
233//! let session = SessionHelper::create_validated_session(
234//!     &framework,
235//!     &auth_context,
236//!     Some(chrono::Duration::hours(4))
237//! ).await?;
238//!
239//! println!("Session ID: {}", session.session_id);
240//! println!("JWT Token: {}", session.jwt_token.unwrap_or_default());
241//!
242//! // Validate and refresh session if needed
243//! let refreshed_session = SessionHelper::validate_and_refresh_session(
244//!     &framework,
245//!     &session.session_id
246//! ).await?;
247//! ```
248//!
249//! ## Security Monitoring
250//!
251//! ```rust,ignore
252//! use pulseengine_mcp_auth::integration::MonitoringHelper;
253//! use pulseengine_mcp_auth::monitoring::SecurityEventType;
254//! use pulseengine_mcp_auth::security::SecuritySeverity;
255//!
256//! // Log security events
257//! MonitoringHelper::log_security_event(
258//!     &framework,
259//!     SecurityEventType::AuthSuccess,
260//!     SecuritySeverity::Low,
261//!     "User logged in successfully".to_string(),
262//!     Some(&auth_context),
263//!     Some({
264//!         let mut data = std::collections::HashMap::new();
265//!         data.insert("client_ip".to_string(), "192.168.1.100".to_string());
266//!         data
267//!     }),
268//! ).await;
269//!
270//! // Get framework health status
271//! let health = MonitoringHelper::get_health_summary(&framework).await;
272//! for (component, status) in health {
273//!     println!("{}: {}", component, status);
274//! }
275//! ```
276
277pub mod audit;
278pub mod config;
279pub mod consent;
280pub mod crypto;
281pub mod jwt;
282pub mod manager;
283pub mod manager_vault;
284pub mod middleware;
285pub mod models;
286pub mod monitoring;
287pub mod performance;
288pub mod permissions;
289pub mod security;
290pub mod session;
291pub mod setup;
292pub mod storage;
293pub mod transport;
294pub mod validation;
295pub mod vault;
296
297// Re-export main types
298pub use config::AuthConfig;
299pub use consent::manager::{ConsentConfig, ConsentManager, ConsentStorage, MemoryConsentStorage};
300pub use consent::{
301    ConsentAuditEntry, ConsentError, ConsentRecord, ConsentStatus, ConsentSummary, ConsentType,
302    LegalBasis,
303};
304pub use manager::{
305    AuthenticationManager, RateLimitStats, RoleRateLimitConfig, RoleRateLimitStats,
306    ValidationConfig,
307};
308pub use manager_vault::{VaultAuthManagerError, VaultAuthenticationManager, VaultStatus};
309pub use middleware::{
310    AuthExtractionError, McpAuthConfig, McpAuthMiddleware, SessionMiddleware,
311    SessionMiddlewareConfig, SessionMiddlewareError, SessionRequestContext,
312};
313pub use models::{
314    ApiCompletenessCheck, ApiKey, AuthContext, AuthResult, KeyCreationRequest, KeyUsageStats, Role,
315    SecureApiKey,
316};
317pub use monitoring::{
318    AlertAction, AlertRule, AlertThreshold, MonitoringError, SecurityAlert, SecurityDashboard,
319    SecurityEvent, SecurityEventType, SecurityMetrics, SecurityMonitor, SecurityMonitorConfig,
320    SystemHealth, create_default_alert_rules,
321};
322pub use performance::{PerformanceConfig, PerformanceResults, PerformanceTest, TestOperation};
323pub use permissions::{
324    McpPermission, McpPermissionChecker, PermissionAction, PermissionConfig, PermissionError,
325    PermissionRule, ResourcePermissionConfig, ToolPermissionConfig,
326};
327pub use security::{
328    InputSanitizer, RequestLimitsConfig, RequestSecurityConfig, RequestSecurityValidator,
329    SecurityValidationError, SecurityViolation,
330};
331pub use session::{
332    MemorySessionStorage, Session, SessionConfig, SessionError, SessionManager, SessionStats,
333    SessionStorage,
334};
335pub use storage::{EnvironmentStorage, FileStorage, StorageBackend};
336pub use transport::{
337    AuthExtractionResult, AuthExtractor, HttpAuthConfig, HttpAuthExtractor, StdioAuthConfig,
338    StdioAuthExtractor, TransportAuthContext, WebSocketAuthConfig, WebSocketAuthExtractor,
339};
340pub use vault::{VaultClientInfo, VaultConfig, VaultError, VaultIntegration, VaultType};
341
342/// Initialize default authentication configuration
343pub fn default_config() -> AuthConfig {
344    AuthConfig::default()
345}
346
347/// Initialize application-specific authentication configuration
348pub fn for_application(app_name: &str) -> AuthConfig {
349    AuthConfig::for_application(app_name)
350}
351
352/// Create an authentication manager with default configuration
353pub async fn create_auth_manager() -> Result<AuthenticationManager, crate::manager::AuthError> {
354    AuthenticationManager::new(default_config()).await
355}
356
357/// Create an authentication manager with application-specific configuration
358pub async fn create_auth_manager_for_application(
359    app_name: &str,
360) -> Result<AuthenticationManager, crate::manager::AuthError> {
361    AuthenticationManager::new(for_application(app_name)).await
362}