fallow-core 3.46.0

Internal detector backend for fallow-engine and fallow-api
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
//! Local security candidate detection (opt-in, surfaced only by `fallow security`).
//!
//! These are CANDIDATES for downstream agent verification, NOT verified
//! vulnerabilities. The graph-structural `client-server-leak` rule has two
//! sink predicates over the SAME `"use client"` transitive import cone (static
//! and dynamic):
//!
//! 1. The cone reaches a module that reads a non-public env secret
//!    (`category: "client-server-leak"`, the original finding).
//! 2. The cone reaches a SERVER-ONLY module (`category: Some("server-only-import")`):
//!    a module importing the `server-only` poison package or a server-only
//!    Next.js / Node API (see the shared `imports_server_only_code` predicate in
//!    `analyze::server_only`). A `"use server"` directive is deliberately NOT a
//!    server-only marker here: a Server Action module imported from a
//!    `"use client"` file is the framework's sanctioned mutation pattern (the
//!    bundler swaps the import for an action reference), so only its server-only
//!    IMPORTS count, and those still surface through re-export chains.
//!
//! Server Action boundary: a `"use server"` module whose value exports are all
//! async functions (`ModuleInfo::is_server_action_module`) stops the cone. The
//! bundler replaces the import with action references, so neither the module
//! nor its imports enter the client bundle (issue #2941). A `"use server"`
//! module with a non-action value export stays in the cone, because that
//! export does ship to the client. The remediation text for such a sink asks
//! whether the non-action export leaks the import into the client bundle.
//!
//! Type-only edges: an import that names only type exports of the target
//! (`import { Props } from "./x"` where `x` has `export interface Props`) is
//! erased at build time and is not a cone edge, the same as `import type`.
//!
//! fallow emits the structural import-hop trace; it does not prove the path is
//! exploitable.
//!
//! Blind spots (surfaced in-band via [`LeakScanStats`], not silently
//! dropped): the BFS follows only resolved static import edges, so glob-shaped
//! dynamic `import()` patterns and unresolved specifiers can hide a real leak.
//!
//! ssr:false escape hatch: a server module pulled in ONLY through
//! `next/dynamic(() => import('./X'), { ssr: false })` is the sanctioned
//! client-only escape hatch, NOT a leak. fallow's arrow-wrapped dynamic-import
//! detection resolves `next/dynamic(() => import('./X'))` to a STATIC graph edge
//! (it credits the target's default export), so that edge IS in the cone. The
//! extract layer records the `import()` span of each ssr:false call on
//! `ModuleInfo::client_only_dynamic_import_spans`, and the BFS excludes an edge
//! reached ONLY through such a span (see
//! `ModuleGraph::outgoing_edge_summaries_with_exclusions`). An edge also reached
//! via a real static import stays in the cone.

use rustc_hash::{FxHashMap, FxHashSet};
use std::collections::VecDeque;

use fallow_types::extract::{EnvRead, ModuleInfo};
use fallow_types::output::{IssueAction, SuppressFileAction, SuppressFileKind};
use fallow_types::results::{
    SecurityCandidate, SecurityCandidateBoundary, SecurityCandidateSink, SecurityFinding,
    SecurityFindingKind, SecuritySeverity, TraceHop, TraceHopRole, TraceSecretRead,
};
use fallow_types::security_stable_id::SecurityStableIdInput;
use fallow_types::suppress::IssueKind;

use super::{LineOffsetsMap, byte_offset_to_line_col};
use crate::discover::FileId;
use crate::graph::{ModuleGraph, ModuleNode};
use crate::suppress::SuppressionContext;

mod framework_roots;
mod hardcoded_secret;
mod rank;
mod route_module_split;
mod tainted_sink;

use framework_roots::{ClientRootKind, FrameworkClientRoots};
pub use hardcoded_secret::find_hardcoded_secret_candidates;
pub use rank::{
    SecurityRankingInput, annotate_dead_code_cross_links, boundary_crossings_by_file,
    rank_security_findings, reportable_dead_code_for_cross_links,
};
pub use tainted_sink::{CategoryFilter, TaintedSinkContext, find_tainted_sinks};

/// Segment-aware callee pattern matcher, re-exported for the boundary
/// forbidden-call detector (`analyze::boundary_calls`).
pub use fallow_security::{CalleePattern, Matcher};

#[must_use]
pub fn catalogue_matchers() -> &'static [Matcher] {
    fallow_security::catalogue().matchers()
}

// The provenance predicate lives in `fallow-security` so that the mutation
// plan applies the same import check as the detectors.
#[cfg(test)]
use fallow_security::import_source_matches;

