anodizer-core 0.15.0

Core configuration, context, and template engine for the anodizer release tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! PATH-stub harness for faking external command-line tools in tests.
//!
//! Many stages shell out to external tools — `codesign`/`xcrun` (notarize),
//! `syft` (sbom), `makeself`, `rpmbuild` (srpm), `docker`, `upx`, `appimagetool`.
//! Those code paths are the largest uncovered blocks in the tree precisely
//! because a real run needs the tool installed, often on a specific OS. This
//! harness makes them testable on any host by installing executable stub
//! scripts that emit canned stdout/stderr, exit with a chosen code, optionally
//! create output files, and record every invocation's argv for assertions.
//!
//! Two ways to route a stage at a stub:
//!
//! 1. **Configurable command** (e.g. sbom's `cmd:`): point the config value
//!    straight at [`FakeToolDir::tool_path`] — no PATH mutation, no `#[serial]`.
//! 2. **Hard-coded tool name** (e.g. notarize's `codesign`): call
//!    [`FakeToolDir::activate`] to prepend the stub dir to `PATH`. This mutates
//!    the process environment, so such tests **must** be `#[serial]` (the guard
//!    holds [`crate::test_helpers::env::env_mutex`] for its lifetime and
//!    restores the prior `PATH` on drop).
//!
//! ## Example — configurable command (sbom)
//!
//! ```no_run
//! use anodizer_core::test_helpers::fake_tool::FakeToolDir;
//!
//! let tools = FakeToolDir::new();
//! tools
//!     .tool("syft")
//!     .creates("sbom.spdx.json", "{}")
//!     .stdout("generated 1 document\n")
//!     .install();
//! // point the sbom `cmd:` config at tools.tool_path("syft") ...
//! // run the stage ...
//! assert!(tools.was_called("syft"));
//! let argv = tools.calls("syft");
//! assert_eq!(argv[0][0], "scan"); // first arg of the first invocation
//! ```
//!
//! ## Example — hard-coded tool on PATH (notarize), serialised
//!
//! ```no_run
//! use anodizer_core::test_helpers::fake_tool::FakeToolDir;
//!
//! // #[test] #[serial] fn notarize_happy_path() {
//! let tools = FakeToolDir::new();
//! tools.tool("codesign").install();
//! tools.tool("xcrun").stdout("{\"status\":\"Accepted\"}\n").install();
//! let _path = tools.activate(); // prepend to PATH until `_path` drops
//! // run the notarize stage ...
//! // }
//! ```

use std::path::{Path, PathBuf};

use tempfile::TempDir;

use crate::test_helpers::env::env_mutex;

/// Argument separator written by stub scripts between successive argv entries.
const ARG_SEP: char = '\u{1f}';
/// Record separator written by stub scripts after each invocation's argv.
const REC_SEP: char = '\u{1e}';

/// A temporary directory of installed fake-tool stubs.
///
/// Lives for the duration of a test; the backing temp dir (and every stub in
/// it) is deleted when this value drops. Build stubs with [`tool`](Self::tool),
/// route stages at them via [`tool_path`](Self::tool_path) or
/// [`activate`](Self::activate), then assert with [`was_called`](Self::was_called)
/// / [`calls`](Self::calls).
pub struct FakeToolDir {
    dir: TempDir,
}

impl FakeToolDir {
    /// Create a fresh, empty stub directory backed by a temp dir.
    ///
    /// # Panics
    /// Panics if the temp directory cannot be created.
    pub fn new() -> Self {
        let dir = TempDir::new().expect("fake_tool: create temp dir");
        Self { dir }
    }

    /// The directory holding the installed stubs (what [`activate`](Self::activate)
    /// prepends to `PATH`).
    pub fn bin_dir(&self) -> &Path {
        self.dir.path()
    }

    /// Absolute path to a named stub, suitable for a configurable `cmd:` field.
    /// The stub need not exist yet; pair with [`tool`](Self::tool)`.install()`.
    pub fn tool_path(&self, name: &str) -> PathBuf {
        self.dir.path().join(stub_file_name(name))
    }

