llm-shield-api 0.1.0

Production-grade REST API for LLM Shield
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Scan handlers

use crate::models::{ApiError, BatchScanRequest, ScanOutputRequest, ScanPromptRequest};
use crate::services::ScannerService;
use crate::state::AppState;
use axum::{extract::State, http::StatusCode, response::IntoResponse, Json};
use llm_shield_core::ScannerType;
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::Semaphore;
use validator::Validate;

/// POST /v1/scan/prompt - Scan user prompt
///
/// Executes all requested input scanners on the provided prompt.
///
/// ## Request Body
/// ```json
/// {
///   "prompt": "User prompt text to scan",
///   "scanners": ["toxicity", "secrets"],  // Optional, empty = all input scanners
///   "cacheEnabled": true                   // Optional, default true
/// }
/// ```
///
/// ## Response
/// ```json
/// {
///   "isValid": true,
///   "riskScore": 0.0,
///   "sanitizedText": "...",
///   "scannerResults": [...],
///   "scanTimeMs": 50,
///   "cacheHit": false
/// }
/// ```
pub async fn scan_prompt(
    State(state): State<AppState>,
    Json(req): Json<ScanPromptRequest>,
) -> Result<impl IntoResponse, ApiError> {
    // Validate request
    req.validate()
        .map_err(|e| ApiError::ValidationError(e.to_string()))?;

    let start = Instant::now();

    // Check cache if enabled
    if req.cache_enabled {
        let cache_key = format!("prompt:{}", req.prompt);
        if let Some(_cached_result) = state.cache.get(&cache_key) {
            // TODO: Deserialize cached ScanResponse
            // For now, fall through to actual scan
        }
    }

    // Determine which scanners to run
    let scanners_to_run = if req.scanners.is_empty() {
        // Get all input scanners
        state
            .scanners
            .values()
            .filter(|s| matches!(s.scanner_type(), ScannerType::Input | ScannerType::Bidirectional))
            .cloned()
            .collect()
    } else {
        // Get requested scanners
        let mut scanners = Vec::new();
        for scanner_name in &req.scanners {
            match state.get_scanner(scanner_name) {
                Some(scanner) => scanners.push(scanner),
                None => {
                    return Err(ApiError::NotFound(format!(
                        "Scanner not found: {}",
                        scanner_name
                    )))
                }
            }
        }
        scanners
    };

    if scanners_to_run.is_empty() {
        return Err(ApiError::InvalidRequest(
            "No scanners available or requested".to_string(),
        ));
    }

    // Execute scanners
    let scanner_service = ScannerService::new();
    let scanner_results = scanner_service
        .execute_scanners(scanners_to_run, &req.prompt)
        .await
        .map_err(|e| ApiError::ScannerError(e))?;

    let scan_time_ms = start.elapsed().as_millis() as u64;

    // Create response
    let response = scanner_service.create_scan_response(scanner_results, scan_time_ms, false);

    // Cache result if enabled
    if req.cache_enabled {
        // TODO: Cache the response
    }

    Ok((StatusCode::OK, Json(response)))
}

/// POST /v1/scan/output - Scan LLM output
///
/// Executes all requested output scanners on the provided LLM output.
/// The prompt is provided for context but output is what gets scanned.
///
/// ## Request Body
/// ```json
/// {
///   "prompt": "User prompt text",
///   "output": "LLM response to scan",
///   "scanners": ["malicious_urls", "sensitive"],  // Optional, empty = all output scanners
///   "cacheEnabled": true                          // Optional, default true
/// }
/// ```
///
/// ## Response
/// ```json
/// {
///   "isValid": true,
///   "riskScore": 0.0,
///   "sanitizedText": "...",
///   "scannerResults": [...],
///   "scanTimeMs": 50,
///   "cacheHit": false
/// }
/// ```
pub async fn scan_output(
    State(state): State<AppState>,
    Json(req): Json<ScanOutputRequest>,
) -> Result<impl IntoResponse, ApiError> {
    // Validate request
    req.validate()
        .map_err(|e| ApiError::ValidationError(e.to_string()))?;

    let start = Instant::now();

    // Check cache if enabled
    if req.cache_enabled {
        let cache_key = format!("output:{}:{}", req.prompt, req.output);
        if let Some(_cached_result) = state.cache.get(&cache_key) {
            // TODO: Deserialize cached ScanResponse
            // For now, fall through to actual scan
        }
    }

    // Determine which scanners to run
    let scanners_to_run = if req.scanners.is_empty() {
        // Get all output scanners
        state
            .scanners
            .values()
            .filter(|s| matches!(s.scanner_type(), ScannerType::Output | ScannerType::Bidirectional))
            .cloned()
            .collect()
    } else {
        // Get requested scanners
        let mut scanners = Vec::new();
        for scanner_name in &req.scanners {
            match state.get_scanner(scanner_name) {
                Some(scanner) => scanners.push(scanner),
                None => {
                    return Err(ApiError::NotFound(format!(
                        "Scanner not found: {}",
                        scanner_name
                    )))
                }
            }
        }
        scanners
    };

    if scanners_to_run.is_empty() {
        return Err(ApiError::InvalidRequest(
            "No scanners available or requested".to_string(),
        ));
    }

    // Execute scanners on output (prompt available for context)
    // TODO: Pass prompt as context to scanners that need it
    let scanner_service = ScannerService::new();
    let scanner_results = scanner_service
        .execute_scanners(scanners_to_run, &req.output)
        .await
        .map_err(|e| ApiError::ScannerError(e))?;

    let scan_time_ms = start.elapsed().as_millis() as u64;

    // Create response
    let response = scanner_service.create_scan_response(scanner_results, scan_time_ms, false);

    // Cache result if enabled
    if req.cache_enabled {
        // TODO: Cache the response
    }

    Ok((StatusCode::OK, Json(response)))
}

