team-ljyzipelo

공개
555줄18 KB
1use super::*;
2use sha2::{Digest, Sha256};
3
4fn directory(s: &Scratch, name: &str) {
5 let path = s.0.join(name);
6 fs::create_dir_all(&path).unwrap();
7 #[cfg(unix)]
8 {
9 use std::os::unix::fs::PermissionsExt;
10 let mut current = path.as_path();
11 while current != s.0 {
12 fs::set_permissions(current, fs::Permissions::from_mode(0o700)).unwrap();
13 current = current.parent().unwrap();
14 }
15 }
16}
17fn pieces(s: &Scratch, bytes: &[u8], ends: &[usize]) -> Vec<PathBuf> {
18 let mut begin = 0;
19 let mut paths = Vec::new();
20 for (index, end) in ends.iter().copied().chain(Some(bytes.len())).enumerate() {
21 assert!(begin <= end && end <= bytes.len());
22 let path = s.0.join(format!("sample.7z.{:03}", index + 1));
23 fs::write(&path, &bytes[begin..end]).unwrap();
24 paths.push(path);
25 begin = end;
26 }
27 paths
28}
29fn setup(s: &Scratch, count: usize, fixture: &str) -> (Vec<u8>, Vec<PathBuf>) {
30 let bytes = seven_fixture(fixture);
31 let ends = (1..count)
32 .map(|i| i * bytes.len() / count)
33 .collect::<Vec<_>>();
34 let paths = pieces(s, &bytes, &ends);
35 (bytes, paths)
36}
37fn list(s: &Scratch) -> Vec<Message> {
38 execute(Start {
39 action: Action::List {
40 archive: s.path("sample.7z.001"),
41 },
42 limits: Limits::default(),
43 })
44}
45fn id(events: &[Message]) -> ListId {
46 assert_eq!(terminal(events).outcome, Outcome::Completed, "{events:?}");
47 events
48 .iter()
49 .find_map(|event| match event {
50 Message::ListEnd { list_id, .. } => Some(list_id.clone()),
51 _ => None,
52 })
53 .unwrap()
54}
55fn request(s: &Scratch, list_id: Option<ListId>, selection: Selection) -> Start {
56 Start {
57 action: Action::Extract {
58 archive: s.path("sample.7z.001"),
59 destination: s.path("output"),
60 selection,
61 list_id,
62 gzip_output_name: None,
63 },
64 limits: Limits::default(),
65 }
66}
67fn failure(events: &[Message], error: ErrorCode) {
68 assert_eq!(terminal(events).outcome, Outcome::Failed, "{events:?}");
69 assert_eq!(terminal(events).error, error, "{events:?}");
70 assert_eq!(terminal(events).created_count, 0, "{events:?}");
71 assert_eq!(
72 terminal(events).publication,
73 Publication::None,
74 "{events:?}"
75 );
76 assert!(
77 !events
78 .iter()
79 .any(|event| matches!(event, Message::Output { .. } | Message::ListEnd { .. })),
80 "{events:?}"
81 );
82}
83fn hashes(paths: &[PathBuf]) -> Vec<[u8; 32]> {
84 paths
85 .iter()
86 .map(|p| Sha256::digest(fs::read(p).unwrap()).into())
87 .collect()
88}
89fn problem(events: &[Message], reason: VolumeProblemReason, leaf: &str) {
90 let problems = events
91 .iter()
92 .filter_map(|event| match event {
93 Message::VolumeProblem { reason, volume } => Some((reason, volume)),
94 _ => None,
95 })
96 .collect::<Vec<_>>();
97 assert_eq!(problems.len(), 1, "{events:?}");
98 assert_eq!(
99 problems[0],
100 (&reason, &NativePath::from_path(std::path::Path::new(leaf)))
101 );
102 let accepted = events
103 .iter()
104 .position(|event| matches!(event, Message::Accepted { .. }))
105 .unwrap();
106 let reported = events
107 .iter()
108 .position(|event| matches!(event, Message::VolumeProblem { .. }))
109 .unwrap();
110 assert!(accepted < reported && reported < events.len() - 1);
111}
112
113#[test]
114fn headers_and_data_cross_variable_part_boundaries_for_reference_archives() {
115 for fixture in [
116 "copy.7z",
117 "lzma.7z",
118 "lzma2.7z",
119 "libarchive-lzma1.7z",
120 "libarchive-lzma2.7z",
121 ] {
122 let s = Scratch::new();
123 let bytes = seven_fixture(fixture);
124 let paths = pieces(&s, &bytes, &[1, 6, 13, 31, 32, 40]);
125 let before = hashes(&paths);
126 let listed = list(&s);
127 let token = id(&listed);
128 assert_eq!(token.catalog_version, 2);
129 assert_eq!(token.format, Format::SevenZip);
130 assert!(matches!(
131 token.source_object,
132 SourceObject::SplitSevenZip { .. }
133 ));
134 assert_eq!(token.archive_bytes, bytes.len() as u64);
135 assert_eq!(
136 token.archive_sha256,
137 <[u8; 32]>::from(Sha256::digest(&bytes))
138 );
139 directory(&s, "output");
140 let result = execute(request(&s, Some(token), Selection::EntryIds(vec![0])));
141 assert_eq!(
142 terminal(&result).outcome,
143 Outcome::Completed,
144 "{fixture}: {result:?}"
145 );
146 assert_eq!(
147 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
148 SEVEN_PAYLOAD.repeat(100)
149 );
150 assert_eq!(hashes(&paths), before);
151 }
152}
153
154#[test]
155fn numeric_order_crosses_009_010_and_accepts_exactly_999_parts() {
156 for count in [11, 999] {
157 let s = Scratch::new();
158 let (bytes, paths) = setup(&s, count, "copy.7z");
159 let before = hashes(&paths);
160 let token = id(&list(&s));
161 assert_eq!(token.archive_bytes, bytes.len() as u64);
162 directory(&s, "output");
163 let result = execute(request(&s, Some(token), Selection::All));
164 assert_eq!(
165 terminal(&result).outcome,
166 Outcome::Completed,
167 "{count}: {result:?}"
168 );
169 assert_eq!(
170 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
171 SEVEN_PAYLOAD.repeat(100)
172 );
173 assert_eq!(hashes(&paths), before);
174 fs::write(s.0.join("sample.7z.1000"), [0]).unwrap();
175 failure(&list(&s), ErrorCode::Limit);
176 }
177}
178
179#[test]
180fn nonfirst_selection_and_definite_middle_gaps_name_the_exact_required_part() {
181 let s = Scratch::new();
182 let (_, paths) = setup(&s, 11, "copy.7z");
183 let result = execute(Start {
184 action: Action::List {
185 archive: s.path("sample.7z.002"),
186 },
187 limits: Limits::default(),
188 });
189 failure(&result, ErrorCode::InvalidRequest);
190 problem(
191 &result,
192 VolumeProblemReason::FirstVolumeRequired,
193 "sample.7z.001",
194 );
195 fs::remove_file(&paths[8]).unwrap();
196 let result = list(&s);
197 failure(&result, ErrorCode::MissingVolume);
198 problem(&result, VolumeProblemReason::MissingVolume, "sample.7z.009");
199}
200
201#[test]
202fn missing_tail_truncated_empty_and_extra_bytes_never_guess_a_missing_name() {
203 for mode in 0..4 {
204 let s = Scratch::new();
205 let (_, paths) = setup(&s, 3, "copy.7z");
206 match mode {
207 0 => fs::remove_file(&paths[2]).unwrap(),
208 1 => {
209 let mut bytes = fs::read(&paths[2]).unwrap();
210 bytes.pop();
211 fs::write(&paths[2], bytes).unwrap();
212 }
213 2 => fs::write(&paths[1], []).unwrap(),
214 _ => {
215 let mut bytes = fs::read(&paths[2]).unwrap();
216 bytes.push(0);
217 fs::write(&paths[2], bytes).unwrap();
218 }
219 }
220 let result = list(&s);
221 failure(&result, ErrorCode::Integrity);
222 problem(&result, VolumeProblemReason::IncompleteSet, "sample.7z.001");
223 }
224}
225
226#[test]
227fn detectable_mixed_reordered_and_corrupt_payloads_never_publish() {
228 for mode in 0..3 {
229 let s = Scratch::new();
230 let (_, paths) = setup(&s, 11, "copy.7z");
231 if mode == 0 {
232 let a = fs::read(&paths[4]).unwrap();
233 let b = fs::read(&paths[5]).unwrap();
234 fs::write(&paths[4], b).unwrap();
235 fs::write(&paths[5], a).unwrap();
236 } else {
237 let mut bytes = fs::read(&paths[4]).unwrap();
238 if mode == 1 {
239 bytes.fill(0x5a);
240 } else {
241 bytes[0] ^= 1;
242 }
243 fs::write(&paths[4], bytes).unwrap();
244 }
245 directory(&s, "output");
246 let result = execute(request(&s, None, Selection::All));
247 failure(&result, ErrorCode::Integrity);
248 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
249 }
250}
251
252#[test]
253fn changing_middle_tail_length_object_or_count_after_listing_invalidates_the_token() {
254 for mode in 0..8 {
255 let s = Scratch::new();
256 let (_, paths) = setup(&s, 3, "copy.7z");
257 let token = id(&list(&s));
258 let selected = if mode == 0 { &paths[1] } else { &paths[2] };
259 match mode {
260 0 | 1 => {
261 let mut data = fs::read(selected).unwrap();
262 data[0] ^= 1;
263 fs::write(selected, data).unwrap();
264 }
265 2 => {
266 let data = fs::read(selected).unwrap();
267 fs::rename(selected, s.0.join("old-part")).unwrap();
268 fs::write(selected, data).unwrap();
269 }
270 3 => {
271 let mut data = fs::read(selected).unwrap();
272 data.pop();
273 fs::write(selected, data).unwrap();
274 }
275 4 => fs::remove_file(selected).unwrap(),
276 5 => fs::write(s.0.join("sample.7z.004"), [0]).unwrap(),
277 6 => fs::remove_file(&paths[1]).unwrap(),
278 _ => {
279 for path in &paths {
280 fs::remove_file(path).unwrap();
281 }
282 }
283 }
284 directory(&s, "output");
285 let result = execute(request(&s, Some(token), Selection::All));
286 failure(
287 &result,
288 if mode == 6 {
289 ErrorCode::MissingVolume
290 } else {
291 ErrorCode::SourceChanged
292 },
293 );
294 if mode == 6 {
295 problem(&result, VolumeProblemReason::MissingVolume, "sample.7z.002");
296 } else {
297 assert!(
298 !result
299 .iter()
300 .any(|event| matches!(event, Message::VolumeProblem { .. }))
301 );
302 }
303 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
304 }
305}
306
307#[test]
308fn replacement_or_gap_during_conflict_wait_is_rechecked_before_first_file_commit() {
309 for mode in 0..3 {
310 let s = Scratch::new();
311 let (_, paths) = setup(&s, 3, "copy.7z");
312 let token = id(&list(&s));
313 directory(&s, "output/folder");
314 fs::write(s.0.join("output/folder/hello.txt"), b"keep").unwrap();
315 let mut changed = false;
316 let result = guarded::run(
317 &s,
318 GuardedStart {
319 start: request(&s, Some(token), Selection::All),
320 ceiling: Limits::default(),
321 interactive: true,
322 },
323 |event| {
324 if let Message::ConflictRequired { challenge_id, .. } = event {
325 changed = true;
326 if mode == 2 {
327 fs::remove_file(&paths[1]).unwrap();
328 } else {
329 let target = &paths[if mode == 0 { 1 } else { 2 }];
330 let mut bytes = fs::read(target).unwrap();
331 bytes[0] ^= 1;
332 fs::write(target, bytes).unwrap();
333 }
334 return Some(vec![Message::ConflictReply {
335 challenge_id: *challenge_id,
336 choice: ConflictChoice::Overwrite,
337 apply_to_remaining: false,
338 }]);
339 }
340 None
341 },
342 );
343 assert!(changed, "{result:?}");
344 failure(
345 &result,
346 if mode == 2 {
347 ErrorCode::MissingVolume
348 } else {
349 ErrorCode::SourceChanged
350 },
351 );
352 assert_eq!(
353 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
354 b"keep"
355 );
356 assert_eq!(terminal(&result).cleanup, Cleanup::Complete);
357 assert_eq!(fs::read_dir(s.0.join("output/folder")).unwrap().count(), 1);
358 }
359}
360
361#[test]
362fn split_capture_uses_aggregate_input_budget_and_existing_output_permission() {
363 for allow in [false, true] {
364 let s = Scratch::new();
365 let (bytes, paths) = setup(&s, 11, "copy.7z");
366 let before = hashes(&paths);
367 directory(&s, "output");
368 let mut start = request(&s, None, Selection::All);
369 start.limits.input = bytes.len() as u64;
370 start.limits.output = 1;
371 let ceiling = Limits {
372 input: bytes.len() as u64,
373 output: 8192,
374 ..Limits::default()
375 };
376 let mut questions = 0;
377 let result = guarded::run(
378 &s,
379 GuardedStart {
380 start,
381 ceiling,
382 interactive: true,
383 },
384 |event| {
385 if let Message::ResourceRequired {
386 challenge_id,
387 scope,
388 ..
389 } = event
390 {
391 questions += 1;
392 return Some(vec![Message::ResourceReply {
393 challenge_id: *challenge_id,
394 scope: *scope,
395 allow,
396 }]);
397 }
398 None
399 },
400 );
401 assert_eq!(questions, 1);
402 assert_eq!(
403 terminal(&result).outcome,
404 if allow {
405 Outcome::Completed
406 } else {
407 Outcome::Cancelled
408 },
409 "{result:?}"
410 );
411 if allow {
412 assert_eq!(
413 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
414 SEVEN_PAYLOAD.repeat(100)
415 );
416 } else {
417 assert_eq!(terminal(&result).created_count, 0);
418 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
419 }
420 assert_eq!(hashes(&paths), before);
421 }
422 let s = Scratch::new();
423 let (bytes, _) = setup(&s, 11, "copy.7z");
424 directory(&s, "output");
425 let mut start = request(&s, None, Selection::All);
426 start.limits.input = bytes.len() as u64 - 1;
427 failure(&execute(start), ErrorCode::Limit);
428}
429
430#[test]
431fn cancellation_at_conflict_keeps_source_and_existing_output() {
432 let s = Scratch::new();
433 let (_, paths) = setup(&s, 3, "copy.7z");
434 let before = hashes(&paths);
435 directory(&s, "output/folder");
436 fs::write(s.0.join("output/folder/hello.txt"), b"keep").unwrap();
437 let result = guarded::run(
438 &s,
439 GuardedStart {
440 start: request(&s, None, Selection::All),
441 ceiling: Limits::default(),
442 interactive: true,
443 },
444 |event| matches!(event, Message::ConflictRequired { .. }).then(|| vec![Message::Cancel]),
445 );
446 assert_eq!(terminal(&result).outcome, Outcome::Cancelled);
447 assert_eq!(terminal(&result).created_count, 0);
448 assert_eq!(
449 fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
450 b"keep"
451 );
452 assert_eq!(hashes(&paths), before);
453}
454
455#[test]
456fn split_preview_and_excluded_zip_volume_names_are_not_retried_as_single_inputs() {
457 let s = Scratch::new();
458 let (_, paths) = setup(&s, 3, "copy.7z");
459 let token = id(&list(&s));
460 let preview = Start {
461 action: Action::Preview {
462 archive: s.path("sample.7z.001"),
463 entry_id: 0,
464 list_id: token,
465 },
466 limits: Limits::default(),
467 };
468 let result = guarded::run(
469 &s,
470 GuardedStart {
471 start: preview,
472 ceiling: Limits::default(),
473 interactive: true,
474 },
475 |_| None,
476 );
477 failure(&result, ErrorCode::UnsupportedFeature);
478 assert!(
479 !result
480 .iter()
481 .any(|event| matches!(event, Message::PreviewBegin(_)))
482 );
483 for name in ["sample.zip.001", "sample.z01"] {
484 fs::write(s.0.join(name), include_bytes!("fixtures/store.zip")).unwrap();
485 let result = execute(Start {
486 action: Action::List {
487 archive: s.path(name),
488 },
489 limits: Limits::default(),
490 });
491 failure(&result, ErrorCode::UnsupportedFeature);
492 }
493 assert_eq!(paths.len(), 3);
494}
495
496fn reference_fixture(s: &Scratch, name: &str) -> Vec<PathBuf> {
497 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
498 .join("../../tests/rust-archive-worker/fixtures/split7z");
499 let mut paths = Vec::new();
500 for index in 1..=999 {
501 let source = root.join(format!("{name}.7z.{index:03}"));
502 match fs::read(source) {
503 Ok(data) => {
504 let destination = s.0.join(format!("sample.7z.{index:03}"));
505 fs::write(&destination, data).unwrap();
506 paths.push(destination);
507 }
508 Err(error) if error.kind() == std::io::ErrorKind::NotFound => break,
509 Err(error) => panic!("{error:?}"),
510 }
511 }
512 assert!(paths.len() > 1);
513 paths
514}
515
516#[test]
517fn seven_zip_created_volumes_list_and_extract_with_matching_reference_hashes() {
518 let s = Scratch::new();
519 let paths = reference_fixture(&s, "reference");
520 let before = hashes(&paths);
521 let token = id(&list(&s));
522 directory(&s, "output");
523 let result = execute(request(&s, Some(token), Selection::All));
524 assert_eq!(terminal(&result).outcome, Outcome::Completed, "{result:?}");
525 let expected = SEVEN_PAYLOAD.repeat(100);
526 let actual = fs::read(s.0.join("output/folder/hello.txt")).unwrap();
527 assert_eq!(Sha256::digest(&actual), Sha256::digest(&expected));
528 assert_eq!(actual, expected);
529 let expected = (0..4096usize)
530 .map(|index| ((index * 37 + (index >> 3)) % 256) as u8)
531 .collect::<Vec<_>>();
532 let actual = fs::read(s.0.join("output/second.bin")).unwrap();
533 assert_eq!(Sha256::digest(&actual), Sha256::digest(&expected));
534 assert_eq!(actual, expected);
535 assert_eq!(hashes(&paths), before);
536}
537
538#[test]
539fn encrypted_seven_zip_volumes_keep_the_existing_unsupported_policy() {
540 for name in ["encrypted-header", "encrypted-body"] {
541 let s = Scratch::new();
542 let paths = reference_fixture(&s, name);
543 let before = hashes(&paths);
544 directory(&s, "output");
545 let result = execute(request(&s, None, Selection::All));
546 failure(&result, ErrorCode::UnsupportedFeature);
547 assert!(
548 !result
549 .iter()
550 .any(|event| matches!(event, Message::PasswordRequired { .. }))
551 );
552 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
553 assert_eq!(hashes(&paths), before);
554 }
555}