nyx-scanner 0.6.1

A multi-language static analysis tool for detecting security vulnerabilities
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
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
#![allow(clippy::collapsible_if)]

// ─── PredicateKind ───────────────────────────────────────────────────────────

/// Classification of what an if-condition tests.
///
/// Determined by heuristic analysis of the raw condition text.
/// Classification is conservative: prefer [`Unknown`](PredicateKind::Unknown)
/// over a wrong guess.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PredicateKind {
    /// `x.is_none()`, `x == null`, `x == nil`, `x is None`
    NullCheck,
    /// `x.is_empty()`, `x.len() == 0`, `x == ""`
    EmptyCheck,
    /// `x.is_err()`, `x.is_ok()`, `err != nil`
    ErrorCheck,
    /// Call to a validation/guard function: `validate(x)`, `is_safe(x)`
    ValidationCall,
    /// Call to a sanitizer function: `sanitize(x)`, `escape(x)`
    SanitizerCall,
    /// Allowlist/membership check: `.includes(x)`, `x in ALLOWED`, `in_array(x, ...)`
    AllowlistCheck,
    /// Type-check guard: `typeof x`, `isinstance(x, int)`, `is_numeric(x)`
    TypeCheck,
    /// Negative-validation of shell metacharacters:
    /// `x.contains(";")`, `x.match(/[;|&]/)`, `";" in x`, etc.
    ///
    /// The **true branch is the REJECT path** (early return / panic / throw)
    /// and the **false branch is the validated path**.  Use inverted polarity
    /// when applying branch predicates.
    ShellMetaValidated,
    /// Bounded-length rejection: `x.len() > N` / `x.length < N` with N >= 2.
    ///
    /// Commonly paired with `ShellMetaValidated` in OR-chain rejection
    /// idioms (`if x.len() > MAX || x.contains(";") { reject }`).  Counts as
    /// a dominator guard for `cfg-unguarded-sink` purposes, but intentionally
    /// does **not** mark variables as validated, the rejection direction is
    /// ambiguous from the condition alone (a `.len() > 5 { sink(x) }`
    /// gate is a precondition, not a rejection).
    BoundedLength,
    /// Comparison operators: `x == 5`, `x > threshold`
    Comparison,
    /// Generic boolean test, cannot classify further.
    Unknown,
}

/// Single-character shell metacharacters that a rejection check commonly
/// guards against before constructing a shell command.
///
/// Presence of any of these in user input is sufficient to enable shell
/// injection, so rejecting input that contains them is a real sanitizer.
/// `"foo"` or other non-metachar needles don't qualify, a rejection of
/// those is business logic, not security.
const SHELL_METACHARS: &[&str] = &[";", "|", "&", "`", "$", ">", "<", "\n", "\r", "\0"];

/// Check whether `text` matches a shell-metachar rejection idiom.
///
/// Recognizes:
/// - Rust / Java / Go: `x.contains("<METACHAR>")`
/// - JS / TS:          `x.includes("<METACHAR>")`
/// - Python:           `"<METACHAR>" in x`
/// - Ruby:             `x.include?("<METACHAR>")`
/// - Regex form:       `x.match(/[;|&]/)` / `re.search(r"[;|&]", x)` with a
///   character class containing only metacharacters.
///
/// Returns `false` if the needle is a non-metachar literal or cannot be
/// extracted, falls through to broader classification.
fn is_shell_metachar_rejection(text: &str) -> bool {
    // Method-call form: `.contains(…)` / `.includes(…)` / `.include?(…)`
    for method in [".contains(", ".includes(", ".include?("] {
        if let Some(idx) = text.find(method) {
            let args_start = idx + method.len();
            if let Some(needle) = extract_first_string_arg(&text[args_start..]) {
                if SHELL_METACHARS.contains(&needle.as_str()) {
                    return true;
                }
            }
        }
    }
    // Python membership form: `"<METACHAR>" in x` (but not `x in ALLOWED`)
    if let Some(needle) = extract_python_in_needle(text) {
        if SHELL_METACHARS.contains(&needle.as_str()) {
            return true;
        }
    }
    // Regex character-class form: `.match(/[;|&]/)` / `re.search(r"[…]", …)`
    if is_metachar_regex_class(text) {
        return true;
    }
    false
}

/// Extract the first string literal argument from a slice starting just after
/// an opening `(` in a call expression.  Returns the raw inner text of the
/// literal (without surrounding quotes).
///
/// Handles `"..."`, `'...'`, and simple escapes `\"`, `\'`, `\\`.
fn extract_first_string_arg(after_open: &str) -> Option<String> {
    let bytes = after_open.as_bytes();
    let mut i = 0;
    while i < bytes.len() && bytes[i].is_ascii_whitespace() {
        i += 1;
    }
    if i >= bytes.len() {
        return None;
    }
    let quote = bytes[i];
    if quote != b'"' && quote != b'\'' {
        return None;
    }
    i += 1;
    let mut out = Vec::new();
    while i < bytes.len() {
        let b = bytes[i];
        if b == b'\\' && i + 1 < bytes.len() {
            match bytes[i + 1] {
                b'n' => out.push(b'\n'),
                b'r' => out.push(b'\r'),
                b't' => out.push(b'\t'),
                b'0' => out.push(b'\0'),
                c => out.push(c),
            }
            i += 2;
            continue;
        }
        if b == quote {
            return String::from_utf8(out).ok();
        }
        out.push(b);
        i += 1;
    }
    None
}

/// For Python `"<METACHAR>" in x` (needle on the left side of ` in `), return
/// the needle.  Returns `None` for `x in ALLOWED` (identifier on the left) ,
/// that is an allowlist check, not a rejection.
fn extract_python_in_needle(text: &str) -> Option<String> {
    let pos = text.find(" in ")?;
    let left = text[..pos].trim();
    // Strip leading `!` / `not` for rejection contexts
    let left = left.strip_prefix('!').unwrap_or(left).trim();
    let bytes = left.as_bytes();
    let quote = *bytes.first()?;
    if quote != b'"' && quote != b'\'' {
        return None;
    }
    if bytes.last() != Some(&quote) || bytes.len() < 2 {
        return None;
    }
    let inner = &left[1..left.len() - 1];
    Some(inner.to_string())
}

/// Detect regex character classes that contain only shell metacharacters:
/// `[;|&]`, `[;&`$]`, etc.  Missing: escape-class metacharacters inside the
/// class (e.g. `[\n]`), conservative, returns false there.
fn is_metachar_regex_class(text: &str) -> bool {
    // Find `[` followed by content and `]`, anywhere in the text.
    let mut rest = text;
    while let Some(open) = rest.find('[') {
        let after = &rest[open + 1..];
        if let Some(close) = after.find(']') {
            let inner = &after[..close];
            if !inner.is_empty()
                && inner
                    .chars()
                    .all(|c| SHELL_METACHARS.iter().any(|m| m.starts_with(c)))
            {
                return true;
            }
            rest = &after[close + 1..];
        } else {
            break;
        }
    }
    false
}

