ramparts 0.6.8

A CLI tool for scanning Model Context Protocol (MCP) servers
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
use crate::config::{ScannerConfig, ScannerConfigManager};
use crate::scanner::MCPScanner;
use crate::types::{config_utils, ScanConfigBuilder, ScanOptions, ScanResult};
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::warn;

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ScanRequest {
    pub url: String,
    pub timeout: Option<u64>,
    pub http_timeout: Option<u64>,
    pub detailed: Option<bool>,
    pub format: Option<String>,
    pub auth_headers: Option<HashMap<String, String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanResponse {
    pub success: bool,
    pub result: Option<ScanResult>,
    pub error: Option<String>,
    pub timestamp: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchScanRequest {
    pub urls: Vec<String>,
    pub options: Option<ScanRequest>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchScanResponse {
    pub success: bool,
    pub results: Vec<ScanResponse>,
    pub total: usize,
    pub successful: usize,
    pub failed: usize,
    pub timestamp: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResponse {
    pub success: bool,
    pub valid: bool,
    pub error: Option<String>,
    pub timestamp: String,
}

pub struct MCPScannerCore {
    scanner: MCPScanner,
    config_manager: ScannerConfigManager,
}

impl MCPScannerCore {
    pub fn new() -> Result<Self> {
        let config_manager = ScannerConfigManager::new();
        let scanner_config = match config_manager.load_config() {
            Ok(config) => config,
            Err(e) => {
                warn!("Failed to load scanner config, using defaults: {}", e);
                ScannerConfig::default()
            }
        };

        Ok(Self {
            scanner: MCPScanner::with_timeout(scanner_config.scanner.http_timeout)?,
            config_manager,
        })
    }

    /// Parse scan options from request parameters
    fn parse_scan_options(&self, request: &ScanRequest) -> ScanOptions {
        let scanner_config = self.config_manager.load_config().unwrap_or_default();

        let mut builder = ScanConfigBuilder::new()
            .timeout(
                request
                    .timeout
                    .unwrap_or(scanner_config.scanner.scan_timeout),
            )
            .http_timeout(
                request
                    .http_timeout
                    .unwrap_or(scanner_config.scanner.http_timeout),
            )
            .detailed(request.detailed.unwrap_or(scanner_config.scanner.detailed))
            .format(
                request
                    .format
                    .clone()
                    .unwrap_or(scanner_config.scanner.format),
            );

        // Handle auth headers with minimal conversion for Javelin API key
        if let Some(auth_headers) = &request.auth_headers {
            let mut headers = auth_headers.clone();

            // If we have x-javelin-api-key, add the formats that work with Javelin MCP
            if let Some(api_key) = auth_headers.get("x-javelin-api-key") {
                // Only proceed if the API key is not empty
                if !api_key.trim().is_empty() {
                    // Add x-javelin-apikey format
                    headers.insert("x-javelin-apikey".to_string(), api_key.clone());

                    // Only add authorization header if one doesn't already exist (case-insensitive check)
                    let has_auth_header = headers
                        .keys()
                        .any(|key| key.to_lowercase() == "authorization");
                    if !has_auth_header {
                        headers.insert("authorization".to_string(), format!("Bearer {api_key}"));
                    }
                }
            }

            builder = builder.auth_headers(Some(headers));
        }

        builder.build()
    }

    /// Perform a scan with the given options
    pub async fn scan(&self, request: ScanRequest) -> ScanResponse {
        let timestamp = chrono::Utc::now().to_rfc3339();

        match self.perform_scan_internal(request).await {
            Ok(result) => ScanResponse {
                success: true,
                result: Some(result),
                error: None,
                timestamp,
            },
            Err(e) => ScanResponse {
                success: false,
                result: None,
                error: Some(e.to_string()),
                timestamp,
            },
        }
    }

    /// Internal scan implementation
    async fn perform_scan_internal(&self, request: ScanRequest) -> Result<ScanResult> {
        // Parse and validate options
        let scan_options = self.parse_scan_options(&request);

        // Validate configuration
        config_utils::validate_scan_config(&scan_options)
            .map_err(|e| anyhow!("Configuration validation failed: {}", e))?;

        // Perform scan
        let result = self.scanner.scan_single(&request.url, scan_options).await?;
        Ok(result)
    }

    /// Validate scan configuration
    pub fn validate_config(&self, request: &ScanRequest) -> ValidationResponse {
        let timestamp = chrono::Utc::now().to_rfc3339();

        let options = self.parse_scan_options(request); // No conversion for validation
        match config_utils::validate_scan_config(&options) {
            Ok(()) => ValidationResponse {
                success: true,
                valid: true,
                error: None,
                timestamp,
            },
            Err(e) => ValidationResponse {
                success: false,
                valid: false,
                error: Some(e.to_string()),
                timestamp,
            },
        }
    }

    /// Perform batch scan of multiple URLs
    pub async fn batch_scan(&self, request: BatchScanRequest) -> BatchScanResponse {
        let timestamp = chrono::Utc::now().to_rfc3339();
        let mut results = Vec::new();

        // Process URLs sequentially to avoid overwhelming servers
        let default_options = request.options.clone().unwrap_or_default();
        for url in &request.urls {
            let scan_request = ScanRequest {
                url: url.clone(),
                ..default_options.clone()
            };

            let response = self.scan(scan_request).await;
            results.push(response);
        }

        let successful = results.iter().filter(|r| r.success).count();
        let failed = results.len() - successful;

        BatchScanResponse {
            success: failed == 0, // Set success to false if any scans failed
            results,
            total: request.urls.len(),
            successful,
            failed,
            timestamp,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_scan_request_creation() {
        let request = ScanRequest {
            url: "http://example.com".to_string(),
            timeout: Some(60),
            http_timeout: Some(30),
            detailed: Some(true),
            format: Some("json".to_string()),
            auth_headers: Some(HashMap::from([(
                "Authorization".to_string(),
                "Bearer token".to_string(),
            )])),
        };

        assert_eq!(request.url, "http://example.com");
        assert_eq!(request.timeout, Some(60));
        assert_eq!(request.http_timeout, Some(30));
        assert_eq!(request.detailed, Some(true));
        assert_eq!(request.format, Some("json".to_string()));
        assert!(request.auth_headers.is_some());
    }

    #[test]
    fn test_scan_request_default() {
        let request = ScanRequest::default();
        assert_eq!(request.url, "");
        assert_eq!(request.timeout, None);
        assert_eq!(request.http_timeout, None);
        assert_eq!(request.detailed, None);
        assert_eq!(request.format, None);
        assert_eq!(request.auth_headers, None);
    }

    #[test]
    fn test_scan_response_creation() {
        let result = ScanResult::new("http://example.com".to_string());
        let response = ScanResponse {
            success: true,
            result: Some(result),
            error: None,
            timestamp: "2024-01-01T00:00:00Z".to_string(),
        };

        assert!(response.success);
        assert!(response.result.is_some());
        assert!(response.error.is_none());
        assert_eq!(response.timestamp, "2024-01-01T00:00:00Z");
    }

    #[test]
    fn test_scan_response_error() {
        let response = ScanResponse {
            success: false,
            result: None,
            error: Some("Test error".to_string()),
            timestamp: "2024-01-01T00:00:00Z".to_string(),
        };

        assert!(!response.success);
        assert!(response.result.is_none());
        assert_eq!(response.error, Some("Test error".to_string()));
    }

    #[test]
    fn test_batch_scan_request() {
        let urls = vec![
            "http://example1.com".to_string(),
            "http://example2.com".to_string(),
        ];
        let options = ScanRequest {
            url: String::new(),
            timeout: Some(60),
            http_timeout: Some(30),
            detailed: Some(false),
            format: Some("text".to_string()),
            auth_headers: None,
        };

        let request = BatchScanRequest {
            urls: urls.clone(),
            options: Some(options),
        };

        assert_eq!(request.urls.len(), 2);
        assert_eq!(request.urls[0], "http://example1.com");
        assert_eq!(request.urls[1], "http://example2.com");
        assert!(request.options.is_some());
    }

    #[test]
    fn test_batch_scan_response() {
        let results = vec![
            ScanResponse {
                success: true,
                result: Some(ScanResult::new("http://example1.com".to_string())),
                error: None,
                timestamp: "2024-01-01T00:00:00Z".to_string(),
            },
            ScanResponse {
                success: false,
                result: None,
                error: Some("Failed".to_string()),
                timestamp: "2024-01-01T00:00:01Z".to_string(),
            },
        ];

        let response = BatchScanResponse {
            success: false, // Should be false when there are failures
            results: results.clone(),
            total: 2,
            successful: 1,
            failed: 1,
            timestamp: "2024-01-01T00:00:02Z".to_string(),
        };

        assert!(!response.success); // Should be false when there are failures
        assert_eq!(response.results.len(), 2);
        assert_eq!(response.total, 2);
        assert_eq!(response.successful, 1);
        assert_eq!(response.failed, 1);
    }

    #[test]
    fn test_batch_scan_response_all_successful() {
        let results = vec![
            ScanResponse {
                success: true,
                result: Some(ScanResult::new("http://example1.com".to_string())),
                error: None,
                timestamp: "2024-01-01T00:00:00Z".to_string(),
            },
            ScanResponse {
                success: true,
                result: Some(ScanResult::new("http://example2.com".to_string())),
                error: None,
                timestamp: "2024-01-01T00:00:01Z".to_string(),
            },
        ];

        let response = BatchScanResponse {
            success: true, // Should be true when all scans are successful
            results: results.clone(),
            total: 2,
            successful: 2,
            failed: 0,
            timestamp: "2024-01-01T00:00:02Z".to_string(),
        };

        assert!(response.success); // Should be true when all scans are successful
        assert_eq!(response.results.len(), 2);
        assert_eq!(response.total, 2);
        assert_eq!(response.successful, 2);
        assert_eq!(response.failed, 0);
    }

    #[test]
    fn test_validation_response() {
        let response = ValidationResponse {
            success: true,
            valid: true,
            error: None,
            timestamp: "2024-01-01T00:00:00Z".to_string(),
        };

        assert!(response.success);
        assert!(response.valid);
        assert!(response.error.is_none());
        assert_eq!(response.timestamp, "2024-01-01T00:00:00Z");
    }

    #[test]
    fn test_validation_response_invalid() {
        let response = ValidationResponse {
            success: false,
            valid: false,
            error: Some("Invalid configuration".to_string()),
            timestamp: "2024-01-01T00:00:00Z".to_string(),
        };

        assert!(!response.success);
        assert!(!response.valid);
        assert_eq!(response.error, Some("Invalid configuration".to_string()));
    }

    #[test]
    fn test_mcp_scanner_core_creation() {
        let core = MCPScannerCore::new();
        assert!(core.is_ok());
    }

    #[test]
    fn test_parse_scan_options() {
        let core = MCPScannerCore::new().unwrap();
        let request = ScanRequest {
            url: "http://example.com".to_string(),
            timeout: Some(120),
            http_timeout: Some(60),
            detailed: Some(true),
            format: Some("json".to_string()),
            auth_headers: Some(HashMap::from([(
                "Authorization".to_string(),
                "Bearer token".to_string(),
            )])),
        };

        let options = core.parse_scan_options(&request); // No conversion for test
        assert_eq!(options.timeout, 120);
        assert_eq!(options.http_timeout, 60);
        assert!(options.detailed);
        assert_eq!(options.format, "json");
        assert!(options.auth_headers.is_some());
    }

    #[test]
    fn test_parse_scan_options_with_defaults() {
        let core = MCPScannerCore::new().unwrap();
        let request = ScanRequest {
            url: "http://example.com".to_string(),
            timeout: None,
            http_timeout: None,
            detailed: None,
            format: None,
            auth_headers: None,
        };

        let options = core.parse_scan_options(&request); // No conversion for test
                                                         // These will use default values from config
        assert!(options.timeout > 0);
        assert!(options.http_timeout > 0);
        assert!(!options.detailed); // Default is false
        assert_eq!(options.format, "table"); // Default is table
        assert!(options.auth_headers.is_none());
    }
}