/// The inline suppression kind token for the client-server-leak rule.
const SUPPRESS_KIND: &str = "security-client-server-leak";

/// Stable `category` string of the secret-leak sink. It equals the rule name,
/// so every security finding carries a category.
const SECRET_LEAK_CATEGORY: &str = "client-server-leak";

/// Stable `category` string distinguishing the server-only-import sink from the
/// secret-leak sink (`category: "client-server-leak"`). Same rule, same suppress kind, same
/// `SecurityFinding` shape; only the category differs so JSON / human / SARIF
/// consumers can tell "reaches server-only code" apart from "reads a secret".
const SERVER_ONLY_CATEGORY: &str = "server-only-import";

/// Build the machine-actionable suppress hint emitted on every finding. Single
/// file-level suppress action (`auto_fixable: false`): there is no auto-fix
/// because verifying the candidate is the agent's job, not fallow's.
fn build_actions() -> Vec<IssueAction> {
    vec![IssueAction::SuppressFile(SuppressFileAction {
        kind: SuppressFileKind::SuppressFile,
        auto_fixable: false,
        description: "Suppress with a file-level comment at the top of the client file".to_string(),
        comment: format!("// fallow-ignore-file {SUPPRESS_KIND}"),
    })]
}

fn build_client_server_leak_finding(
    evidence: String,
    trace: Vec<TraceHop>,
    candidate: SecurityCandidate,
) -> SecurityFinding {
    let category = candidate.sink.category.clone();

    SecurityFinding {
        finding_id: String::new(),
        stable_finding_id: None,
        stable_id_input: None,
        kind: SecurityFindingKind::ClientServerLeak,
        category,
        cwe: None,
        path: candidate.sink.path.clone(),
        line: candidate.sink.line,
        col: candidate.sink.col,
        evidence,
        // The client-server-leak rule is graph-structural, not source-to-sink;
        // source-backing is a tainted-sink concept (issue #859).
        source_backed: false,
        // client-server-leak is module-level by construction (no arg-level read).
        source_read: None,
        severity: SecuritySeverity::Low,
        trace,
        actions: build_actions(),
        dead_code: None,
        reachability: None,
        candidate,
        taint_flow: None,
        runtime: None,
        attack_surface: None,
    }
}

/// The React Server Components client-boundary directive.
const USE_CLIENT: &str = "use client";

/// Singular/plural noun for the count of secret vars named in the evidence.
const fn secret_word(count: usize) -> &'static str {
    if count == 1 { "secret" } else { "secrets" }
}

/// For each module that reads a non-public env secret: its reads in source
/// order.
type SecretSources = FxHashMap<FileId, Vec<EnvRead>>;

#[cfg(test)]
use fallow_types::extract::is_public_env_var;

/// Blind-spot accounting surfaced in-band so the user is never told "clean" when
/// the analysis could not see part of the import graph.
#[derive(Debug, Default, Clone, Copy)]
pub struct LeakScanStats {
    /// Number of `"use client"` files whose transitive import cone contains a
    /// dynamic `import()` pattern the reachability BFS cannot follow, so a leak
    /// could be hiding behind it.
    pub client_files_with_unresolved_edges: usize,
    /// Number of starting points of the leak scan: files with a top-level
    /// `"use client"` directive plus the client roots of framework plugins.
    /// Zero means the rule checked nothing.
    pub client_roots: usize,
}

/// Run the security MVP rules over the graph. Returns the findings plus the
/// blind-spot stats. Callers gate this on the `security_client_server_leak`
/// rule severity; it never runs under bare `fallow` or the `audit` gate.
#[must_use]
pub(super) fn find_security_findings(
    ctx: &super::SecurityDetectionContext<'_, '_>,
) -> (Vec<SecurityFinding>, LeakScanStats) {
    let framework_roots =
        FrameworkClientRoots::collect(ctx.graph, &ctx.config.root, ctx.plugin_result);
    let modules_by_id: FxHashMap<FileId, &ModuleInfo> =
        ctx.modules.iter().map(|m| (m.file_id, m)).collect();

    let mut secret_sources = compute_secret_source_set(&modules_by_id);
    let mut server_only_sources = compute_server_only_source_set(&modules_by_id);
    apply_route_splits(
        &modules_by_id,
        &framework_roots,
        &mut secret_sources,
        &mut server_only_sources,
    );
    server_only_sources.extend(framework_roots.server_sinks());

    find_client_server_leaks(
        &LeakSources {
            graph: ctx.graph,
            modules_by_id: &modules_by_id,
            secret_sources: &secret_sources,
            server_only_sources: &server_only_sources,
            framework_roots: &framework_roots,
        },
        ctx.suppressions,
        ctx.line_offsets_by_file,
    )
}

