From 4a0d3df9bb77a87c4948f6a532436b66d820bbef Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 15:47:22 +1300 Subject: [PATCH 1/6] Add a CircleCI mode to mockci: setup workflows, continuation and the cache CircleCI parity item (a). `circleci local execute` runs single jobs and skips cache steps, so nothing could show what CircleCI does with a setup workflow, a continuation or a cache key. Simulator::run_circleci runs .circleci/config.yml at the event's commit and returns a PipelineReport. - Setup workflows: continuation/continue and finish run natively (the orb's script posts to CircleCI and writes to the host's /tmp), with the orb's own checks and what the continue API refuses: a second continuation, a setup config, undeclared or mistyped parameters. - Jobs: requires order, blocked jobs, branch filters, checkout, run with BASH_ENV, step when, circleci step halt, commands with parameters, << pipeline.* >> substitution, a home directory per job. - The cache: one scope for the project, keys matched as prefixes newest first, immutable, expiring 15 days after the save; checksum, .Branch, .Revision, .Environment and epoch templates. - Strict: unknown keys, other orbs and anything that would touch the host (absolute cache paths, working directories outside ~) are errors. Tests: tests/mockci_circleci.rs and tests/mockci_circleci_setup.rs, with hand-written configs. MOCK_CI.md documents the mode and its limits. --- Cargo.lock | 1 + crates/mockci/Cargo.toml | 1 + crates/mockci/src/circleci/cache.rs | 149 ++++++++++ crates/mockci/src/circleci/config.rs | 240 ++++++++++++++++ crates/mockci/src/circleci/continuation.rs | 176 ++++++++++++ crates/mockci/src/circleci/job.rs | 233 +++++++++++++++ crates/mockci/src/circleci/mod.rs | 17 ++ crates/mockci/src/circleci/order.rs | 72 +++++ crates/mockci/src/circleci/params.rs | 204 +++++++++++++ crates/mockci/src/circleci/pipeline.rs | 270 ++++++++++++++++++ crates/mockci/src/circleci/report.rs | 70 +++++ crates/mockci/src/circleci/steps.rs | 147 ++++++++++ crates/mockci/src/circleci/template.rs | 59 ++++ crates/mockci/src/circleci/workflow_config.rs | 73 +++++ crates/mockci/src/db.rs | 10 + crates/mockci/src/lib.rs | 2 + crates/mockci/src/sim.rs | 2 +- internal_docs/DIRECTION.md | 2 +- internal_docs/MOCK_CI.md | 46 ++- internal_docs/STATUS.md | 5 +- tests/mockci_circleci.rs | 215 ++++++++++++++ tests/mockci_circleci_setup.rs | 171 +++++++++++ tests/support/circleci.rs | 35 +++ tests/support/mod.rs | 1 + 24 files changed, 2194 insertions(+), 7 deletions(-) create mode 100644 crates/mockci/src/circleci/cache.rs create mode 100644 crates/mockci/src/circleci/config.rs create mode 100644 crates/mockci/src/circleci/continuation.rs create mode 100644 crates/mockci/src/circleci/job.rs create mode 100644 crates/mockci/src/circleci/mod.rs create mode 100644 crates/mockci/src/circleci/order.rs create mode 100644 crates/mockci/src/circleci/params.rs create mode 100644 crates/mockci/src/circleci/pipeline.rs create mode 100644 crates/mockci/src/circleci/report.rs create mode 100644 crates/mockci/src/circleci/steps.rs create mode 100644 crates/mockci/src/circleci/template.rs create mode 100644 crates/mockci/src/circleci/workflow_config.rs create mode 100644 tests/mockci_circleci.rs create mode 100644 tests/mockci_circleci_setup.rs create mode 100644 tests/support/circleci.rs 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/circleci/cache.rs b/crates/mockci/src/circleci/cache.rs new file mode 100644 index 0000000..066baba --- /dev/null +++ b/crates/mockci/src/circleci/cache.rs @@ -0,0 +1,149 @@ +//! 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::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, + /// The job's home directory: saved paths are stored relative to it. + pub home: &'a Path, +} + +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() { + copy_tree(&stored, &self.home.join(path))?; + } + } + 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 relative = paths + .iter() + .map(|path| { + path.strip_prefix(self.home) + .map(Path::to_path_buf) + .map_err(|_| { + anyhow::anyhow!( + "mockci caches only paths under the job's home directory, got {}", + path.display() + ) + }) + }) + .collect::>>()?; + 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, relative)) in paths.iter().zip(&relative).enumerate() { + manifest.push_str(&format!("{}\n", relative.display())); + if path.exists() { + copy_tree(path, &dir.join(index.to_string()))?; + } + } + std::fs::write(dir.join("paths"), manifest)?; + self.record("save", key, None, "saved")?; + Ok(format!("Stored cache for key: {key}")) + } + + 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: `~/x` under its home, `x` under its working +/// directory. Absolute paths would reach the host, so they're errors. +pub fn resolve_path(path: &str, home: &Path, working_directory: &Path) -> Result { + if path.contains(['*', '?', '[']) { + bail!("mockci doesn't model glob patterns in cache paths, got `{path}`"); + } + if path.split('/').any(|part| part == "..") { + bail!("mockci doesn't model `..` in cache paths, got `{path}`"); + } + if let Some(rest) = path.strip_prefix("~/") { + return Ok(home.join(rest)); + } + if path == "~" { + return Ok(home.to_path_buf()); + } + if path.starts_with('/') { + bail!( + "mockci runs steps on the host, so it can't cache the absolute path `{path}`: use a path under `~` or the working directory" + ); + } + Ok(working_directory.join(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..65fd33b --- /dev/null +++ b/crates/mockci/src/circleci/config.rs @@ -0,0 +1,240 @@ +//! 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, +} + +#[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..ade2bba --- /dev/null +++ b/crates/mockci/src/circleci/continuation.rs @@ -0,0 +1,176 @@ +//! 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 config_path = job + .working_directory + .join(¶meters["configuration_path"]); + let Ok(config) = std::fs::read_to_string(&config_path) else { + return Ok(StepResult::failed(format!( + "can't read {}", + config_path.display() + ))); + }; + let raw = ¶meters["parameters"]; + let file = job.working_directory.join(raw); + let text = if file.is_file() { + std::fs::read_to_string(&file)? + } else { + 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..7f4a4e9 --- /dev/null +++ b/crates/mockci/src/circleci/job.rs @@ -0,0 +1,233 @@ +//! Runs one CircleCI job: its environment, its steps in order with `when:`, `BASH_ENV`, and +//! `circleci step halt`. + +use super::params::Expanded; +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, + pub temp: PathBuf, + /// Commands on `PATH` that stand in for CircleCI's own (`circleci step halt`). + pub bin: PathBuf, + pub env: BTreeMap, + /// Set in a setup workflow: where a continuation is recorded. + pub continuation: Option<&'a mut Option>, +} + +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.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.resolve_dir(&dir)?, + 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.temp) + .env("BASH_ENV", self.bash_env()); + command + } + + /// A directory as a step names it: `~/x` under the job's home, `x` under the working + /// directory. Absolute paths would reach the host, so they're errors. + pub fn resolve_dir(&self, dir: &str) -> Result { + if let Some(rest) = dir.strip_prefix("~/") { + return Ok(self.home.join(rest)); + } + if dir == "~" { + return Ok(self.home.clone()); + } + if dir.starts_with('/') { + bail!( + "mockci runs steps on the host, so it can't use the absolute directory `{dir}`: use `~/...`" + ); + } + Ok(self.working_directory.join(dir)) + } +} diff --git a/crates/mockci/src/circleci/mod.rs b/crates/mockci/src/circleci/mod.rs new file mode 100644 index 0000000..d176809 --- /dev/null +++ b/crates/mockci/src/circleci/mod.rs @@ -0,0 +1,17 @@ +//! 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 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..065a80c --- /dev/null +++ b/crates/mockci/src/circleci/order.rs @@ -0,0 +1,72 @@ +//! 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). +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); + } + } + for entry in included.values() { + for need in &entry.requires { + if !by_name.contains_key(need.as_str()) { + bail!( + "`{}` requires `{need}`, which isn't in the workflow", + entry.name + ); + } + if !included.contains_key(need.as_str()) { + bail!( + "`{}` requires `{need}`, which the branch filters leave out: mockci doesn't model that", + entry.name + ); + } + } + } + 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.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/pipeline.rs b/crates/mockci/src/circleci/pipeline.rs new file mode 100644 index 0000000..196c246 --- /dev/null +++ b/crates/mockci/src/circleci/pipeline.rs @@ -0,0 +1,270 @@ +//! 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::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)?; + let blocked = entry + .requires + .iter() + .any(|need| reports[need].result != Outcome::Success); + 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"); + let working = match working.strip_prefix('~') { + Some(rest) => home.join(rest.trim_start_matches('/')), + None => bail!( + "job `{}`: mockci runs steps on the host, so `working_directory` must start with `~`, got `{working}`", + entry.job + ), + }; + 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}"), + ); + } + 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"), + bin: dir.join("bin"), + env, + continuation: continuation.as_deref_mut(), + }; + 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)) +} 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..f97ff0c --- /dev/null +++ b/crates/mockci/src/circleci/steps.rs @@ -0,0 +1,147 @@ +//! 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.resolve_dir(&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))?; + } + 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.env, + working_directory: &job.working_directory, + home: &job.home, + 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, + home: &job.home, + } +} + +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 = match cache::render_keys(&keys, &template_context(job)) { + Ok(keys) => keys, + Err(error) => return Ok((name, StepResult::failed(format!("{error:#}")))), + }; + 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.home, &job.working_directory)) + .collect::>>()?; + let name = optional_scalar(&settings, "name")?.unwrap_or_else(|| "Saving cache".into()); + let key = match template::render(&key, &template_context(job)) { + Ok(key) => key, + Err(error) => return Ok((name, StepResult::failed(format!("{error:#}")))), + }; + 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..869d3f7 --- /dev/null +++ b/crates/mockci/src/circleci/template.rs @@ -0,0 +1,59 @@ +//! Cache key templates: `{{ checksum "file" }}`, `{{ .Branch }}`, `{{ .Revision }}`, +//! `{{ .Environment.NAME }}` and `{{ epoch }}`. Anything else is an error. + +use anyhow::{Context as _, Result, bail}; +use base64::Engine; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::Path; + +pub struct Context<'a> { + pub branch: &'a str, + pub revision: &'a str, + pub env: &'a BTreeMap, + pub working_directory: &'a Path, + pub home: &'a Path, + /// 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 = match file.strip_prefix("~/") { + Some(rest) => ctx.home.join(rest), + None if file.starts_with('/') => { + bail!( + "mockci runs steps on the host, so it can't checksum the absolute path `{file}`" + ) + } + None => ctx.working_directory.join(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 Ok(ctx.env.get(name).cloned().unwrap_or_default()); + } + 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..bb9a4f7 --- /dev/null +++ b/crates/mockci/src/circleci/workflow_config.rs @@ -0,0 +1,73 @@ +//! A workflow in a CircleCI config: its `when` and its jobs with `requires`, `name` and branch +//! filters. + +use super::config::{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(names)) => names.iter().map(scalar).collect::>()?, + Some(other) => bail!("`requires` must be a list of job names, 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)?]), + } +} 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 7db0fb0..011bd7c 100644 --- a/internal_docs/DIRECTION.md +++ b/internal_docs/DIRECTION.md @@ -380,7 +380,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..27affed 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. @@ -47,6 +47,43 @@ 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 (a job whose required job didn't succeed is blocked and reported as + skipped), branch `only` and `ignore` filters with exact names, `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 the working directory defaults to `~/project` inside it. 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 }}`. + +Steps run on the host, so mockci refuses what would touch it: an absolute cache path, `checksum` or step directory, and +a `working_directory` that doesn't start with `~`. Config that writes to `/tmp` on the host can't run safely. 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 job requiring one its branch filters leave out. 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 +107,7 @@ 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, and the 6-hour limit on continuing. 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 8de1a8a..fbd3c17 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -106,10 +106,13 @@ 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`, `circleci step halt`, the project-wide cache (prefix keys newest first, + immutable, gone after 15 days), setup workflows that continue once with checked parameters, and `finish`. - `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..a843041 --- /dev/null +++ b/tests/mockci_circleci.rs @@ -0,0 +1,215 @@ +//! 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::{log, push_to, 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}"); +} + +/// One job that restores `keys`, prints what it found, and saves `stored` under `save_key`. +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] +"# + ) +} + +#[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}" + ); +} + +#[test] +fn what_mockci_cant_model_is_an_error() { + let cases = [ + ( + "version: 2.1\nexecutors: {}\n", + "unknown top-level key `executors`", + ), + ( + "version: 2.1\norbs:\n node: circleci/node@1.0.0\n", + "mockci runs only", + ), + ( + &cache_config("['a']", "a") + .replace("cat lock", "echo value") + .replace("[~/stored]", "[/tmp/stored]"), + "absolute path `/tmp/stored`", + ), + ]; + for (config, expected) in cases { + let (repo, sha) = repo_with(config); + let mut sim = Simulator::new(repo.path()).unwrap(); + let error = sim + .run_circleci(&push_to("main", &sha)) + .map(|report| report.to_string()) + .unwrap_err(); + assert!(format!("{error:#}").contains(expected), "{error:#}"); + } +} 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/support/circleci.rs b/tests/support/circleci.rs new file mode 100644 index 0000000..821f9bf --- /dev/null +++ b/tests/support/circleci.rs @@ -0,0 +1,35 @@ +//! 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() +} 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; From 596a3a67a485be230057dd7f783f69d426388737 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 15:54:12 +1300 Subject: [PATCH 2/6] mockci CircleCI: requires with statuses, filtered requirements ignored, a /tmp per job From CircleCI's configuration reference: - `requires` can name statuses: `build: failed`, `build: [success, failed]`, `build: terminal` (success, failed, canceled, unauthorized, not_run). A blocked job counts as not_run. (b)'s gate needs this to run when a job fails. - "If filters stop a dependency from running, CircleCI ignores them as dependencies for other jobs." mockci errored instead; now it ignores them. - restore_cache puts files back where they were saved from, so markers that pass between jobs with different images belong in /tmp. Each job gets its own /tmp, which steps reach through TMPDIR; cache paths, checksum files and step directories under /tmp/ resolve to it. --- crates/mockci/src/circleci/cache.rs | 59 +++++++++----- crates/mockci/src/circleci/config.rs | 10 ++- crates/mockci/src/circleci/job.rs | 24 ++++-- crates/mockci/src/circleci/order.rs | 20 +++-- crates/mockci/src/circleci/pipeline.rs | 20 ++++- crates/mockci/src/circleci/steps.rs | 13 ++- crates/mockci/src/circleci/template.rs | 3 + crates/mockci/src/circleci/workflow_config.rs | 37 ++++++++- internal_docs/MOCK_CI.md | 29 ++++--- internal_docs/STATUS.md | 5 +- tests/mockci_circleci.rs | 81 ++++++++++++++++++- 11 files changed, 239 insertions(+), 62 deletions(-) diff --git a/crates/mockci/src/circleci/cache.rs b/crates/mockci/src/circleci/cache.rs index 066baba..581b0bd 100644 --- a/crates/mockci/src/circleci/cache.rs +++ b/crates/mockci/src/circleci/cache.rs @@ -19,13 +19,36 @@ pub const SCOPE: &str = "circleci-project"; const VERSION: &str = "circleci"; pub const EXPIRY_SECONDS: i64 = 15 * 24 * 60 * 60; +/// Where a job's paths resolve: its home, its own `/tmp` and its working directory. +pub struct JobDirs<'a> { + pub home: &'a Path, + pub tmp: &'a Path, + pub working_directory: &'a Path, +} + +impl JobDirs<'_> { + /// 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. + 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() + ) + } +} + pub struct Cache<'a> { pub db: &'a Db, pub blobs: &'a Path, pub job_row: i64, pub now: i64, - /// The job's home directory: saved paths are stored relative to it. - pub home: &'a Path, + pub dirs: JobDirs<'a>, } impl Cache<'_> { @@ -43,7 +66,7 @@ impl Cache<'_> { for (index, path) in manifest.lines().enumerate() { let stored = dir.join(index.to_string()); if stored.exists() { - copy_tree(&stored, &self.home.join(path))?; + copy_tree(&stored, &resolve_path(path, &self.dirs)?)?; } } self.record("restore", key, Some(&entry.key), "hit")?; @@ -68,18 +91,9 @@ impl Cache<'_> { "Skipping cache generation, cache already exists for key: {key}" )); } - let relative = paths + let logical = paths .iter() - .map(|path| { - path.strip_prefix(self.home) - .map(Path::to_path_buf) - .map_err(|_| { - anyhow::anyhow!( - "mockci caches only paths under the job's home directory, got {}", - path.display() - ) - }) - }) + .map(|path| self.dirs.logical(path)) .collect::>>()?; if !paths.iter().any(|path| path.exists()) { self.record("save", key, None, "no-files")?; @@ -89,8 +103,8 @@ impl Cache<'_> { let dir = self.blob_dir(id); std::fs::create_dir_all(&dir)?; let mut manifest = String::new(); - for (index, (path, relative)) in paths.iter().zip(&relative).enumerate() { - manifest.push_str(&format!("{}\n", relative.display())); + 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()))?; } @@ -118,9 +132,11 @@ impl Cache<'_> { } } -/// A cache path as the job would see it: `~/x` under its home, `x` under its working -/// directory. Absolute paths would reach the host, so they're errors. -pub fn resolve_path(path: &str, home: &Path, working_directory: &Path) -> Result { +/// A cache path as the job would see it: `~/x` under its home, `/tmp/x` in its own `/tmp`, +/// `x` under its working directory. Other absolute paths would reach the host, so they're +/// errors. +pub fn resolve_path(path: &str, dirs: &JobDirs) -> Result { + let (home, tmp, working_directory) = (dirs.home, dirs.tmp, dirs.working_directory); if path.contains(['*', '?', '[']) { bail!("mockci doesn't model glob patterns in cache paths, got `{path}`"); } @@ -133,9 +149,12 @@ pub fn resolve_path(path: &str, home: &Path, working_directory: &Path) -> Result if path == "~" { return Ok(home.to_path_buf()); } + if let Some(rest) = path.strip_prefix("/tmp/") { + return Ok(tmp.join(rest)); + } if path.starts_with('/') { bail!( - "mockci runs steps on the host, so it can't cache the absolute path `{path}`: use a path under `~` or the working directory" + "mockci runs steps on the host, so it can't cache the absolute path `{path}`: use a path under `~`, `/tmp` or the working directory" ); } Ok(working_directory.join(path)) diff --git a/crates/mockci/src/circleci/config.rs b/crates/mockci/src/circleci/config.rs index 65fd33b..e4afe27 100644 --- a/crates/mockci/src/circleci/config.rs +++ b/crates/mockci/src/circleci/config.rs @@ -48,13 +48,21 @@ pub struct Workflow { 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 requires: Vec, pub branches_only: Vec, pub branches_ignore: Vec, } diff --git a/crates/mockci/src/circleci/job.rs b/crates/mockci/src/circleci/job.rs index 7f4a4e9..4eb71f7 100644 --- a/crates/mockci/src/circleci/job.rs +++ b/crates/mockci/src/circleci/job.rs @@ -28,7 +28,11 @@ pub struct JobRun<'a> { 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, @@ -68,7 +72,13 @@ impl JobRun<'_> { /// 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.bin] { + 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(), "")?; @@ -209,13 +219,14 @@ impl JobRun<'_> { .envs(env) .env("HOME", &self.home) .env("PATH", path.join(":")) - .env("TMPDIR", &self.temp) + .env("TMPDIR", &self.tmp) .env("BASH_ENV", self.bash_env()); command } - /// A directory as a step names it: `~/x` under the job's home, `x` under the working - /// directory. Absolute paths would reach the host, so they're errors. + /// A directory as a step names it: `~/x` under the job's home, `/tmp/x` in its own `/tmp`, + /// `x` under the working directory. Other absolute paths would reach the host, so they're + /// errors. pub fn resolve_dir(&self, dir: &str) -> Result { if let Some(rest) = dir.strip_prefix("~/") { return Ok(self.home.join(rest)); @@ -223,9 +234,12 @@ impl JobRun<'_> { if dir == "~" { return Ok(self.home.clone()); } + if let Some(rest) = dir.strip_prefix("/tmp/") { + return Ok(self.tmp.join(rest)); + } if dir.starts_with('/') { bail!( - "mockci runs steps on the host, so it can't use the absolute directory `{dir}`: use `~/...`" + "mockci runs steps on the host, so it can't use the absolute directory `{dir}`: use `~/...` or `/tmp/...`" ); } Ok(self.working_directory.join(dir)) diff --git a/crates/mockci/src/circleci/order.rs b/crates/mockci/src/circleci/order.rs index 065a80c..934f5a3 100644 --- a/crates/mockci/src/circleci/order.rs +++ b/crates/mockci/src/circleci/order.rs @@ -6,7 +6,8 @@ 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). +/// among jobs ready at the same time). A required job the filters leave out is ignored, as +/// CircleCI ignores it. pub fn order<'a>(workflow: &'a Workflow, branch: &str) -> Result> { let mut by_name = BTreeMap::new(); for entry in &workflow.jobs { @@ -22,16 +23,11 @@ pub fn order<'a>(workflow: &'a Workflow, branch: &str) -> Result(workflow: &'a Workflow, branch: &str) -> Result = BTreeMap::new(); for entry in order(workflow, &branch)? { let job_row = self.db.start_job(run_id, &entry.name)?; - let blocked = entry - .requires - .iter() - .any(|need| reports[need].result != Outcome::Success); + // 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(), @@ -178,6 +180,7 @@ impl Simulator { home, working_directory: working, temp: dir.join("temp"), + tmp: dir.join("tmp"), bin: dir.join("bin"), env, continuation: continuation.as_deref_mut(), @@ -268,3 +271,12 @@ fn pipeline_values( } 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/steps.rs b/crates/mockci/src/circleci/steps.rs index f97ff0c..9d8ae79 100644 --- a/crates/mockci/src/circleci/steps.rs +++ b/crates/mockci/src/circleci/steps.rs @@ -1,7 +1,7 @@ //! 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::cache::{self, Cache, JobDirs}; use super::continuation; use super::job::{JobRun, StepResult}; use super::params::Expanded; @@ -83,6 +83,7 @@ fn template_context<'a>(job: &'a JobRun) -> template::Context<'a> { env: &job.env, working_directory: &job.working_directory, home: &job.home, + tmp: &job.tmp, epoch: job.sim.now, } } @@ -93,7 +94,15 @@ fn cache<'a>(job: &'a JobRun) -> Cache<'a> { blobs: &job.sim.cache_dir, job_row: job.job_row, now: job.sim.now, + dirs: dirs(job), + } +} + +fn dirs<'a>(job: &'a JobRun) -> JobDirs<'a> { + JobDirs { home: &job.home, + tmp: &job.tmp, + working_directory: &job.working_directory, } } @@ -136,7 +145,7 @@ fn save_cache(job: &JobRun, body: &Yaml) -> Result<(String, StepResult)> { }; let paths = paths .iter() - .map(|path| cache::resolve_path(&scalar(path)?, &job.home, &job.working_directory)) + .map(|path| cache::resolve_path(&scalar(path)?, &dirs(job))) .collect::>>()?; let name = optional_scalar(&settings, "name")?.unwrap_or_else(|| "Saving cache".into()); let key = match template::render(&key, &template_context(job)) { diff --git a/crates/mockci/src/circleci/template.rs b/crates/mockci/src/circleci/template.rs index 869d3f7..756531d 100644 --- a/crates/mockci/src/circleci/template.rs +++ b/crates/mockci/src/circleci/template.rs @@ -13,6 +13,8 @@ pub struct Context<'a> { pub env: &'a BTreeMap, pub working_directory: &'a Path, pub home: &'a Path, + /// The job's own `/tmp`. + pub tmp: &'a Path, /// Seconds since the epoch, for `{{ epoch }}`. pub epoch: i64, } @@ -36,6 +38,7 @@ fn expand(expression: &str, ctx: &Context) -> Result { let file = argument.trim().trim_matches('"'); let path = match file.strip_prefix("~/") { Some(rest) => ctx.home.join(rest), + None if file.starts_with("/tmp/") => ctx.tmp.join(&file[5..]), None if file.starts_with('/') => { bail!( "mockci runs steps on the host, so it can't checksum the absolute path `{file}`" diff --git a/crates/mockci/src/circleci/workflow_config.rs b/crates/mockci/src/circleci/workflow_config.rs index bb9a4f7..132b220 100644 --- a/crates/mockci/src/circleci/workflow_config.rs +++ b/crates/mockci/src/circleci/workflow_config.rs @@ -1,7 +1,7 @@ //! A workflow in a CircleCI config: its `when` and its jobs with `requires`, `name` and branch //! filters. -use super::config::{Workflow, WorkflowJob, as_mapping}; +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; @@ -41,8 +41,8 @@ fn workflow_job(job: String, settings: &Yaml) -> Result { check_keys(settings, &["requires", "name", "filters"], "workflow job")?; let requires = match settings.get("requires") { None => Vec::new(), - Some(Yaml::Sequence(names)) => names.iter().map(scalar).collect::>()?, - Some(other) => bail!("`requires` must be a list of job names, found {other:?}"), + 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") { @@ -71,3 +71,34 @@ fn string_list(value: Option<&Yaml>) -> Result> { 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/internal_docs/MOCK_CI.md b/internal_docs/MOCK_CI.md index 27affed..f0af378 100644 --- a/internal_docs/MOCK_CI.md +++ b/internal_docs/MOCK_CI.md @@ -60,14 +60,18 @@ and the parameters they saw. It shares the simulator's repository, clock, record `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 (a job whose required job didn't succeed is blocked and reported as - skipped), branch `only` and `ignore` filters with exact names, `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 the working directory defaults to `~/project` inside it. A job sees +- **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. 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. @@ -76,11 +80,12 @@ and the parameters they saw. It shares the simulator's repository, clock, record 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 }}`. -Steps run on the host, so mockci refuses what would touch it: an absolute cache path, `checksum` or step directory, and -a `working_directory` that doesn't start with `~`. Config that writes to `/tmp` on the host can't run safely. It also +Steps run on the host, so mockci refuses what would touch it: an absolute cache path, `checksum` or step directory +outside `/tmp`, and a `working_directory` that doesn't 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. 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 job requiring one its branch filters leave out. The `docker` image is checked but not used. +regular expressions in branch filters, logic statements in `when` and a `circleci` subcommand other than `step halt`. +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. diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index fbd3c17..c7d81a7 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -111,8 +111,9 @@ What the code does today, checked against the code in December 2026. Where cigen 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`, `circleci step halt`, the project-wide cache (prefix keys newest first, - immutable, gone after 15 days), setup workflows that continue once with checked parameters, and `finish`. + `BASH_ENV`, commands, `when`, `requires` with statuses, filtered requirements ignored, `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/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 index a843041..d420e2e 100644 --- a/tests/mockci_circleci.rs +++ b/tests/mockci_circleci.rs @@ -199,8 +199,8 @@ fn what_mockci_cant_model_is_an_error() { ( &cache_config("['a']", "a") .replace("cat lock", "echo value") - .replace("[~/stored]", "[/tmp/stored]"), - "absolute path `/tmp/stored`", + .replace("[~/stored]", "[/var/stored]"), + "absolute path `/var/stored`", ), ]; for (config, expected) in cases { @@ -213,3 +213,80 @@ fn what_mockci_cant_model_is_an_error() { assert!(format!("{error:#}").contains(expected), "{error:#}"); } } + +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 }] } + - pass: { name: main-only, filters: { branches: { only: main } } } + - pass: { name: needs-main-only, requires: [main-only] } +"#; + +#[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 a_required_job_the_branch_filters_leave_out_is_ignored() { + let (repo, sha) = repo_with(REQUIRES); + let mut sim = Simulator::new(repo.path()).unwrap(); + let report = run(&mut sim, "feature", &sha); + assert!( + !report.workflows["ci"].jobs.contains_key("main-only"), + "{report}" + ); + assert!(report.ran("needs-main-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}"); +} From 05a158fb56ff9c4e3fbe970850a7f8f012d5e4d1 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 16:00:47 +1300 Subject: [PATCH 3/6] =?UTF-8?q?mockci=20CircleCI:=20fixes=20from=20review?= =?UTF-8?q?=20=E2=80=94=20paths,=20.Environment,=20documented=20gaps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. `{{ .Environment.X }}` 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 (a constant key), so mockci refuses it instead of rendering a varying one. Template errors now stop the run instead of failing the step. A test checks generated CircleCI config uses no .Environment. 2, 3. Every path a config names resolves through src/circleci/paths.rs: cache paths, checksum files, checkout and step directories, the job's working_directory, and the continuation's configuration_path and parameters file. It refuses `..` and absolute paths outside /tmp, so nothing reaches a host file. tests/mockci_circleci_strict.rs probes each. 4, 5. Documented under "Not modelled yet": jobs ready together run one at a time and see each other's caches; the continue API's "Conflicting pipeline parameters" refusal. --- crates/mockci/src/circleci/cache.rs | 49 +------ crates/mockci/src/circleci/continuation.rs | 16 ++- crates/mockci/src/circleci/job.rs | 29 ++-- crates/mockci/src/circleci/mod.rs | 1 + crates/mockci/src/circleci/paths.rs | 85 ++++++++++++ crates/mockci/src/circleci/pipeline.rs | 19 ++- crates/mockci/src/circleci/steps.rs | 33 ++--- crates/mockci/src/circleci/template.rs | 25 ++-- internal_docs/MOCK_CI.md | 16 ++- internal_docs/STATUS.md | 3 +- tests/mockci_circleci.rs | 58 +------- tests/mockci_circleci_strict.rs | 150 +++++++++++++++++++++ tests/support/circleci.rs | 27 ++++ 13 files changed, 332 insertions(+), 179 deletions(-) create mode 100644 crates/mockci/src/circleci/paths.rs create mode 100644 tests/mockci_circleci_strict.rs diff --git a/crates/mockci/src/circleci/cache.rs b/crates/mockci/src/circleci/cache.rs index 581b0bd..9b2d481 100644 --- a/crates/mockci/src/circleci/cache.rs +++ b/crates/mockci/src/circleci/cache.rs @@ -8,6 +8,7 @@ //! - 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}; @@ -19,30 +20,6 @@ pub const SCOPE: &str = "circleci-project"; const VERSION: &str = "circleci"; pub const EXPIRY_SECONDS: i64 = 15 * 24 * 60 * 60; -/// Where a job's paths resolve: its home, its own `/tmp` and its working directory. -pub struct JobDirs<'a> { - pub home: &'a Path, - pub tmp: &'a Path, - pub working_directory: &'a Path, -} - -impl JobDirs<'_> { - /// 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. - 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() - ) - } -} - pub struct Cache<'a> { pub db: &'a Db, pub blobs: &'a Path, @@ -132,32 +109,12 @@ impl Cache<'_> { } } -/// A cache path as the job would see it: `~/x` under its home, `/tmp/x` in its own `/tmp`, -/// `x` under its working directory. Other absolute paths would reach the host, so they're -/// errors. +/// A cache path as the job would see it (`paths.rs`). pub fn resolve_path(path: &str, dirs: &JobDirs) -> Result { - let (home, tmp, working_directory) = (dirs.home, dirs.tmp, dirs.working_directory); if path.contains(['*', '?', '[']) { bail!("mockci doesn't model glob patterns in cache paths, got `{path}`"); } - if path.split('/').any(|part| part == "..") { - bail!("mockci doesn't model `..` in cache paths, got `{path}`"); - } - if let Some(rest) = path.strip_prefix("~/") { - return Ok(home.join(rest)); - } - if path == "~" { - return Ok(home.to_path_buf()); - } - if let Some(rest) = path.strip_prefix("/tmp/") { - return Ok(tmp.join(rest)); - } - if path.starts_with('/') { - bail!( - "mockci runs steps on the host, so it can't cache the absolute path `{path}`: use a path under `~`, `/tmp` or the working directory" - ); - } - Ok(working_directory.join(path)) + dirs.resolve(path, "the cache path") } /// The keys of a `restore_cache` step (`key` or `keys`), rendered. diff --git a/crates/mockci/src/circleci/continuation.rs b/crates/mockci/src/circleci/continuation.rs index ade2bba..1a61cca 100644 --- a/crates/mockci/src/circleci/continuation.rs +++ b/crates/mockci/src/circleci/continuation.rs @@ -92,21 +92,23 @@ fn continue_pipeline( if job.continuation.is_none() { return Ok(StepResult::failed(NO_KEY)); } - let config_path = job - .working_directory - .join(¶meters["configuration_path"]); + 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 file = job.working_directory.join(raw); - let text = if file.is_file() { - std::fs::read_to_string(&file)? - } else { + 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")); diff --git a/crates/mockci/src/circleci/job.rs b/crates/mockci/src/circleci/job.rs index 4eb71f7..15918b4 100644 --- a/crates/mockci/src/circleci/job.rs +++ b/crates/mockci/src/circleci/job.rs @@ -2,6 +2,7 @@ //! `circleci step halt`. use super::params::Expanded; +use super::paths::JobDirs; use super::steps; use crate::event::Event; use crate::report::{JobReport, Outcome, StepReport}; @@ -36,6 +37,9 @@ pub struct JobRun<'a> { /// 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>, } @@ -174,7 +178,7 @@ impl JobRun<'_> { 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.resolve_dir(&dir)?, + Some(dir) => self.dirs().resolve(&dir, "the step's working_directory")?, None => self.working_directory.clone(), }; std::fs::create_dir_all(&cwd)?; @@ -224,24 +228,11 @@ impl JobRun<'_> { command } - /// A directory as a step names it: `~/x` under the job's home, `/tmp/x` in its own `/tmp`, - /// `x` under the working directory. Other absolute paths would reach the host, so they're - /// errors. - pub fn resolve_dir(&self, dir: &str) -> Result { - if let Some(rest) = dir.strip_prefix("~/") { - return Ok(self.home.join(rest)); + pub fn dirs(&self) -> JobDirs<'_> { + JobDirs { + home: &self.home, + tmp: &self.tmp, + working_directory: &self.working_directory, } - if dir == "~" { - return Ok(self.home.clone()); - } - if let Some(rest) = dir.strip_prefix("/tmp/") { - return Ok(self.tmp.join(rest)); - } - if dir.starts_with('/') { - bail!( - "mockci runs steps on the host, so it can't use the absolute directory `{dir}`: use `~/...` or `/tmp/...`" - ); - } - Ok(self.working_directory.join(dir)) } } diff --git a/crates/mockci/src/circleci/mod.rs b/crates/mockci/src/circleci/mod.rs index d176809..1621524 100644 --- a/crates/mockci/src/circleci/mod.rs +++ b/crates/mockci/src/circleci/mod.rs @@ -8,6 +8,7 @@ mod continuation; mod job; mod order; mod params; +mod paths; mod pipeline; mod report; mod steps; diff --git a/crates/mockci/src/circleci/paths.rs b/crates/mockci/src/circleci/paths.rs new file mode 100644 index 0000000..24daf47 --- /dev/null +++ b/crates/mockci/src/circleci/paths.rs @@ -0,0 +1,85 @@ +//! 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. + +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 == "~" { + return Ok(self.home.to_path_buf()); + } + if let Some(rest) = path.strip_prefix("~/") { + return Ok(self.home.join(rest)); + } + if let Some(rest) = path.strip_prefix("/tmp/") { + return Ok(self.tmp.join(rest)); + } + 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" + ); + } + Ok(self.working_directory.join(path)) + } + + /// 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() + ) + } +} + +#[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}"); + } + } +} diff --git a/crates/mockci/src/circleci/pipeline.rs b/crates/mockci/src/circleci/pipeline.rs index e0e5f58..922ca95 100644 --- a/crates/mockci/src/circleci/pipeline.rs +++ b/crates/mockci/src/circleci/pipeline.rs @@ -6,6 +6,7 @@ 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}; @@ -151,13 +152,19 @@ impl Simulator { 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"); - let working = match working.strip_prefix('~') { - Some(rest) => home.join(rest.trim_start_matches('/')), - None => bail!( + 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(), @@ -169,6 +176,7 @@ impl Simulator { format!("mockci-continuation-{run_id}"), ); } + let template_env = env.clone(); for (key, value) in &job.environment { env.insert(key.clone(), params::substitute(value, values)?); } @@ -180,9 +188,10 @@ impl Simulator { home, working_directory: working, temp: dir.join("temp"), - tmp: dir.join("tmp"), + tmp, bin: dir.join("bin"), env, + template_env, continuation: continuation.as_deref_mut(), }; run.run(&entry.name, &steps)? diff --git a/crates/mockci/src/circleci/steps.rs b/crates/mockci/src/circleci/steps.rs index 9d8ae79..53c326d 100644 --- a/crates/mockci/src/circleci/steps.rs +++ b/crates/mockci/src/circleci/steps.rs @@ -1,7 +1,7 @@ //! The built-in steps: `checkout`, `run`, `restore_cache` and `save_cache`, and the //! continuation orb's commands (`continuation.rs`). -use super::cache::{self, Cache, JobDirs}; +use super::cache::{self, Cache}; use super::continuation; use super::job::{JobRun, StepResult}; use super::params::Expanded; @@ -47,7 +47,7 @@ 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.resolve_dir(&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() { @@ -80,10 +80,8 @@ fn template_context<'a>(job: &'a JobRun) -> template::Context<'a> { template::Context { branch: &job.branch, revision: job.event.sha(), - env: &job.env, - working_directory: &job.working_directory, - home: &job.home, - tmp: &job.tmp, + env: &job.template_env, + dirs: job.dirs(), epoch: job.sim.now, } } @@ -94,15 +92,7 @@ fn cache<'a>(job: &'a JobRun) -> Cache<'a> { blobs: &job.sim.cache_dir, job_row: job.job_row, now: job.sim.now, - dirs: dirs(job), - } -} - -fn dirs<'a>(job: &'a JobRun) -> JobDirs<'a> { - JobDirs { - home: &job.home, - tmp: &job.tmp, - working_directory: &job.working_directory, + dirs: job.dirs(), } } @@ -121,10 +111,7 @@ fn restore_cache(job: &JobRun, body: &Yaml) -> Result<(String, StepResult)> { _ => 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 = match cache::render_keys(&keys, &template_context(job)) { - Ok(keys) => keys, - Err(error) => return Ok((name, StepResult::failed(format!("{error:#}")))), - }; + 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(" ")), @@ -145,12 +132,10 @@ fn save_cache(job: &JobRun, body: &Yaml) -> Result<(String, StepResult)> { }; let paths = paths .iter() - .map(|path| cache::resolve_path(&scalar(path)?, &dirs(job))) + .map(|path| cache::resolve_path(&scalar(path)?, &job.dirs())) .collect::>>()?; let name = optional_scalar(&settings, "name")?.unwrap_or_else(|| "Saving cache".into()); - let key = match template::render(&key, &template_context(job)) { - Ok(key) => key, - Err(error) => return Ok((name, StepResult::failed(format!("{error:#}")))), - }; + 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 index 756531d..34b043c 100644 --- a/crates/mockci/src/circleci/template.rs +++ b/crates/mockci/src/circleci/template.rs @@ -1,20 +1,18 @@ //! 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; -use std::path::Path; 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 working_directory: &'a Path, - pub home: &'a Path, - /// The job's own `/tmp`. - pub tmp: &'a Path, + pub dirs: JobDirs<'a>, /// Seconds since the epoch, for `{{ epoch }}`. pub epoch: i64, } @@ -36,22 +34,17 @@ pub fn render(template: &str, ctx: &Context) -> Result { fn expand(expression: &str, ctx: &Context) -> Result { if let Some(argument) = expression.strip_prefix("checksum ") { let file = argument.trim().trim_matches('"'); - let path = match file.strip_prefix("~/") { - Some(rest) => ctx.home.join(rest), - None if file.starts_with("/tmp/") => ctx.tmp.join(&file[5..]), - None if file.starts_with('/') => { - bail!( - "mockci runs steps on the host, so it can't checksum the absolute path `{file}`" - ) - } - None => ctx.working_directory.join(file), - }; + 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 Ok(ctx.env.get(name).cloned().unwrap_or_default()); + 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(), diff --git a/internal_docs/MOCK_CI.md b/internal_docs/MOCK_CI.md index f0af378..d32dde8 100644 --- a/internal_docs/MOCK_CI.md +++ b/internal_docs/MOCK_CI.md @@ -79,12 +79,17 @@ and the parameters they saw. It shares the simulator's repository, clock, record (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 mockci refuses what would touch it: an absolute cache path, `checksum` or step directory -outside `/tmp`, and a `working_directory` that doesn't start with `~`. A step that writes to a literal `/tmp` path +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 any `..` and any absolute path outside `/tmp`. 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. 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` and a `circleci` subcommand other than `step halt`. +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. @@ -114,5 +119,8 @@ put back, four of the scenarios fail. 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, and the 6-hour limit on continuing. A conformance job that runs the same scenarios on GitHub Actions and Blacksmith, to keep +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 c7d81a7..4400b02 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -113,7 +113,8 @@ What the code does today, checked against the code in December 2026. Where cigen - `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, `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`. + 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/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 index d420e2e..73a617d 100644 --- a/tests/mockci_circleci.rs +++ b/tests/mockci_circleci.rs @@ -4,7 +4,7 @@ mod support; use cigen_mockci::{Outcome, Simulator}; -use support::circleci::{log, push_to, repo_with, run}; +use support::circleci::{cache_config, log, repo_with, run}; const JOBS: &str = r#"version: 2.1 commands: @@ -97,33 +97,6 @@ fn circleci_step_halt_ends_the_job_as_a_success() { assert_eq!(job.steps.len(), 1, "{report}"); } -/// One job that restores `keys`, prints what it found, and saves `stored` under `save_key`. -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] -"# - ) -} - #[test] fn the_cache_is_shared_across_branches_immutable_and_gone_after_15_days() { let config = cache_config( @@ -185,35 +158,6 @@ fn restore_keys_match_as_prefixes_in_order_newest_first() { ); } -#[test] -fn what_mockci_cant_model_is_an_error() { - let cases = [ - ( - "version: 2.1\nexecutors: {}\n", - "unknown top-level key `executors`", - ), - ( - "version: 2.1\norbs:\n node: circleci/node@1.0.0\n", - "mockci runs only", - ), - ( - &cache_config("['a']", "a") - .replace("cat lock", "echo value") - .replace("[~/stored]", "[/var/stored]"), - "absolute path `/var/stored`", - ), - ]; - for (config, expected) in cases { - let (repo, sha) = repo_with(config); - let mut sim = Simulator::new(repo.path()).unwrap(); - let error = sim - .run_circleci(&push_to("main", &sha)) - .map(|report| report.to_string()) - .unwrap_err(); - assert!(format!("{error:#}").contains(expected), "{error:#}"); - } -} - const REQUIRES: &str = r#"version: 2.1 jobs: pass: diff --git a/tests/mockci_circleci_strict.rs b/tests/mockci_circleci_strict.rs new file mode 100644 index 0000000..41827bf --- /dev/null +++ b/tests/mockci_circleci_strict.rs @@ -0,0 +1,150 @@ +//! 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()); + } + } +} diff --git a/tests/support/circleci.rs b/tests/support/circleci.rs index 821f9bf..f3c081a 100644 --- a/tests/support/circleci.rs +++ b/tests/support/circleci.rs @@ -33,3 +33,30 @@ pub fn log(report: &PipelineReport, job: &str) -> String { .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] +"# + ) +} From e0f57ae7adce6acc75fcdb257ea7985999c75004 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 16:18:47 +1300 Subject: [PATCH 4/6] =?UTF-8?q?mockci=20CircleCI:=20fixes=20from=20re-revi?= =?UTF-8?q?ew=20=E2=80=94=20`//`=20paths,=20all=20requirements=20filtered,?= =?UTF-8?q?=20host=20/tmp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A. A doubled slash escaped every guard: `~//etc/hosts` stripped to an absolute path that Path::join used as is. paths.rs refuses `//`, and checks that the joined path stays inside its base. The unit test lists `~//etc/passwd`, `/tmp//etc/passwd` and `a//b`. B. "If filters exclude all dependencies of a job, that job doesn't execute either": order.rs leaves such a job out, and carries on to the jobs that lose all their requirements that way. A job with one requirement left still runs. C. save_cache of a /tmp path that the job's /tmp lacks but the host's has is an error pointing at ${TMPDIR:-/tmp}, instead of a quiet "No files to save". --- crates/mockci/src/circleci/cache.rs | 7 +++++++ crates/mockci/src/circleci/order.rs | 26 ++++++++++++++++++++++++-- crates/mockci/src/circleci/paths.rs | 27 +++++++++++++++++---------- internal_docs/MOCK_CI.md | 17 +++++++++-------- internal_docs/STATUS.md | 8 ++++---- tests/mockci_circleci.rs | 14 -------------- tests/mockci_circleci_strict.rs | 27 +++++++++++++++++++++++++++ 7 files changed, 88 insertions(+), 38 deletions(-) diff --git a/crates/mockci/src/circleci/cache.rs b/crates/mockci/src/circleci/cache.rs index 9b2d481..f6bab8f 100644 --- a/crates/mockci/src/circleci/cache.rs +++ b/crates/mockci/src/circleci/cache.rs @@ -72,6 +72,13 @@ impl Cache<'_> { .iter() .map(|path| self.dirs.logical(path)) .collect::>>()?; + for (path, logical) in paths.iter().zip(&logical) { + if logical.starts_with("/tmp/") && !path.exists() && Path::new(logical).exists() { + 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}")); diff --git a/crates/mockci/src/circleci/order.rs b/crates/mockci/src/circleci/order.rs index 934f5a3..b9278ce 100644 --- a/crates/mockci/src/circleci/order.rs +++ b/crates/mockci/src/circleci/order.rs @@ -7,7 +7,8 @@ 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. +/// 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 { @@ -21,7 +22,28 @@ pub fn order<'a>(workflow: &'a Workflow, branch: &str) -> Result = 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!( diff --git a/crates/mockci/src/circleci/paths.rs b/crates/mockci/src/circleci/paths.rs index 24daf47..2fce7d1 100644 --- a/crates/mockci/src/circleci/paths.rs +++ b/crates/mockci/src/circleci/paths.rs @@ -19,21 +19,28 @@ impl JobDirs<'_> { if path.split('/').any(|part| part == "..") { bail!("mockci runs steps on the host, so {what} `{path}` can't use `..`"); } - if path == "~" { - return Ok(self.home.to_path_buf()); + if path.contains("//") { + bail!("mockci runs steps on the host, so {what} `{path}` can't use `//`"); } - if let Some(rest) = path.strip_prefix("~/") { - return Ok(self.home.join(rest)); - } - if let Some(rest) = path.strip_prefix("/tmp/") { - return Ok(self.tmp.join(rest)); - } - if path.starts_with('/') || path.starts_with('~') { + 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) { + bail!("mockci runs steps on the host, so {what} `{path}` must stay inside the job"); } - Ok(self.working_directory.join(path)) + Ok(resolved) } /// How a job names `path`: `~/x` or `/tmp/x`. CircleCI restores a cache to the path it was diff --git a/internal_docs/MOCK_CI.md b/internal_docs/MOCK_CI.md index d32dde8..4d6ee17 100644 --- a/internal_docs/MOCK_CI.md +++ b/internal_docs/MOCK_CI.md @@ -63,7 +63,8 @@ and the parameters they saw. It shares the simulator's repository, clock, record - **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. Branch `only` and `ignore` filters take exact names. Steps: `checkout`, `run` + 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 >>`, @@ -84,13 +85,13 @@ and the parameters they saw. It shares the simulator's repository, clock, record 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 any `..` and any absolute path outside `/tmp`. 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. 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. +(`src/circleci/paths.rs`), which refuses `..`, `//` and any absolute path outside `/tmp`, and checks that the result +stays inside 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 present on the host 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. diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 4400b02..555afe3 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -111,10 +111,10 @@ What the code does today, checked against the code in December 2026. Where cigen 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, `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. + `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/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 index 73a617d..9fa94f4 100644 --- a/tests/mockci_circleci.rs +++ b/tests/mockci_circleci.rs @@ -174,8 +174,6 @@ workflows: - 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 }] } - - pass: { name: main-only, filters: { branches: { only: main } } } - - pass: { name: needs-main-only, requires: [main-only] } "#; #[test] @@ -192,18 +190,6 @@ fn requires_can_name_statuses_and_a_blocked_job_ends_not_run() { assert!(report.ran("not-run-only"), "{report}"); } -#[test] -fn a_required_job_the_branch_filters_leave_out_is_ignored() { - let (repo, sha) = repo_with(REQUIRES); - let mut sim = Simulator::new(repo.path()).unwrap(); - let report = run(&mut sim, "feature", &sha); - assert!( - !report.workflows["ci"].jobs.contains_key("main-only"), - "{report}" - ); - assert!(report.ran("needs-main-only"), "{report}"); -} - #[test] fn each_job_has_its_own_tmp_and_caches_under_it_restore_there() { let config = r#"version: 2.1 diff --git a/tests/mockci_circleci_strict.rs b/tests/mockci_circleci_strict.rs index 41827bf..4e051af 100644 --- a/tests/mockci_circleci_strict.rs +++ b/tests/mockci_circleci_strict.rs @@ -148,3 +148,30 @@ fn generated_circleci_config_uses_no_environment_in_keys() { } } } + +/// 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}"); +} + +/// "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}"); +} From 64fe75cdb66f6a0e7b39ee962e8e3be845f8044e Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 16:54:34 +1300 Subject: [PATCH 5/6] mockci: symlinks cached as symlinks, no restore through a symlink, stale host /tmp not blamed copy_tree recursed forever on a directory symlink (walkdir reports it as not a directory, so it called itself on the same path). It now copies symlinks as symlinks, replaces a symlink at the destination instead of writing through it, and refuses a parent that resolves outside the destination. The CircleCI path guard follows symlinks a step made before checking containment. save_cache blames the host's /tmp only when that path changed after the job started. --- crates/mockci/src/cache.rs | 56 +++++++++-- crates/mockci/src/circleci/cache.rs | 13 ++- crates/mockci/src/circleci/job.rs | 2 + crates/mockci/src/circleci/paths.rs | 43 ++++++++- crates/mockci/src/circleci/pipeline.rs | 1 + crates/mockci/src/circleci/steps.rs | 1 + internal_docs/MOCK_CI.md | 14 +-- internal_docs/STATUS.md | 2 + tests/mockci_circleci_strict.rs | 30 ++++++ tests/mockci_symlinks.rs | 123 +++++++++++++++++++++++++ 10 files changed, 268 insertions(+), 17 deletions(-) create mode 100644 tests/mockci_symlinks.rs diff --git a/crates/mockci/src/cache.rs b/crates/mockci/src/cache.rs index 4a3fbd8..0784dfe 100644 --- a/crates/mockci/src/cache.rs +++ b/crates/mockci/src/cache.rs @@ -162,25 +162,65 @@ impl Cache<'_> { } } -/// Copies a file or a directory tree, replacing files that exist at the destination. +/// Copies a file or a directory tree, replacing files that exist at the destination. Symlinks +/// are copied as symlinks, never followed, and nothing is written through a symlink already at +/// the destination: a restore can't land outside the directory it restores to. pub fn copy_tree(source: &Path, destination: &Path) -> Result<()> { - if source.is_file() { + let metadata = std::fs::symlink_metadata(source) + .with_context(|| format!("reading {}", source.display()))?; + 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)?; + let root = destination + .canonicalize() + .with_context(|| format!("resolving {}", destination.display()))?; + // 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)?); + let parent = target.parent().context("a copied entry has a parent")?; + if !parent.canonicalize()?.starts_with(&root) { + bail!( + "copying {} would write through a symlink to outside {}", + entry.path().display(), + destination.display() + ); + } 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 index f6bab8f..ee5e877 100644 --- a/crates/mockci/src/circleci/cache.rs +++ b/crates/mockci/src/circleci/cache.rs @@ -26,6 +26,9 @@ pub struct Cache<'a> { 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<'_> { @@ -73,7 +76,7 @@ impl Cache<'_> { .map(|path| self.dirs.logical(path)) .collect::>>()?; for (path, logical) in paths.iter().zip(&logical) { - if logical.starts_with("/tmp/") && !path.exists() && Path::new(logical).exists() { + 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}}`" ); @@ -98,6 +101,14 @@ impl Cache<'_> { Ok(format!("Stored cache for key: {key}")) } + /// Whether the host's `path` changed after the job started (a step wrote it), rather than + /// being left there by something else. + fn changed_on_host(&self, path: &str) -> bool { + std::fs::symlink_metadata(path) + .and_then(|metadata| metadata.modified()) + .is_ok_and(|modified| modified >= self.started) + } + fn blob_dir(&self, id: i64) -> PathBuf { self.blobs.join(format!("circleci-{id}")) } diff --git a/crates/mockci/src/circleci/job.rs b/crates/mockci/src/circleci/job.rs index 15918b4..8fd9eb6 100644 --- a/crates/mockci/src/circleci/job.rs +++ b/crates/mockci/src/circleci/job.rs @@ -42,6 +42,8 @@ pub struct JobRun<'a> { 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 { diff --git a/crates/mockci/src/circleci/paths.rs b/crates/mockci/src/circleci/paths.rs index 2fce7d1..29528f7 100644 --- a/crates/mockci/src/circleci/paths.rs +++ b/crates/mockci/src/circleci/paths.rs @@ -1,7 +1,7 @@ //! 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. +//! 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}; @@ -37,7 +37,7 @@ impl JobDirs<'_> { }; 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) { + 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) @@ -59,6 +59,25 @@ impl JobDirs<'_> { } } +/// 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::*; @@ -89,4 +108,24 @@ mod tests { 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 index 922ca95..d7dff07 100644 --- a/crates/mockci/src/circleci/pipeline.rs +++ b/crates/mockci/src/circleci/pipeline.rs @@ -193,6 +193,7 @@ impl Simulator { env, template_env, continuation: continuation.as_deref_mut(), + started: std::time::SystemTime::now(), }; run.run(&entry.name, &steps)? }; diff --git a/crates/mockci/src/circleci/steps.rs b/crates/mockci/src/circleci/steps.rs index 53c326d..5435623 100644 --- a/crates/mockci/src/circleci/steps.rs +++ b/crates/mockci/src/circleci/steps.rs @@ -93,6 +93,7 @@ fn cache<'a>(job: &'a JobRun) -> Cache<'a> { job_row: job.job_row, now: job.sim.now, dirs: job.dirs(), + started: job.started, } } diff --git a/internal_docs/MOCK_CI.md b/internal_docs/MOCK_CI.md index 4d6ee17..7200069 100644 --- a/internal_docs/MOCK_CI.md +++ b/internal_docs/MOCK_CI.md @@ -86,12 +86,14 @@ and the parameters they saw. It shares the simulator's repository, clock, record 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. 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 present on the host 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. +stays inside the job, following any symlink a step made. Caches and artifacts keep symlinks as symlinks, and a restore +never writes through a symlink to outside the directory it restores to. 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 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. diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index 555afe3..ae8aaf2 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -115,6 +115,8 @@ What the code does today, checked against the code in December 2026. Where cigen `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. - `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_strict.rs b/tests/mockci_circleci_strict.rs index 4e051af..474da6c 100644 --- a/tests/mockci_circleci_strict.rs +++ b/tests/mockci_circleci_strict.rs @@ -162,6 +162,36 @@ fn saving_a_tmp_path_a_step_wrote_on_the_host_is_an_error() { 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}"); +} + /// "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] diff --git a/tests/mockci_symlinks.rs b/tests/mockci_symlinks.rs new file mode 100644 index 0000000..776502c --- /dev/null +++ b/tests/mockci_symlinks.rs @@ -0,0 +1,123 @@ +//! 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}"); +} From 5eebf61307a9d98d1a925ffa3c6582fe06509dd3 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 17:20:31 +1300 Subject: [PATCH 6/6] mockci: no restore through a symlink in GitHub mode, artifacts follow links, deep /tmp writes copy_tree takes the root its destination must stay inside (the workspace, the job's home or /tmp, or the cache store), replaces a symlink at the destination, and checks the destination's nearest existing ancestor and each entry's parent against that root, so a GitHub cache restore can't write through `stored -> `. Artifact uploads follow symlinks and leave broken ones out, as upload-artifact's search does (followSymbolicLinks, omitBrokenSymbolicLinks). The host /tmp hint looks at the newest change anywhere under the path. --- crates/mockci/src/actions.rs | 49 ++++++++++----- crates/mockci/src/cache.rs | 51 ++++++++++------ crates/mockci/src/circleci/cache.rs | 24 +++++--- crates/mockci/src/circleci/steps.rs | 2 +- internal_docs/MOCK_CI.md | 22 +++---- internal_docs/STATUS.md | 3 +- tests/mockci_circleci_strict.rs | 22 +++++++ tests/mockci_symlinks.rs | 93 +++++++++++++++++++++++++++++ 8 files changed, 215 insertions(+), 51 deletions(-) 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 0784dfe..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,12 +162,39 @@ impl Cache<'_> { } } -/// Copies a file or a directory tree, replacing files that exist at the destination. Symlinks -/// are copied as symlinks, never followed, and nothing is written through a symlink already at -/// the destination: a restore can't land outside the directory it restores to. -pub fn copy_tree(source: &Path, destination: &Path) -> Result<()> { +/// 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)?; @@ -175,22 +202,12 @@ pub fn copy_tree(source: &Path, destination: &Path) -> Result<()> { return copy_entry(source, destination, metadata.file_type().is_symlink()); } std::fs::create_dir_all(destination)?; - let root = destination - .canonicalize() - .with_context(|| format!("resolving {}", destination.display()))?; // 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)?); - let parent = target.parent().context("a copied entry has a parent")?; - if !parent.canonicalize()?.starts_with(&root) { - bail!( - "copying {} would write through a symlink to outside {}", - entry.path().display(), - destination.display() - ); - } + inside(target.parent().context("a copied entry has a parent")?)?; if entry.file_type().is_dir() { if target .symlink_metadata() diff --git a/crates/mockci/src/circleci/cache.rs b/crates/mockci/src/circleci/cache.rs index ee5e877..18d520a 100644 --- a/crates/mockci/src/circleci/cache.rs +++ b/crates/mockci/src/circleci/cache.rs @@ -46,7 +46,13 @@ impl Cache<'_> { for (index, path) in manifest.lines().enumerate() { let stored = dir.join(index.to_string()); if stored.exists() { - copy_tree(&stored, &resolve_path(path, &self.dirs)?)?; + 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")?; @@ -93,7 +99,7 @@ impl Cache<'_> { 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()))?; + copy_tree(path, &dir.join(index.to_string()), self.blobs)?; } } std::fs::write(dir.join("paths"), manifest)?; @@ -101,12 +107,16 @@ impl Cache<'_> { Ok(format!("Stored cache for key: {key}")) } - /// Whether the host's `path` changed after the job started (a step wrote it), rather than - /// being left there by something else. + /// 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 { - std::fs::symlink_metadata(path) - .and_then(|metadata| metadata.modified()) - .is_ok_and(|modified| modified >= self.started) + 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 { diff --git a/crates/mockci/src/circleci/steps.rs b/crates/mockci/src/circleci/steps.rs index 5435623..ec6bf24 100644 --- a/crates/mockci/src/circleci/steps.rs +++ b/crates/mockci/src/circleci/steps.rs @@ -67,7 +67,7 @@ fn checkout(job: &JobRun, body: &Yaml) -> Result<(String, StepResult)> { &target, )?; for (destination, source) in &job.sim.files { - copy_tree(source, &target.join(destination))?; + copy_tree(source, &target.join(destination), &target)?; } let name = optional_scalar(&settings, "name")?.unwrap_or_else(|| "Checkout code".into()); Ok(( diff --git a/internal_docs/MOCK_CI.md b/internal_docs/MOCK_CI.md index 7200069..6a488c9 100644 --- a/internal_docs/MOCK_CI.md +++ b/internal_docs/MOCK_CI.md @@ -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` @@ -86,14 +88,14 @@ and the parameters they saw. It shares the simulator's repository, clock, record 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 and artifacts keep symlinks as symlinks, and a restore -never writes through a symlink to outside the directory it restores to. 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 +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 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. +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. diff --git a/internal_docs/STATUS.md b/internal_docs/STATUS.md index ae8aaf2..fd50ee3 100644 --- a/internal_docs/STATUS.md +++ b/internal_docs/STATUS.md @@ -116,7 +116,8 @@ What the code does today, checked against the code in December 2026. Where cigen 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. + 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_strict.rs b/tests/mockci_circleci_strict.rs index 474da6c..36e125f 100644 --- a/tests/mockci_circleci_strict.rs +++ b/tests/mockci_circleci_strict.rs @@ -192,6 +192,28 @@ fn a_host_tmp_path_older_than_the_job_is_not_blamed_on_it() { 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] diff --git a/tests/mockci_symlinks.rs b/tests/mockci_symlinks.rs index 776502c..7e25d48 100644 --- a/tests/mockci_symlinks.rs +++ b/tests/mockci_symlinks.rs @@ -121,3 +121,96 @@ fn a_restore_to_a_symlink_that_leaves_the_job_is_refused() { 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}"); +}