tsafe-attest 1.1.0

Attestation pipeline for tsafe — secret scanner + env-injection contract + run-evidence harness (algol-merged)
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
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
//! Secret + env-authority scanner.
//!
//! # Provenance
//!
//! Ported from `algol/src/scan.rs` at the Phase 2.1 commit `4e81948`
//! (`scan(phase2-1): placeholder suppression + extension/regex extension`),
//! itself built on `algol/src/scan.rs` @ commit `6956cfd` (algol HEAD).
//!
//! Re-licensed `AGPL-3.0-or-later` per tsafe v1.1.0. See crate-root docs
//! for the full provenance trail (ADR, plan, Phase 0 audit, Phase 2 + 2.1
//! verdicts).
//!
//! # Phase 2.1 patches (lifted along with the port)
//!
//! - **Patch A — placeholder suppression**: secret detectors are routed
//!   through a file-path / comment / docstring placeholder-context check
//!   and emit `FindingKind::SecretPlaceholder` (severity `Info`) instead
//!   of silently dropping. Verdict classifiers should not count
//!   `SecretPlaceholder` as "scanner says secret".
//! - **Patch B — extension + regex extension**: `.pem`, `.json`, `.yaml`,
//!   `.yml` extensions are walked so PEM private keys and service-account
//!   JSON credentials are scanned. JS / JSON object-syntax AWS credentials
//!   are caught via dedicated regexes. 5 MiB file-size cap.
//!
//! # Hash family
//!
//! `ScanFinding.hash` is BLAKE3 (`blake3:<hex>`) per ec ADR-0003. The
//! Phase 2 algol scanner emitted `sha256:<hex>`; this is a wire-format
//! change. See CHANGELOG.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::Path;

use anyhow::{Context, Result};
use chrono::Utc;
use regex::Regex;
use walkdir::{DirEntry, WalkDir};

use crate::model::{
    CiSecretReference, FindingKind, ObservedEnvRead, ScanFinding, ScanReport, ScanSummary,
    Severity, ATTEST_VERSION, SCAN_SCHEMA,
};
use crate::redact;

const KNOWN_SECRET_NAMES: &[&str] = &[
    "AWS_ACCESS_KEY_ID",
    "AWS_SECRET_ACCESS_KEY",
    "STRIPE_SECRET_KEY",
    "GITHUB_TOKEN",
    "GH_TOKEN",
    "DATABASE_URL",
    "API_TOKEN",
    "SECRET_KEY",
    "PRIVATE_KEY",
    "JWT_SECRET",
    "OPENAI_API_KEY",
    "ANTHROPIC_API_KEY",
    "AZURE_CLIENT_SECRET",
    "PROD_DEPLOY_KEY",
];

const HIGH_RISK_ENV_NAMES: &[&str] = &[
    "AWS_ACCESS_KEY_ID",
    "AWS_SECRET_ACCESS_KEY",
    "STRIPE_SECRET_KEY",
    "GITHUB_TOKEN",
    "GH_TOKEN",
    "PRIVATE_KEY",
    "JWT_SECRET",
    "OPENAI_API_KEY",
    "ANTHROPIC_API_KEY",
    "AZURE_CLIENT_SECRET",
    "PROD_DEPLOY_KEY",
];

/// Heuristic: does `name` look like a sensitive env var?
pub fn is_sensitive_env_name(name: &str) -> bool {
    let upper = name.to_ascii_uppercase();
    HIGH_RISK_ENV_NAMES.contains(&upper.as_str())
        || upper.contains("SECRET")
        || upper.contains("TOKEN")
        || upper.contains("CREDENTIAL")
        || upper.contains("CREDS")
        || upper.contains("PASSWORD")
        || upper.contains("PASSWD")
        || upper.contains("PRIVATE_KEY")
        || upper.ends_with("_KEY")
        || upper.ends_with("_PWD")
}

/// Heuristic: is `name` in the high-risk class (escalates severity)?
pub fn is_high_risk_env_name(name: &str) -> bool {
    let upper = name.to_ascii_uppercase();
    HIGH_RISK_ENV_NAMES.contains(&upper.as_str())
        || upper.starts_with("AWS_")
        || upper.starts_with("GH_")
        || upper.starts_with("GITHUB_")
        || upper.starts_with("STRIPE_")
        || upper.starts_with("AZURE_")
}

/// Walk `repo`, scan every scannable file, return a [`ScanReport`].
pub fn scan_repo(repo: &Path) -> Result<ScanReport> {
    let repo =
        fs::canonicalize(repo).with_context(|| format!("repo not found: {}", repo.display()))?;
    let mut findings = Vec::new();
    let mut observed_env_reads = Vec::new();
    let mut ci_secret_references = Vec::new();
    let mut observed_seen = HashSet::new();

    for entry in WalkDir::new(&repo)
        .into_iter()
        .filter_entry(|entry| !is_ignored_entry(entry))
    {
        let entry = entry?;
        if !entry.file_type().is_file() || !is_scannable_file(entry.path(), &repo) {
            continue;
        }

        let relative = relative_path(entry.path(), &repo);
        // Phase 2.1 Patch B: 5 MiB cap keeps the scanner fast on
        // accidentally-committed binaries. Above any reasonable
        // text-config / source file.
        if entry
            .metadata()
            .map(|m| m.len() > 5 * 1024 * 1024)
            .unwrap_or(false)
        {
            continue;
        }
        let Ok(content) = fs::read_to_string(entry.path()) else {
            continue;
        };
        scan_file(
            &relative,
            &content,
            &mut findings,
            &mut observed_env_reads,
            &mut observed_seen,
            &mut ci_secret_references,
        )?;
    }

    renumber_findings(&mut findings);
    let summary = summarize(&findings);
    Ok(ScanReport {
        schema: SCAN_SCHEMA.to_string(),
        repo_path: repo.display().to_string(),
        repo_commit: current_commit(&repo),
        scanned_at: Utc::now(),
        scanner_version: ATTEST_VERSION.to_string(),
        findings,
        observed_env_reads,
        ci_secret_references,
        summary,
    })
}

