brrr-lint 0.1.0

A fast linter and language server for F* (FStar) with autofix capabilities
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
//! FST017: Security checker for cryptographic code.
//!
//! Detects common cryptographic security issues in F* code:
//!
//! 1. Hardcoded secrets - keys, passwords, tokens embedded in source
//! 2. RawIntTypes usage - may break secret independence guarantees
//! 3. Secret-dependent branches - potential timing side-channel vulnerabilities
//! 4. Buffer operations without bounds verification
//! 5. Key variables without zeroization
//! 6. Nonce/IV initialization issues
//! 7. Division/modulo timing leaks on secrets
//!
//! This rule specifically targets crypto-related files (Hacl*, Crypto*, Spec*).
//!
//! IMPORTANT: This rule distinguishes between PUBLIC and SECRET types in F*:
//!
//! - PUBLIC (safe for branches/division):
//!   - `size_t`, `size_nat` - public size types
//!   - Size operators: `/. `, `%. `, `<. `, `>. `, `=. `, `<>. `, `<=. `, `>=. `
//!   - Variables like `len`, `bLen`, `bBits`, `i`, `j`, `k` (indices/lengths)
//!   - Size literals: `0ul`, `1ul`, `32ul`, etc.
//!
//! - SECRET (requires constant-time operations):
//!   - `uint_t t SEC`, `uint #t #SEC`, `limb t` - secret integers
//!   - Variables named `key`, `secret`, `priv`, or containing these substrings
//!   - Operations on cryptographic values
//!
//! HACL* is designed to be constant-time, and this linter respects that by
//! not flagging valid patterns like `len /. 2ul` or `if i <. len then`.

use lazy_static::lazy_static;
use regex::Regex;
use std::path::PathBuf;

use super::rules::{Diagnostic, DiagnosticSeverity, Range, Rule, RuleCode};

