fallow-core 2.90.0

Analysis orchestration for fallow codebase intelligence (dead code, duplication, plugins, cross-reference)
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
//! Reachability-weighted ranking of security candidates (issues #860 and #885).
//!
//! Reuses the existing module graph to rank `fallow security` candidates by
//! runtime reachability, source-backed evidence, module-level untrusted-source
//! reachability, reverse-dependency fan-in, boundary crossings, and dead-code
//! context. This is graph-side glue plus output ordering only: it touches
//! neither the extract cache nor detector semantics.
//!
//! The ranking is a relative-ordering signal, NOT proof of exploitability:
//! candidates remain CANDIDATES for downstream agent verification.

use std::collections::VecDeque;
use std::path::{Path, PathBuf};

use rustc_hash::{FxHashMap, FxHashSet};

use fallow_types::extract::{ExportName, ModuleInfo};
use fallow_types::output::{FixAction, FixActionType, IssueAction};
use fallow_types::output_dead_code::{UnusedExportFinding, UnusedFileFinding};
use fallow_types::results::{
    SecurityAttackSurfaceEntry, SecurityCandidateBoundary, SecurityDeadCodeContext,
    SecurityDeadCodeKind, SecurityDefensiveBoundary, SecurityDefensiveControl, SecurityFinding,
    SecurityFindingKind, SecurityReachability, SecurityTaintFlow, SecurityZoneCrossing,
    TaintEndpoint, TaintPath, TraceHop, TraceHopRole,
};

use crate::discover::FileId;
use crate::graph::ModuleGraph;

use super::{LineOffsetsMap, byte_offset_to_line_col, catalogue::catalogue};

const UNUSED_FILE_GUIDANCE: &str = "This sink sits in a file fallow also reports as unused. Verify the dead-code finding, then delete the file instead of hardening the sink.";
const UNUSED_EXPORT_GUIDANCE: &str = "This sink sits on an export fallow also reports as unused. Verify the dead-code finding, then remove the export instead of hardening the sink.";
const ZERO_CONTROL_PROMPT: &str = "No known control library was detected on this path. Should validation, sanitization, or auth be required before this sink?";
const CONTROL_PRESENT_PROMPT: &str = "Known defensive controls were detected on this path. Are they sufficient for this sink and untrusted input?";

/// Annotate tainted-sink candidates that overlap dead-code findings from the same
/// analysis run. Client-server leak findings stay unchanged because #884 was
/// narrowed to sink candidates.
pub fn annotate_dead_code_cross_links(
    graph: &ModuleGraph,
    modules: &[ModuleInfo],
    line_offsets_by_file: &LineOffsetsMap<'_>,
    unused_files: &[UnusedFileFinding],
    unused_exports: &[UnusedExportFinding],
    findings: &mut [SecurityFinding],
) {
    if findings.is_empty() || (unused_files.is_empty() && unused_exports.is_empty()) {
        return;
    }

    let unused_file_paths: FxHashSet<&Path> =
        unused_files.iter().map(|f| f.file.path.as_path()).collect();
    let modules_by_id: FxHashMap<FileId, &ModuleInfo> = modules
        .iter()
        .map(|module| (module.file_id, module))
        .collect();
    let module_by_path: FxHashMap<&Path, &ModuleInfo> = graph
        .modules
        .iter()
        .filter_map(|node| {
            modules_by_id
                .get(&node.file_id)
                .map(|module| (node.path.as_path(), *module))
        })
        .collect();

    for finding in findings {
        if !matches!(finding.kind, SecurityFindingKind::TaintedSink) {
            continue;
        }
        if unused_file_paths.contains(finding.path.as_path()) {
            finding.dead_code = Some(SecurityDeadCodeContext {
                kind: SecurityDeadCodeKind::UnusedFile,
                export_name: None,
                line: None,
                guidance: UNUSED_FILE_GUIDANCE.to_string(),
            });
            prepend_dead_code_action(finding);
            continue;
        }

        if let Some(export) = matching_unused_export(
            module_by_path.get(finding.path.as_path()).copied(),
            line_offsets_by_file,
            unused_exports,
            finding,
        ) {
            finding.dead_code = Some(SecurityDeadCodeContext {
                kind: SecurityDeadCodeKind::UnusedExport,
                export_name: Some(export.export.export_name.clone()),
                line: Some(export.export.line),
                guidance: UNUSED_EXPORT_GUIDANCE.to_string(),
            });
            prepend_dead_code_action(finding);
        }
    }
}

fn matching_unused_export<'a>(
    module: Option<&ModuleInfo>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
    unused_exports: &'a [UnusedExportFinding],
    finding: &SecurityFinding,
) -> Option<&'a UnusedExportFinding> {
    let same_file = unused_exports
        .iter()
        .filter(|export| export.export.path == finding.path);

    if let Some(module) = module {
        for export in same_file.clone() {
            let Some(info) = module
                .exports
                .iter()
                .find(|info| export_name_matches(&info.name, &export.export.export_name))
            else {
                continue;
            };
            let (start_line, _) =
                byte_offset_to_line_col(line_offsets_by_file, module.file_id, info.span.start);
            let (end_line, _) =
                byte_offset_to_line_col(line_offsets_by_file, module.file_id, info.span.end);
            if start_line <= finding.line && finding.line <= end_line.max(start_line) {
                return Some(export);
            }
        }
    }

    same_file
        .into_iter()
        .find(|export| export.export.line == finding.line)
}

fn export_name_matches(name: &ExportName, candidate: &str) -> bool {
    match name {
        ExportName::Named(name) => name == candidate,
        ExportName::Default => candidate == "default",
    }
}

