scrollcase-consumer 0.3.2

Verify, prepare, and run caller-supplied local Scrollcase boxes.
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
//! The complete read-only trust chain, over real archives on disk.
//!
//! Every case here builds a box, signs a release over the archive's actual bytes, and then breaks
//! exactly one thing. What is asserted is not that an error occurred but *which* — a check that fires
//! for the wrong reason is a check that has stopped working.

mod support;

use std::io::{Cursor, Write as _};

use scrollcase_consumer::archive::{extract_zip_archive, list_zip_entries};
use scrollcase_consumer::trust::TrustAnchors;
use scrollcase_consumer::verify::inspect_box_archive;
use serde_json::json;
use support::Entry;
use zip::write::SimpleFileOptions;

fn stored_zip(entries: &[(&str, &[u8])]) -> Vec<u8> {
    let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
    for (name, contents) in entries {
        writer
            .start_file(
                *name,
                SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored),
            )
            .unwrap();
        writer.write_all(contents).unwrap();
    }
    writer.finish().unwrap().into_inner()
}

#[test]
fn a_valid_box_passes_the_whole_chain() {
    let fixture = support::valid("archive-valid");
    let inspected = inspect_box_archive(
        &fixture.release_path,
        TrustAnchors::KeyFile(&fixture.key_path),
        Some(&fixture.archive_path),
    )
    .expect("a valid fixture box must pass");

    assert_eq!(inspected.release.release.box_id, "fixture-box");
    assert_eq!(inspected.box_manifest.box_id, "fixture-box");
    assert_eq!(inspected.entries.len(), 3);
}

#[test]
fn the_archive_must_be_the_one_the_release_signed() {
    // Size and hash come from the signed release and are checked before any entry is read.
    let fixture = support::build(
        "archive-size",
        |_| {},
        |_| {},
        |release| release["archive"]["sizeBytes"] = json!(999_999),
    );
    let error = inspect_box_archive(
        &fixture.release_path,
        TrustAnchors::KeyFile(&fixture.key_path),
        Some(&fixture.archive_path),
    )
    .unwrap_err();
    assert!(error.message().contains("Archive size mismatch"), "{error}");

    let fixture = support::build(
        "archive-hash",
        |_| {},
        |_| {},
        |release| release["archive"]["sha256"] = json!("a".repeat(64)),
    );
    let error = inspect_box_archive(
        &fixture.release_path,
        TrustAnchors::KeyFile(&fixture.key_path),
        Some(&fixture.archive_path),
    )
    .unwrap_err();
    assert!(error.message().contains("Archive SHA-256 mismatch"), "{error}");
}

#[test]
fn box_json_must_agree_with_the_signed_release_field_by_field() {
    // The gap this closes: an archive whose hash matches its release perfectly, but which describes
    // a different box. Only comparing the two manifests catches it.
    for (field, mutate) in [
        (
            "modelId",
            Box::new(|manifest: &mut serde_json::Value| {
                manifest["modelId"] = json!("another-model");
            }) as Box<dyn Fn(&mut serde_json::Value)>,
        ),
        (
            "execution",
            Box::new(|manifest: &mut serde_json::Value| {
                manifest["execution"] =
                    json!({ "kind": "python-script", "script": "app/other.py", "defaultArgs": [] });
            }),
        ),
        (
            "environment",
            Box::new(|manifest: &mut serde_json::Value| {
                manifest["environment"] = json!({ "SCROLLCASE_SMUGGLED": "1" });
            }),
        ),
        (
            "provenance",
            Box::new(|manifest: &mut serde_json::Value| {
                manifest["provenance"]["sourceTreeDirty"] = json!(true);
            }),
        ),
    ] {
        // Mutate box.json only: the release keeps describing the original box.
        let fixture = support::build(
            &format!("archive-disagree-{field}"),
            |_| {},
            move |entries| {
                let mut manifest = support::box_manifest();
                mutate(&mut manifest);
                entries[0] = Entry::File(
                    "box.json",
                    serde_json::to_vec_pretty(&manifest).unwrap(),
                    0o644,
                );
            },
            |_| {},
        );
        let error = inspect_box_archive(
            &fixture.release_path,
            TrustAnchors::KeyFile(&fixture.key_path),
            Some(&fixture.archive_path),
        )
        .unwrap_err();
        assert!(
            error.message() == format!("box.json mismatch: {field}"),
            "expected a {field} mismatch, got: {error}"
        );
    }
}