/// Count only the client code of each React Router route module as a sink:
/// drop the env reads and the server-only imports that only its server-only
/// exports use. The same sets serve the route module as a root and as a
/// module that the cone reaches.
fn apply_route_splits(
    modules_by_id: &FxHashMap<FileId, &ModuleInfo>,
    framework_roots: &FrameworkClientRoots,
    secret_sources: &mut SecretSources,
    server_only_sources: &mut FxHashSet<FileId>,
) {
    for (file_id, split) in framework_roots.route_splits() {
        if let Some(reads) = secret_sources.get_mut(&file_id) {
            reads.retain(|read| !split.is_dead_offset(read.span_start));
            if reads.is_empty() {
                secret_sources.remove(&file_id);
            }
        }
        if server_only_sources.contains(&file_id) {
            let imports_client_server_only_code =
                modules_by_id.get(&file_id).is_some_and(|module| {
                    module.imports.iter().any(|import| {
                        super::server_only::is_server_only_import(import)
                            && !split.server_only_spans.contains(&import.span.start)
                    })
                });
            if !imports_client_server_only_code {
                server_only_sources.remove(&file_id);
            }
        }
    }
}

/// The graph facts that the leak scan reads.
struct LeakSources<'a> {
    graph: &'a ModuleGraph,
    modules_by_id: &'a FxHashMap<FileId, &'a ModuleInfo>,
    secret_sources: &'a SecretSources,
    server_only_sources: &'a FxHashSet<FileId>,
    framework_roots: &'a FrameworkClientRoots,
}

/// Map each module that reads a non-public env secret to its reads, in
/// source order. Extraction records the reads (`ModuleInfo::env_reads`) and
/// skips public vars.
fn compute_secret_source_set(modules_by_id: &FxHashMap<FileId, &ModuleInfo>) -> SecretSources {
    let mut sources = SecretSources::default();
    for (&file_id, module) in modules_by_id {
        if module.env_reads.is_empty() {
            continue;
        }
        let mut reads = module.env_reads.clone();
        reads.sort_by_key(|read| read.span_start);
        sources.insert(file_id, reads);
    }
    sources
}

/// The distinct read names of a module, sorted.
fn secret_names(reads: &[EnvRead]) -> Vec<String> {
    let mut names: Vec<String> = reads.iter().map(|read| read.name.clone()).collect();
    names.sort_unstable();
    names.dedup();
    names
}

