treeboot-spec 0.16.0

Executable language-agnostic conformance specification for Treeboot.
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
use std::cell::RefCell;
use std::ffi::OsStr;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Output};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Once};
use std::time::Duration;

use assert_cmd::assert::Assert;
use serde_json::Value;
use tempfile::TempDir;

use crate::{
    CommandTemplate, Invocation, InvocationResult, LocalProcessRunner, Runner, RunnerCapabilities,
    StdinMode, Termination,
};

const CLEAN_ENVIRONMENT: &[&str] = &[
    "TREEBOOT_ROOT_PATH",
    "CODEX_SOURCE_TREE_PATH",
    "CONDUCTOR_ROOT_PATH",
    "SUPERSET_ROOT_PATH",
    "CONDUCTOR_DEFAULT_BRANCH",
    "TREEBOOT_STRICT",
    "TREEBOOT_DANGEROUSLY_ALLOW_SOURCES_OUTSIDE_ROOT",
    "TREEBOOT_DANGEROUSLY_ALLOW_TARGETS_OUTSIDE_WORKTREE",
];

thread_local! {
    static CASE_CONTEXT: RefCell<Option<Arc<CaseContext>>> = const { RefCell::new(None) };
}

static INSTALL_PANIC_HOOK: Once = Once::new();

pub(crate) fn install_case_panic_hook() {
    INSTALL_PANIC_HOOK.call_once(|| {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |panic| {
            let is_captured_case = CASE_CONTEXT
                .try_with(|slot| slot.borrow().is_some())
                .unwrap_or(false);
            if !is_captured_case {
                previous(panic);
            }
        }));
    });
}

pub(crate) struct CaseContext {
    runner: Arc<dyn Runner>,
    timeout: Duration,
    failure: Mutex<Option<ExecutionFailure>>,
    candidate_invoked: AtomicBool,
}

#[derive(Debug, Clone)]
pub(crate) enum ExecutionFailure {
    Skipped(String),
    Runner(String),
    Fixture(String),
    TimedOut(String),
}

impl CaseContext {
    pub(crate) fn new(runner: Arc<dyn Runner>, timeout: Duration) -> Self {
        Self {
            runner,
            timeout,
            failure: Mutex::new(None),
            candidate_invoked: AtomicBool::new(false),
        }
    }

    pub(crate) fn take_failure(&self) -> Option<ExecutionFailure> {
        self.failure
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
    }

    fn record(&self, failure: ExecutionFailure) {
        *self
            .failure
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(failure);
    }

    pub(crate) fn candidate_invoked(&self) -> bool {
        self.candidate_invoked.load(Ordering::Relaxed)
    }

    fn mark_candidate_invoked(&self) {
        self.candidate_invoked.store(true, Ordering::Relaxed);
    }
}

pub(crate) fn with_context<T>(context: Arc<CaseContext>, run: impl FnOnce() -> T) -> T {
    CASE_CONTEXT.with(|slot| {
        let previous = slot.replace(Some(context));
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(run));
        slot.replace(previous);
        match result {
            Ok(value) => value,
            Err(payload) => std::panic::resume_unwind(payload),
        }
    })
}

fn context() -> Arc<CaseContext> {
    CASE_CONTEXT.with(|slot| {
        slot.borrow()
            .as_ref()
            .cloned()
            .expect("conformance case must run through Suite")
    })
}

pub(crate) fn skip(reason: impl Into<String>) -> ! {
    let reason = reason.into();
    context().record(ExecutionFailure::Skipped(reason.clone()));
    panic!("case skipped: {reason}");
}

pub(crate) struct Command {
    invocation: Invocation,
}

impl Command {
    pub(crate) fn arg(&mut self, argument: impl AsRef<OsStr>) -> &mut Self {
        self.invocation =
            std::mem::take(&mut self.invocation).arg(argument.as_ref().to_os_string());
        self
    }

    pub(crate) fn args<I, S>(&mut self, arguments: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.invocation = std::mem::take(&mut self.invocation).args(
            arguments
                .into_iter()
                .map(|value| value.as_ref().to_os_string()),
        );
        self
    }

    pub(crate) fn current_dir(&mut self, path: impl AsRef<Path>) -> &mut Self {
        self.invocation =
            std::mem::take(&mut self.invocation).current_dir(path.as_ref().to_path_buf());
        self
    }

    pub(crate) fn env(&mut self, name: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
        self.invocation = std::mem::take(&mut self.invocation)
            .env(name.as_ref().to_os_string(), value.as_ref().to_os_string());
        self
    }

    pub(crate) fn write_terminal(&mut self, input: impl Into<Vec<u8>>) -> &mut Self {
        self.invocation =
            std::mem::take(&mut self.invocation).stdin(StdinMode::Terminal(input.into()));
        self
    }

