litellm-rs 0.4.16

A high-performance AI Gateway written in Rust, providing OpenAI-compatible APIs with intelligent routing, load balancing, and enterprise features
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
//! PII (Personally Identifiable Information) detection and masking
//!
//! This module provides detection and masking of PII in text content.

use async_trait::async_trait;
use regex::Regex;
use std::collections::HashMap;

use super::config::PIIConfig;
use super::traits::Guardrail;
use super::types::{
    CheckResult, GuardrailAction, GuardrailError, GuardrailResult, PIIMatch, PIIType, Violation,
    ViolationType,
};

/// PII detection and masking guardrail
pub struct PIIGuardrail {
    config: PIIConfig,
    patterns: HashMap<PIIType, Regex>,
}

impl PIIGuardrail {
    /// Create a new PII guardrail
    pub fn new(config: PIIConfig) -> GuardrailResult<Self> {
        let mut patterns = HashMap::new();

        // Build regex patterns for each PII type
        for pii_type in config.effective_types() {
            if let Some(pattern) = Self::get_pattern(&pii_type) {
                let regex = Regex::new(pattern).map_err(|e| {
                    GuardrailError::Config(format!("Invalid regex for {:?}: {}", pii_type, e))
                })?;
                patterns.insert(pii_type, regex);
            }
        }

        Ok(Self { config, patterns })
    }

    /// Get the regex pattern for a PII type
    fn get_pattern(pii_type: &PIIType) -> Option<&'static str> {
        match pii_type {
            PIIType::Email => Some(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"),
            PIIType::Phone => Some(r"\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b"),
            PIIType::CreditCard => Some(r"\b(?:\d{4}[-\s]?){3}\d{4}\b"),
            PIIType::SSN => Some(r"\b\d{3}[-\s]?\d{2}[-\s]?\d{4}\b"),
            PIIType::IpAddress => Some(
                r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b",
            ),
            PIIType::DateOfBirth => {
                Some(r"\b(?:0?[1-9]|1[0-2])[/\-](?:0?[1-9]|[12]\d|3[01])[/\-](?:19|20)\d{2}\b")
            }
            PIIType::Passport => Some(r"\b[A-Z]{1,2}\d{6,9}\b"),
            PIIType::DriversLicense => Some(r"\b[A-Z]{1,2}\d{5,8}\b"),
            PIIType::BankAccount => Some(r"\b\d{8,17}\b"),
            PIIType::Address => None, // Too complex for simple regex
            PIIType::Name => None,    // Requires NER
            PIIType::Custom(_) => None,
        }
    }

    /// Detect PII in text
    pub fn detect(&self, text: &str) -> Vec<PIIMatch> {
        let mut matches = Vec::new();

        for (pii_type, regex) in &self.patterns {
            for m in regex.find_iter(text) {
                let matched_text = m.as_str().to_string();

                // Check allow list
                if self.is_allowed(&matched_text) {
                    continue;
                }

                matches.push(PIIMatch::new(
                    pii_type.clone(),
                    m.start(),
                    m.end(),
                    matched_text,
                ));
            }
        }

        // Sort by position
        matches.sort_by_key(|m| m.start);
        matches
    }

    /// Check if a match is in the allow list
    fn is_allowed(&self, text: &str) -> bool {
        self.config
            .allow_list
            .iter()
            .any(|allowed| text.eq_ignore_ascii_case(allowed))
    }

    /// Mask PII in text
    pub fn mask(&self, text: &str, matches: &[PIIMatch]) -> String {
        if matches.is_empty() {
            return text.to_string();
        }

        let mut result = text.to_string();

        // Process matches in reverse order to preserve positions
        for m in matches.iter().rev() {
            let mask = self.get_mask(m);
            result.replace_range(m.start..m.end, &mask);
        }

        result
    }

