sanitize-engine 0.3.0

Deterministic one-way data sanitization engine
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
//! End-to-end benchmark for the streaming scanner and archive processor.

use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use rayon::prelude::*;
use sanitize_engine::category::Category;
use sanitize_engine::generator::HmacGenerator;
use sanitize_engine::processor::archive::ArchiveProcessor;
use sanitize_engine::processor::ProcessorRegistry;
use sanitize_engine::scanner::{ScanConfig, ScanPattern, StreamScanner};
use sanitize_engine::store::MappingStore;
use std::io::Cursor;
use std::sync::Arc;

/// Build a scanner with only literal patterns (exercises the Aho-Corasick path).
fn build_literal_scanner(chunk_size: usize) -> Arc<StreamScanner> {
    let gen = Arc::new(HmacGenerator::new([42u8; 32]));
    let store = Arc::new(MappingStore::new(gen, None));
    let patterns = vec![
        ScanPattern::from_literal("SECRET_KEY=", Category::AuthToken, "secret_key").unwrap(),
        ScanPattern::from_literal("password=", Category::AuthToken, "password").unwrap(),
        ScanPattern::from_literal("api_key=", Category::AuthToken, "api_key").unwrap(),
        ScanPattern::from_literal("Bearer ", Category::AuthToken, "bearer").unwrap(),
        ScanPattern::from_literal("Authorization:", Category::AuthToken, "auth_header").unwrap(),
    ];
    let config = ScanConfig::new(chunk_size, 4096);
    Arc::new(StreamScanner::new(patterns, store, config).unwrap())
}

/// Build a scanner with both literal and regex patterns (exercises both paths together).
fn build_mixed_scanner(chunk_size: usize) -> Arc<StreamScanner> {
    let gen = Arc::new(HmacGenerator::new([42u8; 32]));
    let store = Arc::new(MappingStore::new(gen, None));
    let patterns = vec![
        ScanPattern::from_literal("SECRET_KEY=", Category::AuthToken, "secret_key").unwrap(),
        ScanPattern::from_literal("password=", Category::AuthToken, "password").unwrap(),
        ScanPattern::from_literal("api_key=", Category::AuthToken, "api_key").unwrap(),
        ScanPattern::from_regex(
            r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
            Category::Email,
            "email",
        )
        .unwrap(),
        ScanPattern::from_regex(
            r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b",
            Category::IpV4,
            "ipv4",
        )
        .unwrap(),
    ];
    let config = ScanConfig::new(chunk_size, 4096);
    Arc::new(StreamScanner::new(patterns, store, config).unwrap())
}

/// Build a reusable scanner + store for benchmarks.
fn build_scanner(chunk_size: usize) -> Arc<StreamScanner> {
    let gen = Arc::new(HmacGenerator::new([42u8; 32]));
    let store = Arc::new(MappingStore::new(gen, None));
    let patterns = vec![
        ScanPattern::from_regex(
            r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
            Category::Email,
            "email",
        )
        .unwrap(),
        ScanPattern::from_regex(
            r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b",
            Category::IpV4,
            "ipv4",
        )
        .unwrap(),
        ScanPattern::from_regex(
            r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b",
            Category::Uuid,
            "uuid",
        )
        .unwrap(),
    ];
    let config = ScanConfig::new(chunk_size, 4096);
    Arc::new(StreamScanner::new(patterns, store, config).unwrap())
}

/// Generate synthetic input with embedded secrets every ~200 bytes.
fn generate_input(size: usize) -> Vec<u8> {
    let line = "server=192.168.1.42 user=alice@corp.com id=550e8400-e29b-41d4-a716-446655440000 lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor\n";
    let mut buf = Vec::with_capacity(size);
    while buf.len() < size {
        let remaining = size - buf.len();
        if remaining >= line.len() {
            buf.extend_from_slice(line.as_bytes());
        } else {
            buf.extend_from_slice(&line.as_bytes()[..remaining]);
        }
    }
    buf.truncate(size);
    buf
}

/// Generate synthetic input with embedded literal secrets every ~200 bytes.
fn generate_literal_input(size: usize) -> Vec<u8> {
    let line = "config: SECRET_KEY=abc123 password=hunter2 api_key=xyzzy Bearer token=foobar Authorization: Basic dXNlcjpwYXNz lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod\n";
    let mut buf = Vec::with_capacity(size);
    while buf.len() < size {
        let remaining = size - buf.len();
        if remaining >= line.len() {
            buf.extend_from_slice(line.as_bytes());
        } else {
            buf.extend_from_slice(&line.as_bytes()[..remaining]);
        }
    }
    buf.truncate(size);
    buf
}

/// Generate synthetic input mixing literal and regex secrets.
fn generate_mixed_input(size: usize) -> Vec<u8> {
    let line = "config: SECRET_KEY=abc123 password=hunter2 api_key=xyzzy user=alice@corp.com server=192.168.1.42 lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod\n";
    let mut buf = Vec::with_capacity(size);
    while buf.len() < size {
        let remaining = size - buf.len();
        if remaining >= line.len() {
            buf.extend_from_slice(line.as_bytes());
        } else {
            buf.extend_from_slice(&line.as_bytes()[..remaining]);
        }
    }
    buf.truncate(size);
    buf
}

