Skip to content

g1t/services/security/src/code_scanning.rs

611 lines29,203 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1//! Code scanning: SARIF uploads read into analyses and alerts, and the
2//! `Code scanning` check on pull requests.
3//!
4//! An upload for the default branch opens an alert for each result not
5//! seen before (by fingerprint, per tool and category), refreshes those
6//! seen again, and fixes the open ones it no longer reports. An upload for
7//! a pull request (`refs/pull/<n>/head` or `/merge`) leaves the alerts
8//! alone: its results are compared with the default branch's, and those
9//! new to the pull request on lines it changes become the check's
10//! annotations, as review comments on those lines, failing the check at
11//! the repository's chosen threshold. Require the check in branch
12//! protection and it gates the merge like any other.
13
14use std::collections::{BTreeMap, BTreeSet};
15
16use g1t_contracts::repos::{BlobArgs, BlobView, CompareArgs, Comparison, GetArgs, LineKind, Repo, RepoPath};
17use g1t_contracts::security::{AlertActivity, AlertState, DismissReason};
18use g1t_contracts::security_suite::{
19 AlertType, CODE_SCANNING_CHECK, CodeAlert, CodeAlertArgs, CodeAlertDetail, CodeScanning, CodeScanningArgs, PaidFeature,
20 PullResult, PullScanning, PullScanningArgs, STARTER_WORKFLOW_PATH, SarifStatusArgs, SarifUpload, SecurityEvent,
21 SetCodeAlertStateArgs, UploadSarifArgs,
22};
23use g1t_contracts::work::{AddCommentArgs, Pull, PullDetail, SetCommitStatusArgs, ViewArgs};
24use g1t_contracts::{FailureCode, Outcome, User};
25use g1t_scan::sarif::{self, Finding, Gate};
26use serde_json::{Value, json};
27use worker::Result;
28
29use crate::Security;
30use crate::store::{Activity, RepoRow};
31use crate::suite::link;
32use crate::suite_store::NewCodeAlert;
33
34const SITE: &str = "https://g1t.sh";
35/// Review comments one analysis of a pull request leaves, at most.
36const MAX_COMMENTS: usize = 10;
37/// Alerts an upload announces one by one; past it, the page says the rest.
38const MAX_EVENTS: usize = 20;
39
40fn fail<T>(code: FailureCode, message: impl Into<String>) -> Outcome<T> {
41 Outcome::fail(code, message)
42}
43
44/// A result as kept with its analysis.
45pub fn result_json(finding: &Finding) -> Value {
46 json!({
47 "ruleId": finding.rule_id,
48 "level": finding.level.as_str(),
49 "securitySeverity": finding.security_severity.map(|severity| severity.as_str()),
50 "severity": finding.severity().as_str(),
51 "message": finding.message,
52 "path": finding.location.as_ref().map(|location| location.path.clone()),
53 "line": finding.location.as_ref().map(|location| location.start_line),
54 })
55}
56
57/// The pull request a ref names: `refs/pull/12/head` or `/merge`.
58pub fn pull_of(git_ref: &str) -> Option<u32> {
59 let rest = git_ref.strip_prefix("refs/pull/")?;
60 let (number, which) = rest.split_once('/')?;
61 matches!(which, "head" | "merge").then(|| number.parse().ok()).flatten()
62}
63
64fn is_sha(text: &str) -> bool {
65 matches!(text.len(), 40 | 64) && text.chars().all(|c| c.is_ascii_hexdigit())
66}
67
68/// The lines each file gains in a comparison.
69pub fn added_lines(comparison: &Comparison) -> BTreeMap<String, BTreeSet<u32>> {
70 let mut out: BTreeMap<String, BTreeSet<u32>> = BTreeMap::new();
71 for file in &comparison.files {
72 for hunk in &file.hunks {
73 for line in &hunk.lines {
74 if line.kind == LineKind::Add
75 && let Some(number) = line.new
76 {
77 out.entry(file.path.clone()).or_default().insert(number);
78 }
79 }
80 }
81 }
82 out
83}
84
85/// A pull request's results, judged: new to it or not, on a line it
86/// changes or not, failing the check or not.
87pub fn judge_pull(found: &[Finding], on_default: &BTreeSet<String>, changed: &BTreeMap<String, BTreeSet<u32>>, gate: Gate) -> Vec<PullResult> {
88 let mut results: Vec<PullResult> = found
89 .iter()
90 .map(|finding| {
91 let location = finding.location.as_ref();
92 let new = !on_default.contains(&finding.fingerprint);
93 let on_changed_line = location.is_some_and(|location| {
94 changed
95 .get(&location.path)
96 .is_some_and(|lines| (location.start_line..=location.end_line).any(|line| lines.contains(&line)))
97 });
98 PullResult {
99 tool: String::new(),
100 rule_id: finding.rule_id.clone(),
101 level: finding.level.as_str().to_owned(),
102 severity: finding.severity().as_str().to_owned(),
103 security_severity: finding.security_severity.map(|severity| severity.as_str().to_owned()),
104 message: finding.message.clone(),
105 path: location.map(|location| location.path.clone()),
106 line: location.map(|location| location.start_line),
107 new,
108 on_changed_line,
109 failing: new && on_changed_line && gate.fails(finding),
110 }
111 })
112 .collect();
113 results.sort_by_key(|result| (!result.failing, !result.new, !result.on_changed_line));
114 results
115}
116
117/// The check's state and line for a pull request's results.
118pub fn verdict(results: &[PullResult]) -> (&'static str, String) {
119 let failing = results.iter().filter(|result| result.failing).count();
120 let new = results.iter().filter(|result| result.new && result.on_changed_line).count();
121 if failing > 0 {
122 let plural = if failing == 1 { "result" } else { "results" };
123 return ("failure", format!("{failing} new {plural} at or above the threshold"));
124 }
125 match new {
126 0 => ("success", "No new results".to_owned()),
127 1 => ("success", "1 new result, below the threshold".to_owned()),
128 n => ("success", format!("{n} new results, below the threshold")),
129 }
130}
131
132/// A review comment for a result on a line the pull request changes.
133pub fn comment_text(tool: &str, finding: &PullResult, alert_page: &str) -> String {
134 let severity = finding.security_severity.as_deref().unwrap_or(&finding.level);
135 format!(
136 "**{tool}: `{}`** ({severity})\n\n{}\n\n[See the results for this pull request]({alert_page}). Fix it here, or dismiss it on the alert once it lands if it is not a real problem.",
137 finding.rule_id, finding.message
138 )
139}
140
141/// The event that tells of a code scanning alert.
142pub fn code_event(repo: &RepoRow, alert: &CodeAlert) -> SecurityEvent {
143 SecurityEvent {
144 repo_id: repo.repo_id.clone(),
145 alert_id: alert.id.clone(),
146 alert_type: AlertType::CodeScanning.as_str().to_owned(),
147 alert_number: Some(alert.number),
148 severity: alert.severity.clone(),
149 title: format!(
150 "{}: {}{}",
151 alert.tool,
152 alert.rule_name.as_deref().unwrap_or(&alert.rule_id),
153 alert.path.as_deref().map(|path| format!(" in {path}")).unwrap_or_default()
154 ),
155 link: link(repo, &format!("code-scanning/{}", alert.number)),
156 path: alert.path.clone(),
157 line: alert.start_line,
158 state: alert.state.as_str().to_owned(),
159 ..SecurityEvent::default()
160 }
161}
162
163impl Security {
164 pub(crate) async fn repo_record(&self, repo: &RepoRow) -> Result<Option<Repo>> {
165 let found: Outcome<Repo> = g1t_kit::call(
166 &self.repos,
167 "get",
168 &GetArgs { path: RepoPath { namespace: repo.namespace.clone(), name: repo.name.clone() }, viewer: Some(User::system(&repo.namespace)) },
169 )
170 .await?;
171 Ok(found.into_result().ok())
172 }
173
174 pub(crate) async fn upload_sarif(&self, a: UploadSarifArgs) -> Result<Outcome<SarifUpload>> {
175 let repo = match self.member_repo(&a.repo, &Some(a.actor.clone()), crate::SEE_FINDINGS).await? {
176 Outcome::Ok(repo) => repo,
177 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
178 };
179 if let Some(refusal) = self.gate(&repo, PaidFeature::CodeScanning).await? {
180 return Ok(refusal);
181 }
182 if !is_sha(&a.commit_sha) {
183 return Ok(fail(FailureCode::Invalid, "commit_sha is a full commit hash."));
184 }
185 if !a.git_ref.starts_with("refs/") {
186 return Ok(fail(FailureCode::Invalid, "ref is a full ref: refs/heads/<branch> or refs/pull/<number>/head."));
187 }
188 let Some(record) = self.repo_record(&repo).await? else {
189 return Ok(fail(FailureCode::NotFound, "Repository not found."));
190 };
191 let default_ref = format!("refs/heads/{}", record.default_branch);
192 let pull = pull_of(&a.git_ref);
193 let id = self.store.add_upload(&repo.repo_id, &a.commit_sha, &a.git_ref, &a.actor.username).await?;
194 let parsed = sarif::decode_upload(&a.sarif).and_then(|text| sarif::parse(&text, a.category.as_deref(), a.checkout_uri.as_deref()));
195 let mut runs = match parsed {
196 Ok(runs) => runs,
197 Err(problem) => {
198 self.store.finish_upload(&id, true, std::slice::from_ref(&problem), &[]).await?;
199 return Ok(Outcome::Ok(self.upload_view(&repo, &id).await?.unwrap_or_else(|| failed_upload(&id, &a, problem))));
200 }
201 };
202 if let (Some(name), [run]) = (a.tool_name.as_deref().map(str::trim).filter(|name| !name.is_empty()), runs.as_mut_slice()) {
203 if run.category == run.tool {
204 run.category = name.to_owned();
205 }
206 run.tool = name.to_owned();
207 }
208 let mut analyses = Vec::new();
209 let mut errors = Vec::new();
210 for run in &runs {
211 if run.dropped > 0 {
212 errors.push(format!("{} results past the first {} of {} were not kept.", run.dropped, sarif::MAX_RESULTS, run.tool));
213 }
214 if a.git_ref == default_ref {
215 let live = self.store.live_fingerprints(&repo.repo_id, &run.tool, &run.category).await?;
216 let (_, fixed) = sarif::reconcile(&live, &run.findings);
217 let items: Vec<NewCodeAlert> = run
218 .findings
219 .iter()
220 .map(|finding| NewCodeAlert { tool: &run.tool, category: &run.category, finding, commit: &a.commit_sha })
221 .collect();
222 let opened = self.store.upsert_code_alerts(&repo.repo_id, &items).await?;
223 let fixed = self.store.fix_code_alerts(&repo.repo_id, &run.tool, &run.category, &fixed).await?;
224 analyses.push(
225 self.store
226 .add_analysis(&repo.repo_id, &id, run, &a.commit_sha, &a.git_ref, None, opened.len() as u32, fixed.len() as u32)
227 .await?,
228 );
229 for (ids, action) in [(&opened, "created"), (&fixed, "fixed")] {
230 for alert_id in ids.iter().take(MAX_EVENTS) {
231 if let Some(alert) = self.store.code_alert_by_id(&repo.repo_id, alert_id).await? {
232 self.alert_event(AlertType::CodeScanning, action, &repo, code_event(&repo, &alert), Some(a.actor.id.clone())).await;
233 }
234 }
235 }
236 } else {
237 analyses.push(self.store.add_analysis(&repo.repo_id, &id, run, &a.commit_sha, &a.git_ref, pull, 0, 0).await?);
238 }
239 }
240 self.store.finish_upload(&id, false, &errors, &analyses).await?;
241 if let Some(number) = pull
242 && let Err(error) = self.code_pull_check(&repo, number, &a.commit_sha, &runs).await
243 {
244 worker::console_error!("security: code scanning check on #{number} of {}: {error}", repo.repo_id);
245 }
246 Ok(Outcome::Ok(self.upload_view(&repo, &id).await?.unwrap_or_else(|| failed_upload(&id, &a, "not recorded".to_owned()))))
247 }
248
249 async fn upload_view(&self, repo: &RepoRow, id: &str) -> Result<Option<SarifUpload>> {
250 Ok(self.store.upload(&repo.repo_id, id).await?.map(|row| SarifUpload {
251 id: row.id,
252 processing_status: row.status,
253 analyses: serde_json::from_str(&row.analyses).unwrap_or_default(),
254 errors: serde_json::from_str(&row.errors).unwrap_or_default(),
255 commit_sha: row.commit_sha,
256 git_ref: row.git_ref,
257 created_at: row.created_at,
258 }))
259 }
260
261 pub(crate) async fn sarif_status(&self, a: SarifStatusArgs) -> Result<Outcome<SarifUpload>> {
262 let repo = match self.member_repo(&a.repo, &a.viewer, crate::SEE_FINDINGS).await? {
263 Outcome::Ok(repo) => repo,
264 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
265 };
266 Ok(match self.upload_view(&repo, &a.id).await? {
267 Some(upload) => Outcome::Ok(upload),
268 None => fail(FailureCode::NotFound, "No such upload."),
269 })
270 }
271
272 pub(crate) async fn code_scanning(&self, a: CodeScanningArgs) -> Result<Outcome<CodeScanning>> {
273 let repo = match self.member_repo(&a.repo, &a.viewer, crate::SEE_FINDINGS).await? {
274 Outcome::Ok(repo) => repo,
275 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
276 };
277 let (_, private) = self.store.repo_settings(&repo.repo_id).await?;
278 let default_branch = self.repo_record(&repo).await?.map(|record| record.default_branch).unwrap_or_else(|| "main".to_owned());
279 let starter: Outcome<BlobView> = g1t_kit::call(
280 &self.repos,
281 "blob",
282 &BlobArgs {
283 path: a.repo.clone(),
284 viewer: Some(User::system(&repo.namespace)),
285 git_ref: default_branch,
286 file_path: STARTER_WORKFLOW_PATH.to_owned(),
287 },
288 )
289 .await
290 .unwrap_or_else(|_| fail(FailureCode::NotFound, "unread"));
291 Ok(Outcome::Ok(CodeScanning {
292 alerts: self.store.code_alerts(&repo.repo_id).await?,
293 analyses: self.store.analyses(&repo.repo_id, 50).await?,
294 entitled: self.entitled(&repo).await?,
295 private,
296 configured: matches!(starter, Outcome::Ok(_)),
297 }))
298 }
299
300 pub(crate) async fn code_alert(&self, a: CodeAlertArgs) -> Result<Outcome<CodeAlertDetail>> {
301 let repo = match self.member_repo(&a.repo, &a.viewer, crate::SEE_FINDINGS).await? {
302 Outcome::Ok(repo) => repo,
303 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
304 };
305 let Some(alert) = self.store.code_alert(&repo.repo_id, a.number).await? else {
306 return Ok(fail(FailureCode::NotFound, "No such alert."));
307 };
308 let activity: Vec<AlertActivity> =
309 self.store.activity(&repo.repo_id, 500).await?.into_iter().filter(|item| item.alert_id == alert.id).collect();
310 Ok(Outcome::Ok(CodeAlertDetail {
311 analyses: self.store.analyses_reporting(&repo.repo_id, &alert.fingerprint).await?,
312 activity,
313 alert,
314 }))
315 }
316
317 pub(crate) async fn set_code_alert_state(&self, a: SetCodeAlertStateArgs) -> Result<Outcome<CodeAlert>> {
318 let repo = match self.member_repo(&a.repo, &Some(a.actor.clone()), crate::SEE_FINDINGS).await? {
319 Outcome::Ok(repo) => repo,
320 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
321 };
322 if !a.actor.verified {
323 return Ok(fail(FailureCode::Forbidden, "Confirm your email address first."));
324 }
325 let Some(alert) = self.store.code_alert(&repo.repo_id, a.number).await? else {
326 return Ok(fail(FailureCode::NotFound, "No such alert."));
327 };
328 let comment: String = a.comment.trim().chars().take(500).collect();
329 let comment = (!comment.is_empty()).then_some(comment);
330 let action = match a.state {
331 AlertState::Dismissed => {
332 let Some(reason) = a.reason.filter(|reason| {
333 matches!(reason, DismissReason::FalsePositive | DismissReason::WontFix | DismissReason::UsedInTests)
334 }) else {
335 return Ok(fail(FailureCode::Invalid, "A code scanning alert is dismissed as false_positive, wont_fix or used_in_tests."));
336 };
337 if alert.state != AlertState::Open {
338 return Ok(fail(FailureCode::Conflict, "This alert is not open."));
339 }
340 self.store.set_code_alert(&repo.repo_id, &alert.id, Some((reason, comment.as_deref(), &a.actor.username))).await?;
341 self.store
342 .record(&repo.repo_id, &[Activity {
343 alert_id: &alert.id,
344 action: "dismissed",
345 actor: Some(&a.actor.username),
346 reason: Some(reason),
347 comment: comment.as_deref(),
348 number: None,
349 }])
350 .await?;
351 "dismissed"
352 }
353 AlertState::Open => {
354 if alert.state != AlertState::Dismissed {
355 return Ok(fail(FailureCode::Conflict, "Only a dismissed alert can be reopened; a fixed one reopens when it is found again."));
356 }
357 self.store.set_code_alert(&repo.repo_id, &alert.id, None).await?;
358 self.store
359 .record(&repo.repo_id, &[Activity {
360 alert_id: &alert.id,
361 action: "reopened",
362 actor: Some(&a.actor.username),
363 reason: None,
364 comment: None,
365 number: None,
366 }])
367 .await?;
368 "reopened"
369 }
370 AlertState::Fixed => return Ok(fail(FailureCode::Invalid, "An alert is fixed by an analysis that no longer reports it.")),
371 };
372 let Some(alert) = self.store.code_alert(&repo.repo_id, a.number).await? else {
373 return Ok(fail(FailureCode::NotFound, "No such alert."));
374 };
375 let event = SecurityEvent { reason: a.reason.map(|reason| reason.as_str().to_owned()), ..code_event(&repo, &alert) };
376 self.alert_event(AlertType::CodeScanning, action, &repo, event, Some(a.actor.id.clone())).await;
377 Ok(Outcome::Ok(alert))
378 }
379
380 pub(crate) async fn pull_by_number(&self, repo: &RepoRow, number: u32) -> Result<Option<Pull>> {
381 let found: Outcome<PullDetail> = g1t_kit::call(
382 &self.work,
383 "get_pull",
384 &ViewArgs {
385 repo: RepoPath { namespace: repo.namespace.clone(), name: repo.name.clone() },
386 number,
387 viewer: Some(User::system(&repo.namespace)),
388 after_seq: 0,
389 },
390 )
391 .await?;
392 Ok(found.into_result().ok().map(|detail| detail.pull))
393 }
394
395 /// What a pull request changes, as the repository compares it: its
396 /// branch (or fork) against where it left the branch it merges into.
397 pub(crate) async fn pull_comparison(&self, repo: &RepoRow, pull: &Pull) -> Result<Option<Comparison>> {
398 let (repo_id, head) = match &pull.fork_repo_id {
399 Some(fork) => (fork.clone(), None),
400 None => (repo.repo_id.clone(), pull.branch.clone()),
401 };
402 let compared: Outcome<Comparison> = g1t_kit::call(
403 &self.repos,
404 "compare",
405 &CompareArgs { repo_id, viewer: Some(User::system(&repo.namespace)), base: None, head, base_branch: pull.base.clone() },
406 )
407 .await?;
408 Ok(compared.into_result().ok())
409 }
410
411 pub(crate) async fn set_status(&self, repo: &RepoRow, sha: &str, context: &str, state: &str, description: &str, number: u32) {
412 let set: Result<Outcome<bool>> = g1t_kit::call(
413 &self.work,
414 "set_commit_status",
415 &SetCommitStatusArgs {
416 repo_id: repo.repo_id.clone(),
417 sha: sha.to_owned(),
418 context: context.to_owned(),
419 state: state.to_owned(),
420 description: Some(description.chars().take(140).collect()),
421 target_url: Some(format!("{SITE}/{}/{}/security/pulls/{number}", repo.namespace, repo.name)),
422 },
423 )
424 .await;
425 if let Err(error) = set {
426 worker::console_error!("security: {context} status on {sha}: {error}");
427 }
428 }
429
430 /// Judges a pull request's code scanning results and reports the check.
431 async fn code_pull_check(&self, repo: &RepoRow, number: u32, commit: &str, runs: &[sarif::Run]) -> Result<()> {
432 let Some(pull) = self.pull_by_number(repo, number).await? else { return Ok(()) };
433 let (settings, _) = self.store.repo_settings(&repo.repo_id).await?;
434 let gate = Gate::parse(&settings.code_scanning_gate).unwrap_or(Gate::AtLeast(g1t_scan::osv::Severity::High));
435 let changed = match self.pull_comparison(repo, &pull).await? {
436 Some(comparison) => added_lines(&comparison),
437 None => BTreeMap::new(),
438 };
439 let on_default = self.store.open_code_fingerprints(&repo.repo_id).await?;
440 // This upload's runs, joined with what earlier uploads for the same
441 // commit found with other tools.
442 let previous = self.store.pull_check(&repo.repo_id, number, "code").await?;
443 let mut results: Vec<PullResult> = Vec::new();
444 let tools: BTreeSet<&str> = runs.iter().map(|run| run.tool.as_str()).collect();
445 if let Some(previous) = &previous
446 && previous.commit_sha == commit
447 {
448 let kept: Vec<PullResult> = serde_json::from_str::<Value>(&previous.detail)
449 .ok()
450 .and_then(|detail| serde_json::from_value(detail["results"].clone()).ok())
451 .unwrap_or_default();
452 results.extend(kept.into_iter().filter(|result| !tools.contains(result.tool.as_str())));
453 }
454 for run in runs {
455 for mut result in judge_pull(&run.findings, &on_default, &changed, gate) {
456 result.tool = run.tool.clone();
457 results.push(result);
458 }
459 }
460 let (state, description) = verdict(&results);
461 // Review comments on changed lines for results new to the pull
462 // request, each once.
463 let mut commented: Vec<String> = previous
464 .as_ref()
465 .and_then(|row| serde_json::from_str(&row.commented).ok())
466 .unwrap_or_default();
467 let page = format!("{SITE}/{}/{}/security/pulls/{number}", repo.namespace, repo.name);
468 let system = User::system(&repo.namespace);
469 let path = RepoPath { namespace: repo.namespace.clone(), name: repo.name.clone() };
470 let mut left = 0;
471 for result in results.iter().filter(|result| result.new && result.on_changed_line) {
472 let key = format!("{}|{}|{}|{}", result.tool, result.rule_id, result.path.as_deref().unwrap_or(""), result.line.unwrap_or(0));
473 if commented.contains(&key) || left == MAX_COMMENTS {
474 continue;
475 }
476 let _: Result<Outcome<Value>> = g1t_kit::call(
477 &self.work,
478 "add_comment",
479 &AddCommentArgs {
480 actor: system.clone(),
481 repo: path.clone(),
482 number,
483 body: comment_text(&result.tool, result, &page),
484 path: result.path.clone(),
485 line: result.line,
486 verdict: None,
487 },
488 )
489 .await;
490 commented.push(key);
491 left += 1;
492 }
493 self.store
494 .set_pull_check(&repo.repo_id, number, "code", commit, state, &description, &json!({ "results": results }), &commented)
495 .await?;
496 self.set_status(repo, commit, CODE_SCANNING_CHECK, state, &description, number).await;
497 Ok(())
498 }
499
500 pub(crate) async fn pull_code_scanning(&self, a: PullScanningArgs) -> Result<Outcome<PullScanning>> {
501 let repo = match self.member_repo(&a.repo, &a.viewer, crate::SEE_FINDINGS).await? {
502 Outcome::Ok(repo) => repo,
503 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
504 };
505 let code = self.store.pull_check(&repo.repo_id, a.number, "code").await?;
506 let review = self.store.pull_check(&repo.repo_id, a.number, "review").await?;
507 Ok(Outcome::Ok(PullScanning {
508 commit: code.as_ref().or(review.as_ref()).map(|row| row.commit_sha.clone()),
509 results: code
510 .as_ref()
511 .and_then(|row| serde_json::from_str::<Value>(&row.detail).ok())
512 .and_then(|detail| serde_json::from_value(detail["results"].clone()).ok())
513 .unwrap_or_default(),
514 review: review.as_ref().and_then(|row| serde_json::from_str(&row.detail).ok()),
515 code_status: code.as_ref().map(|row| row.state.clone()),
516 code_description: code.as_ref().map(|row| row.description.clone()),
517 }))
518 }
519}
520
521fn failed_upload(id: &str, a: &UploadSarifArgs, problem: String) -> SarifUpload {
522 SarifUpload {
523 id: id.to_owned(),
524 processing_status: "failed".to_owned(),
525 analyses: Vec::new(),
526 errors: vec![problem],
527 commit_sha: a.commit_sha.clone(),
528 git_ref: a.git_ref.clone(),
529 created_at: crate::store::now(),
530 }
531}
532
533#[cfg(test)]
534mod tests {
535 use super::*;
536 use g1t_contracts::repos::{DiffLine, FileDiff, FileStatus, Hunk};
537 use g1t_scan::osv::Severity;
538
539 const CODEQL: &str = include_str!("../../../crates/scan/fixtures/codeql.sarif");
540
541 #[test]
542 fn pull_refs_name_their_pull_request() {
543 assert_eq!(pull_of("refs/pull/12/head"), Some(12));
544 assert_eq!(pull_of("refs/pull/12/merge"), Some(12));
545 assert_eq!(pull_of("refs/heads/main"), None);
546 assert_eq!(pull_of("refs/pull/x/head"), None);
547 assert!(is_sha("4807077b296e6edbf410d55e72749d3e1170c291") && !is_sha("main"));
548 }
549
550 fn comparison() -> Comparison {
551 let line = |kind, new| DiffLine { kind, old: None, new, text: String::new() };
552 Comparison {
553 base: Some("a".into()),
554 head: "b".into(),
555 truncated: false,
556 files: vec![FileDiff {
557 path: "src/server.js".into(),
558 status: FileStatus::Modified,
559 additions: 1,
560 deletions: 0,
561 binary: false,
562 hunks: vec![Hunk { lines: vec![line(LineKind::Context, Some(11)), line(LineKind::Add, Some(12)), line(LineKind::Delete, None)] }],
563 }],
564 }
565 }
566
567 #[test]
568 fn only_new_results_on_changed_lines_fail_the_check() {
569 let runs = sarif::parse(CODEQL, None, None).unwrap();
570 let findings = &runs[0].findings;
571 let changed = added_lines(&comparison());
572 assert_eq!(changed["src/server.js"], BTreeSet::from([12]));
573 // Nothing on the default branch yet: the injection on line 12 is new
574 // and on a changed line, and high, so it fails.
575 let results = judge_pull(findings, &BTreeSet::new(), &changed, Gate::AtLeast(Severity::High));
576 let injection = results.iter().find(|result| result.rule_id == "js/sql-injection").unwrap();
577 assert!(injection.new && injection.on_changed_line && injection.failing);
578 // The logging result is new but on a line the pull request did not touch.
579 let logging = results.iter().find(|result| result.rule_id == "js/clear-text-logging").unwrap();
580 assert!(logging.new && !logging.on_changed_line && !logging.failing);
581 assert_eq!(verdict(&results), ("failure", "1 new result at or above the threshold".to_owned()));
582 // Already open on the default branch: not this pull request's.
583 let known: BTreeSet<String> = findings.iter().map(|finding| finding.fingerprint.clone()).collect();
584 let results = judge_pull(findings, &known, &changed, Gate::AtLeast(Severity::High));
585 assert!(results.iter().all(|result| !result.new && !result.failing));
586 assert_eq!(verdict(&results).0, "success");
587 // A gate of none never fails.
588 let results = judge_pull(findings, &BTreeSet::new(), &changed, Gate::None);
589 assert_eq!(verdict(&results), ("success", "1 new result, below the threshold".to_owned()));
590 }
591
592 #[test]
593 fn a_comment_names_the_tool_rule_and_severity() {
594 let result = PullResult {
595 tool: "CodeQL".into(),
596 rule_id: "js/sql-injection".into(),
597 level: "error".into(),
598 severity: "high".into(),
599 security_severity: Some("high".into()),
600 message: "This query string depends on a user-provided value.".into(),
601 path: Some("src/server.js".into()),
602 line: Some(12),
603 new: true,
604 on_changed_line: true,
605 failing: true,
606 };
607 let text = comment_text("CodeQL", &result, "https://g1t.sh/acme/rocket/security/pulls/3");
608 assert!(text.starts_with("**CodeQL: `js/sql-injection`** (high)"));
609 assert!(text.contains("depends on a user-provided value") && text.contains("/security/pulls/3"));
610 }
611}