team-ljyzipelo

공개
398줄13 KB
1use super::*;
2use sha2::{Digest, Sha256};
3
4fn fixture(format: &str, name: &str, bytes: &[u8]) -> (Scratch, String, ListId, u32) {
5 let s = Scratch::new();
6 fs::write(s.0.join("payload"), bytes).unwrap();
7 let script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8 .join("../../tests/rust-archive-worker/preview_cases.py");
9 let result = Command::new("python3")
10 .arg("-B")
11 .arg(script)
12 .arg(&s.0)
13 .arg(format)
14 .arg(name)
15 .output()
16 .unwrap();
17 assert!(
18 result.status.success(),
19 "{}",
20 String::from_utf8_lossy(&result.stderr)
21 );
22 let path = if format == "gzip" {
23 format!("{name}.gz")
24 } else {
25 "input".into()
26 };
27 let events = execute(Start {
28 action: Action::List {
29 archive: s.path(&path),
30 },
31 limits: Limits::default(),
32 });
33 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
34 let id = events
35 .iter()
36 .find_map(|e| match e {
37 Message::Entry(entry) if entry.name == name || format == "gzip" => Some(entry.entry_id),
38 _ => None,
39 })
40 .unwrap();
41 let list = events
42 .into_iter()
43 .find_map(|e| match e {
44 Message::ListEnd { list_id, .. } => Some(list_id),
45 _ => None,
46 })
47 .unwrap();
48 (s, path, list, id)
49}
50fn request(s: &Scratch, path: &str, list_id: ListId, entry_id: u32) -> GuardedStart {
51 GuardedStart {
52 start: Start {
53 action: Action::Preview {
54 archive: s.path(path),
55 entry_id,
56 list_id,
57 },
58 limits: Limits::default(),
59 },
60 ceiling: Limits::default(),
61 interactive: true,
62 }
63}
64fn run(s: &Scratch, start: GuardedStart) -> Vec<Message> {
65 guarded::run(s, start, |event| match event {
66 Message::ResourceRequired {
67 challenge_id,
68 scope,
69 ..
70 } => Some(vec![Message::ResourceReply {
71 challenge_id: *challenge_id,
72 scope: *scope,
73 allow: true,
74 }]),
75 Message::PasswordRequired { challenge_id, .. } => Some(vec![Message::Password {
76 challenge_id: *challenge_id,
77 secret: Secret(b"fixture-password".to_vec()),
78 }]),
79 _ => None,
80 })
81}
82fn result(events: &[Message]) -> (PreviewInfo, Vec<u8>) {
83 let terminal = terminal(events);
84 assert_eq!(terminal.outcome, Outcome::Completed, "{events:?}");
85 assert_eq!(terminal.publication, Publication::None);
86 assert_eq!(terminal.created_count, 0);
87 assert_eq!(terminal.cleanup, Cleanup::Complete);
88 assert!(
89 !events
90 .iter()
91 .any(|e| matches!(e, Message::Output { .. } | Message::ConflictRequired { .. }))
92 );
93 let mut info = None;
94 let mut data = Vec::new();
95 let mut ended = false;
96 for event in events {
97 match event {
98 Message::PreviewBegin(value) => {
99 assert!(info.replace(*value).is_none());
100 assert!(value.valid());
101 }
102 Message::PreviewChunk {
103 entry_id,
104 offset,
105 data: bytes,
106 } => {
107 assert!(!ended);
108 assert_eq!(Some(*entry_id), info.map(|i| i.entry_id));
109 assert_eq!(*offset, data.len() as u64);
110 assert!(bytes.len() <= MAX_PREVIEW_CHUNK_BYTES);
111 data.extend(bytes);
112 }
113 Message::PreviewEnd {
114 entry_id,
115 total_bytes,
116 sha256,
117 } => {
118 assert!(!ended);
119 ended = true;
120 let info = info.unwrap();
121 assert_eq!(*entry_id, info.entry_id);
122 assert_eq!(*total_bytes, info.total_bytes);
123 assert_eq!(*total_bytes, data.len() as u64);
124 assert_eq!(*sha256, <[u8; 32]>::from(Sha256::digest(&data)));
125 }
126 _ => {}
127 }
128 }
129 assert!(ended);
130 (info.unwrap(), data)
131}
132fn no_result(events: &[Message], error: ErrorCode) {
133 assert_eq!(terminal(events).outcome, Outcome::Failed, "{events:?}");
134 assert_eq!(terminal(events).error, error, "{events:?}");
135 assert_eq!(terminal(events).publication, Publication::None);
136 assert_eq!(terminal(events).created_count, 0);
137 assert!(!events.iter().any(|e| matches!(
138 e,
139 Message::PreviewBegin(_)
140 | Message::PreviewChunk { .. }
141 | Message::PreviewEnd { .. }
142 | Message::Output { .. }
143 )));
144}
145fn png(width: u32, height: u32) -> Vec<u8> {
146 let mut bytes = Vec::new();
147 let mut encoder = png::Encoder::new(&mut bytes, width, height);
148 encoder.set_color(png::ColorType::Rgba);
149 let mut writer = encoder.write_header().unwrap();
150 writer
151 .write_image_data(&vec![20; (width * height * 4) as usize])
152 .unwrap();
153 drop(writer);
154 bytes
155}
156#[test]
157fn preview_actual_formats_keep_source_and_publish_nothing() {
158 for format in [
159 "zip",
160 "zip-selected",
161 "zip-selected-damaged",
162 "7z-folders",
163 "tar",
164 "gz",
165 "bz2",
166 "xz",
167 "gzip",
168 "7z-copy",
169 "7z-lzma",
170 "7z-lzma2",
171 "aes",
172 ] {
173 let expected = "가나다\n".repeat(10000);
174 let (s, path, list, id) = fixture(format, "payload.txt", expected.as_bytes());
175 let original = fs::read(s.0.join(&path)).unwrap();
176 let (_, data) = result(&run(&s, request(&s, &path, list, id)));
177 assert_eq!(data, expected.as_bytes(), "{format}");
178 assert_eq!(fs::read(s.0.join(&path)).unwrap(), original);
179 assert_eq!(fs::read_dir(&s.0).unwrap().count(), 2);
180 }
181}
182#[test]
183fn preview_actual_png_and_jpeg_have_exact_rgba_metadata() {
184 for (name, bytes, width, height) in [
185 ("payload.png", png(3, 2), 3, 2),
186 (
187 "payload.jpg",
188 include_bytes!("fixtures/preview-baseline.jpg").to_vec(),
189 3,
190 2,
191 ),
192 (
193 "payload.jpeg",
194 include_bytes!("fixtures/preview-progressive.jpg").to_vec(),
195 3,
196 2,
197 ),
198 ] {
199 for format in ["zip", "tar", "7z-lzma2"] {
200 let (s, path, list, id) = fixture(format, name, &bytes);
201 let (info, data) = result(&run(&s, request(&s, &path, list, id)));
202 assert_eq!(
203 (info.width, info.height, info.total_bytes),
204 (width, height, u64::from(width * height * 4))
205 );
206 assert_eq!(data.len(), (width * height * 4) as usize);
207 }
208 }
209}
210#[test]
211fn preview_own_limit_is_not_expanded_by_permission() {
212 for (name, bytes) in [
213 (
214 "payload.txt",
215 vec![b'x'; MAX_PREVIEW_TEXT_BYTES as usize + 1],
216 ),
217 ("payload.png", vec![0; MAX_PREVIEW_IMAGE_BYTES as usize + 1]),
218 ] {
219 let (s, path, list, id) = fixture("zip", name, &bytes);
220 let mut start = request(&s, &path, list, id);
221 start.ceiling.output = 64 * 1024 * 1024 * 1024;
222 let events = run(&s, start);
223 assert!(
224 events
225 .iter()
226 .any(|e| matches!(e, Message::ResourceRequired { .. }))
227 );
228 no_result(&events, ErrorCode::Limit);
229 }
230 let expected = vec![b'x'; MAX_PREVIEW_TEXT_BYTES as usize];
231 let (s, path, list, id) = fixture("zip", "payload.txt", &expected);
232 assert_eq!(result(&run(&s, request(&s, &path, list, id))).1, expected);
233}
234#[test]
235fn preview_rejects_corruption_unsupported_and_stale_selection() {
236 for (name, bytes, error) in [
237 ("payload.txt", vec![0xff], ErrorCode::Integrity),
238 (
239 "payload.svg",
240 b"<svg/>".to_vec(),
241 ErrorCode::UnsupportedFeature,
242 ),
243 (
244 "payload.png",
245 b"GIF89a".to_vec(),
246 ErrorCode::UnsupportedFormat,
247 ),
248 ("payload.jpg", vec![0xff, 0xd8], ErrorCode::Integrity),
249 ] {
250 let (s, path, list, id) = fixture("zip", name, &bytes);
251 no_result(&run(&s, request(&s, &path, list, id)), error);
252 }
253 let (s, path, list, id) = fixture("zip", "payload.txt", b"text");
254 let mut changed = list.clone();
255 changed.archive_sha256[0] ^= 1;
256 no_result(
257 &run(&s, request(&s, &path, changed, id)),
258 ErrorCode::SourceChanged,
259 );
260 no_result(
261 &run(&s, request(&s, &path, list, u32::MAX)),
262 ErrorCode::InvalidRequest,
263 );
264}
265#[test]
266fn preview_solid_budget_still_applies_to_preceding_content() {
267 let (s, path, list, id) = fixture("7z-lzma2", "payload.txt", b"text");
268 let mut start = request(&s, &path, list, id);
269 start.start.limits.output = 100_000;
270 start.ceiling = start.start.limits;
271 no_result(&run(&s, start), ErrorCode::Limit);
272}
273#[test]
274fn preview_cancels_before_decode_and_during_chunk_transmission() {
275 for stage in [0, 1, 2] {
276 let (s, path, list, id) = fixture("zip", "payload.png", &png(4000, 4000));
277 let mut cancelled = false;
278 let events = guarded::run(&s, request(&s, &path, list, id), |event| {
279 let target = match stage {
280 0 => matches!(event, Message::Accepted { .. }),
281 1 => matches!(
282 event,
283 Message::Progress {
284 stage: Stage::Decode,
285 ..
286 }
287 ),
288 _ => matches!(event, Message::PreviewChunk { .. }),
289 };
290 if target && !cancelled {
291 cancelled = true;
292 Some(vec![Message::Cancel])
293 } else {
294 None
295 }
296 });
297 assert!(cancelled);
298 assert_eq!(
299 terminal(&events).outcome,
300 Outcome::Cancelled,
301 "stage={stage}"
302 );
303 assert_eq!(terminal(&events).publication, Publication::None);
304 assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
305 assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
306 }
307}
308
309#[test]
310fn preview_password_retry_and_cancel_never_publish_plaintext() {
311 let (s, path, list, id) = fixture("aes", "payload.txt", b"secret preview");
312 let mut attempts = Vec::new();
313 let events = guarded::run(
314 &s,
315 request(&s, &path, list.clone(), id),
316 |event| match event {
317 Message::PasswordRequired {
318 challenge_id,
319 attempt,
320 ..
321 } => {
322 attempts.push(*attempt);
323 Some(vec![Message::Password {
324 challenge_id: *challenge_id,
325 secret: Secret(if *attempt == 1 {
326 b"wrong".to_vec()
327 } else {
328 b"fixture-password".to_vec()
329 }),
330 }])
331 }
332 _ => None,
333 },
334 );
335 assert_eq!(attempts, [1, 2]);
336 assert_eq!(result(&events).1, b"secret preview");
337 let events = guarded::run(&s, request(&s, &path, list, id), |event| {
338 if matches!(event, Message::PasswordRequired { .. }) {
339 Some(vec![Message::Cancel])
340 } else {
341 None
342 }
343 });
344 assert_eq!(terminal(&events).outcome, Outcome::Cancelled);
345 assert!(!events.iter().any(|e| matches!(
346 e,
347 Message::PreviewBegin(_)
348 | Message::PreviewChunk { .. }
349 | Message::PreviewEnd { .. }
350 | Message::Output { .. }
351 )));
352}
353
354#[test]
355fn preview_empty_text_uses_begin_and_end_without_chunks() {
356 for format in ["zip", "tar", "7z-lzma2", "gzip"] {
357 let (s, path, list, id) = fixture(format, "payload.txt", b"");
358 let events = run(&s, request(&s, &path, list, id));
359 assert!(result(&events).1.is_empty());
360 assert!(
361 !events
362 .iter()
363 .any(|e| matches!(e, Message::PreviewChunk { .. }))
364 );
365 }
366}
367#[test]
368fn preview_rejects_directory_link_and_changed_source_object() {
369 for format in ["tar-folder", "tar-link"] {
370 let (s, path, list, id) = fixture(format, "payload.txt", b"");
371 no_result(
372 &run(&s, request(&s, &path, list, id)),
373 ErrorCode::InvalidRequest,
374 );
375 }
376 let (s, path, list, id) = fixture("zip", "payload.txt", b"original");
377 fs::write(s.0.join(&path), b"changed").unwrap();
378 no_result(
379 &run(&s, request(&s, &path, list, id)),
380 ErrorCode::SourceChanged,
381 );
382 assert_eq!(fs::read(s.0.join(&path)).unwrap(), b"changed");
383}
384
385#[test]
386fn preview_runtime_rejects_missing_image_scan_data() {
387 let original = include_bytes!("fixtures/preview-baseline.jpg");
388 let mut jpeg = original[..623].to_vec();
389 jpeg.extend([0xff, 0xd9]);
390 let mut png = png(1, 1);
391 png[20..24].copy_from_slice(&2u32.to_be_bytes());
392 let crc = zlib_rs::crc32::crc32(0, &png[12..29]);
393 png[29..33].copy_from_slice(&crc.to_be_bytes());
394 for (name, bytes) in [("missing.jpg", jpeg), ("missing.png", png)] {
395 let (s, path, list, id) = fixture("zip", name, &bytes);
396 no_result(&run(&s, request(&s, &path, list, id)), ErrorCode::Integrity);
397 }
398}