team-ljyzipelo

공개

작업자 실제 경로 시험과 ZIP 확장 해석을 통합함

작성자
시로사키 하나
작성 시각
커밋
dee7d8c42240877d4f1de51cd2619063861bf096
부모
ef72c47
이 시점의 파일 보기

변경된 파일 17개

+638-287
수정experiments/rust-archive-worker/src/archive.rs+3-46
@@ -382,39 +382,9 @@ fn tar(
382382 validate_members(&members)?;
383383 Ok(members)
384384}
385삭제: #[derive(Clone, Copy, PartialEq, Eq)]
386삭제: pub(crate) struct AesExtra {
387삭제: pub version: u16,
388삭제: pub method: u16,
389삭제: }
385추가: pub(crate) use crate::zip_extra::AesExtra;
390386pub(crate) fn aes_extra(extra: &[u8]) -> Result<Option<AesExtra>> {
391삭제: let mut at = 0;
392삭제: let mut found = None;
393삭제: while at < extra.len() {
394삭제: let tag = u16at(extra, at)?;
395삭제: let len = u16at(extra, at + 2)? as usize;
396삭제: let value = part(extra, at + 4, len)?;
397삭제: if tag == 1 {
398삭제: return Err(ErrorCode::UnsupportedFeature);
399삭제: }
400삭제: if tag == 0x9901 {
401삭제: if found.is_some() || len < 7 {
402삭제: return Err(ErrorCode::Integrity);
403삭제: }
404삭제: let version = u16at(value, 0)?;
405삭제: let method = u16at(value, 5)?;
406삭제: if !matches!(version, 1 | 2)
407삭제: || &value[2..4] != b"AE"
408삭제: || value[4] != 3
409삭제: || !matches!(method, 0 | 8)
410삭제: {
411삭제: return Err(ErrorCode::UnsupportedFeature);
412삭제: }
413삭제: found = Some(AesExtra { version, method });
414삭제: }
415삭제: at += 4 + len;
416삭제: }
417삭제: Ok(found)
387추가: crate::zip_extra::parse(extra, crate::zip_extra::Policy::Classic).map(|extra| extra.aes)
418388}
419389/// ZIP 항목 이름을 해석함.
420390///
@@ -431,20 +401,7 @@ pub(crate) fn zip_name(raw: &[u8], flags: u16, extra: &[u8]) -> Result<String> {
431401 .map(str::to_owned)
432402 .map_err(|_| ErrorCode::Integrity);
433403 }
434삭제: let mut at = 0;
435삭제: let mut unicode = None;
436삭제: while at < extra.len() {
437삭제: let tag = u16at(extra, at)?;
438삭제: let len = u16at(extra, at + 2)? as usize;
439삭제: let value = part(extra, at + 4, len)?;
440삭제: if tag == 0x7075 {
441삭제: if unicode.is_some() || len < 5 {
442삭제: return Err(ErrorCode::Integrity);
443삭제: }
444삭제: unicode = Some(value);
445삭제: }
446삭제: at += 4 + len;
447삭제: }
404추가: let unicode = crate::zip_extra::parse(extra, crate::zip_extra::Policy::Names)?.unicode;
448405 if let Some(value) = unicode
449406 && value[0] == 1
450407 && u32::from_le_bytes(value[1..5].try_into().unwrap()) == crc32(0, raw)
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -17,4 +17,5 @@ mod split_seven_zip;
1717mod spool;
1818mod streaming;
1919pub mod wire;
20추가: mod zip_extra;
2021mod zip_recovery;
수정experiments/rust-archive-worker/src/streaming.rs+9-75
@@ -3,6 +3,7 @@ use crate::{
33 crypto,
44 protocol::*,
55 spool,
6추가: zip_extra::{self, Policy, disk_start, expanded, large_value, local_sizes},
67};
78use std::{
89 fs::File,
@@ -357,77 +358,6 @@ struct Packed {
357358 aes: bool,
358359}
359360
360삭제: fn extra(bytes: &[u8]) -> Result<(Option<archive::AesExtra>, Option<Vec<u8>>)> {
361삭제: let mut at = 0;
362삭제: let mut aes = Vec::new();
363삭제: let mut large = None;
364삭제: while at < bytes.len() {
365삭제: if bytes.len() - at < 4 {
366삭제: return Err(ErrorCode::Integrity);
367삭제: }
368삭제: let tag = u16at(bytes, at);
369삭제: let len = u16at(bytes, at + 2) as usize;
370삭제: let end = at + 4 + len;
371삭제: if end > bytes.len() {
372삭제: return Err(ErrorCode::Integrity);
373삭제: }
374삭제: if tag == 1 {
375삭제: if large.is_some() {
376삭제: return Err(ErrorCode::Integrity);
377삭제: }
378삭제: large = Some(bytes[at + 4..end].to_vec());
379삭제: } else {
380삭제: aes.extend_from_slice(&bytes[at..end]);
381삭제: }
382삭제: at = end;
383삭제: }
384삭제: Ok((archive::aes_extra(&aes)?, large))
385삭제: }
386삭제: fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> {
387삭제: if value != u32::MAX {
388삭제: return Ok(value as u64);
389삭제: }
390삭제: if extra.len() < 8 {
391삭제: return Err(ErrorCode::Integrity);
392삭제: }
393삭제: let result = u64at(extra, 0);
394삭제: *extra = &extra[8..];
395삭제: Ok(result)
396삭제: }
397삭제: fn expanded(value: u64, maximum: u64, large: u64) -> Result<u64> {
398삭제: if value == maximum || value == large {
399삭제: Ok(large)
400삭제: } else {
401삭제: Err(ErrorCode::Integrity)
402삭제: }
403삭제: }
404삭제: fn disk_start(value: u16, extra: &mut &[u8]) -> Result<u32> {
405삭제: if value != u16::MAX {
406삭제: return Ok(value as u32);
407삭제: }
408삭제: if extra.len() < 4 {
409삭제: return Err(ErrorCode::Integrity);
410삭제: }
411삭제: let result = u32at(extra, 0);
412삭제: *extra = &extra[4..];
413삭제: Ok(result)
414삭제: }
415삭제: fn local_sizes(size: u32, compressed: u32, extra: Option<&[u8]>) -> Result<(u64, u64)> {
416삭제: if let Some(extra) = extra {
417삭제: // 로컬 ZIP64 추가 필드에는 두 크기가 함께 들어감.
418삭제: if extra.len() < 16 {
419삭제: return Err(ErrorCode::Integrity);
420삭제: }
421삭제: Ok((
422삭제: expanded(size as u64, u32::MAX as u64, u64at(extra, 0))?,
423삭제: expanded(compressed as u64, u32::MAX as u64, u64at(extra, 8))?,
424삭제: ))
425삭제: } else if size == u32::MAX || compressed == u32::MAX {
426삭제: Err(ErrorCode::Integrity)
427삭제: } else {
428삭제: Ok((size as u64, compressed as u64))
429삭제: }
430삭제: }
431361fn descriptor_size(
432362 bytes: &[u8],
433363 crc: u32,
@@ -572,10 +502,12 @@ fn zip(
572502 }
573503 let raw = bytes(source, cursor + 46, nn as usize)?;
574504 let central_extra = bytes(source, cursor + 46 + nn, ne as usize)?;
575삭제: let (aes, large) = extra(&central_extra)?;
505추가: let parsed_extra = zip_extra::parse(&central_extra, Policy::Streaming)?;
506추가: let aes = parsed_extra.aes;
507추가: let large = parsed_extra.zip64;
576508 let name = archive::zip_name(&raw, flags, &central_extra)?;
577509 let name = name.as_str();
578삭제: let mut large = large.as_deref().unwrap_or(&[]);
510추가: let mut large = large.unwrap_or(&[]);
579511 let size = large_value(u32at(&h, 24), &mut large)?;
580512 let compressed = large_value(u32at(&h, 20), &mut large)?;
581513 let local = large_value(u32at(&h, 42), &mut large)?;
@@ -653,7 +585,9 @@ fn zip(
653585 if bytes(source, local + 30, ln as usize)? != raw {
654586 return Err(ErrorCode::Integrity);
655587 }
656삭제: let (local_aes, local_large) = extra(&bytes(source, local + 30 + ln, le as usize)?)?;
588추가: let local_extra = bytes(source, local + 30 + ln, le as usize)?;
589추가: let parsed_local = zip_extra::parse(&local_extra, Policy::Streaming)?;
590추가: let (local_aes, local_large) = (parsed_local.aes, parsed_local.zip64);
657591 if local_aes != aes || local_large.as_ref().is_some_and(|values| values.len() < 16) {
658592 return Err(ErrorCode::Integrity);
659593 }
@@ -664,7 +598,7 @@ fn zip(
664598 || local_large.is_some();
665599 if flags & 8 == 0 {
666600 let (local_size, local_compressed) =
667삭제: local_sizes(u32at(&lh, 22), u32at(&lh, 18), local_large.as_deref())?;
601추가: local_sizes(u32at(&lh, 22), u32at(&lh, 18), local_large)?;
668602 if u32at(&lh, 14) != crc || local_size != size || local_compressed != compressed {
669603 return Err(ErrorCode::Integrity);
670604 }
추가experiments/rust-archive-worker/src/zip_extra.rs+157-0
@@ -0,0 +1,157 @@
1추가: use crate::protocol::ErrorCode;
2추가:
3추가: type Result<T> = std::result::Result<T, ErrorCode>;
4추가:
5추가: #[derive(Clone, Copy, PartialEq, Eq)]
6추가: pub(crate) enum Policy {
7추가: Streaming,
8추가: Classic,
9추가: Recovery,
10추가: Names,
11추가: }
12추가:
13추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)]
14추가: pub(crate) struct AesExtra {
15추가: pub version: u16,
16추가: pub method: u16,
17추가: }
18추가:
19추가: #[derive(Default, Debug)]
20추가: pub(crate) struct Extra<'a> {
21추가: pub aes: Option<AesExtra>,
22추가: pub zip64: Option<&'a [u8]>,
23추가: pub unicode: Option<&'a [u8]>,
24추가: }
25추가:
26추가: fn u16at(bytes: &[u8], at: usize) -> u16 {
27추가: u16::from_le_bytes(bytes[at..at + 2].try_into().unwrap())
28추가: }
29추가: fn u32at(bytes: &[u8], at: usize) -> u32 {
30추가: u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
31추가: }
32추가: fn u64at(bytes: &[u8], at: usize) -> u64 {
33추가: u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())
34추가: }
35추가:
36추가: fn aes(value: &[u8]) -> Result<AesExtra> {
37추가: if value.len() < 7 {
38추가: return Err(ErrorCode::Integrity);
39추가: }
40추가: let version = u16at(value, 0);
41추가: let method = u16at(value, 5);
42추가: if !matches!(version, 1 | 2)
43추가: || &value[2..4] != b"AE"
44추가: || value[4] != 3
45추가: || !matches!(method, 0 | 8)
46추가: {
47추가: return Err(ErrorCode::UnsupportedFeature);
48추가: }
49추가: Ok(AesExtra { version, method })
50추가: }
51추가:
52추가: pub(crate) fn parse(bytes: &[u8], policy: Policy) -> Result<Extra<'_>> {
53추가: let mut found = Extra::default();
54추가: let mut deferred_aes = None;
55추가: let mut duplicate_aes = false;
56추가: let mut at = 0;
57추가: while at < bytes.len() {
58추가: if bytes.len() - at < 4 {
59추가: return Err(ErrorCode::Integrity);
60추가: }
61추가: let tag = u16at(bytes, at);
62추가: let length = u16at(bytes, at + 2) as usize;
63추가: // 복구 경로는 확장 크기와 강한 암호화를 해석하지 않음.
64추가: if policy == Policy::Recovery && matches!(tag, 1 | 0x0017 | 0x0018) {
65추가: return Err(ErrorCode::UnsupportedFeature);
66추가: }
67추가: let end = at.checked_add(4 + length).ok_or(ErrorCode::Integrity)?;
68추가: let value = bytes.get(at + 4..end).ok_or(ErrorCode::Integrity)?;
69추가: match (policy, tag) {
70추가: (Policy::Classic, 1) => return Err(ErrorCode::UnsupportedFeature),
71추가: (Policy::Streaming, 1) => {
72추가: if found.zip64.replace(value).is_some() {
73추가: return Err(ErrorCode::Integrity);
74추가: }
75추가: }
76추가: (Policy::Classic, 0x9901) => {
77추가: if found.aes.is_some() {
78추가: return Err(ErrorCode::Integrity);
79추가: }
80추가: found.aes = Some(aes(value)?);
81추가: }
82추가: (Policy::Streaming, 0x9901) => {
83추가: if deferred_aes.is_some() {
84추가: duplicate_aes = true;
85추가: } else {
86추가: deferred_aes = Some(value);
87추가: }
88추가: }
89추가: (Policy::Names, 0x7075) => {
90추가: if found.unicode.is_some() || length < 5 {
91추가: return Err(ErrorCode::Integrity);
92추가: }
93추가: found.unicode = Some(value);
94추가: }
95추가: _ => {}
96추가: }
97추가: at = end;
98추가: }
99추가: // 스트리밍은 전체 필드 경계를 확인한 뒤 AES 지원 여부를 판단함.
100추가: if let Some(value) = deferred_aes {
101추가: found.aes = Some(aes(value)?);
102추가: if duplicate_aes {
103추가: return Err(ErrorCode::Integrity);
104추가: }
105추가: }
106추가: Ok(found)
107추가: }
108추가:
109추가: pub(crate) fn large_value(value: u32, extra: &mut &[u8]) -> Result<u64> {
110추가: if value != u32::MAX {
111추가: return Ok(value as u64);
112추가: }
113추가: if extra.len() < 8 {
114추가: return Err(ErrorCode::Integrity);
115추가: }
116추가: let result = u64at(extra, 0);
117추가: *extra = &extra[8..];
118추가: Ok(result)
119추가: }
120추가: pub(crate) fn expanded(value: u64, maximum: u64, large: u64) -> Result<u64> {
121추가: if value == maximum || value == large {
122추가: Ok(large)
123추가: } else {
124추가: Err(ErrorCode::Integrity)
125추가: }
126추가: }
127추가: pub(crate) fn disk_start(value: u16, extra: &mut &[u8]) -> Result<u32> {
128추가: if value != u16::MAX {
129추가: return Ok(value as u32);
130추가: }
131추가: if extra.len() < 4 {
132추가: return Err(ErrorCode::Integrity);
133추가: }
134추가: let result = u32at(extra, 0);
135추가: *extra = &extra[4..];
136추가: Ok(result)
137추가: }
138추가: pub(crate) fn local_sizes(size: u32, compressed: u32, extra: Option<&[u8]>) -> Result<(u64, u64)> {
139추가: if let Some(extra) = extra {
140추가: // 로컬 ZIP64 추가 필드에는 두 크기가 함께 들어감.
141추가: if extra.len() < 16 {
142추가: return Err(ErrorCode::Integrity);
143추가: }
144추가: Ok((
145추가: expanded(size as u64, u32::MAX as u64, u64at(extra, 0))?,
146추가: expanded(compressed as u64, u32::MAX as u64, u64at(extra, 8))?,
147추가: ))
148추가: } else if size == u32::MAX || compressed == u32::MAX {
149추가: Err(ErrorCode::Integrity)
150추가: } else {
151추가: Ok((size as u64, compressed as u64))
152추가: }
153추가: }
154추가:
155추가: #[cfg(test)]
156추가: #[path = "../../../tests/rust-archive-worker/zip_extra.rs"]
157추가: mod tests;
수정experiments/rust-archive-worker/src/zip_recovery.rs+2-20
@@ -38,24 +38,6 @@ fn bytes(source: &mut File, offset: u64, size: usize, end: u64) -> Result<Vec<u8
3838 io(source.read_exact(&mut data))?;
3939 Ok(data)
4040}
41삭제: fn extra(data: &[u8]) -> Result<()> {
42삭제: let mut at = 0;
43삭제: while at < data.len() {
44삭제: if data.len() - at < 4 {
45삭제: return Err(ErrorCode::Integrity);
46삭제: }
47삭제: let tag = u16at(data, at);
48삭제: let size = u16at(data, at + 2) as usize;
49삭제: if matches!(tag, 1 | 0x0017 | 0x0018) {
50삭제: return Err(ErrorCode::UnsupportedFeature);
51삭제: }
52삭제: at = at
53삭제: .checked_add(4 + size)
54삭제: .filter(|n| *n <= data.len())
55삭제: .ok_or(ErrorCode::Integrity)?;
56삭제: }
57삭제: Ok(())
58삭제: }
5941struct Candidate {
6042 finding: RecoveryEntry,
6143 start: u64,
@@ -438,7 +420,7 @@ fn central(
438420 charge(&mut metadata, nn, ne, check)?;
439421 let raw = bytes(source, at + 46, nn, cd_end)?;
440422 let ext = bytes(source, at + 46 + nn as u64, ne, cd_end)?;
441삭제: extra(&ext)?;
423추가: crate::zip_extra::parse(&ext, crate::zip_extra::Policy::Recovery)?;
442424 let (size, packed) = declared(u32at(&h, 24), u32at(&h, 20))?;
443425 let unix_kind = (u32at(&h, 38) >> 16) & 0xf000;
444426 let kind = match unix_kind {
@@ -579,7 +561,7 @@ fn local(
579561 }
580562 let raw = bytes(source, at + 30, nn, len)?;
581563 let ext = bytes(source, at + 30 + nn as u64, ne, len)?;
582삭제: extra(&ext)?;
564추가: crate::zip_extra::parse(&ext, crate::zip_extra::Policy::Recovery)?;
583565 let kind = if raw.ends_with(b"/") {
584566 EntryKind::Directory
585567 } else {
수정tests/ci/README.md+1-0
@@ -17,6 +17,7 @@ python3 tests/ci/run_rust.py local --job rust-local
1717- 추적된 fixture를 Git blob과 대조합니다. Windows checkout 시 core.autocrlf=false를 사용해야 하며 기대값의 바이트를 바꾸지 않습니다.
1818- 개별 단계는 `build`, `test`, `cross-build`로 실행할 수 있습니다. 한 crate가 실패해도 다른 crate 결과를 수집합니다.
1919- GUI 앱은 컴파일하며 실제 화면 시나리오는 실행하지 않습니다. C# 시험과 역사적 hash 검사는 포함하지 않습니다.
20추가: - Linux 작업자의 작은 임시 공간 시험은 기본 실행에 포함합니다. 자식 프로세스에만 적용한 LD_PRELOAD 보조 코드로 2MiB 공유 용량, 부분 쓰기와 ENOSPC 및 핸들 종료 후 공간 반환을 재현합니다. 커널 tmpfs를 직접 마운트한 실기 검증은 아닙니다.
2021
2122## 출시 전 Windows 실기 확인
2223
수정tests/rust-archive-worker/folder_inputs.rs+1-1
@@ -149,7 +149,7 @@ fn empty_root_folder_is_preserved() {
149149 let events = execute(start);
150150 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
151151 let bytes = fs::read(s.0.join("created.zip")).unwrap();
152삭제: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
152추가: let catalog = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
153153 assert_eq!(catalog.members.len(), 1);
154154 assert_eq!(catalog.members[0].entry.kind, EntryKind::Directory);
155155 assert_eq!(catalog.members[0].entry.name, "documents");
수정tests/rust-archive-worker/guarded.rs+1-1
@@ -828,7 +828,7 @@ fn created_empty_files_and_directories_refresh_idle_deadline() {
828828 assert_eq!(terminal(&events).publication, Publication::Complete);
829829 assert_eq!(terminal(&events).created_count, 1);
830830 let bytes = fs::read(s.0.join("new.zip")).unwrap();
831삭제: let parsed = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
831추가: let parsed = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
832832 assert_eq!(parsed.members.len(), 37);
833833 assert!(parsed.members.iter().any(|member| {
834834 member.entry.name == "source" && member.entry.kind == EntryKind::Directory
수정tests/rust-archive-worker/main.rs+19-44
@@ -10,17 +10,21 @@ use zipelo_archive_worker::{
1010 protocol::*,
1111 wire::{Reader, Writer},
1212};
13추가: mod real_catalog;
14추가: use real_catalog::worker_catalog;
15추가:
1316static NEXT: AtomicU64 = AtomicU64::new(0);
1417struct Scratch(PathBuf);
1518impl Scratch {
1619 fn new() -> Self {
17삭제: let path = PathBuf::from(std::env::var_os("ZIPELO_TEST_WORK_DIR").expect("runner 작업 경로 필요"))
18삭제: .join("fixtures/rust-archive-worker")
19삭제: .join(format!(
20삭제: "{}-{}",
21삭제: std::process::id(),
22삭제: NEXT.fetch_add(1, Ordering::Relaxed)
23삭제: ));
20추가: let path =
21추가: PathBuf::from(std::env::var_os("ZIPELO_TEST_WORK_DIR").expect("runner 작업 경로 필요"))
22추가: .join("fixtures/rust-archive-worker")
23추가: .join(format!(
24추가: "{}-{}",
25추가: std::process::id(),
26추가: NEXT.fetch_add(1, Ordering::Relaxed)
27추가: ));
2428 fs::create_dir_all(path.parent().unwrap()).unwrap();
2529 let builder = fs::DirBuilder::new();
2630 #[cfg(unix)]
@@ -414,7 +418,7 @@ fn create_store_and_deflate_zip() {
414418 });
415419 assert_eq!(terminal(&e).outcome, Outcome::Completed, "{e:?}");
416420 let bytes = fs::read(s.0.join("result.zip")).unwrap();
417삭제: let parsed = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
421추가: let parsed = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
418422 assert_eq!(parsed.members[0].data, PAYLOAD);
419423 }
420424}
@@ -723,15 +727,7 @@ fn shallow_zip_parent_metadata_is_bounded() {
723727 .iter()
724728 .all(|n| n.split('/').count() <= archive::MAX_PATH_DEPTH)
725729 );
726삭제: assert!(
727삭제: archive::parse(
728삭제: &path_fixture_zip(&names),
729삭제: Limits::default(),
730삭제: false,
731삭제: &mut || Ok(())
732삭제: )
733삭제: .is_ok()
734삭제: );
730추가: assert!(worker_catalog(&path_fixture_zip(&names), Limits::default(), false, None).is_ok());
735731 assert_metadata_limit(&names);
736732}
737733
@@ -749,7 +745,7 @@ fn aggregate_archive_name_metadata_is_bounded() {
749745 let bytes = path_fixture_zip(&names);
750746 assert!((bytes.len() as u64) < Limits::default().input);
751747 assert!(matches!(
752삭제: archive::parse(&bytes, Limits::default(), false, &mut || Ok(())),
748추가: worker_catalog(&bytes, Limits::default(), false, None),
753749 Err(ErrorCode::Limit)
754750 ));
755751 assert_metadata_limit(&names);
@@ -787,7 +783,7 @@ fn zero_payload_gzip_is_not_tar() {
787783 for length in [512, 1024, 1536] {
788784 let scratch = Scratch::new();
789785 let bytes = zeros_gzip(length);
790삭제: let parsed = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
786추가: let parsed = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
791787 assert_eq!(parsed.format, Format::Gzip);
792788 let events = extract(
793789 &scratch,
@@ -1160,14 +1156,7 @@ fn empty_aes_members_and_random_salts_round_trip() {
11601156 )
11611157 .unwrap();
11621158 assert_ne!(a, b);
1163삭제: let decoded = archive::parse_with_password(
1164삭제: &a,
1165삭제: Limits::default(),
1166삭제: true,
1167삭제: Some(TEST_PASSWORD),
1168삭제: &mut || Ok(()),
1169삭제: )
1170삭제: .unwrap();
1159추가: let decoded = worker_catalog(&a, Limits::default(), true, Some(TEST_PASSWORD)).unwrap();
11711160 assert!(decoded.members[0].data.is_empty());
11721161}
11731162
@@ -1230,7 +1219,7 @@ fn seven_zip_lzma_lzma2_and_copy_interoperate() {
12301219 "libarchive-lzma2.7z",
12311220 ] {
12321221 let bytes = seven_fixture(name);
1233삭제: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(()))
1222추가: let catalog = worker_catalog(&bytes, Limits::default(), true, None)
12341223 .unwrap_or_else(|e| panic!("{name}: {e:?}"));
12351224 assert_eq!(catalog.format, Format::SevenZip);
12361225 assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(100), "{name}");
@@ -1251,7 +1240,7 @@ fn seven_zip_lzma_lzma2_and_copy_interoperate() {
12511240fn seven_zip_encoded_header_solid_and_empty_entries() {
12521241 let s = Scratch::new();
12531242 let bytes = seven_fixture("encoded-solid.7z");
1254삭제: let catalog = archive::parse(&bytes, Limits::default(), false, &mut || Ok(())).unwrap();
1243추가: let catalog = worker_catalog(&bytes, Limits::default(), false, None).unwrap();
12551244 assert_eq!(catalog.members.len(), 4);
12561245 let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
12571246 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
@@ -1268,7 +1257,7 @@ fn seven_zip_encoded_header_solid_and_empty_entries() {
12681257fn seven_zip_long_matches_and_lzma2_chunks() {
12691258 for name in ["long-match.7z", "lzma2-chunks.7z"] {
12701259 let bytes = seven_fixture(name);
1271삭제: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(()))
1260추가: let catalog = worker_catalog(&bytes, Limits::default(), true, None)
12721261 .unwrap_or_else(|e| panic!("{name}: {e:?}"));
12731262 if name == "long-match.7z" {
12741263 assert_eq!(catalog.members[0].data, SEVEN_PAYLOAD.repeat(10000));
@@ -1445,20 +1434,6 @@ fn seven_zip_limits_truncation_and_existing_files_are_preserved() {
14451434 assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
14461435}
14471436#[test]
1448삭제: fn seven_zip_parser_honors_cancellation_checkpoints() {
1449삭제: let bytes = seven_fixture("long-match.7z");
1450삭제: let mut calls = 0;
1451삭제: let result = archive::parse(&bytes, Limits::default(), true, &mut || {
1452삭제: calls += 1;
1453삭제: if calls >= 5 {
1454삭제: Err(ErrorCode::None)
1455삭제: } else {
1456삭제: Ok(())
1457삭제: }
1458삭제: });
1459삭제: assert!(matches!(result, Err(ErrorCode::None)));
1460삭제: }
1461삭제: #[test]
14621437fn pr64_malicious_corpus_is_rejected_without_writes() {
14631438 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14641439 .join("../../tests/malicious-archive-fixtures/fixtures");
추가tests/rust-archive-worker/real_catalog.rs+76-0
@@ -0,0 +1,76 @@
1추가: use super::*;
2추가:
3추가: pub(super) fn worker_catalog(
4추가: bytes: &[u8],
5추가: limits: Limits,
6추가: decode: bool,
7추가: password: Option<&[u8]>,
8추가: ) -> Result<archive::Catalog, ErrorCode> {
9추가: let scratch = Scratch::new();
10추가: fs::write(scratch.0.join("input"), bytes).unwrap();
11추가: let events = execute(Start {
12추가: action: Action::List {
13추가: archive: scratch.path("input"),
14추가: },
15추가: limits,
16추가: });
17추가: if terminal(&events).outcome != Outcome::Completed {
18추가: return Err(terminal(&events).error);
19추가: }
20추가: let list_id = events
21추가: .iter()
22추가: .find_map(|event| match event {
23추가: Message::ListEnd { list_id, .. } => Some(list_id.clone()),
24추가: _ => None,
25추가: })
26추가: .expect("작업자의 목록 식별자가 필요함");
27추가: let entries: Vec<_> = events
28추가: .into_iter()
29추가: .filter_map(|event| match event {
30추가: Message::Entry(entry) => Some(entry),
31추가: _ => None,
32추가: })
33추가: .collect();
34추가: if decode {
35추가: let builder = fs::DirBuilder::new();
36추가: #[cfg(unix)]
37추가: let mut builder = builder;
38추가: #[cfg(unix)]
39추가: {
40추가: use std::os::unix::fs::DirBuilderExt;
41추가: builder.mode(0o700);
42추가: }
43추가: builder.create(scratch.0.join("output")).unwrap();
44추가: let action = Action::Extract {
45추가: archive: scratch.path("input"),
46추가: destination: scratch.path("output"),
47추가: selection: Selection::All,
48추가: gzip_output_name: (list_id.format == Format::Gzip).then(|| entries[0].name.clone()),
49추가: list_id: Some(list_id.clone()),
50추가: };
51추가: let start = Start { action, limits };
52추가: let extracted = if let Some(password) = password {
53추가: interactive(start, |id, _, _| password_reply(id, password))
54추가: } else {
55추가: execute(start)
56추가: };
57추가: if terminal(&extracted).outcome != Outcome::Completed {
58추가: return Err(terminal(&extracted).error);
59추가: }
60추가: }
61추가: let members = entries
62추가: .into_iter()
63추가: .map(|entry| {
64추가: let data = if decode && entry.kind == EntryKind::File {
65추가: fs::read(scratch.0.join("output").join(&entry.name)).unwrap()
66추가: } else {
67추가: Vec::new()
68추가: };
69추가: archive::Member { entry, data }
70추가: })
71추가: .collect();
72추가: Ok(archive::Catalog {
73추가: format: list_id.format,
74추가: members,
75추가: })
76추가: }
수정tests/rust-archive-worker/recovery.rs+1-1
@@ -141,7 +141,7 @@ fn six_damaged_corpora_preserve_source_and_independent_expected_hashes() {
141141 assert_eq!(t.created_count, 1);
142142 assert_eq!(t.publication, Publication::Complete);
143143 let bytes = fs::read(s.0.join("recovered.zip")).unwrap();
144삭제: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
144추가: let catalog = worker_catalog(&bytes, Limits::default(), true, None).unwrap();
145145 assert_eq!(catalog.members.len(), count);
146146 for member in &catalog.members {
147147 let (_, sha) = expected
수정tests/rust-archive-worker/recovery_checks.rs+30-0
@@ -410,3 +410,33 @@ fn central_zip64_fields_and_extra_remain_unsupported() {
410410 Err(ErrorCode::UnsupportedFeature)
411411 ));
412412}
413추가:
414추가: #[test]
415추가: fn central_rejects_extra_crossing_only_the_next_local_file() {
416추가: let mut damaged = include_bytes!("../zip-recovery-fixtures/control.zip").to_vec();
417추가: let cd = u32at(&damaged, damaged.len() - 6) as usize;
418추가: let second = cd
419추가: + 46
420추가: + u16at(&damaged, cd + 28) as usize
421추가: + u16at(&damaged, cd + 30) as usize
422추가: + u16at(&damaged, cd + 32) as usize;
423추가: let next_local = u32at(&damaged, second + 42) as usize;
424추가: let names_end = 30 + u16at(&damaged, 26) as usize;
425추가: let extra = next_local - names_end + 1;
426추가: let data_start = names_end + extra;
427추가: assert!(data_start > next_local);
428추가: assert!(data_start + u32at(&damaged, cd + 20) as usize <= cd);
429추가: damaged[28..30].copy_from_slice(&(extra as u16).to_le_bytes());
430추가: let scratch = Scratch::new(&damaged);
431추가: let mut source = File::open(scratch.path()).unwrap();
432추가: assert!(matches!(
433추가: central(
434추가: &mut source,
435추가: damaged.len() as u64,
436추가: Limits::default(),
437추가: &mut || Ok(())
438추가: ),
439추가: Err(ErrorCode::Integrity)
440추가: ));
441추가: assert_eq!(std::fs::read(scratch.path()).unwrap(), damaged);
442추가: }
수정tests/rust-archive-worker/spool_fallback.rs+103-73
@@ -59,19 +59,31 @@ impl Case {
5959 self.archive_names.sort();
6060 (self.scratch.path("archive/split.7z.001"), originals)
6161 }
62추가: fn library(&self) -> PathBuf {
63추가: let library = self.scratch.0.join("location.so");
64추가: if !library.exists() {
65추가: assert!(
66추가: Command::new("cc")
67추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
68추가: .arg(
69추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
70추가: .join("../../tests/rust-archive-worker/spool_location_fault.c")
71추가: )
72추가: .args(["-ldl", "-o"])
73추가: .arg(&library)
74추가: .status()
75추가: .unwrap()
76추가: .success()
77추가: );
78추가: }
79추가: library
80추가: }
6281 fn run(&self, action: Action, phase: &str, mask: u8, named: bool) -> Vec<Message> {
6382 let s = &self.scratch;
6483 let mut command = s.worker();
6584 command
6685 .env("XDG_CACHE_HOME", s.0.join("cache"))
67삭제: .env(
68삭제: "TMPDIR",
69삭제: if phase == "real" {
70삭제: PathBuf::from(std::env::var_os("ZIPELO_SPOOL_REAL_TMP").unwrap())
71삭제: } else {
72삭제: s.0.join("system")
73삭제: },
74삭제: )
86추가: .env("TMPDIR", s.0.join("system"))
7587 .env("HOME", &s.0);
7688 if phase == "home" {
7789 command.env_remove("XDG_CACHE_HOME");
@@ -87,31 +99,14 @@ impl Case {
8799 },
88100 );
89101 }
90삭제: if phase != "real" {
91삭제: let library = s.0.join("location.so");
92삭제: if !library.exists() {
93삭제: assert!(
94삭제: Command::new("cc")
95삭제: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
96삭제: .arg(
97삭제: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
98삭제: .join("../../tests/rust-archive-worker/spool_location_fault.c")
99삭제: )
100삭제: .args(["-ldl", "-o"])
101삭제: .arg(&library)
102삭제: .status()
103삭제: .unwrap()
104삭제: .success()
105삭제: );
106삭제: }
107삭제: command
108삭제: .env("LD_PRELOAD", library)
109삭제: .env("ZIPELO_SPOOL_PHASE", phase)
110삭제: .env("ZIPELO_SPOOL_MASK", mask.to_string())
111삭제: .env("ZIPELO_SPOOL_TRACE", s.0.join("trace"));
112삭제: if named {
113삭제: command.env("ZIPELO_SPOOL_NAMED", "1");
114삭제: }
102추가: let library = self.library();
103추가: command
104추가: .env("LD_PRELOAD", library)
105추가: .env("ZIPELO_SPOOL_PHASE", phase)
106추가: .env("ZIPELO_SPOOL_MASK", mask.to_string())
107추가: .env("ZIPELO_SPOOL_TRACE", s.0.join("trace"));
108추가: if named {
109추가: command.env("ZIPELO_SPOOL_NAMED", "1");
115110 }
116111 let mut child = Running(
117112 command
@@ -689,45 +684,80 @@ fn source_change_during_direct_read_prevents_success() {
689684}
690685
691686#[test]
692삭제: #[ignore = "별도 VM의 작은 tmpfs 경로를 ZIPELO_SPOOL_REAL_TMP로 지정해야 함"]
693삭제: fn actual_tmpfs_quota_lists_and_previews_large_zip_and_seven_zip() {
694삭제: let path = PathBuf::from(std::env::var_os("ZIPELO_SPOOL_REAL_TMP").unwrap());
695삭제: let filesystem = Command::new("stat")
696삭제: .args(["-f", "-c", "%T"])
697삭제: .arg(&path)
698삭제: .output()
699삭제: .unwrap();
700삭제: assert_eq!(
701삭제: String::from_utf8(filesystem.stdout).unwrap().trim(),
702삭제: "tmpfs"
703삭제: );
704삭제: let capacity = Command::new("stat")
705삭제: .args(["-f", "-c", "%S %b"])
706삭제: .arg(&path)
707삭제: .output()
708삭제: .unwrap();
709삭제: let fields: Vec<u64> = String::from_utf8(capacity.stdout)
710삭제: .unwrap()
711삭제: .split_whitespace()
712삭제: .map(|value| value.parse().unwrap())
713삭제: .collect();
714삭제: let bytes = fields[0] * fields[1];
715삭제: assert!(bytes > 0 && bytes < 16 * 1024 * 1024, "{bytes}");
716삭제: let probe = path.join("capacity-probe");
717삭제: let error = fs::write(&probe, vec![0; bytes as usize + 4096]).unwrap_err();
718삭제: assert_eq!(error.kind(), std::io::ErrorKind::StorageFull);
719삭제: fs::remove_file(probe).unwrap();
720삭제: let c = Case::new();
721삭제: for format in ["zip", "7z"] {
722삭제: c.assert_preview(format, "real", 0, false);
687추가: fn small_temporary_quota_lists_and_previews_large_zip_and_seven_zip() {
688추가: for named in [false, true] {
689추가: let c = Case::new();
690추가: let library = c.library();
691추가: let probe = Command::new("python3")
692추가: .arg("-B")
693추가: .arg("-c")
694추가: .arg(
695추가: r#"
696추가: import errno, os, sys
697추가: from pathlib import Path
698추가: root = Path(sys.argv[1])
699추가: a = os.open(root / "quota-a", os.O_CREAT | os.O_RDWR, 0o600)
700추가: b = os.open(root / "quota-b", os.O_CREAT | os.O_RDWR, 0o600)
701추가: duplicate = os.dup(a)
702추가: try:
703추가: assert os.write(a, bytes(1024 * 1024)) == 1024 * 1024
704추가: assert os.write(b, bytes(2 * 1024 * 1024)) == 1024 * 1024
705추가: try:
706추가: os.write(b, b"x")
707추가: except OSError as error:
708추가: assert error.errno == errno.ENOSPC
709추가: else:
710추가: raise AssertionError("공유 임시 용량 한도가 적용되지 않음")
711추가: os.close(duplicate)
712추가: duplicate = -1
713추가: os.close(a)
714추가: a = -1
715추가: (root / "quota-a").unlink()
716추가: assert os.write(b, b"x") == 1
717추가: finally:
718추가: if duplicate >= 0:
719추가: os.close(duplicate)
720추가: if a >= 0:
721추가: os.close(a)
722추가: os.close(b)
723추가: for name in ["quota-a", "quota-b"]:
724추가: (root / name).unlink(missing_ok=True)
725추가: "#,
726추가: )
727추가: .arg(c.scratch.0.join("system"))
728추가: .env("LD_PRELOAD", library)
729추가: .env("ZIPELO_SPOOL_PHASE", "tiny-tmpfs")
730추가: .env("ZIPELO_SPOOL_TRACE", c.scratch.0.join("trace"))
731추가: .output()
732추가: .unwrap();
733추가: assert!(probe.status.success(), "{:?}", probe.stderr);
734추가: assert!(
735추가: fs::read_to_string(c.scratch.0.join("trace"))
736추가: .unwrap()
737추가: .contains('F')
738추가: );
739추가: for format in ["zip", "7z"] {
740추가: c.assert_preview(format, "tiny-tmpfs", 0, named);
741추가: }
742추가: assert!(
743추가: Command::new("python3")
744추가: .arg("-B")
745추가: .arg(
746추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
747추가: .join("../../tests/rust-archive-worker/spool_fallback_cases.py")
748추가: )
749추가: .arg(&c.scratch.0)
750추가: .arg("non-solid")
751추가: .status()
752추가: .unwrap()
753추가: .success()
754추가: );
755추가: for format in ["zip", "7z"] {
756추가: c.assert_preview(format, "tiny-tmpfs", 3, named);
757추가: }
758추가: let trace = fs::read_to_string(c.scratch.0.join("trace")).unwrap();
759추가: assert!(trace.contains('2'), "{trace}");
760추가: assert_eq!(fs::read_dir(c.scratch.0.join("system")).unwrap().count(), 0);
761추가: c.clean();
723762 }
724삭제: assert_eq!(fs::read_dir(path).unwrap().count(), 0);
725삭제: assert_eq!(
726삭제: fs::metadata(c.scratch.0.join("cache/zipelo"))
727삭제: .unwrap()
728삭제: .permissions()
729삭제: .mode()
730삭제: & 0o777,
731삭제: 0o700
732삭제: );
733763}
수정tests/rust-archive-worker/spool_location_fault.c+61-0
@@ -1,5 +1,6 @@
11#define _GNU_SOURCE
22#include <dlfcn.h>
3추가: #include <dirent.h>
34#include <errno.h>
45#include <fcntl.h>
56#include <stdarg.h>
@@ -60,10 +61,50 @@ static void trace(int at) {
6061 close(fd);
6162 }
6263}
64추가: static unsigned long long temporary_usage(void) {
65추가: DIR *directory = opendir("/proc/self/fd");
66추가: if (!directory) _exit(98);
67추가: struct dirent *entry;
68추가: struct stat seen[256];
69추가: size_t count = 0;
70추가: unsigned long long used = 0;
71추가: while ((entry = readdir(directory))) {
72추가: if (entry->d_name[0] == '.') continue;
73추가: int fd = atoi(entry->d_name);
74추가: char path[4096];
75추가: struct stat value;
76추가: if (descriptor(fd, path, sizeof(path)) != 2 || fstat(fd, &value)
77추가: || !S_ISREG(value.st_mode)) continue;
78추가: size_t i;
79추가: for (i = 0; i < count; i++) {
80추가: if (seen[i].st_dev == value.st_dev && seen[i].st_ino == value.st_ino) break;
81추가: }
82추가: if (i < count) continue;
83추가: if (count == 256) _exit(97);
84추가: seen[count++] = value;
85추가: used += value.st_size;
86추가: }
87추가: closedir(directory);
88추가: return used;
89추가: }
90추가: static void exhausted(void) {
91추가: const char *path = getenv("ZIPELO_SPOOL_TRACE");
92추가: if (!path) return;
93추가: int fd = original_openat(AT_FDCWD, path, O_CREAT | O_WRONLY | O_APPEND, 0600);
94추가: if (fd >= 0) {
95추가: original_write(fd, "F", 1);
96추가: close(fd);
97추가: }
98추가: }
99추가: #define TEMPORARY_CAPACITY (2ULL * 1024 * 1024)
63100static int reject(int at, int flags) {
64101 if ((flags & O_TMPFILE) != O_TMPFILE && !(flags & O_CREAT)) return 0;
65102 trace(at);
66103 const char *phase = getenv("ZIPELO_SPOOL_PHASE");
104추가: if (affected(at) && at < 2 && phase && !strcmp(phase, "tiny-tmpfs")) {
105추가: errno = EDQUOT;
106추가: return 1;
107추가: }
67108 if (affected(at) && phase && (!strcmp(phase, "create") || !strcmp(phase, "denied"))) {
68109 errno = !strcmp(phase, "denied") ? EACCES : EDQUOT;
69110 return 1;
@@ -115,6 +156,20 @@ ssize_t write(int fd, const void *bytes, size_t count) {
115156 char path[4096];
116157 int at = descriptor(fd, path, sizeof(path));
117158 const char *phase = getenv("ZIPELO_SPOOL_PHASE");
159추가: if (phase && !strcmp(phase, "tiny-tmpfs") && at == 2) {
160추가: struct stat value;
161추가: off_t position = lseek(fd, 0, SEEK_CUR);
162추가: if (position < 0 || fstat(fd, &value)) _exit(96);
163추가: unsigned long long used = temporary_usage();
164추가: unsigned long long room = used < TEMPORARY_CAPACITY ? TEMPORARY_CAPACITY - used : 0;
165추가: unsigned long long end = (unsigned long long)value.st_size + room;
166추가: if ((unsigned long long)position >= end) {
167추가: exhausted();
168추가: errno = ENOSPC;
169추가: return -1;
170추가: }
171추가: if (count > end - position) count = end - position;
172추가: }
118173 int stage = phase && !strcmp(phase, "stage-write") && fd != snapshot_fd;
119174 if (affected(at) && phase && (stage || !strcmp(phase, "write")
120175 || !strcmp(phase, "changed") || !strcmp(phase, "io"))) {
@@ -140,6 +195,12 @@ int fstatvfs(int fd, struct statvfs *value) {
140195 value->f_frsize = 1;
141196 value->f_bavail = 65536;
142197 }
198추가: if (!result && at == 2 && phase && !strcmp(phase, "tiny-tmpfs")) {
199추가: unsigned long long used = temporary_usage();
200추가: value->f_frsize = 1;
201추가: value->f_blocks = TEMPORARY_CAPACITY;
202추가: value->f_bavail = value->f_bfree = used < TEMPORARY_CAPACITY ? TEMPORARY_CAPACITY - used : 0;
203추가: }
143204 return result;
144205}
145206
수정tests/rust-archive-worker/streaming_bounds.rs+24-0
@@ -122,3 +122,27 @@ fn descriptor_width_uses_sizes_and_crc() {
122122 );
123123 }
124124}
125추가:
126추가: #[test]
127추가: fn seven_zip_parser_honors_cancellation_checkpoints() {
128추가: let bytes = include_bytes!("fixtures/7z/long-match.7z");
129추가: let mut source = spool::temporary().unwrap();
130추가: source.write_all(bytes).unwrap();
131추가: let mut calls = 0;
132추가: let result = Catalog::open(
133추가: &mut source,
134추가: bytes.len() as u64,
135추가: Limits::default(),
136추가: true,
137추가: None,
138추가: &mut || {
139추가: calls += 1;
140추가: if calls >= 5 {
141추가: Err(ErrorCode::None)
142추가: } else {
143추가: Ok(())
144추가: }
145추가: },
146추가: );
147추가: assert!(matches!(result, Err(ErrorCode::None)));
148추가: }
추가tests/rust-archive-worker/zip_extra.rs+129-0
@@ -0,0 +1,129 @@
1추가: use super::*;
2추가:
3추가: fn field(tag: u16, value: &[u8]) -> Vec<u8> {
4추가: [
5추가: tag.to_le_bytes().as_slice(),
6추가: &(value.len() as u16).to_le_bytes(),
7추가: value,
8추가: ]
9추가: .concat()
10추가: }
11추가:
12추가: #[test]
13추가: fn truncated_headers_and_values_are_rejected_by_every_policy() {
14추가: for policy in [
15추가: Policy::Streaming,
16추가: Policy::Classic,
17추가: Policy::Recovery,
18추가: Policy::Names,
19추가: ] {
20추가: for bytes in [vec![0], vec![0, 0], vec![0, 0, 0], vec![2, 0, 1, 0]] {
21추가: assert!(matches!(parse(&bytes, policy), Err(ErrorCode::Integrity)));
22추가: }
23추가: assert!(parse(&field(2, &[]), policy).is_ok());
24추가: }
25추가: }
26추가:
27추가: #[test]
28추가: fn zip64_is_borrowed_only_for_normal_streaming() {
29추가: let bytes = field(1, &[0; 16]);
30추가: assert_eq!(
31추가: parse(&bytes, Policy::Streaming).unwrap().zip64,
32추가: Some(&bytes[4..])
33추가: );
34추가: for policy in [Policy::Classic, Policy::Recovery] {
35추가: assert!(matches!(
36추가: parse(&bytes, policy),
37추가: Err(ErrorCode::UnsupportedFeature)
38추가: ));
39추가: }
40추가: assert!(matches!(
41추가: parse(
42추가: &[bytes.as_slice(), bytes.as_slice()].concat(),
43추가: Policy::Streaming
44추가: ),
45추가: Err(ErrorCode::Integrity)
46추가: ));
47추가: for tag in [1, 0x0017, 0x0018] {
48추가: assert!(matches!(
49추가: parse(&field(tag, &[]), Policy::Recovery),
50추가: Err(ErrorCode::UnsupportedFeature)
51추가: ));
52추가: }
53추가: }
54추가:
55추가: #[test]
56추가: fn aes_policy_keeps_support_and_duplicate_checks() {
57추가: let value = [2, 0, b'A', b'E', 3, 8, 0];
58추가: let bytes = field(0x9901, &value);
59추가: for policy in [Policy::Streaming, Policy::Classic] {
60추가: assert_eq!(
61추가: parse(&bytes, policy).unwrap().aes,
62추가: Some(AesExtra {
63추가: version: 2,
64추가: method: 8
65추가: })
66추가: );
67추가: assert!(matches!(
68추가: parse(&[bytes.as_slice(), bytes.as_slice()].concat(), policy),
69추가: Err(ErrorCode::Integrity)
70추가: ));
71추가: assert!(matches!(
72추가: parse(&field(0x9901, &value[..6]), policy),
73추가: Err(ErrorCode::Integrity)
74추가: ));
75추가: let mut unsupported = value;
76추가: unsupported[4] = 2;
77추가: assert!(matches!(
78추가: parse(&field(0x9901, &unsupported), policy),
79추가: Err(ErrorCode::UnsupportedFeature)
80추가: ));
81추가: }
82추가: assert!(parse(&bytes, Policy::Recovery).unwrap().aes.is_none());
83추가: }
84추가:
85추가: #[test]
86추가: fn unicode_and_aes_fields_can_share_the_same_extra() {
87추가: let bytes = [
88추가: field(0x7075, &[1, 0, 0, 0, 0]),
89추가: field(0x9901, &[2, 0, b'A', b'E', 3, 0, 0]),
90추가: ]
91추가: .concat();
92추가: assert_eq!(
93추가: parse(&bytes, Policy::Names).unwrap().unicode,
94추가: Some(&bytes[4..9])
95추가: );
96추가: assert!(parse(&bytes, Policy::Streaming).unwrap().aes.is_some());
97추가: assert!(matches!(
98추가: parse(&field(0x7075, &[0; 4]), Policy::Names),
99추가: Err(ErrorCode::Integrity)
100추가: ));
101추가: }
102추가:
103추가: #[test]
104추가: fn mixed_invalid_fields_keep_error_precedence() {
105추가: let unsupported_aes = field(0x9901, &[3, 0, b'A', b'E', 3, 0, 0]);
106추가: let duplicate_zip64 = [field(1, &[]), field(1, &[])].concat();
107추가: let extra = [unsupported_aes.as_slice(), duplicate_zip64.as_slice()].concat();
108추가: assert!(matches!(
109추가: parse(&extra, Policy::Streaming),
110추가: Err(ErrorCode::Integrity)
111추가: ));
112추가: assert!(matches!(
113추가: parse(&extra, Policy::Classic),
114추가: Err(ErrorCode::UnsupportedFeature)
115추가: ));
116추가: let truncated = [unsupported_aes.as_slice(), &[2, 0, 1, 0]].concat();
117추가: assert!(matches!(
118추가: parse(&truncated, Policy::Streaming),
119추가: Err(ErrorCode::Integrity)
120추가: ));
121추가: assert!(matches!(
122추가: parse(&truncated, Policy::Classic),
123추가: Err(ErrorCode::UnsupportedFeature)
124추가: ));
125추가: assert!(matches!(
126추가: parse(&[1, 0, 8, 0], Policy::Recovery),
127추가: Err(ErrorCode::UnsupportedFeature)
128추가: ));
129추가: }
수정tests/rust-archive-worker/zip_names.rs+20-26
@@ -107,20 +107,11 @@ fn listed_names(bytes: &[u8]) -> std::result::Result<Vec<String>, ErrorCode> {
107107 .collect())
108108}
109109
110삭제: /// 스트리밍 목록과 메모리 파서가 같은 이름 또는 같은 오류를 내는지 확인함.
111삭제: fn names_agree(bytes: &[u8]) -> std::result::Result<Vec<String>, ErrorCode> {
112삭제: let streamed = listed_names(bytes);
113삭제: let parsed = archive::parse(bytes, Limits::default(), false, &mut || Ok(()))
114삭제: .map(|c| c.members.into_iter().map(|m| m.entry.name).collect());
115삭제: assert_eq!(streamed, parsed);
116삭제: streamed
117삭제: }
118삭제:
119110#[test]
120111fn infozip_utf8_names_without_flag_list_and_extract() {
121삭제: assert_eq!(names_agree(KOREAN).unwrap(), ["README.md", "회의록.txt"]);
112추가: assert_eq!(listed_names(KOREAN).unwrap(), ["README.md", "회의록.txt"]);
122113 assert_eq!(
123삭제: names_agree(KOREAN_TREE).unwrap(),
114추가: listed_names(KOREAN_TREE).unwrap(),
124115 ["README.md", "회의록.txt", "폴더", "폴더/메모.txt"]
125116 );
126117 for bytes in [KOREAN, KOREAN_TREE] {
@@ -149,7 +140,7 @@ fn infozip_multi_entry_zipcrypto_trees_list_and_extract() {
149140 (ZIPCRYPTO_ASCII_TREE, "docs/notes.txt"),
150141 (ZIPCRYPTO_KOREAN_TREE, "폴더/메모.txt"),
151142 ] {
152삭제: let names = names_agree(bytes).unwrap();
143추가: let names = listed_names(bytes).unwrap();
153144 assert!(names.iter().any(|n| n == file), "{names:?}");
154145 let s = Scratch::new();
155146 let events = interactive(encrypted_start(&s, bytes), |id, _, purpose| {
@@ -168,7 +159,7 @@ fn unicode_path_extra_is_used_only_when_its_crc_matches() {
168159 let cp949 = b"\xc8\xb8\xc0\xc7\xb7\xcf.txt";
169160 let extra = unicode_path(cp949, "회의록.txt");
170161 assert_eq!(
171삭제: names_agree(&single_entry_zip(cp949, 0, &extra, b"hi\n")).unwrap(),
162추가: listed_names(&single_entry_zip(cp949, 0, &extra, b"hi\n")).unwrap(),
172163 ["회의록.txt"]
173164 );
174165 let s = Scratch::new();
@@ -180,24 +171,24 @@ fn unicode_path_extra_is_used_only_when_its_crc_matches() {
180171 // CRC가 다른 확장 필드는 이름이 바뀐 뒤 남은 낡은 값이므로 무시함.
181172 let stale = unicode_path(b"old.txt", "회의록.txt");
182173 assert_eq!(
183삭제: names_agree(&single_entry_zip(b"new.txt", 0, &stale, b"hi\n")).unwrap(),
174추가: listed_names(&single_entry_zip(b"new.txt", 0, &stale, b"hi\n")).unwrap(),
184175 ["new.txt"]
185176 );
186177 let stale = unicode_path(b"other", "회의록.txt");
187178 assert_eq!(
188삭제: names_agree(&single_entry_zip(cp949, 0, &stale, b"hi\n")),
179추가: listed_names(&single_entry_zip(cp949, 0, &stale, b"hi\n")),
189180 Err(ErrorCode::UnsupportedFeature)
190181 );
191182 // UTF-8 플래그가 있으면 이름 자체가 UTF-8이므로 확장 필드를 보지 않음.
192183 let ignored = unicode_path("a.txt".as_bytes(), "b.txt");
193184 assert_eq!(
194삭제: names_agree(&single_entry_zip(b"a.txt", 0x0800, &ignored, b"hi\n")).unwrap(),
185추가: listed_names(&single_entry_zip(b"a.txt", 0x0800, &ignored, b"hi\n")).unwrap(),
195186 ["a.txt"]
196187 );
197188}
198189
199190fn assert_rejected_without_output(bytes: &[u8], error: ErrorCode) {
200삭제: assert_eq!(names_agree(bytes), Err(error));
191추가: assert_eq!(listed_names(bytes), Err(error));
201192 let s = Scratch::new();
202193 let events = extract(&s, bytes, None, Selection::All, None, Limits::default());
203194 let result = terminal(&events);
@@ -223,7 +214,10 @@ fn converted_names_colliding_with_other_paths_are_rejected_before_writes() {
223214 let first = b"first.txt";
224215 let second = b"second.txt";
225216 let original = stored_entries_zip(&[(first, 0, &[], b"first"), (second, 0, &[], b"second")]);
226삭제: assert_eq!(names_agree(&original).unwrap(), ["first.txt", "second.txt"]);
217추가: assert_eq!(
218추가: listed_names(&original).unwrap(),
219추가: ["first.txt", "second.txt"]
220추가: );
227221 for (first_name, second_name) in [
228222 ("회의록.txt", "회의록.txt"),
229223 ("폴더/Memo.txt", "폴더/memo.txt"),
@@ -236,7 +230,7 @@ fn converted_names_colliding_with_other_paths_are_rejected_before_writes() {
236230 (second.as_slice(), &second_extra, second_name),
237231 ] {
238232 let bytes = single_entry_zip(raw, 0, extra, b"hi\n");
239삭제: assert_eq!(names_agree(&bytes).unwrap(), [name]);
233추가: assert_eq!(listed_names(&bytes).unwrap(), [name]);
240234 }
241235 let bytes = stored_entries_zip(&[
242236 (first, 0, &first_extra, b"first"),
@@ -251,26 +245,26 @@ fn legacy_and_hostile_names_stay_rejected() {
251245 let cp949 = b"\xc8\xb8\xc0\xc7\xb7\xcf.txt";
252246 // 코드 페이지를 추측하지 않음.
253247 assert_eq!(
254삭제: names_agree(&single_entry_zip(cp949, 0, &[], b"hi\n")),
248추가: listed_names(&single_entry_zip(cp949, 0, &[], b"hi\n")),
255249 Err(ErrorCode::UnsupportedFeature)
256250 );
257251 // UTF-8 플래그와 맞지 않는 이름은 손상으로 봄.
258252 assert_eq!(
259삭제: names_agree(&single_entry_zip(cp949, 0x0800, &[], b"hi\n")),
253추가: listed_names(&single_entry_zip(cp949, 0x0800, &[], b"hi\n")),
260254 Err(ErrorCode::Integrity)
261255 );
262256 // 확장 필드로 들어온 이름도 같은 경로 검사를 거침.
263257 for hostile in ["../escape.txt", "/absolute.txt", "C:drive.txt", "CON.txt"] {
264258 let extra = unicode_path(b"safe.txt", hostile);
265259 assert_eq!(
266삭제: names_agree(&single_entry_zip(b"safe.txt", 0, &extra, b"hi\n")),
260추가: listed_names(&single_entry_zip(b"safe.txt", 0, &extra, b"hi\n")),
267261 Err(ErrorCode::UnsafePath),
268262 "{hostile}"
269263 );
270264 }
271265 for hostile in ["../회의록.txt", "폴더/../../x"] {
272266 assert_eq!(
273삭제: names_agree(&single_entry_zip(hostile.as_bytes(), 0, &[], b"hi\n")),
267추가: listed_names(&single_entry_zip(hostile.as_bytes(), 0, &[], b"hi\n")),
274268 Err(ErrorCode::UnsafePath),
275269 "{hostile}"
276270 );
@@ -280,20 +274,20 @@ fn legacy_and_hostile_names_stay_rejected() {
280274 let len = broken.len();
281275 broken[len - 1] = 0xff;
282276 assert_eq!(
283삭제: names_agree(&single_entry_zip(b"safe.txt", 0, &broken, b"hi\n")),
277추가: listed_names(&single_entry_zip(b"safe.txt", 0, &broken, b"hi\n")),
284278 Err(ErrorCode::Integrity)
285279 );
286280 let mut short = 0x7075u16.to_le_bytes().to_vec();
287281 short.extend([4, 0, 1, 0, 0, 0]);
288282 assert_eq!(
289삭제: names_agree(&single_entry_zip(b"safe.txt", 0, &short, b"hi\n")),
283추가: listed_names(&single_entry_zip(b"safe.txt", 0, &short, b"hi\n")),
290284 Err(ErrorCode::Integrity)
291285 );
292286 // APPNOTE 4.6.9에 따라 모르는 버전의 확장 필드는 무시함.
293287 let mut version = unicode_path(b"safe.txt", "x");
294288 version[4] = 2;
295289 assert_eq!(
296삭제: names_agree(&single_entry_zip(b"safe.txt", 0, &version, b"hi\n")).unwrap(),
290추가: listed_names(&single_entry_zip(b"safe.txt", 0, &version, b"hi\n")).unwrap(),
297291 ["safe.txt"]
298292 );
299293}