team-ljyzipelo

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