team-ljyzipelo

공개
977줄32 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 create = start.clone();
429 create.start.action = Action::CreateZip {
430 sources: vec![Source {
431 path: s.path("source"),
432 archive_name: "source".into(),
433 }],
434 output_file: s.path("new.zip"),
435 method: Method::Store,
436 encryption: Encryption::None,
437 };
438 create.ceiling = Limits::expanded(ActionKind::CreateZip);
439 assert_eq!(create.ceiling.output, u64::MAX);
440 assert!(create.valid());
441 let mut bytes = Vec::new();
442 Writer::new(&mut bytes, 17)
443 .send(&Message::StartGuarded(create.clone()))
444 .unwrap();
445 match Reader::new(bytes.as_slice()).read().unwrap().unwrap().2 {
446 Message::StartGuarded(decoded) => assert_eq!(decoded, create),
447 other => panic!("{other:?}"),
448 }
449 assert_eq!(
450 Limits::expanded(ActionKind::Extract).output,
451 MAX_EXPANDED_OUTPUT
452 );
453 let mut invalid = start;
454 invalid.ceiling.output = MAX_EXPANDED_OUTPUT + 1;
455 assert!(!invalid.valid());
456 assert!(
457 Writer::new(Vec::new(), 17)
458 .send(&Message::StartGuarded(invalid))
459 .is_err()
460 );
461 let mut reply = Vec::new();
462 Writer::new(&mut reply, 17)
463 .send(&Message::ResourceReply {
464 challenge_id: 4,
465 scope: ResourceScope {
466 ratio: true,
467 ..ResourceScope::default()
468 },
469 allow: true,
470 })
471 .unwrap();
472 assert_eq!(&reply[6..8], &7u16.to_le_bytes());
473 reply[43] = 2;
474 assert!(Reader::new(reply.as_slice()).read().is_err());
475}
476
477fn generate(s: &Scratch, case: &str) {
478 let result = Command::new("python3")
479 .arg(
480 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
481 .join("../../tests/rust-archive-worker/guarded_cases.py"),
482 )
483 .arg(&s.0)
484 .arg(case)
485 .output()
486 .unwrap();
487 assert!(
488 result.status.success(),
489 "{}",
490 String::from_utf8_lossy(&result.stderr)
491 );
492}
493#[test]
494fn compressed_formats_keep_limits_after_permission() {
495 for kind in ["gz", "tar", "targz", "bz2", "xz", "7z"] {
496 let s = setup();
497 match kind {
498 "gz" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.gz")).unwrap(),
499 "tar" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar")).unwrap(),
500 "targz" => {
501 fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar.gz")).unwrap()
502 }
503 "bz2" | "xz" => generate(&s, kind),
504 "7z" => fs::write(
505 s.0.join("input"),
506 fs::read(
507 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
508 .join("../../tests/rust-archive-worker/fixtures/7z/copy.7z"),
509 )
510 .unwrap(),
511 )
512 .unwrap(),
513 _ => unreachable!(),
514 }
515 let mut start = request(&s, 16, 65536);
516 if kind == "gz" {
517 if let Action::Extract {
518 gzip_output_name, ..
519 } = &mut start.start.action
520 {
521 *gzip_output_name = Some("payload".into());
522 }
523 }
524 let events = run(&s, start, approve);
525 assert_eq!(
526 terminal(&events).outcome,
527 Outcome::Completed,
528 "{kind}: {events:?}"
529 );
530 }
531}
532#[test]
533fn small_high_ratio_stream_requires_another_scope_and_cancels_promptly() {
534 let s = setup();
535 generate(&s, "bomb");
536 assert!(fs::metadata(s.0.join("input")).unwrap().len() < 1024 * 1024);
537 let mut start = request(&s, 16 * 1024 * 1024 * 1024, 64 * 1024 * 1024 * 1024);
538 if let Action::Extract {
539 gzip_output_name, ..
540 } = &mut start.start.action
541 {
542 *gzip_output_name = Some("payload".into());
543 }
544 let mut ratio = false;
545 let mut cancelled = None;
546 let events = run(&s, start, |event| {
547 if let Message::ResourceRequired { scope, usage, .. } = event {
548 if scope.ratio {
549 ratio = true;
550 assert!(!scope.output && !scope.entries);
551 assert!(usage.actual_bytes.unwrap() >= 256 * 1024 * 1024);
552 assert!(usage.compressed_bytes.unwrap() < 1024 * 1024);
553 cancelled = Some(std::time::Instant::now());
554 return Some(vec![Message::Cancel]);
555 }
556 }
557 if matches!(event, Message::CancelAck { .. }) {
558 assert!(cancelled.unwrap().elapsed() < Duration::from_secs(2));
559 }
560 approve(event)
561 });
562 assert!(ratio);
563 assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}");
564 assert_eq!(terminal(&events).created_count, 0);
565 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
566}
567
568#[cfg(target_os = "linux")]
569#[test]
570fn disk_space_and_write_failures_remain_enforced_after_permission() {
571 for fault in ["space-destination", "codec-full", "full"] {
572 let s = setup();
573 let mut permitted = false;
574 let events = run_fault(&s, request(&s, 16, 64), Some(fault), |event| {
575 if matches!(event, Message::ResourceRequired { .. }) {
576 permitted = true;
577 }
578 approve(event)
579 });
580 assert!(permitted);
581 assert_eq!(
582 terminal(&events).error,
583 ErrorCode::DiskFull,
584 "{fault}: {events:?}"
585 );
586 assert_eq!(terminal(&events).cleanup, Cleanup::Complete, "{events:?}");
587 assert!(!s.0.join("output/folder/hello.txt").exists());
588 assert!(!fs::read_dir(s.0.join("output")).unwrap().any(|e| {
589 e.unwrap()
590 .file_name()
591 .to_string_lossy()
592 .starts_with(".zipelo-")
593 }));
594 }
595}
596
597#[test]
598fn split_zip_ratio_requires_permission_before_decoding() {
599 let s = setup();
600 generate(&s, "split-zip");
601 assert!(fs::metadata(s.0.join("input")).unwrap().len() < 300_000);
602 let mut start = request(&s, Limits::default().output, Limits::default().output);
603 start.ceiling.entries = Limits::default().entries;
604 for mode in 0..3 {
605 let outcome = if mode == 2 {
606 Outcome::Completed
607 } else {
608 Outcome::Cancelled
609 };
610 let mut asked = false;
611 let events = run(&s, start.clone(), |event| {
612 if let Message::ResourceRequired {
613 challenge_id,
614 scope,
615 usage,
616 ..
617 } = event
618 {
619 assert!(!asked);
620 asked = true;
621 assert_eq!(
622 *scope,
623 ResourceScope {
624 ratio: true,
625 ..ResourceScope::default()
626 }
627 );
628 assert_eq!(usage.estimated_bytes, Some(258 * 1024 * 1024));
629 assert_eq!(usage.ratio_output_bytes, usage.estimated_bytes);
630 assert_eq!(usage.actual_bytes, None);
631 assert!(usage.compressed_bytes.unwrap() < 300_000);
632 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
633 if mode == 0 {
634 return Some(vec![Message::Cancel]);
635 }
636 return Some(vec![Message::ResourceReply {
637 challenge_id: *challenge_id,
638 scope: *scope,
639 allow: outcome == Outcome::Completed,
640 }]);
641 }
642 None
643 });
644 assert!(asked);
645 assert_eq!(terminal(&events).outcome, outcome, "{events:?}");
646 assert_eq!(
647 terminal(&events).created_count,
648 if outcome == Outcome::Completed { 2 } else { 0 }
649 );
650 }
651 for name in ["first.bin", "second.bin"] {
652 let mut file = fs::File::open(s.0.join("output").join(name)).unwrap();
653 assert_eq!(file.metadata().unwrap().len(), 129 * 1024 * 1024);
654 let mut block = [0; 65536];
655 loop {
656 let n = file.read(&mut block).unwrap();
657 if n == 0 {
658 break;
659 }
660 assert!(block[..n].iter().all(|b| *b == 0));
661 }
662 }
663}
664
665#[cfg(target_os = "linux")]
666fn progress_archive(s: &Scratch, kind: EntryKind, size: u64) {
667 if kind == EntryKind::Directory {
668 generate(s, "empty-directories");
669 return;
670 }
671 let members = (0..36)
672 .map(|entry_id| archive::Member {
673 entry: Entry {
674 entry_id,
675 name: format!("entry-{entry_id}"),
676 kind,
677 size,
678 compressed_size: size,
679 encrypted: false,
680 },
681 data: vec![0; size as usize],
682 })
683 .collect::<Vec<_>>();
684 let zip =
685 archive::create_zip(&members, Method::Store, Limits::default(), &mut || Ok(())).unwrap();
686 fs::write(s.0.join("input"), zip).unwrap();
687}
688
689#[cfg(target_os = "linux")]
690#[test]
691fn completed_empty_files_and_directories_refresh_idle_deadline() {
692 for (kind, size) in [
693 (EntryKind::File, 0),
694 (EntryKind::File, 1),
695 (EntryKind::Directory, 0),
696 ] {
697 let s = setup();
698 progress_archive(&s, kind, size);
699 let events = run_fault(&s, request(&s, 64, 128), Some("clock-progress"), approve);
700 assert_eq!(
701 terminal(&events).outcome,
702 Outcome::Completed,
703 "{kind:?}: {events:?}"
704 );
705 assert_eq!(terminal(&events).created_count, 36);
706 assert_eq!(terminal(&events).durability, Durability::Synced);
707 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 36);
708 }
709}
710
711#[cfg(target_os = "linux")]
712#[test]
713fn publication_still_stops_after_sixty_seconds_without_progress() {
714 let s = setup();
715 progress_archive(&s, EntryKind::File, 0);
716 let events = run_fault(&s, request(&s, 64, 128), Some("clock-stall"), approve);
717 assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
718 assert_eq!(terminal(&events).error, ErrorCode::Limit);
719 assert_eq!(terminal(&events).created_count, 0);
720 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
721}
722
723#[test]
724fn approved_list_reaches_two_hundred_thousand_short_entries() {
725 let s = setup();
726 generate(&s, "many-entries");
727 let mut start = request(&s, Limits::default().output, Limits::default().output);
728 start.start.action = Action::List {
729 archive: s.path("input"),
730 };
731 start.ceiling.entries = start.start.limits.entries;
732 let events = run(&s, start.clone(), |_| None);
733 assert_eq!(terminal(&events).error, ErrorCode::Limit);
734 assert!(
735 !events
736 .iter()
737 .any(|e| matches!(e, Message::ResourceRequired { .. }))
738 );
739 start.ceiling.entries = 200_000;
740 let mut count = 0;
741 // 대량 목록을 시험 부모에 모아 이후 자식의 RSS 측정을 오염시키지 않음.
742 let events = run_record(&s, start, None, false, |event| {
743 if let Message::Entry(entry) = event {
744 assert_eq!(entry.entry_id, count);
745 assert_eq!(entry.name, format!("e{count}"));
746 count += 1;
747 }
748 approve(event)
749 });
750 assert_eq!(
751 terminal(&events).outcome,
752 Outcome::Completed,
753 "{:?}",
754 terminal(&events)
755 );
756 assert_eq!(count, 200_000);
757 assert!(events.iter().any(|event| matches!(
758 event,
759 Message::ListEnd {
760 entry_count: 200_000,
761 ..
762 }
763 )));
764 assert_eq!(terminal(&events).created_count, 0);
765}
766
767#[test]
768fn metadata_growth_requires_a_grant_even_below_entry_and_output_caps() {
769 let s = setup();
770 generate(&s, "wide-names");
771 let mut start = request(&s, 1, 1);
772 start.start.action = Action::List {
773 archive: s.path("input"),
774 };
775 start.ceiling.entries = start.start.limits.entries;
776 let events = run(&s, start.clone(), |_| None);
777 assert_eq!(terminal(&events).error, ErrorCode::Limit);
778 assert!(
779 !events
780 .iter()
781 .any(|e| matches!(e, Message::ResourceRequired { .. } | Message::Entry(_)))
782 );
783 start.ceiling.output = 2;
784 let events = run(&s, start, approve);
785 assert_eq!(
786 terminal(&events).outcome,
787 Outcome::Completed,
788 "{:?}",
789 terminal(&events)
790 );
791 assert_eq!(
792 events
793 .iter()
794 .filter(|e| matches!(e, Message::Entry(_)))
795 .count(),
796 9000
797 );
798}
799
800#[cfg(target_os = "linux")]
801fn create_progress_request(
802 s: &Scratch,
803 kind: EntryKind,
804 size: usize,
805 method: Method,
806) -> GuardedStart {
807 fs::create_dir(s.0.join("source")).unwrap();
808 for entry_id in 0..36 {
809 let path = s.0.join(format!("source/entry-{entry_id}"));
810 if kind == EntryKind::Directory {
811 fs::create_dir(path).unwrap();
812 } else {
813 fs::write(path, vec![0; size]).unwrap();
814 }
815 }
816 let mut start = request(s, 64, 128);
817 start.start.action = Action::CreateZip {
818 sources: vec![Source {
819 path: s.path("source"),
820 archive_name: "source".into(),
821 }],
822 output_file: s.path("new.zip"),
823 method,
824 encryption: Encryption::None,
825 };
826 start
827}
828
829#[cfg(target_os = "linux")]
830#[test]
831fn created_empty_files_and_directories_refresh_idle_deadline() {
832 for method in [Method::Store, Method::Deflate] {
833 for (kind, size) in [
834 (EntryKind::Directory, 0),
835 (EntryKind::File, 0),
836 (EntryKind::File, 1),
837 ] {
838 let s = setup();
839 let start = create_progress_request(&s, kind, size, method);
840 let mut approved = false;
841 let events = run_fault(&s, start, Some("clock-create-progress"), |event| {
842 if matches!(event, Message::ResourceRequired { .. }) {
843 approved = true;
844 }
845 approve(event)
846 });
847 assert!(approved);
848 assert_eq!(
849 terminal(&events).outcome,
850 Outcome::Completed,
851 "{method:?} {kind:?} {size}: {events:?}"
852 );
853 assert_eq!(terminal(&events).publication, Publication::Complete);
854 assert_eq!(terminal(&events).created_count, 1);
855 let bytes = fs::read(s.0.join("new.zip")).unwrap();
856 let parsed = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
857 assert_eq!(parsed.members.len(), 37);
858 assert!(parsed.members.iter().any(|member| {
859 member.entry.name == "source" && member.entry.kind == EntryKind::Directory
860 }));
861 for entry_id in 0..36 {
862 let name = format!("source/entry-{entry_id}");
863 let member = parsed
864 .members
865 .iter()
866 .find(|member| member.entry.name == name)
867 .unwrap();
868 assert_eq!(member.entry.kind, kind);
869 assert_eq!(member.data, vec![0; size]);
870 }
871 }
872 }
873}
874
875#[cfg(target_os = "linux")]
876#[test]
877fn zip_creation_still_stops_after_sixty_seconds_without_progress() {
878 let s = setup();
879 let start = create_progress_request(&s, EntryKind::Directory, 0, Method::Store);
880 let events = run_fault(&s, start, Some("clock-create-stall"), approve);
881 assert_eq!(terminal(&events).outcome, Outcome::Failed, "{events:?}");
882 assert_eq!(terminal(&events).error, ErrorCode::Limit);
883 assert_eq!(terminal(&events).publication, Publication::None);
884 assert_eq!(terminal(&events).created_count, 0);
885 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
886 assert!(!s.0.join("new.zip").exists());
887}
888
889#[cfg(target_os = "linux")]
890#[test]
891fn large_selection_reaches_worker_permission_and_destination_checks() {
892 let s = setup();
893 generate(&s, "selection-entries");
894 let mut start = request(&s, Limits::default().output, Limits::default().output);
895 start.start.action = Action::List {
896 archive: s.path("input"),
897 };
898 let mut count = 0;
899 let mut list_id = None;
900 let events = run_record(&s, start, None, false, |event| {
901 match event {
902 Message::Entry(entry) => {
903 assert_eq!(entry.entry_id, count);
904 count += 1;
905 }
906 Message::ListEnd { list_id: id, .. } => list_id = Some(id.clone()),
907 _ => {}
908 }
909 approve(event)
910 });
911 assert_eq!(terminal(&events).outcome, Outcome::Completed);
912 assert_eq!(count, 32_770);
913 let list_id = list_id.unwrap();
914 for decision in 0..3 {
915 let mut start = request(&s, Limits::default().output, Limits::default().output);
916 if let Action::Extract {
917 selection,
918 list_id: token,
919 ..
920 } = &mut start.start.action
921 {
922 *selection = Selection::EntryIds((0..32_769).collect());
923 *token = Some(list_id.clone());
924 }
925 let mut asked = false;
926 let events = run_fault(&s, start, Some("space-destination"), |event| {
927 if let Message::ResourceRequired {
928 challenge_id,
929 scope,
930 ..
931 } = event
932 {
933 asked = true;
934 assert!(scope.entries && !scope.output && !scope.ratio);
935 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
936 return Some(if decision == 1 {
937 vec![Message::Cancel]
938 } else {
939 vec![Message::ResourceReply {
940 challenge_id: *challenge_id,
941 scope: *scope,
942 allow: decision == 2,
943 }]
944 });
945 }
946 None
947 });
948 assert!(asked);
949 assert_eq!(
950 terminal(&events).outcome,
951 if decision == 2 {
952 Outcome::Failed
953 } else {
954 Outcome::Cancelled
955 },
956 "{decision}: {events:?}"
957 );
958 if decision == 2 {
959 assert_eq!(terminal(&events).error, ErrorCode::DiskFull);
960 assert!(s.0.join("marker").exists());
961 }
962 assert_eq!(terminal(&events).publication, Publication::None);
963 assert_eq!(terminal(&events).created_count, 0);
964 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
965 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
966 }
967}
968
969#[cfg(target_os = "linux")]
970#[path = "item_progress.rs"]
971mod item_progress;
972
973#[path = "header_budget.rs"]
974mod header_budget;
975
976#[path = "tar_stream_limit.rs"]
977mod tar_stream_limit;