fn prepend_dead_code_action(finding: &mut SecurityFinding) {
    let Some(context) = &finding.dead_code else {
        return;
    };
    let action = match context.kind {
        SecurityDeadCodeKind::UnusedFile => IssueAction::Fix(FixAction {
            kind: FixActionType::DeleteFile,
            auto_fixable: false,
            description: "Delete this unused file instead of hardening the sink".to_string(),
            note: Some(
                "Verify the unused-file finding before deleting production code".to_string(),
            ),
            available_in_catalogs: None,
            suggested_target: None,
        }),
        SecurityDeadCodeKind::UnusedExport => IssueAction::Fix(FixAction {
            kind: FixActionType::RemoveExport,
            auto_fixable: false,
            description: "Remove the unused export instead of hardening the sink".to_string(),
            note: context
                .export_name
                .as_ref()
                .map(|name| format!("Verify that export `{name}` is unused before removing it")),
            available_in_catalogs: None,
            suggested_target: None,
        }),
    };
    finding.actions.insert(0, action);
}

/// Rank security findings in place: fill each finding's [`SecurityReachability`]
/// from the graph, then re-sort so the highest-priority candidates sort first.
///
/// `boundary_crossings` maps each file path that participates in an
/// architecture-boundary violation found in the same run (importing or imported
/// side) to the `(from_zone, to_zone)` names of that crossing; a finding whose
/// anchor is a key is flagged `crosses_boundary` and its candidate records the
/// zone names (issue #900).
///
/// Sort order (descending priority): reachable-from-entry first, same-module
/// source-backed sinks, module-level source-reachable sinks, larger blast
/// radius, crosses-boundary, active-code over dead-code candidates, then the
/// existing deterministic `(path, line, col, category)` tiebreak so output stays
/// stable across runs.
pub fn rank_security_findings(
    graph: &ModuleGraph,
    modules: &[ModuleInfo],
    line_offsets_by_file: &LineOffsetsMap<'_>,
    declared_deps: &FxHashSet<String>,
    boundary_crossings: &FxHashMap<PathBuf, (String, String)>,
    findings: &mut [SecurityFinding],
) {
    if findings.is_empty() {
        return;
    }

    // O(1) path -> FileId index over graph modules, built once.
    let path_to_id: FxHashMap<&Path, FileId> = graph
        .modules
        .iter()
        .map(|node| (node.path.as_path(), node.file_id))
        .collect();
    let source_index = UntrustedSourceIndex::build(graph, modules, declared_deps);
    let modules_by_id: FxHashMap<FileId, &ModuleInfo> = modules
        .iter()
        .map(|module| (module.file_id, module))
        .collect();
    let modules_by_path: FxHashMap<&Path, &ModuleInfo> = graph
        .modules
        .iter()
        .filter_map(|node| {
            modules_by_id
                .get(&node.file_id)
                .map(|module| (node.path.as_path(), *module))
        })
        .collect();

    for finding in findings.iter_mut() {
        let reachability = path_to_id.get(finding.path.as_path()).map(|&file_id| {
            compute_reachability(
                graph,
                file_id,
                finding,
                boundary_crossings,
                &source_index,
                line_offsets_by_file,
            )
        });
        finding.reachability = reachability;
        // Issue #900: fill the candidate boundary slot and the taint-flow triple
        // from the reachability + trace just computed. Pure re-projection: no new
        // analysis. The zone names come from the same boundary-crossing map.
        enrich_candidate(finding, boundary_crossings.get(&finding.path));
        finding.attack_surface =
            build_attack_surface(finding, &modules_by_path, line_offsets_by_file);
    }

    findings.sort_by(|a, b| {
        let (ra, rb) = (a.reachability.as_ref(), b.reachability.as_ref());
        // Reachable-from-entry findings sort first.
        let reach_a = ra.is_some_and(|r| r.reachable_from_entry);
        let reach_b = rb.is_some_and(|r| r.reachable_from_entry);
        reach_b
            .cmp(&reach_a)
            // Then same-module source-backed sinks first.
            .then_with(|| b.source_backed.cmp(&a.source_backed))
            // Then module-level source-reachable sinks first.
            .then_with(|| {
                let source_a = ra.is_some_and(|r| r.reachable_from_untrusted_source);
                let source_b = rb.is_some_and(|r| r.reachable_from_untrusted_source);
                source_b.cmp(&source_a)
            })
            // Then larger blast radius first.
            .then_with(|| {
                let ba = ra.map_or(0, |r| r.blast_radius);
                let bb = rb.map_or(0, |r| r.blast_radius);
                bb.cmp(&ba)
            })
            // Then boundary-crossing candidates first.
            .then_with(|| {
                let ca = ra.is_some_and(|r| r.crosses_boundary);
                let cb = rb.is_some_and(|r| r.crosses_boundary);
                cb.cmp(&ca)
            })
            // Then active-code candidates before dead-code candidates.
            .then_with(|| a.dead_code.is_some().cmp(&b.dead_code.is_some()))
            // Deterministic tiebreak (matches the detectors' own ordering).
            .then_with(|| a.path.cmp(&b.path))
            .then_with(|| a.line.cmp(&b.line))
            .then_with(|| a.col.cmp(&b.col))
            .then_with(|| a.category.cmp(&b.category))
    });
}