/// The `secret-source` hop of a module: it points at the first read and lists
/// every read.
fn secret_source_hop(
    graph: &ModuleGraph,
    file_id: FileId,
    reads: &[EnvRead],
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> TraceHop {
    let secret_reads: Vec<TraceSecretRead> = reads
        .iter()
        .map(|read| {
            let (line, col) =
                byte_offset_to_line_col(line_offsets_by_file, file_id, read.span_start);
            TraceSecretRead {
                name: read.name.clone(),
                line,
                col,
            }
        })
        .collect();
    let (line, col) = secret_reads
        .first()
        .map_or((1, 0), |read| (read.line, read.col));
    TraceHop {
        path: graph.modules[file_id.0 as usize].path.clone(),
        line,
        col,
        role: TraceHopRole::SecretSource,
        secret_reads,
    }
}

/// The offset of the first server-only import of a module that ships to the
/// client. `None` for a module that is a sink for another reason, such as a
/// React Router `.server` module.
fn first_server_only_import_start(scan: &LeakScanInput<'_>, file_id: FileId) -> Option<u32> {
    let module = scan.modules_by_id.get(&file_id)?;
    let excluded = scan.excluded_spans.get(&file_id);
    module
        .imports
        .iter()
        .filter(|import| super::server_only::is_server_only_import(import))
        .map(|import| import.span.start)
        .filter(|start| excluded.is_none_or(|spans| !spans.contains(start)))
        .min()
}

/// The `(line, col)` of the first server-only import of a module, or the
/// module start.
fn server_only_location(scan: &LeakScanInput<'_>, file_id: FileId) -> (u32, u32) {
    first_server_only_import_start(scan, file_id).map_or((1, 0), |start| {
        byte_offset_to_line_col(scan.line_offsets_by_file, file_id, start)
    })
}

/// Set of file ids whose module is a SERVER-ONLY sink: it imports a server-only
/// package or a server-only named API from `next/headers`. Delegates to the
/// shared
/// [`imports_server_only_code`](super::server_only::imports_server_only_code)
/// predicate. A bare `"use server"` directive does NOT qualify: a Server Action
/// module is meant to be imported by client components, so only its server-only
/// imports make it a sink.
fn compute_server_only_source_set(
    modules_by_id: &FxHashMap<FileId, &ModuleInfo>,
) -> FxHashSet<FileId> {
    let mut server_only: FxHashSet<FileId> = FxHashSet::default();
    for (&file_id, module) in modules_by_id {
        if super::server_only::imports_server_only_code(module) {
            server_only.insert(file_id);
        }
    }
    server_only
}

/// For each `"use client"` file, BFS its transitive import cone (static and
/// dynamic). Two
/// distinct sink predicates run over the SAME cone:
///
/// - reaching a module that reads a non-public env secret emits the secret-leak
///   finding (`category: "client-server-leak"`);
/// - reaching a SERVER-ONLY module emits the server-only finding
///   (`category: Some("server-only-import")`).
///
/// Both can fire for one client file (they are different concerns). Type-only
/// edges are skipped (erased at build, so they cannot carry a secret or a
/// server-only import into the client bundle).
/// Result of a single client file's import-cone BFS: the parent map for trace
/// reconstruction, the first secret / server-only module reached, and whether
/// any unresolved dynamic-import edge was seen in the cone.
struct ClientConeResult {
    parent: FxHashMap<FileId, (FileId, Option<u32>)>,
    reached_secret: Option<FileId>,
    reached_server_only: Option<FileId>,
    had_unresolved_edge: bool,
}

/// BFS the import cone (static and dynamic) of a `"use client"` file, draining
/// the FULL cone (no early break) so the dynamic-import blind-spot count
/// reflects every edge, not just the path to the first finding. A plain
/// `import()` edge stays in the cone, because its chunk still ships to the
/// client. Type-only and `next/dynamic ssr:false`-only edges are excluded
/// (neither can leak into the client bundle).
fn walk_client_cone(scan: &LeakScanInput<'_>, client_id: FileId) -> ClientConeResult {
    let mut visited: FxHashSet<FileId> = FxHashSet::default();
    visited.insert(client_id);
    let mut result = ClientConeResult {
        parent: FxHashMap::default(),
        reached_secret: None,
        reached_server_only: None,
        had_unresolved_edge: false,
    };
    let mut queue: VecDeque<FileId> = VecDeque::new();
    queue.push_back(client_id);

    while let Some(current) = queue.pop_front() {
        record_client_cone_module(scan, client_id, current, &mut result);
        let excluded = scan
            .excluded_spans
            .get(&current)
            .unwrap_or(scan.empty_spans);
        enqueue_client_cone_edges(
            scan,
            current,
            excluded,
            &mut visited,
            &mut result.parent,
            &mut queue,
        );
    }

    result
}

fn record_client_cone_module(
    scan: &LeakScanInput<'_>,
    client_id: FileId,
    current: FileId,
    result: &mut ClientConeResult,
) {
    if let Some(current_module) = scan.modules_by_id.get(&current)
        && !current_module.dynamic_import_patterns.is_empty()
    {
        result.had_unresolved_edge = true;
    }

    if current == client_id {
        return;
    }
    if result.reached_secret.is_none() && scan.secret_sources.contains_key(&current) {
        result.reached_secret = Some(current);
    }
    if result.reached_server_only.is_none() && scan.server_only_sources.contains(&current) {
        result.reached_server_only = Some(current);
    }
}

/// Enqueue the cone edges of `current`. `excluded` holds the import span
/// starts whose edges do not ship to the client: the `next/dynamic
/// ssr:false` imports of `current` (the client-only escape hatch) and, for a
/// React Router route module, the imports of its server-only exports.
fn enqueue_client_cone_edges(
    scan: &LeakScanInput<'_>,
    current: FileId,
    excluded: &FxHashSet<u32>,
    visited: &mut FxHashSet<FileId>,
    parent: &mut FxHashMap<FileId, (FileId, Option<u32>)>,
    queue: &mut VecDeque<FileId>,
) {
    for (target, all_type_only, span_start, all_client_only) in scan
        .graph
        .outgoing_edge_summaries_with_exclusions(current, excluded)
    {
        if all_type_only {
            continue; // type-only imports are erased at build; cannot leak.
        }
        if all_client_only {
            // Reached only via next/dynamic ssr:false: the sanctioned
            // client-only escape hatch, not a leak edge.
            continue;
        }
        if scan
            .modules_by_id
            .get(&target)
            .is_some_and(|m| m.is_server_action_module)
        {
            // An all-action "use server" module: the bundler replaces the
            // import with action references, so the module and its imports
            // stay on the server.
            continue;
        }
        if visited.insert(target) {
            parent.insert(target, (current, span_start));
            queue.push_back(target);
        }
    }
}

fn find_client_server_leaks(
    sources: &LeakSources<'_>,
    suppressions: &SuppressionContext<'_>,
    line_offsets_by_file: &LineOffsetsMap<'_>,
) -> (Vec<SecurityFinding>, LeakScanStats) {
    let mut findings = Vec::new();
    let mut stats = LeakScanStats::default();

    // Per-file set of `next/dynamic(..., { ssr: false })` dynamic-import span
    // starts. The BFS excludes an edge reached ONLY through one of these so a
    // server-only (or secret) module pulled in via the sanctioned client-only
    // escape hatch is not flagged. Empty sets are skipped at the call site.
    let mut excluded_spans: FxHashMap<FileId, FxHashSet<u32>> = sources
        .modules_by_id
        .iter()
        .filter(|(_, m)| !m.client_only_dynamic_import_spans.is_empty())
        .map(|(&id, m)| {
            (
                id,
                m.client_only_dynamic_import_spans.iter().copied().collect(),
            )
        })
        .collect();
    // React Router removes the server-only exports of a route module from the
    // client build wherever the module is imported, so the cone skips their
    // imports at every route module, not only at a root.
    for (file_id, split) in sources.framework_roots.route_splits() {
        excluded_spans
            .entry(file_id)
            .or_default()
            .extend(split.server_only_spans.iter().copied());
    }
    let empty_spans: FxHashSet<u32> = FxHashSet::default();

    let scan = LeakScanInput {
        graph: sources.graph,
        modules_by_id: sources.modules_by_id,
        secret_sources: sources.secret_sources,
        server_only_sources: sources.server_only_sources,
        framework_roots: sources.framework_roots,
        suppressions,
        line_offsets_by_file,
        excluded_spans: &excluded_spans,
        empty_spans: &empty_spans,
    };

    for node in &sources.graph.modules {
        scan_client_file_for_leaks(&scan, node, &mut findings, &mut stats);
    }

    findings.sort_by(|a, b| {
        a.path
            .cmp(&b.path)
            .then(a.line.cmp(&b.line))
            .then(a.category.cmp(&b.category))
    });
    (findings, stats)
}

/// Shared immutable inputs for the per-client-file leak scan.
struct LeakScanInput<'a> {
    graph: &'a ModuleGraph,
    modules_by_id: &'a FxHashMap<FileId, &'a ModuleInfo>,
    secret_sources: &'a SecretSources,
    server_only_sources: &'a FxHashSet<FileId>,
    framework_roots: &'a FrameworkClientRoots,
    suppressions: &'a SuppressionContext<'a>,
    line_offsets_by_file: &'a LineOffsetsMap<'a>,
    /// Per file, the import span starts whose edges the cone does not follow.
    excluded_spans: &'a FxHashMap<FileId, FxHashSet<u32>>,
    empty_spans: &'a FxHashSet<u32>,
}

