leaktor 0.4.0

A secrets scanner with pattern matching, entropy analysis, and live validation
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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! Multi-format scanning: decode and scan secrets in structured files.
//!
//! Supported formats:
//!   - Terraform state files (`.tfstate`) -- base64-encoded values
//!   - Kubernetes secrets (`kind: Secret`)  -- base64 `.data` values
//!   - Docker Compose / docker-compose.yml -- `environment:` values
//!   - AWS CloudFormation templates        -- `Parameters`/`Default` secrets
//!
//! The scanner operates on a single file and returns additional findings that
//! would normally be hidden inside base64 blobs or nested YAML/JSON.

use crate::detectors::{ContextAnalyzer, PatternDetector};
use crate::models::{Context, Finding, Location};
use crate::scan_warn;
use anyhow::Result;
use std::path::Path;

/// Identifies the structured format of a file (if any).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StructuredFormat {
    TerraformState,
    KubernetesSecret,
    DockerCompose,
    CloudFormation,
}

/// Detect the structured format of a file based on filename and content peek.
pub fn detect_format(path: &Path, content: &str) -> Option<StructuredFormat> {
    let name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("")
        .to_lowercase();
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    // Terraform state
    if name.ends_with(".tfstate") || name.ends_with(".tfstate.backup") {
        return Some(StructuredFormat::TerraformState);
    }

    // Kubernetes Secret manifest
    if (ext == "yaml" || ext == "yml" || ext == "json")
        && content.contains("kind:")
        && content.contains("Secret")
        && content.contains("data:")
    {
        return Some(StructuredFormat::KubernetesSecret);
    }

    // Docker Compose
    if (name.starts_with("docker-compose") || name.starts_with("compose"))
        && (ext == "yml" || ext == "yaml")
    {
        return Some(StructuredFormat::DockerCompose);
    }

    // CloudFormation
    if (ext == "yaml" || ext == "yml" || ext == "json" || ext == "template")
        && (content.contains("AWSTemplateFormatVersion")
            || content.contains("aws-template-format-version")
            || (content.contains("Resources")
                && (content.contains("AWS::") || content.contains("aws::"))))
    {
        return Some(StructuredFormat::CloudFormation);
    }

    None
}

/// Scan a structured file, returning additional findings from decoded values.
pub fn scan_structured_file(
    path: &Path,
    content: &str,
    format: StructuredFormat,
    detector: &PatternDetector,
    entropy_threshold: f64,
) -> Result<Vec<Finding>> {
    match format {
        StructuredFormat::TerraformState => {
            scan_terraform_state(path, content, detector, entropy_threshold)
        }
        StructuredFormat::KubernetesSecret => {
            scan_kubernetes_secret(path, content, detector, entropy_threshold)
        }
        StructuredFormat::DockerCompose => {
            scan_docker_compose(path, content, detector, entropy_threshold)
        }
        StructuredFormat::CloudFormation => {
            scan_cloudformation(path, content, detector, entropy_threshold)
        }
    }
}

// ── Terraform state ──────────────────────────────────────────────────────────

fn scan_terraform_state(
    path: &Path,
    content: &str,
    detector: &PatternDetector,
    entropy_threshold: f64,
) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();

    // Parse as JSON
    let value: serde_json::Value = match serde_json::from_str(content) {
        Ok(v) => v,
        Err(e) => {
            scan_warn!(
                "parse",
                "failed to parse {} as Terraform state JSON: {}",
                path.display(),
                e
            );
            return Ok(findings);
        }
    };

    // Recursively walk all string values looking for secrets
    let file_context = ContextAnalyzer::analyze_file(path);
    walk_json_values(
        &value,
        path,
        &file_context,
        detector,
        entropy_threshold,
        &mut findings,
        "",
    );

    // Also look for base64-encoded blobs and decode them
    walk_json_decode_base64(
        &value,
        path,
        &file_context,
        detector,
        entropy_threshold,
        &mut findings,
    );

    Ok(findings)
}

fn walk_json_values(
    value: &serde_json::Value,
    path: &Path,
    file_context: &crate::detectors::context::FileContext,
    detector: &PatternDetector,
    entropy_threshold: f64,
    findings: &mut Vec<Finding>,
    json_path: &str,
) {
    walk_json_values_inner(
        value, path, file_context, detector, entropy_threshold, findings, json_path, None,
    );
}

