team-ljyzipelo

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