    /// Begin defining a stub tool. Chain setters, then call
    /// [`ToolSpec::install`].
    pub fn tool<'a>(&'a self, name: &str) -> ToolSpec<'a> {
        ToolSpec {
            dir: self,
            name: name.to_string(),
            stdout: String::new(),
            stderr: String::new(),
            exit: 0,
            script: None,
            creates: Vec::new(),
        }
    }

    /// Prepend [`bin_dir`](Self::bin_dir) to `PATH` for hard-coded tool names.
    ///
    /// Returns a guard that restores the prior `PATH` and releases the env mutex
    /// when dropped. The test **must** be `#[serial]`; the guard holds the
    /// shared [`env_mutex`] so it cannot race other env-mutating tests, but
    /// `#[serial]` is still required because coverage runs share one process.
    pub fn activate(&self) -> PathGuard {
        let lock = env_mutex().lock().unwrap_or_else(|e| e.into_inner());
        let prior = std::env::var_os("PATH");
        let mut entries: Vec<PathBuf> = vec![self.dir.path().to_path_buf()];
        if let Some(ref p) = prior {
            entries.extend(std::env::split_paths(p));
        }
        let joined = std::env::join_paths(entries).expect("fake_tool: join PATH");
        // env-ok: PATH is resolved by spawned children via execvp(3), not
        // through any injectable EnvSource, so binary-stub tests must mutate the
        // real process PATH; env_mutex (held for the guard's life) + the
        // documented `#[serial]` caller requirement serialise it.
        // SAFETY: serialised by the env mutex held in `lock` for the guard's life.
        unsafe { std::env::set_var("PATH", &joined) };
        PathGuard { prior, _lock: lock }
    }

    /// Every recorded invocation of `name`, outer `Vec` per call, inner `Vec`
    /// the argv (excluding arg0). Empty if the stub was never run.
    pub fn calls(&self, name: &str) -> Vec<Vec<String>> {
        let log = self.calls_path(name);
        let Ok(raw) = std::fs::read_to_string(&log) else {
            return Vec::new();
        };
        // Each invocation writes its argv terminated by REC_SEP, so the element
        // after the final terminator is always an empty tail — drop it. Every
        // remaining element is one invocation (an empty one means a zero-arg
        // call, which still counts).
        let mut records: Vec<&str> = raw.split(REC_SEP).collect();
        if records.last() == Some(&"") {
            records.pop();
        }
        records
            .iter()
            .map(|rec| {
                rec.split(ARG_SEP)
                    .filter(|a| !a.is_empty())
                    .map(|a| a.to_string())
                    .collect()
            })
            .collect()
    }

    /// Whether `name` was invoked at least once.
    pub fn was_called(&self, name: &str) -> bool {
        self.calls_path(name).exists()
    }

    /// Number of times `name` was invoked.
    pub fn call_count(&self, name: &str) -> usize {
        self.calls(name).len()
    }

    fn calls_path(&self, name: &str) -> PathBuf {
        self.dir.path().join(format!(".calls.{name}"))
    }
}

impl Default for FakeToolDir {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for a single fake tool. Created by [`FakeToolDir::tool`].
#[must_use = "call `.install()` to write the stub"]
pub struct ToolSpec<'a> {
    dir: &'a FakeToolDir,
    name: String,
    stdout: String,
    stderr: String,
    exit: i32,
    script: Option<String>,
    creates: Vec<(String, String)>,
}