#[allow(clippy::too_many_arguments)]
/// Inner recursive walker that also receives the parent JSON key name.
/// When a string value is encountered under an object key, the key name is
/// combined with the value (`key=value`) before scanning so that
/// context-dependent patterns (e.g. `aws_secret_access_key=...`) can match.
/// This mirrors the approach used by the Docker Compose scanner.
fn walk_json_values_inner(
    value: &serde_json::Value,
    path: &Path,
    file_context: &crate::detectors::context::FileContext,
    detector: &PatternDetector,
    entropy_threshold: f64,
    findings: &mut Vec<Finding>,
    json_path: &str,
    parent_key: Option<&str>,
) {
    match value {
        serde_json::Value::String(s) => {
            if s.len() < 8 || s.len() > 5000 {
                return;
            }

            // Combine key=value so context-dependent patterns can match
            // (e.g. "secret": "wJalr..." becomes "secret=wJalr..." for scanning)
            let combined = if let Some(key) = parent_key {
                format!("{}={}", key, s)
            } else {
                s.clone()
            };

            let matches = detector.scan_line_with_positions(&combined, entropy_threshold);
            for m in matches {
                let context = Context {
                    line_before: Some(format!("JSON path: {}", json_path)),
                    line_content: truncate_for_context(s),
                    line_after: None,
                    is_test_file: file_context.is_test_file,
                    is_config_file: true,
                    is_documentation: false,
                    file_extension: file_context.file_extension.clone(),
                };
                let location = Location {
                    file_path: path.to_path_buf(),
                    line_number: 1,
                    column_start: m.column_start,
                    column_end: m.column_end,
                    commit_hash: None,
                    commit_author: None,
                    commit_date: None,
                };
                findings.push(Finding::new(m.secret, location, context));
            }
        }
        serde_json::Value::Object(map) => {
            for (k, v) in map {
                let child_path = if json_path.is_empty() {
                    k.clone()
                } else {
                    format!("{}.{}", json_path, k)
                };
                walk_json_values_inner(
                    v,
                    path,
                    file_context,
                    detector,
                    entropy_threshold,
                    findings,
                    &child_path,
                    Some(k),
                );
            }
        }
        serde_json::Value::Array(arr) => {
            for (i, v) in arr.iter().enumerate() {
                let child_path = format!("{}[{}]", json_path, i);
                walk_json_values_inner(
                    v,
                    path,
                    file_context,
                    detector,
                    entropy_threshold,
                    findings,
                    &child_path,
                    None,
                );
            }
        }
        _ => {}
    }
}

fn walk_json_decode_base64(
    value: &serde_json::Value,
    path: &Path,
    file_context: &crate::detectors::context::FileContext,
    detector: &PatternDetector,
    entropy_threshold: f64,
    findings: &mut Vec<Finding>,
) {
    use base64::Engine as _;
    match value {
        serde_json::Value::String(s) => {
            // Try base64 decode
            if s.len() >= 16 && looks_like_base64(s) {
                if let Ok(decoded_bytes) = base64::engine::general_purpose::STANDARD.decode(s) {
                    if let Ok(decoded) = String::from_utf8(decoded_bytes) {
                        if decoded.len() >= 8 {
                            let matches =
                                detector.scan_line_with_positions(&decoded, entropy_threshold);
                            for m in matches {
                                let context = Context {
                                    line_before: Some("[base64 decoded]".to_string()),
                                    line_content: truncate_for_context(&decoded),
                                    line_after: None,
                                    is_test_file: file_context.is_test_file,
                                    is_config_file: true,
                                    is_documentation: false,
                                    file_extension: file_context.file_extension.clone(),
                                };
                                let location = Location {
                                    file_path: path.to_path_buf(),
                                    line_number: 1,
                                    column_start: m.column_start,
                                    column_end: m.column_end,
                                    commit_hash: None,
                                    commit_author: None,
                                    commit_date: None,
                                };
                                findings.push(Finding::new(m.secret, location, context));
                            }
                        }
                    }
                }
            }
        }
        serde_json::Value::Object(map) => {
            for v in map.values() {
                walk_json_decode_base64(
                    v,
                    path,
                    file_context,
                    detector,
                    entropy_threshold,
                    findings,
                );
            }
        }
        serde_json::Value::Array(arr) => {
            for v in arr {
                walk_json_decode_base64(
                    v,
                    path,
                    file_context,
                    detector,
                    entropy_threshold,
                    findings,
                );
            }
        }
        _ => {}
    }
}

