| 1 | use super::*; |
| 2 | use std::{io::Read, process::Child, sync::mpsc, time::Duration}; |
| 3 | |
| 4 | struct Running(Child); |
| 5 | impl Drop for Running { |
| 6 | fn drop(&mut self) { |
| 7 | let _ = self.0.kill(); |
| 8 | let _ = self.0.wait(); |
| 9 | } |
| 10 | } |
| 11 | 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 | } |
| 18 | fn run_fault( |
| 19 | s: &Scratch, |
| 20 | start: GuardedStart, |
| 21 | fault: Option<&str>, |
| 22 | mut respond: impl FnMut(&Message) -> Option<Vec<Message>>, |
| 23 | ) -> Vec<Message> { |
| 24 | let mut command = s.worker(); |
| 25 | #[cfg(target_os = "linux")] |
| 26 | if let Some(fault) = fault { |
| 27 | let shim = s.0.join("io_fault.so"); |
| 28 | assert!( |
| 29 | Command::new("cc") |
| 30 | .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"]) |
| 31 | .arg( |
| 32 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 33 | .join("../../tests/rust-archive-worker/io_fault.c") |
| 34 | ) |
| 35 | .args(["-ldl", "-o"]) |
| 36 | .arg(&shim) |
| 37 | .status() |
| 38 | .unwrap() |
| 39 | .success() |
| 40 | ); |
| 41 | command |
| 42 | .env("LD_PRELOAD", shim) |
| 43 | .env("ZIPELO_TEST_FAULT", fault) |
| 44 | .env("ZIPELO_TEST_MARKER", s.0.join("marker")); |
| 45 | } |
| 46 | #[cfg(not(target_os = "linux"))] |
| 47 | assert!(fault.is_none()); |
| 48 | let mut child = Running( |
| 49 | command |
| 50 | .stdin(Stdio::piped()) |
| 51 | .stdout(Stdio::piped()) |
| 52 | .stderr(Stdio::piped()) |
| 53 | .spawn() |
| 54 | .unwrap(), |
| 55 | ); |
| 56 | let mut writer = Some(Writer::new(child.0.stdin.take().unwrap(), 17)); |
| 57 | writer |
| 58 | .as_mut() |
| 59 | .unwrap() |
| 60 | .send(&Message::StartGuarded(start)) |
| 61 | .unwrap(); |
| 62 | let stdout = child.0.stdout.take().unwrap(); |
| 63 | let mut stderr = child.0.stderr.take().unwrap(); |
| 64 | let (send, receive) = mpsc::channel(); |
| 65 | let reader = std::thread::spawn(move || { |
| 66 | let mut reader = Reader::new(stdout); |
| 67 | loop { |
| 68 | let frame = reader.read(); |
| 69 | let done = !matches!(frame, Ok(Some(_))); |
| 70 | if send.send(frame).is_err() || done { |
| 71 | break; |
| 72 | } |
| 73 | } |
| 74 | }); |
| 75 | let mut events = Vec::new(); |
| 76 | loop { |
| 77 | let Some((job, _, event)) = receive |
| 78 | .recv_timeout(Duration::from_secs(20)) |
| 79 | .expect("worker timeout") |
| 80 | .unwrap() |
| 81 | else { |
| 82 | break; |
| 83 | }; |
| 84 | assert_eq!(job, 17); |
| 85 | if let Some(messages) = respond(&event) { |
| 86 | if messages.is_empty() { |
| 87 | writer = None; |
| 88 | } else { |
| 89 | for message in messages { |
| 90 | writer.as_mut().unwrap().send(&message).unwrap(); |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | let done = matches!(event, Message::Terminal(_)); |
| 95 | events.push(event); |
| 96 | if done { |
| 97 | writer = None; |
| 98 | } |
| 99 | } |
| 100 | assert!(child.0.wait().unwrap().success(), "{events:?}"); |
| 101 | let mut errors = Vec::new(); |
| 102 | stderr.read_to_end(&mut errors).unwrap(); |
| 103 | assert!(errors.is_empty(), "{errors:?}"); |
| 104 | reader.join().unwrap(); |
| 105 | assert!(matches!(events.last(), Some(Message::Terminal(_)))); |
| 106 | events |
| 107 | } |
| 108 | fn request(s: &Scratch, output: u64, ceiling: u64) -> GuardedStart { |
| 109 | GuardedStart { |
| 110 | start: Start { |
| 111 | action: Action::Extract { |
| 112 | archive: s.path("input"), |
| 113 | destination: s.path("output"), |
| 114 | selection: Selection::All, |
| 115 | list_id: None, |
| 116 | gzip_output_name: None, |
| 117 | }, |
| 118 | limits: Limits { |
| 119 | output, |
| 120 | ..Limits::default() |
| 121 | }, |
| 122 | }, |
| 123 | ceiling: Limits { |
| 124 | output: ceiling, |
| 125 | entries: 200_000, |
| 126 | ..Limits::default() |
| 127 | }, |
| 128 | interactive: false, |
| 129 | } |
| 130 | } |
| 131 | fn setup() -> Scratch { |
| 132 | let s = Scratch::new(); |
| 133 | fs::write(s.0.join("input"), include_bytes!("fixtures/deflate.zip")).unwrap(); |
| 134 | fs::create_dir(s.0.join("output")).unwrap(); |
| 135 | #[cfg(unix)] |
| 136 | { |
| 137 | use std::os::unix::fs::PermissionsExt; |
| 138 | fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap(); |
| 139 | } |
| 140 | s |
| 141 | } |
| 142 | fn approve(event: &Message) -> Option<Vec<Message>> { |
| 143 | if let Message::ResourceRequired { |
| 144 | challenge_id, |
| 145 | scope, |
| 146 | .. |
| 147 | } = event |
| 148 | { |
| 149 | Some(vec![Message::ResourceReply { |
| 150 | challenge_id: *challenge_id, |
| 151 | scope: *scope, |
| 152 | allow: true, |
| 153 | }]) |
| 154 | } else { |
| 155 | None |
| 156 | } |
| 157 | } |
| 158 | #[test] |
| 159 | fn scaled_output_boundaries_and_approval() { |
| 160 | for limit in [ |
| 161 | PAYLOAD.len() as u64 + 1, |
| 162 | PAYLOAD.len() as u64, |
| 163 | PAYLOAD.len() as u64 - 1, |
| 164 | ] { |
| 165 | let s = setup(); |
| 166 | let events = run(&s, request(&s, limit, 64), approve); |
| 167 | assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); |
| 168 | assert_eq!( |
| 169 | events |
| 170 | .iter() |
| 171 | .filter(|e| matches!(e, Message::ResourceRequired { .. })) |
| 172 | .count(), |
| 173 | 1 |
| 174 | ); |
| 175 | assert_eq!( |
| 176 | fs::read(s.0.join("output/folder/hello.txt")).unwrap(), |
| 177 | PAYLOAD |
| 178 | ); |
| 179 | } |
| 180 | } |
| 181 | #[test] |
| 182 | fn decline_cancel_and_eof_publish_nothing() { |
| 183 | for mode in 0..3 { |
| 184 | let s = setup(); |
| 185 | let events = run(&s, request(&s, 16, 64), |event| { |
| 186 | if let Message::ResourceRequired { |
| 187 | challenge_id, |
| 188 | scope, |
| 189 | usage, |
| 190 | .. |
| 191 | } = event |
| 192 | { |
| 193 | assert_eq!(usage.estimated_bytes, None); |
| 194 | assert_eq!(usage.actual_bytes, None); |
| 195 | assert!(usage.available_bytes.is_some()); |
| 196 | Some(match mode { |
| 197 | 0 => vec![Message::ResourceReply { |
| 198 | challenge_id: *challenge_id, |
| 199 | scope: *scope, |
| 200 | allow: false, |
| 201 | }], |
| 202 | 1 => vec![Message::Cancel], |
| 203 | _ => vec![], |
| 204 | }) |
| 205 | } else { |
| 206 | None |
| 207 | } |
| 208 | }); |
| 209 | assert_eq!( |
| 210 | terminal(&events).outcome, |
| 211 | if mode == 2 { |
| 212 | Outcome::Failed |
| 213 | } else { |
| 214 | Outcome::Cancelled |
| 215 | }, |
| 216 | "{events:?}" |
| 217 | ); |
| 218 | assert_eq!(terminal(&events).publication, Publication::None); |
| 219 | assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); |
| 220 | if mode == 1 { |
| 221 | assert!(events.iter().any(|e| matches!( |
| 222 | e, |
| 223 | Message::CancelAck { |
| 224 | status: CancelStatus::Requested, |
| 225 | .. |
| 226 | } |
| 227 | ))); |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | #[test] |
| 232 | fn stale_duplicate_wrong_scope_and_premature_replies_are_rejected() { |
| 233 | for mode in 0..4 { |
| 234 | let s = setup(); |
| 235 | let events = run(&s, request(&s, 16, 64), |event| { |
| 236 | if mode == 3 && matches!(event, Message::Accepted { .. }) { |
| 237 | return Some(vec![Message::ResourceReply { |
| 238 | challenge_id: 99, |
| 239 | scope: ResourceScope::default(), |
| 240 | allow: true, |
| 241 | }]); |
| 242 | } |
| 243 | if let Message::ResourceRequired { |
| 244 | challenge_id, |
| 245 | scope, |
| 246 | .. |
| 247 | } = event |
| 248 | { |
| 249 | let reply = |id, scope| Message::ResourceReply { |
| 250 | challenge_id: id, |
| 251 | scope, |
| 252 | allow: true, |
| 253 | }; |
| 254 | Some(match mode { |
| 255 | 0 => vec![reply(challenge_id + 1, *scope)], |
| 256 | 1 => vec![reply(*challenge_id, ResourceScope::default())], |
| 257 | 2 => vec![reply(*challenge_id, *scope), reply(*challenge_id, *scope)], |
| 258 | _ => vec![], |
| 259 | }) |
| 260 | } else { |
| 261 | None |
| 262 | } |
| 263 | }); |
| 264 | assert_eq!( |
| 265 | terminal(&events).error, |
| 266 | ErrorCode::Protocol, |
| 267 | "{mode}: {events:?}" |
| 268 | ); |
| 269 | assert_eq!(terminal(&events).publication, Publication::None); |
| 270 | } |
| 271 | } |
| 272 | #[test] |
| 273 | fn ceiling_bytes_and_entries_cannot_be_approved_away() { |
| 274 | for entries in [false, true] { |
| 275 | let s = setup(); |
| 276 | let mut start = request(&s, 1, 16); |
| 277 | if entries { |
| 278 | start.start.limits.output = 64; |
| 279 | start.ceiling.output = 64; |
| 280 | start.start.limits.entries = 1; |
| 281 | start.ceiling.entries = 2; |
| 282 | let members = (0..3) |
| 283 | .map(|id| archive::Member { |
| 284 | entry: Entry { |
| 285 | entry_id: id, |
| 286 | name: format!("empty{id}"), |
| 287 | kind: EntryKind::File, |
| 288 | size: 0, |
| 289 | compressed_size: 0, |
| 290 | encrypted: false, |
| 291 | }, |
| 292 | data: Vec::new(), |
| 293 | }) |
| 294 | .collect::<Vec<_>>(); |
| 295 | let zip = |
| 296 | archive::create_zip(&members, Method::Store, Limits::default(), &mut || Ok(())) |
| 297 | .unwrap(); |
| 298 | fs::write(s.0.join("input"), zip).unwrap(); |
| 299 | } |
| 300 | let mut approved = false; |
| 301 | let events = run(&s, start, |event| { |
| 302 | if matches!(event, Message::ResourceRequired { .. }) { |
| 303 | approved = true; |
| 304 | } |
| 305 | approve(event) |
| 306 | }); |
| 307 | assert!(approved); |
| 308 | assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}"); |
| 309 | assert_eq!(terminal(&events).created_count, 0); |
| 310 | } |
| 311 | } |
| 312 | #[test] |
| 313 | fn entries_have_a_separate_approval() { |
| 314 | let s = setup(); |
| 315 | let mut start = request(&s, 64, 64); |
| 316 | start.start.limits.entries = 1; |
| 317 | start.ceiling.entries = 3; |
| 318 | let events = run(&s, start, |event| { |
| 319 | if let Message::ResourceRequired { scope, .. } = event { |
| 320 | assert!(scope.entries); |
| 321 | assert!(!scope.output); |
| 322 | } |
| 323 | approve(event) |
| 324 | }); |
| 325 | assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); |
| 326 | } |
| 327 | #[test] |
| 328 | fn resource_then_password_then_conflict_use_distinct_questions() { |
| 329 | let s = setup(); |
| 330 | fs::write( |
| 331 | s.0.join("input"), |
| 332 | include_bytes!("fixtures/aes2-deflate.zip"), |
| 333 | ) |
| 334 | .unwrap(); |
| 335 | fs::create_dir_all(s.0.join("output/folder")).unwrap(); |
| 336 | fs::write(s.0.join("output/payload.bin"), b"old").unwrap(); |
| 337 | let mut start = request(&s, 16, 8192); |
| 338 | start.interactive = true; |
| 339 | let mut ids = Vec::new(); |
| 340 | let events = run(&s, start, |event| match event { |
| 341 | Message::ResourceRequired { challenge_id, .. } => { |
| 342 | ids.push(*challenge_id); |
| 343 | approve(event) |
| 344 | } |
| 345 | Message::PasswordRequired { challenge_id, .. } => { |
| 346 | ids.push(*challenge_id); |
| 347 | Some(vec![Message::Password { |
| 348 | challenge_id: *challenge_id, |
| 349 | secret: Secret(TEST_PASSWORD.to_vec()), |
| 350 | }]) |
| 351 | } |
| 352 | Message::ConflictRequired { challenge_id, .. } => { |
| 353 | ids.push(*challenge_id); |
| 354 | Some(vec![Message::ConflictReply { |
| 355 | challenge_id: *challenge_id, |
| 356 | choice: ConflictChoice::Overwrite, |
| 357 | apply_to_remaining: false, |
| 358 | }]) |
| 359 | } |
| 360 | _ => None, |
| 361 | }); |
| 362 | assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); |
| 363 | assert!(ids.len() >= 3, "{events:?}"); |
| 364 | assert!(ids.windows(2).all(|w| w[0] < w[1])); |
| 365 | } |
| 366 | #[test] |
| 367 | fn create_source_total_is_approved_before_password() { |
| 368 | let s = setup(); |
| 369 | fs::write(s.0.join("source"), b"12345678").unwrap(); |
| 370 | let mut start = request(&s, 7, 8); |
| 371 | start.start.action = Action::CreateZip { |
| 372 | sources: vec![Source { |
| 373 | path: s.path("source"), |
| 374 | archive_name: "source".into(), |
| 375 | }], |
| 376 | output_file: s.path("new.zip"), |
| 377 | method: Method::Store, |
| 378 | encryption: Encryption::Aes256, |
| 379 | }; |
| 380 | let mut approved = false; |
| 381 | let events = run(&s, start, |event| match event { |
| 382 | Message::ResourceRequired { action, .. } => { |
| 383 | assert_eq!(*action, ActionKind::CreateZip); |
| 384 | approved = true; |
| 385 | approve(event) |
| 386 | } |
| 387 | Message::PasswordRequired { challenge_id, .. } => { |
| 388 | assert!(approved); |
| 389 | Some(vec![Message::Password { |
| 390 | challenge_id: *challenge_id, |
| 391 | secret: Secret(b"secret".to_vec()), |
| 392 | }]) |
| 393 | } |
| 394 | _ => None, |
| 395 | }); |
| 396 | assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); |
| 397 | assert!(s.0.join("new.zip").exists()); |
| 398 | } |
| 399 | #[test] |
| 400 | fn guarded_wire_round_trip_and_invalid_ceiling() { |
| 401 | let s = setup(); |
| 402 | let start = request(&s, 16, 64); |
| 403 | let mut bytes = Vec::new(); |
| 404 | Writer::new(&mut bytes, 17) |
| 405 | .send(&Message::StartGuarded(start.clone())) |
| 406 | .unwrap(); |
| 407 | assert_eq!(&bytes[6..8], &6u16.to_le_bytes()); |
| 408 | match Reader::new(bytes.as_slice()).read().unwrap().unwrap().2 { |
| 409 | Message::StartGuarded(decoded) => assert_eq!(decoded, start), |
| 410 | other => panic!("{other:?}"), |
| 411 | } |
| 412 | let mut invalid = start; |
| 413 | invalid.ceiling.output = 64 * 1024 * 1024 * 1024 + 1; |
| 414 | assert!(!invalid.valid()); |
| 415 | assert!( |
| 416 | Writer::new(Vec::new(), 17) |
| 417 | .send(&Message::StartGuarded(invalid)) |
| 418 | .is_err() |
| 419 | ); |
| 420 | let mut reply = Vec::new(); |
| 421 | Writer::new(&mut reply, 17) |
| 422 | .send(&Message::ResourceReply { |
| 423 | challenge_id: 4, |
| 424 | scope: ResourceScope { |
| 425 | ratio: true, |
| 426 | ..ResourceScope::default() |
| 427 | }, |
| 428 | allow: true, |
| 429 | }) |
| 430 | .unwrap(); |
| 431 | assert_eq!(&reply[6..8], &7u16.to_le_bytes()); |
| 432 | reply[43] = 2; |
| 433 | assert!(Reader::new(reply.as_slice()).read().is_err()); |
| 434 | } |
| 435 | |
| 436 | fn generate(s: &Scratch, case: &str) { |
| 437 | let result = Command::new("python3") |
| 438 | .arg( |
| 439 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 440 | .join("../../tests/rust-archive-worker/guarded_cases.py"), |
| 441 | ) |
| 442 | .arg(&s.0) |
| 443 | .arg(case) |
| 444 | .output() |
| 445 | .unwrap(); |
| 446 | assert!( |
| 447 | result.status.success(), |
| 448 | "{}", |
| 449 | String::from_utf8_lossy(&result.stderr) |
| 450 | ); |
| 451 | } |
| 452 | #[test] |
| 453 | fn compressed_formats_keep_limits_after_permission() { |
| 454 | for kind in ["gz", "tar", "targz", "bz2", "xz", "7z"] { |
| 455 | let s = setup(); |
| 456 | match kind { |
| 457 | "gz" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.gz")).unwrap(), |
| 458 | "tar" => fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar")).unwrap(), |
| 459 | "targz" => { |
| 460 | fs::write(s.0.join("input"), include_bytes!("fixtures/sample.tar.gz")).unwrap() |
| 461 | } |
| 462 | "bz2" | "xz" => generate(&s, kind), |
| 463 | "7z" => fs::write( |
| 464 | s.0.join("input"), |
| 465 | fs::read( |
| 466 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 467 | .join("../../tests/rust-archive-worker/fixtures/7z/copy.7z"), |
| 468 | ) |
| 469 | .unwrap(), |
| 470 | ) |
| 471 | .unwrap(), |
| 472 | _ => unreachable!(), |
| 473 | } |
| 474 | let mut start = request(&s, 16, 65536); |
| 475 | if kind == "gz" { |
| 476 | if let Action::Extract { |
| 477 | gzip_output_name, .. |
| 478 | } = &mut start.start.action |
| 479 | { |
| 480 | *gzip_output_name = Some("payload".into()); |
| 481 | } |
| 482 | } |
| 483 | let events = run(&s, start, approve); |
| 484 | assert_eq!( |
| 485 | terminal(&events).outcome, |
| 486 | Outcome::Completed, |
| 487 | "{kind}: {events:?}" |
| 488 | ); |
| 489 | } |
| 490 | } |
| 491 | #[test] |
| 492 | fn small_high_ratio_stream_requires_another_scope_and_cancels_promptly() { |
| 493 | let s = setup(); |
| 494 | generate(&s, "bomb"); |
| 495 | assert!(fs::metadata(s.0.join("input")).unwrap().len() < 1024 * 1024); |
| 496 | let mut start = request(&s, 16 * 1024 * 1024 * 1024, 64 * 1024 * 1024 * 1024); |
| 497 | if let Action::Extract { |
| 498 | gzip_output_name, .. |
| 499 | } = &mut start.start.action |
| 500 | { |
| 501 | *gzip_output_name = Some("payload".into()); |
| 502 | } |
| 503 | let mut ratio = false; |
| 504 | let mut cancelled = None; |
| 505 | let events = run(&s, start, |event| { |
| 506 | if let Message::ResourceRequired { scope, usage, .. } = event { |
| 507 | if scope.ratio { |
| 508 | ratio = true; |
| 509 | assert!(!scope.output && !scope.entries); |
| 510 | assert!(usage.actual_bytes.unwrap() >= 256 * 1024 * 1024); |
| 511 | assert!(usage.compressed_bytes.unwrap() < 1024 * 1024); |
| 512 | cancelled = Some(std::time::Instant::now()); |
| 513 | return Some(vec![Message::Cancel]); |
| 514 | } |
| 515 | } |
| 516 | if matches!(event, Message::CancelAck { .. }) { |
| 517 | assert!(cancelled.unwrap().elapsed() < Duration::from_secs(2)); |
| 518 | } |
| 519 | approve(event) |
| 520 | }); |
| 521 | assert!(ratio); |
| 522 | assert_eq!(terminal(&events).outcome, Outcome::Cancelled, "{events:?}"); |
| 523 | assert_eq!(terminal(&events).created_count, 0); |
| 524 | assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); |
| 525 | } |
| 526 | |
| 527 | #[cfg(target_os = "linux")] |
| 528 | #[test] |
| 529 | fn disk_space_and_write_failures_remain_enforced_after_permission() { |
| 530 | for fault in ["space-destination", "codec-full", "full"] { |
| 531 | let s = setup(); |
| 532 | let mut permitted = false; |
| 533 | let events = run_fault(&s, request(&s, 16, 64), Some(fault), |event| { |
| 534 | if matches!(event, Message::ResourceRequired { .. }) { |
| 535 | permitted = true; |
| 536 | } |
| 537 | approve(event) |
| 538 | }); |
| 539 | assert!(permitted); |
| 540 | assert_eq!( |
| 541 | terminal(&events).error, |
| 542 | ErrorCode::DiskFull, |
| 543 | "{fault}: {events:?}" |
| 544 | ); |
| 545 | assert_eq!(terminal(&events).cleanup, Cleanup::Complete, "{events:?}"); |
| 546 | assert!(!s.0.join("output/folder/hello.txt").exists()); |
| 547 | assert!(!fs::read_dir(s.0.join("output")).unwrap().any(|e| { |
| 548 | e.unwrap() |
| 549 | .file_name() |
| 550 | .to_string_lossy() |
| 551 | .starts_with(".zipelo-") |
| 552 | })); |
| 553 | } |
| 554 | } |