team-ljyzipelo

공개

Merge pull request #84 from Team-LJY/fix/zip-folder-input

폴더 입력과 빈 폴더를 ZIP 생성에 포함
작성자
LeeJunyoung
작성 시각
커밋
75dc876a5b5330be931f76bf7be9870dd7d35035
이 시점의 파일 보기

변경된 파일 10개

+835-64
수정experiments/rust-archive-worker/README.md+6-0
@@ -48,6 +48,12 @@ revision 2의 기존 필드와 오류 tag 0~12 및 입력/출력 기본 한도
4848
49497z의 Copy/LZMA/LZMA2 입력과 solid 출력은 고정 버퍼와 임시 파일로 처리합니다. 모든 폴더와 하위 스트림의 CRC와 크기 검증이 끝난 뒤 기존 게시 경로를 사용합니다. ZIP 생성의 압축 및 AES 처리도 64 KiB 버퍼를 사용하며 여유 공간 사전 검사와 실제 쓰기의 DiskFull 구분을 적용합니다. 공간 예약을 보장하지 않으므로 다른 프로세스와의 경쟁으로 쓰기가 실패할 수 있습니다.
5050
51추가: ## ZIP 생성 입력
52추가:
53추가: 원본에 일반 파일과 폴더를 함께 지정할 수 있습니다. 각 archive_name을 최상위 이름으로 쓰고 폴더 안의 상대 경로와 빈 폴더를 보존합니다. 재귀 수집된 파일과 폴더 모두 항목 수 한도에 포함하며 파일 크기 합계에는 기존 16 GiB 기본 한도를 적용합니다. 이름 충돌과 한도는 암호 요청 전에 검사합니다.
54추가:
55추가: 심볼릭 링크, Windows reparse point와 특수 파일은 건너뛰거나 따라가지 않고 작업 전체를 거부합니다. 열린 디렉터리 기준으로 수집하고 파일은 검증한 핸들에서 캡처하며, 감지된 원본 교체나 변경은 게시 전 SourceChanged로 끝납니다. 전체 폴더 트리의 원자적 스냅샷을 보장하지는 않습니다. AES-256은 파일 내용에 적용하고 디렉터리 항목은 0바이트 비암호화 항목으로 기록합니다.
56추가:
5157## 공유 codec
5258
5359`protocol.rs`는 요청과 이벤트 타입, `wire.rs`는 LE codec이며 비밀 값이 담긴 프레임 버퍼는 zeroize로 정리합니다. 앱은 이 라이브러리의 타입과 Reader/Writer를 사용할 수 있습니다. `contract.json`은 합의한 revision 2 원문입니다.
수정experiments/rust-archive-worker/contract.json+8-0
@@ -184,5 +184,13 @@
184184 "mapping": "Insufficient preflight space and StorageFull I/O failures return DiskFull 13. Windows ERROR_HANDLE_DISK_FULL 39 and ERROR_DISK_FULL 112 also map to DiskFull. Query failure, permission errors and other I/O failures return Io 8. No error classification by localized detail text.",
185185 "detail": "디스크 여유 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요",
186186 "publication": "Keep existing publication, durability and cleanup semantics. DiskFull does not imply rollback or absence of previously published outputs."
187추가: },
188추가: "create_zip_sources": {
189추가: "agreement": "Proposed semantic extension under manager task 82093f56-73b7-4be4-ba6d-2597ffc2c6f7; frontend joint agreement is pending. Revision 2 fields, encoding, numeric quotas and error tags are unchanged.",
190추가: "roots": "Each source may be a regular file or directory. archive_name names that root inside the ZIP; directory descendants retain relative paths and every directory, including empty directories, gets a trailing-slash ZIP entry.",
191추가: "links": "Reject the whole job with UnsafePath for symbolic links, Windows reparse points, special files or unsafe/non-UTF-8 descendant names. Do not skip entries or follow external links. Open each path component without following links; enumerate pinned directories.",
192추가: "limits": "All expanded file and directory entries count toward entries (default 10000). Only file logical bytes count toward min(input,output), default output 16 GiB. Preserve 8 MiB metadata and 64-component name limits. Validate the complete plan and case-insensitive/path-prefix conflicts before requesting a password.",
193추가: "consistency": "Capture each file from its validated open handle. Compare planned object identity, kind, size and modification time before capture and check planned objects again before publishing the completed ZIP; detected changes fail SourceChanged. This is not an atomic snapshot of an entire directory tree.",
194추가: "encryption": "AES-256 protects file contents using the existing AE-2 encoding. Directory entries are stored as zero-byte unencrypted directory records; entry names remain visible, as with other ZIP entries."
187195 }
188196}
수정experiments/rust-archive-worker/src/create.rs+53-58
@@ -1,8 +1,4 @@
1삭제: use crate::{
2삭제: archive::{self, Member, MetadataBudget},
3삭제: protocol::*,
4삭제: spool,
5삭제: };
1추가: use crate::{protocol::*, spool};
62use std::{
73 fs::File,
84 io::{Read, Seek, Write},
@@ -110,34 +106,16 @@ fn pack(
110106 }
111107 }
112108}
113삭제: pub(crate) fn plan(sources: &[Source], limits: Limits) -> Result<Vec<Member>> {
114삭제: if sources.len() > limits.entries as usize {
115삭제: return Err(ErrorCode::Limit);
116삭제: }
117삭제: let mut metadata = MetadataBudget::default();
118삭제: let mut members = Vec::new();
119삭제: for source in sources {
120삭제: source.path.to_path()?;
121삭제: let name = archive::valid_name(&source.archive_name, false)?;
122삭제: metadata.charge(&name)?;
123삭제: members.push(Member {
124삭제: entry: Entry {
125삭제: entry_id: members.len() as u32,
126삭제: name,
127삭제: kind: EntryKind::File,
128삭제: size: 0,
129삭제: compressed_size: 0,
130삭제: encrypted: false,
131삭제: },
132삭제: data: Vec::new(),
133삭제: });
134삭제: }
135삭제: archive::validate_members(&members)?;
136삭제: Ok(members)
109추가: pub(crate) use crate::create_sources::Plan;
110추가: pub(crate) fn plan(
111추가: sources: &[Source],
112추가: limits: Limits,
113추가: check: &mut impl FnMut() -> Result<()>,
114추가: ) -> Result<Plan> {
115추가: Plan::new(sources, limits, check)
137116}
138117pub(crate) fn zip(
139삭제: sources: &[Source],
140삭제: members: &[Member],
118추가: plan: &Plan,
141119 method: Method,
142120 limits: Limits,
143121 password: Option<&[u8]>,
@@ -147,36 +125,53 @@ pub(crate) fn zip(
147125 let mut central = Vec::new();
148126 let mut total = 0u64;
149127 let mut have_zip64 = false;
150삭제: for (source, member) in sources.iter().zip(members) {
128추가: for source in &plan.items {
129추가: let member = &source.member;
130추가: let directory = member.entry.kind == EntryKind::Directory;
131추가: let method = if directory { Method::Store } else { method };
132추가: let password = if directory { None } else { password };
151133 check()?;
152134 let remaining = limits
153135 .input
154136 .min(limits.output)
155137 .checked_sub(total)
156138 .ok_or(ErrorCode::Limit)?;
157삭제: let mut snapshot = spool::Snapshot::open(&source.path.to_path()?, remaining, check)?;
139추가: let mut input = source.open()?;
140추가: let mut snapshot = if directory {
141추가: None
142추가: } else {
143추가: Some(spool::Snapshot::capture(&mut input.file, remaining, check)?)
144추가: };
145추가: let length = snapshot.as_ref().map_or(0, |s| s.len);
158146 total = total
159삭제: .checked_add(snapshot.len)
147추가: .checked_add(length)
160148 .filter(|n| *n <= limits.output)
161149 .ok_or(ErrorCode::Limit)?;
162150 // 압축 결과의 보수적 상한과 ZIP에 복사할 공간을 함께 확인함.
163삭제: let bound = snapshot
164삭제: .len
165삭제: .checked_add(snapshot.len / 16383 * 5)
151추가: let bound = length
152추가: .checked_add(length / 16383 * 5)
166153 .and_then(|n| n.checked_add(131072))
167154 .ok_or(ErrorCode::Limit)?;
168155 crate::space::ensure(&output, bound.checked_mul(2).ok_or(ErrorCode::Limit)?)?;
169156 let mut packed = spool::temporary()?;
170삭제: let (packed_size, crc) =
171삭제: pack(&mut snapshot.file, snapshot.len, method, &mut packed, check)?;
157추가: let (packed_size, crc) = if let Some(snapshot) = snapshot.as_mut() {
158추가: pack(&mut snapshot.file, length, method, &mut packed, check)?
159추가: } else {
160추가: (0, 0)
161추가: };
172162 let packed_size = packed_size
173163 .checked_add(if password.is_some() { 28 } else { 0 })
174164 .ok_or(ErrorCode::Limit)?;
175165 let offset = io(output.stream_position())?;
176삭제: let name = member.entry.name.as_bytes();
166추가: let zip_name = if directory {
167추가: format!("{}/", member.entry.name)
168추가: } else {
169추가: member.entry.name.clone()
170추가: };
171추가: let name = zip_name.as_bytes();
177172 let real_method = if method == Method::Store { 0 } else { 8 };
178173 let flags = if password.is_some() { 0x0801 } else { 0x0800 };
179삭제: let wide_sizes = snapshot.len >= u32::MAX as u64 || packed_size >= u32::MAX as u64;
174추가: let wide_sizes = length >= u32::MAX as u64 || packed_size >= u32::MAX as u64;
180175 let wide_offset = offset >= u32::MAX as u64;
181176 have_zip64 |= wide_sizes || wide_offset;
182177 let version = if password.is_some() {
@@ -197,7 +192,7 @@ pub(crate) fn zip(
197192 aes.push(3);
198193 put16(&mut aes, real_method);
199194 }
200삭제: let mut extra = zip64_extra(snapshot.len, packed_size, None);
195추가: let mut extra = zip64_extra(length, packed_size, None);
201196 extra.extend(&aes);
202197 let mut header = Vec::new();
203198 header.extend(b"PK\x03\x04");
@@ -215,11 +210,7 @@ pub(crate) fn zip(
215210 );
216211 put32(
217212 &mut header,
218삭제: if wide_sizes {
219삭제: u32::MAX
220삭제: } else {
221삭제: snapshot.len as u32
222삭제: },
213추가: if wide_sizes { u32::MAX } else { length as u32 },
223214 );
224215 put16(&mut header, name.len() as u16);
225216 put16(&mut header, extra.len() as u16);
@@ -246,7 +237,7 @@ pub(crate) fn zip(
246237 io(output.write_all(&buffer[..n]))?;
247238 }
248239 }
249삭제: let mut extra = zip64_extra(snapshot.len, packed_size, Some(offset));
240추가: let mut extra = zip64_extra(length, packed_size, Some(offset));
250241 extra.extend(&aes);
251242 central.extend(b"PK\x01\x02");
252243 put16(&mut central, 0x032d);
@@ -264,18 +255,21 @@ pub(crate) fn zip(
264255 );
265256 put32(
266257 &mut central,
267삭제: if wide_sizes {
268삭제: u32::MAX
269삭제: } else {
270삭제: snapshot.len as u32
271삭제: },
258추가: if wide_sizes { u32::MAX } else { length as u32 },
272259 );
273260 put16(&mut central, name.len() as u16);
274261 put16(&mut central, extra.len() as u16);
275262 for _ in 0..3 {
276263 put16(&mut central, 0);
277264 }
278삭제: put32(&mut central, 0o100600 << 16);
265추가: put32(
266추가: &mut central,
267추가: if directory {
268추가: (0o40700 << 16) | 0x10
269추가: } else {
270추가: 0o100600 << 16
271추가: },
272추가: );
279273 put32(
280274 &mut central,
281275 if wide_offset { u32::MAX } else { offset as u32 },
@@ -296,8 +290,8 @@ pub(crate) fn zip(
296290 put16(&mut end, 45);
297291 put32(&mut end, 0);
298292 put32(&mut end, 0);
299삭제: put64(&mut end, sources.len() as u64);
300삭제: put64(&mut end, sources.len() as u64);
293추가: put64(&mut end, plan.items.len() as u64);
294추가: put64(&mut end, plan.items.len() as u64);
301295 put64(&mut end, central.len() as u64);
302296 put64(&mut end, at);
303297 end.extend(b"PK\x06\x07");
@@ -316,13 +310,14 @@ pub(crate) fn zip(
316310 end.extend(b"PK\x05\x06");
317311 put16(&mut end, 0);
318312 put16(&mut end, 0);
319삭제: put16(&mut end, sources.len() as u16);
320삭제: put16(&mut end, sources.len() as u16);
313추가: put16(&mut end, plan.items.len() as u16);
314추가: put16(&mut end, plan.items.len() as u16);
321315 put32(&mut end, central.len() as u32);
322316 put32(&mut end, at as u32);
323317 put16(&mut end, 0);
324318 }
325319 io(output.write_all(&end))?;
320추가: plan.verify(check)?;
326321 let size = io(output.stream_position())?;
327322 io(output.rewind())?;
328323 Ok((output, size))
추가experiments/rust-archive-worker/src/create_sources.rs+315-0
@@ -0,0 +1,315 @@
1추가: use crate::{
2추가: archive::{self, Member, MetadataBudget},
3추가: filesystem,
4추가: protocol::*,
5추가: };
6추가: use std::{
7추가: fs::{self, File, Metadata},
8추가: path::{Component, Path, PathBuf},
9추가: time::SystemTime,
10추가: };
11추가:
12추가: type Result<T> = std::result::Result<T, ErrorCode>;
13추가:
14추가: pub(super) struct Input {
15추가: pub file: File,
16추가: #[cfg(windows)]
17추가: _parents: Vec<File>,
18추가: }
19추가: impl Input {
20추가: #[cfg(target_os = "linux")]
21추가: fn child(file: &File, name: &std::ffi::OsStr) -> Result<File> {
22추가: use std::os::{
23추가: fd::{AsRawFd, FromRawFd},
24추가: unix::ffi::OsStrExt,
25추가: };
26추가: unsafe extern "C" {
27추가: fn openat(fd: i32, name: *const i8, flags: i32, ...) -> i32;
28추가: }
29추가: let name = std::ffi::CString::new(name.as_bytes()).map_err(|_| ErrorCode::UnsafePath)?;
30추가: // 링크를 따라가지 않는 경로 핸들로 객체 종류를 확인함.
31추가: let fd = unsafe {
32추가: openat(
33추가: file.as_raw_fd(),
34추가: name.as_ptr(),
35추가: 0x80000 | 0x20000 | 0x200000,
36추가: )
37추가: };
38추가: if fd < 0 {
39추가: let error = std::io::Error::last_os_error();
40추가: return Err(if matches!(error.raw_os_error(), Some(20 | 40)) {
41추가: ErrorCode::UnsafePath
42추가: } else {
43추가: crate::space::io_error(error)
44추가: });
45추가: }
46추가: let pinned = unsafe { File::from_raw_fd(fd) };
47추가: Self::validate(&pinned)?;
48추가: Ok(pinned)
49추가: }
50추가: #[cfg(target_os = "linux")]
51추가: fn read(pinned: File) -> Result<File> {
52추가: use std::os::fd::AsRawFd;
53추가: // 읽기 권한은 최종 입력에만 요청함.
54추가: File::open(format!("/proc/self/fd/{}", pinned.as_raw_fd())).map_err(crate::space::io_error)
55추가: }
56추가: pub fn open(path: &Path) -> Result<Self> {
57추가: if !path.is_absolute() {
58추가: return Err(ErrorCode::InvalidRequest);
59추가: }
60추가: #[cfg(target_os = "linux")]
61추가: {
62추가: use std::os::unix::fs::OpenOptionsExt;
63추가: let mut file = fs::OpenOptions::new()
64추가: .read(true)
65추가: .custom_flags(0x200000 | 0x20000 | 0x10000 | 0x80000)
66추가: .open("/")
67추가: .map_err(crate::space::io_error)?;
68추가: for part in path.components() {
69추가: match part {
70추가: Component::RootDir => {}
71추가: Component::Normal(name) => file = Self::child(&file, name)?,
72추가: _ => return Err(ErrorCode::UnsafePath),
73추가: }
74추가: }
75추가: let file = Self::read(file)?;
76추가: Self::validate(&file)?;
77추가: Ok(Self { file })
78추가: }
79추가: #[cfg(windows)]
80추가: {
81추가: use std::os::windows::fs::OpenOptionsExt;
82추가: let mut current = PathBuf::new();
83추가: let mut parents = Vec::new();
84추가: for part in path.components() {
85추가: match part {
86추가: Component::Prefix(_) | Component::RootDir => current.push(part.as_os_str()),
87추가: Component::Normal(name) => {
88추가: if parents.is_empty() {
89추가: parents.push(Self::lock(&current)?);
90추가: }
91추가: current.push(name);
92추가: parents.push(Self::lock(&current)?);
93추가: }
94추가: _ => return Err(ErrorCode::UnsafePath),
95추가: }
96추가: }
97추가: let file = fs::OpenOptions::new()
98추가: .read(true)
99추가: .share_mode(1)
100추가: .custom_flags(0x02000000 | 0x00200000)
101추가: .open(&current)
102추가: .map_err(crate::space::io_error)?;
103추가: Self::validate(&file)?;
104추가: Ok(Self {
105추가: file,
106추가: _parents: parents,
107추가: })
108추가: }
109추가: }
110추가: #[cfg(windows)]
111추가: fn lock(path: &Path) -> Result<File> {
112추가: use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
113추가: let file = fs::OpenOptions::new()
114추가: .access_mode(0)
115추가: .share_mode(3)
116추가: .custom_flags(0x02000000 | 0x00200000)
117추가: .open(path)
118추가: .map_err(crate::space::io_error)?;
119추가: if file
120추가: .metadata()
121추가: .map_err(crate::space::io_error)?
122추가: .file_attributes()
123추가: & 0x400
124추가: != 0
125추가: {
126추가: return Err(ErrorCode::UnsafePath);
127추가: }
128추가: Ok(file)
129추가: }
130추가: fn validate(file: &File) -> Result<()> {
131추가: let metadata = file.metadata().map_err(crate::space::io_error)?;
132추가: #[cfg(windows)]
133추가: {
134추가: use std::os::windows::fs::MetadataExt;
135추가: if metadata.file_attributes() & 0x400 != 0 {
136추가: return Err(ErrorCode::UnsafePath);
137추가: }
138추가: }
139추가: if !metadata.is_dir() && !metadata.is_file() {
140추가: return Err(ErrorCode::UnsafePath);
141추가: }
142추가: Ok(())
143추가: }
144추가: fn open_child(&self, path: &Path, name: &str) -> Result<Self> {
145추가: #[cfg(target_os = "linux")]
146추가: {
147추가: let _ = path;
148추가: let file = Self::read(Self::child(&self.file, std::ffi::OsStr::new(name))?)?;
149추가: Self::validate(&file)?;
150추가: Ok(Self { file })
151추가: }
152추가: #[cfg(windows)]
153추가: {
154추가: Self::open(&path.join(name))
155추가: }
156추가: }
157추가: fn children(&self, path: &Path) -> Result<fs::ReadDir> {
158추가: #[cfg(target_os = "linux")]
159추가: {
160추가: use std::os::fd::AsRawFd;
161추가: let _ = path;
162추가: fs::read_dir(format!("/proc/self/fd/{}", self.file.as_raw_fd()))
163추가: .map_err(crate::space::io_error)
164추가: }
165추가: #[cfg(windows)]
166추가: {
167추가: fs::read_dir(path).map_err(crate::space::io_error)
168추가: }
169추가: }
170추가: }
171추가:
172추가: pub(super) struct Planned {
173추가: pub member: Member,
174추가: path: PathBuf,
175추가: object: SourceObject,
176추가: modified: Option<SystemTime>,
177추가: }
178추가: impl Planned {
179추가: pub fn open(&self) -> Result<Input> {
180추가: let input = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
181추가: if !self.matches(&input.file)? {
182추가: return Err(ErrorCode::SourceChanged);
183추가: }
184추가: Ok(input)
185추가: }
186추가: fn matches(&self, file: &File) -> Result<bool> {
187추가: let metadata = file.metadata().map_err(crate::space::io_error)?;
188추가: Ok(filesystem::object(file)? == self.object
189추가: && metadata.modified().ok() == self.modified
190추가: && metadata.is_dir() == (self.member.entry.kind == EntryKind::Directory)
191추가: && (metadata.is_dir() || metadata.len() == self.member.entry.size))
192추가: }
193추가: }
194추가: pub(super) struct Plan {
195추가: pub items: Vec<Planned>,
196추가: limits: Limits,
197추가: budget: MetadataBudget,
198추가: total: u64,
199추가: }
200추가: impl Plan {
201추가: pub fn new(
202추가: sources: &[Source],
203추가: limits: Limits,
204추가: check: &mut impl FnMut() -> Result<()>,
205추가: ) -> Result<Self> {
206추가: if sources.len() > limits.entries as usize {
207추가: return Err(ErrorCode::Limit);
208추가: }
209추가: let mut plan = Self {
210추가: items: Vec::new(),
211추가: limits,
212추가: budget: MetadataBudget::default(),
213추가: total: 0,
214추가: };
215추가: let mut roots = std::collections::BTreeSet::new();
216추가: for source in sources {
217추가: check()?;
218추가: let name = archive::valid_name(&source.archive_name, false)?;
219추가: if !roots.insert(name.to_lowercase()) {
220추가: return Err(ErrorCode::Conflict);
221추가: }
222추가: }
223추가: for source in sources {
224추가: let path = source.path.to_path()?;
225추가: let input = Input::open(&path)?;
226추가: plan.visit(path, source.archive_name.clone(), input, check)?;
227추가: }
228추가: let members = plan
229추가: .items
230추가: .iter()
231추가: .map(|p| Member {
232추가: entry: p.member.entry.clone(),
233추가: data: Vec::new(),
234추가: })
235추가: .collect::<Vec<_>>();
236추가: archive::validate_members(&members)?;
237추가: Ok(plan)
238추가: }
239추가: fn visit(
240추가: &mut self,
241추가: path: PathBuf,
242추가: name: String,
243추가: input: Input,
244추가: check: &mut impl FnMut() -> Result<()>,
245추가: ) -> Result<()> {
246추가: check()?;
247추가: if self.items.len() >= self.limits.entries as usize {
248추가: return Err(ErrorCode::Limit);
249추가: }
250추가: let metadata: Metadata = input.file.metadata().map_err(crate::space::io_error)?;
251추가: let directory = metadata.is_dir();
252추가: let name = archive::valid_name(&name, directory)?;
253추가: self.budget.charge(&name)?;
254추가: self.budget.charge(&path.to_string_lossy())?;
255추가: let size = if directory { 0 } else { metadata.len() };
256추가: self.total = self
257추가: .total
258추가: .checked_add(size)
259추가: .filter(|n| *n <= self.limits.input.min(self.limits.output))
260추가: .ok_or(ErrorCode::Limit)?;
261추가: self.items.push(Planned {
262추가: member: Member {
263추가: entry: Entry {
264추가: entry_id: self.items.len() as u32,
265추가: name: name.clone(),
266추가: kind: if directory {
267추가: EntryKind::Directory
268추가: } else {
269추가: EntryKind::File
270추가: },
271추가: size,
272추가: compressed_size: 0,
273추가: encrypted: false,
274추가: },
275추가: data: Vec::new(),
276추가: },
277추가: path: path.clone(),
278추가: object: filesystem::object(&input.file)?,
279추가: modified: metadata.modified().ok(),
280추가: });
281추가: if directory {
282추가: let mut children = Vec::new();
283추가: for entry in input.children(&path)? {
284추가: check()?;
285추가: if self.items.len() + children.len() >= self.limits.entries as usize {
286추가: return Err(ErrorCode::Limit);
287추가: }
288추가: let leaf = entry
289추가: .map_err(crate::space::io_error)?
290추가: .file_name()
291추가: .into_string()
292추가: .map_err(|_| ErrorCode::UnsafePath)?;
293추가: self.budget.charge(&leaf)?;
294추가: children.push(leaf);
295추가: }
296추가: children.sort();
297추가: for leaf in children {
298추가: let child = input.open_child(&path, &leaf)?;
299추가: self.visit(path.join(&leaf), format!("{name}/{leaf}"), child, check)?;
300추가: }
301추가: }
302추가: Ok(())
303추가: }
304추가: pub fn verify(&self, check: &mut impl FnMut() -> Result<()>) -> Result<()> {
305추가: for item in &self.items {
306추가: check()?;
307추가: item.open()?;
308추가: }
309추가: Ok(())
310추가: }
311추가: }
312추가:
313추가: #[cfg(test)]
314추가: #[path = "../../../tests/rust-archive-worker/create_sources.rs"]
315추가: mod tests;
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -1,5 +1,6 @@
11pub mod archive;
22mod create;
3추가: mod create_sources;
34mod crypto;
45pub mod filesystem;
56mod lzma;
수정experiments/rust-archive-worker/src/runtime.rs+1-2
@@ -407,7 +407,7 @@ impl<W: Write> Job<W> {
407407 let name = archive::valid_name(leaf, false)?;
408408 let root = Dir::root(output.parent().ok_or(ErrorCode::InvalidRequest)?)?;
409409 filesystem::preflight(&root, &[(name.clone(), EntryKind::File)])?;
410삭제: let members = crate::create::plan(&sources, start.limits)?;
410추가: let members = crate::create::plan(&sources, start.limits, &mut || self.check())?;
411411 let secret = if encryption == Encryption::Aes256 {
412412 let secret = self.password(PasswordPurpose::Encrypt, 1)?;
413413 if secret.0.is_empty() {
@@ -418,7 +418,6 @@ impl<W: Write> Job<W> {
418418 None
419419 };
420420 let (mut data, length) = crate::create::zip(
421삭제: &sources,
422421 &members,
423422 method,
424423 start.limits,
수정experiments/rust-archive-worker/src/spool.rs+15-4
@@ -91,6 +91,20 @@ impl Snapshot {
9191 options.share_mode(1);
9292 }
9393 let mut source = options.open(path).map_err(|_| ErrorCode::Io)?;
94추가: let snapshot = Self::capture(&mut source, limit, check)?;
95추가: let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?;
96추가: if filesystem::object(&named)? != snapshot.object
97추가: || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file()
98추가: {
99추가: return Err(ErrorCode::SourceChanged);
100추가: }
101추가: Ok(snapshot)
102추가: }
103추가: pub(crate) fn capture(
104추가: source: &mut File,
105추가: limit: u64,
106추가: check: &mut impl FnMut() -> Result<()>,
107추가: ) -> Result<Self> {
94108 let before = source.metadata().map_err(|_| ErrorCode::Io)?;
95109 if !before.is_file() {
96110 return Err(ErrorCode::InvalidRequest);
@@ -120,12 +134,9 @@ impl Snapshot {
120134 hash.update(&buffer[..n]);
121135 }
122136 let after = source.metadata().map_err(|_| ErrorCode::Io)?;
123삭제: let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?;
124삭제: if filesystem::object(&named)? != object
125삭제: || filesystem::object(&source)? != object
137추가: if filesystem::object(&source)? != object
126138 || before.len() != len
127139 || after.len() != len
128삭제: || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file()
129140 || before.modified().ok() != after.modified().ok()
130141 {
131142 return Err(ErrorCode::SourceChanged);
추가tests/rust-archive-worker/create_sources.rs+107-0
@@ -0,0 +1,107 @@
1추가: use super::*;
2추가: use std::sync::atomic::{AtomicU64, Ordering};
3추가: static NEXT: AtomicU64 = AtomicU64::new(0);
4추가: struct Scratch(PathBuf);
5추가: impl Scratch {
6추가: fn new() -> Self {
7추가: let root =
8추가: Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/rust-archive-worker/runs");
9추가: fs::create_dir_all(&root).unwrap();
10추가: let path = root.join(format!(
11추가: "sources-{}-{}",
12추가: std::process::id(),
13추가: NEXT.fetch_add(1, Ordering::Relaxed)
14추가: ));
15추가: fs::create_dir(&path).unwrap();
16추가: Self(path.canonicalize().unwrap())
17추가: }
18추가: fn source(&self, name: &str) -> Source {
19추가: Source {
20추가: path: NativePath::from_path(&self.0.join(name)),
21추가: archive_name: name.into(),
22추가: }
23추가: }
24추가: }
25추가: impl Drop for Scratch {
26추가: fn drop(&mut self) {
27추가: fs::remove_dir_all(&self.0).unwrap();
28추가: }
29추가: }
30추가: #[test]
31추가: fn recursive_counts_and_source_bytes_honor_exact_quotas() {
32추가: let s = Scratch::new();
33추가: fs::create_dir(s.0.join("folder")).unwrap();
34추가: fs::create_dir(s.0.join("folder/empty")).unwrap();
35추가: fs::write(s.0.join("folder/file"), b"abc").unwrap();
36추가: for (entries, output, expected) in [
37추가: (3, 3, None),
38추가: (2, 3, Some(ErrorCode::Limit)),
39추가: (3, 2, Some(ErrorCode::Limit)),
40추가: ] {
41추가: let result = Plan::new(
42추가: &[s.source("folder")],
43추가: Limits {
44추가: entries,
45추가: output,
46추가: ..Limits::default()
47추가: },
48추가: &mut || Ok(()),
49추가: );
50추가: assert_eq!(result.as_ref().err().copied(), expected);
51추가: if let Ok(plan) = result {
52추가: assert_eq!(plan.items.len(), 3);
53추가: }
54추가: }
55추가: }
56추가: #[test]
57추가: fn replaced_source_is_rejected_before_capture() {
58추가: let s = Scratch::new();
59추가: fs::write(s.0.join("file"), b"original").unwrap();
60추가: let plan = Plan::new(&[s.source("file")], Limits::default(), &mut || Ok(())).unwrap();
61추가: fs::rename(s.0.join("file"), s.0.join("previous")).unwrap();
62추가: fs::write(s.0.join("file"), b"different").unwrap();
63추가: assert!(matches!(
64추가: plan.items[0].open(),
65추가: Err(ErrorCode::SourceChanged)
66추가: ));
67추가: }
68추가: #[test]
69추가: fn cancellation_stops_directory_enumeration() {
70추가: let s = Scratch::new();
71추가: fs::create_dir(s.0.join("folder")).unwrap();
72추가: for n in 0..20 {
73추가: fs::write(s.0.join(format!("folder/{n}")), b"x").unwrap();
74추가: }
75추가: let mut calls = 0;
76추가: let result = Plan::new(&[s.source("folder")], Limits::default(), &mut || {
77추가: calls += 1;
78추가: if calls == 5 {
79추가: Err(ErrorCode::None)
80추가: } else {
81추가: Ok(())
82추가: }
83추가: });
84추가: assert!(matches!(result, Err(ErrorCode::None)));
85추가: }
86추가: #[cfg(target_os = "linux")]
87추가: #[test]
88추가: fn pinned_directory_enumeration_does_not_follow_replacement_link() {
89추가: let s = Scratch::new();
90추가: fs::create_dir(s.0.join("folder")).unwrap();
91추가: fs::create_dir(s.0.join("outside")).unwrap();
92추가: fs::write(s.0.join("folder/original"), b"original").unwrap();
93추가: fs::write(s.0.join("outside/secret"), b"secret").unwrap();
94추가: let path = s.0.join("folder");
95추가: let input = Input::open(&path).unwrap();
96추가: fs::rename(&path, s.0.join("moved")).unwrap();
97추가: std::os::unix::fs::symlink(s.0.join("outside"), &path).unwrap();
98추가: let names = input
99추가: .children(&path)
100추가: .unwrap()
101추가: .map(|v| v.unwrap().file_name())
102추가: .collect::<Vec<_>>();
103추가: assert_eq!(names, vec![std::ffi::OsString::from("original")]);
104추가: assert!(input.open_child(&path, "original").is_ok());
105추가: assert!(input.open_child(&path, "secret").is_err());
106추가: assert!(matches!(Input::open(&path), Err(ErrorCode::UnsafePath)));
107추가: }
추가tests/rust-archive-worker/folder_inputs.rs+327-0
@@ -0,0 +1,327 @@
1추가: use super::*;
2추가: use sha2::{Digest, Sha256};
3추가: fn request(s: &Scratch, method: Method, encryption: Encryption) -> Start {
4추가: Start {
5추가: action: Action::CreateZip {
6추가: sources: vec![
7추가: Source {
8추가: path: s.path("tree"),
9추가: archive_name: "documents".into(),
10추가: },
11추가: Source {
12추가: path: s.path("loose"),
13추가: archive_name: "loose.bin".into(),
14추가: },
15추가: ],
16추가: output_file: s.path("created.zip"),
17추가: method,
18추가: encryption,
19추가: },
20추가: limits: Limits::default(),
21추가: }
22추가: }
23추가: fn seed(s: &Scratch) -> Vec<u8> {
24추가: fs::create_dir_all(s.0.join("tree/nested")).unwrap();
25추가: fs::create_dir(s.0.join("tree/empty")).unwrap();
26추가: let bytes = (0..262157).map(|i| (i % 251) as u8).collect::<Vec<_>>();
27추가: fs::write(s.0.join("tree/nested/한글.bin"), &bytes).unwrap();
28추가: fs::write(s.0.join("tree/zero"), []).unwrap();
29추가: fs::write(s.0.join("loose"), b"loose content").unwrap();
30추가: bytes
31추가: }
32추가: #[test]
33추가: fn mixed_folders_and_files_round_trip_plain_and_aes_with_sha256() {
34추가: for method in [Method::Store, Method::Deflate] {
35추가: for encryption in [Encryption::None, Encryption::Aes256] {
36추가: let s = Scratch::new();
37추가: let original = seed(&s);
38추가: let events = interactive(request(&s, method, encryption), |id, _, _| {
39추가: vec![Message::Password {
40추가: challenge_id: id,
41추가: secret: Secret(b"folder-password".to_vec()),
42추가: }]
43추가: });
44추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
45추가: let listed = execute(Start {
46추가: action: Action::List {
47추가: archive: s.path("created.zip"),
48추가: },
49추가: limits: Limits::default(),
50추가: });
51추가: assert_eq!(terminal(&listed).outcome, Outcome::Completed, "{listed:?}");
52추가: let entries = listed
53추가: .iter()
54추가: .filter_map(|e| {
55추가: if let Message::Entry(e) = e {
56추가: Some(e)
57추가: } else {
58추가: None
59추가: }
60추가: })
61추가: .collect::<Vec<_>>();
62추가: assert_eq!(entries.len(), 6);
63추가: assert_eq!(
64추가: entries
65추가: .iter()
66추가: .filter(|e| e.kind == EntryKind::Directory)
67추가: .count(),
68추가: 3
69추가: );
70추가: for entry in entries {
71추가: assert_eq!(
72추가: entry.encrypted,
73추가: encryption == Encryption::Aes256 && entry.kind == EntryKind::File
74추가: );
75추가: }
76추가: if encryption == Encryption::None {
77추가: assert!(Command::new("python3").arg("-c").arg("import sys,zipfile; z=zipfile.ZipFile(sys.argv[1]); assert z.testzip() is None; assert z.getinfo('documents/empty/').is_dir(); assert z.read('loose.bin') == b'loose content'").arg(s.0.join("created.zip")).status().unwrap().success());
78추가: }
79추가: fs::create_dir(s.0.join("output")).unwrap();
80추가: #[cfg(unix)]
81추가: {
82추가: use std::os::unix::fs::PermissionsExt;
83추가: fs::set_permissions(s.0.join("output"), fs::Permissions::from_mode(0o700)).unwrap();
84추가: }
85추가: let extracted = interactive(
86추가: Start {
87추가: action: Action::Extract {
88추가: archive: s.path("created.zip"),
89추가: destination: s.path("output"),
90추가: selection: Selection::All,
91추가: list_id: None,
92추가: gzip_output_name: None,
93추가: },
94추가: limits: Limits::default(),
95추가: },
96추가: |id, _, _| {
97추가: vec![Message::Password {
98추가: challenge_id: id,
99추가: secret: Secret(b"folder-password".to_vec()),
100추가: }]
101추가: },
102추가: );
103추가: assert_eq!(
104추가: terminal(&extracted).outcome,
105추가: Outcome::Completed,
106추가: "{extracted:?}"
107추가: );
108추가: assert_eq!(
109추가: Sha256::digest(fs::read(s.0.join("output/documents/nested/한글.bin")).unwrap()),
110추가: Sha256::digest(original)
111추가: );
112추가: assert_eq!(
113추가: Sha256::digest(fs::read(s.0.join("output/loose.bin")).unwrap()),
114추가: Sha256::digest(b"loose content")
115추가: );
116추가: assert_eq!(
117추가: fs::read(s.0.join("output/documents/zero")).unwrap(),
118추가: Vec::<u8>::new()
119추가: );
120추가: assert!(s.0.join("output/documents/empty").is_dir());
121추가: }
122추가: }
123추가: }
124추가: #[test]
125추가: fn descendant_name_conflict_is_rejected_before_password() {
126추가: let s = Scratch::new();
127추가: seed(&s);
128추가: let mut start = request(&s, Method::Store, Encryption::Aes256);
129추가: if let Action::CreateZip { sources, .. } = &mut start.action {
130추가: sources[1].archive_name = "documents/zero".into();
131추가: }
132추가: let events = execute(start);
133추가: assert_eq!(terminal(&events).error, ErrorCode::Conflict, "{events:?}");
134추가: assert!(
135추가: !events
136추가: .iter()
137추가: .any(|e| matches!(e, Message::PasswordRequired { .. }))
138추가: );
139추가: assert!(!s.0.join("created.zip").exists());
140추가: }
141추가: #[test]
142추가: fn empty_root_folder_is_preserved() {
143추가: let s = Scratch::new();
144추가: fs::create_dir(s.0.join("tree")).unwrap();
145추가: let mut start = request(&s, Method::Deflate, Encryption::None);
146추가: if let Action::CreateZip { sources, .. } = &mut start.action {
147추가: sources.truncate(1);
148추가: }
149추가: let events = execute(start);
150추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
151추가: let bytes = fs::read(s.0.join("created.zip")).unwrap();
152추가: let catalog = archive::parse(&bytes, Limits::default(), true, &mut || Ok(())).unwrap();
153추가: assert_eq!(catalog.members.len(), 1);
154추가: assert_eq!(catalog.members[0].entry.kind, EntryKind::Directory);
155추가: assert_eq!(catalog.members[0].entry.name, "documents");
156추가: }
157추가: #[cfg(target_os = "linux")]
158추가: #[test]
159추가: fn symlinks_and_special_files_are_not_followed() {
160추가: let s = Scratch::new();
161추가: seed(&s);
162추가: for target in ["loose", "tree", "missing"] {
163추가: std::os::unix::fs::symlink(s.0.join(target), s.0.join("tree/link")).unwrap();
164추가: let events = execute(request(&s, Method::Store, Encryption::Aes256));
165추가: assert_eq!(terminal(&events).error, ErrorCode::UnsafePath, "{events:?}");
166추가: assert!(
167추가: !events
168추가: .iter()
169추가: .any(|e| matches!(e, Message::PasswordRequired { .. }))
170추가: );
171추가: assert!(!s.0.join("created.zip").exists());
172추가: fs::remove_file(s.0.join("tree/link")).unwrap();
173추가: }
174추가: assert!(
175추가: Command::new("mkfifo")
176추가: .arg(s.0.join("tree/pipe"))
177추가: .status()
178추가: .unwrap()
179추가: .success()
180추가: );
181추가: let events = execute(request(&s, Method::Store, Encryption::None));
182추가: assert_eq!(terminal(&events).error, ErrorCode::UnsafePath, "{events:?}");
183추가: }
184추가: #[test]
185추가: fn source_replacement_while_waiting_for_password_leaves_no_zip() {
186추가: let s = Scratch::new();
187추가: seed(&s);
188추가: let events = interactive(
189추가: request(&s, Method::Store, Encryption::Aes256),
190추가: |id, _, _| {
191추가: fs::rename(s.0.join("tree/nested/한글.bin"), s.0.join("previous")).unwrap();
192추가: fs::write(s.0.join("tree/nested/한글.bin"), b"replacement").unwrap();
193추가: vec![Message::Password {
194추가: challenge_id: id,
195추가: secret: Secret(b"folder-password".to_vec()),
196추가: }]
197추가: },
198추가: );
199추가: assert_eq!(
200추가: terminal(&events).error,
201추가: ErrorCode::SourceChanged,
202추가: "{events:?}"
203추가: );
204추가: assert!(!s.0.join("created.zip").exists());
205추가: }
206추가:
207추가: #[cfg(target_os = "linux")]
208추가: #[test]
209추가: fn invalid_descendant_names_and_case_collisions_fail_before_password() {
210추가: let s = Scratch::new();
211추가: seed(&s);
212추가: for (leaf, expected) in [
213추가: ("CON.txt", ErrorCode::UnsafePath),
214추가: ("ZERO", ErrorCode::Conflict),
215추가: ] {
216추가: fs::write(s.0.join("tree").join(leaf), b"not exported").unwrap();
217추가: let events = execute(request(&s, Method::Store, Encryption::Aes256));
218추가: assert_eq!(terminal(&events).error, expected, "{events:?}");
219추가: assert!(
220추가: !events
221추가: .iter()
222추가: .any(|e| matches!(e, Message::PasswordRequired { .. }))
223추가: );
224추가: assert!(!s.0.join("created.zip").exists());
225추가: fs::remove_file(s.0.join("tree").join(leaf)).unwrap();
226추가: }
227추가: }
228추가:
229추가: #[cfg(target_os = "linux")]
230추가: fn readable_sources_under_parent(mode: u32) {
231추가: use std::os::unix::fs::PermissionsExt;
232추가: struct RestoreParent(PathBuf);
233추가: impl Drop for RestoreParent {
234추가: fn drop(&mut self) {
235추가: fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700)).unwrap();
236추가: }
237추가: }
238추가: let s = Scratch::new();
239추가: let parent = s.0.join("restricted");
240추가: fs::create_dir_all(parent.join("tree/empty")).unwrap();
241추가: fs::write(parent.join("loose"), b"readable file").unwrap();
242추가: fs::write(parent.join("tree/nested"), b"nested content").unwrap();
243추가: let _restore = RestoreParent(parent.clone());
244추가: fs::set_permissions(&parent, fs::Permissions::from_mode(mode)).unwrap();
245추가: if mode == 0o111 {
246추가: assert_eq!(
247추가: fs::read_dir(&parent).unwrap_err().kind(),
248추가: std::io::ErrorKind::PermissionDenied
249추가: );
250추가: } else {
251추가: assert!(fs::read_dir(&parent).is_ok());
252추가: }
253추가: assert_eq!(fs::read(parent.join("loose")).unwrap(), b"readable file");
254추가: for (name, encryption) in [("plain", Encryption::None), ("aes", Encryption::Aes256)] {
255추가: let archive_name = format!("{name}.zip");
256추가: let events = interactive(
257추가: Start {
258추가: action: Action::CreateZip {
259추가: sources: vec![
260추가: Source {
261추가: path: NativePath::from_path(&parent.join("loose")),
262추가: archive_name: "loose.txt".into(),
263추가: },
264추가: Source {
265추가: path: NativePath::from_path(&parent.join("tree")),
266추가: archive_name: "tree".into(),
267추가: },
268추가: ],
269추가: output_file: s.path(&archive_name),
270추가: method: Method::Deflate,
271추가: encryption,
272추가: },
273추가: limits: Limits::default(),
274추가: },
275추가: |id, _, _| {
276추가: vec![Message::Password {
277추가: challenge_id: id,
278추가: secret: Secret(b"parent-password".to_vec()),
279추가: }]
280추가: },
281추가: );
282추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
283추가: let output = format!("output-{name}");
284추가: fs::create_dir(s.0.join(&output)).unwrap();
285추가: fs::set_permissions(s.0.join(&output), fs::Permissions::from_mode(0o700)).unwrap();
286추가: let extracted = interactive(
287추가: Start {
288추가: action: Action::Extract {
289추가: archive: s.path(&archive_name),
290추가: destination: s.path(&output),
291추가: selection: Selection::All,
292추가: list_id: None,
293추가: gzip_output_name: None,
294추가: },
295추가: limits: Limits::default(),
296추가: },
297추가: |id, _, _| {
298추가: vec![Message::Password {
299추가: challenge_id: id,
300추가: secret: Secret(b"parent-password".to_vec()),
301추가: }]
302추가: },
303추가: );
304추가: assert_eq!(
305추가: terminal(&extracted).outcome,
306추가: Outcome::Completed,
307추가: "{extracted:?}"
308추가: );
309추가: for (source, destination) in [("loose", "loose.txt"), ("tree/nested", "tree/nested")] {
310추가: assert_eq!(
311추가: Sha256::digest(fs::read(parent.join(source)).unwrap()),
312추가: Sha256::digest(fs::read(s.0.join(&output).join(destination)).unwrap())
313추가: );
314추가: }
315추가: assert!(s.0.join(&output).join("tree/empty").is_dir());
316추가: }
317추가: }
318추가: #[cfg(target_os = "linux")]
319추가: #[test]
320추가: fn readable_sources_under_search_only_parent_0111() {
321추가: readable_sources_under_parent(0o111);
322추가: }
323추가: #[cfg(target_os = "linux")]
324추가: #[test]
325추가: fn readable_sources_under_readable_parent_0711() {
326추가: readable_sources_under_parent(0o711);
327추가: }
수정tests/rust-archive-worker/main.rs+2-0
@@ -1593,3 +1593,5 @@ fn disk_full_error_tag_preserves_previous_tags_and_rejects_unknown() {
15931593 assert!(Reader::new(bytes.as_slice()).read().is_err());
15941594 }
15951595}
1596추가:
1597추가: mod folder_inputs;