runnerd-core 0.1.5

Config, domain logic and API types shared by runnerd and its clients
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
//! The verifier against what GNU tar does with the same bytes (ADR 0147): `git archive`'s own output passes and lists
//! as `tar -tzf` lists it, and every shape GNU tar reads differently from a plain reading of the headers is refused:
//! global PAX fields besides the comment, extended headers beyond one `path`, GNU long names, links, entries outside
//! a directory seen before them, and a tar that does not end in two zero blocks and zero padding.

#![allow(
    clippy::unwrap_used,
    reason = "tests: a fixture that cannot be made fails the test"
)]

use std::fs;
use std::io::Write as _;
use std::path::Path;
use std::process::Command;

use flate2::Compression;
use flate2::write::GzEncoder;

use super::{BUDGET, Rejected, listing, verify};
use crate::testdir::TestDir;

const SHA: &str = "08eba0b27e820071cde6df949e0beb9ba4906955";
const TOP: &str = "o-r-08eba0b/";

fn gzip(bytes: &[u8]) -> Vec<u8> {
    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
    encoder.write_all(bytes).unwrap();
    encoder.finish().unwrap()
}

/// A ustar header as `git archive` writes it: `name` split into prefix and name when it is longer than 100 bytes.
fn header(name: &str, kind: u8, size: usize, mode: u32) -> [u8; 512] {
    let mut block = [0_u8; 512];
    let (prefix, name) = if name.len() > 100 {
        let split = name[..=155.min(name.len() - 1)].rfind('/').unwrap();
        (&name[..split], &name[split + 1..])
    } else {
        ("", name)
    };
    block[..name.len()].copy_from_slice(name.as_bytes());
    block[100..108].copy_from_slice(format!("{mode:07o}\0").as_bytes());
    block[108..116].copy_from_slice(b"0000000\0");
    block[116..124].copy_from_slice(b"0000000\0");
    block[124..136].copy_from_slice(format!("{size:011o}\0").as_bytes());
    block[136..148].copy_from_slice(b"14531234567\0");
    block[156] = kind;
    block[257..263].copy_from_slice(b"ustar\0");
    block[263..265].copy_from_slice(b"00");
    block[345..345 + prefix.len()].copy_from_slice(prefix.as_bytes());
    checksum(&mut block);
    block
}

fn checksum(block: &mut [u8; 512]) {
    block[148..156].fill(b' ');
    let sum: u32 = block.iter().map(|&byte| u32::from(byte)).sum();
    block[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes());
}

/// PAX records, each `<length> <key>=<value>\n`.
fn records(pairs: &[(&str, &str)]) -> Vec<u8> {
    let mut out = Vec::new();
    for (key, value) in pairs {
        let body = format!(" {key}={value}\n");
        // The length counts its own digits.
        let mut length = body.len() + 1;
        while body.len() + length.to_string().len() != length {
            length = body.len() + length.to_string().len();
        }
        out.extend(format!("{length}{body}").into_bytes());
    }
    out
}

/// One entry: a header and its data, padded.
fn entry(out: &mut Vec<u8>, name: &str, kind: u8, data: &[u8], mode: u32) {
    out.extend(header(name, kind, data.len(), mode));
    out.extend(data);
    out.resize(out.len().next_multiple_of(512), 0);
}

/// The global header `git archive` opens with.
fn global(out: &mut Vec<u8>, pairs: &[(&str, &str)]) {
    entry(out, "pax_global_header", b'g', &records(pairs), 0o666);
}

/// Two zero blocks, then zeros to a 10240-byte record, as `git archive` ends.
fn end(out: &mut Vec<u8>) {
    out.extend([0_u8; 1024]);
    out.resize(out.len().next_multiple_of(10240), 0);
}

/// A well-formed archive of `SHA` around `body`, which writes its entries after the top directory.
fn archive(body: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
    let mut out = Vec::new();
    global(&mut out, &[("comment", SHA)]);
    entry(&mut out, TOP, b'5', b"", 0o775);
    body(&mut out);
    end(&mut out);
    out
}

/// An archive of only its top directory, after a global header of `pairs`.
fn opened(pairs: &[(&str, &str)]) -> Vec<u8> {
    let mut out = Vec::new();
    global(&mut out, pairs);
    entry(&mut out, TOP, b'5', b"", 0o775);
    end(&mut out);
    out
}

