team-ljyzipelo

공개
964줄36 KB
1use super::*;
2use std::{fs::File, io::Read};
3
4fn generate(s: &Scratch, kind: &str, size: u64) {
5 if let Some(method) = kind.strip_prefix("7z-") {
6 assert!(
7 Command::new("python3")
8 .arg(
9 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
10 .join("../../tests/rust-archive-worker/seven_zip_large.py")
11 )
12 .arg(&s.0)
13 .arg(method)
14 .arg(size.to_string())
15 .status()
16 .unwrap()
17 .success()
18 );
19 return;
20 }
21 assert!(
22 Command::new("python3")
23 .arg(
24 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
25 .join("../../tests/rust-archive-worker/hardening_cases.py")
26 )
27 .arg(&s.0)
28 .arg(kind)
29 .arg(size.to_string())
30 .status()
31 .unwrap()
32 .success()
33 );
34}
35fn start(s: &Scratch, gzip: bool, output: u64) -> Start {
36 fs::DirBuilder::new().create(s.0.join("output")).unwrap();
37 #[cfg(unix)]
38 {
39 use std::os::unix::fs::PermissionsExt;
40 fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
41 }
42 Start {
43 action: Action::Extract {
44 archive: s.path("input"),
45 destination: s.path("output"),
46 selection: Selection::All,
47 list_id: None,
48 gzip_output_name: gzip.then(|| "payload.bin".to_owned()),
49 },
50 limits: Limits {
51 output,
52 ..Limits::default()
53 },
54 }
55}
56fn assert_zero_file(path: &std::path::Path, length: u64) {
57 let mut file = File::open(path).unwrap();
58 assert_eq!(file.metadata().unwrap().len(), length);
59 let mut buffer = [0; 65536];
60 let mut total = 0;
61 loop {
62 let n = file.read(&mut buffer).unwrap();
63 if n == 0 {
64 break;
65 }
66 assert!(buffer[..n].iter().all(|b| *b == 0));
67 total += n as u64;
68 }
69 assert_eq!(total, length);
70}
71#[test]
72fn streaming_defaults_and_invalid_seven_zip_header() {
73 assert_eq!(Limits::default().input, u64::MAX);
74 assert_eq!(Limits::default().output, 16 * 1024 * 1024 * 1024);
75 assert!(
76 !Limits {
77 output: 16 * 1024 * 1024 * 1024 + 1,
78 ..Limits::default()
79 }
80 .valid()
81 );
82 let s = Scratch::new();
83 let file = File::create(s.0.join("input")).unwrap();
84 (&file).write_all(b"7z\xbc\xaf\x27\x1c").unwrap();
85 file.set_len(32).unwrap();
86 let events = execute(start(&s, false, Limits::default().output));
87 assert_eq!(terminal(&events).error, ErrorCode::Integrity);
88 assert_eq!(terminal(&events).created_count, 0);
89}
90#[test]
91fn streaming_zip64_local_headers_and_chunk_boundaries() {
92 let s = Scratch::new();
93 generate(&s, "zip64", 9 * 1024 * 1024 + 13);
94 let events = execute(start(&s, false, Limits::default().output));
95 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
96 assert_zero_file(&s.0.join("output/payload.bin"), 9 * 1024 * 1024 + 13);
97}
98#[test]
99fn generated_zero_deflate_zip_round_trips_through_list_and_extract() {
100 let s = Scratch::new();
101 fs::write(s.0.join("source"), vec![0; 2 * 1024 * 1024]).unwrap();
102 let events = execute(Start {
103 action: Action::CreateZip {
104 sources: vec![Source {
105 path: s.path("source"),
106 archive_name: "payload.bin".into(),
107 }],
108 output_file: s.path("input"),
109 method: Method::Deflate,
110 encryption: Encryption::None,
111 },
112 limits: Limits::default(),
113 });
114 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
115 let events = execute(Start {
116 action: Action::List {
117 archive: s.path("input"),
118 },
119 limits: Limits::default(),
120 });
121 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
122 let list_id = events
123 .iter()
124 .find_map(|e| match e {
125 Message::ListEnd { list_id, .. } => Some(list_id.clone()),
126 _ => None,
127 })
128 .unwrap();
129 assert!(events.iter().any(|e| matches!(e, Message::Entry(entry)
130 if entry.size == 2 * 1024 * 1024 && entry.size > entry.compressed_size * 1000)));
131 let mut request = start(&s, false, Limits::default().output);
132 if let Action::Extract { list_id: id, .. } = &mut request.action {
133 *id = Some(list_id);
134 }
135 let events = execute(request);
136 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
137 assert_zero_file(&s.0.join("output/payload.bin"), 2 * 1024 * 1024);
138}
139#[test]
140fn streaming_high_ratio_zip_extracts_below_total_limit() {
141 let s = Scratch::new();
142 generate(&s, "bomb", 16 * 1024 * 1024);
143 let events = execute(start(&s, false, Limits::default().output));
144 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
145 assert_zero_file(&s.0.join("output/payload.bin"), 16 * 1024 * 1024);
146}
147#[test]
148fn streaming_tar_and_gzip_truncation_never_publish() {
149 for kind in ["tar", "targz", "gzip"] {
150 let s = Scratch::new();
151 generate(&s, kind, 1024 * 1024 + 1);
152 let file = fs::OpenOptions::new()
153 .write(true)
154 .open(s.0.join("input"))
155 .unwrap();
156 file.set_len(file.metadata().unwrap().len() - 1).unwrap();
157 let events = execute(start(&s, kind == "gzip", Limits::default().output));
158 assert_eq!(
159 terminal(&events).outcome,
160 Outcome::Failed,
161 "{kind}: {events:?}"
162 );
163 assert_eq!(terminal(&events).created_count, 0);
164 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
165 }
166}
167
168#[test]
169fn zip64_directory_and_descriptor_interoperate() {
170 for kind in ["central64", "descriptor64"] {
171 let s = Scratch::new();
172 generate(&s, kind, 65536 + 19);
173 let events = execute(start(&s, false, Limits::default().output));
174 assert_eq!(
175 terminal(&events).outcome,
176 Outcome::Completed,
177 "{kind}: {events:?}"
178 );
179 assert_zero_file(&s.0.join("output/payload.bin"), 65536 + 19);
180 }
181}
182#[test]
183fn zip64_offset_only_keeps_32_bit_descriptors() {
184 for kind in ["offset64-descriptor-signed", "offset64-descriptor-unsigned"] {
185 let s = Scratch::new();
186 generate(&s, kind, 65536 + 19);
187 let events = execute(Start {
188 action: Action::List {
189 archive: s.path("input"),
190 },
191 limits: Limits::default(),
192 });
193 assert_eq!(
194 terminal(&events).outcome,
195 Outcome::Completed,
196 "{kind}: {events:?}"
197 );
198 let events = execute(start(&s, false, Limits::default().output));
199 assert_eq!(
200 terminal(&events).outcome,
201 Outcome::Completed,
202 "{kind}: {events:?}"
203 );
204 assert_zero_file(&s.0.join("output/payload.bin"), 65536 + 19);
205 }
206}
207#[test]
208fn zip64_locator_with_ordinary_eocd_fields_interoperates() {
209 let s = Scratch::new();
210 generate(&s, "locator64", 20);
211 assert_eq!(fs::metadata(s.0.join("input")).unwrap().len(), 260);
212 let events = execute(Start {
213 action: Action::List {
214 archive: s.path("input"),
215 },
216 limits: Limits::default(),
217 });
218 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
219 let events = execute(start(&s, false, Limits::default().output));
220 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
221 assert_zero_file(&s.0.join("output/payload.bin"), 20);
222}
223#[test]
224fn zip64_locator_corruption_never_publishes() {
225 for (kind, error) in [
226 ("locator64-bad-offset", ErrorCode::Integrity),
227 ("locator64-bad-size", ErrorCode::Integrity),
228 ("locator64-conflicting-count", ErrorCode::Integrity),
229 ("locator64-multidisk", ErrorCode::UnsupportedFeature),
230 ] {
231 let s = Scratch::new();
232 generate(&s, kind, 20);
233 let events = execute(start(&s, false, Limits::default().output));
234 assert_eq!(terminal(&events).error, error, "{kind}: {events:?}");
235 assert_eq!(terminal(&events).publication, Publication::None);
236 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
237 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
238 }
239}
240#[test]
241fn classic_directory_comment_is_not_a_zip64_locator() {
242 let s = Scratch::new();
243 generate(&s, "classic-locator-decoy", 20);
244 let events = execute(start(&s, false, Limits::default().output));
245 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
246 assert_zero_file(&s.0.join("output/payload.bin"), 20);
247}
248#[test]
249fn untrusted_zip64_u64_sizes_and_offsets_never_allocate_or_publish() {
250 for (kind, error) in [
251 ("central64-size-overflow", ErrorCode::Limit),
252 ("central64-offset-overflow", ErrorCode::Integrity),
253 ] {
254 let s = Scratch::new();
255 generate(&s, kind, 1024);
256 let events = execute(start(&s, false, Limits::default().output));
257 assert_eq!(terminal(&events).error, error, "{kind}: {events:?}");
258 assert_eq!(terminal(&events).publication, Publication::None);
259 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
260 }
261}
262#[test]
263fn gzip_high_ratio_members_extract_below_total_limit() {
264 let s = Scratch::new();
265 generate(&s, "gzip-bomb-joined", 16 * 1024 * 1024);
266 let events = execute(start(&s, true, Limits::default().output));
267 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
268 assert_zero_file(&s.0.join("output/payload.bin"), 32 * 1024 * 1024);
269}
270#[test]
271fn streamed_aes_counter_survives_many_read_chunks() {
272 let s = Scratch::new();
273 generate(&s, "store", 129 * 1024 * 1024 + 17);
274 fs::rename(s.0.join("input"), s.0.join("source")).unwrap();
275 let events = interactive(
276 Start {
277 action: Action::CreateZip {
278 sources: vec![Source {
279 path: s.path("source"),
280 archive_name: "payload.bin".to_owned(),
281 }],
282 output_file: s.path("input"),
283 method: Method::Store,
284 encryption: Encryption::Aes256,
285 },
286 limits: Limits::default(),
287 },
288 |id, _, _| password_reply(id, TEST_PASSWORD),
289 );
290 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
291 let events = interactive(start(&s, false, Limits::default().output), |id, _, _| {
292 password_reply(id, TEST_PASSWORD)
293 });
294 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
295 let mut source = File::open(s.0.join("source")).unwrap();
296 let mut output = File::open(s.0.join("output/payload.bin")).unwrap();
297 let mut a = [0; 65536];
298 let mut b = [0; 65536];
299 loop {
300 let n = source.read(&mut a).unwrap();
301 output.read_exact(&mut b[..n]).unwrap();
302 assert_eq!(a[..n], b[..n]);
303 if n == 0 {
304 break;
305 }
306 }
307 assert_eq!(
308 source.metadata().unwrap().len(),
309 output.metadata().unwrap().len()
310 );
311}
312
313#[test]
314fn seven_zip_output_total_rejects_before_decode() {
315 let s = Scratch::new();
316 let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
317 .join("../../tests/rust-archive-worker/seven_zip_large.py");
318 assert!(
319 Command::new("python3")
320 .arg(helper)
321 .arg(&s.0)
322 .arg("lzma2")
323 .arg("1024")
324 .arg((Limits::default().output + 1).to_string())
325 .status()
326 .unwrap()
327 .success()
328 );
329 let events = execute(start(&s, false, Limits::default().output));
330 assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}");
331 assert_eq!(terminal(&events).publication, Publication::None);
332 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
333}
334#[test]
335fn streamed_creation_limits_sum_source_bytes() {
336 for limit in [131071, 131072] {
337 let s = Scratch::new();
338 fs::write(s.0.join("a"), vec![0; 65536]).unwrap();
339 fs::write(s.0.join("b"), vec![0; 65536]).unwrap();
340 let events = execute(Start {
341 action: Action::CreateZip {
342 sources: vec![
343 Source {
344 path: s.path("a"),
345 archive_name: "a".into(),
346 },
347 Source {
348 path: s.path("b"),
349 archive_name: "b".into(),
350 },
351 ],
352 output_file: s.path("input"),
353 method: Method::Deflate,
354 encryption: Encryption::None,
355 },
356 limits: Limits {
357 output: limit,
358 ..Limits::default()
359 },
360 });
361 assert_eq!(
362 terminal(&events).error,
363 if limit == 131072 {
364 ErrorCode::None
365 } else {
366 ErrorCode::Limit
367 },
368 "{events:?}"
369 );
370 assert_eq!(s.0.join("input").exists(), limit == 131072);
371 }
372}
373#[test]
374fn streamed_seven_zip_honors_exact_output_boundary() {
375 for limit in [65535, 65536] {
376 let s = Scratch::new();
377 generate(&s, "7z-lzma2", 65536);
378 let events = execute(start(&s, false, limit));
379 assert_eq!(
380 terminal(&events).error,
381 if limit == 65536 {
382 ErrorCode::None
383 } else {
384 ErrorCode::Limit
385 },
386 "{events:?}"
387 );
388 if limit == 65536 {
389 assert_zero_file(&s.0.join("output/payload.bin"), 65536);
390 } else {
391 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
392 }
393 }
394}
395
396#[cfg(target_os = "linux")]
397mod linux {
398 use super::*;
399 use std::{
400 os::raw::c_long,
401 time::{Duration, Instant},
402 };
403 #[repr(C)]
404 #[derive(Default)]
405 struct Usage {
406 user: [c_long; 2],
407 system: [c_long; 2],
408 max_rss: c_long,
409 rest: [c_long; 13],
410 }
411 unsafe extern "C" {
412 fn wait4(pid: i32, status: *mut i32, options: i32, usage: *mut Usage) -> i32;
413 fn prctl(option: i32, ...) -> i32;
414 fn kill(pid: i32, signal: i32) -> i32;
415 }
416 fn command() -> Command {
417 let worker = std::env::var_os("ZIPELO_BASELINE_WORKER")
418 .map(PathBuf::from)
419 .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_zipelo-archive-worker")));
420 Command::new(worker)
421 }
422 fn staging(s: &Scratch) -> PathBuf {
423 use std::os::unix::fs::DirBuilderExt;
424 let path = s.0.join("staging");
425 fs::DirBuilder::new().mode(0o700).create(&path).unwrap();
426 path
427 }
428 fn spawn(s: &Scratch, mut start: Start, mode: Option<&str>) -> std::process::Child {
429 if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() {
430 start.limits = Limits {
431 input: 64 * 1024 * 1024,
432 output: 128 * 1024 * 1024,
433 entries: 10000,
434 };
435 }
436 let mut cmd = command();
437 cmd.env("TMPDIR", staging(s))
438 .stdin(Stdio::piped())
439 .stdout(File::create(s.0.join("events")).unwrap())
440 .stderr(File::create(s.0.join("stderr")).unwrap());
441 if let Some(mode) = mode {
442 cmd.env("LD_PRELOAD", shim(s))
443 .env("ZIPELO_TEST_FAULT", mode)
444 .env("ZIPELO_TEST_MARKER", s.0.join("paused"))
445 .env("ZIPELO_TEST_RELEASE", s.0.join("release"));
446 }
447 let mut child = cmd.spawn().unwrap();
448 Writer::new(child.stdin.take().unwrap(), 17)
449 .send(&Message::Start(start))
450 .unwrap();
451 child
452 }
453 fn wait(pid: u32) -> (i32, u64) {
454 let deadline = Instant::now() + Duration::from_secs(320);
455 loop {
456 let mut status = 0;
457 let mut usage = Usage::default();
458 let r = unsafe { wait4(pid as i32, &mut status, 1, &mut usage) };
459 if r == pid as i32 {
460 return (status, usage.max_rss as u64 * 1024);
461 }
462 assert!(
463 r >= 0 || std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted
464 );
465 if Instant::now() > deadline {
466 unsafe {
467 kill(pid as i32, 9);
468 wait4(pid as i32, &mut status, 0, &mut usage);
469 }
470 panic!("worker timeout");
471 }
472 std::thread::sleep(Duration::from_millis(10));
473 }
474 }
475 fn events(s: &Scratch) -> Vec<Message> {
476 assert!(fs::read(s.0.join("stderr")).unwrap().is_empty());
477 let mut reader = Reader::new(File::open(s.0.join("events")).unwrap());
478 let mut result = Vec::new();
479 while let Some((_, _, message)) = reader.read().unwrap() {
480 result.push(message);
481 }
482 result
483 }
484 fn shim(s: &Scratch) -> PathBuf {
485 let path = s.0.join("io_fault.so");
486 assert!(
487 Command::new("cc")
488 .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
489 .arg(
490 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
491 .join("../../tests/rust-archive-worker/io_fault.c")
492 )
493 .arg("-ldl")
494 .arg("-o")
495 .arg(&path)
496 .status()
497 .unwrap()
498 .success()
499 );
500 path
501 }
502
503 #[test]
504 fn gigabyte_seven_zip_and_zip_creation_stay_below_64_mib() {
505 let mut measurements = Vec::new();
506 for method in ["copy", "lzma", "lzma2"] {
507 let s = Scratch::new();
508 generate(&s, &format!("7z-{method}"), 1024 * 1024 * 1024);
509 let request = start(&s, false, Limits::default().output);
510 let child = spawn(&s, request, None);
511 let (status, rss) = wait(child.id());
512 assert_eq!(status, 0, "{method}");
513 let events = events(&s);
514 assert_eq!(
515 terminal(&events).outcome,
516 Outcome::Completed,
517 "{method}: {events:?}"
518 );
519 assert_eq!(terminal(&events).publication, Publication::Complete);
520 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
521 assert_eq!(terminal(&events).created_count, 1);
522 assert!(rss <= 64 * 1024 * 1024, "{method}: RSS {rss}");
523 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024 * 1024);
524 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
525 measurements.push(format!("7z-{method}: {rss}"));
526 }
527 for (method, length) in [
528 (Method::Store, 1u64 << 30),
529 (Method::Deflate, 1 << 30),
530 (Method::Deflate, (1 << 32) + 17),
531 ] {
532 let s = Scratch::new();
533 File::create(s.0.join("source"))
534 .unwrap()
535 .set_len(length)
536 .unwrap();
537 let request = Start {
538 action: Action::CreateZip {
539 sources: vec![Source {
540 path: s.path("source"),
541 archive_name: "payload.bin".into(),
542 }],
543 output_file: s.path("input"),
544 method,
545 encryption: Encryption::None,
546 },
547 limits: Limits::default(),
548 };
549 let child = spawn(&s, request, None);
550 let (status, rss) = wait(child.id());
551 assert_eq!(status, 0);
552 let created = events(&s);
553 assert_eq!(
554 terminal(&created).outcome,
555 Outcome::Completed,
556 "{method:?}: {created:?}"
557 );
558 assert!(rss <= 64 * 1024 * 1024, "{method:?}: RSS {rss}");
559 assert!(Command::new("python3").arg("-c").arg(
560 "import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); assert z.getinfo('payload.bin').file_size==int(sys.argv[2]); assert z.testzip() is None"
561 ).arg(s.0.join("input")).arg(length.to_string()).status().unwrap().success());
562 fs::remove_dir(s.0.join("staging")).unwrap();
563 let request = start(&s, false, Limits::default().output);
564 let child = spawn(&s, request, None);
565 assert_eq!(wait(child.id()).0, 0);
566 assert_eq!(terminal(&events(&s)).outcome, Outcome::Completed);
567 assert_zero_file(&s.0.join("output/payload.bin"), length);
568 measurements.push(format!("create-{method:?}-{length}: {rss}"));
569 }
570 println!(
571 "1 GiB 7z/creation peak RSS bytes: {}",
572 measurements.join(", ")
573 );
574 fs::write(
575 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
576 .join("../../tests/ci/seven-zip-streaming-rss.log"),
577 measurements.join("\n") + "\n",
578 )
579 .unwrap();
580 }
581 #[test]
582 fn seven_zip_and_creation_disk_errors_cleanup_staging_and_partial_output() {
583 for create in [false, true] {
584 for mode in ["codec-full", "full", "space-destination", "space-error"] {
585 let s = Scratch::new();
586 let request = if create {
587 fs::write(s.0.join("source"), vec![0; 1024 * 1024]).unwrap();
588 Start {
589 action: Action::CreateZip {
590 sources: vec![Source {
591 path: s.path("source"),
592 archive_name: "payload.bin".into(),
593 }],
594 output_file: s.path("input"),
595 method: Method::Deflate,
596 encryption: Encryption::None,
597 },
598 limits: Limits::default(),
599 }
600 } else {
601 generate(&s, "7z-lzma2", 1024 * 1024);
602 start(&s, false, Limits::default().output)
603 };
604 let child = spawn(&s, request, Some(mode));
605 assert_eq!(wait(child.id()).0, 0);
606 let messages = events(&s);
607 let end = terminal(&messages);
608 assert_eq!(
609 end.error,
610 if mode == "space-error" {
611 ErrorCode::Io
612 } else {
613 ErrorCode::DiskFull
614 },
615 "{create} {mode}: {messages:?}"
616 );
617 assert_eq!(end.publication, Publication::None);
618 assert_eq!(end.retained_partial_count, 0);
619 assert_eq!(end.cleanup, Cleanup::Complete);
620 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
621 if create {
622 assert!(!s.0.join("input").exists());
623 } else {
624 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
625 }
626 }
627 }
628 }
629
630 #[test]
631 fn gigabyte_formats_stay_below_64_mib_peak_rss() {
632 let mut measurements = Vec::new();
633 for kind in ["store", "deflate", "tar", "gzip", "targz"] {
634 let s = Scratch::new();
635 generate(&s, kind, 1024 * 1024 * 1024);
636 let request = start(&s, kind == "gzip", Limits::default().output);
637 let child = spawn(&s, request, None);
638 let (status, rss) = wait(child.id());
639 assert_eq!(status, 0, "{kind}");
640 let events = events(&s);
641 assert_eq!(
642 terminal(&events).outcome,
643 Outcome::Completed,
644 "{kind}: {events:?}"
645 );
646 assert_eq!(terminal(&events).publication, Publication::Complete);
647 assert!(rss <= 64 * 1024 * 1024, "{kind}: RSS {rss}");
648 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024 * 1024);
649 measurements.push(format!("{kind}: {rss}"));
650 }
651 println!(
652 "1 GiB extraction peak RSS bytes: {}",
653 measurements.join(", ")
654 );
655 fs::write(
656 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/ci/streaming-rss.log"),
657 measurements.join("\n") + "\n",
658 )
659 .unwrap();
660 }
661 #[test]
662 fn enospc_at_create_or_after_partial_write_cleans_output() {
663 for mode in [
664 "create-full",
665 "full",
666 "stage-full",
667 "temp-full",
668 "sync-full",
669 ] {
670 let s = Scratch::new();
671 generate(&s, "store", 1024 * 1024);
672 fs::write(s.0.join("preserve"), b"original").unwrap();
673 fs::create_dir(s.0.join("zipelo-source")).unwrap();
674 fs::rename(s.0.join("input"), s.0.join("zipelo-source/zipelo-input")).unwrap();
675 let mut request = start(&s, false, Limits::default().output);
676 if let Action::Extract { archive, .. } = &mut request.action {
677 *archive = s.path("zipelo-source/zipelo-input");
678 }
679 let child = spawn(&s, request, Some(mode));
680 assert_eq!(wait(child.id()).0, 0);
681 let events = events(&s);
682 let t = terminal(&events);
683 assert_eq!(t.error, ErrorCode::DiskFull, "{mode}: {events:?}");
684 assert_eq!(
685 t.detail,
686 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
687 );
688 assert_eq!(t.publication, Publication::None);
689 assert_eq!(t.retained_partial_count, 0);
690 assert_eq!(t.cleanup, Cleanup::Complete);
691 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
692 assert_eq!(fs::read(s.0.join("preserve")).unwrap(), b"original");
693 }
694 }
695 #[test]
696 fn disk_space_preflight_rejects_without_outputs_and_closes_staging() {
697 for mode in [
698 "space-stage",
699 "space-destination",
700 "space-combined",
701 "space-error",
702 ] {
703 let s = Scratch::new();
704 generate(&s, "store", 1024 * 1024);
705 let request = start(&s, false, Limits::default().output);
706 let child = spawn(&s, request, Some(mode));
707 assert_eq!(wait(child.id()).0, 0);
708 let events = events(&s);
709 let t = terminal(&events);
710 let expected = if mode == "space-error" {
711 ErrorCode::Io
712 } else {
713 ErrorCode::DiskFull
714 };
715 assert_eq!(t.error, expected, "{mode}: {events:?}");
716 assert_eq!(t.publication, Publication::None);
717 assert_eq!(t.cleanup, Cleanup::Complete);
718 assert_eq!(t.created_count, 0);
719 assert!(t.detail.contains("디스크 여유 공간"));
720 assert!(s.0.join("paused").exists());
721 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
722 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
723 }
724 }
725 #[test]
726 fn disk_full_during_directory_sync_retains_reported_outputs() {
727 for nested in [false, true] {
728 let s = Scratch::new();
729 fs::write(s.0.join("source"), vec![0; 1024]).unwrap();
730 let name = if nested {
731 "folder/payload.bin"
732 } else {
733 "payload.bin"
734 };
735 let created = execute(Start {
736 action: Action::CreateZip {
737 sources: vec![Source {
738 path: s.path("source"),
739 archive_name: name.into(),
740 }],
741 output_file: s.path("input"),
742 method: Method::Store,
743 encryption: Encryption::None,
744 },
745 limits: Limits::default(),
746 });
747 assert_eq!(terminal(&created).outcome, Outcome::Completed);
748 let request = start(&s, false, Limits::default().output);
749 let child = spawn(&s, request, Some("dir-sync-full"));
750 assert_eq!(wait(child.id()).0, 0);
751 let events = events(&s);
752 let t = terminal(&events);
753 assert_eq!(t.error, ErrorCode::DiskFull, "{events:?}");
754 assert_eq!(t.publication, Publication::Partial);
755 assert_eq!(t.created_count, 1);
756 assert_eq!(t.durability, Durability::Failed);
757 assert_eq!(t.cleanup, Cleanup::Complete);
758 assert_eq!(t.retained_partial_count, 0);
759 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
760 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
761 if nested {
762 assert_eq!(fs::read_dir(s.0.join("output/folder")).unwrap().count(), 0);
763 } else {
764 assert_zero_file(&s.0.join("output/payload.bin"), 1024);
765 }
766 }
767 }
768 #[test]
769 fn permission_and_generic_write_errors_remain_io() {
770 for mode in ["create-denied", "write-io"] {
771 let s = Scratch::new();
772 generate(&s, "store", 1024 * 1024);
773 let request = start(&s, false, Limits::default().output);
774 let child = spawn(&s, request, Some(mode));
775 assert_eq!(wait(child.id()).0, 0);
776 let events = events(&s);
777 let t = terminal(&events);
778 assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}");
779 assert_eq!(t.publication, Publication::None);
780 assert_eq!(t.retained_partial_count, 0);
781 assert_eq!(t.cleanup, Cleanup::Complete);
782 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
783 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
784 }
785 }
786 #[test]
787 fn anonymous_tempfile_fallback_unlinks_before_use() {
788 let s = Scratch::new();
789 generate(&s, "store", 1024 * 1024);
790 let request = start(&s, false, Limits::default().output);
791 let child = spawn(&s, request, Some("fallback"));
792 assert_eq!(wait(child.id()).0, 0);
793 let events = events(&s);
794 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
795 assert!(s.0.join("paused").exists());
796 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
797 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
798 }
799 struct Subreaper(i32);
800 impl Subreaper {
801 fn new() -> Self {
802 let mut old = 0;
803 assert_eq!(unsafe { prctl(37, &mut old as *mut i32, 0, 0, 0) }, 0);
804 assert_eq!(unsafe { prctl(36, 1, 0, 0, 0) }, 0);
805 Self(old)
806 }
807 }
808 impl Drop for Subreaper {
809 fn drop(&mut self) {
810 assert_eq!(unsafe { prctl(36, self.0, 0, 0, 0) }, 0);
811 }
812 }
813 #[test]
814 fn orphan_app_helper() {
815 let Some(path) = std::env::var_os("ZIPELO_TEST_APP_HELPER") else {
816 return;
817 };
818 let s = std::mem::ManuallyDrop::new(Scratch(PathBuf::from(path)));
819 let mut request = Start {
820 action: Action::Extract {
821 archive: s.path("input"),
822 destination: s.path("output"),
823 selection: Selection::All,
824 list_id: None,
825 gzip_output_name: None,
826 },
827 limits: Limits::default(),
828 };
829 if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() {
830 request.limits = Limits {
831 input: 64 * 1024 * 1024,
832 output: 128 * 1024 * 1024,
833 entries: 10000,
834 };
835 }
836 let mut cmd = command();
837 cmd.env("TMPDIR", staging(&s))
838 .stdin(Stdio::piped())
839 .stdout(File::create(s.0.join("events")).unwrap())
840 .stderr(File::create(s.0.join("stderr")).unwrap())
841 .env("LD_PRELOAD", s.0.join("io_fault.so"))
842 .env("ZIPELO_TEST_FAULT", "pause")
843 .env("ZIPELO_TEST_MARKER", s.0.join("paused"))
844 .env("ZIPELO_TEST_RELEASE", s.0.join("release"));
845 let mut child = cmd.spawn().unwrap();
846 fs::write(s.0.join("worker.pid"), child.id().to_string()).unwrap();
847 let mut writer = Writer::new(child.stdin.take().unwrap(), 17);
848 writer.send(&Message::Start(request)).unwrap();
849 loop {
850 std::thread::sleep(Duration::from_millis(20));
851 }
852 }
853 #[test]
854 fn app_death_stops_worker_and_removes_partial_temp() {
855 let _guard = Subreaper::new();
856 let s = Scratch::new();
857 generate(&s, "store", 1024 * 1024);
858 let _ = start(&s, false, Limits::default().output);
859 shim(&s);
860 let mut helper = Command::new(std::env::current_exe().unwrap())
861 .args([
862 "--exact",
863 "hardening::linux::orphan_app_helper",
864 "--nocapture",
865 ])
866 .env("ZIPELO_TEST_APP_HELPER", &s.0)
867 .stdout(Stdio::null())
868 .stderr(Stdio::null())
869 .spawn()
870 .unwrap();
871 let deadline = Instant::now() + Duration::from_secs(20);
872 while !s.0.join("paused").exists() {
873 if Instant::now() > deadline {
874 helper.kill().unwrap();
875 helper.wait().unwrap();
876 if let Ok(pid) = fs::read_to_string(s.0.join("worker.pid")) {
877 unsafe {
878 kill(pid.parse().unwrap(), 9);
879 }
880 wait(pid.trim().parse().unwrap());
881 }
882 panic!("worker did not reach publication");
883 }
884 std::thread::sleep(Duration::from_millis(10));
885 }
886 let pid = fs::read_to_string(s.0.join("worker.pid"))
887 .unwrap()
888 .parse::<u32>()
889 .unwrap();
890 helper.kill().unwrap();
891 helper.wait().unwrap();
892 fs::write(s.0.join("release"), b"").unwrap();
893 assert_eq!(wait(pid).0, 0);
894 let events = events(&s);
895 assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}");
896 assert_eq!(terminal(&events).publication, Publication::None);
897 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
898 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
899 }
900}
901
902#[test]
903fn creation_validates_before_password_and_rejects_more_than_16_gib() {
904 let s = Scratch::new();
905 File::create(s.0.join("source"))
906 .unwrap()
907 .set_len(Limits::default().output + 1)
908 .unwrap();
909 let action = |sources, encryption| Start {
910 action: Action::CreateZip {
911 sources,
912 output_file: s.path("input"),
913 method: Method::Deflate,
914 encryption,
915 },
916 limits: Limits::default(),
917 };
918 let source = Source {
919 path: s.path("source"),
920 archive_name: "same".into(),
921 };
922 let rejected = execute(action(
923 vec![source.clone(), source.clone()],
924 Encryption::Aes256,
925 ));
926 assert_eq!(terminal(&rejected).error, ErrorCode::Conflict);
927 assert!(
928 !rejected
929 .iter()
930 .any(|e| matches!(e, Message::PasswordRequired { .. }))
931 );
932 let rejected = execute(action(vec![source], Encryption::None));
933 assert_eq!(terminal(&rejected).error, ErrorCode::Limit);
934 assert!(!s.0.join("input").exists());
935}
936
937#[test]
938fn streamed_empty_aes_members_round_trip() {
939 for method in [Method::Store, Method::Deflate] {
940 let s = Scratch::new();
941 File::create(s.0.join("source")).unwrap();
942 let events = interactive(
943 Start {
944 action: Action::CreateZip {
945 sources: vec![Source {
946 path: s.path("source"),
947 archive_name: "payload.bin".into(),
948 }],
949 output_file: s.path("input"),
950 method,
951 encryption: Encryption::Aes256,
952 },
953 limits: Limits::default(),
954 },
955 |id, _, _| password_reply(id, TEST_PASSWORD),
956 );
957 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
958 let events = interactive(start(&s, false, Limits::default().output), |id, _, _| {
959 password_reply(id, TEST_PASSWORD)
960 });
961 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
962 assert_zero_file(&s.0.join("output/payload.bin"), 0);
963 }
964}