    #[track_caller]
    pub(crate) fn assert(&mut self) -> Assert {
        let output = self.execute().unwrap_or_else(|error| panic!("{error}"));
        Assert::new(output)
    }

    pub(crate) fn output(&mut self) -> io::Result<Output> {
        self.execute().map_err(io::Error::other)
    }

    fn execute(&mut self) -> Result<Output, String> {
        let context = context();
        if self.invocation.timeout_value().is_none() {
            self.invocation = std::mem::take(&mut self.invocation).timeout(context.timeout);
        }
        context.mark_candidate_invoked();
        let result = context.runner.run(&self.invocation).map_err(|error| {
            let message = error.to_string();
            match error {
                crate::RunnerError::UnsupportedCapability { .. } => {
                    context.record(ExecutionFailure::Skipped(message.clone()));
                }
                _ => context.record(ExecutionFailure::Runner(message.clone())),
            }
            message
        })?;
        result_to_output(&context, result, "candidate")
    }
}

fn result_to_output(
    context: &CaseContext,
    result: InvocationResult,
    process: &str,
) -> Result<Output, String> {
    if result.termination() == Termination::TimedOut {
        let message = format!(
            "{process} timed out after {} ms; stdout: {}; stderr: {}",
            result.duration().as_millis(),
            String::from_utf8_lossy(result.stdout()),
            String::from_utf8_lossy(result.stderr())
        );
        context.record(ExecutionFailure::TimedOut(message.clone()));
        return Err(message);
    }

    Ok(Output {
        status: native_status(result.termination()),
        stdout: result.stdout().to_vec(),
        stderr: result.stderr().to_vec(),
    })
}

pub(crate) struct HostProcess {
    runner: LocalProcessRunner,
    invocation: Invocation,
}

impl HostProcess {
    pub(crate) fn arg(&mut self, argument: impl AsRef<OsStr>) -> &mut Self {
        self.invocation =
            std::mem::take(&mut self.invocation).arg(argument.as_ref().to_os_string());
        self
    }

    pub(crate) fn args<I, S>(&mut self, arguments: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.invocation = std::mem::take(&mut self.invocation).args(
            arguments
                .into_iter()
                .map(|value| value.as_ref().to_os_string()),
        );
        self
    }

    pub(crate) fn current_dir(&mut self, path: impl AsRef<Path>) -> &mut Self {
        self.invocation =
            std::mem::take(&mut self.invocation).current_dir(path.as_ref().to_path_buf());
        self
    }

    pub(crate) fn env(&mut self, name: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
        self.invocation = std::mem::take(&mut self.invocation)
            .env(name.as_ref().to_os_string(), value.as_ref().to_os_string());
        self
    }

    pub(crate) fn output(&mut self) -> io::Result<Output> {
        let context = context();
        if self.invocation.timeout_value().is_none() {
            self.invocation = std::mem::take(&mut self.invocation).timeout(context.timeout);
        }
        let result = self.runner.run(&self.invocation).map_err(|error| {
            let message = format!("host subprocess failed: {error}");
            context.record(ExecutionFailure::Fixture(message.clone()));
            io::Error::other(message)
        })?;
        result_to_output(&context, result, "host subprocess").map_err(io::Error::other)
    }
}

pub(crate) fn host_process(program: impl AsRef<OsStr>) -> HostProcess {
    let mut invocation = Invocation::new();
    for name in CLEAN_ENVIRONMENT {
        invocation = invocation.env_remove(*name);
    }
    HostProcess {
        runner: LocalProcessRunner::new(CommandTemplate::new(program.as_ref().to_os_string())),
        invocation,
    }
}