// ── Kubernetes Secret ────────────────────────────────────────────────────────

fn scan_kubernetes_secret(
    path: &Path,
    content: &str,
    detector: &PatternDetector,
    entropy_threshold: f64,
) -> Result<Vec<Finding>> {
    use base64::Engine as _;
    let mut findings = Vec::new();
    let file_context = ContextAnalyzer::analyze_file(path);

    // Parse as YAML (may have multiple documents)
    for doc in serde_yaml::Deserializer::from_str(content) {
        let value: serde_yaml::Value = match serde_yaml::Value::deserialize(doc) {
            Ok(v) => v,
            Err(e) => {
                scan_warn!(
                    "parse",
                    "failed to parse YAML document in {}: {}",
                    path.display(),
                    e
                );
                continue;
            }
        };

        // Check if this doc is a K8s Secret
        let kind = value.get("kind").and_then(|k| k.as_str()).unwrap_or("");
        if kind != "Secret" {
            continue;
        }

        // Decode .data values
        if let Some(data) = value.get("data").and_then(|d| d.as_mapping()) {
            for (key, val) in data {
                let key_str = key.as_str().unwrap_or("unknown");
                let val_str = match val.as_str() {
                    Some(s) => s,
                    None => continue,
                };

                // Decode base64
                let decoded = match base64::engine::general_purpose::STANDARD.decode(val_str.trim())
                {
                    Ok(bytes) => match String::from_utf8(bytes) {
                        Ok(s) => s,
                        Err(_) => continue, // binary data, not a text secret
                    },
                    Err(e) => {
                        scan_warn!(
                            "parse",
                            "invalid base64 in K8s Secret .data.{} in {}: {}",
                            key_str,
                            path.display(),
                            e
                        );
                        continue;
                    }
                };

                if decoded.len() < 4 {
                    continue;
                }

                let matches = detector.scan_line_with_positions(&decoded, entropy_threshold);
                for m in matches {
                    let line_num = find_line_number(content, val_str);
                    let context = Context {
                        line_before: Some(format!("K8s Secret .data.{} [base64 decoded]", key_str)),
                        line_content: truncate_for_context(&decoded),
                        line_after: None,
                        is_test_file: file_context.is_test_file,
                        is_config_file: true,
                        is_documentation: false,
                        file_extension: file_context.file_extension.clone(),
                    };
                    let location = Location {
                        file_path: path.to_path_buf(),
                        line_number: line_num,
                        column_start: m.column_start,
                        column_end: m.column_end,
                        commit_hash: None,
                        commit_author: None,
                        commit_date: None,
                    };
                    findings.push(Finding::new(m.secret, location, context));
                }
            }
        }

        // Also check .stringData (plaintext, no decoding needed -- already handled by normal scan)
    }

    Ok(findings)
}

// ── Docker Compose ───────────────────────────────────────────────────────────

fn scan_docker_compose(
    path: &Path,
    content: &str,
    detector: &PatternDetector,
    entropy_threshold: f64,
) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();
    let file_context = ContextAnalyzer::analyze_file(path);

    let value: serde_yaml::Value = match serde_yaml::from_str(content) {
        Ok(v) => v,
        Err(e) => {
            scan_warn!(
                "parse",
                "failed to parse {} as Docker Compose YAML: {}",
                path.display(),
                e
            );
            return Ok(findings);
        }
    };

    // Walk services -> each service -> environment
    if let Some(services) = value.get("services").and_then(|s| s.as_mapping()) {
        for (_svc_name, svc_val) in services {
            if let Some(env) = svc_val.get("environment") {
                scan_compose_environment(
                    path,
                    content,
                    env,
                    &file_context,
                    detector,
                    entropy_threshold,
                    &mut findings,
                );
            }
        }
    }

    Ok(findings)
}

