team-ljyzipelo

공개
952줄31 KB
1use super::*;
2use std::{io::Read, process::Child, sync::mpsc, time::Duration};
3
4struct Running(Child);
5impl Drop for Running {
6 fn drop(&mut self) {
7 let _ = self.0.kill();
8 let _ = self.0.wait();
9 }
10}
11pub(super) fn run(
12 s: &Scratch,
13 start: GuardedStart,
14 respond: impl FnMut(&Message) -> Option<Vec<Message>>,
15) -> Vec<Message> {
16 run_fault(s, start, None, respond)
17}
18fn run_fault(
19 s: &Scratch,
20 start: GuardedStart,
21 fault: Option<&str>,
22 respond: impl FnMut(&Message) -> Option<Vec<Message>>,
23) -> Vec<Message> {
24 run_record(s, start, fault, true, respond)
25}
26fn run_record(
27 s: &Scratch,
28 start: GuardedStart,
29 fault: Option<&str>,
30 record_entries: bool,
31 mut respond: impl FnMut(&Message) -> Option<Vec<Message>>,
32) -> Vec<Message> {
33 let mut command = s.worker();
34 #[cfg(target_os = "linux")]
35 if let Some(fault) = fault {
36 let shim = s.0.join("io_fault.so");
37 assert!(
38 Command::new("cc")
39 .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
40 .arg(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(
41 if fault.starts_with("phase-") {
42 "../../tests/rust-archive-worker/phase_clock.c"
43 } else if fault.starts_with("clock-") {
44 "../../tests/rust-archive-worker/progress_clock.c"
45 } else {
46 "../../tests/rust-archive-worker/io_fault.c"
47 }
48 ))
49 .args(["-ldl", "-o"])
50 .arg(&shim)
51 .status()
52 .unwrap()
53 .success()
54 );
55 command
56 .env("LD_PRELOAD", shim)
57 .env("ZIPELO_TEST_FAULT", fault)
58 .env("ZIPELO_TEST_MARKER", s.0.join("marker"));
59 }
60 #[cfg(not(target_os = "linux"))]
61 assert!(fault.is_none());
62 let mut child = Running(
63 command
64 .stdin(Stdio::piped())
65 .stdout(Stdio::piped())
66 .stderr(Stdio::piped())
67 .spawn()
68 .unwrap(),
69 );
70 let mut writer = Some(Writer::new(child.0.stdin.take().unwrap(), 17));
71 writer
72 .as_mut()
73 .unwrap()
74 .send(&Message::StartGuarded(start))
75 .unwrap();
76 let stdout = child.0.stdout.take().unwrap();
77 let mut stderr = child.0.stderr.take().unwrap();
78 let (send, receive) = mpsc::sync_channel(128);
79 let reader = std::thread::spawn(move || {
80 let mut reader = Reader::new(stdout);
81 loop {
82 let frame = reader.read();
83 let done = !matches!(frame, Ok(Some(_)));
84 if send.send(frame).is_err() || done {
85 break;
86 }
87 }
88 });
89 let mut events = Vec::new();
90 loop {
91 let Some((job, _, event)) = receive
92 .recv_timeout(Duration::from_secs(20))
93 .expect("worker timeout")
94 .unwrap()
95 else {
96 break;
97 };
98 assert_eq!(job, 17);
99 if let Some(messages) = respond(&event) {
100 if messages.is_empty() {
101 writer = None;
102 } else {
103 for message in messages {
104 writer.as_mut().unwrap().send(&message).unwrap();
105 }
106 }
107 }
108 let done = matches!(event, Message::Terminal(_));
109 if record_entries || !matches!(event, Message::Entry(_)) {
110 events.push(event);
111 }
112 if done {
113 writer = None;
114 }
115 }
116 assert!(child.0.wait().unwrap().success(), "{events:?}");
117 let mut errors = Vec::new();
118 stderr.read_to_end(&mut errors).unwrap();
119 assert!(errors.is_empty(), "{errors:?}");
120 reader.join().unwrap();
121 assert!(matches!(events.last(), Some(Message::Terminal(_))));
122 events
123}
124fn request(s: &Scratch, output: u64, ceiling: u64) -> GuardedStart {
125 GuardedStart {
126 start: Start {
127 action: Action::Extract {
128 archive: s.path("input"),
129 destination: s.path("output"),
130 selection: Selection::All,
131 list_id: None,
132 gzip_output_name: None,
133 },
134 limits: Limits {
135 output,
136 ..Limits::default()
137 },
138 },
139 ceiling: Limits {
140 output: ceiling,
141 entries: 200_000,
142 ..Limits::default()
143 },
144 interactive: false,
145 }
146}
147fn setup() -> Scratch {
148 let s = Scratch::new();
149 fs::write(s.0.join("input"), include_bytes!("fixtures/deflate.zip")).unwrap();
150 fs::create_dir(s.0.join("output")).unwrap();
151 #[cfg(unix)]
152 {
153 use std::os::unix::fs::PermissionsExt;
154 fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
155 }
156 s
157}
158fn approve(event: &Message) -> Option<Vec<Message>> {
159 if let Message::ResourceRequired {
160 challenge_id,
161 scope,
162 ..
163 } = event
164 {
165 Some(vec![Message::ResourceReply {
166 challenge_id: *challenge_id,
167 scope: *scope,
168 allow: true,
169 }])
170 } else {
171 None
172 }
173}
174#[test]
175fn scaled_output_boundaries_and_approval() {
176 for limit in [
177 PAYLOAD.len() as u64 + 1,
178 PAYLOAD.len() as u64,
179 PAYLOAD.len() as u64 - 1,
180 ] {
181 let s = setup();
182 let events = run(&s, request(&s, limit, 64), approve);
183 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
184 assert_eq!(
185 events
186 .iter()
187 .filter(|e| matches!(e, Message::ResourceRequired { .. }))
188 .count(),
189 1
190 );
191 assert_eq!(
192 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
193 PAYLOAD
194 );
195 }
196}
197#[test]
198fn decline_cancel_and_eof_publish_nothing() {
199 for mode in 0..3 {
200 let s = setup();
201 let events = run(&s, request(&s, 16, 64), |event| {
202 if let Message::ResourceRequired {
203 challenge_id,
204 scope,
205 usage,
206 ..
207 } = event
208 {
209 assert_eq!(usage.estimated_bytes, None);
210 assert_eq!(usage.actual_bytes, None);
211 assert!(usage.available_bytes.is_some());
212 Some(match mode {
213 0 => vec![Message::ResourceReply {
214 challenge_id: *challenge_id,
215 scope: *scope,
216 allow: false,
217 }],
218 1 => vec![Message::Cancel],
219 _ => vec![],
220 })
221 } else {
222 None
223 }
224 });
225 assert_eq!(
226 terminal(&events).outcome,
227 if mode == 2 {
228 Outcome::Failed
229 } else {
230 Outcome::Cancelled
231 },
232 "{events:?}"
233 );
234 assert_eq!(terminal(&events).publication, Publication::None);
235 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
236 if mode == 1 {
237 assert!(events.iter().any(|e| matches!(
238 e,
239 Message::CancelAck {
240 status: CancelStatus::Requested,
241 ..
242 }
243 )));
244 }
245 }
246}
247#[test]
248fn stale_duplicate_wrong_scope_and_premature_replies_are_rejected() {
249 for mode in 0..4 {
250 let s = setup();
251 let events = run(&s, request(&s, 16, 64), |event| {
252 if mode == 3 && matches!(event, Message::Accepted { .. }) {
253 return Some(vec![Message::ResourceReply {
254 challenge_id: 99,
255 scope: ResourceScope::default(),
256 allow: true,
257 }]);
258 }
259 if let Message::ResourceRequired {
260 challenge_id,
261 scope,
262 ..
263 } = event
264 {
265 let reply = |id, scope| Message::ResourceReply {
266 challenge_id: id,
267 scope,
268 allow: true,
269 };
270 Some(match mode {
271 0 => vec![reply(challenge_id + 1, *scope)],
272 1 => vec![reply(*challenge_id, ResourceScope::default())],
273 2 => vec![reply(*challenge_id, *scope), reply(*challenge_id, *scope)],
274 _ => vec![],
275 })
276 } else {
277 None
278 }
279 });
280 assert_eq!(
281 terminal(&events).error,
282 ErrorCode::Protocol,
283 "{mode}: {events:?}"
284 );
285 assert_eq!(terminal(&events).publication, Publication::None);
286 }
287}
288#[test]
289fn ceiling_bytes_and_entries_cannot_be_approved_away() {
290 for entries in [false, true] {
291 let s = setup();
292 let mut start = request(&s, 1, 16);
293 if entries {
294 start.start.limits.output = 64;
295 start.ceiling.output = 64;
296 start.start.limits.entries = 1;
297 start.ceiling.entries = 2;
298 let members = (0..3)
299 .map(|id| archive::Member {
300 entry: Entry {
301 entry_id: id,
302 name: format!("empty{id}"),
303 kind: EntryKind::File,
304 size: 0,
305 compressed_size: 0,
306 encrypted: false,
307 },
308 data: Vec::new(),
309 })
310 .collect::<Vec<_>>();
311 let zip =
312 archive::create_zip(&members, Method::Store, Limits::default(), &mut || Ok(()))
313 .unwrap();
314 fs::write(s.0.join("input"), zip).unwrap();
315 }
316 let mut approved = false;
317 let events = run(&s, start, |event| {
318 if matches!(event, Message::ResourceRequired { .. }) {
319 approved = true;
320 }
321 approve(event)
322 });
323 assert!(approved);
324 assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}");
325 assert_eq!(terminal(&events).created_count, 0);
326 }
327}
328#[test]
329fn entries_have_a_separate_approval() {
330 let s = setup();
331 let mut start = request(&s, 64, 64);
332 start.start.limits.entries = 1;
333 start.ceiling.entries = 3;
334 let events = run(&s, start, |event| {
335 if let Message::ResourceRequired { scope, .. } = event {
336 assert!(scope.entries);
337 assert!(!scope.output);
338 }
339 approve(event)
340 });
341 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
342}
343#[test]
344fn resource_then_password_then_conflict_use_distinct_questions() {
345 let s = setup();
346 fs::write(
347 s.0.join("input"),
348 include_bytes!("fixtures/aes2-deflate.zip"),
349 )
350 .unwrap();
351 fs::create_dir_all(s.0.join("output/folder")).unwrap();
352 fs::write(s.0.join("output/payload.bin"), b"old").unwrap();
353 let mut start = request(&s, 16, 8192);
354 start.interactive = true;
355 let mut ids = Vec::new();
356 let events = run(&s, start, |event| match event {
357 Message::ResourceRequired { challenge_id, .. } => {
358 ids.push(*challenge_id);
359 approve(event)
360 }
361 Message::PasswordRequired { challenge_id, .. } => {
362 ids.push(*challenge_id);
363 Some(vec![Message::Password {
364 challenge_id: *challenge_id,
365 secret: Secret(TEST_PASSWORD.to_vec()),
366 }])
367 }
368 Message::ConflictRequired { challenge_id, .. } => {
369 ids.push(*challenge_id);
370 Some(vec![Message::ConflictReply {
371 challenge_id: *challenge_id,
372 choice: ConflictChoice::Overwrite,
373 apply_to_remaining: false,
374 }])
375 }
376 _ => None,
377 });
378 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
379 assert!(ids.len() >= 3, "{events:?}");
380 assert!(ids.windows(2).all(|w| w[0] < w[1]));
381}
382#[test]
383fn create_source_total_is_approved_before_password() {
384 let s = setup();
385 fs::write(s.0.join("source"), b"12345678").unwrap();
386 let mut start = request(&s, 7, 8);
387 start.start.action = Action::CreateZip {
388 sources: vec![Source {
389 path: s.path("source"),
390 archive_name: "source".into(),
391 }],
392 output_file: s.path("new.zip"),
393 method: Method::Store,
394 encryption: Encryption::Aes256,
395 };
396 let mut approved = false;
397 let events = run(&s, start, |event| match event {
398 Message::ResourceRequired { action, .. } => {
399 assert_eq!(*action, ActionKind::CreateZip);
400 approved = true;
401 approve(event)
402 }
403 Message::PasswordRequired { challenge_id, .. } => {
404 assert!(approved);
405 Some(vec![Message::Password {
406 challenge_id: *challenge_id,
407 secret: Secret(b"secret".to_vec()),
408 }])
409 }
410 _ => None,
411 });
412 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
413 assert!(s.0.join("new.zip").exists());
414}
415#[test]
416fn guarded_wire_round_trip_and_invalid_ceiling() {
417 let s = setup();
418 let start = request(&s, 16, 64);
419 let mut bytes = Vec::new();
420 Writer::new(&mut bytes, 17)
421 .send(&Message::StartGuarded(start.clone()))
422 .unwrap();
423 assert_eq!(&bytes[6..8], &6u16.to_le_bytes());
424 match Reader::new(bytes.as_slice()).read().unwrap().unwrap().2 {
425 Message::StartGuarded(decoded) => assert_eq!(decoded, start),
426 other => panic!("{other:?}"),
427 }
428 let mut invalid = start;
429 invalid.ceiling.output = 64 * 1024 * 1024 * 1024 + 1;
430 assert!(!invalid.valid());
431 assert!(
432 Writer::new(Vec::new(), 17)
433 .send(&Message::StartGuarded(invalid))
434 .is_err()
435 );
436 let mut reply = Vec::new();
437 Writer::new(&mut reply, 17)
438 .send(&Message::ResourceReply {
439 challenge_id: 4,
440 scope: ResourceScope {
441 ratio: true,
442 ..ResourceScope::default()
443 },
444 allow: true,
445 })
446 .unwrap();
447 assert_eq!(&reply[6..8], &7u16.to_le_bytes());
448 reply[43] = 2;
449 assert!(Reader::new(reply.as_slice()).read().is_err());
450}
451
452fn generate(s: &Scratch, case: &str) {
453 let result = Command::new("python3")
454 .arg(
455 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
456 .join("../../tests/rust-archive-worker/guarded_cases.py"),
457 )
458 .arg(&s.0)
459 .arg(case)
460 .output()
461 .unwrap();
462 assert!(
463 result.status.success(),
464 "{}",
465 String::from_utf8_lossy(&result.stderr)
466 );
467}
468#[test]
469fn compressed_formats_keep_limits_after_permission() {
470 for kind in ["gz", "tar", "targz", "bz2", "xz", "7z"] {
471 let s = setup();
472 match kind {
473 "gz" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.gz")).unwrap(),
474 "tar" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar")).unwrap(),
475 "targz" => {
476 fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar.gz")).unwrap()
477 }
478 "bz2" | "xz" => generate(&s, kind),
479 "7z" => fs::write(
480 s.0.join("input"),
481 fs::read(
482 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
483 .join("../../tests/rust-archive-worker/fixtures/7z/copy.7z"),
484 )
485 .unwrap(),
486 )
487 .unwrap(),
488 _ => unreachable!(),
489 }
490 let mut start = request(&s, 16, 65536);
491 if kind == "gz" {
492 if let Action::Extract {
493 gzip_output_name, ..
494 } = &mut start.start.action
495 {
496 *gzip_output_name = Some("payload".into());
497 }
498 }
499 let events = run(&s, start, approve);
500 assert_eq!(
501 terminal(&events).outcome,
502 Outcome::Completed,
503 "{kind}: {events:?}"
504 );
505 }
506}
507#[test]
508fn small_high_ratio_stream_requires_another_scope_and_cancels_promptly() {
509 let s = setup();
510 generate(&s, "bomb");
511 assert!(fs::metadata(s.0.join("input")).unwrap().len() < 1024 * 1024);
512 let mut start = request(&s, 16 * 1024 * 1024 * 1024, 64 * 1024 * 1024 * 1024);
513 if let Action::Extract {
514 gzip_output_name, ..
515 } = &mut start.start.action
516 {
517 *gzip_output_name = Some("payload".into());
518 }
519 let mut ratio = false;
520 let mut cancelled = None;
521 let events = run(&s, start, |event| {
522 if let Message::ResourceRequired { scope, usage, .. } = event {
523 if scope.ratio {
524 ratio = true;
525 assert!(!scope.output && !scope.entries);
526 assert!(usage.actual_bytes.unwrap() >= 256 * 1024 * 1024);
527 assert!(usage.compressed_bytes.unwrap() < 1024 * 1024);
528 cancelled = Some(std::time::Instant::now());
529 return Some(vec![Message::Cancel]);
530 }
531 }
532 if matches!(event, Message::CancelAck { .. }) {
533 assert!(cancelled.unwrap().elapsed() < Duration::from_secs(2));
534 }
535 approve(event)
536 });
537 assert!(ratio);
538 assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}");
539 assert_eq!(terminal(&events).created_count, 0);
540 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
541}
542
543#[cfg(target_os = "linux")]
544#[test]
545fn disk_space_and_write_failures_remain_enforced_after_permission() {
546 for fault in ["space-destination", "codec-full", "full"] {
547 let s = setup();
548 let mut permitted = false;
549 let events = run_fault(&s, request(&s, 16, 64), Some(fault), |event| {
550 if matches!(event, Message::ResourceRequired { .. }) {
551 permitted = true;
552 }
553 approve(event)
554 });
555 assert!(permitted);
556 assert_eq!(
557 terminal(&events).error,
558 ErrorCode::DiskFull,
559 "{fault}: {events:?}"
560 );
561 assert_eq!(terminal(&events).cleanup, Cleanup::Complete, "{events:?}");
562 assert!(!s.0.join("output/folder/hello.txt").exists());
563 assert!(!fs::read_dir(s.0.join("output")).unwrap().any(|e| {
564 e.unwrap()
565 .file_name()
566 .to_string_lossy()
567 .starts_with(".zipelo-")
568 }));
569 }
570}
571
572#[test]
573fn split_zip_ratio_requires_permission_before_decoding() {
574 let s = setup();
575 generate(&s, "split-zip");
576 assert!(fs::metadata(s.0.join("input")).unwrap().len() < 300_000);
577 let mut start = request(&s, Limits::default().output, Limits::default().output);
578 start.ceiling.entries = Limits::default().entries;
579 for mode in 0..3 {
580 let outcome = if mode == 2 {
581 Outcome::Completed
582 } else {
583 Outcome::Cancelled
584 };
585 let mut asked = false;
586 let events = run(&s, start.clone(), |event| {
587 if let Message::ResourceRequired {
588 challenge_id,
589 scope,
590 usage,
591 ..
592 } = event
593 {
594 assert!(!asked);
595 asked = true;
596 assert_eq!(
597 *scope,
598 ResourceScope {
599 ratio: true,
600 ..ResourceScope::default()
601 }
602 );
603 assert_eq!(usage.estimated_bytes, Some(258 * 1024 * 1024));
604 assert_eq!(usage.ratio_output_bytes, usage.estimated_bytes);
605 assert_eq!(usage.actual_bytes, None);
606 assert!(usage.compressed_bytes.unwrap() < 300_000);
607 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
608 if mode == 0 {
609 return Some(vec![Message::Cancel]);
610 }
611 return Some(vec![Message::ResourceReply {
612 challenge_id: *challenge_id,
613 scope: *scope,
614 allow: outcome == Outcome::Completed,
615 }]);
616 }
617 None
618 });
619 assert!(asked);
620 assert_eq!(terminal(&events).outcome, outcome, "{events:?}");
621 assert_eq!(
622 terminal(&events).created_count,
623 if outcome == Outcome::Completed { 2 } else { 0 }
624 );
625 }
626 for name in ["first.bin", "second.bin"] {
627 let mut file = fs::File::open(s.0.join("output").join(name)).unwrap();
628 assert_eq!(file.metadata().unwrap().len(), 129 * 1024 * 1024);
629 let mut block = [0; 65536];
630 loop {
631 let n = file.read(&mut block).unwrap();
632 if n == 0 {
633 break;
634 }
635 assert!(block[..n].iter().all(|b| *b == 0));
636 }
637 }
638}
639
640#[cfg(target_os = "linux")]
641fn progress_archive(s: &Scratch, kind: EntryKind, size: u64) {
642 if kind == EntryKind::Directory {
643 generate(s, "empty-directories");
644 return;
645 }
646 let members = (0..36)
647 .map(|entry_id| archive::Member {
648 entry: Entry {
649 entry_id,
650 name: format!("entry-{entry_id}"),
651 kind,
652 size,
653 compressed_size: size,
654 encrypted: false,
655 },
656 data: vec![0; size as usize],
657 })
658 .collect::<Vec<_>>();
659 let zip =
660 archive::create_zip(&members, Method::Store, Limits::default(), &mut || Ok(())).unwrap();
661 fs::write(s.0.join("input"), zip).unwrap();
662}
663
664#[cfg(target_os = "linux")]
665#[test]
666fn completed_empty_files_and_directories_refresh_idle_deadline() {
667 for (kind, size) in [
668 (EntryKind::File, 0),
669 (EntryKind::File, 1),
670 (EntryKind::Directory, 0),
671 ] {
672 let s = setup();
673 progress_archive(&s, kind, size);
674 let events = run_fault(&s, request(&s, 64, 128), Some("clock-progress"), approve);
675 assert_eq!(
676 terminal(&events).outcome,
677 Outcome::Completed,
678 "{kind:?}: {events:?}"
679 );
680 assert_eq!(terminal(&events).created_count, 36);
681 assert_eq!(terminal(&events).durability, Durability::Synced);
682 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 36);
683 }
684}
685
686#[cfg(target_os = "linux")]
687#[test]
688fn publication_still_stops_after_sixty_seconds_without_progress() {
689 let s = setup();
690 progress_archive(&s, EntryKind::File, 0);
691 let events = run_fault(&s, request(&s, 64, 128), Some("clock-stall"), approve);
692 assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
693 assert_eq!(terminal(&events).error, ErrorCode::Limit);
694 assert_eq!(terminal(&events).created_count, 0);
695 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
696}
697
698#[test]
699fn approved_list_reaches_two_hundred_thousand_short_entries() {
700 let s = setup();
701 generate(&s, "many-entries");
702 let mut start = request(&s, Limits::default().output, Limits::default().output);
703 start.start.action = Action::List {
704 archive: s.path("input"),
705 };
706 start.ceiling.entries = start.start.limits.entries;
707 let events = run(&s, start.clone(), |_| None);
708 assert_eq!(terminal(&events).error, ErrorCode::Limit);
709 assert!(
710 !events
711 .iter()
712 .any(|e| matches!(e, Message::ResourceRequired { .. }))
713 );
714 start.ceiling.entries = 200_000;
715 let mut count = 0;
716 // 대량 목록을 시험 부모에 모아 이후 자식의 RSS 측정을 오염시키지 않음.
717 let events = run_record(&s, start, None, false, |event| {
718 if let Message::Entry(entry) = event {
719 assert_eq!(entry.entry_id, count);
720 assert_eq!(entry.name, format!("e{count}"));
721 count += 1;
722 }
723 approve(event)
724 });
725 assert_eq!(
726 terminal(&events).outcome,
727 Outcome::Completed,
728 "{:?}",
729 terminal(&events)
730 );
731 assert_eq!(count, 200_000);
732 assert!(events.iter().any(|event| matches!(
733 event,
734 Message::ListEnd {
735 entry_count: 200_000,
736 ..
737 }
738 )));
739 assert_eq!(terminal(&events).created_count, 0);
740}
741
742#[test]
743fn metadata_growth_requires_a_grant_even_below_entry_and_output_caps() {
744 let s = setup();
745 generate(&s, "wide-names");
746 let mut start = request(&s, 1, 1);
747 start.start.action = Action::List {
748 archive: s.path("input"),
749 };
750 start.ceiling.entries = start.start.limits.entries;
751 let events = run(&s, start.clone(), |_| None);
752 assert_eq!(terminal(&events).error, ErrorCode::Limit);
753 assert!(
754 !events
755 .iter()
756 .any(|e| matches!(e, Message::ResourceRequired { .. } | Message::Entry(_)))
757 );
758 start.ceiling.output = 2;
759 let events = run(&s, start, approve);
760 assert_eq!(
761 terminal(&events).outcome,
762 Outcome::Completed,
763 "{:?}",
764 terminal(&events)
765 );
766 assert_eq!(
767 events
768 .iter()
769 .filter(|e| matches!(e, Message::Entry(_)))
770 .count(),
771 9000
772 );
773}
774
775#[cfg(target_os = "linux")]
776fn create_progress_request(
777 s: &Scratch,
778 kind: EntryKind,
779 size: usize,
780 method: Method,
781) -> GuardedStart {
782 fs::create_dir(s.0.join("source")).unwrap();
783 for entry_id in 0..36 {
784 let path = s.0.join(format!("source/entry-{entry_id}"));
785 if kind == EntryKind::Directory {
786 fs::create_dir(path).unwrap();
787 } else {
788 fs::write(path, vec![0; size]).unwrap();
789 }
790 }
791 let mut start = request(s, 64, 128);
792 start.start.action = Action::CreateZip {
793 sources: vec![Source {
794 path: s.path("source"),
795 archive_name: "source".into(),
796 }],
797 output_file: s.path("new.zip"),
798 method,
799 encryption: Encryption::None,
800 };
801 start
802}
803
804#[cfg(target_os = "linux")]
805#[test]
806fn created_empty_files_and_directories_refresh_idle_deadline() {
807 for method in [Method::Store, Method::Deflate] {
808 for (kind, size) in [
809 (EntryKind::Directory, 0),
810 (EntryKind::File, 0),
811 (EntryKind::File, 1),
812 ] {
813 let s = setup();
814 let start = create_progress_request(&s, kind, size, method);
815 let mut approved = false;
816 let events = run_fault(&s, start, Some("clock-create-progress"), |event| {
817 if matches!(event, Message::ResourceRequired { .. }) {
818 approved = true;
819 }
820 approve(event)
821 });
822 assert!(approved);
823 assert_eq!(
824 terminal(&events).outcome,
825 Outcome::Completed,
826 "{method:?} {kind:?} {size}: {events:?}"
827 );
828 assert_eq!(terminal(&events).publication, Publication::Complete);
829 assert_eq!(terminal(&events).created_count, 1);
830 let bytes = fs::read(s.0.join("new.zip")).unwrap();
831 let parsed = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
832 assert_eq!(parsed.members.len(), 37);
833 assert!(parsed.members.iter().any(|member| {
834 member.entry.name == "source" && member.entry.kind == EntryKind::Directory
835 }));
836 for entry_id in 0..36 {
837 let name = format!("source/entry-{entry_id}");
838 let member = parsed
839 .members
840 .iter()
841 .find(|member| member.entry.name == name)
842 .unwrap();
843 assert_eq!(member.entry.kind, kind);
844 assert_eq!(member.data, vec![0; size]);
845 }
846 }
847 }
848}
849
850#[cfg(target_os = "linux")]
851#[test]
852fn zip_creation_still_stops_after_sixty_seconds_without_progress() {
853 let s = setup();
854 let start = create_progress_request(&s, EntryKind::Directory, 0, Method::Store);
855 let events = run_fault(&s, start, Some("clock-create-stall"), approve);
856 assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
857 assert_eq!(terminal(&events).error, ErrorCode::Limit);
858 assert_eq!(terminal(&events).publication, Publication::None);
859 assert_eq!(terminal(&events).created_count, 0);
860 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
861 assert!(!s.0.join("new.zip").exists());
862}
863
864#[cfg(target_os = "linux")]
865#[test]
866fn large_selection_reaches_worker_permission_and_destination_checks() {
867 let s = setup();
868 generate(&s, "selection-entries");
869 let mut start = request(&s, Limits::default().output, Limits::default().output);
870 start.start.action = Action::List {
871 archive: s.path("input"),
872 };
873 let mut count = 0;
874 let mut list_id = None;
875 let events = run_record(&s, start, None, false, |event| {
876 match event {
877 Message::Entry(entry) => {
878 assert_eq!(entry.entry_id, count);
879 count += 1;
880 }
881 Message::ListEnd { list_id: id, .. } => list_id = Some(id.clone()),
882 _ => {}
883 }
884 approve(event)
885 });
886 assert_eq!(terminal(&events).outcome, Outcome::Completed);
887 assert_eq!(count, 32_770);
888 let list_id = list_id.unwrap();
889 for decision in 0..3 {
890 let mut start = request(&s, Limits::default().output, Limits::default().output);
891 if let Action::Extract {
892 selection,
893 list_id: token,
894 ..
895 } = &mut start.start.action
896 {
897 *selection = Selection::EntryIds((0..32_769).collect());
898 *token = Some(list_id.clone());
899 }
900 let mut asked = false;
901 let events = run_fault(&s, start, Some("space-destination"), |event| {
902 if let Message::ResourceRequired {
903 challenge_id,
904 scope,
905 ..
906 } = event
907 {
908 asked = true;
909 assert!(scope.entries && !scope.output && !scope.ratio);
910 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
911 return Some(if decision == 1 {
912 vec![Message::Cancel]
913 } else {
914 vec![Message::ResourceReply {
915 challenge_id: *challenge_id,
916 scope: *scope,
917 allow: decision == 2,
918 }]
919 });
920 }
921 None
922 });
923 assert!(asked);
924 assert_eq!(
925 terminal(&events).outcome,
926 if decision == 2 {
927 Outcome::Failed
928 } else {
929 Outcome::Cancelled
930 },
931 "{decision}: {events:?}"
932 );
933 if decision == 2 {
934 assert_eq!(terminal(&events).error, ErrorCode::DiskFull);
935 assert!(s.0.join("marker").exists());
936 }
937 assert_eq!(terminal(&events).publication, Publication::None);
938 assert_eq!(terminal(&events).created_count, 0);
939 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
940 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
941 }
942}
943
944#[cfg(target_os = "linux")]
945#[path = "item_progress.rs"]
946mod item_progress;
947
948#[path = "header_budget.rs"]
949mod header_budget;
950
951#[path = "tar_stream_limit.rs"]
952mod tar_stream_limit;