lazy_static! {
    // === Existing patterns ===

    /// Potential secret-dependent branch pattern.
    /// Matches conditionals comparing variables that may contain secrets.
    /// NOTE: This is now more conservative - we check context for public types.
    static ref SECRET_BRANCH: Regex = Regex::new(
        r"if\s+(?:v\s+)?(\w+)\s*(?:=|<>|<|>|<=|>=)"
    ).unwrap();

    /// Hardcoded secrets patterns - matches assignments of string literals
    /// to variables with security-sensitive names.
    static ref HARDCODED_KEY: Regex = Regex::new(
        r#"(?:key|secret|password|token)\s*=\s*["'][^"']+["']"#
    ).unwrap();

    /// Key usage pattern - tracks where key variables are referenced.
    static ref KEY_USAGE: Regex = Regex::new(r"\bkey\b").unwrap();

    /// RawIntTypes module usage - can break secret independence guarantees
    /// by exposing implementation details or enabling timing attacks.
    static ref RAW_INT_TYPES: Regex = Regex::new(r"\bRawIntTypes\b").unwrap();

    /// Constant-time mask operations (GOOD patterns) - indicate proper
    /// side-channel resistant implementations.
    static ref CT_MASK: Regex = Regex::new(r"\b(?:eq_mask|gte_mask|lt_mask|gt_mask|lte_mask|neq_mask)\b").unwrap();

    /// Secret-indicating variable name patterns.
    /// Base pattern - refined by is_secret_variable() helper function.
    static ref SECRET_VAR_PATTERN: Regex = Regex::new(
        r"\b(\w*(?:key|secret|priv)\w*)\b"
    ).unwrap();

    /// Metadata suffixes that indicate a value is NOT secret (e.g., key_len, secret_size).
    static ref METADATA_SUFFIX: Regex = Regex::new(
        r"(?i)(?:_len|_length|_size|_sz|_bytes|_bits|len$|length$|size$|bits$)"
    ).unwrap();

    /// Function name prefixes that indicate a function, not a secret variable.
    static ref FUNCTION_PREFIX: Regex = Regex::new(
        r"^(?:update_|get_|set_|init_|derive_|expand_|clear_|malloc_|blake2_|poly1305_|chacha20_|aead_|hmac_|hash_|encrypt_|decrypt_|sign_|verify_)"
    ).unwrap();

    // === F* Public Type Patterns (safe for branches/division) ===

    /// Size type operators in F* - these operate on public size_t values.
    /// Examples: `/. `, `%. `, `<. `, `>. `, `=. `, `<>. `, `<=. `, `>=. `
    static ref SIZE_OPERATORS: Regex = Regex::new(
        r"(?:/\.|%\.|<\.|>\.|=\.|<>\.|<=\.|>=\.)"
    ).unwrap();

    /// Size literals in F* - public values like `0ul`, `1ul`, `32ul`.
    static ref SIZE_LITERAL: Regex = Regex::new(r"\b\d+ul\b").unwrap();

    /// Public size variable names - indices, lengths, bit counts.
    /// These are commonly used in HACL* and are always public.
    static ref PUBLIC_VAR_NAMES: Regex = Regex::new(
        r"\b(?:len|bLen|aLen|cLen|nLen|bBits|nBits|ind|idx|pbits|nbits|table_len|ctx_len)\b"
    ).unwrap();

    /// Loop index variable patterns - typically single letters used in loops.
    /// When used with size operators, these are public.
    static ref LOOP_INDEX: Regex = Regex::new(r"\bfor\s+\d+ul\s+\w+\s+inv").unwrap();

    /// F* SEC (secret) type annotation - marks secret integers.
    static ref SEC_TYPE: Regex = Regex::new(
        r"(?:uint_t\s+\w+\s+SEC|uint\s+#\w+\s+#SEC|\bSEC\b)"
    ).unwrap();

    /// F* PUB (public) type annotation - marks public integers.
    static ref PUB_TYPE: Regex = Regex::new(
        r"(?:uint_t\s+\w+\s+PUB|uint\s+#\w+\s+#PUB|\bPUB\b)"
    ).unwrap();

    /// Size type declarations - these are always public.
    static ref SIZE_TYPE_DECL: Regex = Regex::new(
        r"(?:size_t|size_nat|size_pos)\b"
    ).unwrap();

    /// Mask select operations (constant-time conditional).
    static ref MASK_SELECT: Regex = Regex::new(r"\bmask_select\b").unwrap();

    // === Buffer operations patterns ===

    /// Buffer.index without explicit bounds - potential out-of-bounds access.
    static ref BUFFER_INDEX: Regex = Regex::new(r"Buffer\.index\s+\w+\s+(\w+)").unwrap();

    /// Buffer.sub slice operation - needs bounds verification.
    static ref BUFFER_SUB: Regex = Regex::new(r"Buffer\.sub\s+\w+\s+(\w+)\s+(\w+)").unwrap();

    /// Buffer.blit copy operation - needs bounds on both source and destination.
    static ref BUFFER_BLIT: Regex = Regex::new(r"Buffer\.blit\s+").unwrap();

    /// Unsafe buffer upd without length check.
    static ref BUFFER_UPD: Regex = Regex::new(r"Buffer\.upd\s+\w+\s+(\w+)").unwrap();

    // === Key/secret lifecycle patterns ===

    /// Key buffer allocation - matches ACTUAL buffer allocations containing secrets.
    /// Pattern: `let key = create/alloca/sub/malloc ...`
    /// This specifically matches buffer creation operations, not function definitions.
    static ref KEY_BUFFER_ALLOC: Regex = Regex::new(
        r"let\s+(\w*(?:key|secret|priv)\w*)\s*=\s*(?:create|alloca|sub|malloc|gcmalloc|B\.create|Buffer\.create)\b"
    ).unwrap();

    /// Names that indicate metadata (length/size), NOT the actual secret.
    /// These suffixes are excluded from key zeroization warnings.
    static ref KEY_METADATA_SUFFIX: Regex = Regex::new(
        r"(?i)(?:_len|_length|_size|_sz|_bytes|_bits|len$|length$|size$)"
    ).unwrap();

    /// Function name patterns - prefixes for functions operating on keys.
    /// These are function names, not key buffer variables.
    static ref KEY_FUNCTION_PREFIX: Regex = Regex::new(
        r"^(?:update_|get_|set_|init_|derive_|expand_|clear_|malloc_|blake2_|poly1305_|chacha20_|aead_|hmac_)"
    ).unwrap();

    /// Type definition suffix - indicates a type alias, not a variable.
    static ref TYPE_DEF_SUFFIX: Regex = Regex::new(r"(?:_st|_t)$").unwrap();

    /// Function definition pattern - detects `let name : type -> type` or `val name :`.
    /// These are function definitions, not variable bindings.
    static ref FUNCTION_TYPE_DEF: Regex = Regex::new(
        r"(?:let|val)\s+\w+\s*:\s*[^=]*->"
    ).unwrap();

    /// Memory zeroing function call - should be used to clear secrets.
    static ref MEMZERO: Regex = Regex::new(r"\bmemzero\b").unwrap();

    /// Clear function variants for secret cleanup.
    static ref CLEAR_FN: Regex = Regex::new(r"\b(?:clear_\w+|wipe|scrub)\b").unwrap();

    /// Secret allocation on stack - may leak on early returns.
    /// Matches actual buffer allocation with secret-like content.
    static ref STACK_ALLOC_SECRET: Regex = Regex::new(
        r"let\s+\w*(?:secret|priv)\w*\s*=\s*(?:create|alloca)\s+"
    ).unwrap();

    // === Nonce/IV patterns ===

    /// Nonce variable detection.
    static ref NONCE_VAR: Regex = Regex::new(r"\bnonce\b").unwrap();

    /// IV (initialization vector) variable detection.
    static ref IV_VAR: Regex = Regex::new(r"\biv\b").unwrap();

    /// Counter variable that may be used as nonce.
    static ref COUNTER_VAR: Regex = Regex::new(r"\b(?:counter|ctr)\b").unwrap();

    /// Random source usage (good pattern for nonce generation).
    static ref RANDOM_SOURCE: Regex = Regex::new(r"(?i)\b(?:random|randombytes|getrandom)\b").unwrap();

    /// Zero initialization (bad for nonce/IV).
    static ref ZERO_INIT: Regex = Regex::new(r"(?:=|<-)\s*(?:0x0+|0+)\s*$").unwrap();

    // === Timing side-channel patterns ===

    /// Division by variable (potential timing leak).
    /// NOTE: `/. ` is the PUBLIC size division operator - safe!
    /// Only flag bare `/` without the dot when operating on secrets.
    static ref DIV_BY_VAR: Regex = Regex::new(r"/\s*(\w+)").unwrap();

    /// Size division operator (PUBLIC - safe).
    /// In F*, `/. ` operates on size_t values which are public.
    static ref SIZE_DIV: Regex = Regex::new(r"/\.").unwrap();

    /// Modulo by variable (potential timing leak).
    /// NOTE: `%. ` is the PUBLIC size modulo operator - safe!
    static ref MOD_BY_VAR: Regex = Regex::new(r"%\s*(\w+)").unwrap();

    /// Size modulo operator (PUBLIC - safe).
    /// In F*, `%. ` operates on size_t values which are public.
    static ref SIZE_MOD: Regex = Regex::new(r"%\.").unwrap();

    /// Comparison operators on potential secrets in if conditions.
    /// Must be more specific to avoid false positives on public comparisons.
    static ref SECRET_COMPARISON: Regex = Regex::new(
        r"if\s+.*\b(\w*(?:_key|secret_|_secret|priv_|_priv)\w*)\s*(?:=|<>|<|>|<=|>=)"
    ).unwrap();

    /// Public comparison operators in F* (size comparisons - safe).
    /// Examples: `<. `, `>. `, `=. `, `<>. `, `<=. `, `>=. `
    static ref SIZE_COMPARISON: Regex = Regex::new(r"(?:<\.|>\.|=\.|<>\.|<=\.|>=\.)").unwrap();

    /// Early return pattern that may leak information.
    static ref EARLY_RETURN: Regex = Regex::new(r"\breturn\b").unwrap();

    /// Short-circuit evaluation on secrets (timing leak).
    static ref SHORT_CIRCUIT: Regex = Regex::new(r"(?:&&|\|\|)").unwrap();

    /// Secret type annotation in function signatures.
    /// Used to detect functions operating on secret data.
    static ref SECRET_PARAM: Regex = Regex::new(
        r"(?:uint_t\s+\w+\s+SEC|limb\s+\w+|lbuffer\s+\(uint_t\s+\w+\s+SEC\))"
    ).unwrap();

    // === Safe constant-time operations (GOOD patterns) ===

    /// Constant-time select operations.
    static ref CT_SELECT: Regex = Regex::new(r"\b(?:ct_select|select_constant_time|cmov)\b").unwrap();

    /// Constant-time comparison operations.
    static ref CT_COMPARE: Regex = Regex::new(
        r"\b(?:ct_compare|constant_time_compare|crypto_verify|verify_\d+)\b"
    ).unwrap();

    /// Constant-time conditional operations.
    static ref CT_COND: Regex = Regex::new(r"\b(?:ct_cond|constant_time_cond)\b").unwrap();

    // === Bounds check patterns (GOOD patterns) ===

    /// Explicit length check before buffer operation.
    static ref LENGTH_CHECK: Regex = Regex::new(r"(?:length|len|size)\s*(?:>=|>|<=|<|=)\s*\d+").unwrap();

    /// Assert for bounds verification.
    static ref BOUNDS_ASSERT: Regex = Regex::new(r"assert\s*\(.*(?:length|len|<|>)").unwrap();

    /// Requires clause with length constraint.
    static ref REQUIRES_LEN: Regex = Regex::new(r"requires\s*\{.*(?:length|len)").unwrap();
}

