Skip to main content

surjection_core/scan/external/
mod.rs

1//! The optional external scanner: a second opinion beside the built-in
2//! scanner, never instead of it. Off by default.
3//!
4//! Since 0.8.0 (#30) that is NVIDIA SkillSpector ([`skillspector`]), run
5//! locally from the user's own `uv` or `skillspector`; Surjection never
6//! installs it outside its data folder. Snyk Agent Scan (#27) shipped in
7//! 0.7.0 and was disabled in 0.7.1; only the cleanup of a 0.7.0 install
8//! remains ([`snyk_leftover`]).
9//!
10//! Results map into the M40 findings model ([`Finding`], `scanner =`
11//! [`Scanner::as_str`]) and are shown beside the built-in findings. A
12//! `dangerous` external verdict needs the same explicit "install anyway"
13//! as a built-in one ([`gate`]); a run that did not happen or whose output
14//! was not understood never blocks and is never shown as clean.
15
16pub mod download;
17mod process;
18pub mod skillspector;
19pub mod snyk_leftover;
20mod text;
21
22use serde::{Deserialize, Serialize};
23
24pub use process::RUNS_DIR;
25
26use super::{Finding, Severity, Verdict};
27use crate::error::{CoreError, ErrorCode};
28
29/// `<SURJECTION_HOME>/<TOOLS_DIR>/`: tools Surjection downloaded (machine-local,
30/// never synced, never on `PATH`): SkillSpector's private `uv/` (and
31/// `snyk-agent-scan/` left by 0.7.0, [`snyk_leftover`]).
32pub const TOOLS_DIR: &str = "tools";
33
34/// Which external scanner made a report.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
36pub enum Scanner {
37    #[serde(rename = "skillspector")]
38    SkillSpector,
39}
40
41impl Scanner {
42    /// The id: `Finding::scanner`, `--json` and IPC.
43    pub const fn as_str(self) -> &'static str {
44        match self {
45            Scanner::SkillSpector => "skillspector",
46        }
47    }
48
49    /// The name people read.
50    pub const fn name(self) -> &'static str {
51        match self {
52            Scanner::SkillSpector => "SkillSpector",
53        }
54    }
55}
56
57/// Whether the run happened and was understood.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60pub enum ExternalStatus {
61    /// The scanner ran and its output was understood: the findings (none
62    /// for a clean verdict) are its answer.
63    Scanned,
64    /// The content was not scanned ([`ExternalReport::reason`]).
65    NotScanned,
66    /// The scanner ran but its output is not the schema this build reads
67    /// ("scanner output not understood (version X)"); never clean.
68    NotUnderstood,
69}
70
71impl ExternalStatus {
72    pub const fn as_str(self) -> &'static str {
73        match self {
74            ExternalStatus::Scanned => "scanned",
75            ExternalStatus::NotScanned => "not_scanned",
76            ExternalStatus::NotUnderstood => "not_understood",
77        }
78    }
79}
80
81/// Why the content was not scanned. None of these blocks an install.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum NotScanned {
85    /// SkillSpector: neither uv nor a usable `skillspector` is on `PATH`.
86    NotAvailable,
87    /// SkillSpector: uv is on `PATH` but the pinned SkillSpector is not
88    /// downloaded yet (or uv's cache lost it): run Prepare.
89    NotPrepared,
90    /// The run took longer than the timeout and was stopped.
91    Timeout,
92    /// The user canceled the run.
93    Canceled,
94    /// Any other failure (the scanner did not start, exited with an
95    /// error): see [`ExternalReport::detail`].
96    Failed,
97}
98
99impl NotScanned {
100    pub const fn as_str(self) -> &'static str {
101        match self {
102            NotScanned::NotAvailable => "not_available",
103            NotScanned::NotPrepared => "not_prepared",
104            NotScanned::Timeout => "timeout",
105            NotScanned::Canceled => "canceled",
106            NotScanned::Failed => "failed",
107        }
108    }
109
110    /// English, for the CLI: "not scanned (<this>)".
111    pub const fn text(self) -> &'static str {
112        match self {
113            NotScanned::NotAvailable => "SkillSpector was not found; see `surject scanner status`",
114            NotScanned::NotPrepared => {
115                "SkillSpector is not downloaded yet; run `surject scanner prepare`"
116            }
117            NotScanned::Timeout => "timed out",
118            NotScanned::Canceled => "canceled",
119            NotScanned::Failed => "the scanner failed",
120        }
121    }
122}
123
124/// One external scan of one skill.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct ExternalReport {
127    pub scanner: Scanner,
128    /// The scanner's version that ran (or would have run).
129    pub version: String,
130    pub status: ExternalStatus,
131    /// Set when `status` is [`ExternalStatus::NotScanned`].
132    pub reason: Option<NotScanned>,
133    /// The worst finding. `Clean` also when nothing was scanned: always
134    /// read [`ExternalReport::status`] and [`ExternalReport::incomplete`]
135    /// first.
136    pub verdict: Verdict,
137    /// Sorted by file, line and rule.
138    pub findings: Vec<Finding>,
139    /// The scanner says it did not fully scan the content (an `info`
140    /// finding says how much): never shown as clean.
141    #[serde(default)]
142    pub incomplete: bool,
143    /// [`crate::skills::content_hash`] of what was scanned.
144    pub content_hash: Option<String>,
145    /// English, one line, no paths or values: why it was not scanned,
146    /// what was not understood.
147    pub detail: Option<String>,
148}
149
150impl ExternalReport {
151    pub fn not_scanned(
152        scanner: Scanner,
153        version: &str,
154        reason: NotScanned,
155        detail: Option<String>,
156    ) -> Self {
157        Self {
158            scanner,
159            version: version.to_owned(),
160            status: ExternalStatus::NotScanned,
161            reason: Some(reason),
162            verdict: Verdict::Clean,
163            findings: Vec::new(),
164            incomplete: false,
165            content_hash: None,
166            detail,
167        }
168    }
169
170    pub fn not_understood(scanner: Scanner, version: &str, why: &str) -> Self {
171        Self {
172            scanner,
173            version: version.to_owned(),
174            status: ExternalStatus::NotUnderstood,
175            reason: None,
176            verdict: Verdict::Clean,
177            findings: Vec::new(),
178            incomplete: false,
179            content_hash: None,
180            detail: Some(format!(
181                "scanner output not understood (version {version}): {why}"
182            )),
183        }
184    }
185
186    /// One line for the CLI: `dangerous (2 findings)`, `not fully scanned
187    /// (1 finding)`, `warning (3 findings), not fully scanned`, `not
188    /// scanned (timed out)`, `scanner output not understood (version
189    /// 2.13.7)`.
190    pub fn summary(&self) -> String {
191        match (self.status, self.reason) {
192            (ExternalStatus::NotScanned, Some(reason)) => {
193                format!("not scanned ({})", reason.text())
194            }
195            (ExternalStatus::NotUnderstood, _) => {
196                format!("scanner output not understood (version {})", self.version)
197            }
198            _ => {
199                let n = self.findings.len();
200                let plural = if n == 1 { "" } else { "s" };
201                match (self.incomplete, self.verdict) {
202                    (true, Verdict::Clean) => format!("not fully scanned ({n} finding{plural})"),
203                    (true, verdict) => {
204                        format!(
205                            "{} ({n} finding{plural}), not fully scanned",
206                            verdict.as_str()
207                        )
208                    }
209                    (false, verdict) => format!("{} ({n} finding{plural})", verdict.as_str()),
210                }
211            }
212        }
213    }
214
215    /// The findings that make the verdict `dangerous`.
216    pub fn dangerous(&self) -> impl Iterator<Item = &Finding> {
217        self.findings
218            .iter()
219            .filter(|finding| finding.severity == Severity::Dangerous)
220    }
221}
222
223/// Refuses content the external scanner found `dangerous` (`scan_blocked`)
224/// unless the user explicitly chose to install it anyway. A report that is
225/// not scanned or not understood never blocks (it carries no findings).
226pub fn gate(report: &ExternalReport, allow_dangerous: bool) -> Result<(), CoreError> {
227    if allow_dangerous || report.verdict != Verdict::Dangerous {
228        return Ok(());
229    }
230    let labels: Vec<String> = report.dangerous().map(Finding::label).collect();
231    let mut shown = labels
232        .iter()
233        .take(3)
234        .cloned()
235        .collect::<Vec<_>>()
236        .join(", ");
237    if labels.len() > 3 {
238        shown.push_str(&format!(" and {} more", labels.len() - 3));
239    }
240    let plural = if labels.len() == 1 { "" } else { "s" };
241    Err(CoreError::new(
242        ErrorCode::ScanBlocked,
243        format!(
244            "{} found {} dangerous finding{plural}: {shown}; review them, and install anyway only if you trust this content",
245            report.scanner.name(),
246            labels.len()
247        ),
248    ))
249}
250
251/// A per-run override of the setting (`--external` / `--no-external`).
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
253pub enum Choice {
254    /// The machine's setting.
255    #[default]
256    Default,
257    On,
258    Off,
259}
260
261impl Choice {
262    /// Whether to run: [`Choice::On`], or [`Choice::Default`] with the
263    /// scanner turned on (`enabled`).
264    pub const fn wants(self, enabled: bool) -> bool {
265        match self {
266            Choice::On => true,
267            Choice::Off => false,
268            Choice::Default => enabled,
269        }
270    }
271}