/// Compute the reachability signal for a single anchor module.
fn compute_reachability(
    graph: &ModuleGraph,
    file_id: FileId,
    finding: &SecurityFinding,
    boundary_crossings: &FxHashMap<PathBuf, (String, String)>,
    source_index: &UntrustedSourceIndex,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> SecurityReachability {
    let reachable_from_entry = graph
        .modules
        .get(file_id.0 as usize)
        .is_some_and(|node| node.is_runtime_reachable());
    let source_trace = source_index.trace_for(graph, file_id, finding, line_offsets_by_file);

    SecurityReachability {
        reachable_from_entry,
        reachable_from_untrusted_source: source_trace.is_some(),
        untrusted_source_hop_count: source_trace.as_ref().map(|source| source.hop_count),
        untrusted_source_trace: source_trace.map_or_else(Vec::new, |source| source.trace),
        blast_radius: transitive_dependent_count(graph, file_id),
        crosses_boundary: boundary_crossings.contains_key(&finding.path),
    }
}

/// Fill the candidate's boundary slot and the taint-flow triple from the
/// finding's trace and the reachability just computed (issue #900). Re-projection
/// only: client/server from a `ClientBoundary` trace hop, cross-module from the
/// untrusted-source hop count, and the architecture zone from the run's
/// boundary-crossing map. The `source_kind` and `sink` slots are set by the
/// detectors and left untouched here.
fn enrich_candidate(finding: &mut SecurityFinding, zone: Option<&(String, String)>) {
    let client_server = finding
        .trace
        .iter()
        .any(|hop| hop.role == TraceHopRole::ClientBoundary);
    let hop_count = finding
        .reachability
        .as_ref()
        .and_then(|reach| reach.untrusted_source_hop_count);
    finding.candidate.boundary = SecurityCandidateBoundary {
        client_server,
        cross_module: hop_count.is_some_and(|count| count > 0),
        architecture_zone: zone.map(|(from, to)| SecurityZoneCrossing {
            from: from.clone(),
            to: to.clone(),
        }),
    };
    finding.taint_flow = build_taint_flow(finding);
}

/// Build the `{ source, sink, path }` taint-flow triple when an untrusted source
/// is import-reachable to the sink. The full ordered hops are NOT duplicated:
/// `path` is the compact shape, the hops stay on `reachability.untrusted_source_trace`.
fn build_taint_flow(finding: &SecurityFinding) -> Option<SecurityTaintFlow> {
    let reach = finding.reachability.as_ref()?;
    if !reach.reachable_from_untrusted_source {
        return None;
    }
    let first = reach.untrusted_source_trace.first()?;
    let last = reach.untrusted_source_trace.last()?;
    let hop_count = reach.untrusted_source_hop_count.unwrap_or(0);
    Some(SecurityTaintFlow {
        source: TaintEndpoint {
            path: first.path.clone(),
            line: first.line,
            col: first.col,
        },
        sink: TaintEndpoint {
            path: last.path.clone(),
            line: last.line,
            col: last.col,
        },
        path: TaintPath {
            intra_module: hop_count == 0,
            cross_module_hops: hop_count,
        },
    })
}

fn build_attack_surface(
    finding: &SecurityFinding,
    modules_by_path: &FxHashMap<&Path, &ModuleInfo>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Option<SecurityAttackSurfaceEntry> {
    let flow = finding.taint_flow.as_ref()?;
    let reach = finding.reachability.as_ref()?;
    let path = reach.untrusted_source_trace.clone();
    if path.is_empty() {
        return None;
    }
    let controls = defensive_controls_for_path(&path, modules_by_path, line_offsets_by_file);
    let verification_prompt = if controls.is_empty() {
        ZERO_CONTROL_PROMPT
    } else {
        CONTROL_PRESENT_PROMPT
    }
    .to_string();

    Some(SecurityAttackSurfaceEntry {
        source: flow.source.clone(),
        sink: finding.candidate.sink.clone(),
        path,
        defensive_boundary: SecurityDefensiveBoundary {
            controls,
            verification_prompt,
        },
    })
}

fn defensive_controls_for_path(
    path: &[TraceHop],
    modules_by_path: &FxHashMap<&Path, &ModuleInfo>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> Vec<SecurityDefensiveControl> {
    let mut controls = Vec::new();
    let mut seen_files = FxHashSet::default();
    for hop in path {
        if !seen_files.insert(hop.path.as_path()) {
            continue;
        }
        let Some(module) = modules_by_path.get(hop.path.as_path()).copied() else {
            continue;
        };
        for control in &module.security_control_sites {
            let (line, col) =
                byte_offset_to_line_col(line_offsets_by_file, module.file_id, control.span_start);
            controls.push(SecurityDefensiveControl {
                kind: control.kind,
                path: hop.path.clone(),
                line,
                col,
                callee: control.callee_path.clone(),
            });
        }
    }
    controls.sort_by(|a, b| {
        a.path
            .cmp(&b.path)
            .then_with(|| a.line.cmp(&b.line))
            .then_with(|| a.col.cmp(&b.col))
            .then_with(|| a.callee.cmp(&b.callee))
            .then_with(|| a.kind.cmp(&b.kind))
    });
    controls.dedup_by(|a, b| {
        a.path == b.path
            && a.line == b.line
            && a.col == b.col
            && a.kind == b.kind
            && a.callee == b.callee
    });
    controls
}

#[derive(Debug, Clone, Copy)]
struct SourceParent {
    previous: FileId,
    import_span_start: Option<u32>,
}

struct UntrustedSourceIndex {
    source_for: Vec<Option<FileId>>,
    parent: Vec<Option<SourceParent>>,
}

struct UntrustedSourceTrace {
    hop_count: u32,
    trace: Vec<TraceHop>,
}

impl UntrustedSourceIndex {
    fn build(
        graph: &ModuleGraph,
        modules: &[ModuleInfo],
        declared_deps: &FxHashSet<String>,
    ) -> Self {
        let modules_by_id: FxHashMap<FileId, &ModuleInfo> = modules
            .iter()
            .map(|module| (module.file_id, module))
            .collect();
        let mut source_for = vec![None; graph.modules.len()];
        let mut parent = vec![None; graph.modules.len()];
        let mut queue: VecDeque<FileId> = VecDeque::new();

        for node in &graph.modules {
            let Some(module) = modules_by_id.get(&node.file_id) else {
                continue;
            };
            if !module_contains_untrusted_source(module, declared_deps) {
                continue;
            }
            let idx = node.file_id.0 as usize;
            if idx >= source_for.len() || source_for[idx].is_some() {
                continue;
            }
            source_for[idx] = Some(node.file_id);
            queue.push_back(node.file_id);
        }

        while let Some(current) = queue.pop_front() {
            let Some(source_id) = source_for.get(current.0 as usize).copied().flatten() else {
                continue;
            };
            for (target, all_type_only, span) in graph.outgoing_edge_summaries(current) {
                if all_type_only {
                    continue;
                }
                let idx = target.0 as usize;
                if idx >= source_for.len() || source_for[idx].is_some() {
                    continue;
                }
                source_for[idx] = Some(source_id);
                parent[idx] = Some(SourceParent {
                    previous: current,
                    import_span_start: span,
                });
                queue.push_back(target);
            }
        }

        Self { source_for, parent }
    }

    fn trace_for(
        &self,
        graph: &ModuleGraph,
        sink_id: FileId,
        finding: &SecurityFinding,
        line_offsets_by_file: &LineOffsetsMap<'_>,
    ) -> Option<UntrustedSourceTrace> {
        if !is_source_reachability_candidate(finding) {
            return None;
        }
        let source_id = self.source_for.get(sink_id.0 as usize).copied().flatten()?;
        let mut ids = vec![sink_id];
        let mut current = sink_id;
        while current != source_id {
            let parent = self.parent.get(current.0 as usize).copied().flatten()?;
            current = parent.previous;
            ids.push(current);
        }
        ids.reverse();
        let hop_count = u32::try_from(ids.len().saturating_sub(1)).unwrap_or(u32::MAX);

        if source_id == sink_id {
            return Some(UntrustedSourceTrace {
                hop_count,
                trace: vec![
                    TraceHop {
                        path: finding.path.clone(),
                        line: 1,
                        col: 0,
                        role: TraceHopRole::UntrustedSource,
                    },
                    TraceHop {
                        path: finding.path.clone(),
                        line: finding.line,
                        col: finding.col,
                        role: TraceHopRole::Sink,
                    },
                ],
            });
        }

        let mut trace = Vec::with_capacity(ids.len().saturating_add(1));
        for (idx, &file_id) in ids.iter().enumerate() {
            let path = graph.modules.get(file_id.0 as usize)?.path.clone();
            if idx == ids.len() - 1 {
                trace.push(TraceHop {
                    path,
                    line: finding.line,
                    col: finding.col,
                    role: TraceHopRole::Sink,
                });
                continue;
            }

            let Some(&next_id) = ids.get(idx + 1) else {
                continue;
            };
            let next_parent = self.parent.get(next_id.0 as usize).copied().flatten();
            let (line, col) = next_parent
                .and_then(|p| p.import_span_start)
                .map_or((1, 0), |span| {
                    byte_offset_to_line_col(line_offsets_by_file, file_id, span)
                });
            trace.push(TraceHop {
                path,
                line,
                col,
                role: if idx == 0 {
                    TraceHopRole::UntrustedSource
                } else {
                    TraceHopRole::Intermediate
                },
            });
        }

        Some(UntrustedSourceTrace { hop_count, trace })
    }
}

fn is_source_reachability_candidate(finding: &SecurityFinding) -> bool {
    matches!(finding.kind, SecurityFindingKind::TaintedSink)
        && finding.category.as_deref() != Some(super::hardcoded_secret::CATEGORY_ID)
}

fn module_contains_untrusted_source(
    module: &ModuleInfo,
    declared_deps: &FxHashSet<String>,
) -> bool {
    let cat = catalogue();
    module.tainted_bindings.iter().any(|binding| {
        cat.matching_source_for_deps(&binding.source_path, declared_deps)
            .is_some()
    }) || module.security_sinks.iter().any(|sink| {
        sink.arg_source_paths
            .iter()
            .any(|path| cat.matching_source_for_deps(path, declared_deps).is_some())
    }) || module.member_accesses.iter().any(|access| {
        let full_path = format!("{}.{}", access.object, access.member);
        cat.matching_source_for_deps(&full_path, declared_deps)
            .is_some()
            || cat
                .matching_source_for_deps(&access.object, declared_deps)
                .is_some()
    })
}

/// Count the distinct modules that transitively depend on `target` (fan-in) via
/// the graph's reverse-dependency index. Bounded BFS with a visited set; the
/// target itself is excluded from the count.
fn transitive_dependent_count(graph: &ModuleGraph, target: FileId) -> u32 {
    let mut visited: FxHashSet<FileId> = FxHashSet::default();
    let mut queue: VecDeque<FileId> = VecDeque::new();
    queue.push_back(target);
    visited.insert(target);

    while let Some(current) = queue.pop_front() {
        let Some(dependents) = graph.reverse_deps.get(current.0 as usize) else {
            continue;
        };
        for &dep in dependents {
            if visited.insert(dep) {
                queue.push_back(dep);
            }
        }
    }

    // Exclude the target itself; saturate into u32 for the wire type.
    u32::try_from(visited.len().saturating_sub(1)).unwrap_or(u32::MAX)
}

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

    use fallow_types::discover::{DiscoveredFile, EntryPoint, EntryPointSource};
    use fallow_types::extract::{
        MemberAccess, SecurityControlKind, SecurityControlSite, TaintedBinding,
    };
    use fallow_types::output::{FixActionType, IssueAction};
    use fallow_types::output_dead_code::{UnusedExportFinding, UnusedFileFinding};
    use fallow_types::results::{
        SecurityDeadCodeKind, SecurityFindingKind, TraceHop, TraceHopRole, UnusedExport, UnusedFile,
    };

    use crate::graph::ModuleGraph;
    use crate::resolve::{ResolveResult, ResolvedImport, ResolvedModule};

    const ROOT: &str = "/proj";

    /// Build a graph from `file_names` and `(from, to)` import edges. `entry`
    /// indices become runtime entry points (so their cones are runtime-reachable).
    fn build_graph(file_names: &[&str], edges: &[(usize, usize)], entry: &[usize]) -> ModuleGraph {
        let edges: Vec<(usize, usize, bool)> =
            edges.iter().map(|&(from, to)| (from, to, false)).collect();
        build_graph_with_type_edges(file_names, &edges, entry)
    }

    fn build_graph_with_type_edges(
        file_names: &[&str],
        edges: &[(usize, usize, bool)],
        entry: &[usize],
    ) -> ModuleGraph {
        let files: Vec<DiscoveredFile> = file_names
            .iter()
            .enumerate()
            .map(|(i, name)| DiscoveredFile {
                id: FileId(i as u32),
                path: PathBuf::from(ROOT).join(name),
                size_bytes: 100,
            })
            .collect();

        let resolved: Vec<ResolvedModule> = files
            .iter()
            .map(|f| {
                let imports: Vec<ResolvedImport> = edges
                    .iter()
                    .filter(|(from, _, _)| *from == f.id.0 as usize)
                    .map(|&(_, to, is_type_only)| ResolvedImport {
                        target: ResolveResult::InternalModule(FileId(to as u32)),
                        info: fallow_types::extract::ImportInfo {
                            source: format!("./{}", file_names[to]),
                            imported_name: fallow_types::extract::ImportedName::Default,
                            local_name: "x".to_string(),
                            is_type_only,
                            from_style: false,
                            span: oxc_span::Span::new(0, 10),
                            source_span: oxc_span::Span::new(0, 10),
                        },
                    })
                    .collect();
                ResolvedModule {
                    file_id: f.id,
                    path: f.path.clone(),
                    exports: vec![],
                    re_exports: vec![],
                    resolved_imports: imports,
                    resolved_dynamic_imports: vec![],
                    resolved_dynamic_patterns: vec![],
                    member_accesses: vec![],
                    whole_object_uses: vec![],
                    has_cjs_exports: false,
                    has_angular_component_template_url: false,
                    unused_import_bindings: FxHashSet::default(),
                    type_referenced_import_bindings: vec![],
                    value_referenced_import_bindings: vec![],
                    namespace_object_aliases: vec![],
                }
            })
            .collect();

        let entry_points: Vec<EntryPoint> = entry
            .iter()
            .map(|&i| EntryPoint {
                path: files[i].path.clone(),
                source: EntryPointSource::ManualEntry,
            })
            .collect();

        ModuleGraph::build(&resolved, &entry_points, &files)
    }

    /// Test wrapper: accepts the boundary-anchor path set (the pre-#900 shape)
    /// and lifts each path into the `(from_zone, to_zone)` map the production
    /// signature now takes, with placeholder zone names. Existing call sites that
    /// only assert on `crosses_boundary` stay unchanged.
    fn rank(
        graph: &ModuleGraph,
        boundary_anchor_paths: &FxHashSet<PathBuf>,
        findings: &mut [SecurityFinding],
    ) {
        let modules = Vec::new();
        let line_offsets = FxHashMap::default();
        let declared_deps = FxHashSet::default();
        let boundary_crossings: FxHashMap<PathBuf, (String, String)> = boundary_anchor_paths
            .iter()
            .map(|path| (path.clone(), ("from".to_string(), "to".to_string())))
            .collect();
        rank_security_findings(
            graph,
            &modules,
            &line_offsets,
            &declared_deps,
            &boundary_crossings,
            findings,
        );
    }

    fn rank_with_modules(
        graph: &ModuleGraph,
        modules: &[ModuleInfo],
        findings: &mut [SecurityFinding],
    ) {
        let line_offsets = FxHashMap::default();
        let declared_deps = FxHashSet::default();
        let boundary_crossings = FxHashMap::default();
        rank_security_findings(
            graph,
            modules,
            &line_offsets,
            &declared_deps,
            &boundary_crossings,
            findings,
        );
    }

    fn module(file_id: u32) -> ModuleInfo {
        ModuleInfo {
            file_id: FileId(file_id),
            exports: vec![],
            imports: vec![],
            re_exports: vec![],
            dynamic_imports: vec![],
            dynamic_import_patterns: vec![],
            require_calls: vec![],
            package_path_references: vec![],
            member_accesses: vec![],
            whole_object_uses: vec![],
            has_cjs_exports: false,
            has_angular_component_template_url: false,
            content_hash: 0,
            suppressions: vec![],
            unknown_suppression_kinds: vec![],
            unused_import_bindings: vec![],
            type_referenced_import_bindings: vec![],
            value_referenced_import_bindings: vec![],
            line_offsets: vec![],
            complexity: vec![],
            flag_uses: vec![],
            class_heritage: vec![],
            injection_tokens: vec![],
            local_type_declarations: vec![],
            public_signature_type_references: vec![],
            namespace_object_aliases: vec![],
            iconify_prefixes: vec![],
            iconify_icon_names: vec![],
            auto_import_candidates: vec![],
            directives: vec![],
            security_sinks: vec![],
            security_sinks_skipped: 0,
            tainted_bindings: vec![],
            sanitized_sink_args: vec![],
            security_control_sites: vec![],
        }
    }

    fn member_source_module(file_id: u32) -> ModuleInfo {
        let mut module = module(file_id);
        module.member_accesses.push(MemberAccess {
            object: "req".to_string(),
            member: "body".to_string(),
        });
        module
    }

    fn tainted_binding_source_module(file_id: u32) -> ModuleInfo {
        let mut module = module(file_id);
        module.tainted_bindings.push(TaintedBinding {
            local: "body".to_string(),
            source_path: "req.body".to_string(),
        });
        module
    }

    fn validation_control_module(file_id: u32) -> ModuleInfo {
        let mut module = module(file_id);
        module.security_control_sites.push(SecurityControlSite {
            kind: SecurityControlKind::Validation,
            callee_path: "schema.parse".to_string(),
            span_start: 0,
            span_end: 12,
        });
        module
    }

    fn finding(name: &str) -> SecurityFinding {
        use fallow_types::results::{SecurityCandidate, SecurityCandidateSink};
        let path = PathBuf::from(ROOT).join(name);
        SecurityFinding {
            finding_id: String::new(),
            kind: SecurityFindingKind::TaintedSink,
            category: Some("dangerous-html".to_string()),
            cwe: Some(79),
            path: path.clone(),
            line: 1,
            col: 0,
            evidence: "candidate".to_string(),
            trace: vec![TraceHop {
                path: path.clone(),
                line: 1,
                col: 0,
                role: TraceHopRole::Sink,
            }],
            actions: Vec::<IssueAction>::new(),
            dead_code: None,
            reachability: None,
            source_backed: false,
            candidate: SecurityCandidate {
                source_kind: None,
                sink: SecurityCandidateSink {
                    path,
                    line: 1,
                    col: 0,
                    category: Some("dangerous-html".to_string()),
                    cwe: Some(79),
                    callee: None,
                },
                boundary: SecurityCandidateBoundary::default(),
                network: None,
            },
            taint_flow: None,
            runtime: None,
            attack_surface: None,
        }
    }

    #[test]
    fn reachable_from_entry_sorts_first() {
        // entry(0) -> reachable(1); orphan(2) is not in any entry cone.
        let graph = build_graph(&["entry.ts", "reachable.ts", "orphan.ts"], &[(0, 1)], &[0]);
        let empty = FxHashSet::default();
        // Seed in the "wrong" order to prove the sort moves the reachable one up.
        let mut findings = vec![finding("orphan.ts"), finding("reachable.ts")];
        rank(&graph, &empty, &mut findings);

        assert!(findings[0].path.ends_with("reachable.ts"));
        assert!(
            findings[0]
                .reachability
                .as_ref()
                .expect("ranked")
                .reachable_from_entry
        );
        assert!(findings[1].path.ends_with("orphan.ts"));
        assert!(
            !findings[1]
                .reachability
                .as_ref()
                .expect("ranked")
                .reachable_from_entry
        );
    }

    #[test]
    fn attack_surface_records_detected_controls_on_source_to_sink_path() {
        let graph = build_graph(&["source.ts", "sink.ts"], &[(0, 1)], &[0]);
        let modules = vec![
            tainted_binding_source_module(0),
            validation_control_module(1),
        ];
        let mut findings = vec![finding("sink.ts")];

        rank_with_modules(&graph, &modules, &mut findings);

        let surface = findings[0].attack_surface.as_ref().expect("surface entry");
        assert_eq!(surface.source.path, PathBuf::from(ROOT).join("source.ts"));
        assert_eq!(surface.sink.path, PathBuf::from(ROOT).join("sink.ts"));
        assert_eq!(surface.defensive_boundary.controls.len(), 1);
        assert_eq!(
            surface.defensive_boundary.controls[0].kind,
            SecurityControlKind::Validation
        );
        assert!(
            surface
                .defensive_boundary
                .verification_prompt
                .contains("Are they sufficient")
        );
    }

    #[test]
    fn attack_surface_zero_control_prompt_is_a_question() {
        let graph = build_graph(&["source.ts", "sink.ts"], &[(0, 1)], &[0]);
        let modules = vec![tainted_binding_source_module(0), module(1)];
        let mut findings = vec![finding("sink.ts")];

        rank_with_modules(&graph, &modules, &mut findings);

        let prompt = &findings[0]
            .attack_surface
            .as_ref()
            .expect("surface entry")
            .defensive_boundary
            .verification_prompt;
        assert!(prompt.ends_with('?'));
        assert!(prompt.contains("No known control library"));
    }

    #[test]
    fn higher_blast_radius_wins_among_reachable() {
        // entry(0) imports both hub(1) and leaf(2); extra(3) also imports hub(1).
        // hub has fan-in {entry, extra} = 2; leaf has fan-in {entry} = 1.
        let graph = build_graph(
            &["entry.ts", "hub.ts", "leaf.ts", "extra.ts"],
            &[(0, 1), (0, 2), (3, 1)],
            &[0, 3],
        );
        let empty = FxHashSet::default();
        let mut findings = vec![finding("leaf.ts"), finding("hub.ts")];
        rank(&graph, &empty, &mut findings);

        assert!(findings[0].path.ends_with("hub.ts"));
        let hub = findings[0].reachability.as_ref().expect("ranked");
        let leaf = findings[1].reachability.as_ref().expect("ranked");
        assert!(hub.reachable_from_entry && leaf.reachable_from_entry);
        assert!(
            hub.blast_radius > leaf.blast_radius,
            "hub {} should exceed leaf {}",
            hub.blast_radius,
            leaf.blast_radius
        );
    }

    #[test]
    fn boundary_crossing_breaks_tie() {
        // Two equally-reachable, equal-fan-in siblings imported by entry(0).
        let graph = build_graph(&["entry.ts", "a.ts", "b.ts"], &[(0, 1), (0, 2)], &[0]);
        let mut boundary = FxHashSet::default();
        boundary.insert(PathBuf::from(ROOT).join("b.ts"));
        // Seed a-first; b crosses a boundary so it should sort ahead.
        let mut findings = vec![finding("a.ts"), finding("b.ts")];
        rank(&graph, &boundary, &mut findings);

        assert!(findings[0].path.ends_with("b.ts"));
        assert!(
            findings[0]
                .reachability
                .as_ref()
                .expect("ranked")
                .crosses_boundary
        );
        assert!(
            !findings[1]
                .reachability
                .as_ref()
                .expect("ranked")
                .crosses_boundary
        );
    }

    #[test]
    fn full_tie_is_deterministic_by_path() {
        let graph = build_graph(&["entry.ts", "a.ts", "b.ts"], &[(0, 1), (0, 2)], &[0]);
        let empty = FxHashSet::default();
        let mut findings = vec![finding("b.ts"), finding("a.ts")];
        rank(&graph, &empty, &mut findings);
        assert!(findings[0].path.ends_with("a.ts"));
        assert!(findings[1].path.ends_with("b.ts"));
    }

    #[test]
    fn dead_code_cross_link_marks_unused_file_sink() {
        let graph = build_graph(&["dead.ts"], &[], &[]);
        let mut findings = vec![finding("dead.ts")];
        let unused_files = vec![UnusedFileFinding::with_actions(UnusedFile {
            path: PathBuf::from(ROOT).join("dead.ts"),
        })];
        let line_offsets = FxHashMap::default();

        annotate_dead_code_cross_links(
            &graph,
            &[],
            &line_offsets,
            &unused_files,
            &[],
            &mut findings,
        );

        let context = findings[0].dead_code.as_ref().expect("dead-code context");
        assert_eq!(context.kind, SecurityDeadCodeKind::UnusedFile);
        assert_eq!(context.export_name, None);
        match &findings[0].actions[0] {
            IssueAction::Fix(action) => assert_eq!(action.kind, FixActionType::DeleteFile),
            other => panic!("expected delete-file action, got {other:?}"),
        }
    }

    #[test]
    fn dead_code_cross_link_marks_same_line_unused_export_sink() {
        let graph = build_graph(&["sink.ts"], &[], &[]);
        let mut findings = vec![finding("sink.ts")];
        let unused_exports = vec![UnusedExportFinding::with_actions(UnusedExport {
            path: PathBuf::from(ROOT).join("sink.ts"),
            export_name: "dangerous".to_string(),
            is_type_only: false,
            line: 1,
            col: 0,
            span_start: 0,
            is_re_export: false,
        })];
        let line_offsets = FxHashMap::default();

        annotate_dead_code_cross_links(
            &graph,
            &[],
            &line_offsets,
            &[],
            &unused_exports,
            &mut findings,
        );

        let context = findings[0].dead_code.as_ref().expect("dead-code context");
        assert_eq!(context.kind, SecurityDeadCodeKind::UnusedExport);
        assert_eq!(context.export_name.as_deref(), Some("dangerous"));
        assert_eq!(context.line, Some(1));
        match &findings[0].actions[0] {
            IssueAction::Fix(action) => assert_eq!(action.kind, FixActionType::RemoveExport),
            other => panic!("expected remove-export action, got {other:?}"),
        }
    }

    #[test]
    fn dead_code_cross_link_skips_client_server_leak_findings() {
        let graph = build_graph(&["dead.ts"], &[], &[]);
        let mut findings = vec![finding("dead.ts")];
        findings[0].kind = SecurityFindingKind::ClientServerLeak;
        let unused_files = vec![UnusedFileFinding::with_actions(UnusedFile {
            path: PathBuf::from(ROOT).join("dead.ts"),
        })];
        let line_offsets = FxHashMap::default();

        annotate_dead_code_cross_links(
            &graph,
            &[],
            &line_offsets,
            &unused_files,
            &[],
            &mut findings,
        );

        assert!(findings[0].dead_code.is_none());
        assert!(findings[0].actions.is_empty());
    }

    #[test]
    fn active_code_sorts_ahead_of_dead_code_when_rank_signals_tie() {
        let graph = build_graph(
            &["entry.ts", "active.ts", "dead.ts"],
            &[(0, 1), (0, 2)],
            &[0],
        );
        let empty = FxHashSet::default();
        let mut dead = finding("dead.ts");
        dead.dead_code = Some(SecurityDeadCodeContext {
            kind: SecurityDeadCodeKind::UnusedFile,
            export_name: None,
            line: None,
            guidance: UNUSED_FILE_GUIDANCE.to_string(),
        });
        let mut findings = vec![dead, finding("active.ts")];

        rank(&graph, &empty, &mut findings);

        assert!(findings[0].path.ends_with("active.ts"));
        assert!(findings[0].dead_code.is_none());
        assert!(findings[1].path.ends_with("dead.ts"));
        assert!(findings[1].dead_code.is_some());
    }

    #[test]
    fn empty_findings_is_noop() {
        let graph = build_graph(&["entry.ts"], &[], &[0]);
        let empty = FxHashSet::default();
        let mut findings: Vec<SecurityFinding> = vec![];
        rank(&graph, &empty, &mut findings);
        assert!(findings.is_empty());
    }

    #[test]
    fn untrusted_source_reachability_uses_value_import_path() {
        let graph = build_graph(&["handler.ts", "helper.ts"], &[(0, 1)], &[]);
        let modules = vec![member_source_module(0), module(1)];
        let mut findings = vec![finding("helper.ts")];

        rank_with_modules(&graph, &modules, &mut findings);

        let reach = findings[0].reachability.as_ref().expect("ranked");
        assert!(reach.reachable_from_untrusted_source);
        assert_eq!(reach.untrusted_source_hop_count, Some(1));
        assert_eq!(
            reach
                .untrusted_source_trace
                .iter()
                .map(|hop| hop.role)
                .collect::<Vec<_>>(),
            vec![TraceHopRole::UntrustedSource, TraceHopRole::Sink]
        );
    }

    #[test]
    fn untrusted_source_reachability_skips_type_only_import_path() {
        let graph = build_graph_with_type_edges(&["handler.ts", "helper.ts"], &[(0, 1, true)], &[]);
        let modules = vec![member_source_module(0), module(1)];
        let mut findings = vec![finding("helper.ts")];

        rank_with_modules(&graph, &modules, &mut findings);

        let reach = findings[0].reachability.as_ref().expect("ranked");
        assert!(!reach.reachable_from_untrusted_source);
        assert_eq!(reach.untrusted_source_hop_count, None);
        assert!(reach.untrusted_source_trace.is_empty());
    }

    #[test]
    fn same_file_untrusted_source_and_sink_has_zero_hop_trace() {
        let graph = build_graph(&["handler.ts"], &[], &[]);
        let modules = vec![tainted_binding_source_module(0)];
        let mut findings = vec![finding("handler.ts")];

        rank_with_modules(&graph, &modules, &mut findings);

        let reach = findings[0].reachability.as_ref().expect("ranked");
        assert!(reach.reachable_from_untrusted_source);
        assert_eq!(reach.untrusted_source_hop_count, Some(0));
        assert_eq!(
            reach
                .untrusted_source_trace
                .iter()
                .map(|hop| hop.role)
                .collect::<Vec<_>>(),
            vec![TraceHopRole::UntrustedSource, TraceHopRole::Sink]
        );
    }

    #[test]
    fn source_backed_sorts_ahead_of_module_level_source_when_entry_ties() {
        let graph = build_graph(
            &["entry.ts", "source.ts", "module.ts", "direct.ts"],
            &[(0, 1), (0, 2), (0, 3), (1, 2)],
            &[0],
        );
        let modules = vec![
            module(0),
            member_source_module(1),
            module(2),
            tainted_binding_source_module(3),
        ];
        let mut direct = finding("direct.ts");
        direct.source_backed = true;
        let mut findings = vec![finding("module.ts"), direct];

        rank_with_modules(&graph, &modules, &mut findings);

        assert!(findings[0].path.ends_with("direct.ts"));
        assert!(findings[0].source_backed);
        assert!(findings[1].path.ends_with("module.ts"));
        assert!(
            findings[1]
                .reachability
                .as_ref()
                .expect("ranked")
                .reachable_from_untrusted_source
        );
    }

    #[test]
    fn runtime_entry_reachability_sorts_before_module_source_reachability() {
        let graph = build_graph(
            &["entry.ts", "reachable.ts", "source.ts", "module.ts"],
            &[(0, 1), (2, 3)],
            &[0],
        );
        let modules = vec![module(0), module(1), member_source_module(2), module(3)];
        let mut findings = vec![finding("module.ts"), finding("reachable.ts")];

        rank_with_modules(&graph, &modules, &mut findings);

        assert!(findings[0].path.ends_with("reachable.ts"));
        assert!(
            findings[0]
                .reachability
                .as_ref()
                .expect("ranked")
                .reachable_from_entry
        );
        assert!(findings[1].path.ends_with("module.ts"));
        assert!(
            findings[1]
                .reachability
                .as_ref()
                .expect("ranked")
                .reachable_from_untrusted_source
        );
    }

    #[test]
    fn hardcoded_secret_and_client_server_leak_are_not_source_annotated() {
        let graph = build_graph(&["source.ts", "candidate.ts"], &[(0, 1)], &[]);
        let modules = vec![member_source_module(0), module(1)];
        let mut hardcoded = finding("candidate.ts");
        hardcoded.category = Some(super::super::hardcoded_secret::CATEGORY_ID.to_string());
        let mut leak = finding("candidate.ts");
        leak.kind = SecurityFindingKind::ClientServerLeak;
        leak.category = None;
        let mut findings = vec![hardcoded, leak];

        rank_with_modules(&graph, &modules, &mut findings);

        for finding in findings {
            let reach = finding.reachability.as_ref().expect("ranked");
            assert!(!reach.reachable_from_untrusted_source);
            assert!(reach.untrusted_source_trace.is_empty());
        }
    }
}