team-ljyzipelo

공개
441줄15 KB
1use super::*;
2
3fn request(windows: bool) -> Action {
4 let (source, output_file) = if windows {
5 (
6 NativePath::Windows("C:\\s".encode_utf16().collect()),
7 NativePath::Windows("C:\\o.7z".encode_utf16().collect()),
8 )
9 } else {
10 (
11 NativePath::Unix(b"/s".to_vec()),
12 NativePath::Unix(b"/o.7z".to_vec()),
13 )
14 };
15 Action::CreateSevenZip {
16 sources: vec![Source {
17 path: source,
18 archive_name: "한글".to_owned(),
19 }],
20 output_file,
21 method: SevenZipMethod::Lzma2,
22 solid: false,
23 encryption: Encryption::None,
24 volume_size: None,
25 }
26}
27
28fn start(action: Action) -> Start {
29 Start {
30 action,
31 limits: Limits::default(),
32 }
33}
34
35fn guarded(start: Start) -> GuardedStart {
36 GuardedStart {
37 ceiling: Limits {
38 input: start.limits.input,
39 output: 64 * 1024 * 1024 * 1024,
40 entries: 200_000,
41 },
42 start,
43 interactive: false,
44 }
45}
46
47fn encode(message: &Message) -> Vec<u8> {
48 let mut bytes = Vec::new();
49 Writer::new(&mut bytes, 17).send(message).unwrap();
50 bytes
51}
52
53fn decode(bytes: &[u8]) -> Message {
54 let mut reader = Reader::new(bytes);
55 let (job, sequence, message) = reader.read().unwrap().unwrap();
56 assert_eq!((job, sequence), (17, 0));
57 assert!(reader.read().unwrap().is_none());
58 message
59}
60
61fn raw(kind: u16, body: &[u8]) -> Vec<u8> {
62 let mut bytes = b"ZAW1\x01\x00".to_vec();
63 bytes.extend(kind.to_le_bytes());
64 bytes.extend((body.len() as u32).to_le_bytes());
65 bytes.extend([0; 4]);
66 bytes.extend(17u64.to_le_bytes());
67 bytes.extend(0u64.to_le_bytes());
68 bytes.extend(body);
69 bytes
70}
71
72fn reject_encode(message: Message) {
73 let mut bytes = Vec::new();
74 assert_eq!(
75 Writer::new(&mut bytes, 17)
76 .send(&message)
77 .unwrap_err()
78 .kind(),
79 std::io::ErrorKind::InvalidData
80 );
81 assert!(bytes.is_empty());
82}
83
84fn reject_decode(bytes: &[u8]) {
85 assert_eq!(
86 Reader::new(bytes).read().unwrap_err().kind(),
87 std::io::ErrorKind::InvalidData
88 );
89}
90
91#[test]
92fn request_preserves_agreed_field_order_and_native_encodings() {
93 for windows in [false, true] {
94 let start = start(request(windows));
95 assert_eq!(start.action.kind(), ActionKind::CreateSevenZip);
96 let mut expected = vec![4, 1, 0, 0, 0];
97 if windows {
98 expected.extend(b"\x02\x04\x00\x00\x00C\x00:\x00\\\x00s\x00");
99 } else {
100 expected.extend(b"\x01\x02\x00\x00\x00/s");
101 }
102 expected.extend(b"\x06\x00\x00\x00\xed\x95\x9c\xea\xb8\x80");
103 if windows {
104 expected.extend(b"\x02\x07\x00\x00\x00C\x00:\x00\\\x00o\x00.\x007\x00z\x00");
105 } else {
106 expected.extend(b"\x01\x05\x00\x00\x00/o.7z");
107 }
108 // 방식, solid, 암호화, 분할 크기(없음).
109 expected.extend([0, 0, 0, 0]);
110 expected.extend(u64::MAX.to_le_bytes());
111 expected.extend((16u64 * 1024 * 1024 * 1024).to_le_bytes());
112 expected.extend(10_000u32.to_le_bytes());
113 let bytes = encode(&Message::Start(start.clone()));
114 assert_eq!(bytes, raw(1, &expected));
115 match decode(&bytes) {
116 Message::Start(actual) => assert_eq!(actual, start),
117 other => panic!("{other:?}"),
118 }
119 let guarded = guarded(start);
120 assert!(guarded.valid());
121 expected.extend(u64::MAX.to_le_bytes());
122 expected.extend((64u64 * 1024 * 1024 * 1024).to_le_bytes());
123 expected.extend(200_000u32.to_le_bytes());
124 expected.push(0);
125 let bytes = encode(&Message::StartGuarded(guarded.clone()));
126 assert_eq!(bytes, raw(6, &expected));
127 match decode(&bytes) {
128 Message::StartGuarded(actual) => assert_eq!(actual, guarded),
129 other => panic!("{other:?}"),
130 }
131 }
132}
133
134#[test]
135fn unsupported_options_remain_structurally_valid_without_silent_conversion() {
136 for solid in [false, true] {
137 for encryption in [Encryption::None, Encryption::Aes256] {
138 let mut action = request(false);
139 if let Action::CreateSevenZip {
140 solid: actual_solid,
141 encryption: actual_encryption,
142 ..
143 } = &mut action
144 {
145 *actual_solid = solid;
146 *actual_encryption = encryption;
147 }
148 let start = start(action);
149 match decode(&encode(&Message::Start(start.clone()))) {
150 Message::Start(actual) => assert_eq!(actual, start),
151 other => panic!("{other:?}"),
152 }
153 }
154 }
155}
156
157#[test]
158fn creation_never_accepts_interactive_conflict_requests() {
159 let start = start(request(false));
160 reject_encode(Message::StartInteractive(start.clone()));
161 let bytes = encode(&Message::Start(start.clone()));
162 reject_decode(&raw(4, &bytes[32..]));
163 let mut guarded = guarded(start);
164 guarded.interactive = true;
165 assert!(!guarded.valid());
166 reject_encode(Message::StartGuarded(guarded));
167 let mut bytes = encode(&Message::StartGuarded(self::guarded(self::start(request(
168 false,
169 )))));
170 *bytes.last_mut().unwrap() = 1;
171 reject_decode(&bytes);
172}
173
174#[test]
175fn truncated_unknown_and_trailing_creation_fields_are_rejected() {
176 for windows in [false, true] {
177 let bytes = encode(&Message::Start(start(request(windows))));
178 let body = &bytes[32..];
179 for length in 0..body.len() {
180 reject_decode(&raw(1, &body[..length]));
181 }
182 let mut trailing = body.to_vec();
183 trailing.push(0);
184 reject_decode(&raw(1, &trailing));
185 let method = body.len() - 20 - 4;
186 for (at, value) in [
187 (0, 5),
188 (method, 1),
189 (method + 1, 2),
190 (method + 2, 2),
191 (method + 3, 2),
192 ] {
193 let mut body = body.to_vec();
194 body[at] = value;
195 reject_decode(&raw(1, &body));
196 }
197 }
198}
199
200#[test]
201fn guarded_approval_never_expands_source_vector_string_or_path_wire_limits() {
202 let mut action = request(false);
203 if let Action::CreateSevenZip { sources, .. } = &mut action {
204 sources[0].archive_name = "a".repeat(32_768);
205 }
206 let guarded = guarded(start(action.clone()));
207 assert!(matches!(
208 decode(&encode(&Message::StartGuarded(guarded))),
209 Message::StartGuarded(_)
210 ));
211 if let Action::CreateSevenZip { sources, .. } = &mut action {
212 sources[0].archive_name.push('a');
213 }
214 reject_encode(Message::StartGuarded(self::guarded(start(action))));
215 for windows in [false, true] {
216 let mut action = request(windows);
217 if let Action::CreateSevenZip { sources, .. } = &mut action {
218 sources[0].path = if windows {
219 NativePath::Windows(vec![b'a' as u16; 32_769])
220 } else {
221 NativePath::Unix(vec![b'a'; 32_769])
222 };
223 }
224 reject_encode(Message::StartGuarded(self::guarded(start(action))));
225 }
226 let mut action = request(false);
227 if let Action::CreateSevenZip { sources, .. } = &mut action {
228 *sources = vec![sources[0].clone(); 32_769];
229 }
230 reject_encode(Message::StartGuarded(self::guarded(start(action))));
231 let bytes = encode(&Message::StartGuarded(self::guarded(start(request(false)))));
232 for at in [1, 6, 12] {
233 let mut body = bytes[32..].to_vec();
234 body[at..at + 4].copy_from_slice(&32_769u32.to_le_bytes());
235 reject_decode(&raw(6, &body));
236 }
237}
238
239#[test]
240fn action_kind_events_keep_existing_tags_and_append_creation_tag_four() {
241 for (tag, action) in [
242 ActionKind::List,
243 ActionKind::Extract,
244 ActionKind::CreateZip,
245 ActionKind::Preview,
246 ActionKind::CreateSevenZip,
247 ]
248 .into_iter()
249 .enumerate()
250 {
251 let encryption = action != ActionKind::CreateSevenZip;
252 let bytes = encode(&Message::Accepted { action, encryption });
253 assert_eq!(bytes, raw(100, &[tag as u8, u8::from(encryption)]));
254 assert!(
255 matches!(decode(&bytes), Message::Accepted { action: actual, encryption: value } if actual == action && value == encryption)
256 );
257 let scope = ResourceScope {
258 entries: true,
259 ..ResourceScope::default()
260 };
261 let bytes = encode(&Message::ResourceRequired {
262 challenge_id: 23,
263 action,
264 scope,
265 usage: ResourceUsage::default(),
266 soft_limits: Limits::default(),
267 ceiling: guarded(start(request(false))).ceiling,
268 });
269 assert_eq!(bytes[32 + 8], tag as u8);
270 assert!(
271 matches!(decode(&bytes), Message::ResourceRequired { action: actual, scope: value, .. } if actual == action && value == scope)
272 );
273 let mut body = bytes[32..].to_vec();
274 body[8] = 6;
275 reject_decode(&raw(110, &body));
276 }
277 reject_decode(&raw(100, &[6, 0]));
278}
279
280#[test]
281fn zip_methods_and_existing_request_bytes_stay_independent() {
282 for (tag, method) in [(0, Method::Store), (1, Method::Deflate)] {
283 let action = Action::CreateZip {
284 sources: Vec::new(),
285 output_file: NativePath::Unix(b"/a.zip".to_vec()),
286 method,
287 encryption: Encryption::Aes256,
288 };
289 let start = start(action);
290 let mut body = b"\x02\x00\x00\x00\x00\x01\x06\x00\x00\x00/a.zip".to_vec();
291 body.extend([tag, 1]);
292 body.extend(u64::MAX.to_le_bytes());
293 body.extend((16u64 * 1024 * 1024 * 1024).to_le_bytes());
294 body.extend(10_000u32.to_le_bytes());
295 assert_eq!(encode(&Message::Start(start.clone())), raw(1, &body));
296 assert!(matches!(decode(&raw(1, &body)), Message::Start(actual) if actual == start));
297 body[16] = 2;
298 reject_decode(&raw(1, &body));
299 }
300}
301
302struct Temporary(PathBuf);
303impl Temporary {
304 fn new() -> Self {
305 let root = std::env::var_os("TMPDIR")
306 .map(PathBuf::from)
307 .unwrap_or_else(|| {
308 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")
309 });
310 fs::create_dir_all(&root).unwrap();
311 let path = root.canonicalize().unwrap().join(format!(
312 "zipelo-seven-create-{}-{}",
313 std::process::id(),
314 NEXT.fetch_add(1, Ordering::Relaxed)
315 ));
316 fs::create_dir(&path).unwrap();
317 Self(path)
318 }
319 fn run(&self, message: Message) -> Vec<Message> {
320 let output = self.0.join("saved.7z");
321 fs::write(&output, b"existing user data").unwrap();
322 let bytes = encode(&message);
323 let mut child = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
324 .env("TMPDIR", self.0.join("unavailable-temp"))
325 .env("TMP", self.0.join("unavailable-temp"))
326 .env("TEMP", self.0.join("unavailable-temp"))
327 .stdin(Stdio::piped())
328 .stdout(Stdio::piped())
329 .stderr(Stdio::piped())
330 .spawn()
331 .unwrap();
332 child.stdin.take().unwrap().write_all(&bytes).unwrap();
333 let output = child.wait_with_output().unwrap();
334 assert!(output.status.success(), "{:?}", output.stderr);
335 assert!(output.stderr.is_empty());
336 let mut reader = Reader::new(output.stdout.as_slice());
337 let mut events = Vec::new();
338 while let Some((job, _, message)) = reader.read().unwrap() {
339 assert_eq!(job, 17);
340 events.push(message);
341 }
342 assert_eq!(
343 fs::read(self.0.join("saved.7z")).unwrap(),
344 b"existing user data"
345 );
346 assert_eq!(fs::read_dir(&self.0).unwrap().count(), 1);
347 events
348 }
349}
350impl Drop for Temporary {
351 fn drop(&mut self) {
352 fs::remove_dir_all(&self.0).expect("7z 생성 시험 임시 폴더 정리에 실패함");
353 }
354}
355
356#[test]
357fn unsupported_options_fail_before_questions_or_file_access() {
358 let temporary = Temporary::new();
359 for solid in [false, true] {
360 for encryption in [Encryption::None, Encryption::Aes256] {
361 if !solid && encryption == Encryption::None {
362 continue;
363 }
364 for kind in [1, 6, 7] {
365 let action = Action::CreateSevenZip {
366 sources: vec![Source {
367 path: NativePath::from_path(&temporary.0.join("missing/source")),
368 archive_name: "source".to_owned(),
369 }],
370 output_file: NativePath::from_path(&temporary.0.join("saved.7z")),
371 method: SevenZipMethod::Lzma2,
372 solid,
373 encryption,
374 volume_size: None,
375 };
376 let start = start(action);
377 let message = if kind == 1 {
378 Message::Start(start)
379 } else {
380 let mut guarded = guarded(start);
381 if kind == 7 {
382 guarded.ceiling = guarded.start.limits;
383 }
384 Message::StartGuarded(guarded)
385 };
386 let events = temporary.run(message);
387 assert_eq!(events.len(), 2, "{events:?}");
388 assert!(matches!(
389 events[0],
390 Message::Accepted {
391 action: ActionKind::CreateSevenZip,
392 encryption: false
393 }
394 ));
395 let terminal = terminal(&events);
396 assert_eq!(terminal.outcome, Outcome::Failed);
397 assert_eq!(terminal.error, ErrorCode::UnsupportedFeature);
398 assert_eq!(terminal.publication, Publication::None);
399 assert_eq!(terminal.created_count, 0);
400 assert_eq!(terminal.retained_partial_count, 0);
401 assert_eq!(terminal.cleanup, Cleanup::Complete);
402 assert_eq!(terminal.durability, Durability::NotApplicable);
403 }
404 }
405 }
406}
407
408#[test]
409fn existing_runtime_encryption_capability_is_preserved() {
410 let temporary = Temporary::new();
411 let events = temporary.run(Message::Start(start(Action::List {
412 archive: NativePath::from_path(&temporary.0.join("missing.zip")),
413 })));
414 assert!(matches!(
415 events[0],
416 Message::Accepted {
417 action: ActionKind::List,
418 encryption: true
419 }
420 ));
421 assert_eq!(terminal(&events).outcome, Outcome::Failed);
422}
423
424#[test]
425fn split_volume_size_round_trips_and_absence_stays_distinct() {
426 for size in [
427 None,
428 Some(MIN_SEVEN_ZIP_VOLUME_BYTES),
429 Some(5 * 1024 * 1024 * 1024),
430 ] {
431 let mut action = request(false);
432 if let Action::CreateSevenZip { volume_size, .. } = &mut action {
433 *volume_size = size;
434 }
435 let start = start(action);
436 match decode(&encode(&Message::Start(start.clone()))) {
437 Message::Start(actual) => assert_eq!(actual, start),
438 other => panic!("{other:?}"),
439 }
440 }
441}