/// FST017: Security checker for cryptographic F* code.
///
/// Analyzes code for common cryptographic security issues including
/// hardcoded secrets, potential timing vulnerabilities, buffer safety,
/// key lifecycle management, and nonce handling.
pub struct SecurityRule;

impl SecurityRule {
    /// Create a new SecurityRule instance.
    pub fn new() -> Self {
        Self
    }

    /// Check if a file is crypto-related based on its path.
    ///
    /// Returns true for files in HACL*, Crypto, or Spec directories.
    fn is_crypto_file(file: &PathBuf) -> bool {
        let filename = file.to_string_lossy();
        filename.contains("Hacl")
            || filename.contains("Crypto")
            || filename.contains("crypto")
            || filename.contains("Spec")
    }

    /// Check if a file is a specification module (not compiled to executable code).
    ///
    /// In F*, Spec modules contain mathematical specifications used for verification.
    /// They are NOT compiled to executable code, so timing attacks don't apply.
    /// Pattern: `*.Spec.*` or `Spec.*` in the filename.
    fn is_spec_module(file: &PathBuf) -> bool {
        let filename = file.to_string_lossy();
        // Match patterns like:
        // - Hacl.Spec.Bignum.fst
        // - Spec.Blake2.fst
        // - anything.Spec.something.fst
        filename.contains(".Spec.") || filename.starts_with("Spec.")
    }

