team-ljyzipelo

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