team-ljyzipelo

공개
959줄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 let request = start(&s, false, Limits::default().output);
674 let child = spawn(&s, request, Some(mode));
675 assert_eq!(wait(child.id()).0, 0);
676 let events = events(&s);
677 let t = terminal(&events);
678 assert_eq!(t.error, ErrorCode::DiskFull, "{mode}: {events:?}");
679 assert_eq!(
680 t.detail,
681 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
682 );
683 assert_eq!(t.publication, Publication::None);
684 assert_eq!(t.retained_partial_count, 0);
685 assert_eq!(t.cleanup, Cleanup::Complete);
686 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
687 assert_eq!(fs::read(s.0.join("preserve")).unwrap(), b"original");
688 }
689 }
690 #[test]
691 fn disk_space_preflight_rejects_without_outputs_and_closes_staging() {
692 for mode in [
693 "space-stage",
694 "space-destination",
695 "space-combined",
696 "space-error",
697 ] {
698 let s = Scratch::new();
699 generate(&s, "store", 1024 * 1024);
700 let request = start(&s, false, Limits::default().output);
701 let child = spawn(&s, request, Some(mode));
702 assert_eq!(wait(child.id()).0, 0);
703 let events = events(&s);
704 let t = terminal(&events);
705 let expected = if mode == "space-error" {
706 ErrorCode::Io
707 } else {
708 ErrorCode::DiskFull
709 };
710 assert_eq!(t.error, expected, "{mode}: {events:?}");
711 assert_eq!(t.publication, Publication::None);
712 assert_eq!(t.cleanup, Cleanup::Complete);
713 assert_eq!(t.created_count, 0);
714 assert!(t.detail.contains("디스크 여유 공간"));
715 assert!(s.0.join("paused").exists());
716 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
717 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
718 }
719 }
720 #[test]
721 fn disk_full_during_directory_sync_retains_reported_outputs() {
722 for nested in [false, true] {
723 let s = Scratch::new();
724 fs::write(s.0.join("source"), vec![0; 1024]).unwrap();
725 let name = if nested {
726 "folder/payload.bin"
727 } else {
728 "payload.bin"
729 };
730 let created = execute(Start {
731 action: Action::CreateZip {
732 sources: vec![Source {
733 path: s.path("source"),
734 archive_name: name.into(),
735 }],
736 output_file: s.path("input"),
737 method: Method::Store,
738 encryption: Encryption::None,
739 },
740 limits: Limits::default(),
741 });
742 assert_eq!(terminal(&created).outcome, Outcome::Completed);
743 let request = start(&s, false, Limits::default().output);
744 let child = spawn(&s, request, Some("dir-sync-full"));
745 assert_eq!(wait(child.id()).0, 0);
746 let events = events(&s);
747 let t = terminal(&events);
748 assert_eq!(t.error, ErrorCode::DiskFull, "{events:?}");
749 assert_eq!(t.publication, Publication::Partial);
750 assert_eq!(t.created_count, 1);
751 assert_eq!(t.durability, Durability::Failed);
752 assert_eq!(t.cleanup, Cleanup::Complete);
753 assert_eq!(t.retained_partial_count, 0);
754 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
755 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
756 if nested {
757 assert_eq!(fs::read_dir(s.0.join("output/folder")).unwrap().count(), 0);
758 } else {
759 assert_zero_file(&s.0.join("output/payload.bin"), 1024);
760 }
761 }
762 }
763 #[test]
764 fn permission_and_generic_write_errors_remain_io() {
765 for mode in ["create-denied", "write-io"] {
766 let s = Scratch::new();
767 generate(&s, "store", 1024 * 1024);
768 let request = start(&s, false, Limits::default().output);
769 let child = spawn(&s, request, Some(mode));
770 assert_eq!(wait(child.id()).0, 0);
771 let events = events(&s);
772 let t = terminal(&events);
773 assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}");
774 assert_eq!(t.publication, Publication::None);
775 assert_eq!(t.retained_partial_count, 0);
776 assert_eq!(t.cleanup, Cleanup::Complete);
777 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
778 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
779 }
780 }
781 #[test]
782 fn anonymous_tempfile_fallback_unlinks_before_use() {
783 let s = Scratch::new();
784 generate(&s, "store", 1024 * 1024);
785 let request = start(&s, false, Limits::default().output);
786 let child = spawn(&s, request, Some("fallback"));
787 assert_eq!(wait(child.id()).0, 0);
788 let events = events(&s);
789 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
790 assert!(s.0.join("paused").exists());
791 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
792 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
793 }
794 struct Subreaper(i32);
795 impl Subreaper {
796 fn new() -> Self {
797 let mut old = 0;
798 assert_eq!(unsafe { prctl(37, &mut old as *mut i32, 0, 0, 0) }, 0);
799 assert_eq!(unsafe { prctl(36, 1, 0, 0, 0) }, 0);
800 Self(old)
801 }
802 }
803 impl Drop for Subreaper {
804 fn drop(&mut self) {
805 assert_eq!(unsafe { prctl(36, self.0, 0, 0, 0) }, 0);
806 }
807 }
808 #[test]
809 fn orphan_app_helper() {
810 let Some(path) = std::env::var_os("ZIPELO_TEST_APP_HELPER") else {
811 return;
812 };
813 let s = std::mem::ManuallyDrop::new(Scratch(PathBuf::from(path)));
814 let mut request = Start {
815 action: Action::Extract {
816 archive: s.path("input"),
817 destination: s.path("output"),
818 selection: Selection::All,
819 list_id: None,
820 gzip_output_name: None,
821 },
822 limits: Limits::default(),
823 };
824 if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() {
825 request.limits = Limits {
826 input: 64 * 1024 * 1024,
827 output: 128 * 1024 * 1024,
828 entries: 10000,
829 };
830 }
831 let mut cmd = command();
832 cmd.env("TMPDIR", staging(&s))
833 .stdin(Stdio::piped())
834 .stdout(File::create(s.0.join("events")).unwrap())
835 .stderr(File::create(s.0.join("stderr")).unwrap())
836 .env("LD_PRELOAD", s.0.join("io_fault.so"))
837 .env("ZIPELO_TEST_FAULT", "pause")
838 .env("ZIPELO_TEST_MARKER", s.0.join("paused"))
839 .env("ZIPELO_TEST_RELEASE", s.0.join("release"));
840 let mut child = cmd.spawn().unwrap();
841 fs::write(s.0.join("worker.pid"), child.id().to_string()).unwrap();
842 let mut writer = Writer::new(child.stdin.take().unwrap(), 17);
843 writer.send(&Message::Start(request)).unwrap();
844 loop {
845 std::thread::sleep(Duration::from_millis(20));
846 }
847 }
848 #[test]
849 fn app_death_stops_worker_and_removes_partial_temp() {
850 let _guard = Subreaper::new();
851 let s = Scratch::new();
852 generate(&s, "store", 1024 * 1024);
853 let _ = start(&s, false, Limits::default().output);
854 shim(&s);
855 let mut helper = Command::new(std::env::current_exe().unwrap())
856 .args([
857 "--exact",
858 "hardening::linux::orphan_app_helper",
859 "--nocapture",
860 ])
861 .env("ZIPELO_TEST_APP_HELPER", &s.0)
862 .stdout(Stdio::null())
863 .stderr(Stdio::null())
864 .spawn()
865 .unwrap();
866 let deadline = Instant::now() + Duration::from_secs(20);
867 while !s.0.join("paused").exists() {
868 if Instant::now() > deadline {
869 helper.kill().unwrap();
870 helper.wait().unwrap();
871 if let Ok(pid) = fs::read_to_string(s.0.join("worker.pid")) {
872 unsafe {
873 kill(pid.parse().unwrap(), 9);
874 }
875 wait(pid.trim().parse().unwrap());
876 }
877 panic!("worker did not reach publication");
878 }
879 std::thread::sleep(Duration::from_millis(10));
880 }
881 let pid = fs::read_to_string(s.0.join("worker.pid"))
882 .unwrap()
883 .parse::<u32>()
884 .unwrap();
885 helper.kill().unwrap();
886 helper.wait().unwrap();
887 fs::write(s.0.join("release"), b"").unwrap();
888 assert_eq!(wait(pid).0, 0);
889 let events = events(&s);
890 assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}");
891 assert_eq!(terminal(&events).publication, Publication::None);
892 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
893 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
894 }
895}
896
897#[test]
898fn creation_validates_before_password_and_rejects_more_than_16_gib() {
899 let s = Scratch::new();
900 File::create(s.0.join("source"))
901 .unwrap()
902 .set_len(Limits::default().output + 1)
903 .unwrap();
904 let action = |sources, encryption| Start {
905 action: Action::CreateZip {
906 sources,
907 output_file: s.path("input"),
908 method: Method::Deflate,
909 encryption,
910 },
911 limits: Limits::default(),
912 };
913 let source = Source {
914 path: s.path("source"),
915 archive_name: "same".into(),
916 };
917 let rejected = execute(action(
918 vec![source.clone(), source.clone()],
919 Encryption::Aes256,
920 ));
921 assert_eq!(terminal(&rejected).error, ErrorCode::Conflict);
922 assert!(
923 !rejected
924 .iter()
925 .any(|e| matches!(e, Message::PasswordRequired { .. }))
926 );
927 let rejected = execute(action(vec![source], Encryption::None));
928 assert_eq!(terminal(&rejected).error, ErrorCode::Limit);
929 assert!(!s.0.join("input").exists());
930}
931
932#[test]
933fn streamed_empty_aes_members_round_trip() {
934 for method in [Method::Store, Method::Deflate] {
935 let s = Scratch::new();
936 File::create(s.0.join("source")).unwrap();
937 let events = interactive(
938 Start {
939 action: Action::CreateZip {
940 sources: vec![Source {
941 path: s.path("source"),
942 archive_name: "payload.bin".into(),
943 }],
944 output_file: s.path("input"),
945 method,
946 encryption: Encryption::Aes256,
947 },
948 limits: Limits::default(),
949 },
950 |id, _, _| password_reply(id, TEST_PASSWORD),
951 );
952 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
953 let events = interactive(start(&s, false, Limits::default().output), |id, _, _| {
954 password_reply(id, TEST_PASSWORD)
955 });
956 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
957 assert_zero_file(&s.0.join("output/payload.bin"), 0);
958 }
959}