diff --git a/Cargo.lock b/Cargo.lock index d13fa4c..3f635d9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -364,6 +364,7 @@ name = "cigen-mockci" version = "0.1.0" dependencies = [ "anyhow", + "base64", "globset", "hex", "rusqlite", diff --git a/crates/mockci/Cargo.toml b/crates/mockci/Cargo.toml index eb93ce0..a6011ce 100644 --- a/crates/mockci/Cargo.toml +++ b/crates/mockci/Cargo.toml @@ -8,6 +8,7 @@ publish = false [dependencies] anyhow.workspace = true +base64 = "0.22.1" globset = "0.4.22" hex = "0.4.3" rusqlite = { version = "0.43.0", features = ["bundled"] } diff --git a/crates/mockci/src/actions.rs b/crates/mockci/src/actions.rs index 644f783..ec071b5 100644 --- a/crates/mockci/src/actions.rs +++ b/crates/mockci/src/actions.rs @@ -135,7 +135,7 @@ fn checkout(ctx: &JobContext) -> Result { )?; for (destination, source) in &ctx.sim.files { let target = ctx.workspace.join(destination); - copy_tree(source, &target)?; + copy_tree(source, &target, &ctx.workspace)?; make_executable(&target)?; } Ok(ActionResult::ok(format!("checked out {}", ctx.event.sha()))) @@ -208,29 +208,32 @@ fn upload(with: &BTreeMap, ctx: &JobContext) -> Result entry, + Err(error) if error.path().is_some_and(is_broken_link) => continue, + Err(error) => return Err(error.into()), + }; if entry.file_type().is_file() { - copy_tree( + copy_followed( entry.path(), &destination.join(entry.path().strip_prefix(&source)?), )?; @@ -255,11 +258,27 @@ fn download(with: &BTreeMap, ctx: &JobContext) -> Result Result<()> { + if let Some(parent) = destination.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::copy(source, destination) + .with_context(|| format!("copying {} to {}", source.display(), destination.display()))?; + Ok(()) +} + +fn is_broken_link(path: &Path) -> bool { + path.symlink_metadata() + .is_ok_and(|m| m.file_type().is_symlink()) + && !path.exists() +} + fn make_executable(path: &Path) -> Result<()> { use std::os::unix::fs::PermissionsExt; if path.is_file() { diff --git a/crates/mockci/src/cache.rs b/crates/mockci/src/cache.rs index 4a3fbd8..972728f 100644 --- a/crates/mockci/src/cache.rs +++ b/crates/mockci/src/cache.rs @@ -82,7 +82,7 @@ impl Cache<'_> { for (index, path) in paths.iter().enumerate() { let stored = self.blob_path(entry.id, index); if stored.exists() { - copy_tree(&stored, &workspace.join(path))?; + copy_tree(&stored, &workspace.join(path), workspace)?; } } let exact = entry.key == key; @@ -131,7 +131,7 @@ impl Cache<'_> { for (index, path) in paths.iter().enumerate() { let source = workspace.join(path); if source.exists() { - copy_tree(&source, &self.blob_path(id, index))?; + copy_tree(&source, &self.blob_path(id, index), self.blobs)?; } } self.record("save", key, None, Some(scope), "saved") @@ -162,25 +162,82 @@ impl Cache<'_> { } } -/// Copies a file or a directory tree, replacing files that exist at the destination. -pub fn copy_tree(source: &Path, destination: &Path) -> Result<()> { - if source.is_file() { +/// Copies a file or a directory tree to `destination`, which must stay inside `root` (a job's +/// workspace or directory, or the cache's own store), replacing files that exist there. +/// Symlinks are copied as symlinks, never followed, as tar does for caches. Nothing is written +/// through a symlink: a symlink at the destination is replaced, and the destination's nearest +/// existing ancestor, and each entry's parent, must resolve inside `root`. +pub fn copy_tree(source: &Path, destination: &Path, root: &Path) -> Result<()> { + let metadata = std::fs::symlink_metadata(source) + .with_context(|| format!("reading {}", source.display()))?; + std::fs::create_dir_all(root)?; + let root = root + .canonicalize() + .with_context(|| format!("resolving {}", root.display()))?; + if destination + .symlink_metadata() + .is_ok_and(|m| m.file_type().is_symlink()) + { + std::fs::remove_file(destination)?; + } + let inside = |path: &Path| -> Result<()> { + let existing = path + .ancestors() + .find(|ancestor| ancestor.symlink_metadata().is_ok()) + .context("a path with no existing ancestor")?; + if !existing.canonicalize()?.starts_with(&root) { + bail!( + "writing {} would go through a symlink to outside {}", + path.display(), + root.display() + ); + } + Ok(()) + }; + inside(destination)?; + if !metadata.is_dir() { if let Some(parent) = destination.parent() { std::fs::create_dir_all(parent)?; } - std::fs::copy(source, destination).with_context(|| { - format!("copying {} to {}", source.display(), destination.display()) - })?; - return Ok(()); + return copy_entry(source, destination, metadata.file_type().is_symlink()); } - for entry in walkdir::WalkDir::new(source) { + std::fs::create_dir_all(destination)?; + // Directories come before their contents, so each entry's parent exists by the time it's + // copied, and is checked first. + for entry in walkdir::WalkDir::new(source).min_depth(1) { let entry = entry?; let target = destination.join(entry.path().strip_prefix(source)?); + inside(target.parent().context("a copied entry has a parent")?)?; if entry.file_type().is_dir() { + if target + .symlink_metadata() + .is_ok_and(|m| m.file_type().is_symlink()) + { + std::fs::remove_file(&target)?; + } std::fs::create_dir_all(&target)?; } else { - copy_tree(entry.path(), &target)?; + copy_entry(entry.path(), &target, entry.file_type().is_symlink())?; } } Ok(()) } + +/// Copies one file or symlink, replacing whatever file or symlink is at `target` rather than +/// writing through it. +fn copy_entry(source: &Path, target: &Path, is_symlink: bool) -> Result<()> { + if let Ok(existing) = target.symlink_metadata() + && !existing.is_dir() + { + std::fs::remove_file(target)?; + } + if is_symlink { + let link = std::fs::read_link(source)?; + std::os::unix::fs::symlink(&link, target) + .with_context(|| format!("linking {} to {}", target.display(), link.display()))?; + } else { + std::fs::copy(source, target) + .with_context(|| format!("copying {} to {}", source.display(), target.display()))?; + } + Ok(()) +} diff --git a/crates/mockci/src/circleci/cache.rs b/crates/mockci/src/circleci/cache.rs new file mode 100644 index 0000000..18d520a --- /dev/null +++ b/crates/mockci/src/circleci/cache.rs @@ -0,0 +1,153 @@ +//! A model of CircleCI's cache, as `restore_cache` and `save_cache` see it: +//! +//! - One scope for the whole project: every branch, and pull requests from the same repository, +//! read and write the same caches. +//! - `restore_cache` tries each key in order. Each key matches as a prefix, and the most +//! recently saved match wins. +//! - Caches are immutable: saving a key that exists does nothing. +//! - Caches expire 15 days after they're saved, however often they're read. +//! - A cache restores its files to the paths they were saved from. + +use super::paths::JobDirs; +use super::template; +use crate::cache::copy_tree; +use crate::db::{CacheEvent, Db}; +use anyhow::{Context, Result, bail}; +use std::path::{Path, PathBuf}; + +/// The `scope` CircleCI entries have in the shared table, apart from GitHub's refs. +pub const SCOPE: &str = "circleci-project"; +const VERSION: &str = "circleci"; +pub const EXPIRY_SECONDS: i64 = 15 * 24 * 60 * 60; + +pub struct Cache<'a> { + pub db: &'a Db, + pub blobs: &'a Path, + pub job_row: i64, + pub now: i64, + pub dirs: JobDirs<'a>, + /// When the job started, on the host's clock: a host `/tmp` path changed since then was + /// written by one of its steps. + pub started: std::time::SystemTime, +} + +impl Cache<'_> { + /// Restores the newest cache matching the first key that matches anything. Returns the + /// key it restored, if any. + pub fn restore(&self, keys: &[String]) -> Result> { + self.db + .expire_cache_entries(SCOPE, self.now, EXPIRY_SECONDS)?; + for key in keys { + let Some(entry) = self.db.find_prefix_cache_entry(key, VERSION, SCOPE)? else { + continue; + }; + let dir = self.blob_dir(entry.id); + let manifest = std::fs::read_to_string(dir.join("paths"))?; + for (index, path) in manifest.lines().enumerate() { + let stored = dir.join(index.to_string()); + if stored.exists() { + let target = resolve_path(path, &self.dirs)?; + let root = if target.starts_with(self.dirs.tmp) { + self.dirs.tmp + } else { + self.dirs.home + }; + copy_tree(&stored, &target, root)?; + } + } + self.record("restore", key, Some(&entry.key), "hit")?; + return Ok(Some(entry.key)); + } + self.record("restore", &keys.join(" "), None, "miss")?; + Ok(None) + } + + /// Saves `paths` (already resolved) under `key`, unless a cache with that key exists. + /// Returns what CircleCI would print. + pub fn save(&self, key: &str, paths: &[PathBuf]) -> Result { + self.db + .expire_cache_entries(SCOPE, self.now, EXPIRY_SECONDS)?; + if self + .db + .find_exact_cache_entry(key, VERSION, SCOPE)? + .is_some() + { + self.record("save", key, None, "exists")?; + return Ok(format!( + "Skipping cache generation, cache already exists for key: {key}" + )); + } + let logical = paths + .iter() + .map(|path| self.dirs.logical(path)) + .collect::>>()?; + for (path, logical) in paths.iter().zip(&logical) { + if logical.starts_with("/tmp/") && !path.exists() && self.changed_on_host(logical) { + bail!( + "`save_cache` of `{logical}`: the job's /tmp has no `{logical}`, but the host's does, so a step wrote to the host. Steps reach the job's /tmp through `${{TMPDIR:-/tmp}}`" + ); + } + } + if !paths.iter().any(|path| path.exists()) { + self.record("save", key, None, "no-files")?; + return Ok(format!("No files to save for key: {key}")); + } + let id = self.db.insert_cache_entry(key, VERSION, SCOPE, self.now)?; + let dir = self.blob_dir(id); + std::fs::create_dir_all(&dir)?; + let mut manifest = String::new(); + for (index, (path, logical)) in paths.iter().zip(&logical).enumerate() { + manifest.push_str(&format!("{logical}\n")); + if path.exists() { + copy_tree(path, &dir.join(index.to_string()), self.blobs)?; + } + } + std::fs::write(dir.join("paths"), manifest)?; + self.record("save", key, None, "saved")?; + Ok(format!("Stored cache for key: {key}")) + } + + /// Whether anything at or under the host's `path` changed after the job started (a step + /// wrote it), rather than being left there by something else. + /// The newest change anywhere under `path` counts: a write deep inside an old directory + /// changes only its own parent's time. + fn changed_on_host(&self, path: &str) -> bool { + walkdir::WalkDir::new(path) + .into_iter() + .filter_map(Result::ok) + .filter_map(|entry| entry.metadata().ok()?.modified().ok()) + .any(|modified| modified >= self.started) + } + + fn blob_dir(&self, id: i64) -> PathBuf { + self.blobs.join(format!("circleci-{id}")) + } + + fn record(&self, action: &str, key: &str, matched: Option<&str>, result: &str) -> Result<()> { + self.db.record_cache_event( + self.job_row, + &CacheEvent { + action: action.to_string(), + key: key.to_string(), + matched_key: matched.map(str::to_string), + scope: Some(SCOPE.to_string()), + result: result.to_string(), + }, + ) + } +} + +/// A cache path as the job would see it (`paths.rs`). +pub fn resolve_path(path: &str, dirs: &JobDirs) -> Result { + if path.contains(['*', '?', '[']) { + bail!("mockci doesn't model glob patterns in cache paths, got `{path}`"); + } + dirs.resolve(path, "the cache path") +} + +/// The keys of a `restore_cache` step (`key` or `keys`), rendered. +pub fn render_keys(keys: &[String], ctx: &template::Context) -> Result> { + keys.iter() + .map(|key| template::render(key, ctx).with_context(|| format!("in cache key `{key}`"))) + .collect() +} diff --git a/crates/mockci/src/circleci/config.rs b/crates/mockci/src/circleci/config.rs new file mode 100644 index 0000000..e4afe27 --- /dev/null +++ b/crates/mockci/src/circleci/config.rs @@ -0,0 +1,248 @@ +//! A CircleCI 2.1 config, as far as mockci models it. Unknown keys are errors, so a test can't +//! pass because something was silently ignored. + +use super::workflow_config::workflow; +use crate::yaml::{check_keys, optional_bool, optional_scalar, scalar, string_map}; +use anyhow::{Context, Result, bail}; +use serde_yaml::{Mapping, Value as Yaml}; +use std::collections::BTreeMap; + +/// The orb mockci runs natively, and the alias it has to be declared under. +pub const CONTINUATION_ORB: &str = "circleci/continuation"; + +#[derive(Debug, Clone)] +pub struct Config { + pub setup: bool, + pub parameters: BTreeMap, + pub commands: BTreeMap, + pub jobs: BTreeMap, + pub workflows: BTreeMap, + /// Whether `continuation: circleci/continuation@...` is declared. + pub has_continuation_orb: bool, +} + +#[derive(Debug, Clone)] +pub struct Parameter { + pub kind: String, + pub default: Option, + pub allowed: Vec, +} + +#[derive(Debug, Clone)] +pub struct Command { + pub parameters: BTreeMap, + pub steps: Vec, +} + +#[derive(Debug, Clone)] +pub struct Job { + pub working_directory: Option, + pub environment: BTreeMap, + pub steps: Vec, +} + +#[derive(Debug, Clone)] +pub struct Workflow { + /// `when:` as written: a boolean or `<< pipeline.parameters.x >>`. + pub when: Option, + pub jobs: Vec, +} + +/// A job another job requires, and the statuses it may finish with (`success` unless the +/// config lists others). +#[derive(Debug, Clone)] +pub struct Requirement { + pub job: String, + pub statuses: Vec, +} + +#[derive(Debug, Clone)] +pub struct WorkflowJob { + /// The job definition it runs. + pub job: String, + /// Its name in the workflow (`name:`, or the job's). + pub name: String, + pub requires: Vec, + pub branches_only: Vec, + pub branches_ignore: Vec, +} + +pub fn parse(text: &str) -> Result { + let root: Yaml = serde_yaml::from_str(text).context("parsing the config")?; + let Yaml::Mapping(root) = root else { + bail!("a CircleCI config must be a mapping"); + }; + check_keys( + &root, + &[ + "version", + "setup", + "parameters", + "orbs", + "commands", + "jobs", + "workflows", + ], + "top-level", + )?; + let version = optional_scalar(&root, "version")?; + if version.as_deref() != Some("2.1") { + bail!("mockci models `version: 2.1` only, found {version:?}"); + } + let mut has_continuation_orb = false; + for (alias, reference) in mapping(&root, "orbs")? { + let reference = scalar(&reference)?; + let alias = scalar(&alias)?; + let Some((name, _version)) = reference.split_once('@') else { + bail!("orb `{alias}` must pin a version (`{reference}`)"); + }; + if name != CONTINUATION_ORB || alias != "continuation" { + bail!( + "mockci runs only `continuation: {CONTINUATION_ORB}@`, not `{alias}: {reference}`" + ); + } + has_continuation_orb = true; + } + let config = Config { + setup: optional_bool(&root, "setup")?, + parameters: parameters(&root).context("in `parameters`")?, + commands: mapping(&root, "commands")? + .into_iter() + .map(|(name, body)| { + let name = scalar(&name)?; + let command = command(&body).with_context(|| format!("in command `{name}`"))?; + Ok((name, command)) + }) + .collect::>()?, + jobs: mapping(&root, "jobs")? + .into_iter() + .map(|(name, body)| { + let name = scalar(&name)?; + let job = job(&body).with_context(|| format!("in job `{name}`"))?; + Ok((name, job)) + }) + .collect::>()?, + workflows: mapping(&root, "workflows")? + .into_iter() + .map(|(name, body)| { + let name = scalar(&name)?; + let workflow = workflow(&body).with_context(|| format!("in workflow `{name}`"))?; + Ok((name, workflow)) + }) + .collect::>()?, + has_continuation_orb, + }; + for (name, workflow) in &config.workflows { + for entry in &workflow.jobs { + if !config.jobs.contains_key(&entry.job) { + bail!( + "workflow `{name}` runs job `{}`, which isn't defined", + entry.job + ); + } + } + } + if config.setup && config.workflows.len() != 1 { + bail!( + "a setup config must have exactly one workflow, found {}", + config.workflows.len() + ); + } + Ok(config) +} + +fn mapping(map: &Mapping, key: &str) -> Result { + match map.get(key) { + None | Some(Yaml::Null) => Ok(Mapping::new()), + Some(Yaml::Mapping(entries)) => Ok(entries.clone()), + Some(other) => bail!("`{key}` must be a mapping, found {other:?}"), + } +} + +pub(super) fn as_mapping<'a>(value: &'a Yaml, what: &str) -> Result<&'a Mapping> { + value + .as_mapping() + .with_context(|| format!("{what} must be a mapping, found {value:?}")) +} + +fn parameters(map: &Mapping) -> Result> { + mapping(map, "parameters")? + .iter() + .map(|(name, body)| { + let name = scalar(name)?; + let body = as_mapping(body, &format!("parameter `{name}`"))?; + check_keys( + body, + &["type", "default", "description", "enum"], + "parameter", + )?; + let kind = optional_scalar(body, "type")? + .with_context(|| format!("parameter `{name}` needs a `type`"))?; + if !["string", "boolean", "integer", "enum"].contains(&kind.as_str()) { + bail!("parameter `{name}`: mockci doesn't model `type: {kind}`"); + } + let allowed = match body.get("enum") { + None => Vec::new(), + Some(Yaml::Sequence(values)) => values.iter().map(scalar).collect::>()?, + Some(other) => bail!("parameter `{name}`: `enum` must be a list, found {other:?}"), + }; + Ok(( + name, + Parameter { + kind, + default: body.get("default").cloned(), + allowed, + }, + )) + }) + .collect() +} + +fn steps(map: &Mapping) -> Result> { + match map.get("steps") { + Some(Yaml::Sequence(steps)) => Ok(steps.clone()), + other => bail!("`steps` must be a list, found {other:?}"), + } +} + +fn command(body: &Yaml) -> Result { + let body = as_mapping(body, "a command")?; + check_keys(body, &["description", "parameters", "steps"], "command")?; + Ok(Command { + parameters: parameters(body)?, + steps: steps(body)?, + }) +} + +fn job(body: &Yaml) -> Result { + let body = as_mapping(body, "a job")?; + check_keys( + body, + &[ + "docker", + "resource_class", + "working_directory", + "environment", + "steps", + ], + "job", + )?; + // The first image is the one steps run in; its `environment` comes before the job's. + let (_image, mut environment) = match body.get("docker") { + Some(Yaml::Sequence(images)) if !images.is_empty() => { + let first = as_mapping(&images[0], "a docker image")?; + check_keys(first, &["image", "environment", "auth"], "docker image")?; + let image = optional_scalar(first, "image")?.context("a docker image needs `image`")?; + (image, string_map(first, "environment")?) + } + other => { + bail!("mockci models docker jobs only: `docker` must list images, found {other:?}") + } + }; + environment.extend(string_map(body, "environment")?); + Ok(Job { + working_directory: optional_scalar(body, "working_directory")?, + environment, + steps: steps(body)?, + }) +} diff --git a/crates/mockci/src/circleci/continuation.rs b/crates/mockci/src/circleci/continuation.rs new file mode 100644 index 0000000..1a61cca --- /dev/null +++ b/crates/mockci/src/circleci/continuation.rs @@ -0,0 +1,178 @@ +//! The continuation orb's `continue` and `finish`, run natively: the orb's own script posts to +//! CircleCI's API and writes to the host's `/tmp`. + +use super::config::{self, Parameter}; +use super::job::{Continued, JobRun, StepResult}; +use super::params::resolve; +use crate::yaml::scalar; +use anyhow::{Context, Result, bail}; +use serde_yaml::{Mapping, Value as Yaml}; +use std::collections::BTreeMap; + +fn parameter(kind: &str, default: Option<&str>, allowed: &[&str]) -> Parameter { + Parameter { + kind: kind.into(), + default: default.map(|value| Yaml::String(value.into())), + allowed: allowed.iter().map(|value| value.to_string()).collect(), + } +} + +fn finish_declared() -> BTreeMap { + BTreeMap::from([( + "circleci_domain".into(), + parameter("string", Some("circleci.com"), &[]), + )]) +} + +fn given(body: &Yaml) -> Result> { + let map = match body { + Yaml::Null => Mapping::new(), + Yaml::Mapping(map) => map.clone(), + other => bail!("a continuation command takes a mapping, found {other:?}"), + }; + map.iter() + .map(|(k, v)| Ok((scalar(k)?, v.clone()))) + .collect() +} + +/// The `continue` step's `when` parameter. +pub fn when(body: &Yaml) -> Result { + Ok(continue_parameters(body)?["when"].clone()) +} + +pub fn run_continue(job: &mut JobRun, body: &Yaml) -> Result<(String, StepResult)> { + let parameters = continue_parameters(body)?; + Ok(( + "Continue Pipeline".into(), + continue_pipeline(job, ¶meters)?, + )) +} + +pub fn run_finish(job: &mut JobRun, body: &Yaml) -> Result<(String, StepResult)> { + resolve(&finish_declared(), &given(body)?, "continuation/finish")?; + Ok(("Finish Pipeline".into(), finish(job))) +} + +/// The `continue` command's parameters, as orb version 1.0.0 declares them. +fn continue_parameters(body: &Yaml) -> Result> { + let mut declared = finish_declared(); + declared.insert("configuration_path".into(), parameter("string", None, &[])); + declared.insert("parameters".into(), parameter("string", Some("{}"), &[])); + declared.insert( + "when".into(), + parameter( + "enum", + Some("on_success"), + &["on_success", "on_fail", "always"], + ), + ); + resolve(&declared, &given(body)?, "continuation/continue") +} + +const NO_KEY: &str = "CIRCLE_CONTINUATION_KEY is required. Make sure setup workflows are enabled."; + +fn take_continuation<'a>(job: &'a mut JobRun) -> Result<&'a mut Option, StepResult> { + let Some(slot) = job.continuation.as_deref_mut() else { + return Err(StepResult::failed(NO_KEY)); + }; + if slot.is_some() { + return Err(StepResult::failed( + "The continue API refused: this pipeline has already been continued", + )); + } + Ok(slot) +} + +/// Fails as the orb does, in the orb's order: no continuation key, then unreadable inputs, then +/// whatever the continue API refuses. +fn continue_pipeline( + job: &mut JobRun, + parameters: &BTreeMap, +) -> Result { + if job.continuation.is_none() { + return Ok(StepResult::failed(NO_KEY)); + } + let dirs = job.dirs(); + let config_path = dirs.resolve(¶meters["configuration_path"], "configuration_path")?; + let Ok(config) = std::fs::read_to_string(&config_path) else { + return Ok(StepResult::failed(format!( + "can't read {}", + config_path.display() + ))); + }; + // `parameters` is JSON, or a path to a file holding JSON: the orb tries it as a file first. + let raw = ¶meters["parameters"]; + let text = if raw.trim_start().starts_with('{') { + raw.clone() + } else { + match dirs.resolve(raw, "the parameters file")? { + file if file.is_file() => std::fs::read_to_string(&file)?, + _ => raw.clone(), + } + }; + let Ok(serde_json::Value::Object(values)) = serde_json::from_str(&text) else { + return Ok(StepResult::failed("PARAMETERS aren't valid json")); + }; + let continued = + config::parse(&config).with_context(|| format!("in {}", config_path.display()))?; + if continued.setup { + return Ok(StepResult::failed( + "The continue API refused: a pipeline can't continue with another setup config", + )); + } + if let Err(error) = resolve( + &continued.parameters, + &json_to_yaml(&values)?, + "the continued config", + ) { + return Ok(StepResult::failed(format!( + "The continue API refused: {error:#}" + ))); + } + let slot = match take_continuation(job) { + Ok(slot) => slot, + Err(result) => return Ok(result), + }; + *slot = Some(Continued { + config: Some(config), + parameters: values.clone(), + }); + Ok(StepResult::ok(format!( + "continued with {} and parameters {}", + parameters["configuration_path"], + serde_json::Value::Object(values) + ))) +} + +fn finish(job: &mut JobRun) -> StepResult { + match take_continuation(job) { + Ok(slot) => { + *slot = Some(Continued { + config: None, + parameters: serde_json::Map::new(), + }); + StepResult::ok("finished the pipeline without continuing") + } + Err(result) => result, + } +} + +/// Pipeline parameter values as JSON (from the trigger or a continuation), as YAML. +pub fn json_to_yaml( + values: &serde_json::Map, +) -> Result> { + values + .iter() + .map(|(name, value)| { + let value = match value { + serde_json::Value::Bool(b) => Yaml::Bool(*b), + serde_json::Value::String(s) => Yaml::String(s.clone()), + serde_json::Value::Number(n) => serde_yaml::to_value(n)?, + other => bail!( + "pipeline parameter `{name}` must be a string, number or boolean, got {other}" + ), + }; + Ok((name.clone(), value)) + }) + .collect() +} diff --git a/crates/mockci/src/circleci/job.rs b/crates/mockci/src/circleci/job.rs new file mode 100644 index 0000000..8fd9eb6 --- /dev/null +++ b/crates/mockci/src/circleci/job.rs @@ -0,0 +1,240 @@ +//! Runs one CircleCI job: its environment, its steps in order with `when:`, `BASH_ENV`, and +//! `circleci step halt`. + +use super::params::Expanded; +use super::paths::JobDirs; +use super::steps; +use crate::event::Event; +use crate::report::{JobReport, Outcome, StepReport}; +use crate::sim::Simulator; +use crate::yaml::{check_keys, optional_scalar, string_map}; +use anyhow::{Context, Result, bail}; +use serde_yaml::Value as Yaml; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// What `continuation/continue` or `continuation/finish` handed to CircleCI. +#[derive(Debug, Clone)] +pub struct Continued { + /// The config to continue with; `None` after `finish`. + pub config: Option, + pub parameters: serde_json::Map, +} + +pub struct JobRun<'a> { + pub sim: &'a Simulator, + pub event: &'a Event, + pub job_row: i64, + pub branch: String, + pub home: PathBuf, + pub working_directory: PathBuf, + /// mockci's own files for the job: step scripts, `BASH_ENV`. + pub temp: PathBuf, + /// The job's own `/tmp`, which steps reach through `TMPDIR`; cache paths and checksums + /// under `/tmp/` resolve here. + pub tmp: PathBuf, + /// Commands on `PATH` that stand in for CircleCI's own (`circleci step halt`). + pub bin: PathBuf, + pub env: BTreeMap, + /// What `{{ .Environment.X }}` sees: CircleCI's own variables and the project's, not the + /// job's or the image's `environment:`. + pub template_env: BTreeMap, + /// Set in a setup workflow: where a continuation is recorded. + pub continuation: Option<&'a mut Option>, + /// When the job started, on the host's clock. + pub started: std::time::SystemTime, +} + +pub struct StepResult { + pub outcome: Outcome, + pub log: String, +} + +impl StepResult { + pub fn ok(log: impl Into) -> Self { + Self { + outcome: Outcome::Success, + log: log.into(), + } + } + + pub fn failed(log: impl Into) -> Self { + Self { + outcome: Outcome::Failure, + log: log.into(), + } + } +} + +impl JobRun<'_> { + pub fn bash_env(&self) -> PathBuf { + self.temp.join("bash_env") + } + + fn halt_marker(&self) -> PathBuf { + self.temp.join("halted") + } + + /// Creates the job's directories, its `BASH_ENV` file and the fake `circleci` command. + pub fn prepare(&self) -> Result<()> { + for dir in [ + &self.home, + &self.working_directory, + &self.temp, + &self.tmp, + &self.bin, + ] { + std::fs::create_dir_all(dir)?; + } + std::fs::write(self.bash_env(), "")?; + let halt = self.halt_marker(); + let script = format!( + "#!/bin/sh\nif [ \"$1 $2\" = \"step halt\" ] && [ $# -eq 2 ]; then\n : > '{}'\n exit 0\nfi\necho \"mockci models only 'circleci step halt', not 'circleci $*'\" >&2\nexit 1\n", + halt.display() + ); + let path = self.bin.join("circleci"); + std::fs::write(&path, script)?; + let mut permissions = std::fs::metadata(&path)?.permissions(); + std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o755); + std::fs::set_permissions(&path, permissions)?; + Ok(()) + } + + /// Runs the steps and reports the job. A failed step fails the job; later steps run only + /// if their `when` allows it. + pub fn run(&mut self, name: &str, steps: &[Expanded]) -> Result { + self.prepare()?; + let mut failed = false; + let mut reports = Vec::new(); + for (index, step) in steps.iter().enumerate() { + let when = steps::when(step)?; + let runs = match when.as_str() { + "on_success" => !failed, + "always" => true, + "on_fail" => failed, + other => bail!("step `when: {other}` isn't on_success, on_fail or always"), + }; + if !runs { + continue; + } + let (step_name, result) = steps::execute(self, step, index).with_context(|| { + format!("in step {} (`{}`) of job `{name}`", index + 1, step.kind) + })?; + failed |= result.outcome == Outcome::Failure; + reports.push(StepReport { + name: step_name, + id: None, + outcome: result.outcome, + conclusion: result.outcome, + log: result.log, + }); + if self.halt_marker().exists() { + break; + } + } + Ok(JobReport { + id: name.to_string(), + result: if failed { + Outcome::Failure + } else { + Outcome::Success + }, + steps: reports, + outputs: BTreeMap::new(), + cache_events: self.sim.db.cache_events(self.job_row)?, + }) + } + + /// Runs a `run` step. + pub fn run_step(&self, body: &Yaml, index: usize) -> Result<(String, StepResult)> { + let (command, settings) = match body { + Yaml::String(command) => (command.clone(), serde_yaml::Mapping::new()), + Yaml::Mapping(map) => { + check_keys( + map, + &[ + "name", + "command", + "shell", + "environment", + "working_directory", + "when", + "no_output_timeout", + ], + "run step", + )?; + let command = + optional_scalar(map, "command")?.context("a `run` step needs `command`")?; + (command, map.clone()) + } + other => bail!("`run` takes a command or a mapping, found {other:?}"), + }; + let name = optional_scalar(&settings, "name")?.unwrap_or_else(|| { + command + .lines() + .find(|line| !line.trim().is_empty()) + .unwrap_or("") + .to_string() + }); + let shell = + optional_scalar(&settings, "shell")?.unwrap_or_else(|| "/bin/bash -eo pipefail".into()); + let cwd = match optional_scalar(&settings, "working_directory")? { + Some(dir) => self.dirs().resolve(&dir, "the step's working_directory")?, + None => self.working_directory.clone(), + }; + std::fs::create_dir_all(&cwd)?; + let script = self.temp.join(format!("step-{index}.sh")); + std::fs::write(&script, &command)?; + let mut argv: Vec = shell.split_whitespace().map(str::to_string).collect(); + argv.push(script.to_string_lossy().into_owned()); + let mut env = self.env.clone(); + env.extend(string_map(&settings, "environment")?); + let output = self + .command(&argv, &cwd, &env) + .output() + .with_context(|| format!("starting `{shell}`"))?; + let mut log = String::from_utf8_lossy(&output.stdout).into_owned(); + log.push_str(&String::from_utf8_lossy(&output.stderr)); + let result = if output.status.success() { + StepResult::ok(log) + } else { + StepResult::failed(format!( + "{log}Exited with code {}", + output.status.code().unwrap_or(-1) + )) + }; + Ok((name, result)) + } + + fn command(&self, argv: &[String], cwd: &Path, env: &BTreeMap) -> Command { + let mut path = Vec::new(); + if self.sim.bin_dir.is_dir() { + path.push(self.sim.bin_dir.to_string_lossy().into_owned()); + } + path.push(self.bin.to_string_lossy().into_owned()); + path.push(std::env::var("PATH").unwrap_or_default()); + let mut command = Command::new(&argv[0]); + command.args(&argv[1..]).current_dir(cwd).env_clear(); + for name in ["LANG", "USER"] { + if let Ok(value) = std::env::var(name) { + command.env(name, value); + } + } + command + .envs(env) + .env("HOME", &self.home) + .env("PATH", path.join(":")) + .env("TMPDIR", &self.tmp) + .env("BASH_ENV", self.bash_env()); + command + } + + pub fn dirs(&self) -> JobDirs<'_> { + JobDirs { + home: &self.home, + tmp: &self.tmp, + working_directory: &self.working_directory, + } + } +} diff --git a/crates/mockci/src/circleci/mod.rs b/crates/mockci/src/circleci/mod.rs new file mode 100644 index 0000000..1621524 --- /dev/null +++ b/crates/mockci/src/circleci/mod.rs @@ -0,0 +1,18 @@ +//! A CircleCI mode: runs a CircleCI 2.1 config (setup workflows and dynamic config included) +//! with the same simulator, repository, clock and record as the GitHub Actions mode. See +//! `internal_docs/MOCK_CI.md`. + +mod cache; +mod config; +mod continuation; +mod job; +mod order; +mod params; +mod paths; +mod pipeline; +mod report; +mod steps; +mod template; +mod workflow_config; + +pub use report::PipelineReport; diff --git a/crates/mockci/src/circleci/order.rs b/crates/mockci/src/circleci/order.rs new file mode 100644 index 0000000..b9278ce --- /dev/null +++ b/crates/mockci/src/circleci/order.rs @@ -0,0 +1,92 @@ +//! The order a workflow's jobs run in: those that pass their branch filters, in `requires` +//! order. + +use super::config::{Workflow, WorkflowJob}; +use anyhow::{Result, bail}; +use std::collections::{BTreeMap, BTreeSet}; + +/// The workflow's jobs that pass their branch filters, in `requires` order (alphabetical +/// among jobs ready at the same time). A required job the filters leave out is ignored, as +/// CircleCI ignores it, unless the filters leave out every job a job requires: then that job +/// doesn't run either. +pub fn order<'a>(workflow: &'a Workflow, branch: &str) -> Result> { + let mut by_name = BTreeMap::new(); + for entry in &workflow.jobs { + if by_name.insert(entry.name.as_str(), entry).is_some() { + bail!("two jobs are named `{}`: give one a `name`", entry.name); + } + } + let mut included = BTreeMap::new(); + for (name, entry) in &by_name { + if passes(entry, branch)? { + included.insert(*name, *entry); + } + } + // A job all of whose requirements the filters leave out doesn't run either, and neither + // do the jobs that then lose all of theirs. + loop { + let orphaned: Vec<&str> = included + .iter() + .filter(|(_, entry)| { + !entry.requires.is_empty() + && entry + .requires + .iter() + .all(|need| !included.contains_key(need.job.as_str())) + }) + .map(|(name, _)| *name) + .collect(); + if orphaned.is_empty() { + break; + } + for name in orphaned { + included.remove(name); + } + } + for entry in by_name.values() { + for need in &entry.requires { + if !by_name.contains_key(need.job.as_str()) { + bail!( + "`{}` requires `{}`, which isn't in the workflow", + entry.name, + need.job + ); + } + } + } + let mut done = BTreeSet::new(); + let mut ordered = Vec::new(); + while ordered.len() < included.len() { + let ready: Vec<_> = included + .values() + .filter(|e| { + !done.contains(e.name.as_str()) + && e.requires.iter().all(|r| { + done.contains(r.job.as_str()) || !included.contains_key(r.job.as_str()) + }) + }) + .copied() + .collect(); + if ready.is_empty() { + bail!("the jobs' `requires` form a cycle"); + } + for entry in ready { + done.insert(entry.name.as_str()); + ordered.push(entry); + } + } + Ok(ordered) +} + +fn passes(entry: &WorkflowJob, branch: &str) -> Result { + for pattern in entry.branches_only.iter().chain(&entry.branches_ignore) { + if pattern.starts_with('/') { + bail!( + "`{}`: mockci doesn't model regular expressions in branch filters (`{pattern}`)", + entry.name + ); + } + } + let only = entry.branches_only.is_empty() || entry.branches_only.iter().any(|b| b == branch); + Ok(only && !entry.branches_ignore.iter().any(|b| b == branch)) +} diff --git a/crates/mockci/src/circleci/params.rs b/crates/mockci/src/circleci/params.rs new file mode 100644 index 0000000..3e05a84 --- /dev/null +++ b/crates/mockci/src/circleci/params.rs @@ -0,0 +1,204 @@ +//! `<< ... >>` substitution and command expansion: what CircleCI does to a config before any +//! step runs. A job's steps come out as a flat list of built-in steps. + +use super::config::{CONTINUATION_ORB, Config, Parameter}; +use crate::yaml::scalar; +use anyhow::{Context, Result, bail}; +use serde_yaml::{Mapping, Value as Yaml}; +use std::collections::BTreeMap; + +/// Values `<< name >>` can refer to: `pipeline.parameters.x`, `pipeline.git.branch`, +/// `parameters.x` inside a command, and so on. +pub type Values = BTreeMap; + +/// Replaces every `<< name >>` in `text`. A name with no value is an error, as in CircleCI. +pub fn substitute(text: &str, values: &Values) -> Result { + let mut out = String::new(); + let mut rest = text; + while let Some(start) = rest.find("<<") { + out.push_str(&rest[..start]); + let after = &rest[start + 2..]; + let end = after + .find(">>") + .with_context(|| format!("unclosed `<<` in `{text}`"))?; + let name = after[..end].trim(); + let value = values.get(name).with_context(|| { + format!( + "`<< {name} >>` has no value here (known: {})", + values.keys().cloned().collect::>().join(", ") + ) + })?; + out.push_str(value); + rest = &after[end + 2..]; + } + out.push_str(rest); + Ok(out) +} + +/// `substitute` over every string in a YAML value, keys included. +pub fn substitute_yaml(value: &Yaml, values: &Values) -> Result { + Ok(match value { + Yaml::String(text) => Yaml::String(substitute(text, values)?), + Yaml::Sequence(items) => Yaml::Sequence( + items + .iter() + .map(|item| substitute_yaml(item, values)) + .collect::>()?, + ), + Yaml::Mapping(map) => Yaml::Mapping( + map.iter() + .map(|(k, v)| Ok((substitute_yaml(k, values)?, substitute_yaml(v, values)?))) + .collect::>()?, + ), + other => other.clone(), + }) +} + +/// The value a parameter takes: the one given, else its default. Checks the type and enum. +pub fn resolve( + declared: &BTreeMap, + given: &BTreeMap, + what: &str, +) -> Result> { + for name in given.keys() { + if !declared.contains_key(name) { + bail!("{what} has no parameter `{name}`"); + } + } + declared + .iter() + .map(|(name, parameter)| { + let value = given + .get(name) + .or(parameter.default.as_ref()) + .with_context(|| format!("{what} needs a value for parameter `{name}`"))?; + let ok = matches!( + (parameter.kind.as_str(), value), + ("boolean", Yaml::Bool(_)) + | ("integer", Yaml::Number(_)) + | ("string" | "enum", Yaml::String(_)) + | ("string", Yaml::Number(_) | Yaml::Bool(_)) + ); + if !ok { + bail!( + "{what}: parameter `{name}` is a {}, got {value:?}", + parameter.kind + ); + } + let text = scalar(value)?; + if parameter.kind == "enum" && !parameter.allowed.contains(&text) { + bail!("{what}: `{text}` isn't one of parameter `{name}`'s values"); + } + Ok((name.clone(), text)) + }) + .collect() +} + +/// A built-in step after expansion, still as YAML, with its kind. +#[derive(Debug, Clone)] +pub struct Expanded { + pub kind: String, + /// The step's settings (`{}` for a bare `checkout`, the command for a string `run`). + pub body: Yaml, +} + +const BUILT_IN: &[&str] = &["checkout", "run", "restore_cache", "save_cache"]; +const MAX_DEPTH: usize = 16; + +/// Expands `steps` (already substituted) into built-in steps, following commands. +pub fn expand(config: &Config, steps: &[Yaml], pipeline: &Values) -> Result> { + let mut out = Vec::new(); + expand_into(config, steps, pipeline, 0, &mut out)?; + Ok(out) +} + +fn expand_into( + config: &Config, + steps: &[Yaml], + pipeline: &Values, + depth: usize, + out: &mut Vec, +) -> Result<()> { + if depth > MAX_DEPTH { + bail!("commands nest more than {MAX_DEPTH} deep; is one calling itself?"); + } + for step in steps { + let (name, body) = match step { + Yaml::String(name) => (name.clone(), Yaml::Null), + Yaml::Mapping(single) if single.len() == 1 => { + let (name, body) = single.iter().next().unwrap(); + (scalar(name)?, body.clone()) + } + other => bail!("a step must be a name or a one-key mapping, found {other:?}"), + }; + if BUILT_IN.contains(&name.as_str()) + || name == "continuation/continue" + || name == "continuation/finish" + { + if name.starts_with("continuation/") && !config.has_continuation_orb { + bail!("`{name}` needs `orbs: {{ continuation: {CONTINUATION_ORB}@ }}`"); + } + out.push(Expanded { kind: name, body }); + continue; + } + if name == "when" || name == "unless" { + let body = body + .as_mapping() + .context("`when` needs `condition` and `steps`")?; + crate::yaml::check_keys(body, &["condition", "steps"], "conditional step")?; + let condition = match body.get("condition") { + Some(Yaml::Bool(b)) => *b, + Some(Yaml::String(s)) if s == "true" || s == "false" => s == "true", + other => bail!("mockci models only boolean `condition`s, found {other:?}"), + }; + if condition == (name == "when") { + let Some(Yaml::Sequence(inner)) = body.get("steps") else { + bail!("`{name}` needs `steps`"); + }; + expand_into(config, inner, pipeline, depth + 1, out)?; + } + continue; + } + let command = config.commands.get(&name).with_context(|| { + format!("step `{name}` isn't a built-in step mockci models or a command in the config") + })?; + let given: BTreeMap = match &body { + Yaml::Null => BTreeMap::new(), + Yaml::Mapping(map) => map + .iter() + .map(|(k, v)| Ok((scalar(k)?, v.clone()))) + .collect::>()?, + other => bail!("command `{name}` takes a mapping of parameters, found {other:?}"), + }; + let mut values = pipeline.clone(); + for (key, value) in resolve(&command.parameters, &given, &format!("command `{name}`"))? { + values.insert(format!("parameters.{key}"), value); + } + let inner = command + .steps + .iter() + .map(|step| substitute_yaml(step, &values)) + .collect::>>() + .with_context(|| format!("in command `{name}`"))?; + expand_into(config, &inner, pipeline, depth + 1, out)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn substitutes_with_and_without_spaces_and_rejects_unknown_names() { + let values = Values::from([("parameters.x".to_string(), "one".to_string())]); + assert_eq!( + substitute("a << parameters.x >> <>", &values).unwrap(), + "a one one" + ); + let error = substitute("<< parameters.y >>", &values) + .unwrap_err() + .to_string(); + assert!(error.contains("parameters.y"), "{error}"); + } +} diff --git a/crates/mockci/src/circleci/paths.rs b/crates/mockci/src/circleci/paths.rs new file mode 100644 index 0000000..29528f7 --- /dev/null +++ b/crates/mockci/src/circleci/paths.rs @@ -0,0 +1,131 @@ +//! Where the paths a job names resolve. Steps run on the host, so every path a config names +//! goes through here: `~/x` under the job's home, `/tmp/x` in the job's own `/tmp`, `x` under +//! its working directory. Any other absolute path, and any `..`, could reach the host, so +//! they're errors, and so is a path that goes through a symlink to outside the job. + +use anyhow::{Result, bail}; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Copy)] +pub struct JobDirs<'a> { + pub home: &'a Path, + pub tmp: &'a Path, + pub working_directory: &'a Path, +} + +impl JobDirs<'_> { + /// `path` as the job sees it. `what` names it in the error ("the cache path"). + pub fn resolve(&self, path: &str, what: &str) -> Result { + if path.split('/').any(|part| part == "..") { + bail!("mockci runs steps on the host, so {what} `{path}` can't use `..`"); + } + if path.contains("//") { + bail!("mockci runs steps on the host, so {what} `{path}` can't use `//`"); + } + let (base, rest) = if path == "~" { + (self.home, "") + } else if let Some(rest) = path.strip_prefix("~/") { + (self.home, rest) + } else if let Some(rest) = path.strip_prefix("/tmp/") { + (self.tmp, rest) + } else if path.starts_with('/') || path.starts_with('~') { + bail!( + "mockci runs steps on the host, so it can't use {what} `{path}`: use a path under `~`, `/tmp` or the working directory" + ); + } else { + (self.working_directory, path) + }; + let resolved = base.join(rest); + // `rest` is relative and has no `..`, but check anyway: nothing may land outside `base`. + if rest.starts_with('/') || !resolved.starts_with(base) || !really_inside(&resolved, base) { + bail!("mockci runs steps on the host, so {what} `{path}` must stay inside the job"); + } + Ok(resolved) + } + + /// How a job names `path`: `~/x` or `/tmp/x`. CircleCI restores a cache to the path it was + /// saved from, so the next job finds it at the same name. + pub fn logical(&self, path: &Path) -> Result { + if let Ok(rest) = path.strip_prefix(self.tmp) { + return Ok(format!("/tmp/{}", rest.display())); + } + if let Ok(rest) = path.strip_prefix(self.home) { + return Ok(format!("~/{}", rest.display())); + } + bail!( + "mockci caches only paths under `~` or `/tmp`, got {}", + path.display() + ) + } +} + +/// Whether `path` stays inside `base` once symlinks are followed: the deepest part of it that +/// exists, resolved, must be inside `base`, resolved. A step can `ln -s` a host directory into +/// the job, and a path through that link would reach the host. +fn really_inside(path: &Path, base: &Path) -> bool { + let Ok(real_base) = base.canonicalize() else { + return true; // nothing exists yet, so nothing can be a link + }; + let Some(existing) = path + .ancestors() + .take_while(|ancestor| ancestor.starts_with(base)) + .find(|ancestor| ancestor.symlink_metadata().is_ok()) + else { + return true; + }; + existing + .canonicalize() + .is_ok_and(|real| real.starts_with(&real_base)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn paths_resolve_inside_the_job_and_nowhere_else() { + let (home, tmp, work) = ( + Path::new("/j/home"), + Path::new("/j/tmp"), + Path::new("/j/home/project"), + ); + let dirs = JobDirs { + home, + tmp, + working_directory: work, + }; + assert_eq!(dirs.resolve("~/a", "x").unwrap(), home.join("a")); + assert_eq!(dirs.resolve("/tmp/a", "x").unwrap(), tmp.join("a")); + assert_eq!(dirs.resolve("a/b", "x").unwrap(), work.join("a/b")); + for bad in [ + "/etc/passwd", + "../a", + "a/../../b", + "~/../a", + "/tmp/../a", + "~other/a", + ] { + assert!(dirs.resolve(bad, "x").is_err(), "{bad}"); + } + } + + #[test] + fn a_path_through_a_symlink_to_outside_the_job_is_refused() { + let job = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + let home = job.path().join("home"); + std::fs::create_dir_all(home.join("inside")).unwrap(); + std::os::unix::fs::symlink(outside.path(), home.join("link")).unwrap(); + std::os::unix::fs::symlink(home.join("inside"), home.join("local")).unwrap(); + let dirs = JobDirs { + home: &home, + tmp: &job.path().join("tmp"), + working_directory: &home, + }; + for bad in ["~/link", "~/link/a/b", "link/a"] { + assert!(dirs.resolve(bad, "x").is_err(), "{bad}"); + } + assert!(dirs.resolve("~/local/a", "x").is_ok()); + assert!(dirs.resolve("~/not/yet/made", "x").is_ok()); + } +} diff --git a/crates/mockci/src/circleci/pipeline.rs b/crates/mockci/src/circleci/pipeline.rs new file mode 100644 index 0000000..d7dff07 --- /dev/null +++ b/crates/mockci/src/circleci/pipeline.rs @@ -0,0 +1,292 @@ +//! A CircleCI pipeline: the config at the event's commit, its setup workflow and the config it +//! continues with, or its own workflows; each workflow's jobs in `requires` order. + +use super::config::{self, Config, Workflow}; +use super::continuation::json_to_yaml; +use super::job::{Continued, JobRun}; +use super::order::order; +use super::params::{self, Values}; +use super::paths::JobDirs; +use super::report::PipelineReport; +use crate::event::Event; +use crate::report::{JobReport, Outcome, RunReport}; +use crate::sim::Simulator; +use anyhow::{Context, Result, bail}; +use serde_yaml::Value as Yaml; +use std::collections::BTreeMap; + +pub const CONFIG_PATH: &str = ".circleci/config.yml"; + +/// The branch CircleCI builds: a pull request builds its head branch's commit, so pass the +/// head commit as the event's `sha`. +fn branch(event: &Event) -> String { + match event { + Event::Push { branch, .. } => branch.clone(), + Event::PullRequest { head, .. } => head.clone(), + } +} + +impl Simulator { + /// Runs `.circleci/config.yml` as it is at the event's commit, as CircleCI would. + pub fn run_circleci(&mut self, event: &Event) -> Result { + self.run_circleci_with(event, serde_json::Map::new()) + } + + /// `run_circleci`, triggered with these pipeline parameters. + pub fn run_circleci_with( + &mut self, + event: &Event, + parameters: serde_json::Map, + ) -> Result { + let text = crate::git::run( + &["show", &format!("{}:{CONFIG_PATH}", event.sha())], + &self.repo, + ) + .with_context(|| format!("reading {CONFIG_PATH} at {}", event.sha()))?; + let config = config::parse(&text).with_context(|| format!("in {CONFIG_PATH}"))?; + let (values, resolved) = pipeline_values(&config, ¶meters, event)?; + let mut report = PipelineReport { + setup: None, + workflows: BTreeMap::new(), + parameters: resolved, + finished: false, + }; + if !config.setup { + report.workflows = self.run_workflows(&config, &values, event, None)?; + return Ok(report); + } + let mut continued = None; + let setup = self.run_workflows(&config, &values, event, Some(&mut continued))?; + report.setup = setup.into_values().next(); + report.parameters = BTreeMap::new(); + match continued { + None => {} + Some(Continued { config: None, .. }) => report.finished = true, + Some(Continued { + config: Some(text), + parameters, + }) => { + let config = config::parse(&text).context("in the continued config")?; + let (values, resolved) = pipeline_values(&config, ¶meters, event)?; + report.parameters = resolved; + report.workflows = self.run_workflows(&config, &values, event, None)?; + } + } + Ok(report) + } + + fn run_workflows( + &mut self, + config: &Config, + values: &Values, + event: &Event, + mut continuation: Option<&mut Option>, + ) -> Result> { + let mut runs = BTreeMap::new(); + for (name, workflow) in &config.workflows { + let when = match &workflow.when { + None => true, + Some(when) => match params::substitute_yaml(when, values)? { + Yaml::Bool(b) => b, + Yaml::String(s) if s == "true" || s == "false" => s == "true", + other => bail!( + "workflow `{name}`: mockci models only a boolean `when`, found {other:?}" + ), + }, + }; + if when { + let run = self + .run_workflow( + config, + name, + workflow, + values, + event, + continuation.as_deref_mut(), + ) + .with_context(|| format!("in workflow `{name}`"))?; + runs.insert(name.clone(), run); + } + } + Ok(runs) + } + + fn run_workflow( + &mut self, + config: &Config, + name: &str, + workflow: &Workflow, + values: &Values, + event: &Event, + mut continuation: Option<&mut Option>, + ) -> Result { + let branch = branch(event); + let run_id = + self.db + .start_run(name, event.name(), &event.git_ref(), event.sha(), self.now)?; + let mut reports: BTreeMap = BTreeMap::new(); + for entry in order(workflow, &branch)? { + let job_row = self.db.start_job(run_id, &entry.name)?; + // A required job the branch filters left out has no report and is ignored. + let blocked = entry.requires.iter().any(|need| { + reports + .get(&need.job) + .is_some_and(|report| !need.statuses.iter().any(|s| s == status(report))) + }); + let report = if blocked { + JobReport { + id: entry.name.clone(), + result: Outcome::Skipped, + steps: Vec::new(), + outputs: BTreeMap::new(), + cache_events: Vec::new(), + } + } else { + let job = &config.jobs[&entry.job]; + let steps = params::substitute_yaml(&Yaml::Sequence(job.steps.clone()), values)?; + let Yaml::Sequence(steps) = steps else { + unreachable!() + }; + let steps = params::expand(config, &steps, values) + .with_context(|| format!("in job `{}`", entry.job))?; + let dir = self.runs_dir.join(run_id.to_string()).join(&entry.name); + let home = dir.join("home"); + let working = job.working_directory.as_deref().unwrap_or("~/project"); + if !working.starts_with('~') { + bail!( + "job `{}`: mockci runs steps on the host, so `working_directory` must start with `~`, got `{working}`", + entry.job + ); + } + let tmp = dir.join("tmp"); + let dirs = JobDirs { + home: &home, + tmp: &tmp, + working_directory: &home, + }; + let working = dirs.resolve(working, "the job's working_directory")?; + let mut env = self.circleci_env(event, &branch, &entry.name, run_id, job_row); + env.insert( + "CIRCLE_WORKING_DIRECTORY".into(), + working.to_string_lossy().into_owned(), + ); + if continuation.is_some() { + env.insert( + "CIRCLE_CONTINUATION_KEY".into(), + format!("mockci-continuation-{run_id}"), + ); + } + let template_env = env.clone(); + for (key, value) in &job.environment { + env.insert(key.clone(), params::substitute(value, values)?); + } + let mut run = JobRun { + sim: self, + event, + job_row, + branch: branch.clone(), + home, + working_directory: working, + temp: dir.join("temp"), + tmp, + bin: dir.join("bin"), + env, + template_env, + continuation: continuation.as_deref_mut(), + started: std::time::SystemTime::now(), + }; + run.run(&entry.name, &steps)? + }; + for (position, step) in report.steps.iter().enumerate() { + let (outcome, conclusion) = (step.outcome.as_str(), step.conclusion.as_str()); + self.db.record_step( + job_row, position, &step.name, outcome, conclusion, &step.log, + )?; + } + self.db.finish_job(job_row, report.result.as_str())?; + reports.insert(entry.name.clone(), report); + } + let conclusion = if reports.values().any(|job| job.result == Outcome::Failure) { + Outcome::Failure + } else { + Outcome::Success + }; + self.db.finish_run(run_id, conclusion.as_str())?; + Ok(RunReport { + run_id, + triggered: true, + conclusion, + jobs: reports, + }) + } + + /// The variables CircleCI sets in every job, then the project's environment variables + /// (the simulator's secrets and runner environment). + fn circleci_env( + &self, + event: &Event, + branch: &str, + job: &str, + run_id: i64, + job_row: i64, + ) -> BTreeMap { + let repo_name = self + .repo + .file_name() + .map_or("repo".into(), |n| n.to_string_lossy().into_owned()); + let mut env = BTreeMap::from([ + ("CI".to_string(), "true".to_string()), + ("CIRCLECI".into(), "true".into()), + ("CIRCLE_BRANCH".into(), branch.to_string()), + ("CIRCLE_SHA1".into(), event.sha().to_string()), + ("CIRCLE_JOB".into(), job.to_string()), + ("CIRCLE_BUILD_NUM".into(), job_row.to_string()), + ( + "CIRCLE_WORKFLOW_ID".into(), + format!("mockci-workflow-{run_id}"), + ), + ( + "CIRCLE_REPOSITORY_URL".into(), + format!("file://{}", self.repo.display()), + ), + ("CIRCLE_PROJECT_USERNAME".into(), "mockci".into()), + ("CIRCLE_PROJECT_REPONAME".into(), repo_name.clone()), + ]); + if let Event::PullRequest { number, .. } = event { + env.insert("CIRCLE_PR_NUMBER".into(), number.to_string()); + env.insert( + "CIRCLE_PULL_REQUEST".into(), + format!("https://github.com/mockci/{repo_name}/pull/{number}"), + ); + } + env.extend(self.secrets.clone()); + env.extend(self.runner_env.clone()); + env + } +} + +/// `<< pipeline.* >>` values for a config, from the parameters it was given. +fn pipeline_values( + config: &Config, + given: &serde_json::Map, + event: &Event, +) -> Result<(Values, BTreeMap)> { + let resolved = params::resolve(&config.parameters, &json_to_yaml(given)?, "the pipeline")?; + let mut values = Values::from([ + ("pipeline.git.branch".to_string(), branch(event)), + ("pipeline.git.revision".to_string(), event.sha().to_string()), + ]); + for (name, value) in &resolved { + values.insert(format!("pipeline.parameters.{name}"), value.clone()); + } + Ok((values, resolved)) +} + +/// A finished job's status, as `requires` names it. A blocked job ends as `not_run`. +fn status(report: &JobReport) -> &'static str { + match report.result { + Outcome::Success => "success", + Outcome::Failure => "failed", + Outcome::Skipped => "not_run", + } +} diff --git a/crates/mockci/src/circleci/report.rs b/crates/mockci/src/circleci/report.rs new file mode 100644 index 0000000..c63b4d3 --- /dev/null +++ b/crates/mockci/src/circleci/report.rs @@ -0,0 +1,70 @@ +//! What a simulated CircleCI pipeline did. + +use crate::report::{JobReport, Outcome, RunReport}; +use std::collections::BTreeMap; +use std::fmt; + +#[derive(Debug, Clone)] +pub struct PipelineReport { + /// The setup workflow, when `.circleci/config.yml` has `setup: true`. + pub setup: Option, + /// The workflows that ran: the continued config's after a setup workflow, otherwise the + /// config's own. A workflow whose `when` is false isn't here. + pub workflows: BTreeMap, + /// The pipeline parameters those workflows saw. + pub parameters: BTreeMap, + /// True when the setup workflow called `continuation/finish` instead of continuing. + pub finished: bool, +} + +impl PipelineReport { + fn all_jobs(&self) -> impl Iterator { + self.setup + .iter() + .chain(self.workflows.values()) + .flat_map(|run| run.jobs.values()) + } + + /// The job named `name` in any workflow. Panics if none or several have that name. + pub fn job(&self, name: &str) -> &JobReport { + let found: Vec<_> = self.all_jobs().filter(|job| job.id == name).collect(); + match found.as_slice() { + [job] => job, + [] => panic!("the pipeline has no job `{name}`\n{self}"), + _ => panic!("several workflows have a job `{name}`\n{self}"), + } + } + + /// True when a job named `name` ran (it exists and wasn't blocked). + pub fn ran(&self, name: &str) -> bool { + self.all_jobs() + .any(|job| job.id == name && job.result != Outcome::Skipped) + } + + /// Failure if any job failed, otherwise success. + pub fn conclusion(&self) -> Outcome { + if self.all_jobs().any(|job| job.result == Outcome::Failure) { + Outcome::Failure + } else { + Outcome::Success + } + } +} + +impl fmt::Display for PipelineReport { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if let Some(setup) = &self.setup { + write!(f, "setup workflow: {setup}")?; + } + if self.finished { + writeln!(f, "setup finished the pipeline without continuing")?; + } + if !self.parameters.is_empty() { + writeln!(f, "parameters: {:?}", self.parameters)?; + } + for (name, run) in &self.workflows { + write!(f, "workflow {name}: {run}")?; + } + Ok(()) + } +} diff --git a/crates/mockci/src/circleci/steps.rs b/crates/mockci/src/circleci/steps.rs new file mode 100644 index 0000000..ec6bf24 --- /dev/null +++ b/crates/mockci/src/circleci/steps.rs @@ -0,0 +1,142 @@ +//! The built-in steps: `checkout`, `run`, `restore_cache` and `save_cache`, and the +//! continuation orb's commands (`continuation.rs`). + +use super::cache::{self, Cache}; +use super::continuation; +use super::job::{JobRun, StepResult}; +use super::params::Expanded; +use super::template; +use crate::cache::copy_tree; +use crate::yaml::{check_keys, optional_scalar, scalar}; +use anyhow::{Context, Result, bail}; +use serde_yaml::{Mapping, Value as Yaml}; + +/// A step's `when:` (`on_success` unless it says otherwise). +pub fn when(step: &Expanded) -> Result { + if step.kind == "continuation/continue" { + return continuation::when(&step.body); + } + Ok(match &step.body { + Yaml::Mapping(map) => optional_scalar(map, "when")?, + _ => None, + } + .unwrap_or_else(|| "on_success".into())) +} + +pub fn execute(job: &mut JobRun, step: &Expanded, index: usize) -> Result<(String, StepResult)> { + match step.kind.as_str() { + "run" => job.run_step(&step.body, index), + "checkout" => checkout(job, &step.body), + "restore_cache" => restore_cache(job, &step.body), + "save_cache" => save_cache(job, &step.body), + "continuation/continue" => continuation::run_continue(job, &step.body), + "continuation/finish" => continuation::run_finish(job, &step.body), + other => bail!("mockci doesn't model step `{other}`"), + } +} + +fn mapping(body: &Yaml, what: &str) -> Result { + match body { + Yaml::Null => Ok(Mapping::new()), + Yaml::Mapping(map) => Ok(map.clone()), + other => bail!("`{what}` takes a mapping, found {other:?}"), + } +} + +fn checkout(job: &JobRun, body: &Yaml) -> Result<(String, StepResult)> { + let settings = mapping(body, "checkout")?; + check_keys(&settings, &["path", "name"], "checkout step")?; + let target = match optional_scalar(&settings, "path")? { + Some(path) => job.dirs().resolve(&path, "the checkout path")?, + None => job.working_directory.clone(), + }; + if target.is_dir() && std::fs::read_dir(&target)?.next().is_some() { + return Ok(( + "Checkout code".into(), + StepResult::failed(format!( + "Directory ({}) you are trying to checkout to is not empty and not a git repository", + target.display() + )), + )); + } + let repo = job.sim.repo.to_string_lossy().into_owned(); + let target_text = target.to_string_lossy().into_owned(); + crate::git::run(&["clone", "--quiet", &repo, &target_text], &job.sim.repo)?; + crate::git::run( + &["checkout", "--quiet", "--detach", job.event.sha()], + &target, + )?; + for (destination, source) in &job.sim.files { + copy_tree(source, &target.join(destination), &target)?; + } + let name = optional_scalar(&settings, "name")?.unwrap_or_else(|| "Checkout code".into()); + Ok(( + name, + StepResult::ok(format!("checked out {}", job.event.sha())), + )) +} + +fn template_context<'a>(job: &'a JobRun) -> template::Context<'a> { + template::Context { + branch: &job.branch, + revision: job.event.sha(), + env: &job.template_env, + dirs: job.dirs(), + epoch: job.sim.now, + } +} + +fn cache<'a>(job: &'a JobRun) -> Cache<'a> { + Cache { + db: &job.sim.db, + blobs: &job.sim.cache_dir, + job_row: job.job_row, + now: job.sim.now, + dirs: job.dirs(), + started: job.started, + } +} + +fn restore_cache(job: &JobRun, body: &Yaml) -> Result<(String, StepResult)> { + let settings = mapping(body, "restore_cache")?; + check_keys( + &settings, + &["key", "keys", "name", "when"], + "restore_cache step", + )?; + let keys = match (settings.get("key"), settings.get("keys")) { + (Some(key), None) => vec![scalar(key)?], + (None, Some(Yaml::Sequence(keys))) if !keys.is_empty() => { + keys.iter().map(scalar).collect::>()? + } + _ => bail!("`restore_cache` needs `key` or a non-empty `keys` list, not both"), + }; + let name = optional_scalar(&settings, "name")?.unwrap_or_else(|| "Restoring cache".into()); + let keys = cache::render_keys(&keys, &template_context(job))?; + let log = match cache(job).restore(&keys)? { + Some(key) => format!("Found a cache at {key}"), + None => format!("No cache is found for keys: {}", keys.join(" ")), + }; + Ok((name, StepResult::ok(log))) +} + +fn save_cache(job: &JobRun, body: &Yaml) -> Result<(String, StepResult)> { + let settings = mapping(body, "save_cache")?; + check_keys( + &settings, + &["key", "paths", "name", "when"], + "save_cache step", + )?; + let key = optional_scalar(&settings, "key")?.context("`save_cache` needs `key`")?; + let Some(Yaml::Sequence(paths)) = settings.get("paths") else { + bail!("`save_cache` needs a `paths` list"); + }; + let paths = paths + .iter() + .map(|path| cache::resolve_path(&scalar(path)?, &job.dirs())) + .collect::>>()?; + let name = optional_scalar(&settings, "name")?.unwrap_or_else(|| "Saving cache".into()); + let key = template::render(&key, &template_context(job)) + .with_context(|| format!("in cache key `{key}`"))?; + Ok((name, StepResult::ok(cache(job).save(&key, &paths)?))) +} diff --git a/crates/mockci/src/circleci/template.rs b/crates/mockci/src/circleci/template.rs new file mode 100644 index 0000000..34b043c --- /dev/null +++ b/crates/mockci/src/circleci/template.rs @@ -0,0 +1,55 @@ +//! Cache key templates: `{{ checksum "file" }}`, `{{ .Branch }}`, `{{ .Revision }}`, +//! `{{ .Environment.NAME }}` and `{{ epoch }}`. Anything else is an error. + +use super::paths::JobDirs; +use anyhow::{Context as _, Result, bail}; +use base64::Engine; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; + +pub struct Context<'a> { + pub branch: &'a str, + pub revision: &'a str, + /// CircleCI's own variables and the project's: what `.Environment` sees. + pub env: &'a BTreeMap, + pub dirs: JobDirs<'a>, + /// Seconds since the epoch, for `{{ epoch }}`. + pub epoch: i64, +} + +pub fn render(template: &str, ctx: &Context) -> Result { + let mut out = String::new(); + let mut rest = template; + while let Some(start) = rest.find("{{") { + out.push_str(&rest[..start]); + let after = &rest[start + 2..]; + let end = after.find("}}").context("unclosed `{{`")?; + out.push_str(&expand(after[..end].trim(), ctx)?); + rest = &after[end + 2..]; + } + out.push_str(rest); + Ok(out) +} + +fn expand(expression: &str, ctx: &Context) -> Result { + if let Some(argument) = expression.strip_prefix("checksum ") { + let file = argument.trim().trim_matches('"'); + let path = ctx.dirs.resolve(file, "the checksum file")?; + let bytes = std::fs::read(&path) + .with_context(|| format!("mockci can't read `{file}` for `{{{{ checksum }}}}`"))?; + return Ok(base64::engine::general_purpose::STANDARD.encode(Sha256::digest(&bytes))); + } + if let Some(name) = expression.strip_prefix(".Environment.") { + return ctx.env.get(name).cloned().with_context(|| { + format!( + "`{{{{ .Environment.{name} }}}}`: CircleCI renders only its own variables and the project's here (not a job's or an image's `environment:`), and `{name}` isn't one, so the key would hold ``" + ) + }); + } + Ok(match expression { + ".Branch" => ctx.branch.to_string(), + ".Revision" => ctx.revision.to_string(), + "epoch" => ctx.epoch.to_string(), + other => bail!("mockci doesn't model `{{{{ {other} }}}}` in cache keys"), + }) +} diff --git a/crates/mockci/src/circleci/workflow_config.rs b/crates/mockci/src/circleci/workflow_config.rs new file mode 100644 index 0000000..132b220 --- /dev/null +++ b/crates/mockci/src/circleci/workflow_config.rs @@ -0,0 +1,104 @@ +//! A workflow in a CircleCI config: its `when` and its jobs with `requires`, `name` and branch +//! filters. + +use super::config::{Requirement, Workflow, WorkflowJob, as_mapping}; +use crate::yaml::{check_keys, optional_scalar, scalar}; +use anyhow::{Context, Result, bail}; +use serde_yaml::Value as Yaml; + +pub fn workflow(body: &Yaml) -> Result { + let body = as_mapping(body, "a workflow")?; + check_keys(body, &["jobs", "when"], "workflow")?; + let Some(Yaml::Sequence(entries)) = body.get("jobs") else { + bail!("`jobs` must be a list"); + }; + let jobs = entries + .iter() + .map(|entry| match entry { + Yaml::String(job) => Ok(WorkflowJob { + job: job.clone(), + name: job.clone(), + requires: Vec::new(), + branches_only: Vec::new(), + branches_ignore: Vec::new(), + }), + Yaml::Mapping(single) if single.len() == 1 => { + let (job, settings) = single.iter().next().unwrap(); + let job = scalar(job)?; + workflow_job(job.clone(), settings).with_context(|| format!("in `{job}`")) + } + other => bail!("a workflow job must be a name or a one-key mapping, found {other:?}"), + }) + .collect::>()?; + Ok(Workflow { + when: body.get("when").cloned(), + jobs, + }) +} + +fn workflow_job(job: String, settings: &Yaml) -> Result { + let settings = as_mapping(settings, "a workflow job's settings")?; + check_keys(settings, &["requires", "name", "filters"], "workflow job")?; + let requires = match settings.get("requires") { + None => Vec::new(), + Some(Yaml::Sequence(items)) => items.iter().map(requirement).collect::>()?, + Some(other) => bail!("`requires` must be a list, found {other:?}"), + }; + let (mut only, mut ignore) = (Vec::new(), Vec::new()); + if let Some(filters) = settings.get("filters") { + let filters = as_mapping(filters, "`filters`")?; + check_keys(filters, &["branches"], "filters")?; + if let Some(branches) = filters.get("branches") { + let branches = as_mapping(branches, "`filters.branches`")?; + check_keys(branches, &["only", "ignore"], "branch filter")?; + only = string_list(branches.get("only"))?; + ignore = string_list(branches.get("ignore"))?; + } + } + Ok(WorkflowJob { + name: optional_scalar(settings, "name")?.unwrap_or_else(|| job.clone()), + job, + requires, + branches_only: only, + branches_ignore: ignore, + }) +} + +fn string_list(value: Option<&Yaml>) -> Result> { + match value { + None => Ok(Vec::new()), + Some(Yaml::Sequence(items)) => items.iter().map(scalar).collect(), + Some(single) => Ok(vec![scalar(single)?]), + } +} + +/// The statuses a requirement can name. `terminal` stands for all of them. +pub const STATUSES: &[&str] = &["success", "failed", "canceled", "unauthorized", "not_run"]; + +/// `build`, `build: failed`, `build: [success, failed]` or `build: terminal`. +fn requirement(item: &Yaml) -> Result { + let (job, statuses) = match item { + Yaml::Mapping(single) if single.len() == 1 => { + let (job, statuses) = single.iter().next().unwrap(); + (scalar(job)?, string_list(Some(statuses))?) + } + other => (scalar(other)?, vec!["success".to_string()]), + }; + let mut expanded = Vec::new(); + for status in statuses { + if status == "terminal" { + expanded.extend(STATUSES.iter().map(|s| s.to_string())); + } else if STATUSES.contains(&status.as_str()) { + expanded.push(status); + } else { + bail!( + "`requires` status `{status}` for `{job}` isn't one of {}, or terminal", + STATUSES.join(", ") + ); + } + } + Ok(Requirement { + job, + statuses: expanded, + }) +} diff --git a/crates/mockci/src/db.rs b/crates/mockci/src/db.rs index a91025d..115e7ae 100644 --- a/crates/mockci/src/db.rs +++ b/crates/mockci/src/db.rs @@ -149,6 +149,16 @@ impl Db { )?) } + /// Marks entries in `scope` saved `max_age` seconds ago or earlier as evicted, as CircleCI + /// does 15 days after a save. + pub fn expire_cache_entries(&self, scope: &str, now: i64, max_age: i64) -> Result { + Ok(self.conn.execute( + "UPDATE cache_entries SET evicted_at = ?1 + WHERE evicted_at IS NULL AND scope = ?2 AND created_at <= ?3", + params![now, scope, now - max_age], + )?) + } + pub fn find_exact_cache_entry( &self, key: &str, diff --git a/crates/mockci/src/lib.rs b/crates/mockci/src/lib.rs index 6b4cc30..7de07e3 100644 --- a/crates/mockci/src/lib.rs +++ b/crates/mockci/src/lib.rs @@ -8,6 +8,7 @@ mod actions; mod cache; +mod circleci; mod db; mod event; pub mod expr; @@ -19,6 +20,7 @@ mod sim; pub mod workflow; mod yaml; +pub use circleci::PipelineReport; pub use db::CacheEvent; pub use event::Event; pub use report::{JobReport, Outcome, RunReport, StepReport}; diff --git a/crates/mockci/src/sim.rs b/crates/mockci/src/sim.rs index f33da6d..346b808 100644 --- a/crates/mockci/src/sim.rs +++ b/crates/mockci/src/sim.rs @@ -18,7 +18,7 @@ pub struct Simulator { pub(crate) db: Db, pub(crate) cache_dir: PathBuf, pub(crate) artifacts_dir: PathBuf, - runs_dir: PathBuf, + pub(crate) runs_dir: PathBuf, /// Seconds since the simulation started. pub(crate) now: i64, pub(crate) default_branch: String, diff --git a/internal_docs/DIRECTION.md b/internal_docs/DIRECTION.md index 23776e8..fefc646 100644 --- a/internal_docs/DIRECTION.md +++ b/internal_docs/DIRECTION.md @@ -596,7 +596,7 @@ Small pull requests, each with its tests and STATUS.md: An in-house, test-only CI simulator, so bugs like the constant skip-cache key are caught before users hit them: - Models the provider behaviour cigen relies on: `${{ }}` expressions, `needs`, `if`, job outputs, cache scoping by - branch, exact and prefix cache hits, eviction, fork permissions, and later CircleCI's setup workflows and `$BASH_ENV`. + branch, exact and prefix cache hits, eviction, fork permissions, and CircleCI's setup workflows and `$BASH_ENV` (built: MOCK_CI.md, "CircleCI mode"). - Runs generated steps as real shell commands and records pipelines, workflows, jobs, cache hits and skips in SQLite. - Scenario tests assert behaviour across runs ("change only a Rust file: clippy must run"; "a fork writes no pass record"; "after a merge, `main` reuses the pull request's results for the same tree"). diff --git a/internal_docs/MOCK_CI.md b/internal_docs/MOCK_CI.md index 8d89c89..6a488c9 100644 --- a/internal_docs/MOCK_CI.md +++ b/internal_docs/MOCK_CI.md @@ -1,7 +1,7 @@ # mockci -`crates/mockci` (package `cigen-mockci`, not published) is a small GitHub Actions simulator for testing the workflows -cigen generates. It exists because golden files only prove the output didn't change: they can't tell you that a +`crates/mockci` (package `cigen-mockci`, not published) is a small GitHub Actions and CircleCI simulator for testing +the config cigen generates. It exists because golden files only prove the output didn't change: they can't tell you that a skip-cache key is a constant string, or that a job skips after its inputs changed. mockci runs the output and shows what GitHub would do with it. @@ -20,10 +20,12 @@ what GitHub would do with it. - **The cache service** (`src/cache.rs`), as `actions/cache` sees it: lookups search the run's ref, then a pull request's base branch, then the default branch, each by exact key, then prefix; `cache-hit` is `'true'` only for an exact match; entries are immutable; saves happen in a post step only when the job succeeded and the key wasn't an - exact hit, and go to the run's own ref; entries unused for 7 days are evicted. `actions/cache/restore` and - `actions/cache/save` work too. + exact hit, and go to the run's own ref; entries unused for 7 days are evicted. Symlinks are cached as symlinks, and a + restore never writes through a symlink to outside the workspace. `actions/cache/restore` and `actions/cache/save` work + too. - **Artifacts:** `actions/upload-artifact` (a file as itself, a directory's contents, hidden files under a directory - left out unless `include-hidden-files: true`) and `actions/download-artifact` by name, within a run. + left out unless `include-hidden-files: true`, symlinks followed and broken ones left out, as its search does) and + `actions/download-artifact` by name, within a run. - **Tools in the image:** `Simulator::provide_file` places a file in the workspace after every checkout, the way a prebuilt runner image would provide a tool. `Simulator::provide_command` puts a command first on every step's `PATH` (a fake `rustup` that records how it was called), the way a runner image provides its tools. `Simulator::runner_env` @@ -47,6 +49,56 @@ mockci fails instead of guessing, so a test can't pass because something was sil - running a matrix job (they parse, so `workflow::load` can check any workflow), `paths` trigger filters, negated branch patterns and glob cache paths, which it doesn't model yet. +## CircleCI mode + +`Simulator::run_circleci(&event)` (or `run_circleci_with(&event, parameters)` for pipeline parameters) runs +`.circleci/config.yml` at the event's commit and returns a `PipelineReport`: the setup workflow, the workflows that ran +and the parameters they saw. It shares the simulator's repository, clock, record and project environment (`secret` and +`runner_env` become project environment variables). The code is in `src/circleci/`. + +- **Setup workflows and dynamic config:** a `setup: true` config runs its one workflow with `CIRCLE_CONTINUATION_KEY` + set. mockci runs `continuation/continue` and `continuation/finish` natively, since the orb's own script posts to + CircleCI's API and writes to `/tmp` on the host. It models what the orb (version 1.0.0) checks: the continuation key, + `parameters` as JSON or as a path to a JSON file. It also models what the continue API refuses: a second + continuation, a setup config, and parameters the continued config doesn't declare or that have the wrong type. The + continued config then runs with those parameters, and a workflow whose `when` is false is left out. +- **Jobs and steps:** workflow `requires` order, with statuses (`build: failed`, `build: [success, failed]`, + `build: terminal`; plain `build` means `success`). A job whose requirements aren't met is blocked, reported as + skipped, and counts as `not_run` for the jobs that require it. A required job the branch filters leave out is ignored, + as on CircleCI, unless they leave out every job it requires: then it doesn't run either, and neither do the jobs that + lose all their requirements that way. Branch `only` and `ignore` filters take exact names. Steps: `checkout`, `run` + (`/bin/bash -eo pipefail` by default, a `BASH_ENV` file every step sources, `environment`, `working_directory`), step + `when` (`on_success`, `always`, `on_fail`), `circleci step halt` (the job stops after that step and succeeds), + commands with parameters, and `when` and `unless` steps with a boolean condition. `<< pipeline.parameters.x >>`, + `<< pipeline.git.branch >>`, `<< pipeline.git.revision >>` and a command's `<< parameters.x >>` are substituted, with + or without spaces; a name with no value is an error. +- **Each job gets its own home directory and its own `/tmp`**, and the working directory defaults to `~/project` inside + the home. Steps reach the job's `/tmp` through `TMPDIR`; cache paths, `checksum` files and step directories under + `/tmp/` resolve to it, so a cache saved from `/tmp/x` restores to the next job's `/tmp/x`, as on CircleCI. A job sees + `CIRCLE_SHA1`, `CIRCLE_BRANCH`, `CIRCLE_JOB`, `CIRCLE_REPOSITORY_URL` (a `file://` URL for the repository), and for a + pull request `CIRCLE_PR_NUMBER` and `CIRCLE_PULL_REQUEST`. A pull request builds its head branch, so give the event + the head commit. +- **The cache** (`src/circleci/cache.rs`), as `restore_cache` and `save_cache` see it: one scope for the whole project + (every branch shares it); each key in order matches as a prefix, newest save first; caches are immutable and expire 15 + days after they're saved; files restore to the paths they were saved from. Keys support `{{ checksum "file" }}` + (base64 of the file's SHA-256), `{{ .Branch }}`, `{{ .Revision }}`, `{{ .Environment.NAME }}` and `{{ epoch }}`. + `.Environment` sees only CircleCI's own variables and the project's: a job's or an image's `environment:`, or an + unset name, renders as `` on CircleCI and makes a constant key, so mockci refuses it. + +Steps run on the host, so every path a config names (cache paths, `checksum` files, `checkout` and step directories, +`working_directory`, the continuation's `configuration_path` and parameters file) resolves through one function +(`src/circleci/paths.rs`), which refuses `..`, `//` and any absolute path outside `/tmp`, and checks that the result +stays inside the job, following any symlink a step made. Caches keep symlinks as symlinks, as tar does, and a restore +replaces a symlink at its path and never writes through one to outside the job. A job's `working_directory` must start +with `~`. A step that writes to a literal `/tmp` path reaches the host's: config meant to run in mockci writes to +`${TMPDIR:-/tmp}`, which is `/tmp` on CircleCI. Saving a `/tmp` path that's missing from the job's `/tmp` but changed on +the host since the job started (anything under it) is an error that says so. It also fails on unknown keys, orbs other +than `continuation`, executors other than `docker`, job parameters, glob cache paths, regular expressions in branch +filters, logic statements in `when`, a `circleci` subcommand other than `step halt`, and a cache key template it can't +render. The `docker` image is checked but not used. + +`tests/mockci_circleci.rs` and `tests/mockci_circleci_setup.rs` run hand-written configs through all of this. + ## Writing a scenario `tests/skip_scenarios.rs` shows the pattern: build a throwaway repository with `tests/support/fixture_repo.rs`, run @@ -70,6 +122,10 @@ put back, four of the scenarios fail. ## Not modelled yet -Matrices, `paths` filters, fork permissions and secrets, cache size limits, concurrency groups, reusable workflows, -services, and CircleCI. A conformance job that runs the same scenarios on GitHub Actions and Blacksmith, to keep +Matrices, `paths` filters, fork permissions and secrets, cache size limits, concurrency groups, reusable workflows and +services. On CircleCI: workspaces, artifacts, contexts, approval jobs, scheduled pipelines, fork builds and their +environment variables, the 6-hour limit on continuing, and the continue API's "Conflicting pipeline parameters" refusal +(a parameter both configs declare, passed by the continuation, whose trigger value differs from the setup config's +default). Jobs and workflows run one at a time, alphabetically among those ready, so jobs that would run at the same +time on CircleCI see each other's caches; a scenario must not rely on that. A conformance job that runs the same scenarios on GitHub Actions and Blacksmith, to keep mockci honest, is planned in [DIRECTION.md](DIRECTION.md). diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 8e5b7f5..e542a9d 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -124,10 +124,18 @@ What the code does today, checked against the code in December 2026. Where cigen `CIGEN_UPDATE_GOLDEN=1 cargo test --test golden_fixtures` and review the diff. It also checks that generation is deterministic and that split and inline configs generate the same files. - `tests/skip_scenarios.rs`: end-to-end skip tests. Each generates a GitHub workflow for a throwaway repository, runs - it in mockci (`crates/mockci`, a GitHub Actions simulator with a cache model; see [MOCK_CI.md](MOCK_CI.md)), changes + it in mockci (`crates/mockci`, a GitHub Actions and CircleCI simulator with cache models; see [MOCK_CI.md](MOCK_CI.md)), changes the repository or the clock, and runs it again: an unchanged tree skips, a changed input or job definition runs (so does any key of a step), a failure records no pass, a pass expires after 7 idle days, a pull request reuses `main`'s passes but `main` can't reuse the pull request's. +- `tests/mockci_circleci.rs` and `tests/mockci_circleci_setup.rs`: mockci's CircleCI mode with hand-written configs: + `BASH_ENV`, commands, `when`, `requires` with statuses, filtered requirements ignored (unless all are), + `circleci step halt`, a `/tmp` per job, the project-wide cache (prefix keys newest first, immutable, gone after 15 + days), setup workflows that continue once with checked parameters, and `finish`. `tests/mockci_circleci_strict.rs`: + what it refuses, including paths that would reach the host and `.Environment` names CircleCI wouldn't render. +- `tests/mockci_symlinks.rs`: in both modes, a cached directory symlink restores as a symlink, and a restore never + writes through a symlink to outside the job; an artifact stores what its symlinks point to and leaves broken ones + out, as upload-artifact does. - `tests/config_layouts.rs`: both layouts load and hash the same, and the errors for both layouts present, a key in two files, unknown and provider-only keys, duplicate job ids and input group cycles. - `tests/json_schema.rs`: the committed schemas match the types, every config in the repository follows them, and they diff --git a/tests/mockci_circleci.rs b/tests/mockci_circleci.rs new file mode 100644 index 0000000..9fa94f4 --- /dev/null +++ b/tests/mockci_circleci.rs @@ -0,0 +1,222 @@ +//! mockci's CircleCI mode with hand-written configs: jobs, steps and the cache. +//! `tests/mockci_circleci_setup.rs` covers setup workflows and continuation. + +mod support; + +use cigen_mockci::{Outcome, Simulator}; +use support::circleci::{cache_config, log, repo_with, run}; + +const JOBS: &str = r#"version: 2.1 +commands: + greet: + parameters: + who: { type: string, default: world } + steps: + - run: echo "hello << parameters.who >>" +jobs: + build: + docker: [{ image: cimg/base:current }] + environment: { LEVEL: job } + steps: + - checkout + - run: + name: Export + command: echo 'export FROM_BASH_ENV=yes' >> "$BASH_ENV" + - run: + name: Read + command: echo "bash env $FROM_BASH_ENV, level $LEVEL, branch $CIRCLE_BRANCH, in $(basename "$PWD")" + - greet: { who: mockci } + - greet + test: + docker: [{ image: cimg/base:current }] + steps: + - run: + name: Fail + command: exit 3 + - run: + name: After a failure + command: echo never + - run: + name: Always + command: echo always + when: always + - run: + name: On failure + command: echo cleaning up + when: on_fail + deploy: + docker: [{ image: cimg/base:current }] + steps: + - run: echo deploying +workflows: + ci: + jobs: + - build + - test: + requires: [build] + - deploy: + requires: [test] +"#; + +#[test] +fn steps_share_bash_env_and_commands_expand_with_their_parameters() { + let (repo, sha) = repo_with(JOBS); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + let build = report.job("build"); + assert_eq!(build.result, Outcome::Success, "{report}"); + assert!( + log(&report, "build").contains("bash env yes, level job, branch main, in project"), + "{report}" + ); + assert!(log(&report, "build").contains("hello mockci"), "{report}"); + assert!(log(&report, "build").contains("hello world"), "{report}"); +} + +#[test] +fn a_failed_step_fails_the_job_and_blocks_the_jobs_that_require_it() { + let (repo, sha) = repo_with(JOBS); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + let test = report.job("test"); + assert_eq!(test.result, Outcome::Failure, "{report}"); + let names: Vec<_> = test.steps.iter().map(|step| step.name.as_str()).collect(); + assert_eq!(names, ["Fail", "Always", "On failure"], "{report}"); + assert!(!report.ran("deploy"), "{report}"); + assert_eq!(report.conclusion(), Outcome::Failure); +} + +#[test] +fn circleci_step_halt_ends_the_job_as_a_success() { + let config = "version: 2.1\njobs:\n only:\n docker: [{ image: cimg/base:current }]\n steps:\n - run:\n name: Halt\n command: circleci step halt\n - run:\n name: Never\n command: exit 1\nworkflows:\n ci:\n jobs: [only]\n"; + let (repo, sha) = repo_with(config); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + let job = report.job("only"); + assert_eq!(job.result, Outcome::Success, "{report}"); + assert_eq!(job.steps.len(), 1, "{report}"); +} + +#[test] +fn the_cache_is_shared_across_branches_immutable_and_gone_after_15_days() { + let config = cache_config( + r#"['v1-{{ checksum "lock" }}']"#, + r#"v1-{{ checksum "lock" }}"#, + ); + let repo = support::fixture_repo::FixtureRepo::new(); + repo.write(".circleci/config.yml", &config) + .write("lock", "lock one\n"); + let sha = repo.commit("initial"); + let mut sim = Simulator::new(repo.path()).unwrap(); + + let first = run(&mut sim, "main", &sha); + assert!(log(&first, "cache").contains("nothing"), "{first}"); + let saved = &first.job("cache").cache_events[1]; + assert_eq!(saved.key, "v1-lXLILRBXMA4lm0dbxR9f6ag4KJwHLUQaAtAuWh1EhsI="); + assert_eq!(saved.result, "saved"); + + let other_branch = run(&mut sim, "feature", &sha); + assert!( + log(&other_branch, "cache").contains("lock one"), + "{other_branch}" + ); + assert_eq!(other_branch.job("cache").cache_events[1].result, "exists"); + + sim.advance_days(15); + let expired = run(&mut sim, "main", &sha); + assert!(log(&expired, "cache").contains("nothing"), "{expired}"); +} + +#[test] +fn restore_keys_match_as_prefixes_in_order_newest_first() { + let repo = support::fixture_repo::FixtureRepo::new(); + let config = cache_config( + "['v1-{{ .Branch }}-', 'v1-']", + "v1-{{ .Branch }}-{{ .Revision }}", + ); + repo.write(".circleci/config.yml", &config) + .write("lock", "first\n"); + let first = repo.commit("first"); + repo.write("lock", "second\n"); + let second = repo.commit("second"); + let mut sim = Simulator::new(repo.path()).unwrap(); + + run(&mut sim, "main", &first); + sim.advance_days(1); + run(&mut sim, "main", &second); + let feature = run(&mut sim, "feature", &first); + assert!( + log(&feature, "cache").contains("second"), + "newest `v1-` match: {feature}" + ); + sim.advance_days(1); + run(&mut sim, "other", &second); + let back = run(&mut sim, "feature", &first); + assert!( + log(&back, "cache").contains("first"), + "the first key matches: {back}" + ); +} + +const REQUIRES: &str = r#"version: 2.1 +jobs: + pass: + docker: [{ image: cimg/base:current }] + steps: [{ run: "true" }] + fail: + docker: [{ image: cimg/base:current }] + steps: [{ run: "false" }] +workflows: + ci: + jobs: + - fail + - pass: { name: after-fail, requires: [fail] } + - pass: { name: on-failure, requires: [{ fail: failed }] } + - pass: { name: gate, requires: [{ fail: terminal }, { after-fail: terminal }] } + - pass: { name: not-run-only, requires: [{ after-fail: not_run }] } +"#; + +#[test] +fn requires_can_name_statuses_and_a_blocked_job_ends_not_run() { + let (repo, sha) = repo_with(REQUIRES); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + assert!(!report.ran("after-fail"), "{report}"); + assert!(report.ran("on-failure"), "{report}"); + assert!( + report.ran("gate"), + "terminal includes failed and not_run: {report}" + ); + assert!(report.ran("not-run-only"), "{report}"); +} + +#[test] +fn each_job_has_its_own_tmp_and_caches_under_it_restore_there() { + let config = r#"version: 2.1 +jobs: + write: + docker: [{ image: cimg/base:current }] + steps: + - run: mkdir -p "$TMPDIR/marks" && echo one > "$TMPDIR/marks/write" + - save_cache: + key: marks-{{ checksum "/tmp/marks/write" }} + paths: [/tmp/marks] + read: + docker: [{ image: cimg/base:current }] + steps: + - run: test ! -e "$TMPDIR/marks" + - restore_cache: + keys: [marks-] + - run: cat "$TMPDIR/marks/write" +workflows: + ci: + jobs: + - write + - read: { requires: [write] } +"#; + let (repo, sha) = repo_with(config); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + assert_eq!(report.job("read").result, Outcome::Success, "{report}"); + assert!(log(&report, "read").contains("one"), "{report}"); +} diff --git a/tests/mockci_circleci_setup.rs b/tests/mockci_circleci_setup.rs new file mode 100644 index 0000000..77893af --- /dev/null +++ b/tests/mockci_circleci_setup.rs @@ -0,0 +1,171 @@ +//! mockci's CircleCI mode: setup workflows, `continuation/continue` and `continuation/finish`, +//! and pipeline parameters. + +mod support; + +use cigen_mockci::{Outcome, Simulator}; +use support::circleci::{log, run}; +use support::fixture_repo::FixtureRepo; + +/// A setup config whose one job runs `script`, then the steps in `last`. +fn setup(script: &str, last: &str) -> String { + format!( + r#"version: 2.1 +setup: true +parameters: + force: {{ type: boolean, default: false }} +orbs: + continuation: circleci/continuation@1.0.0 +jobs: + setup: + docker: [{{ image: cimg/base:current }}] + steps: + - checkout + - run: + name: Plan + command: | +{script} +{last} +workflows: + setup: + jobs: [setup] +"# + ) +} + +const CONTINUE: &str = " - continuation/continue:\n configuration_path: .circleci/main.yml\n parameters: params.json\n"; + +const MAIN: &str = r#"version: 2.1 +parameters: + run_tests: { type: boolean, default: false } + label: { type: string, default: none } +jobs: + build: + docker: [{ image: cimg/base:current }] + steps: + - run: echo "building << pipeline.parameters.label >> at << pipeline.git.branch >>" + test: + docker: [{ image: cimg/base:current }] + steps: + - run: echo testing +workflows: + build: + jobs: [build] + test: + when: << pipeline.parameters.run_tests >> + jobs: [test] +"#; + +fn repo(setup_config: &str) -> (FixtureRepo, String) { + let repo = FixtureRepo::new(); + repo.write(".circleci/config.yml", setup_config) + .write(".circleci/main.yml", MAIN); + let sha = repo.commit("initial"); + (repo, sha) +} + +#[test] +fn the_setup_job_continues_with_the_config_and_parameters_it_chooses() { + let script = " echo '{\"run_tests\": true, \"label\": \"planned\"}' > params.json"; + let (repo, sha) = repo(&setup(script, CONTINUE)); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "feature", &sha); + assert_eq!(report.job("setup").result, Outcome::Success, "{report}"); + assert!( + log(&report, "build").contains("building planned at feature"), + "{report}" + ); + assert!(report.ran("test"), "{report}"); + assert_eq!(report.parameters["run_tests"], "true"); +} + +#[test] +fn a_false_workflow_when_leaves_the_workflow_out() { + let script = " echo '{}' > params.json"; + let (repo, sha) = repo(&setup(script, CONTINUE)); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + assert!(log(&report, "build").contains("building none"), "{report}"); + assert!(!report.workflows.contains_key("test"), "{report}"); +} + +#[test] +fn only_the_setup_workflow_has_a_continuation_key() { + let script = " echo \"key=${CIRCLE_CONTINUATION_KEY:-none}\"; echo '{\"run_tests\": true}' > params.json"; + let repo = FixtureRepo::new(); + repo.write(".circleci/config.yml", &setup(script, CONTINUE)) + .write( + ".circleci/main.yml", + &MAIN.replace( + "echo testing", + "echo \"key=${CIRCLE_CONTINUATION_KEY:-none}\"", + ), + ); + let sha = repo.commit("initial"); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + assert!( + log(&report, "setup").contains("key=mockci-continuation-"), + "{report}" + ); + assert!(log(&report, "test").contains("key=none"), "{report}"); +} + +#[test] +fn a_pipeline_continues_once() { + let script = " echo '{}' > params.json"; + let twice = format!("{CONTINUE}{CONTINUE}"); + let (repo, sha) = repo(&setup(script, &twice)); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + let setup = report.job("setup"); + assert_eq!(setup.result, Outcome::Failure, "{report}"); + assert!( + log(&report, "setup").contains("already been continued"), + "{report}" + ); + assert!( + report.ran("build"), + "the first continuation stands: {report}" + ); +} + +#[test] +fn finish_ends_the_pipeline_without_running_anything() { + let finish = " - continuation/finish\n"; + let (repo, sha) = repo(&setup(" echo planned", finish)); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + assert!(report.finished, "{report}"); + assert!(report.workflows.is_empty(), "{report}"); +} + +#[test] +fn the_continue_api_refuses_undeclared_or_mistyped_parameters() { + for params in ["{\"unknown\": 1}", "{\"run_tests\": \"yes\"}", "not json"] { + let script = format!(" echo '{params}' > params.json"); + let (repo, sha) = repo(&setup(&script, CONTINUE)); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + assert_eq!( + report.job("setup").result, + Outcome::Failure, + "{params}: {report}" + ); + assert!(report.workflows.is_empty(), "{params}: {report}"); + } +} + +#[test] +fn a_job_outside_a_setup_workflow_cant_continue() { + let config = format!( + "version: 2.1\norbs:\n continuation: circleci/continuation@1.0.0\njobs:\n plain:\n docker: [{{ image: cimg/base:current }}]\n steps:\n - checkout\n{CONTINUE}workflows:\n ci:\n jobs: [plain]\n" + ); + let (repo, sha) = repo(&config); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "main", &sha); + assert!( + log(&report, "plain").contains("CIRCLE_CONTINUATION_KEY is required"), + "{report}" + ); +} diff --git a/tests/mockci_circleci_strict.rs b/tests/mockci_circleci_strict.rs new file mode 100644 index 0000000..36e125f --- /dev/null +++ b/tests/mockci_circleci_strict.rs @@ -0,0 +1,229 @@ +//! What mockci's CircleCI mode refuses: config it doesn't model, and paths that would reach the +//! host, since steps run there. + +mod support; + +use cigen_mockci::Simulator; +use support::circleci::{cache_config, push_to, repo_with}; + +/// The error mockci gives for `config`, or a panic if the pipeline ran. +fn error_for(config: &str) -> String { + let (repo, sha) = repo_with(config); + let mut sim = Simulator::new(repo.path()).unwrap(); + sim.runner_env("PROJECT_SALT", "salt"); + match sim.run_circleci(&push_to("main", &sha)) { + Ok(report) => panic!("expected an error, but the pipeline ran:\n{report}"), + Err(error) => format!("{error:#}"), + } +} + +/// A job with `steps` (YAML lines indented for a job's steps list) and `extra` job keys. +fn job(extra: &str, steps: &str) -> String { + format!( + "version: 2.1\njobs:\n only:\n docker: [{{ image: cimg/base:current }}]\n{extra} steps:\n{steps}workflows:\n ci:\n jobs: [only]\n" + ) +} + +#[test] +fn config_mockci_doesnt_model_is_an_error() { + let cases = [ + ( + "version: 2.1\nexecutors: {}\n".to_string(), + "unknown top-level key `executors`", + ), + ( + "version: 2.1\norbs:\n node: circleci/node@1.0.0\n".to_string(), + "mockci runs only", + ), + ( + job("", " - run: echo\n") + .replace("jobs: [only]", "jobs: [{ only: { context: x } }]"), + "unknown workflow job key `context`", + ), + ]; + for (config, expected) in cases { + let error = error_for(&config); + assert!(error.contains(expected), "{error}"); + } +} + +#[test] +fn paths_that_would_reach_the_host_are_errors() { + let save = |path: &str| { + cache_config("['a']", "a") + .replace("cat lock", "echo value") + .replace("[~/stored]", &format!("[{path}]")) + }; + let cases = [ + (save("/var/stored"), "/var/stored"), + (save("~/../stored"), "can't use `..`"), + ( + job("", " - checkout: { path: ../outside }\n"), + "can't use `..`", + ), + ( + job( + "", + " - run: { command: pwd, working_directory: /etc }\n", + ), + "`/etc`", + ), + ( + job( + " working_directory: ~/../outside\n", + " - run: pwd\n", + ), + "can't use `..`", + ), + ( + job( + "", + " - restore_cache: { key: 'k-{{ checksum \"../x\" }}' }\n", + ), + "can't use `..`", + ), + ( + job( + "", + " - restore_cache: { key: 'k-{{ checksum \"/etc/hosts\" }}' }\n", + ), + "`/etc/hosts`", + ), + ]; + for (config, expected) in cases { + let error = error_for(&config); + assert!(error.contains(expected), "{expected}: {error}"); + } +} + +#[test] +fn a_continuation_cant_read_a_host_file() { + let config = |path: &str| { + format!( + "version: 2.1\nsetup: true\norbs:\n continuation: circleci/continuation@1.0.0\njobs:\n setup:\n docker: [{{ image: cimg/base:current }}]\n steps:\n - continuation/continue:\n configuration_path: {path}\nworkflows:\n setup:\n jobs: [setup]\n" + ) + }; + for path in ["/etc/hosts", "../../outside.yml"] { + let error = error_for(&config(path)); + assert!(error.contains(path), "{error}"); + } +} + +/// `.Environment` sees CircleCI's variables and the project's (`runner_env` here), not the job's +/// or the image's `environment:`, which CircleCI renders as ``. +#[test] +fn environment_in_a_cache_key_is_only_circleci_and_project_variables() { + let key = |name: &str| { + format!(" - restore_cache: {{ key: 'k-{{{{ .Environment.{name} }}}}' }}\n") + }; + let job_env = " environment: { JOB_LEVEL: x }\n"; + for name in ["JOB_LEVEL", "UNSET"] { + let error = error_for(&job(job_env, &key(name))); + assert!(error.contains(""), "{name}: {error}"); + } + for name in ["CIRCLE_BRANCH", "PROJECT_SALT"] { + let (repo, sha) = repo_with(&job(job_env, &key(name))); + let mut sim = Simulator::new(repo.path()).unwrap(); + sim.runner_env("PROJECT_SALT", "salt"); + let report = sim.run_circleci(&push_to("main", &sha)).unwrap(); + let expected = if name == "CIRCLE_BRANCH" { + "k-main" + } else { + "k-salt" + }; + assert_eq!(report.job("only").cache_events[0].key, expected, "{report}"); + } +} + +/// cigen's generated CircleCI cache keys never use `.Environment`: mockci can't tell whether a +/// variable would render on CircleCI, and one that doesn't makes a constant key. +#[test] +fn generated_circleci_config_uses_no_environment_in_keys() { + for fixture in std::fs::read_dir(support::repo_root().join("integration_tests")).unwrap() { + let dir = fixture.unwrap().path().join(".circleci"); + for file in std::fs::read_dir(&dir).into_iter().flatten() { + let path = file.unwrap().path(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(!text.contains(".Environment."), "{}", path.display()); + } + } +} + +/// A step that writes a literal `/tmp` path reaches the host's `/tmp`; saving that path from +/// the job's own `/tmp` would silently find nothing, so it's an error that names the fix. +#[test] +fn saving_a_tmp_path_a_step_wrote_on_the_host_is_an_error() { + let unique = format!("mockci-host-{}", std::process::id()); + let steps = format!( + " - run: mkdir -p /tmp/{unique} && touch /tmp/{unique}/x\n - save_cache: {{ key: k, paths: [/tmp/{unique}] }}\n" + ); + let error = error_for(&job("", &steps)); + let _ = std::fs::remove_dir_all(format!("/tmp/{unique}")); + assert!(error.contains("TMPDIR"), "{error}"); +} + +/// A host `/tmp` path that was there before the job started isn't the job's doing: saving it +/// finds nothing, as on CircleCI. +#[test] +fn a_host_tmp_path_older_than_the_job_is_not_blamed_on_it() { + let unique = format!("mockci-stale-{}", std::process::id()); + let host = format!("/tmp/{unique}"); + std::fs::create_dir_all(&host).unwrap(); + let old = std::time::SystemTime::now() - std::time::Duration::from_secs(3600); + std::fs::File::open(&host) + .unwrap() + .set_modified(old) + .unwrap(); + let config = job( + "", + &format!(" - save_cache: {{ key: k, paths: [{host}] }}\n"), + ); + let (repo, sha) = repo_with(&config); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = sim.run_circleci(&push_to("main", &sha)); + let _ = std::fs::remove_dir_all(&host); + let report = report.unwrap(); + let log: String = report + .job("only") + .steps + .iter() + .map(|step| step.log.as_str()) + .collect(); + assert!(log.contains("No files to save for key: k"), "{report}"); +} + +/// A write deep inside an old host directory changes only its own parent's time, so the check +/// looks at the newest change anywhere under the path. +#[test] +fn a_write_deep_inside_an_old_host_tmp_directory_is_still_blamed() { + let unique = format!("mockci-deep-{}", std::process::id()); + let host = format!("/tmp/{unique}"); + std::fs::create_dir_all(format!("{host}/sub")).unwrap(); + let old = std::time::SystemTime::now() - std::time::Duration::from_secs(3600); + for dir in [host.clone(), format!("{host}/sub")] { + std::fs::File::open(&dir) + .unwrap() + .set_modified(old) + .unwrap(); + } + let steps = format!( + " - run: touch {host}/sub/x\n - save_cache: {{ key: k, paths: [{host}] }}\n" + ); + let error = error_for(&job("", &steps)); + let _ = std::fs::remove_dir_all(&host); + assert!(error.contains("TMPDIR"), "{error}"); +} + +/// "If filters exclude all dependencies of a job, that job doesn't execute either", and that +/// carries on down the workflow. A job with one requirement left still runs. +#[test] +fn a_job_whose_requirements_the_filters_all_leave_out_doesnt_run() { + let config = "version: 2.1\njobs:\n only:\n docker: [{ image: cimg/base:current }]\n steps: [{ run: \"true\" }]\nworkflows:\n ci:\n jobs:\n - only: { name: release, filters: { branches: { only: release } } }\n - only: { name: plain }\n - only: { name: after-release, requires: [release] }\n - only: { name: after-that, requires: [after-release] }\n - only: { name: after-both, requires: [release, plain] }\n"; + let (repo, sha) = repo_with(config); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = sim.run_circleci(&push_to("main", &sha)).unwrap(); + let jobs = &report.workflows["ci"].jobs; + assert!(!jobs.contains_key("after-release"), "{report}"); + assert!(!jobs.contains_key("after-that"), "{report}"); + assert!(report.ran("after-both"), "{report}"); +} diff --git a/tests/mockci_symlinks.rs b/tests/mockci_symlinks.rs new file mode 100644 index 0000000..7e25d48 --- /dev/null +++ b/tests/mockci_symlinks.rs @@ -0,0 +1,216 @@ +//! Symlinks in cached directories, in both of mockci's modes: they're cached as symlinks, and a +//! restore never writes through a symlink to outside the job. pnpm's `node_modules` is full of +//! directory symlinks; following one used to recurse until the stack overflowed. + +mod support; + +use cigen_mockci::{Event, Outcome, Simulator}; +use support::circleci::{push_to, repo_with}; +use support::fixture_repo::FixtureRepo; + +/// Makes `stored/real/file` and `stored/link -> real`, then lists what `link` points to. +const MAKE: &str = + "mkdir -p stored/real && echo cached > stored/real/file && ln -s real stored/link"; +const SHOW: &str = "readlink stored/link && cat stored/link/file"; + +#[test] +fn github_caches_a_directory_symlink_as_a_symlink() { + let workflow = format!( + r#"on: push +jobs: + write: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: {MAKE} + - uses: actions/cache@v4 + with: {{ path: stored, key: links }} + read: + needs: write + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/cache@v4 + with: {{ path: stored, key: links }} + - run: {SHOW} +"# + ); + let repo = FixtureRepo::new(); + repo.write(".github/workflows/ci.yml", &workflow); + let sha = repo.commit("initial"); + let mut sim = Simulator::new(repo.path()).unwrap(); + let event = Event::Push { + branch: "main".into(), + sha, + }; + let run = sim.run(".github/workflows/ci.yml", &event).unwrap(); + let read = run.job("read"); + assert_eq!(read.result, Outcome::Success, "{run}"); + let log: String = read.steps.iter().map(|step| step.log.as_str()).collect(); + assert!(log.contains("real\ncached"), "{run}"); +} + +fn circleci(steps_write: &str, steps_read: &str) -> String { + format!( + r#"version: 2.1 +jobs: + write: + docker: [{{ image: cimg/base:current }}] + working_directory: ~/w + steps: +{steps_write} - save_cache: {{ key: links, paths: [~/w/stored] }} + read: + docker: [{{ image: cimg/base:current }}] + working_directory: ~/w + steps: +{steps_read} - restore_cache: {{ keys: [links] }} + - run: {SHOW} +workflows: + ci: + jobs: [write, {{ read: {{ requires: [write] }} }}] +"# + ) +} + +#[test] +fn circleci_caches_a_directory_symlink_as_a_symlink() { + let config = circleci(&format!(" - run: {MAKE}\n"), ""); + let (repo, sha) = repo_with(&config); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = sim.run_circleci(&push_to("main", &sha)).unwrap(); + let read = report.job("read"); + assert_eq!(read.result, Outcome::Success, "{report}"); + let log: String = read.steps.iter().map(|step| step.log.as_str()).collect(); + assert!(log.contains("real\ncached"), "{report}"); +} + +#[test] +fn a_restored_directory_replaces_a_symlink_instead_of_writing_through_it() { + let outside = tempfile::tempdir().unwrap(); + let config = circleci( + &format!(" - run: {MAKE}\n"), + &format!( + " - run: mkdir -p stored && ln -s {} stored/real\n", + outside.path().display() + ), + ); + let (repo, sha) = repo_with(&config); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = sim.run_circleci(&push_to("main", &sha)).unwrap(); + assert!( + !outside.path().join("file").exists(), + "the restore wrote to the host" + ); + assert_eq!(report.job("read").result, Outcome::Success, "{report}"); +} + +#[test] +fn a_restore_to_a_symlink_that_leaves_the_job_is_refused() { + let outside = tempfile::tempdir().unwrap(); + let config = circleci( + &format!(" - run: {MAKE}\n"), + &format!(" - run: ln -s {} stored\n", outside.path().display()), + ); + let (repo, sha) = repo_with(&config); + let mut sim = Simulator::new(repo.path()).unwrap(); + let result = sim.run_circleci(&push_to("main", &sha)); + assert!( + !outside.path().join("real").exists(), + "the restore wrote to the host" + ); + let error = format!("{:#}", result.expect_err("the restore should be refused")); + assert!(error.contains("must stay inside the job"), "{error}"); +} + +/// A GitHub workflow whose `read` job runs `setup` and then restores the cache of `path`. +fn github(path: &str, setup: &str) -> String { + format!( + r#"on: push +jobs: + write: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: {MAKE} && mkdir -p stored/inner && echo inner > stored/inner/file + - uses: actions/cache@v4 + with: {{ path: {path}, key: links }} + read: + needs: write + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: {setup} + - uses: actions/cache/restore@v4 + with: {{ path: {path}, key: links }} +"# + ) +} + +fn run_github(workflow: &str) -> anyhow::Result { + let repo = FixtureRepo::new(); + repo.write(".github/workflows/ci.yml", workflow); + let sha = repo.commit("initial"); + let mut sim = Simulator::new(repo.path()).unwrap(); + let event = Event::Push { + branch: "main".into(), + sha, + }; + sim.run(".github/workflows/ci.yml", &event) +} + +#[test] +fn github_restore_replaces_a_symlink_at_the_cache_path() { + let outside = tempfile::tempdir().unwrap(); + let setup = format!("ln -s {} stored", outside.path().display()); + let run = run_github(&github("stored", &setup)).unwrap(); + assert_eq!(run.job("read").result, Outcome::Success, "{run}"); + assert!( + std::fs::read_dir(outside.path()).unwrap().next().is_none(), + "the restore wrote to the host: {run}" + ); +} + +#[test] +fn github_restore_under_a_symlink_that_leaves_the_workspace_is_refused() { + let outside = tempfile::tempdir().unwrap(); + let setup = format!("ln -s {} stored", outside.path().display()); + let result = run_github(&github("stored/inner", &setup)); + assert!( + std::fs::read_dir(outside.path()).unwrap().next().is_none(), + "the restore wrote to the host" + ); + let error = format!("{:#}", result.expect_err("the restore should be refused")); + assert!(error.contains("through a symlink"), "{error}"); +} + +/// upload-artifact follows symlinks and leaves broken ones out (`followSymbolicLinks: true`, +/// `omitBrokenSymbolicLinks: true` in its search), so a download has the files they point to. +#[test] +fn artifacts_store_what_symlinks_point_to_and_leave_broken_ones_out() { + let workflow = r#"on: push +jobs: + up: + runs-on: ubuntu-latest + steps: + - run: | + mkdir -p art/real && echo cached > art/real/file + ln -s real art/dirlink && ln -s real/file art/filelink && ln -s missing art/broken + - uses: actions/upload-artifact@v4 + with: { name: links, path: art } + down: + needs: up + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: { name: links, path: got } + - run: | + test ! -L got/dirlink && cat got/dirlink/file + test ! -L got/filelink && cat got/filelink + test ! -e got/broken && test ! -L got/broken && echo no-broken +"#; + let run = run_github(workflow).unwrap(); + let down = run.job("down"); + assert_eq!(down.result, Outcome::Success, "{run}"); + let log: String = down.steps.iter().map(|step| step.log.as_str()).collect(); + assert!(log.contains("cached\ncached\nno-broken"), "{run}"); +} diff --git a/tests/support/circleci.rs b/tests/support/circleci.rs new file mode 100644 index 0000000..f3c081a --- /dev/null +++ b/tests/support/circleci.rs @@ -0,0 +1,62 @@ +//! Helpers for running hand-written CircleCI configs in mockci's CircleCI mode. + +use super::fixture_repo::FixtureRepo; +use cigen_mockci::{Event, PipelineReport, Simulator}; + +/// A repository holding `config` as `.circleci/config.yml`, committed on `main`. +pub fn repo_with(config: &str) -> (FixtureRepo, String) { + let repo = FixtureRepo::new(); + repo.write(".circleci/config.yml", config); + let sha = repo.commit("initial"); + (repo, sha) +} + +pub fn push_to(branch: &str, sha: &str) -> Event { + Event::Push { + branch: branch.into(), + sha: sha.into(), + } +} + +/// Runs the pipeline for a push to `branch`. +pub fn run(sim: &mut Simulator, branch: &str, sha: &str) -> PipelineReport { + sim.run_circleci(&push_to(branch, sha)) + .expect("run the pipeline") +} + +/// The logs of every step of `job`, joined. +pub fn log(report: &PipelineReport, job: &str) -> String { + report + .job(job) + .steps + .iter() + .map(|step| step.log.as_str()) + .collect() +} + +/// One job that restores `keys`, prints what it found, and saves `stored` under `save_key`. +pub fn cache_config(keys: &str, save_key: &str) -> String { + format!( + r#"version: 2.1 +jobs: + cache: + docker: [{{ image: cimg/base:current }}] + steps: + - checkout + - restore_cache: + keys: {keys} + - run: + name: Show + command: cat ~/stored/value 2>/dev/null || echo nothing + - run: + name: Write + command: mkdir -p ~/stored && cat lock > ~/stored/value + - save_cache: + key: {save_key} + paths: [~/stored] +workflows: + ci: + jobs: [cache] +"# + ) +} diff --git a/tests/support/mod.rs b/tests/support/mod.rs index de81891..8c58462 100644 --- a/tests/support/mod.rs +++ b/tests/support/mod.rs @@ -6,6 +6,7 @@ #![allow(dead_code)] +pub mod circleci; pub mod doc_examples; pub mod fixture_repo; pub mod release;