cf-integration 0.1.0

Integration and conformance harness for ContextForge control-plane and data-plane services
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
use std::ffi::{OsStr, OsString};
use std::fs;
use std::path::{Path, PathBuf};

use cf_integration::infrastructure::InfrastructureError;
#[cfg(unix)]
use cf_integration::infrastructure::process::LoggingProcessRunner;
use cf_integration::infrastructure::process::{
    CapturedOutput, CommandSpec, ProcessRunner, SystemProcessRunner,
};
#[cfg(unix)]
use tempfile::TempDir;

#[cfg(unix)]
use std::sync::Arc;
#[cfg(unix)]
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(unix)]
use std::time::Duration;

#[cfg(unix)]
use std::os::unix::ffi::OsStringExt;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

fn assert_runner_interface(_runner: &dyn ProcessRunner) {}

struct FakeProcessRunner;

impl ProcessRunner for FakeProcessRunner {
    fn run(&self, _spec: &CommandSpec) -> Result<(), InfrastructureError> {
        Ok(())
    }

    fn capture_stdout(&self, _spec: &CommandSpec) -> Result<Vec<u8>, InfrastructureError> {
        Ok(b"synthetic stdout".to_vec())
    }

    fn capture_output(&self, _spec: &CommandSpec) -> Result<CapturedOutput, InfrastructureError> {
        Ok(CapturedOutput::new(
            b"synthetic stdout".to_vec(),
            b"synthetic stderr".to_vec(),
        ))
    }

    fn run_to_log(&self, _spec: &CommandSpec, _log_path: &Path) -> Result<(), InfrastructureError> {
        Ok(())
    }
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn logging_runner_hides_ordinary_output_in_an_aggregate_log() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(
        &directory,
        "aggregate-log.sh",
        "printf 'ordinary stdout\\n'; printf 'ordinary stderr\\n' >&2",
    );
    let log_path = directory.path().join("setup.log");
    let system = SystemProcessRunner;
    let runner = LoggingProcessRunner::new(&system, &log_path);

    runner
        .run_async(&CommandSpec::new(script))
        .await
        .expect("logged child should succeed");

    let log = fs::read(&log_path).expect("aggregate log should be readable");
    assert!(
        log.windows(b"ordinary stdout\n".len())
            .any(|part| part == b"ordinary stdout\n")
    );
    assert!(
        log.windows(b"ordinary stderr\n".len())
            .any(|part| part == b"ordinary stderr\n")
    );
}

#[cfg(unix)]
fn executable_script(directory: &TempDir, name: &str, body: &str) -> PathBuf {
    let path = directory.path().join(name);
    fs::write(&path, format!("#!/bin/sh\nset -eu\n{body}\n"))
        .expect("temporary script should be written");
    let mut permissions = fs::metadata(&path)
        .expect("temporary script metadata should be readable")
        .permissions();
    permissions.set_mode(0o700);
    fs::set_permissions(&path, permissions).expect("temporary script should be executable");
    path
}

#[test]
fn command_spec_builder_exposes_program_arguments_cwd_and_sorted_environment() {
    let cwd = PathBuf::from("working-directory");
    let spec = CommandSpec::new(OsString::from("program"))
        .arg(OsString::from("first"))
        .args([OsString::from("second"), OsString::from("third")])
        .cwd(cwd.clone())
        .env(OsString::from("Z_KEY"), OsString::from("last"))
        .env(OsString::from("A_KEY"), OsString::from("first"));

    assert_eq!(spec.program(), OsStr::new("program"));
    assert_eq!(
        spec.arguments(),
        [
            OsString::from("first"),
            OsString::from("second"),
            OsString::from("third")
        ]
    );
    assert_eq!(spec.working_directory(), Some(cwd.as_path()));
    assert_eq!(
        spec.environment().keys().collect::<Vec<_>>(),
        [OsStr::new("A_KEY"), OsStr::new("Z_KEY")]
    );
    assert_eq!(
        spec.environment().get(OsStr::new("A_KEY")),
        Some(&OsString::from("first"))
    );
    assert!(spec.inherits_environment());
}

#[test]
fn command_spec_can_request_an_isolated_child_environment() {
    let spec = CommandSpec::new("program")
        .clear_environment()
        .env("PATH", "/safe/bin");

    assert!(!spec.inherits_environment());
    assert_eq!(
        spec.environment().get(OsStr::new("PATH")),
        Some(&OsString::from("/safe/bin"))
    );
}