/// Emit direct and transitive client-server leak findings for one module when it
/// is a non-suppressed `"use client"` file. Non-client and file-suppressed nodes
/// are skipped. Direct secret / server-only reads and transitive cone reaches
/// each emit at most one finding, never double-flagging the same file.
fn scan_client_file_for_leaks(
    scan: &LeakScanInput<'_>,
    node: &ModuleNode,
    findings: &mut Vec<SecurityFinding>,
    stats: &mut LeakScanStats,
) {
    let Some(module) = scan.modules_by_id.get(&node.file_id) else {
        return;
    };
    let kind = if module.directives.iter().any(|d| d == USE_CLIENT) {
        ClientRootKind::UseClient
    } else if let Some(kind) = scan.framework_roots.root_kind(node.file_id) {
        kind
    } else {
        return;
    };
    stats.client_roots += 1;
    let client_id = node.file_id;
    // A file-level `// fallow-ignore-file security-client-server-leak`
    // (or a blanket file ignore) opts the whole client file out. Routed
    // through the SuppressionContext so the marker is recorded as consumed
    // (otherwise a working suppression would later be flagged stale).
    if scan
        .suppressions
        .is_file_suppressed(client_id, IssueKind::SecurityClientServerLeak)
    {
        return;
    }

    emit_direct_client_file_leaks(scan, client_id, kind, findings);
    emit_transitive_client_file_leaks(scan, client_id, kind, findings, stats);
}

fn emit_direct_client_file_leaks(
    scan: &LeakScanInput<'_>,
    client_id: FileId,
    kind: ClientRootKind,
    findings: &mut Vec<SecurityFinding>,
) {
    // Direct case: the client file itself reads a non-public secret. The
    // most direct leak; no import hop needed.
    if scan.secret_sources.contains_key(&client_id) {
        findings.push(build_direct_finding(scan, client_id, kind));
        // Still count its dynamic-import blind spot below.
    }

    // Direct server-only case: the client file itself IS a server-only sink
    // (imports a server-only package or a server-only next/headers
    // API). The most direct server-only leak; no
    // import hop needed. The transitive server-only emit below is gated so a
    // file that is both a direct AND a transitive sink is flagged once.
    if scan.server_only_sources.contains(&client_id) {
        findings.push(build_direct_server_only_finding(scan, client_id, kind));
    }
}

