use rustc_hash::{FxHashMap, FxHashSet};
use std::collections::VecDeque;
use fallow_types::extract::ModuleInfo;
use fallow_types::output::{IssueAction, SuppressFileAction, SuppressFileKind};
use fallow_types::results::{
SecurityCandidate, SecurityCandidateBoundary, SecurityCandidateSink, SecurityFinding,
SecurityFindingKind, SecuritySeverity, TraceHop, TraceHopRole,
};
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};
pub use fallow_security::{CalleePattern, Matcher};
#[must_use]
pub fn catalogue_matchers() -> &'static [Matcher] {
fallow_security::catalogue().matchers()
}
#[cfg(test)]
use fallow_security::import_source_matches;
const SUPPRESS_KIND: &str = "security-client-server-leak";
const SECRET_LEAK_CATEGORY: &str = "client-server-leak";
const SERVER_ONLY_CATEGORY: &str = "server-only-import";
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,
source_backed: false,
source_read: None,
severity: SecuritySeverity::Low,
trace,
actions: build_actions(),
dead_code: None,
reachability: None,
candidate,
taint_flow: None,
runtime: None,
attack_surface: None,
}
}
const USE_CLIENT: &str = "use client";
const fn secret_word(count: usize) -> &'static str {
if count == 1 { "secret" } else { "secrets" }
}
const PROCESS_ENV_OBJECT: &str = "process.env";
const IMPORT_META_ENV_OBJECT: &str = "import.meta.env";
const ENV_SOURCE_OBJECTS: &[&str] = &[PROCESS_ENV_OBJECT, IMPORT_META_ENV_OBJECT];
use fallow_types::extract::is_public_env_var;
#[derive(Debug, Default, Clone, Copy)]
pub struct LeakScanStats {
pub client_files_with_unresolved_edges: usize,
pub client_roots: usize,
}
#[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,
)
}
fn apply_route_splits(
modules_by_id: &FxHashMap<FileId, &ModuleInfo>,
framework_roots: &FrameworkClientRoots,
secret_sources: &mut FxHashMap<FileId, Vec<String>>,
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.dead_only_env_reads.contains(read));
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);
}
}
}
}
struct LeakSources<'a> {
graph: &'a ModuleGraph,
modules_by_id: &'a FxHashMap<FileId, &'a ModuleInfo>,
secret_sources: &'a FxHashMap<FileId, Vec<String>>,
server_only_sources: &'a FxHashSet<FileId>,
framework_roots: &'a FrameworkClientRoots,
}
fn compute_secret_source_set(
modules_by_id: &FxHashMap<FileId, &ModuleInfo>,
) -> FxHashMap<FileId, Vec<String>> {
let mut sources: FxHashMap<FileId, Vec<String>> = FxHashMap::default();
for (&file_id, module) in modules_by_id {
let mut vars: Vec<String> = module
.member_accesses
.iter()
.filter(|ma| {
ENV_SOURCE_OBJECTS.contains(&ma.object.as_str()) && !is_public_env_var(&ma.member)
})
.map(|ma| format!("{}.{}", ma.object, ma.member))
.collect();
if vars.is_empty() {
continue;
}
vars.sort_unstable();
vars.dedup();
sources.insert(file_id, vars);
}
sources
}
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
}
struct ClientConeResult {
parent: FxHashMap<FileId, (FileId, Option<u32>)>,
reached_secret: Option<FileId>,
reached_server_only: Option<FileId>,
had_unresolved_edge: bool,
}
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(¤t)
.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(¤t)
&& !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(¤t) {
result.reached_secret = Some(current);
}
if result.reached_server_only.is_none() && scan.server_only_sources.contains(¤t) {
result.reached_server_only = Some(current);
}
}
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; }
if all_client_only {
continue;
}
if scan
.modules_by_id
.get(&target)
.is_some_and(|m| m.is_server_action_module)
{
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();
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();
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)
}
struct LeakScanInput<'a> {
graph: &'a ModuleGraph,
modules_by_id: &'a FxHashMap<FileId, &'a ModuleInfo>,
secret_sources: &'a FxHashMap<FileId, Vec<String>>,
server_only_sources: &'a FxHashSet<FileId>,
framework_roots: &'a FrameworkClientRoots,
suppressions: &'a SuppressionContext<'a>,
line_offsets_by_file: &'a LineOffsetsMap<'a>,
excluded_spans: &'a FxHashMap<FileId, FxHashSet<u32>>,
empty_spans: &'a FxHashSet<u32>,
}
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;
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>,
) {
if scan.secret_sources.contains_key(&client_id) {
findings.push(build_direct_finding(
scan.graph,
client_id,
kind,
scan.secret_sources,
));
}
if scan.server_only_sources.contains(&client_id) {
findings.push(build_direct_server_only_finding(
scan.graph, client_id, kind,
));
}
}
fn emit_transitive_client_file_leaks(
scan: &LeakScanInput<'_>,
client_id: FileId,
kind: ClientRootKind,
findings: &mut Vec<SecurityFinding>,
stats: &mut LeakScanStats,
) {
let cone = walk_client_cone(scan, client_id);
if cone.had_unresolved_edge {
stats.client_files_with_unresolved_edges += 1;
}
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,
));
}
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,
));
}
}
fn build_client_server_trace(
graph: &ModuleGraph,
client_id: FileId,
sink_id: FileId,
parent: &FxHashMap<FileId, (FileId, Option<u32>)>,
line_offsets_by_file: &LineOffsetsMap<'_>,
terminal_role: TraceHopRole,
) -> Vec<TraceHop> {
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 role = if idx == 0 {
TraceHopRole::ClientBoundary
} else if file_id == sink_id {
terminal_role
} else {
TraceHopRole::Intermediate
};
let (line, col) = if let Some(&next) = chain.get(idx + 1) {
parent
.get(&next)
.and_then(|&(_, span)| span)
.map_or((1, 0), |s| {
byte_offset_to_line_col(line_offsets_by_file, file_id, s)
})
} else {
(1, 0)
};
trace.push(TraceHop {
path: graph.modules[file_id.0 as usize].path.clone(),
line,
col,
role,
});
}
trace
}
fn build_leak_finding(
scan: &LeakScanInput<'_>,
client_id: FileId,
kind: ClientRootKind,
secret_id: FileId,
parent: &FxHashMap<FileId, (FileId, Option<u32>)>,
) -> SecurityFinding {
let secret_sources = scan.secret_sources;
let trace = build_client_server_trace(
scan.graph,
client_id,
secret_id,
parent,
scan.line_offsets_by_file,
TraceHopRole::SecretSource,
);
let anchor = &trace[0];
let empty = Vec::new();
let var_list = secret_sources.get(&secret_id).unwrap_or(&empty);
let vars = var_list.join(", ");
let word = secret_word(var_list.len());
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."
);
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);
let mut secret_names = var_list.clone();
secret_names.sort_unstable();
secret_names.dedup();
finding.stable_id_input = Some(SecurityStableIdInput::SecretReads(secret_names));
finding
}
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.graph,
client_id,
server_id,
parent,
scan.line_offsets_by_file,
TraceHopRole::Sink,
);
let anchor = &trace[0];
let subject = kind.subject();
let sink_reason = if scan.framework_roots.is_server_sink(server_id) {
"it is a React Router .server module"
} else {
"it imports server-only code such as server-only, next/headers, next/server, or \
node:fs / node:child_process"
};
let evidence = format!(
"{subject} transitively imports a SERVER-ONLY module \
({sink_reason}; 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)
}
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,
}
}
fn build_direct_finding(
graph: &ModuleGraph,
client_id: FileId,
kind: ClientRootKind,
secret_sources: &FxHashMap<FileId, Vec<String>>,
) -> SecurityFinding {
let path = graph.modules[client_id.0 as usize].path.clone();
let empty = Vec::new();
let var_list = secret_sources.get(&client_id).unwrap_or(&empty);
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 candidate =
client_leak_candidate(path.clone(), 1, 0, Some(SECRET_LEAK_CATEGORY.to_owned()));
let trace = vec![TraceHop {
path,
line: 1,
col: 0,
role: TraceHopRole::SecretSource,
}];
build_client_server_leak_finding(evidence, trace, candidate)
}
fn build_direct_server_only_finding(
graph: &ModuleGraph,
client_id: FileId,
kind: ClientRootKind,
) -> SecurityFinding {
let path = graph.modules[client_id.0 as usize].path.clone();
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(), 1, 0, Some(SERVER_ONLY_CATEGORY.to_owned()));
let trace = vec![TraceHop {
path,
line: 1,
col: 0,
role: TraceHopRole::Sink,
}];
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"));
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"));
}
}