#[test]
fn an_archive_without_its_declared_interpreter_is_refused() {
    let fixture = support::build(
        "archive-no-interpreter",
        |_| {},
        |entries| {
            // The entry point differs per target, so it is asked for rather than spelled out.
            let interpreter = support::native_python_entry_point();
            entries.retain(|entry| !matches!(entry, Entry::File(path, _, _) if *path == interpreter));
        },
        |_| {},
    );
    let error = inspect_box_archive(
        &fixture.release_path,
        TrustAnchors::KeyFile(&fixture.key_path),
        Some(&fixture.archive_path),
    )
    .unwrap_err();
    assert!(error.message().contains("Archive is missing venv/"), "{error}");
}

#[test]
fn an_archive_without_its_declared_script_is_refused() {
    let fixture = support::build(
        "archive-no-script",
        |_| {},
        |entries| {
            entries.retain(|entry| !matches!(entry, Entry::File("app/main.py", _, _)));
        },
        |_| {},
    );
    let error = inspect_box_archive(
        &fixture.release_path,
        TrustAnchors::KeyFile(&fixture.key_path),
        Some(&fixture.archive_path),
    )
    .unwrap_err();
    assert!(error.message().contains("Execution script is missing"), "{error}");
}

#[test]
fn box_json_must_be_an_entry_with_its_own_bytes() {
    // A link resolves, but metadata is read out of the archive, so `box.json` has to be a file.
    let fixture = support::build(
        "archive-box-json-link",
        |_| {},
        |entries| {
            entries[0] = Entry::File("real-box.json", b"{}".to_vec(), 0o644);
            entries.push(Entry::Link("box.json", "real-box.json"));
        },
        |_| {},
    );
    let error = inspect_box_archive(
        &fixture.release_path,
        TrustAnchors::KeyFile(&fixture.key_path),
        Some(&fixture.archive_path),
    )
    .unwrap_err();
    assert!(error.message().contains("missing box.json"), "{error}");
}

#[test]
fn a_link_the_contract_permits_survives_listing_and_extraction() {
    let fixture = support::build(
        "archive-good-link",
        |_| {},
        |entries| {
            entries.push(Entry::File("venv/bin/python3.11", b"#!/bin/sh\n".to_vec(), 0o755));
            entries.push(Entry::Link("venv/bin/python3", "python3.11"));
        },
        |_| {},
    );
    let entries = list_zip_entries(&fixture.archive_path).expect("the link must be carryable");
    assert_eq!(entries.len(), 5);

    let destination = fixture.directory.join("extracted");
    extract_zip_archive(&fixture.archive_path, &destination).expect("extraction must succeed");
    let link = destination.join("venv/bin/python3");
    assert!(std::fs::symlink_metadata(&link).unwrap().is_symlink());
    // Written as the relative string it was validated as, so it means the same thing wherever the
    // box lands.
    assert_eq!(std::fs::read_link(&link).unwrap().to_str().unwrap(), "python3.11");
}

#[test]
fn a_link_out_of_the_payload_is_refused_before_anything_is_written() {
    let fixture = support::build(
        "archive-escaping-link",
        |_| {},
        |entries| entries.push(Entry::Link("venv/bin/escape", "../../../../etc/passwd")),
        |_| {},
    );
    let error = list_zip_entries(&fixture.archive_path).unwrap_err();
    assert!(
        error
            .message()
            .contains("link does not resolve to a file inside the payload"),
        "{error}"
    );

    // And nothing reaches disk: extraction refuses on the same listing, before it writes.
    let destination = fixture.directory.join("extracted");
    assert!(extract_zip_archive(&fixture.archive_path, &destination).is_err());
    assert!(!destination.exists());
}

#[test]
fn nothing_may_be_written_through_a_link() {
    let fixture = support::build(
        "archive-through-link",
        |_| {},
        |entries| {
            entries.push(Entry::File("venv/lib/python3.11/os.py", b"real\n".to_vec(), 0o644));
            entries.push(Entry::Link("venv/lib/python3.1", "python3.11"));
            entries.push(Entry::File(
                "venv/lib/python3.1/evil.py",
                b"planted\n".to_vec(),
                0o644,
            ));
        },
        |_| {},
    );
    let error = list_zip_entries(&fixture.archive_path).unwrap_err();
    // A directory link is refused first, which is exactly why rule 4 is only a second lock.
    assert!(
        error.message().contains("link does not resolve to a file inside the payload")
            || error.message().contains("would be written through a link"),
        "{error}"
    );
}

#[test]
fn extraction_reproduces_the_payload_and_its_modes() {
    let fixture = support::valid("archive-extract");
    let destination = fixture.directory.join("extracted");
    extract_zip_archive(&fixture.archive_path, &destination).unwrap();

    assert!(destination.join("box.json").is_file());
    assert_eq!(
        std::fs::read(destination.join("app/main.py")).unwrap(),
        b"print('fixture')\n"
    );

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt as _;
        let mode = std::fs::metadata(destination.join("venv/bin/python"))
            .unwrap()
            .permissions()
            .mode();
        // The interpreter has to come out executable, or the box cannot run itself.
        assert_eq!(mode & 0o777, 0o755);
    }

    assert_eq!(
        scrollcase_consumer::filesystem::payload_size(&destination).unwrap(),
        std::fs::metadata(destination.join("box.json")).unwrap().len()
            + std::fs::metadata(destination.join(support::native_python_entry_point()))
                .unwrap()
                .len()
            + std::fs::metadata(destination.join("app/main.py")).unwrap().len()
    );
}

