pulseengine-mcp-auth 0.16.0

Authentication and authorization framework for MCP servers - PulseEngine MCP Framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! MCP Authentication Middleware
//!
//! This middleware provides comprehensive authentication and authorization
//! for MCP requests, integrating with the AuthenticationManager and
//! permission system.

use crate::{AuthContext, AuthenticationManager, models::Role, security::RequestSecurityValidator};
use async_trait::async_trait;
use pulseengine_mcp_protocol::{Error as McpError, Request, Response};
use std::collections::HashMap;
use std::sync::Arc;
use thiserror::Error;
use tracing::{debug, error, warn};

/// Errors that can occur during authentication extraction
#[derive(Debug, Error)]
pub enum AuthExtractionError {
    #[error("No authentication provided")]
    NoAuth,

    #[error("Invalid authentication format: {0}")]
    InvalidFormat(String),

    #[error("Authentication method not supported: {0}")]
    UnsupportedMethod(String),

    #[error("Missing required header: {0}")]
    MissingHeader(String),
}

/// Configuration for MCP authentication middleware
#[derive(Debug, Clone)]
pub struct McpAuthConfig {
    /// Require authentication for all requests
    pub require_auth: bool,

    /// Allow anonymous access to specific methods
    pub anonymous_methods: Vec<String>,

    /// Methods that require specific roles
    pub method_role_requirements: HashMap<String, Vec<Role>>,

    /// Enable permission checking for tools and resources
    pub enable_permission_checking: bool,

    /// Custom authentication header name (default: "Authorization")
    pub auth_header_name: String,

    /// Enable audit logging for authentication events
    pub enable_audit_logging: bool,

    /// Client IP header name for proxy environments
    pub client_ip_header: Option<String>,
}

impl Default for McpAuthConfig {
    fn default() -> Self {
        Self {
            require_auth: true,
            anonymous_methods: vec!["initialize".to_string(), "ping".to_string()],
            method_role_requirements: HashMap::new(),
            enable_permission_checking: true,
            auth_header_name: "Authorization".to_string(),
            enable_audit_logging: true,
            client_ip_header: Some("X-Forwarded-For".to_string()),
        }
    }
}

/// Authentication context extracted from request
#[derive(Debug, Clone)]
pub struct McpAuthContext {
    /// Authenticated API key context
    pub auth_context: Option<AuthContext>,

    /// Client IP address
    pub client_ip: Option<String>,

    /// Authentication method used
    pub auth_method: Option<String>,

    /// Whether the request is anonymous
    pub is_anonymous: bool,
}

/// Request context that includes authentication and metadata
#[derive(Debug, Clone)]
pub struct McpRequestContext {
    /// Unique request identifier
    pub request_id: String,

    /// Authentication context
    pub auth: McpAuthContext,

    /// Request timestamp
    pub timestamp: chrono::DateTime<chrono::Utc>,

    /// Additional metadata
    pub metadata: HashMap<String, String>,
}

impl McpRequestContext {
    pub fn new(request_id: String) -> Self {
        Self {
            request_id,
            auth: McpAuthContext {
                auth_context: None,
                client_ip: None,
                auth_method: None,
                is_anonymous: true,
            },
            timestamp: chrono::Utc::now(),
            metadata: HashMap::new(),
        }
    }

    pub fn with_auth(mut self, auth_context: AuthContext, auth_method: String) -> Self {
        self.auth.auth_context = Some(auth_context);
        self.auth.auth_method = Some(auth_method);
        self.auth.is_anonymous = false;
        self
    }

    pub fn with_client_ip(mut self, client_ip: String) -> Self {
        self.auth.client_ip = Some(client_ip);
        self
    }
}

/// MCP Authentication Middleware
pub struct McpAuthMiddleware {
    /// Authentication manager for key validation
    auth_manager: Arc<AuthenticationManager>,

    /// Middleware configuration
    config: McpAuthConfig,

    /// Request security validator
    security_validator: Arc<RequestSecurityValidator>,
}

impl McpAuthMiddleware {
    /// Create a new MCP authentication middleware
    pub fn new(auth_manager: Arc<AuthenticationManager>, config: McpAuthConfig) -> Self {
        Self {
            auth_manager,
            config,
            security_validator: Arc::new(RequestSecurityValidator::default()),
        }
    }