#[track_caller]
pub(crate) fn assert_fixture_process_success(label: &str, output: &Output) {
    if output.status.success() {
        return;
    }

    let message = format!(
        "{label} should succeed\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    context().record(ExecutionFailure::Fixture(message.clone()));
    panic!("{message}");
}

#[cfg(test)]
pub(crate) fn fixture_failure_after_candidate_for_suite_regression() {
    treeboot()
        .arg("--version")
        .output()
        .expect("candidate invocation should run");
    let output = host_process(std::env::current_exe().expect("test executable should resolve"))
        .args([
            "cases::support::tests::failing_host_subprocess_helper",
            "--exact",
            "--ignored",
        ])
        .output()
        .expect("failing host subprocess should run");
    assert_fixture_process_success("host subprocess", &output);
}

#[cfg(unix)]
fn native_status(termination: Termination) -> ExitStatus {
    use std::os::unix::process::ExitStatusExt;

    match termination {
        Termination::Exited { code } => ExitStatus::from_raw(code << 8),
        Termination::Signaled | Termination::TimedOut => ExitStatus::from_raw(9),
    }
}

#[cfg(windows)]
fn native_status(termination: Termination) -> ExitStatus {
    use std::os::windows::process::ExitStatusExt;

    match termination {
        Termination::Exited { code } => ExitStatus::from_raw(code as u32),
        Termination::Signaled | Termination::TimedOut => ExitStatus::from_raw(u32::MAX),
    }
}

pub(crate) fn treeboot() -> Command {
    let mut invocation = Invocation::new();
    for name in CLEAN_ENVIRONMENT {
        invocation = invocation.env_remove(*name);
    }
    Command { invocation }
}

pub(crate) fn runner_capabilities() -> RunnerCapabilities {
    context().runner.capabilities()
}

pub(crate) fn canonical_path(path: &Path) -> PathBuf {
    dunce::canonicalize(path).expect("path should canonicalize")
}

pub(crate) fn display_path(path: &str) -> String {
    path.split('/').collect::<PathBuf>().display().to_string()
}

pub(crate) fn toml_string_path(path: &Path) -> String {
    toml_string(&path.display().to_string())
}

pub(crate) fn toml_string(value: &str) -> String {
    value.replace('\\', "\\\\").replace('"', "\\\"")
}

pub(crate) fn git(args: &[&str], cwd: &Path) {
    let output = host_process("git")
        .args(args.iter().copied())
        .current_dir(cwd)
        .output()
        .expect("git should run");
    assert_fixture_process_success(&format!("git {args:?}"), &output);
}

pub(crate) fn git_repo() -> TempDir {
    let repo = TempDir::new().expect("tempdir should be created");
    git(&["init"], repo.path());
    repo
}

pub(crate) struct GitWorktree {
    root: TempDir,
    _worktree_parent: TempDir,
    worktree_path: PathBuf,
}

impl GitWorktree {
    pub(crate) fn root_path(&self) -> &Path {
        self.root.path()
    }

    pub(crate) fn worktree_path(&self) -> &Path {
        &self.worktree_path
    }
}

pub(crate) fn git_worktree() -> GitWorktree {
    let root = git_repo();
    git(&["config", "user.name", "treeboot"], root.path());
    git(
        &["config", "user.email", "treeboot@example.invalid"],
        root.path(),
    );
    git(&["config", "commit.gpgsign", "false"], root.path());
    write_file(&root.path().join("README.md"), "treeboot test repo\n");
    git(&["add", "README.md"], root.path());
    git(&["commit", "-m", "Initial commit"], root.path());

    let worktree_parent = TempDir::new().expect("worktree parent should be created");
    let worktree_path = worktree_parent.path().join("linked");
    let worktree = worktree_path
        .to_str()
        .expect("worktree path should be valid UTF-8");
    git(
        &["worktree", "add", "-b", "treeboot-test-worktree", worktree],
        root.path(),
    );

    GitWorktree {
        root,
        _worktree_parent: worktree_parent,
        worktree_path,
    }
}

pub(crate) fn write_file(path: &Path, content: &str) {
    std::fs::write(path, content).expect("file should be written");
}

#[cfg(unix)]
pub(crate) fn symlink_file(source: impl AsRef<Path>, target: impl AsRef<Path>) {
    std::os::unix::fs::symlink(source.as_ref(), target.as_ref())
        .expect("file symlink should be created");
}

#[cfg(windows)]
pub(crate) fn symlink_file(source: impl AsRef<Path>, target: impl AsRef<Path>) {
    match std::os::windows::fs::symlink_file(source.as_ref(), target.as_ref()) {
        Ok(()) => {}
        Err(error) if error.raw_os_error() == Some(1314) => skip(
            "requires Windows symbolic-link privilege or Developer Mode to create fixture links",
        ),
        Err(error) => panic!("file symlink should be created: {error}"),
    }
}

#[cfg(unix)]
pub(crate) fn symlink_dir(source: impl AsRef<Path>, target: impl AsRef<Path>) {
    std::os::unix::fs::symlink(source.as_ref(), target.as_ref())
        .expect("directory symlink should be created");
}

#[cfg(windows)]
pub(crate) fn symlink_dir(source: impl AsRef<Path>, target: impl AsRef<Path>) {
    match std::os::windows::fs::symlink_dir(source.as_ref(), target.as_ref()) {
        Ok(()) => {}
        Err(error) if error.raw_os_error() == Some(1314) => skip(
            "requires Windows symbolic-link privilege or Developer Mode to create fixture links",
        ),
        Err(error) => panic!("directory symlink should be created: {error}"),
    }
}

pub(crate) fn parse_json(stdout: Vec<u8>, context: &str) -> Value {
    serde_json::from_slice(&stdout).unwrap_or_else(|error| {
        panic!("{context} JSON should parse: {error}");
    })
}

pub(crate) fn assert_json_object_keys(value: &Value, expected: &[&str]) {
    let object = value.as_object().expect("value should be a JSON object");
    let mut actual = object.keys().map(String::as_str).collect::<Vec<_>>();
    actual.sort_unstable();

    let mut expected = expected.to_vec();
    expected.sort_unstable();

    assert_eq!(actual, expected);
}

pub(crate) fn assert_context_shape(value: &Value) {
    assert_json_object_keys(value, &["default_branch", "root_path", "worktree_path"]);
    assert!(value["root_path"].is_string());
    assert!(value["worktree_path"].is_string());
    assert!(value["default_branch"].is_string());
}

#[cfg(unix)]
pub(crate) fn write_executable_script(path: &Path, content: &str) {
    use std::os::unix::fs::PermissionsExt;

    write_file(path, content);
    let mut permissions = path
        .metadata()
        .expect("script metadata should be readable")
        .permissions();
    permissions.set_mode(0o755);
    std::fs::set_permissions(path, permissions).expect("script permissions should be set");
}

pub(crate) fn candidate_package_version() -> String {
    let output = treeboot()
        .args(["version", "--json"])
        .output()
        .expect("candidate version query should run");
    assert!(
        output.status.success(),
        "candidate version query should succeed\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let value = parse_json(output.stdout, "candidate version");
    value["version"]
        .as_str()
        .expect("candidate version should be a string")
        .to_owned()
}

#[cfg(test)]
mod tests {
    use std::time::Instant;

    use super::*;

    #[test]
    fn blocking_host_subprocess_should_record_timeout_without_candidate_invocation() {
        let context = Arc::new(CaseContext::new(
            Arc::new(LocalProcessRunner::new(CommandTemplate::new(
                "unused-candidate",
            ))),
            Duration::from_millis(100),
        ));
        let started = Instant::now();

        with_context(Arc::clone(&context), || {
            host_process(std::env::current_exe().expect("test executable should resolve"))
                .args([
                    "cases::support::tests::blocking_host_subprocess_helper",
                    "--exact",
                    "--ignored",
                ])
                .output()
                .expect_err("blocking host subprocess should time out");
        });

        assert!(matches!(
            context.take_failure(),
            Some(ExecutionFailure::TimedOut(_))
        ));
        assert!(!context.candidate_invoked());
        assert!(started.elapsed() < Duration::from_secs(5));
    }

    #[test]
    fn host_launch_failure_should_remain_a_fixture_error_after_candidate_invocation() {
        let context = Arc::new(CaseContext::new(
            Arc::new(LocalProcessRunner::new(CommandTemplate::new(
                "unused-candidate",
            ))),
            Duration::from_secs(1),
        ));
        context.mark_candidate_invoked();

        with_context(Arc::clone(&context), || {
            host_process("treeboot-spec-host-program-that-does-not-exist")
                .output()
                .expect_err("missing host program should fail to launch");
        });

        assert!(matches!(
            context.take_failure(),
            Some(ExecutionFailure::Fixture(_))
        ));
        assert!(context.candidate_invoked());
    }

    #[test]
    fn host_nonzero_exit_should_remain_a_fixture_error_after_candidate_invocation() {
        let context = Arc::new(CaseContext::new(
            Arc::new(LocalProcessRunner::new(CommandTemplate::new(
                "unused-candidate",
            ))),
            Duration::from_secs(1),
        ));
        context.mark_candidate_invoked();

        with_context(Arc::clone(&context), || {
            let output =
                host_process(std::env::current_exe().expect("test executable should resolve"))
                    .args([
                        "cases::support::tests::failing_host_subprocess_helper",
                        "--exact",
                        "--ignored",
                    ])
                    .output()
                    .expect("failing host subprocess should run");
            let failure = std::panic::catch_unwind(|| {
                assert_fixture_process_success("host subprocess", &output);
            });
            assert!(failure.is_err());
        });

        assert!(matches!(
            context.take_failure(),
            Some(ExecutionFailure::Fixture(_))
        ));
        assert!(context.candidate_invoked());
    }

    #[test]
    #[ignore = "helper process for the bounded host-subprocess regression"]
    fn blocking_host_subprocess_helper() {
        std::thread::sleep(Duration::from_secs(30));
    }

    #[test]
    #[ignore = "helper process for the non-zero host-subprocess regression"]
    fn failing_host_subprocess_helper() {
        std::process::exit(99);
    }
}