team-ljyzipelo

공개
1,678줄52 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// umask 002에서 폴더 선택 창으로 새로 만든 폴더(775)에도 풀 수 있어야 함.
523// 다른 계정이 쓸 수 있는 폴더(777)는 계속 거부함.
524#[cfg(target_os = "linux")]
525#[test]
526fn private_group_writable_output_is_accepted() {
527 use std::os::unix::fs::{MetadataExt, PermissionsExt};
528 for (mode, other) in [(0o775, false), (0o777, true)] {
529 let s = Scratch::new();
530 fs::create_dir(s.0.join("output")).unwrap();
531 fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(mode)).unwrap();
532 let gid = fs::metadata(s.0.join("output")).unwrap().gid();
533 let entry = Command::new("getent")
534 .args(["group", &gid.to_string()])
535 .output()
536 .unwrap();
537 let entry = String::from_utf8_lossy(&entry.stdout);
538 let egid = Command::new("id").arg("-g").output().unwrap();
539 let private = String::from_utf8_lossy(&egid.stdout).trim() == gid.to_string()
540 && entry.trim_end().ends_with(':');
541 let e = extract(
542 &s,
543 include_bytes!("fixtures/store.zip"),
544 None,
545 Selection::All,
546 None,
547 Limits::default(),
548 );
549 if other || !private {
550 assert_eq!(terminal(&e).error, ErrorCode::UnsafePath, "{mode:o}");
551 assert!(!s.0.join("output/folder").exists());
552 } else {
553 assert_eq!(terminal(&e).outcome, Outcome::Completed, "{e:?}");
554 assert_eq!(
555 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
556 PAYLOAD
557 );
558 }
559 }
560}
561
562#[test]
563fn changed_source_is_reopen_error_before_decode() {
564 let s = Scratch::new();
565 let bytes = include_bytes!("fixtures/store.zip");
566 fs::write(s.0.join("input"), bytes).unwrap();
567 let id = listing(&s);
568 let mut changed = bytes.to_vec();
569 changed[40] ^= 1;
570 let e = extract(
571 &s,
572 &changed,
573 None,
574 Selection::EntryIds(vec![0]),
575 Some(id),
576 Limits::default(),
577 );
578 assert_eq!(terminal(&e).error, ErrorCode::SourceChanged);
579 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
580}
581#[test]
582fn cancel_ack_and_terminal_are_distinct() {
583 let s = Scratch::new();
584 fs::write(s.0.join("source"), vec![0u8; 16 * 1024 * 1024]).unwrap();
585 let start = Start {
586 action: Action::CreateZip {
587 sources: vec![Source {
588 path: s.path("source"),
589 archive_name: "data".into(),
590 }],
591 output_file: s.path("result.zip"),
592 method: Method::Deflate,
593 encryption: Encryption::None,
594 },
595 limits: Limits::default(),
596 };
597 let mut child = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
598 .stdin(Stdio::piped())
599 .stdout(Stdio::piped())
600 .stderr(Stdio::piped())
601 .spawn()
602 .unwrap();
603 let mut writer = Writer::new(child.stdin.take().unwrap(), 19);
604 let mut reader = Reader::new(child.stdout.take().unwrap());
605 writer.send(&Message::Start(start)).unwrap();
606 assert!(matches!(
607 reader.read().unwrap(),
608 Some((19, 0, Message::Accepted { .. }))
609 ));
610 writer.send(&Message::Cancel).unwrap();
611 writer.send(&Message::Cancel).unwrap();
612 let mut events = Vec::new();
613 while let Some((_, _, m)) = reader.read().unwrap() {
614 events.push(m);
615 }
616 assert!(child.wait().unwrap().success());
617 let terminal = terminal(&events);
618 assert!(matches!(
619 terminal.outcome,
620 Outcome::Cancelled | Outcome::Completed
621 ));
622 for m in &events {
623 if let Message::CancelAck {
624 request_sequence,
625 status,
626 } = m
627 {
628 assert!([1, 2].contains(request_sequence));
629 assert!(matches!(
630 status,
631 CancelStatus::Requested
632 | CancelStatus::AlreadyRequested
633 | CancelStatus::TooLate
634 | CancelStatus::Finished
635 ));
636 }
637 }
638 assert!(
639 events
640 .iter()
641 .any(|m| matches!(m, Message::CancelAck { .. })),
642 "cancel must be consumed during bounded source read: {events:?}"
643 );
644}
645
646#[test]
647fn encrypted_zip_password_eof_preserves_outputs() {
648 let mut bytes = include_bytes!("fixtures/store.zip").to_vec();
649 bytes[6] |= 1;
650 let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
651 bytes[central + 8] |= 1;
652 let s = Scratch::new();
653 let e = extract(&s, &bytes, None, Selection::All, None, Limits::default());
654 assert_eq!(terminal(&e).error, ErrorCode::Protocol);
655 assert_eq!(terminal(&e).publication, Publication::None);
656 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
657}
658#[test]
659fn uncertain_report_survives_codec() {
660 let t = Terminal {
661 outcome: Outcome::Failed,
662 error: ErrorCode::Io,
663 publication: Publication::Uncertain,
664 created_count: 2,
665 retained_partial_count: 1,
666 durability: Durability::Failed,
667 cleanup: Cleanup::Failed,
668 detail: "publication uncertain".into(),
669 };
670 let mut bytes = Vec::new();
671 Writer::new(&mut bytes, 88)
672 .send(&Message::Terminal(t.clone()))
673 .unwrap();
674 let mut reader = Reader::new(bytes.as_slice());
675 match reader.read().unwrap() {
676 Some((88, 0, Message::Terminal(actual))) => assert_eq!(actual, t),
677 other => panic!("{other:?}"),
678 };
679 assert!(reader.read().unwrap().is_none());
680}
681
682fn path_fixture_zip(names: &[String]) -> Vec<u8> {
683 let mut output = Vec::new();
684 let mut central = Vec::new();
685 for name in names {
686 let offset = output.len() as u32;
687 output.extend(b"PK\x03\x04");
688 for value in [20u16, 0x0800, 0, 0, 33] {
689 output.extend(value.to_le_bytes());
690 }
691 for value in [0u32, 0, 0] {
692 output.extend(value.to_le_bytes());
693 }
694 output.extend((name.len() as u16).to_le_bytes());
695 output.extend(0u16.to_le_bytes());
696 output.extend(name.as_bytes());
697 central.extend(b"PK\x01\x02");
698 for value in [0x0314u16, 20, 0x0800, 0, 0, 33] {
699 central.extend(value.to_le_bytes());
700 }
701 for value in [0u32, 0, 0] {
702 central.extend(value.to_le_bytes());
703 }
704 central.extend((name.len() as u16).to_le_bytes());
705 for value in [0u16, 0, 0, 0] {
706 central.extend(value.to_le_bytes());
707 }
708 central.extend((0o100600u32 << 16).to_le_bytes());
709 central.extend(offset.to_le_bytes());
710 central.extend(name.as_bytes());
711 }
712 let offset = output.len() as u32;
713 output.extend(&central);
714 output.extend(b"PK\x05\x06");
715 for value in [0u16, 0, names.len() as u16, names.len() as u16] {
716 output.extend(value.to_le_bytes());
717 }
718 output.extend((central.len() as u32).to_le_bytes());
719 output.extend(offset.to_le_bytes());
720 output.extend(0u16.to_le_bytes());
721 output
722}
723
724fn assert_metadata_limit(names: &[String]) {
725 let scratch = Scratch::new();
726 let events = extract(
727 &scratch,
728 &path_fixture_zip(names),
729 None,
730 Selection::All,
731 None,
732 Limits::default(),
733 );
734 let result = terminal(&events);
735 assert_eq!(result.outcome, Outcome::Failed, "{events:?}");
736 assert_eq!(result.error, ErrorCode::Limit, "{events:?}");
737 assert_eq!(result.publication, Publication::None);
738 assert_eq!(result.created_count, 0);
739 assert_eq!(fs::read_dir(scratch.0.join("output")).unwrap().count(), 0);
740}
741
742#[test]
743fn deep_zip_returns_limit_without_abort_or_writes() {
744 let names = (0..100)
745 .map(|i| format!("{}file{i:03}", "a/".repeat(2000)))
746 .collect::<Vec<_>>();
747 assert_metadata_limit(&names);
748}
749
750#[test]
751fn shallow_zip_parent_metadata_is_bounded() {
752 let names = (0..500)
753 .map(|i| {
754 format!(
755 "d{i:04}{}/{}file",
756 "a".repeat(180),
757 format!("{}/", "b".repeat(200)).repeat(7)
758 )
759 })
760 .collect::<Vec<_>>();
761 assert!(
762 names
763 .iter()
764 .all(|n| n.split('/').count() <= archive::MAX_PATH_DEPTH)
765 );
766 assert!(
767 archive::parse(
768 &path_fixture_zip(&names),
769 Limits::default(),
770 false,
771 &mut || Ok(())
772 )
773 .is_ok()
774 );
775 assert_metadata_limit(&names);
776}
777
778#[test]
779fn aggregate_archive_name_metadata_is_bounded() {
780 let names = (0..1100)
781 .map(|i| {
782 format!(
783 "d{i:04}{}/{}file",
784 "a".repeat(180),
785 format!("{}/", "b".repeat(200)).repeat(9)
786 )
787 })
788 .collect::<Vec<_>>();
789 let bytes = path_fixture_zip(&names);
790 assert!((bytes.len() as u64) < Limits::default().input);
791 assert!(matches!(
792 archive::parse(&bytes, Limits::default(), false, &mut || Ok(())),
793 Err(ErrorCode::Limit)
794 ));
795 assert_metadata_limit(&names);
796}
797
798#[test]
799fn path_depth_boundary_is_explicit() {
800 let accepted = format!("{}file", "a/".repeat(archive::MAX_PATH_DEPTH - 1));
801 let rejected = format!("{}file", "a/".repeat(archive::MAX_PATH_DEPTH));
802 assert!(archive::valid_name(&accepted, false).is_ok());
803 assert_eq!(archive::valid_name(&rejected, false), Err(ErrorCode::Limit));
804}
805
806fn zeros_gzip(length: usize) -> Vec<u8> {
807 let mut gzip = vec![31, 139, 8, 0, 0, 0, 0, 0, 0, 255];
808 let mut left = length;
809 loop {
810 let size = left.min(u16::MAX as usize) as u16;
811 left -= size as usize;
812 gzip.push(u8::from(left == 0));
813 gzip.extend(size.to_le_bytes());
814 gzip.extend((!size).to_le_bytes());
815 gzip.resize(gzip.len() + size as usize, 0);
816 if left == 0 {
817 break;
818 }
819 }
820 gzip.extend(zlib_rs::crc32::crc32(0, &vec![0; length]).to_le_bytes());
821 gzip.extend((length as u32).to_le_bytes());
822 gzip
823}
824
825#[test]
826fn zero_payload_gzip_is_not_tar() {
827 for length in [512, 1024, 1536] {
828 let scratch = Scratch::new();
829 let bytes = zeros_gzip(length);
830 let parsed = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
831 assert_eq!(parsed.format, Format::Gzip);
832 let events = extract(
833 &scratch,
834 &bytes,
835 Some("zeros.bin"),
836 Selection::All,
837 None,
838 Limits::default(),
839 );
840 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
841 assert_eq!(
842 fs::read(scratch.0.join("output/zeros.bin")).unwrap(),
843 vec![0; length]
844 );
845 fs::write(scratch.0.join("input"), &bytes).unwrap();
846 let list_id = listing(&scratch);
847 assert_eq!(list_id.format, Format::Gzip);
848 }
849}
850
851const 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";
852const TEST_PASSWORD: &[u8] = b"fixture-password";
853const AES_ZIP: &[u8] = include_bytes!("fixtures/aes2-deflate.zip");
854fn interactive(
855 start: Start,
856 mut respond: impl FnMut(u64, u32, PasswordPurpose) -> Vec<Message>,
857) -> Vec<Message> {
858 use std::{io::Read, sync::mpsc, time::Duration};
859 let temporary = Scratch::new();
860 let mut child = temporary
861 .worker()
862 .stdin(Stdio::piped())
863 .stdout(Stdio::piped())
864 .stderr(Stdio::piped())
865 .spawn()
866 .unwrap();
867 let mut writer = Some(Writer::new(child.stdin.take().unwrap(), 17));
868 writer
869 .as_mut()
870 .unwrap()
871 .send(&Message::Start(start))
872 .unwrap();
873 let output = child.stdout.take().unwrap();
874 let mut errors = child.stderr.take().unwrap();
875 let error_thread = std::thread::spawn(move || {
876 let mut bytes = Vec::new();
877 errors.read_to_end(&mut bytes).unwrap();
878 bytes
879 });
880 let (sender, receiver) = mpsc::channel();
881 let reader_thread = std::thread::spawn(move || {
882 let mut reader = Reader::new(output);
883 loop {
884 let event = reader.read().map(|v| {
885 v.map(|(job, _, message)| {
886 assert_eq!(job, 17);
887 message
888 })
889 });
890 let done = !matches!(event, Ok(Some(_)));
891 if sender.send(event).is_err() || done {
892 break;
893 }
894 }
895 });
896 let mut events = Vec::new();
897 loop {
898 let event = match receiver.recv_timeout(Duration::from_secs(10)) {
899 Ok(event) => event.unwrap(),
900 Err(error) => {
901 child.kill().unwrap();
902 child.wait().unwrap();
903 panic!("worker timeout: {error}");
904 }
905 };
906 let Some(event) = event else {
907 break;
908 };
909 if let Message::PasswordRequired {
910 challenge_id,
911 attempt,
912 purpose,
913 } = &event
914 {
915 let commands = respond(*challenge_id, *attempt, *purpose);
916 if commands.is_empty() {
917 writer = None;
918 } else {
919 for command in commands {
920 writer.as_mut().unwrap().send(&command).unwrap();
921 }
922 }
923 }
924 if matches!(event, Message::Terminal(_)) {
925 writer = None;
926 }
927 events.push(event);
928 }
929 assert!(child.wait().unwrap().success());
930 reader_thread.join().unwrap();
931 assert!(error_thread.join().unwrap().is_empty());
932 assert!(matches!(events.last(), Some(Message::Terminal(_))));
933 events
934}
935fn password_reply(id: u64, password: &[u8]) -> Vec<Message> {
936 vec![Message::Password {
937 challenge_id: id,
938 secret: Secret(password.to_vec()),
939 }]
940}
941fn encrypted_start(s: &Scratch, bytes: &[u8]) -> Start {
942 fs::write(s.0.join("input"), bytes).unwrap();
943 fs::create_dir(s.0.join("output")).unwrap();
944 #[cfg(unix)]
945 {
946 use std::os::unix::fs::PermissionsExt;
947 fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
948 }
949 Start {
950 action: Action::Extract {
951 archive: s.path("input"),
952 destination: s.path("output"),
953 selection: Selection::All,
954 list_id: None,
955 gzip_output_name: None,
956 },
957 limits: Limits::default(),
958 }
959}
960fn no_encrypted_output(s: &Scratch, events: &[Message], error: ErrorCode) {
961 assert_eq!(terminal(events).error, error, "{events:?}");
962 assert_eq!(terminal(events).publication, Publication::None);
963 assert_eq!(terminal(events).created_count, 0);
964 assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
965 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
966}
967#[test]
968fn independent_encrypted_fixtures_list_and_extract() {
969 for bytes in [
970 include_bytes!("fixtures/aes1-store.zip").as_slice(),
971 include_bytes!("fixtures/aes1-deflate.zip").as_slice(),
972 include_bytes!("fixtures/aes2-store.zip").as_slice(),
973 AES_ZIP,
974 include_bytes!("fixtures/zipcrypto-store.zip").as_slice(),
975 include_bytes!("fixtures/zipcrypto-deflate.zip").as_slice(),
976 ] {
977 let s = Scratch::new();
978 let start = encrypted_start(&s, bytes);
979 let listing = execute(Start {
980 action: Action::List {
981 archive: s.path("input"),
982 },
983 limits: Limits::default(),
984 });
985 assert_eq!(
986 terminal(&listing).outcome,
987 Outcome::Completed,
988 "{listing:?}"
989 );
990 assert!(listing.iter().any(|e| matches!(
991 e,
992 Message::Entry(Entry {
993 encrypted: true,
994 ..
995 })
996 )));
997 assert!(
998 !listing
999 .iter()
1000 .any(|e| matches!(e, Message::PasswordRequired { .. }))
1001 );
1002 let events = interactive(start, |id, attempt, purpose| {
1003 assert_eq!(purpose, PasswordPurpose::Decrypt);
1004 assert_eq!(attempt, 1);
1005 password_reply(id, TEST_PASSWORD)
1006 });
1007 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1008 assert_eq!(
1009 fs::read(s.0.join("output/payload.bin")).unwrap(),
1010 ENCRYPTED_PAYLOAD
1011 );
1012 }
1013}
1014#[test]
1015fn aes_creation_uses_password_flow_and_independent_verification() {
1016 for method in [Method::Store, Method::Deflate] {
1017 let s = Scratch::new();
1018 fs::write(s.0.join("source"), ENCRYPTED_PAYLOAD).unwrap();
1019 let events = interactive(
1020 Start {
1021 action: Action::CreateZip {
1022 sources: vec![Source {
1023 path: s.path("source"),
1024 archive_name: "payload.bin".into(),
1025 }],
1026 output_file: s.path("encrypted.zip"),
1027 method,
1028 encryption: Encryption::Aes256,
1029 },
1030 limits: Limits::default(),
1031 },
1032 |id, attempt, purpose| {
1033 assert_eq!(purpose, PasswordPurpose::Encrypt);
1034 assert_eq!(attempt, 1);
1035 password_reply(id, TEST_PASSWORD)
1036 },
1037 );
1038 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1039 assert!(events.iter().any(|e| matches!(
1040 e,
1041 Message::Accepted {
1042 encryption: true,
1043 ..
1044 }
1045 )));
1046 #[cfg(target_os = "linux")]
1047 {
1048 let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1049 .join("../../tests/rust-archive-worker/encryption_fixtures.py");
1050 assert!(
1051 Command::new("python3")
1052 .arg(helper)
1053 .arg("--verify")
1054 .arg(s.0.join("encrypted.zip"))
1055 .status()
1056 .unwrap()
1057 .success()
1058 );
1059 }
1060 let bytes = fs::read(s.0.join("encrypted.zip")).unwrap();
1061 let start = encrypted_start(&s, &bytes);
1062 let events = interactive(start, |id, _, _| password_reply(id, TEST_PASSWORD));
1063 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1064 assert_eq!(
1065 fs::read(s.0.join("output/payload.bin")).unwrap(),
1066 ENCRYPTED_PAYLOAD
1067 );
1068 }
1069}
1070#[test]
1071fn wrong_password_retries_with_new_challenge_then_succeeds() {
1072 let s = Scratch::new();
1073 let start = encrypted_start(&s, AES_ZIP);
1074 let mut previous = 0;
1075 let events = interactive(start, |id, attempt, _| {
1076 assert!(id > previous);
1077 previous = id;
1078 password_reply(
1079 id,
1080 if attempt == 1 {
1081 b"wrong"
1082 } else {
1083 TEST_PASSWORD
1084 },
1085 )
1086 });
1087 assert_eq!(terminal(&events).outcome, Outcome::Completed);
1088 assert_eq!(previous, 2);
1089}
1090#[test]
1091fn wrong_password_attempts_are_bounded_without_writes() {
1092 let s = Scratch::new();
1093 let start = encrypted_start(&s, AES_ZIP);
1094 let mut attempts = 0;
1095 let events = interactive(start, |id, attempt, _| {
1096 attempts = attempt;
1097 password_reply(id, b"wrong")
1098 });
1099 assert_eq!(attempts, 3);
1100 no_encrypted_output(&s, &events, ErrorCode::WrongPassword);
1101}
1102#[test]
1103fn cancellation_while_waiting_for_password_is_acknowledged() {
1104 let s = Scratch::new();
1105 let start = encrypted_start(&s, AES_ZIP);
1106 let events = interactive(start, |_, _, _| vec![Message::Cancel]);
1107 assert_eq!(terminal(&events).outcome, Outcome::Cancelled);
1108 assert!(events.iter().any(|e| matches!(
1109 e,
1110 Message::CancelAck {
1111 status: CancelStatus::Requested,
1112 ..
1113 }
1114 )));
1115 no_encrypted_output(&s, &events, ErrorCode::None);
1116}
1117#[test]
1118fn stale_and_mismatched_password_challenges_fail_without_writes() {
1119 for stale in [false, true] {
1120 let s = Scratch::new();
1121 let start = encrypted_start(&s, AES_ZIP);
1122 let events = interactive(start, |id, attempt, _| {
1123 if stale && attempt == 1 {
1124 password_reply(id, b"wrong")
1125 } else {
1126 password_reply(if stale { id - 1 } else { id + 1 }, TEST_PASSWORD)
1127 }
1128 });
1129 no_encrypted_output(&s, &events, ErrorCode::Protocol);
1130 }
1131}
1132#[test]
1133fn password_input_eof_fails_without_writes() {
1134 let s = Scratch::new();
1135 let start = encrypted_start(&s, AES_ZIP);
1136 let events = interactive(start, |_, _, _| vec![]);
1137 no_encrypted_output(&s, &events, ErrorCode::Protocol);
1138}
1139#[test]
1140fn aes_authentication_failure_never_publishes_plaintext() {
1141 for tamper_tag in [false, true] {
1142 let mut bytes = AES_ZIP.to_vec();
1143 let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
1144 if tamper_tag {
1145 bytes[central - 1] ^= 1;
1146 } else {
1147 bytes[30 + b"payload.bin".len() + 11 + 18] ^= 1;
1148 }
1149 let s = Scratch::new();
1150 let start = encrypted_start(&s, &bytes);
1151 let events = interactive(start, |id, _, _| password_reply(id, TEST_PASSWORD));
1152 no_encrypted_output(&s, &events, ErrorCode::Integrity);
1153 }
1154}
1155#[test]
1156fn aes1_crc_and_extra_consistency_are_checked() {
1157 let original = include_bytes!("fixtures/aes1-store.zip");
1158 for corrupt_extra in [false, true] {
1159 let mut bytes = original.to_vec();
1160 let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
1161 if corrupt_extra {
1162 bytes[30 + b"payload.bin".len() + 4] = 2;
1163 } else {
1164 bytes[14] ^= 1;
1165 bytes[central + 16] ^= 1;
1166 }
1167 let s = Scratch::new();
1168 let start = encrypted_start(&s, &bytes);
1169 let events = interactive(start, |id, _, _| password_reply(id, TEST_PASSWORD));
1170 no_encrypted_output(&s, &events, ErrorCode::Integrity);
1171 }
1172}
1173#[test]
1174fn empty_aes_members_and_random_salts_round_trip() {
1175 let members = vec![archive::Member {
1176 entry: Entry {
1177 entry_id: 0,
1178 name: "empty".into(),
1179 kind: EntryKind::File,
1180 size: 0,
1181 compressed_size: 0,
1182 encrypted: false,
1183 },
1184 data: vec![],
1185 }];
1186 let a = archive::create_zip_with_password(
1187 &members,
1188 Method::Store,
1189 Limits::default(),
1190 Some(TEST_PASSWORD),
1191 &mut || Ok(()),
1192 )
1193 .unwrap();
1194 let b = archive::create_zip_with_password(
1195 &members,
1196 Method::Store,
1197 Limits::default(),
1198 Some(TEST_PASSWORD),
1199 &mut || Ok(()),
1200 )
1201 .unwrap();
1202 assert_ne!(a, b);
1203 let decoded = archive::parse_with_password(
1204 &a,
1205 Limits::default(),
1206 true,
1207 Some(TEST_PASSWORD),
1208 &mut || Ok(()),
1209 )
1210 .unwrap();
1211 assert!(decoded.members[0].data.is_empty());
1212}
1213
1214#[test]
1215fn password_racing_after_cancel_does_not_override_cancellation() {
1216 let s = Scratch::new();
1217 let start = encrypted_start(&s, AES_ZIP);
1218 let events = interactive(start, |id, _, _| {
1219 vec![
1220 Message::Cancel,
1221 Message::Password {
1222 challenge_id: id,
1223 secret: Secret(TEST_PASSWORD.to_vec()),
1224 },
1225 ]
1226 });
1227 assert_eq!(terminal(&events).outcome, Outcome::Cancelled);
1228 no_encrypted_output(&s, &events, ErrorCode::None);
1229}
1230#[test]
1231fn empty_encryption_password_never_creates_zip() {
1232 let s = Scratch::new();
1233 let events = interactive(
1234 Start {
1235 action: Action::CreateZip {
1236 sources: vec![],
1237 output_file: s.path("empty.zip"),
1238 method: Method::Store,
1239 encryption: Encryption::Aes256,
1240 },
1241 limits: Limits::default(),
1242 },
1243 |id, _, _| password_reply(id, b""),
1244 );
1245 assert_eq!(terminal(&events).error, ErrorCode::InvalidRequest);
1246 assert_eq!(terminal(&events).publication, Publication::None);
1247 assert!(!s.0.join("empty.zip").exists());
1248}
1249
1250const SEVEN_PAYLOAD: &[u8] = b"Zipelo 7z interoperability\n";
1251fn seven_fixture(name: &str) -> Vec<u8> {
1252 fs::read(
1253 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1254 .join("../../tests/rust-archive-worker/fixtures/7z")
1255 .join(name),
1256 )
1257 .unwrap()
1258}
1259#[test]
1260fn seven_zip_lzma_lzma2_and_copy_interoperate() {
1261 for name in [
1262 "copy.7z",
1263 "lzma.7z",
1264 "lzma2.7z",
1265 "properties-0.7z",
1266 "properties-1.7z",
1267 "properties-2.7z",
1268 "properties-3.7z",
1269 "libarchive-lzma1.7z",
1270 "libarchive-lzma2.7z",
1271 ] {
1272 let bytes = seven_fixture(name);
1273 let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(()))
1274 .unwrap_or_else(|e| panic!("{name}: {e:?}"));
1275 assert_eq!(catalog.format, Format::SevenZip);
1276 assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(100), "{name}");
1277 let s = Scratch::new();
1278 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1279 assert_eq!(
1280 terminal(&events).outcome,
1281 Outcome::Completed,
1282 "{name}: {events:?}"
1283 );
1284 assert_eq!(
1285 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
1286 SEVEN_PAYLOAD.repeat(100)
1287 );
1288 }
1289}
1290#[test]
1291fn seven_zip_encoded_header_solid_and_empty_entries() {
1292 let s = Scratch::new();
1293 let bytes = seven_fixture("encoded-solid.7z");
1294 let catalog = archive::parse(&bytes, Limits::default(), false, &mut || Ok(())).unwrap();
1295 assert_eq!(catalog.members.len(), 4);
1296 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1297 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
1298 assert_eq!(fs::read(s.0.join("output/folder/empty")).unwrap(), b"");
1299 assert_eq!(
1300 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
1301 SEVEN_PAYLOAD.repeat(100)
1302 );
1303 let mut reverse = SEVEN_PAYLOAD.repeat(100);
1304 reverse.reverse();
1305 assert_eq!(fs::read(s.0.join("output/한글.txt")).unwrap(), reverse);
1306}
1307#[test]
1308fn seven_zip_long_matches_and_lzma2_chunks() {
1309 for name in ["long-match.7z", "lzma2-chunks.7z"] {
1310 let bytes = seven_fixture(name);
1311 let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(()))
1312 .unwrap_or_else(|e| panic!("{name}: {e:?}"));
1313 if name == "long-match.7z" {
1314 assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(10000));
1315 } else {
1316 let expected = (0..100000u64)
1317 .map(|i| (((i * 1103515245 + (i >> 2) * 12345) >> ((i % 4) * 8)) & 255) as u8)
1318 .collect::<Vec<_>>();
1319 assert_eq!(catalog.members[0].data, expected);
1320 }
1321 }
1322}
1323#[test]
1324fn seven_zip_malicious_inputs_never_write() {
1325 for name in [
1326 "unsafe-dotdot.7z",
1327 "unsafe-absolute.7z",
1328 "unsafe-drive.7z",
1329 "unsafe-backslash.7z",
1330 "unsafe-deep.7z",
1331 "symlink.7z",
1332 "collision.7z",
1333 "bad-payload.7z",
1334 "bad-crc.7z",
1335 "bad-dictionary.7z",
1336 ] {
1337 let s = Scratch::new();
1338 let bytes = seven_fixture(name);
1339 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1340 assert_eq!(
1341 terminal(&events).outcome,
1342 Outcome::Failed,
1343 "{name}: {events:?}"
1344 );
1345 assert_eq!(terminal(&events).publication, Publication::None);
1346 assert_eq!(terminal(&events).created_count, 0);
1347 assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
1348 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1349 assert!(!s.0.join("outside.txt").exists());
1350 }
1351}
1352
1353#[test]
1354fn seven_zip_format_wire_tag_preserves_existing_encodings() {
1355 for (tag, format) in [
1356 Format::Zip,
1357 Format::Tar,
1358 Format::Gzip,
1359 Format::TarGzip,
1360 Format::SevenZip,
1361 ]
1362 .into_iter()
1363 .enumerate()
1364 {
1365 let token = ListId {
1366 catalog_version: 1,
1367 format,
1368 source_object: SourceObject::Unix {
1369 device: 1,
1370 inode: 2,
1371 },
1372 archive_bytes: 3,
1373 archive_sha256: [4; 32],
1374 };
1375 let mut bytes = Vec::new();
1376 Writer::new(&mut bytes, 17)
1377 .send(&Message::ListEnd {
1378 entry_count: 5,
1379 list_id: token.clone(),
1380 })
1381 .unwrap();
1382 assert_eq!(bytes[38], tag as u8);
1383 match Reader::new(bytes.as_slice()).read().unwrap().unwrap().2 {
1384 Message::ListEnd {
1385 entry_count,
1386 list_id,
1387 } => {
1388 assert_eq!(entry_count, 5);
1389 assert_eq!(list_id, token);
1390 }
1391 _ => panic!("expected ListEnd"),
1392 }
1393 }
1394}
1395#[test]
1396fn seven_zip_listing_token_and_selection() {
1397 let s = Scratch::new();
1398 let bytes = seven_fixture("encoded-solid.7z");
1399 fs::write(s.0.join("input"), &bytes).unwrap();
1400 let events = execute(Start {
1401 action: Action::List {
1402 archive: s.path("input"),
1403 },
1404 limits: Limits::default(),
1405 });
1406 assert_eq!(terminal(&events).outcome, Outcome::Completed);
1407 let list_id = events
1408 .into_iter()
1409 .find_map(|e| {
1410 if let Message::ListEnd { list_id, .. } = e {
1411 Some(list_id)
1412 } else {
1413 None
1414 }
1415 })
1416 .unwrap();
1417 assert_eq!(list_id.format, Format::SevenZip);
1418 let events = extract(
1419 &s,
1420 &bytes,
1421 None,
1422 Selection::EntryIds(vec![3]),
1423 Some(list_id),
1424 Limits::default(),
1425 );
1426 assert_eq!(terminal(&events).outcome, Outcome::Completed);
1427 assert_eq!(terminal(&events).created_count, 1);
1428 assert!(!s.0.join("output/folder").exists());
1429 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
1430}
1431#[test]
1432fn seven_zip_limits_truncation_and_existing_files_are_preserved() {
1433 let bytes = seven_fixture("lzma2.7z");
1434 for cut in [0, 1, 6, 12, 31, 32, bytes.len() - 1] {
1435 let s = Scratch::new();
1436 let events = extract(
1437 &s,
1438 &bytes[..cut],
1439 None,
1440 Selection::All,
1441 None,
1442 Limits::default(),
1443 );
1444 assert_eq!(terminal(&events).outcome, Outcome::Failed);
1445 assert_eq!(terminal(&events).publication, Publication::None);
1446 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1447 }
1448 let s = Scratch::new();
1449 let events = extract(
1450 &s,
1451 &bytes,
1452 None,
1453 Selection::All,
1454 None,
1455 Limits {
1456 output: 100,
1457 ..Limits::default()
1458 },
1459 );
1460 assert_eq!(terminal(&events).error, ErrorCode::Limit);
1461 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1462 fs::create_dir(s.0.join("output/folder")).unwrap();
1463 #[cfg(unix)]
1464 {
1465 use std::os::unix::fs::PermissionsExt;
1466 fs::set_permissions(s.0.join("output/folder"), fs::Permissions::from_mode(0o700)).unwrap();
1467 }
1468 fs::write(s.0.join("output/folder/hello.txt"), b"preserve").unwrap();
1469 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
1470 assert_eq!(terminal(&events).error, ErrorCode::Conflict);
1471 assert_eq!(
1472 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
1473 b"preserve"
1474 );
1475 let s = Scratch::new();
1476 let events = extract(
1477 &s,
1478 &seven_fixture("bad-trailing.7z"),
1479 None,
1480 Selection::All,
1481 None,
1482 Limits::default(),
1483 );
1484 assert_eq!(terminal(&events).error, ErrorCode::Integrity);
1485 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1486}
1487#[test]
1488fn seven_zip_parser_honors_cancellation_checkpoints() {
1489 let bytes = seven_fixture("long-match.7z");
1490 let mut calls = 0;
1491 let result = archive::parse(&bytes, Limits::default(), true, &mut || {
1492 calls += 1;
1493 if calls >= 5 {
1494 Err(ErrorCode::None)
1495 } else {
1496 Ok(())
1497 }
1498 });
1499 assert!(matches!(result, Err(ErrorCode::None)));
1500}
1501#[test]
1502fn pr64_malicious_corpus_is_rejected_without_writes() {
1503 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1504 .join("../../tests/malicious-archive-fixtures/fixtures");
1505 let cases = [
1506 ("zip-dotdot.zip", ErrorCode::UnsafePath, 131072, None),
1507 (
1508 "zip-absolute-posix.zip",
1509 ErrorCode::UnsafePath,
1510 131072,
1511 None,
1512 ),
1513 (
1514 "zip-absolute-drive.zip",
1515 ErrorCode::UnsafePath,
1516 131072,
1517 None,
1518 ),
1519 (
1520 "zip-backslash-dotdot.zip",
1521 ErrorCode::UnsafePath,
1522 131072,
1523 None,
1524 ),
1525 ("tar-dotdot.tar", ErrorCode::UnsafePath, 131072, None),
1526 ("targz-dotdot.tar.gz", ErrorCode::UnsafePath, 131072, None),
1527 (
1528 "tar-absolute-posix.tar",
1529 ErrorCode::UnsafePath,
1530 131072,
1531 None,
1532 ),
1533 ("zip-symlink-escape.zip", ErrorCode::Conflict, 131072, None),
1534 ("tar-symlink-escape.tar", ErrorCode::Conflict, 131072, None),
1535 ("zip-output-limit.zip", ErrorCode::Limit, 1024, None),
1536 (
1537 "gzip-output-limit.gz",
1538 ErrorCode::Limit,
1539 1024,
1540 Some("payload.bin"),
1541 ),
1542 ("targz-output-limit.tar.gz", ErrorCode::Limit, 1024, None),
1543 (
1544 "zip-bad-local-header.zip",
1545 ErrorCode::Integrity,
1546 131072,
1547 None,
1548 ),
1549 ("tar-bad-checksum.tar", ErrorCode::Integrity, 131072, None),
1550 (
1551 "gzip-reserved-flags.gz",
1552 ErrorCode::Integrity,
1553 131072,
1554 Some("payload.bin"),
1555 ),
1556 ];
1557 for (name, expected, output, gzip) in cases {
1558 let s = Scratch::new();
1559 let bytes = fs::read(root.join(name)).unwrap();
1560 fs::write(s.0.join("outside.txt"), b"preserve").unwrap();
1561 let events = extract(
1562 &s,
1563 &bytes,
1564 gzip,
1565 Selection::All,
1566 None,
1567 Limits {
1568 input: 1048576,
1569 output,
1570 entries: 64,
1571 },
1572 );
1573 assert_eq!(
1574 terminal(&events).outcome,
1575 Outcome::Failed,
1576 "{name}: {events:?}"
1577 );
1578 assert_eq!(terminal(&events).error, expected, "{name}");
1579 assert_eq!(terminal(&events).publication, Publication::None);
1580 assert_eq!(terminal(&events).created_count, 0);
1581 assert_eq!(terminal(&events).retained_partial_count, 0);
1582 assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
1583 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
1584 assert_eq!(fs::read(s.0.join("outside.txt")).unwrap(), b"preserve");
1585 assert_eq!(fs::read(s.0.join("input")).unwrap(), bytes);
1586 }
1587}
1588#[cfg(target_os = "linux")]
1589#[test]
1590fn seven_zip_reference_reader_accepts_synthetic_fixtures() {
1591 let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1592 .join("../../tests/rust-archive-worker/seven_zip_reference.py");
1593 assert!(
1594 Command::new("python3")
1595 .arg(helper)
1596 .status()
1597 .unwrap()
1598 .success()
1599 );
1600}
1601
1602mod hardening;
1603
1604#[test]
1605fn disk_full_error_tag_preserves_previous_tags_and_rejects_unknown() {
1606 for (tag, error) in [
1607 ErrorCode::None,
1608 ErrorCode::Integrity,
1609 ErrorCode::UnsupportedFormat,
1610 ErrorCode::UnsupportedFeature,
1611 ErrorCode::WrongPassword,
1612 ErrorCode::UnsafePath,
1613 ErrorCode::Conflict,
1614 ErrorCode::Limit,
1615 ErrorCode::Io,
1616 ErrorCode::Protocol,
1617 ErrorCode::Internal,
1618 ErrorCode::SourceChanged,
1619 ErrorCode::InvalidRequest,
1620 ErrorCode::DiskFull,
1621 ]
1622 .into_iter()
1623 .enumerate()
1624 {
1625 let message = Message::Terminal(Terminal {
1626 outcome: Outcome::Failed,
1627 error,
1628 publication: Publication::None,
1629 created_count: 0,
1630 retained_partial_count: 0,
1631 durability: Durability::NotApplicable,
1632 cleanup: Cleanup::Complete,
1633 detail: String::new(),
1634 });
1635 let mut bytes = Vec::new();
1636 Writer::new(&mut bytes, 17).send(&message).unwrap();
1637 assert_eq!(bytes[33], tag as u8);
1638 let decoded = Reader::new(bytes.as_slice()).read().unwrap().unwrap().2;
1639 assert_eq!(terminal(&[decoded]).error, error);
1640 bytes[33] = 17;
1641 assert!(Reader::new(bytes.as_slice()).read().is_err());
1642 }
1643}
1644
1645mod folder_inputs;
1646
1647mod zip_names;
1648
1649mod conflict_wire;
1650
1651mod preview_wire;
1652
1653mod split_volume_wire;
1654
1655mod preview_runtime;
1656
1657mod conflicts;
1658
1659mod compressed_tar;
1660
1661mod guarded;
1662
1663mod split_runtime;
1664
1665mod seven_zip_create;
1666
1667mod seven_zip_create_runtime;
1668
1669mod recovery;
1670
1671#[cfg(target_os = "linux")]
1672mod partial_output;
1673
1674#[cfg(target_os = "linux")]
1675mod spool_location;
1676
1677#[cfg(target_os = "linux")]
1678mod spool_fallback;