fn scan_compose_environment(
    path: &Path,
    content: &str,
    env: &serde_yaml::Value,
    file_context: &crate::detectors::context::FileContext,
    detector: &PatternDetector,
    entropy_threshold: f64,
    findings: &mut Vec<Finding>,
) {
    match env {
        // Mapping style: environment: { KEY: value }
        serde_yaml::Value::Mapping(map) => {
            for (key, val) in map {
                let key_str = key.as_str().unwrap_or("unknown");
                let val_str = match val.as_str() {
                    Some(s) => s,
                    None => continue,
                };

                // Combine key=value for scanning (catches patterns like 'AWS_KEY=AKIA...')
                let combined = format!("{}={}", key_str, val_str);
                let matches = detector.scan_line_with_positions(&combined, entropy_threshold);
                for m in matches {
                    let line_num = find_line_number(content, val_str);
                    let context = Context {
                        line_before: Some(format!("Docker Compose environment: {}", key_str)),
                        line_content: truncate_for_context(&combined),
                        line_after: None,
                        is_test_file: file_context.is_test_file,
                        is_config_file: true,
                        is_documentation: false,
                        file_extension: file_context.file_extension.clone(),
                    };
                    let location = Location {
                        file_path: path.to_path_buf(),
                        line_number: line_num,
                        column_start: m.column_start,
                        column_end: m.column_end,
                        commit_hash: None,
                        commit_author: None,
                        commit_date: None,
                    };
                    findings.push(Finding::new(m.secret, location, context));
                }
            }
        }
        // List style: environment: [ "KEY=value" ]
        serde_yaml::Value::Sequence(list) => {
            for item in list {
                let val_str = match item.as_str() {
                    Some(s) => s,
                    None => continue,
                };
                let matches = detector.scan_line_with_positions(val_str, entropy_threshold);
                for m in matches {
                    let line_num = find_line_number(content, val_str);
                    let context = Context {
                        line_before: Some("Docker Compose environment list".to_string()),
                        line_content: truncate_for_context(val_str),
                        line_after: None,
                        is_test_file: file_context.is_test_file,
                        is_config_file: true,
                        is_documentation: false,
                        file_extension: file_context.file_extension.clone(),
                    };
                    let location = Location {
                        file_path: path.to_path_buf(),
                        line_number: line_num,
                        column_start: m.column_start,
                        column_end: m.column_end,
                        commit_hash: None,
                        commit_author: None,
                        commit_date: None,
                    };
                    findings.push(Finding::new(m.secret, location, context));
                }
            }
        }
        _ => {}
    }
}

// ── CloudFormation ───────────────────────────────────────────────────────────

fn scan_cloudformation(
    path: &Path,
    content: &str,
    detector: &PatternDetector,
    entropy_threshold: f64,
) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();
    let file_context = ContextAnalyzer::analyze_file(path);

    // Try JSON first, then YAML
    let value: serde_json::Value = if let Ok(v) = serde_json::from_str(content) {
        v
    } else {
        match serde_yaml::from_str::<serde_yaml::Value>(content) {
            Ok(yaml_val) => match serde_json::to_value(yaml_val) {
                Ok(v) => v,
                Err(e) => {
                    scan_warn!(
                        "parse",
                        "failed to convert CloudFormation YAML to JSON in {}: {}",
                        path.display(),
                        e
                    );
                    return Ok(findings);
                }
            },
            Err(e) => {
                scan_warn!(
                    "parse",
                    "failed to parse {} as CloudFormation (JSON/YAML): {}",
                    path.display(),
                    e
                );
                return Ok(findings);
            }
        }
    };

    // Scan Parameters for Default values
    if let Some(params) = value.get("Parameters").and_then(|p| p.as_object()) {
        for (param_name, param_val) in params {
            if let Some(default) = param_val.get("Default").and_then(|d| d.as_str()) {
                let matches = detector.scan_line_with_positions(default, entropy_threshold);
                for m in matches {
                    let line_num = find_line_number(content, default);
                    let context = Context {
                        line_before: Some(format!("CloudFormation Parameter: {}", param_name)),
                        line_content: truncate_for_context(default),
                        line_after: None,
                        is_test_file: file_context.is_test_file,
                        is_config_file: true,
                        is_documentation: false,
                        file_extension: file_context.file_extension.clone(),
                    };
                    let location = Location {
                        file_path: path.to_path_buf(),
                        line_number: line_num,
                        column_start: m.column_start,
                        column_end: m.column_end,
                        commit_hash: None,
                        commit_author: None,
                        commit_date: None,
                    };
                    findings.push(Finding::new(m.secret, location, context));
                }
            }
        }
    }

    // Recursively scan Resources for hardcoded secrets in properties
    if let Some(resources) = value.get("Resources") {
        walk_json_values(
            resources,
            path,
            &file_context,
            detector,
            entropy_threshold,
            &mut findings,
            "Resources",
        );
    }

    Ok(findings)
}