fn check(dir: &TestDir, tar: &[u8]) -> Result<super::Verified, Rejected> {
    let path = dir.0.join("a.tar.gz");
    fs::write(&path, gzip(tar)).unwrap();
    verify(&path, SHA, BUDGET)
}

/// A git command in `repo`, isolated from the host's configuration.
fn git(repo: &Path, home: &Path, args: &[&str]) -> Vec<u8> {
    let output = Command::new("git")
        .args(args)
        .current_dir(repo)
        .env("HOME", home)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_AUTHOR_NAME", "t")
        .env("GIT_AUTHOR_EMAIL", "t@example.com")
        .env("GIT_COMMITTER_NAME", "t")
        .env("GIT_COMMITTER_EMAIL", "t@example.com")
        .output()
        .unwrap();
    assert!(output.status.success(), "git {args:?}: {output:?}");
    output.stdout
}

/// A repository with `files` committed, and its `git archive` as GitHub serves it: gzip, under one top directory.
fn git_archive(
    dir: &TestDir,
    files: &[(&str, &str)],
    links: &[(&str, &str)],
) -> (String, std::path::PathBuf) {
    let repo = dir.0.join("repo");
    let home = dir.0.join("home");
    fs::create_dir_all(&repo).unwrap();
    fs::create_dir_all(&home).unwrap();
    git(&repo, &home, &["init", "-q", "-b", "main"]);
    for (name, text) in files {
        let path = repo.join(name);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, text).unwrap();
    }
    for (name, target) in links {
        std::os::unix::fs::symlink(target, repo.join(name)).unwrap();
    }
    git(&repo, &home, &["add", "-A"]);
    git(&repo, &home, &["commit", "-q", "-m", "c"]);
    let sha = String::from_utf8(git(&repo, &home, &["rev-parse", "HEAD"])).unwrap();
    let sha = sha.trim().to_owned();
    let path = dir.0.join("archive.tar.gz");
    let prefix = format!("--prefix=o-r-{}/", &sha[..7]);
    let bytes = git(
        &repo,
        &home,
        &["archive", "--format=tar.gz", &prefix, "HEAD"],
    );
    fs::write(&path, bytes).unwrap();
    (sha, path)
}

#[test]
fn what_git_archive_writes_passes_and_lists_as_gnu_tar_lists_it() {
    let dir = TestDir::new("verify");
    let deep = format!("{}/file.txt", ["nested-directory"; 8].join("/"));
    let long = format!("dir/{}.txt", "n".repeat(120));
    let (sha, path) = git_archive(
        &dir,
        &[
            ("action.yml", "runs:\n  using: node24\n  main: index.js\n"),
            ("sub/action.yaml", "runs: {}\n"),
            ("sub/action.yml", "runs:\n  using: composite\n  steps: []\n"),
            ("index.js", "console.log(1)\n"),
            (deep.as_str(), "deep"),
            (long.as_str(), "long"),
        ],
        &[],
    );
    let verified = verify(&path, &sha, BUDGET).unwrap();
    let sub = &verified.actions["sub"];
    assert!(sub.yml, "the runner loads action.yml before action.yaml");
    assert_eq!(
        sub.bytes.as_deref(),
        Some(&b"runs:\n  using: composite\n  steps: []\n"[..])
    );
    let tar = Command::new("tar").arg("-tzf").arg(&path).output().unwrap();
    assert!(tar.status.success(), "{tar:?}");
    let mut gnu: Vec<String> = String::from_utf8(tar.stdout)
        .unwrap()
        .lines()
        .map(str::to_owned)
        .collect();
    gnu.sort();
    assert_eq!(
        listing(&path, &sha).unwrap(),
        gnu,
        "what tar unpacks is what was checked"
    );
}

#[test]
fn an_archive_with_a_link_is_refused_and_the_runner_downloads_it_itself() {
    let dir = TestDir::new("verify");
    let (sha, path) = git_archive(
        &dir,
        &[("action.yml", "runs: {}\n")],
        &[("link", "action.yml")],
    );
    assert!(
        matches!(verify(&path, &sha, BUDGET), Err(Rejected::Kind(_))),
        "a link stays out until links are checked as the runner's copy follows them"
    );
}

