team-ljyzipelo

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