inklog 0.2.0

Enterprise-grade Rust logging infrastructure
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
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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! Log content sanitization for security.
//!
//! This module provides log content sanitization to prevent log injection attacks
//! and ensure safe log output for SIEM systems.

use regex::Regex;
use std::sync::LazyLock;

/// Pre-compiled regex for ANSI SGR (Select Graphic Rendition) escape sequences.
static ANSI_SGR_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\x1b\[[0-9;]*m").expect("hardcoded ANSI SGR regex is valid"));

/// Escape mode for log content sanitization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EscapeMode {
    /// Minimal escaping - only escape newlines and control characters
    #[default]
    Minimal,
    /// Strict escaping - escape all non-printable characters
    Strict,
    /// JSON-safe escaping - escape for JSON output
    JsonSafe,
}

/// Configuration for log sanitization.
#[derive(Debug, Clone)]
pub struct SanitizerConfig {
    /// Escape mode
    pub mode: EscapeMode,
    /// Maximum message length (0 = unlimited)
    pub max_length: usize,
    /// Replace patterns with replacement
    pub sensitive_patterns: Vec<(Regex, String)>,
    /// Custom replacements for specific strings
    pub custom_replacements: Vec<(String, String)>,
}

impl Default for SanitizerConfig {
    fn default() -> Self {
        Self {
            mode: EscapeMode::Minimal,
            max_length: 0,
            sensitive_patterns: Vec::new(),
            custom_replacements: vec![
                ("\r\n".to_string(), "\\n".to_string()),
                ("\n".to_string(), "\\n".to_string()),
                ("\r".to_string(), "\\r".to_string()),
            ],
        }
    }
}

/// Log sanitizer for preventing log injection.
#[derive(Debug, Clone)]
pub struct LogSanitizer {
    config: SanitizerConfig,
    sensitive_regexes: Vec<(Regex, String)>,
}

/// Default sensitive patterns compiled once and shared across all LogSanitizer instances.
/// Using LazyLock avoids recompiling these stable regex patterns on every constructor call.
static DEFAULT_SENSITIVE_PATTERNS: LazyLock<Vec<(Regex, String)>> = LazyLock::new(|| {
    vec![
        (
            Regex::new(r"\b\d{13,16}\b").expect("hardcoded card number regex is valid"),
            "[CARD_NUM]".to_string(),
        ),
        (
            Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b")
                .expect("hardcoded email regex is valid"),
            "[EMAIL]".to_string(),
        ),
        (
            Regex::new(r"\b\d{3}-\d{2}-\d{4}\b").expect("hardcoded SSN regex is valid"),
            "[SSN]".to_string(),
        ),
        (
            Regex::new(r"(?i)password\s*[=:]\s*\S+").expect("hardcoded password regex is valid"),
            "password=[REDACTED]".to_string(),
        ),
        (
            Regex::new(r"(?i)token\s*[=:]\s*\S+").expect("hardcoded token regex is valid"),
            "token=[REDACTED]".to_string(),
        ),
        (
            Regex::new(r"(?i)api[_-]?key\s*[=:]\s*\S+").expect("hardcoded api_key regex is valid"),
            "api_key=[REDACTED]".to_string(),
        ),
        (
            Regex::new(r"Bearer\s+[A-Za-z0-9\-\.]+")
                .expect("hardcoded Bearer token regex is valid"),
            "Bearer [TOKEN]".to_string(),
        ),
        (
            Regex::new(r"Basic\s+[A-Za-z0-9+/=]+").expect("hardcoded Basic auth regex is valid"),
            "Basic [AUTH]".to_string(),
        ),
    ]
});

impl LogSanitizer {
    /// Create a new LogSanitizer with default configuration.
    pub fn new() -> Self {
        Self {
            config: SanitizerConfig::default(),
            sensitive_regexes: Self::default_sensitive_patterns(),
        }
    }

    /// Create with custom configuration.
    /// User-provided `sensitive_patterns` are merged with default patterns.
    pub fn with_config(mut config: SanitizerConfig) -> Self {
        let mut sensitive_regexes = Self::default_sensitive_patterns();
        sensitive_regexes.append(&mut config.sensitive_patterns);
        Self {
            config,
            sensitive_regexes,
        }
    }