    /// Check for buffer operations without obvious bounds verification.
    ///
    /// Scans surrounding context for length checks, asserts, or requires clauses.
    fn check_buffer_operations(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();
        let lines: Vec<&str> = content.lines().collect();

        for (line_num, line) in lines.iter().enumerate() {
            let line_number = line_num + 1;

            // Skip comments
            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") || trimmed.starts_with("*") {
                continue;
            }

            // Check Buffer.index usage
            if BUFFER_INDEX.is_match(line) {
                if !self.has_bounds_context(&lines, line_num) {
                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST017,
                        severity: DiagnosticSeverity::Hint,
                        file: file.clone(),
                        range: Range::point(line_number, 1),
                        message: "Buffer.index without visible bounds check - verify index is within bounds".to_string(),
                        fix: None,
                    });
                }
            }

            // Check Buffer.sub usage
            if BUFFER_SUB.is_match(line) {
                if !self.has_bounds_context(&lines, line_num) {
                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST017,
                        severity: DiagnosticSeverity::Hint,
                        file: file.clone(),
                        range: Range::point(line_number, 1),
                        message: "Buffer.sub without visible bounds check - verify start+len is within bounds".to_string(),
                        fix: None,
                    });
                }
            }

            // Check Buffer.blit usage
            if BUFFER_BLIT.is_match(line) {
                if !self.has_bounds_context(&lines, line_num) {
                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST017,
                        severity: DiagnosticSeverity::Hint,
                        file: file.clone(),
                        range: Range::point(line_number, 1),
                        message: "Buffer.blit without visible bounds check - verify both buffers have sufficient space".to_string(),
                        fix: None,
                    });
                }
            }

            // Check Buffer.upd usage
            if BUFFER_UPD.is_match(line) {
                if !self.has_bounds_context(&lines, line_num) {
                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST017,
                        severity: DiagnosticSeverity::Hint,
                        file: file.clone(),
                        range: Range::point(line_number, 1),
                        message: "Buffer.upd without visible bounds check - verify index is within bounds".to_string(),
                        fix: None,
                    });
                }
            }
        }

        diagnostics
    }

    /// Check if there's a bounds verification in the surrounding context.
    ///
    /// Looks at a window of lines before/after for length checks,
    /// asserts, or requires clauses.
    fn has_bounds_context(&self, lines: &[&str], current_line: usize) -> bool {
        // Look at 5 lines before and after
        let start = current_line.saturating_sub(5);
        let end = (current_line + 5).min(lines.len());

        for i in start..end {
            let line = lines[i];
            if LENGTH_CHECK.is_match(line)
                || BOUNDS_ASSERT.is_match(line)
                || REQUIRES_LEN.is_match(line)
            {
                return true;
            }
        }
        false
    }

    /// Check if a variable name represents a metadata value (length, size, etc.)
    /// rather than actual secret data.
    fn is_key_metadata(name: &str) -> bool {
        KEY_METADATA_SUFFIX.is_match(name)
    }

    /// Check if a variable name looks like a function name rather than a buffer variable.
    fn is_function_name(name: &str) -> bool {
        KEY_FUNCTION_PREFIX.is_match(name) || TYPE_DEF_SUFFIX.is_match(name)
    }

    /// Check if a line is a function/type definition (not a variable binding).
    fn is_function_definition(line: &str) -> bool {
        FUNCTION_TYPE_DEF.is_match(line)
    }

    /// Check if a variable name indicates it holds secret data.
    /// Returns false for:
    /// - Metadata names: key_len, key_size, secret_length, etc.
    /// - Function names: update_key, derive_key, init_secret, etc.
    /// - Type names: key_t, key_st
    /// - Loop indices and public variables
    fn is_secret_variable(name: &str) -> bool {
        // Must contain a secret-indicating substring
        let lower = name.to_lowercase();
        let has_secret_indicator =
            lower.contains("key") || lower.contains("secret") || lower.contains("priv");

        if !has_secret_indicator {
            return false;
        }

        // Exclude metadata (lengths, sizes, etc.)
        if METADATA_SUFFIX.is_match(name) {
            return false;
        }

        // Exclude function names
        if FUNCTION_PREFIX.is_match(name) {
            return false;
        }

        // Exclude type definitions
        if TYPE_DEF_SUFFIX.is_match(name) {
            return false;
        }

        true
    }

    /// Check if a line contains a secret variable that would be affected by timing.
    fn line_has_secret_variable(line: &str) -> bool {
        SECRET_VAR_PATTERN
            .captures_iter(line)
            .filter_map(|c| c.get(1))
            .any(|m| Self::is_secret_variable(m.as_str()))
    }

    /// Check for key variables that may not be properly zeroized.
    ///
    /// This function uses precise pattern matching to avoid false positives:
    /// - Only matches actual buffer allocations (create, alloca, sub, malloc)
    /// - Excludes length/size variables (key_len, key_size, etc.)
    /// - Excludes function names (update_key, derive_key, etc.)
    /// - Excludes type definitions (key_st, key_t, etc.)
    fn check_key_zeroization(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        // Collect actual key buffer allocations with line numbers
        // Must be: let <name> = create/alloca/sub/malloc (actual buffer allocation)
        let key_vars: Vec<(usize, String)> = content
            .lines()
            .enumerate()
            .filter_map(|(i, line)| {
                // Skip comments
                let trimmed = line.trim();
                if trimmed.starts_with("(*")
                    || trimmed.starts_with("//")
                    || trimmed.starts_with("*")
                {
                    return None;
                }

                // Skip function/type definitions
                if Self::is_function_definition(line) {
                    return None;
                }

                // Match actual buffer allocations
                KEY_BUFFER_ALLOC
                    .captures(line)
                    .and_then(|c| c.get(1))
                    .map(|m| m.as_str().to_string())
                    .filter(|name| {
                        // Exclude metadata variables (lengths, sizes)
                        !Self::is_key_metadata(name)
                            // Exclude function names
                            && !Self::is_function_name(name)
                    })
                    .map(|name| (i + 1, name))
            })
            .collect();

        // Check if any cleanup function is present in the file
        let has_cleanup = MEMZERO.is_match(content) || CLEAR_FN.is_match(content);

        // If there are key allocations but no cleanup, warn
        for (line, key_var) in &key_vars {
            // Only warn if no cleanup is found anywhere in the file
            if !has_cleanup {
                diagnostics.push(Diagnostic {
                    rule: RuleCode::FST017,
                    severity: DiagnosticSeverity::Warning,
                    file: file.clone(),
                    range: Range::point(*line, 1),
                    message: format!(
                        "Key buffer `{}` may not be zeroized - use `memzero` or `clear_*` before deallocation",
                        key_var
                    ),
                    fix: None,
                });
            }
        }

        // Check for stack-allocated secrets (may leak on early returns)
        for (line_num, line) in content.lines().enumerate() {
            // Skip comments
            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") || trimmed.starts_with("*") {
                continue;
            }

            if STACK_ALLOC_SECRET.is_match(line) {
                diagnostics.push(Diagnostic {
                    rule: RuleCode::FST017,
                    severity: DiagnosticSeverity::Hint,
                    file: file.clone(),
                    range: Range::point(line_num + 1, 1),
                    message:
                        "Stack-allocated secret may leak on early return - ensure cleanup on all paths"
                            .to_string(),
                    fix: None,
                });
            }
        }

        diagnostics
    }

    /// Check for nonce/IV initialization issues.
    ///
    /// Detects zero-initialization of nonces and missing random sources.
    fn check_nonce_patterns(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for (line_num, line) in content.lines().enumerate() {
            let line_number = line_num + 1;

            // Skip comments
            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") || trimmed.starts_with("*") {
                continue;
            }

            let is_nonce_line =
                NONCE_VAR.is_match(line) || IV_VAR.is_match(line) || COUNTER_VAR.is_match(line);

            if !is_nonce_line {
                continue;
            }

            // Check for zero initialization of nonce/IV
            if ZERO_INIT.is_match(line) {
                diagnostics.push(Diagnostic {
                    rule: RuleCode::FST017,
                    severity: DiagnosticSeverity::Error,
                    file: file.clone(),
                    range: Range::point(line_number, 1),
                    message:
                        "Nonce/IV initialized to zero - use random generation or unique counter"
                            .to_string(),
                    fix: None,
                });
            }

            // Check for assignment without random source
            if (line.contains('=') || line.contains("<-"))
                && !RANDOM_SOURCE.is_match(line)
                && !line.contains("increment")
                && !line.contains("++")
                && !line.contains("+")
            {
                // Look for a literal assignment (not from another variable that might be random)
                if line.contains("0x") || trimmed.ends_with("0") {
                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST017,
                        severity: DiagnosticSeverity::Warning,
                        file: file.clone(),
                        range: Range::point(line_number, 1),
                        message: "Nonce/IV assigned constant value - ensure uniqueness for each encryption".to_string(),
                        fix: None,
                    });
                }
            }
        }

        diagnostics
    }

    /// Check for timing side-channel vulnerabilities.
    ///
    /// Detects division/modulo on secrets and early returns based on secret comparisons.
    fn check_timing_patterns(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        for (line_num, line) in content.lines().enumerate() {
            let line_number = line_num + 1;

            // Skip comments
            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") || trimmed.starts_with("*") {
                continue;
            }

            // Skip lines that use constant-time operations
            if CT_SELECT.is_match(line) || CT_COMPARE.is_match(line) || CT_COND.is_match(line) {
                continue;
            }

            // Check division/modulo operations involving secrets
            // Use refined check that excludes metadata (key_len, key_size, etc.)
            if (DIV_BY_VAR.is_match(line) || MOD_BY_VAR.is_match(line))
                && Self::line_has_secret_variable(line)
            {
                diagnostics.push(Diagnostic {
                    rule: RuleCode::FST017,
                    severity: DiagnosticSeverity::Warning,
                    file: file.clone(),
                    range: Range::point(line_number, 1),
                    message: "Division/modulo operation on secret data may leak timing information"
                        .to_string(),
                    fix: None,
                });
            }

            // Check early return based on secret comparison
            if EARLY_RETURN.is_match(line) && SECRET_COMPARISON.is_match(line) {
                diagnostics.push(Diagnostic {
                    rule: RuleCode::FST017,
                    severity: DiagnosticSeverity::Warning,
                    file: file.clone(),
                    range: Range::point(line_number, 1),
                    message: "Early return based on secret value may leak timing information"
                        .to_string(),
                    fix: None,
                });
            }

            // Check short-circuit evaluation on secrets
            // Use refined check that excludes metadata (key_len, key_size, etc.)
            if SHORT_CIRCUIT.is_match(line) && Self::line_has_secret_variable(line) {
                // Only warn if it looks like a boolean expression on secret
                if line.contains("if ") || line.contains("then") || line.contains("else") {
                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST017,
                        severity: DiagnosticSeverity::Hint,
                        file: file.clone(),
                        range: Range::point(line_number, 1),
                        message: "Short-circuit evaluation on secret may leak timing information - consider constant-time alternative".to_string(),
                        fix: None,
                    });
                }
            }
        }

        diagnostics
    }
}

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

impl Rule for SecurityRule {
    fn code(&self) -> RuleCode {
        RuleCode::FST017
    }

    fn check(&self, file: &PathBuf, content: &str) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        // Only check crypto-related files to reduce false positives
        if !Self::is_crypto_file(file) {
            return diagnostics;
        }

