Skip to main content

fallow_output/
security.rs

1//! Security command output contracts.
2
3use std::collections::BTreeMap;
4
5use crate::root_envelopes::{attach_telemetry_meta, serialize_named_json_output};
6use fallow_types::envelope::{ElapsedMs, Meta, ToolVersion};
7use fallow_types::results::{
8    SecurityAttackSurfaceEntry, SecurityFinding, SecurityFindingKind, SecurityRuntimeState,
9    SecuritySeverity, TaintConfidence,
10};
11use fallow_types::workspace::WorkspaceDiagnostic;
12use serde::{Deserialize, Serialize, de::DeserializeOwned};
13
14/// Current `fallow security --format json` schema version.
15pub const SECURITY_SCHEMA_VERSION: u32 = 8;
16
17/// The `fallow security --format json` schema version. Independently versioned
18/// from the main contract, mirroring `ImpactReportSchemaVersion`.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21pub enum SecuritySchemaVersion {
22    /// First release of the `fallow security --format json` shape.
23    #[serde(rename = "1")]
24    V1,
25    /// Adds per-finding `severity` for verification-priority tiering.
26    #[serde(rename = "2")]
27    V2,
28    /// Adds version, elapsed time, explain metadata, and safe config metadata.
29    #[serde(rename = "3")]
30    V3,
31    /// Adds bounded diagnostics for unresolved callee blind spots.
32    #[serde(rename = "4")]
33    V4,
34    /// Adds summary metadata to security summary JSON.
35    #[serde(rename = "5")]
36    V5,
37    /// Adds `candidate.sink.url_shape` for URL-shaped security candidates.
38    #[serde(rename = "6")]
39    V6,
40    /// Adds the server-only-import category on client-server-leak findings.
41    #[serde(rename = "7")]
42    V7,
43    /// Expands the required semantic omission reason-code enum.
44    #[serde(rename = "8")]
45    V8,
46}
47
48/// Gate verdict on the wire. `fail` is the CI-state token; human output renders
49/// it as "REVIEW REQUIRED" because these stay unverified candidates, never
50/// confirmed vulnerabilities.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
52#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
53#[serde(rename_all = "kebab-case")]
54pub enum SecurityGateVerdict {
55    /// No new candidate in the changed lines.
56    Pass,
57    /// At least one new candidate in the changed lines.
58    Fail,
59}
60
61/// The `gate` block on `SecurityOutput`, present only when `--gate <mode>` ran.
62/// Invariant: `verdict == Fail  IFF  exit code 8  IFF  new_count > 0`.
63#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
64#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
65pub struct SecurityGate<Mode> {
66    /// Gate mode that was selected on the command line.
67    pub mode: Mode,
68    /// Gate outcome for this run.
69    pub verdict: SecurityGateVerdict,
70    /// Number of candidates matching the selected gate mode.
71    pub new_count: usize,
72}
73
74/// Allowlisted config context for `fallow security --format json`.
75#[derive(Debug, Clone, Deserialize, Serialize)]
76#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
77#[cfg_attr(
78    feature = "schema",
79    schemars(extend("required" = ["rules", "categories_include", "categories_exclude"]))
80)]
81pub struct SecurityOutputConfig<Severity> {
82    /// Relevant rule severities before and after this command applies its
83    /// default-on behavior for security-only rules. These values come from the
84    /// top-level `rules` only. A matching `overrides` entry can set another
85    /// severity for a path: `off` drops the candidates in that path, and
86    /// `error` makes the run fail, also when the value here is `warn`.
87    pub rules: SecurityOutputRulesConfig<Severity>,
88    /// `security.categories.include` from config. `null` means unset, `[]`
89    /// means explicitly empty.
90    pub categories_include: Option<Vec<String>>,
91    /// `security.categories.exclude` from config. `null` means unset, `[]`
92    /// means explicitly empty.
93    pub categories_exclude: Option<Vec<String>>,
94}
95
96/// Per-rule severity context inside [`SecurityOutputConfig::rules`].
97#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
98#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
99pub struct SecurityOutputRulesConfig<Severity> {
100    /// Severity context for the client-server-leak rule.
101    pub security_client_server_leak: SecurityRuleSeverityConfig<Severity>,
102    /// Severity context for the security-sink rule.
103    pub security_sink: SecurityRuleSeverityConfig<Severity>,
104}
105
106/// Configured-versus-effective severity for one security rule.
107#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
108#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
109pub struct SecurityRuleSeverityConfig<Severity> {
110    /// Top-level severity read from resolved config before the security
111    /// command applies its default-on behavior. Per-path `overrides` are not
112    /// part of this value.
113    pub configured: Severity,
114    /// Top-level severity used for this command run. A matching `overrides`
115    /// entry can drop a candidate (`off`) or fail the run (`error`) for its
116    /// path, also when this value is `warn`.
117    pub effective: Severity,
118}
119
120/// The `fallow security --format json` envelope. `FallowOutput` discriminates it
121/// by the `kind: "security"` tag; the optional `gate` block is additive and is
122/// not part of that discrimination.
123#[derive(Debug, Clone, Serialize)]
124#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
125pub struct SecurityOutput<Config, Gate> {
126    /// Schema version of this envelope.
127    pub schema_version: SecuritySchemaVersion,
128    /// Fallow CLI version that produced this output.
129    pub version: ToolVersion,
130    /// Wall-clock milliseconds spent producing the report.
131    pub elapsed_ms: ElapsedMs,
132    /// Privacy-safe config context relevant to security candidate generation.
133    pub config: Config,
134    /// The verdict of every gate this run evaluated, keyed by name. The CLI
135    /// always emits it, with the command's default exit rule in it also when
136    /// no flag armed a gate, so a CI integration reads the verdict instead of
137    /// guessing from a process status it usually cannot see. A gate fails the
138    /// build when `status` is `fail` and `enforced` is true. The typed
139    /// programmatic API runs no CLI gate and leaves it absent. See
140    /// [`crate::GateOutcomes`].
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub gate_outcomes: Option<crate::GateOutcomes>,
143    /// Every narrowing or shaping request this run received, keyed by name,
144    /// absent when it was asked for nothing. An entry whose `status` is not
145    /// `applied` means the run could not do what it was asked and reported
146    /// something wider instead, so what follows is a valid report of a scope
147    /// nobody requested. Honoured requests are published too, with
148    /// `status: "applied"`, so an absent object means "nothing was asked for",
149    /// never "nothing failed". See [`crate::RequestOutcomes`].
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub request_outcomes: Option<crate::RequestOutcomes>,
152    /// `_meta` block. A `--format json` run of the CLI always sets
153    /// `telemetry.analysis_run_id`. With `--explain`, it also holds the
154    /// security rule and field definitions.
155    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
156    pub meta: Option<Meta>,
157    /// Gate verdict, present only when `--gate <mode>` was set (issue #886).
158    /// Emitted on pass too (`verdict: "pass"`, `new_count: 0`) so consumers
159    /// distinguish "gate ran and passed" from "gate did not run" (absent).
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub gate: Option<Gate>,
162    /// Diagnostics owned by this security analysis run.
163    #[serde(default, skip_serializing_if = "Vec::is_empty")]
164    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
165    /// Security candidates. Paths are project-root-relative, forward-slash.
166    pub security_findings: Vec<SecurityFinding>,
167    /// Opt-in attack-surface inventory from untrusted entry points to reachable
168    /// sinks. Present only when `--surface` was requested.
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub attack_surface: Option<Vec<SecurityAttackSurfaceEntry>>,
171    /// In-band blind spot: number of `"use client"` files whose transitive
172    /// import cone contains a dynamic `import()` the reachability BFS could not
173    /// follow. A leak hidden behind such an edge would not be reported, so a
174    /// zero finding count with a non-zero value here is NOT a clean bill.
175    pub unresolved_edge_files: usize,
176    /// In-band blind spot: number of sink-shaped nodes the catalogue detector
177    /// could not flatten to a static callee path (dynamic dispatch, computed
178    /// members, aliased bindings). A zero finding count with a non-zero value
179    /// here is NOT a clean bill.
180    pub unresolved_callee_sites: usize,
181    /// Bounded diagnostics for unresolved callee blind spots.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub unresolved_callee_diagnostics: Option<SecurityUnresolvedCalleeDiagnostics>,
184}
185
186/// Bounded unresolved-callee diagnostics for `fallow security --format json`.
187#[derive(Debug, Clone, Deserialize, Serialize)]
188#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
189pub struct SecurityUnresolvedCalleeDiagnostics {
190    /// Deterministic sample rows, capped by `sample_limit`.
191    pub sampled: Vec<SecurityUnresolvedCalleeSample>,
192    /// Files with the most unresolved callees, capped by `top_files_limit`.
193    pub top_files: Vec<SecurityUnresolvedCalleeTopFile>,
194    /// Full count by unresolved-callee reason, sorted by count then reason.
195    pub by_reason: Vec<SecurityUnresolvedCalleeReasonCount>,
196    /// Maximum number of sample rows emitted.
197    pub sample_limit: usize,
198    /// Maximum number of top-file rows emitted.
199    pub top_files_limit: usize,
200}
201
202/// One sampled unresolved-callee row.
203#[derive(Debug, Clone, Deserialize, Serialize)]
204#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
205pub struct SecurityUnresolvedCalleeSample {
206    /// File path relative to the analysed root.
207    pub path: String,
208    /// 1-based line of the skipped call site.
209    pub line: u32,
210    /// 1-based column of the skipped call site.
211    pub col: u32,
212    /// Why the callee could not be resolved.
213    pub reason: fallow_types::extract::SkippedSecurityCalleeReason,
214    /// Compact syntax shape of the skipped callee.
215    pub expression_kind: fallow_types::extract::SkippedSecurityCalleeExpressionKind,
216}
217
218/// Count of unresolved callees in one file.
219#[derive(Debug, Clone, Deserialize, Serialize)]
220#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
221pub struct SecurityUnresolvedCalleeTopFile {
222    /// File path relative to the analysed root.
223    pub path: String,
224    /// Number of unresolved callees in this file.
225    pub count: usize,
226}
227
228/// Count of unresolved callees for one reason.
229#[derive(Debug, Clone, Deserialize, Serialize)]
230#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
231pub struct SecurityUnresolvedCalleeReasonCount {
232    /// Why the callees could not be resolved.
233    pub reason: fallow_types::extract::SkippedSecurityCalleeReason,
234    /// Number of unresolved callees with this reason.
235    pub count: usize,
236}
237
238/// Compact `fallow security --summary --format json` payload. Uses the same
239/// `kind: "security"` discriminator as the full payload, but omits candidate
240/// arrays and exposes only aggregate counts.
241#[derive(Debug, Clone, Serialize)]
242#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
243pub struct SecuritySummaryOutput<Config, Gate> {
244    /// Schema version of this envelope.
245    pub schema_version: SecuritySchemaVersion,
246    /// Fallow CLI version that produced this output.
247    pub version: ToolVersion,
248    /// Wall-clock milliseconds spent producing the report.
249    pub elapsed_ms: ElapsedMs,
250    /// Privacy-safe config context relevant to security candidate generation.
251    pub config: Config,
252    /// The verdict of every gate this run evaluated, keyed by name. The CLI
253    /// always emits it, with the command's default exit rule in it also when
254    /// no flag armed a gate, so a CI integration reads the verdict instead of
255    /// guessing from a process status it usually cannot see. A gate fails the
256    /// build when `status` is `fail` and `enforced` is true. The typed
257    /// programmatic API runs no CLI gate and leaves it absent. See
258    /// [`crate::GateOutcomes`].
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub gate_outcomes: Option<crate::GateOutcomes>,
261    /// Every narrowing or shaping request this run received, keyed by name,
262    /// absent when it was asked for nothing. An entry whose `status` is not
263    /// `applied` means the run could not do what it was asked and reported
264    /// something wider instead, so what follows is a valid report of a scope
265    /// nobody requested. Honoured requests are published too, with
266    /// `status: "applied"`, so an absent object means "nothing was asked for",
267    /// never "nothing failed". See [`crate::RequestOutcomes`].
268    #[serde(default, skip_serializing_if = "Option::is_none")]
269    pub request_outcomes: Option<crate::RequestOutcomes>,
270    /// `_meta` block. A `--format json` run of the CLI always sets
271    /// `telemetry.analysis_run_id`. With `--explain`, it also holds the
272    /// security rule and field definitions.
273    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
274    pub meta: Option<Meta>,
275    /// Gate verdict, present only when `--gate <mode>` was set.
276    #[serde(default, skip_serializing_if = "Option::is_none")]
277    pub gate: Option<Gate>,
278    /// Diagnostics owned by the full security analysis summarized here.
279    #[serde(default, skip_serializing_if = "Vec::is_empty")]
280    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
281    /// Aggregate security counts after all filters, gates, and scopes.
282    pub summary: SecuritySummary,
283}
284
285#[derive(Deserialize)]
286#[serde(rename_all = "kebab-case")]
287enum SavedSecurityGateMode {
288    New,
289    NewlyReachable,
290}
291
292#[derive(Deserialize)]
293struct SavedSecurityEnvelope {
294    #[serde(rename = "version")]
295    _version: String,
296    #[serde(rename = "elapsed_ms")]
297    _elapsed_ms: u64,
298    #[serde(rename = "config")]
299    _config: SecurityOutputConfig<fallow_config::Severity>,
300    #[serde(rename = "_meta", default)]
301    meta: Option<serde_json::Value>,
302    #[serde(rename = "gate", default)]
303    _gate: Option<SecurityGate<SavedSecurityGateMode>>,
304}
305
306#[derive(Deserialize)]
307struct SavedSecurityFullPayload {
308    #[serde(rename = "security_findings")]
309    _security_findings: Vec<SecurityFinding>,
310    #[serde(rename = "attack_surface", default)]
311    _attack_surface: Option<Vec<SecurityAttackSurfaceEntry>>,
312    #[serde(rename = "unresolved_edge_files")]
313    _unresolved_edge_files: usize,
314    #[serde(rename = "unresolved_callee_sites")]
315    _unresolved_callee_sites: usize,
316    #[serde(rename = "unresolved_callee_diagnostics", default)]
317    _unresolved_callee_diagnostics: Option<SecurityUnresolvedCalleeDiagnostics>,
318}
319
320#[derive(Deserialize)]
321struct SavedSecuritySummaryPayload {
322    #[serde(rename = "summary")]
323    _summary: SecuritySummary,
324}
325
326/// Validate a saved security envelope against the current output-owned schema.
327///
328/// Older known schemas remain readable for compatibility. Current envelopes
329/// fail closed when required fields or nested payloads are malformed.
330pub fn validate_saved_security_envelope(value: &serde_json::Value) -> Result<(), String> {
331    let raw_version = value
332        .get("schema_version")
333        .and_then(serde_json::Value::as_str)
334        .ok_or_else(|| "saved security envelope is missing a string `schema_version`".to_owned())?;
335    let version = raw_version.parse::<u32>().map_err(|_| {
336        format!("saved security envelope has invalid schema version `{raw_version}`")
337    })?;
338    let current = SECURITY_SCHEMA_VERSION;
339    if version == 0 || version > current {
340        return Err(format!(
341            "unsupported saved security schema version {version}; this Fallow version supports versions 1 through {current}"
342        ));
343    }
344    if version < current {
345        return Ok(());
346    }
347
348    let envelope: SavedSecurityEnvelope = parse_saved_security(value, "envelope")?;
349    if let Some(meta) = envelope.meta {
350        let meta = meta
351            .as_object()
352            .ok_or_else(|| "saved security envelope field `_meta` must be an object".to_owned())?;
353        if let Some(type_aware) = meta.get("type_aware").filter(|value| !value.is_null()) {
354            parse_saved_security::<fallow_types::envelope::TypeAwareMeta>(
355                type_aware,
356                "type-aware metadata",
357            )?;
358        }
359    }
360
361    if value.get("security_findings").is_some() {
362        parse_saved_security::<SavedSecurityFullPayload>(value, "full payload")?;
363    } else if value.get("summary").is_some() {
364        parse_saved_security::<SavedSecuritySummaryPayload>(value, "summary payload")?;
365    } else {
366        return Err(
367            "saved security envelope is missing `security_findings` or `summary`".to_owned(),
368        );
369    }
370    Ok(())
371}
372
373fn parse_saved_security<T: DeserializeOwned>(
374    value: &serde_json::Value,
375    label: &str,
376) -> Result<T, String> {
377    T::deserialize(value).map_err(|error| {
378        format!("saved security {label} is incompatible with this Fallow version: {error}")
379    })
380}
381
382/// Build the compact aggregate payload for `fallow security --summary --format json`.
383#[must_use]
384pub fn build_security_summary<Config, Gate>(
385    output: &SecurityOutput<Config, Gate>,
386) -> SecuritySummary {
387    let mut counts = SecuritySummaryCounts::default();
388
389    for finding in &output.security_findings {
390        counts.record(finding);
391    }
392
393    SecuritySummary {
394        security_findings: output.security_findings.len(),
395        by_severity: counts.severity,
396        by_category: counts.category,
397        by_reachability: counts.reachability,
398        by_runtime_state: counts.runtime_state,
399        unresolved_edge_files: output.unresolved_edge_files,
400        unresolved_callee_sites: output.unresolved_callee_sites,
401        attack_surface_entries: output.attack_surface.as_ref().map_or(0, Vec::len),
402    }
403}
404
405#[derive(Default)]
406struct SecuritySummaryCounts {
407    severity: SecuritySeverityCounts,
408    category: BTreeMap<String, usize>,
409    reachability: SecurityReachabilityCounts,
410    runtime_state: SecurityRuntimeStateCounts,
411}
412
413impl SecuritySummaryCounts {
414    fn record(&mut self, finding: &SecurityFinding) {
415        record_security_severity(finding.severity, &mut self.severity);
416        record_security_category(finding, &mut self.category);
417        record_security_reachability(finding, &mut self.reachability);
418        record_security_runtime_state(finding, &mut self.runtime_state);
419    }
420}
421
422fn record_security_severity(severity: SecuritySeverity, by_severity: &mut SecuritySeverityCounts) {
423    match severity {
424        SecuritySeverity::High => by_severity.high += 1,
425        SecuritySeverity::Medium => by_severity.medium += 1,
426        SecuritySeverity::Low => by_severity.low += 1,
427    }
428}
429
430fn record_security_category(finding: &SecurityFinding, by_category: &mut BTreeMap<String, usize>) {
431    let category = finding
432        .category
433        .clone()
434        .unwrap_or_else(|| security_kind_key(finding.kind).to_owned());
435    *by_category.entry(category).or_insert(0) += 1;
436}
437
438fn security_kind_key(kind: SecurityFindingKind) -> &'static str {
439    match kind {
440        SecurityFindingKind::ClientServerLeak => "client-server-leak",
441        SecurityFindingKind::TaintedSink => "tainted-sink",
442    }
443}
444
445fn record_security_reachability(
446    finding: &SecurityFinding,
447    by_reachability: &mut SecurityReachabilityCounts,
448) {
449    if finding.source_backed {
450        by_reachability.source_backed += 1;
451    }
452    let Some(reachability) = &finding.reachability else {
453        return;
454    };
455
456    if reachability.reachable_from_entry {
457        by_reachability.entry_reachable += 1;
458    }
459    if reachability.reachable_from_untrusted_source {
460        by_reachability.untrusted_source_reachable += 1;
461    }
462    if reachability.crosses_boundary {
463        by_reachability.crosses_boundary += 1;
464    }
465    match reachability.taint_confidence {
466        Some(TaintConfidence::ArgLevel) => by_reachability.arg_level += 1,
467        Some(TaintConfidence::ModuleLevel) => by_reachability.module_level += 1,
468        None => {}
469    }
470}
471
472fn record_security_runtime_state(
473    finding: &SecurityFinding,
474    by_runtime_state: &mut SecurityRuntimeStateCounts,
475) {
476    match finding.runtime.as_ref().map(|runtime| runtime.state) {
477        Some(SecurityRuntimeState::RuntimeHot) => by_runtime_state.runtime_hot += 1,
478        Some(SecurityRuntimeState::RuntimeCold) => by_runtime_state.runtime_cold += 1,
479        Some(SecurityRuntimeState::NeverExecuted) => by_runtime_state.never_executed += 1,
480        Some(SecurityRuntimeState::LowTraffic) => by_runtime_state.low_traffic += 1,
481        Some(SecurityRuntimeState::CoverageUnavailable) => {
482            by_runtime_state.coverage_unavailable += 1;
483        }
484        Some(SecurityRuntimeState::RuntimeUnknown) => by_runtime_state.runtime_unknown += 1,
485        None => by_runtime_state.not_collected += 1,
486    }
487}
488
489/// Serialize the full `fallow security --format json` envelope.
490///
491/// # Errors
492///
493/// Returns a serde error when the envelope cannot be converted to JSON.
494pub fn serialize_security_json_output<Config, Gate>(
495    output: SecurityOutput<Config, Gate>,
496    analysis_run_id: Option<&str>,
497) -> Result<serde_json::Value, serde_json::Error>
498where
499    Config: Serialize,
500    Gate: Serialize,
501{
502    let mut value = serialize_named_json_output(output, "security")?;
503    attach_telemetry_meta(&mut value, analysis_run_id);
504    Ok(value)
505}
506
507/// Serialize the compact `fallow security --summary --format json` envelope.
508///
509/// # Errors
510///
511/// Returns a serde error when the envelope cannot be converted to JSON.
512pub fn serialize_security_summary_json_output<Config, Gate>(
513    output: &SecurityOutput<Config, Gate>,
514    analysis_run_id: Option<&str>,
515) -> Result<serde_json::Value, serde_json::Error>
516where
517    Config: Clone + Serialize,
518    Gate: Copy + Serialize,
519{
520    let summary = SecuritySummaryOutput {
521        schema_version: output.schema_version,
522        version: output.version.clone(),
523        elapsed_ms: output.elapsed_ms,
524        config: output.config.clone(),
525        gate_outcomes: output.gate_outcomes.clone(),
526        request_outcomes: output.request_outcomes.clone(),
527        meta: output.meta.clone(),
528        gate: output.gate,
529        workspace_diagnostics: output.workspace_diagnostics.clone(),
530        summary: build_security_summary(output),
531    };
532    let mut value = serialize_named_json_output(summary, "security")?;
533    attach_telemetry_meta(&mut value, analysis_run_id);
534    Ok(value)
535}
536
537/// Serialize the `fallow security survivors --format json` envelope.
538///
539/// # Errors
540///
541/// Returns a serde error when the envelope cannot be converted to JSON.
542pub fn serialize_security_survivors_json_output(
543    output: SecuritySurvivorsOutput,
544) -> Result<serde_json::Value, serde_json::Error> {
545    serialize_named_json_output(output, "security-survivors")
546}
547
548/// Serialize the `fallow security blind-spots --format json` envelope.
549///
550/// # Errors
551///
552/// Returns a serde error when the envelope cannot be converted to JSON.
553pub fn serialize_security_blind_spots_json_output(
554    output: SecurityBlindSpotsOutput,
555) -> Result<serde_json::Value, serde_json::Error> {
556    serialize_named_json_output(output, "security-blind-spots")
557}
558
559/// Aggregate counts for `fallow security --summary --format json`.
560#[derive(Debug, Clone, Deserialize, Serialize)]
561#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
562pub struct SecuritySummary {
563    /// Number of security candidates after all filters, gates, and scopes.
564    pub security_findings: usize,
565    /// Fixed severity counts for the closed security severity enum.
566    pub by_severity: SecuritySeverityCounts,
567    /// Finding counts by catalogue category, or by kind for findings without a
568    /// catalogue category.
569    pub by_category: BTreeMap<String, usize>,
570    /// Fixed reachability counts for ranking and triage signals.
571    pub by_reachability: SecurityReachabilityCounts,
572    /// Fixed runtime coverage counts for runtime-state triage signals.
573    pub by_runtime_state: SecurityRuntimeStateCounts,
574    /// Number of client files whose dynamic imports could not be followed.
575    pub unresolved_edge_files: usize,
576    /// Number of sink-shaped callees that could not be statically flattened.
577    pub unresolved_callee_sites: usize,
578    /// Number of attack-surface entries included in the prepared full output.
579    pub attack_surface_entries: usize,
580}
581
582/// Fixed severity counters for summary JSON.
583#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
584#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
585pub struct SecuritySeverityCounts {
586    /// High-severity candidates.
587    pub high: usize,
588    /// Medium-severity candidates.
589    pub medium: usize,
590    /// Low-severity candidates.
591    pub low: usize,
592}
593
594/// Fixed reachability counters for summary JSON.
595#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
596#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
597pub struct SecurityReachabilityCounts {
598    /// Candidates reachable from an entry point.
599    pub entry_reachable: usize,
600    /// Candidates reachable from an untrusted input source.
601    pub untrusted_source_reachable: usize,
602    /// Candidates where taint flows through a call argument.
603    pub arg_level: usize,
604    /// Candidates where taint is only module-level.
605    pub module_level: usize,
606    /// Candidates whose flow crosses a client/server boundary.
607    pub crosses_boundary: usize,
608    /// Candidates backed by a concrete taint source.
609    pub source_backed: usize,
610}
611
612/// Fixed runtime coverage counters for summary JSON.
613#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
614#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
615pub struct SecurityRuntimeStateCounts {
616    /// Candidates on frequently executed runtime paths.
617    pub runtime_hot: usize,
618    /// Candidates on rarely executed runtime paths.
619    pub runtime_cold: usize,
620    /// Candidates on paths never seen executing.
621    pub never_executed: usize,
622    /// Candidates on low-traffic paths.
623    pub low_traffic: usize,
624    /// Candidates in files runtime coverage did not observe.
625    pub coverage_unavailable: usize,
626    /// Candidates whose runtime state could not be classified.
627    pub runtime_unknown: usize,
628    /// Candidates analysed without any runtime coverage data.
629    pub not_collected: usize,
630}
631
632/// The `fallow security survivors --format json` schema version.
633#[derive(Debug, Clone, Copy, Serialize)]
634#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
635pub enum SecuritySurvivorsSchemaVersion {
636    /// Adds `summary.unverdicted` for incomplete verdict files.
637    #[serde(rename = "2")]
638    V2,
639}
640
641/// Verifier verdict status accepted by `fallow security survivors`.
642#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
643#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
644#[serde(rename_all = "kebab-case")]
645pub enum SecurityVerifierVerdictStatus {
646    /// The verifier could not dismiss the candidate from supplied evidence.
647    Survivor,
648    /// The verifier dismissed the candidate from supplied evidence.
649    Dismissed,
650    /// The verifier needs human review before dismissal or remediation.
651    NeedsHumanReview,
652}
653
654/// One supported verifier verdict input row.
655#[derive(Debug, Clone, Deserialize, Serialize)]
656#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
657pub struct SecurityVerifierVerdict {
658    /// Must be `fallow-security-verdict/v1`.
659    pub schema_version: String,
660    /// Candidate id: `security_findings[].finding_id` or
661    /// `security_findings[].stable_finding_id`. Use the stable id when the
662    /// verdict must survive edits that move the sink to another line.
663    pub finding_id: String,
664    /// Verifier's verdict for the candidate.
665    pub verdict: SecurityVerifierVerdictStatus,
666    /// Short machine-oriented verdict reason.
667    #[serde(default, skip_serializing_if = "Option::is_none")]
668    pub reason: Option<String>,
669    /// Longer free-form verdict explanation.
670    #[serde(default, skip_serializing_if = "Option::is_none")]
671    pub rationale: Option<String>,
672    /// Optional verifier-provided confidence or review priority.
673    #[serde(default, skip_serializing_if = "Option::is_none")]
674    pub confidence: Option<String>,
675    /// Optional verifier-provided impact statement.
676    #[serde(default, skip_serializing_if = "Option::is_none")]
677    pub impact: Option<String>,
678    /// Optional verifier-owned remediation direction.
679    #[serde(default, skip_serializing_if = "Option::is_none")]
680    pub fix_direction: Option<String>,
681}
682
683/// The `fallow security survivors --format json` envelope.
684#[derive(Debug, Clone, Serialize)]
685#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
686pub struct SecuritySurvivorsOutput {
687    /// Schema version of this envelope.
688    pub schema_version: SecuritySurvivorsSchemaVersion,
689    /// Fallow CLI version that produced this output.
690    pub version: ToolVersion,
691    /// Wall-clock milliseconds spent producing the report.
692    pub elapsed_ms: ElapsedMs,
693    /// Diagnostics preserved from the candidate security report.
694    #[serde(default, skip_serializing_if = "Vec::is_empty")]
695    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
696    /// Aggregate verdict counts.
697    pub summary: SecuritySurvivorsSummary,
698    /// Verifier-retained candidates keyed by the candidate `finding_id`, also
699    /// when the verdict names the candidate by its `stable_finding_id`.
700    pub survivors: BTreeMap<String, SecuritySurvivor>,
701    /// Ambiguous candidates keyed by finding id. These are not dismissed and are
702    /// kept explicit so queues can decide whether to include them.
703    pub needs_human_review: BTreeMap<String, SecuritySurvivor>,
704}
705
706/// Aggregate counts for survivor rendering.
707#[derive(Debug, Clone, Copy, Serialize)]
708#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
709pub struct SecuritySurvivorsSummary {
710    /// Candidates in the input security report.
711    pub candidates: usize,
712    /// Verifier verdicts supplied.
713    pub verdicts: usize,
714    /// Candidates the verifier retained.
715    pub survivors: usize,
716    /// Candidates the verifier dismissed.
717    pub dismissed: usize,
718    /// Candidates the verifier flagged as ambiguous.
719    pub needs_human_review: usize,
720    /// Candidates without any verdict.
721    pub unverdicted: usize,
722}
723
724/// One verifier-retained candidate row.
725#[derive(Debug, Clone, Serialize)]
726#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
727pub struct SecuritySurvivor {
728    /// Stable candidate id from `security_findings[].finding_id`.
729    pub finding_id: String,
730    /// Verifier's verdict for the candidate.
731    pub verdict: SecurityVerifierVerdictStatus,
732    /// Short machine-oriented verdict reason.
733    #[serde(default, skip_serializing_if = "Option::is_none")]
734    pub reason: Option<String>,
735    /// Longer free-form verdict explanation.
736    #[serde(default, skip_serializing_if = "Option::is_none")]
737    pub rationale: Option<String>,
738    /// Optional verifier-provided confidence or review priority.
739    #[serde(default, skip_serializing_if = "Option::is_none")]
740    pub confidence: Option<String>,
741    /// Optional verifier-provided impact statement.
742    #[serde(default, skip_serializing_if = "Option::is_none")]
743    pub impact: Option<String>,
744    /// Optional verifier-owned remediation direction.
745    #[serde(default, skip_serializing_if = "Option::is_none")]
746    pub fix_direction: Option<String>,
747    /// Original typed fallow security candidate.
748    pub candidate: SecurityFinding,
749}
750
751/// The `fallow security blind-spots --format json` schema version.
752#[derive(Debug, Clone, Copy, Serialize)]
753#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
754pub enum SecurityBlindSpotsSchemaVersion {
755    /// Initial blind-spot grouping output contract.
756    #[serde(rename = "1")]
757    V1,
758}
759
760/// The `fallow security blind-spots --format json` envelope.
761#[derive(Debug, Clone, Serialize)]
762#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
763pub struct SecurityBlindSpotsOutput {
764    /// Schema version of this envelope.
765    pub schema_version: SecurityBlindSpotsSchemaVersion,
766    /// Fallow CLI version that produced this output.
767    pub version: ToolVersion,
768    /// Wall-clock milliseconds spent producing the report.
769    pub elapsed_ms: ElapsedMs,
770    /// Diagnostics owned by the security analysis used for this view.
771    #[serde(default, skip_serializing_if = "Vec::is_empty")]
772    pub workspace_diagnostics: Vec<WorkspaceDiagnostic>,
773    /// Aggregate blind-spot counts from the security analysis.
774    pub summary: SecurityBlindSpotsSummary,
775    /// Grouped unresolved callee diagnostics, derived from existing samples.
776    pub groups: Vec<SecurityBlindSpotGroup>,
777}
778
779/// Aggregate counts for blind-spot output.
780#[derive(Debug, Clone, Copy, Serialize)]
781#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
782pub struct SecurityBlindSpotsSummary {
783    /// Files containing at least one unresolved callee.
784    pub unresolved_edge_files: usize,
785    /// Total unresolved callee sites in the analysis.
786    pub unresolved_callee_sites: usize,
787    /// Callee sites captured in the bounded diagnostic sample.
788    pub sampled_callee_sites: usize,
789}
790
791/// One actionable blind-spot group.
792#[derive(Debug, Clone, Serialize)]
793#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
794pub struct SecurityBlindSpotGroup {
795    /// Why the callees in this group could not be resolved.
796    pub reason: fallow_types::extract::SkippedSecurityCalleeReason,
797    /// Compact syntax shape of the skipped callee.
798    pub expression_kind: fallow_types::extract::SkippedSecurityCalleeExpressionKind,
799    /// Count in the bounded diagnostic sample.
800    pub sampled_count: usize,
801    /// Top files in this bounded diagnostic sample.
802    pub files: Vec<SecurityBlindSpotFile>,
803    /// Suggested next action for this group.
804    pub suggestion: String,
805}
806
807/// One file inside a blind-spot group.
808#[derive(Debug, Clone, Serialize)]
809#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
810pub struct SecurityBlindSpotFile {
811    /// File path relative to the analysed root.
812    pub path: String,
813    /// Count in the bounded diagnostic sample.
814    pub sampled_count: usize,
815}
816
817#[cfg(test)]
818mod tests {
819    use super::*;
820    use serde_json::json;
821
822    fn current_security_envelope() -> serde_json::Value {
823        json!({
824            "schema_version": "8",
825            "version": "test",
826            "elapsed_ms": 1,
827            "config": {
828                "rules": {
829                    "security_client_server_leak": {
830                        "configured": "warn",
831                        "effective": "warn"
832                    },
833                    "security_sink": {
834                        "configured": "warn",
835                        "effective": "warn"
836                    }
837                },
838                "categories_include": null,
839                "categories_exclude": null
840            },
841            "security_findings": [],
842            "unresolved_edge_files": 0,
843            "unresolved_callee_sites": 0
844        })
845    }
846
847    #[test]
848    fn security_summary_json_output_uses_security_root_contract() {
849        let output = SecurityOutput {
850            gate_outcomes: None,
851            request_outcomes: None,
852            schema_version: SecuritySchemaVersion::V8,
853            version: ToolVersion("test".to_string()),
854            elapsed_ms: ElapsedMs(12),
855            config: json!({"rules": {}}),
856            meta: None,
857            gate: None::<()>,
858            workspace_diagnostics: vec![WorkspaceDiagnostic::new(
859                std::path::Path::new("/project"),
860                std::path::PathBuf::from("package.json"),
861                fallow_types::workspace::WorkspaceDiagnosticKind::UndeclaredWorkspace,
862            )],
863            security_findings: Vec::new(),
864            attack_surface: None,
865            unresolved_edge_files: 2,
866            unresolved_callee_sites: 3,
867            unresolved_callee_diagnostics: None,
868        };
869
870        let value = serialize_security_summary_json_output(&output, None)
871            .expect("security summary should serialize");
872
873        assert_eq!(value["kind"], "security");
874        assert_eq!(value["schema_version"], "8");
875        assert_eq!(value["summary"]["security_findings"], 0);
876        assert_eq!(value["summary"]["unresolved_edge_files"], 2);
877        assert_eq!(value["summary"]["unresolved_callee_sites"], 3);
878        assert_eq!(value["workspace_diagnostics"][0]["path"], "package.json");
879        assert!(value.get("security_findings").is_none());
880    }
881
882    #[test]
883    fn saved_security_validator_accepts_current_full_and_summary_payloads() {
884        let full = current_security_envelope();
885        validate_saved_security_envelope(&full).expect("current full security envelope");
886
887        let mut summary = current_security_envelope();
888        summary
889            .as_object_mut()
890            .expect("security envelope")
891            .remove("security_findings");
892        summary
893            .as_object_mut()
894            .expect("security envelope")
895            .remove("unresolved_edge_files");
896        summary
897            .as_object_mut()
898            .expect("security envelope")
899            .remove("unresolved_callee_sites");
900        summary["summary"] = serde_json::to_value(SecuritySummary {
901            security_findings: 0,
902            by_severity: SecuritySeverityCounts::default(),
903            by_category: BTreeMap::new(),
904            by_reachability: SecurityReachabilityCounts::default(),
905            by_runtime_state: SecurityRuntimeStateCounts::default(),
906            unresolved_edge_files: 0,
907            unresolved_callee_sites: 0,
908            attack_surface_entries: 0,
909        })
910        .expect("security summary");
911        validate_saved_security_envelope(&summary).expect("current summary security envelope");
912    }
913
914    #[test]
915    fn saved_security_validator_accepts_legacy_v7_type_aware_payload() {
916        let mut envelope = current_security_envelope();
917        envelope["schema_version"] = json!("7");
918        envelope["_meta"] = json!({
919            "type_aware": {
920                "executed": true,
921                "protocol_version": 6,
922                "sidecar_version": "0.6.0",
923                "backend": "typescript-go",
924                "backend_version": "7.0.0-dev",
925                "selected_tsconfigs": ["tsconfig.json"],
926                "candidate_count": 1,
927                "confirmed_used_count": 0,
928                "contract_preserved_count": 0,
929                "no_static_references_count": 1,
930                "fix_eligible_count": 0,
931                "unresolved_count": 0,
932                "abstained_count": 0,
933                "abstention_reasons": {
934                    "no_project": 0,
935                    "ambiguous_project": 0,
936                    "blocking_diagnostics": 0,
937                    "svelte_virtual_module_exports": 0,
938                    "unknown_symbol": 0,
939                    "unsupported_syntax": 0,
940                    "capacity": 0
941                },
942                "projects": [],
943                "warning_count": 0,
944                "warnings": [],
945                "elapsed_ms": 4,
946                "phase_timings_ms": {
947                    "project_setup": 1,
948                    "diagnostics": 1,
949                    "symbol_scan": 2
950                }
951            }
952        });
953
954        validate_saved_security_envelope(&envelope)
955            .expect("legacy schema 7 type-aware metadata stays readable");
956    }
957
958    #[test]
959    fn saved_security_validator_rejects_malformed_current_payloads() {
960        let mut findings = current_security_envelope();
961        findings["security_findings"] = json!("not-an-array");
962        assert!(validate_saved_security_envelope(&findings).is_err());
963
964        let mut type_aware = current_security_envelope();
965        type_aware["_meta"] = json!({"type_aware": {"queries": "not-an-array"}});
966        assert!(validate_saved_security_envelope(&type_aware).is_err());
967    }
968
969    #[test]
970    fn saved_security_validator_accepts_legacy_and_rejects_future_schema() {
971        validate_saved_security_envelope(&json!({"schema_version": "7"}))
972            .expect("known legacy security schema");
973        let error = validate_saved_security_envelope(&json!({"schema_version": "9"}))
974            .expect_err("future security schema must fail closed");
975        assert!(error.contains("unsupported saved security schema version 9"));
976    }
977
978    fn assert_saved_security_parse_parity<T: DeserializeOwned>(
979        value: &serde_json::Value,
980        label: &str,
981        valid: bool,
982    ) {
983        let owned = serde_json::from_value::<T>(value.clone())
984            .map(|_| ())
985            .map_err(|error| {
986                format!("saved security {label} is incompatible with this Fallow version: {error}")
987            });
988        let borrowed = parse_saved_security::<T>(value, label).map(|_| ());
989        assert_eq!(borrowed.is_ok(), valid, "{label}: {borrowed:?}");
990        assert_eq!(
991            borrowed, owned,
992            "{label} must retain exact validation errors"
993        );
994    }
995
996    #[test]
997    fn saved_security_parsing_preserves_owned_value_contract() {
998        let mut full = current_security_envelope();
999        full["security_findings"] = json!([{
1000            "finding_id": "security-fixture",
1001            "kind": "tainted-sink",
1002            "path": "src/[route]/café.ts",
1003            "line": 12,
1004            "col": 3,
1005            "evidence": "quoted \"value\" and unicode café",
1006            "severity": "low",
1007            "trace": [],
1008            "actions": [],
1009            "candidate": fallow_types::results::SecurityCandidate::default()
1010        }]);
1011        full["future_field"] = json!({"nested": ["ignored", {"value": null}]});
1012        assert_saved_security_parse_parity::<SavedSecurityEnvelope>(&full, "envelope", true);
1013        assert_saved_security_parse_parity::<SavedSecurityFullPayload>(&full, "full payload", true);
1014        validate_saved_security_envelope(&full).expect("nonempty current payload remains valid");
1015
1016        for (field, invalid) in [
1017            ("line", json!(-1)),
1018            ("severity", json!("invalid")),
1019            ("candidate", json!([])),
1020        ] {
1021            let mut malformed = full.clone();
1022            malformed["security_findings"][0][field] = invalid;
1023            assert_saved_security_parse_parity::<SavedSecurityFullPayload>(
1024                &malformed,
1025                "full payload",
1026                false,
1027            );
1028            assert!(validate_saved_security_envelope(&malformed).is_err());
1029        }
1030        for malformed in [
1031            serde_json::Value::Null,
1032            json!({}),
1033            json!({"security_findings": "not-an-array"}),
1034        ] {
1035            assert_saved_security_parse_parity::<SavedSecurityFullPayload>(
1036                &malformed,
1037                "full payload",
1038                false,
1039            );
1040        }
1041        let mut invalid_header = full.clone();
1042        invalid_header["elapsed_ms"] = json!("invalid");
1043        assert_saved_security_parse_parity::<SavedSecurityEnvelope>(
1044            &invalid_header,
1045            "envelope",
1046            false,
1047        );
1048
1049        let summary = json!({"summary": {
1050            "security_findings": 1,
1051            "by_severity": {"high": 0, "medium": 0, "low": 1},
1052            "by_category": {"dangerous-html": 1},
1053            "by_reachability": SecurityReachabilityCounts::default(),
1054            "by_runtime_state": SecurityRuntimeStateCounts::default(),
1055            "unresolved_edge_files": 0,
1056            "unresolved_callee_sites": 0,
1057            "attack_surface_entries": 0
1058        }});
1059        assert_saved_security_parse_parity::<SavedSecuritySummaryPayload>(
1060            &summary,
1061            "summary payload",
1062            true,
1063        );
1064        assert_saved_security_parse_parity::<SavedSecuritySummaryPayload>(
1065            &json!({"summary": false}),
1066            "summary payload",
1067            false,
1068        );
1069    }
1070}