/// Check whether `text` looks like a bounded-length rejection:
/// `x.len() > N`, `x.len() < N`, `x.length >= N`, etc. where `N` is an
/// integer literal >= 2.  Excludes `> 0` / `>= 1` / `< 1`, those are
/// non-empty checks, which are not length-bound validations.
fn is_bounded_length_check(lower: &str) -> bool {
    const PROBES: &[&str] = &[
        ".len()", ".length", // JS/TS/Java `.length` property (no parens)
    ];
    for probe in PROBES {
        let mut rest = lower;
        while let Some(pos) = rest.find(probe) {
            let after = &rest[pos + probe.len()..];
            // Skip the optional `()` that `.length` never has but `.len` does.
            let after = after.trim_start();
            let after = after.strip_prefix("()").unwrap_or(after);
            let after = after.trim_start();
            for op in [">=", "<=", ">", "<"] {
                if let Some(tail) = after.strip_prefix(op) {
                    let tail = tail.trim_start();
                    if let Some(n) = parse_leading_uint(tail) {
                        if n >= 2 {
                            return true;
                        }
                    }
                    break;
                }
            }
            rest = &rest[pos + probe.len()..];
        }
    }
    false
}

/// Parse a leading non-negative integer literal (decimal only).
fn parse_leading_uint(s: &str) -> Option<u64> {
    let mut n: u64 = 0;
    let mut any = false;
    for c in s.chars() {
        if let Some(d) = c.to_digit(10) {
            n = n.checked_mul(10)?.checked_add(d as u64)?;
            any = true;
        } else {
            break;
        }
    }
    any.then_some(n)
}

/// Classify a raw condition text into a [`PredicateKind`].
///
/// # Rules
///
/// - Empty/None text → [`Unknown`](PredicateKind::Unknown).
/// - `ValidationCall` / `SanitizerCall` require a `(` in the text **and** a
///   matching callee token. This avoids misclassifying comparisons like
///   `x_valid == true`.
/// - Prefers [`Unknown`](PredicateKind::Unknown) over false positives.
pub fn classify_condition(text: &str) -> PredicateKind {
    if text.is_empty() {
        return PredicateKind::Unknown;
    }

    let lower = text.to_ascii_lowercase();

    // ── Error checks (before null checks: `err != nil` is an error check,
    //    not a null check, even though it contains `!= nil`) ──────────────
    if lower.contains("is_err")
        || lower.contains("is_ok")
        || lower.contains("err != nil")
        || lower.contains("err == nil")
        || lower.contains("error != nil")
        || lower.contains("error == nil")
    {
        return PredicateKind::ErrorCheck;
    }

    // ── Null checks ──────────────────────────────────────────────────────
    if lower.contains("is_none")
        || lower.contains("is_some")
        || lower.contains("== none")
        || lower.contains("!= none")
        || lower.contains("is none")
        || lower.contains("is not none")
        || lower.contains("== null")
        || lower.contains("!= null")
        || lower.contains("=== null")
        || lower.contains("!== null")
        || lower.contains("== nil")
        || lower.contains("!= nil")
    {
        return PredicateKind::NullCheck;
    }

    // ── Empty checks ─────────────────────────────────────────────────────
    if lower.contains("is_empty")
        || lower.contains(".len() == 0")
        || lower.contains(".len() != 0")
        || lower.contains(".length == 0")
        || lower.contains(".length === 0")
        || lower.contains(".length != 0")
        || lower.contains(".length !== 0")
        || lower.contains("== \"\"")
        || lower.contains("== ''")
    {
        return PredicateKind::EmptyCheck;
    }

    // ── Shell-metachar negative validation ───────────────────────────────
    //
    // Matched BEFORE AllowlistCheck so that `x.contains(";")` is recognized
    // as a rejection idiom rather than a membership test.  Checked on the
    // raw (non-lowercased) text so metacharacter comparisons stay
    // case-accurate, `;` / `|` / `&` have no case.
    if is_shell_metachar_rejection(text) {
        return PredicateKind::ShellMetaValidated;
    }

    // ── Allowlist / membership checks ────────────────────────────────────
    if lower.contains(".includes(")
        || lower.contains(".include?(")
        || lower.contains(".contains(")
        || lower.contains(".indexof(")
        || lower.contains(".has(")
        || lower.contains("in_array(")
        || lower.contains(" in ")
        || (lower.contains('[') && !lower.contains('('))
    {
        return PredicateKind::AllowlistCheck;
    }

    // ── Java/Kotlin Pattern.matcher().matches() chain (before TypeCheck) ─
    //
    // Recognise `<re>.matcher(value).matches()` as a regex allowlist
    // validator, not a TypeCheck.  The receiver of `.matcher(` must
    // contain `regex` or `pattern` so we don't widen to arbitrary
    // `obj.matcher(x).matches()` calls.  Surfaced by GHSA-h8cj-hpmg-636v
    // (Appsmith FILTER_TEMP_TABLE_NAME_PATTERN.matcher(tableName).matches()).
    // Matched here (before the generic `.matches(` TypeCheck branch
    // below) so the chain doesn't silently fall into TypeCheck.
    if let Some(matcher_pos) = lower.find(".matcher(")
        && lower[matcher_pos..].contains(".matches(")
    {
        let receiver = &lower[..matcher_pos];
        if receiver.contains("regex") || receiver.contains("pattern") {
            return PredicateKind::ValidationCall;
        }
    }

    // ── Type-check guards ──────────────────────────────────────────────
    if lower.contains("typeof ")
        || lower.contains("isinstance(")
        || lower.contains(" instanceof ")
        || lower.contains(".matches(")
        || lower.contains("is_numeric(")
        || lower.contains("is_int(")
        || lower.contains("is_string(")
        || lower.contains("is_float(")
        || lower.contains("ctype_")
        || lower.contains(".is_a?(")
        || lower.contains(".kind_of?(")
        // Rust character-class validation: `.chars().all(|c| c.is_ascii_*())`
        // and similar per-character validations.  Presence of `is_ascii_`
        // inside an `.all(…)` / `.iter().all(…)` call is a strong validation
        // signal equivalent to a TypeCheck.
        || (lower.contains(".all(") && lower.contains("is_ascii_"))
        || (lower.contains(".all(") && lower.contains("is_alphanumeric"))
        || (lower.contains(".all(") && lower.contains("is_numeric("))
    {
        return PredicateKind::TypeCheck;
    }

    // ── Bounded-length rejection ─────────────────────────────────────────
    //
    // `.len() > N` / `.length < N` with N >= 2.  Pairs with
    // ShellMetaValidated in OR-chain rejection patterns.  Kept as its own
    // kind (not TypeCheck) because the rejection direction is ambiguous: a
    // `.len() > 5 { sink(x) }` gate is a precondition, not a rejection, so
    // marking condition vars as validated on the true branch would silence
    // legitimate findings.  `cfg-unguarded-sink` still treats this as a
    // dominator guard (structural intent), just without SSA-level validation.
    if is_bounded_length_check(&lower) {
        return PredicateKind::BoundedLength;
    }

    // ── Call-based kinds (require `(` to be present) ─────────────────────
    if lower.contains('(') {
        // Strip leading wrappers (parens, `!`, whitespace) before locating
        // the callee token.  Without this, idiomatic forms like
        // `(!validate(x))` (TypeScript / JS) or `not validate(x)` (Python)
        // produce an empty `callee_part` and the classifier misses
        // ValidationCall, defeating downstream validated-must propagation.
        let trimmed = lower.trim_start_matches(['(', '!', ' ', '\t']);
        // Strip a leading `not ` keyword (Python boolean not) plus surrounding
        // whitespace.  Without this, `not validate_no_dotdot(raw)` skips
        // ValidationCall classification and validation never propagates.
        let trimmed = trimmed.strip_prefix("not ").unwrap_or(trimmed).trim();
        // Extract a rough callee token: everything before the first `(`
        // that looks like an identifier (letters, digits, underscores, dots).
        let callee_part = trimmed.split('(').next().unwrap_or("");
        // Take the last segment (after `.` or `::`) as the bare name.
        let bare = callee_part
            .rsplit(['.', ':'])
            .next()
            .unwrap_or(callee_part)
            .trim();

        // Validation
        if bare.contains("valid")
            || bare.contains("check")
            || bare.contains("verify")
            || bare.starts_with("is_safe")
            || bare.starts_with("is_authorized")
            || bare.starts_with("is_authenticated")
        {
            return PredicateKind::ValidationCall;
        }

        // Regex / pattern allowlist `<X>.test(value)` / `<X>.match(value)` calls
        // where the receiver name carries a regex or pattern marker.  The
        // standard JS / TS / Python / Java / Ruby / Go regex APIs all expose a
        // boolean test method; the success arm (true) means `value` matches the
        // pattern.  Conservative on receiver names so non-regex methods like
        // `obj.test(x)` (test runner), `db.test(...)` (test column) etc. don't
        // get pulled in.  Motivated by Payload CVE-2026-25544
        // (`if (!SAFE_STRING_REGEX.test(value)) throw …;`).
        if (bare == "test" || bare == "match" || bare == "matches")
            && let Some(dot_pos) = callee_part.rfind('.')
        {
            let receiver = &callee_part[..dot_pos];
            let receiver_lower = receiver.to_ascii_lowercase();
            if receiver_lower.contains("regex") || receiver_lower.contains("pattern") {
                return PredicateKind::ValidationCall;
            }
        }

        // Java idiom `<PATTERN>.matcher(value).matches()` — the regex
        // allowlist on Java/Kotlin is a two-step chain (`Pattern.matcher`
        // returns a `Matcher`, `.matches()` is the boolean predicate).
        // The bare callee here is `matches` (no args), so the
        // single-call recogniser above doesn't fire.  Lock on the
        // chain shape and require the receiver of `.matcher(` to carry
        // a regex / pattern marker so we don't widen to `.matcher(` on
        // arbitrary types.  Surfaced by GHSA-h8cj-hpmg-636v
        // (Appsmith FILTER_TEMP_TABLE_NAME_PATTERN.matcher(tableName).matches()).
        if bare == "matches"
            && let Some(matcher_pos) = lower.find(".matcher(")
        {
            let receiver = &lower[..matcher_pos];
            if receiver.contains("regex") || receiver.contains("pattern") {
                return PredicateKind::ValidationCall;
            }
        }

        // Sanitizer
        if bare.contains("sanitiz") || bare.contains("escape") || bare.contains("encode") {
            return PredicateKind::SanitizerCall;
        }
    }

    // ── Comparison operators ─────────────────────────────────────────────
    if lower.contains("==")
        || lower.contains("!=")
        || lower.contains(">=")
        || lower.contains("<=")
        || lower.contains(" > ")
        || lower.contains(" < ")
    {
        return PredicateKind::Comparison;
    }

    PredicateKind::Unknown
}

