team-ljyzipelo

공개

폴더 입력과 빈 폴더를 ZIP 생성에 포함함

작성자
시로사키 하나
작성 시각
커밋
75563ccd487598fcd0bf1b722419e2b7078889af
부모
8bfa254
이 시점의 파일 보기

변경된 파일 10개

+723-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+303-0
@@ -0,0 +1,303 @@
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추가: File::open(format!("/proc/self/fd/{}", pinned.as_raw_fd())).map_err(crate::space::io_error)
49추가: }
50추가: pub fn open(path: &Path) -> Result<Self> {
51추가: if !path.is_absolute() {
52추가: return Err(ErrorCode::InvalidRequest);
53추가: }
54추가: #[cfg(target_os = "linux")]
55추가: {
56추가: let mut file = File::open("/").map_err(crate::space::io_error)?;
57추가: for part in path.components() {
58추가: match part {
59추가: Component::RootDir => {}
60추가: Component::Normal(name) => file = Self::child(&file, name)?,
61추가: _ => return Err(ErrorCode::UnsafePath),
62추가: }
63추가: }
64추가: Self::validate(&file)?;
65추가: Ok(Self { file })
66추가: }
67추가: #[cfg(windows)]
68추가: {
69추가: use std::os::windows::fs::OpenOptionsExt;
70추가: let mut current = PathBuf::new();
71추가: let mut parents = Vec::new();
72추가: for part in path.components() {
73추가: match part {
74추가: Component::Prefix(_) | Component::RootDir => current.push(part.as_os_str()),
75추가: Component::Normal(name) => {
76추가: if parents.is_empty() {
77추가: parents.push(Self::lock(&current)?);
78추가: }
79추가: current.push(name);
80추가: parents.push(Self::lock(&current)?);
81추가: }
82추가: _ => return Err(ErrorCode::UnsafePath),
83추가: }
84추가: }
85추가: let file = fs::OpenOptions::new()
86추가: .read(true)
87추가: .share_mode(1)
88추가: .custom_flags(0x02000000 | 0x00200000)
89추가: .open(&current)
90추가: .map_err(crate::space::io_error)?;
91추가: Self::validate(&file)?;
92추가: Ok(Self {
93추가: file,
94추가: _parents: parents,
95추가: })
96추가: }
97추가: }
98추가: #[cfg(windows)]
99추가: fn lock(path: &Path) -> Result<File> {
100추가: use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
101추가: let file = fs::OpenOptions::new()
102추가: .access_mode(0x80)
103추가: .share_mode(3)
104추가: .custom_flags(0x02000000 | 0x00200000)
105추가: .open(path)
106추가: .map_err(crate::space::io_error)?;
107추가: if file
108추가: .metadata()
109추가: .map_err(crate::space::io_error)?
110추가: .file_attributes()
111추가: & 0x400
112추가: != 0
113추가: {
114추가: return Err(ErrorCode::UnsafePath);
115추가: }
116추가: Ok(file)
117추가: }
118추가: fn validate(file: &File) -> Result<()> {
119추가: let metadata = file.metadata().map_err(crate::space::io_error)?;
120추가: #[cfg(windows)]
121추가: {
122추가: use std::os::windows::fs::MetadataExt;
123추가: if metadata.file_attributes() & 0x400 != 0 {
124추가: return Err(ErrorCode::UnsafePath);
125추가: }
126추가: }
127추가: if !metadata.is_dir() && !metadata.is_file() {
128추가: return Err(ErrorCode::UnsafePath);
129추가: }
130추가: Ok(())
131추가: }
132추가: fn open_child(&self, path: &Path, name: &str) -> Result<Self> {
133추가: #[cfg(target_os = "linux")]
134추가: {
135추가: let _ = path;
136추가: let file = Self::child(&self.file, std::ffi::OsStr::new(name))?;
137추가: Self::validate(&file)?;
138추가: Ok(Self { file })
139추가: }
140추가: #[cfg(windows)]
141추가: {
142추가: Self::open(&path.join(name))
143추가: }
144추가: }
145추가: fn children(&self, path: &Path) -> Result<fs::ReadDir> {
146추가: #[cfg(target_os = "linux")]
147추가: {
148추가: use std::os::fd::AsRawFd;
149추가: let _ = path;
150추가: fs::read_dir(format!("/proc/self/fd/{}", self.file.as_raw_fd()))
151추가: .map_err(crate::space::io_error)
152추가: }
153추가: #[cfg(windows)]
154추가: {
155추가: fs::read_dir(path).map_err(crate::space::io_error)
156추가: }
157추가: }
158추가: }
159추가:
160추가: pub(super) struct Planned {
161추가: pub member: Member,
162추가: path: PathBuf,
163추가: object: SourceObject,
164추가: modified: Option<SystemTime>,
165추가: }
166추가: impl Planned {
167추가: pub fn open(&self) -> Result<Input> {
168추가: let input = Input::open(&self.path).map_err(|_| ErrorCode::SourceChanged)?;
169추가: if !self.matches(&input.file)? {
170추가: return Err(ErrorCode::SourceChanged);
171추가: }
172추가: Ok(input)
173추가: }
174추가: fn matches(&self, file: &File) -> Result<bool> {
175추가: let metadata = file.metadata().map_err(crate::space::io_error)?;
176추가: Ok(filesystem::object(file)? == self.object
177추가: && metadata.modified().ok() == self.modified
178추가: && metadata.is_dir() == (self.member.entry.kind == EntryKind::Directory)
179추가: && (metadata.is_dir() || metadata.len() == self.member.entry.size))
180추가: }
181추가: }
182추가: pub(super) struct Plan {
183추가: pub items: Vec<Planned>,
184추가: limits: Limits,
185추가: budget: MetadataBudget,
186추가: total: u64,
187추가: }
188추가: impl Plan {
189추가: pub fn new(
190추가: sources: &[Source],
191추가: limits: Limits,
192추가: check: &mut impl FnMut() -> Result<()>,
193추가: ) -> Result<Self> {
194추가: if sources.len() > limits.entries as usize {
195추가: return Err(ErrorCode::Limit);
196추가: }
197추가: let mut plan = Self {
198추가: items: Vec::new(),
199추가: limits,
200추가: budget: MetadataBudget::default(),
201추가: total: 0,
202추가: };
203추가: let mut roots = std::collections::BTreeSet::new();
204추가: for source in sources {
205추가: check()?;
206추가: let name = archive::valid_name(&source.archive_name, false)?;
207추가: if !roots.insert(name.to_lowercase()) {
208추가: return Err(ErrorCode::Conflict);
209추가: }
210추가: }
211추가: for source in sources {
212추가: let path = source.path.to_path()?;
213추가: let input = Input::open(&path)?;
214추가: plan.visit(path, source.archive_name.clone(), input, check)?;
215추가: }
216추가: let members = plan
217추가: .items
218추가: .iter()
219추가: .map(|p| Member {
220추가: entry: p.member.entry.clone(),
221추가: data: Vec::new(),
222추가: })
223추가: .collect::<Vec<_>>();
224추가: archive::validate_members(&members)?;
225추가: Ok(plan)
226추가: }
227추가: fn visit(
228추가: &mut self,
229추가: path: PathBuf,
230추가: name: String,
231추가: input: Input,
232추가: check: &mut impl FnMut() -> Result<()>,
233추가: ) -> Result<()> {
234추가: check()?;
235추가: if self.items.len() >= self.limits.entries as usize {
236추가: return Err(ErrorCode::Limit);
237추가: }
238추가: let metadata: Metadata = input.file.metadata().map_err(crate::space::io_error)?;
239추가: let directory = metadata.is_dir();
240추가: let name = archive::valid_name(&name, directory)?;
241추가: self.budget.charge(&name)?;
242추가: self.budget.charge(&path.to_string_lossy())?;
243추가: let size = if directory { 0 } else { metadata.len() };
244추가: self.total = self
245추가: .total
246추가: .checked_add(size)
247추가: .filter(|n| *n <= self.limits.input.min(self.limits.output))
248추가: .ok_or(ErrorCode::Limit)?;
249추가: self.items.push(Planned {
250추가: member: Member {
251추가: entry: Entry {
252추가: entry_id: self.items.len() as u32,
253추가: name: name.clone(),
254추가: kind: if directory {
255추가: EntryKind::Directory
256추가: } else {
257추가: EntryKind::File
258추가: },
259추가: size,
260추가: compressed_size: 0,
261추가: encrypted: false,
262추가: },
263추가: data: Vec::new(),
264추가: },
265추가: path: path.clone(),
266추가: object: filesystem::object(&input.file)?,
267추가: modified: metadata.modified().ok(),
268추가: });
269추가: if directory {
270추가: let mut children = Vec::new();
271추가: for entry in input.children(&path)? {
272추가: check()?;
273추가: if self.items.len() + children.len() >= self.limits.entries as usize {
274추가: return Err(ErrorCode::Limit);
275추가: }
276추가: let leaf = entry
277추가: .map_err(crate::space::io_error)?
278추가: .file_name()
279추가: .into_string()
280추가: .map_err(|_| ErrorCode::UnsafePath)?;
281추가: self.budget.charge(&leaf)?;
282추가: children.push(leaf);
283추가: }
284추가: children.sort();
285추가: for leaf in children {
286추가: let child = input.open_child(&path, &leaf)?;
287추가: self.visit(path.join(&leaf), format!("{name}/{leaf}"), child, check)?;
288추가: }
289추가: }
290추가: Ok(())
291추가: }
292추가: pub fn verify(&self, check: &mut impl FnMut() -> Result<()>) -> Result<()> {
293추가: for item in &self.items {
294추가: check()?;
295추가: item.open()?;
296추가: }
297추가: Ok(())
298추가: }
299추가: }
300추가:
301추가: #[cfg(test)]
302추가: #[path = "../../../tests/rust-archive-worker/create_sources.rs"]
303추가: 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+227-0
@@ -0,0 +1,227 @@
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추가: }
수정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;