// ---------------------------------------------------------------------------
// Streaming scanner benchmarks
// ---------------------------------------------------------------------------

fn bench_scan_throughput(c: &mut Criterion) {
    let mut group = c.benchmark_group("scan_throughput");

    for &size_mib in &[1, 16, 64] {
        let size = size_mib * 1024 * 1024;
        let input = generate_input(size);
        let scanner = build_scanner(1024 * 1024);

        group.throughput(Throughput::Bytes(size as u64));
        group.bench_with_input(
            BenchmarkId::new("default_chunk", format!("{size_mib}MiB")),
            &input,
            |b, input| {
                b.iter(|| {
                    let mut output = Vec::with_capacity(input.len());
                    scanner.scan_reader(input.as_slice(), &mut output).unwrap();
                });
            },
        );
    }
    group.finish();
}

fn bench_chunk_sizes(c: &mut Criterion) {
    let mut group = c.benchmark_group("chunk_size_impact");
    let size = 16 * 1024 * 1024; // 16 MiB
    let input = generate_input(size);

    for &chunk_kib in &[64, 256, 1024, 4096] {
        let chunk_size = chunk_kib * 1024;
        let scanner = build_scanner(chunk_size);

        group.throughput(Throughput::Bytes(size as u64));
        group.bench_with_input(
            BenchmarkId::new("16MiB_input", format!("{chunk_kib}KiB")),
            &input,
            |b, input| {
                b.iter(|| {
                    let mut output = Vec::with_capacity(input.len());
                    scanner.scan_reader(input.as_slice(), &mut output).unwrap();
                });
            },
        );
    }
    group.finish();
}

// ---------------------------------------------------------------------------
// Archive processing benchmark
// ---------------------------------------------------------------------------

fn bench_tar_processing(c: &mut Criterion) {
    let mut group = c.benchmark_group("tar_processing");

    // Build a tar archive with N files of 64 KiB each.
    for &file_count in &[10, 50] {
        let file_size = 64 * 1024;
        let file_data = generate_input(file_size);

        // Create tar in memory.
        let mut tar_buf = Vec::new();
        {
            let mut builder = tar::Builder::new(&mut tar_buf);
            for i in 0..file_count {
                let mut header = tar::Header::new_gnu();
                header.set_size(file_data.len() as u64);
                header.set_mode(0o644);
                header.set_cksum();
                builder
                    .append_data(&mut header, format!("file_{i}.log"), file_data.as_slice())
                    .unwrap();
            }
            builder.finish().unwrap();
        }

        let gen = Arc::new(HmacGenerator::new([42u8; 32]));
        let store = Arc::new(MappingStore::new(gen, None));
        let scanner = build_scanner(1024 * 1024);
        let registry = Arc::new(ProcessorRegistry::new());
        let archive_proc = ArchiveProcessor::new(registry, scanner, store, vec![]);

        group.throughput(Throughput::Bytes(tar_buf.len() as u64));
        group.bench_with_input(
            BenchmarkId::new("files", file_count),
            &tar_buf,
            |b, tar_buf| {
                b.iter(|| {
                    let reader = Cursor::new(tar_buf);
                    let mut output = Vec::with_capacity(tar_buf.len());
                    archive_proc.process_tar(reader, &mut output).unwrap();
                });
            },
        );
    }
    group.finish();
}

// ---------------------------------------------------------------------------
// Literal-only (Aho-Corasick path) benchmark
// ---------------------------------------------------------------------------

fn bench_literal_scan_throughput(c: &mut Criterion) {
    let mut group = c.benchmark_group("literal_scan_throughput");

    for &size_mib in &[1, 16, 64] {
        let size = size_mib * 1024 * 1024;
        let input = generate_literal_input(size);
        let scanner = build_literal_scanner(1024 * 1024);

        group.throughput(Throughput::Bytes(size as u64));
        group.bench_with_input(
            BenchmarkId::new("aho_corasick", format!("{size_mib}MiB")),
            &input,
            |b, input| {
                b.iter(|| {
                    let mut output = Vec::with_capacity(input.len());
                    scanner.scan_reader(input.as_slice(), &mut output).unwrap();
                });
            },
        );
    }
    group.finish();
}

// ---------------------------------------------------------------------------
// Mixed literal+regex benchmark
// ---------------------------------------------------------------------------

fn bench_mixed_scan_throughput(c: &mut Criterion) {
    let mut group = c.benchmark_group("mixed_scan_throughput");

    for &size_mib in &[1, 16, 64] {
        let size = size_mib * 1024 * 1024;
        let input = generate_mixed_input(size);
        let scanner = build_mixed_scanner(1024 * 1024);

        group.throughput(Throughput::Bytes(size as u64));
        group.bench_with_input(
            BenchmarkId::new("hybrid_ac_regex", format!("{size_mib}MiB")),
            &input,
            |b, input| {
                b.iter(|| {
                    let mut output = Vec::with_capacity(input.len());
                    scanner.scan_reader(input.as_slice(), &mut output).unwrap();
                });
            },
        );
    }
    group.finish();
}