impl ToolSpec<'_> {
    /// Text the stub writes to stdout.
    pub fn stdout(mut self, s: impl Into<String>) -> Self {
        self.stdout = s.into();
        self
    }

    /// Text the stub writes to stderr.
    pub fn stderr(mut self, s: impl Into<String>) -> Self {
        self.stderr = s.into();
        self
    }

    /// Exit code the stub returns (default `0`).
    pub fn exit(mut self, code: i32) -> Self {
        self.exit = code;
        self
    }

    /// Make the stub create an output file (path relative to the tool's working
    /// directory, or absolute) with the given contents before exiting. Useful
    /// for tools whose stage asserts the artifact exists (sbom, makeself, srpm).
    /// Unix only.
    pub fn creates(mut self, rel_path: impl Into<String>, contents: impl Into<String>) -> Self {
        self.creates.push((rel_path.into(), contents.into()));
        self
    }

    /// Replace the default emit-and-exit body with an arbitrary `sh` snippet,
    /// run after argv is recorded. The snippet can read `"$@"` and create files.
    /// Unix only; overrides [`stdout`](Self::stdout)/[`stderr`](Self::stderr)/
    /// [`exit`](Self::exit).
    pub fn script(mut self, body: impl Into<String>) -> Self {
        self.script = Some(body.into());
        self
    }

    /// Write the stub to disk and make it executable.
    ///
    /// # Panics
    /// Panics if the stub cannot be written or marked executable.
    pub fn install(self) {
        let path = self.dir.tool_path(&self.name);
        let calls = self.dir.calls_path(&self.name);
        let body = self.render_script(&calls);
        std::fs::write(&path, body).expect("fake_tool: write stub");
        make_executable(&path);
    }

    #[cfg(unix)]
    fn render_script(&self, calls: &Path) -> String {
        let mut s = String::from("#!/bin/sh\n");
        // Record argv (excluding arg0) as ARG_SEP-joined, REC_SEP-terminated.
        // Build the whole record in one variable and emit it with a single
        // `printf` so the append is one atomic write — stages that invoke the
        // tool in parallel (e.g. makeself) append concurrently, and two
        // separate writes per call would interleave and merge records.
        s.push_str(&format!(
            "__r=''\nfor __a in \"$@\"; do __r=\"${{__r}}${{__a}}{arg}\"; done\n\
             printf '%s{rec}' \"$__r\" >> {log}\n",
            arg = ARG_SEP,
            rec = REC_SEP,
            log = sh_quote(&calls.to_string_lossy()),
        ));
        for (rel, contents) in &self.creates {
            // mkdir -p the parent so relative nested outputs work.
            s.push_str(&format!(
                "mkdir -p \"$(dirname {p})\" 2>/dev/null || true\n",
                p = sh_quote(rel)
            ));
            s.push_str(&format!(
                "printf '%s' {c} > {p}\n",
                c = sh_quote(contents),
                p = sh_quote(rel),
            ));
        }
        if let Some(custom) = &self.script {
            s.push_str(custom);
            if !custom.ends_with('\n') {
                s.push('\n');
            }
        } else {
            // Drain stdin to EOF before emitting output: a stubbed tool that the
            // producer pipes input to (e.g. a kms CLI fed plaintext on stdin)
            // must consume it, or the producer's write hits a broken pipe when
            // this stub exits first. Harmless when nothing is piped — under the
            // test harness stdin is /dev/null, so this returns immediately.
            // (A custom `.script()` owns its own stdin handling.)
            s.push_str("cat >/dev/null 2>&1\n");
            if !self.stdout.is_empty() {
                s.push_str(&format!("printf '%s' {}\n", sh_quote(&self.stdout)));
            }
            if !self.stderr.is_empty() {
                s.push_str(&format!("printf '%s' {} 1>&2\n", sh_quote(&self.stderr)));
            }
            s.push_str(&format!("exit {}\n", self.exit));
        }
        s
    }

    #[cfg(not(unix))]
    fn render_script(&self, calls: &Path) -> String {
        assert!(
            self.script.is_none() && self.creates.is_empty(),
            "fake_tool: .script()/.creates() are unix-only"
        );
        let mut s = String::from("@echo off\r\n");
        s.push_str(&format!(">>\"{}\" echo %*\r\n", calls.display()));
        if !self.stdout.is_empty() {
            s.push_str(&format!(
                "echo|set /p=\"{}\"\r\n",
                self.stdout.replace('\n', " ")
            ));
        }
        if !self.stderr.is_empty() {
            s.push_str(&format!(
                "echo|set /p=\"{}\" 1>&2\r\n",
                self.stderr.replace('\n', " ")
            ));
        }
        s.push_str(&format!("exit /b {}\r\n", self.exit));
        s
    }
}

/// Restores `PATH` and releases the env mutex when dropped. Returned by
/// [`FakeToolDir::activate`].
pub struct PathGuard {
    prior: Option<std::ffi::OsString>,
    _lock: std::sync::MutexGuard<'static, ()>,
}

impl Drop for PathGuard {
    fn drop(&mut self) {
        // SAFETY: still serialised by `_lock`, dropped after this.
        unsafe {
            match &self.prior {
                Some(p) => std::env::set_var("PATH", p),
                None => std::env::remove_var("PATH"),
            }
        }
    }
}

#[cfg(unix)]
fn stub_file_name(name: &str) -> String {
    name.to_string()
}

#[cfg(not(unix))]
fn stub_file_name(name: &str) -> String {
    format!("{name}.cmd")
}

#[cfg(unix)]
fn make_executable(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = std::fs::metadata(path)
        .expect("fake_tool: stat stub")
        .permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(path, perms).expect("fake_tool: chmod stub");
}

#[cfg(not(unix))]
fn make_executable(_path: &Path) {}