    /// Clone from the shared LazyLock cache to avoid recompiling regexes.
    /// Each caller gets its own owned copy so mutations (add_pattern) don't affect others.
    fn default_sensitive_patterns() -> Vec<(Regex, String)> {
        DEFAULT_SENSITIVE_PATTERNS.clone()
    }

    /// Sanitize a log message.
    pub fn sanitize(&self, message: &str) -> String {
        // Strip ANSI escape sequences before any other processing
        let mut result = self.strip_ansi(message).into_owned();

        for (pattern, replacement) in &self.sensitive_regexes {
            result = pattern
                .replace_all(&result, replacement.as_str())
                .to_string();
        }

        for (from, to) in &self.config.custom_replacements {
            result = result.replace(from, to);
        }

        match self.config.mode {
            EscapeMode::Minimal => {
                result = self.escape_minimal(&result);
            }
            EscapeMode::Strict => {
                result = self.escape_strict(&result);
            }
            EscapeMode::JsonSafe => {
                result = self.escape_json(&result);
            }
        }

        if self.config.max_length > 0 && result.len() > self.config.max_length {
            // Find a safe UTF-8 char boundary to avoid splitting multi-byte characters
            let mut end = self.config.max_length;
            while end > 0 && !result.is_char_boundary(end) {
                end -= 1;
            }
            result.truncate(end);
            result.push_str("...[truncated]");
        }

        result
    }

    fn escape_minimal(&self, s: &str) -> String {
        let mut result = String::with_capacity(s.len());
        for c in s.chars() {
            match c {
                '\n' => result.push_str("\\n"),
                '\r' => result.push_str("\\r"),
                '\t' => result.push_str("\\t"),
                c if c.is_control() && c != '\n' && c != '\r' && c != '\t' => {
                    result.push_str(&format!("\\x{:02x}", c as u8));
                }
                _ => result.push(c),
            }
        }
        result
    }

    /// Strict escape mode: converts control characters and quotes to `\uXXXX` form.
    ///
    /// This method is idempotent: calling it twice on the same input produces
    /// the same output, because already-escaped `\uXXXX` sequences are detected
    /// and not re-escaped.
    fn escape_strict(&self, s: &str) -> String {
        let mut result = String::with_capacity(s.len());
        let mut chars = s.chars().peekable();
        while let Some(c) = chars.next() {
            // Check if this backslash starts an existing \uXXXX escape sequence
            if c == '\\' {
                if chars.peek() == Some(&'u') {
                    // Pass through existing \uXXXX sequences unchanged
                    result.push(c);
                } else {
                    // Escape standalone backslashes
                    result.push_str(&format!("\\u{:04x}", c as u32));
                }
            } else if c.is_control() || c == '"' {
                result.push_str(&format!("\\u{:04x}", c as u32));
            } else {
                result.push(c);
            }
        }
        result
    }

    fn escape_json(&self, s: &str) -> String {
        let mut result = String::with_capacity(s.len());
        for c in s.chars() {
            match c {
                '"' => result.push_str("\\\""),
                '\\' => result.push_str("\\\\"),
                '\n' => result.push_str("\\n"),
                '\r' => result.push_str("\\r"),
                '\t' => result.push_str("\\t"),
                c if c.is_control() => {
                    result.push_str(&format!("\\u{:04x}", c as u32));
                }
                _ => result.push(c),
            }
        }
        result
    }

    /// Add a custom sensitive pattern.
    pub fn add_pattern(&mut self, pattern: Regex, replacement: String) {
        self.sensitive_regexes.push((pattern, replacement));
    }

    /// Add a custom string replacement.
    pub fn add_replacement(&mut self, from: String, to: String) {
        self.config.custom_replacements.push((from, to));
    }

    /// Strip ANSI SGR escape sequences from the input string.
    ///
    /// Fast path: if the input contains no `\x1b` (ESC) character,
    /// returns the original string without any allocation.
    pub fn strip_ansi<'a>(&self, input: &'a str) -> std::borrow::Cow<'a, str> {
        if !input.contains('\x1b') {
            return std::borrow::Cow::Borrowed(input);
        }
        std::borrow::Cow::Owned(ANSI_SGR_REGEX.replace_all(input, "").into_owned())
    }
}

impl Default for LogSanitizer {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_newline_escaping() {
        let sanitizer = LogSanitizer::new();

