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 bar | 1 | //! 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 | ||
| 14 | use std::collections::{BTreeMap, BTreeSet}; | |
| 15 | ||
| 16 | use g1t_contracts::repos::{BlobArgs, BlobView, CompareArgs, Comparison, GetArgs, LineKind, Repo, RepoPath}; | |
| 17 | use g1t_contracts::security::{AlertActivity, AlertState, DismissReason}; | |
| 18 | use 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 | }; | |
| 23 | use g1t_contracts::work::{AddCommentArgs, Pull, PullDetail, SetCommitStatusArgs, ViewArgs}; | |
| 24 | use g1t_contracts::{FailureCode, Outcome, User}; | |
| 25 | use g1t_scan::sarif::{self, Finding, Gate}; | |
| 26 | use serde_json::{Value, json}; | |
| 27 | use worker::Result; | |
| 28 | ||
| 29 | use crate::Security; | |
| 30 | use crate::store::{Activity, RepoRow}; | |
| 31 | use crate::suite::link; | |
| 32 | use crate::suite_store::NewCodeAlert; | |
| 33 | ||
| 34 | const SITE: &str = "https://g1t.sh"; | |
| 35 | /// Review comments one analysis of a pull request leaves, at most. | |
| 36 | const MAX_COMMENTS: usize = 10; | |
| 37 | /// Alerts an upload announces one by one; past it, the page says the rest. | |
| 38 | const MAX_EVENTS: usize = 20; | |
| 39 | ||
| 40 | fn 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. | |
| 45 | pub 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`. | |
| 58 | pub 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 | ||
| 64 | fn 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. | |
| 69 | pub 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. | |
| 87 | pub 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. | |
| 118 | pub 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. | |
| 133 | pub 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. | |
| 142 | pub 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 | ||
| 163 | impl 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)), | |
| Merge rulesets: branch and tag rules, agent-first, enforced on push and merge | 422 | source: Some("security".to_owned()), |
| Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar | 423 | }, |
| 424 | ) | |
| 425 | .await; | |
| 426 | if let Err(error) = set { | |
| 427 | worker::console_error!("security: {context} status on {sha}: {error}"); | |
| 428 | } | |
| 429 | } | |
| 430 | ||
| 431 | /// Judges a pull request's code scanning results and reports the check. | |
| 432 | async fn code_pull_check(&self, repo: &RepoRow, number: u32, commit: &str, runs: &[sarif::Run]) -> Result<()> { | |
| 433 | let Some(pull) = self.pull_by_number(repo, number).await? else { return Ok(()) }; | |
| 434 | let (settings, _) = self.store.repo_settings(&repo.repo_id).await?; | |
| 435 | let gate = Gate::parse(&settings.code_scanning_gate).unwrap_or(Gate::AtLeast(g1t_scan::osv::Severity::High)); | |
| 436 | let changed = match self.pull_comparison(repo, &pull).await? { | |
| 437 | Some(comparison) => added_lines(&comparison), | |
| 438 | None => BTreeMap::new(), | |
| 439 | }; | |
| 440 | let on_default = self.store.open_code_fingerprints(&repo.repo_id).await?; | |
| 441 | // This upload's runs, joined with what earlier uploads for the same | |
| 442 | // commit found with other tools. | |
| 443 | let previous = self.store.pull_check(&repo.repo_id, number, "code").await?; | |
| 444 | let mut results: Vec<PullResult> = Vec::new(); | |
| 445 | let tools: BTreeSet<&str> = runs.iter().map(|run| run.tool.as_str()).collect(); | |
| 446 | if let Some(previous) = &previous | |
| 447 | && previous.commit_sha == commit | |
| 448 | { | |
| 449 | let kept: Vec<PullResult> = serde_json::from_str::<Value>(&previous.detail) | |
| 450 | .ok() | |
| 451 | .and_then(|detail| serde_json::from_value(detail["results"].clone()).ok()) | |
| 452 | .unwrap_or_default(); | |
| 453 | results.extend(kept.into_iter().filter(|result| !tools.contains(result.tool.as_str()))); | |
| 454 | } | |
| 455 | for run in runs { | |
| 456 | for mut result in judge_pull(&run.findings, &on_default, &changed, gate) { | |
| 457 | result.tool = run.tool.clone(); | |
| 458 | results.push(result); | |
| 459 | } | |
| 460 | } | |
| 461 | let (state, description) = verdict(&results); | |
| 462 | // Review comments on changed lines for results new to the pull | |
| 463 | // request, each once. | |
| 464 | let mut commented: Vec<String> = previous | |
| 465 | .as_ref() | |
| 466 | .and_then(|row| serde_json::from_str(&row.commented).ok()) | |
| 467 | .unwrap_or_default(); | |
| 468 | let page = format!("{SITE}/{}/{}/security/pulls/{number}", repo.namespace, repo.name); | |
| 469 | let system = User::system(&repo.namespace); | |
| 470 | let path = RepoPath { namespace: repo.namespace.clone(), name: repo.name.clone() }; | |
| 471 | let mut left = 0; | |
| 472 | for result in results.iter().filter(|result| result.new && result.on_changed_line) { | |
| 473 | let key = format!("{}|{}|{}|{}", result.tool, result.rule_id, result.path.as_deref().unwrap_or(""), result.line.unwrap_or(0)); | |
| 474 | if commented.contains(&key) || left == MAX_COMMENTS { | |
| 475 | continue; | |
| 476 | } | |
| 477 | let _: Result<Outcome<Value>> = g1t_kit::call( | |
| 478 | &self.work, | |
| 479 | "add_comment", | |
| 480 | &AddCommentArgs { | |
| 481 | actor: system.clone(), | |
| 482 | repo: path.clone(), | |
| 483 | number, | |
| 484 | body: comment_text(&result.tool, result, &page), | |
| 485 | path: result.path.clone(), | |
| 486 | line: result.line, | |
| 487 | verdict: None, | |
| 488 | }, | |
| 489 | ) | |
| 490 | .await; | |
| 491 | commented.push(key); | |
| 492 | left += 1; | |
| 493 | } | |
| 494 | self.store | |
| 495 | .set_pull_check(&repo.repo_id, number, "code", commit, state, &description, &json!({ "results": results }), &commented) | |
| 496 | .await?; | |
| 497 | self.set_status(repo, commit, CODE_SCANNING_CHECK, state, &description, number).await; | |
| 498 | Ok(()) | |
| 499 | } | |
| 500 | ||
| 501 | pub(crate) async fn pull_code_scanning(&self, a: PullScanningArgs) -> Result<Outcome<PullScanning>> { | |
| 502 | let repo = match self.member_repo(&a.repo, &a.viewer, crate::SEE_FINDINGS).await? { | |
| 503 | Outcome::Ok(repo) => repo, | |
| 504 | Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)), | |
| 505 | }; | |
| 506 | let code = self.store.pull_check(&repo.repo_id, a.number, "code").await?; | |
| 507 | let review = self.store.pull_check(&repo.repo_id, a.number, "review").await?; | |
| 508 | Ok(Outcome::Ok(PullScanning { | |
| 509 | commit: code.as_ref().or(review.as_ref()).map(|row| row.commit_sha.clone()), | |
| 510 | results: code | |
| 511 | .as_ref() | |
| 512 | .and_then(|row| serde_json::from_str::<Value>(&row.detail).ok()) | |
| 513 | .and_then(|detail| serde_json::from_value(detail["results"].clone()).ok()) | |
| 514 | .unwrap_or_default(), | |
| 515 | review: review.as_ref().and_then(|row| serde_json::from_str(&row.detail).ok()), | |
| 516 | code_status: code.as_ref().map(|row| row.state.clone()), | |
| 517 | code_description: code.as_ref().map(|row| row.description.clone()), | |
| 518 | })) | |
| 519 | } | |
| 520 | } | |
| 521 | ||
| 522 | fn failed_upload(id: &str, a: &UploadSarifArgs, problem: String) -> SarifUpload { | |
| 523 | SarifUpload { | |
| 524 | id: id.to_owned(), | |
| 525 | processing_status: "failed".to_owned(), | |
| 526 | analyses: Vec::new(), | |
| 527 | errors: vec![problem], | |
| 528 | commit_sha: a.commit_sha.clone(), | |
| 529 | git_ref: a.git_ref.clone(), | |
| 530 | created_at: crate::store::now(), | |
| 531 | } | |
| 532 | } | |
| 533 | ||
| 534 | #[cfg(test)] | |
| 535 | mod tests { | |
| 536 | use super::*; | |
| 537 | use g1t_contracts::repos::{DiffLine, FileDiff, FileStatus, Hunk}; | |
| 538 | use g1t_scan::osv::Severity; | |
| 539 | ||
| 540 | const CODEQL: &str = include_str!("../../../crates/scan/fixtures/codeql.sarif"); | |
| 541 | ||
| 542 | #[test] | |
| 543 | fn pull_refs_name_their_pull_request() { | |
| 544 | assert_eq!(pull_of("refs/pull/12/head"), Some(12)); | |
| 545 | assert_eq!(pull_of("refs/pull/12/merge"), Some(12)); | |
| 546 | assert_eq!(pull_of("refs/heads/main"), None); | |
| 547 | assert_eq!(pull_of("refs/pull/x/head"), None); | |
| 548 | assert!(is_sha("4807077b296e6edbf410d55e72749d3e1170c291") && !is_sha("main")); | |
| 549 | } | |
| 550 | ||
| 551 | fn comparison() -> Comparison { | |
| 552 | let line = |kind, new| DiffLine { kind, old: None, new, text: String::new() }; | |
| 553 | Comparison { | |
| 554 | base: Some("a".into()), | |
| 555 | head: "b".into(), | |
| 556 | truncated: false, | |
| 557 | files: vec![FileDiff { | |
| 558 | path: "src/server.js".into(), | |
| 559 | status: FileStatus::Modified, | |
| 560 | additions: 1, | |
| 561 | deletions: 0, | |
| 562 | binary: false, | |
| 563 | hunks: vec![Hunk { lines: vec![line(LineKind::Context, Some(11)), line(LineKind::Add, Some(12)), line(LineKind::Delete, None)] }], | |
| 564 | }], | |
| 565 | } | |
| 566 | } | |
| 567 | ||
| 568 | #[test] | |
| 569 | fn only_new_results_on_changed_lines_fail_the_check() { | |
| 570 | let runs = sarif::parse(CODEQL, None, None).unwrap(); | |
| 571 | let findings = &runs[0].findings; | |
| 572 | let changed = added_lines(&comparison()); | |
| 573 | assert_eq!(changed["src/server.js"], BTreeSet::from([12])); | |
| 574 | // Nothing on the default branch yet: the injection on line 12 is new | |
| 575 | // and on a changed line, and high, so it fails. | |
| 576 | let results = judge_pull(findings, &BTreeSet::new(), &changed, Gate::AtLeast(Severity::High)); | |
| 577 | let injection = results.iter().find(|result| result.rule_id == "js/sql-injection").unwrap(); | |
| 578 | assert!(injection.new && injection.on_changed_line && injection.failing); | |
| 579 | // The logging result is new but on a line the pull request did not touch. | |
| 580 | let logging = results.iter().find(|result| result.rule_id == "js/clear-text-logging").unwrap(); | |
| 581 | assert!(logging.new && !logging.on_changed_line && !logging.failing); | |
| 582 | assert_eq!(verdict(&results), ("failure", "1 new result at or above the threshold".to_owned())); | |
| 583 | // Already open on the default branch: not this pull request's. | |
| 584 | let known: BTreeSet<String> = findings.iter().map(|finding| finding.fingerprint.clone()).collect(); | |
| 585 | let results = judge_pull(findings, &known, &changed, Gate::AtLeast(Severity::High)); | |
| 586 | assert!(results.iter().all(|result| !result.new && !result.failing)); | |
| 587 | assert_eq!(verdict(&results).0, "success"); | |
| 588 | // A gate of none never fails. | |
| 589 | let results = judge_pull(findings, &BTreeSet::new(), &changed, Gate::None); | |
| 590 | assert_eq!(verdict(&results), ("success", "1 new result, below the threshold".to_owned())); | |
| 591 | } | |
| 592 | ||
| 593 | #[test] | |
| 594 | fn a_comment_names_the_tool_rule_and_severity() { | |
| 595 | let result = PullResult { | |
| 596 | tool: "CodeQL".into(), | |
| 597 | rule_id: "js/sql-injection".into(), | |
| 598 | level: "error".into(), | |
| 599 | severity: "high".into(), | |
| 600 | security_severity: Some("high".into()), | |
| 601 | message: "This query string depends on a user-provided value.".into(), | |
| 602 | path: Some("src/server.js".into()), | |
| 603 | line: Some(12), | |
| 604 | new: true, | |
| 605 | on_changed_line: true, | |
| 606 | failing: true, | |
| 607 | }; | |
| 608 | let text = comment_text("CodeQL", &result, "https://g1t.sh/acme/rocket/security/pulls/3"); | |
| 609 | assert!(text.starts_with("**CodeQL: `js/sql-injection`** (high)")); | |
| 610 | assert!(text.contains("depends on a user-provided value") && text.contains("/security/pulls/3")); | |
| 611 | } | |
| 612 | } |
This file's history is long; its oldest lines are credited to the oldest commit read.