// ── Helpers ──────────────────────────────────────────────────────────────────

fn truncate_for_context(s: &str) -> String {
    if s.len() <= 120 {
        s.to_string()
    } else {
        format!("{}...", &s[..117])
    }
}

fn find_line_number(content: &str, needle: &str) -> usize {
    if let Some(pos) = content.find(needle) {
        content[..pos].lines().count() + 1
    } else {
        1
    }
}

fn looks_like_base64(s: &str) -> bool {
    if s.len() < 16 {
        return false;
    }
    let trimmed = s.trim();
    trimmed.chars().all(|c| {
        c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=' || c == '\n' || c == '\r'
    })
}

use serde::Deserialize;

// Re-export for other modules
pub fn format_label(fmt: StructuredFormat) -> &'static str {
    match fmt {
        StructuredFormat::TerraformState => "Terraform state",
        StructuredFormat::KubernetesSecret => "Kubernetes Secret",
        StructuredFormat::DockerCompose => "Docker Compose",
        StructuredFormat::CloudFormation => "CloudFormation",
    }
}

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

    #[test]
    fn test_detect_terraform_state() {
        let path = Path::new("terraform.tfstate");
        assert_eq!(
            detect_format(path, "{}"),
            Some(StructuredFormat::TerraformState)
        );
    }

    #[test]
    fn test_detect_kubernetes_secret() {
        let path = Path::new("secret.yaml");
        let content = "apiVersion: v1\nkind: Secret\ndata:\n  password: cGFzc3dvcmQ=";
        assert_eq!(
            detect_format(path, content),
            Some(StructuredFormat::KubernetesSecret)
        );
    }

    #[test]
    fn test_detect_docker_compose() {
        let path = Path::new("docker-compose.yml");
        assert_eq!(
            detect_format(path, "services:"),
            Some(StructuredFormat::DockerCompose)
        );
    }

    #[test]
    fn test_detect_cloudformation() {
        let path = Path::new("template.yaml");
        let content = "AWSTemplateFormatVersion: '2010-09-09'\nResources:";
        assert_eq!(
            detect_format(path, content),
            Some(StructuredFormat::CloudFormation)
        );
    }

    #[test]
    fn test_detect_normal_file() {
        let path = Path::new("main.rs");
        assert_eq!(detect_format(path, "fn main() {}"), None);
    }

    #[test]
    fn test_k8s_secret_base64_decode() {
        let content = r#"apiVersion: v1
kind: Secret
metadata:
  name: test-secret
data:
  aws_key: QUtJQVo1MkhHWFlSTjRXQlRFU1Q=
"#;
        let path = Path::new("secret.yaml");
        let detector = PatternDetector::new();
        let findings = scan_kubernetes_secret(path, content, &detector, 3.0).unwrap();
        assert!(
            !findings.is_empty(),
            "Should find AWS key in base64-encoded K8s secret"
        );
    }

    #[test]
    fn test_docker_compose_env() {
        let content = r#"
services:
  app:
    image: myapp
    environment:
      AWS_ACCESS_KEY_ID: AKIAZ52HGXYRN4WBTEST
      SAFE_VAR: hello
"#;
        let path = Path::new("docker-compose.yml");
        let detector = PatternDetector::new();
        let findings = scan_docker_compose(path, content, &detector, 3.0).unwrap();
        assert!(
            !findings.is_empty(),
            "Should find AWS key in docker-compose environment"
        );
    }

    #[test]
    fn test_looks_like_base64() {
        assert!(looks_like_base64("QUtJQVo1MkhHWFlSTjRXQlRFU1Q="));
        assert!(!looks_like_base64("short"));
        assert!(!looks_like_base64("this has spaces and symbols!@#"));
    }
}