#[test]
fn command_spec_preserves_empty_values_and_redacts_environment_debug_output() {
    const SECRET: &str = "process-secret-77c2bc";
    let spec = CommandSpec::new(OsString::new())
        .arg(OsString::new())
        .env(OsString::from("EMPTY"), OsString::new())
        .env(OsString::from("SECRET"), OsString::from(SECRET));

    assert_eq!(spec.program(), OsStr::new(""));
    assert_eq!(spec.arguments(), [OsString::new()]);
    assert_eq!(
        spec.environment().get(OsStr::new("EMPTY")),
        Some(&OsString::new())
    );
    let debug = format!("{spec:?}");
    assert!(debug.contains("SECRET"));
    assert!(!debug.contains(SECRET));
}

#[test]
fn command_spec_debug_omits_argument_values_and_reports_only_the_count() {
    const ARGUMENT_SECRET: &str = "argument-secret-f5c8c7";
    let spec = CommandSpec::new("program")
        .arg("ordinary-argument")
        .arg(ARGUMENT_SECRET);

    let debug = format!("{spec:?}");

    assert!(debug.contains("arg_count: 2"), "{debug}");
    assert!(!debug.contains("ordinary-argument"), "{debug}");
    assert!(!debug.contains(ARGUMENT_SECRET), "{debug}");
}

#[test]
fn external_fake_runner_can_construct_and_return_captured_output() {
    let runner: &dyn ProcessRunner = &FakeProcessRunner;

    let output = runner
        .capture_output(&CommandSpec::new("synthetic-program"))
        .expect("fake capture should succeed");

    assert_eq!(output.stdout(), b"synthetic stdout");
    assert_eq!(output.stderr(), b"synthetic stderr");
    assert_eq!(
        output.into_parts(),
        (b"synthetic stdout".to_vec(), b"synthetic stderr".to_vec())
    );
}

#[cfg(unix)]
#[test]
fn command_spec_preserves_non_utf8_arguments_and_environment() {
    let argument = OsString::from_vec(vec![b'a', 0xff, b'b']);
    let value = OsString::from_vec(vec![b'v', 0xfe]);
    let spec = CommandSpec::new("program")
        .arg(argument.clone())
        .env("RAW_VALUE", value.clone());

    assert_eq!(spec.arguments(), [argument]);
    assert_eq!(
        spec.environment().get(OsStr::new("RAW_VALUE")),
        Some(&value)
    );
}

#[cfg(unix)]
#[test]
fn runner_propagates_cwd_and_environment_overrides() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(
        &directory,
        "cwd-env.sh",
        "printf '%s\\n%s\\n' \"$PWD\" \"$PROCESS_TEST_VALUE\"",
    );
    let spec = CommandSpec::new(script)
        .cwd(directory.path())
        .env("PROCESS_TEST_VALUE", "from-command-spec");

    let stdout = SystemProcessRunner
        .capture_stdout(&spec)
        .expect("script should run successfully");

    let canonical_directory = fs::canonicalize(directory.path())
        .expect("temporary directory should have a canonical path");
    let expected = format!("{}\nfrom-command-spec\n", canonical_directory.display());
    assert_eq!(stdout, expected.as_bytes());
}

#[cfg(unix)]
#[test]
fn runner_clears_parent_environment_when_requested() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(
        &directory,
        "isolated-env.sh",
        "if env | grep '^CARGO_MANIFEST_DIR=' >/dev/null; then exit 41; fi\nprintf '%s\\n' \"$PROCESS_ALLOWED_VALUE\"",
    );
    let result = SystemProcessRunner.capture_stdout(
        &CommandSpec::new(script)
            .clear_environment()
            .env("PATH", "/usr/bin:/bin")
            .env("PROCESS_ALLOWED_VALUE", "allowed"),
    );

    assert_eq!(
        result.expect("isolated child should not receive the parent secret"),
        b"allowed\n"
    );
}