#[test]
fn pax_records_gnu_tar_reads_otherwise_are_refused() {
    let dir = TestDir::new("verify");
    let file = |out: &mut Vec<u8>| entry(out, &format!("{TOP}a"), b'0', b"a", 0o664);
    let cases: Vec<(&str, Vec<u8>)> = vec![
        (
            "a global path",
            opened(&[("comment", SHA), ("path", "../../evil")]),
        ),
        ("a global size", opened(&[("size", "0"), ("comment", SHA)])),
        (
            "two comments",
            opened(&[("comment", SHA), ("comment", SHA)]),
        ),
        ("a global header after an entry", {
            let mut out = Vec::new();
            global(&mut out, &[("comment", SHA)]);
            entry(&mut out, TOP, b'5', b"", 0o775);
            global(&mut out, &[("comment", SHA)]);
            end(&mut out);
            out
        }),
        (
            "an extended linkpath",
            archive(|out| {
                entry(
                    out,
                    "x",
                    b'x',
                    &records(&[("linkpath", "/etc/passwd")]),
                    0o644,
                );
                file(out);
            }),
        ),
        (
            "two extended paths",
            archive(|out| {
                let path = format!("{TOP}b");
                entry(
                    out,
                    "x",
                    b'x',
                    &records(&[("path", &path), ("path", "../evil")]),
                    0o644,
                );
                file(out);
            }),
        ),
        (
            "an extended mtime",
            archive(|out| {
                entry(out, "x", b'x', &records(&[("mtime", "1")]), 0o644);
                file(out);
            }),
        ),
        (
            "an extended header before the end",
            archive(|out| {
                let path = format!("{TOP}b");
                entry(out, "x", b'x', &records(&[("path", &path)]), 0o644);
            }),
        ),
        (
            "a malformed record",
            archive(|out| {
                entry(out, "x", b'x', b"99 path=o-r-08eba0b/b\n", 0o644);
                file(out);
            }),
        ),
        (
            "a GNU long name",
            archive(|out| {
                entry(
                    out,
                    "././@LongLink",
                    b'L',
                    format!("{TOP}b\0").as_bytes(),
                    0o644,
                );
                file(out);
            }),
        ),
    ];
    for (case, tar) in cases {
        let result = check(&dir, &tar);
        assert!(result.is_err(), "{case} is refused: {result:?}");
    }
    assert!(
        check(&dir, &archive(file)).is_ok(),
        "the same archive without them passes"
    );
}