    /// Create with custom security validator
    pub fn with_security_validator(
        auth_manager: Arc<AuthenticationManager>,
        config: McpAuthConfig,
        security_validator: Arc<RequestSecurityValidator>,
    ) -> Self {
        Self {
            auth_manager,
            config,
            security_validator,
        }
    }

    /// Create middleware with default configuration
    pub fn with_default_config(auth_manager: Arc<AuthenticationManager>) -> Self {
        Self::new(auth_manager, McpAuthConfig::default())
    }

    /// Get access to the security validator for monitoring violations
    pub fn security_validator(&self) -> &RequestSecurityValidator {
        &self.security_validator
    }

    /// Process an incoming MCP request
    pub async fn process_request(
        &self,
        request: Request,
        headers: Option<&HashMap<String, String>>,
    ) -> Result<(Request, McpRequestContext), McpError> {
        // Step 1: Validate request security first
        if let Err(security_error) = self
            .security_validator
            .validate_request(&request, None)
            .await
        {
            error!("Request security validation failed: {}", security_error);
            return Err(McpError::invalid_request(&format!(
                "Security validation failed: {}",
                security_error
            )));
        }

        // Step 2: Sanitize request if needed
        let sanitized_request = self.security_validator.sanitize_request(request).await;

        let request_id = match &sanitized_request.id {
            Some(id) => id.to_string(),
            None => uuid::Uuid::new_v4().to_string(),
        };
        let mut context = McpRequestContext::new(request_id);

        // Extract client IP if available
        if let Some(headers) = headers {
            if let Some(ip_header) = &self.config.client_ip_header {
                if let Some(client_ip) = headers.get(ip_header) {
                    context = context.with_client_ip(client_ip.clone());
                }
            }
        }

        // Check if authentication is required for this method
        if self.should_skip_auth(&sanitized_request.method) {
            debug!(
                "Skipping authentication for method: {}",
                sanitized_request.method
            );
            return Ok((sanitized_request, context));
        }

        // Extract authentication from headers
        let auth_result = if let Some(headers) = headers {
            self.extract_authentication(headers).await
        } else {
            Err(AuthExtractionError::NoAuth)
        };

        match auth_result {
            Ok((auth_context, auth_method)) => {
                // Authentication successful
                context = context.with_auth(auth_context, auth_method);

                // Check method-specific role requirements
                if let Err(e) = self
                    .check_method_permissions(&sanitized_request.method, &context)
                    .await
                {
                    error!("Method permission check failed: {}", e);
                    return Err(McpError::invalid_request(&format!("Access denied: {}", e)));
                }

                debug!("Request authenticated successfully");
                Ok((sanitized_request, context))
            }
            Err(e) => {
                if self.config.require_auth {
                    warn!("Authentication failed: {}", e);
                    Err(McpError::invalid_request(&format!(
                        "Authentication required: {}",
                        e
                    )))
                } else {
                    debug!("Authentication failed but not required: {}", e);
                    Ok((sanitized_request, context))
                }
            }
        }
    }

    /// Process an outgoing MCP response
    pub async fn process_response(
        &self,
        response: Response,
        _context: &McpRequestContext,
    ) -> Result<Response, McpError> {
        // Add security headers or process response as needed
        // For now, just pass through
        Ok(response)
    }

    /// Extract authentication from request headers
    async fn extract_authentication(
        &self,
        headers: &HashMap<String, String>,
    ) -> Result<(AuthContext, String), AuthExtractionError> {
        // Try to extract from Authorization header
        if let Some(auth_header) = headers.get(&self.config.auth_header_name) {
            return self.parse_auth_header(auth_header).await;
        }

        // Try to extract from X-API-Key header
        if let Some(api_key) = headers.get("X-API-Key") {
            return self.validate_api_key(api_key, "X-API-Key").await;
        }

        Err(AuthExtractionError::NoAuth)
    }

    /// Parse the Authorization header
    async fn parse_auth_header(
        &self,
        auth_header: &str,
    ) -> Result<(AuthContext, String), AuthExtractionError> {
        let parts: Vec<&str> = auth_header.splitn(2, ' ').collect();
        if parts.len() != 2 {
            return Err(AuthExtractionError::InvalidFormat(
                "Authorization header must be in format 'Type Token'".to_string(),
            ));
        }

        let auth_type = parts[0].to_lowercase();
        let token = parts[1];

        match auth_type.as_str() {
            "bearer" => self.validate_api_key(token, "Bearer").await,
            "apikey" => self.validate_api_key(token, "ApiKey").await,
            _ => Err(AuthExtractionError::UnsupportedMethod(auth_type)),
        }
    }