#[cfg(unix)]
#[test]
fn inherited_mode_returns_success() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(&directory, "success.sh", ":");
    let runner = SystemProcessRunner;
    assert_runner_interface(&runner);

    runner
        .run(&CommandSpec::new(script))
        .expect("successful inherited process should return success");
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn async_runner_keeps_a_single_thread_executor_responsive() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(&directory, "slow-success.sh", "sleep 0.2");
    let executor_progressed = Arc::new(AtomicBool::new(false));
    let progress_flag = Arc::clone(&executor_progressed);
    let heartbeat = tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(25)).await;
        progress_flag.store(true, Ordering::SeqCst);
    });

    SystemProcessRunner
        .run_async(&CommandSpec::new(script))
        .await
        .expect("asynchronous child should succeed");

    assert!(
        executor_progressed.load(Ordering::SeqCst),
        "waiting for a child must not starve loopback proxy tasks"
    );
    heartbeat.await.expect("heartbeat task should join");
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn cancellable_async_runner_kills_and_reaps_active_child() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let pid_path = directory.path().join("child.pid");
    let script = executable_script(
        &directory,
        "long-lived.sh",
        "printf '%s' \"$$\" > \"$PROCESS_PID_FILE\"\nexec sleep 60",
    );
    let spec = CommandSpec::new(script).env("PROCESS_PID_FILE", pid_path.as_os_str());
    let (cancellation_sender, cancellation_receiver) = tokio::sync::watch::channel(false);
    let cancellation_pid_path = pid_path.clone();
    let cancel = tokio::spawn(async move {
        for _ in 0..200 {
            if cancellation_pid_path.is_file() {
                cancellation_sender.send_replace(true);
                return;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        panic!("child did not publish its PID before cancellation deadline");
    });

    let error = tokio::time::timeout(
        Duration::from_secs(5),
        SystemProcessRunner.run_async_cancellable(&spec, cancellation_receiver),
    )
    .await
    .expect("cancellable child should return promptly")
    .expect_err("cancellation should be reported");
    cancel.await.expect("cancellation task should join");

    assert!(error.to_string().contains("cancelled and reaped"));
    let pid = fs::read_to_string(&pid_path)
        .expect("child PID should be recorded")
        .parse::<u32>()
        .expect("child PID should be numeric");
    let still_running = std::process::Command::new("/bin/kill")
        .args(["-0", &pid.to_string()])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("kill probe should execute")
        .success();
    assert!(!still_running, "cancelled child {pid} must be gone");
}

#[cfg(unix)]
#[test]
fn capture_stdout_returns_exact_bytes_while_stderr_is_inherited() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(
        &directory,
        "stdout.sh",
        "printf 'out\\000bytes'; printf 'inherited stderr\\n' >&2",
    );

    let stdout = SystemProcessRunner
        .capture_stdout(&CommandSpec::new(script))
        .expect("stdout should be captured");

    assert_eq!(stdout, b"out\0bytes");
}

#[cfg(unix)]
#[tokio::test(flavor = "current_thread")]
async fn cancellable_log_runner_records_both_streams_and_replaces_stale_output() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(
        &directory,
        "logged-async.sh",
        "printf 'stdout-line\\n'; printf 'stderr-line\\n' >&2",
    );
    let log_path = directory.path().join("process.log");
    fs::write(&log_path, b"stale output\n").expect("stale log should be written");
    let (_cancellation_sender, cancellation_receiver) = tokio::sync::watch::channel(false);

    SystemProcessRunner
        .run_async_cancellable_to_log(&CommandSpec::new(script), cancellation_receiver, &log_path)
        .await
        .expect("logged child should succeed");

    assert_eq!(
        fs::read(&log_path).expect("process log should be readable"),
        b"stdout-line\nstderr-line\n"
    );
}

#[cfg(unix)]
#[test]
fn capture_output_returns_exact_stdout_and_stderr_bytes() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(
        &directory,
        "output.sh",
        "printf 'stdout\\n'; printf 'stderr\\000bytes' >&2",
    );

    let output = SystemProcessRunner
        .capture_output(&CommandSpec::new("/bin/sh").arg(script))
        .expect("both streams should be captured");

    assert_eq!(output.stdout(), b"stdout\n");
    assert_eq!(output.stderr(), b"stderr\0bytes");
}

#[cfg(unix)]
#[test]
fn log_mode_appends_both_streams_to_one_file() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(
        &directory,
        "logged.sh",
        "printf 'stdout-line\\n'; printf 'stderr-line\\n' >&2",
    );
    let log_path = directory.path().join("process.log");
    fs::write(&log_path, b"existing-line\n").expect("initial log should be written");

    SystemProcessRunner
        .run_to_log(&CommandSpec::new(script), &log_path)
        .expect("logged process should run successfully");

    let log = fs::read(&log_path).expect("process log should be readable");
    assert!(log.starts_with(b"existing-line\n"));
    assert!(
        log.windows(b"stdout-line\n".len())
            .any(|part| part == b"stdout-line\n")
    );
    assert!(
        log.windows(b"stderr-line\n".len())
            .any(|part| part == b"stderr-line\n")
    );
}

#[test]
fn missing_program_has_safe_context_and_native_exit_code() {
    const SECRET: &str = "must-not-appear-924bce";
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let missing = directory.path().join("missing-program");
    let spec = CommandSpec::new(&missing)
        .cwd(directory.path())
        .env("SECRET", SECRET);

    let failure = SystemProcessRunner
        .run(&spec)
        .expect_err("missing program should fail to spawn");

    assert!(matches!(failure, InfrastructureError::Native(_)));
    assert_eq!(failure.exit_code(), 1);
    let message = failure.to_string();
    assert!(message.contains("spawn"), "{message}");
    assert!(message.contains("missing-program"), "{message}");
    assert!(message.contains("cwd"), "{message}");
    assert!(!message.contains(SECRET), "{message}");
}

