team-ljyzipelo

공개
890줄32 KB
1use super::*;
2use sha2::{Digest, Sha256};
3
4fn start(s: &Scratch) -> Start {
5 Start {
6 action: Action::RecoverZip {
7 archive: s.path("damaged.zip"),
8 output_file: s.path("recovered.zip"),
9 },
10 limits: Limits::default(),
11 }
12}
13fn hash(data: &[u8]) -> String {
14 format!("{:x}", Sha256::digest(data))
15}
16fn recovery_end(events: &[Message]) -> &RecoveryEnd {
17 events
18 .iter()
19 .find_map(|e| {
20 if let Message::RecoveryEnd(end) = e {
21 Some(end)
22 } else {
23 None
24 }
25 })
26 .unwrap()
27}
28#[test]
29fn six_damaged_corpora_preserve_source_and_independent_expected_hashes() {
30 let cases: &[(&str, &[u8], usize, bool)] = &[
31 (
32 "broken-local-header.zip",
33 include_bytes!("../zip-recovery-fixtures/broken-local-header.zip"),
34 6,
35 true,
36 ),
37 (
38 "missing-directory.zip",
39 include_bytes!("../zip-recovery-fixtures/missing-directory.zip"),
40 6,
41 false,
42 ),
43 (
44 "broken-eocd.zip",
45 include_bytes!("../zip-recovery-fixtures/broken-eocd.zip"),
46 6,
47 false,
48 ),
49 (
50 "middle-truncated.zip",
51 include_bytes!("../zip-recovery-fixtures/middle-truncated.zip"),
52 4,
53 false,
54 ),
55 (
56 "body-corrupt.zip",
57 include_bytes!("../zip-recovery-fixtures/body-corrupt.zip"),
58 5,
59 false,
60 ),
61 (
62 "unrecoverable.zip",
63 include_bytes!("../zip-recovery-fixtures/unrecoverable.zip"),
64 0,
65 false,
66 ),
67 ];
68 let expected = [
69 (
70 "hello.txt",
71 "29020da72fa4030c58e0303f558b922f6ed5b6766600e67d79e0abf13971f9da",
72 ),
73 (
74 "한글/자료.txt",
75 "3fd2605633caf264a9cf9eb1fc23abc4a60b3191fc808a6a0f71863c64690be5",
76 ),
77 (
78 "empty.txt",
79 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
80 ),
81 (
82 "empty-dir",
83 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
84 ),
85 (
86 "middle.bin",
87 "785b0751fc2c53dc14a4ce3d800e69ef9ce1009eb327ccf458afe09c242c26c9",
88 ),
89 (
90 "after.txt",
91 "7ea5f891c2d1be8db73893862b433f6680e33e11a7246baeea0addd8d296975c",
92 ),
93 ];
94 for &(sample, input, count, complete) in cases {
95 let s = Scratch::new();
96 fs::write(s.0.join("damaged.zip"), input).unwrap();
97 let events = execute(start(&s));
98 let t = terminal(&events);
99 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), input);
100 let end = recovery_end(&events);
101 assert_eq!(end.source_sha256, <[u8; 32]>::from(Sha256::digest(input)));
102 assert_eq!(end.verified_entries as usize, count);
103 assert_eq!(end.unknown_loss, !complete);
104 assert_eq!(end.known_entries, if complete { Some(6) } else { None });
105 assert!(!events.iter().any(|e| matches!(
106 e,
107 Message::Entry(_)
108 | Message::ListEnd { .. }
109 | Message::PasswordRequired { .. }
110 | Message::ConflictRequired { .. }
111 )));
112 assert!(matches!(
113 events[0],
114 Message::Accepted {
115 action: ActionKind::RecoverZip,
116 encryption: false
117 }
118 ));
119 if count == 0 {
120 assert_eq!(t.error, ErrorCode::RecoveryImpossible);
121 assert_eq!(t.publication, Publication::None);
122 assert!(!s.0.join("recovered.zip").exists());
123 continue;
124 }
125 assert_eq!(
126 t.error,
127 if complete {
128 ErrorCode::None
129 } else {
130 ErrorCode::RecoveryIncomplete
131 }
132 );
133 assert_eq!(
134 t.outcome,
135 if complete {
136 Outcome::Completed
137 } else {
138 Outcome::Failed
139 }
140 );
141 assert_eq!(t.created_count, 1);
142 assert_eq!(t.publication, Publication::Complete);
143 let bytes = fs::read(s.0.join("recovered.zip")).unwrap();
144 let catalog = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
145 assert_eq!(catalog.members.len(), count);
146 for member in &catalog.members {
147 let (_, sha) = expected
148 .iter()
149 .find(|(name, _)| *name == member.entry.name)
150 .unwrap();
151 assert_eq!(&hash(&member.data), sha);
152 }
153 let checker = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
154 .join("../../tests/zip-recovery-fixtures/verify.py");
155 let checked = Command::new("python3")
156 .arg("-B")
157 .arg(checker)
158 .arg("--recovered")
159 .arg(sample)
160 .arg(s.0.join("recovered.zip"))
161 .output()
162 .unwrap();
163 assert!(checked.status.success(), "{:?}", checked);
164 let findings: Vec<_> = events
165 .iter()
166 .filter_map(|e| {
167 if let Message::RecoveryEntry(f) = e {
168 Some(f)
169 } else {
170 None
171 }
172 })
173 .collect();
174 for (i, f) in findings.iter().enumerate() {
175 assert_eq!(f.candidate_id, i as u32);
176 assert!(f.valid());
177 assert!(f.source_offset < end.source_bytes);
178 if i > 0 {
179 assert!(findings[i - 1].source_offset < f.source_offset);
180 }
181 }
182 if count == 4 {
183 assert!(
184 !findings
185 .iter()
186 .any(|f| f.name.as_deref() == Some("after.txt"))
187 );
188 }
189 if count == 5 {
190 assert!(findings.iter().any(
191 |f| f.name.as_deref() == Some("middle.bin") && f.status == RecoveryStatus::Lost
192 ));
193 }
194 }
195}
196#[test]
197fn healthy_source_and_existing_destination_are_never_rewritten() {
198 let s = Scratch::new();
199 let bytes = include_bytes!("../zip-recovery-fixtures/control.zip");
200 fs::write(s.0.join("damaged.zip"), bytes).unwrap();
201 let events = execute(start(&s));
202 assert_eq!(terminal(&events).error, ErrorCode::InvalidRequest);
203 assert!(!s.0.join("recovered.zip").exists());
204 fs::write(s.0.join("recovered.zip"), b"keep").unwrap();
205 let events = execute(start(&s));
206 assert_eq!(terminal(&events).error, ErrorCode::Conflict);
207 assert_eq!(fs::read(s.0.join("recovered.zip")).unwrap(), b"keep");
208 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), bytes);
209}
210#[test]
211fn lower_input_output_and_candidate_quotas_leave_no_artifact() {
212 for kind in 0..3 {
213 let s = Scratch::new();
214 fs::write(
215 s.0.join("damaged.zip"),
216 include_bytes!("../zip-recovery-fixtures/missing-directory.zip"),
217 )
218 .unwrap();
219 let mut request = start(&s);
220 match kind {
221 0 => request.limits.input = 100,
222 1 => request.limits.output = 100,
223 _ => request.limits.entries = 2,
224 }
225 let events = execute(request);
226 assert_eq!(terminal(&events).error, ErrorCode::Limit);
227 assert!(!s.0.join("recovered.zip").exists());
228 }
229}
230#[test]
231fn unsafe_names_unsupported_input_and_payload_signatures_do_not_trigger_scanning() {
232 let original = include_bytes!("../zip-recovery-fixtures/missing-directory.zip");
233 for kind in 0..4 {
234 let s = Scratch::new();
235 let mut bytes = original.to_vec();
236 let expected = match kind {
237 0 => {
238 bytes[30..39].copy_from_slice(b"../x.txt/");
239 ErrorCode::UnsafePath
240 }
241 1 => {
242 bytes[18..22].copy_from_slice(&u32::MAX.to_le_bytes());
243 ErrorCode::UnsupportedFeature
244 }
245 2 => {
246 bytes[..2].copy_from_slice(b"MZ");
247 ErrorCode::UnsupportedFeature
248 }
249 _ => {
250 bytes[39..43].copy_from_slice(b"PK\x03\x04");
251 ErrorCode::RecoveryIncomplete
252 }
253 };
254 fs::write(s.0.join("damaged.zip"), &bytes).unwrap();
255 let events = execute(start(&s));
256 assert_eq!(terminal(&events).error, expected);
257 if kind == 3 {
258 assert_eq!(recovery_end(&events).verified_entries, 5);
259 } else {
260 assert!(!s.0.join("recovered.zip").exists());
261 }
262 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), bytes);
263 }
264}
265#[test]
266fn recovery_wire_rejects_interactive_modes_invalid_hashes_and_summary_overflow() {
267 let s = Scratch::new();
268 let request = start(&s);
269 assert!(
270 Writer::new(Vec::new(), 17)
271 .send(&Message::StartInteractive(request.clone()))
272 .is_err()
273 );
274 let guarded = GuardedStart {
275 start: request,
276 ceiling: Limits::default(),
277 interactive: true,
278 };
279 assert!(!guarded.valid());
280 assert!(
281 Writer::new(Vec::new(), 17)
282 .send(&Message::StartGuarded(guarded))
283 .is_err()
284 );
285 let good = RecoveryEntry {
286 candidate_id: 0,
287 source_offset: 0,
288 name: Some("ok".into()),
289 kind: Some(EntryKind::File),
290 status: RecoveryStatus::Verified,
291 reason: RecoveryReason::HeaderRebuilt,
292 declared_size: Some(0),
293 verified_size: Some(0),
294 sha256: Some([0; 32]),
295 };
296 let mut bytes = Vec::new();
297 Writer::new(&mut bytes, 17)
298 .send(&Message::RecoveryEntry(good.clone()))
299 .unwrap();
300 assert_eq!(u16::from_le_bytes(bytes[6..8].try_into().unwrap()), 115);
301 assert!(
302 matches!(Reader::new(bytes.as_slice()).read().unwrap().unwrap().2,Message::RecoveryEntry(f) if f==good)
303 );
304 let mut bad = good;
305 bad.sha256 = None;
306 assert!(
307 Writer::new(Vec::new(), 17)
308 .send(&Message::RecoveryEntry(bad))
309 .is_err()
310 );
311 let summary = RecoveryEnd {
312 mode: RecoveryMode::LocalChain,
313 source_bytes: 10,
314 source_sha256: [0; 32],
315 known_entries: None,
316 verified_entries: u32::MAX,
317 lost_entries: 1,
318 unverified_entries: 0,
319 unknown_loss: true,
320 };
321 assert!(!summary.valid());
322 assert!(
323 Writer::new(Vec::new(), 17)
324 .send(&Message::RecoveryEnd(summary))
325 .is_err()
326 );
327}
328
329#[cfg(target_os = "linux")]
330fn shim(s: &Scratch) -> PathBuf {
331 let library = s.0.join("fault.so");
332 assert!(
333 Command::new("cc")
334 .args(["-shared", "-fPIC", "-O2"])
335 .arg(
336 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
337 .join("../../tests/rust-archive-worker/io_fault.c")
338 )
339 .arg("-ldl")
340 .arg("-o")
341 .arg(&library)
342 .status()
343 .unwrap()
344 .success()
345 );
346 library
347}
348#[cfg(target_os = "linux")]
349#[test]
350fn recovery_disk_errors_preserve_publication_truth_and_source() {
351 for mode in [
352 "temp-full",
353 "codec-full",
354 "create-full",
355 "full",
356 "write-io",
357 "sync-full",
358 "dir-sync-full",
359 ] {
360 let s = Scratch::new();
361 let original = include_bytes!("../zip-recovery-fixtures/missing-directory.zip");
362 fs::write(s.0.join("damaged.zip"), original).unwrap();
363 let mut command = s.worker();
364 command
365 .env("LD_PRELOAD", shim(&s))
366 .env("ZIPELO_TEST_FAULT", mode)
367 .env("ZIPELO_TEST_MARKER", s.0.join("marker"))
368 .stdin(Stdio::piped())
369 .stdout(Stdio::piped())
370 .stderr(Stdio::piped());
371 let mut child = command.spawn().unwrap();
372 Writer::new(child.stdin.take().unwrap(), 17)
373 .send(&Message::Start(start(&s)))
374 .unwrap();
375 let output = child.wait_with_output().unwrap();
376 assert!(output.status.success());
377 assert!(output.stderr.is_empty());
378 let mut reader = Reader::new(output.stdout.as_slice());
379 let mut events = Vec::new();
380 while let Some((_, _, event)) = reader.read().unwrap() {
381 events.push(event);
382 }
383 let t = terminal(&events);
384 assert_eq!(t.outcome, Outcome::Failed, "{mode}: {events:?}");
385 assert_eq!(
386 t.error,
387 if mode == "write-io" {
388 ErrorCode::Io
389 } else {
390 ErrorCode::DiskFull
391 },
392 "{mode}: {events:?}"
393 );
394 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), original);
395 assert_eq!(s.0.join("recovered.zip").exists(), mode == "dir-sync-full");
396 assert_eq!(t.created_count, u64::from(mode == "dir-sync-full"));
397 assert!(!fs::read_dir(&s.0).unwrap().any(|e| {
398 e.unwrap()
399 .file_name()
400 .to_string_lossy()
401 .starts_with(".zipelo-")
402 }));
403 }
404}
405#[cfg(target_os = "linux")]
406#[test]
407fn recovery_publication_rechecks_source_destination_and_cancel() {
408 use std::time::{Duration, Instant};
409 struct Running(std::process::Child);
410 impl Drop for Running {
411 fn drop(&mut self) {
412 let _ = self.0.kill();
413 let _ = self.0.wait();
414 }
415 }
416 for mode in 0..3 {
417 let s = Scratch::new();
418 let original = include_bytes!("../zip-recovery-fixtures/missing-directory.zip");
419 fs::write(s.0.join("damaged.zip"), original).unwrap();
420 let marker = s.0.join("marker");
421 let release = s.0.join("release");
422 let mut cmd = s.worker();
423 cmd.env("LD_PRELOAD", shim(&s))
424 .env("ZIPELO_TEST_FAULT", "pause")
425 .env("ZIPELO_TEST_MARKER", &marker)
426 .env("ZIPELO_TEST_RELEASE", &release)
427 .stdin(Stdio::piped())
428 .stdout(Stdio::piped())
429 .stderr(Stdio::piped());
430 let mut child = Running(cmd.spawn().unwrap());
431 let mut writer = Writer::new(child.0.stdin.take().unwrap(), 17);
432 writer.send(&Message::Start(start(&s))).unwrap();
433 let until = Instant::now() + Duration::from_secs(10);
434 while !marker.exists() {
435 assert!(Instant::now() < until);
436 std::thread::sleep(Duration::from_millis(5));
437 }
438 let mut reader = Reader::new(child.0.stdout.take().unwrap());
439 let mut events = Vec::new();
440 let mut expected = original.to_vec();
441 if mode == 0 {
442 expected[40] ^= 1;
443 fs::write(s.0.join("damaged.zip"), &expected).unwrap();
444 }
445 if mode == 1 {
446 fs::write(s.0.join("recovered.zip"), b"user save").unwrap();
447 }
448 if mode == 2 {
449 writer.send(&Message::Cancel).unwrap();
450 loop {
451 let event = reader.read().unwrap().unwrap().2;
452 let ack = matches!(
453 event,
454 Message::CancelAck {
455 status: CancelStatus::Requested,
456 ..
457 }
458 );
459 events.push(event);
460 if ack {
461 break;
462 }
463 }
464 }
465 fs::write(&release, b"go").unwrap();
466 while let Some((_, _, event)) = reader.read().unwrap() {
467 events.push(event);
468 }
469 drop(writer);
470 assert!(child.0.wait().unwrap().success());
471 let t = terminal(&events);
472 assert_eq!(
473 t.error,
474 match mode {
475 0 => ErrorCode::SourceChanged,
476 1 => ErrorCode::Conflict,
477 _ => ErrorCode::None,
478 }
479 );
480 assert_eq!(
481 t.outcome,
482 if mode == 2 {
483 Outcome::Cancelled
484 } else {
485 Outcome::Failed
486 }
487 );
488 assert_eq!(t.created_count, 0);
489 assert_eq!(t.publication, Publication::None);
490 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), expected);
491 if mode == 1 {
492 assert_eq!(fs::read(s.0.join("recovered.zip")).unwrap(), b"user save");
493 } else {
494 assert!(!s.0.join("recovered.zip").exists());
495 }
496 }
497}
498
499#[test]
500fn central_comment_locator_bytes_do_not_reject_zip32_recovery() {
501 let source = include_bytes!("../zip-recovery-fixtures/broken-local-header.zip");
502 for comment_len in [20usize, 37] {
503 for archive_comment_len in [0usize, 41] {
504 let mut input = source[..source.len() - 22].to_vec();
505 let last = input.windows(4).rposition(|w| w == b"PK\x01\x02").unwrap();
506 input[last + 32..last + 34].copy_from_slice(&(comment_len as u16).to_le_bytes());
507 let mut comment = vec![0; comment_len];
508 comment[comment_len - 20..comment_len - 16].copy_from_slice(b"PK\x06\x07");
509 input.extend(comment);
510 let mut end = source[source.len() - 22..].to_vec();
511 let size = u32::from_le_bytes(end[12..16].try_into().unwrap());
512 end[12..16].copy_from_slice(&(size + comment_len as u32).to_le_bytes());
513 end[20..22].copy_from_slice(&(archive_comment_len as u16).to_le_bytes());
514 input.extend(end);
515 input.extend(vec![0; archive_comment_len]);
516 let s = Scratch::new();
517 fs::write(s.0.join("damaged.zip"), &input).unwrap();
518 let events = execute(start(&s));
519 let t = terminal(&events);
520 assert_eq!(t.error, ErrorCode::None);
521 assert_eq!(t.outcome, Outcome::Completed);
522 assert_eq!(t.publication, Publication::Complete);
523 assert_eq!(t.created_count, 1);
524 let end = recovery_end(&events);
525 assert!(end.complete());
526 assert_eq!(end.verified_entries, 6);
527 assert_eq!(end.source_sha256, <[u8; 32]>::from(Sha256::digest(&input)));
528 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), input);
529 assert!(
530 Command::new("python3")
531 .arg("-B")
532 .arg(
533 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
534 .join("../../tests/zip-recovery-fixtures/verify.py")
535 )
536 .args(["--recovered", "broken-local-header.zip"])
537 .arg(s.0.join("recovered.zip"))
538 .status()
539 .unwrap()
540 .success()
541 );
542 }
543 }
544}
545
546#[test]
547fn fake_eocd_in_archive_comment_keeps_real_central_directory() {
548 let source = include_bytes!("../zip-recovery-fixtures/broken-local-header.zip");
549 for fake_kind in 0..7 {
550 for locator in [false, true] {
551 let mut comment = Vec::new();
552 if locator {
553 comment.extend(b"PK\x06\x07");
554 comment.extend([0; 16]);
555 }
556 let mut fake = [0u8; 22];
557 fake[..4].copy_from_slice(b"PK\x05\x06");
558 match fake_kind {
559 0 => fake[4..6].copy_from_slice(&1u16.to_le_bytes()),
560 1 => fake[10..12].copy_from_slice(&u16::MAX.to_le_bytes()),
561 2 => fake[16..20].copy_from_slice(&u32::MAX.to_le_bytes()),
562 3 => fake[12..16].copy_from_slice(&u32::MAX.to_le_bytes()),
563 4 => {
564 fake[12..16].copy_from_slice(&46u32.to_le_bytes());
565 fake[16..20].copy_from_slice(&39u32.to_le_bytes());
566 }
567 5 => {
568 fake[12..16].copy_from_slice(&340u32.to_le_bytes());
569 fake[16..20].copy_from_slice(&1372u32.to_le_bytes());
570 }
571 _ => {
572 fake[4..6].copy_from_slice(&1u16.to_le_bytes());
573 let size = (source.len() + comment.len() - 1372) as u32;
574 fake[12..16].copy_from_slice(&size.to_le_bytes());
575 fake[16..20].copy_from_slice(&1372u32.to_le_bytes());
576 }
577 }
578 comment.extend(fake);
579 let mut input = source.to_vec();
580 let end = input.len() - 22;
581 input[end + 20..end + 22].copy_from_slice(&(comment.len() as u16).to_le_bytes());
582 input.extend(comment);
583 let s = Scratch::new();
584 fs::write(s.0.join("damaged.zip"), &input).unwrap();
585 let events = execute(start(&s));
586 let terminal = terminal(&events);
587 assert_eq!(terminal.error, ErrorCode::None, "{fake_kind}/{locator}");
588 assert_eq!(terminal.outcome, Outcome::Completed);
589 assert_eq!(terminal.publication, Publication::Complete);
590 let summary = recovery_end(&events);
591 assert!(summary.complete());
592 assert_eq!(summary.mode, RecoveryMode::CentralDirectory);
593 assert_eq!(summary.known_entries, Some(6));
594 assert_eq!(
595 summary.source_sha256,
596 <[u8; 32]>::from(Sha256::digest(&input))
597 );
598 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), input);
599 let checked = Command::new("python3")
600 .arg("-B")
601 .arg(
602 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
603 .join("../../tests/zip-recovery-fixtures/verify.py"),
604 )
605 .args(["--recovered", "broken-local-header.zip"])
606 .arg(s.0.join("recovered.zip"))
607 .output()
608 .unwrap();
609 assert!(checked.status.success(), "{checked:?}");
610 }
611 }
612}
613
614#[test]
615fn nested_central_directories_in_comments_cannot_hide_original_members() {
616 let source = include_bytes!("../zip-recovery-fixtures/broken-local-header.zip");
617 for entries in [1usize, 3, 6] {
618 let mut stop = 1372;
619 for _ in 0..entries {
620 stop += 46
621 + u16::from_le_bytes(source[stop + 28..stop + 30].try_into().unwrap()) as usize
622 + u16::from_le_bytes(source[stop + 30..stop + 32].try_into().unwrap()) as usize
623 + u16::from_le_bytes(source[stop + 32..stop + 34].try_into().unwrap()) as usize;
624 }
625 for depth in [1, 3] {
626 for locator in [false, true] {
627 for maximum_comment in [false, true] {
628 let mut input = source.to_vec();
629 let mut ends = vec![source.len() - 22];
630 for _ in 0..depth {
631 let cd = input.len();
632 input.extend(&source[1372..stop]);
633 if locator {
634 input.extend(b"PK\x06\x07");
635 input.extend([0; 16]);
636 }
637 let mut end = source[source.len() - 22..].to_vec();
638 end[8..10].copy_from_slice(&(entries as u16).to_le_bytes());
639 end[10..12].copy_from_slice(&(entries as u16).to_le_bytes());
640 end[12..16].copy_from_slice(&((stop - 1372) as u32).to_le_bytes());
641 end[16..20].copy_from_slice(&(cd as u32).to_le_bytes());
642 ends.push(input.len());
643 input.extend(end);
644 }
645 if maximum_comment {
646 input.resize(source.len() + u16::MAX as usize, 0);
647 }
648 let len = input.len();
649 for end in ends {
650 input[end + 20..end + 22]
651 .copy_from_slice(&((len - end - 22) as u16).to_le_bytes());
652 }
653 assert_full_comment_recovery(
654 &input,
655 &format!("{entries}/{depth}/{locator}/{maximum_comment}"),
656 );
657 }
658 }
659 }
660 }
661}
662
663fn assert_full_comment_recovery(input: &[u8], case: &str) {
664 let s = Scratch::new();
665 fs::write(s.0.join("damaged.zip"), input).unwrap();
666 let events = execute(start(&s));
667 let terminal = terminal(&events);
668 assert_eq!(terminal.error, ErrorCode::None, "{case}");
669 assert_eq!(terminal.outcome, Outcome::Completed);
670 assert_eq!(terminal.publication, Publication::Complete);
671 assert_eq!(terminal.created_count, 1);
672 let summary = recovery_end(&events);
673 assert!(summary.complete());
674 assert_eq!(summary.mode, RecoveryMode::CentralDirectory);
675 assert_eq!(summary.known_entries, Some(6));
676 assert_eq!(summary.verified_entries, 6);
677 assert_eq!(
678 summary.source_sha256,
679 <[u8; 32]>::from(Sha256::digest(input))
680 );
681 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), input);
682 let checked = Command::new("python3")
683 .arg("-B")
684 .arg(
685 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
686 .join("../../tests/zip-recovery-fixtures/verify.py"),
687 )
688 .args(["--recovered", "broken-local-header.zip"])
689 .arg(s.0.join("recovered.zip"))
690 .output()
691 .unwrap();
692 assert!(checked.status.success(), "{case}: {checked:?}");
693}
694
695#[test]
696fn nested_directory_in_central_entry_comment_is_not_an_outer_archive() {
697 let source = include_bytes!("../zip-recovery-fixtures/broken-local-header.zip");
698 for wraps_real_end in [false, true] {
699 let mut fake_cd = source[1372..1427].to_vec();
700 if wraps_real_end {
701 fake_cd[32..34].copy_from_slice(&22u16.to_le_bytes());
702 }
703 let mut input = source[..source.len() - 22].to_vec();
704 let last = input.windows(4).rposition(|w| w == b"PK\x01\x02").unwrap();
705 let comment_len = fake_cd.len() + if wraps_real_end { 0 } else { 22 };
706 input[last + 32..last + 34].copy_from_slice(&(comment_len as u16).to_le_bytes());
707 let fake_offset = input.len();
708 input.extend(&fake_cd);
709 let mut real_end = source[source.len() - 22..].to_vec();
710 real_end[12..16].copy_from_slice(&((340 + comment_len) as u32).to_le_bytes());
711 let mut fake_end = source[source.len() - 22..].to_vec();
712 fake_end[8..10].copy_from_slice(&1u16.to_le_bytes());
713 fake_end[10..12].copy_from_slice(&1u16.to_le_bytes());
714 fake_end[12..16].copy_from_slice(
715 &((fake_cd.len() + if wraps_real_end { 22 } else { 0 }) as u32).to_le_bytes(),
716 );
717 fake_end[16..20].copy_from_slice(&(fake_offset as u32).to_le_bytes());
718 if wraps_real_end {
719 real_end[20..22].copy_from_slice(&22u16.to_le_bytes());
720 input.extend(real_end);
721 input.extend(fake_end);
722 } else {
723 fake_end[20..22].copy_from_slice(&22u16.to_le_bytes());
724 input.extend(fake_end);
725 input.extend(real_end);
726 }
727 assert_full_comment_recovery(&input, &format!("central-comment/{wraps_real_end}"));
728 }
729}
730
731#[test]
732fn fake_directory_and_eocd_in_member_payload_cannot_hide_members() {
733 assert_payload_recovery_cases((0..32).chain([32]));
734}
735
736#[test]
737fn local_size_damage_and_payload_eocd_preserve_complete_inventory() {
738 let cases = (1..=5)
739 .flat_map(|size_mode| (0..32).map(move |base| (size_mode << 6) | base))
740 .chain([
741 32 | (3 << 6),
742 512 | (3 << 6),
743 512 | (3 << 6) | 4,
744 1024 | (3 << 6),
745 2048 | (3 << 6),
746 2048 | (3 << 6) | 4,
747 2048 | 512 | (3 << 6),
748 2048 | 1024 | (3 << 6),
749 ]);
750 assert_payload_recovery_cases(cases);
751}
752
753fn assert_payload_recovery_cases(cases: impl IntoIterator<Item = u32>) {
754 let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
755 .join("../../tests/rust-archive-worker/payload_eocd.py");
756 for variant in cases {
757 let s = Scratch::new();
758 let generated = Command::new("python3")
759 .arg("-B")
760 .arg(&helper)
761 .arg("create")
762 .arg(&s.0)
763 .arg(variant.to_string())
764 .output()
765 .unwrap();
766 assert!(generated.status.success(), "{generated:?}");
767 let input = fs::read(s.0.join("damaged.zip")).unwrap();
768 let events = execute(start(&s));
769 let terminal = terminal(&events);
770 assert_eq!(terminal.error, ErrorCode::None, "variant {variant}");
771 assert_eq!(terminal.outcome, Outcome::Completed);
772 assert_eq!(terminal.publication, Publication::Complete);
773 assert_eq!(terminal.created_count, 1);
774 let summary = recovery_end(&events);
775 assert!(summary.complete());
776 assert_eq!(summary.mode, RecoveryMode::CentralDirectory);
777 assert_eq!(summary.known_entries, Some(2));
778 assert_eq!(summary.verified_entries, 2);
779 assert_eq!(
780 summary.source_sha256,
781 <[u8; 32]>::from(Sha256::digest(&input))
782 );
783 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), input);
784 let checked = Command::new("python3")
785 .arg("-B")
786 .arg(&helper)
787 .arg("verify")
788 .arg(&s.0)
789 .output()
790 .unwrap();
791 assert!(checked.status.success(), "variant {variant}: {checked:?}");
792 }
793}
794
795#[test]
796fn candidate_body_probes_do_not_bypass_recovery_quotas() {
797 let helper = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
798 .join("../../tests/rust-archive-worker/payload_eocd.py");
799 let output_limit = Limits::default().output;
800 for (variant, entries, output) in [
801 (192, 1, output_limit),
802 (1216, 1, output_limit),
803 (1216, 10000, 12),
804 ] {
805 let s = Scratch::new();
806 let generated = Command::new("python3")
807 .arg("-B")
808 .arg(&helper)
809 .arg("create")
810 .arg(&s.0)
811 .arg(variant.to_string())
812 .output()
813 .unwrap();
814 assert!(generated.status.success(), "{generated:?}");
815 let input = fs::read(s.0.join("damaged.zip")).unwrap();
816 let mut request = start(&s);
817 request.limits.entries = entries;
818 request.limits.output = output;
819 let events = execute(request);
820 let terminal = terminal(&events);
821 assert_eq!(
822 terminal.error,
823 ErrorCode::Limit,
824 "{variant}/{entries}/{output}"
825 );
826 assert_eq!(terminal.publication, Publication::None);
827 assert_eq!(terminal.created_count, 0);
828 assert!(!s.0.join("recovered.zip").exists());
829 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), input);
830 }
831}
832
833#[test]
834fn corrupt_local_zip64_directory_sizes_recover_list_and_extract() {
835 let s = Scratch::new();
836 let fixture = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
837 .join("../../tests/rust-archive-worker/local_zip64_fixture.py");
838 let generated = Command::new("python3")
839 .arg("-B")
840 .arg(&fixture)
841 .arg(s.0.join("damaged.zip"))
842 .output()
843 .unwrap();
844 assert!(generated.status.success(), "{generated:?}");
845 let original = fs::read(s.0.join("damaged.zip")).unwrap();
846 let events = execute(start(&s));
847 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
848 let end = recovery_end(&events);
849 assert_eq!(end.mode, RecoveryMode::CentralDirectory);
850 assert_eq!(end.known_entries, Some(2));
851 assert_eq!(end.verified_entries, 2);
852 assert!(!end.unknown_loss);
853 assert!(events.iter().any(|event| matches!(
854 event,
855 Message::RecoveryEntry(entry)
856 if entry.name.as_deref() == Some("folder")
857 && entry.reason == RecoveryReason::HeaderRebuilt
858 && entry.status == RecoveryStatus::Verified
859 )));
860 assert_eq!(fs::read(s.0.join("damaged.zip")).unwrap(), original);
861 let checked = Command::new("python3")
862 .arg("-B")
863 .arg(&fixture)
864 .arg("--verify")
865 .arg(s.0.join("recovered.zip"))
866 .output()
867 .unwrap();
868 assert!(checked.status.success(), "{checked:?}");
869 let recovered = fs::read(s.0.join("recovered.zip")).unwrap();
870 fs::write(s.0.join("input"), &recovered).unwrap();
871 let id = listing(&s);
872 let extracted = extract(
873 &s,
874 &recovered,
875 None,
876 Selection::All,
877 Some(id),
878 Limits::default(),
879 );
880 assert_eq!(
881 terminal(&extracted).outcome,
882 Outcome::Completed,
883 "{extracted:?}"
884 );
885 assert!(s.0.join("output/folder").is_dir());
886 assert_eq!(
887 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
888 b"Central directory recovery reference\n"
889 );
890}