/// POST /v1/scan/batch - Scan multiple prompts in parallel
///
/// Executes scans on multiple prompts with controlled concurrency.
///
/// ## Request Body
/// ```json
/// {
///   "items": [
///     {
///       "prompt": "First prompt",
///       "scanners": [],
///       "cacheEnabled": true
///     },
///     {
///       "prompt": "Second prompt",
///       "scanners": ["toxicity"],
///       "cacheEnabled": false
///     }
///   ],
///   "maxConcurrent": 5  // Optional, default 5
/// }
/// ```
///
/// ## Response
/// ```json
/// {
///   "results": [...],
///   "totalTimeMs": 150,
///   "successCount": 2,
///   "failureCount": 0
/// }
/// ```
pub async fn scan_batch(
    State(state): State<AppState>,
    Json(req): Json<BatchScanRequest>,
) -> Result<impl IntoResponse, ApiError> {
    // Validate request
    req.validate()
        .map_err(|e| ApiError::ValidationError(e.to_string()))?;

    let start = Instant::now();

    // Create semaphore for concurrency control
    let semaphore = Arc::new(Semaphore::new(req.max_concurrent));
    let mut handles = Vec::new();

    // Spawn tasks for each item
    for item in req.items {
        let state = state.clone();
        let semaphore = semaphore.clone();

        let handle = tokio::spawn(async move {
            // Acquire semaphore permit
            let _permit = semaphore.acquire().await.unwrap();

            // Process individual scan prompt
            let result = process_scan_prompt_internal(&state, item).await;
            result
        });

        handles.push(handle);
    }

    // Collect results
    let mut results = Vec::new();
    let mut success_count = 0;
    let mut failure_count = 0;

    for handle in handles {
        match handle.await {
            Ok(Ok(scan_response)) => {
                results.push(scan_response);
                success_count += 1;
            }
            Ok(Err(e)) => {
                // For failed scans, we could create an error response
                // For now, just count the failure
                failure_count += 1;
                // Log error but continue processing
                eprintln!("Scan failed: {:?}", e);
            }
            Err(e) => {
                // Task join error
                failure_count += 1;
                eprintln!("Task join error: {:?}", e);
            }
        }
    }

    let total_time_ms = start.elapsed().as_millis() as u64;

    let response = crate::models::response::BatchScanResponse {
        results,
        total_time_ms,
        success_count,
        failure_count,
    };

    Ok((StatusCode::OK, Json(response)))
}