#[test]
fn extraction_refuses_to_write_over_an_existing_file() {
    let fixture = support::valid("archive-existing");
    let destination = fixture.directory.join("extracted");
    std::fs::create_dir_all(destination.join("app")).unwrap();
    std::fs::write(destination.join("app/main.py"), b"already here\n").unwrap();

    let error = extract_zip_archive(&fixture.archive_path, &destination).unwrap_err();
    assert!(error.message().contains("cannot write"), "{error}");
    // The file that was already there is untouched.
    assert_eq!(
        std::fs::read(destination.join("app/main.py")).unwrap(),
        b"already here\n"
    );
}

#[test]
fn a_special_entry_is_refused_by_the_real_reader() {
    // The classifier is covered by unit tests; this proves the same refusal through the production
    // reading path, on an archive whose bytes really do declare a fifo.
    let fixture = support::valid("archive-special-entry");
    support::set_entry_file_type(&fixture.archive_path, "app/main.py", 0o010_000);

    let error = list_zip_entries(&fixture.archive_path).unwrap_err();
    assert!(error.message().contains("special entries"), "{error}");

    let destination = fixture.directory.join("extracted");
    assert!(extract_zip_archive(&fixture.archive_path, &destination).is_err());
    assert!(!destination.exists(), "a hostile archive reached the filesystem");
}

#[test]
fn an_encrypted_entry_is_refused_by_the_real_reader() {
    let fixture = support::valid("archive-encrypted-entry");
    support::mark_entry_encrypted(&fixture.archive_path, "app/main.py");

    let error = list_zip_entries(&fixture.archive_path).unwrap_err();
    assert!(error.message().contains("Encrypted ZIP entries"), "{error}");

    let destination = fixture.directory.join("extracted");
    assert!(extract_zip_archive(&fixture.archive_path, &destination).is_err());
    assert!(!destination.exists(), "a hostile archive reached the filesystem");
}

#[test]
fn central_directory_signatures_inside_stored_entries_are_not_index_records() {
    // Already-compressed payloads are stored rather than deflated. Two nested archives therefore
    // carry identical central-directory bytes in the outer archive's file data, but their outer
    // names are distinct and there is no collision to refuse.
    let fixture = support::valid("archive-nested-stored");
    let nested = stored_zip(&[("ecg.npy", b"fixture")]);
    let outer = stored_zip(&[("first.zip", &nested), ("second.zip", &nested)]);
    std::fs::write(&fixture.archive_path, outer).unwrap();

    let entries = list_zip_entries(&fixture.archive_path).expect("nested indexes are payload data");
    assert_eq!(
        entries.iter().map(|entry| entry.path.as_str()).collect::<Vec<_>>(),
        ["first.zip", "second.zip"]
    );
}

#[test]
fn a_name_repeated_in_the_real_central_directory_is_refused() {
    let fixture = support::valid("archive-real-duplicate");
    let mut archive = stored_zip(&[("a.txt", b"first"), ("b.txt", b"second")]);
    let central_headers: Vec<usize> = archive
        .windows(4)
        .enumerate()
        .filter_map(|(offset, bytes)| (bytes == b"PK\x01\x02").then_some(offset))
        .collect();
    assert_eq!(central_headers.len(), 2);
    let second_name = central_headers[1] + 46;
    assert_eq!(&archive[second_name..second_name + 5], b"b.txt");
    archive[second_name..second_name + 5].copy_from_slice(b"a.txt");
    std::fs::write(&fixture.archive_path, archive).unwrap();

    let error = list_zip_entries(&fixture.archive_path).unwrap_err();
    assert!(
        error
            .message()
            .contains("Archive entry collides with another entry: a.txt"),
        "{error}"
    );
}

#[test]
fn a_zip64_central_directory_is_scanned_by_its_declared_record_count() {
    let fixture = support::valid("archive-zip64-directory");
    let file = std::fs::File::create(&fixture.archive_path).unwrap();
    let mut writer = zip::ZipWriter::new(file);
    let options =
        SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
    for index in 0..=u16::MAX {
        writer
            .start_file(format!("entry-{index:05}.txt"), options)
            .unwrap();
    }
    writer.finish().unwrap();

    let entries = list_zip_entries(&fixture.archive_path).expect("ZIP64 directory must be readable");
    assert_eq!(entries.len(), usize::from(u16::MAX) + 1);
}