fn emit_transitive_client_file_leaks(
    scan: &LeakScanInput<'_>,
    client_id: FileId,
    kind: ClientRootKind,
    findings: &mut Vec<SecurityFinding>,
    stats: &mut LeakScanStats,
) {
    // Transitive case: BFS the import cone.
    let cone = walk_client_cone(scan, client_id);

    if cone.had_unresolved_edge {
        stats.client_files_with_unresolved_edges += 1;
    }

    // Only emit a transitive secret finding when the client is not ALREADY
    // flagged by the direct case (avoid double-flagging the same file).
    if let Some(secret_id) = cone.reached_secret
        && !scan.secret_sources.contains_key(&client_id)
    {
        findings.push(build_leak_finding(
            scan,
            client_id,
            kind,
            secret_id,
            &cone.parent,
        ));
    }

    // The server-only sink is a DISTINCT category, independent of the secret
    // case: a client cone can reach BOTH a secret reader and a server-only
    // module, and a reviewer wants to see both. Only emit a transitive
    // server-only finding when the client is not ALREADY flagged by the
    // direct server-only case above (avoid double-flagging the same file).
    if let Some(server_id) = cone.reached_server_only
        && !scan.server_only_sources.contains(&client_id)
    {
        findings.push(build_server_only_finding(
            scan,
            client_id,
            kind,
            server_id,
            &cone.parent,
        ));
    }
}

/// Walk the BFS parent map from `sink_id` back to `client_id`, building the
/// shortest-path trace. Each non-terminal hop's line is the import site in that
/// file (where it imports the NEXT hop). The terminal hop points at the first
/// secret read (`SecretSource`) or the first server-only import (`Sink`), and
/// falls back to the module start when the module has neither. Shared by the
/// secret-leak and server-only findings.
fn build_client_server_trace(
    scan: &LeakScanInput<'_>,
    client_id: FileId,
    sink_id: FileId,
    parent: &FxHashMap<FileId, (FileId, Option<u32>)>,
    terminal_role: TraceHopRole,
) -> Vec<TraceHop> {
    let graph = scan.graph;
    let line_offsets_by_file = scan.line_offsets_by_file;
    // Walk parent pointers from the sink back to the client, then reverse.
    let mut chain: Vec<FileId> = vec![sink_id];
    let mut cursor = sink_id;
    while let Some(&(prev, _)) = parent.get(&cursor) {
        chain.push(prev);
        cursor = prev;
        if prev == client_id {
            break;
        }
    }
    chain.reverse();

    let mut trace: Vec<TraceHop> = Vec::with_capacity(chain.len());
    for (idx, &file_id) in chain.iter().enumerate() {
        let Some(&next) = chain.get(idx + 1) else {
            trace.push(terminal_hop(scan, sink_id, terminal_role));
            continue;
        };
        let role = if idx == 0 {
            TraceHopRole::ClientBoundary
        } else {
            TraceHopRole::Intermediate
        };
        // The line for a non-terminal hop is where it imports the NEXT hop.
        let (line, col) = parent
            .get(&next)
            .and_then(|&(_, span)| span)
            .map_or((1, 0), |s| {
                byte_offset_to_line_col(line_offsets_by_file, file_id, s)
            });
        trace.push(TraceHop {
            path: graph.modules[file_id.0 as usize].path.clone(),
            line,
            col,
            role,
            secret_reads: Vec::new(),
        });
    }
    trace
}

/// The last hop of a transitive trace: the module that reads the secret or
/// imports the server-only code.
fn terminal_hop(scan: &LeakScanInput<'_>, sink_id: FileId, role: TraceHopRole) -> TraceHop {
    if role == TraceHopRole::SecretSource
        && let Some(reads) = scan.secret_sources.get(&sink_id)
    {
        return secret_source_hop(scan.graph, sink_id, reads, scan.line_offsets_by_file);
    }
    let (line, col) = server_only_location(scan, sink_id);
    TraceHop {
        path: scan.graph.modules[sink_id.0 as usize].path.clone(),
        line,
        col,
        role,
        secret_reads: Vec::new(),
    }
}