        // Run line-by-line checks for original patterns
        for (line_num, line) in content.lines().enumerate() {
            let line_number = line_num + 1;

            // Skip comment lines (simple heuristic)
            let trimmed = line.trim();
            if trimmed.starts_with("(*") || trimmed.starts_with("//") || trimmed.starts_with("*") {
                continue;
            }

            // Check for hardcoded secrets - highest severity
            if HARDCODED_KEY.is_match(line) {
                diagnostics.push(Diagnostic {
                    rule: RuleCode::FST017,
                    severity: DiagnosticSeverity::Error,
                    file: file.clone(),
                    range: Range::point(line_number, 1),
                    message: "Hardcoded secret detected - use secure key derivation".to_string(),
                    fix: None,
                });
            }

            // Check for RawIntTypes (may break secret independence)
            if RAW_INT_TYPES.is_match(line) {
                diagnostics.push(Diagnostic {
                    rule: RuleCode::FST017,
                    severity: DiagnosticSeverity::Warning,
                    file: file.clone(),
                    range: Range::point(line_number, 1),
                    message: "RawIntTypes usage may break secret independence".to_string(),
                    fix: None,
                });
            }

            // Check for potential secret-dependent branches
            // Skip if line uses constant-time masks (proper implementation)
            // Skip for Spec modules (specification code, not compiled)
            if SECRET_BRANCH.is_match(line)
                && !CT_MASK.is_match(line)
                && !CT_SELECT.is_match(line)
                && !CT_COMPARE.is_match(line)
                && !Self::is_spec_module(file)
            {
                // Heuristic: check if variable name suggests secret data
                // Use refined check that excludes metadata (key_len, key_size, etc.)
                if Self::line_has_secret_variable(line) {
                    diagnostics.push(Diagnostic {
                        rule: RuleCode::FST017,
                        severity: DiagnosticSeverity::Warning,
                        file: file.clone(),
                        range: Range::point(line_number, 1),
                        message: "Potential secret-dependent branch - use constant-time masks"
                            .to_string(),
                        fix: None,
                    });
                }
            }
        }

        // Run additional specialized checks
        diagnostics.extend(self.check_buffer_operations(file, content));
        diagnostics.extend(self.check_key_zeroization(file, content));
        diagnostics.extend(self.check_nonce_patterns(file, content));

        // Skip timing checks for Spec modules (specification code, not compiled)
        if !Self::is_spec_module(file) {
            diagnostics.extend(self.check_timing_patterns(file, content));
        }

