hl-engine 0.1.13

Safe Rust lifecycle API for the standalone HL Linux guest engine
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
use hl_engine::network::Namespace;
use hl_engine::{Config, Engine, Exit, Guest, Stdio};
use std::fs;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::process::Command;
use std::sync::OnceLock;
use std::time::{Duration, Instant};

fn rootfs() -> &'static PathBuf {
    static ROOTFS: OnceLock<PathBuf> = OnceLock::new();
    ROOTFS.get_or_init(|| {
        let path = std::env::temp_dir().join(format!("hl-alpine-{}", std::process::id()));
        let _ = fs::remove_dir_all(&path);
        fs::create_dir(&path).unwrap();
        let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("assets/alpine/alpine-minirootfs-3.24.1-aarch64.tar.gz");
        let status = Command::new("tar")
            .args(["-xzf"])
            .arg(fixture)
            .arg("-C")
            .arg(&path)
            .status()
            .unwrap();
        assert!(status.success(), "cannot extract pinned Alpine fixture");
        path
    })
}

fn alive(pid: u32) -> bool {
    Command::new("kill")
        .args(["-0", &pid.to_string()])
        .status()
        .is_ok_and(|status| status.success())
}

#[test]
fn private_udp_loopback_preserves_datagrams_and_readiness_across_fork() {
    let mut child = Engine::new()
        .command(Guest::Aarch64, "/bin/sh")
        .config(
            Config::new()
                .root(rootfs())
                .network(true)
                .network_namespace(Namespace::new("rust-private-udp").unwrap()),
        )
        .args([
            "-c",
            "( echo UDP_PRIVATE_OK | nc -u -l -p 19231 -w 2 ) & sleep 0.2; echo request | nc -u -w 2 127.0.0.1 19231",
        ])
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut output = String::new();
    child
        .take_stdout()
        .unwrap()
        .read_to_string(&mut output)
        .unwrap();
    assert_eq!(child.wait().unwrap(), Exit::Code(0));
    assert!(output.lines().any(|line| line == "request"));
    assert!(output.lines().any(|line| line == "UDP_PRIVATE_OK"));
}

#[test]
fn private_udp_loopback_is_shared_by_independent_launches() {
    let config = || {
        Config::new()
            .root(rootfs())
            .network(true)
            .network_namespace(Namespace::new("rust-private-udp-launches").unwrap())
    };
    let mut server = Engine::new()
        .command(Guest::Aarch64, "/bin/sh")
        .config(config())
        .args([
            "-c",
            "echo UDP_LAUNCH_OK | nc -u -l -s 127.0.0.1 -p 19232 -w 3",
        ])
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    std::thread::sleep(Duration::from_millis(300));
    let mut client = Engine::new()
        .command(Guest::Aarch64, "/bin/sh")
        .config(config())
        .args(["-c", "echo request | nc -u -w 2 127.0.0.1 19232"])
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut reply = String::new();
    client
        .take_stdout()
        .unwrap()
        .read_to_string(&mut reply)
        .unwrap();
    assert_eq!(client.wait().unwrap(), Exit::Code(0));
    assert_eq!(reply.trim(), "UDP_LAUNCH_OK");
    let mut request = String::new();
    server
        .take_stdout()
        .unwrap()
        .read_to_string(&mut request)
        .unwrap();
    assert_eq!(server.wait().unwrap(), Exit::Code(0));
    assert_eq!(request.trim(), "request");
}

#[test]
fn process_domain_stops_double_forked_new_session_without_touching_siblings() {
    let pid_file = rootfs().join("tmp/domain-daemon.pid");
    let _ = fs::remove_file(&pid_file);
    let mut sibling = Command::new("sleep").arg("30").spawn().unwrap();
    let child = Engine::new()
        .command(Guest::Aarch64, "/bin/sh")
        .config(Config::new().root(rootfs()))
        .args([
            "-c",
            "( setsid sh -c 'sleep 30 </dev/null >/dev/null 2>&1 & echo $! >/tmp/domain-daemon.pid' </dev/null >/dev/null 2>&1 ) & exit 0",
        ])
        .spawn()
        .unwrap();
    let domain = child.domain();
    assert_eq!(child.wait().unwrap(), Exit::Code(0));
    let deadline = Instant::now() + Duration::from_secs(3);
    let daemon = loop {
        if let Ok(text) = fs::read_to_string(&pid_file) {
            if let Ok(pid) = text.trim().parse::<u32>() {
                if alive(pid) {
                    break pid;
                }
            }
        }
        assert!(Instant::now() < deadline, "daemon did not publish its pid");
        std::thread::sleep(Duration::from_millis(10));
    };
    domain.terminate().unwrap();
    domain.terminate().unwrap();
    let deadline = Instant::now() + Duration::from_secs(3);
    while alive(daemon) && Instant::now() < deadline {
        std::thread::sleep(Duration::from_millis(10));
    }
    assert!(!alive(daemon), "domain member survived termination");
    assert!(alive(sibling.id()), "unrelated sibling was terminated");
    sibling.kill().unwrap();
    sibling.wait().unwrap();
}