/// Classify a condition AND extract the specific validated variable target.
///
/// For `ValidationCall`/`SanitizerCall`, tries to extract the first argument
/// or method receiver as the validated variable:
/// - `validate(x, ...)` → target = `"x"`
/// - `x.validate(...)` → target = `"x"`
///
/// When target extraction fails on a multi-argument call (e.g.,
/// `validate(expr, limit)` where `expr` is not a plain identifier), the
/// validator's effect is opaque: we can't tell which argument is being
/// checked. Returning the original kind with `None` target would cause
/// upstream code to over-validate (mark every `condition_var` as validated).
/// Instead, we fall back to `PredicateKind::Unknown`, safer to assume the
/// validator did nothing than to assume it validated every variable in the
/// condition. Single-argument calls retain `(kind, None)` so downstream code
/// can still use the predicate-summary bit tracking.
pub fn classify_condition_with_target(text: &str) -> (PredicateKind, Option<String>) {
    let kind = classify_condition(text);

    match kind {
        PredicateKind::ValidationCall | PredicateKind::SanitizerCall => {
            if let Some(target) = extract_validation_target(text) {
                (kind, Some(target))
            } else if count_call_args(text).map(|n| n > 1).unwrap_or(false) {
                (PredicateKind::Unknown, None)
            } else {
                (kind, None)
            }
        }
        PredicateKind::AllowlistCheck => {
            let target = extract_allowlist_target(text);
            (kind, target)
        }
        PredicateKind::TypeCheck => {
            let target = extract_type_check_target(text);
            (kind, target)
        }
        PredicateKind::ShellMetaValidated => {
            // The receiver of `.contains(…)` / `.includes(…)` is the value
            // being validated.  Reuses the validation extractor which already
            // handles `x.method(arg)` → `"x"`.
            let target = extract_validation_target(text);
            (kind, target)
        }
        PredicateKind::Comparison => {
            // `x === '/login'`, `x == 5`, `null != obj`, when exactly one
            // side is a literal, extract the identifier side as the target.
            // Downstream `apply_branch_predicates` uses this to mark the
            // variable as `validated_may` on the true (equal) branch.
            let target = extract_comparison_target(text);
            (kind, target)
        }
        _ => (kind, None),
    }
}

/// Extract the identifier side of an equality/inequality comparison where
/// exactly one side is a scalar literal.
///
/// Examples:
/// - `x === '/login'` → `Some("x")`
/// - `x !== 5` → `Some("x")`
/// - `null != obj` → `Some("obj")`
/// - `x === y` → `None` (neither side is a literal)
/// - `'a' == 'b'` → `None` (both sides are literals)
/// - `obj.field == 3` → `None` (not a bare identifier)
///
/// Best-effort text analysis, kept conservative to avoid false validation.
fn extract_comparison_target(text: &str) -> Option<String> {
    let trimmed = text.trim();

    // Find the operator token.  Check longer forms first so `===` doesn't
    // match as `==` with a trailing `=`.
    for op in &["===", "!==", "==", "!="] {
        if let Some(pos) = trimmed.find(op) {
            let left = trimmed[..pos].trim();
            let right = trimmed[pos + op.len()..].trim();
            let left_is_ident = is_identifier(left);
            let right_is_ident = is_identifier(right);
            let left_is_lit = is_comparison_literal(left);
            let right_is_lit = is_comparison_literal(right);
            return match (left_is_ident, right_is_ident, left_is_lit, right_is_lit) {
                (true, _, false, true) => Some(left.to_string()),
                (_, true, true, false) => Some(right.to_string()),
                _ => None,
            };
        }
    }
    None
}