/// Internal helper to process a single scan prompt
async fn process_scan_prompt_internal(
    state: &AppState,
    req: ScanPromptRequest,
) -> Result<crate::models::response::ScanResponse, String> {
    // Validate request
    req.validate()
        .map_err(|e| format!("Validation error: {}", e))?;

    let start = Instant::now();

    // Determine which scanners to run
    let scanners_to_run = if req.scanners.is_empty() {
        // Get all input scanners
        state
            .scanners
            .values()
            .filter(|s| matches!(s.scanner_type(), ScannerType::Input | ScannerType::Bidirectional))
            .cloned()
            .collect()
    } else {
        // Get requested scanners
        let mut scanners = Vec::new();
        for scanner_name in &req.scanners {
            match state.get_scanner(scanner_name) {
                Some(scanner) => scanners.push(scanner),
                None => {
                    return Err(format!("Scanner not found: {}", scanner_name));
                }
            }
        }
        scanners
    };

    if scanners_to_run.is_empty() {
        return Err("No scanners available or requested".to_string());
    }

    // Execute scanners
    let scanner_service = ScannerService::new();
    let scanner_results = scanner_service
        .execute_scanners(scanners_to_run, &req.prompt)
        .await?;

    let scan_time_ms = start.elapsed().as_millis() as u64;

    // Create response
    let response = scanner_service.create_scan_response(scanner_results, scan_time_ms, false);

    Ok(response)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::AppStateBuilder;
    use llm_shield_core::{async_trait, Result, ScanResult, Scanner, Vault};
    use std::sync::Arc;

    struct MockScanner {
        name: String,
        is_valid: bool,
        risk_score: f32,
        scanner_type: ScannerType,
    }

    #[async_trait]
    impl Scanner for MockScanner {
        fn name(&self) -> &str {
            &self.name
        }

        async fn scan(&self, input: &str, _vault: &Vault) -> Result<ScanResult> {
            Ok(ScanResult::new(
                input.to_string(),
                self.is_valid,
                self.risk_score,
            ))
        }

        fn scanner_type(&self) -> ScannerType {
            self.scanner_type
        }
    }

    fn create_test_state() -> AppState {
        let config = crate::config::AppConfig::default();
        AppStateBuilder::new(config)
            .register_scanner(Arc::new(MockScanner {
                name: "toxicity".to_string(),
                is_valid: true,
                risk_score: 0.0,
                scanner_type: ScannerType::Input,
            }))
            .register_scanner(Arc::new(MockScanner {
                name: "secrets".to_string(),
                is_valid: true,
                risk_score: 0.0,
                scanner_type: ScannerType::Input,
            }))
            .build()
    }

    #[tokio::test]
    async fn test_scan_prompt_valid_request() {
        let state = create_test_state();
        let req = ScanPromptRequest {
            prompt: "Hello world".to_string(),
            scanners: vec!["toxicity".to_string()],
            cache_enabled: false,
        };

        let result = scan_prompt(State(state), Json(req)).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_scan_prompt_empty_prompt() {
        let state = create_test_state();
        let req = ScanPromptRequest {
            prompt: "".to_string(),
            scanners: vec![],
            cache_enabled: false,
        };

        let result = scan_prompt(State(state), Json(req)).await;

        assert!(result.is_err());
        let err = result.err().unwrap();
        match err {
            ApiError::ValidationError(_) => {}
            _ => panic!("Expected ValidationError"),
        }
    }

    #[tokio::test]
    async fn test_scan_prompt_nonexistent_scanner() {
        let state = create_test_state();
        let req = ScanPromptRequest {
            prompt: "Test".to_string(),
            scanners: vec!["nonexistent".to_string()],
            cache_enabled: false,
        };

        let result = scan_prompt(State(state), Json(req)).await;

        assert!(result.is_err());
        let err = result.err().unwrap();
        match err {
            ApiError::NotFound(_) => {}
            _ => panic!("Expected NotFound error"),
        }
    }

    #[tokio::test]
    async fn test_scan_prompt_all_scanners() {
        let state = create_test_state();
        let req = ScanPromptRequest {
            prompt: "Test prompt".to_string(),
            scanners: vec![], // Empty = all scanners
            cache_enabled: false,
        };

        let result = scan_prompt(State(state), Json(req)).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_scan_prompt_multiple_scanners() {
        let state = create_test_state();
        let req = ScanPromptRequest {
            prompt: "Test prompt".to_string(),
            scanners: vec!["toxicity".to_string(), "secrets".to_string()],
            cache_enabled: false,
        };

        let result = scan_prompt(State(state), Json(req)).await;

        assert!(result.is_ok());
    }

    // Tests for scan_output

    fn create_output_scanner_state() -> AppState {
        let config = crate::config::AppConfig::default();
        AppStateBuilder::new(config)
            .register_scanner(Arc::new(MockScanner {
                name: "malicious_urls".to_string(),
                is_valid: true,
                risk_score: 0.0,
                scanner_type: ScannerType::Output,
            }))
            .register_scanner(Arc::new(MockScanner {
                name: "sensitive".to_string(),
                is_valid: true,
                risk_score: 0.0,
                scanner_type: ScannerType::Output,
            }))
            .build()
    }

    #[tokio::test]
    async fn test_scan_output_valid_request() {
        let state = create_output_scanner_state();
        let req = ScanOutputRequest {
            prompt: "What is the capital of France?".to_string(),
            output: "The capital of France is Paris.".to_string(),
            scanners: vec!["malicious_urls".to_string()],
            cache_enabled: false,
        };

        let result = scan_output(State(state), Json(req)).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_scan_output_empty_prompt() {
        let state = create_output_scanner_state();
        let req = ScanOutputRequest {
            prompt: "".to_string(),
            output: "Some output".to_string(),
            scanners: vec![],
            cache_enabled: false,
        };

        let result = scan_output(State(state), Json(req)).await;

        assert!(result.is_err());
        let err = result.err().unwrap();
        match err {
            ApiError::ValidationError(_) => {}
            _ => panic!("Expected ValidationError"),
        }
    }

    #[tokio::test]
    async fn test_scan_output_empty_output() {
        let state = create_output_scanner_state();
        let req = ScanOutputRequest {
            prompt: "Test prompt".to_string(),
            output: "".to_string(),
            scanners: vec![],
            cache_enabled: false,
        };

        let result = scan_output(State(state), Json(req)).await;

        assert!(result.is_err());
        let err = result.err().unwrap();
        match err {
            ApiError::ValidationError(_) => {}
            _ => panic!("Expected ValidationError"),
        }
    }

    #[tokio::test]
    async fn test_scan_output_nonexistent_scanner() {
        let state = create_output_scanner_state();
        let req = ScanOutputRequest {
            prompt: "Test prompt".to_string(),
            output: "Test output".to_string(),
            scanners: vec!["nonexistent".to_string()],
            cache_enabled: false,
        };

        let result = scan_output(State(state), Json(req)).await;

        assert!(result.is_err());
        let err = result.err().unwrap();
        match err {
            ApiError::NotFound(_) => {}
            _ => panic!("Expected NotFound error"),
        }
    }

    #[tokio::test]
    async fn test_scan_output_all_scanners() {
        let state = create_output_scanner_state();
        let req = ScanOutputRequest {
            prompt: "Test prompt".to_string(),
            output: "Test output".to_string(),
            scanners: vec![], // Empty = all output scanners
            cache_enabled: false,
        };

        let result = scan_output(State(state), Json(req)).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_scan_output_multiple_scanners() {
        let state = create_output_scanner_state();
        let req = ScanOutputRequest {
            prompt: "Test prompt".to_string(),
            output: "Test output".to_string(),
            scanners: vec!["malicious_urls".to_string(), "sensitive".to_string()],
            cache_enabled: false,
        };

        let result = scan_output(State(state), Json(req)).await;

        assert!(result.is_ok());
    }

    // Tests for scan_batch

    #[tokio::test]
    async fn test_scan_batch_valid_request() {
        let state = create_test_state();
        let req = BatchScanRequest {
            items: vec![
                ScanPromptRequest {
                    prompt: "First prompt".to_string(),
                    scanners: vec!["toxicity".to_string()],
                    cache_enabled: false,
                },
                ScanPromptRequest {
                    prompt: "Second prompt".to_string(),
                    scanners: vec!["secrets".to_string()],
                    cache_enabled: false,
                },
            ],
            max_concurrent: 2,
        };

        let result = scan_batch(State(state), Json(req)).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_scan_batch_empty_items() {
        let state = create_test_state();
        let req = BatchScanRequest {
            items: vec![],
            max_concurrent: 2,
        };

        let result = scan_batch(State(state), Json(req)).await;

        assert!(result.is_err());
        let err = result.err().unwrap();
        match err {
            ApiError::ValidationError(_) => {}
            _ => panic!("Expected ValidationError"),
        }
    }

    #[tokio::test]
    async fn test_scan_batch_invalid_concurrency() {
        let state = create_test_state();
        let req = BatchScanRequest {
            items: vec![ScanPromptRequest {
                prompt: "Test".to_string(),
                scanners: vec![],
                cache_enabled: false,
            }],
            max_concurrent: 0, // Invalid: must be >= 1
        };

        let result = scan_batch(State(state), Json(req)).await;

        assert!(result.is_err());
        let err = result.err().unwrap();
        match err {
            ApiError::ValidationError(_) => {}
            _ => panic!("Expected ValidationError"),
        }
    }

    #[tokio::test]
    async fn test_scan_batch_multiple_items() {
        let state = create_test_state();
        let items = (0..5)
            .map(|i| ScanPromptRequest {
                prompt: format!("Prompt {}", i),
                scanners: vec![],
                cache_enabled: false,
            })
            .collect();

        let req = BatchScanRequest {
            items,
            max_concurrent: 3,
        };

        let result = scan_batch(State(state), Json(req)).await;

        assert!(result.is_ok());
    }
}