    /// Validate an API key
    async fn validate_api_key(
        &self,
        api_key: &str,
        method: &str,
    ) -> Result<(AuthContext, String), AuthExtractionError> {
        match self.auth_manager.validate_api_key(api_key, None).await {
            Ok(Some(auth_context)) => Ok((auth_context, method.to_string())),
            Ok(None) => Err(AuthExtractionError::InvalidFormat(
                "Invalid API key".to_string(),
            )),
            Err(e) => {
                error!("API key validation failed: {}", e);
                Err(AuthExtractionError::InvalidFormat(
                    "Authentication failed".to_string(),
                ))
            }
        }
    }

    /// Check if authentication should be skipped for a method
    fn should_skip_auth(&self, method: &str) -> bool {
        if !self.config.require_auth {
            return true;
        }

        self.config.anonymous_methods.contains(&method.to_string())
    }

    /// Check method-specific role requirements
    async fn check_method_permissions(
        &self,
        method: &str,
        context: &McpRequestContext,
    ) -> Result<(), String> {
        // If no specific requirements, allow
        if let Some(required_roles) = self.config.method_role_requirements.get(method) {
            if let Some(auth_context) = &context.auth.auth_context {
                // Check if user has one of the required roles
                let has_required_role = auth_context
                    .roles
                    .iter()
                    .any(|role| required_roles.contains(role));
                if !has_required_role {
                    return Err(format!(
                        "Method '{}' requires one of these roles: {:?}, but user has roles: {:?}",
                        method, required_roles, auth_context.roles
                    ));
                }
            } else {
                return Err(format!("Method '{}' requires authentication", method));
            }
        }

        Ok(())
    }
}

/// Trait for middleware that can process MCP requests and responses
#[async_trait]
pub trait McpMiddleware: Send + Sync {
    /// Process an incoming request
    async fn process_request(
        &self,
        request: Request,
        context: &McpRequestContext,
    ) -> Result<Request, McpError>;

    /// Process an outgoing response
    async fn process_response(
        &self,
        response: Response,
        context: &McpRequestContext,
    ) -> Result<Response, McpError>;
}

#[async_trait]
impl McpMiddleware for McpAuthMiddleware {
    async fn process_request(
        &self,
        request: Request,
        _context: &McpRequestContext,
    ) -> Result<Request, McpError> {
        // This implementation assumes context has already been created
        // by the initial process_request call
        Ok(request)
    }

    async fn process_response(
        &self,
        response: Response,
        context: &McpRequestContext,
    ) -> Result<Response, McpError> {
        self.process_response(response, context).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::AuthConfig;

    #[tokio::test]
    async fn test_auth_middleware_creation() {
        let config = AuthConfig::memory();
        let auth_manager = Arc::new(AuthenticationManager::new(config).await.unwrap());
        let middleware = McpAuthMiddleware::with_default_config(auth_manager);

        assert!(!middleware.config.anonymous_methods.is_empty());
        assert!(middleware.config.require_auth);
    }

    #[tokio::test]
    async fn test_anonymous_method_detection() {
        let config = AuthConfig::memory();
        let auth_manager = Arc::new(AuthenticationManager::new(config).await.unwrap());
        let middleware = McpAuthMiddleware::with_default_config(auth_manager);

        assert!(middleware.should_skip_auth("initialize"));
        assert!(middleware.should_skip_auth("ping"));
        assert!(!middleware.should_skip_auth("tools/call"));
    }

    #[tokio::test]
    async fn test_auth_header_parsing() {
        let config = AuthConfig::memory();
        let auth_manager = Arc::new(AuthenticationManager::new(config).await.unwrap());
        let middleware = McpAuthMiddleware::with_default_config(auth_manager);

        // Test invalid format
        let result = middleware.parse_auth_header("invalid").await;
        assert!(result.is_err());

        // Test unsupported method
        let result = middleware.parse_auth_header("Basic token123").await;
        assert!(matches!(
            result,
            Err(AuthExtractionError::UnsupportedMethod(_))
        ));
    }
}