        diagnostics
    }
}

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

    fn crypto_path() -> PathBuf {
        PathBuf::from("Hacl.Impl.Curve25519.fst")
    }

    fn non_crypto_path() -> PathBuf {
        PathBuf::from("Utils.fst")
    }

    // === Original tests ===

    #[test]
    fn test_hardcoded_secret() {
        let rule = SecurityRule::new();
        let content = r#"let key = "supersecretkey123""#;
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.iter().any(|d| d.message.contains("Hardcoded secret")));
        assert!(diags
            .iter()
            .any(|d| d.severity == DiagnosticSeverity::Error));
    }

    #[test]
    fn test_raw_int_types() {
        let rule = SecurityRule::new();
        let content = "open FStar.RawIntTypes";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags
            .iter()
            .any(|d| d.message.contains("RawIntTypes usage")));
    }

    #[test]
    fn test_secret_branch() {
        let rule = SecurityRule::new();
        let content = "if secret_val = 0 then branch1 else branch2";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.iter().any(|d| d.message.contains("secret-dependent")));
    }

    #[test]
    fn test_constant_time_mask_ok() {
        let rule = SecurityRule::new();
        let content = "let mask = eq_mask secret_a secret_b";
        let diags = rule.check(&crypto_path(), content);
        // Should not warn about secret-dependent branch when using CT masks
        assert!(!diags.iter().any(|d| d.message.contains("secret-dependent")));
    }

    #[test]
    fn test_non_crypto_file_skipped() {
        let rule = SecurityRule::new();
        let content = r#"let key = "notsosecret""#;
        let diags = rule.check(&non_crypto_path(), content);
        // Non-crypto files should not be checked
        assert!(diags.is_empty());
    }

    #[test]
    fn test_comment_lines_skipped() {
        let rule = SecurityRule::new();
        let content = r#"(* let key = "shouldbeignored" *)"#;
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.is_empty());
    }

    // === Buffer operations tests ===

    #[test]
    fn test_buffer_index_without_bounds() {
        let rule = SecurityRule::new();
        let content = "let x = Buffer.index buf idx";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.iter().any(|d| d.message.contains("Buffer.index")));
        assert!(diags.iter().any(|d| d.severity == DiagnosticSeverity::Hint));
    }

    #[test]
    fn test_buffer_index_with_bounds_check() {
        let rule = SecurityRule::new();
        let content = r#"
assert (length buf > idx);
let x = Buffer.index buf idx
"#;
        let diags = rule.check(&crypto_path(), content);
        // Should not warn when bounds check is present
        assert!(!diags.iter().any(|d| d.message.contains("Buffer.index")));
    }

    #[test]
    fn test_buffer_sub_without_bounds() {
        let rule = SecurityRule::new();
        let content = "let slice = Buffer.sub buf start len";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.iter().any(|d| d.message.contains("Buffer.sub")));
    }

    #[test]
    fn test_buffer_blit_without_bounds() {
        let rule = SecurityRule::new();
        let content = "Buffer.blit src 0ul dst 0ul len";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.iter().any(|d| d.message.contains("Buffer.blit")));
    }

    // === Key zeroization tests ===

    #[test]
    fn test_key_without_zeroization() {
        let rule = SecurityRule::new();
        let content = r#"
let my_key = create 32 0uy
(* use key *)
"#;
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.iter().any(|d| d.message.contains("zeroized")));
    }

    #[test]
    fn test_key_with_memzero() {
        let rule = SecurityRule::new();
        let content = r#"
let my_key = create 32 0uy
(* use key *)
memzero my_key 32ul
"#;
        let diags = rule.check(&crypto_path(), content);
        // Should not warn when memzero is present
        assert!(!diags.iter().any(|d| d.message.contains("zeroized")));
    }

    #[test]
    fn test_key_with_clear_function() {
        let rule = SecurityRule::new();
        let content = r#"
let secret_data = alloc 64ul
(* use secret *)
clear_bytes secret_data
"#;
        let diags = rule.check(&crypto_path(), content);
        // Should not warn when clear function is present
        assert!(!diags.iter().any(|d| d.message.contains("zeroized")));
    }

    #[test]
    fn test_stack_alloc_secret() {
        let rule = SecurityRule::new();
        // A secret-named buffer being stack-allocated should warn
        let content = "let secret_data = create 32ul (u8 0)";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            diags
                .iter()
                .any(|d| d.message.contains("Stack-allocated secret")),
            "Stack-allocated secret buffer should trigger warning"
        );
    }

    // === Nonce/IV tests ===

    #[test]
    fn test_nonce_zero_init() {
        let rule = SecurityRule::new();
        let content = "let nonce = 0";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags
            .iter()
            .any(|d| d.message.contains("Nonce/IV initialized to zero")));
        assert!(diags
            .iter()
            .any(|d| d.severity == DiagnosticSeverity::Error));
    }

    #[test]
    fn test_iv_zero_init() {
        let rule = SecurityRule::new();
        let content = "let iv <- 0x00";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags
            .iter()
            .any(|d| d.message.contains("Nonce/IV initialized to zero")));
    }

    #[test]
    fn test_nonce_with_random() {
        let rule = SecurityRule::new();
        let content = "let nonce = randombytes 12";
        let diags = rule.check(&crypto_path(), content);
        // Should not warn when random source is used
        assert!(!diags
            .iter()
            .any(|d| d.message.contains("Nonce/IV initialized to zero")));
    }

    #[test]
    fn test_counter_constant_value() {
        let rule = SecurityRule::new();
        let content = "let counter = 0x00000001";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.iter().any(|d| d.message.contains("constant value")));
    }

    // === Timing pattern tests ===

    #[test]
    fn test_division_by_secret() {
        let rule = SecurityRule::new();
        let content = "let result = total / secret_divisor";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags
            .iter()
            .any(|d| d.message.contains("Division/modulo operation")));
    }

    #[test]
    fn test_modulo_by_key_len_not_flagged() {
        let rule = SecurityRule::new();
        // key_len is metadata (length), NOT the actual secret - should NOT warn
        let content = "let remainder = value % key_len";
        let diags = rule.check(&crypto_path(), content);
        assert!(!diags
            .iter()
            .any(|d| d.message.contains("Division/modulo operation")));
    }

    #[test]
    fn test_modulo_by_actual_secret() {
        let rule = SecurityRule::new();
        // key_byte is an actual secret value - SHOULD warn
        let content = "let remainder = value % secret_divisor";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags
            .iter()
            .any(|d| d.message.contains("Division/modulo operation")));
    }

    #[test]
    fn test_early_return_on_secret() {
        let rule = SecurityRule::new();
        let content = "if key_byte = 0 then return false";
        let diags = rule.check(&crypto_path(), content);
        // Should detect both secret-dependent branch AND early return
        assert!(
            diags.iter().any(|d| d.message.contains("secret-dependent"))
                || diags.iter().any(|d| d.message.contains("Early return"))
        );
    }

    #[test]
    fn test_short_circuit_on_secret() {
        let rule = SecurityRule::new();
        let content = "if secret_a > 0 && secret_b < 10 then process else skip";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags
            .iter()
            .any(|d| d.message.contains("Short-circuit evaluation")));
    }

    // === Safe patterns tests ===

    #[test]
    fn test_ct_select_ok() {
        let rule = SecurityRule::new();
        let content = "let result = ct_select mask val_a val_b";
        let diags = rule.check(&crypto_path(), content);
        // ct_select should suppress timing warnings
        assert!(!diags
            .iter()
            .any(|d| d.message.contains("timing information")));
    }

    #[test]
    fn test_ct_compare_ok() {
        let rule = SecurityRule::new();
        let content = "let equal = constant_time_compare key1 key2 32";
        let diags = rule.check(&crypto_path(), content);
        // constant_time_compare should suppress timing warnings
        assert!(!diags
            .iter()
            .any(|d| d.message.contains("timing information")));
    }

    #[test]
    fn test_verify_function_ok() {
        let rule = SecurityRule::new();
        let content = "let valid = verify_32 mac expected";
        let diags = rule.check(&crypto_path(), content);
        // verify_* functions are constant-time
        assert!(!diags
            .iter()
            .any(|d| d.message.contains("timing information")));
    }

    // === Edge cases ===

    #[test]
    fn test_multiple_issues_same_line() {
        let rule = SecurityRule::new();
        // Line has both key variable and division
        let content = "let key_part = total_key / 2";
        let diags = rule.check(&crypto_path(), content);
        // Should detect division/modulo issue (2 is not secret, but key_part is)
        assert!(diags.len() >= 1);
    }

    #[test]
    fn test_empty_file() {
        let rule = SecurityRule::new();
        let content = "";
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.is_empty());
    }

    #[test]
    fn test_only_comments() {
        let rule = SecurityRule::new();
        let content = r#"
(* This is a comment *)
// Another comment
(* let key = "hidden" *)
"#;
        let diags = rule.check(&crypto_path(), content);
        assert!(diags.is_empty());
    }

    #[test]
    fn test_requires_clause_bounds() {
        let rule = SecurityRule::new();
        let content = r#"
requires { length buf >= idx }
let x = Buffer.index buf idx
"#;
        let diags = rule.check(&crypto_path(), content);
        // Should not warn when requires clause with length is present
        assert!(!diags.iter().any(|d| d.message.contains("Buffer.index")));
    }

    // === FALSE POSITIVE PREVENTION TESTS ===
    // These tests verify that the linter does NOT incorrectly flag valid code

    #[test]
    fn test_function_name_update_key_not_flagged() {
        let rule = SecurityRule::new();
        // update_key is a FUNCTION name, not a key variable - should NOT warn
        let content = r#"
let update_key : blake2_update_key_st Spec.Blake2S Core.M32 =
  blake2_update_key #Spec.Blake2S #Core.M32 update_block
"#;
        let diags = rule.check(&crypto_path(), content);
        // Should NOT have zeroization warning for function definition
        assert!(
            !diags.iter().any(|d| d.message.contains("zeroized")),
            "Function name update_key should not trigger zeroization warning"
        );
    }

    #[test]
    fn test_key_length_variable_not_flagged() {
        let rule = SecurityRule::new();
        // key_len is the LENGTH of a key, not the key itself - should NOT warn for zeroization
        let content = "let key_len = 32ul";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            !diags.iter().any(|d| d.message.contains("zeroized")),
            "key_len (length variable) should not trigger zeroization warning"
        );
    }

    #[test]
    fn test_key_size_variable_not_flagged() {
        let rule = SecurityRule::new();
        // size_key is a SIZE constant, not the key itself
        let content = "let size_key = 32";
        let diags = rule.check(&crypto_path(), content);
        // size_key ends with "key" but doesn't look like a buffer allocation
        // No create/alloca/sub = no zeroization warning
        assert!(
            !diags.iter().any(|d| d.message.contains("zeroized")),
            "size_key (size constant) should not trigger zeroization warning"
        );
    }

    #[test]
    fn test_derive_key_function_not_flagged() {
        let rule = SecurityRule::new();
        // derive_key is a function name
        let content = "let derive_key_poly1305_do #w k n aadlen aad mlen m out =";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            !diags.iter().any(|d| d.message.contains("zeroized")),
            "Function derive_key_poly1305_do should not trigger zeroization warning"
        );
    }

    #[test]
    fn test_actual_key_buffer_allocation_flagged() {
        let rule = SecurityRule::new();
        // This IS an actual key buffer allocation - SHOULD warn if no cleanup
        let content = "let key = sub tmp 0ul 32ul";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            diags.iter().any(|d| d.message.contains("zeroized")),
            "Actual key buffer allocation should trigger zeroization warning"
        );
    }

    #[test]
    fn test_secret_buffer_with_create_flagged() {
        let rule = SecurityRule::new();
        // Actual secret buffer allocation
        let content = "let my_secret = create 64ul (u8 0)";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            diags.iter().any(|d| d.message.contains("zeroized")),
            "Secret buffer allocation should trigger zeroization warning"
        );
    }

    #[test]
    fn test_priv_key_buffer_allocation_flagged() {
        let rule = SecurityRule::new();
        // priv_key buffer allocation
        let content = "let priv_key = alloca 32ul (u8 0)";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            diags.iter().any(|d| d.message.contains("zeroized")),
            "priv_key buffer allocation should trigger zeroization warning"
        );
    }

    #[test]
    fn test_key_type_st_not_flagged() {
        let rule = SecurityRule::new();
        // blake2_update_key_st is a TYPE, not a variable
        let content = "let blake2_update_key_st (al:Spec.alg) (ms:m_spec) =";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            !diags.iter().any(|d| d.message.contains("zeroized")),
            "Type definition _st should not trigger zeroization warning"
        );
    }

    #[test]
    fn test_key_bytes_metadata_not_flagged_for_timing() {
        let rule = SecurityRule::new();
        // key_bytes is metadata (byte count), not secret data
        let content = "if key_bytes = 32 then use_aes256 else use_aes128";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            !diags.iter().any(|d| d.message.contains("secret-dependent")),
            "key_bytes (metadata) should not trigger secret-dependent branch warning"
        );
    }

    #[test]
    fn test_actual_key_in_branch_flagged() {
        let rule = SecurityRule::new();
        // key_data is actual secret data
        let content = "if key_data = 0 then skip else process";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            diags.iter().any(|d| d.message.contains("secret-dependent")),
            "Actual key variable in branch should trigger warning"
        );
    }

    #[test]
    fn test_real_hacl_pattern_key_parameter() {
        let rule = SecurityRule::new();
        // Real HACL* pattern: key is a parameter, not allocation
        // This is just a function type annotation
        let content = r#"
val aead_encrypt: #w:field_spec -> aead_encrypt_st w

let aead_encrypt #w output tag input input_len data data_len key nonce =
  chacha20_encrypt #w input_len output input key nonce 1ul
"#;
        let diags = rule.check(&crypto_path(), content);
        // Parameter references should not trigger zeroization
        assert!(
            !diags.iter().any(|d| d.message.contains("zeroized")),
            "Function parameter references should not trigger zeroization warning"
        );
    }

    #[test]
    fn test_real_hacl_derived_key_pattern() {
        let rule = SecurityRule::new();
        // Real HACL* pattern: derived key that gets properly handled
        let content = r#"
push_frame ();
let tmp = create 64ul (u8 0) in
chacha20_encrypt #w 64ul tmp tmp k n 0ul;
let key = sub tmp 0ul 32ul in
poly1305_do #w key aadlen aad mlen m out;
pop_frame()
"#;
        let diags = rule.check(&crypto_path(), content);
        // This SHOULD warn - the derived key should be zeroized but isn't
        assert!(
            diags.iter().any(|d| d.message.contains("zeroized")),
            "Derived key without explicit zeroization should warn"
        );
    }

    #[test]
    fn test_division_by_key_length_not_flagged() {
        let rule = SecurityRule::new();
        // Division by key_length is safe - it's public metadata
        let content = "let blocks = total /. key_length";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            !diags.iter().any(|d| d.message.contains("Division/modulo")),
            "Division by key_length (metadata) should not trigger timing warning"
        );
    }

    #[test]
    fn test_secret_in_division_operand_flagged() {
        let rule = SecurityRule::new();
        // Division involving actual secret value
        let content = "let result = secret_value / 2";
        let diags = rule.check(&crypto_path(), content);
        assert!(
            diags.iter().any(|d| d.message.contains("Division/modulo")),
            "Division on secret value should trigger timing warning"
        );
    }

    #[test]
    fn test_helper_is_secret_variable() {
        // Test the is_secret_variable helper directly
        assert!(SecurityRule::is_secret_variable("key"));
        assert!(SecurityRule::is_secret_variable("my_key"));
        assert!(SecurityRule::is_secret_variable("secret"));
        assert!(SecurityRule::is_secret_variable("priv_key"));
        assert!(SecurityRule::is_secret_variable("key_data"));

        // Metadata should NOT be flagged as secret
        assert!(!SecurityRule::is_secret_variable("key_len"));
        assert!(!SecurityRule::is_secret_variable("key_length"));
        assert!(!SecurityRule::is_secret_variable("key_size"));
        assert!(!SecurityRule::is_secret_variable("keylen"));
        assert!(!SecurityRule::is_secret_variable("secret_size"));
        assert!(!SecurityRule::is_secret_variable("key_bits"));
        assert!(!SecurityRule::is_secret_variable("key_bytes"));

        // Function names should NOT be flagged as secret
        assert!(!SecurityRule::is_secret_variable("update_key"));
        assert!(!SecurityRule::is_secret_variable("derive_key"));
        assert!(!SecurityRule::is_secret_variable("init_secret"));
        assert!(!SecurityRule::is_secret_variable("get_key"));
        assert!(!SecurityRule::is_secret_variable("set_key"));
        assert!(!SecurityRule::is_secret_variable("expand_key"));
        assert!(!SecurityRule::is_secret_variable("clear_key"));

        // Type names should NOT be flagged as secret
        assert!(!SecurityRule::is_secret_variable("key_t"));
        assert!(!SecurityRule::is_secret_variable("key_st"));
    }

    // === HACL* SIZE OPERATOR TESTS ===
    // F* uses `/. ` and `%. ` for size_t operations which are PUBLIC

    #[test]
    fn test_size_division_operator_public() {
        let rule = SecurityRule::new();
        // `/. ` is the F* size division operator - operates on public size_t
        let content = "let i = ind /. pbits";
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - this is a public operation
        assert!(
            !diags.iter().any(|d| d.message.contains("Division/modulo")),
            "Size division operator /. should not trigger timing warning"
        );
    }

    #[test]
    fn test_size_modulo_operator_public() {
        let rule = SecurityRule::new();
        // `%. ` is the F* size modulo operator - operates on public size_t
        let content = "let j = ind %. pbits";
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - this is a public operation
        assert!(
            !diags.iter().any(|d| d.message.contains("Division/modulo")),
            "Size modulo operator %. should not trigger timing warning"
        );
    }

    #[test]
    fn test_size_comparison_operators_public() {
        let rule = SecurityRule::new();
        // Size comparisons like `<. `, `>. ` are public operations
        let content = "if len <. bn_mul_threshold then branch1 else branch2";
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - size comparisons are public
        assert!(
            !diags.iter().any(|d| d.message.contains("secret-dependent")),
            "Size comparison operators should not trigger secret-dependent warning"
        );
    }

    #[test]
    fn test_hacl_karatsuba_pattern() {
        let rule = SecurityRule::new();
        // Real pattern from Hacl.Bignum.Karatsuba.fst
        let content = r#"
  if len <. bn_mul_threshold || len %. 2ul =. 1ul then
    bn_mul res a b
  else
    let len2 = len /. 2ul in
    karatsuba_mul res a b len2
"#;
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn on any of these - all public size operations
        assert!(
            !diags.iter().any(|d| d.message.contains("Division/modulo")),
            "HACL* Karatsuba pattern should not trigger Division/modulo warning"
        );
        assert!(
            !diags.iter().any(|d| d.message.contains("secret-dependent")),
            "HACL* Karatsuba pattern should not trigger secret-dependent warning"
        );
    }

    #[test]
    fn test_hacl_exponentiation_pattern() {
        let rule = SecurityRule::new();
        // Real pattern from Hacl.Impl.Exponentiation.fst
        let content = r#"
  let bk = bBits -! bBits %. l in
  Lib.Loops.for 0ul (bBits /. l) inv (fun i -> ladder_step k i)
"#;
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - bBits, l are public, using size operators
        assert!(
            !diags.iter().any(|d| d.message.contains("Division/modulo")),
            "HACL* exponentiation pattern should not trigger Division/modulo warning"
        );
    }

    #[test]
    fn test_eq_mask_constant_time() {
        let rule = SecurityRule::new();
        // eq_mask is a constant-time operation
        let content = "let beq = eq_mask a.(i) b.(i) in acc.(0ul) <- mask_select beq acc.(0ul) blt";
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - using constant-time operations
        assert!(
            !diags.iter().any(|d| d.message.contains("secret-dependent")),
            "eq_mask should not trigger secret-dependent warning"
        );
    }

    #[test]
    fn test_mask_select_constant_time() {
        let rule = SecurityRule::new();
        // mask_select is a constant-time conditional
        let content = "priv.(0ul) <- mask_select mask priv.(0ul) (size_to_limb i)";
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - mask_select is constant-time
        assert!(
            !diags.iter().any(|d| d.message.contains("timing")),
            "mask_select should not trigger timing warning"
        );
    }

    #[test]
    fn test_cswap_pattern_constant_time() {
        let rule = SecurityRule::new();
        // Pattern from cswap2_st - constant-time conditional swap
        let content = r#"
let mask = uint #t 0 -. bit in
let dummy = mask &. (b1.(i) ^. b2.(i)) in
b1.(i) <- b1.(i) ^. dummy
"#;
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - this is a constant-time swap pattern
        assert!(
            !diags.iter().any(|d| d.message.contains("secret-dependent")),
            "cswap pattern should not trigger secret-dependent warning"
        );
    }

    #[test]
    fn test_bbits_public_variable() {
        let rule = SecurityRule::new();
        // bBits (bit count) is always public
        let content = "if bBits <. size SE.bn_exp_mont_consttime_threshold then fast_path else slow_path";
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - bBits is public metadata
        assert!(
            !diags.iter().any(|d| d.message.contains("secret-dependent")),
            "bBits should not trigger secret-dependent warning"
        );
    }

    #[test]
    fn test_len_public_variable() {
        let rule = SecurityRule::new();
        // len is always public
        let content = "if len > 0ul then process len else skip";
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - len is public
        assert!(
            !diags.iter().any(|d| d.message.contains("secret-dependent")),
            "len should not trigger secret-dependent warning"
        );
    }

    #[test]
    fn test_ind_public_index() {
        let rule = SecurityRule::new();
        // ind (index) is always public
        let content = "let x = ind /. 64 in buf.(ind)";
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - ind is a public index
        assert!(
            !diags.iter().any(|d| d.message.contains("Division/modulo")),
            "ind (public index) should not trigger timing warning"
        );
    }

    #[test]
    fn test_size_literal_division() {
        let rule = SecurityRule::new();
        // Division by size literal is public
        let content = "let half = total / 2ul";
        let diags = rule.check(&crypto_path(), content);
        // Should NOT warn - size literal division is public
        assert!(
            !diags.iter().any(|d| d.message.contains("Division/modulo")),
            "Division by size literal should not trigger timing warning"
        );
    }

    // === SPEC MODULE TESTS ===
    // Spec modules are mathematical specifications, not compiled code

    fn spec_module_path() -> PathBuf {
        PathBuf::from("Hacl.Spec.Bignum.Lib.fst")
    }

    #[test]
    fn test_spec_module_detection() {
        // Test the is_spec_module helper
        assert!(SecurityRule::is_spec_module(&PathBuf::from("Hacl.Spec.Bignum.fst")));
        assert!(SecurityRule::is_spec_module(&PathBuf::from("Hacl.Spec.Bignum.Lib.fst")));
        assert!(SecurityRule::is_spec_module(&PathBuf::from("Spec.Blake2.fst")));
        assert!(SecurityRule::is_spec_module(&PathBuf::from("Spec.Chacha20.fst")));
        assert!(SecurityRule::is_spec_module(&PathBuf::from("Lib.Spec.Something.fst")));

        // These are NOT spec modules
        assert!(!SecurityRule::is_spec_module(&PathBuf::from("Hacl.Impl.Bignum.fst")));
        assert!(!SecurityRule::is_spec_module(&PathBuf::from("Hacl.Bignum.Lib.fst")));
        assert!(!SecurityRule::is_spec_module(&PathBuf::from("Speculative.fst"))); // Not a spec module
    }

    #[test]
    fn test_spec_module_branch_not_flagged() {
        let rule = SecurityRule::new();
        // This pattern WOULD be flagged in implementation code,
        // but Spec modules are specifications, not compiled code
        let content = "if v mask = 0 then secret_val else other_val";
        let diags = rule.check(&spec_module_path(), content);
        // Should NOT warn - spec modules are not compiled
        assert!(
            !diags.iter().any(|d| d.message.contains("secret-dependent")),
            "Spec modules should not trigger secret-dependent branch warnings"
        );
    }

    #[test]
    fn test_spec_module_timing_not_flagged() {
        let rule = SecurityRule::new();
        // Division/modulo in spec modules is fine
        let content = "let result = secret_val / divisor";
        let diags = rule.check(&spec_module_path(), content);
        // Should NOT warn for timing - spec modules are not compiled
        assert!(
            !diags.iter().any(|d| d.message.contains("Division/modulo")),
            "Spec modules should not trigger timing warnings"
        );
    }

    #[test]
    fn test_impl_module_branch_flagged() {
        let rule = SecurityRule::new();
        // In implementation modules, secret-dependent branches SHOULD be flagged
        let content = "if secret_val = 0 then branch1 else branch2";
        let diags = rule.check(&crypto_path(), content);
        // SHOULD warn - implementation code needs constant-time operations
        assert!(
            diags.iter().any(|d| d.message.contains("secret-dependent")),
            "Implementation modules SHOULD trigger secret-dependent branch warnings"
        );
    }
}