#[test]
fn a_header_git_archive_does_not_write_is_refused() {
    let dir = TestDir::new("verify");
    let cases: Vec<(&str, Vec<u8>)> = vec![
        (
            "a bad checksum",
            archive(|out| {
                let mut block = header(&format!("{TOP}a"), b'0', 0, 0o664);
                block[148] = b'7';
                out.extend(block);
            }),
        ),
        (
            "GNU's magic",
            archive(|out| {
                let mut block = header(&format!("{TOP}a"), b'0', 0, 0o664);
                block[257..265].copy_from_slice(b"ustar  \0");
                checksum(&mut block);
                out.extend(block);
            }),
        ),
        (
            "a base-256 size",
            archive(|out| {
                let mut block = header(&format!("{TOP}a"), b'0', 0, 0o664);
                block[124..136].copy_from_slice(&[0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
                checksum(&mut block);
                out.extend(block);
            }),
        ),
        (
            "a setuid file",
            archive(|out| entry(out, &format!("{TOP}a"), b'0', b"a", 0o4755)),
        ),
        (
            "a hard link",
            archive(|out| entry(out, &format!("{TOP}a"), b'1', b"", 0o644)),
        ),
        (
            "a symbolic link",
            archive(|out| entry(out, &format!("{TOP}a"), b'2', b"", 0o777)),
        ),
    ];
    for (case, tar) in cases {
        let result = check(&dir, &tar);
        assert!(result.is_err(), "{case} is refused: {result:?}");
    }
    let file = |out: &mut Vec<u8>| entry(out, &format!("{TOP}a"), b'0', b"a", 0o664);
    assert!(
        check(&dir, &archive(file)).is_ok(),
        "the same archive without them passes"
    );
}

#[test]
fn every_entry_sits_in_a_directory_seen_before_it() {
    let dir = TestDir::new("verify");
    let cases: Vec<(&str, Vec<u8>)> = vec![
        (
            "a file used as a directory",
            archive(|out| {
                entry(out, &format!("{TOP}a"), b'0', b"a", 0o664);
                entry(out, &format!("{TOP}a/b"), b'0', b"b", 0o664);
            }),
        ),
        (
            "a directory never listed",
            archive(|out| entry(out, &format!("{TOP}a/b"), b'0', b"b", 0o664)),
        ),
        (
            "a file and a directory of one name",
            archive(|out| {
                entry(out, &format!("{TOP}a"), b'0', b"a", 0o664);
                entry(out, &format!("{TOP}a/"), b'5', b"", 0o775);
            }),
        ),
        ("a file before the top directory", {
            let mut out = Vec::new();
            global(&mut out, &[("comment", SHA)]);
            entry(&mut out, &format!("{TOP}a"), b'0', b"a", 0o664);
            entry(&mut out, TOP, b'5', b"", 0o775);
            end(&mut out);
            out
        }),
        (
            "an extended path outside the top directory",
            archive(|out| {
                entry(out, "x", b'x', &records(&[("path", "../evil")]), 0o644);
                entry(out, &format!("{TOP}a"), b'0', b"a", 0o664);
            }),
        ),
    ];
    for (case, tar) in cases {
        let result = check(&dir, &tar);
        assert!(result.is_err(), "{case} is refused: {result:?}");
    }
}

#[test]
fn a_tar_ends_in_two_zero_blocks_and_nothing_but_zeros_after() {
    let dir = TestDir::new("verify");
    let body = |out: &mut Vec<u8>| {
        global(out, &[("comment", SHA)]);
        entry(out, TOP, b'5', b"", 0o775);
        entry(out, &format!("{TOP}a"), b'0', b"a", 0o664);
    };
    let cases: Vec<(&str, Vec<u8>)> = vec![
        ("no end", {
            let mut out = Vec::new();
            body(&mut out);
            out
        }),
        ("one zero block", {
            let mut out = Vec::new();
            body(&mut out);
            out.extend([0_u8; 512]);
            out
        }),
        ("an entry after one zero block", {
            let mut out = Vec::new();
            body(&mut out);
            out.extend([0_u8; 512]);
            entry(&mut out, &format!("{TOP}hidden"), b'0', b"h", 0o664);
            end(&mut out);
            out
        }),
        ("bytes in the padding", {
            let mut out = Vec::new();
            body(&mut out);
            end(&mut out);
            let last = out.len() - 1;
            out[last] = 1;
            out
        }),
    ];
    for (case, tar) in cases {
        let result = check(&dir, &tar);
        assert!(result.is_err(), "{case} is refused: {result:?}");
    }
}

#[test]
fn a_pax_record_with_a_control_character_is_refused_where_gnu_tar_reads_another_name() {
    let dir = TestDir::new("verify");
    let nul = archive(|out| {
        entry(out, &format!("{TOP}a"), b'0', b"a", 0o664);
        let path = format!("{TOP}a\0b");
        entry(out, "x", b'x', &records(&[("path", &path)]), 0o644);
        entry(out, &format!("{TOP}c"), b'0', b"c", 0o664);
    });
    let path = dir.0.join("nul.tar.gz");
    fs::write(&path, gzip(&nul)).unwrap();
    let tar = Command::new("tar").arg("-tzf").arg(&path).output().unwrap();
    let listed = String::from_utf8_lossy(&tar.stdout).into_owned();
    assert_eq!(
        listed.matches(&format!("{TOP}a\n")).count(),
        2,
        "GNU tar ends the path at its NUL, so it unpacks a second file of the first one's name: {listed:?}"
    );
    assert!(
        matches!(verify(&path, SHA, BUDGET), Err(Rejected::Header(_))),
        "the verifier refuses what GNU tar reads otherwise"
    );
    for control in ["\u{1}", "\t", "\u{7f}", "\r"] {
        let tar = archive(|out| {
            let path = format!("{TOP}a{control}b");
            entry(out, "x", b'x', &records(&[("path", &path)]), 0o644);
            entry(out, &format!("{TOP}c"), b'0', b"c", 0o664);
        });
        let result = check(&dir, &tar);
        assert!(
            result.is_err(),
            "{control:?} in a record is refused: {result:?}"
        );
    }
}