criterion_group!(
    benches,
    bench_scan_throughput,
    bench_chunk_sizes,
    bench_literal_scan_throughput,
    bench_mixed_scan_throughput,
    bench_tar_processing,
    bench_parallel_archive_entries,
    bench_parallel_multi_file,
);
criterion_main!(benches);

// ---------------------------------------------------------------------------
// Parallel archive-entry benchmark
//
// Compares serial (threshold = usize::MAX) vs parallel (threshold = 1) entry
// sanitization for a tar with a fixed number of file entries.
// ---------------------------------------------------------------------------

fn bench_parallel_archive_entries(c: &mut Criterion) {
    let mut group = c.benchmark_group("parallel_archive_entries");

    let file_size = 64 * 1024; // 64 KiB per entry
    let file_data = generate_input(file_size);

    for &file_count in &[8, 20, 50] {
        let mut tar_buf = Vec::new();
        {
            let mut builder = tar::Builder::new(&mut tar_buf);
            for i in 0..file_count {
                let mut header = tar::Header::new_gnu();
                header.set_size(file_data.len() as u64);
                header.set_mode(0o644);
                header.set_cksum();
                builder
                    .append_data(&mut header, format!("file_{i}.log"), file_data.as_slice())
                    .unwrap();
            }
            builder.finish().unwrap();
        }

        let make_proc = |parallel_threshold: usize| {
            let gen = Arc::new(HmacGenerator::new([42u8; 32]));
            let store = Arc::new(MappingStore::new(gen, None));
            let scanner = build_scanner(1024 * 1024);
            let registry = Arc::new(ProcessorRegistry::new());
            ArchiveProcessor::new(registry, scanner, store, vec![])
                .with_parallel_threshold(parallel_threshold)
        };

        group.throughput(Throughput::Bytes(tar_buf.len() as u64));

        // Serial baseline: parallel_threshold = usize::MAX disables par_iter.
        let serial_proc = make_proc(usize::MAX);
        group.bench_with_input(
            BenchmarkId::new(format!("serial_files{file_count}"), file_count),
            &tar_buf,
            |b, tar_buf| {
                b.iter(|| {
                    let reader = Cursor::new(tar_buf);
                    let mut output = Vec::with_capacity(tar_buf.len());
                    serial_proc.process_tar(reader, &mut output).unwrap();
                });
            },
        );

        // Parallel: parallel_threshold = 1 always uses par_iter.
        let parallel_proc = make_proc(1);
        group.bench_with_input(
            BenchmarkId::new(format!("parallel_files{file_count}"), file_count),
            &tar_buf,
            |b, tar_buf| {
                b.iter(|| {
                    let reader = Cursor::new(tar_buf);
                    let mut output = Vec::with_capacity(tar_buf.len());
                    parallel_proc.process_tar(reader, &mut output).unwrap();
                });
            },
        );
    }

    group.finish();
}

// ---------------------------------------------------------------------------
// Parallel multi-file benchmark
//
// Compares sequential vs rayon::par_iter for scanning N independent files.
// Exercises the same code path as the parallel top-level file loop added in
// run_sanitize.
// ---------------------------------------------------------------------------

fn bench_parallel_multi_file(c: &mut Criterion) {
    let mut group = c.benchmark_group("parallel_multi_file");

    let file_size = 1024 * 1024; // 1 MiB per file
    let scanner = build_mixed_scanner(1024 * 1024);

    for &file_count in &[2, 4, 8] {
        let files: Vec<Vec<u8>> = (0..file_count)
            .map(|_| generate_mixed_input(file_size))
            .collect();

        let total_bytes = (file_size * file_count) as u64;
        group.throughput(Throughput::Bytes(total_bytes));

        // Sequential baseline.
        let scanner_seq = Arc::clone(&scanner);
        group.bench_with_input(
            BenchmarkId::new(format!("sequential_files{file_count}"), file_count),
            &files,
            |b, files| {
                b.iter(|| {
                    for file in files {
                        let mut out = Vec::with_capacity(file.len());
                        scanner_seq.scan_reader(file.as_slice(), &mut out).unwrap();
                    }
                });
            },
        );

        // Parallel via rayon.
        let scanner_par = Arc::clone(&scanner);
        group.bench_with_input(
            BenchmarkId::new(format!("parallel_files{file_count}"), file_count),
            &files,
            |b, files| {
                b.iter(|| {
                    files.par_iter().for_each(|file| {
                        let mut out = Vec::with_capacity(file.len());
                        scanner_par.scan_reader(file.as_slice(), &mut out).unwrap();
                    });
                });
            },
        );
    }

    group.finish();
}