team-ljyzipelo

공개
608줄18 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(env!("CARGO_MANIFEST_DIR"))
18 .parent()
19 .unwrap()
20 .parent()
21 .unwrap()
22 .join("tests/rust-archive-worker/runs")
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}
44impl Drop for Scratch {
45 fn drop(&mut self) {
46 fs::remove_dir_all(&self.0).unwrap();
47 }
48}
49fn execute(start: Start) -> Vec<Message> {
50 let mut data = Vec::new();
51 Writer::new(&mut data, 17)
52 .send(&Message::Start(start))
53 .unwrap();
54 let mut child = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
55 .stdin(Stdio::piped())
56 .stdout(Stdio::piped())
57 .stderr(Stdio::piped())
58 .spawn()
59 .unwrap();
60 child.stdin.take().unwrap().write_all(&data).unwrap();
61 let output = child.wait_with_output().unwrap();
62 assert!(output.status.success(), "{:?}", output.stderr);
63 assert!(output.stderr.is_empty());
64 let mut reader = Reader::new(output.stdout.as_slice());
65 let mut events = Vec::new();
66 while let Some((job, _, event)) = reader.read().unwrap() {
67 assert_eq!(job, 17);
68 events.push(event);
69 }
70 assert!(matches!(events.last(), Some(Message::Terminal(_))));
71 events
72}
73fn terminal(events: &[Message]) -> &Terminal {
74 match events.last().unwrap() {
75 Message::Terminal(t) => t,
76 _ => panic!("missing terminal"),
77 }
78}
79fn extract(
80 s: &Scratch,
81 bytes: &[u8],
82 gzip: Option<&str>,
83 selection: Selection,
84 list_id: Option<ListId>,
85 limits: Limits,
86) -> Vec<Message> {
87 fs::write(s.0.join("input"), bytes).unwrap();
88 if !s.0.join("output").exists() {
89 let d = fs::DirBuilder::new();
90 #[cfg(unix)]
91 let mut d = d;
92 #[cfg(unix)]
93 {
94 use std::os::unix::fs::DirBuilderExt;
95 d.mode(0o700);
96 }
97 d.create(s.0.join("output")).unwrap();
98 }
99 execute(Start {
100 action: Action::Extract {
101 archive: s.path("input"),
102 destination: s.path("output"),
103 selection,
104 list_id,
105 gzip_output_name: gzip.map(str::to_owned),
106 },
107 limits,
108 })
109}
110const PAYLOAD: &[u8] = b"Zipelo worker interoperability\n";
111fn basic(bytes: &[u8], gzip: Option<&str>, output: &str) {
112 let s = Scratch::new();
113 let events = extract(&s, bytes, gzip, Selection::All, None, Limits::default());
114 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
115 assert_eq!(terminal(&events).publication, Publication::Complete);
116 assert_eq!(fs::read(s.0.join("output").join(output)).unwrap(), PAYLOAD);
117}
118#[test]
119fn stored_zip() {
120 basic(
121 include_bytes!("fixtures/store.zip"),
122 None,
123 "folder/hello.txt",
124 );
125}
126#[test]
127fn deflated_zip() {
128 basic(
129 include_bytes!("fixtures/deflate.zip"),
130 None,
131 "folder/hello.txt",
132 );
133}
134#[test]
135fn tar() {
136 basic(
137 include_bytes!("fixtures/sample.tar"),
138 None,
139 "folder/hello.txt",
140 );
141}
142#[test]
143fn tar_gzip() {
144 basic(
145 include_bytes!("fixtures/sample.tar.gz"),
146 None,
147 "folder/hello.txt",
148 );
149}
150#[test]
151fn gzip_explicit_name_ignores_fname() {
152 basic(
153 include_bytes!("fixtures/sample.gz"),
154 Some("chosen.txt"),
155 "chosen.txt",
156 );
157}
158#[test]
159fn gzip_concatenated_members() {
160 let s = Scratch::new();
161 let events = extract(
162 &s,
163 include_bytes!("fixtures/concat.gz"),
164 Some("combined"),
165 Selection::All,
166 None,
167 Limits::default(),
168 );
169 assert_eq!(terminal(&events).outcome, Outcome::Completed);
170 assert_eq!(fs::read(s.0.join("output/combined")).unwrap(), b"onetwo");
171}
172#[test]
173fn gzip_requires_leaf() {
174 for name in [None, Some("../escape"), Some("a/b")] {
175 let s = Scratch::new();
176 let e = extract(
177 &s,
178 include_bytes!("fixtures/sample.gz"),
179 name,
180 Selection::All,
181 None,
182 Limits::default(),
183 );
184 assert_eq!(terminal(&e).error, ErrorCode::InvalidRequest);
185 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
186 }
187}
188#[test]
189fn archive_rejects_gzip_name() {
190 let s = Scratch::new();
191 let e = extract(
192 &s,
193 include_bytes!("fixtures/store.zip"),
194 Some("a"),
195 Selection::All,
196 None,
197 Limits::default(),
198 );
199 assert_eq!(terminal(&e).error, ErrorCode::InvalidRequest);
200}
201#[test]
202fn no_clobber_and_preflight_no_partial_outputs() {
203 let s = Scratch::new();
204 fs::create_dir(s.0.join("output")).unwrap();
205 #[cfg(unix)]
206 {
207 use std::os::unix::fs::PermissionsExt;
208 fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
209 }
210 fs::create_dir(s.0.join("output/folder")).unwrap();
211 #[cfg(unix)]
212 {
213 use std::os::unix::fs::PermissionsExt;
214 fs::set_permissions(s.0.join("output/folder"), fs::Permissions::from_mode(0o700)).unwrap();
215 }
216 fs::write(s.0.join("output/folder/hello.txt"), b"preserve").unwrap();
217 let e = extract(
218 &s,
219 include_bytes!("fixtures/store.zip"),
220 None,
221 Selection::All,
222 None,
223 Limits::default(),
224 );
225 assert_eq!(terminal(&e).error, ErrorCode::Conflict);
226 assert_eq!(
227 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
228 b"preserve"
229 );
230 assert!(!s.0.join("output/empty").exists());
231}
232#[test]
233fn unsafe_archives_reject_without_writes() {
234 for bytes in [
235 include_bytes!("fixtures/traversal.zip").as_slice(),
236 include_bytes!("fixtures/absolute.zip"),
237 include_bytes!("fixtures/drive.zip"),
238 include_bytes!("fixtures/reserved.zip"),
239 include_bytes!("fixtures/link.zip"),
240 include_bytes!("fixtures/collision.zip"),
241 include_bytes!("fixtures/parent-collision.zip"),
242 ] {
243 let s = Scratch::new();
244 let e = extract(&s, bytes, None, Selection::All, None, Limits::default());
245 assert_eq!(terminal(&e).outcome, Outcome::Failed, "{e:?}");
246 assert_eq!(terminal(&e).created_count, 0);
247 assert_eq!(terminal(&e).publication, Publication::None);
248 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
249 }
250}
251#[test]
252fn bomb_rejects_before_writes() {
253 let s = Scratch::new();
254 let e = extract(
255 &s,
256 include_bytes!("fixtures/bomb.zip"),
257 None,
258 Selection::All,
259 None,
260 Limits {
261 output: 1024,
262 ..Limits::default()
263 },
264 );
265 assert_eq!(terminal(&e).error, ErrorCode::Limit);
266 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
267}
268#[test]
269fn corrupt_crc_and_truncation_reject_without_writes() {
270 let mut zip = include_bytes!("fixtures/store.zip").to_vec();
271 let at = zip
272 .windows(PAYLOAD.len())
273 .position(|b| b == PAYLOAD)
274 .unwrap();
275 zip[at] ^= 1;
276 for bytes in [zip.as_slice(), &include_bytes!("fixtures/store.zip")[..40]] {
277 let s = Scratch::new();
278 let e = extract(&s, bytes, None, Selection::All, None, Limits::default());
279 assert_eq!(terminal(&e).outcome, Outcome::Failed);
280 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
281 }
282}
283fn listing(s: &Scratch) -> ListId {
284 let e = execute(Start {
285 action: Action::List {
286 archive: s.path("input"),
287 },
288 limits: Limits::default(),
289 });
290 assert_eq!(terminal(&e).outcome, Outcome::Completed);
291 e.into_iter()
292 .find_map(|m| {
293 if let Message::ListEnd { list_id, .. } = m {
294 Some(list_id)
295 } else {
296 None
297 }
298 })
299 .unwrap()
300}
301#[test]
302fn list_and_selected_extract() {
303 let s = Scratch::new();
304 let bytes = include_bytes!("fixtures/store.zip");
305 fs::write(s.0.join("input"), bytes).unwrap();
306 let id = listing(&s);
307 let e = extract(
308 &s,
309 bytes,
310 None,
311 Selection::EntryIds(vec![0]),
312 Some(id),
313 Limits::default(),
314 );
315 assert_eq!(terminal(&e).outcome, Outcome::Completed);
316 assert!(!s.0.join("output/empty").exists());
317 assert_eq!(
318 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
319 PAYLOAD
320 );
321}
322#[test]
323fn stale_list_content_rejected() {
324 let s = Scratch::new();
325 fs::write(s.0.join("input"), include_bytes!("fixtures/store.zip")).unwrap();
326 let mut id = listing(&s);
327 id.archive_sha256[0] ^= 1;
328 let e = extract(
329 &s,
330 include_bytes!("fixtures/store.zip"),
331 None,
332 Selection::EntryIds(vec![0]),
333 Some(id),
334 Limits::default(),
335 );
336 assert_eq!(terminal(&e).error, ErrorCode::SourceChanged);
337 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
338}
339#[test]
340fn missing_duplicate_and_out_of_range_selection() {
341 for ids in [vec![], vec![0, 0], vec![999]] {
342 let s = Scratch::new();
343 fs::write(s.0.join("input"), include_bytes!("fixtures/store.zip")).unwrap();
344 let id = listing(&s);
345 let e = extract(
346 &s,
347 include_bytes!("fixtures/store.zip"),
348 None,
349 Selection::EntryIds(ids),
350 Some(id),
351 Limits::default(),
352 );
353 assert_eq!(terminal(&e).error, ErrorCode::InvalidRequest);
354 }
355 let s = Scratch::new();
356 let e = extract(
357 &s,
358 include_bytes!("fixtures/store.zip"),
359 None,
360 Selection::EntryIds(vec![0]),
361 None,
362 Limits::default(),
363 );
364 assert_eq!(terminal(&e).error, ErrorCode::InvalidRequest);
365}
366#[test]
367fn create_store_and_deflate_zip() {
368 for method in [Method::Store, Method::Deflate] {
369 let s = Scratch::new();
370 fs::write(s.0.join("source"), PAYLOAD).unwrap();
371 let e = execute(Start {
372 action: Action::CreateZip {
373 sources: vec![Source {
374 path: s.path("source"),
375 archive_name: "dir/hello.txt".into(),
376 }],
377 output_file: s.path("result.zip"),
378 method,
379 encryption: Encryption::None,
380 },
381 limits: Limits::default(),
382 });
383 assert_eq!(terminal(&e).outcome, Outcome::Completed, "{e:?}");
384 let bytes = fs::read(s.0.join("result.zip")).unwrap();
385 let parsed = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
386 assert_eq!(parsed.members[0].data, PAYLOAD);
387 }
388}
389#[test]
390fn encrypted_creation_is_explicitly_unsupported() {
391 let s = Scratch::new();
392 let e = execute(Start {
393 action: Action::CreateZip {
394 sources: vec![],
395 output_file: s.path("result.zip"),
396 method: Method::Store,
397 encryption: Encryption::Aes256,
398 },
399 limits: Limits::default(),
400 });
401 assert_eq!(terminal(&e).error, ErrorCode::UnsupportedFeature);
402 assert!(!s.0.join("result.zip").exists());
403}
404#[test]
405fn name_policy() {
406 for name in [
407 "../a", "/a", "a\\b", "C:a", "a/../b", "a.", "a ", "COM1.txt", "a//b", "a/./b",
408 ] {
409 assert!(archive::valid_name(name, false).is_err(), "{name}");
410 }
411 assert!(archive::valid_name("folder/한글.txt", false).is_ok());
412}
413#[test]
414fn frame_round_trip_and_secret_redaction() {
415 let mut b = Vec::new();
416 Writer::new(&mut b, 42).send(&Message::Cancel).unwrap();
417 let mut reader = Reader::new(b.as_slice());
418 assert!(matches!(
419 reader.read().unwrap(),
420 Some((42, 0, Message::Cancel))
421 ));
422 assert!(reader.read().unwrap().is_none());
423 assert!(
424 !format!(
425 "{:?}",
426 Message::Password {
427 challenge_id: 1,
428 secret: Secret(b"private-password".to_vec())
429 }
430 )
431 .contains("private-password")
432 );
433}
434#[test]
435fn invalid_headers_are_rejected() {
436 let mut b = Vec::new();
437 Writer::new(&mut b, 42).send(&Message::Cancel).unwrap();
438 for (offset, value) in [(0, 0), (4, 2), (12, 1), (16, 0), (24, 1)] {
439 let mut bad = b.clone();
440 bad[offset] = value;
441 assert!(Reader::new(bad.as_slice()).read().is_err());
442 }
443 let mut big = b.clone();
444 big[8..12].copy_from_slice(&1_048_577u32.to_le_bytes());
445 assert!(Reader::new(big.as_slice()).read().is_err());
446 assert!(Reader::new(&b[..16]).read().is_err());
447}
448#[test]
449fn terminal_is_final_frame() {
450 let t = Terminal {
451 outcome: Outcome::Failed,
452 error: ErrorCode::Io,
453 publication: Publication::Uncertain,
454 created_count: 0,
455 retained_partial_count: 0,
456 durability: Durability::Unconfirmed,
457 cleanup: Cleanup::Unconfirmed,
458 detail: "uncertain".into(),
459 };
460 let mut b = Vec::new();
461 let mut w = Writer::new(&mut b, 1);
462 w.send(&Message::Terminal(t)).unwrap();
463 assert!(w.send(&Message::Cancel).is_err());
464}
465#[cfg(unix)]
466#[test]
467fn symlink_parent_escape_is_rejected() {
468 use std::os::unix::fs::symlink;
469 let s = Scratch::new();
470 let d = fs::DirBuilder::new();
471 #[cfg(unix)]
472 let mut d = d;
473 use std::os::unix::fs::DirBuilderExt;
474 d.mode(0o700);
475 d.create(s.0.join("output")).unwrap();
476 d.create(s.0.join("outside")).unwrap();
477 symlink(s.0.join("outside"), s.0.join("output/folder")).unwrap();
478 let e = extract(
479 &s,
480 include_bytes!("fixtures/store.zip"),
481 None,
482 Selection::All,
483 None,
484 Limits::default(),
485 );
486 assert_eq!(terminal(&e).error, ErrorCode::UnsafePath);
487 assert_eq!(fs::read_dir(s.0.join("outside")).unwrap().count(), 0);
488}
489
490#[test]
491fn changed_source_is_reopen_error_before_decode() {
492 let s = Scratch::new();
493 let bytes = include_bytes!("fixtures/store.zip");
494 fs::write(s.0.join("input"), bytes).unwrap();
495 let id = listing(&s);
496 let mut changed = bytes.to_vec();
497 changed[40] ^= 1;
498 let e = extract(
499 &s,
500 &changed,
501 None,
502 Selection::EntryIds(vec![0]),
503 Some(id),
504 Limits::default(),
505 );
506 assert_eq!(terminal(&e).error, ErrorCode::SourceChanged);
507 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
508}
509#[test]
510fn cancel_ack_and_terminal_are_distinct() {
511 let s = Scratch::new();
512 fs::write(s.0.join("source"), vec![0u8; 16 * 1024 * 1024]).unwrap();
513 let start = Start {
514 action: Action::CreateZip {
515 sources: vec![Source {
516 path: s.path("source"),
517 archive_name: "data".into(),
518 }],
519 output_file: s.path("result.zip"),
520 method: Method::Deflate,
521 encryption: Encryption::None,
522 },
523 limits: Limits::default(),
524 };
525 let mut child = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
526 .stdin(Stdio::piped())
527 .stdout(Stdio::piped())
528 .stderr(Stdio::piped())
529 .spawn()
530 .unwrap();
531 let mut writer = Writer::new(child.stdin.take().unwrap(), 19);
532 let mut reader = Reader::new(child.stdout.take().unwrap());
533 writer.send(&Message::Start(start)).unwrap();
534 assert!(matches!(
535 reader.read().unwrap(),
536 Some((19, 0, Message::Accepted { .. }))
537 ));
538 writer.send(&Message::Cancel).unwrap();
539 writer.send(&Message::Cancel).unwrap();
540 let mut events = Vec::new();
541 while let Some((_, _, m)) = reader.read().unwrap() {
542 events.push(m);
543 }
544 assert!(child.wait().unwrap().success());
545 let terminal = terminal(&events);
546 assert!(matches!(
547 terminal.outcome,
548 Outcome::Cancelled | Outcome::Completed
549 ));
550 for m in &events {
551 if let Message::CancelAck {
552 request_sequence,
553 status,
554 } = m
555 {
556 assert!([1, 2].contains(request_sequence));
557 assert!(matches!(
558 status,
559 CancelStatus::Requested
560 | CancelStatus::AlreadyRequested
561 | CancelStatus::TooLate
562 | CancelStatus::Finished
563 ));
564 }
565 }
566 assert!(
567 events
568 .iter()
569 .any(|m| matches!(m, Message::CancelAck { .. })),
570 "cancel must be consumed during bounded source read: {events:?}"
571 );
572}
573
574#[test]
575fn encrypted_zip_rejects_without_outputs() {
576 let mut bytes = include_bytes!("fixtures/store.zip").to_vec();
577 bytes[6] |= 1;
578 let central = bytes.windows(4).position(|b| b == b"PK\x01\x02").unwrap();
579 bytes[central + 8] |= 1;
580 let s = Scratch::new();
581 let e = extract(&s, &bytes, None, Selection::All, None, Limits::default());
582 assert_eq!(terminal(&e).error, ErrorCode::UnsupportedFeature);
583 assert_eq!(terminal(&e).publication, Publication::None);
584 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
585}
586#[test]
587fn uncertain_report_survives_codec() {
588 let t = Terminal {
589 outcome: Outcome::Failed,
590 error: ErrorCode::Io,
591 publication: Publication::Uncertain,
592 created_count: 2,
593 retained_partial_count: 1,
594 durability: Durability::Failed,
595 cleanup: Cleanup::Failed,
596 detail: "publication uncertain".into(),
597 };
598 let mut bytes = Vec::new();
599 Writer::new(&mut bytes, 88)
600 .send(&Message::Terminal(t.clone()))
601 .unwrap();
602 let mut reader = Reader::new(bytes.as_slice());
603 match reader.read().unwrap() {
604 Some((88, 0, Message::Terminal(actual))) => assert_eq!(actual, t),
605 other => panic!("{other:?}"),
606 };
607 assert!(reader.read().unwrap().is_none());
608}