        let result = sanitizer.sanitize("Hello\nWorld");
        assert!(result.contains("\\n"));
        assert!(!result.contains('\n'));
    }

    #[test]
    fn test_sensitive_data_redaction() {
        let sanitizer = LogSanitizer::new();

        let result = sanitizer.sanitize("User password=secret123");
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("secret123"));

        let result = sanitizer.sanitize("api_key=sk-1234567890");
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("sk-1234567890"));
    }

    #[test]
    fn test_email_redaction() {
        let sanitizer = LogSanitizer::new();

        let result = sanitizer.sanitize("Contact user@example.com");
        assert!(result.contains("[EMAIL]"));
        assert!(!result.contains("user@example.com"));
    }

    #[test]
    fn test_escape_modes() {
        let config = SanitizerConfig {
            mode: EscapeMode::JsonSafe,
            ..Default::default()
        };
        let sanitizer = LogSanitizer::with_config(config);

        let result = sanitizer.sanitize("Hello\"World");
        assert!(result.contains("\\\""));
    }

    #[test]
    fn test_max_length() {
        let config = SanitizerConfig {
            max_length: 10,
            ..Default::default()
        };
        let sanitizer = LogSanitizer::with_config(config);

        let result = sanitizer.sanitize("This is a very long message");
        assert!(result.len() <= 10 + "...[truncated]".len());
        assert!(result.contains("...[truncated]"));
    }

    #[test]
    fn test_control_character_escaping() {
        let sanitizer = LogSanitizer::new();

        let result = sanitizer.sanitize("Hello\x00World");
        assert!(result.contains("\\x00"));
    }

    #[test]
    fn test_default_log_sanitizer() {
        let sanitizer = LogSanitizer::default();
        let result = sanitizer.sanitize("test\nmessage");
        assert!(result.contains("\\n"));
        assert!(!result.contains('\n'));
    }

    #[test]
    fn test_strict_escape_mode() {
        let config = SanitizerConfig {
            mode: EscapeMode::Strict,
            custom_replacements: Vec::new(),
            ..Default::default()
        };
        let sanitizer = LogSanitizer::with_config(config);

        let result = sanitizer.sanitize("Hello\nWorld");
        assert!(result.contains("\\u000a"));
        assert!(!result.contains('\n'));
    }

    #[test]
    fn test_escape_strict_with_backslash_and_quote() {
        let config = SanitizerConfig {
            mode: EscapeMode::Strict,
            custom_replacements: Vec::new(),
            ..Default::default()
        };
        let sanitizer = LogSanitizer::with_config(config);

        let result = sanitizer.sanitize("path\\to\"file");
        assert!(result.contains("\\u005c"));
        assert!(result.contains("\\u0022"));
        // The raw backslash and quote should be replaced by escape sequences
        // Note: escape sequences themselves contain backslashes, so we verify
        // the escape sequences are present rather than checking for absence of '\'
        assert!(!result.contains("\""));
    }

    #[test]
    fn test_escape_strict_preserves_printable() {
        let config = SanitizerConfig {
            mode: EscapeMode::Strict,
            custom_replacements: Vec::new(),
            ..Default::default()
        };
        let sanitizer = LogSanitizer::with_config(config);

        let result = sanitizer.sanitize("Hello World 123");
        assert_eq!(result, "Hello World 123");
    }

    #[test]
    fn test_escape_minimal_with_newline_tab_carriage_return() {
        let config = SanitizerConfig {
            mode: EscapeMode::Minimal,
            custom_replacements: Vec::new(),
            ..Default::default()
        };
        let sanitizer = LogSanitizer::with_config(config);

        let result = sanitizer.sanitize("line1\nline2\r\ttabbed");
        assert_eq!(result, "line1\\nline2\\r\\ttabbed");
        assert!(!result.contains('\n'));
        assert!(!result.contains('\r'));
        assert!(!result.contains('\t'));
    }

    #[test]
    fn test_escape_json_all_special_chars() {
        let config = SanitizerConfig {
            mode: EscapeMode::JsonSafe,
            custom_replacements: Vec::new(),
            ..Default::default()
        };
        let sanitizer = LogSanitizer::with_config(config);

        let input = "quote\"backslash\\newline\ncarriage\rtab\t";
        let result = sanitizer.sanitize(input);
        assert!(result.contains("\\\""));
        assert!(result.contains("\\\\"));
        assert!(result.contains("\\n"));
        assert!(result.contains("\\r"));
        assert!(result.contains("\\t"));
        assert!(!result.contains('\n'));
        assert!(!result.contains('\r'));
        assert!(!result.contains('\t'));
    }

    #[test]
    fn test_escape_json_control_character() {
        let config = SanitizerConfig {
            mode: EscapeMode::JsonSafe,
            custom_replacements: Vec::new(),
            ..Default::default()
        };
        let sanitizer = LogSanitizer::with_config(config);

        let result = sanitizer.sanitize("null\x00byte");
        assert!(result.contains("\\u0000"));
    }

    #[test]
    fn test_add_pattern() {
        let mut sanitizer = LogSanitizer::new();
        let pattern = Regex::new(r"SECRET-\d+").expect("valid regex");
        sanitizer.add_pattern(pattern, "[SECRET]".to_string());

        let result = sanitizer.sanitize("found SECRET-12345 here");
        assert!(result.contains("[SECRET]"));
        assert!(!result.contains("SECRET-12345"));
    }

    #[test]
    fn test_add_replacement() {
        let mut sanitizer = LogSanitizer::new();
        sanitizer.add_replacement("foo".to_string(), "bar".to_string());

        let result = sanitizer.sanitize("hello foo world");
        assert!(result.contains("bar"));
        assert!(!result.contains("foo"));
    }

    #[test]
    fn test_add_pattern_and_replacement_combined() {
        let mut sanitizer = LogSanitizer::new();
        let pattern = Regex::new(r"\bPHONE-\d+\b").expect("valid regex");
        sanitizer.add_pattern(pattern, "[PHONE]".to_string());
        sanitizer.add_replacement("internal".to_string(), "external".to_string());

        let result = sanitizer.sanitize("call PHONE-555 internal line");
        assert!(result.contains("[PHONE]"));
        assert!(result.contains("external"));
        assert!(!result.contains("PHONE-555"));
        assert!(!result.contains("internal"));
    }

    #[test]
    fn test_sanitize_truncate_respects_utf8_boundaries() {
        let mut config = super::SanitizerConfig::default();
        config.max_length = 7;
        let sanitizer = super::LogSanitizer::with_config(config);
        let result = sanitizer.sanitize("你好世界");
        assert!(result.starts_with("你好"));
        assert!(result.contains("...[truncated]"));
    }

    #[test]
    fn test_strip_ansi_sgr_sequence() {
        let sanitizer = LogSanitizer::new();
        assert_eq!(sanitizer.strip_ansi("\x1b[31mERROR\x1b[0m"), "ERROR");
    }

    #[test]
    fn test_strip_ansi_multiple_sequences() {
        let sanitizer = LogSanitizer::new();
        assert_eq!(sanitizer.strip_ansi("\x1b[1;32mOK\x1b[0m"), "OK");
    }

    #[test]
    fn test_strip_ansi_fast_path_no_esc() {
        let sanitizer = LogSanitizer::new();
        let input = "no ansi here";
        let result = sanitizer.strip_ansi(input);
        assert_eq!(result, "no ansi here");
        assert!(matches!(result, std::borrow::Cow::Borrowed(_)));
    }

    #[test]
    fn test_strip_ansi_nested_sequences() {
        let sanitizer = LogSanitizer::new();
        assert_eq!(
            sanitizer.strip_ansi("\x1b[1m\x1b[31mBOLD RED\x1b[0m\x1b[0m"),
            "BOLD RED"
        );
    }

    #[test]
    fn test_strip_ansi_empty_input() {
        let sanitizer = LogSanitizer::new();
        assert_eq!(sanitizer.strip_ansi(""), "");
    }

    #[test]
    fn test_strip_ansi_only_esc_char() {
        let sanitizer = LogSanitizer::new();
        let result = sanitizer.strip_ansi("\x1b");
        assert_eq!(result, "\x1b");
    }

    #[test]
    fn test_sanitize_strips_ansi_before_processing() {
        let sanitizer = LogSanitizer::new();
        let result = sanitizer.sanitize("\x1b[31mERROR\x1b[0m");
        assert_eq!(result, "ERROR");
        assert!(!result.contains('\x1b'));
    }
}