/// Test whether `s` is a scalar literal for comparison-target extraction.
/// Accepts string literals (single/double/backtick quoted), numeric literals,
/// and the null/undefined/nil/true/false tokens.
fn is_comparison_literal(s: &str) -> bool {
    let s = s.trim();
    if s.is_empty() {
        return false;
    }

    // String literal: delimited by matching quotes.
    let bytes = s.as_bytes();
    if bytes.len() >= 2 {
        let first = bytes[0];
        let last = bytes[bytes.len() - 1];
        if (first == b'"' || first == b'\'' || first == b'`') && first == last {
            return true;
        }
    }

    // Keyword literal tokens.
    if matches!(s, "null" | "undefined" | "nil" | "None" | "true" | "false") {
        return true;
    }

    // Numeric literal: optional sign + digits, optional decimal point.
    let mut chars = s.chars();
    let first = chars.next().unwrap();
    let rest_start = if first == '-' || first == '+' {
        match chars.next() {
            Some(c) => c,
            None => return false,
        }
    } else {
        first
    };
    if !rest_start.is_ascii_digit() {
        return false;
    }
    s.chars()
        .skip(if first == '-' || first == '+' { 1 } else { 0 })
        .all(|c| c.is_ascii_digit() || c == '.' || c == '_')
}

/// Count positional arguments in a call-shaped condition text.
///
/// Returns `None` when the text does not look like a call (no `(`). Returns
/// `Some(0)` for a call with empty argument list. Respects paren/bracket/brace
/// nesting so `f(g(a, b), c)` counts as 2 top-level args.
///
/// Best-effort, operates on source text, not an AST. Used by
/// `classify_condition_with_target` to distinguish single-arg vs multi-arg
/// validator calls when target extraction fails.
fn count_call_args(text: &str) -> Option<usize> {
    let trimmed = text.trim();
    let trimmed = trimmed.strip_prefix('!').unwrap_or(trimmed).trim();
    let paren_pos = trimmed.find('(')?;
    let args_part = &trimmed[paren_pos + 1..];
    let args_inner = args_part
        .trim_end()
        .strip_suffix(')')
        .unwrap_or(args_part)
        .trim();
    if args_inner.is_empty() {
        return Some(0);
    }
    let mut count = 1usize;
    let mut depth: i32 = 0;
    for ch in args_inner.chars() {
        match ch {
            '(' | '[' | '{' => depth += 1,
            ')' | ']' | '}' => depth -= 1,
            ',' if depth == 0 => count += 1,
            _ => {}
        }
    }
    Some(count)
}

/// Extract the first top-level argument from `args_part`, the substring
/// immediately following the open paren of a call expression.  Walks
/// paren/bracket/brace depth and skips quoted strings so nested calls and
/// punctuation inside string literals do not confuse the scan.  Returns
/// the trimmed argument substring up to the first top-level `,` or
/// matching `)`, or `None` when no balanced close paren is found.
///
/// Robust against trailing wrapper parens such as
/// `(!ALLOWED.includes(cmd))` where naïve `strip_suffix(')')` would leave
/// `cmd)` and lose the argument.
fn first_call_arg(args_part: &str) -> Option<&str> {
    let bytes = args_part.as_bytes();
    let mut depth: usize = 1;
    let mut end: Option<usize> = None;
    let mut first_comma: Option<usize> = None;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        match b {
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => {
                depth -= 1;
                if depth == 0 {
                    end = Some(i);
                    break;
                }
            }
            b',' if depth == 1 && first_comma.is_none() => first_comma = Some(i),
            b'"' | b'\'' => {
                let quote = b;
                i += 1;
                while i < bytes.len() {
                    if bytes[i] == b'\\' && i + 1 < bytes.len() {
                        i += 2;
                        continue;
                    }
                    if bytes[i] == quote {
                        break;
                    }
                    i += 1;
                }
            }
            _ => {}
        }
        i += 1;
    }
    let end = end?;
    let cut = first_comma.unwrap_or(end);
    Some(args_part[..cut].trim())
}

/// Extract the validated variable from a condition text.
///
/// Handles two patterns:
/// - Function call: `validate(x, ...)` → `"x"`
/// - Method call: `x.validate(...)` → `"x"`
fn extract_validation_target(text: &str) -> Option<String> {
    let trimmed = text.trim();

    // Strip leading wrappers (parens, `!`, `not `) so idiomatic forms like
    // `(!validate(x))` (TS/JS) and `not validate(x)` (Python) are reachable.
    let trimmed = trimmed.trim_start_matches(['(', '!', ' ', '\t']);
    let trimmed = trimmed.strip_prefix("not ").unwrap_or(trimmed).trim();

    // Java/Kotlin chain `<re>.matcher(value).matches()`: the validated
    // target is the inner `.matcher()` argument, not the bare `.matches()`
    // receiver.  Locked on the same regex/pattern receiver gate as the
    // classifier (GHSA-h8cj-hpmg-636v).
    if trimmed.to_ascii_lowercase().contains(".matches(")
        && let Some(matcher_pos) = trimmed.find(".matcher(")
    {
        let receiver_lower = trimmed[..matcher_pos].to_ascii_lowercase();
        if receiver_lower.contains("regex") || receiver_lower.contains("pattern") {
            let args_start = matcher_pos + ".matcher(".len();
            if let Some(first_arg) = first_call_arg(&trimmed[args_start..]) {
                let first_arg = first_arg.strip_prefix('&').unwrap_or(first_arg).trim();
                if !first_arg.is_empty() && is_identifier(first_arg) {
                    return Some(first_arg.to_string());
                }
            }
        }
    }

    // Find the first `(` which separates callee from args
    let paren_pos = trimmed.find('(')?;
    let callee_part = &trimmed[..paren_pos];
    let args_part = &trimmed[paren_pos + 1..];

    // Check for method call pattern: `x.method(...)` or `x.method_name(...)`
    if let Some(dot_pos) = callee_part.rfind('.') {
        let receiver = callee_part[..dot_pos].trim();
        let method = callee_part[dot_pos + 1..].trim().to_ascii_lowercase();
        // Regex-allowlist `<re>.test(value)` / `<re>.match(value)` / `<re>.matches(value)`:
        // the validated target is the call's first argument, not the regex
        // receiver.  Without this special case, branch narrowing would mark
        // the regex itself as validated and leave the user input alone.
        if matches!(method.as_str(), "test" | "match" | "matches")
            && let Some(first_arg) = first_call_arg(args_part)
        {
            let first_arg = first_arg.strip_prefix('&').unwrap_or(first_arg).trim();
            if !first_arg.is_empty() && is_identifier(first_arg) {
                return Some(first_arg.to_string());
            }
        }
        if !receiver.is_empty() && is_identifier(receiver) {
            return Some(receiver.to_string());
        }
    }

    // Function call pattern: `func(x, ...)`, extract first argument with
    // balanced-paren scan so trailing wrapper parens (`(validate(x))`) do
    // not corrupt the argument substring.
    let first_arg = first_call_arg(args_part)?;

    // Strip reference operators (e.g. `&x` → `x`)
    let first_arg = first_arg.strip_prefix('&').unwrap_or(first_arg).trim();

    if !first_arg.is_empty() && is_identifier(first_arg) {
        Some(first_arg.to_string())
    } else {
        None
    }
}

