team-ljyzipelo

공개
1,015줄38 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#[cfg(target_os = "linux")]
314#[test]
315fn worker_temp_isolated_from_unusable_inherited_directory() {
316 let s = Scratch::new();
317 let invalid = s.0.join("not-a-directory");
318 fs::write(&invalid, b"preserve inherited path").unwrap();
319 let output = Command::new(std::env::current_exe().unwrap())
320 .args([
321 "--exact",
322 "hardening::streamed_aes_counter_survives_many_read_chunks",
323 "--nocapture",
324 ])
325 .env("TMPDIR", &invalid)
326 .env("TMP", &invalid)
327 .env("TEMP", &invalid)
328 .output()
329 .unwrap();
330 assert!(
331 output.status.success(),
332 "{}\n{}",
333 String::from_utf8_lossy(&output.stdout),
334 String::from_utf8_lossy(&output.stderr)
335 );
336 assert_eq!(fs::read(&invalid).unwrap(), b"preserve inherited path");
337}
338
339#[test]
340fn seven_zip_output_total_rejects_before_decode() {
341 let s = Scratch::new();
342 let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
343 .join("../../tests/rust-archive-worker/seven_zip_large.py");
344 assert!(
345 Command::new("python3")
346 .arg(helper)
347 .arg(&s.0)
348 .arg("lzma2")
349 .arg("1024")
350 .arg((Limits::default().output + 1).to_string())
351 .status()
352 .unwrap()
353 .success()
354 );
355 let events = execute(start(&s, false, Limits::default().output));
356 assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}");
357 assert_eq!(terminal(&events).publication, Publication::None);
358 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
359}
360#[test]
361fn streamed_creation_limits_sum_source_bytes() {
362 for limit in [131071, 131072] {
363 let s = Scratch::new();
364 fs::write(s.0.join("a"), vec![0; 65536]).unwrap();
365 fs::write(s.0.join("b"), vec![0; 65536]).unwrap();
366 let events = execute(Start {
367 action: Action::CreateZip {
368 sources: vec![
369 Source {
370 path: s.path("a"),
371 archive_name: "a".into(),
372 },
373 Source {
374 path: s.path("b"),
375 archive_name: "b".into(),
376 },
377 ],
378 output_file: s.path("input"),
379 method: Method::Deflate,
380 encryption: Encryption::None,
381 },
382 limits: Limits {
383 output: limit,
384 ..Limits::default()
385 },
386 });
387 assert_eq!(
388 terminal(&events).error,
389 if limit == 131072 {
390 ErrorCode::None
391 } else {
392 ErrorCode::Limit
393 },
394 "{events:?}"
395 );
396 assert_eq!(s.0.join("input").exists(), limit == 131072);
397 }
398}
399#[test]
400fn streamed_seven_zip_honors_exact_output_boundary() {
401 for limit in [65535, 65536] {
402 let s = Scratch::new();
403 generate(&s, "7z-lzma2", 65536);
404 let events = execute(start(&s, false, limit));
405 assert_eq!(
406 terminal(&events).error,
407 if limit == 65536 {
408 ErrorCode::None
409 } else {
410 ErrorCode::Limit
411 },
412 "{events:?}"
413 );
414 if limit == 65536 {
415 assert_zero_file(&s.0.join("output/payload.bin"), 65536);
416 } else {
417 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
418 }
419 }
420}
421
422#[cfg(target_os = "linux")]
423mod linux {
424 use super::*;
425 use std::{
426 os::raw::c_long,
427 time::{Duration, Instant},
428 };
429 #[repr(C)]
430 #[derive(Default)]
431 struct Usage {
432 user: [c_long; 2],
433 system: [c_long; 2],
434 max_rss: c_long,
435 rest: [c_long; 13],
436 }
437 unsafe extern "C" {
438 fn wait4(pid: i32, status: *mut i32, options: i32, usage: *mut Usage) -> i32;
439 fn prctl(option: i32, ...) -> i32;
440 fn kill(pid: i32, signal: i32) -> i32;
441 }
442 fn command() -> Command {
443 let worker = std::env::var_os("ZIPELO_BASELINE_WORKER")
444 .map(PathBuf::from)
445 .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_zipelo-archive-worker")));
446 Command::new(worker)
447 }
448 fn staging(s: &Scratch) -> PathBuf {
449 use std::os::unix::fs::DirBuilderExt;
450 let path = s.0.join("staging");
451 fs::DirBuilder::new().mode(0o700).create(&path).unwrap();
452 path
453 }
454 fn spawn(s: &Scratch, mut start: Start, mode: Option<&str>) -> std::process::Child {
455 if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() {
456 start.limits = Limits {
457 input: 64 * 1024 * 1024,
458 output: 128 * 1024 * 1024,
459 entries: 10000,
460 };
461 }
462 let mut cmd = command();
463 cmd.env("TMPDIR", staging(s))
464 .stdin(Stdio::piped())
465 .stdout(File::create(s.0.join("events")).unwrap())
466 .stderr(File::create(s.0.join("stderr")).unwrap());
467 if let Some(mode) = mode {
468 cmd.env("LD_PRELOAD", shim(s))
469 .env("ZIPELO_TEST_FAULT", mode)
470 .env("ZIPELO_TEST_MARKER", s.0.join("paused"))
471 .env("ZIPELO_TEST_RELEASE", s.0.join("release"));
472 }
473 let mut child = cmd.spawn().unwrap();
474 Writer::new(child.stdin.take().unwrap(), 17)
475 .send(&Message::Start(start))
476 .unwrap();
477 child
478 }
479 fn wait(pid: u32) -> (i32, u64) {
480 let deadline = Instant::now() + Duration::from_secs(320);
481 loop {
482 let mut status = 0;
483 let mut usage = Usage::default();
484 let r = unsafe { wait4(pid as i32, &mut status, 1, &mut usage) };
485 if r == pid as i32 {
486 return (status, usage.max_rss as u64 * 1024);
487 }
488 assert!(
489 r >= 0 || std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted
490 );
491 if Instant::now() > deadline {
492 unsafe {
493 kill(pid as i32, 9);
494 wait4(pid as i32, &mut status, 0, &mut usage);
495 }
496 panic!("worker timeout");
497 }
498 std::thread::sleep(Duration::from_millis(10));
499 }
500 }
501 fn events(s: &Scratch) -> Vec<Message> {
502 assert!(fs::read(s.0.join("stderr")).unwrap().is_empty());
503 let mut reader = Reader::new(File::open(s.0.join("events")).unwrap());
504 let mut result = Vec::new();
505 while let Some((_, _, message)) = reader.read().unwrap() {
506 result.push(message);
507 }
508 result
509 }
510 fn shim(s: &Scratch) -> PathBuf {
511 let path = s.0.join("io_fault.so");
512 assert!(
513 Command::new("cc")
514 .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
515 .arg(
516 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
517 .join("../../tests/rust-archive-worker/io_fault.c")
518 )
519 .arg("-ldl")
520 .arg("-o")
521 .arg(&path)
522 .status()
523 .unwrap()
524 .success()
525 );
526 path
527 }
528
529 #[test]
530 fn gigabyte_seven_zip_and_zip_creation_stay_below_64_mib() {
531 let mut measurements = Vec::new();
532 for method in ["copy", "lzma", "lzma2"] {
533 let s = Scratch::new();
534 generate(&s, &format!("7z-{method}"), 1024 * 1024 * 1024);
535 let request = start(&s, false, Limits::default().output);
536 let child = spawn(&s, request, None);
537 let (status, rss) = wait(child.id());
538 assert_eq!(status, 0, "{method}");
539 let events = events(&s);
540 assert_eq!(
541 terminal(&events).outcome,
542 Outcome::Completed,
543 "{method}: {events:?}"
544 );
545 assert_eq!(terminal(&events).publication, Publication::Complete);
546 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
547 assert_eq!(terminal(&events).created_count, 1);
548 assert!(rss <= 64 * 1024 * 1024, "{method}: RSS {rss}");
549 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024 * 1024);
550 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
551 measurements.push(format!("7z-{method}: {rss}"));
552 }
553 for (method, length) in [
554 (Method::Store, 1u64 << 30),
555 (Method::Deflate, 1 << 30),
556 (Method::Deflate, (1 << 32) + 17),
557 ] {
558 let s = Scratch::new();
559 File::create(s.0.join("source"))
560 .unwrap()
561 .set_len(length)
562 .unwrap();
563 let request = Start {
564 action: Action::CreateZip {
565 sources: vec![Source {
566 path: s.path("source"),
567 archive_name: "payload.bin".into(),
568 }],
569 output_file: s.path("input"),
570 method,
571 encryption: Encryption::None,
572 },
573 limits: Limits::default(),
574 };
575 let child = spawn(&s, request, None);
576 let (status, rss) = wait(child.id());
577 assert_eq!(status, 0);
578 let created = events(&s);
579 assert_eq!(
580 terminal(&created).outcome,
581 Outcome::Completed,
582 "{method:?}: {created:?}"
583 );
584 assert!(rss <= 64 * 1024 * 1024, "{method:?}: RSS {rss}");
585 assert!(Command::new("python3").arg("-c").arg(
586 "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"
587 ).arg(s.0.join("input")).arg(length.to_string()).status().unwrap().success());
588 fs::remove_dir(s.0.join("staging")).unwrap();
589 let request = start(&s, false, Limits::default().output);
590 let child = spawn(&s, request, None);
591 assert_eq!(wait(child.id()).0, 0);
592 assert_eq!(terminal(&events(&s)).outcome, Outcome::Completed);
593 assert_zero_file(&s.0.join("output/payload.bin"), length);
594 measurements.push(format!("create-{method:?}-{length}: {rss}"));
595 }
596 println!(
597 "1 GiB 7z/creation peak RSS bytes: {}",
598 measurements.join(", ")
599 );
600 fs::write(
601 PathBuf::from(std::env::var_os("ZIPELO_TEST_WORK_DIR").expect("runner 작업 경로 필요"))
602 .join("seven-zip-streaming-rss.log"),
603 measurements.join("\n") + "\n",
604 )
605 .unwrap();
606 }
607 #[test]
608 fn seven_zip_and_creation_disk_errors_cleanup_staging_and_partial_output() {
609 for create in [false, true] {
610 for mode in ["codec-full", "full", "space-destination", "space-error"] {
611 let s = Scratch::new();
612 let request = if create {
613 fs::write(s.0.join("source"), vec![0; 1024 * 1024]).unwrap();
614 Start {
615 action: Action::CreateZip {
616 sources: vec![Source {
617 path: s.path("source"),
618 archive_name: "payload.bin".into(),
619 }],
620 output_file: s.path("input"),
621 method: Method::Deflate,
622 encryption: Encryption::None,
623 },
624 limits: Limits::default(),
625 }
626 } else {
627 generate(&s, "7z-lzma2", 1024 * 1024);
628 start(&s, false, Limits::default().output)
629 };
630 let child = spawn(&s, request, Some(mode));
631 assert_eq!(wait(child.id()).0, 0);
632 let messages = events(&s);
633 let end = terminal(&messages);
634 assert_eq!(
635 end.error,
636 if mode == "space-error" {
637 ErrorCode::Io
638 } else {
639 ErrorCode::DiskFull
640 },
641 "{create} {mode}: {messages:?}"
642 );
643 assert_eq!(end.publication, Publication::None);
644 assert_eq!(end.retained_partial_count, 0);
645 assert_eq!(end.cleanup, Cleanup::Complete);
646 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
647 if create {
648 assert!(!s.0.join("input").exists());
649 } else {
650 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
651 }
652 }
653 }
654 }
655
656 #[test]
657 fn gigabyte_formats_stay_below_64_mib_peak_rss() {
658 let mut measurements = Vec::new();
659 for kind in ["store", "deflate", "tar", "gzip", "targz"] {
660 let s = Scratch::new();
661 generate(&s, kind, 1024 * 1024 * 1024);
662 let request = start(&s, kind == "gzip", Limits::default().output);
663 let child = spawn(&s, request, None);
664 let (status, rss) = wait(child.id());
665 assert_eq!(status, 0, "{kind}");
666 let events = events(&s);
667 assert_eq!(
668 terminal(&events).outcome,
669 Outcome::Completed,
670 "{kind}: {events:?}"
671 );
672 assert_eq!(terminal(&events).publication, Publication::Complete);
673 assert!(rss <= 64 * 1024 * 1024, "{kind}: RSS {rss}");
674 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024 * 1024);
675 measurements.push(format!("{kind}: {rss}"));
676 }
677 println!(
678 "1 GiB extraction peak RSS bytes: {}",
679 measurements.join(", ")
680 );
681 fs::write(
682 PathBuf::from(std::env::var_os("ZIPELO_TEST_WORK_DIR").expect("runner 작업 경로 필요"))
683 .join("streaming-rss.log"),
684 measurements.join("\n") + "\n",
685 )
686 .unwrap();
687 }
688 #[test]
689 fn enospc_at_create_or_after_partial_write_cleans_output() {
690 for mode in [
691 "create-full",
692 "full",
693 "stage-full",
694 "temp-full",
695 "sync-full",
696 ] {
697 let s = Scratch::new();
698 generate(&s, "store", 1024 * 1024);
699 fs::write(s.0.join("preserve"), b"original").unwrap();
700 fs::create_dir(s.0.join("zipelo-source")).unwrap();
701 fs::rename(s.0.join("input"), s.0.join("zipelo-source/zipelo-input")).unwrap();
702 let mut request = start(&s, false, Limits::default().output);
703 if let Action::Extract { archive, .. } = &mut request.action {
704 *archive = s.path("zipelo-source/zipelo-input");
705 }
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 assert_eq!(t.error, ErrorCode::DiskFull, "{mode}: {events:?}");
711 assert_eq!(
712 t.detail,
713 "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요"
714 );
715 assert_eq!(t.publication, Publication::None);
716 assert_eq!(t.retained_partial_count, 0);
717 assert_eq!(t.cleanup, Cleanup::Complete);
718 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
719 assert_eq!(fs::read(s.0.join("preserve")).unwrap(), b"original");
720 }
721 }
722 #[test]
723 fn disk_space_preflight_rejects_without_outputs_and_closes_staging() {
724 for mode in [
725 "space-stage",
726 "space-destination",
727 "space-combined",
728 "space-error",
729 ] {
730 let s = Scratch::new();
731 generate(&s, "store", 1024 * 1024);
732 let request = start(&s, false, Limits::default().output);
733 let child = spawn(&s, request, Some(mode));
734 assert_eq!(wait(child.id()).0, 0);
735 let events = events(&s);
736 let t = terminal(&events);
737 let expected = if mode == "space-error" {
738 ErrorCode::Io
739 } else {
740 ErrorCode::DiskFull
741 };
742 assert_eq!(t.error, expected, "{mode}: {events:?}");
743 assert_eq!(t.publication, Publication::None);
744 assert_eq!(t.cleanup, Cleanup::Complete);
745 assert_eq!(t.created_count, 0);
746 assert!(t.detail.contains("디스크 여유 공간"));
747 assert!(s.0.join("paused").exists());
748 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
749 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
750 }
751 }
752 #[test]
753 fn disk_full_during_directory_sync_retains_reported_outputs() {
754 for nested in [false, true] {
755 let s = Scratch::new();
756 fs::write(s.0.join("source"), vec![0; 1024]).unwrap();
757 let name = if nested {
758 "folder/payload.bin"
759 } else {
760 "payload.bin"
761 };
762 let created = execute(Start {
763 action: Action::CreateZip {
764 sources: vec![Source {
765 path: s.path("source"),
766 archive_name: name.into(),
767 }],
768 output_file: s.path("input"),
769 method: Method::Store,
770 encryption: Encryption::None,
771 },
772 limits: Limits::default(),
773 });
774 assert_eq!(terminal(&created).outcome, Outcome::Completed);
775 let request = start(&s, false, Limits::default().output);
776 let child = spawn(&s, request, Some("dir-sync-full"));
777 assert_eq!(wait(child.id()).0, 0);
778 let events = events(&s);
779 let t = terminal(&events);
780 assert_eq!(t.error, ErrorCode::DiskFull, "{events:?}");
781 assert_eq!(t.publication, Publication::Partial);
782 assert_eq!(t.created_count, 1);
783 assert_eq!(t.durability, Durability::Failed);
784 assert_eq!(t.cleanup, Cleanup::Complete);
785 assert_eq!(t.retained_partial_count, 0);
786 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
787 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
788 if nested {
789 assert_eq!(fs::read_dir(s.0.join("output/folder")).unwrap().count(), 0);
790 } else {
791 assert_zero_file(&s.0.join("output/payload.bin"), 1024);
792 }
793 }
794 }
795 #[test]
796 fn permission_and_generic_write_errors_remain_io() {
797 for mode in ["create-denied", "write-io"] {
798 let s = Scratch::new();
799 generate(&s, "store", 1024 * 1024);
800 let request = start(&s, false, Limits::default().output);
801 let child = spawn(&s, request, Some(mode));
802 assert_eq!(wait(child.id()).0, 0);
803 let events = events(&s);
804 let t = terminal(&events);
805 assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}");
806 assert_eq!(t.publication, Publication::None);
807 assert_eq!(t.retained_partial_count, 0);
808 assert_eq!(t.cleanup, Cleanup::Complete);
809 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
810 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
811 }
812 }
813 #[test]
814 fn anonymous_tempfile_fallback_unlinks_before_use() {
815 let s = Scratch::new();
816 generate(&s, "store", 1024 * 1024);
817 let request = start(&s, false, Limits::default().output);
818 let child = spawn(&s, request, Some("fallback"));
819 assert_eq!(wait(child.id()).0, 0);
820 let events = events(&s);
821 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
822 assert!(s.0.join("paused").exists());
823 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
824 // 출력 폴더의 이름 있는 대체 임시 파일도 사용 전에 이름이 지워져야 함.
825 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
826 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
827 }
828 #[test]
829 fn destination_fallback_unlink_failure_reports_cleanup_and_moves_to_system_temp() {
830 let s = Scratch::new();
831 generate(&s, "store", 1024 * 1024);
832 let request = start(&s, false, Limits::default().output);
833 let child = spawn(&s, request, Some("fallback-unlink-denied"));
834 assert_eq!(wait(child.id()).0, 0);
835 let events = events(&s);
836 let t = terminal(&events);
837 // 이름을 지우지 못한 대체 임시 파일은 정리 실패로 알리고, 남은 작업은 시스템 임시 폴더에서 계속함.
838 assert_eq!(t.outcome, Outcome::Completed, "{events:?}");
839 assert_eq!(t.cleanup, Cleanup::Failed, "{events:?}");
840 assert!(s.0.join("paused").exists());
841 let leftovers = fs::read_dir(s.0.join("output"))
842 .unwrap()
843 .map(|entry| entry.unwrap().file_name().into_string().unwrap())
844 .filter(|name| name.starts_with(".zipelo-"))
845 .count();
846 assert_eq!(leftovers, 1, "첫 시도의 대체 임시 파일 하나만 남아야 함");
847 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
848 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
849 }
850 struct Subreaper(i32);
851 impl Subreaper {
852 fn new() -> Self {
853 let mut old = 0;
854 assert_eq!(unsafe { prctl(37, &mut old as *mut i32, 0, 0, 0) }, 0);
855 assert_eq!(unsafe { prctl(36, 1, 0, 0, 0) }, 0);
856 Self(old)
857 }
858 }
859 impl Drop for Subreaper {
860 fn drop(&mut self) {
861 assert_eq!(unsafe { prctl(36, self.0, 0, 0, 0) }, 0);
862 }
863 }
864 #[test]
865 fn orphan_app_helper() {
866 let Some(path) = std::env::var_os("ZIPELO_TEST_APP_HELPER") else {
867 return;
868 };
869 let s = std::mem::ManuallyDrop::new(Scratch(PathBuf::from(path)));
870 let mut request = Start {
871 action: Action::Extract {
872 archive: s.path("input"),
873 destination: s.path("output"),
874 selection: Selection::All,
875 list_id: None,
876 gzip_output_name: None,
877 },
878 limits: Limits::default(),
879 };
880 if std::env::var_os("ZIPELO_BASELINE_WORKER").is_some() {
881 request.limits = Limits {
882 input: 64 * 1024 * 1024,
883 output: 128 * 1024 * 1024,
884 entries: 10000,
885 };
886 }
887 let mut cmd = command();
888 cmd.env("TMPDIR", staging(&s))
889 .stdin(Stdio::piped())
890 .stdout(File::create(s.0.join("events")).unwrap())
891 .stderr(File::create(s.0.join("stderr")).unwrap())
892 .env("LD_PRELOAD", s.0.join("io_fault.so"))
893 .env("ZIPELO_TEST_FAULT", "pause")
894 .env("ZIPELO_TEST_MARKER", s.0.join("paused"))
895 .env("ZIPELO_TEST_RELEASE", s.0.join("release"));
896 let mut child = cmd.spawn().unwrap();
897 fs::write(s.0.join("worker.pid"), child.id().to_string()).unwrap();
898 let mut writer = Writer::new(child.stdin.take().unwrap(), 17);
899 writer.send(&Message::Start(request)).unwrap();
900 loop {
901 std::thread::sleep(Duration::from_millis(20));
902 }
903 }
904 #[test]
905 fn app_death_stops_worker_and_removes_partial_temp() {
906 let _guard = Subreaper::new();
907 let s = Scratch::new();
908 generate(&s, "store", 1024 * 1024);
909 let _ = start(&s, false, Limits::default().output);
910 shim(&s);
911 let mut helper = Command::new(std::env::current_exe().unwrap())
912 .args([
913 "--exact",
914 "hardening::linux::orphan_app_helper",
915 "--nocapture",
916 ])
917 .env("ZIPELO_TEST_APP_HELPER", &s.0)
918 .stdout(Stdio::null())
919 .stderr(Stdio::null())
920 .spawn()
921 .unwrap();
922 let deadline = Instant::now() + Duration::from_secs(20);
923 while !s.0.join("paused").exists() {
924 if Instant::now() > deadline {
925 helper.kill().unwrap();
926 helper.wait().unwrap();
927 if let Ok(pid) = fs::read_to_string(s.0.join("worker.pid")) {
928 unsafe {
929 kill(pid.parse().unwrap(), 9);
930 }
931 wait(pid.trim().parse().unwrap());
932 }
933 panic!("worker did not reach publication");
934 }
935 std::thread::sleep(Duration::from_millis(10));
936 }
937 let pid = fs::read_to_string(s.0.join("worker.pid"))
938 .unwrap()
939 .parse::<u32>()
940 .unwrap();
941 helper.kill().unwrap();
942 helper.wait().unwrap();
943 fs::write(s.0.join("release"), b"").unwrap();
944 assert_eq!(wait(pid).0, 0);
945 let events = events(&s);
946 assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}");
947 assert_eq!(terminal(&events).publication, Publication::None);
948 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
949 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
950 }
951}
952
953#[test]
954fn creation_validates_before_password_and_rejects_more_than_16_gib() {
955 let s = Scratch::new();
956 File::create(s.0.join("source"))
957 .unwrap()
958 .set_len(Limits::default().output + 1)
959 .unwrap();
960 let action = |sources, encryption| Start {
961 action: Action::CreateZip {
962 sources,
963 output_file: s.path("input"),
964 method: Method::Deflate,
965 encryption,
966 },
967 limits: Limits::default(),
968 };
969 let source = Source {
970 path: s.path("source"),
971 archive_name: "same".into(),
972 };
973 let rejected = execute(action(
974 vec![source.clone(), source.clone()],
975 Encryption::Aes256,
976 ));
977 assert_eq!(terminal(&rejected).error, ErrorCode::Conflict);
978 assert!(
979 !rejected
980 .iter()
981 .any(|e| matches!(e, Message::PasswordRequired { .. }))
982 );
983 let rejected = execute(action(vec![source], Encryption::None));
984 assert_eq!(terminal(&rejected).error, ErrorCode::Limit);
985 assert!(!s.0.join("input").exists());
986}
987
988#[test]
989fn streamed_empty_aes_members_round_trip() {
990 for method in [Method::Store, Method::Deflate] {
991 let s = Scratch::new();
992 File::create(s.0.join("source")).unwrap();
993 let events = interactive(
994 Start {
995 action: Action::CreateZip {
996 sources: vec![Source {
997 path: s.path("source"),
998 archive_name: "payload.bin".into(),
999 }],
1000 output_file: s.path("input"),
1001 method,
1002 encryption: Encryption::Aes256,
1003 },
1004 limits: Limits::default(),
1005 },
1006 |id, _, _| password_reply(id, TEST_PASSWORD),
1007 );
1008 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1009 let events = interactive(start(&s, false, Limits::default().output), |id, _, _| {
1010 password_reply(id, TEST_PASSWORD)
1011 });
1012 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1013 assert_zero_file(&s.0.join("output/payload.bin"), 0);
1014 }
1015}