/// Best-effort: read the current git HEAD commit hash from `<repo>/.git/HEAD`.
///
/// Returns `None` if the repo isn't a git checkout or the HEAD can't be
/// resolved. We deliberately avoid shelling out to `git` to keep the
/// scanner usable in environments without git on PATH (CI runners, etc.).
fn current_commit(repo: &Path) -> Option<String> {
    let head = repo.join(".git/HEAD");
    let head_content = fs::read_to_string(&head).ok()?;
    let trimmed = head_content.trim();
    // HEAD is either `ref: refs/heads/<branch>` or a raw SHA-1.
    if let Some(reference) = trimmed.strip_prefix("ref: ") {
        let ref_path = repo.join(".git").join(reference);
        let sha = fs::read_to_string(ref_path).ok()?.trim().to_string();
        if sha.is_empty() {
            return None;
        }
        Some(sha)
    } else {
        Some(trimmed.to_string())
    }
}

/// Serialise + write a [`ScanReport`] as pretty JSON.
pub fn write_scan(report: &ScanReport, output: &Path) -> Result<()> {
    let json = serde_json::to_string_pretty(report)?;
    ensure_parent_dir(output)?;
    fs::write(output, json).with_context(|| format!("write scan report: {}", output.display()))
}

/// Print a human-readable summary of `report` to stdout.
pub fn print_summary(report: &ScanReport) {
    println!("tsafe attest scan complete");
    println!("Repo: {}", report.repo_path);
    println!(
        "Commit: {}",
        report.repo_commit.as_deref().unwrap_or("unknown")
    );
    println!("Findings:");
    for finding in &report.findings {
        let name = finding.name.as_deref().unwrap_or("-");
        println!(
            "  {:<8} {:<32} {}",
            finding.severity.label(),
            format!("{}:{}", finding.file, finding.line),
            format!("{name} {}", finding.message).trim()
        );
    }
    println!("Risk score: {}/100", report.summary.risk_score);
}