/// Extract the target variable from an allowlist/membership check.
///
/// Handles:
/// - `.includes(cmd)` → `cmd` (first argument)
/// - `in_array($cmd, $allowed)` → `cmd` (first arg, strip `$`)
/// - `cmd not in ALLOWED` / `cmd in ALLOWED` → `cmd` (left of ` in `)
/// - `allowed[cmd]` → `cmd` (inside brackets)
fn extract_allowlist_target(text: &str) -> Option<String> {
    let trimmed = text.trim();
    let lower = trimmed.to_ascii_lowercase();

    // Method call pattern: something.includes(arg) / .contains(arg) / .has(arg) / .indexof(arg)
    for method in &[
        ".includes(",
        ".include?(",
        ".contains(",
        ".indexof(",
        ".has(",
    ] {
        if let Some(pos) = lower.find(method) {
            let args_start = pos + method.len();
            let args_part = &trimmed[args_start..];
            if let Some(first_arg) = first_call_arg(args_part) {
                let first_arg = first_arg.strip_prefix('$').unwrap_or(first_arg);
                if !first_arg.is_empty() && is_identifier(first_arg) {
                    return Some(first_arg.to_string());
                }
            }
        }
    }

    // in_array($cmd, $allowed) → cmd
    if let Some(pos) = lower.find("in_array(") {
        let args_start = pos + "in_array(".len();
        let args_part = &trimmed[args_start..];
        if let Some(first_arg) = first_call_arg(args_part) {
            let first_arg = first_arg.strip_prefix('$').unwrap_or(first_arg);
            if !first_arg.is_empty() && is_identifier(first_arg) {
                return Some(first_arg.to_string());
            }
        }
    }

    // Python `in` operator: `cmd in ALLOWED` / `cmd not in ALLOWED`
    if lower.contains(" in ") {
        // Find the leftmost ` in `, everything before it is the target expression
        // Handle `not in` by looking for ` not in ` first
        let target_part = if let Some(pos) = lower.find(" not in ") {
            &trimmed[..pos]
        } else if let Some(pos) = lower.find(" in ") {
            &trimmed[..pos]
        } else {
            return None;
        };
        let target = target_part.trim();
        let target = target.strip_prefix('!').unwrap_or(target).trim();
        let target = target.strip_prefix('$').unwrap_or(target);
        if !target.is_empty() && is_identifier(target) {
            return Some(target.to_string());
        }
    }

    // Go map lookup: `allowed[cmd]`
    if let Some(open) = trimmed.find('[') {
        if let Some(close) = trimmed.find(']') {
            if close > open + 1 {
                let inner = trimmed[open + 1..close].trim();
                let inner = inner.strip_prefix('$').unwrap_or(inner);
                if !inner.is_empty() && is_identifier(inner) {
                    return Some(inner.to_string());
                }
            }
        }
    }

    None
}

/// Extract the target variable from a type-check guard.
///
/// Handles:
/// - `typeof input !== 'number'` → `input` (word after `typeof`)
/// - `isinstance(user_id, int)` → `user_id` (first arg)
/// - `input.matches("\\d+")` → `input` (receiver)
/// - `is_numeric($id)` → `id` (first arg, strip `$`)
fn extract_type_check_target(text: &str) -> Option<String> {
    let trimmed = text.trim();
    let lower = trimmed.to_ascii_lowercase();

    // typeof: `typeof input !== 'number'`
    if let Some(pos) = lower.find("typeof ") {
        let after = &trimmed[pos + "typeof ".len()..];
        // The target is the next identifier-like word
        let target: String = after
            .chars()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .collect();
        if !target.is_empty() {
            return Some(target);
        }
    }

    // isinstance(user_id, int) → user_id
    if let Some(pos) = lower.find("isinstance(") {
        let args_start = pos + "isinstance(".len();
        let args_part = &trimmed[args_start..];
        let inner = args_part.strip_suffix(')').unwrap_or(args_part);
        let first_arg = inner.split(',').next()?.trim();
        let first_arg = first_arg.strip_prefix('$').unwrap_or(first_arg);
        if !first_arg.is_empty() && is_identifier(first_arg) {
            return Some(first_arg.to_string());
        }
    }

    // Java/TS instanceof: "x instanceof String" → "x"
    if let Some(pos) = lower.find(" instanceof ") {
        let var_part = trimmed[..pos].trim();
        if !var_part.is_empty() && is_identifier(var_part) {
            return Some(var_part.to_string());
        }
    }

    // .matches("...") → receiver
    if let Some(pos) = lower.find(".matches(") {
        let receiver = trimmed[..pos].trim();
        let receiver = receiver.strip_prefix('!').unwrap_or(receiver).trim();
        if !receiver.is_empty() && is_identifier(receiver) {
            return Some(receiver.to_string());
        }
    }

    // PHP type checks: is_numeric($id), is_int($x), is_string($x), is_float($x)
    for func in &["is_numeric(", "is_int(", "is_string(", "is_float("] {
        if let Some(pos) = lower.find(func) {
            let args_start = pos + func.len();
            let args_part = &trimmed[args_start..];
            let inner = args_part.strip_suffix(')').unwrap_or(args_part);
            let first_arg = inner.split(',').next()?.trim();
            let first_arg = first_arg.strip_prefix('$').unwrap_or(first_arg);
            if !first_arg.is_empty() && is_identifier(first_arg) {
                return Some(first_arg.to_string());
            }
        }
    }

    // Ruby type checks: user_id.is_a?(Integer), x.kind_of?(String) → receiver
    for method in &[".is_a?(", ".kind_of?("] {
        if let Some(pos) = lower.find(method) {
            let receiver = trimmed[..pos].trim();
            let receiver = receiver.strip_prefix('!').unwrap_or(receiver).trim();
            if !receiver.is_empty() && is_identifier(receiver) {
                return Some(receiver.to_string());
            }
        }
    }

    // ctype_ functions: ctype_digit($x)
    if let Some(pos) = lower.find("ctype_") {
        // Find the `(` after ctype_xxx
        if let Some(paren_pos) = trimmed[pos..].find('(') {
            let args_start = pos + paren_pos + 1;
            let args_part = &trimmed[args_start..];
            let inner = args_part.strip_suffix(')').unwrap_or(args_part);
            let first_arg = inner.split(',').next()?.trim();
            let first_arg = first_arg.strip_prefix('$').unwrap_or(first_arg);
            if !first_arg.is_empty() && is_identifier(first_arg) {
                return Some(first_arg.to_string());
            }
        }
    }

    None
}

/// Check if a string is a simple identifier (letters, digits, underscores, dots).
fn is_identifier(s: &str) -> bool {
    !s.is_empty()
        && s.chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '.')
        && !s.starts_with(|c: char| c.is_ascii_digit())
}

