team-ljyzipelo

공개
1,627줄50 KB
1use std::{
2 fs,
3 io::Write,
4 path::PathBuf,
5 process::{Command, Stdio},
6 sync::atomic::{AtomicU64, Ordering},
7};
8use zipelo_archive_worker::{
9 archive,
10 protocol::*,
11 wire::{Reader, Writer},
12};
13mod real_catalog;
14use real_catalog::worker_catalog;
15
16static NEXT: AtomicU64 = AtomicU64::new(0);
17struct Scratch(PathBuf);
18impl Scratch {
19 fn new() -> Self {
20 let path =
21 PathBuf::from(std::env::var_os("ZIPELO_TEST_WORK_DIR").expect("runner 작업 경로 필요"))
22 .join("fixtures/rust-archive-worker")
23 .join(format!(
24 "{}-{}",
25 std::process::id(),
26 NEXT.fetch_add(1, Ordering::Relaxed)
27 ));
28 fs::create_dir_all(path.parent().unwrap()).unwrap();
29 let builder = fs::DirBuilder::new();
30 #[cfg(unix)]
31 let mut builder = builder;
32 #[cfg(unix)]
33 {
34 use std::os::unix::fs::DirBuilderExt;
35 builder.mode(0o700);
36 }
37 builder.create(&path).unwrap();
38 Self(path)
39 }
40 fn path(&self, name: &str) -> NativePath {
41 NativePath::from_path(&self.0.join(name))
42 }
43 fn worker(&self) -> Command {
44 let mut command = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"));
45 // 공유 임시 폴더의 할당량과 다른 시험의 사용량에 의존하지 않음.
46 command
47 .env("TMPDIR", &self.0)
48 .env("TMP", &self.0)
49 .env("TEMP", &self.0);
50 command
51 }
52}
53impl Drop for Scratch {
54 fn drop(&mut self) {
55 fs::remove_dir_all(&self.0).unwrap();
56 }
57}
58fn execute(start: Start) -> Vec<Message> {
59 let mut data = Vec::new();
60 Writer::new(&mut data, 17)
61 .send(&Message::Start(start))
62 .unwrap();
63 let temporary = Scratch::new();
64 let mut command = temporary.worker();
65 command
66 .stdin(Stdio::piped())
67 .stdout(Stdio::piped())
68 .stderr(Stdio::piped());
69 #[cfg(target_os = "linux")]
70 {
71 use std::os::unix::process::CommandExt;
72 #[repr(C)]
73 struct Limit {
74 soft: usize,
75 hard: usize,
76 }
77 unsafe extern "C" {
78 fn setrlimit(resource: i32, limit: *const Limit) -> i32;
79 }
80 // 자식 프로세스의 주소 공간만 512 MiB로 제한함.
81 unsafe {
82 command.pre_exec(|| {
83 let limit = Limit {
84 soft: 512 * 1024 * 1024,
85 hard: 512 * 1024 * 1024,
86 };
87 if setrlimit(9, &limit) == 0 {
88 Ok(())
89 } else {
90 Err(std::io::Error::last_os_error())
91 }
92 });
93 }
94 }
95 let mut child = command.spawn().unwrap();
96 child.stdin.take().unwrap().write_all(&data).unwrap();
97 let output = child.wait_with_output().unwrap();
98 assert!(output.status.success(), "{:?}", output.stderr);
99 assert!(output.stderr.is_empty());
100 let mut reader = Reader::new(output.stdout.as_slice());
101 let mut events = Vec::new();
102 while let Some((job, _, event)) = reader.read().unwrap() {
103 assert_eq!(job, 17);
104 events.push(event);
105 }
106 assert!(matches!(events.last(), Some(Message::Terminal(_))));
107 events
108}
109fn terminal(events: &[Message]) -> &Terminal {
110 match events.last().unwrap() {
111 Message::Terminal(t) => t,
112 _ => panic!("missing terminal"),
113 }
114}
115fn extract(
116 s: &Scratch,
117 bytes: &[u8],
118 gzip: Option<&str>,
119 selection: Selection,
120 list_id: Option<ListId>,
121 limits: Limits,
122) -> Vec<Message> {
123 fs::write(s.0.join("input"), bytes).unwrap();
124 if !s.0.join("output").exists() {
125 let d = fs::DirBuilder::new();
126 #[cfg(unix)]
127 let mut d = d;
128 #[cfg(unix)]
129 {
130 use std::os::unix::fs::DirBuilderExt;
131 d.mode(0o700);
132 }
133 d.create(s.0.join("output")).unwrap();
134 }
135 execute(Start {
136 action: Action::Extract {
137 archive: s.path("input"),
138 destination: s.path("output"),
139 selection,
140 list_id,
141 gzip_output_name: gzip.map(str::to_owned),
142 },
143 limits,
144 })
145}
146const PAYLOAD: &[u8] = b"Zipelo worker interoperability\n";
147fn basic(bytes: &[u8], gzip: Option<&str>, output: &str) {
148 let s = Scratch::new();
149 let events = extract(&s, bytes, gzip, Selection::All, None, Limits::default());
150 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
151 assert_eq!(terminal(&events).publication, Publication::Complete);
152 assert_eq!(fs::read(s.0.join("output").join(output)).unwrap(), PAYLOAD);
153}
154#[test]
155fn stored_zip() {
156 basic(
157 include_bytes!("fixtures/store.zip"),
158 None,
159 "folder/hello.txt",
160 );
161}
162#[test]
163fn deflated_zip() {
164 basic(
165 include_bytes!("fixtures/deflate.zip"),
166 None,
167 "folder/hello.txt",
168 );
169}
170#[test]
171fn tar() {
172 basic(
173 include_bytes!("fixtures/sample.tar"),
174 None,
175 "folder/hello.txt",
176 );
177}
178#[test]
179fn tar_gzip() {
180 basic(
181 include_bytes!("fixtures/sample.tar.gz"),
182 None,
183 "folder/hello.txt",
184 );
185}
186#[test]
187fn gzip_explicit_name_ignores_fname() {
188 basic(
189 include_bytes!("fixtures/sample.gz"),
190 Some("chosen.txt"),
191 "chosen.txt",
192 );
193}
194#[test]
195fn gzip_concatenated_members() {
196 let s = Scratch::new();
197 let events = extract(
198 &s,
199 include_bytes!("fixtures/concat.gz"),
200 Some("combined"),
201 Selection::All,
202 None,
203 Limits::default(),
204 );
205 assert_eq!(terminal(&events).outcome, Outcome::Completed);
206 assert_eq!(fs::read(s.0.join("output/combined")).unwrap(), b"onetwo");
207}
208#[test]
209fn gzip_requires_leaf() {
210 for name in [None, Some("../escape"), Some("a/b")] {
211 let s = Scratch::new();
212 let e = extract(
213 &s,
214 include_bytes!("fixtures/sample.gz"),
215 name,
216 Selection::All,
217 None,
218 Limits::default(),
219 );
220 assert_eq!(terminal(&e).error, ErrorCode::InvalidRequest);
221 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
222 }
223}
224#[test]
225fn archive_rejects_gzip_name() {
226 let s = Scratch::new();
227 let e = extract(
228 &s,
229 include_bytes!("fixtures/store.zip"),
230 Some("a"),
231 Selection::All,
232 None,
233 Limits::default(),
234 );
235 assert_eq!(terminal(&e).error, ErrorCode::InvalidRequest);
236}
237#[test]
238fn no_clobber_and_preflight_no_partial_outputs() {
239 let s = Scratch::new();
240 fs::create_dir(s.0.join("output")).unwrap();
241 #[cfg(unix)]
242 {
243 use std::os::unix::fs::PermissionsExt;
244 fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
245 }
246 fs::create_dir(s.0.join("output/folder")).unwrap();
247 #[cfg(unix)]
248 {
249 use std::os::unix::fs::PermissionsExt;
250 fs::set_permissions(s.0.join("output/folder"), fs::Permissions::from_mode(0o700)).unwrap();
251 }
252 fs::write(s.0.join("output/folder/hello.txt"), b"preserve").unwrap();
253 let e = extract(
254 &s,
255 include_bytes!("fixtures/store.zip"),
256 None,
257 Selection::All,
258 None,
259 Limits::default(),
260 );
261 assert_eq!(terminal(&e).error, ErrorCode::Conflict);
262 assert_eq!(
263 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
264 b"preserve"
265 );
266 assert!(!s.0.join("output/empty").exists());
267}
268#[test]
269fn unsafe_archives_reject_without_writes() {
270 for bytes in [
271 include_bytes!("fixtures/traversal.zip").as_slice(),
272 include_bytes!("fixtures/absolute.zip"),
273 include_bytes!("fixtures/drive.zip"),
274 include_bytes!("fixtures/reserved.zip"),
275 include_bytes!("fixtures/link.zip"),
276 include_bytes!("fixtures/collision.zip"),
277 include_bytes!("fixtures/parent-collision.zip"),
278 ] {
279 let s = Scratch::new();
280 let e = extract(&s, bytes, None, Selection::All, None, Limits::default());
281 assert_eq!(terminal(&e).outcome, Outcome::Failed, "{e:?}");
282 assert_eq!(terminal(&e).created_count, 0);
283 assert_eq!(terminal(&e).publication, Publication::None);
284 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
285 }
286}
287#[test]
288fn bomb_rejects_before_writes() {
289 let s = Scratch::new();
290 let e = extract(
291 &s,
292 include_bytes!("fixtures/bomb.zip"),
293 None,
294 Selection::All,
295 None,
296 Limits {
297 output: 1024,
298 ..Limits::default()
299 },
300 );
301 assert_eq!(terminal(&e).error, ErrorCode::Limit);
302 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
303}
304#[test]
305fn corrupt_crc_and_truncation_reject_without_writes() {
306 let mut zip = include_bytes!("fixtures/store.zip").to_vec();
307 let at = zip
308 .windows(PAYLOAD.len())
309 .position(|b| b == PAYLOAD)
310 .unwrap();
311 zip[at] ^= 1;
312 for bytes in [zip.as_slice(), &include_bytes!("fixtures/store.zip")[..40]] {
313 let s = Scratch::new();
314 let e = extract(&s, bytes, None, Selection::All, None, Limits::default());
315 assert_eq!(terminal(&e).outcome, Outcome::Failed);
316 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
317 }
318}
319fn listing(s: &Scratch) -> ListId {
320 let e = execute(Start {
321 action: Action::List {
322 archive: s.path("input"),
323 },
324 limits: Limits::default(),
325 });
326 assert_eq!(terminal(&e).outcome, Outcome::Completed);
327 e.into_iter()
328 .find_map(|m| {
329 if let Message::ListEnd { list_id, .. } = m {
330 Some(list_id)
331 } else {
332 None
333 }
334 })
335 .unwrap()
336}
337#[test]
338fn list_and_selected_extract() {
339 let s = Scratch::new();
340 let bytes = include_bytes!("fixtures/store.zip");
341 fs::write(s.0.join("input"), bytes).unwrap();
342 let id = listing(&s);
343 let e = extract(
344 &s,
345 bytes,
346 None,
347 Selection::EntryIds(vec![0]),
348 Some(id),
349 Limits::default(),
350 );
351 assert_eq!(terminal(&e).outcome, Outcome::Completed);
352 assert!(!s.0.join("output/empty").exists());
353 assert_eq!(
354 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
355 PAYLOAD
356 );
357}
358#[test]
359fn stale_list_content_rejected() {
360 let s = Scratch::new();
361 fs::write(s.0.join("input"), include_bytes!("fixtures/store.zip")).unwrap();
362 let mut id = listing(&s);
363 id.archive_sha256[0] ^= 1;
364 let e = extract(
365 &s,
366 include_bytes!("fixtures/store.zip"),
367 None,
368 Selection::EntryIds(vec![0]),
369 Some(id),
370 Limits::default(),
371 );
372 assert_eq!(terminal(&e).error, ErrorCode::SourceChanged);
373 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
374}
375#[test]
376fn missing_duplicate_and_out_of_range_selection() {
377 for ids in [vec![], vec![0, 0], vec![999]] {
378 let s = Scratch::new();
379 fs::write(s.0.join("input"), include_bytes!("fixtures/store.zip")).unwrap();
380 let id = listing(&s);
381 let e = extract(
382 &s,
383 include_bytes!("fixtures/store.zip"),
384 None,
385 Selection::EntryIds(ids),
386 Some(id),
387 Limits::default(),
388 );
389 assert_eq!(terminal(&e).error, ErrorCode::InvalidRequest);
390 }
391 let s = Scratch::new();
392 let e = extract(
393 &s,
394 include_bytes!("fixtures/store.zip"),
395 None,
396 Selection::EntryIds(vec![0]),
397 None,
398 Limits::default(),
399 );
400 assert_eq!(terminal(&e).error, ErrorCode::InvalidRequest);
401}
402#[test]
403fn create_store_and_deflate_zip() {
404 for method in [Method::Store, Method::Deflate] {
405 let s = Scratch::new();
406 fs::write(s.0.join("source"), PAYLOAD).unwrap();
407 let e = execute(Start {
408 action: Action::CreateZip {
409 sources: vec![Source {
410 path: s.path("source"),
411 archive_name: "dir/hello.txt".into(),
412 }],
413 output_file: s.path("result.zip"),
414 method,
415 encryption: Encryption::None,
416 },
417 limits: Limits::default(),
418 });
419 assert_eq!(terminal(&e).outcome, Outcome::Completed, "{e:?}");
420 let bytes = fs::read(s.0.join("result.zip")).unwrap();
421 let parsed = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
422 assert_eq!(parsed.members[0].data, PAYLOAD);
423 }
424}
425#[test]
426fn encryption_password_eof_is_protocol_failure() {
427 let s = Scratch::new();
428 let e = execute(Start {
429 action: Action::CreateZip {
430 sources: vec![],
431 output_file: s.path("result.zip"),
432 method: Method::Store,
433 encryption: Encryption::Aes256,
434 },
435 limits: Limits::default(),
436 });
437 assert_eq!(terminal(&e).error, ErrorCode::Protocol);
438 assert!(!s.0.join("result.zip").exists());
439}
440#[test]
441fn name_policy() {
442 for name in [
443 "../a", "/a", "a\\b", "C:a", "a/../b", "a.", "a ", "COM1.txt", "a//b", "a/./b",
444 ] {
445 assert!(archive::valid_name(name, false).is_err(), "{name}");
446 }
447 assert!(archive::valid_name("folder/한글.txt", false).is_ok());
448}
449#[test]
450fn frame_round_trip_and_secret_redaction() {
451 let mut b = Vec::new();
452 Writer::new(&mut b, 42).send(&Message::Cancel).unwrap();
453 let mut reader = Reader::new(b.as_slice());
454 assert!(matches!(
455 reader.read().unwrap(),
456 Some((42, 0, Message::Cancel))
457 ));
458 assert!(reader.read().unwrap().is_none());
459 assert!(
460 !format!(
461 "{:?}",
462 Message::Password {
463 challenge_id: 1,
464 secret: Secret(b"private-password".to_vec())
465 }
466 )
467 .contains("private-password")
468 );
469}
470#[test]
471fn invalid_headers_are_rejected() {
472 let mut b = Vec::new();
473 Writer::new(&mut b, 42).send(&Message::Cancel).unwrap();
474 for (offset, value) in [(0, 0), (4, 2), (12, 1), (16, 0), (24, 1)] {
475 let mut bad = b.clone();
476 bad[offset] = value;
477 assert!(Reader::new(bad.as_slice()).read().is_err());
478 }
479 let mut big = b.clone();
480 big[8..12].copy_from_slice(&1_048_577u32.to_le_bytes());
481 assert!(Reader::new(big.as_slice()).read().is_err());
482 assert!(Reader::new(&b[..16]).read().is_err());
483}
484#[test]
485fn terminal_is_final_frame() {
486 let t = Terminal {
487 outcome: Outcome::Failed,
488 error: ErrorCode::Io,
489 publication: Publication::Uncertain,
490 created_count: 0,
491 retained_partial_count: 0,
492 durability: Durability::Unconfirmed,
493 cleanup: Cleanup::Unconfirmed,
494 detail: "uncertain".into(),
495 };
496 let mut b = Vec::new();
497 let mut w = Writer::new(&mut b, 1);
498 w.send(&Message::Terminal(t)).unwrap();
499 assert!(w.send(&Message::Cancel).is_err());
500}
501#[cfg(unix)]
502#[test]
503fn symlink_parent_escape_is_rejected() {
504 use std::os::unix::fs::symlink;
505 let s = Scratch::new();
506 let d = fs::DirBuilder::new();
507 #[cfg(unix)]
508 let mut d = d;
509 use std::os::unix::fs::DirBuilderExt;
510 d.mode(0o700);
511 d.create(s.0.join("output")).unwrap();
512 d.create(s.0.join("outside")).unwrap();
513 symlink(s.0.join("outside"), s.0.join("output/folder")).unwrap();
514 let e = extract(
515 &s,
516 include_bytes!("fixtures/store.zip"),
517 None,
518 Selection::All,
519 None,
520 Limits::default(),
521 );
522 assert_eq!(terminal(&e).error, ErrorCode::UnsafePath);
523 assert_eq!(fs::read_dir(s.0.join("outside")).unwrap().count(), 0);
524}
525
526// 개인 그룹의 압축 해제만 허용하고 공유 쓰기는 거부함.
527#[cfg(target_os = "linux")]
528#[test]
529fn private_group_writable_output_is_accepted() {
530 private_group::check_extraction("personal", true);
531 private_group::check_extraction("shared-primary", false);
532 private_group::check_extraction("world-writable", false);
533}
534
535#[test]
536fn changed_source_is_reopen_error_before_decode() {
537 let s = Scratch::new();
538 let bytes = include_bytes!("fixtures/store.zip");
539 fs::write(s.0.join("input"), bytes).unwrap();
540 let id = listing(&s);
541 let mut changed = bytes.to_vec();
542 changed[40] ^= 1;
543 let e = extract(
544 &s,
545 &changed,
546 None,
547 Selection::EntryIds(vec![0]),
548 Some(id),
549 Limits::default(),
550 );
551 assert_eq!(terminal(&e).error, ErrorCode::SourceChanged);
552 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
553}
554#[test]
555fn cancel_ack_and_terminal_are_distinct() {
556 let s = Scratch::new();
557 fs::write(s.0.join("source"), vec![0u8; 16 * 1024 * 1024]).unwrap();
558 let start = Start {
559 action: Action::CreateZip {
560 sources: vec![Source {
561 path: s.path("source"),
562 archive_name: "data".into(),
563 }],
564 output_file: s.path("result.zip"),
565 method: Method::Deflate,
566 encryption: Encryption::None,
567 },
568 limits: Limits::default(),
569 };
570 let mut child = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
571 .stdin(Stdio::piped())
572 .stdout(Stdio::piped())
573 .stderr(Stdio::piped())
574 .spawn()
575 .unwrap();
576 let mut writer = Writer::new(child.stdin.take().unwrap(), 19);
577 let mut reader = Reader::new(child.stdout.take().unwrap());
578 writer.send(&Message::Start(start)).unwrap();
579 assert!(matches!(
580 reader.read().unwrap(),
581 Some((19, 0, Message::Accepted { .. }))
582 ));
583 writer.send(&Message::Cancel).unwrap();
584 writer.send(&Message::Cancel).unwrap();
585 let mut events = Vec::new();
586 while let Some((_, _, m)) = reader.read().unwrap() {
587 events.push(m);
588 }
589 assert!(child.wait().unwrap().success());
590 let terminal = terminal(&events);
591 assert!(matches!(
592 terminal.outcome,
593 Outcome::Cancelled | Outcome::Completed
594 ));
595 for m in &events {
596 if let Message::CancelAck {
597 request_sequence,
598 status,
599 } = m
600 {
601 assert!([1, 2].contains(request_sequence));
602 assert!(matches!(
603 status,
604 CancelStatus::Requested
605 | CancelStatus::AlreadyRequested
606 | CancelStatus::TooLate
607 | CancelStatus::Finished
608 ));
609 }
610 }
611 assert!(
612 events
613 .iter()
614 .any(|m| matches!(m, Message::CancelAck { .. })),
615 "cancel must be consumed during bounded source read: {events:?}"
616 );
617}
618
619#[test]
620fn encrypted_zip_password_eof_preserves_outputs() {
621 let mut bytes = include_bytes!("fixtures/store.zip").to_vec();
622 bytes[6] |= 1;
623 let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
624 bytes[central + 8] |= 1;
625 let s = Scratch::new();
626 let e = extract(&s, &bytes, None, Selection::All, None, Limits::default());
627 assert_eq!(terminal(&e).error, ErrorCode::Protocol);
628 assert_eq!(terminal(&e).publication, Publication::None);
629 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
630}
631#[test]
632fn uncertain_report_survives_codec() {
633 let t = Terminal {
634 outcome: Outcome::Failed,
635 error: ErrorCode::Io,
636 publication: Publication::Uncertain,
637 created_count: 2,
638 retained_partial_count: 1,
639 durability: Durability::Failed,
640 cleanup: Cleanup::Failed,
641 detail: "publication uncertain".into(),
642 };
643 let mut bytes = Vec::new();
644 Writer::new(&mut bytes, 88)
645 .send(&Message::Terminal(t.clone()))
646 .unwrap();
647 let mut reader = Reader::new(bytes.as_slice());
648 match reader.read().unwrap() {
649 Some((88, 0, Message::Terminal(actual))) => assert_eq!(actual, t),
650 other => panic!("{other:?}"),
651 };
652 assert!(reader.read().unwrap().is_none());
653}
654
655fn path_fixture_zip(names: &[String]) -> Vec<u8> {
656 let mut output = Vec::new();
657 let mut central = Vec::new();
658 for name in names {
659 let offset = output.len() as u32;
660 output.extend(b"PK\x03\x04");
661 for value in [20u16, 0x0800, 0, 0, 33] {
662 output.extend(value.to_le_bytes());
663 }
664 for value in [0u32, 0, 0] {
665 output.extend(value.to_le_bytes());
666 }
667 output.extend((name.len() as u16).to_le_bytes());
668 output.extend(0u16.to_le_bytes());
669 output.extend(name.as_bytes());
670 central.extend(b"PK\x01\x02");
671 for value in [0x0314u16, 20, 0x0800, 0, 0, 33] {
672 central.extend(value.to_le_bytes());
673 }
674 for value in [0u32, 0, 0] {
675 central.extend(value.to_le_bytes());
676 }
677 central.extend((name.len() as u16).to_le_bytes());
678 for value in [0u16, 0, 0, 0] {
679 central.extend(value.to_le_bytes());
680 }
681 central.extend((0o100600u32 << 16).to_le_bytes());
682 central.extend(offset.to_le_bytes());
683 central.extend(name.as_bytes());
684 }
685 let offset = output.len() as u32;
686 output.extend(&central);
687 output.extend(b"PK\x05\x06");
688 for value in [0u16, 0, names.len() as u16, names.len() as u16] {
689 output.extend(value.to_le_bytes());
690 }
691 output.extend((central.len() as u32).to_le_bytes());
692 output.extend(offset.to_le_bytes());
693 output.extend(0u16.to_le_bytes());
694 output
695}
696
697fn assert_metadata_limit(names: &[String]) {
698 let scratch = Scratch::new();
699 let events = extract(
700 &scratch,
701 &path_fixture_zip(names),
702 None,
703 Selection::All,
704 None,
705 Limits::default(),
706 );
707 let result = terminal(&events);
708 assert_eq!(result.outcome, Outcome::Failed, "{events:?}");
709 assert_eq!(result.error, ErrorCode::Limit, "{events:?}");
710 assert_eq!(result.publication, Publication::None);
711 assert_eq!(result.created_count, 0);
712 assert_eq!(fs::read_dir(scratch.0.join("output")).unwrap().count(), 0);
713}
714
715#[test]
716fn deep_zip_returns_limit_without_abort_or_writes() {
717 let names = (0..100)
718 .map(|i| format!("{}file{i:03}", "a/".repeat(2000)))
719 .collect::<Vec<_>>();
720 assert_metadata_limit(&names);
721}
722
723#[test]
724fn shallow_zip_parent_metadata_is_bounded() {
725 let names = (0..500)
726 .map(|i| {
727 format!(
728 "d{i:04}{}/{}file",
729 "a".repeat(180),
730 format!("{}/", "b".repeat(200)).repeat(7)
731 )
732 })
733 .collect::<Vec<_>>();
734 assert!(
735 names
736 .iter()
737 .all(|n| n.split('/').count() <= archive::MAX_PATH_DEPTH)
738 );
739 assert!(worker_catalog(&path_fixture_zip(&names), Limits::default(), false, None).is_ok());
740 assert_metadata_limit(&names);
741}
742
743#[test]
744fn aggregate_archive_name_metadata_is_bounded() {
745 let names = (0..1100)
746 .map(|i| {
747 format!(
748 "d{i:04}{}/{}file",
749 "a".repeat(180),
750 format!("{}/", "b".repeat(200)).repeat(9)
751 )
752 })
753 .collect::<Vec<_>>();
754 let bytes = path_fixture_zip(&names);
755 assert!((bytes.len() as u64) < Limits::default().input);
756 assert!(matches!(
757 worker_catalog(&bytes, Limits::default(), false, None),
758 Err(ErrorCode::Limit)
759 ));
760 assert_metadata_limit(&names);
761}
762
763#[test]
764fn path_depth_boundary_is_explicit() {
765 let accepted = format!("{}file", "a/".repeat(archive::MAX_PATH_DEPTH - 1));
766 let rejected = format!("{}file", "a/".repeat(archive::MAX_PATH_DEPTH));
767 assert!(archive::valid_name(&accepted, false).is_ok());
768 assert_eq!(archive::valid_name(&rejected, false), Err(ErrorCode::Limit));
769}
770
771fn zeros_gzip(length: usize) -> Vec<u8> {
772 let mut gzip = vec![31, 139, 8, 0, 0, 0, 0, 0, 0, 255];
773 let mut left = length;
774 loop {
775 let size = left.min(u16::MAX as usize) as u16;
776 left -= size as usize;
777 gzip.push(u8::from(left == 0));
778 gzip.extend(size.to_le_bytes());
779 gzip.extend((!size).to_le_bytes());
780 gzip.resize(gzip.len() + size as usize, 0);
781 if left == 0 {
782 break;
783 }
784 }
785 gzip.extend(zlib_rs::crc32::crc32(0, &vec![0; length]).to_le_bytes());
786 gzip.extend((length as u32).to_le_bytes());
787 gzip
788}
789
790#[test]
791fn zero_payload_gzip_is_not_tar() {
792 for length in [512, 1024, 1536] {
793 let scratch = Scratch::new();
794 let bytes = zeros_gzip(length);
795 let parsed = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
796 assert_eq!(parsed.format, Format::Gzip);
797 let events = extract(
798 &scratch,
799 &bytes,
800 Some("zeros.bin"),
801 Selection::All,
802 None,
803 Limits::default(),
804 );
805 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
806 assert_eq!(
807 fs::read(scratch.0.join("output/zeros.bin")).unwrap(),
808 vec![0; length]
809 );
810 fs::write(scratch.0.join("input"), &bytes).unwrap();
811 let list_id = listing(&scratch);
812 assert_eq!(list_id.format, Format::Gzip);
813 }
814}
815
816const ENCRYPTED_PAYLOAD: &[u8] = b"Zipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\nZipelo encrypted interoperability\n";
817const TEST_PASSWORD: &[u8] = b"fixture-password";
818const AES_ZIP: &[u8] = include_bytes!("fixtures/aes2-deflate.zip");
819fn interactive(
820 start: Start,
821 mut respond: impl FnMut(u64, u32, PasswordPurpose) -> Vec<Message>,
822) -> Vec<Message> {
823 use std::{io::Read, sync::mpsc, time::Duration};
824 let temporary = Scratch::new();
825 let mut child = temporary
826 .worker()
827 .stdin(Stdio::piped())
828 .stdout(Stdio::piped())
829 .stderr(Stdio::piped())
830 .spawn()
831 .unwrap();
832 let mut writer = Some(Writer::new(child.stdin.take().unwrap(), 17));
833 writer
834 .as_mut()
835 .unwrap()
836 .send(&Message::Start(start))
837 .unwrap();
838 let output = child.stdout.take().unwrap();
839 let mut errors = child.stderr.take().unwrap();
840 let error_thread = std::thread::spawn(move || {
841 let mut bytes = Vec::new();
842 errors.read_to_end(&mut bytes).unwrap();
843 bytes
844 });
845 let (sender, receiver) = mpsc::channel();
846 let reader_thread = std::thread::spawn(move || {
847 let mut reader = Reader::new(output);
848 loop {
849 let event = reader.read().map(|v| {
850 v.map(|(job, _, message)| {
851 assert_eq!(job, 17);
852 message
853 })
854 });
855 let done = !matches!(event, Ok(Some(_)));
856 if sender.send(event).is_err() || done {
857 break;
858 }
859 }
860 });
861 let mut events = Vec::new();
862 loop {
863 let event = match receiver.recv_timeout(Duration::from_secs(10)) {
864 Ok(event) => event.unwrap(),
865 Err(error) => {
866 child.kill().unwrap();
867 child.wait().unwrap();
868 panic!("worker timeout: {error}");
869 }
870 };
871 let Some(event) = event else {
872 break;
873 };
874 if let Message::PasswordRequired {
875 challenge_id,
876 attempt,
877 purpose,
878 } = &event
879 {
880 let commands = respond(*challenge_id, *attempt, *purpose);
881 if commands.is_empty() {
882 writer = None;
883 } else {
884 for command in commands {
885 writer.as_mut().unwrap().send(&command).unwrap();
886 }
887 }
888 }
889 if matches!(event, Message::Terminal(_)) {
890 writer = None;
891 }
892 events.push(event);
893 }
894 assert!(child.wait().unwrap().success());
895 reader_thread.join().unwrap();
896 assert!(error_thread.join().unwrap().is_empty());
897 assert!(matches!(events.last(), Some(Message::Terminal(_))));
898 events
899}
900fn password_reply(id: u64, password: &[u8]) -> Vec<Message> {
901 vec![Message::Password {
902 challenge_id: id,
903 secret: Secret(password.to_vec()),
904 }]
905}
906fn encrypted_start(s: &Scratch, bytes: &[u8]) -> Start {
907 fs::write(s.0.join("input"), bytes).unwrap();
908 fs::create_dir(s.0.join("output")).unwrap();
909 #[cfg(unix)]
910 {
911 use std::os::unix::fs::PermissionsExt;
912 fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
913 }
914 Start {
915 action: Action::Extract {
916 archive: s.path("input"),
917 destination: s.path("output"),
918 selection: Selection::All,
919 list_id: None,
920 gzip_output_name: None,
921 },
922 limits: Limits::default(),
923 }
924}
925fn no_encrypted_output(s: &Scratch, events: &[Message], error: ErrorCode) {
926 assert_eq!(terminal(events).error, error, "{events:?}");
927 assert_eq!(terminal(events).publication, Publication::None);
928 assert_eq!(terminal(events).created_count, 0);
929 assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
930 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
931}
932#[test]
933fn independent_encrypted_fixtures_list_and_extract() {
934 for bytes in [
935 include_bytes!("fixtures/aes1-store.zip").as_slice(),
936 include_bytes!("fixtures/aes1-deflate.zip").as_slice(),
937 include_bytes!("fixtures/aes2-store.zip").as_slice(),
938 AES_ZIP,
939 include_bytes!("fixtures/zipcrypto-store.zip").as_slice(),
940 include_bytes!("fixtures/zipcrypto-deflate.zip").as_slice(),
941 ] {
942 let s = Scratch::new();
943 let start = encrypted_start(&s, bytes);
944 let listing = execute(Start {
945 action: Action::List {
946 archive: s.path("input"),
947 },
948 limits: Limits::default(),
949 });
950 assert_eq!(
951 terminal(&listing).outcome,
952 Outcome::Completed,
953 "{listing:?}"
954 );
955 assert!(listing.iter().any(|e| matches!(
956 e,
957 Message::Entry(Entry {
958 encrypted: true,
959 ..
960 })
961 )));
962 assert!(
963 !listing
964 .iter()
965 .any(|e| matches!(e, Message::PasswordRequired { .. }))
966 );
967 let events = interactive(start, |id, attempt, purpose| {
968 assert_eq!(purpose, PasswordPurpose::Decrypt);
969 assert_eq!(attempt, 1);
970 password_reply(id, TEST_PASSWORD)
971 });
972 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
973 assert_eq!(
974 fs::read(s.0.join("output/payload.bin")).unwrap(),
975 ENCRYPTED_PAYLOAD
976 );
977 }
978}
979#[test]
980fn aes_creation_uses_password_flow_and_independent_verification() {
981 for method in [Method::Store, Method::Deflate] {
982 let s = Scratch::new();
983 fs::write(s.0.join("source"), ENCRYPTED_PAYLOAD).unwrap();
984 let events = interactive(
985 Start {
986 action: Action::CreateZip {
987 sources: vec![Source {
988 path: s.path("source"),
989 archive_name: "payload.bin".into(),
990 }],
991 output_file: s.path("encrypted.zip"),
992 method,
993 encryption: Encryption::Aes256,
994 },
995 limits: Limits::default(),
996 },
997 |id, attempt, purpose| {
998 assert_eq!(purpose, PasswordPurpose::Encrypt);
999 assert_eq!(attempt, 1);
1000 password_reply(id, TEST_PASSWORD)
1001 },
1002 );
1003 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1004 assert!(events.iter().any(|e| matches!(
1005 e,
1006 Message::Accepted {
1007 encryption: true,
1008 ..
1009 }
1010 )));
1011 #[cfg(target_os = "linux")]
1012 {
1013 let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1014 .join("../../tests/rust-archive-worker/encryption_fixtures.py");
1015 assert!(
1016 Command::new("python3")
1017 .arg(helper)
1018 .arg("--verify")
1019 .arg(s.0.join("encrypted.zip"))
1020 .status()
1021 .unwrap()
1022 .success()
1023 );
1024 }
1025 let bytes = fs::read(s.0.join("encrypted.zip")).unwrap();
1026 let start = encrypted_start(&s, &bytes);
1027 let events = interactive(start, |id, _, _| password_reply(id, TEST_PASSWORD));
1028 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1029 assert_eq!(
1030 fs::read(s.0.join("output/payload.bin")).unwrap(),
1031 ENCRYPTED_PAYLOAD
1032 );
1033 }
1034}
1035#[test]
1036fn wrong_password_retries_with_new_challenge_then_succeeds() {
1037 let s = Scratch::new();
1038 let start = encrypted_start(&s, AES_ZIP);
1039 let mut previous = 0;
1040 let events = interactive(start, |id, attempt, _| {
1041 assert!(id > previous);
1042 previous = id;
1043 password_reply(
1044 id,
1045 if attempt == 1 {
1046 b"wrong"
1047 } else {
1048 TEST_PASSWORD
1049 },
1050 )
1051 });
1052 assert_eq!(terminal(&events).outcome, Outcome::Completed);
1053 assert_eq!(previous, 2);
1054}
1055#[test]
1056fn wrong_password_attempts_are_bounded_without_writes() {
1057 let s = Scratch::new();
1058 let start = encrypted_start(&s, AES_ZIP);
1059 let mut attempts = 0;
1060 let events = interactive(start, |id, attempt, _| {
1061 attempts = attempt;
1062 password_reply(id, b"wrong")
1063 });
1064 assert_eq!(attempts, 3);
1065 no_encrypted_output(&s, &events, ErrorCode::WrongPassword);
1066}
1067#[test]
1068fn cancellation_while_waiting_for_password_is_acknowledged() {
1069 let s = Scratch::new();
1070 let start = encrypted_start(&s, AES_ZIP);
1071 let events = interactive(start, |_, _, _| vec![Message::Cancel]);
1072 assert_eq!(terminal(&events).outcome, Outcome::Cancelled);
1073 assert!(events.iter().any(|e| matches!(
1074 e,
1075 Message::CancelAck {
1076 status: CancelStatus::Requested,
1077 ..
1078 }
1079 )));
1080 no_encrypted_output(&s, &events, ErrorCode::None);
1081}
1082#[test]
1083fn stale_and_mismatched_password_challenges_fail_without_writes() {
1084 for stale in [false, true] {
1085 let s = Scratch::new();
1086 let start = encrypted_start(&s, AES_ZIP);
1087 let events = interactive(start, |id, attempt, _| {
1088 if stale && attempt == 1 {
1089 password_reply(id, b"wrong")
1090 } else {
1091 password_reply(if stale { id - 1 } else { id + 1 }, TEST_PASSWORD)
1092 }
1093 });
1094 no_encrypted_output(&s, &events, ErrorCode::Protocol);
1095 }
1096}
1097#[test]
1098fn password_input_eof_fails_without_writes() {
1099 let s = Scratch::new();
1100 let start = encrypted_start(&s, AES_ZIP);
1101 let events = interactive(start, |_, _, _| vec![]);
1102 no_encrypted_output(&s, &events, ErrorCode::Protocol);
1103}
1104#[test]
1105fn aes_authentication_failure_never_publishes_plaintext() {
1106 for tamper_tag in [false, true] {
1107 let mut bytes = AES_ZIP.to_vec();
1108 let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
1109 if tamper_tag {
1110 bytes[central - 1] ^= 1;
1111 } else {
1112 bytes[30 + b"payload.bin".len() + 11 + 18] ^= 1;
1113 }
1114 let s = Scratch::new();
1115 let start = encrypted_start(&s, &bytes);
1116 let events = interactive(start, |id, _, _| password_reply(id, TEST_PASSWORD));
1117 no_encrypted_output(&s, &events, ErrorCode::Integrity);
1118 }
1119}
1120#[test]
1121fn aes1_crc_and_extra_consistency_are_checked() {
1122 let original = include_bytes!("fixtures/aes1-store.zip");
1123 for corrupt_extra in [false, true] {
1124 let mut bytes = original.to_vec();
1125 let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
1126 if corrupt_extra {
1127 bytes[30 + b"payload.bin".len() + 4] = 2;
1128 } else {
1129 bytes[14] ^= 1;
1130 bytes[central + 16] ^= 1;
1131 }
1132 let s = Scratch::new();
1133 let start = encrypted_start(&s, &bytes);
1134 let events = interactive(start, |id, _, _| password_reply(id, TEST_PASSWORD));
1135 no_encrypted_output(&s, &events, ErrorCode::Integrity);
1136 }
1137}
1138#[test]
1139fn empty_aes_members_and_random_salts_round_trip() {
1140 let members = vec![archive::Member {
1141 entry: Entry {
1142 entry_id: 0,
1143 name: "empty".into(),
1144 kind: EntryKind::File,
1145 size: 0,
1146 compressed_size: 0,
1147 encrypted: false,
1148 },
1149 data: vec![],
1150 }];
1151 let a = archive::create_zip_with_password(
1152 &members,
1153 Method::Store,
1154 Limits::default(),
1155 Some(TEST_PASSWORD),
1156 &mut || Ok(()),
1157 )
1158 .unwrap();
1159 let b = archive::create_zip_with_password(
1160 &members,
1161 Method::Store,
1162 Limits::default(),
1163 Some(TEST_PASSWORD),
1164 &mut || Ok(()),
1165 )
1166 .unwrap();
1167 assert_ne!(a, b);
1168 let decoded = worker_catalog(&a, Limits::default(), true, Some(TEST_PASSWORD)).unwrap();
1169 assert!(decoded.members[0].data.is_empty());
1170}
1171
1172#[test]
1173fn password_racing_after_cancel_does_not_override_cancellation() {
1174 let s = Scratch::new();
1175 let start = encrypted_start(&s, AES_ZIP);
1176 let events = interactive(start, |id, _, _| {
1177 vec![
1178 Message::Cancel,
1179 Message::Password {
1180 challenge_id: id,
1181 secret: Secret(TEST_PASSWORD.to_vec()),
1182 },
1183 ]
1184 });
1185 assert_eq!(terminal(&events).outcome, Outcome::Cancelled);
1186 no_encrypted_output(&s, &events, ErrorCode::None);
1187}
1188#[test]
1189fn empty_encryption_password_never_creates_zip() {
1190 let s = Scratch::new();
1191 let events = interactive(
1192 Start {
1193 action: Action::CreateZip {
1194 sources: vec![],
1195 output_file: s.path("empty.zip"),
1196 method: Method::Store,
1197 encryption: Encryption::Aes256,
1198 },
1199 limits: Limits::default(),
1200 },
1201 |id, _, _| password_reply(id, b""),
1202 );
1203 assert_eq!(terminal(&events).error, ErrorCode::InvalidRequest);
1204 assert_eq!(terminal(&events).publication, Publication::None);
1205 assert!(!s.0.join("empty.zip").exists());
1206}
1207
1208const SEVEN_PAYLOAD: &[u8] = b"Zipelo 7z interoperability\n";
1209fn seven_fixture(name: &str) -> Vec<u8> {
1210 fs::read(
1211 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1212 .join("../../tests/rust-archive-worker/fixtures/7z")
1213 .join(name),
1214 )
1215 .unwrap()
1216}
1217#[test]
1218fn seven_zip_lzma_lzma2_and_copy_interoperate() {
1219 for name in [
1220 "copy.7z",
1221 "lzma.7z",
1222 "lzma2.7z",
1223 "properties-0.7z",
1224 "properties-1.7z",
1225 "properties-2.7z",
1226 "properties-3.7z",
1227 "libarchive-lzma1.7z",
1228 "libarchive-lzma2.7z",
1229 ] {
1230 let bytes = seven_fixture(name);
1231 let catalog = worker_catalog(&bytes, Limits::default(), true, None)
1232 .unwrap_or_else(|e| panic!("{name}: {e:?}"));
1233 assert_eq!(catalog.format, Format::SevenZip);
1234 assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(100), "{name}");
1235 let s = Scratch::new();
1236 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1237 assert_eq!(
1238 terminal(&events).outcome,
1239 Outcome::Completed,
1240 "{name}: {events:?}"
1241 );
1242 assert_eq!(
1243 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
1244 SEVEN_PAYLOAD.repeat(100)
1245 );
1246 }
1247}
1248#[test]
1249fn seven_zip_encoded_header_solid_and_empty_entries() {
1250 let s = Scratch::new();
1251 let bytes = seven_fixture("encoded-solid.7z");
1252 let catalog = worker_catalog(&bytes, Limits::default(), false, None).unwrap();
1253 assert_eq!(catalog.members.len(), 4);
1254 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1255 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1256 assert_eq!(fs::read(s.0.join("output/folder/empty")).unwrap(), b"");
1257 assert_eq!(
1258 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
1259 SEVEN_PAYLOAD.repeat(100)
1260 );
1261 let mut reverse = SEVEN_PAYLOAD.repeat(100);
1262 reverse.reverse();
1263 assert_eq!(fs::read(s.0.join("output/한글.txt")).unwrap(), reverse);
1264}
1265#[test]
1266fn seven_zip_long_matches_and_lzma2_chunks() {
1267 for name in ["long-match.7z", "lzma2-chunks.7z"] {
1268 let bytes = seven_fixture(name);
1269 let catalog = worker_catalog(&bytes, Limits::default(), true, None)
1270 .unwrap_or_else(|e| panic!("{name}: {e:?}"));
1271 if name == "long-match.7z" {
1272 assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(10000));
1273 } else {
1274 let expected = (0..100000u64)
1275 .map(|i| (((i * 1103515245 + (i >> 2) * 12345) >> ((i % 4) * 8)) & 255) as u8)
1276 .collect::<Vec<_>>();
1277 assert_eq!(catalog.members[0].data, expected);
1278 }
1279 }
1280}
1281#[test]
1282fn seven_zip_malicious_inputs_never_write() {
1283 for name in [
1284 "unsafe-dotdot.7z",
1285 "unsafe-absolute.7z",
1286 "unsafe-drive.7z",
1287 "unsafe-backslash.7z",
1288 "unsafe-deep.7z",
1289 "symlink.7z",
1290 "collision.7z",
1291 "bad-payload.7z",
1292 "bad-crc.7z",
1293 "bad-dictionary.7z",
1294 ] {
1295 let s = Scratch::new();
1296 let bytes = seven_fixture(name);
1297 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1298 assert_eq!(
1299 terminal(&events).outcome,
1300 Outcome::Failed,
1301 "{name}: {events:?}"
1302 );
1303 assert_eq!(terminal(&events).publication, Publication::None);
1304 assert_eq!(terminal(&events).created_count, 0);
1305 assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
1306 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1307 assert!(!s.0.join("outside.txt").exists());
1308 }
1309}
1310
1311#[test]
1312fn seven_zip_format_wire_tag_preserves_existing_encodings() {
1313 for (tag, format) in [
1314 Format::Zip,
1315 Format::Tar,
1316 Format::Gzip,
1317 Format::TarGzip,
1318 Format::SevenZip,
1319 ]
1320 .into_iter()
1321 .enumerate()
1322 {
1323 let token = ListId {
1324 catalog_version: 1,
1325 format,
1326 source_object: SourceObject::Unix {
1327 device: 1,
1328 inode: 2,
1329 },
1330 archive_bytes: 3,
1331 archive_sha256: [4; 32],
1332 };
1333 let mut bytes = Vec::new();
1334 Writer::new(&mut bytes, 17)
1335 .send(&Message::ListEnd {
1336 entry_count: 5,
1337 list_id: token.clone(),
1338 })
1339 .unwrap();
1340 assert_eq!(bytes[38], tag as u8);
1341 match Reader::new(bytes.as_slice()).read().unwrap().unwrap().2 {
1342 Message::ListEnd {
1343 entry_count,
1344 list_id,
1345 } => {
1346 assert_eq!(entry_count, 5);
1347 assert_eq!(list_id, token);
1348 }
1349 _ => panic!("expected ListEnd"),
1350 }
1351 }
1352}
1353#[test]
1354fn seven_zip_listing_token_and_selection() {
1355 let s = Scratch::new();
1356 let bytes = seven_fixture("encoded-solid.7z");
1357 fs::write(s.0.join("input"), &bytes).unwrap();
1358 let events = execute(Start {
1359 action: Action::List {
1360 archive: s.path("input"),
1361 },
1362 limits: Limits::default(),
1363 });
1364 assert_eq!(terminal(&events).outcome, Outcome::Completed);
1365 let list_id = events
1366 .into_iter()
1367 .find_map(|e| {
1368 if let Message::ListEnd { list_id, .. } = e {
1369 Some(list_id)
1370 } else {
1371 None
1372 }
1373 })
1374 .unwrap();
1375 assert_eq!(list_id.format, Format::SevenZip);
1376 let events = extract(
1377 &s,
1378 &bytes,
1379 None,
1380 Selection::EntryIds(vec![3]),
1381 Some(list_id),
1382 Limits::default(),
1383 );
1384 assert_eq!(terminal(&events).outcome, Outcome::Completed);
1385 assert_eq!(terminal(&events).created_count, 1);
1386 assert!(!s.0.join("output/folder").exists());
1387 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
1388}
1389#[test]
1390fn seven_zip_limits_truncation_and_existing_files_are_preserved() {
1391 let bytes = seven_fixture("lzma2.7z");
1392 for cut in [0, 1, 6, 12, 31, 32, bytes.len() - 1] {
1393 let s = Scratch::new();
1394 let events = extract(
1395 &s,
1396 &bytes[..cut],
1397 None,
1398 Selection::All,
1399 None,
1400 Limits::default(),
1401 );
1402 assert_eq!(terminal(&events).outcome, Outcome::Failed);
1403 assert_eq!(terminal(&events).publication, Publication::None);
1404 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1405 }
1406 let s = Scratch::new();
1407 let events = extract(
1408 &s,
1409 &bytes,
1410 None,
1411 Selection::All,
1412 None,
1413 Limits {
1414 output: 100,
1415 ..Limits::default()
1416 },
1417 );
1418 assert_eq!(terminal(&events).error, ErrorCode::Limit);
1419 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1420 fs::create_dir(s.0.join("output/folder")).unwrap();
1421 #[cfg(unix)]
1422 {
1423 use std::os::unix::fs::PermissionsExt;
1424 fs::set_permissions(s.0.join("output/folder"), fs::Permissions::from_mode(0o700)).unwrap();
1425 }
1426 fs::write(s.0.join("output/folder/hello.txt"), b"preserve").unwrap();
1427 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1428 assert_eq!(terminal(&events).error, ErrorCode::Conflict);
1429 assert_eq!(
1430 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
1431 b"preserve"
1432 );
1433 let s = Scratch::new();
1434 let events = extract(
1435 &s,
1436 &seven_fixture("bad-trailing.7z"),
1437 None,
1438 Selection::All,
1439 None,
1440 Limits::default(),
1441 );
1442 assert_eq!(terminal(&events).error, ErrorCode::Integrity);
1443 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1444}
1445#[test]
1446fn pr64_malicious_corpus_is_rejected_without_writes() {
1447 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1448 .join("../../tests/malicious-archive-fixtures/fixtures");
1449 let cases = [
1450 ("zip-dotdot.zip", ErrorCode::UnsafePath, 131072, None),
1451 (
1452 "zip-absolute-posix.zip",
1453 ErrorCode::UnsafePath,
1454 131072,
1455 None,
1456 ),
1457 (
1458 "zip-absolute-drive.zip",
1459 ErrorCode::UnsafePath,
1460 131072,
1461 None,
1462 ),
1463 (
1464 "zip-backslash-dotdot.zip",
1465 ErrorCode::UnsafePath,
1466 131072,
1467 None,
1468 ),
1469 ("tar-dotdot.tar", ErrorCode::UnsafePath, 131072, None),
1470 ("targz-dotdot.tar.gz", ErrorCode::UnsafePath, 131072, None),
1471 (
1472 "tar-absolute-posix.tar",
1473 ErrorCode::UnsafePath,
1474 131072,
1475 None,
1476 ),
1477 ("zip-symlink-escape.zip", ErrorCode::Conflict, 131072, None),
1478 ("tar-symlink-escape.tar", ErrorCode::Conflict, 131072, None),
1479 ("zip-output-limit.zip", ErrorCode::Limit, 1024, None),
1480 (
1481 "gzip-output-limit.gz",
1482 ErrorCode::Limit,
1483 1024,
1484 Some("payload.bin"),
1485 ),
1486 ("targz-output-limit.tar.gz", ErrorCode::Limit, 1024, None),
1487 (
1488 "zip-bad-local-header.zip",
1489 ErrorCode::Integrity,
1490 131072,
1491 None,
1492 ),
1493 ("tar-bad-checksum.tar", ErrorCode::Integrity, 131072, None),
1494 (
1495 "gzip-reserved-flags.gz",
1496 ErrorCode::Integrity,
1497 131072,
1498 Some("payload.bin"),
1499 ),
1500 ];
1501 for (name, expected, output, gzip) in cases {
1502 let s = Scratch::new();
1503 let bytes = fs::read(root.join(name)).unwrap();
1504 fs::write(s.0.join("outside.txt"), b"preserve").unwrap();
1505 let events = extract(
1506 &s,
1507 &bytes,
1508 gzip,
1509 Selection::All,
1510 None,
1511 Limits {
1512 input: 1048576,
1513 output,
1514 entries: 64,
1515 },
1516 );
1517 assert_eq!(
1518 terminal(&events).outcome,
1519 Outcome::Failed,
1520 "{name}: {events:?}"
1521 );
1522 assert_eq!(terminal(&events).error, expected, "{name}");
1523 assert_eq!(terminal(&events).publication, Publication::None);
1524 assert_eq!(terminal(&events).created_count, 0);
1525 assert_eq!(terminal(&events).retained_partial_count, 0);
1526 assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
1527 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1528 assert_eq!(fs::read(s.0.join("outside.txt")).unwrap(), b"preserve");
1529 assert_eq!(fs::read(s.0.join("input")).unwrap(), bytes);
1530 }
1531}
1532#[cfg(target_os = "linux")]
1533#[test]
1534fn seven_zip_reference_reader_accepts_synthetic_fixtures() {
1535 let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1536 .join("../../tests/rust-archive-worker/seven_zip_reference.py");
1537 assert!(
1538 Command::new("python3")
1539 .arg(helper)
1540 .status()
1541 .unwrap()
1542 .success()
1543 );
1544}
1545
1546mod hardening;
1547
1548#[test]
1549fn disk_full_error_tag_preserves_previous_tags_and_rejects_unknown() {
1550 for (tag, error) in [
1551 ErrorCode::None,
1552 ErrorCode::Integrity,
1553 ErrorCode::UnsupportedFormat,
1554 ErrorCode::UnsupportedFeature,
1555 ErrorCode::WrongPassword,
1556 ErrorCode::UnsafePath,
1557 ErrorCode::Conflict,
1558 ErrorCode::Limit,
1559 ErrorCode::Io,
1560 ErrorCode::Protocol,
1561 ErrorCode::Internal,
1562 ErrorCode::SourceChanged,
1563 ErrorCode::InvalidRequest,
1564 ErrorCode::DiskFull,
1565 ]
1566 .into_iter()
1567 .enumerate()
1568 {
1569 let message = Message::Terminal(Terminal {
1570 outcome: Outcome::Failed,
1571 error,
1572 publication: Publication::None,
1573 created_count: 0,
1574 retained_partial_count: 0,
1575 durability: Durability::NotApplicable,
1576 cleanup: Cleanup::Complete,
1577 detail: String::new(),
1578 });
1579 let mut bytes = Vec::new();
1580 Writer::new(&mut bytes, 17).send(&message).unwrap();
1581 assert_eq!(bytes[33], tag as u8);
1582 let decoded = Reader::new(bytes.as_slice()).read().unwrap().unwrap().2;
1583 assert_eq!(terminal(&[decoded]).error, error);
1584 bytes[33] = 17;
1585 assert!(Reader::new(bytes.as_slice()).read().is_err());
1586 }
1587}
1588
1589mod folder_inputs;
1590
1591mod zip_names;
1592
1593mod conflict_wire;
1594
1595mod preview_wire;
1596
1597mod split_volume_wire;
1598
1599mod preview_runtime;
1600
1601mod conflicts;
1602
1603mod compressed_tar;
1604
1605mod guarded;
1606
1607mod split_runtime;
1608
1609mod seven_zip_create;
1610
1611mod seven_zip_create_runtime;
1612
1613mod seven_zip_aes;
1614
1615mod recovery;
1616
1617#[cfg(target_os = "linux")]
1618mod partial_output;
1619
1620#[cfg(target_os = "linux")]
1621mod spool_location;
1622
1623#[cfg(target_os = "linux")]
1624mod spool_fallback;
1625
1626#[cfg(target_os = "linux")]
1627mod private_group;