Skip to main content

fallow_cli/
security.rs

1//! `fallow security` command: opt-in local security-candidate surface.
2//!
3//! Ships the graph-structural `client-server-leak` rule plus the data-driven
4//! `tainted-sink` catalogue (one `TaintedSink` kind covering every CWE category
5//! in `security_matchers.toml`). Findings are CANDIDATES for downstream agent
6//! verification, NOT verified vulnerabilities.
7//! This command is the ONLY surface for security findings: they never appear
8//! under bare `fallow` or the `audit` gate. There is no `confidence` or
9//! `signal_strength` field; structural traces and reachability context are the
10//! only honest signals.
11
12use crate::report::sink::outln;
13use colored::Colorize;
14use std::cmp::Ordering;
15use std::collections::{BTreeMap, BTreeSet};
16use std::io::Write;
17use std::path::{Path, PathBuf};
18use std::process::ExitCode;
19use std::time::Instant;
20
21use fallow_config::{OutputFormat, ProductionAnalysis, Severity};
22use fallow_engine::{derive_security_severity, security_catalogue_title};
23pub use fallow_output::{
24    SecurityBlindSpotFile, SecurityBlindSpotGroup, SecurityBlindSpotsOutput,
25    SecurityBlindSpotsSchemaVersion, SecurityBlindSpotsSummary, SecurityGateVerdict,
26    SecuritySchemaVersion, SecuritySurvivor, SecuritySurvivorsOutput,
27    SecuritySurvivorsSchemaVersion, SecuritySurvivorsSummary, SecurityUnresolvedCalleeDiagnostics,
28    SecurityUnresolvedCalleeReasonCount, SecurityUnresolvedCalleeSample,
29    SecurityUnresolvedCalleeTopFile, SecurityVerifierVerdict, SecurityVerifierVerdictStatus,
30};
31use fallow_types::discover::DiscoveredFile;
32use fallow_types::envelope::{ElapsedMs, ToolVersion};
33use fallow_types::extract::ModuleInfo;
34use fallow_types::results::{
35    AnalysisResults, SecurityAttackSurfaceEntry, SecurityDeadCodeKind, SecurityFinding,
36    SecurityFindingKind, TraceHop, TraceHopRole,
37};
38use fallow_types::results::{
39    SecurityRuntimeContext, SecurityRuntimeState, SecuritySeverity,
40    SecurityUnresolvedCalleeDiagnostic, TaintConfidence,
41};
42use rustc_hash::FxHashSet;
43use xxhash_rust::xxh3::xxh3_64;
44
45use crate::base_worktree::{BaseWorktree, git_rev_parse};
46use crate::error::emit_error;
47use crate::health::HealthOptions;
48use crate::load_config_for_analysis;
49use fallow_output::{
50    RuntimeCoverageFinding, RuntimeCoverageHotPath, RuntimeCoverageReport, RuntimeCoverageVerdict,
51};
52
53pub use fallow_api::SecurityGateMode;
54
55const UNRESOLVED_CALLEE_SAMPLE_LIMIT: usize = 25;
56const UNRESOLVED_CALLEE_TOP_FILES_LIMIT: usize = 10;
57
58/// CLI parser mode for `fallow security --gate <mode>`.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
60pub enum SecurityGateArg {
61    /// Fail when the change introduces a new security-sink candidate on a
62    /// changed line.
63    New,
64    /// Fail when a candidate becomes runtime-reachable from an entry point in
65    /// head but the matching candidate was not runtime-reachable in base.
66    NewlyReachable,
67}
68
69impl SecurityGateArg {
70    #[must_use]
71    pub const fn into_mode(self) -> SecurityGateMode {
72        match self {
73            Self::New => SecurityGateMode::New,
74            Self::NewlyReachable => SecurityGateMode::NewlyReachable,
75        }
76    }
77}
78
79pub type SecurityGate = fallow_output::SecurityGate<SecurityGateMode>;
80
81pub type SecurityOutputConfig = fallow_output::SecurityOutputConfig<Severity>;
82
83pub type SecurityOutputRulesConfig = fallow_output::SecurityOutputRulesConfig<Severity>;
84
85pub type SecurityRuleSeverityConfig = fallow_output::SecurityRuleSeverityConfig<Severity>;
86
87pub type SecurityOutput = fallow_output::SecurityOutput<SecurityOutputConfig, SecurityGate>;
88
89/// Options for `fallow security`, mirroring the global CLI flags it honors.
90pub struct SecurityOptions<'a> {
91    /// Project root.
92    pub root: &'a Path,
93    /// Explicit config path (global `--config`).
94    pub config_path: &'a Option<PathBuf>,
95    /// Output format.
96    pub output: OutputFormat,
97    /// Disable the extraction cache.
98    pub no_cache: bool,
99    /// Resolved thread-pool size.
100    pub threads: usize,
101    /// Suppress progress output.
102    pub quiet: bool,
103    /// Exit with code 1 when candidates are found.
104    pub fail_on_issues: bool,
105    /// Write SARIF to a sidecar file in addition to the primary output.
106    pub sarif_file: Option<&'a Path>,
107    /// Show a compact human summary instead of per-finding detail.
108    pub summary: bool,
109    /// `--changed-since <ref>`: scope findings to files changed since the ref.
110    pub changed_since: Option<&'a str>,
111    /// Apply the shared `--diff-file` / `--diff-stdin` line filter.
112    pub use_shared_diff_index: bool,
113    /// `--workspace <patterns...>`: scope findings to selected workspace roots.
114    pub workspace: Option<&'a [String]>,
115    /// `--changed-workspaces <ref>`: scope to workspaces with changed files.
116    pub changed_workspaces: Option<&'a str>,
117    /// `--file <PATH>`: scope findings to selected files or trace hops.
118    pub file: &'a [PathBuf],
119    /// `--surface`: include the top-level attack-surface inventory in JSON.
120    pub surface: bool,
121    /// `--gate <mode>`: opt-in regression gate. `new` requires a diff source and
122    /// reports candidates introduced in changed lines. `newly-reachable`
123    /// requires `--changed-since <ref>` and reports candidates newly reachable
124    /// from runtime entry points.
125    pub gate: Option<SecurityGateMode>,
126    /// Paid local runtime-coverage sidecar input.
127    pub runtime_coverage: Option<&'a Path>,
128    /// Threshold for hot-path classification when `--runtime-coverage` is set.
129    pub min_invocations_hot: u64,
130    /// Include security-specific `_meta` in JSON output.
131    pub explain: bool,
132}
133
134/// Options for `fallow security survivors`.
135pub struct SecuritySurvivorsOptions<'a> {
136    /// Output format.
137    pub output: OutputFormat,
138    /// Raw `fallow security --format json` candidate file.
139    pub candidates: &'a Path,
140    /// Verifier verdict JSON file.
141    pub verdicts: &'a Path,
142    /// Exit with code 2 when any candidate lacks a matching verdict.
143    pub require_verdict_for_each_candidate: bool,
144}
145
146/// Run `fallow security survivors`.
147pub fn run_survivors(opts: &SecuritySurvivorsOptions<'_>) -> ExitCode {
148    let started = Instant::now();
149    if let Err(code) = validate_derived_security_output(opts.output, "survivors") {
150        return code;
151    }
152    let output = match build_survivors_output(opts, started) {
153        Ok(output) => output,
154        Err(message) => return emit_error(&message, 2, opts.output),
155    };
156    // Note find-state for telemetry before any exit (issue #1650): the survivors
157    // subcommand emits a `security` workflow event, and without this the
158    // process-global findings-present accumulator stays unset (-> null). The
159    // retained, non-dismissed candidates (survivors + needs-human-review) are
160    // what this run surfaced as actionable; an all-dismissed run is clean.
161    crate::telemetry::note_result_count(
162        output.summary.survivors + output.summary.needs_human_review,
163    );
164    if opts.require_verdict_for_each_candidate && output.summary.unverdicted > 0 {
165        return emit_error(
166            &format!(
167                "Verifier verdict file is missing verdicts for {} candidate{}.",
168                output.summary.unverdicted,
169                crate::report::plural(output.summary.unverdicted)
170            ),
171            2,
172            opts.output,
173        );
174    }
175    outln!("{}", render_survivors_output(opts.output, &output));
176    ExitCode::SUCCESS
177}
178
179/// Run `fallow security blind-spots`.
180pub fn run_blind_spots(opts: &SecurityOptions<'_>) -> ExitCode {
181    let started = Instant::now();
182    if let Err(code) = validate_derived_security_output(opts.output, "blind-spots") {
183        return code;
184    }
185    let (security_output, _) = match build_security_command_output(opts, started) {
186        Ok(output) => output,
187        Err(code) => return code,
188    };
189    let output = build_blind_spots_output(&security_output);
190    // Note find-state for telemetry before exit (issue #1650): the blind-spots
191    // subcommand emits a `security` workflow event; without this the
192    // findings-present accumulator stays unset (-> null). Its findings are the
193    // unresolved callee sites it surfaces; zero blind spots is a clean run.
194    crate::telemetry::note_result_count(output.summary.unresolved_callee_sites);
195    outln!("{}", render_blind_spots_output(opts.output, &output));
196    ExitCode::SUCCESS
197}
198
199/// Run `fallow security`. Always exits 0 unless the user explicitly raised the
200/// `security-client-server-leak` rule to `error` AND findings exist (the rule
201/// defaults to `off` and the command forces it to `warn`, so the common case is
202/// advisory). Unsupported output formats exit 2.
203pub fn run(opts: &SecurityOptions<'_>) -> ExitCode {
204    let started = Instant::now();
205    let (output, effective_severities) = match build_security_command_output(opts, started) {
206        Ok(output) => output,
207        Err(code) => return code,
208    };
209    crate::telemetry::note_result_count(output.security_findings.len());
210
211    if let Err(code) = maybe_write_security_sarif(opts, &output) {
212        return code;
213    }
214
215    outln!("{}", render_security_output(opts, &output));
216    security_exit_code(opts, &output, effective_severities)
217}
218
219fn build_security_command_output(
220    opts: &SecurityOptions<'_>,
221    started: Instant,
222) -> Result<(SecurityOutput, SecurityRuleSeverities), ExitCode> {
223    validate_security_output(opts.output)?;
224
225    let mut config = load_config_for_analysis(
226        opts.root,
227        opts.config_path,
228        crate::ConfigLoadOptions {
229            output: opts.output,
230            no_cache: opts.no_cache,
231            threads: opts.threads,
232            production_override: None,
233            quiet: opts.quiet,
234        },
235        ProductionAnalysis::DeadCode,
236    )?;
237
238    let configured_severities = security_rule_severities(&config);
239    force_security_rules(&mut config);
240    let effective_severities = security_rule_severities(&config);
241
242    let mut analysis = analyze_security_candidates(opts, &config)?;
243
244    apply_security_scopes(opts, &mut analysis)?;
245
246    let gate_mode = apply_security_gate(opts, &config, &mut analysis.results)?;
247
248    let unresolved_edge_files = analysis.results.security_unresolved_edge_files;
249    let unresolved_callee_sites = analysis.results.security_unresolved_callee_sites;
250    let unresolved_callee_diagnostics = unresolved_callee_diagnostics(
251        &analysis.results.security_unresolved_callee_diagnostics,
252        &config.root,
253    );
254    let runtime_report = security_runtime_report(opts, &mut analysis)?;
255    let PreparedSecurityFindings {
256        findings,
257        attack_surface,
258    } = prepare_security_findings(
259        &mut analysis,
260        runtime_report.as_ref(),
261        &config.root,
262        opts.surface,
263    );
264
265    let output = build_security_output(SecurityOutputInput {
266        opts,
267        started,
268        config: &config,
269        configured_severities,
270        effective_severities,
271        gate_mode,
272        findings,
273        attack_surface,
274        unresolved_edge_files,
275        unresolved_callee_sites,
276        unresolved_callee_diagnostics,
277    });
278    Ok((output, effective_severities))
279}
280
281#[derive(Clone, Copy)]
282struct SecurityRuleSeverities {
283    leak: Severity,
284    sink: Severity,
285}
286
287struct SecurityOutputInput<'a, 'b> {
288    opts: &'a SecurityOptions<'b>,
289    started: Instant,
290    config: &'a fallow_config::ResolvedConfig,
291    configured_severities: SecurityRuleSeverities,
292    effective_severities: SecurityRuleSeverities,
293    gate_mode: Option<SecurityGateMode>,
294    findings: Vec<SecurityFinding>,
295    attack_surface: Option<Vec<SecurityAttackSurfaceEntry>>,
296    unresolved_edge_files: usize,
297    unresolved_callee_sites: usize,
298    unresolved_callee_diagnostics: Option<SecurityUnresolvedCalleeDiagnostics>,
299}
300
301fn validate_security_output(output: OutputFormat) -> Result<(), ExitCode> {
302    if matches!(
303        output,
304        OutputFormat::Human | OutputFormat::Json | OutputFormat::Sarif
305    ) {
306        Ok(())
307    } else {
308        Err(emit_error(
309            "fallow security supports --format human, json, or sarif only.",
310            2,
311            output,
312        ))
313    }
314}
315
316fn validate_derived_security_output(
317    output: OutputFormat,
318    subcommand: &'static str,
319) -> Result<(), ExitCode> {
320    if matches!(output, OutputFormat::Human | OutputFormat::Json) {
321        Ok(())
322    } else {
323        Err(emit_error(
324            &format!("fallow security {subcommand} supports --format human or json only."),
325            2,
326            output,
327        ))
328    }
329}
330
331fn build_survivors_output(
332    opts: &SecuritySurvivorsOptions<'_>,
333    started: Instant,
334) -> Result<SecuritySurvivorsOutput, String> {
335    let candidates = load_candidate_map(opts.candidates)?;
336    let verdicts = load_verdicts(opts.verdicts)?;
337    let mut seen = BTreeSet::new();
338    let mut survivors = BTreeMap::new();
339    let mut needs_human_review = BTreeMap::new();
340    let mut dismissed = 0;
341
342    for verdict in &verdicts {
343        validate_verdict(verdict)?;
344        if !seen.insert(verdict.finding_id.clone()) {
345            return Err(format!(
346                "Verifier verdict file has duplicate verdict for finding_id `{}`.",
347                verdict.finding_id
348            ));
349        }
350        let Some(candidate) = candidates.get(&verdict.finding_id) else {
351            return Err(format!(
352                "Verifier verdict references unknown finding_id `{}`.",
353                verdict.finding_id
354            ));
355        };
356        match verdict.verdict {
357            SecurityVerifierVerdictStatus::Survivor => {
358                survivors.insert(
359                    verdict.finding_id.clone(),
360                    survivor_from_verdict(verdict, candidate),
361                );
362            }
363            SecurityVerifierVerdictStatus::Dismissed => dismissed += 1,
364            SecurityVerifierVerdictStatus::NeedsHumanReview => {
365                needs_human_review.insert(
366                    verdict.finding_id.clone(),
367                    survivor_from_verdict(verdict, candidate),
368                );
369            }
370        }
371    }
372
373    let unverdicted = candidates.len().saturating_sub(seen.len());
374
375    Ok(SecuritySurvivorsOutput {
376        schema_version: SecuritySurvivorsSchemaVersion::V2,
377        version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
378        elapsed_ms: ElapsedMs(started.elapsed().as_millis() as u64),
379        summary: SecuritySurvivorsSummary {
380            candidates: candidates.len(),
381            verdicts: verdicts.len(),
382            survivors: survivors.len(),
383            dismissed,
384            needs_human_review: needs_human_review.len(),
385            unverdicted,
386        },
387        survivors,
388        needs_human_review,
389    })
390}
391
392fn load_candidate_map(path: &Path) -> Result<BTreeMap<String, SecurityFinding>, String> {
393    let value = load_json_file(path, "candidate")?;
394    let Some(findings) = value
395        .get("security_findings")
396        .and_then(serde_json::Value::as_array)
397    else {
398        return Err(format!(
399            "Candidate file {} must be raw `fallow security --format json` output with a security_findings array.",
400            path.display()
401        ));
402    };
403    let mut candidates = BTreeMap::new();
404    for finding in findings {
405        let finding: SecurityFinding = serde_json::from_value(finding.clone()).map_err(|err| {
406            format!(
407                "Candidate file {} contains a malformed security finding: {err}",
408                path.display()
409            )
410        })?;
411        if finding.finding_id.is_empty() {
412            return Err(format!(
413                "Candidate file {} contains a security finding with an empty finding_id.",
414                path.display()
415            ));
416        }
417        if candidates
418            .insert(finding.finding_id.clone(), finding.clone())
419            .is_some()
420        {
421            return Err(format!(
422                "Candidate file {} contains duplicate finding_id `{}`.",
423                path.display(),
424                finding.finding_id
425            ));
426        }
427    }
428    Ok(candidates)
429}
430
431fn load_verdicts(path: &Path) -> Result<Vec<SecurityVerifierVerdict>, String> {
432    let value = load_json_file(path, "verdict")?;
433    let verdicts_value = if let Some(items) = value.get("verdicts") {
434        if value
435            .get("schema_version")
436            .and_then(serde_json::Value::as_str)
437            != Some("fallow-security-verdicts/v1")
438        {
439            return Err(format!(
440                "Verifier verdict file {} must use schema_version `fallow-security-verdicts/v1`.",
441                path.display()
442            ));
443        }
444        if !items.is_array() {
445            return Err(format!(
446                "Verifier verdict file {} must contain a verdicts array.",
447                path.display()
448            ));
449        }
450        items.clone()
451    } else {
452        value
453    };
454    serde_json::from_value::<Vec<SecurityVerifierVerdict>>(verdicts_value).map_err(|err| {
455        format!(
456            "Failed to parse verifier verdict file {}: {err}",
457            path.display()
458        )
459    })
460}
461
462fn load_json_file(path: &Path, label: &str) -> Result<serde_json::Value, String> {
463    let src = std::fs::read_to_string(path)
464        .map_err(|err| format!("Failed to read {label} file {}: {err}", path.display()))?;
465    serde_json::from_str(&src)
466        .map_err(|err| format!("Failed to parse {label} file {}: {err}", path.display()))
467}
468
469fn validate_verdict(verdict: &SecurityVerifierVerdict) -> Result<(), String> {
470    if verdict.schema_version != "fallow-security-verdict/v1" {
471        return Err(format!(
472            "Verifier verdict for finding_id `{}` must use schema_version `fallow-security-verdict/v1`.",
473            verdict.finding_id
474        ));
475    }
476    if verdict.finding_id.is_empty() {
477        return Err("Verifier verdict contains an empty finding_id.".to_owned());
478    }
479    Ok(())
480}
481
482fn survivor_from_verdict(
483    verdict: &SecurityVerifierVerdict,
484    candidate: &SecurityFinding,
485) -> SecuritySurvivor {
486    SecuritySurvivor {
487        finding_id: verdict.finding_id.clone(),
488        verdict: verdict.verdict,
489        reason: verdict.reason.clone(),
490        rationale: verdict.rationale.clone(),
491        confidence: verdict.confidence.clone(),
492        impact: verdict.impact.clone(),
493        fix_direction: verdict.fix_direction.clone(),
494        candidate: candidate.clone(),
495    }
496}
497
498fn security_rule_severities(config: &fallow_config::ResolvedConfig) -> SecurityRuleSeverities {
499    SecurityRuleSeverities {
500        leak: config.rules.security_client_server_leak,
501        sink: config.rules.security_sink,
502    }
503}
504
505fn build_security_output(input: SecurityOutputInput<'_, '_>) -> SecurityOutput {
506    SecurityOutput {
507        schema_version: SecuritySchemaVersion::V7,
508        version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
509        elapsed_ms: ElapsedMs(input.started.elapsed().as_millis() as u64),
510        config: security_output_config(
511            input.config,
512            input.configured_severities.leak,
513            input.effective_severities.leak,
514            input.configured_severities.sink,
515            input.effective_severities.sink,
516        ),
517        meta: input.opts.explain.then(crate::explain::security_meta),
518        gate: input
519            .gate_mode
520            .map(|mode| security_gate_output(mode, input.findings.len())),
521        security_findings: input.findings,
522        attack_surface: input.attack_surface,
523        unresolved_edge_files: input.unresolved_edge_files,
524        unresolved_callee_sites: input.unresolved_callee_sites,
525        unresolved_callee_diagnostics: input.unresolved_callee_diagnostics,
526    }
527}
528
529fn security_gate_output(mode: SecurityGateMode, finding_count: usize) -> SecurityGate {
530    // In gate mode the displayed set is the strict "new" set, so its length is
531    // the new-candidate count. The gate block is emitted unconditionally when a
532    // gate ran so consumers can distinguish pass from "gate did not run".
533    SecurityGate {
534        mode,
535        verdict: if finding_count > 0 {
536            SecurityGateVerdict::Fail
537        } else {
538            SecurityGateVerdict::Pass
539        },
540        new_count: finding_count,
541    }
542}
543
544fn maybe_write_security_sarif(
545    opts: &SecurityOptions<'_>,
546    output: &SecurityOutput,
547) -> Result<(), ExitCode> {
548    if let Some(path) = opts.sarif_file
549        && let Err(message) = write_sarif_file(output, path)
550    {
551        return Err(emit_error(&message, 2, opts.output));
552    }
553    Ok(())
554}
555
556fn render_security_output(opts: &SecurityOptions<'_>, output: &SecurityOutput) -> String {
557    match opts.output {
558        OutputFormat::Json if opts.summary => render_json_summary(output),
559        OutputFormat::Json => render_json(output),
560        OutputFormat::Sarif => render_sarif(output),
561        _ if opts.summary => render_human_summary(output),
562        _ => render_human(output),
563    }
564}
565
566fn security_exit_code(
567    opts: &SecurityOptions<'_>,
568    output: &SecurityOutput,
569    effective_severities: SecurityRuleSeverities,
570) -> ExitCode {
571    if let Some(gate) = &output.gate {
572        if gate.verdict == SecurityGateVerdict::Fail {
573            ExitCode::from(8)
574        } else {
575            ExitCode::SUCCESS
576        }
577    } else if security_advisory_failed(opts, output, effective_severities) {
578        ExitCode::from(1)
579    } else {
580        ExitCode::SUCCESS
581    }
582}
583
584fn security_advisory_failed(
585    opts: &SecurityOptions<'_>,
586    output: &SecurityOutput,
587    effective_severities: SecurityRuleSeverities,
588) -> bool {
589    (opts.fail_on_issues
590        || effective_severities.leak == Severity::Error
591        || effective_severities.sink == Severity::Error)
592        && !output.security_findings.is_empty()
593}
594
595struct PreparedSecurityFindings {
596    findings: Vec<SecurityFinding>,
597    attack_surface: Option<Vec<SecurityAttackSurfaceEntry>>,
598}
599
600fn prepare_security_findings(
601    analysis: &mut SecurityAnalysisState,
602    runtime_report: Option<&RuntimeCoverageReport>,
603    root: &Path,
604    include_surface: bool,
605) -> PreparedSecurityFindings {
606    let mut findings: Vec<SecurityFinding> =
607        std::mem::take(&mut analysis.results.security_findings)
608            .into_iter()
609            .map(|f| relativize_finding(f, root))
610            .collect();
611    if let (Some(report), Some(modules), Some(files)) = (
612        runtime_report,
613        analysis.modules.as_ref(),
614        analysis.files.as_ref(),
615    ) {
616        apply_runtime_context(&mut findings, modules, files, root, report);
617    }
618    apply_security_severity(&mut findings);
619    sort_by_security_severity(&mut findings);
620    for finding in &mut findings {
621        finding.finding_id = security_finding_id(finding);
622    }
623    let (findings, attack_surface) = prepare_findings(findings, root, include_surface);
624    PreparedSecurityFindings {
625        findings,
626        attack_surface,
627    }
628}
629
630fn force_security_rules(config: &mut fallow_config::ResolvedConfig) {
631    // Respect explicit user severities; force the rules on when they are the
632    // default off so this dedicated command actually surfaces candidates.
633    if config.rules.security_client_server_leak == Severity::Off {
634        config.rules.security_client_server_leak = Severity::Warn;
635    }
636    if config.rules.security_sink == Severity::Off {
637        config.rules.security_sink = Severity::Warn;
638    }
639}
640
641fn security_output_config(
642    config: &fallow_config::ResolvedConfig,
643    configured_severity: Severity,
644    effective_severity: Severity,
645    configured_sink_severity: Severity,
646    effective_sink_severity: Severity,
647) -> SecurityOutputConfig {
648    let categories = config.security.categories.as_ref();
649    SecurityOutputConfig {
650        rules: SecurityOutputRulesConfig {
651            security_client_server_leak: SecurityRuleSeverityConfig {
652                configured: configured_severity,
653                effective: effective_severity,
654            },
655            security_sink: SecurityRuleSeverityConfig {
656                configured: configured_sink_severity,
657                effective: effective_sink_severity,
658            },
659        },
660        categories_include: categories.and_then(|categories| categories.include.clone()),
661        categories_exclude: categories.and_then(|categories| categories.exclude.clone()),
662    }
663}
664
665fn apply_changed_scope(opts: &SecurityOptions<'_>, results: &mut AnalysisResults) {
666    if let Some(git_ref) = opts.changed_since
667        && let Some(changed) = fallow_engine::get_changed_files(opts.root, git_ref)
668    {
669        fallow_engine::filter_results_by_changed_files(results, &changed);
670    }
671    if opts.use_shared_diff_index
672        && let Some(diff_index) = crate::report::ci::diff_filter::shared_diff_index()
673    {
674        crate::check::filtering::filter_results_by_diff(results, diff_index, opts.root);
675    }
676}
677
678fn apply_security_scopes(
679    opts: &SecurityOptions<'_>,
680    analysis: &mut SecurityAnalysisState,
681) -> Result<(), ExitCode> {
682    let ws_roots = crate::check::filtering::resolve_workspace_scope(
683        opts.root,
684        opts.workspace,
685        opts.changed_workspaces,
686        opts.output,
687    )?;
688    if let Some(ref roots) = ws_roots {
689        crate::check::filtering::filter_to_workspaces(&mut analysis.results, roots);
690    }
691
692    if !matches!(opts.gate, Some(SecurityGateMode::NewlyReachable)) {
693        apply_changed_scope(opts, &mut analysis.results);
694    }
695    filter_to_files(&mut analysis.results, opts.root, opts.file, opts.quiet);
696
697    Ok(())
698}
699
700fn apply_security_gate(
701    opts: &SecurityOptions<'_>,
702    config: &fallow_config::ResolvedConfig,
703    results: &mut AnalysisResults,
704) -> Result<Option<SecurityGateMode>, ExitCode> {
705    let Some(mode) = opts.gate else {
706        return Ok(None);
707    };
708
709    if matches!(mode, SecurityGateMode::NewlyReachable) {
710        retain_gate_newly_reachable(opts, config, results)?;
711        return Ok(Some(mode));
712    }
713
714    // Security gate (issue #886): narrow to the STRICT "new in changed lines"
715    // predicate and drive a dedicated exit code. The gate requires a diff
716    // source; a diff it cannot compute is a LOUD error (exit 2), never a green
717    // gate (a silent miss defeats a security gate).
718    let mut owned_gate_diff: Option<crate::report::ci::diff_filter::DiffIndex> = None;
719    let gate_diff: &crate::report::ci::diff_filter::DiffIndex =
720        if let Some(shared) = crate::report::ci::diff_filter::shared_diff_index() {
721            shared
722        } else if let Some(git_ref) = opts.changed_since {
723            match fallow_engine::try_get_changed_diff(opts.root, git_ref) {
724                Ok(text) => owned_gate_diff
725                    .insert(crate::report::ci::diff_filter::DiffIndex::from_unified_diff(&text)),
726                Err(err) => {
727                    return Err(emit_error(
728                        &format!(
729                            "fallow security --gate could not compute the diff for '{git_ref}': {}",
730                            err.describe()
731                        ),
732                        2,
733                        opts.output,
734                    ));
735                }
736            }
737        } else {
738            return Err(emit_error(
739                "fallow security --gate requires a diff source: --changed-since <ref>, \
740                     --diff-file <path>, or --diff-stdin.",
741                2,
742                opts.output,
743            ));
744        };
745    crate::check::filtering::retain_gate_new(results, gate_diff, opts.root);
746    Ok(Some(mode))
747}
748
749const SECURITY_BASE_SNAPSHOT_CACHE_VERSION: u8 = 1;
750const MAX_SECURITY_BASE_SNAPSHOT_CACHE_SIZE: usize = 8 * 1024 * 1024;
751
752#[derive(Debug, Clone)]
753struct SecurityKeySnapshot {
754    reachable: FxHashSet<String>,
755}
756
757struct SecurityBaseSnapshotCacheKey {
758    hash: u64,
759    base_sha: String,
760}
761
762#[derive(bitcode::Encode, bitcode::Decode)]
763struct CachedSecurityKeySnapshot {
764    version: u8,
765    cli_version: String,
766    key_hash: u64,
767    base_sha: String,
768    reachable: Vec<String>,
769}
770
771fn retain_gate_newly_reachable(
772    opts: &SecurityOptions<'_>,
773    config: &fallow_config::ResolvedConfig,
774    results: &mut AnalysisResults,
775) -> Result<(), ExitCode> {
776    let Some(base_ref) = opts.changed_since else {
777        return Err(emit_error(
778            "fallow security --gate newly-reachable requires --changed-since <ref>; \
779             --diff-file and --diff-stdin do not identify a base tree.",
780            2,
781            opts.output,
782        ));
783    };
784    let Some(base_sha) = git_rev_parse(opts.root, base_ref) else {
785        return Err(emit_error(
786            &format!(
787                "fallow security --gate newly-reachable could not resolve base ref '{base_ref}'."
788            ),
789            2,
790            opts.output,
791        ));
792    };
793    let cache_key = security_base_snapshot_cache_key(opts, config, &base_sha)?;
794    let base = if let Some(snapshot) = load_cached_security_base_snapshot(config, &cache_key) {
795        snapshot
796    } else {
797        let snapshot = compute_base_security_snapshot(opts, config, base_ref, &base_sha)?;
798        save_cached_security_base_snapshot(config, &cache_key, &snapshot);
799        snapshot
800    };
801    results.security_findings.retain(|finding| {
802        security_reachability_key(finding, opts.root)
803            .is_some_and(|key| !base.reachable.contains(&key))
804    });
805    Ok(())
806}
807
808fn compute_base_security_snapshot(
809    opts: &SecurityOptions<'_>,
810    config: &fallow_config::ResolvedConfig,
811    base_ref: &str,
812    base_sha: &str,
813) -> Result<SecurityKeySnapshot, ExitCode> {
814    let Some(worktree) = BaseWorktree::create(opts.root, base_ref, Some(base_sha)) else {
815        return Err(emit_error(
816            &format!("could not create a temporary worktree for base ref '{base_ref}'"),
817            2,
818            opts.output,
819        ));
820    };
821    let base_root = base_analysis_root(opts.root, worktree.path());
822    let current_config_path = opts
823        .config_path
824        .clone()
825        .or_else(|| fallow_config::FallowConfig::find_config_path(opts.root));
826    let mut base_config = load_config_for_analysis(
827        &base_root,
828        &current_config_path,
829        crate::ConfigLoadOptions {
830            output: opts.output,
831            no_cache: opts.no_cache,
832            threads: opts.threads,
833            production_override: None,
834            quiet: true,
835        },
836        ProductionAnalysis::DeadCode,
837    )?;
838    base_config.cache_dir =
839        remap_cache_dir_for_base_worktree(opts.root, &base_root, &config.cache_dir);
840    force_security_rules(&mut base_config);
841    let mut base_analysis = analyze_security_candidates(
842        &base_snapshot_security_options(opts, &base_root, &current_config_path),
843        &base_config,
844    )?;
845    scope_base_snapshot_to_workspaces(opts, &base_root, &mut base_analysis.results)?;
846    Ok(SecurityKeySnapshot {
847        reachable: security_reachable_keys(&base_analysis.results.security_findings, &base_root),
848    })
849}
850
851/// Build the quiet, non-gating `SecurityOptions` used to re-analyze the base
852/// worktree for the `--gate newly-reachable` snapshot.
853#[expect(
854    clippy::ref_option,
855    reason = "config_path mirrors the SecurityOptions.config_path field which is &Option<PathBuf>"
856)]
857fn base_snapshot_security_options<'a>(
858    opts: &SecurityOptions<'a>,
859    base_root: &'a Path,
860    config_path: &'a Option<PathBuf>,
861) -> SecurityOptions<'a> {
862    SecurityOptions {
863        root: base_root,
864        config_path,
865        output: opts.output,
866        no_cache: opts.no_cache,
867        threads: opts.threads,
868        quiet: true,
869        fail_on_issues: false,
870        sarif_file: None,
871        summary: false,
872        changed_since: None,
873        use_shared_diff_index: false,
874        workspace: opts.workspace,
875        changed_workspaces: None,
876        file: &[],
877        surface: false,
878        gate: None,
879        runtime_coverage: None,
880        min_invocations_hot: opts.min_invocations_hot,
881        explain: false,
882    }
883}
884
885/// Apply the run's `--workspace` scope to the base-snapshot results so the
886/// reachable-key set matches the head scope it is diffed against.
887fn scope_base_snapshot_to_workspaces(
888    opts: &SecurityOptions<'_>,
889    base_root: &Path,
890    results: &mut AnalysisResults,
891) -> Result<(), ExitCode> {
892    if let Some(ref roots) = crate::check::filtering::resolve_workspace_scope(
893        base_root,
894        opts.workspace,
895        None,
896        opts.output,
897    )? {
898        crate::check::filtering::filter_to_workspaces(results, roots);
899    }
900    Ok(())
901}
902
903fn security_reachable_keys(findings: &[SecurityFinding], root: &Path) -> FxHashSet<String> {
904    findings
905        .iter()
906        .filter_map(|finding| security_reachability_key(finding, root))
907        .collect()
908}
909
910fn security_reachability_key(finding: &SecurityFinding, root: &Path) -> Option<String> {
911    if !finding
912        .reachability
913        .as_ref()
914        .is_some_and(|reachability| reachability.reachable_from_entry)
915    {
916        return None;
917    }
918    let category = finding.category.as_deref().unwrap_or("none");
919    Some(format!(
920        "security-reach:{}:{}:{}",
921        relative_key(&finding.path, root),
922        security_kind_key(finding.kind),
923        category,
924    ))
925}
926
927fn security_kind_key(kind: SecurityFindingKind) -> &'static str {
928    match kind {
929        SecurityFindingKind::ClientServerLeak => "client-server-leak",
930        SecurityFindingKind::TaintedSink => "tainted-sink",
931    }
932}
933
934fn security_base_snapshot_cache_key(
935    opts: &SecurityOptions<'_>,
936    config: &fallow_config::ResolvedConfig,
937    base_sha: &str,
938) -> Result<SecurityBaseSnapshotCacheKey, ExitCode> {
939    let payload = serde_json::json!({
940        "cache_version": SECURITY_BASE_SNAPSHOT_CACHE_VERSION,
941        "cli_version": env!("CARGO_PKG_VERSION"),
942        "base_sha": base_sha,
943        "config_hash": format!("{:016x}", config.cache_config_hash),
944        "security_client_server_leak": format!("{:?}", config.rules.security_client_server_leak),
945        "security_sink": format!("{:?}", config.rules.security_sink),
946        "workspace": opts.workspace,
947        "changed_workspaces": opts.changed_workspaces,
948    });
949    let bytes = serde_json::to_vec(&payload).map_err(|err| {
950        emit_error(
951            &format!("failed to build security gate cache key: {err}"),
952            2,
953            opts.output,
954        )
955    })?;
956    Ok(SecurityBaseSnapshotCacheKey {
957        hash: xxh3_64(&bytes),
958        base_sha: base_sha.to_owned(),
959    })
960}
961
962fn security_base_snapshot_cache_dir(config: &fallow_config::ResolvedConfig) -> PathBuf {
963    config.cache_dir.join("cache").join(format!(
964        "security-base-v{SECURITY_BASE_SNAPSHOT_CACHE_VERSION}"
965    ))
966}
967
968fn security_base_snapshot_cache_file(
969    config: &fallow_config::ResolvedConfig,
970    key: &SecurityBaseSnapshotCacheKey,
971) -> PathBuf {
972    security_base_snapshot_cache_dir(config).join(format!("{:016x}.bin", key.hash))
973}
974
975fn ensure_security_base_snapshot_cache_dir(dir: &Path) -> Result<(), std::io::Error> {
976    std::fs::create_dir_all(dir)?;
977    let gitignore = dir.join(".gitignore");
978    if std::fs::read_to_string(&gitignore).ok().as_deref() != Some("*\n") {
979        std::fs::write(gitignore, "*\n")?;
980    }
981    Ok(())
982}
983
984fn load_cached_security_base_snapshot(
985    config: &fallow_config::ResolvedConfig,
986    key: &SecurityBaseSnapshotCacheKey,
987) -> Option<SecurityKeySnapshot> {
988    if config.no_cache {
989        return None;
990    }
991    let path = security_base_snapshot_cache_file(config, key);
992    let data = std::fs::read(path).ok()?;
993    if data.len() > MAX_SECURITY_BASE_SNAPSHOT_CACHE_SIZE {
994        return None;
995    }
996    let cached: CachedSecurityKeySnapshot = bitcode::decode(&data).ok()?;
997    if cached.version != SECURITY_BASE_SNAPSHOT_CACHE_VERSION
998        || cached.cli_version != env!("CARGO_PKG_VERSION")
999        || cached.key_hash != key.hash
1000        || cached.base_sha != key.base_sha
1001    {
1002        return None;
1003    }
1004    Some(SecurityKeySnapshot {
1005        reachable: cached.reachable.into_iter().collect(),
1006    })
1007}
1008
1009fn save_cached_security_base_snapshot(
1010    config: &fallow_config::ResolvedConfig,
1011    key: &SecurityBaseSnapshotCacheKey,
1012    snapshot: &SecurityKeySnapshot,
1013) {
1014    if config.no_cache {
1015        return;
1016    }
1017    let dir = security_base_snapshot_cache_dir(config);
1018    if ensure_security_base_snapshot_cache_dir(&dir).is_err() {
1019        return;
1020    }
1021    let mut reachable = snapshot.reachable.iter().cloned().collect::<Vec<_>>();
1022    reachable.sort_unstable();
1023    let data = bitcode::encode(&CachedSecurityKeySnapshot {
1024        version: SECURITY_BASE_SNAPSHOT_CACHE_VERSION,
1025        cli_version: env!("CARGO_PKG_VERSION").to_owned(),
1026        key_hash: key.hash,
1027        base_sha: key.base_sha.clone(),
1028        reachable,
1029    });
1030    let Ok(mut tmp) = tempfile::NamedTempFile::new_in(&dir) else {
1031        return;
1032    };
1033    if tmp.write_all(&data).is_err() {
1034        return;
1035    }
1036    let _ = tmp.persist(security_base_snapshot_cache_file(config, key));
1037}
1038
1039fn base_analysis_root(current_root: &Path, base_worktree_root: &Path) -> PathBuf {
1040    if current_root.is_absolute()
1041        && let Some(git_root) = crate::base_worktree::git_toplevel(current_root)
1042        && let Ok(relative) = current_root.strip_prefix(git_root)
1043    {
1044        return base_worktree_root.join(relative);
1045    }
1046    base_worktree_root.to_path_buf()
1047}
1048
1049fn remap_cache_dir_for_base_worktree(
1050    current_root: &Path,
1051    base_worktree_root: &Path,
1052    cache_dir: &Path,
1053) -> PathBuf {
1054    if cache_dir.is_absolute()
1055        && let Ok(relative) = cache_dir.strip_prefix(current_root)
1056    {
1057        return base_worktree_root.join(relative);
1058    }
1059    cache_dir.to_path_buf()
1060}
1061
1062struct SecurityAnalysisState {
1063    results: AnalysisResults,
1064    modules: Option<Vec<ModuleInfo>>,
1065    files: Option<Vec<DiscoveredFile>>,
1066    analysis_output: Option<fallow_engine::DeadCodeAnalysisArtifacts>,
1067}
1068
1069fn analyze_security_candidates(
1070    opts: &SecurityOptions<'_>,
1071    config: &fallow_config::ResolvedConfig,
1072) -> Result<SecurityAnalysisState, ExitCode> {
1073    if opts.runtime_coverage.is_none() {
1074        return fallow_engine::analyze(config)
1075            .map(|analysis| SecurityAnalysisState {
1076                results: analysis.results,
1077                modules: None,
1078                files: None,
1079                analysis_output: None,
1080            })
1081            .map_err(|err| emit_error(&format!("Analysis error: {err}"), 2, opts.output));
1082    }
1083
1084    fallow_engine::analyze_retaining_modules(config, true, true)
1085        .map(|mut output| {
1086            let modules = output.modules.take();
1087            let files = output.files.take();
1088            let results = output.results.clone();
1089            SecurityAnalysisState {
1090                results,
1091                modules,
1092                files,
1093                analysis_output: Some(output),
1094            }
1095        })
1096        .map_err(|err| emit_error(&format!("Analysis error: {err}"), 2, opts.output))
1097}
1098
1099fn security_runtime_report(
1100    opts: &SecurityOptions<'_>,
1101    analysis: &mut SecurityAnalysisState,
1102) -> Result<Option<RuntimeCoverageReport>, ExitCode> {
1103    let Some(path) = opts.runtime_coverage else {
1104        return Ok(None);
1105    };
1106    let (Some(modules), Some(files), Some(analysis_output)) = (
1107        analysis.modules.as_ref(),
1108        analysis.files.as_ref(),
1109        analysis.analysis_output.take(),
1110    ) else {
1111        return Ok(None);
1112    };
1113    analyze_security_runtime(opts, path, modules.clone(), files.clone(), analysis_output)
1114}
1115
1116fn analyze_security_runtime(
1117    opts: &SecurityOptions<'_>,
1118    path: &Path,
1119    modules: Vec<ModuleInfo>,
1120    files: Vec<DiscoveredFile>,
1121    analysis_output: fallow_engine::DeadCodeAnalysisArtifacts,
1122) -> Result<Option<RuntimeCoverageReport>, ExitCode> {
1123    let runtime_coverage = crate::health::coverage::prepare_options(
1124        path,
1125        opts.min_invocations_hot,
1126        None,
1127        None,
1128        opts.output,
1129    )?;
1130    let result = crate::health::execute_health_with_shared_parse(
1131        &security_runtime_health_options(opts, runtime_coverage),
1132        fallow_engine::HealthSharedParseData {
1133            files,
1134            modules,
1135            analysis_output: Some(analysis_output),
1136        },
1137    )?;
1138    Ok(result.report.runtime_coverage)
1139}
1140
1141/// Build the production-forced `HealthOptions` used to compute runtime coverage
1142/// context for security findings (complexity/hotspot/ownership all disabled).
1143fn security_runtime_health_options<'a>(
1144    opts: &SecurityOptions<'a>,
1145    runtime_coverage: fallow_engine::RuntimeCoverageOptions,
1146) -> HealthOptions<'a> {
1147    HealthOptions {
1148        root: opts.root,
1149        config_path: opts.config_path,
1150        output: opts.output,
1151        no_cache: opts.no_cache,
1152        threads: opts.threads,
1153        quiet: opts.quiet,
1154        thresholds: fallow_engine::HealthThresholdOverrides::default(),
1155        top: None,
1156        sort: fallow_engine::HealthSort::Cyclomatic,
1157        production: true,
1158        production_override: Some(true),
1159        changed_since: opts.changed_since,
1160        diff_index: None,
1161        use_shared_diff_index: opts.use_shared_diff_index,
1162        workspace: opts.workspace,
1163        changed_workspaces: opts.changed_workspaces,
1164        baseline: None,
1165        save_baseline: None,
1166        complexity: false,
1167        file_scores: false,
1168        coverage_gaps: false,
1169        config_activates_coverage_gaps: false,
1170        hotspots: false,
1171        ownership: false,
1172        ownership_emails: None,
1173        targets: false,
1174        css: false,
1175        force_full: false,
1176        score_only_output: false,
1177        enforce_coverage_gap_gate: false,
1178        effort: None,
1179        score: false,
1180        gates: fallow_engine::HealthGateOptions::default(),
1181        since: None,
1182        min_commits: None,
1183        explain: false,
1184        summary: false,
1185        save_snapshot: None,
1186        trend: false,
1187        coverage_inputs: fallow_engine::HealthCoverageInputs::default(),
1188        performance: false,
1189        runtime_coverage: Some(runtime_coverage),
1190        churn_file: None,
1191        complexity_breakdown: false,
1192        group_by: None,
1193    }
1194}
1195
1196#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1197struct RuntimeFunctionKey {
1198    path: String,
1199    function: String,
1200    line: u32,
1201}
1202
1203#[derive(Debug, Clone)]
1204struct FunctionSpan {
1205    key: RuntimeFunctionKey,
1206    end_line: u32,
1207}
1208
1209fn apply_runtime_context(
1210    findings: &mut Vec<SecurityFinding>,
1211    modules: &[ModuleInfo],
1212    files: &[fallow_types::discover::DiscoveredFile],
1213    root: &Path,
1214    report: &RuntimeCoverageReport,
1215) {
1216    let spans = function_spans(modules, files, root);
1217    let runtime = SecurityRuntimeIndex::new(report);
1218    let mut indexed = findings.drain(..).enumerate().collect::<Vec<_>>();
1219    for (_, finding) in &mut indexed {
1220        if !matches!(finding.kind, SecurityFindingKind::TaintedSink) {
1221            continue;
1222        }
1223        finding.runtime = runtime_context_for_finding(finding, &spans, &runtime);
1224    }
1225    indexed.sort_by(|(left_index, left), (right_index, right)| {
1226        runtime_rank(left)
1227            .cmp(&runtime_rank(right))
1228            .then_with(|| left_index.cmp(right_index))
1229    });
1230    findings.extend(indexed.into_iter().map(|(_, finding)| finding));
1231}
1232
1233fn function_spans(
1234    modules: &[ModuleInfo],
1235    files: &[fallow_types::discover::DiscoveredFile],
1236    root: &Path,
1237) -> Vec<FunctionSpan> {
1238    let paths_by_id = files
1239        .iter()
1240        .map(|file| (file.id, &file.path))
1241        .collect::<rustc_hash::FxHashMap<_, _>>();
1242    let mut spans = Vec::new();
1243    for module in modules {
1244        let Some(path) = paths_by_id.get(&module.file_id) else {
1245            continue;
1246        };
1247        let path = relative_key(path, root);
1248        for function in &module.complexity {
1249            spans.push(FunctionSpan {
1250                key: RuntimeFunctionKey {
1251                    path: path.clone(),
1252                    function: function.name.clone(),
1253                    line: function.line,
1254                },
1255                end_line: function.line.saturating_add(function.line_count),
1256            });
1257        }
1258    }
1259    spans
1260}
1261
1262struct SecurityRuntimeIndex {
1263    hot_paths: Vec<(RuntimeFunctionKey, u32, SecurityRuntimeContext)>,
1264    findings: rustc_hash::FxHashMap<RuntimeFunctionKey, SecurityRuntimeContext>,
1265}
1266
1267impl SecurityRuntimeIndex {
1268    fn new(report: &RuntimeCoverageReport) -> Self {
1269        let hot_paths = report
1270            .hot_paths
1271            .iter()
1272            .map(|hot| {
1273                (
1274                    runtime_hot_key(hot),
1275                    hot.end_line.max(hot.line),
1276                    SecurityRuntimeContext {
1277                        state: SecurityRuntimeState::RuntimeHot,
1278                        function: hot.function.clone(),
1279                        line: hot.line,
1280                        invocations: Some(hot.invocations),
1281                        stable_id: hot.stable_id.clone(),
1282                        evidence: Some(format!(
1283                            "production hot path observed with {} invocation{}",
1284                            hot.invocations,
1285                            crate::report::plural(hot.invocations as usize)
1286                        )),
1287                    },
1288                )
1289            })
1290            .collect();
1291        let findings = report
1292            .findings
1293            .iter()
1294            .map(runtime_finding_context)
1295            .collect();
1296        Self {
1297            hot_paths,
1298            findings,
1299        }
1300    }
1301}
1302
1303fn runtime_context_for_finding(
1304    finding: &SecurityFinding,
1305    spans: &[FunctionSpan],
1306    runtime: &SecurityRuntimeIndex,
1307) -> Option<SecurityRuntimeContext> {
1308    let path = path_key(&finding.path);
1309    let span = spans
1310        .iter()
1311        .filter(|span| {
1312            span.key.path == path && span.key.line <= finding.line && finding.line <= span.end_line
1313        })
1314        .min_by_key(|span| span.end_line.saturating_sub(span.key.line))?;
1315    if let Some((_, _, context)) = runtime.hot_paths.iter().find(|(key, end_line, _)| {
1316        key == &span.key && key.line <= finding.line && finding.line <= *end_line
1317    }) {
1318        return Some(context.clone());
1319    }
1320    runtime.findings.get(&span.key).cloned().or_else(|| {
1321        Some(SecurityRuntimeContext {
1322            state: SecurityRuntimeState::RuntimeUnknown,
1323            function: span.key.function.clone(),
1324            line: span.key.line,
1325            invocations: None,
1326            stable_id: None,
1327            evidence: Some("runtime coverage carried no matching function evidence".to_owned()),
1328        })
1329    })
1330}
1331
1332fn runtime_rank(finding: &SecurityFinding) -> u8 {
1333    match finding.runtime.as_ref().map(|runtime| runtime.state) {
1334        Some(SecurityRuntimeState::RuntimeHot) => 0,
1335        Some(SecurityRuntimeState::LowTraffic) => 1,
1336        None | Some(SecurityRuntimeState::RuntimeUnknown) => 2,
1337        Some(SecurityRuntimeState::CoverageUnavailable) => 3,
1338        Some(SecurityRuntimeState::RuntimeCold) => 4,
1339        Some(SecurityRuntimeState::NeverExecuted) => 5,
1340    }
1341}
1342
1343fn apply_security_severity(findings: &mut [SecurityFinding]) {
1344    for finding in findings {
1345        finding.severity = derive_security_severity(finding);
1346    }
1347}
1348
1349fn sort_by_security_severity(findings: &mut [SecurityFinding]) {
1350    findings.sort_by(compare_security_priority);
1351}
1352
1353fn compare_security_priority(left: &SecurityFinding, right: &SecurityFinding) -> Ordering {
1354    security_severity_rank(left.severity)
1355        .cmp(&security_severity_rank(right.severity))
1356        .then_with(|| runtime_rank(left).cmp(&runtime_rank(right)))
1357        .then_with(|| {
1358            right
1359                .reachability
1360                .as_ref()
1361                .is_some_and(|reach| reach.reachable_from_entry)
1362                .cmp(
1363                    &left
1364                        .reachability
1365                        .as_ref()
1366                        .is_some_and(|reach| reach.reachable_from_entry),
1367                )
1368        })
1369        .then_with(|| taint_rank(left).cmp(&taint_rank(right)))
1370        .then_with(|| security_blast_radius(right).cmp(&security_blast_radius(left)))
1371        .then_with(|| security_crosses_boundary(right).cmp(&security_crosses_boundary(left)))
1372        .then_with(|| left.dead_code.is_some().cmp(&right.dead_code.is_some()))
1373        .then_with(|| left.path.cmp(&right.path))
1374        .then_with(|| left.line.cmp(&right.line))
1375        .then_with(|| left.col.cmp(&right.col))
1376        .then_with(|| left.category.cmp(&right.category))
1377}
1378
1379fn taint_rank(finding: &SecurityFinding) -> u8 {
1380    match finding
1381        .reachability
1382        .as_ref()
1383        .and_then(|reach| reach.taint_confidence)
1384    {
1385        Some(TaintConfidence::ArgLevel) => 0,
1386        Some(TaintConfidence::ModuleLevel) => 1,
1387        None if finding.source_backed => 0,
1388        None if finding
1389            .reachability
1390            .as_ref()
1391            .is_some_and(|reach| reach.reachable_from_untrusted_source) =>
1392        {
1393            1
1394        }
1395        None => 2,
1396    }
1397}
1398
1399fn security_blast_radius(finding: &SecurityFinding) -> u32 {
1400    finding
1401        .reachability
1402        .as_ref()
1403        .map_or(0, |reach| reach.blast_radius)
1404}
1405
1406fn security_crosses_boundary(finding: &SecurityFinding) -> bool {
1407    finding
1408        .reachability
1409        .as_ref()
1410        .is_some_and(|reach| reach.crosses_boundary)
1411}
1412
1413const fn security_severity_rank(severity: SecuritySeverity) -> u8 {
1414    match severity {
1415        SecuritySeverity::High => 0,
1416        SecuritySeverity::Medium => 1,
1417        SecuritySeverity::Low => 2,
1418    }
1419}
1420
1421fn runtime_hot_key(hot: &RuntimeCoverageHotPath) -> RuntimeFunctionKey {
1422    RuntimeFunctionKey {
1423        path: path_key(&hot.path),
1424        function: hot.function.clone(),
1425        line: hot.line,
1426    }
1427}
1428
1429fn runtime_finding_context(
1430    finding: &RuntimeCoverageFinding,
1431) -> (RuntimeFunctionKey, SecurityRuntimeContext) {
1432    let state = match finding.verdict {
1433        RuntimeCoverageVerdict::SafeToDelete => SecurityRuntimeState::NeverExecuted,
1434        RuntimeCoverageVerdict::ReviewRequired if finding.invocations.unwrap_or(0) == 0 => {
1435            SecurityRuntimeState::RuntimeCold
1436        }
1437        RuntimeCoverageVerdict::LowTraffic => SecurityRuntimeState::LowTraffic,
1438        RuntimeCoverageVerdict::CoverageUnavailable | RuntimeCoverageVerdict::Unknown => {
1439            SecurityRuntimeState::CoverageUnavailable
1440        }
1441        RuntimeCoverageVerdict::ReviewRequired | RuntimeCoverageVerdict::Active => {
1442            SecurityRuntimeState::RuntimeUnknown
1443        }
1444    };
1445    (
1446        RuntimeFunctionKey {
1447            path: path_key(&finding.path),
1448            function: finding.function.clone(),
1449            line: finding.line,
1450        },
1451        SecurityRuntimeContext {
1452            state,
1453            function: finding.function.clone(),
1454            line: finding.line,
1455            invocations: finding.invocations,
1456            stable_id: finding.stable_id.clone(),
1457            evidence: Some(format!("runtime coverage verdict: {}", finding.verdict)),
1458        },
1459    )
1460}
1461
1462fn relative_key(path: &Path, root: &Path) -> String {
1463    path_key(path.strip_prefix(root).unwrap_or(path))
1464}
1465
1466fn path_key(path: &Path) -> String {
1467    path.to_string_lossy().replace('\\', "/")
1468}
1469
1470fn unresolved_callee_diagnostics(
1471    diagnostics: &[SecurityUnresolvedCalleeDiagnostic],
1472    root: &Path,
1473) -> Option<SecurityUnresolvedCalleeDiagnostics> {
1474    if diagnostics.is_empty() {
1475        return None;
1476    }
1477
1478    let mut sorted = diagnostics.to_vec();
1479    sorted.sort_by(|a, b| {
1480        a.path
1481            .cmp(&b.path)
1482            .then(a.line.cmp(&b.line))
1483            .then(a.col.cmp(&b.col))
1484            .then(a.reason.cmp(&b.reason))
1485            .then(a.expression_kind.cmp(&b.expression_kind))
1486    });
1487
1488    let sampled = sorted
1489        .iter()
1490        .take(UNRESOLVED_CALLEE_SAMPLE_LIMIT)
1491        .map(|diagnostic| SecurityUnresolvedCalleeSample {
1492            path: relative_key(&diagnostic.path, root),
1493            line: diagnostic.line,
1494            col: diagnostic.col,
1495            reason: diagnostic.reason,
1496            expression_kind: diagnostic.expression_kind,
1497        })
1498        .collect();
1499
1500    let mut by_file: BTreeMap<String, usize> = BTreeMap::new();
1501    let mut by_reason: BTreeMap<fallow_types::extract::SkippedSecurityCalleeReason, usize> =
1502        BTreeMap::new();
1503    for diagnostic in &sorted {
1504        *by_file
1505            .entry(relative_key(&diagnostic.path, root))
1506            .or_insert(0) += 1;
1507        *by_reason.entry(diagnostic.reason).or_insert(0) += 1;
1508    }
1509
1510    let mut top_files: Vec<_> = by_file
1511        .into_iter()
1512        .map(|(path, count)| SecurityUnresolvedCalleeTopFile { path, count })
1513        .collect();
1514    top_files.sort_by(|a, b| b.count.cmp(&a.count).then(a.path.cmp(&b.path)));
1515    top_files.truncate(UNRESOLVED_CALLEE_TOP_FILES_LIMIT);
1516
1517    let mut by_reason: Vec<_> = by_reason
1518        .into_iter()
1519        .map(|(reason, count)| SecurityUnresolvedCalleeReasonCount { reason, count })
1520        .collect();
1521    by_reason.sort_by(|a, b| b.count.cmp(&a.count).then(a.reason.cmp(&b.reason)));
1522
1523    Some(SecurityUnresolvedCalleeDiagnostics {
1524        sampled,
1525        top_files,
1526        by_reason,
1527        sample_limit: UNRESOLVED_CALLEE_SAMPLE_LIMIT,
1528        top_files_limit: UNRESOLVED_CALLEE_TOP_FILES_LIMIT,
1529    })
1530}
1531
1532fn filter_to_files(results: &mut AnalysisResults, root: &Path, files: &[PathBuf], quiet: bool) {
1533    if files.is_empty() {
1534        return;
1535    }
1536
1537    let resolved_files: Vec<PathBuf> = files
1538        .iter()
1539        .map(|path| {
1540            if crate::path_util::is_absolute_path_any_platform(path) {
1541                path.clone()
1542            } else {
1543                root.join(path)
1544            }
1545        })
1546        .collect();
1547
1548    if !quiet {
1549        for (original, resolved) in files.iter().zip(&resolved_files) {
1550            if !resolved.exists() {
1551                eprintln!(
1552                    "Warning: --file '{}' (resolved to '{}') was not found in the project",
1553                    original.display(),
1554                    resolved.display()
1555                );
1556            }
1557        }
1558    }
1559
1560    let file_set: rustc_hash::FxHashSet<PathBuf> = resolved_files.into_iter().collect();
1561    fallow_engine::filter_results_by_changed_files(results, &file_set);
1562}
1563
1564fn prepare_findings(
1565    findings: Vec<SecurityFinding>,
1566    root: &Path,
1567    include_surface: bool,
1568) -> (
1569    Vec<SecurityFinding>,
1570    Option<Vec<SecurityAttackSurfaceEntry>>,
1571) {
1572    let mut findings: Vec<SecurityFinding> = findings
1573        .into_iter()
1574        .map(|f| {
1575            let mut f = relativize_finding(f, root);
1576            f.finding_id = security_finding_id(&f);
1577            f
1578        })
1579        .collect();
1580    let attack_surface = include_surface.then(|| {
1581        findings
1582            .iter()
1583            .filter_map(|finding| finding.attack_surface.clone())
1584            .collect()
1585    });
1586    for finding in &mut findings {
1587        finding.attack_surface = None;
1588    }
1589    (findings, attack_surface)
1590}
1591
1592/// Rewrite a finding's anchor + every trace hop path to be project-root-relative
1593/// (forward-slash normalization happens at serialize time via `serde_path`).
1594fn relativize_finding(mut finding: SecurityFinding, root: &Path) -> SecurityFinding {
1595    finding.path = relativize(&finding.path, root);
1596    for hop in &mut finding.trace {
1597        hop.path = relativize(&hop.path, root);
1598    }
1599    if let Some(reachability) = &mut finding.reachability {
1600        for hop in &mut reachability.untrusted_source_trace {
1601            hop.path = relativize(&hop.path, root);
1602        }
1603    }
1604    finding.candidate.sink.path = relativize(&finding.candidate.sink.path, root);
1605    if let Some(flow) = &mut finding.taint_flow {
1606        flow.source.path = relativize(&flow.source.path, root);
1607        flow.sink.path = relativize(&flow.sink.path, root);
1608    }
1609    if let Some(surface) = &mut finding.attack_surface {
1610        surface.source.path = relativize(&surface.source.path, root);
1611        surface.sink.path = relativize(&surface.sink.path, root);
1612        for hop in &mut surface.path {
1613            hop.path = relativize(&hop.path, root);
1614        }
1615        for control in &mut surface.defensive_boundary.controls {
1616            control.path = relativize(&control.path, root);
1617        }
1618    }
1619    finding
1620}
1621
1622fn relativize(path: &Path, root: &Path) -> PathBuf {
1623    path.strip_prefix(root)
1624        .map_or_else(|_| path.to_path_buf(), Path::to_path_buf)
1625}
1626
1627/// JSON: the `SecurityOutput` envelope, pretty-printed.
1628#[must_use]
1629pub fn render_json(output: &SecurityOutput) -> String {
1630    let Ok(value) = fallow_output::serialize_security_json_output(
1631        output.clone(),
1632        crate::output_runtime::current_root_envelope_mode(),
1633        crate::output_runtime::telemetry_analysis_run_id().as_deref(),
1634    ) else {
1635        return "{\"error\":\"failed to serialize security output\"}".to_owned();
1636    };
1637    serde_json::to_string_pretty(&value)
1638        .unwrap_or_else(|_| "{\"error\":\"failed to serialize security output\"}".to_owned())
1639}
1640
1641/// JSON summary: compact aggregate payload without per-finding arrays.
1642#[must_use]
1643pub fn render_json_summary(output: &SecurityOutput) -> String {
1644    let Ok(value) = fallow_output::serialize_security_summary_json_output(
1645        output,
1646        crate::output_runtime::current_root_envelope_mode(),
1647        None,
1648    ) else {
1649        return "{\"error\":\"failed to serialize security summary output\"}".to_owned();
1650    };
1651    serde_json::to_string_pretty(&value).unwrap_or_else(|_| {
1652        "{\"error\":\"failed to serialize security summary output\"}".to_owned()
1653    })
1654}
1655
1656fn render_survivors_output(
1657    output_format: OutputFormat,
1658    output: &SecuritySurvivorsOutput,
1659) -> String {
1660    match output_format {
1661        OutputFormat::Json => render_survivors_json(output),
1662        _ => render_survivors_human(output),
1663    }
1664}
1665
1666#[must_use]
1667pub fn render_survivors_json(output: &SecuritySurvivorsOutput) -> String {
1668    let Ok(value) = fallow_output::serialize_security_survivors_json_output(
1669        output.clone(),
1670        crate::output_runtime::current_root_envelope_mode(),
1671    ) else {
1672        return "{\"error\":\"failed to serialize security survivors output\"}".to_owned();
1673    };
1674    serde_json::to_string_pretty(&value).unwrap_or_else(|_| {
1675        "{\"error\":\"failed to serialize security survivors output\"}".to_owned()
1676    })
1677}
1678
1679#[must_use]
1680fn render_survivors_human(output: &SecuritySurvivorsOutput) -> String {
1681    use crate::report::plural;
1682    use std::fmt::Write as _;
1683
1684    let mut out = String::new();
1685    let _ = writeln!(
1686        out,
1687        "Security survivors: {} verifier-retained candidate{}.",
1688        output.summary.survivors,
1689        plural(output.summary.survivors)
1690    );
1691    let _ = writeln!(
1692        out,
1693        "Verdicts: {}/{} candidates covered, {} dismissed.",
1694        output.summary.verdicts, output.summary.candidates, output.summary.dismissed
1695    );
1696    if output.summary.needs_human_review > 0 {
1697        let _ = writeln!(
1698            out,
1699            "Needs human review: {} candidate{}.",
1700            output.summary.needs_human_review,
1701            plural(output.summary.needs_human_review)
1702        );
1703    }
1704    if output.summary.unverdicted > 0 {
1705        let _ = writeln!(
1706            out,
1707            "Unreviewed candidates: {} candidate{}.",
1708            output.summary.unverdicted,
1709            plural(output.summary.unverdicted)
1710        );
1711    }
1712    out.push_str(
1713        "Retained and human-review rows are verifier dispositions, not vulnerabilities proven by fallow.\n",
1714    );
1715    if output.summary.unverdicted > 0 {
1716        out.push_str("Unreviewed candidates have no verifier disposition yet.\n");
1717    }
1718
1719    if output.survivors.is_empty() && output.needs_human_review.is_empty() {
1720        if output.summary.unverdicted > 0 {
1721            out.push_str("\nNo retained or human-review details to show yet.\n");
1722        } else {
1723            out.push_str("\nNo retained candidate details to show.\n");
1724        }
1725        return out;
1726    }
1727
1728    push_survivor_group(&mut out, "Survivors", &output.survivors);
1729    push_survivor_group(&mut out, "Needs human review", &output.needs_human_review);
1730    out
1731}
1732
1733fn push_survivor_group(
1734    out: &mut String,
1735    title: &str,
1736    survivors: &BTreeMap<String, SecuritySurvivor>,
1737) {
1738    use std::fmt::Write as _;
1739
1740    if survivors.is_empty() {
1741        return;
1742    }
1743    let _ = writeln!(out, "\n{title}:");
1744    for survivor in survivors.values() {
1745        let path = survivor.candidate.path.to_string_lossy().replace('\\', "/");
1746        let line = survivor.candidate.line;
1747        let category = survivor
1748            .candidate
1749            .category
1750            .as_deref()
1751            .unwrap_or_else(|| security_kind_key(survivor.candidate.kind));
1752        let _ = writeln!(
1753            out,
1754            "- {}:{} ({}) [{}]",
1755            path, line, category, survivor.finding_id
1756        );
1757        if let Some(reason) = survivor.reason.as_ref().or(survivor.rationale.as_ref()) {
1758            let _ = writeln!(out, "  reason: {reason}");
1759        }
1760        if let Some(impact) = &survivor.impact {
1761            let _ = writeln!(out, "  impact: {impact}");
1762        }
1763        if let Some(fix_direction) = &survivor.fix_direction {
1764            let _ = writeln!(out, "  fix direction: {fix_direction}");
1765        }
1766        out.push_str("  Next: review the original candidate evidence before editing code.\n");
1767    }
1768}
1769
1770fn build_blind_spots_output(output: &SecurityOutput) -> SecurityBlindSpotsOutput {
1771    let diagnostics = output.unresolved_callee_diagnostics.as_ref();
1772    let groups = diagnostics
1773        .map(group_blind_spot_samples)
1774        .unwrap_or_default();
1775    let sampled_callee_sites = diagnostics.map_or(0, |diagnostics| diagnostics.sampled.len());
1776    let unresolved_callee_sites =
1777        diagnostics.map_or(output.unresolved_callee_sites, |diagnostics| {
1778            diagnostics
1779                .by_reason
1780                .iter()
1781                .map(|reason| reason.count)
1782                .sum()
1783        });
1784
1785    SecurityBlindSpotsOutput {
1786        schema_version: SecurityBlindSpotsSchemaVersion::V1,
1787        version: output.version.clone(),
1788        elapsed_ms: output.elapsed_ms,
1789        summary: SecurityBlindSpotsSummary {
1790            unresolved_edge_files: output.unresolved_edge_files,
1791            unresolved_callee_sites,
1792            sampled_callee_sites,
1793        },
1794        groups,
1795    }
1796}
1797
1798fn group_blind_spot_samples(
1799    diagnostics: &SecurityUnresolvedCalleeDiagnostics,
1800) -> Vec<SecurityBlindSpotGroup> {
1801    let mut groups: BTreeMap<
1802        (
1803            fallow_types::extract::SkippedSecurityCalleeReason,
1804            fallow_types::extract::SkippedSecurityCalleeExpressionKind,
1805        ),
1806        BTreeMap<String, usize>,
1807    > = BTreeMap::new();
1808
1809    for sample in &diagnostics.sampled {
1810        let files = groups
1811            .entry((sample.reason, sample.expression_kind))
1812            .or_default();
1813        *files.entry(sample.path.clone()).or_insert(0) += 1;
1814    }
1815
1816    let mut groups: Vec<SecurityBlindSpotGroup> = groups
1817        .into_iter()
1818        .map(|((reason, expression_kind), files)| {
1819            let sampled_count = files.values().sum();
1820            let mut files: Vec<SecurityBlindSpotFile> = files
1821                .into_iter()
1822                .map(|(path, sampled_count)| SecurityBlindSpotFile {
1823                    path,
1824                    sampled_count,
1825                })
1826                .collect();
1827            files.sort_by(|a, b| {
1828                b.sampled_count
1829                    .cmp(&a.sampled_count)
1830                    .then_with(|| a.path.cmp(&b.path))
1831            });
1832            SecurityBlindSpotGroup {
1833                reason,
1834                expression_kind,
1835                sampled_count,
1836                files,
1837                suggestion: blind_spot_suggestion(reason).to_owned(),
1838            }
1839        })
1840        .collect();
1841
1842    groups.sort_by(|a, b| {
1843        b.sampled_count
1844            .cmp(&a.sampled_count)
1845            .then_with(|| {
1846                unresolved_callee_reason_label(a.reason)
1847                    .cmp(unresolved_callee_reason_label(b.reason))
1848            })
1849            .then_with(|| {
1850                unresolved_callee_expression_label(a.expression_kind)
1851                    .cmp(unresolved_callee_expression_label(b.expression_kind))
1852            })
1853    });
1854    groups
1855}
1856
1857fn render_blind_spots_output(
1858    output_format: OutputFormat,
1859    output: &SecurityBlindSpotsOutput,
1860) -> String {
1861    match output_format {
1862        OutputFormat::Json => render_blind_spots_json(output),
1863        _ => render_blind_spots_human(output),
1864    }
1865}
1866
1867#[must_use]
1868pub fn render_blind_spots_json(output: &SecurityBlindSpotsOutput) -> String {
1869    let Ok(value) = fallow_output::serialize_security_blind_spots_json_output(
1870        output.clone(),
1871        crate::output_runtime::current_root_envelope_mode(),
1872    ) else {
1873        return "{\"error\":\"failed to serialize security blind-spots output\"}".to_owned();
1874    };
1875    serde_json::to_string_pretty(&value).unwrap_or_else(|_| {
1876        "{\"error\":\"failed to serialize security blind-spots output\"}".to_owned()
1877    })
1878}
1879
1880#[must_use]
1881fn render_blind_spots_human(output: &SecurityBlindSpotsOutput) -> String {
1882    use crate::report::plural;
1883    use std::fmt::Write as _;
1884
1885    let mut out = String::new();
1886    let callee_count = output.summary.unresolved_callee_sites;
1887    let edge_count = output.summary.unresolved_edge_files;
1888    if callee_count == 0 && edge_count == 0 {
1889        out.push_str("Security blind spots: no unresolved security edges or callees found.\n");
1890        return out;
1891    }
1892
1893    let _ = writeln!(
1894        out,
1895        "Security blind spots: {callee_count} unresolved callee{} and {edge_count} unresolved client import edge{}.",
1896        plural(callee_count),
1897        plural(edge_count)
1898    );
1899    out.push_str("A non-zero blind-spot count means fallow may have missed security candidates behind dynamic code shapes.\n");
1900
1901    for group in &output.groups {
1902        let reason = unresolved_callee_reason_label(group.reason);
1903        let expression = unresolved_callee_expression_label(group.expression_kind);
1904        let _ = writeln!(
1905            out,
1906            "\n{} Blind spot: {reason} / {expression}, {} sampled site{}.",
1907            "[I]".blue().bold(),
1908            group.sampled_count,
1909            plural(group.sampled_count)
1910        );
1911        for file in group.files.iter().take(3) {
1912            let _ = writeln!(out, "  {} ({})", file.path, file.sampled_count);
1913        }
1914        let _ = writeln!(out, "  Next: {}", group.suggestion);
1915    }
1916
1917    out
1918}
1919
1920fn unresolved_callee_expression_label(
1921    expression_kind: fallow_types::extract::SkippedSecurityCalleeExpressionKind,
1922) -> &'static str {
1923    match expression_kind {
1924        fallow_types::extract::SkippedSecurityCalleeExpressionKind::ComputedMemberExpression => {
1925            "computed-member"
1926        }
1927        fallow_types::extract::SkippedSecurityCalleeExpressionKind::Identifier => "identifier",
1928        fallow_types::extract::SkippedSecurityCalleeExpressionKind::StaticMemberExpression => {
1929            "member-expression"
1930        }
1931        fallow_types::extract::SkippedSecurityCalleeExpressionKind::Other => "other",
1932    }
1933}
1934
1935fn blind_spot_suggestion(
1936    reason: fallow_types::extract::SkippedSecurityCalleeReason,
1937) -> &'static str {
1938    match reason {
1939        fallow_types::extract::SkippedSecurityCalleeReason::ComputedMember => {
1940            "inspect computed property names or convert hot sinks to explicit calls."
1941        }
1942        fallow_types::extract::SkippedSecurityCalleeReason::DynamicDispatch => {
1943            "inspect dynamic dispatch targets and add a narrow wrapper or catalogue shape if the sink is real."
1944        }
1945        fallow_types::extract::SkippedSecurityCalleeReason::UnsupportedAssignmentObject => {
1946            "inspect assignment targets and simplify the object shape if security sink calls are hidden there."
1947        }
1948    }
1949}
1950
1951fn write_sarif_file(output: &SecurityOutput, path: &Path) -> Result<(), String> {
1952    if let Some(parent) = path.parent()
1953        && !parent.as_os_str().is_empty()
1954    {
1955        std::fs::create_dir_all(parent).map_err(|err| {
1956            format!(
1957                "Failed to create directory for SARIF file {}: {err}",
1958                path.display()
1959            )
1960        })?;
1961    }
1962    std::fs::write(path, render_sarif(output))
1963        .map_err(|err| format!("Failed to write SARIF file {}: {err}", path.display()))
1964}
1965
1966/// One-line gate verdict header. Leads with the ACTION ("REVIEW REQUIRED") and
1967/// immediately qualifies with the candidate framing, so a human never reads the
1968/// gate as "fallow confirmed a vulnerability". The wire `verdict` token stays
1969/// `fail`; only this human prose says "REVIEW REQUIRED".
1970fn gate_human_header(gate: &SecurityGate) -> String {
1971    use crate::report::plural;
1972    let checked = match gate.mode {
1973        SecurityGateMode::New => "in changed lines",
1974        SecurityGateMode::NewlyReachable => "newly reachable from entry points",
1975    };
1976    match gate.verdict {
1977        SecurityGateVerdict::Fail => format!(
1978            "Gate: REVIEW REQUIRED, {} new security item{} {checked}. fallow has not confirmed a vulnerability.",
1979            gate.new_count,
1980            plural(gate.new_count),
1981        ),
1982        SecurityGateVerdict::Pass => {
1983            format!("Gate: PASS, no new security items {checked}.")
1984        }
1985    }
1986}
1987
1988fn unresolved_callee_human_hint(output: &SecurityOutput) -> Option<String> {
1989    let diagnostics = output.unresolved_callee_diagnostics.as_ref()?;
1990    let top_reason = diagnostics.by_reason.first()?;
1991    let top_file = diagnostics.top_files.first()?;
1992    Some(format!(
1993        "Most unresolved callees: {} in {}.",
1994        unresolved_callee_reason_label(top_reason.reason),
1995        top_file.path
1996    ))
1997}
1998
1999fn unresolved_callee_reason_label(
2000    reason: fallow_types::extract::SkippedSecurityCalleeReason,
2001) -> &'static str {
2002    match reason {
2003        fallow_types::extract::SkippedSecurityCalleeReason::ComputedMember => "computed-member",
2004        fallow_types::extract::SkippedSecurityCalleeReason::DynamicDispatch => "dynamic-dispatch",
2005        fallow_types::extract::SkippedSecurityCalleeReason::UnsupportedAssignmentObject => {
2006            "unsupported-assignment-object"
2007        }
2008    }
2009}
2010
2011#[must_use]
2012fn render_human_summary(output: &SecurityOutput) -> String {
2013    use crate::report::plural;
2014    use std::fmt::Write as _;
2015
2016    let mut out = String::new();
2017    if let Some(gate) = &output.gate {
2018        out.push_str(&gate_human_header(gate));
2019        out.push('\n');
2020    }
2021    let count = output.security_findings.len();
2022    if count == 0 {
2023        out.push_str("Security review: no items to check in the scanned code.\n");
2024    } else {
2025        let _ = writeln!(
2026            out,
2027            "Security review: {count} item{} to check. These are unverified security candidates, not confirmed vulnerabilities.",
2028            plural(count),
2029        );
2030        out.push_str(
2031            "Next: check whether the listed code can run with unsafe input, secrets, or settings, and whether anything blocks the risk.\n",
2032        );
2033    }
2034    if output.unresolved_edge_files > 0 {
2035        let n = output.unresolved_edge_files;
2036        let verb = if n == 1 { "uses" } else { "use" };
2037        let _ = writeln!(
2038            out,
2039            "Blind spot: {n} client file{} {verb} dynamic imports that fallow could not follow.",
2040            plural(n)
2041        );
2042    }
2043    if output.unresolved_callee_sites > 0 {
2044        let n = output.unresolved_callee_sites;
2045        let verb = if n == 1 { "uses" } else { "use" };
2046        let _ = writeln!(
2047            out,
2048            "Blind spot: {n} call site{} {verb} code patterns that fallow could not resolve.",
2049            plural(n)
2050        );
2051        if let Some(hint) = unresolved_callee_human_hint(output) {
2052            let _ = writeln!(out, "{hint}");
2053        }
2054    }
2055    out
2056}
2057
2058/// Human output. Frames findings as candidates and states the next human action
2059/// per finding; surfaces the unresolved-edge blind spot as a counted line.
2060#[must_use]
2061#[expect(
2062    clippy::format_push_string,
2063    reason = "small report renderer; readability over avoiding the extra allocation"
2064)]
2065pub fn render_human(output: &SecurityOutput) -> String {
2066    use crate::report::plural;
2067
2068    let mut out = String::new();
2069    push_human_gate(&mut out, output);
2070    let count = output.security_findings.len();
2071    out.push_str(&format!("Security review: {count} item{}", plural(count)));
2072    if count == 0 {
2073        out.push_str(" to check in the scanned code.\n");
2074    } else {
2075        out.push_str(" to check.\n");
2076        out.push_str(
2077            "These are unverified security candidates, not confirmed vulnerabilities. Check whether the listed code can run with unsafe input, secrets, or settings, and whether anything blocks the risk.\n",
2078        );
2079    }
2080    out.push('\n');
2081
2082    if output.security_findings.is_empty() {
2083        out.push_str("No security details to show.\n");
2084    } else {
2085        push_human_findings(&mut out, &output.security_findings);
2086    }
2087
2088    push_human_blind_spots(&mut out, output);
2089
2090    out.push_str(&format!(
2091        "\nResult: {count} security item{} to check.",
2092        plural(count),
2093    ));
2094    if count > 0 {
2095        out.push_str(" Review the listed evidence and trace before changing code.");
2096    }
2097    out.push('\n');
2098    out
2099}
2100
2101fn push_human_gate(out: &mut String, output: &SecurityOutput) {
2102    if let Some(gate) = &output.gate {
2103        out.push_str(&gate_human_header(gate));
2104        out.push_str("\n\n");
2105    }
2106}
2107
2108fn push_human_findings(out: &mut String, findings: &[SecurityFinding]) {
2109    for finding in findings {
2110        push_human_finding(out, finding);
2111    }
2112}
2113
2114fn push_human_finding(out: &mut String, finding: &SecurityFinding) {
2115    use std::fmt::Write as _;
2116
2117    push_human_finding_header(out, finding);
2118    let _ = writeln!(out, "    evidence: {}", finding.evidence);
2119    if let Some(hint) = dead_code_hint(finding) {
2120        let _ = writeln!(out, "    dead-code: {hint}");
2121    }
2122    if let Some(runtime) = finding.runtime.as_ref() {
2123        let _ = writeln!(out, "    runtime: {}", runtime_hint_text(runtime));
2124    }
2125    push_human_reachability(out, finding);
2126    push_human_import_trace(out, finding);
2127    push_human_next_step(out, finding);
2128    out.push('\n');
2129}
2130
2131fn push_human_finding_header(out: &mut String, finding: &SecurityFinding) {
2132    use colored::Colorize;
2133    use std::fmt::Write as _;
2134
2135    let kind = security_finding_label(finding);
2136    let (glyph, label) = human_severity_marker(finding.severity);
2137    let _ = writeln!(
2138        out,
2139        "{} {label} {kind}  {}:{}",
2140        glyph,
2141        finding.path.to_string_lossy().replace('\\', "/").bold(),
2142        finding.line,
2143    );
2144}
2145
2146fn push_human_reachability(out: &mut String, finding: &SecurityFinding) {
2147    use std::fmt::Write as _;
2148
2149    let Some(reach) = finding.reachability.as_ref() else {
2150        return;
2151    };
2152    let entry = if reach.reachable_from_entry {
2153        "reachable from a runtime entry point"
2154    } else {
2155        "not reached from any runtime entry point"
2156    };
2157    let boundary = if reach.crosses_boundary {
2158        "; crosses an architecture boundary"
2159    } else {
2160        ""
2161    };
2162    let _ = writeln!(
2163        out,
2164        "    code path: {entry} (blast radius {}){boundary}",
2165        reach.blast_radius,
2166    );
2167    if reach.reachable_from_untrusted_source {
2168        push_human_untrusted_trace(out, finding);
2169    }
2170}
2171
2172fn push_human_untrusted_trace(out: &mut String, finding: &SecurityFinding) {
2173    use std::fmt::Write as _;
2174
2175    let Some(reach) = finding.reachability.as_ref() else {
2176        return;
2177    };
2178    let hops = reach.untrusted_source_hop_count.unwrap_or(0);
2179    let _ = writeln!(
2180        out,
2181        "    input path: this module is reachable from a module that receives \
2182         untrusted input via {hops} import hop{}",
2183        crate::report::plural(hops as usize),
2184    );
2185    if !reach.untrusted_source_trace.is_empty() {
2186        out.push_str("    input import trace:\n");
2187        for hop in &reach.untrusted_source_trace {
2188            let _ = writeln!(
2189                out,
2190                "      {}:{} ({})",
2191                hop.path.to_string_lossy().replace('\\', "/"),
2192                hop.line,
2193                hop_role_label(hop.role),
2194            );
2195        }
2196    }
2197}
2198
2199fn push_human_import_trace(out: &mut String, finding: &SecurityFinding) {
2200    use std::fmt::Write as _;
2201
2202    if finding.trace.is_empty() {
2203        return;
2204    }
2205    out.push_str("    import trace:\n");
2206    for hop in &finding.trace {
2207        let _ = writeln!(
2208            out,
2209            "      {}:{} ({})",
2210            hop.path.to_string_lossy().replace('\\', "/"),
2211            hop.line,
2212            hop_role_label(hop.role),
2213        );
2214    }
2215}
2216
2217fn push_human_next_step(out: &mut String, finding: &SecurityFinding) {
2218    if is_server_only_leak(finding) {
2219        out.push_str(
2220            "    Next: check whether this server-only code is meant to run on the client. \
2221             If it is pulled in only through next/dynamic(..., { ssr: false }), type-only, \
2222             or removed at build time, mark it as a false positive.\n",
2223        );
2224    } else if matches!(finding.kind, SecurityFindingKind::ClientServerLeak) {
2225        out.push_str(
2226            "    Next: check whether this import can ship a secret to the browser. If \
2227             it is type-only, server-only, or removed at build time, mark it as a false \
2228             positive.\n",
2229        );
2230    } else if finding.dead_code.is_some() {
2231        out.push_str(
2232            "    Next: first verify the dead-code finding. If the code is safe to \
2233             remove, delete it. Otherwise check and harden the risky call.\n",
2234        );
2235    } else {
2236        out.push_str(
2237            "    Next: check whether unsafe input, secrets, or settings can reach this \
2238             risky call without a safe guard. If not, mark it as a false positive.\n",
2239        );
2240    }
2241}
2242
2243fn push_human_blind_spots(out: &mut String, output: &SecurityOutput) {
2244    use crate::report::plural;
2245    use std::fmt::Write as _;
2246
2247    if output.unresolved_edge_files > 0 {
2248        let n = output.unresolved_edge_files;
2249        let verb = if n == 1 { "uses" } else { "use" };
2250        let _ = writeln!(
2251            out,
2252            "{} Blind spot: {n} client file{} {verb} dynamic imports that fallow could not \
2253             follow. Code behind those imports may be missing from this report.",
2254            "[I]".blue().bold(),
2255            plural(n),
2256        );
2257    }
2258
2259    if output.unresolved_callee_sites > 0 {
2260        let n = output.unresolved_callee_sites;
2261        let verb = if n == 1 { "uses" } else { "use" };
2262        let _ = writeln!(
2263            out,
2264            "{} Blind spot: {n} call site{} {verb} code patterns that fallow could not resolve, \
2265             such as dynamic dispatch, computed members, or aliased bindings.",
2266            "[I]".blue().bold(),
2267            plural(n),
2268        );
2269        if let Some(hint) = unresolved_callee_human_hint(output) {
2270            let _ = writeln!(out, "    {hint}");
2271        }
2272    }
2273}
2274
2275/// Render the human-facing label for a finding. The secret-leak
2276/// `ClientServerLeak` keeps its bespoke kebab kind; the server-only variant uses
2277/// its own kebab label so a reader tells the two apart; `TaintedSink` uses the
2278/// catalogue title plus the CWE number carried on the finding.
2279fn security_finding_label(finding: &SecurityFinding) -> String {
2280    match finding.kind {
2281        SecurityFindingKind::ClientServerLeak if is_server_only_leak(finding) => {
2282            "server-only-import".to_string()
2283        }
2284        SecurityFindingKind::ClientServerLeak => "client-server-leak".to_string(),
2285        SecurityFindingKind::TaintedSink => {
2286            let title = finding
2287                .category
2288                .as_deref()
2289                .and_then(security_catalogue_title)
2290                .or(finding.category.as_deref())
2291                .unwrap_or("tainted-sink");
2292            match finding.cwe {
2293                Some(cwe) => format!("{title} (CWE-{cwe})"),
2294                None => title.to_string(),
2295            }
2296        }
2297    }
2298}
2299
2300fn human_severity_marker(severity: SecuritySeverity) -> (colored::ColoredString, &'static str) {
2301    use colored::Colorize;
2302    match severity {
2303        SecuritySeverity::High => ("[H]".red().bold(), "high"),
2304        SecuritySeverity::Medium => ("[M]".yellow().bold(), "medium"),
2305        SecuritySeverity::Low => ("[L]".blue().bold(), "low"),
2306    }
2307}
2308
2309fn dead_code_hint(finding: &SecurityFinding) -> Option<String> {
2310    let context = finding.dead_code.as_ref()?;
2311    match context.kind {
2312        SecurityDeadCodeKind::UnusedFile => Some(
2313            "also reported as unused-file; delete this file instead of hardening the sink"
2314                .to_string(),
2315        ),
2316        SecurityDeadCodeKind::UnusedExport => Some(format!(
2317            "also reported as unused-export{}; remove the export instead of hardening the sink",
2318            context
2319                .export_name
2320                .as_ref()
2321                .map_or(String::new(), |name| format!(" `{name}`"))
2322        )),
2323    }
2324}
2325
2326const fn hop_role_label(role: TraceHopRole) -> &'static str {
2327    match role {
2328        TraceHopRole::ClientBoundary => "client boundary",
2329        TraceHopRole::UntrustedSource => "untrusted source",
2330        TraceHopRole::ModuleSource => "source module",
2331        TraceHopRole::Intermediate => "intermediate",
2332        TraceHopRole::SecretSource => "secret source",
2333        TraceHopRole::Sink => "sink site",
2334    }
2335}
2336
2337fn source_reachability_hint(finding: &SecurityFinding) -> Option<&'static str> {
2338    finding
2339        .reachability
2340        .as_ref()
2341        .filter(|reach| reach.reachable_from_untrusted_source)
2342        .map(|_| {
2343            "Module-level context: the sink module is reachable from an untrusted-source module; fallow does not prove value flow."
2344        })
2345}
2346
2347fn runtime_hint_text(runtime: &SecurityRuntimeContext) -> String {
2348    use std::fmt::Write as _;
2349
2350    let mut text = format!(
2351        "{} in {}:{}",
2352        runtime_state_label(runtime.state),
2353        runtime.function,
2354        runtime.line
2355    );
2356    if let Some(invocations) = runtime.invocations {
2357        let _ = write!(
2358            text,
2359            " ({} invocation{})",
2360            invocations,
2361            crate::report::plural(invocations as usize)
2362        );
2363    }
2364    if let Some(evidence) = runtime.evidence.as_deref() {
2365        text.push_str("; ");
2366        text.push_str(evidence);
2367    }
2368    text
2369}
2370
2371const fn runtime_state_label(state: SecurityRuntimeState) -> &'static str {
2372    match state {
2373        SecurityRuntimeState::RuntimeHot => "runtime-hot",
2374        SecurityRuntimeState::RuntimeCold => "runtime-cold",
2375        SecurityRuntimeState::NeverExecuted => "never-executed",
2376        SecurityRuntimeState::LowTraffic => "low-traffic",
2377        SecurityRuntimeState::CoverageUnavailable => "coverage-unavailable",
2378        SecurityRuntimeState::RuntimeUnknown => "runtime-unknown",
2379    }
2380}
2381
2382/// The `category` string distinguishing the server-only-import sink from the
2383/// secret-leak sink (both `ClientServerLeak` kind). Matches the constant in
2384/// `crates/core/src/analyze/security/mod.rs`.
2385const SERVER_ONLY_CATEGORY: &str = "server-only-import";
2386
2387/// Whether a `ClientServerLeak` finding is the server-only-import variant rather
2388/// than the original secret-leak variant. Keys on `category` because both share
2389/// the `ClientServerLeak` kind and the same rule.
2390fn is_server_only_leak(finding: &SecurityFinding) -> bool {
2391    matches!(finding.kind, SecurityFindingKind::ClientServerLeak)
2392        && finding.category.as_deref() == Some(SERVER_ONLY_CATEGORY)
2393}
2394
2395/// The SARIF ruleId for a finding. The secret-leak `client-server-leak` keeps its
2396/// bespoke id; the server-only variant gets `security/server-only-import` so the
2397/// GitHub Security tab tells "reaches server-only code" apart from "reads a
2398/// secret"; each `TaintedSink` category gets `security/<category>` so candidates
2399/// group and label per CWE class.
2400fn sarif_rule_id(finding: &SecurityFinding) -> String {
2401    match finding.kind {
2402        SecurityFindingKind::ClientServerLeak if is_server_only_leak(finding) => {
2403            "security/server-only-import".to_owned()
2404        }
2405        SecurityFindingKind::ClientServerLeak => "security/client-server-leak".to_owned(),
2406        SecurityFindingKind::TaintedSink => {
2407            format!(
2408                "security/{}",
2409                finding.category.as_deref().unwrap_or("tainted-sink")
2410            )
2411        }
2412    }
2413}
2414
2415fn security_help_text(title: &str) -> String {
2416    format!(
2417        "Verify this unverified {title} candidate before acting. Review the source, sink, \
2418         SARIF code flow, and any runtime or dead-code context. fallow does not prove \
2419         exploitability, attacker control, or missing sanitization."
2420    )
2421}
2422
2423fn security_help_markdown(title: &str) -> String {
2424    format!(
2425        "Verify this unverified **{title}** candidate before acting.\n\n\
2426         1. Review the source and sink in the SARIF code flow.\n\
2427         2. Confirm whether attacker-controlled data can reach the sink unsanitized.\n\
2428         3. Use runtime and dead-code context only as triage signals."
2429    )
2430}
2431
2432fn cwe_taxon_id(cwe: u32) -> String {
2433    format!("CWE-{cwe}")
2434}
2435
2436fn cwe_taxon(cwe: u32) -> serde_json::Value {
2437    let id = cwe_taxon_id(cwe);
2438    serde_json::json!({
2439        "id": id,
2440        "name": id,
2441        "shortDescription": { "text": format!("Common Weakness Enumeration {id}") },
2442        "fullDescription": { "text": format!("MITRE Common Weakness Enumeration {id}") },
2443        "helpUri": format!("https://cwe.mitre.org/data/definitions/{cwe}.html")
2444    })
2445}
2446
2447fn cwe_relationship(cwe: u32, taxon_index: usize) -> serde_json::Value {
2448    serde_json::json!({
2449        "target": {
2450            "id": cwe_taxon_id(cwe),
2451            "index": taxon_index,
2452            "toolComponent": {
2453                "name": "CWE",
2454                "index": 0
2455            }
2456        },
2457        "kinds": ["superset"]
2458    })
2459}
2460
2461fn collect_cwes(findings: &[SecurityFinding]) -> Vec<u32> {
2462    let mut cwes: Vec<u32> = findings.iter().filter_map(|finding| finding.cwe).collect();
2463    cwes.sort_unstable();
2464    cwes.dedup();
2465    cwes
2466}
2467
2468fn cwe_index(cwes: &[u32], cwe: u32) -> Option<usize> {
2469    cwes.iter().position(|existing| *existing == cwe)
2470}
2471
2472fn cwe_taxonomy(cwes: &[u32]) -> Option<serde_json::Value> {
2473    if cwes.is_empty() {
2474        return None;
2475    }
2476    let taxa = cwes.iter().map(|cwe| cwe_taxon(*cwe)).collect::<Vec<_>>();
2477    Some(serde_json::json!({
2478        "name": "CWE",
2479        "fullName": "Common Weakness Enumeration",
2480        "organization": "MITRE",
2481        "informationUri": "https://cwe.mitre.org/",
2482        "taxa": taxa
2483    }))
2484}
2485
2486/// Build the SARIF rule definition for a ruleId, deriving per-category metadata
2487/// (catalogue title + CWE tag and relationship) for `TaintedSink` findings so
2488/// CWE grouping survives in SARIF-aware consumers.
2489fn sarif_rule_def(
2490    rule_id: &str,
2491    finding: &SecurityFinding,
2492    cwe_taxon_index: Option<usize>,
2493) -> serde_json::Value {
2494    match finding.kind {
2495        SecurityFindingKind::ClientServerLeak if is_server_only_leak(finding) => {
2496            sarif_rule_def_server_only_leak(rule_id)
2497        }
2498        SecurityFindingKind::ClientServerLeak => sarif_rule_def_secret_leak(rule_id),
2499        SecurityFindingKind::TaintedSink => {
2500            sarif_rule_def_tainted_sink(rule_id, finding, cwe_taxon_index)
2501        }
2502    }
2503}
2504
2505/// SARIF rule definition for the server-only-import flavor of `ClientServerLeak`.
2506fn sarif_rule_def_server_only_leak(rule_id: &str) -> serde_json::Value {
2507    let title = "Client imports server-only code";
2508    serde_json::json!({
2509        "id": rule_id,
2510        "name": title,
2511        "shortDescription": { "text": "Client imports server-only code candidate (unverified)" },
2512        "fullDescription": { "text":
2513            "Unverified candidate, requires verification: a \"use client\" file \
2514             transitively imports a server-only module (one carrying a \"use server\" \
2515             directive or importing server-only code such as server-only, next/headers, \
2516             next/server, or node:fs / node:child_process). fallow does not prove this \
2517             code runs on the client; a module pulled in only through \
2518             next/dynamic(..., { ssr: false }) is a false positive." },
2519        "help": {
2520            "text": security_help_text(title),
2521            "markdown": security_help_markdown(title)
2522        },
2523        "helpUri": "https://github.com/fallow-rs/fallow",
2524        "defaultConfiguration": { "level": "note" }
2525    })
2526}
2527
2528/// SARIF rule definition for the secret-leak flavor of `ClientServerLeak`.
2529fn sarif_rule_def_secret_leak(rule_id: &str) -> serde_json::Value {
2530    let title = "Client-server secret leak";
2531    serde_json::json!({
2532        "id": rule_id,
2533        "name": title,
2534        "shortDescription": { "text": "Client-server secret leak candidate (unverified)" },
2535        "fullDescription": { "text":
2536            "Unverified candidate, requires verification: a \"use client\" file \
2537             transitively imports a module that reads a non-public process.env \
2538             secret. fallow does not prove the secret reaches client-bundled code." },
2539        "help": {
2540            "text": security_help_text(title),
2541            "markdown": security_help_markdown(title)
2542        },
2543        "helpUri": "https://github.com/fallow-rs/fallow",
2544        "defaultConfiguration": { "level": "note" }
2545    })
2546}
2547
2548/// SARIF rule definition for `TaintedSink` findings, attaching CWE tags and the
2549/// CWE taxonomy relationship when the finding carries a CWE id.
2550fn sarif_rule_def_tainted_sink(
2551    rule_id: &str,
2552    finding: &SecurityFinding,
2553    cwe_taxon_index: Option<usize>,
2554) -> serde_json::Value {
2555    let title = finding
2556        .category
2557        .as_deref()
2558        .and_then(security_catalogue_title)
2559        .or(finding.category.as_deref())
2560        .unwrap_or("tainted-sink");
2561    let mut rule = serde_json::json!({
2562        "id": rule_id,
2563        "name": title,
2564        "shortDescription": { "text": format!("{title} candidate (unverified)") },
2565        "fullDescription": { "text": format!(
2566            "Unverified candidate, requires verification: {title}. fallow flags a \
2567             syntactic sink reached by a non-literal argument; it does not prove the \
2568             value is attacker-controlled or reaches the sink unsanitized."
2569        ) },
2570        "help": {
2571            "text": security_help_text(title),
2572            "markdown": security_help_markdown(title)
2573        },
2574        "helpUri": "https://github.com/fallow-rs/fallow",
2575        "defaultConfiguration": { "level": "note" }
2576    });
2577    if let Some(cwe) = finding.cwe {
2578        rule["properties"] = serde_json::json!({
2579            "tags": [format!("external/cwe/cwe-{cwe}")]
2580        });
2581        if let Some(taxon_index) = cwe_taxon_index {
2582            rule["relationships"] = serde_json::json!([cwe_relationship(cwe, taxon_index)]);
2583        }
2584    }
2585    rule
2586}
2587
2588fn hop_role_token(role: TraceHopRole) -> &'static str {
2589    match role {
2590        TraceHopRole::ClientBoundary => "client-boundary",
2591        TraceHopRole::UntrustedSource => "untrusted-source",
2592        TraceHopRole::ModuleSource => "module-source",
2593        TraceHopRole::Intermediate => "intermediate",
2594        TraceHopRole::SecretSource => "secret-source",
2595        TraceHopRole::Sink => "sink",
2596    }
2597}
2598
2599fn sarif_thread_flow_location(hop: &TraceHop) -> serde_json::Value {
2600    let role = hop_role_token(hop.role);
2601    serde_json::json!({
2602        "location": sarif_location(&hop.path, hop.line, hop.col),
2603        "kinds": [role],
2604        "properties": { "fallowTraceRole": role }
2605    })
2606}
2607
2608fn primary_code_flow_hops(finding: &SecurityFinding) -> &[TraceHop] {
2609    if let Some(reachability) = finding.reachability.as_ref()
2610        && !reachability.untrusted_source_trace.is_empty()
2611    {
2612        return &reachability.untrusted_source_trace;
2613    }
2614    &finding.trace
2615}
2616
2617fn sarif_code_flows(finding: &SecurityFinding) -> Option<serde_json::Value> {
2618    let hops = primary_code_flow_hops(finding);
2619    if hops.is_empty() {
2620        return None;
2621    }
2622    let locations = hops
2623        .iter()
2624        .map(sarif_thread_flow_location)
2625        .collect::<Vec<_>>();
2626    Some(serde_json::json!([
2627        {
2628            "threadFlows": [
2629                { "locations": locations }
2630            ]
2631        }
2632    ]))
2633}
2634
2635fn push_related_location(related: &mut Vec<serde_json::Value>, hop: &TraceHop) {
2636    let location = sarif_location(&hop.path, hop.line, hop.col);
2637    if !related.iter().any(|existing| existing == &location) {
2638        related.push(location);
2639    }
2640}
2641
2642fn sarif_related_locations(finding: &SecurityFinding) -> Vec<serde_json::Value> {
2643    let mut related = Vec::new();
2644    for hop in &finding.trace {
2645        push_related_location(&mut related, hop);
2646    }
2647    if let Some(reachability) = finding.reachability.as_ref() {
2648        for hop in &reachability.untrusted_source_trace {
2649            push_related_location(&mut related, hop);
2650        }
2651    }
2652    related
2653}
2654
2655const fn sarif_level(severity: SecuritySeverity) -> &'static str {
2656    match severity {
2657        SecuritySeverity::High | SecuritySeverity::Medium => "warning",
2658        SecuritySeverity::Low => "note",
2659    }
2660}
2661
2662/// Build the SARIF `result` object for a single finding, composing the
2663/// candidate-framed message, related locations, fingerprint, and code flows.
2664fn sarif_result_for_finding(finding: &SecurityFinding) -> serde_json::Value {
2665    let rule_id = sarif_rule_id(finding);
2666    let mut message = dead_code_hint(finding).map_or_else(
2667        || finding.evidence.clone(),
2668        |hint| format!("{} Dead-code cross-link: {hint}.", finding.evidence),
2669    );
2670    if let Some(hint) = source_reachability_hint(finding) {
2671        message.push(' ');
2672        message.push_str(hint);
2673    }
2674    if let Some(runtime) = finding.runtime.as_ref() {
2675        message.push_str(" Runtime context: ");
2676        message.push_str(&runtime_hint_text(runtime));
2677        message.push('.');
2678    }
2679    let related = sarif_related_locations(finding);
2680    // Stable dedup key for GHAS: rule + anchor path + line. Without
2681    // partialFingerprints, every run re-opens previously triaged alerts.
2682    // Same helper as the JSON `finding_id` field so the two never drift
2683    // (issue #900).
2684    let mut result = serde_json::json!({
2685        "ruleId": rule_id,
2686        "level": sarif_level(finding.severity),
2687        "message": { "text": message },
2688        "locations": [sarif_location(&finding.path, finding.line, finding.col)],
2689        "relatedLocations": related,
2690        "partialFingerprints": { "fallowSecurity/v1": security_finding_id(finding) },
2691    });
2692    if let Some(code_flows) = sarif_code_flows(finding) {
2693        result["codeFlows"] = code_flows;
2694    }
2695    result
2696}
2697
2698/// Collect one SARIF rule definition per distinct ruleId present in `findings`,
2699/// in first-seen order, attaching the CWE taxonomy index when available.
2700fn sarif_rule_defs(findings: &[SecurityFinding], cwes: &[u32]) -> Vec<serde_json::Value> {
2701    let mut seen: Vec<String> = Vec::new();
2702    let mut rules: Vec<serde_json::Value> = Vec::new();
2703    for finding in findings {
2704        let rule_id = sarif_rule_id(finding);
2705        if seen.iter().any(|s| s == &rule_id) {
2706            continue;
2707        }
2708        seen.push(rule_id.clone());
2709        let cwe_taxon_index = finding.cwe.and_then(|cwe| cwe_index(cwes, cwe));
2710        rules.push(sarif_rule_def(&rule_id, finding, cwe_taxon_index));
2711    }
2712    rules
2713}
2714
2715/// SARIF output. Maps the candidate's verification-priority tier to SARIF
2716/// `level` while keeping the message text candidate-framed. Each finding's ruleId is
2717/// per-category (`security/<category>` for tainted-sink, `security/client-server-leak`
2718/// for the graph rule); the `rules` array carries one definition per distinct
2719/// ruleId present, with the CWE tag for tainted-sink categories. Detector trace
2720/// hops and source-reachability hops become `relatedLocations` of the result.
2721#[must_use]
2722fn render_sarif(output: &SecurityOutput) -> String {
2723    let cwes = collect_cwes(&output.security_findings);
2724    let results: Vec<serde_json::Value> = output
2725        .security_findings
2726        .iter()
2727        .map(sarif_result_for_finding)
2728        .collect();
2729    let rules = sarif_rule_defs(&output.security_findings, &cwes);
2730
2731    let mut run = serde_json::json!({
2732        "tool": { "driver": {
2733            "name": "fallow",
2734            "version": env!("CARGO_PKG_VERSION"),
2735            "informationUri": "https://github.com/fallow-rs/fallow",
2736            "rules": rules,
2737        }},
2738        "results": results,
2739    });
2740    if let Some(taxonomy) = cwe_taxonomy(&cwes) {
2741        run["taxonomies"] = serde_json::json!([taxonomy]);
2742        run["tool"]["driver"]["supportedTaxonomies"] = serde_json::json!([
2743            { "name": "CWE", "index": 0 }
2744        ]);
2745    }
2746    // Gate verdict rides as a RUN-level property, never on result severity.
2747    // Result levels come from candidate review-priority severity and deliberately
2748    // avoid `error`, so GHAS does not frame candidates as confirmed problems.
2749    if let Some(gate) = &output.gate
2750        && let Ok(gate_value) = serde_json::to_value(gate)
2751    {
2752        run["properties"] = serde_json::json!({ "fallowGate": gate_value });
2753    }
2754
2755    let sarif = serde_json::json!({
2756        "version": "2.1.0",
2757        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
2758        "runs": [run],
2759    });
2760    serde_json::to_string_pretty(&sarif)
2761        .unwrap_or_else(|_| "{\"error\":\"failed to serialize sarif\"}".to_owned())
2762}
2763
2764/// Small FNV-1a hex digest for SARIF `partialFingerprints` dedup stability.
2765fn fnv_hex(input: &str) -> String {
2766    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
2767    for byte in input.bytes() {
2768        hash ^= u64::from(byte);
2769        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
2770    }
2771    format!("{hash:016x}")
2772}
2773
2774/// Stable per-finding correlation id: FNV-1a hex of `rule:path:line`. The single
2775/// source of truth for BOTH the JSON `finding_id` field and the SARIF
2776/// `partialFingerprints` value, so an agent can join the two and they never
2777/// drift. Computed on the project-relative path, so it must run after the
2778/// finding is relativized (issue #900).
2779fn security_finding_id(finding: &SecurityFinding) -> String {
2780    let fp = format!(
2781        "{}:{}:{}",
2782        sarif_rule_id(finding),
2783        finding.path.to_string_lossy().replace('\\', "/"),
2784        finding.line,
2785    );
2786    fnv_hex(&fp)
2787}
2788
2789fn sarif_location(path: &Path, line: u32, col: u32) -> serde_json::Value {
2790    serde_json::json!({
2791        "physicalLocation": {
2792            "artifactLocation": { "uri": path.to_string_lossy().replace('\\', "/") },
2793            "region": { "startLine": line.max(1), "startColumn": col.saturating_add(1) }
2794        }
2795    })
2796}
2797
2798#[cfg(test)]
2799mod tests {
2800    use super::*;
2801    use fallow_types::results::{
2802        SecurityCandidate, SecurityCandidateBoundary, SecurityCandidateSink,
2803        SecurityDeadCodeContext, SecurityDeadCodeKind, SecurityFinding, SecurityFindingKind,
2804        TraceHop, TraceHopRole,
2805    };
2806    use fallow_types::results::{
2807        SecurityReachability, SecurityTaintFlow, TaintEndpoint, TaintPath,
2808    };
2809
2810    /// Build a finding anchored under `root` with a three-hop client -> secret trace.
2811    fn sample_finding(root: &Path) -> SecurityFinding {
2812        SecurityFinding {
2813            kind: SecurityFindingKind::ClientServerLeak,
2814            path: root.join("src/app.tsx"),
2815            line: 12,
2816            col: 3,
2817            evidence: "reaches process.env.SECRET_KEY".to_owned(),
2818            source_backed: false,
2819            source_read: None,
2820            severity: SecuritySeverity::High,
2821            trace: vec![
2822                TraceHop {
2823                    path: root.join("src/app.tsx"),
2824                    line: 12,
2825                    col: 3,
2826                    role: TraceHopRole::ClientBoundary,
2827                },
2828                TraceHop {
2829                    path: root.join("src/lib/util.ts"),
2830                    line: 4,
2831                    col: 0,
2832                    role: TraceHopRole::Intermediate,
2833                },
2834                TraceHop {
2835                    path: root.join("src/lib/secret.ts"),
2836                    line: 8,
2837                    col: 2,
2838                    role: TraceHopRole::SecretSource,
2839                },
2840            ],
2841            actions: vec![],
2842            category: None,
2843            cwe: None,
2844            dead_code: None,
2845            reachability: None,
2846            finding_id: String::new(),
2847            candidate: SecurityCandidate {
2848                source_kind: None,
2849                sink: SecurityCandidateSink {
2850                    path: root.join("src/app.tsx"),
2851                    line: 12,
2852                    col: 3,
2853                    category: None,
2854                    cwe: None,
2855                    callee: None,
2856                    url_shape: None,
2857                },
2858                boundary: SecurityCandidateBoundary {
2859                    client_server: true,
2860                    cross_module: false,
2861                    architecture_zone: None,
2862                },
2863                network: None,
2864            },
2865            taint_flow: None,
2866            runtime: None,
2867            attack_surface: None,
2868        }
2869    }
2870
2871    fn output_with(findings: Vec<SecurityFinding>, unresolved_edge_files: usize) -> SecurityOutput {
2872        SecurityOutput {
2873            schema_version: SecuritySchemaVersion::V7,
2874            version: ToolVersion("test".to_string()),
2875            elapsed_ms: ElapsedMs(0),
2876            config: test_output_config(),
2877            meta: None,
2878            gate: None,
2879            security_findings: findings,
2880            attack_surface: None,
2881            unresolved_edge_files,
2882            unresolved_callee_sites: 0,
2883            unresolved_callee_diagnostics: None,
2884        }
2885    }
2886
2887    fn output_with_gate(verdict: SecurityGateVerdict, new_count: usize) -> SecurityOutput {
2888        SecurityOutput {
2889            schema_version: SecuritySchemaVersion::V7,
2890            version: ToolVersion("test".to_string()),
2891            elapsed_ms: ElapsedMs(0),
2892            config: test_output_config(),
2893            meta: None,
2894            gate: Some(SecurityGate {
2895                mode: SecurityGateMode::New,
2896                verdict,
2897                new_count,
2898            }),
2899            security_findings: vec![],
2900            attack_surface: None,
2901            unresolved_edge_files: 0,
2902            unresolved_callee_sites: 0,
2903            unresolved_callee_diagnostics: None,
2904        }
2905    }
2906
2907    fn survivor_candidate_json(
2908        finding_id: &str,
2909        path: &str,
2910        line: u32,
2911        kind: SecurityFindingKind,
2912        category: Option<&str>,
2913    ) -> serde_json::Value {
2914        let root = Path::new("/proj/root");
2915        let mut finding = relativize_finding(sample_finding(root), root);
2916        finding.finding_id = finding_id.to_owned();
2917        finding.path = PathBuf::from(path);
2918        finding.line = line;
2919        finding.kind = kind;
2920        finding.category = category.map(str::to_owned);
2921        finding.candidate.sink.path = PathBuf::from(path);
2922        finding.candidate.sink.line = line;
2923        finding.candidate.sink.category = category.map(str::to_owned);
2924        serde_json::to_value(finding).expect("security finding serializes")
2925    }
2926
2927    fn sample_unresolved_callee_diagnostics(root: &Path) -> SecurityUnresolvedCalleeDiagnostics {
2928        unresolved_callee_diagnostics(
2929            &[
2930                SecurityUnresolvedCalleeDiagnostic {
2931                    path: root.join("src/z.ts"),
2932                    line: 9,
2933                    col: 4,
2934                    reason: fallow_types::extract::SkippedSecurityCalleeReason::ComputedMember,
2935                    expression_kind:
2936                        fallow_types::extract::SkippedSecurityCalleeExpressionKind::ComputedMemberExpression,
2937                },
2938                SecurityUnresolvedCalleeDiagnostic {
2939                    path: root.join("src/a.ts"),
2940                    line: 3,
2941                    col: 2,
2942                    reason: fallow_types::extract::SkippedSecurityCalleeReason::DynamicDispatch,
2943                    expression_kind: fallow_types::extract::SkippedSecurityCalleeExpressionKind::Other,
2944                },
2945                SecurityUnresolvedCalleeDiagnostic {
2946                    path: root.join("src/a.ts"),
2947                    line: 4,
2948                    col: 2,
2949                    reason: fallow_types::extract::SkippedSecurityCalleeReason::DynamicDispatch,
2950                    expression_kind: fallow_types::extract::SkippedSecurityCalleeExpressionKind::Other,
2951                },
2952            ],
2953            root,
2954        )
2955        .expect("diagnostics summarized")
2956    }
2957
2958    fn test_output_config() -> SecurityOutputConfig {
2959        SecurityOutputConfig {
2960            rules: SecurityOutputRulesConfig {
2961                security_client_server_leak: SecurityRuleSeverityConfig {
2962                    configured: Severity::Off,
2963                    effective: Severity::Warn,
2964                },
2965                security_sink: SecurityRuleSeverityConfig {
2966                    configured: Severity::Off,
2967                    effective: Severity::Warn,
2968                },
2969            },
2970            categories_include: None,
2971            categories_exclude: None,
2972        }
2973    }
2974
2975    #[test]
2976    fn survivors_json_keeps_survivors_and_review_candidates_by_finding_id() {
2977        let dir = tempfile::tempdir().expect("temp dir");
2978        let candidates = dir.path().join("candidates.json");
2979        let verdicts = dir.path().join("verdicts.json");
2980        std::fs::write(
2981            &candidates,
2982            serde_json::json!({
2983                "kind": "security",
2984                "security_findings": [
2985                    survivor_candidate_json("sec-a", "src/a.ts", 10, SecurityFindingKind::TaintedSink, Some("ssrf")),
2986                    survivor_candidate_json("sec-b", "src/b.ts", 11, SecurityFindingKind::TaintedSink, Some("redos-regex")),
2987                    survivor_candidate_json("sec-c", "src/c.ts", 12, SecurityFindingKind::ClientServerLeak, None)
2988                ]
2989            })
2990            .to_string(),
2991        )
2992        .expect("write candidates");
2993        std::fs::write(
2994            &verdicts,
2995            serde_json::json!({
2996                "schema_version": "fallow-security-verdicts/v1",
2997                "verdicts": [
2998                    { "schema_version": "fallow-security-verdict/v1", "finding_id": "sec-b", "verdict": "dismissed" },
2999                    { "schema_version": "fallow-security-verdict/v1", "finding_id": "sec-a", "verdict": "survivor", "rationale": "input controls URL" },
3000                    { "schema_version": "fallow-security-verdict/v1", "finding_id": "sec-c", "verdict": "needs-human-review" }
3001                ]
3002            })
3003            .to_string(),
3004        )
3005        .expect("write verdicts");
3006
3007        let output = build_survivors_output(
3008            &SecuritySurvivorsOptions {
3009                output: OutputFormat::Json,
3010                candidates: &candidates,
3011                verdicts: &verdicts,
3012                require_verdict_for_each_candidate: false,
3013            },
3014            Instant::now(),
3015        )
3016        .expect("survivors output");
3017        let rendered: serde_json::Value =
3018            serde_json::from_str(&render_survivors_json(&output)).expect("json");
3019
3020        assert_eq!(rendered["kind"], "security-survivors");
3021        assert!(rendered["survivors"]["sec-a"].is_object());
3022        assert!(rendered["survivors"]["sec-b"].is_null());
3023        assert!(rendered["needs_human_review"]["sec-c"].is_object());
3024        assert_eq!(rendered["summary"]["dismissed"], 1);
3025    }
3026
3027    #[test]
3028    fn survivors_reject_duplicate_verdicts_and_unknown_candidates() {
3029        let dir = tempfile::tempdir().expect("temp dir");
3030        let candidates = dir.path().join("candidates.json");
3031        let verdicts = dir.path().join("verdicts.json");
3032        std::fs::write(
3033            &candidates,
3034            serde_json::json!({
3035                "security_findings": [
3036                    survivor_candidate_json("sec-a", "src/a.ts", 1, SecurityFindingKind::TaintedSink, Some("ssrf"))
3037                ]
3038            })
3039            .to_string(),
3040        )
3041        .expect("write candidates");
3042        std::fs::write(
3043            &verdicts,
3044            r#"[
3045                {"schema_version":"fallow-security-verdict/v1","finding_id":"sec-a","verdict":"survivor"},
3046                {"schema_version":"fallow-security-verdict/v1","finding_id":"sec-a","verdict":"dismissed"}
3047            ]"#,
3048        )
3049        .expect("write duplicate verdicts");
3050        let duplicate = build_survivors_output(
3051            &SecuritySurvivorsOptions {
3052                output: OutputFormat::Json,
3053                candidates: &candidates,
3054                verdicts: &verdicts,
3055                require_verdict_for_each_candidate: false,
3056            },
3057            Instant::now(),
3058        )
3059        .expect_err("duplicate verdict should fail");
3060        assert!(duplicate.contains("duplicate verdict"));
3061
3062        std::fs::write(
3063            &verdicts,
3064            r#"[{"schema_version":"fallow-security-verdict/v1","finding_id":"sec-missing","verdict":"survivor"}]"#,
3065        )
3066        .expect("write missing verdict");
3067        let missing = build_survivors_output(
3068            &SecuritySurvivorsOptions {
3069                output: OutputFormat::Json,
3070                candidates: &candidates,
3071                verdicts: &verdicts,
3072                require_verdict_for_each_candidate: false,
3073            },
3074            Instant::now(),
3075        )
3076        .expect_err("missing candidate should fail");
3077        assert!(missing.contains("unknown finding_id"));
3078    }
3079
3080    #[test]
3081    fn survivors_reject_malformed_schema_versions_and_unknown_verdicts() {
3082        let dir = tempfile::tempdir().expect("temp dir");
3083        let candidates = dir.path().join("candidates.json");
3084        let verdicts = dir.path().join("verdicts.json");
3085        std::fs::write(
3086            &candidates,
3087            serde_json::json!({
3088                "security_findings": [
3089                    survivor_candidate_json("sec-a", "src/a.ts", 1, SecurityFindingKind::TaintedSink, Some("ssrf"))
3090                ]
3091            })
3092            .to_string(),
3093        )
3094        .expect("write candidates");
3095        std::fs::write(
3096            &verdicts,
3097            r#"[{"schema_version":"wrong","finding_id":"sec-a","verdict":"survivor"}]"#,
3098        )
3099        .expect("write bad schema");
3100        let bad_schema = build_survivors_output(
3101            &SecuritySurvivorsOptions {
3102                output: OutputFormat::Json,
3103                candidates: &candidates,
3104                verdicts: &verdicts,
3105                require_verdict_for_each_candidate: false,
3106            },
3107            Instant::now(),
3108        )
3109        .expect_err("bad schema should fail");
3110        assert!(bad_schema.contains("schema_version"));
3111
3112        std::fs::write(
3113            &verdicts,
3114            r#"[{"schema_version":"fallow-security-verdict/v1","finding_id":"sec-a","verdict":"maybe"}]"#,
3115        )
3116        .expect("write unknown verdict");
3117        let unknown = build_survivors_output(
3118            &SecuritySurvivorsOptions {
3119                output: OutputFormat::Json,
3120                candidates: &candidates,
3121                verdicts: &verdicts,
3122                require_verdict_for_each_candidate: false,
3123            },
3124            Instant::now(),
3125        )
3126        .expect_err("unknown verdict should fail");
3127        assert!(unknown.contains("Failed to parse verifier verdict file"));
3128    }
3129
3130    #[test]
3131    fn blind_spots_group_existing_diagnostics_with_suggestions() {
3132        let root = Path::new("/proj/root");
3133        let mut output = output_with(vec![], 2);
3134        output.unresolved_callee_sites = 99;
3135        output.unresolved_callee_diagnostics = Some(sample_unresolved_callee_diagnostics(root));
3136
3137        let blind_spots = build_blind_spots_output(&output);
3138        let rendered: serde_json::Value =
3139            serde_json::from_str(&render_blind_spots_json(&blind_spots)).expect("json");
3140
3141        assert_eq!(rendered["kind"], "security-blind-spots");
3142        assert_eq!(rendered["summary"]["unresolved_edge_files"], 2);
3143        assert_eq!(rendered["summary"]["unresolved_callee_sites"], 3);
3144        assert_eq!(rendered["groups"][0]["reason"], "dynamic-dispatch");
3145        assert_eq!(rendered["groups"][0]["expression_kind"], "other");
3146        assert_eq!(rendered["groups"][0]["files"][0]["path"], "src/a.ts");
3147        assert!(rendered["groups"][0]["suggestion"].is_string());
3148    }
3149
3150    #[test]
3151    fn blind_spots_human_preserves_non_clean_bill_framing() {
3152        let root = Path::new("/proj/root");
3153        let mut output = output_with(vec![], 0);
3154        output.unresolved_callee_sites = 3;
3155        output.unresolved_callee_diagnostics = Some(sample_unresolved_callee_diagnostics(root));
3156
3157        let out = render_blind_spots_human(&build_blind_spots_output(&output));
3158
3159        assert!(out.contains("may have missed security candidates"));
3160        assert!(out.contains("dynamic-dispatch / other"));
3161        assert!(out.contains("Next: inspect dynamic dispatch targets"));
3162    }
3163
3164    fn tainted_with_runtime(root: &Path, state: Option<SecurityRuntimeState>) -> SecurityFinding {
3165        let mut finding = sample_finding(root);
3166        finding.kind = SecurityFindingKind::TaintedSink;
3167        finding.category = Some("dangerous-html".to_owned());
3168        finding.cwe = Some(79);
3169        finding.runtime = state.map(|state| SecurityRuntimeContext {
3170            state,
3171            function: "render".to_owned(),
3172            line: 10,
3173            invocations: Some(123),
3174            stable_id: Some("fallow:fn:test".to_owned()),
3175            evidence: Some("production runtime evidence".to_owned()),
3176        });
3177        finding
3178    }
3179
3180    #[test]
3181    fn runtime_rank_promotes_hot_and_demotes_never_executed() {
3182        let root = Path::new("/proj/root");
3183        let mut findings = [
3184            tainted_with_runtime(root, Some(SecurityRuntimeState::NeverExecuted)),
3185            tainted_with_runtime(root, None),
3186            tainted_with_runtime(root, Some(SecurityRuntimeState::RuntimeHot)),
3187            tainted_with_runtime(root, Some(SecurityRuntimeState::CoverageUnavailable)),
3188        ];
3189
3190        findings.sort_by_key(runtime_rank);
3191
3192        assert_eq!(
3193            findings
3194                .iter()
3195                .map(|finding| finding.runtime.as_ref().map(|runtime| runtime.state))
3196                .collect::<Vec<_>>(),
3197            vec![
3198                Some(SecurityRuntimeState::RuntimeHot),
3199                None,
3200                Some(SecurityRuntimeState::CoverageUnavailable),
3201                Some(SecurityRuntimeState::NeverExecuted),
3202            ]
3203        );
3204    }
3205
3206    #[test]
3207    fn severity_sort_orders_tiers_then_location() {
3208        let root = Path::new("/proj/root");
3209        let mut high = sample_finding(root);
3210        high.path = root.join("z.ts");
3211        high.severity = SecuritySeverity::High;
3212        let mut low = sample_finding(root);
3213        low.path = root.join("a.ts");
3214        low.severity = SecuritySeverity::Low;
3215        let mut medium_a = sample_finding(root);
3216        medium_a.path = root.join("a.ts");
3217        medium_a.severity = SecuritySeverity::Medium;
3218        medium_a.reachability = Some(fallow_types::results::SecurityReachability {
3219            reachable_from_entry: false,
3220            reachable_from_untrusted_source: true,
3221            taint_confidence: Some(TaintConfidence::ModuleLevel),
3222            untrusted_source_hop_count: Some(1),
3223            untrusted_source_trace: vec![],
3224            blast_radius: 10,
3225            crosses_boundary: false,
3226        });
3227        let mut medium_b = sample_finding(root);
3228        medium_b.path = root.join("b.ts");
3229        medium_b.severity = SecuritySeverity::Medium;
3230        medium_b.source_backed = true;
3231        medium_b.reachability = Some(fallow_types::results::SecurityReachability {
3232            reachable_from_entry: false,
3233            reachable_from_untrusted_source: true,
3234            taint_confidence: Some(TaintConfidence::ArgLevel),
3235            untrusted_source_hop_count: Some(0),
3236            untrusted_source_trace: vec![],
3237            blast_radius: 1,
3238            crosses_boundary: false,
3239        });
3240        let mut findings = vec![low, medium_b, high, medium_a];
3241
3242        sort_by_security_severity(&mut findings);
3243
3244        assert_eq!(
3245            findings
3246                .iter()
3247                .map(|finding| (finding.severity, finding.path.file_name().unwrap()))
3248                .collect::<Vec<_>>(),
3249            vec![
3250                (SecuritySeverity::High, std::ffi::OsStr::new("z.ts")),
3251                (SecuritySeverity::Medium, std::ffi::OsStr::new("b.ts")),
3252                (SecuritySeverity::Medium, std::ffi::OsStr::new("a.ts")),
3253                (SecuritySeverity::Low, std::ffi::OsStr::new("a.ts")),
3254            ]
3255        );
3256    }
3257
3258    #[test]
3259    fn human_render_includes_runtime_context_line() {
3260        let root = Path::new("/proj/root");
3261        let finding = relativize_finding(
3262            tainted_with_runtime(root, Some(SecurityRuntimeState::RuntimeHot)),
3263            root,
3264        );
3265        let out = render_human(&output_with(vec![finding], 0));
3266
3267        assert!(
3268            out.contains("runtime: runtime-hot in render:10"),
3269            "got: {out}"
3270        );
3271        assert!(out.contains("production runtime evidence"), "got: {out}");
3272    }
3273
3274    #[test]
3275    fn sarif_render_includes_runtime_context_in_message() {
3276        let root = Path::new("/proj/root");
3277        let finding = relativize_finding(
3278            tainted_with_runtime(root, Some(SecurityRuntimeState::RuntimeHot)),
3279            root,
3280        );
3281        let rendered = render_sarif(&output_with(vec![finding], 0));
3282        let sarif: serde_json::Value = serde_json::from_str(&rendered).expect("valid SARIF JSON");
3283        let message = sarif["runs"][0]["results"][0]["message"]["text"]
3284            .as_str()
3285            .expect("message text");
3286
3287        assert!(message.contains("Runtime context"), "got: {message}");
3288        assert!(
3289            message.contains("runtime-hot in render:10"),
3290            "got: {message}"
3291        );
3292    }
3293
3294    #[test]
3295    fn gate_human_header_fail_says_review_required_not_fail() {
3296        let gate = SecurityGate {
3297            mode: SecurityGateMode::New,
3298            verdict: SecurityGateVerdict::Fail,
3299            new_count: 2,
3300        };
3301        let header = gate_human_header(&gate);
3302        assert!(header.contains("REVIEW REQUIRED"));
3303        assert!(header.contains("2 new security items"));
3304        assert!(header.contains("not confirmed a vulnerability"));
3305        assert!(!header.to_uppercase().contains("GATE: FAIL"));
3306    }
3307
3308    #[test]
3309    fn gate_human_header_fail_singular_for_one_candidate() {
3310        // The gate makes new_count == 1 the common case (one PR adds one sink).
3311        let gate = SecurityGate {
3312            mode: SecurityGateMode::New,
3313            verdict: SecurityGateVerdict::Fail,
3314            new_count: 1,
3315        };
3316        let header = gate_human_header(&gate);
3317        assert!(header.contains("1 new security item in changed lines"));
3318        assert!(!header.contains("1 new security candidates"));
3319    }
3320
3321    #[test]
3322    fn gate_human_header_pass() {
3323        let gate = SecurityGate {
3324            mode: SecurityGateMode::New,
3325            verdict: SecurityGateVerdict::Pass,
3326            new_count: 0,
3327        };
3328        assert!(gate_human_header(&gate).contains("Gate: PASS"));
3329    }
3330
3331    #[test]
3332    fn gate_json_block_is_snake_case_and_present_on_pass() {
3333        let json = render_json(&output_with_gate(SecurityGateVerdict::Pass, 0));
3334        assert!(json.contains("\"gate\""));
3335        assert!(json.contains("\"mode\": \"new\""));
3336        assert!(json.contains("\"verdict\": \"pass\""));
3337        assert!(json.contains("\"new_count\": 0"));
3338    }
3339
3340    #[test]
3341    fn reachability_key_includes_path_kind_and_category() {
3342        let root = Path::new("/proj/root");
3343        let mut leak = sample_finding(root);
3344        leak.reachability = Some(SecurityReachability {
3345            reachable_from_entry: true,
3346            reachable_from_untrusted_source: false,
3347            taint_confidence: None,
3348            untrusted_source_hop_count: None,
3349            untrusted_source_trace: vec![],
3350            blast_radius: 0,
3351            crosses_boundary: false,
3352        });
3353        let mut sink = leak.clone();
3354        sink.kind = SecurityFindingKind::TaintedSink;
3355        sink.category = Some("dangerous-html".to_owned());
3356
3357        assert_eq!(
3358            security_reachability_key(&leak, root).as_deref(),
3359            Some("security-reach:src/app.tsx:client-server-leak:none")
3360        );
3361        assert_eq!(
3362            security_reachability_key(&sink, root).as_deref(),
3363            Some("security-reach:src/app.tsx:tainted-sink:dangerous-html")
3364        );
3365    }
3366
3367    #[test]
3368    fn reachability_key_ignores_unreachable_findings() {
3369        let root = Path::new("/proj/root");
3370        let finding = sample_finding(root);
3371
3372        assert!(security_reachability_key(&finding, root).is_none());
3373    }
3374
3375    #[test]
3376    fn gate_absent_from_json_when_no_gate_ran() {
3377        let json = render_json(&output_with(vec![], 0));
3378        assert!(!json.contains("\"gate\""));
3379    }
3380
3381    #[test]
3382    fn gate_sarif_is_a_run_property_not_result_severity() {
3383        let sarif = render_sarif(&output_with_gate(SecurityGateVerdict::Fail, 1));
3384        assert!(sarif.contains("fallowGate"));
3385        // The gate verdict is a run property and creates no result severity.
3386        assert!(!sarif.contains("\"level\": \"error\""));
3387        assert!(!sarif.contains("\"level\": \"warning\""));
3388    }
3389
3390    fn add_untrusted_source_reachability(finding: &mut SecurityFinding, root: &Path) {
3391        finding.reachability = Some(SecurityReachability {
3392            reachable_from_entry: true,
3393            reachable_from_untrusted_source: true,
3394            // Cross-module reachability is module-level (issue #1093).
3395            taint_confidence: Some(TaintConfidence::ModuleLevel),
3396            untrusted_source_hop_count: Some(1),
3397            untrusted_source_trace: vec![
3398                TraceHop {
3399                    path: root.join("src/routes/api.ts"),
3400                    line: 3,
3401                    col: 0,
3402                    role: TraceHopRole::ModuleSource,
3403                },
3404                TraceHop {
3405                    path: root.join("src/lib/sink.ts"),
3406                    line: 9,
3407                    col: 2,
3408                    role: TraceHopRole::Sink,
3409                },
3410            ],
3411            blast_radius: 2,
3412            crosses_boundary: false,
3413        });
3414    }
3415
3416    fn add_taint_flow(finding: &mut SecurityFinding, root: &Path) {
3417        finding.taint_flow = Some(SecurityTaintFlow {
3418            source: TaintEndpoint {
3419                path: root.join("src/routes/api.ts"),
3420                line: 3,
3421                col: 0,
3422            },
3423            sink: TaintEndpoint {
3424                path: root.join("src/lib/sink.ts"),
3425                line: 9,
3426                col: 2,
3427            },
3428            path: TaintPath {
3429                intra_module: false,
3430                cross_module_hops: 1,
3431            },
3432        });
3433    }
3434
3435    #[test]
3436    fn relativize_strips_root_prefix() {
3437        let root = Path::new("/proj/root");
3438        let abs = root.join("src/app.tsx");
3439        let rel = relativize(&abs, root);
3440        assert_eq!(rel.to_string_lossy().replace('\\', "/"), "src/app.tsx");
3441    }
3442
3443    #[test]
3444    fn relativize_keeps_path_when_outside_root() {
3445        let root = Path::new("/proj/root");
3446        let outside = Path::new("/elsewhere/file.ts");
3447        // Not under root: the original path is returned unchanged.
3448        assert_eq!(relativize(outside, root), outside.to_path_buf());
3449    }
3450
3451    #[test]
3452    fn relativize_finding_relativizes_anchor_and_every_hop() {
3453        let root = Path::new("/proj/root");
3454        let finding = relativize_finding(sample_finding(root), root);
3455        assert_eq!(
3456            finding.path.to_string_lossy().replace('\\', "/"),
3457            "src/app.tsx"
3458        );
3459        let hop_paths: Vec<String> = finding
3460            .trace
3461            .iter()
3462            .map(|h| h.path.to_string_lossy().replace('\\', "/"))
3463            .collect();
3464        assert_eq!(
3465            hop_paths,
3466            vec!["src/app.tsx", "src/lib/util.ts", "src/lib/secret.ts"]
3467        );
3468    }
3469
3470    #[test]
3471    fn relativize_finding_relativizes_untrusted_source_trace() {
3472        let root = Path::new("/proj/root");
3473        let mut finding = sample_finding(root);
3474        add_untrusted_source_reachability(&mut finding, root);
3475        let finding = relativize_finding(finding, root);
3476        let reach = finding.reachability.as_ref().expect("reachability");
3477        let hop_paths: Vec<String> = reach
3478            .untrusted_source_trace
3479            .iter()
3480            .map(|h| h.path.to_string_lossy().replace('\\', "/"))
3481            .collect();
3482        assert_eq!(hop_paths, vec!["src/routes/api.ts", "src/lib/sink.ts"]);
3483    }
3484
3485    #[test]
3486    fn fnv_hex_is_deterministic_and_16_hex_digits() {
3487        let a = fnv_hex("security/client-server-leak:src/app.tsx:12");
3488        let b = fnv_hex("security/client-server-leak:src/app.tsx:12");
3489        assert_eq!(a, b, "same input must hash identically");
3490        assert_eq!(a.len(), 16);
3491        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
3492        // Distinct input yields a distinct digest (anchor line differs).
3493        assert_ne!(a, fnv_hex("security/client-server-leak:src/app.tsx:13"));
3494    }
3495
3496    #[test]
3497    fn hop_role_labels_cover_every_role() {
3498        assert_eq!(
3499            hop_role_label(TraceHopRole::ClientBoundary),
3500            "client boundary"
3501        );
3502        assert_eq!(
3503            hop_role_label(TraceHopRole::UntrustedSource),
3504            "untrusted source"
3505        );
3506        assert_eq!(hop_role_label(TraceHopRole::ModuleSource), "source module");
3507        assert_eq!(hop_role_label(TraceHopRole::Intermediate), "intermediate");
3508        assert_eq!(hop_role_label(TraceHopRole::SecretSource), "secret source");
3509        assert_eq!(hop_role_label(TraceHopRole::Sink), "sink site");
3510    }
3511
3512    #[test]
3513    fn sarif_location_clamps_line_and_offsets_column() {
3514        // A zero line clamps to 1; the 0-based column becomes 1-based.
3515        let loc = sarif_location(Path::new("a\\b.ts"), 0, 0);
3516        let region = &loc["physicalLocation"]["region"];
3517        assert_eq!(region["startLine"], 1);
3518        assert_eq!(region["startColumn"], 1);
3519        // Backslash separators normalize to forward slashes in the URI.
3520        assert_eq!(loc["physicalLocation"]["artifactLocation"]["uri"], "a/b.ts");
3521    }
3522
3523    #[test]
3524    fn human_summary_reports_zero_without_edge_line() {
3525        let out = render_human_summary(&output_with(vec![], 0));
3526        assert!(
3527            out.contains("Security review: no items to check in the scanned code."),
3528            "got: {out}"
3529        );
3530        assert!(!out.contains("Blind spot"));
3531    }
3532
3533    #[test]
3534    fn human_summary_pluralizes_and_surfaces_unresolved_edges() {
3535        let root = Path::new("/proj/root");
3536        let out = render_human_summary(&output_with(vec![sample_finding(root)], 2));
3537        assert!(
3538            out.contains("Security review: 1 item to check."),
3539            "got: {out}"
3540        );
3541        assert!(out.contains("not confirmed vulnerabilities"));
3542        assert!(out.contains("unsafe input, secrets, or settings"));
3543        assert!(out.contains("Blind spot: 2 client files use dynamic imports"));
3544    }
3545
3546    #[test]
3547    fn human_render_empty_states_no_candidates() {
3548        colored::control::set_override(false);
3549        let out = render_human(&output_with(vec![], 0));
3550        assert!(out.contains("Security review: 0 items to check"));
3551        assert!(out.contains("No security details to show."));
3552        assert!(out.contains("Result: 0 security items to check."));
3553    }
3554
3555    #[test]
3556    fn human_render_shows_finding_trace_and_next_action() {
3557        colored::control::set_override(false);
3558        let root = Path::new("/proj/root");
3559        let finding = relativize_finding(sample_finding(root), root);
3560        let out = render_human(&output_with(vec![finding], 0));
3561        assert!(out.contains("[H] high client-server-leak"));
3562        assert!(out.contains("client-server-leak"));
3563        assert!(out.contains("src/app.tsx:12"));
3564        assert!(out.contains("evidence: reaches process.env.SECRET_KEY"));
3565        assert!(out.contains("import trace:"));
3566        assert!(out.contains("src/lib/secret.ts:8 (secret source)"));
3567        assert!(out.contains("src/app.tsx:12 (client boundary)"));
3568        assert!(out.contains("Next: check whether this import can ship a secret to the browser"));
3569        assert!(out.contains("Result: 1 security item to check."));
3570    }
3571
3572    #[test]
3573    fn human_render_shows_dead_code_hint_and_delete_next_step() {
3574        colored::control::set_override(false);
3575        let root = Path::new("/proj/root");
3576        let mut finding = relativize_finding(sample_finding(root), root);
3577        finding.kind = SecurityFindingKind::TaintedSink;
3578        finding.dead_code = Some(SecurityDeadCodeContext {
3579            kind: SecurityDeadCodeKind::UnusedFile,
3580            export_name: None,
3581            line: None,
3582            guidance: "delete instead of harden".to_string(),
3583        });
3584        let out = render_human(&output_with(vec![finding], 0));
3585        assert!(
3586            out.contains("dead-code: also reported as unused-file"),
3587            "got: {out}"
3588        );
3589        assert!(
3590            out.contains("If the code is safe to remove, delete it"),
3591            "got: {out}"
3592        );
3593    }
3594
3595    #[test]
3596    fn human_render_shows_untrusted_source_path_as_module_context() {
3597        colored::control::set_override(false);
3598        let root = Path::new("/proj/root");
3599        let mut finding = sample_finding(root);
3600        finding.kind = SecurityFindingKind::TaintedSink;
3601        finding.category = Some("command-injection".to_string());
3602        add_untrusted_source_reachability(&mut finding, root);
3603        let finding = relativize_finding(finding, root);
3604
3605        let out = render_human(&output_with(vec![finding], 0));
3606
3607        assert!(
3608            out.contains("reachable from a module that receives untrusted input via 1 import hop"),
3609            "got: {out}"
3610        );
3611        assert!(out.contains("input import trace:"), "got: {out}");
3612        assert!(
3613            out.contains("src/routes/api.ts:3 (source module)"),
3614            "got: {out}"
3615        );
3616    }
3617
3618    #[test]
3619    fn human_render_surfaces_unresolved_edge_blind_spot() {
3620        colored::control::set_override(false);
3621        let out = render_human(&output_with(vec![], 3));
3622        assert!(out.contains("Blind spot: 3 client files use dynamic imports"));
3623        assert!(out.contains("Code behind those imports may be missing from this report."));
3624    }
3625
3626    #[test]
3627    fn human_render_blind_spots_use_singular_verbs() {
3628        colored::control::set_override(false);
3629        let mut output = output_with(vec![], 1);
3630        output.unresolved_callee_sites = 1;
3631
3632        let out = render_human(&output);
3633
3634        assert!(out.contains("Blind spot: 1 client file uses dynamic imports"));
3635        assert!(out.contains("Blind spot: 1 call site uses code patterns"));
3636    }
3637
3638    #[test]
3639    fn human_render_mentions_top_unresolved_callee_reason_and_file() {
3640        colored::control::set_override(false);
3641        let root = Path::new("/proj/root");
3642        let mut output = output_with(vec![], 0);
3643        output.unresolved_callee_sites = 3;
3644        output.unresolved_callee_diagnostics = Some(sample_unresolved_callee_diagnostics(root));
3645
3646        let out = render_human(&output);
3647
3648        assert!(
3649            out.contains("Most unresolved callees: dynamic-dispatch in src/a.ts."),
3650            "got: {out}"
3651        );
3652    }
3653
3654    #[test]
3655    fn json_render_carries_schema_version_and_findings() {
3656        let root = Path::new("/proj/root");
3657        let finding = relativize_finding(sample_finding(root), root);
3658        let rendered = render_json(&output_with(vec![finding], 1));
3659        let value: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
3660        assert_eq!(value["schema_version"], "7");
3661        assert_eq!(value["version"], "test");
3662        assert_eq!(value["elapsed_ms"], 0);
3663        assert_eq!(
3664            value["config"]["rules"]["security_client_server_leak"]["configured"],
3665            "off"
3666        );
3667        assert_eq!(
3668            value["config"]["rules"]["security_client_server_leak"]["effective"],
3669            "warn"
3670        );
3671        assert!(value["config"]["categories_include"].is_null());
3672        assert!(value["config"]["categories_exclude"].is_null());
3673        assert_eq!(value["unresolved_edge_files"], 1);
3674        let findings = value["security_findings"].as_array().expect("array");
3675        assert_eq!(findings.len(), 1);
3676        assert_eq!(findings[0]["kind"], "client-server-leak");
3677        assert_eq!(findings[0]["path"], "src/app.tsx");
3678        assert_eq!(findings[0]["severity"], "high");
3679    }
3680
3681    #[test]
3682    fn json_render_carries_bounded_unresolved_callee_diagnostics() {
3683        let root = Path::new("/proj/root");
3684        let mut output = output_with(vec![], 0);
3685        output.unresolved_callee_sites = 3;
3686        output.unresolved_callee_diagnostics = Some(sample_unresolved_callee_diagnostics(root));
3687
3688        let rendered = render_json(&output);
3689        let value: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
3690        let diagnostics = &value["unresolved_callee_diagnostics"];
3691
3692        assert_eq!(diagnostics["sample_limit"], 25);
3693        assert_eq!(diagnostics["top_files_limit"], 10);
3694        assert_eq!(diagnostics["sampled"][0]["path"], "src/a.ts");
3695        assert_eq!(diagnostics["sampled"][0]["reason"], "dynamic-dispatch");
3696        assert_eq!(diagnostics["sampled"][0]["expression_kind"], "other");
3697        assert_eq!(diagnostics["top_files"][0]["path"], "src/a.ts");
3698        assert_eq!(diagnostics["top_files"][0]["count"], 2);
3699        assert_eq!(diagnostics["by_reason"][0]["reason"], "dynamic-dispatch");
3700        assert_eq!(diagnostics["by_reason"][0]["count"], 2);
3701    }
3702
3703    #[test]
3704    fn json_summary_omits_finding_arrays_and_counts_security_findings() {
3705        let root = Path::new("/proj/root");
3706        let mut leak = relativize_finding(sample_finding(root), root);
3707        leak.severity = SecuritySeverity::High;
3708
3709        let mut sink = relativize_finding(sample_finding(root), root);
3710        sink.kind = SecurityFindingKind::TaintedSink;
3711        sink.category = Some("dangerous-html".to_string());
3712        sink.severity = SecuritySeverity::Medium;
3713        sink.source_backed = true;
3714        sink.reachability = Some(SecurityReachability {
3715            reachable_from_entry: true,
3716            reachable_from_untrusted_source: true,
3717            taint_confidence: Some(TaintConfidence::ArgLevel),
3718            untrusted_source_hop_count: Some(0),
3719            untrusted_source_trace: vec![],
3720            blast_radius: 3,
3721            crosses_boundary: true,
3722        });
3723        sink.runtime = Some(SecurityRuntimeContext {
3724            state: SecurityRuntimeState::RuntimeHot,
3725            function: "render".to_owned(),
3726            line: 10,
3727            invocations: Some(120),
3728            stable_id: Some("src/app.tsx::render:10".to_owned()),
3729            evidence: Some("production hot path observed".to_owned()),
3730        });
3731
3732        let mut output = output_with(vec![leak, sink], 2);
3733        output.elapsed_ms = ElapsedMs(17);
3734        output.unresolved_callee_sites = 3;
3735
3736        let rendered = render_json_summary(&output);
3737        let value: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
3738
3739        assert_eq!(value["kind"], "security");
3740        assert_eq!(value["schema_version"], "7");
3741        assert_eq!(value["version"], "test");
3742        assert_eq!(value["elapsed_ms"], 17);
3743        assert!(value.get("config").is_some());
3744        assert!(value.get("security_findings").is_none());
3745        assert!(value.get("attack_surface").is_none());
3746        assert!(value.get("_meta").is_none());
3747        assert_eq!(value["summary"]["security_findings"], 2);
3748        assert_eq!(value["summary"]["by_severity"]["high"], 1);
3749        assert_eq!(value["summary"]["by_severity"]["medium"], 1);
3750        assert_eq!(value["summary"]["by_severity"]["low"], 0);
3751        assert_eq!(value["summary"]["by_category"]["client-server-leak"], 1);
3752        assert_eq!(value["summary"]["by_category"]["dangerous-html"], 1);
3753        assert_eq!(value["summary"]["by_reachability"]["entry_reachable"], 1);
3754        assert_eq!(
3755            value["summary"]["by_reachability"]["untrusted_source_reachable"],
3756            1
3757        );
3758        assert_eq!(value["summary"]["by_reachability"]["arg_level"], 1);
3759        assert_eq!(value["summary"]["by_reachability"]["module_level"], 0);
3760        assert_eq!(value["summary"]["by_reachability"]["crosses_boundary"], 1);
3761        assert_eq!(value["summary"]["by_reachability"]["source_backed"], 1);
3762        assert_eq!(value["summary"]["by_runtime_state"]["runtime_hot"], 1);
3763        assert_eq!(value["summary"]["by_runtime_state"]["runtime_cold"], 0);
3764        assert_eq!(value["summary"]["by_runtime_state"]["never_executed"], 0);
3765        assert_eq!(value["summary"]["by_runtime_state"]["low_traffic"], 0);
3766        assert_eq!(
3767            value["summary"]["by_runtime_state"]["coverage_unavailable"],
3768            0
3769        );
3770        assert_eq!(value["summary"]["by_runtime_state"]["runtime_unknown"], 0);
3771        assert_eq!(value["summary"]["by_runtime_state"]["not_collected"], 1);
3772        assert_eq!(value["summary"]["unresolved_edge_files"], 2);
3773        assert_eq!(value["summary"]["unresolved_callee_sites"], 3);
3774        assert_eq!(value["summary"]["attack_surface_entries"], 0);
3775    }
3776
3777    #[test]
3778    fn json_summary_carries_security_meta_when_explain_requested() {
3779        let root = Path::new("/proj/root");
3780        let mut output = output_with(vec![relativize_finding(sample_finding(root), root)], 0);
3781        output.meta = Some(crate::explain::security_meta());
3782
3783        let rendered = render_json_summary(&output);
3784        let value: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
3785
3786        assert!(value.get("security_findings").is_none());
3787        assert!(value["_meta"]["field_definitions"]["security_findings[]"].is_string());
3788        assert!(value["_meta"]["field_definitions"]["summary.by_reachability"].is_string());
3789        assert!(value["_meta"]["field_definitions"]["summary.by_runtime_state"].is_string());
3790        assert!(value["_meta"]["field_definitions"]["unresolved_callee_sites"].is_string());
3791    }
3792
3793    #[test]
3794    fn json_summary_preserves_gate_block() {
3795        let output = output_with_gate(SecurityGateVerdict::Fail, 1);
3796        let rendered = render_json_summary(&output);
3797        let value: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
3798
3799        assert_eq!(value["kind"], "security");
3800        assert_eq!(value["gate"]["mode"], "new");
3801        assert_eq!(value["gate"]["verdict"], "fail");
3802        assert_eq!(value["gate"]["new_count"], 1);
3803        assert_eq!(value["summary"]["security_findings"], 0);
3804    }
3805
3806    #[test]
3807    fn json_render_carries_security_meta_when_explain_requested() {
3808        let mut output = output_with(vec![], 0);
3809        output.meta = Some(crate::explain::security_meta());
3810
3811        let rendered = render_json(&output);
3812        let value: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
3813
3814        assert_eq!(
3815            value["_meta"]["field_definitions"]["security_findings[]"],
3816            "Unverified security candidates for downstream human or agent verification."
3817        );
3818        assert!(value["_meta"]["rules"]["security/tainted-sink"].is_object());
3819    }
3820
3821    #[test]
3822    fn json_render_carries_candidate_record_and_omits_impact() {
3823        // Issue #900: every finding carries a 3-slot candidate record; there is
3824        // NO `impact` key on the wire (agent-owned, documented in the schema). A
3825        // client-server-leak has no source kind and no taint flow.
3826        let root = Path::new("/proj/root");
3827        let finding = relativize_finding(sample_finding(root), root);
3828        let rendered = render_json(&output_with(vec![finding], 0));
3829        let value: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
3830        let finding = &value["security_findings"][0];
3831
3832        let candidate = &finding["candidate"];
3833        assert!(candidate.is_object(), "candidate record present");
3834        assert!(candidate["sink"].is_object(), "sink slot present");
3835        assert_eq!(candidate["boundary"]["client_server"], true);
3836        assert!(
3837            candidate.get("impact").is_none(),
3838            "impact must NOT be a wire field"
3839        );
3840        assert!(
3841            candidate.get("source_kind").is_none(),
3842            "client-server-leak has no source kind"
3843        );
3844        assert!(
3845            finding.get("taint_flow").is_none(),
3846            "no untrusted-source flow on a client-server-leak"
3847        );
3848        assert!(
3849            finding.get("finding_id").is_some(),
3850            "finding_id is on the wire"
3851        );
3852    }
3853
3854    #[test]
3855    fn finding_id_is_stable_and_matches_sarif_fingerprint() {
3856        // Issue #900: one helper computes both the JSON finding_id and the SARIF
3857        // partialFingerprint, so an agent can join the two and they never drift.
3858        let root = Path::new("/proj/root");
3859        let finding = relativize_finding(sample_finding(root), root);
3860        let id = security_finding_id(&finding);
3861        assert!(!id.is_empty());
3862        assert_eq!(
3863            id,
3864            security_finding_id(&finding),
3865            "deterministic across calls"
3866        );
3867
3868        let sarif: serde_json::Value =
3869            serde_json::from_str(&render_sarif(&output_with(vec![finding], 0)))
3870                .expect("valid SARIF");
3871        assert_eq!(
3872            sarif["runs"][0]["results"][0]["partialFingerprints"]["fallowSecurity/v1"],
3873            serde_json::Value::String(id)
3874        );
3875    }
3876
3877    #[test]
3878    fn json_render_carries_dead_code_context() {
3879        let root = Path::new("/proj/root");
3880        let mut finding = relativize_finding(sample_finding(root), root);
3881        finding.kind = SecurityFindingKind::TaintedSink;
3882        finding.dead_code = Some(SecurityDeadCodeContext {
3883            kind: SecurityDeadCodeKind::UnusedExport,
3884            export_name: Some("handler".to_string()),
3885            line: Some(12),
3886            guidance: "remove export instead of harden".to_string(),
3887        });
3888        let rendered = render_json(&output_with(vec![finding], 0));
3889        let value: serde_json::Value = serde_json::from_str(&rendered).expect("valid JSON");
3890        let context = &value["security_findings"][0]["dead_code"];
3891        assert_eq!(context["kind"], "unused-export");
3892        assert_eq!(context["export_name"], "handler");
3893        assert_eq!(context["line"], 12);
3894    }
3895
3896    #[test]
3897    fn sarif_render_emits_warning_level_with_fingerprint_and_related_locations() {
3898        let root = Path::new("/proj/root");
3899        let finding = relativize_finding(sample_finding(root), root);
3900        let rendered = render_sarif(&output_with(vec![finding], 0));
3901        let sarif: serde_json::Value = serde_json::from_str(&rendered).expect("valid SARIF JSON");
3902        assert_eq!(sarif["version"], "2.1.0");
3903        let run = &sarif["runs"][0];
3904        assert_eq!(run["tool"]["driver"]["name"], "fallow");
3905        let result = &run["results"][0];
3906        // Candidate framing: a high-priority finding is warning, never error.
3907        assert_eq!(result["level"], "warning");
3908        assert_eq!(result["ruleId"], "security/client-server-leak");
3909        assert_eq!(result["message"]["text"], "reaches process.env.SECRET_KEY");
3910        // Trace hops surface as relatedLocations and codeFlows.
3911        assert_eq!(result["relatedLocations"].as_array().unwrap().len(), 3);
3912        let flow_locations = result["codeFlows"][0]["threadFlows"][0]["locations"]
3913            .as_array()
3914            .expect("thread flow locations");
3915        assert_eq!(flow_locations.len(), 3);
3916        assert_eq!(
3917            flow_locations[0]["location"]["physicalLocation"]["artifactLocation"]["uri"],
3918            "src/app.tsx"
3919        );
3920        assert_eq!(
3921            flow_locations[2]["location"]["physicalLocation"]["artifactLocation"]["uri"],
3922            "src/lib/secret.ts"
3923        );
3924        assert_eq!(
3925            flow_locations[2]["kinds"][0],
3926            serde_json::json!("secret-source")
3927        );
3928        // Stable dedup fingerprint present for GHAS.
3929        assert!(result["partialFingerprints"]["fallowSecurity/v1"].is_string());
3930
3931        let rules = run["tool"]["driver"]["rules"].as_array().unwrap();
3932        assert_eq!(rules[0]["name"], "Client-server secret leak");
3933        assert!(rules[0]["help"]["text"].is_string());
3934        assert!(rules[0].get("relationships").is_none());
3935        assert!(run.get("taxonomies").is_none());
3936    }
3937
3938    #[test]
3939    fn sarif_render_keeps_low_severity_as_note() {
3940        let root = Path::new("/proj/root");
3941        let mut finding = sample_finding(root);
3942        finding.severity = SecuritySeverity::Low;
3943        let rendered = render_sarif(&output_with(vec![relativize_finding(finding, root)], 0));
3944        let sarif: serde_json::Value = serde_json::from_str(&rendered).expect("valid SARIF JSON");
3945
3946        assert_eq!(sarif["runs"][0]["results"][0]["level"], "note");
3947    }
3948
3949    #[test]
3950    fn sarif_render_includes_dead_code_hint_in_message() {
3951        let root = Path::new("/proj/root");
3952        let mut finding = relativize_finding(sample_finding(root), root);
3953        finding.kind = SecurityFindingKind::TaintedSink;
3954        finding.dead_code = Some(SecurityDeadCodeContext {
3955            kind: SecurityDeadCodeKind::UnusedFile,
3956            export_name: None,
3957            line: None,
3958            guidance: "delete instead of harden".to_string(),
3959        });
3960        let rendered = render_sarif(&output_with(vec![finding], 0));
3961        let sarif: serde_json::Value = serde_json::from_str(&rendered).expect("valid SARIF JSON");
3962        let message = sarif["runs"][0]["results"][0]["message"]["text"]
3963            .as_str()
3964            .expect("message text");
3965        assert!(message.contains("Dead-code cross-link"), "got: {message}");
3966        assert!(
3967            message.contains("delete this file instead of hardening"),
3968            "got: {message}"
3969        );
3970    }
3971
3972    #[test]
3973    fn sarif_render_includes_untrusted_source_context_and_related_locations() {
3974        let root = Path::new("/proj/root");
3975        let mut finding = sample_finding(root);
3976        finding.kind = SecurityFindingKind::TaintedSink;
3977        finding.category = Some("command-injection".to_string());
3978        add_untrusted_source_reachability(&mut finding, root);
3979        add_taint_flow(&mut finding, root);
3980        finding.trace.push(TraceHop {
3981            path: root.join("src/lib/sink.ts"),
3982            line: 9,
3983            col: 2,
3984            role: TraceHopRole::Sink,
3985        });
3986        let rendered = render_sarif(&output_with(vec![relativize_finding(finding, root)], 0));
3987        let sarif: serde_json::Value = serde_json::from_str(&rendered).expect("valid SARIF JSON");
3988        let result = &sarif["runs"][0]["results"][0];
3989        let message = result["message"]["text"].as_str().expect("message text");
3990        assert!(message.contains("Module-level context"), "got: {message}");
3991        assert!(
3992            message.contains("does not prove value flow"),
3993            "got: {message}"
3994        );
3995        // The sink appears in both trace families, but SARIF relatedLocations requires unique items.
3996        assert_eq!(result["relatedLocations"].as_array().unwrap().len(), 5);
3997        let flow_locations = result["codeFlows"][0]["threadFlows"][0]["locations"]
3998            .as_array()
3999            .expect("thread flow locations");
4000        assert_eq!(flow_locations.len(), 2);
4001        assert_eq!(
4002            flow_locations[0]["location"]["physicalLocation"]["artifactLocation"]["uri"],
4003            "src/routes/api.ts"
4004        );
4005        assert_eq!(
4006            flow_locations[1]["location"]["physicalLocation"]["artifactLocation"]["uri"],
4007            "src/lib/sink.ts"
4008        );
4009    }
4010
4011    #[test]
4012    fn sarif_tainted_sink_uses_per_category_rule_id_and_cwe_metadata() {
4013        let root = Path::new("/proj/root");
4014        let mut finding = sample_finding(root);
4015        finding.kind = SecurityFindingKind::TaintedSink;
4016        finding.category = Some("dangerous-html".to_owned());
4017        finding.cwe = Some(79);
4018        let rendered = render_sarif(&output_with(vec![relativize_finding(finding, root)], 0));
4019        let sarif: serde_json::Value = serde_json::from_str(&rendered).expect("valid SARIF JSON");
4020        let run = &sarif["runs"][0];
4021        // The finding is grouped under its own per-category rule, not collapsed
4022        // into client-server-leak, and stays candidate-framed.
4023        let result = &run["results"][0];
4024        assert_eq!(result["level"], "warning");
4025        assert_eq!(result["ruleId"], "security/dangerous-html");
4026        // Exactly one rule definition, carrying compatible tags plus SARIF-native CWE taxonomy.
4027        let rules = run["tool"]["driver"]["rules"].as_array().unwrap();
4028        assert_eq!(rules.len(), 1);
4029        assert_eq!(rules[0]["id"], "security/dangerous-html");
4030        assert_eq!(rules[0]["name"], "Dangerous HTML sink");
4031        assert!(
4032            rules[0]["help"]["text"]
4033                .as_str()
4034                .expect("help text")
4035                .contains("Verify this unverified")
4036        );
4037        assert!(
4038            rules[0]["help"]["markdown"]
4039                .as_str()
4040                .expect("help markdown")
4041                .contains("**Dangerous HTML sink**")
4042        );
4043        let tags = rules[0]["properties"]["tags"].as_array().unwrap();
4044        assert!(tags.iter().any(|t| t == "external/cwe/cwe-79"));
4045        let relationship = &rules[0]["relationships"][0];
4046        assert_eq!(relationship["target"]["id"], "CWE-79");
4047        assert_eq!(relationship["target"]["index"], 0);
4048        assert_eq!(relationship["target"]["toolComponent"]["name"], "CWE");
4049        assert_eq!(relationship["kinds"][0], "superset");
4050
4051        let taxonomy = &run["taxonomies"][0];
4052        assert_eq!(taxonomy["name"], "CWE");
4053        assert_eq!(taxonomy["taxa"][0]["id"], "CWE-79");
4054        assert_eq!(
4055            run["tool"]["driver"]["supportedTaxonomies"][0]["name"],
4056            "CWE"
4057        );
4058    }
4059
4060    #[test]
4061    fn write_sarif_file_creates_parent_dir_and_writes_valid_sarif() {
4062        let root = Path::new("/proj/root");
4063        let finding = relativize_finding(sample_finding(root), root);
4064        let output = output_with(vec![finding], 0);
4065        let dir = tempfile::tempdir().expect("tempdir");
4066        let path = dir.path().join("nested/out.sarif");
4067        write_sarif_file(&output, &path).expect("write succeeds and creates parent dir");
4068        let written = std::fs::read_to_string(&path).expect("file exists");
4069        let sarif: serde_json::Value = serde_json::from_str(&written).expect("valid SARIF JSON");
4070        assert_eq!(sarif["version"], "2.1.0");
4071    }
4072
4073    /// No explicit `--config`; static so the `&'a Option<PathBuf>` field borrows it.
4074    const NO_CONFIG: Option<PathBuf> = None;
4075
4076    fn leak_fixture_root() -> PathBuf {
4077        Path::new(env!("CARGO_MANIFEST_DIR"))
4078            .join("../../tests/fixtures/security-client-server-leak")
4079    }
4080
4081    fn source_reachability_fixture_root() -> PathBuf {
4082        Path::new(env!("CARGO_MANIFEST_DIR"))
4083            .join("../../tests/fixtures/security-source-reachability-885")
4084    }
4085
4086    fn run_opts(root: &Path, output: OutputFormat, fail_on_issues: bool) -> SecurityOptions<'_> {
4087        SecurityOptions {
4088            root,
4089            config_path: &NO_CONFIG,
4090            output,
4091            no_cache: true,
4092            threads: 1,
4093            quiet: true,
4094            fail_on_issues,
4095            sarif_file: None,
4096            summary: false,
4097            changed_since: None,
4098            use_shared_diff_index: false,
4099            workspace: None,
4100            changed_workspaces: None,
4101            file: &[],
4102            surface: false,
4103            gate: None,
4104            runtime_coverage: None,
4105            min_invocations_hot: 100,
4106            explain: false,
4107        }
4108    }
4109
4110    #[test]
4111    fn source_reachability_fixture_marks_cross_module_sink() {
4112        let root = source_reachability_fixture_root();
4113        let mut config = load_config_for_analysis(
4114            &root,
4115            &NO_CONFIG,
4116            crate::ConfigLoadOptions {
4117                output: OutputFormat::Json,
4118                no_cache: true,
4119                threads: 1,
4120                production_override: None,
4121                quiet: true,
4122            },
4123            ProductionAnalysis::DeadCode,
4124        )
4125        .expect("fixture config loads");
4126        config.rules.security_sink = Severity::Warn;
4127
4128        let analysis = fallow_engine::analyze(&config).expect("fixture analyzes");
4129        let finding = analysis
4130            .results
4131            .security_findings
4132            .iter()
4133            .find(|finding| finding.path.ends_with("src/runner.ts"))
4134            .expect("runner sink finding");
4135        let reach = finding.reachability.as_ref().expect("reachability");
4136
4137        assert!(reach.reachable_from_untrusted_source);
4138        assert_eq!(reach.untrusted_source_hop_count, Some(1));
4139        // Cross-module reachability is module-level: the structured discriminator
4140        // says so, and the source node is honestly labeled `ModuleSource`, never
4141        // `UntrustedSource` (which is reserved for an arg-level same-module read).
4142        assert_eq!(reach.taint_confidence, Some(TaintConfidence::ModuleLevel));
4143        assert_eq!(
4144            reach
4145                .untrusted_source_trace
4146                .iter()
4147                .map(|hop| hop.role)
4148                .collect::<Vec<_>>(),
4149            vec![TraceHopRole::ModuleSource, TraceHopRole::Sink]
4150        );
4151        assert!(
4152            reach.untrusted_source_trace[0]
4153                .path
4154                .ends_with("src/route.ts")
4155        );
4156
4157        // Issue #900: the candidate boundary slot records the cross-module hop,
4158        // and the taint-flow triple re-projects the reachability endpoints + a
4159        // compact path (not a duplicate hop array).
4160        assert!(
4161            finding.candidate.boundary.cross_module,
4162            "a sink reached across a module hop crosses a module boundary"
4163        );
4164        let flow = finding.taint_flow.as_ref().expect("taint_flow present");
4165        assert!(!flow.path.intra_module);
4166        assert_eq!(flow.path.cross_module_hops, 1);
4167        assert!(flow.source.path.ends_with("src/route.ts"));
4168        assert!(flow.sink.path.ends_with("src/runner.ts"));
4169    }
4170
4171    #[test]
4172    fn file_scope_keeps_security_finding_when_anchor_matches() {
4173        let root = Path::new("/proj/root");
4174        let mut results = AnalysisResults::default();
4175        results.security_findings.push(sample_finding(root));
4176
4177        filter_to_files(&mut results, root, &[PathBuf::from("src/app.tsx")], true);
4178
4179        assert_eq!(results.security_findings.len(), 1);
4180    }
4181
4182    #[test]
4183    fn file_scope_keeps_security_finding_when_trace_hop_matches() {
4184        let root = Path::new("/proj/root");
4185        let mut results = AnalysisResults::default();
4186        results.security_findings.push(sample_finding(root));
4187
4188        filter_to_files(
4189            &mut results,
4190            root,
4191            &[PathBuf::from("src/lib/secret.ts")],
4192            true,
4193        );
4194
4195        assert_eq!(results.security_findings.len(), 1);
4196    }
4197
4198    #[test]
4199    fn file_scope_drops_unrelated_security_finding() {
4200        let root = Path::new("/proj/root");
4201        let mut results = AnalysisResults::default();
4202        results.security_findings.push(sample_finding(root));
4203
4204        filter_to_files(&mut results, root, &[PathBuf::from("src/other.ts")], true);
4205
4206        assert!(results.security_findings.is_empty());
4207    }
4208
4209    #[test]
4210    fn run_is_advisory_and_exits_zero_even_with_candidates() {
4211        // The rule defaults to off; the command forces it to warn, so findings on
4212        // the fixture are surfaced but the exit stays 0 (advisory) by default.
4213        let root = leak_fixture_root();
4214        let code = run(&run_opts(&root, OutputFormat::Json, false));
4215        assert_eq!(code, ExitCode::SUCCESS);
4216    }
4217
4218    #[test]
4219    fn run_with_fail_on_issues_exits_one_when_candidates_found() {
4220        // The fixture has real leak candidates, so --fail-on-issues raises exit 1.
4221        let root = leak_fixture_root();
4222        let code = run(&run_opts(&root, OutputFormat::Human, true));
4223        assert_eq!(code, ExitCode::from(1));
4224    }
4225
4226    #[test]
4227    fn run_rejects_unsupported_output_format() {
4228        // Only human / json / sarif are supported; compact exits 2 before analysis.
4229        let root = leak_fixture_root();
4230        let code = run(&run_opts(&root, OutputFormat::Compact, false));
4231        assert_eq!(code, ExitCode::from(2));
4232    }
4233
4234    #[test]
4235    fn run_summary_mode_dispatches_compact_human_renderer() {
4236        let root = leak_fixture_root();
4237        let opts = SecurityOptions {
4238            summary: true,
4239            ..run_opts(&root, OutputFormat::Human, false)
4240        };
4241        assert_eq!(run(&opts), ExitCode::SUCCESS);
4242    }
4243
4244    #[test]
4245    fn run_sarif_format_dispatches_sarif_renderer() {
4246        let root = leak_fixture_root();
4247        assert_eq!(
4248            run(&run_opts(&root, OutputFormat::Sarif, false)),
4249            ExitCode::SUCCESS
4250        );
4251    }
4252
4253    #[test]
4254    fn run_writes_sarif_sidecar_file_when_requested() {
4255        let root = leak_fixture_root();
4256        let dir = tempfile::tempdir().expect("tempdir");
4257        let sidecar = dir.path().join("security.sarif");
4258        let opts = SecurityOptions {
4259            sarif_file: Some(&sidecar),
4260            ..run_opts(&root, OutputFormat::Human, false)
4261        };
4262        assert_eq!(run(&opts), ExitCode::SUCCESS);
4263        let written = std::fs::read_to_string(&sidecar).expect("sidecar SARIF written");
4264        let sarif: serde_json::Value = serde_json::from_str(&written).expect("valid SARIF JSON");
4265        assert_eq!(sarif["version"], "2.1.0");
4266    }
4267}