/// Single-quote a string for safe interpolation into an `sh` script.
#[cfg(unix)]
fn sh_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// `Command::output` with a bounded retry on `ETXTBSY` ("Text file busy").
///
/// A test that installs a [`FakeToolDir`] stub and execs it immediately
/// from the same process races every sibling test thread's `fork`: a child
/// forked inside the install's write window briefly inherits the stub's
/// writable fd, and the exec here fails with `ETXTBSY` until that child
/// reaches its own `exec` (the fd is CLOEXEC). A short bounded retry is
/// the standard remedy. Use this instead of routing the stub through
/// `sh <stub>` — both close the race, but the retry keeps the real
/// spawn-the-tool code path under test. Production code never
/// writes-then-execs its own tools and cannot hit this.
#[cfg(unix)]
pub fn output_retrying_etxtbsy(cmd: &mut std::process::Command) -> std::process::Output {
    for _ in 0..50 {
        match cmd.output() {
            Err(e) if e.kind() == std::io::ErrorKind::ExecutableFileBusy => {
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
            other => return other.expect("spawn fake tool"),
        }
    }
    panic!("fake tool stayed ETXTBSY after 50 retries");
}

// Unix-only: every test here spawns a fake tool that is a shell script, so the
// whole module compiles only on unix — gating it once here keeps the Windows
// build free of unused-import warnings without per-item `#[cfg(unix)]`.
#[cfg(all(test, unix))]
mod tests {
    use super::*;
    use std::process::Command;

    #[test]
    fn records_argv_across_invocations() {
        let tools = FakeToolDir::new();
        tools.tool("widget").stdout("ok\n").install();
        let bin = tools.tool_path("widget");

        let out = output_retrying_etxtbsy(Command::new(&bin).args(["build", "--fast"]));
        assert!(out.status.success());
        assert_eq!(String::from_utf8_lossy(&out.stdout), "ok\n");
        output_retrying_etxtbsy(Command::new(&bin).arg("clean"));

        assert!(tools.was_called("widget"));
        assert_eq!(tools.call_count("widget"), 2);
        let calls = tools.calls("widget");
        assert_eq!(calls[0], vec!["build", "--fast"]);
        assert_eq!(calls[1], vec!["clean"]);
    }

    #[test]
    fn honors_exit_code_and_stderr() {
        let tools = FakeToolDir::new();
        tools.tool("boom").stderr("fatal\n").exit(7).install();
        let out = output_retrying_etxtbsy(&mut Command::new(tools.tool_path("boom")));
        assert_eq!(out.status.code(), Some(7));
        assert_eq!(String::from_utf8_lossy(&out.stderr), "fatal\n");
    }

    #[test]
    fn creates_output_file() {
        let tools = FakeToolDir::new();
        tools
            .tool("gen")
            .creates("out/doc.json", "{\"k\":1}")
            .install();
        let work = TempDir::new().unwrap();
        let out =
            output_retrying_etxtbsy(Command::new(tools.tool_path("gen")).current_dir(work.path()));
        assert!(out.status.success());
        let body = std::fs::read_to_string(work.path().join("out/doc.json")).unwrap();
        assert_eq!(body, "{\"k\":1}");
    }

    #[test]
    fn custom_script_sees_argv() {
        let tools = FakeToolDir::new();
        // syft-style: write the file named after the `-o fmt=PATH` arg.
        tools
            .tool("syft")
            .script("for a in \"$@\"; do case \"$a\" in *=*) echo '{}' > \"${a#*=}\";; esac; done")
            .install();
        let work = TempDir::new().unwrap();
        output_retrying_etxtbsy(
            Command::new(tools.tool_path("syft"))
                .current_dir(work.path())
                .args(["scan", "-o", "spdx-json=bom.json"]),
        );
        assert_eq!(
            std::fs::read_to_string(work.path().join("bom.json")).unwrap(),
            "{}\n"
        );
    }

    #[test]
    #[serial_test::serial]
    fn activate_prepends_path_and_restores() {
        let before = std::env::var_os("PATH");
        let tools = FakeToolDir::new();
        tools.tool("findme").install();
        {
            let _g = tools.activate();
            let resolved = which_on_path("findme");
            assert_eq!(
                resolved.as_deref(),
                Some(tools.tool_path("findme").as_path())
            );
        }
        assert_eq!(std::env::var_os("PATH"), before);
    }

    fn which_on_path(name: &str) -> Option<PathBuf> {
        let path = std::env::var_os("PATH")?;
        std::env::split_paths(&path)
            .map(|d| d.join(name))
            .find(|p| p.exists())
    }
}