#[allow(clippy::too_many_arguments)]
fn scan_file(
    file: &str,
    content: &str,
    findings: &mut Vec<ScanFinding>,
    observed_env_reads: &mut Vec<ObservedEnvRead>,
    observed_seen: &mut HashSet<(String, String, usize)>,
    ci_secret_references: &mut Vec<CiSecretReference>,
) -> Result<()> {
    let env_assign = Regex::new(r#"^\s*([A-Z0-9_]+)\s*=\s*("?[^"\n]*"?|'?[^'\n]*'?)\s*$"#)?;
    let private_key = Regex::new(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")?;
    let connection = Regex::new(r#"(?i)(postgres|mysql|mongodb|redis)://[^ \n'"]+"#)?;
    let generic_secret = Regex::new(
        r#"(?i)(api[_-]?key|secret|token|password|passwd|pwd)\s*[:=]\s*['"]?([A-Za-z0-9_\-./+=]{16,})['"]?"#,
    )?;
    let gha_secret = Regex::new(r#"\$\{\{\s*secrets\.([A-Z0-9_]+)\s*\}\}"#)?;
    // Phase 2.1 Patch B — JS / JSON object-syntax AWS credentials.
    let aws_object_key_id = Regex::new(
        r#"(?i)['"]?\b(?:aws[_-]?access[_-]?key[_-]?id|accessKeyId)\b['"]?\s*[:=]\s*['"]([A-Z0-9]{16,})['"]"#,
    )?;
    let aws_object_secret = Regex::new(
        r#"(?i)['"]?\b(?:aws[_-]?secret[_-]?access[_-]?key|secretAccessKey)\b['"]?\s*[:=]\s*['"]([A-Za-z0-9+/=]{20,})['"]"#,
    )?;
    let aws_akia_literal = Regex::new(r#"\b(AKIA[0-9A-Z]{16})\b"#)?;

    let js_full_env = Regex::new(r"\bprocess\.env\b")?;
    let js_dot = Regex::new(r"process\.env\.([A-Z0-9_]+)")?;
    let js_index = Regex::new(r#"process\.env\[['"]([A-Z0-9_]+)['"]\]"#)?;
    let js_env_alias = Regex::new(
        r#"\b(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*process\.env(?:\.([A-Z0-9_]+)|\[['"]([A-Z0-9_]+)['"]\])"#,
    )?;
    let py_environ = Regex::new(r#"os\.environ\[['"]([A-Z0-9_]+)['"]\]"#)?;
    let py_getenv = Regex::new(r#"os\.getenv\(['"]([A-Z0-9_]+)['"]\)"#)?;
    let rust_env = Regex::new(r#"(?:std::env::var|env::var)\(["']([A-Z0-9_]+)["']\)"#)?;
    let shell_export = Regex::new(r"export\s+([A-Z0-9_]+)=")?;
    let shell_var = Regex::new(r#"\$\{?([A-Z][A-Z0-9_]{2,})\}?"#)?;
    let env_interpolation = Regex::new(r#"\$\{([A-Z][A-Z0-9_]{2,})(?::[-?][^}]*)?\}"#)?;
    let compose_bare_env = Regex::new(r"^\s*-\s*([A-Z][A-Z0-9_]{2,})\s*(?:#.*)?$")?;
    let docker_bare_arg = Regex::new(r"^\s*ARG\s+([A-Z][A-Z0-9_]{2,})\s*(?:#.*)?$")?;

    let mut env_aliases: HashMap<String, String> = HashMap::new();

    // Phase 2.1 Patch A — precompute Python docstring regions + file-path
    // placeholder gate. Cheap O(lines) state machine.
    let docstring_lines: Vec<bool> = compute_docstring_lines(file, content);
    let file_path_is_placeholder = is_placeholder_file_path(file);

    for (index, line) in content.lines().enumerate() {
        let line_number = index + 1;
        let in_docstring = *docstring_lines.get(index).unwrap_or(&false);

        if is_env_file(file) {
            if let Some(caps) = env_assign.captures(line) {
                let name = caps.get(1).map(|m| m.as_str()).unwrap_or_default();
                let value = caps
                    .get(2)
                    .map(|m| m.as_str().trim().trim_matches(['"', '\'']))
                    .unwrap_or_default();
                let secretish = is_sensitive_env_name(name) || connection.is_match(value);
                if secretish {
                    // Phase 2.1 Patch A — only suppress when the file path
                    // signals placeholder content or the value is a pure
                    // env-interpolation reference. The general
                    // `is_placeholder` heuristic is too aggressive here
                    // because production DB connection strings legitimately
                    // contain `example.com` hostnames (RFC 2606).
                    let placeholder_match =
                        file_path_is_placeholder || is_env_interpolation_value(value);
                    let kind = if placeholder_match {
                        FindingKind::SecretPlaceholder
                    } else {
                        FindingKind::EnvFile
                    };
                    let severity = if placeholder_match {
                        Severity::Info
                    } else {
                        env_file_severity(file, value)
                    };
                    let message = if placeholder_match {
                        ".env example/placeholder value (suppressed)"
                    } else {
                        ".env file contains a likely secret-bearing variable"
                    };
                    push_secret_finding(
                        findings,
                        SecretFindingInput {
                            kind,
                            severity,
                            confidence: confidence_for_value(value, 0.85),
                            location: FindingLocation {
                                file,
                                line: line_number,
                                column: column_of(line, name),
                            },
                            secret_type: "generic-env",
                            name,
                            value,
                            message,
                        },
                    );
                } else if file.ends_with(".example") {
                    // Patch A: an `.env.example` row that didn't trip any
                    // sensitivity check is informational only — emit
                    // `SecretPlaceholder` so the corpus measurement does
                    // not count it as "scanner says secret".
                    findings.push(base_finding(
                        FindingKind::SecretPlaceholder,
                        Severity::Info,
                        0.35,
                        FindingLocation {
                            file,
                            line: line_number,
                            column: 1,
                        },
                        Some(name.to_string()),
                        ".env example variable present (suppressed)".to_string(),
                    ));
                }
            }
        }

        if private_key.is_match(line) {
            let placeholder_match =
                file_path_is_placeholder || in_docstring || is_doc_or_comment_line(file, line);
            let kind = if placeholder_match {
                FindingKind::SecretPlaceholder
            } else {
                FindingKind::PrivateKey
            };
            let severity = if placeholder_match {
                Severity::Info
            } else {
                Severity::Critical
            };
            let message = if placeholder_match {
                "Private key block in placeholder/comment context (suppressed)".to_string()
            } else {
                "Private key block committed".to_string()
            };
            findings.push(base_finding(
                kind,
                severity,
                0.90,
                FindingLocation {
                    file,
                    line: line_number,
                    column: 1,
                },
                Some("PRIVATE_KEY".to_string()),
                message,
            ));
        }

        for secret_name in KNOWN_SECRET_NAMES {
            let Some(value) = extract_assigned_value(line, secret_name) else {
                continue;
            };
            if should_skip_hardcoded_secret(file, line, value) {
                continue;
            }
            // Patch A: file-path / comment / docstring context only.
            let placeholder_match =
                file_path_is_placeholder || in_docstring || is_doc_or_comment_line(file, line);
            let kind = if placeholder_match {
                FindingKind::SecretPlaceholder
            } else {
                FindingKind::HardcodedSecret
            };
            let severity = if placeholder_match {
                Severity::Info
            } else if is_high_risk_env_name(secret_name) {
                Severity::High
            } else {
                Severity::Medium
            };
            let message = if placeholder_match {
                "Known secret-bearing variable in placeholder/comment context (suppressed)"
            } else {
                "Known secret-bearing variable appears in source"
            };
            push_secret_finding(
                findings,
                SecretFindingInput {
                    kind,
                    severity,
                    confidence: confidence_for_value(value, 0.95),
                    location: FindingLocation {
                        file,
                        line: line_number,
                        column: column_of(line, secret_name),
                    },
                    secret_type: "known-secret-name",
                    name: secret_name,
                    value,
                    message,
                },
            );
        }

        if !is_env_file(file) {
            for caps in connection.captures_iter(line) {
                if let Some(value) = caps.get(0) {
                    let placeholder_match = file_path_is_placeholder
                        || in_docstring
                        || is_doc_or_comment_line(file, line);
                    let kind = if placeholder_match {
                        FindingKind::SecretPlaceholder
                    } else {
                        FindingKind::HardcodedSecret
                    };
                    let severity = if placeholder_match {
                        Severity::Info
                    } else {
                        Severity::High
                    };
                    let message = if placeholder_match {
                        "Connection string in placeholder/comment context (suppressed)"
                    } else {
                        "Connection string appears in source"
                    };
                    push_secret_finding(
                        findings,
                        SecretFindingInput {
                            kind,
                            severity,
                            confidence: confidence_for_value(value.as_str(), 0.75),
                            location: FindingLocation {
                                file,
                                line: line_number,
                                column: value.start() + 1,
                            },
                            secret_type: "connection-string",
                            name: "CONNECTION_STRING",
                            value: value.as_str(),
                            message,
                        },
                    );
                }
            }
        }

        if !should_skip_generic_secret_line(file, line) {
            for caps in generic_secret.captures_iter(line) {
                let name = caps.get(1).map(|m| m.as_str()).unwrap_or("SECRET");
                let value = caps.get(2).map(|m| m.as_str()).unwrap_or_default();
                if value.contains("process.env") || value.contains("secrets.") {
                    continue;
                }
                let placeholder_match =
                    file_path_is_placeholder || in_docstring || is_doc_or_comment_line(file, line);
                let kind = if placeholder_match {
                    FindingKind::SecretPlaceholder
                } else {
                    FindingKind::HardcodedSecret
                };
                let severity = if placeholder_match {
                    Severity::Info
                } else {
                    Severity::High
                };
                let message = if placeholder_match {
                    "Generic secret-looking value in placeholder/comment context (suppressed)"
                } else {
                    "Generic secret-looking assignment appears in source"
                };
                push_secret_finding(
                    findings,
                    SecretFindingInput {
                        kind,
                        severity,
                        confidence: confidence_for_value(value, 0.75),
                        location: FindingLocation {
                            file,
                            line: line_number,
                            column: column_of(line, name),
                        },
                        secret_type: "generic-secret",
                        name,
                        value,
                        message,
                    },
                );
            }
        }

        // Phase 2.1 Patch B — AWS object-syntax detection.
        if !is_yaml_comment_line(line) {
            for caps in aws_object_key_id.captures_iter(line) {
                if let Some(value) = caps.get(1) {
                    push_aws_object_finding(
                        findings,
                        AwsObjectFindingArgs {
                            file,
                            line,
                            line_number,
                            value: value.as_str(),
                            name: "AWS_ACCESS_KEY_ID",
                            file_path_is_placeholder,
                            in_docstring,
                        },
                    );
                }
            }
            for caps in aws_object_secret.captures_iter(line) {
                if let Some(value) = caps.get(1) {
                    push_aws_object_finding(
                        findings,
                        AwsObjectFindingArgs {
                            file,
                            line,
                            line_number,
                            value: value.as_str(),
                            name: "AWS_SECRET_ACCESS_KEY",
                            file_path_is_placeholder,
                            in_docstring,
                        },
                    );
                }
            }
            // Bare AKIA literal — last-resort catch. Only fires if the
            // earlier detectors did not already emit a finding for this
            // line.
            let already_caught = aws_object_key_id.is_match(line)
                || extract_assigned_value(line, "AWS_ACCESS_KEY_ID").is_some();
            if !already_caught {
                for caps in aws_akia_literal.captures_iter(line) {
                    if let Some(value) = caps.get(1) {
                        push_aws_object_finding(
                            findings,
                            AwsObjectFindingArgs {
                                file,
                                line,
                                line_number,
                                value: value.as_str(),
                                name: "AWS_ACCESS_KEY_ID",
                                file_path_is_placeholder,
                                in_docstring,
                            },
                        );
                    }
                }
            }
        }

        if !is_yaml_comment_line(line) {
            for caps in gha_secret.captures_iter(line) {
                let name = caps.get(1).map(|m| m.as_str()).unwrap_or_default();
                ci_secret_references.push(CiSecretReference {
                    name: name.to_string(),
                    provider: "github-actions".to_string(),
                    file: file.to_string(),
                    line: line_number,
                    context: format!("secrets.{name}"),
                });
                findings.push(base_finding(
                    FindingKind::CiSecretReference,
                    Severity::High,
                    0.95,
                    FindingLocation {
                        file,
                        line: line_number,
                        column: column_of(line, name),
                    },
                    Some(name.to_string()),
                    format!("GitHub Actions secret {name} referenced"),
                ));
            }
        }

        if file == "package.json" && line.contains("\"scripts\"") {
            findings.push(base_finding(
                FindingKind::RiskyEnvPropagation,
                Severity::Low,
                0.50,
                FindingLocation {
                    file,
                    line: line_number,
                    column: 1,
                },
                None,
                "npm script likely inherits ambient environment".to_string(),
            ));
        }

        if !is_js_comment_line(line)
            && js_full_env.is_match(line)
            && !js_dot.is_match(line)
            && !js_index.is_match(line)
        {
            findings.push(base_finding(
                FindingKind::RiskyEnvPropagation,
                Severity::Medium,
                0.70,
                FindingLocation {
                    file,
                    line: line_number,
                    column: column_of(line, "process.env"),
                },
                Some("process.env".to_string()),
                "JavaScript references the full process.env ambient environment".to_string(),
            ));
        }

        if !is_js_comment_line(line) {
            for caps in js_env_alias.captures_iter(line) {
                let Some(variable) = caps.get(1).map(|m| m.as_str()) else {
                    continue;
                };
                let Some(env_name) = caps.get(2).or_else(|| caps.get(3)).map(|m| m.as_str()) else {
                    continue;
                };
                env_aliases.insert(variable.to_string(), env_name.to_string());
            }

            for (variable, env_name) in &env_aliases {
                if is_destructive_path_sink(line, variable) {
                    findings.push(base_finding(
                        FindingKind::RiskyEnvPropagation,
                        Severity::High,
                        0.80,
                        FindingLocation {
                            file,
                            line: line_number,
                            column: column_of(line, variable),
                        },
                        Some(env_name.to_string()),
                        format!(
                            "Environment-controlled path {env_name} is used in a destructive filesystem operation"
                        ),
                    ));
                }
            }
        }

        if is_dockerfile(file) {
            if let Some(name) = docker_bare_arg
                .captures(line)
                .and_then(|caps| caps.get(1))
                .map(|m| m.as_str())
            {
                push_env_authority_reference(
                    findings,
                    observed_env_reads,
                    observed_seen,
                    EnvAuthorityInput {
                        file,
                        source_line: line,
                        line_number,
                        name,
                        language: "dockerfile",
                        confidence: 0.65,
                        kind: FindingKind::RiskyEnvPropagation,
                        severity: Severity::Low,
                        message: format!(
                            "Dockerfile build argument {name} can receive ambient build environment"
                        ),
                    },
                );
            }
        }

        if !is_yaml_comment_line(line) && (is_dockerfile(file) || is_docker_compose_file(file)) {
            let language = if is_dockerfile(file) {
                "dockerfile"
            } else {
                "docker-compose"
            };
            for caps in env_interpolation.captures_iter(line) {
                if let Some(name) = caps.get(1).map(|m| m.as_str()) {
                    push_env_read(
                        findings,
                        observed_env_reads,
                        observed_seen,
                        EnvReadInput {
                            file,
                            source_line: line,
                            line_number,
                            name,
                            language,
                            confidence: 0.75,
                        },
                    );
                }
            }
        }

        if !is_yaml_comment_line(line) && is_docker_compose_file(file) {
            if let Some(name) = compose_bare_env
                .captures(line)
                .and_then(|caps| caps.get(1))
                .map(|m| m.as_str())
            {
                push_env_read(
                    findings,
                    observed_env_reads,
                    observed_seen,
                    EnvReadInput {
                        file,
                        source_line: line,
                        line_number,
                        name,
                        language: "docker-compose",
                        confidence: 0.65,
                    },
                );
            }
        }

        for (regex, language) in [
            (&js_dot, "javascript"),
            (&js_index, "javascript"),
            (&py_environ, "python"),
            (&py_getenv, "python"),
            (&rust_env, "rust"),
        ] {
            for caps in regex.captures_iter(line) {
                if let Some(name) = caps.get(1).map(|m| m.as_str()) {
                    push_env_read(
                        findings,
                        observed_env_reads,
                        observed_seen,
                        EnvReadInput {
                            file,
                            source_line: line,
                            line_number,
                            name,
                            language,
                            confidence: 0.90,
                        },
                    );
                }
            }
        }

        if file.ends_with(".sh") {
            for caps in shell_export.captures_iter(line) {
                if let Some(name) = caps.get(1).map(|m| m.as_str()) {
                    findings.push(base_finding(
                        FindingKind::UnsafeExport,
                        Severity::Medium,
                        0.65,
                        FindingLocation {
                            file,
                            line: line_number,
                            column: column_of(line, name),
                        },
                        Some(name.to_string()),
                        format!("Shell script exports {name} into process environment"),
                    ));
                }
            }

            for caps in shell_var.captures_iter(line) {
                if let Some(name) = caps.get(1).map(|m| m.as_str()) {
                    push_env_read(
                        findings,
                        observed_env_reads,
                        observed_seen,
                        EnvReadInput {
                            file,
                            source_line: line,
                            line_number,
                            name,
                            language: "shell",
                            confidence: 0.50,
                        },
                    );
                }
            }
        }
    }

    Ok(())
}

#[derive(Clone, Copy)]
struct FindingLocation<'a> {
    file: &'a str,
    line: usize,
    column: usize,
}

struct EnvReadInput<'a> {
    file: &'a str,
    source_line: &'a str,
    line_number: usize,
    name: &'a str,
    language: &'a str,
    confidence: f32,
}

struct EnvAuthorityInput<'a> {
    file: &'a str,
    source_line: &'a str,
    line_number: usize,
    name: &'a str,
    language: &'a str,
    confidence: f32,
    kind: FindingKind,
    severity: Severity,
    message: String,
}

struct SecretFindingInput<'a> {
    kind: FindingKind,
    severity: Severity,
    confidence: f32,
    location: FindingLocation<'a>,
    secret_type: &'a str,
    name: &'a str,
    value: &'a str,
    message: &'a str,
}

#[derive(Clone, Copy)]
struct AwsObjectFindingArgs<'a> {
    file: &'a str,
    line: &'a str,
    line_number: usize,
    value: &'a str,
    name: &'a str,
    file_path_is_placeholder: bool,
    in_docstring: bool,
}

fn push_env_read(
    findings: &mut Vec<ScanFinding>,
    observed_env_reads: &mut Vec<ObservedEnvRead>,
    observed_seen: &mut HashSet<(String, String, usize)>,
    input: EnvReadInput<'_>,
) {
    push_env_authority_reference(
        findings,
        observed_env_reads,
        observed_seen,
        EnvAuthorityInput {
            file: input.file,
            source_line: input.source_line,
            line_number: input.line_number,
            name: input.name,
            language: input.language,
            confidence: input.confidence,
            kind: FindingKind::RuntimeEnvRead,
            severity: Severity::Medium,
            message: format!("Runtime reads environment variable {}", input.name),
        },
    );
}

fn push_env_authority_reference(
    findings: &mut Vec<ScanFinding>,
    observed_env_reads: &mut Vec<ObservedEnvRead>,
    observed_seen: &mut HashSet<(String, String, usize)>,
    input: EnvAuthorityInput<'_>,
) {
    let key = (
        input.name.to_string(),
        input.file.to_string(),
        input.line_number,
    );
    if observed_seen.insert(key) {
        observed_env_reads.push(ObservedEnvRead {
            name: input.name.to_string(),
            file: input.file.to_string(),
            line: input.line_number,
            language: input.language.to_string(),
            confidence: input.confidence,
        });
    }

    findings.push(base_finding(
        input.kind,
        input.severity,
        input.confidence,
        FindingLocation {
            file: input.file,
            line: input.line_number,
            column: column_of(input.source_line, input.name),
        },
        Some(input.name.to_string()),
        input.message,
    ));
}

fn push_secret_finding(findings: &mut Vec<ScanFinding>, input: SecretFindingInput<'_>) {
    let mut finding = base_finding(
        input.kind,
        input.severity,
        input.confidence,
        input.location,
        Some(input.name.to_string()),
        input.message.to_string(),
    );
    finding.secret_type = Some(input.secret_type.to_string());
    finding.redacted_value = Some(redact::redacted(input.value));
    finding.hash = Some(redact::fingerprint(input.value));
    findings.push(finding);
}

fn push_aws_object_finding(findings: &mut Vec<ScanFinding>, args: AwsObjectFindingArgs<'_>) {
    let placeholder_match = args.file_path_is_placeholder
        || args.in_docstring
        || is_doc_or_comment_line(args.file, args.line);
    let kind = if placeholder_match {
        FindingKind::SecretPlaceholder
    } else {
        FindingKind::HardcodedSecret
    };
    let severity = if placeholder_match {
        Severity::Info
    } else {
        Severity::High
    };
    let message = if placeholder_match {
        "AWS credential in placeholder/comment context (suppressed)"
    } else {
        "AWS credential appears in object-syntax assignment"
    };
    push_secret_finding(
        findings,
        SecretFindingInput {
            kind,
            severity,
            confidence: confidence_for_value(args.value, 0.92),
            location: FindingLocation {
                file: args.file,
                line: args.line_number,
                column: column_of(args.line, args.value),
            },
            secret_type: "aws-object-syntax",
            name: args.name,
            value: args.value,
            message,
        },
    );
}

fn base_finding(
    kind: FindingKind,
    severity: Severity,
    confidence: f32,
    location: FindingLocation<'_>,
    name: Option<String>,
    message: String,
) -> ScanFinding {
    ScanFinding {
        id: String::new(),
        kind,
        severity,
        confidence,
        file: location.file.to_string(),
        line: location.line,
        column: location.column,
        secret_type: None,
        name,
        redacted_value: None,
        hash: None,
        message,
    }
}

fn renumber_findings(findings: &mut [ScanFinding]) {
    for (index, finding) in findings.iter_mut().enumerate() {
        // Phase 4 rename: emit `TSAFE-FINDING-NNNN`. Downstream consumers
        // that grep for the legacy `ALGOL-FINDING-` prefix must update;
        // the prefix change is documented in CHANGELOG.
        finding.id = format!("TSAFE-FINDING-{number:04}", number = index + 1);
    }
}

fn summarize(findings: &[ScanFinding]) -> ScanSummary {
    let mut summary = ScanSummary {
        total_findings: findings.len(),
        ..ScanSummary::default()
    };
    let mut score = 0;
    for finding in findings {
        score += finding.severity.weight();
        match finding.severity {
            Severity::Critical => summary.critical += 1,
            Severity::High => summary.high += 1,
            Severity::Medium => summary.medium += 1,
            Severity::Low => summary.low += 1,
            Severity::Info => {}
        }
    }
    summary.risk_score = score.min(100);
    summary
}

fn is_ignored_entry(entry: &DirEntry) -> bool {
    let name = entry.file_name().to_string_lossy();
    matches!(
        name.as_ref(),
        ".git" | "node_modules" | "target" | "dist" | "build" | ".venv" | "vendor"
    )
}

fn is_scannable_file(path: &Path, repo: &Path) -> bool {
    let relative = relative_path(path, repo);
    let name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or_default();
    let extension = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or_default();

    is_env_file(&relative)
        || relative.starts_with(".github/workflows/") && matches!(extension, "yml" | "yaml")
        || matches!(
            name,
            "package.json" | "Dockerfile" | "docker-compose.yml" | "docker-compose.yaml"
        )
        // Phase 2.1 Patch B: extend scannable extensions to include
        // private-key + JSON config + YAML files so the existing
        // private-key + AWS detectors can fire on them.
        || matches!(
            extension,
            "env" | "sh" | "js" | "ts" | "py" | "rs" | "pem" | "json" | "yaml" | "yml"
        )
}

fn is_env_file(file: &str) -> bool {
    let name = Path::new(file)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(file);
    name == ".env" || name.starts_with(".env.") || name.ends_with(".env")
}

/// Phase 2.1 Patch A — detect file paths that signal placeholder content.
///
/// Findings emitted from such files are downgraded to
/// [`FindingKind::SecretPlaceholder`] (`Severity::Info`) and excluded
/// from the corpus measurement's "scanner says secret" classifier. The
/// audit trail still retains the original match for traceability.
fn is_placeholder_file_path(file: &str) -> bool {
    let normalised = file.replace('\\', "/");
    let lower = normalised.to_ascii_lowercase();
    let name = Path::new(&normalised)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(&normalised)
        .to_ascii_lowercase();

    if name.ends_with(".example")
        || name.ends_with(".template")
        || name.ends_with(".sample")
        || name.ends_with(".dist")
        || name.ends_with(".fixture")
        || name.ends_with(".tmpl")
    {
        return true;
    }
    if name.contains(".example.") || name.contains(".template.") || name.contains(".sample.") {
        return true;
    }
    if name.starts_with("example.")
        || name.starts_with("examples.")
        || name.starts_with("template.")
        || name.starts_with("sample.")
        || name.starts_with("test_fixture")
        || name.starts_with("test-fixture")
        || name.starts_with("fixture")
    {
        return true;
    }
    for marker in [
        "/docs/",
        "/doc/",
        "/examples/",
        "/example/",
        "/test-fixtures/",
        "/test_fixtures/",
        "/fixtures/",
        "/samples/",
        "/sample/",
        "/templates/",
        "/template/",
    ] {
        if lower.contains(marker) {
            return true;
        }
    }
    false
}

/// Phase 2.1 Patch A — detect comment / doc-comment lines so findings on
/// commented-out example code are suppressed.
fn is_doc_or_comment_line(file: &str, line: &str) -> bool {
    let trimmed = line.trim_start();
    if trimmed.is_empty() {
        return false;
    }
    // Rust doc-comment (`///`, `//!`) and ordinary `//` comments.
    if trimmed.starts_with("///") || trimmed.starts_with("//!") || trimmed.starts_with("//") {
        return true;
    }
    // C-style block comment continuation lines (` * foo`).
    if trimmed.starts_with("/*") || trimmed.starts_with('*') {
        let after = trimmed.trim_start_matches(['*', '/']);
        if after.is_empty() || after.starts_with(' ') || after.starts_with('\t') {
            return true;
        }
    }
    // Shell / Python / YAML / TOML `#` line comments.
    if trimmed.starts_with('#') {
        let _ = file; // file is currently unused; kept for future per-language tuning.
        return true;
    }
    false
}

/// Phase 2.1 Patch A — detect values that are pure env-interpolation,
/// e.g. `${GITHUB_TOKEN}`. Common in `.env`-style files that read from
/// the environment rather than committing a literal secret.
fn is_env_interpolation_value(value: &str) -> bool {
    let trimmed = value.trim().trim_matches(['"', '\'']);
    trimmed.starts_with("${") && trimmed.ends_with('}')
}

/// Phase 2.1 Patch A — precompute, for each line of `content`, whether
/// the line is inside a Python triple-quoted string (treated as a
/// docstring / module docstring). Returns all-false for non-Python files.
fn compute_docstring_lines(file: &str, content: &str) -> Vec<bool> {
    let path = Path::new(file);
    let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let total_lines = content.lines().count();

    if extension != "py" {
        return vec![false; total_lines];
    }

    let mut out = Vec::with_capacity(total_lines);
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum Quote {
        None,
        Double,
        Single,
    }
    let mut state = Quote::None;
    for line in content.lines() {
        let started_in_string = state != Quote::None;
        let mut remaining = line;
        loop {
            match state {
                Quote::None => {
                    let dq = remaining.find("\"\"\"");
                    let sq = remaining.find("'''");
                    let next = match (dq, sq) {
                        (Some(a), Some(b)) if a < b => Some((a, Quote::Double)),
                        (Some(a), Some(_b)) => Some((a, Quote::Double)).filter(|_| a < _b),
                        (Some(a), None) => Some((a, Quote::Double)),
                        (None, Some(b)) => Some((b, Quote::Single)),
                        (None, None) => None,
                    };
                    match next {
                        Some((idx, q)) => {
                            state = q;
                            let after_idx = idx + 3;
                            if after_idx >= remaining.len() {
                                remaining = "";
                            } else {
                                remaining = &remaining[after_idx..];
                            }
                        }
                        None => break,
                    }
                }
                Quote::Double => {
                    if let Some(idx) = remaining.find("\"\"\"") {
                        state = Quote::None;
                        let after_idx = idx + 3;
                        if after_idx >= remaining.len() {
                            remaining = "";
                        } else {
                            remaining = &remaining[after_idx..];
                        }
                    } else {
                        break;
                    }
                }
                Quote::Single => {
                    if let Some(idx) = remaining.find("'''") {
                        state = Quote::None;
                        let after_idx = idx + 3;
                        if after_idx >= remaining.len() {
                            remaining = "";
                        } else {
                            remaining = &remaining[after_idx..];
                        }
                    } else {
                        break;
                    }
                }
            }
        }
        let ended_in_string = state != Quote::None;
        out.push(started_in_string || ended_in_string);
    }
    out
}

fn is_dockerfile(file: &str) -> bool {
    Path::new(file).file_name().and_then(|name| name.to_str()) == Some("Dockerfile")
}

fn is_docker_compose_file(file: &str) -> bool {
    matches!(
        Path::new(file).file_name().and_then(|name| name.to_str()),
        Some("docker-compose.yml" | "docker-compose.yaml")
    )
}

fn is_yaml_comment_line(line: &str) -> bool {
    line.trim_start().starts_with('#')
}

fn is_js_comment_line(line: &str) -> bool {
    let trimmed = line.trim_start();
    trimmed.starts_with("//") || trimmed.starts_with("/*") || trimmed.starts_with('*')
}

fn is_destructive_path_sink(line: &str, variable: &str) -> bool {
    line.contains(variable)
        && [
            "forceRemove(",
            "fs.rm(",
            "fs.rmSync(",
            "fs.unlink(",
            "fs.unlinkSync(",
            "rm(",
            "rmSync(",
            "remove(",
        ]
        .iter()
        .any(|sink| line.contains(sink))
}

fn env_file_severity(file: &str, value: &str) -> Severity {
    if file.contains("production") && !redact::is_placeholder(value) {
        Severity::Critical
    } else if file.ends_with(".example") {
        Severity::Low
    } else {
        Severity::High
    }
}

fn confidence_for_value(value: &str, base: f32) -> f32 {
    if redact::is_placeholder(value) {
        (base - 0.25).max(0.35)
    } else {
        base
    }
}

fn extract_assigned_value<'a>(line: &'a str, name: &str) -> Option<&'a str> {
    let position = line.find(name)?;
    let after = &line[position + name.len()..];
    let after = after.trim_start();
    let value = after
        .strip_prefix('=')
        .or_else(|| after.strip_prefix(':'))?
        .trim_start()
        .trim_start_matches(['"', '\''])
        .split(['"', '\'', ' ', '\t'])
        .next()?;
    (!value.is_empty()).then_some(value)
}

fn should_skip_hardcoded_secret(file: &str, line: &str, value: &str) -> bool {
    is_env_file(file)
        || line.contains("${{ secrets.")
        || line.contains("process.env.")
        || line.contains("process.env[")
        || line.contains("os.getenv(")
        || line.contains("os.environ[")
        || line.contains("std::env::var(")
        || line.contains("env::var(")
        || line.trim_start().starts_with("export ")
        || value.contains("process.env")
        || value.contains("os.getenv")
        || value.contains("os.environ")
        || value.contains("std::env::var")
        || value.contains("env::var")
        || value.contains("secrets.")
        || value.contains("${")
}

fn should_skip_generic_secret_line(file: &str, line: &str) -> bool {
    is_env_file(file)
        || line.contains("${{ secrets.")
        || line.contains("process.env.")
        || line.contains("process.env[")
        || line.contains("os.getenv(")
        || line.contains("os.environ[")
        || line.contains("std::env::var(")
        || line.contains("env::var(")
        || line.trim_start().starts_with("export ")
        || line.contains("${")
}

fn ensure_parent_dir(path: &Path) -> Result<()> {
    if let Some(parent) = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        fs::create_dir_all(parent)
            .with_context(|| format!("create output directory: {}", parent.display()))?;
    }
    Ok(())
}

fn column_of(line: &str, needle: &str) -> usize {
    line.find(needle).map(|index| index + 1).unwrap_or(1)
}

fn relative_path(path: &Path, repo: &Path) -> String {
    path.strip_prefix(repo)
        .unwrap_or(path)
        .to_string_lossy()
        .replace('\\', "/")
}

#[cfg(test)]
mod tests {
    use std::fs;

    use tempfile::tempdir;

    use super::*;

    // ── Phase 2 (algol baseline) ─────────────────────────────────────────

    #[test]
    fn detects_env_files_process_reads_github_secrets_and_exports() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join(".github/workflows")).unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::create_dir_all(tmp.path().join("scripts")).unwrap();
        fs::write(
            tmp.path().join(".env"),
            "DATABASE_URL=postgres://user:password@localhost:5432/app\n",
        )
        .unwrap();
        fs::write(
            tmp.path().join(".github/workflows/ci.yml"),
            "env:\n  PROD_DEPLOY_KEY: ${{ secrets.PROD_DEPLOY_KEY }}\n",
        )
        .unwrap();
        fs::write(
            tmp.path().join("src/config.js"),
            "const token = process.env.API_TOKEN;\n",
        )
        .unwrap();
        fs::write(
            tmp.path().join("scripts/dev.sh"),
            "export STRIPE_SECRET_KEY=sk_live_fake_exported_1234567890\n",
        )
        .unwrap();

        let report = scan_repo(tmp.path()).unwrap();
        assert!(report.findings.iter().any(|f| f.file == ".env"));
        assert!(report
            .observed_env_reads
            .iter()
            .any(|read| read.name == "API_TOKEN"));
        assert!(report
            .ci_secret_references
            .iter()
            .any(|reference| reference.name == "PROD_DEPLOY_KEY"));
        assert!(report
            .findings
            .iter()
            .any(|finding| finding.kind == FindingKind::UnsafeExport));
    }

    #[test]
    fn ignores_node_modules() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("node_modules/pkg")).unwrap();
        fs::write(
            tmp.path().join("node_modules/pkg/index.js"),
            "const token = process.env.API_TOKEN;\n",
        )
        .unwrap();

        let report = scan_repo(tmp.path()).unwrap();
        assert!(report.observed_env_reads.is_empty());
    }

    #[test]
    fn reduces_confidence_for_placeholder_values() {
        let tmp = tempdir().unwrap();
        fs::write(tmp.path().join(".env"), "API_TOKEN=your-key-here\n").unwrap();

        let report = scan_repo(tmp.path()).unwrap();
        assert!(report
            .findings
            .iter()
            .any(|finding| finding.confidence < 0.85));
    }

    #[test]
    fn treats_credential_names_as_sensitive() {
        for name in ["GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_GHA_CREDS_PATH"] {
            assert!(is_sensitive_env_name(name), "{name} was not sensitive");
        }
    }

    #[test]
    fn does_not_treat_env_reads_as_hardcoded_secrets() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(
            tmp.path().join("src/config.js"),
            "module.exports = { apiToken: process.env.API_TOKEN };\n",
        )
        .unwrap();

        let report = scan_repo(tmp.path()).unwrap();
        assert!(report
            .findings
            .iter()
            .any(|finding| finding.kind == FindingKind::RuntimeEnvRead));
        assert!(!report
            .findings
            .iter()
            .any(|finding| finding.kind == FindingKind::HardcodedSecret));
    }

    #[test]
    fn does_not_treat_output_labels_as_secret_assignments() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("test.js"),
            "console.log(\"DATABASE_URL present:\", Boolean(config.databaseUrl));\n",
        )
        .unwrap();

        let report = scan_repo(tmp.path()).unwrap();
        assert!(report.findings.is_empty());
    }

    // ── Phase 2.1 — Patch A (placeholder suppression) ───────────────────

    fn has_secret_finding(report: &ScanReport) -> bool {
        report.findings.iter().any(|f| {
            matches!(
                f.kind,
                FindingKind::EnvFile | FindingKind::HardcodedSecret | FindingKind::PrivateKey
            )
        })
    }

    fn has_placeholder_finding(report: &ScanReport) -> bool {
        report
            .findings
            .iter()
            .any(|f| f.kind == FindingKind::SecretPlaceholder)
    }

    #[test]
    fn placeholder_env_example_with_your_x_here_does_not_emit_secret() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join(".env.example"),
            "ANTHROPIC_API_KEY=your-anthropic-key-here\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(!has_secret_finding(&report));
        assert!(has_placeholder_finding(&report));
    }

    #[test]
    fn placeholder_env_example_with_angle_brackets_does_not_emit_secret() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join(".env.example"),
            "GITHUB_TOKEN=<your-github-token>\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(!has_secret_finding(&report));
        assert!(has_placeholder_finding(&report));
    }

    #[test]
    fn placeholder_env_example_with_redacted_marker_does_not_emit_secret() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join(".env.example"),
            "DATABASE_URL=REDACTED_BEFORE_COMMIT\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(!has_secret_finding(&report));
    }

    #[test]
    fn placeholder_env_example_with_aws_docs_example_does_not_emit_secret() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join(".env.example"),
            "AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(!has_secret_finding(&report));
    }

    #[test]
    fn env_interpolation_value_does_not_emit_secret() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("config.env"),
            "GITHUB_TOKEN=${GITHUB_TOKEN}\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(!has_secret_finding(&report));
    }

    #[test]
    fn doc_comment_example_does_not_emit_secret() {
        let tmp = tempdir().unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(
            tmp.path().join("src/lib.rs"),
            "/// # Example\n/// // Set GITHUB_TOKEN=ghp_example_here\npub fn from_env() {}\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(!has_secret_finding(&report));
    }

    #[test]
    fn js_comment_example_does_not_emit_secret() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("examples.js"),
            "// const apiKey = 'sk-ant-api03-REPLACE-WITH-YOUR-OWN-KEY';\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(!has_secret_finding(&report));
    }

    #[test]
    fn python_docstring_example_does_not_emit_secret() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("deploy.py"),
            "\"\"\"Module docstring.\n\nExample usage::\n\n    GITHUB_TOKEN=ghp_REPLACE_ME_BEFORE_DEPLOY python deploy.py\n\n\"\"\"\nimport os\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(!has_secret_finding(&report));
    }

    #[test]
    fn test_fixture_env_path_suppresses_findings() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("test_fixture.env"),
            "TEST_SIGNING_KEY=test_signing_key_for_unit_tests_only_v1\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(!has_secret_finding(&report));
    }

    // ── Phase 2.1 — Patch B (extension + regex extension) ───────────────

    #[test]
    fn detects_aws_credentials_in_js_object_syntax() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("config.js"),
            "const creds = { accessKeyId: 'AKIA7D1410K9KELBYMXY', secretAccessKey: 'f7JoLTKaxe0cnoV7TLSl+95ovmXkSfaqdDr75A6R' };\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(report
            .findings
            .iter()
            .any(|f| f.kind == FindingKind::HardcodedSecret

                && f.secret_type.as_deref() == Some("aws-object-syntax")));
    }

    #[test]
    fn detects_aws_credentials_in_json_object_syntax() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("config.json"),
            "{\n  \"awsAccessKeyId\": \"AKIA7D1410K9KELBYMXY\",\n  \"awsSecretAccessKey\": \"f7JoLTKaxe0cnoV7TLSl+95ovmXkSfaqdDr75A6R\"\n}\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(report
            .findings
            .iter()
            .any(|f| f.kind == FindingKind::HardcodedSecret

                && f.secret_type.as_deref() == Some("aws-object-syntax")));
    }

    #[test]
    fn detects_private_key_in_pem_file() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("deploy_key.pem"),
            "-----BEGIN PRIVATE KEY-----\nMIIBVgIBADANBgkqhkiG9w0BAQEFAA\n-----END PRIVATE KEY-----\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(report
            .findings
            .iter()
            .any(|f| f.kind == FindingKind::PrivateKey));
    }

    #[test]
    fn detects_private_key_in_service_account_json() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join("service-account.json"),
            "{\n  \"type\": \"service_account\",\n  \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMIIBVgIBADANBgkqhkiG9w0BAQEFAA\\n-----END PRIVATE KEY-----\\n\"\n}\n",
        )
        .unwrap();
        let report = scan_repo(tmp.path()).unwrap();
        assert!(report
            .findings
            .iter()
            .any(|f| f.kind == FindingKind::PrivateKey));
    }

    // ── Phase 3 — BLAKE3 wire-format change (ec ADR-0003) ───────────────

    #[test]
    fn finding_hash_uses_blake3_prefix() {
        let tmp = tempdir().unwrap();
        fs::write(
            tmp.path().join(".env"),
            "DATABASE_URL=postgres://user:password@db.internal:5432/app\n",
        )
        .unwrap();

        let report = scan_repo(tmp.path()).unwrap();
        let with_hash: Vec<_> = report
            .findings
            .iter()
            .filter(|f| f.hash.is_some())
            .collect();
        assert!(
            !with_hash.is_empty(),
            "expected at least one finding with a hash"
        );
        for finding in with_hash {
            let hash = finding.hash.as_deref().unwrap();
            assert!(
                hash.starts_with("blake3:"),
                "Phase 3 fingerprint MUST be BLAKE3 (ec ADR-0003), got {hash:?} on {:?}",
                finding.kind
            );
            // Hex length check: blake3: + 64 hex chars.
            assert_eq!(hash.len(), "blake3:".len() + 64, "blake3 hash length");
        }
    }
}