/// Reconstruct the shortest path `client -> ... -> secret` from the BFS parent
/// map and build the finding. Each non-terminal hop's line is the import site in
/// that file (where it imports the next hop); the secret-source hop points at
/// the first secret read.
fn build_leak_finding(
    scan: &LeakScanInput<'_>,
    client_id: FileId,
    kind: ClientRootKind,
    secret_id: FileId,
    parent: &FxHashMap<FileId, (FileId, Option<u32>)>,
) -> SecurityFinding {
    let trace = build_client_server_trace(
        scan,
        client_id,
        secret_id,
        parent,
        TraceHopRole::SecretSource,
    );

    let anchor = &trace[0];
    let var_list = scan
        .secret_sources
        .get(&secret_id)
        .map_or_else(Vec::new, |reads| secret_names(reads));
    let vars = var_list.join(", ");
    let word = secret_word(var_list.len());
    // Do NOT embed the secret file path in the message: the SecretSource trace
    // hop already names it (and is root-relativized by the CLI before display),
    // so embedding the absolute path here would leak it past relativization and
    // make output environment-dependent.
    let subject = kind.subject();
    let evidence = format!(
        "{subject} transitively imports a module that reads non-public \
         env {word}: {vars} (see the secret-source hop in the trace). Candidate for \
         verification: confirm the secret value actually reaches client-bundled code."
    );

    // The client-server-leak rule is graph-structural, not catalogue-driven:
    // no source kind, no callee, no CWE. The candidate's sink slot anchors on
    // the client boundary file; the boundary slot is filled by the ranking pass.
    let candidate = client_leak_candidate(
        anchor.path.clone(),
        anchor.line,
        anchor.col,
        Some(SECRET_LEAK_CATEGORY.to_owned()),
    );

    let mut finding = build_client_server_leak_finding(evidence, trace, candidate);
    finding.stable_id_input = Some(SecurityStableIdInput::SecretReads(var_list));
    finding
}

/// Build a finding for the SERVER-ONLY sink: a `"use client"` file whose
/// transitive import cone (static and dynamic) reaches a server-only module
/// (one importing a server-only package or API). Same rule, same suppress
/// kind, same `SecurityFinding` shape as the secret leak; distinguished by
/// `category: Some("server-only-import")` so consumers can tell the two apart.
/// The terminal trace hop carries the `Sink` role (the server-only module is the
/// sink of this candidate).
fn build_server_only_finding(
    scan: &LeakScanInput<'_>,
    client_id: FileId,
    kind: ClientRootKind,
    server_id: FileId,
    parent: &FxHashMap<FileId, (FileId, Option<u32>)>,
) -> SecurityFinding {
    let trace = build_client_server_trace(scan, client_id, server_id, parent, TraceHopRole::Sink);

    let anchor = &trace[0];
    // Do NOT embed the server module path in the message: the Sink trace hop
    // already names it (root-relativized by the CLI before display), so embedding
    // the absolute path here would leak it past relativization and make output
    // environment-dependent.
    let subject = kind.subject();
    // The advice follows the origin of the sink. React Router has no
    // `next/dynamic`, Server Actions or "use server" modules, so a `.server`
    // sink gets React Router advice. The shared phrase lets the `Next:` step
    // pick the same advice.
    let evidence = if scan.framework_roots.is_server_sink(server_id) {
        let phrase = fallow_types::security_next_step::REACT_ROUTER_SERVER_SINK;
        format!(
            "{subject} transitively {phrase} (see the sink hop in the trace). React Router \
             fails the client build for this import. Candidate for verification: confirm \
             that client code reaches the import and that the import is not type-only."
        )
    } else {
        format!(
            "{subject} transitively imports a SERVER-ONLY module \
             (it imports server-only code such as server-only, next/headers, next/server, or \
             node:fs / node:child_process; see the sink hop in the trace). Candidate for \
             verification: confirm whether this server-only code is meant to run on the client. \
             If it is pulled in only through next/dynamic(..., {{ ssr: false }}), it is the \
             sanctioned client-only escape hatch and is a false positive. fallow already \
             excludes a Server Action module whose value exports are all async functions. \
             If the sink is a Server Action module, it has a non-action export (a top-level \
             const, a re-export, or a default value), and that export carries the \
             server-only import into the client bundle."
        )
    };

    let candidate = client_leak_candidate(
        anchor.path.clone(),
        anchor.line,
        anchor.col,
        Some(SERVER_ONLY_CATEGORY.to_owned()),
    );

    build_client_server_leak_finding(evidence, trace, candidate)
}