    /// Get the mask string for a PII match
    fn get_mask(&self, pii_match: &PIIMatch) -> String {
        if let Some(ref pattern) = self.config.mask_pattern {
            pattern.clone()
        } else {
            // Create mask of same length
            let len = pii_match.end - pii_match.start;
            self.config.mask_char.to_string().repeat(len)
        }
    }

    /// Create violations from PII matches
    fn create_violations(&self, matches: &[PIIMatch]) -> Vec<Violation> {
        matches
            .iter()
            .map(|m| {
                Violation::new(
                    ViolationType::PII(m.pii_type.clone()),
                    format!("{:?} detected", m.pii_type),
                )
                .with_location(m.start, m.end)
                .with_severity(m.confidence)
            })
            .collect()
    }
}

#[async_trait]
impl Guardrail for PIIGuardrail {
    fn name(&self) -> &str {
        "pii_detection"
    }

    fn description(&self) -> &str {
        "Detect and mask personally identifiable information"
    }

    fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    fn priority(&self) -> u32 {
        20 // Run after moderation
    }

    async fn check_input(&self, content: &str) -> GuardrailResult<CheckResult> {
        if !self.is_enabled() {
            return Ok(CheckResult::pass());
        }

        let matches = self.detect(content);

        if matches.is_empty() {
            return Ok(CheckResult::pass());
        }

        let violations = self.create_violations(&matches);

        match self.config.action {
            GuardrailAction::Block => Ok(CheckResult::block(violations)),
            GuardrailAction::Mask => {
                let masked = self.mask(content, &matches);
                Ok(CheckResult::mask(masked, violations))
            }
            GuardrailAction::Log => {
                let mut result = CheckResult::pass();
                result.violations = violations;
                result.action = GuardrailAction::Log;
                Ok(result)
            }
            GuardrailAction::Allow => Ok(CheckResult::pass()),
        }
    }
}

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

    fn create_test_guardrail() -> PIIGuardrail {
        let config = PIIConfig {
            enabled: true,
            action: GuardrailAction::Mask,
            ..Default::default()
        };
        PIIGuardrail::new(config).unwrap()
    }

    #[test]
    fn test_guardrail_creation() {
        let guardrail = create_test_guardrail();
        assert_eq!(guardrail.name(), "pii_detection");
        assert!(guardrail.is_enabled());
    }

    #[test]
    fn test_detect_email() {
        let guardrail = create_test_guardrail();
        let text = "Contact me at test@example.com for more info.";
        let matches = guardrail.detect(text);

        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].pii_type, PIIType::Email);
        assert_eq!(matches[0].text, "test@example.com");
    }

    #[test]
    fn test_detect_phone() {
        let guardrail = create_test_guardrail();
        let text = "Call me at 555-123-4567 or (555) 987-6543.";
        let matches = guardrail.detect(text);

        assert_eq!(matches.len(), 2);
        assert!(matches.iter().all(|m| m.pii_type == PIIType::Phone));
    }

    #[test]
    fn test_detect_credit_card() {
        let guardrail = create_test_guardrail();
        let text = "My card number is 4111-1111-1111-1111.";
        let matches = guardrail.detect(text);

        // Should detect credit card (may also match other patterns)
        assert!(matches.iter().any(|m| m.pii_type == PIIType::CreditCard));
    }

    #[test]
    fn test_detect_ssn() {
        let guardrail = create_test_guardrail();
        let text = "SSN: 123-45-6789";
        let matches = guardrail.detect(text);

        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].pii_type, PIIType::SSN);
    }

    #[test]
    fn test_detect_ip_address() {
        let guardrail = create_test_guardrail();
        let text = "Server IP: 192.168.1.100";
        let matches = guardrail.detect(text);

        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].pii_type, PIIType::IpAddress);
    }

    #[test]
    fn test_detect_multiple_pii() {
        let guardrail = create_test_guardrail();
        let text = "Email: user@test.com, Phone: 555-123-4567, SSN: 123-45-6789";
        let matches = guardrail.detect(text);

        assert_eq!(matches.len(), 3);
    }

    #[test]
    fn test_mask_with_char() {
        let config = PIIConfig {
            enabled: true,
            action: GuardrailAction::Mask,
            mask_char: '*',
            mask_pattern: None,
            ..Default::default()
        };
        let guardrail = PIIGuardrail::new(config).unwrap();

        let text = "Email: test@example.com";
        let matches = guardrail.detect(text);
        let masked = guardrail.mask(text, &matches);

        assert!(masked.contains("****************"));
        assert!(!masked.contains("test@example.com"));
    }

    #[test]
    fn test_mask_with_pattern() {
        let config = PIIConfig {
            enabled: true,
            action: GuardrailAction::Mask,
            mask_pattern: Some("[REDACTED]".to_string()),
            ..Default::default()
        };
        let guardrail = PIIGuardrail::new(config).unwrap();

        let text = "Email: test@example.com";
        let matches = guardrail.detect(text);
        let masked = guardrail.mask(text, &matches);

        assert!(masked.contains("[REDACTED]"));
        assert!(!masked.contains("test@example.com"));
    }

    #[test]
    fn test_allow_list() {
        let config = PIIConfig {
            enabled: true,
            action: GuardrailAction::Mask,
            allow_list: vec!["allowed@example.com".to_string()],
            ..Default::default()
        };
        let guardrail = PIIGuardrail::new(config).unwrap();

        let text = "Contact: allowed@example.com or other@example.com";
        let matches = guardrail.detect(text);

        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].text, "other@example.com");
    }

    #[test]
    fn test_no_pii() {
        let guardrail = create_test_guardrail();
        let text = "This is a normal message without any PII.";
        let matches = guardrail.detect(text);

        assert!(matches.is_empty());
    }

    #[tokio::test]
    async fn test_check_input_block() {
        let config = PIIConfig {
            enabled: true,
            action: GuardrailAction::Block,
            ..Default::default()
        };
        let guardrail = PIIGuardrail::new(config).unwrap();

        let result = guardrail
            .check_input("Email: test@example.com")
            .await
            .unwrap();

        assert!(result.is_blocked());
        assert_eq!(result.violations.len(), 1);
    }

    #[tokio::test]
    async fn test_check_input_mask() {
        let config = PIIConfig {
            enabled: true,
            action: GuardrailAction::Mask,
            mask_pattern: Some("[EMAIL]".to_string()),
            ..Default::default()
        };
        let guardrail = PIIGuardrail::new(config).unwrap();

        let result = guardrail
            .check_input("Email: test@example.com")
            .await
            .unwrap();

        assert!(!result.is_blocked());
        assert!(result.is_modified());
        assert!(result.modified_content.unwrap().contains("[EMAIL]"));
    }

    #[tokio::test]
    async fn test_check_input_log() {
        let config = PIIConfig {
            enabled: true,
            action: GuardrailAction::Log,
            ..Default::default()
        };
        let guardrail = PIIGuardrail::new(config).unwrap();

        let result = guardrail
            .check_input("Email: test@example.com")
            .await
            .unwrap();

        assert!(result.passed);
        assert!(!result.is_blocked());
        assert_eq!(result.violations.len(), 1);
        assert_eq!(result.action, GuardrailAction::Log);
    }

    #[tokio::test]
    async fn test_check_input_disabled() {
        let config = PIIConfig {
            enabled: false,
            ..Default::default()
        };
        let guardrail = PIIGuardrail::new(config).unwrap();

        let result = guardrail
            .check_input("Email: test@example.com")
            .await
            .unwrap();

        assert!(result.passed);
    }

    #[test]
    fn test_specific_pii_types() {
        let config = PIIConfig {
            enabled: true,
            types: [PIIType::Email].into_iter().collect(),
            ..Default::default()
        };
        let guardrail = PIIGuardrail::new(config).unwrap();

        let text = "Email: test@example.com, Phone: 555-123-4567";
        let matches = guardrail.detect(text);

        // Should only detect email, not phone
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].pii_type, PIIType::Email);
    }
}