#[test]
fn process_domain_termination_tolerates_an_unreaped_init() {
    let mut child = Engine::new()
        .command(Guest::Aarch64, "/bin/sleep")
        .config(Config::new().root(rootfs()))
        .arg("30")
        .spawn()
        .unwrap();
    let domain = child.domain();
    child.force_stop().unwrap();
    domain.terminate().unwrap();
    assert_eq!(child.wait().unwrap(), Exit::Signal(9));
}

#[test]
fn public_api_runs_real_alpine_shell_with_process_io() {
    let engine = Engine::new();
    let config = Config::new()
        .root(rootfs())
        .working_dir("/tmp")
        .env("HL_TEST", "alpine");
    let command = engine
        .command(Guest::Aarch64, "/bin/sh")
        .config(config)
        .args([
                "-c",
                "read line; printf 'out:%s:%s:%s\\n' \"$HL_TEST\" \"$PWD\" \"$line\"; printf 'err:%s\\n' \"$1\" >&2; exit 17",
                "shell",
                "argument",
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = command.spawn().unwrap();
    assert_ne!(child.id(), 0);
    child.take_stdin().unwrap().write_all(b"input\n").unwrap();
    let mut stdout = String::new();
    let mut stderr = String::new();
    child
        .take_stdout()
        .unwrap()
        .read_to_string(&mut stdout)
        .unwrap();
    child
        .take_stderr()
        .unwrap()
        .read_to_string(&mut stderr)
        .unwrap();
    assert_eq!(child.wait().unwrap(), Exit::Code(17));
    assert_eq!(stdout, "out:alpine:/tmp:input\n");
    assert_eq!(stderr, "err:argument\n");
}

#[test]
fn production_true_has_empty_stdout_and_stderr() {
    let output = Engine::new()
        .command(Guest::Aarch64, "/bin/true")
        .config(Config::new().root(rootfs()))
        .output()
        .unwrap();
    assert_eq!(output.exit, Exit::Code(0));
    assert!(
        output.stdout.is_empty(),
        "unexpected stdout: {:?}",
        output.stdout
    );
    assert!(
        output.stderr.is_empty(),
        "unexpected stderr: {:?}",
        output.stderr
    );
}

#[test]
fn output_drains_large_stdout_and_stderr_concurrently() {
    let engine = Engine::new();
    let output = engine
        .command(Guest::Aarch64, "/bin/sh")
        .config(Config::new().root(rootfs()))
        .args([
            "-c",
            "i=0; while [ $i -lt 6000 ]; do echo out-$i; echo err-$i >&2; i=$((i+1)); done",
        ])
        .output()
        .unwrap();
    assert_eq!(output.exit, Exit::Code(0));
    assert!(output.stdout.len() > 50_000);
    assert!(output.stderr.len() > 50_000);
    assert!(output.stdout.ends_with(b"out-5999\n"));
    assert!(output.stderr.ends_with(b"err-5999\n"));
}

#[test]
fn external_term_reaches_the_guest_handler() {
    let mut child = Engine::new()
        .command(Guest::Aarch64, "/bin/sh")
        .config(Config::new().root(rootfs()))
        .args([
            "-c",
            "trap 'printf GOT_TERM; exit 0' TERM; printf READY; while :; do :; done",
        ])
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let id = child.id().to_string();
    let mut stdout = child.take_stdout().unwrap();
    let mut output = [0_u8; 5];
    stdout.read_exact(&mut output).unwrap();
    assert_eq!(&output, b"READY");
    assert!(Command::new("kill")
        .args(["-TERM", &id])
        .status()
        .unwrap()
        .success());
    let mut rest = Vec::new();
    stdout.read_to_end(&mut rest).unwrap();
    assert_eq!(child.wait().unwrap(), Exit::Code(0));
    assert_eq!(rest, b"GOT_TERM");
}

#[test]
fn piped_streams_enforce_their_direction() {
    let engine = Engine::new();
    let mut child = engine
        .command(Guest::Aarch64, "/bin/echo")
        .config(Config::new().root(rootfs()))
        .arg("hello")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut input = child.take_stdin().unwrap();
    let mut output = child.take_stdout().unwrap();
    assert!(input.read(&mut [0]).is_err());
    assert!(output.write_all(b"wrong direction").is_err());
    drop(input);
    let mut text = String::new();
    output.read_to_string(&mut text).unwrap();
    assert_eq!(text, "hello\n");
    assert_eq!(child.wait().unwrap(), Exit::Code(0));
}

#[test]
fn guest_ownership_is_seeded_and_shared_by_inode() {
    let name = format!("owner-{}", std::process::id());
    let relative = PathBuf::from("tmp").join(&name);
    let hard_relative = PathBuf::from("tmp").join(format!("{name}-hard"));
    let file = rootfs().join(&relative);
    let hard = rootfs().join(&hard_relative);
    fs::write(&file, b"ownership\n").unwrap();
    fs::hard_link(&file, &hard).unwrap();

    let script = format!(
        "stat -c '%u:%g' /{0}; stat -c '%u:%g' /{1}; (chown 56:78 /{1}); stat -c '%u:%g' /{0}",
        relative.display(),
        hard_relative.display()
    );
    let output = Engine::new()
        .command(Guest::Aarch64, "/bin/sh")
        .config(Config::new().root(rootfs()).owner(&relative, 12, 34))
        .args(["-c", &script])
        .output()
        .unwrap();

    assert_eq!(output.exit, Exit::Code(0));
    assert_eq!(output.stdout, b"12:34\n12:34\n56:78\n");
    assert!(output.stderr.is_empty());
    fs::remove_file(hard).unwrap();
    fs::remove_file(file).unwrap();
}

#[test]
fn guest_ownership_is_seeded_for_overlay_lower_entries() {
    let name = format!("overlay-owner-{}", std::process::id());
    let relative = PathBuf::from("tmp").join(&name);
    let file = rootfs().join(&relative);
    fs::write(&file, b"ownership\n").unwrap();
    let overlay = std::env::temp_dir().join(format!("hl-{name}"));
    let _ = fs::remove_dir_all(&overlay);
    fs::create_dir(&overlay).unwrap();
    let upper = overlay.join("upper");
    let work = overlay.join("work");
    fs::create_dir(&upper).unwrap();
    fs::create_dir(&work).unwrap();

    let output = Engine::new()
        .command(Guest::Aarch64, "/bin/stat")
        .config(
            Config::new()
                .overlay(vec![rootfs().clone()], upper, work)
                .owner(&relative, 12, 34),
        )
        .args(["-c", "%u:%g", &format!("/{}", relative.display())])
        .output()
        .unwrap();

    assert_eq!(output.exit, Exit::Code(0));
    assert_eq!(output.stdout, b"12:34\n");
    assert!(output.stderr.is_empty());
    fs::remove_dir_all(overlay).unwrap();
    fs::remove_file(file).unwrap();
}

#[test]
fn image_symlink_chain_can_open_synthetic_standard_error() {
    let name = format!("stderr-alias-{}", std::process::id());
    let relative = PathBuf::from("tmp").join(&name);
    let link = rootfs().join(&relative);
    let _ = fs::remove_file(&link);
    #[cfg(unix)]
    std::os::unix::fs::symlink("/dev/stderr", &link).unwrap();

    let command = format!(
        "test -d /proc/self/fd/ && printf SYNTHETIC_STDERR_OK > /{}",
        relative.display()
    );
    let output = Engine::new()
        .command(Guest::Aarch64, "/bin/sh")
        .config(Config::new().root(rootfs()))
        .args(["-c", &command])
        .output()
        .unwrap();

    assert_eq!(output.exit, Exit::Code(0));
    assert_eq!(output.stderr, b"SYNTHETIC_STDERR_OK");
    fs::remove_file(link).unwrap();
}

#[test]
fn overlay_image_symlink_chain_can_open_synthetic_standard_output() {
    let name = format!("stdout-alias-{}", std::process::id());
    let relative = PathBuf::from("tmp").join(&name);
    let link = rootfs().join(&relative);
    let _ = fs::remove_file(&link);
    #[cfg(unix)]
    std::os::unix::fs::symlink("/dev/stdout", &link).unwrap();
    let overlay = std::env::temp_dir().join(format!("hl-{name}"));
    let upper = overlay.join("upper");
    let work = overlay.join("work");
    fs::create_dir_all(&upper).unwrap();
    fs::create_dir_all(&work).unwrap();

    let command = format!("printf SYNTHETIC_STDOUT_OK > /{}", relative.display());
    let output = Engine::new()
        .command(Guest::Aarch64, "/bin/sh")
        .config(Config::new().overlay(vec![rootfs().clone()], upper, work))
        .args(["-c", &command])
        .output()
        .unwrap();

    assert_eq!(output.exit, Exit::Code(0));
    assert_eq!(output.stdout, b"SYNTHETIC_STDOUT_OK");
    fs::remove_dir_all(overlay).unwrap();
    fs::remove_file(link).unwrap();
}