// ─── Tests ───────────────────────────────────────────────────────────────────

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

    // ── classify_condition ────────────────────────────────────────────────

    #[test]
    fn classify_empty_is_unknown() {
        assert_eq!(classify_condition(""), PredicateKind::Unknown);
    }

    #[test]
    fn classify_null_checks() {
        assert_eq!(classify_condition("x.is_none()"), PredicateKind::NullCheck);
        assert_eq!(classify_condition("x == null"), PredicateKind::NullCheck);
        assert_eq!(classify_condition("x != nil"), PredicateKind::NullCheck);
        assert_eq!(classify_condition("x is None"), PredicateKind::NullCheck);
        assert_eq!(classify_condition("x === null"), PredicateKind::NullCheck);
    }

    #[test]
    fn classify_error_checks() {
        assert_eq!(classify_condition("x.is_err()"), PredicateKind::ErrorCheck);
        assert_eq!(classify_condition("err != nil"), PredicateKind::ErrorCheck);
        assert_eq!(classify_condition("x.is_ok()"), PredicateKind::ErrorCheck);
    }

    #[test]
    fn classify_empty_checks() {
        assert_eq!(
            classify_condition("x.is_empty()"),
            PredicateKind::EmptyCheck
        );
        assert_eq!(
            classify_condition("x.len() == 0"),
            PredicateKind::EmptyCheck
        );
        assert_eq!(
            classify_condition("x.length === 0"),
            PredicateKind::EmptyCheck
        );
    }

    #[test]
    fn classify_validation_call() {
        assert_eq!(
            classify_condition("validate(x)"),
            PredicateKind::ValidationCall
        );
        assert_eq!(
            classify_condition("is_safe(input)"),
            PredicateKind::ValidationCall
        );
        assert_eq!(
            classify_condition("check_auth(req)"),
            PredicateKind::ValidationCall
        );
        assert_eq!(
            classify_condition("input.verify(sig)"),
            PredicateKind::ValidationCall
        );
    }

    #[test]
    fn classify_validation_requires_paren() {
        // `x_valid == true` should NOT be ValidationCall, no `(` call syntax.
        assert_eq!(
            classify_condition("x_valid == true"),
            PredicateKind::Comparison
        );
        assert_eq!(
            classify_condition("is_valid && ready"),
            PredicateKind::Unknown
        );
    }

    #[test]
    fn classify_sanitizer_call() {
        assert_eq!(
            classify_condition("sanitize(x)"),
            PredicateKind::SanitizerCall
        );
        assert_eq!(
            classify_condition("html_escape(s)"),
            PredicateKind::SanitizerCall
        );
        assert_eq!(
            classify_condition("url_encode(path)"),
            PredicateKind::SanitizerCall
        );
    }

    #[test]
    fn classify_comparison() {
        assert_eq!(classify_condition("x == 5"), PredicateKind::Comparison);
        assert_eq!(classify_condition("x != y"), PredicateKind::Comparison);
        assert_eq!(classify_condition("a >= b"), PredicateKind::Comparison);
    }

    #[test]
    fn classify_unknown_fallback() {
        assert_eq!(classify_condition("flag"), PredicateKind::Unknown);
        assert_eq!(classify_condition("a && b"), PredicateKind::Unknown);
    }

    // ── classify_condition_with_target ──────────────────────────────────

    #[test]
    fn target_function_call_first_arg() {
        let (kind, target) = classify_condition_with_target("validate(x, config)");
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target.as_deref(), Some("x"));
    }

    #[test]
    fn target_method_call_receiver() {
        let (kind, target) = classify_condition_with_target("x.isValid()");
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target.as_deref(), Some("x"));
    }

    #[test]
    fn target_sanitizer_first_arg() {
        let (kind, target) = classify_condition_with_target("sanitize(input)");
        assert_eq!(kind, PredicateKind::SanitizerCall);
        assert_eq!(target.as_deref(), Some("input"));
    }

    #[test]
    fn target_negated_validation() {
        let (kind, target) = classify_condition_with_target("!validate(&x)");
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target.as_deref(), Some("x"));
    }

    /// Regex `<X>.test(value)` should classify as ValidationCall and the
    /// validated target should be the call argument, not the regex
    /// receiver.  Pinned because the receiver-as-target heuristic is the
    /// default for method calls.  Motivated by Payload CVE-2026-25544
    /// (`if (!SAFE_STRING_REGEX.test(value)) throw …;`).
    #[test]
    fn target_regex_test_first_arg() {
        let (kind, target) = classify_condition_with_target("!SAFE_STRING_REGEX.test(value)");
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target.as_deref(), Some("value"));
    }

    #[test]
    fn target_regex_test_pattern_receiver() {
        let (kind, target) = classify_condition_with_target("ALLOWED_PATTERN.test(s)");
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target.as_deref(), Some("s"));
    }

    /// Receiver name without a regex/pattern marker should NOT be pulled
    /// in as a validator: `obj.test(x)` is a test runner, not a regex.
    #[test]
    fn target_test_non_regex_receiver_is_not_validation() {
        let kind = classify_condition("obj.test(value)");
        assert_eq!(kind, PredicateKind::Unknown);
    }

    #[test]
    fn target_comparison_extracts_identifier_side() {
        let (kind, target) = classify_condition_with_target("x == 5");
        assert_eq!(kind, PredicateKind::Comparison);
        assert_eq!(target.as_deref(), Some("x"));
    }

    #[test]
    fn target_comparison_strict_equality_with_string() {
        let (kind, target) = classify_condition_with_target("x === '/login'");
        assert_eq!(kind, PredicateKind::Comparison);
        assert_eq!(target.as_deref(), Some("x"));
    }

    #[test]
    fn target_comparison_literal_on_left() {
        let (kind, target) = classify_condition_with_target("null != obj");
        assert_eq!(kind, PredicateKind::Comparison);
        assert_eq!(target.as_deref(), Some("obj"));
    }

    #[test]
    fn target_comparison_both_identifiers_returns_none() {
        let (kind, target) = classify_condition_with_target("x === y");
        assert_eq!(kind, PredicateKind::Comparison);
        assert_eq!(target, None);
    }

    #[test]
    fn target_comparison_both_literals_returns_none() {
        let (kind, target) = classify_condition_with_target("'a' == 'b'");
        assert_eq!(kind, PredicateKind::Comparison);
        assert_eq!(target, None);
    }

    #[test]
    fn target_check_auth_first_arg() {
        let (kind, target) = classify_condition_with_target("check_auth(req)");
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target.as_deref(), Some("req"));
    }

    #[test]
    fn target_method_with_args() {
        let (kind, target) = classify_condition_with_target("input.verify(sig)");
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target.as_deref(), Some("input"));
    }

    #[test]
    fn target_multi_arg_fallback_opaque_expr_is_unknown() {
        // `validate(x + 1, y)`, first arg is an expression, not an identifier.
        // Target extraction fails. Multi-arg call, so fall back to Unknown
        // rather than letting upstream validate every condition var.
        let (kind, target) = classify_condition_with_target("validate(x + 1, y)");
        assert_eq!(kind, PredicateKind::Unknown);
        assert_eq!(target, None);
    }

    #[test]
    fn target_single_arg_fallback_preserves_kind() {
        // Single-arg call with unextractable target: keep the original kind so
        // the predicate-summary bit can still be set. No over-validation risk
        // because there is only one var in scope.
        let (kind, target) = classify_condition_with_target("validate(x + 1)");
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target, None);
    }

    #[test]
    fn count_call_args_basic() {
        assert_eq!(super::count_call_args("f(a, b, c)"), Some(3));
        assert_eq!(super::count_call_args("f(a)"), Some(1));
        assert_eq!(super::count_call_args("f()"), Some(0));
        assert_eq!(super::count_call_args("f(g(x, y), z)"), Some(2));
        assert_eq!(super::count_call_args("not_a_call"), None);
    }

    // ── AllowlistCheck classification ─────────────────────────────────

    #[test]
    fn classify_allowlist_includes() {
        assert_eq!(
            classify_condition("ALLOWED.includes(cmd)"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn classify_allowlist_in_array() {
        assert_eq!(
            classify_condition("in_array($cmd, $allowed)"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn classify_allowlist_python_not_in() {
        assert_eq!(
            classify_condition("cmd not in ALLOWED"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn classify_allowlist_python_in() {
        assert_eq!(
            classify_condition("cmd in ALLOWED"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn classify_allowlist_map_lookup() {
        assert_eq!(
            classify_condition("allowed[cmd]"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn classify_allowlist_contains() {
        assert_eq!(
            classify_condition("whitelist.contains(value)"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn classify_allowlist_has() {
        assert_eq!(
            classify_condition("allowedSet.has(key)"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn extract_allowlist_target_negated_paren_wrapper() {
        // Tree-sitter records the if-condition as `(!ALLOWED.includes(cmd))`,
        // including the surrounding parens.  Naïve `strip_suffix(')')` left
        // `cmd)` and `is_identifier` rejected the trailing `)`, dropping the
        // structural guard for `cfg-unguarded-sink` suppression.  The
        // balanced-paren scan must return `Some("cmd")`.
        let (kind, target) = classify_condition_with_target("(!ALLOWED.includes(cmd))");
        assert_eq!(kind, PredicateKind::AllowlistCheck);
        assert_eq!(target.as_deref(), Some("cmd"));
    }

    #[test]
    fn extract_allowlist_target_java_contains_paren_wrapper() {
        let (kind, target) = classify_condition_with_target("(!ALLOWED.contains(cmd))");
        assert_eq!(kind, PredicateKind::AllowlistCheck);
        assert_eq!(target.as_deref(), Some("cmd"));
    }

    #[test]
    fn extract_allowlist_target_in_array_paren_wrapper() {
        let (kind, target) = classify_condition_with_target("(!in_array($cmd, $allowed))");
        assert_eq!(kind, PredicateKind::AllowlistCheck);
        assert_eq!(target.as_deref(), Some("cmd"));
    }

    // ── TypeCheck classification ──────────────────────────────────────

    #[test]
    fn classify_type_check_typeof() {
        assert_eq!(
            classify_condition("typeof input !== 'number'"),
            PredicateKind::TypeCheck
        );
    }

    #[test]
    fn classify_type_check_isinstance() {
        assert_eq!(
            classify_condition("isinstance(user_id, int)"),
            PredicateKind::TypeCheck
        );
    }

    #[test]
    fn classify_type_check_matches() {
        assert_eq!(
            classify_condition("input.matches(\"\\\\d+\")"),
            PredicateKind::TypeCheck
        );
    }

    #[test]
    fn classify_type_check_is_numeric() {
        assert_eq!(
            classify_condition("is_numeric($id)"),
            PredicateKind::TypeCheck
        );
    }

    #[test]
    fn classify_type_check_is_int() {
        assert_eq!(classify_condition("is_int($x)"), PredicateKind::TypeCheck);
    }

    #[test]
    fn classify_type_check_ctype() {
        assert_eq!(
            classify_condition("ctype_digit($x)"),
            PredicateKind::TypeCheck
        );
    }

    // ── Allowlist target extraction ───────────────────────────────────

    #[test]
    fn target_allowlist_includes() {
        let (kind, target) = classify_condition_with_target("ALLOWED.includes(cmd)");
        assert_eq!(kind, PredicateKind::AllowlistCheck);
        assert_eq!(target.as_deref(), Some("cmd"));
    }

    #[test]
    fn target_allowlist_in_array() {
        let (kind, target) = classify_condition_with_target("in_array($cmd, $allowed)");
        assert_eq!(kind, PredicateKind::AllowlistCheck);
        assert_eq!(target.as_deref(), Some("cmd"));
    }

    #[test]
    fn target_allowlist_python_in() {
        let (kind, target) = classify_condition_with_target("cmd in ALLOWED");
        assert_eq!(kind, PredicateKind::AllowlistCheck);
        assert_eq!(target.as_deref(), Some("cmd"));
    }

    #[test]
    fn target_allowlist_python_not_in() {
        let (kind, target) = classify_condition_with_target("cmd not in ALLOWED");
        assert_eq!(kind, PredicateKind::AllowlistCheck);
        assert_eq!(target.as_deref(), Some("cmd"));
    }

    #[test]
    fn target_allowlist_map_lookup() {
        let (kind, target) = classify_condition_with_target("allowed[cmd]");
        assert_eq!(kind, PredicateKind::AllowlistCheck);
        assert_eq!(target.as_deref(), Some("cmd"));
    }

    // ── TypeCheck target extraction ───────────────────────────────────

    #[test]
    fn target_type_check_typeof() {
        let (kind, target) = classify_condition_with_target("typeof input !== 'number'");
        assert_eq!(kind, PredicateKind::TypeCheck);
        assert_eq!(target.as_deref(), Some("input"));
    }

    #[test]
    fn target_type_check_isinstance() {
        let (kind, target) = classify_condition_with_target("isinstance(user_id, int)");
        assert_eq!(kind, PredicateKind::TypeCheck);
        assert_eq!(target.as_deref(), Some("user_id"));
    }

    #[test]
    fn target_type_check_matches() {
        let (kind, target) = classify_condition_with_target("input.matches(\"\\\\d+\")");
        assert_eq!(kind, PredicateKind::TypeCheck);
        assert_eq!(target.as_deref(), Some("input"));
    }

    #[test]
    fn target_type_check_is_numeric() {
        let (kind, target) = classify_condition_with_target("is_numeric($id)");
        assert_eq!(kind, PredicateKind::TypeCheck);
        assert_eq!(target.as_deref(), Some("id"));
    }

    #[test]
    fn target_type_check_ctype() {
        let (kind, target) = classify_condition_with_target("ctype_digit($x)");
        assert_eq!(kind, PredicateKind::TypeCheck);
        assert_eq!(target.as_deref(), Some("x"));
    }

    #[test]
    fn classify_type_check_is_a() {
        assert_eq!(
            classify_condition("user_id.is_a?(Integer)"),
            PredicateKind::TypeCheck
        );
    }

    #[test]
    fn target_type_check_is_a() {
        let (kind, target) = classify_condition_with_target("user_id.is_a?(Integer)");
        assert_eq!(kind, PredicateKind::TypeCheck);
        assert_eq!(target.as_deref(), Some("user_id"));
    }

    #[test]
    fn classify_allowlist_include_question() {
        assert_eq!(
            classify_condition("ALLOWED.include?(cmd)"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn target_allowlist_include_question() {
        let (kind, target) = classify_condition_with_target("ALLOWED.include?(cmd)");
        assert_eq!(kind, PredicateKind::AllowlistCheck);
        assert_eq!(target.as_deref(), Some("cmd"));
    }

    // ── instanceof classification and target ─────────────────────────────

    #[test]
    fn classify_instanceof_is_type_check() {
        assert_eq!(
            classify_condition("x instanceof String"),
            PredicateKind::TypeCheck
        );
    }

    #[test]
    fn target_instanceof_x_string() {
        let (kind, target) = classify_condition_with_target("x instanceof String");
        assert_eq!(kind, PredicateKind::TypeCheck);
        assert_eq!(target.as_deref(), Some("x"));
    }

    #[test]
    fn target_instanceof_obj_integer() {
        let (kind, target) = classify_condition_with_target("obj instanceof Integer");
        assert_eq!(kind, PredicateKind::TypeCheck);
        assert_eq!(target.as_deref(), Some("obj"));
    }

    // ── ShellMetaValidated classification ─────────────────────────────────

    #[test]
    fn classify_shell_metachar_contains_rust() {
        assert_eq!(
            classify_condition("input.contains(\";\")"),
            PredicateKind::ShellMetaValidated
        );
        assert_eq!(
            classify_condition("cmd.contains(\"|\")"),
            PredicateKind::ShellMetaValidated
        );
        assert_eq!(
            classify_condition("s.contains(\"&\")"),
            PredicateKind::ShellMetaValidated
        );
        assert_eq!(
            classify_condition("s.contains(\"`\")"),
            PredicateKind::ShellMetaValidated
        );
        assert_eq!(
            classify_condition("s.contains(\"$\")"),
            PredicateKind::ShellMetaValidated
        );
    }

    #[test]
    fn classify_shell_metachar_includes_js() {
        assert_eq!(
            classify_condition("input.includes(';')"),
            PredicateKind::ShellMetaValidated
        );
        assert_eq!(
            classify_condition("cmd.includes(\"|\")"),
            PredicateKind::ShellMetaValidated
        );
    }

    #[test]
    fn classify_shell_metachar_include_question_ruby() {
        assert_eq!(
            classify_condition("cmd.include?(\";\")"),
            PredicateKind::ShellMetaValidated
        );
    }

    #[test]
    fn classify_shell_metachar_python_in() {
        assert_eq!(
            classify_condition("\";\" in cmd"),
            PredicateKind::ShellMetaValidated
        );
        assert_eq!(
            classify_condition("'|' in cmd"),
            PredicateKind::ShellMetaValidated
        );
    }

    #[test]
    fn classify_shell_metachar_regex_class() {
        assert_eq!(
            classify_condition("cmd.match(/[;|&]/)"),
            PredicateKind::ShellMetaValidated
        );
        assert_eq!(
            classify_condition("re.search(\"[;|&]\", cmd)"),
            PredicateKind::ShellMetaValidated
        );
    }

    #[test]
    fn classify_non_metachar_contains_stays_allowlist() {
        // `x.contains("foo")` must NOT be credited as a shell-metachar
        // rejection.  It falls back to the existing AllowlistCheck behavior.
        assert_eq!(
            classify_condition("input.contains(\"foo\")"),
            PredicateKind::AllowlistCheck
        );
        assert_eq!(
            classify_condition("path.contains(\"..\")"),
            PredicateKind::AllowlistCheck
        );
        assert_eq!(
            classify_condition("name.contains(\"admin\")"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn classify_allowlist_membership_unaffected() {
        // `x in ALLOWED` (identifier on left) remains AllowlistCheck.
        // Only a quoted metachar on the LEFT of ` in ` triggers ShellMeta.
        assert_eq!(
            classify_condition("cmd in ALLOWED"),
            PredicateKind::AllowlistCheck
        );
        assert_eq!(
            classify_condition("cmd not in ALLOWED"),
            PredicateKind::AllowlistCheck
        );
    }

    #[test]
    fn target_shell_metachar_receiver() {
        let (kind, target) = classify_condition_with_target("input.contains(\";\")");
        assert_eq!(kind, PredicateKind::ShellMetaValidated);
        assert_eq!(target.as_deref(), Some("input"));
    }

    // ── Bounded-length TypeCheck ──────────────────────────────────────────

    #[test]
    fn classify_bounded_length_rust_len() {
        assert_eq!(
            classify_condition("input.len() > 100"),
            PredicateKind::BoundedLength
        );
        assert_eq!(
            classify_condition("s.len() >= 256"),
            PredicateKind::BoundedLength
        );
        assert_eq!(
            classify_condition("s.len() < 4096"),
            PredicateKind::BoundedLength
        );
    }

    #[test]
    fn classify_bounded_length_js_length() {
        assert_eq!(
            classify_condition("input.length > 100"),
            PredicateKind::BoundedLength
        );
    }

    #[test]
    fn classify_non_empty_len_stays_comparison() {
        // `.len() > 0` is a non-empty check, NOT a bounded-length validation.
        // Must fall through to Comparison.
        assert_eq!(
            classify_condition("input.len() > 0"),
            PredicateKind::Comparison
        );
        assert_eq!(
            classify_condition("s.len() >= 1"),
            PredicateKind::Comparison
        );
    }

    // ── Helper sanity ─────────────────────────────────────────────────────

    #[test]
    fn shell_metachar_rejection_detects_common_chars() {
        for m in &[";", "|", "&", "`", "$", ">", "<"] {
            let text = format!("x.contains(\"{m}\")");
            assert!(
                is_shell_metachar_rejection(&text),
                "should detect metachar {m:?} in {text:?}"
            );
        }
    }

    #[test]
    fn shell_metachar_rejection_rejects_non_metachar() {
        assert!(!is_shell_metachar_rejection("x.contains(\"foo\")"));
        assert!(!is_shell_metachar_rejection("x.contains(\"admin\")"));
        assert!(!is_shell_metachar_rejection("x.contains(\"..\")"));
    }

    #[test]
    fn shell_metachar_rejection_handles_escapes() {
        assert!(is_shell_metachar_rejection("x.contains(\"\\n\")"));
    }

    #[test]
    fn bounded_length_rejects_zero_and_one() {
        assert!(!is_bounded_length_check("x.len() > 0"));
        assert!(!is_bounded_length_check("x.len() >= 1"));
        assert!(!is_bounded_length_check("x.len() < 1"));
    }

    #[test]
    fn bounded_length_accepts_small_bounds() {
        assert!(is_bounded_length_check("x.len() > 2"));
        assert!(is_bounded_length_check("x.len() <= 256"));
    }
}

#[cfg(test)]
mod ghsa_h8cj_hpmg_636v_tests {
    use super::*;
    #[test]
    fn java_pattern_matcher_chain_classifies_as_validation() {
        let kind =
            classify_condition("FILTER_TEMP_TABLE_NAME_PATTERN.matcher(tableName).matches()");
        assert_eq!(
            kind,
            PredicateKind::ValidationCall,
            "matcher().matches() chain on PATTERN-named receiver should be ValidationCall"
        );
    }
    #[test]
    fn java_pattern_matcher_chain_target_is_matcher_arg() {
        let (kind, target) = classify_condition_with_target(
            "FILTER_TEMP_TABLE_NAME_PATTERN.matcher(tableName).matches()",
        );
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target.as_deref(), Some("tableName"));
    }
    #[test]
    fn java_negated_pattern_matcher_chain_target_is_matcher_arg() {
        let (kind, target) = classify_condition_with_target(
            "!FILTER_TEMP_TABLE_NAME_PATTERN.matcher(tableName).matches()",
        );
        assert_eq!(kind, PredicateKind::ValidationCall);
        assert_eq!(target.as_deref(), Some("tableName"));
    }
    #[test]
    fn java_pattern_matcher_chain_non_pattern_receiver_is_not_validation() {
        // Precision guard: only fires when receiver name has regex/pattern marker.
        let kind = classify_condition("obj.matcher(x).matches()");
        assert!(
            kind != PredicateKind::ValidationCall,
            "no regex marker should not trigger validation"
        );
    }
}