#[test]
fn missing_program_without_configured_cwd_reports_inherited_cwd() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let missing = directory.path().join("missing-program");

    let failure = SystemProcessRunner
        .run(&CommandSpec::new(missing))
        .expect_err("missing program should fail to spawn");

    let message = failure.to_string();
    assert!(message.contains("inherited cwd"), "{message}");
    assert!(!message.contains("cwd None"), "{message}");
}

#[cfg(unix)]
#[test]
fn child_exit_code_is_preserved_without_process_output() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(&directory, "exit-seven.sh", "exit 7");

    let failure = SystemProcessRunner
        .run(&CommandSpec::new(script))
        .expect_err("exit seven should be represented as a child failure");

    assert!(matches!(failure, InfrastructureError::ChildExit { .. }));
    assert_eq!(failure.exit_code(), 7);
}

#[cfg(unix)]
#[test]
fn signaled_child_maps_to_shell_exit_code() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let script = executable_script(&directory, "sigterm.sh", "kill -TERM $$");

    let failure = SystemProcessRunner
        .run(&CommandSpec::new("/bin/sh").arg(script))
        .expect_err("SIGTERM should be represented as a child failure");

    assert!(matches!(failure, InfrastructureError::ChildExit { .. }));
    assert_eq!(failure.exit_code(), 143);
}

#[cfg(windows)]
#[test]
fn windows_inherited_mode_preserves_success_and_nonzero_exit_codes() {
    assert_runner_interface(&SystemProcessRunner);
    SystemProcessRunner
        .run(&CommandSpec::new("cmd.exe").args(["/D", "/S", "/C", "exit /b 0"]))
        .expect("zero exit should succeed");

    let failure = SystemProcessRunner
        .run(&CommandSpec::new("cmd.exe").args(["/D", "/S", "/C", "exit /b 7"]))
        .expect_err("nonzero exit should be represented as a child failure");

    assert!(matches!(failure, InfrastructureError::ChildExit { .. }));
    assert_eq!(failure.exit_code(), 7);
}

#[cfg(windows)]
#[test]
fn windows_runner_propagates_cwd_and_environment_overrides() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let spec = CommandSpec::new("cmd.exe")
        .args(["/D", "/S", "/C", "echo %CD%& echo %PROCESS_TEST_VALUE%"])
        .cwd(directory.path())
        .env("PROCESS_TEST_VALUE", "from-command-spec");

    let stdout = SystemProcessRunner
        .capture_stdout(&spec)
        .expect("cmd.exe should expose cwd and environment");
    let stdout = String::from_utf8(stdout).expect("cmd.exe output should be UTF-8");
    let mut lines = stdout.lines();

    assert_eq!(
        lines
            .next()
            .expect("cwd line should be present")
            .to_ascii_lowercase(),
        directory.path().display().to_string().to_ascii_lowercase()
    );
    assert_eq!(lines.next().map(str::trim), Some("from-command-spec"));
}

#[cfg(windows)]
#[test]
fn windows_capture_output_returns_both_streams() {
    let output = SystemProcessRunner
        .capture_output(&CommandSpec::new("cmd.exe").args([
            "/D",
            "/S",
            "/C",
            "echo stdout-line& echo stderr-line 1>&2",
        ]))
        .expect("cmd.exe streams should be captured");

    assert!(
        output
            .stdout()
            .windows(b"stdout-line".len())
            .any(|part| part == b"stdout-line")
    );
    assert!(
        output
            .stderr()
            .windows(b"stderr-line".len())
            .any(|part| part == b"stderr-line")
    );
}

#[cfg(windows)]
#[test]
fn windows_log_mode_appends_both_streams() {
    let directory = tempfile::tempdir().expect("temporary directory should be created");
    let log_path = directory.path().join("process.log");
    fs::write(&log_path, b"existing-line\r\n").expect("initial log should be written");

    SystemProcessRunner
        .run_to_log(
            &CommandSpec::new("cmd.exe").args([
                "/D",
                "/S",
                "/C",
                "echo stdout-line& echo stderr-line 1>&2",
            ]),
            &log_path,
        )
        .expect("cmd.exe output should be appended");

    let log = fs::read(&log_path).expect("process log should be readable");
    assert!(log.starts_with(b"existing-line\r\n"));
    assert!(
        log.windows(b"stdout-line".len())
            .any(|part| part == b"stdout-line")
    );
    assert!(
        log.windows(b"stderr-line".len())
            .any(|part| part == b"stderr-line")
    );
}