/// Build the candidate record for a `client-server-leak` finding. These findings
/// carry no source kind (graph-structural, not source-to-sink) and no callee;
/// the sink slot anchors on the client boundary file. The boundary slot starts
/// at its default and is filled by the post-detection ranking pass. `category`
/// is `None` for the secret-leak finding and `Some("server-only-import")` for the
/// server-only finding, mirroring the finding's top-level `category`.
fn client_leak_candidate(
    path: std::path::PathBuf,
    line: u32,
    col: u32,
    category: Option<String>,
) -> SecurityCandidate {
    SecurityCandidate {
        source_kind: None,
        sink: SecurityCandidateSink {
            path,
            line,
            col,
            category,
            cwe: None,
            callee: None,
            url_shape: None,
        },
        boundary: SecurityCandidateBoundary::default(),
        network: None,
    }
}

/// Build a finding for the direct case: a `"use client"` file that itself reads
/// a non-public secret. Trace is a single hop on the client file, which is both
/// the boundary and the secret source. The finding points at the first read.
fn build_direct_finding(
    scan: &LeakScanInput<'_>,
    client_id: FileId,
    kind: ClientRootKind,
) -> SecurityFinding {
    let reads = scan
        .secret_sources
        .get(&client_id)
        .map_or(&[][..], Vec::as_slice);
    let var_list = secret_names(reads);
    let vars = var_list.join(", ");
    let word = secret_word(var_list.len());
    let subject = kind.subject();
    let evidence = format!(
        "{subject} directly reads non-public env {word}: {vars}. \
         Candidate for verification: confirm the secret value actually reaches client-bundled \
         code (it may be guarded, server-only, or build-time-stripped)."
    );
    let hop = secret_source_hop(scan.graph, client_id, reads, scan.line_offsets_by_file);
    let candidate = client_leak_candidate(
        hop.path.clone(),
        hop.line,
        hop.col,
        Some(SECRET_LEAK_CATEGORY.to_owned()),
    );
    let mut finding = build_client_server_leak_finding(evidence, vec![hop], candidate);
    finding.stable_id_input = Some(SecurityStableIdInput::SecretReads(var_list));
    finding
}

/// Build a finding for the direct SERVER-ONLY case: a `"use client"` file that is
/// itself a server-only sink (imports a server-only package or a server-only
/// `next/headers` API). No import hop is needed,
/// so the trace is a single self-hop on the client file, which is both the client
/// boundary and the server-only sink. Mirrors [`build_direct_finding`] for the
/// secret case; distinguished by `category: Some("server-only-import")`. The
/// finding points at the first server-only import.
fn build_direct_server_only_finding(
    scan: &LeakScanInput<'_>,
    client_id: FileId,
    kind: ClientRootKind,
) -> SecurityFinding {
    let path = scan.graph.modules[client_id.0 as usize].path.clone();
    let (line, col) = server_only_location(scan, client_id);
    let subject = kind.subject();
    let evidence = format!(
        "{subject} directly imports SERVER-ONLY code \
         (server-only code such as server-only, next/headers, next/server, or \
         node:fs / node:child_process). Candidate for verification: confirm whether this \
         server-only code is meant to run on the client."
    );
    let candidate = client_leak_candidate(
        path.clone(),
        line,
        col,
        Some(SERVER_ONLY_CATEGORY.to_owned()),
    );
    let trace = vec![TraceHop {
        path,
        line,
        col,
        role: TraceHopRole::Sink,
        secret_reads: Vec::new(),
    }];
    build_client_server_leak_finding(evidence, trace, candidate)
}

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

    #[test]
    fn public_env_vars_are_not_secrets() {
        assert!(is_public_env_var("NODE_ENV"));
        assert!(is_public_env_var("NEXT_PUBLIC_API_URL"));
        assert!(is_public_env_var("VITE_TITLE"));
        assert!(is_public_env_var("PUBLIC_SITE_NAME"));
        assert!(is_public_env_var("EXPO_PUBLIC_KEY"));
    }

    #[test]
    fn real_secrets_are_not_public() {
        assert!(!is_public_env_var("DATABASE_URL"));
        assert!(!is_public_env_var("STRIPE_SECRET_KEY"));
        assert!(!is_public_env_var("SESSION_SECRET"));
        // A var that merely contains a public token mid-name is still a secret.
        assert!(!is_public_env_var("MY_NEXT_PUBLIC_FAKE"));
    }

    #[test]
    fn import_source_matches_node_prefix() {
        assert!(import_source_matches("node:child_process", "child_process"));
        assert!(import_source_matches("child_process", "node:child_process"));
        assert!(!import_source_matches("child_process", "node:vm"));
    }

    #[test]
    fn import_source_matches_package_subpath() {
        assert!(import_source_matches("mysql2/promise", "mysql2"));
        assert!(import_source_matches("@scope/pkg/subpath", "@scope/pkg"));
        assert!(!import_source_matches("mysql2-promise", "mysql2"));
    }
}