diff --git a/src/incremental.rs b/src/incremental.rs index 97fa926..7f2007a 100644 --- a/src/incremental.rs +++ b/src/incremental.rs @@ -274,6 +274,9 @@ pub struct DiffSources<'a> { pub manifest: Option<&'a Manifest>, /// The project's ignore rules now, `None` when they could not be read. pub ignore_paths: Option<&'a [String]>, + /// The `scan_configs` the upload will carry, so only scans run with the + /// same settings are offered as a baseline. + pub scan_configs: Option<&'a str>, } /// What an incremental scan of this upload would cover. @@ -325,10 +328,15 @@ fn plan_diff( // after this branch forked. It also finds the earlier runs of a detached // CI pipeline, which recorded no branch for a name to match. let mut lookup = BaselineLookup::NotFound; + let query = api::BaselineQuery { + project: project_name, + engine: BLAST_ENGINE, + scan_configs: sources.scan_configs, + }; if let Some(ancestry) = &ancestry { lookup = match find_ancestor_baseline( config, - project_name, + &query, ancestry, checksums_usable, own_root.as_deref(), @@ -352,14 +360,14 @@ fn plan_diff( // scan of this branch behind a page of dirty ones still beats // trunk's. let (own, trunks) = candidates.split_at(usize::from(branch.is_some())); - match find_baseline(config, project_name, Some(own), checksums_usable) { + match find_baseline(config, &query, Some(own), checksums_usable) { BaselineLookup::NotFound => { - find_baseline(config, project_name, Some(trunks), checksums_usable) + find_baseline(config, &query, Some(trunks), checksums_usable) } found => found, } } - None => find_baseline(config, project_name, None, checksums_usable), + None => find_baseline(config, &query, None, checksums_usable), }; } let baseline = match lookup { @@ -867,7 +875,7 @@ fn join_or(branches: &[String]) -> String { /// it one query for the project's newest usable scan on any branch. fn find_baseline( config: &Config, - project_name: &str, + query: &api::BaselineQuery<'_>, branches: Option<&[String]>, checksums_usable: bool, ) -> BaselineLookup { @@ -879,7 +887,7 @@ fn find_baseline( // Pass one will take a baseline of either kind, so it cannot ask the server // to drop what is not known-clean: that is how a git-less scan reports // itself, and those are the ones carrying checksums. - let found = search_baseline(config, project_name, &searches, checksums_usable, false); + let found = search_baseline(config, query, &searches, checksums_usable, false); if !checksums_usable || branches.is_none() || !matches!(found, BaselineLookup::NotFound) { return found; } @@ -890,13 +898,13 @@ fn find_baseline( // them is a baseline this would otherwise report as not existing. A // checksum baseline is already ruled out, so nothing is left for the // filter to wrongly exclude. - search_baseline(config, project_name, &searches, checksums_usable, true) + search_baseline(config, query, &searches, checksums_usable, true) } /// One walk of the project's scans, newest first, over `searches` in order. fn search_baseline( config: &Config, - project_name: &str, + query: &api::BaselineQuery<'_>, searches: &[Option<&str>], checksums_usable: bool, require_clean: bool, @@ -915,8 +923,7 @@ fn search_baseline( budget -= 1; let response = match api::query_baseline_scans( &url, - project_name, - BLAST_ENGINE, + query, branch, require_clean, page, @@ -1099,7 +1106,7 @@ impl Ancestry { /// is at least as far back, so none of its scans could be closer. fn find_ancestor_baseline( config: &Config, - project_name: &str, + query: &api::BaselineQuery<'_>, ancestry: &Ancestry, checksums_usable: bool, own_root: Option<&str>, @@ -1109,7 +1116,7 @@ fn find_ancestor_baseline( for batch in ancestry.shas.chunks(ANCESTOR_LOOKUP_BATCH) { match search_ancestor_batch( &url, - project_name, + query, ancestry, batch, checksums_usable, @@ -1137,7 +1144,7 @@ fn find_ancestor_baseline( /// the rest on that account. fn search_ancestor_batch( url: &str, - project_name: &str, + query: &api::BaselineQuery<'_>, ancestry: &Ancestry, batch: &[String], checksums_usable: bool, @@ -1165,8 +1172,7 @@ fn search_ancestor_batch( for page in 1..=SCAN_LOOKUP_MAX_PAGES { let response = match api::query_baseline_scans_at_commits( url, - project_name, - BLAST_ENGINE, + query, batch, // Only a checksum baseline may have been dirty, so without one // the server can drop what could never qualify. @@ -2261,6 +2267,7 @@ mod tests { exclude_narrowed: false, manifest: None, ignore_paths: None, + scan_configs: None, }; let (plan, _) = plan_git_diff(&baseline, Some(&repo), &sources).expect("a plan"); @@ -2339,6 +2346,7 @@ mod tests { exclude_narrowed: false, manifest: None, ignore_paths: None, + scan_configs: None, }; let cause = |sources: &DiffSources<'_>, repo: Option<&Repository>| { plan_git_diff(&baseline, repo, sources) @@ -2393,6 +2401,7 @@ mod tests { exclude_narrowed: false, manifest: archived, ignore_paths: now, + scan_configs: None, }, ) } diff --git a/src/scanners/blast.rs b/src/scanners/blast.rs index 2ba67cf..00c2d16 100644 --- a/src/scanners/blast.rs +++ b/src/scanners/blast.rs @@ -820,6 +820,9 @@ fn start_new_scan( // own checksums describe exactly -- so those runs resolve a plan like any // other and say what came of it. A partial scan already names what to // analyze and carries nothing forward, so it is silent too. + // Worked out once for both the baseline lookup and the upload: the server + // only accepts a base scanned with the settings this upload declares. + let scan_configs = utils::api::uploaded_scan_configs(scan_type.as_deref()); let incremental = if *disable_incremental { Err(FullScanReason::new( FullScanCause::DisabledByFlag, @@ -856,6 +859,7 @@ fn start_new_scan( exclude_narrowed: exclude.is_some(), manifest: archive_contents.manifest.as_ref(), ignore_paths: include_rules.project_ignore_paths.as_deref(), + scan_configs: scan_configs.as_deref(), }, ) // Force-included files are usually unchanged, and the server carries @@ -880,7 +884,7 @@ fn start_new_scan( project_name, repo_info, utils::api::UploadOptions { - scan_type, + scan_configs, policy, metadata, incremental, diff --git a/src/utils/api.rs b/src/utils/api.rs index 13f59b6..a54248d 100644 --- a/src/utils/api.rs +++ b/src/utils/api.rs @@ -553,7 +553,9 @@ pub struct UploadZipResult { /// Per-scan settings travelling with the archive without being part of it. #[derive(Debug)] pub struct UploadOptions { - pub scan_type: Option, + /// The `scan_configs` field as sent, from `uploaded_scan_configs`. The + /// baseline lookup is given the same value, so the two cannot disagree. + pub scan_configs: Option, pub policy: Option, pub metadata: Option, /// The diff for the server to analyze instead of the whole project, or why @@ -574,6 +576,21 @@ pub struct UploadOptions { pub partial_files: Option>, } +/// What `--scan-type` becomes in the upload's `scan_configs` field, `None` when +/// the field is not sent. +/// +/// The one place this is worked out. The server compares a scan's settings as +/// they were uploaded, so a baseline lookup that described this run any other +/// way would be offered scans the upload is then refused for. +pub fn uploaded_scan_configs(scan_type: Option<&str>) -> Option { + let scan_type = scan_type?; + Some(if scan_type.contains("blast") { + "base".to_string() + } else { + scan_type.to_string() + }) +} + pub fn upload_zip( file_path: &str, url: &str, @@ -582,7 +599,7 @@ pub fn upload_zip( options: UploadOptions, ) -> Result> { let UploadOptions { - scan_type, + scan_configs, policy, metadata, incremental, @@ -736,13 +753,8 @@ pub fn upload_zip( multipart::Part::text(if info.dirty { DIRTY_TRUE } else { DIRTY_FALSE }), ); } - if let Some(scan_type) = scan_type.clone() { - let scan_type = if scan_type.contains("blast") { - "base".to_string() - } else { - scan_type - }; - form = form.part("scan_configs", multipart::Part::text(scan_type.to_string())); + if let Some(scan_configs) = &scan_configs { + form = form.part("scan_configs", multipart::Part::text(scan_configs.clone())); } if let Some(policy) = policy.clone() { form = form.part("target_policies", multipart::Part::text(policy.to_string())); @@ -1419,6 +1431,14 @@ pub fn query_scan_list( request_scan_list(url, query_params) } +/// What every baseline lookup of one run asks for, however it searches. +pub struct BaselineQuery<'a> { + pub project: &'a str, + pub engine: &'a str, + /// The `scan_configs` this run will upload, from `uploaded_scan_configs`. + pub scan_configs: Option<&'a str>, +} + /// One page of the project's scans that could be diffed against, newest first. /// /// Filters are server-side, so the answer is usually the first entry of page @@ -1435,14 +1455,13 @@ pub fn query_scan_list( /// comparison, but its stored checksums describe its contents exactly. pub fn query_baseline_scans( url: &str, - project: &str, - engine: &str, + query: &BaselineQuery<'_>, branch: Option<&str>, require_clean: bool, page: u16, page_size: u16, ) -> Result> { - let mut query_params = baseline_scan_params(project, engine, require_clean, page, page_size); + let mut query_params = baseline_scan_params(query, require_clean, page, page_size); if let Some(branch) = branch { query_params.push(("branch", branch.to_string())); } @@ -1458,21 +1477,19 @@ pub fn query_baseline_scans( /// they act on. pub fn query_baseline_scans_at_commits( url: &str, - project: &str, - engine: &str, + query: &BaselineQuery<'_>, shas: &[String], require_clean: bool, page: u16, page_size: u16, ) -> Result> { - let mut query_params = baseline_scan_params(project, engine, require_clean, page, page_size); + let mut query_params = baseline_scan_params(query, require_clean, page, page_size); query_params.push(("sha", shas.join(","))); request_scan_list(url, query_params) } fn baseline_scan_params( - project: &str, - engine: &str, + query: &BaselineQuery<'_>, require_clean: bool, page: u16, page_size: u16, @@ -1480,13 +1497,25 @@ fn baseline_scan_params( let mut query_params = vec![ ("page", page.to_string()), ("page_size", page_size.to_string()), - ("project", project.to_string()), - ("engine", engine.to_string()), + ("project", query.project.to_string()), + ("engine", query.engine.to_string()), ("status", "complete".to_string()), ("exclude_pull_requests", "true".to_string()), // A partial scan's findings cover only the files it was pointed at, // so copying forward from one would drop everything else. ("full_project_state", "true".to_string()), + // The server refuses a base whose scan settings differ from the + // upload's and scans everything, so ask only for scans run with the + // settings this one will send. Always sent, empty for a run that + // uploads no `scan_configs`: its presence is what turns the filter + // on. A backend predating it ignores the parameter and answers with + // scans of any settings, and the scan list does not report settings + // to re-check here, so there a mismatched base is still refused on + // upload, as before. + ( + "comparable_scan_configs", + query.scan_configs.unwrap_or_default().to_string(), + ), ]; if require_clean { query_params.push(("worktree_dirty", "false".to_string())); @@ -2663,6 +2692,48 @@ pub struct SCAIssuesResponse { #[cfg(test)] mod tests { use super::*; + + fn comparable_scan_configs_sent(scan_type: Option<&str>) -> Vec { + let scan_configs = uploaded_scan_configs(scan_type); + let query = BaselineQuery { + project: "proj", + engine: "corgea-blast", + scan_configs: scan_configs.as_deref(), + }; + baseline_scan_params(&query, false, 1, 30) + .into_iter() + .filter(|(name, _)| *name == "comparable_scan_configs") + .map(|(_, value)| value) + .collect() + } + + #[test] + fn a_baseline_lookup_names_the_scan_configs_the_upload_will_carry() { + assert_eq!( + comparable_scan_configs_sent(Some("policy,secrets")), + ["policy,secrets"] + ); + } + + #[test] + fn a_baseline_lookup_for_a_default_run_sends_the_parameter_empty() { + // Present even with nothing to say: the parameter is what asks the + // server to drop scans this run could not use, and a default run + // cannot use one that ran only some scan types. + assert_eq!(comparable_scan_configs_sent(None), [""]); + } + + #[test] + fn a_scan_type_containing_blast_is_looked_up_as_it_is_uploaded() { + assert_eq!( + uploaded_scan_configs(Some("blast,secrets")).as_deref(), + Some("base") + ); + assert_eq!( + comparable_scan_configs_sent(Some("blast,secrets")), + ["base"] + ); + } use reqwest::header::{HeaderMap, HeaderValue}; #[test] diff --git a/tests/cloud_commands_e2e/common/mod.rs b/tests/cloud_commands_e2e/common/mod.rs index 101ab61..22f489b 100644 --- a/tests/cloud_commands_e2e/common/mod.rs +++ b/tests/cloud_commands_e2e/common/mod.rs @@ -401,6 +401,7 @@ pub(crate) fn assert_ancestor_lookup_request( assert_query(request, "status", "complete")?; assert_query(request, "exclude_pull_requests", "true")?; assert_query(request, "full_project_state", "true")?; + assert_default_run_scan_configs(request)?; if let Ok(branch) = query_value(request, "branch") { return Err(format!( "a lookup by commit must not ask for branch {branch}" @@ -452,6 +453,7 @@ pub(crate) fn assert_baseline_lookup_request( assert_query(request, "engine", "corgea-blast")?; assert_query(request, "status", "complete")?; assert_query(request, "exclude_pull_requests", "true")?; + assert_default_run_scan_configs(request)?; match (require_clean, query_value(request, "worktree_dirty")) { (true, Ok(value)) if value == "false" => {} (true, _) => return Err("the second walk must ask for clean scans only".to_string()), @@ -472,6 +474,14 @@ pub(crate) fn assert_baseline_lookup_request( assert_query(request, "branch", branch) } +/// A run without `--scan-type` uploads no `scan_configs`, and says so on every +/// baseline lookup with an empty value. Present rather than omitted, because +/// the parameter being there is what makes the server drop scans whose +/// settings differ from this run's. +fn assert_default_run_scan_configs(request: &CapturedRequest) -> Result<(), String> { + assert_query(request, "comparable_scan_configs", "") +} + pub(crate) fn query_value(request: &CapturedRequest, key: &str) -> Result { let (_, query) = target_path_and_query(&request.target); query diff --git a/tests/cloud_commands_e2e/scan_incremental.rs b/tests/cloud_commands_e2e/scan_incremental.rs index b077c05..59d7558 100644 --- a/tests/cloud_commands_e2e/scan_incremental.rs +++ b/tests/cloud_commands_e2e/scan_incremental.rs @@ -1474,6 +1474,80 @@ fn a_clean_baseline_is_found_even_when_dirty_scans_come_back_first() { ); } +/// The server refuses a base whose scan settings differ from the upload's and +/// scans everything. Two jobs scanning one branch with different `--scan-type` +/// values would each be handed the other's newest scan, so every lookup says +/// which settings this run uploads and the server answers with scans it could +/// actually use. +#[test] +fn every_baseline_lookup_names_the_scan_type_the_upload_carries() { + assert_lookups_and_upload_agree("policy,secrets", "policy,secrets"); +} + +/// `--scan-type blast` is uploaded as `base`, and the lookup has to describe +/// the run the way the upload does or the two would name different settings. +#[test] +fn a_blast_scan_type_is_looked_up_under_the_name_it_is_uploaded_as() { + assert_lookups_and_upload_agree("blast", "base"); +} + +/// One `--scan-type` run through both kinds of lookup and the upload, each +/// asserted to carry `uploaded`. +fn assert_lookups_and_upload_agree(scan_type: &str, uploaded: &'static str) { + let project = git_project(); + let base_sha = project.sha.clone(); + second_commit(&project); + + let mut plan = vec![ + verify_request(), + scan_settings_request(PROJECT), + expected_request( + "look up a baseline scan of a recent commit", + move |request| { + assert_authenticated_request(request, Method::GET, "/api/v1/scans")?; + query_value(request, "sha")?; + assert_query(request, "comparable_scan_configs", uploaded) + }, + json_response(scans_response(Vec::new())), + ), + expected_request( + "look up a baseline scan to diff against", + move |request| { + assert_authenticated_request(request, Method::GET, "/api/v1/scans")?; + assert_query(request, "branch", FIXTURE_BRANCH)?; + assert_query(request, "comparable_scan_configs", uploaded) + }, + json_response(scans_response(vec![baseline_scan(&base_sha)])), + ), + start_upload(), + expected_request( + "upload BLAST archive with the diff", + move |request| { + assert_authenticated_request( + request, + Method::PATCH, + "/api/v1/start-scan/transfer-123/", + )?; + assert_multipart_text_field(request, "scan_configs", uploaded)?; + assert_multipart_text_field(request, "incremental_base_sha", &base_sha) + }, + json_response(json!({"scan_id": "blast-scan-123", "project_id": 91})), + ), + ]; + plan.extend(scan_tail()); + + let api = ApiStub::start(plan); + let (mut command, _home) = cloud_command(&api, project.path()); + command.args(["scan", "blast", "--project-name", PROJECT]); + command.args(["--scan-type", scan_type]); + + let output = run_with_timeout(command, &api); + let transcript = api.assert_finished(); + let context = output_context(&output, &transcript); + + assert_eq!(output.status.code(), Some(0), "{context}"); +} + /// No git repository and a baseline that stored no checksums leaves nothing to /// compare either way, which must not stall or fail the scan. #[test]