team-ljyzipelo

공개

압축파일 미리보기 디코더와 제한된 해제를 구현한다

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

변경된 파일 23개

+1,744-21
수정experiments/rust-archive-worker/Cargo.lock+98-0
@@ -2,6 +2,12 @@
22# It is not intended for manual editing.
33version = 4
44
5추가: [[package]]
6추가: name = "adler2"
7추가: version = "2.0.1"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10추가:
511[[package]]
612name = "aes"
713version = "0.8.4"
@@ -14,6 +20,12 @@ dependencies = [
1420 "zeroize",
1521]
1622
23추가: [[package]]
24추가: name = "bitflags"
25추가: version = "2.13.2"
26추가: source = "registry+https://github.com/rust-lang/crates.io-index"
27추가: checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
28추가:
1729[[package]]
1830name = "block-buffer"
1931version = "0.10.4"
@@ -81,6 +93,15 @@ dependencies = [
8193 "libc",
8294]
8395
96추가: [[package]]
97추가: name = "crc32fast"
98추가: version = "1.5.5"
99추가: source = "registry+https://github.com/rust-lang/crates.io-index"
100추가: checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
101추가: dependencies = [
102추가: "cfg-if",
103추가: ]
104추가:
84105[[package]]
85106name = "crypto-common"
86107version = "0.1.7"
@@ -122,6 +143,26 @@ dependencies = [
122143 "crypto-common 0.2.2",
123144]
124145
146추가: [[package]]
147추가: name = "fdeflate"
148추가: version = "0.3.7"
149추가: source = "registry+https://github.com/rust-lang/crates.io-index"
150추가: checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
151추가: dependencies = [
152추가: "simd-adler32",
153추가: ]
154추가:
155추가: [[package]]
156추가: name = "flate2"
157추가: version = "1.1.11"
158추가: source = "registry+https://github.com/rust-lang/crates.io-index"
159추가: checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
160추가: dependencies = [
161추가: "crc32fast",
162추가: "miniz_oxide 0.9.1",
163추가: "zlib-rs",
164추가: ]
165추가:
125166[[package]]
126167name = "generic-array"
127168version = "0.14.7"
@@ -180,6 +221,26 @@ dependencies = [
180221 "sha2 0.11.1",
181222]
182223
224추가: [[package]]
225추가: name = "miniz_oxide"
226추가: version = "0.8.9"
227추가: source = "registry+https://github.com/rust-lang/crates.io-index"
228추가: checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
229추가: dependencies = [
230추가: "adler2",
231추가: "simd-adler32",
232추가: ]
233추가:
234추가: [[package]]
235추가: name = "miniz_oxide"
236추가: version = "0.9.1"
237추가: source = "registry+https://github.com/rust-lang/crates.io-index"
238추가: checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
239추가: dependencies = [
240추가: "adler2",
241추가: "simd-adler32",
242추가: ]
243추가:
183244[[package]]
184245name = "pbkdf2"
185246version = "0.12.2"
@@ -190,6 +251,19 @@ dependencies = [
190251 "hmac",
191252]
192253
254추가: [[package]]
255추가: name = "png"
256추가: version = "0.18.1"
257추가: source = "registry+https://github.com/rust-lang/crates.io-index"
258추가: checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
259추가: dependencies = [
260추가: "bitflags",
261추가: "crc32fast",
262추가: "fdeflate",
263추가: "flate2",
264추가: "miniz_oxide 0.8.9",
265추가: ]
266추가:
193267[[package]]
194268name = "sha1"
195269version = "0.10.7"
@@ -223,6 +297,12 @@ dependencies = [
223297 "digest 0.11.3",
224298]
225299
300추가: [[package]]
301추가: name = "simd-adler32"
302추가: version = "0.3.10"
303추가: source = "registry+https://github.com/rust-lang/crates.io-index"
304추가: checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
305추가:
226306[[package]]
227307name = "subtle"
228308version = "2.6.1"
@@ -256,11 +336,14 @@ dependencies = [
256336 "hmac",
257337 "lzma-rust2",
258338 "pbkdf2",
339추가: "png",
259340 "sha1",
260341 "sha2 0.10.9",
261342 "subtle",
262343 "zeroize",
263344 "zlib-rs",
345추가: "zune-core",
346추가: "zune-jpeg",
264347]
265348
266349[[package]]
@@ -268,3 +351,18 @@ name = "zlib-rs"
268351version = "0.6.8"
269352source = "registry+https://github.com/rust-lang/crates.io-index"
270353checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
354추가:
355추가: [[package]]
356추가: name = "zune-core"
357추가: version = "0.5.3"
358추가: source = "registry+https://github.com/rust-lang/crates.io-index"
359추가: checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
360추가:
361추가: [[package]]
362추가: name = "zune-jpeg"
363추가: version = "0.5.15"
364추가: source = "registry+https://github.com/rust-lang/crates.io-index"
365추가: checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
366추가: dependencies = [
367추가: "zune-core",
368추가: ]
수정experiments/rust-archive-worker/Cargo.toml+3-0
@@ -7,6 +7,9 @@ publish = false
77autotests = false
88
99[dependencies]
10추가: png = "=0.18.1"
11추가: zune-jpeg = { version = "=0.5.15", default-features = false, features = ["std"] }
12추가: zune-core = { version = "=0.5.3", default-features = false, features = ["std"] }
1013bzip2 = "=0.6.1"
1114lzma-rust2 = { version = "=0.25.0", default-features = false, features = ["std", "xz"] }
1215aes = { version = "=0.8.4", features = ["zeroize"] }
수정experiments/rust-archive-worker/README.md+6-3
@@ -132,7 +132,7 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
132132
133133## 미리보기 계약
134134
135삭제: 상태: frontend와 backend의 계약 합의가 완료되었다. protocol.rs와 wire.rs에 공용 타입, 전송 규칙과 상한 검증을 반영했다. 작업자 디코더와 앱 연동 전이므로 미리보기 실행은 UnsupportedFeature로 끝나며 결과를 생성하지 않는다. 확정된 범위는 [PLANS 8.7](../../docs/PLANS.md)을 따른다. 8.8 분할 7z는 이 구현에서 제외한다.
135추가: 상태: frontend와 backend의 계약 합의가 완료되었다. protocol.rs와 wire.rs에 공용 타입, 전송 규칙과 상한 검증을 반영했다. 작업자의 제한된 해제와 PNG/JPEG 디코더를 연결했다. 실제 압축파일을 사용하는 운영체제별 화면 검증과 독립 리뷰는 완료 전이다. 확정된 범위는 [PLANS 8.7](../../docs/PLANS.md)을 따른다. 8.8 분할 7z는 이 구현에서 제외한다.
136136
137137### 요청과 수명
138138
@@ -166,9 +166,12 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
166166- 선택 항목 해제 후 원본 바이트는 텍스트 1 MiB, 이미지 8 MiB 이하다. 실제 읽는 양에도 같은 상한을 적용하며 차원과 픽셀 수를 할당 전에 검사한다. APNG, 다른 애니메이션, 미지원 형식은 제외한다. 손상 입력을 복구하거나 부분 디코딩으로 성공 처리하지 않는다.
167167- UnsupportedFormat/UnsupportedFeature는 형식/확장자 불일치와 미지원, Integrity는 잘못된 UTF-8과 손상, Limit는 바이트/픽셀 또는 공통 자원 상한을 뜻한다. SourceChanged, WrongPassword와 기존 I/O/Protocol 오류는 유지한다. 앱은 미리보기 Limit에 고유 상한 확대를 제안하지 않고 일반 해제를 별도 사용자 동작으로 안내한다.
168168
169삭제: ### 디코더 후보와 담당
169추가: ### 디코더와 담당
170170
171삭제: - PNG는 png 0.18.1(MIT OR Apache-2.0), JPEG는 zune-jpeg 0.5.15와 zune-core(MIT OR Apache-2.0 OR Zlib)의 직접 사용을 우선 검토한다. MIT 또는 Apache-2.0 조건을 선택하고 순수 Rust 기능만 사용한다. 공통 image 래퍼의 기본 관대한 JPEG 처리 대신 strict 디코딩과 치수/출력 제어를 직접 설정할 수 있다는 이유다. 버전과 실제 활성 기능은 구현 시 잠금 파일로 고정하고 권고 적용성을 대조한다.
171추가: - PNG는 png 0.18.1(MIT OR Apache-2.0), JPEG는 zune-jpeg 0.5.15와 zune-core 0.5.3(MIT OR Apache-2.0 OR Zlib)을 직접 사용하며 모두 MIT 조건을 선택한다. zune는 std 기능만 켜고 순수 Rust 디코더를 사용한다. strict 모드, 입력/출력 길이와 치수를 직접 제어하기 위해 공통 image 래퍼 대신 선택했다. packaging/licenses.py에서 선택한 MIT와 체크섬을 대조한 라이선스 원문을 배포 고지에 포함한다.
172추가: - PNG는 모든 청크 CRC와 마지막 IEND를 검증하고 APNG를 거부한다. 텍스트와 ICC 메타데이터의 추가 해독은 끄고 16비트/팔레트/회색조를 RGBA8로 정규화한다. JPEG는 헤더와 스캔 경계를 먼저 확인해 단일 8비트 baseline/progressive 프레임만 해독한다. 회색조와 CMYK도 RGB 해독 뒤 같은 결과 버퍼에서 불투명 RGBA8로 변환한다. 산술 부호화, lossless JPEG와 MPO는 지원하지 않는다.
173추가: - ZIP은 선택 항목만 해제하며 7z는 선택 항목이 속한 solid 블록 전체를 무결성 검증한다. TAR 계열과 GZip 컨테이너 해독, solid 블록 및 메타데이터에는 기존 공통 예산과 임시 공간 감시를 적용한다. 선택 항목을 결과 버퍼로 읽는 양은 텍스트/이미지 고유 상한을 넘지 않는다. PNG 입력 읽기, 변환 행과 결과 청크마다 취소를 확인한다. JPEG 라이브러리 호출은 전후에 취소를 확인하고 기존 자식 종료/회수 정책을 유지한다.
174추가: - 2026-11-14 공개 RustSec DB의 crates 트리 86148de9e400d7460a03b8089d1de31af2d1e6c3에서 추가 의존성 10종 이름의 권고 기록이 없는 것을 확인했다. 이 확인은 전체 잠금 파일의 자동 감사나 취약점 부재를 보장하지 않는다.
172175- PNG의 제한된 Decoder와 행/프레임 API는 [공식 문서](https://docs.rs/png/0.18.1/png/)를 참고한다. 라이브러리 내부 할당 제한을 작업자 전체 RSS의 강제 상한으로 표현하지 않는다. 엄격한 항목 길이, 치수와 결과 길이 검사를 별도로 적용한다.
173176- backend는 작업자 protocol.rs, wire.rs, runtime 및 디코더, 작업자 시험과 packaging/licenses.py 고지를 맡는다. frontend는 앱 재조립/전송 제어, 화면과 앱 시험, --ui-scenario 및 가이드를 맡는다. 같은 원격 브랜치는 양쪽 결과를 확인하며 순차 갱신하고 공용 타입 변경은 이 계약 합의 후 backend가 반영한다.
174177- 시험은 바이트/치수/픽셀 경계, UTF-8 청크 경계와 BOM, 형식 불일치/APNG/손상, 암호와 solid 예산, malformed/순서/중복/초과 전송, 64개 큐 역압과 디코딩 및 전송 중 취소, 늦은 완료 폐기와 정리 및 원본 해시 보존을 포함한다.
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -6,6 +6,7 @@ mod crypto;
66pub mod filesystem;
77mod lzma;
88mod parent;
9추가: mod preview;
910pub mod protocol;
1011pub mod resources;
1112pub mod runtime;
추가experiments/rust-archive-worker/src/preview.rs+348-0
@@ -0,0 +1,348 @@
1추가: use crate::{protocol::*, resources::Monitor};
2추가: use std::io::{self, BufRead, Cursor, Read, Seek, SeekFrom};
3추가: use zlib_rs::crc32::crc32;
4추가: use zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions};
5추가:
6추가: type Result<T> = std::result::Result<T, ErrorCode>;
7추가:
8추가: #[derive(Clone, Copy)]
9추가: pub(crate) enum Kind {
10추가: Text,
11추가: Png,
12추가: Jpeg,
13추가: }
14추가: impl Kind {
15추가: pub fn from_name(name: &str) -> Result<Self> {
16추가: match name
17추가: .rsplit_once('.')
18추가: .map(|(_, ext)| ext.to_ascii_lowercase())
19추가: .as_deref()
20추가: {
21추가: Some("txt" | "md" | "log" | "csv" | "json") => Ok(Self::Text),
22추가: Some("png") => Ok(Self::Png),
23추가: Some("jpg" | "jpeg") => Ok(Self::Jpeg),
24추가: _ => Err(ErrorCode::UnsupportedFeature),
25추가: }
26추가: }
27추가: pub fn limit(self) -> u64 {
28추가: match self {
29추가: Self::Text => MAX_PREVIEW_TEXT_BYTES,
30추가: Self::Png | Self::Jpeg => MAX_PREVIEW_IMAGE_BYTES,
31추가: }
32추가: }
33추가: }
34추가: fn rgba_info(entry_id: u32, width: u32, height: u32) -> Result<PreviewInfo> {
35추가: if width == 0 || height == 0 {
36추가: return Err(ErrorCode::Integrity);
37추가: }
38추가: let total_bytes = u64::from(width)
39추가: .checked_mul(u64::from(height))
40추가: .and_then(|n| n.checked_mul(4))
41추가: .ok_or(ErrorCode::Limit)?;
42추가: let info = PreviewInfo {
43추가: entry_id,
44추가: format: PreviewFormat::Rgba8,
45추가: total_bytes,
46추가: width,
47추가: height,
48추가: };
49추가: if !info.valid() {
50추가: return Err(ErrorCode::Limit);
51추가: }
52추가: Ok(info)
53추가: }
54추가: fn buffer(length: usize) -> Result<Vec<u8>> {
55추가: let mut bytes = Vec::new();
56추가: bytes
57추가: .try_reserve_exact(length)
58추가: .map_err(|_| ErrorCode::Limit)?;
59추가: bytes.resize(length, 0);
60추가: Ok(bytes)
61추가: }
62추가: pub(crate) fn decode(
63추가: kind: Kind,
64추가: entry_id: u32,
65추가: mut source: Vec<u8>,
66추가: check: &mut impl Monitor,
67추가: ) -> Result<(PreviewInfo, Vec<u8>)> {
68추가: check.check()?;
69추가: if source.len() as u64 > kind.limit() {
70추가: return Err(ErrorCode::Limit);
71추가: }
72추가: let result = match kind {
73추가: Kind::Text => {
74추가: std::str::from_utf8(&source).map_err(|_| ErrorCode::Integrity)?;
75추가: if source.starts_with(&[0xef, 0xbb, 0xbf]) {
76추가: source.drain(..3);
77추가: }
78추가: Ok((
79추가: PreviewInfo {
80추가: entry_id,
81추가: format: PreviewFormat::Utf8Text,
82추가: total_bytes: source.len() as u64,
83추가: width: 0,
84추가: height: 0,
85추가: },
86추가: source,
87추가: ))
88추가: }
89추가: Kind::Png => png(entry_id, &source, check),
90추가: Kind::Jpeg => jpeg(entry_id, &source, check),
91추가: };
92추가: check.activity()?;
93추가: result
94추가: }
95추가: struct Input<'a, M> {
96추가: bytes: Cursor<&'a [u8]>,
97추가: check: &'a mut M,
98추가: }
99추가: impl<M: Monitor> Read for Input<'_, M> {
100추가: fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
101추가: self.check
102추가: .check()
103추가: .map_err(|_| io::Error::other("preview interrupted"))?;
104추가: let length = self.bytes.read(bytes)?;
105추가: if length != 0 {
106추가: self.check
107추가: .activity()
108추가: .map_err(|_| io::Error::other("preview interrupted"))?;
109추가: }
110추가: Ok(length)
111추가: }
112추가: }
113추가: impl<M: Monitor> BufRead for Input<'_, M> {
114추가: fn fill_buf(&mut self) -> io::Result<&[u8]> {
115추가: self.check
116추가: .check()
117추가: .map_err(|_| io::Error::other("preview interrupted"))?;
118추가: self.bytes.fill_buf()
119추가: }
120추가: fn consume(&mut self, length: usize) {
121추가: self.bytes.consume(length);
122추가: }
123추가: }
124추가: impl<M: Monitor> Seek for Input<'_, M> {
125추가: fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
126추가: self.check
127추가: .check()
128추가: .map_err(|_| io::Error::other("preview interrupted"))?;
129추가: self.bytes.seek(position)
130추가: }
131추가: }
132추가: fn png(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<(PreviewInfo, Vec<u8>)> {
133추가: if !source.starts_with(b"\x89PNG\r\n\x1a\n") {
134추가: return Err(ErrorCode::UnsupportedFormat);
135추가: }
136추가: let mut at = 8usize;
137추가: let mut ended = false;
138추가: while at < source.len() {
139추가: check.check()?;
140추가: let header = source.get(at..at + 8).ok_or(ErrorCode::Integrity)?;
141추가: let length = u32::from_be_bytes(header[..4].try_into().unwrap()) as usize;
142추가: let end = at
143추가: .checked_add(12)
144추가: .and_then(|n| n.checked_add(length))
145추가: .filter(|n| *n <= source.len())
146추가: .ok_or(ErrorCode::Integrity)?;
147추가: if crc32(0, &source[at + 4..end - 4])
148추가: != u32::from_be_bytes(source[end - 4..end].try_into().unwrap())
149추가: {
150추가: return Err(ErrorCode::Integrity);
151추가: }
152추가: if at == 8 && (&header[4..] != b"IHDR" || length != 13) {
153추가: return Err(ErrorCode::Integrity);
154추가: }
155추가: if matches!(&header[4..], b"acTL" | b"fcTL" | b"fdAT") {
156추가: return Err(ErrorCode::UnsupportedFeature);
157추가: }
158추가: if &header[4..] == b"IEND" {
159추가: if length != 0 || end != source.len() {
160추가: return Err(ErrorCode::Integrity);
161추가: }
162추가: ended = true;
163추가: }
164추가: at = end;
165추가: check.activity()?;
166추가: }
167추가: if !ended {
168추가: return Err(ErrorCode::Integrity);
169추가: }
170추가: let mut decoder = png::Decoder::new_with_limits(
171추가: Input {
172추가: bytes: Cursor::new(source),
173추가: check,
174추가: },
175추가: png::Limits {
176추가: bytes: 128 * 1024 * 1024,
177추가: },
178추가: );
179추가: decoder.set_ignore_text_chunk(true);
180추가: decoder.set_ignore_iccp_chunk(true);
181추가: decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
182추가: let header = decoder
183추가: .read_header_info()
184추가: .map_err(|_| ErrorCode::Integrity)?;
185추가: let info = rgba_info(entry_id, header.width, header.height)?;
186추가: let mut reader = decoder.read_info().map_err(|_| ErrorCode::Integrity)?;
187추가: let length = reader
188추가: .output_buffer_size()
189추가: .filter(|n| *n as u64 <= info.total_bytes)
190추가: .ok_or(ErrorCode::Limit)?;
191추가: let mut raw = buffer(length)?;
192추가: let decoded = reader
193추가: .next_frame(&mut raw)
194추가: .map_err(|_| ErrorCode::Integrity)?;
195추가: reader.finish().map_err(|_| ErrorCode::Integrity)?;
196추가: drop(reader);
197추가: check.activity()?;
198추가: if decoded.width != info.width
199추가: || decoded.height != info.height
200추가: || decoded.bit_depth != png::BitDepth::Eight
201추가: {
202추가: return Err(ErrorCode::Integrity);
203추가: }
204추가: raw.truncate(decoded.buffer_size());
205추가: let channels = match decoded.color_type {
206추가: png::ColorType::Grayscale => 1,
207추가: png::ColorType::GrayscaleAlpha => 2,
208추가: png::ColorType::Rgb => 3,
209추가: png::ColorType::Rgba => 4,
210추가: _ => return Err(ErrorCode::UnsupportedFeature),
211추가: };
212추가: if raw.len() != info.width as usize * info.height as usize * channels {
213추가: return Err(ErrorCode::Integrity);
214추가: }
215추가: if channels == 4 {
216추가: return Ok((info, raw));
217추가: }
218추가: let mut rgba = buffer(info.total_bytes as usize)?;
219추가: for (source, target) in raw
220추가: .chunks_exact(info.width as usize * channels)
221추가: .zip(rgba.chunks_exact_mut(info.width as usize * 4))
222추가: {
223추가: check.activity()?;
224추가: for (pixel, out) in source
225추가: .chunks_exact(channels)
226추가: .zip(target.chunks_exact_mut(4))
227추가: {
228추가: match channels {
229추가: 1 => out.copy_from_slice(&[pixel[0], pixel[0], pixel[0], 255]),
230추가: 2 => out.copy_from_slice(&[pixel[0], pixel[0], pixel[0], pixel[1]]),
231추가: 3 => out.copy_from_slice(&[pixel[0], pixel[1], pixel[2], 255]),
232추가: _ => unreachable!(),
233추가: }
234추가: }
235추가: }
236추가: Ok((info, rgba))
237추가: }
238추가: fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<PreviewInfo> {
239추가: let mut at = 2usize;
240추가: let mut scanning = false;
241추가: let mut info = None;
242추가: let mut seen_scan = false;
243추가: while at < source.len() {
244추가: check.check()?;
245추가: if scanning {
246추가: at += source[at..]
247추가: .iter()
248추가: .position(|byte| *byte == 0xff)
249추가: .ok_or(ErrorCode::Integrity)?;
250추가: }
251추가: if source[at] != 0xff {
252추가: return Err(ErrorCode::Integrity);
253추가: }
254추가: while source.get(at) == Some(&0xff) {
255추가: at += 1;
256추가: }
257추가: let marker = *source.get(at).ok_or(ErrorCode::Integrity)?;
258추가: at += 1;
259추가: match marker {
260추가: 0 | 0xd0..=0xd7 if scanning => continue,
261추가: 0xd9 if at == source.len() && seen_scan => return info.ok_or(ErrorCode::Integrity),
262추가: 0 | 0xd0..=0xd9 => return Err(ErrorCode::Integrity),
263추가: 1 => continue,
264추가: _ => {}
265추가: }
266추가: let length = source.get(at..at + 2).ok_or(ErrorCode::Integrity)?;
267추가: let length = u16::from_be_bytes(length.try_into().unwrap()) as usize;
268추가: let end = at
269추가: .checked_add(length)
270추가: .filter(|n| length >= 2 && *n <= source.len())
271추가: .ok_or(ErrorCode::Integrity)?;
272추가: let body = &source[at + 2..end];
273추가: if matches!(marker, 0xc0..=0xcf) && !matches!(marker, 0xc4 | 0xc8 | 0xcc) {
274추가: if info.is_some() || body.len() < 6 {
275추가: return Err(ErrorCode::Integrity);
276추가: }
277추가: if !matches!(marker, 0xc0 | 0xc2) || body[0] != 8 {
278추가: return Err(ErrorCode::UnsupportedFeature);
279추가: }
280추가: info = Some(rgba_info(
281추가: entry_id,
282추가: u32::from(u16::from_be_bytes(body[3..5].try_into().unwrap())),
283추가: u32::from(u16::from_be_bytes(body[1..3].try_into().unwrap())),
284추가: )?);
285추가: }
286추가: if marker == 0xe2 && body.starts_with(b"MPF\0") {
287추가: return Err(ErrorCode::UnsupportedFeature);
288추가: }
289추가: scanning = marker == 0xda;
290추가: seen_scan |= scanning;
291추가: at = end;
292추가: check.activity()?;
293추가: }
294추가: Err(ErrorCode::Integrity)
295추가: }
296추가: fn jpeg_error(error: zune_jpeg::errors::DecodeErrors) -> ErrorCode {
297추가: match error {
298추가: zune_jpeg::errors::DecodeErrors::LargeDimensions(_) => ErrorCode::Limit,
299추가: zune_jpeg::errors::DecodeErrors::Unsupported(_) => ErrorCode::UnsupportedFeature,
300추가: _ => ErrorCode::Integrity,
301추가: }
302추가: }
303추가: fn jpeg(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<(PreviewInfo, Vec<u8>)> {
304추가: if !source.starts_with(&[0xff, 0xd8]) {
305추가: return Err(ErrorCode::UnsupportedFormat);
306추가: }
307추가: if !source.ends_with(&[0xff, 0xd9]) {
308추가: return Err(ErrorCode::Integrity);
309추가: }
310추가: let expected = jpeg_info(entry_id, source, check)?;
311추가: let options = DecoderOptions::new_safe()
312추가: .set_strict_mode(true)
313추가: .set_max_width(MAX_PREVIEW_DIMENSION as usize)
314추가: .set_max_height(MAX_PREVIEW_DIMENSION as usize)
315추가: .jpeg_set_max_scans(100)
316추가: .jpeg_set_out_colorspace(ColorSpace::RGB);
317추가: let mut decoder = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(source), options);
318추가: decoder.decode_headers().map_err(jpeg_error)?;
319추가: let header = decoder.info().ok_or(ErrorCode::Integrity)?;
320추가: let info = rgba_info(entry_id, u32::from(header.width), u32::from(header.height))?;
321추가: let rgb_bytes = (info.total_bytes / 4 * 3) as usize;
322추가: if info != expected || decoder.output_buffer_size() != Some(rgb_bytes) {
323추가: return Err(ErrorCode::Integrity);
324추가: }
325추가: let mut rgba = buffer(info.total_bytes as usize)?;
326추가: decoder
327추가: .decode_into(&mut rgba[..rgb_bytes])
328추가: .map_err(jpeg_error)?;
329추가: // CMYK의 RGBA 경로를 피하고 같은 버퍼 안에서 불투명 알파를 채움.
330추가: for row in (0..info.height as usize).rev() {
331추가: check.activity()?;
332추가: for column in (0..info.width as usize).rev() {
333추가: let pixel = row * info.width as usize + column;
334추가: let rgb = [
335추가: rgba[pixel * 3],
336추가: rgba[pixel * 3 + 1],
337추가: rgba[pixel * 3 + 2],
338추가: 255,
339추가: ];
340추가: rgba[pixel * 4..pixel * 4 + 4].copy_from_slice(&rgb);
341추가: }
342추가: }
343추가: Ok((info, rgba))
344추가: }
345추가:
346추가: #[cfg(test)]
347추가: #[path = "../../../tests/rust-archive-worker/preview_decode.rs"]
348추가: mod tests;
수정experiments/rust-archive-worker/src/runtime.rs+141-2
@@ -352,6 +352,140 @@ impl<W: Write> Job<W> {
352352 }
353353 Ok(())
354354 }
355추가: fn preview(
356추가: &mut self,
357추가: archive: NativePath,
358추가: entry_id: u32,
359추가: expected: ListId,
360추가: limits: Limits,
361추가: ) -> Result<()> {
362추가: use sha2::{Digest, Sha256};
363추가: use std::io::{Read, Seek, SeekFrom};
364추가: let path = archive.to_path()?;
365추가: self.progress(Stage::Read, 0, None, 0)?;
366추가: let mut snapshot =
367추가: crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| match step {
368추가: crate::spool::Step::Check => self.check(),
369추가: crate::spool::Step::Activity => completed(Ok(()), self),
370추가: crate::spool::Step::Read { bytes, total } => {
371추가: self.progress(Stage::Read, bytes, Some(total), 0)
372추가: }
373추가: })?;
374추가: if expected.catalog_version != 1
375추가: || expected.source_object != snapshot.object
376추가: || expected.archive_bytes != snapshot.len
377추가: || expected.archive_sha256 != snapshot.hash
378추가: {
379추가: return Err(ErrorCode::SourceChanged);
380추가: }
381추가: let mut catalog = crate::streaming::Catalog::open(
382추가: &mut snapshot.file,
383추가: snapshot.len,
384추가: limits,
385추가: false,
386추가: None,
387추가: self,
388추가: )?;
389추가: if expected.format != catalog.format {
390추가: return Err(ErrorCode::SourceChanged);
391추가: }
392추가: let entry = catalog
393추가: .members
394추가: .get(entry_id as usize)
395추가: .ok_or(ErrorCode::InvalidRequest)?
396추가: .entry
397추가: .clone();
398추가: if entry.entry_id != entry_id || entry.kind != EntryKind::File {
399추가: return Err(ErrorCode::InvalidRequest);
400추가: }
401추가: let name = if catalog.format == Format::Gzip {
402추가: let name = path
403추가: .file_name()
404추가: .and_then(|s| s.to_str())
405추가: .ok_or(ErrorCode::UnsupportedFeature)?;
406추가: if !name.to_ascii_lowercase().ends_with(".gz") {
407추가: return Err(ErrorCode::UnsupportedFeature);
408추가: }
409추가: &name[..name.len() - 3]
410추가: } else {
411추가: &entry.name
412추가: };
413추가: let kind = crate::preview::Kind::from_name(name)?;
414추가: if entry.size > kind.limit() {
415추가: return Err(ErrorCode::Limit);
416추가: }
417추가: self.progress(Stage::Decode, 0, Some(entry.size), 0)?;
418추가: if matches!(catalog.format, Format::Zip | Format::SevenZip) {
419추가: for attempt in 1..=3 {
420추가: let secret = if entry.encrypted {
421추가: Some(self.password(PasswordPurpose::Decrypt, attempt)?)
422추가: } else {
423추가: None
424추가: };
425추가: match crate::streaming::Catalog::preview(
426추가: &mut snapshot.file,
427추가: snapshot.len,
428추가: limits,
429추가: secret.as_ref().map(|s| s.0.as_slice()),
430추가: entry_id,
431추가: self,
432추가: ) {
433추가: Ok(decoded) => {
434추가: catalog = decoded;
435추가: break;
436추가: }
437추가: Err(ErrorCode::WrongPassword) if entry.encrypted && attempt < 3 => continue,
438추가: Err(error) => return Err(error),
439추가: }
440추가: }
441추가: }
442추가: let mut bytes = Vec::new();
443추가: bytes
444추가: .try_reserve_exact(entry.size as usize)
445추가: .map_err(|_| ErrorCode::Limit)?;
446추가: catalog
447추가: .data
448추가: .seek(SeekFrom::Start(catalog.offsets[entry_id as usize]))
449추가: .map_err(crate::space::io_error)?;
450추가: let mut remaining = entry.size;
451추가: let mut chunk = [0; 32768];
452추가: while remaining != 0 {
453추가: self.check()?;
454추가: let length = remaining.min(chunk.len() as u64) as usize;
455추가: catalog
456추가: .data
457추가: .read_exact(&mut chunk[..length])
458추가: .map_err(|_| ErrorCode::Integrity)?;
459추가: bytes.extend_from_slice(&chunk[..length]);
460추가: remaining -= length as u64;
461추가: completed(Ok(()), self)?;
462추가: }
463추가: let (info, bytes) = crate::preview::decode(kind, entry_id, bytes, self)?;
464추가: self.check()?;
465추가: let hash: [u8; 32] = Sha256::digest(&bytes).into();
466추가: completed(self.event(Message::PreviewBegin(info)), self)?;
467추가: for (index, chunk) in bytes.chunks(MAX_PREVIEW_CHUNK_BYTES).enumerate() {
468추가: self.check()?;
469추가: completed(
470추가: self.event(Message::PreviewChunk {
471추가: entry_id,
472추가: offset: (index * MAX_PREVIEW_CHUNK_BYTES) as u64,
473추가: data: chunk.to_vec(),
474추가: }),
475추가: self,
476추가: )?;
477추가: }
478추가: self.check()?;
479추가: completed(
480추가: self.event(Message::PreviewEnd {
481추가: entry_id,
482추가: total_bytes: info.total_bytes,
483추가: sha256: hash,
484추가: }),
485추가: self,
486추가: )?;
487추가: Ok(())
488추가: }
355489 fn run(&mut self, start: Start) -> Result<()> {
356490 if !start.limits.valid() {
357491 return Err(ErrorCode::InvalidRequest);
@@ -649,8 +783,13 @@ impl<W: Write> Job<W> {
649783 }
650784 }
651785 }
652삭제: // 미리보기 실행은 디코더 연결 전까지 지원하지 않음.
653삭제: Action::Preview { .. } => return Err(ErrorCode::UnsupportedFeature),
786추가: Action::Preview {
787추가: archive,
788추가: entry_id,
789추가: list_id,
790추가: } => {
791추가: self.preview(archive, entry_id, list_id, limits)?;
792추가: }
654793 Action::CreateZip {
655794 sources,
656795 output_file,
수정experiments/rust-archive-worker/src/seven_zip.rs+38-11
@@ -306,18 +306,28 @@ impl Streams {
306306 input: &mut std::fs::File,
307307 ranges: &[(u64, u64)],
308308 output: &mut std::fs::File,
309추가: selected: Option<usize>,
309310 check: &mut impl crate::resources::Monitor,
310311 ) -> Result<()> {
311312 use std::io::{Read, Seek, SeekFrom, Write};
312삭제: let total = self.folders.iter().try_fold(0u64, |sum, f| {
313삭제: crate::resources::completed(
314삭제: sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit),
315삭제: check,
316삭제: )
317삭제: })?;
313추가: let total = self
314추가: .folders
315추가: .iter()
316추가: .enumerate()
317추가: .filter(|(index, _)| selected.is_none_or(|id| id == *index))
318추가: .try_fold(0u64, |sum, (_, f)| {
319추가: crate::resources::completed(
320추가: sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit),
321추가: check,
322추가: )
323추가: })?;
318324 crate::space::ensure(output, total)?;
319삭제: for (f, (start, size)) in self.folders.iter().zip(ranges) {
325추가: for (index, (f, (start, size))) in self.folders.iter().zip(ranges).enumerate() {
320326 check.check()?;
327추가: if selected.is_some_and(|id| id != index) {
328추가: crate::resources::completed(Ok(()), check)?;
329추가: continue;
330추가: }
321331 let base = output.stream_position().map_err(crate::space::io_error)?;
322332 check.observe(
323333 ResourceUsage {
@@ -584,6 +594,16 @@ pub(crate) fn open(
584594 limits: Limits,
585595 decode: bool,
586596 check: &mut impl crate::resources::Monitor,
597추가: ) -> Result<crate::streaming::Catalog> {
598추가: open_selected(input, length, limits, decode, None, check)
599추가: }
600추가: pub(crate) fn open_selected(
601추가: input: &mut std::fs::File,
602추가: length: u64,
603추가: limits: Limits,
604추가: decode: bool,
605추가: selected: Option<u32>,
606추가: check: &mut impl crate::resources::Monitor,
587607) -> Result<crate::streaming::Catalog> {
588608 use std::io::{Read, Seek, SeekFrom};
589609 check.check()?;
@@ -652,6 +672,7 @@ pub(crate) fn open(
652672 input,
653673 &ranges,
654674 &mut data,
675추가: None,
655676 &mut crate::resources::MetadataMonitor(check),
656677 )?;
657678 data_end = 32u64
@@ -725,9 +746,15 @@ pub(crate) fn open(
725746 let ranges = streams.ranges(input, data_end, check)?;
726747 let mut at = 0u64;
727748 let mut ids = stream_indices.into_iter();
728삭제: for f in &streams.folders {
749추가: let mut selected_folder = None;
750추가: for (folder, f) in streams.folders.iter().enumerate() {
751추가: let base = at;
729752 for size in &f.sizes {
730삭제: offsets[ids.next().ok_or(ErrorCode::Integrity)?] = at;
753추가: let id = ids.next().ok_or(ErrorCode::Integrity)?;
754추가: offsets[id] = if selected.is_some() { at - base } else { at };
755추가: if selected == Some(id as u32) {
756추가: selected_folder = Some(folder);
757추가: }
731758 at = at.checked_add(*size as u64).ok_or(ErrorCode::Limit)?;
732759 crate::resources::completed(Ok(()), check)?;
733760 }
@@ -735,8 +762,8 @@ pub(crate) fn open(
735762 if at > limits.output {
736763 return Err(ErrorCode::Limit);
737764 }
738삭제: if decode {
739삭제: streams.decode_file(input, &ranges, &mut data, check)?;
765추가: if decode && (selected.is_none() || selected_folder.is_some()) {
766추가: streams.decode_file(input, &ranges, &mut data, selected_folder, check)?;
740767 }
741768 }
742769 Ok(crate::streaming::Catalog {
수정experiments/rust-archive-worker/src/streaming.rs+35-4
@@ -53,18 +53,39 @@ impl Catalog {
5353 decode: bool,
5454 password: Option<&[u8]>,
5555 check: &mut impl crate::resources::Monitor,
56추가: ) -> Result<Self> {
57추가: Self::open_selected(source, len, limits, decode, password, None, check)
58추가: }
59추가: pub fn preview(
60추가: source: &mut File,
61추가: len: u64,
62추가: limits: Limits,
63추가: password: Option<&[u8]>,
64추가: entry_id: u32,
65추가: check: &mut impl crate::resources::Monitor,
66추가: ) -> Result<Self> {
67추가: Self::open_selected(source, len, limits, true, password, Some(entry_id), check)
68추가: }
69추가: fn open_selected(
70추가: source: &mut File,
71추가: len: u64,
72추가: limits: Limits,
73추가: decode: bool,
74추가: password: Option<&[u8]>,
75추가: selected: Option<u32>,
76추가: check: &mut impl crate::resources::Monitor,
5677 ) -> Result<Self> {
5778 let mut magic = [0; 6];
5879 let n = len.min(6) as usize;
5980 at(source, 0, &mut magic[..n])?;
6081 if magic.starts_with(b"7z\xbc\xaf\x27\x1c") {
61삭제: return crate::seven_zip::open(source, len, limits, decode, check);
82추가: return crate::seven_zip::open_selected(source, len, limits, decode, selected, check);
6283 }
6384 if magic.starts_with(b"PK\x03\x04")
6485 || magic.starts_with(b"PK\x05\x06")
6586 || magic.starts_with(b"PK\x06\x06")
6687 {
67삭제: return zip(source, len, limits, decode, password, check);
88추가: return zip(source, len, limits, decode, password, selected, check);
6889 }
6990 let compression = if magic.starts_with(b"BZh") {
7091 Some(crate::compressed_tar::Compression::Bzip2)
@@ -425,6 +446,7 @@ fn zip(
425446 limits: Limits,
426447 decode: bool,
427448 password: Option<&[u8]>,
449추가: selected: Option<u32>,
428450 check: &mut impl crate::resources::Monitor,
429451) -> Result<Catalog> {
430452 if len < 22 {
@@ -712,13 +734,22 @@ fn zip(
712734 )?;
713735 let mut data = spool::temporary()?;
714736 if decode {
715삭제: crate::space::ensure(&data, total)?;
737추가: let required = if let Some(id) = selected {
738추가: members
739추가: .get(id as usize)
740추가: .ok_or(ErrorCode::InvalidRequest)?
741추가: .entry
742추가: .size
743추가: } else {
744추가: total
745추가: };
746추가: crate::space::ensure(&data, required)?;
716747 }
717748 let mut offsets = Vec::new();
718749 for (member, packed) in members.iter().zip(packed) {
719750 check.check()?;
720751 offsets.push(io(data.stream_position())?);
721삭제: if !decode {
752추가: if !decode || selected.is_some_and(|id| id != member.entry.entry_id) {
722753 crate::resources::completed(Ok(()), check)?;
723754 continue;
724755 }
수정experiments/rust-ui-memory-app/Cargo.lock+3-0
@@ -4656,11 +4656,14 @@ dependencies = [
46564656 "hmac",
46574657 "lzma-rust2",
46584658 "pbkdf2",
4659추가: "png",
46594660 "sha1",
46604661 "sha2 0.10.9",
46614662 "subtle",
46624663 "zeroize",
46634664 "zlib-rs",
4665추가: "zune-core",
4666추가: "zune-jpeg",
46644667]
46654668
46664669[[package]]
수정packaging/licenses.py+15-0
@@ -11,6 +11,13 @@ import tomllib
1111
1212ROOT = Path(__file__).resolve().parents[1]
1313
14추가: # 미리보기 디코더는 MIT 조건을 선택하며 원문 고지를 함께 수집함.
15추가: LICENSE_CHOICES = {
16추가: ("png", "0.18.1"): "MIT",
17추가: ("zune-jpeg", "0.5.15"): "MIT",
18추가: ("zune-core", "0.5.3"): "MIT",
19추가: }
20추가:
1421
1522def identity(package):
1623 return package["name"], package["version"], package.get("source") or "workspace"
@@ -186,6 +193,12 @@ def inventory(manifests, project_root=None, supplement_path=ROOT / "packaging/li
186193 else:
187194 records[key] = {"name": key[0], "version": key[1], "source": key[2],
188195 "license": package["license"], "files": files}
196추가: for record in records.values():
197추가: selected = LICENSE_CHOICES.get((record["name"], record["version"]))
198추가: if selected:
199추가: if selected not in record["license"].split(" OR "):
200추가: raise ValueError(f"선택한 라이선스 불일치: {record['name']}")
201추가: record["selected_license"] = selected
189202 return [records[key] for key in sorted(records)]
190203
191204
@@ -231,6 +244,8 @@ def render(records):
231244 for record in records:
232245 lines.extend(["=" * 72, f'{record.get("kind", "Crate")}: {record["name"]} {record["version"]}',
233246 f'Source: {record["source"]}', f'License: {record["license"]}', f'Version: {record["version"]}', ""])
247추가: if record.get("selected_license"):
248추가: lines.extend([f'Selected license: {record["selected_license"]}', ""])
234249 for file in record["files"]:
235250 lines.extend([f'File: {file["path"]}', f'SHA-256: {file["sha256"]}'])
236251 if file.get("note"):
추가tests/release-packages/test_preview_licenses.py+32-0
@@ -0,0 +1,32 @@
1추가: """미리보기 디코더의 선택한 라이선스와 고지 원문을 검증함."""
2추가: import importlib.util
3추가: from pathlib import Path
4추가: import unittest
5추가:
6추가: ROOT = Path(__file__).resolve().parents[2]
7추가: SPEC = importlib.util.spec_from_file_location("preview_licenses", ROOT / "packaging/licenses.py")
8추가: LICENSES = importlib.util.module_from_spec(SPEC)
9추가: SPEC.loader.exec_module(LICENSES)
10추가:
11추가:
12추가: class PreviewLicenses(unittest.TestCase):
13추가: def test_decoder_notices_include_selected_mit_and_verified_originals(self):
14추가: records = LICENSES.inventory([ROOT / "experiments/rust-archive-worker/Cargo.toml"])
15추가: selected = {record["name"]: record for record in records}
16추가: for name, version in [("png", "0.18.1"), ("zune-jpeg", "0.5.15"), ("zune-core", "0.5.3")]:
17추가: with self.subTest(name=name):
18추가: record = selected[name]
19추가: self.assertEqual(record["version"], version)
20추가: self.assertEqual(record["selected_license"], "MIT")
21추가: self.assertIn("MIT", record["license"].split(" OR "))
22추가: self.assertTrue(record["files"])
23추가: notice = LICENSES.render([record])
24추가: self.assertIn("Selected license: MIT", notice)
25추가: for original in record["files"]:
26추가: self.assertIn(original["text"], notice)
27추가: self.assertIn(original["sha256"], notice)
28추가: self.assertTrue({"libpng-sys", "libjpeg-sys", "mozjpeg-sys", "libz-sys"}.isdisjoint(selected))
29추가:
30추가:
31추가: if __name__ == "__main__":
32추가: unittest.main()
수정tests/rust-app-real-worker/Cargo.lock+98-0
@@ -2,6 +2,12 @@
22# It is not intended for manual editing.
33version = 4
44
5추가: [[package]]
6추가: name = "adler2"
7추가: version = "2.0.1"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10추가:
511[[package]]
612name = "aes"
713version = "0.8.4"
@@ -14,6 +20,12 @@ dependencies = [
1420 "zeroize",
1521]
1622
23추가: [[package]]
24추가: name = "bitflags"
25추가: version = "2.13.2"
26추가: source = "registry+https://github.com/rust-lang/crates.io-index"
27추가: checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
28추가:
1729[[package]]
1830name = "block-buffer"
1931version = "0.10.4"
@@ -81,6 +93,15 @@ dependencies = [
8193 "libc",
8294]
8395
96추가: [[package]]
97추가: name = "crc32fast"
98추가: version = "1.5.5"
99추가: source = "registry+https://github.com/rust-lang/crates.io-index"
100추가: checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
101추가: dependencies = [
102추가: "cfg-if",
103추가: ]
104추가:
84105[[package]]
85106name = "crypto-common"
86107version = "0.1.7"
@@ -122,6 +143,26 @@ dependencies = [
122143 "crypto-common 0.2.2",
123144]
124145
146추가: [[package]]
147추가: name = "fdeflate"
148추가: version = "0.3.7"
149추가: source = "registry+https://github.com/rust-lang/crates.io-index"
150추가: checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
151추가: dependencies = [
152추가: "simd-adler32",
153추가: ]
154추가:
155추가: [[package]]
156추가: name = "flate2"
157추가: version = "1.1.11"
158추가: source = "registry+https://github.com/rust-lang/crates.io-index"
159추가: checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
160추가: dependencies = [
161추가: "crc32fast",
162추가: "miniz_oxide 0.9.1",
163추가: "zlib-rs",
164추가: ]
165추가:
125166[[package]]
126167name = "generic-array"
127168version = "0.14.7"
@@ -180,6 +221,26 @@ dependencies = [
180221 "sha2 0.11.1",
181222]
182223
224추가: [[package]]
225추가: name = "miniz_oxide"
226추가: version = "0.8.9"
227추가: source = "registry+https://github.com/rust-lang/crates.io-index"
228추가: checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
229추가: dependencies = [
230추가: "adler2",
231추가: "simd-adler32",
232추가: ]
233추가:
234추가: [[package]]
235추가: name = "miniz_oxide"
236추가: version = "0.9.1"
237추가: source = "registry+https://github.com/rust-lang/crates.io-index"
238추가: checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
239추가: dependencies = [
240추가: "adler2",
241추가: "simd-adler32",
242추가: ]
243추가:
183244[[package]]
184245name = "pbkdf2"
185246version = "0.12.2"
@@ -190,6 +251,19 @@ dependencies = [
190251 "hmac",
191252]
192253
254추가: [[package]]
255추가: name = "png"
256추가: version = "0.18.1"
257추가: source = "registry+https://github.com/rust-lang/crates.io-index"
258추가: checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
259추가: dependencies = [
260추가: "bitflags",
261추가: "crc32fast",
262추가: "fdeflate",
263추가: "flate2",
264추가: "miniz_oxide 0.8.9",
265추가: ]
266추가:
193267[[package]]
194268name = "sha1"
195269version = "0.10.7"
@@ -223,6 +297,12 @@ dependencies = [
223297 "digest 0.11.3",
224298]
225299
300추가: [[package]]
301추가: name = "simd-adler32"
302추가: version = "0.3.10"
303추가: source = "registry+https://github.com/rust-lang/crates.io-index"
304추가: checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
305추가:
226306[[package]]
227307name = "subtle"
228308version = "2.6.1"
@@ -256,11 +336,14 @@ dependencies = [
256336 "hmac",
257337 "lzma-rust2",
258338 "pbkdf2",
339추가: "png",
259340 "sha1",
260341 "sha2 0.10.9",
261342 "subtle",
262343 "zeroize",
263344 "zlib-rs",
345추가: "zune-core",
346추가: "zune-jpeg",
264347]
265348
266349[[package]]
@@ -275,3 +358,18 @@ name = "zlib-rs"
275358version = "0.6.8"
276359source = "registry+https://github.com/rust-lang/crates.io-index"
277360checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
361추가:
362추가: [[package]]
363추가: name = "zune-core"
364추가: version = "0.5.3"
365추가: source = "registry+https://github.com/rust-lang/crates.io-index"
366추가: checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
367추가:
368추가: [[package]]
369추가: name = "zune-jpeg"
370추가: version = "0.5.15"
371추가: source = "registry+https://github.com/rust-lang/crates.io-index"
372추가: checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
373추가: dependencies = [
374추가: "zune-core",
375추가: ]
추가tests/rust-archive-worker/fixtures/preview-baseline.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-cmyk.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-gray.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-progressive.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
수정tests/rust-archive-worker/guarded.rs+1-1
@@ -8,7 +8,7 @@ impl Drop for Running {
88 let _ = self.0.wait();
99 }
1010}
11삭제: fn run(
11추가: pub(super) fn run(
1212 s: &Scratch,
1313 start: GuardedStart,
1414 respond: impl FnMut(&Message) -> Option<Vec<Message>>,
수정tests/rust-archive-worker/main.rs+2-0
@@ -1614,6 +1614,8 @@ mod conflict_wire;
16141614
16151615mod preview_wire;
16161616
1617추가: mod preview_runtime;
1618추가:
16171619mod conflicts;
16181620
16191621mod compressed_tar;
추가tests/rust-archive-worker/preview_cases.py+64-0
@@ -0,0 +1,64 @@
1추가: """독립 압축기로 미리보기 입력을 생성함."""
2추가: import gzip
3추가: import io
4추가: from pathlib import Path
5추가: import sys
6추가: import struct
7추가: import zlib
8추가: import tarfile
9추가: import zipfile
10추가:
11추가: from seven_zip_fixtures import archive, integer, property_bytes, SIGNATURE
12추가:
13추가: root = Path(sys.argv[1])
14추가: kind = sys.argv[2]
15추가: name = sys.argv[3]
16추가: data = (root / "payload").read_bytes()
17추가: if kind.startswith("zip"):
18추가: with zipfile.ZipFile(root / "input", "w", compression=zipfile.ZIP_DEFLATED) as target:
19추가: if kind.startswith("zip-selected"):
20추가: target.writestr("before.bin", b"unselected" * 10000)
21추가: target.writestr(name, data)
22추가: target.writestr("after.bin", b"unselected" * 10000)
23추가: if kind == "zip-selected-damaged":
24추가: with zipfile.ZipFile(root / "input") as target:
25추가: info = target.getinfo("before.bin")
26추가: raw = bytearray((root / "input").read_bytes())
27추가: name_size, extra_size = struct.unpack_from("<HH", raw, info.header_offset + 26)
28추가: at = info.header_offset + 30 + name_size + extra_size + info.compress_size // 2
29추가: raw[at] ^= 1
30추가: (root / "input").write_bytes(raw)
31추가: elif kind == "7z-folders":
32추가: entries = [("before.bin", b"prefix" * 10000), (name, data), ("after.bin", b"suffix" * 10000)]
33추가: parts = [part for _, part in entries]
34추가: info = b"\x06\x00\x03\x09" + b"".join(integer(len(part)) for part in parts) + b"\x00"
35추가: info += b"\x07\x0b\x03\x00" + b"\x01\x01\x00" * 3 + b"\x0c"
36추가: info += b"".join(integer(len(part)) for part in parts)
37추가: info += b"\x0a\x01" + b"".join(struct.pack("<I", zlib.crc32(part)) for part in parts) + b"\x00\x08\x00\x00"
38추가: files = b"\x05\x03" + property_bytes(17, b"\x00" + b"".join(n.encode("utf-16le") + b"\x00\x00" for n, _ in entries))
39추가: header = b"\x01\x04" + info + files + b"\x00\x00"
40추가: content = b"".join(parts)
41추가: start = struct.pack("<QQI", len(content), len(header), zlib.crc32(header))
42추가: (root / "input").write_bytes(SIGNATURE + struct.pack("<I", zlib.crc32(start)) + start + content + header)
43추가: elif kind == "aes":
44추가: import encryption_fixtures
45추가: encryption_fixtures.PAYLOAD = data
46추가: raw = encryption_fixtures.aes_zip(2, 8)
47추가: assert raw.count(b"payload.bin") == 2
48추가: (root / "input").write_bytes(raw.replace(b"payload.bin", b"payload.txt"))
49추가: elif kind.startswith("7z"):
50추가: entries = [("before.bin", b"solid prefix" * 20000, 0x20), (name, data, 0x20), ("after.bin", b"solid suffix" * 10000, 0x20)]
51추가: (root / "input").write_bytes(archive(entries, method=kind.split("-")[1], encoded=True))
52추가: elif kind == "gzip":
53추가: (root / (name + ".gz")).write_bytes(gzip.compress(data, mtime=0))
54추가: else:
55추가: with tarfile.open(root / "input", "w" if kind.startswith("tar") else "w:" + kind, format=tarfile.USTAR_FORMAT) as target:
56추가: info = tarfile.TarInfo(name)
57추가: info.size = len(data)
58추가: if kind in {"tar-folder", "tar-link"}:
59추가: info.type = tarfile.DIRTYPE if kind == "tar-folder" else tarfile.SYMTYPE
60추가: info.linkname = "target.txt" if kind == "tar-link" else ""
61추가: info.size = 0
62추가: target.addfile(info)
63추가: else:
64추가: target.addfile(info, io.BytesIO(data))
추가tests/rust-archive-worker/preview_decode.rs+280-0
@@ -0,0 +1,280 @@
1추가: use super::*;
2추가:
3추가: fn png_bytes(
4추가: width: u32,
5추가: height: u32,
6추가: color: png::ColorType,
7추가: depth: png::BitDepth,
8추가: data: &[u8],
9추가: ) -> Vec<u8> {
10추가: let mut bytes = Vec::new();
11추가: let mut encoder = png::Encoder::new(&mut bytes, width, height);
12추가: encoder.set_color(color);
13추가: encoder.set_depth(depth);
14추가: encoder
15추가: .write_header()
16추가: .unwrap()
17추가: .write_image_data(data)
18추가: .unwrap();
19추가: bytes
20추가: }
21추가: fn pixel() -> Vec<u8> {
22추가: png_bytes(
23추가: 1,
24추가: 1,
25추가: png::ColorType::Rgba,
26추가: png::BitDepth::Eight,
27추가: &[10, 20, 30, 40],
28추가: )
29추가: }
30추가: fn chunk(kind: &[u8; 4], bytes: &[u8]) -> Vec<u8> {
31추가: let mut result = (bytes.len() as u32).to_be_bytes().to_vec();
32추가: result.extend(kind);
33추가: result.extend(bytes);
34추가: result.extend(crc32(0, &result[4..]).to_be_bytes());
35추가: result
36추가: }
37추가: fn run(kind: Kind, bytes: Vec<u8>) -> Result<(PreviewInfo, Vec<u8>)> {
38추가: decode(kind, 7, bytes, &mut || Ok(()))
39추가: }
40추가:
41추가: #[test]
42추가: fn preview_text_checks_utf8_bom_and_source_boundaries() {
43추가: for bytes in [
44추가: Vec::new(),
45추가: vec![b'x'; MAX_PREVIEW_TEXT_BYTES as usize],
46추가: "한글\n".as_bytes().to_vec(),
47추가: vec![0xef, 0xbb, 0xbf],
48추가: ] {
49추가: let (info, data) = run(Kind::Text, bytes.clone()).unwrap();
50추가: assert!(info.valid());
51추가: assert_eq!(info.entry_id, 7);
52추가: assert_eq!(info.total_bytes, data.len() as u64);
53추가: assert_eq!(info.format, PreviewFormat::Utf8Text);
54추가: assert_eq!(
55추가: data,
56추가: bytes.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(&bytes)
57추가: );
58추가: }
59추가: assert!(matches!(
60추가: run(Kind::Text, vec![b'x'; MAX_PREVIEW_TEXT_BYTES as usize + 1]),
61추가: Err(ErrorCode::Limit)
62추가: ));
63추가: assert!(matches!(
64추가: run(Kind::Text, vec![0xff]),
65추가: Err(ErrorCode::Integrity)
66추가: ));
67추가: assert!(matches!(
68추가: run(Kind::Text, vec![0xef, 0xbb, 0xbf, 0xff]),
69추가: Err(ErrorCode::Integrity)
70추가: ));
71추가: }
72추가: #[test]
73추가: fn preview_extensions_are_explicit_and_ascii_case_insensitive() {
74추가: for name in [
75추가: "a.txt", "a.MD", "a.log", "a.csv", "a.JSON", "a.PnG", "a.jpg", "a.JPEG",
76추가: ] {
77추가: assert!(Kind::from_name(name).is_ok());
78추가: }
79추가: for name in ["a.svg", "a.gif", "a.webp", "a.exe", "a", "folder.txt/child"] {
80추가: assert!(Kind::from_name(name).is_err());
81추가: }
82추가: }
83추가: #[test]
84추가: fn preview_png_normalizes_gray_rgb_alpha_and_sixteen_bit_pixels() {
85추가: for (color, depth, source, expected) in [
86추가: (
87추가: png::ColorType::Rgba,
88추가: png::BitDepth::Eight,
89추가: vec![10, 20, 30, 40],
90추가: vec![10, 20, 30, 40],
91추가: ),
92추가: (
93추가: png::ColorType::Rgb,
94추가: png::BitDepth::Eight,
95추가: vec![10, 20, 30],
96추가: vec![10, 20, 30, 255],
97추가: ),
98추가: (
99추가: png::ColorType::Grayscale,
100추가: png::BitDepth::Eight,
101추가: vec![10],
102추가: vec![10, 10, 10, 255],
103추가: ),
104추가: (
105추가: png::ColorType::GrayscaleAlpha,
106추가: png::BitDepth::Eight,
107추가: vec![10, 40],
108추가: vec![10, 10, 10, 40],
109추가: ),
110추가: (
111추가: png::ColorType::GrayscaleAlpha,
112추가: png::BitDepth::Sixteen,
113추가: vec![10, 99, 40, 99],
114추가: vec![10, 10, 10, 40],
115추가: ),
116추가: ] {
117추가: let (info, data) = run(Kind::Png, png_bytes(1, 1, color, depth, &source)).unwrap();
118추가: assert_eq!((info.width, info.height, info.total_bytes), (1, 1, 4));
119추가: assert_eq!(data, expected);
120추가: }
121추가: }
122추가: #[test]
123추가: fn preview_png_rejects_crc_truncation_animation_and_format_mismatch() {
124추가: let original = pixel();
125추가: for length in [8, original.len() - 12, original.len() - 1] {
126추가: assert!(run(Kind::Png, original[..length].to_vec()).is_err());
127추가: }
128추가: let mut bad = original.clone();
129추가: bad[29] ^= 1;
130추가: assert!(matches!(run(Kind::Png, bad), Err(ErrorCode::Integrity)));
131추가: let mut trailing = original.clone();
132추가: trailing.push(0);
133추가: assert!(matches!(
134추가: run(Kind::Png, trailing),
135추가: Err(ErrorCode::Integrity)
136추가: ));
137추가: let mut animated = original.clone();
138추가: animated.splice(33..33, chunk(b"acTL", &[0, 0, 0, 1, 0, 0, 0, 0]));
139추가: assert!(matches!(
140추가: run(Kind::Png, animated),
141추가: Err(ErrorCode::UnsupportedFeature)
142추가: ));
143추가: assert!(matches!(
144추가: run(Kind::Png, b"GIF89a".to_vec()),
145추가: Err(ErrorCode::UnsupportedFormat)
146추가: ));
147추가: }
148추가: #[test]
149추가: fn preview_png_checks_dimensions_and_pixels_before_decoding() {
150추가: for (width, height) in [
151추가: (8193u32, 1u32),
152추가: (1, 8193),
153추가: (4001, 4000),
154추가: (8192, 8192),
155추가: (u32::MAX, u32::MAX),
156추가: ] {
157추가: let mut bytes = pixel();
158추가: bytes[16..20].copy_from_slice(&width.to_be_bytes());
159추가: bytes[20..24].copy_from_slice(&height.to_be_bytes());
160추가: let crc = crc32(0, &bytes[12..29]);
161추가: bytes[29..33].copy_from_slice(&crc.to_be_bytes());
162추가: assert!(
163추가: matches!(run(Kind::Png, bytes), Err(ErrorCode::Limit)),
164추가: "{width}x{height}"
165추가: );
166추가: }
167추가: for (width, height) in [(8192, 1), (1, 8192), (4000, 4000)] {
168추가: let bytes = png_bytes(
169추가: width,
170추가: height,
171추가: png::ColorType::Rgba,
172추가: png::BitDepth::Eight,
173추가: &vec![0; (width * height * 4) as usize],
174추가: );
175추가: let (info, rgba) = run(Kind::Png, bytes).unwrap();
176추가: assert_eq!((info.width, info.height), (width, height));
177추가: assert_eq!(rgba.len(), (width * height * 4) as usize);
178추가: }
179추가: }
180추가: #[test]
181추가: fn preview_image_source_limit_includes_ancillary_bytes() {
182추가: let mut bytes = pixel();
183추가: let at = bytes.len() - 12;
184추가: let padding = vec![0; MAX_PREVIEW_IMAGE_BYTES as usize - bytes.len() - 12];
185추가: bytes.splice(at..at, chunk(b"teSt", &padding));
186추가: assert_eq!(bytes.len(), MAX_PREVIEW_IMAGE_BYTES as usize);
187추가: assert!(run(Kind::Png, bytes.clone()).is_ok());
188추가: bytes.push(0);
189추가: assert!(matches!(run(Kind::Png, bytes), Err(ErrorCode::Limit)));
190추가: assert!(matches!(
191추가: run(Kind::Jpeg, vec![0; MAX_PREVIEW_IMAGE_BYTES as usize + 1]),
192추가: Err(ErrorCode::Limit)
193추가: ));
194추가: }
195추가: #[test]
196추가: fn preview_jpeg_strictly_decodes_baseline_and_progressive() {
197추가: for bytes in [
198추가: include_bytes!("fixtures/preview-baseline.jpg").as_slice(),
199추가: include_bytes!("fixtures/preview-progressive.jpg").as_slice(),
200추가: ] {
201추가: let (info, data) = run(Kind::Jpeg, bytes.to_vec()).unwrap();
202추가: assert_eq!((info.width, info.height, info.total_bytes), (3, 2, 24));
203추가: for pixel in data.chunks_exact(4) {
204추가: assert_eq!(pixel[3], 255);
205추가: assert!(pixel[0] > 200 && pixel[1] < 60 && pixel[2] < 80);
206추가: }
207추가: for length in [2, bytes.len() / 2, bytes.len() - 1] {
208추가: assert!(run(Kind::Jpeg, bytes[..length].to_vec()).is_err());
209추가: }
210추가: let mut incomplete = bytes[..bytes.len() / 2].to_vec();
211추가: incomplete.extend([0xff, 0xd9]);
212추가: assert!(run(Kind::Jpeg, incomplete).is_err());
213추가: }
214추가: assert!(matches!(
215추가: run(Kind::Jpeg, pixel()),
216추가: Err(ErrorCode::UnsupportedFormat)
217추가: ));
218추가: }
219추가: #[test]
220추가: fn preview_cancellation_discards_decoded_results_and_conversion() {
221추가: for kind in [Kind::Text, Kind::Png, Kind::Jpeg] {
222추가: let source = match kind {
223추가: Kind::Text => b"text".to_vec(),
224추가: Kind::Png => pixel(),
225추가: Kind::Jpeg => include_bytes!("fixtures/preview-baseline.jpg").to_vec(),
226추가: };
227추가: let mut calls = 0;
228추가: assert!(matches!(
229추가: decode(kind, 7, source, &mut || {
230추가: calls += 1;
231추가: if calls >= 2 {
232추가: Err(ErrorCode::None)
233추가: } else {
234추가: Ok(())
235추가: }
236추가: }),
237추가: Err(ErrorCode::None)
238추가: ));
239추가: }
240추가: }
241추가:
242추가: #[test]
243추가: fn preview_jpeg_checks_dimensions_before_decoder_allocation() {
244추가: let original = include_bytes!("fixtures/preview-baseline.jpg");
245추가: let at = original.windows(2).position(|p| p == [0xff, 0xc0]).unwrap();
246추가: for (width, height) in [(8193u16, 1u16), (1, 8193), (4001, 4000), (8192, 8192)] {
247추가: let mut bytes = original.to_vec();
248추가: bytes[at + 5..at + 7].copy_from_slice(&height.to_be_bytes());
249추가: bytes[at + 7..at + 9].copy_from_slice(&width.to_be_bytes());
250추가: assert!(
251추가: matches!(run(Kind::Jpeg, bytes), Err(ErrorCode::Limit)),
252추가: "{width}x{height}"
253추가: );
254추가: }
255추가: let mut multiple = original.to_vec();
256추가: multiple.extend(original);
257추가: assert!(run(Kind::Jpeg, multiple).is_err());
258추가: }
259추가:
260추가: #[test]
261추가: fn preview_jpeg_normalizes_gray_and_cmyk_to_rgba() {
262추가: for (bytes, gray) in [
263추가: (include_bytes!("fixtures/preview-gray.jpg").as_slice(), true),
264추가: (
265추가: include_bytes!("fixtures/preview-cmyk.jpg").as_slice(),
266추가: false,
267추가: ),
268추가: ] {
269추가: let (info, pixels) = run(Kind::Jpeg, bytes.to_vec()).unwrap();
270추가: assert_eq!((info.width, info.height, info.total_bytes), (3, 2, 24));
271추가: for pixel in pixels.chunks_exact(4) {
272추가: assert_eq!(pixel[3], 255);
273추가: if gray {
274추가: assert!(pixel[..3].iter().all(|v| v.abs_diff(80) <= 2));
275추가: } else {
276추가: assert!(pixel[0] > 240 && pixel[1] < 20 && pixel[2] < 20);
277추가: }
278추가: }
279추가: }
280추가: }
추가tests/rust-archive-worker/preview_runtime.rs+383-0
@@ -0,0 +1,383 @@
1추가: use super::*;
2추가: use sha2::{Digest, Sha256};
3추가:
4추가: fn fixture(format: &str, name: &str, bytes: &[u8]) -> (Scratch, String, ListId, u32) {
5추가: let s = Scratch::new();
6추가: fs::write(s.0.join("payload"), bytes).unwrap();
7추가: let script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8추가: .join("../../tests/rust-archive-worker/preview_cases.py");
9추가: let result = Command::new("python3")
10추가: .arg("-B")
11추가: .arg(script)
12추가: .arg(&s.0)
13추가: .arg(format)
14추가: .arg(name)
15추가: .output()
16추가: .unwrap();
17추가: assert!(
18추가: result.status.success(),
19추가: "{}",
20추가: String::from_utf8_lossy(&result.stderr)
21추가: );
22추가: let path = if format == "gzip" {
23추가: format!("{name}.gz")
24추가: } else {
25추가: "input".into()
26추가: };
27추가: let events = execute(Start {
28추가: action: Action::List {
29추가: archive: s.path(&path),
30추가: },
31추가: limits: Limits::default(),
32추가: });
33추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
34추가: let id = events
35추가: .iter()
36추가: .find_map(|e| match e {
37추가: Message::Entry(entry) if entry.name == name || format == "gzip" => Some(entry.entry_id),
38추가: _ => None,
39추가: })
40추가: .unwrap();
41추가: let list = events
42추가: .into_iter()
43추가: .find_map(|e| match e {
44추가: Message::ListEnd { list_id, .. } => Some(list_id),
45추가: _ => None,
46추가: })
47추가: .unwrap();
48추가: (s, path, list, id)
49추가: }
50추가: fn request(s: &Scratch, path: &str, list_id: ListId, entry_id: u32) -> GuardedStart {
51추가: GuardedStart {
52추가: start: Start {
53추가: action: Action::Preview {
54추가: archive: s.path(path),
55추가: entry_id,
56추가: list_id,
57추가: },
58추가: limits: Limits::default(),
59추가: },
60추가: ceiling: Limits::default(),
61추가: interactive: true,
62추가: }
63추가: }
64추가: fn run(s: &Scratch, start: GuardedStart) -> Vec<Message> {
65추가: guarded::run(s, start, |event| match event {
66추가: Message::ResourceRequired {
67추가: challenge_id,
68추가: scope,
69추가: ..
70추가: } => Some(vec![Message::ResourceReply {
71추가: challenge_id: *challenge_id,
72추가: scope: *scope,
73추가: allow: true,
74추가: }]),
75추가: Message::PasswordRequired { challenge_id, .. } => Some(vec![Message::Password {
76추가: challenge_id: *challenge_id,
77추가: secret: Secret(b"fixture-password".to_vec()),
78추가: }]),
79추가: _ => None,
80추가: })
81추가: }
82추가: fn result(events: &[Message]) -> (PreviewInfo, Vec<u8>) {
83추가: let terminal = terminal(events);
84추가: assert_eq!(terminal.outcome, Outcome::Completed, "{events:?}");
85추가: assert_eq!(terminal.publication, Publication::None);
86추가: assert_eq!(terminal.created_count, 0);
87추가: assert_eq!(terminal.cleanup, Cleanup::Complete);
88추가: assert!(
89추가: !events
90추가: .iter()
91추가: .any(|e| matches!(e, Message::Output { .. } | Message::ConflictRequired { .. }))
92추가: );
93추가: let mut info = None;
94추가: let mut data = Vec::new();
95추가: let mut ended = false;
96추가: for event in events {
97추가: match event {
98추가: Message::PreviewBegin(value) => {
99추가: assert!(info.replace(*value).is_none());
100추가: assert!(value.valid());
101추가: }
102추가: Message::PreviewChunk {
103추가: entry_id,
104추가: offset,
105추가: data: bytes,
106추가: } => {
107추가: assert!(!ended);
108추가: assert_eq!(Some(*entry_id), info.map(|i| i.entry_id));
109추가: assert_eq!(*offset, data.len() as u64);
110추가: assert!(bytes.len() <= MAX_PREVIEW_CHUNK_BYTES);
111추가: data.extend(bytes);
112추가: }
113추가: Message::PreviewEnd {
114추가: entry_id,
115추가: total_bytes,
116추가: sha256,
117추가: } => {
118추가: assert!(!ended);
119추가: ended = true;
120추가: let info = info.unwrap();
121추가: assert_eq!(*entry_id, info.entry_id);
122추가: assert_eq!(*total_bytes, info.total_bytes);
123추가: assert_eq!(*total_bytes, data.len() as u64);
124추가: assert_eq!(*sha256, <[u8; 32]>::from(Sha256::digest(&data)));
125추가: }
126추가: _ => {}
127추가: }
128추가: }
129추가: assert!(ended);
130추가: (info.unwrap(), data)
131추가: }
132추가: fn no_result(events: &[Message], error: ErrorCode) {
133추가: assert_eq!(terminal(events).outcome, Outcome::Failed, "{events:?}");
134추가: assert_eq!(terminal(events).error, error, "{events:?}");
135추가: assert_eq!(terminal(events).publication, Publication::None);
136추가: assert_eq!(terminal(events).created_count, 0);
137추가: assert!(!events.iter().any(|e| matches!(
138추가: e,
139추가: Message::PreviewBegin(_)
140추가: | Message::PreviewChunk { .. }
141추가: | Message::PreviewEnd { .. }
142추가: | Message::Output { .. }
143추가: )));
144추가: }
145추가: fn png(width: u32, height: u32) -> Vec<u8> {
146추가: let mut bytes = Vec::new();
147추가: let mut encoder = png::Encoder::new(&mut bytes, width, height);
148추가: encoder.set_color(png::ColorType::Rgba);
149추가: let mut writer = encoder.write_header().unwrap();
150추가: writer
151추가: .write_image_data(&vec![20; (width * height * 4) as usize])
152추가: .unwrap();
153추가: drop(writer);
154추가: bytes
155추가: }
156추가: #[test]
157추가: fn preview_actual_formats_keep_source_and_publish_nothing() {
158추가: for format in [
159추가: "zip",
160추가: "zip-selected",
161추가: "zip-selected-damaged",
162추가: "7z-folders",
163추가: "tar",
164추가: "gz",
165추가: "bz2",
166추가: "xz",
167추가: "gzip",
168추가: "7z-copy",
169추가: "7z-lzma",
170추가: "7z-lzma2",
171추가: "aes",
172추가: ] {
173추가: let expected = "가나다\n".repeat(10000);
174추가: let (s, path, list, id) = fixture(format, "payload.txt", expected.as_bytes());
175추가: let original = fs::read(s.0.join(&path)).unwrap();
176추가: let (_, data) = result(&run(&s, request(&s, &path, list, id)));
177추가: assert_eq!(data, expected.as_bytes(), "{format}");
178추가: assert_eq!(fs::read(s.0.join(&path)).unwrap(), original);
179추가: assert_eq!(fs::read_dir(&s.0).unwrap().count(), 2);
180추가: }
181추가: }
182추가: #[test]
183추가: fn preview_actual_png_and_jpeg_have_exact_rgba_metadata() {
184추가: for (name, bytes, width, height) in [
185추가: ("payload.png", png(3, 2), 3, 2),
186추가: (
187추가: "payload.jpg",
188추가: include_bytes!("fixtures/preview-baseline.jpg").to_vec(),
189추가: 3,
190추가: 2,
191추가: ),
192추가: (
193추가: "payload.jpeg",
194추가: include_bytes!("fixtures/preview-progressive.jpg").to_vec(),
195추가: 3,
196추가: 2,
197추가: ),
198추가: ] {
199추가: for format in ["zip", "tar", "7z-lzma2"] {
200추가: let (s, path, list, id) = fixture(format, name, &bytes);
201추가: let (info, data) = result(&run(&s, request(&s, &path, list, id)));
202추가: assert_eq!(
203추가: (info.width, info.height, info.total_bytes),
204추가: (width, height, u64::from(width * height * 4))
205추가: );
206추가: assert_eq!(data.len(), (width * height * 4) as usize);
207추가: }
208추가: }
209추가: }
210추가: #[test]
211추가: fn preview_own_limit_is_not_expanded_by_permission() {
212추가: for (name, bytes) in [
213추가: (
214추가: "payload.txt",
215추가: vec![b'x'; MAX_PREVIEW_TEXT_BYTES as usize + 1],
216추가: ),
217추가: ("payload.png", vec![0; MAX_PREVIEW_IMAGE_BYTES as usize + 1]),
218추가: ] {
219추가: let (s, path, list, id) = fixture("zip", name, &bytes);
220추가: let mut start = request(&s, &path, list, id);
221추가: start.ceiling.output = 64 * 1024 * 1024 * 1024;
222추가: let events = run(&s, start);
223추가: assert!(
224추가: events
225추가: .iter()
226추가: .any(|e| matches!(e, Message::ResourceRequired { .. }))
227추가: );
228추가: no_result(&events, ErrorCode::Limit);
229추가: }
230추가: let expected = vec![b'x'; MAX_PREVIEW_TEXT_BYTES as usize];
231추가: let (s, path, list, id) = fixture("zip", "payload.txt", &expected);
232추가: assert_eq!(result(&run(&s, request(&s, &path, list, id))).1, expected);
233추가: }
234추가: #[test]
235추가: fn preview_rejects_corruption_unsupported_and_stale_selection() {
236추가: for (name, bytes, error) in [
237추가: ("payload.txt", vec![0xff], ErrorCode::Integrity),
238추가: (
239추가: "payload.svg",
240추가: b"<svg/>".to_vec(),
241추가: ErrorCode::UnsupportedFeature,
242추가: ),
243추가: (
244추가: "payload.png",
245추가: b"GIF89a".to_vec(),
246추가: ErrorCode::UnsupportedFormat,
247추가: ),
248추가: ("payload.jpg", vec![0xff, 0xd8], ErrorCode::Integrity),
249추가: ] {
250추가: let (s, path, list, id) = fixture("zip", name, &bytes);
251추가: no_result(&run(&s, request(&s, &path, list, id)), error);
252추가: }
253추가: let (s, path, list, id) = fixture("zip", "payload.txt", b"text");
254추가: let mut changed = list.clone();
255추가: changed.archive_sha256[0] ^= 1;
256추가: no_result(
257추가: &run(&s, request(&s, &path, changed, id)),
258추가: ErrorCode::SourceChanged,
259추가: );
260추가: no_result(
261추가: &run(&s, request(&s, &path, list, u32::MAX)),
262추가: ErrorCode::InvalidRequest,
263추가: );
264추가: }
265추가: #[test]
266추가: fn preview_solid_budget_still_applies_to_preceding_content() {
267추가: let (s, path, list, id) = fixture("7z-lzma2", "payload.txt", b"text");
268추가: let mut start = request(&s, &path, list, id);
269추가: start.start.limits.output = 100_000;
270추가: start.ceiling = start.start.limits;
271추가: no_result(&run(&s, start), ErrorCode::Limit);
272추가: }
273추가: #[test]
274추가: fn preview_cancels_before_decode_and_during_chunk_transmission() {
275추가: for stage in [0, 1, 2] {
276추가: let (s, path, list, id) = fixture("zip", "payload.png", &png(4000, 4000));
277추가: let mut cancelled = false;
278추가: let events = guarded::run(&s, request(&s, &path, list, id), |event| {
279추가: let target = match stage {
280추가: 0 => matches!(event, Message::Accepted { .. }),
281추가: 1 => matches!(
282추가: event,
283추가: Message::Progress {
284추가: stage: Stage::Decode,
285추가: ..
286추가: }
287추가: ),
288추가: _ => matches!(event, Message::PreviewChunk { .. }),
289추가: };
290추가: if target && !cancelled {
291추가: cancelled = true;
292추가: Some(vec![Message::Cancel])
293추가: } else {
294추가: None
295추가: }
296추가: });
297추가: assert!(cancelled);
298추가: assert_eq!(
299추가: terminal(&events).outcome,
300추가: Outcome::Cancelled,
301추가: "stage={stage}"
302추가: );
303추가: assert_eq!(terminal(&events).publication, Publication::None);
304추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
305추가: assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
306추가: }
307추가: }
308추가:
309추가: #[test]
310추가: fn preview_password_retry_and_cancel_never_publish_plaintext() {
311추가: let (s, path, list, id) = fixture("aes", "payload.txt", b"secret preview");
312추가: let mut attempts = Vec::new();
313추가: let events = guarded::run(
314추가: &s,
315추가: request(&s, &path, list.clone(), id),
316추가: |event| match event {
317추가: Message::PasswordRequired {
318추가: challenge_id,
319추가: attempt,
320추가: ..
321추가: } => {
322추가: attempts.push(*attempt);
323추가: Some(vec![Message::Password {
324추가: challenge_id: *challenge_id,
325추가: secret: Secret(if *attempt == 1 {
326추가: b"wrong".to_vec()
327추가: } else {
328추가: b"fixture-password".to_vec()
329추가: }),
330추가: }])
331추가: }
332추가: _ => None,
333추가: },
334추가: );
335추가: assert_eq!(attempts, [1, 2]);
336추가: assert_eq!(result(&events).1, b"secret preview");
337추가: let events = guarded::run(&s, request(&s, &path, list, id), |event| {
338추가: if matches!(event, Message::PasswordRequired { .. }) {
339추가: Some(vec![Message::Cancel])
340추가: } else {
341추가: None
342추가: }
343추가: });
344추가: assert_eq!(terminal(&events).outcome, Outcome::Cancelled);
345추가: assert!(!events.iter().any(|e| matches!(
346추가: e,
347추가: Message::PreviewBegin(_)
348추가: | Message::PreviewChunk { .. }
349추가: | Message::PreviewEnd { .. }
350추가: | Message::Output { .. }
351추가: )));
352추가: }
353추가:
354추가: #[test]
355추가: fn preview_empty_text_uses_begin_and_end_without_chunks() {
356추가: for format in ["zip", "tar", "7z-lzma2", "gzip"] {
357추가: let (s, path, list, id) = fixture(format, "payload.txt", b"");
358추가: let events = run(&s, request(&s, &path, list, id));
359추가: assert!(result(&events).1.is_empty());
360추가: assert!(
361추가: !events
362추가: .iter()
363추가: .any(|e| matches!(e, Message::PreviewChunk { .. }))
364추가: );
365추가: }
366추가: }
367추가: #[test]
368추가: fn preview_rejects_directory_link_and_changed_source_object() {
369추가: for format in ["tar-folder", "tar-link"] {
370추가: let (s, path, list, id) = fixture(format, "payload.txt", b"");
371추가: no_result(
372추가: &run(&s, request(&s, &path, list, id)),
373추가: ErrorCode::InvalidRequest,
374추가: );
375추가: }
376추가: let (s, path, list, id) = fixture("zip", "payload.txt", b"original");
377추가: fs::write(s.0.join(&path), b"changed").unwrap();
378추가: no_result(
379추가: &run(&s, request(&s, &path, list, id)),
380추가: ErrorCode::SourceChanged,
381추가: );
382추가: assert_eq!(fs::read(s.0.join(&path)).unwrap(), b"changed");
383추가: }
수정tests/rust-large-archive-fixtures/Cargo.lock+98-0
@@ -2,6 +2,12 @@
22# It is not intended for manual editing.
33version = 4
44
5추가: [[package]]
6추가: name = "adler2"
7추가: version = "2.0.1"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10추가:
511[[package]]
612name = "aes"
713version = "0.8.4"
@@ -14,6 +20,12 @@ dependencies = [
1420 "zeroize",
1521]
1622
23추가: [[package]]
24추가: name = "bitflags"
25추가: version = "2.13.2"
26추가: source = "registry+https://github.com/rust-lang/crates.io-index"
27추가: checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
28추가:
1729[[package]]
1830name = "block-buffer"
1931version = "0.10.4"
@@ -81,6 +93,15 @@ dependencies = [
8193 "libc",
8294]
8395
96추가: [[package]]
97추가: name = "crc32fast"
98추가: version = "1.5.5"
99추가: source = "registry+https://github.com/rust-lang/crates.io-index"
100추가: checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
101추가: dependencies = [
102추가: "cfg-if",
103추가: ]
104추가:
84105[[package]]
85106name = "crypto-common"
86107version = "0.1.7"
@@ -122,6 +143,26 @@ dependencies = [
122143 "crypto-common 0.2.2",
123144]
124145
146추가: [[package]]
147추가: name = "fdeflate"
148추가: version = "0.3.7"
149추가: source = "registry+https://github.com/rust-lang/crates.io-index"
150추가: checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
151추가: dependencies = [
152추가: "simd-adler32",
153추가: ]
154추가:
155추가: [[package]]
156추가: name = "flate2"
157추가: version = "1.1.11"
158추가: source = "registry+https://github.com/rust-lang/crates.io-index"
159추가: checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
160추가: dependencies = [
161추가: "crc32fast",
162추가: "miniz_oxide 0.9.1",
163추가: "zlib-rs",
164추가: ]
165추가:
125166[[package]]
126167name = "generic-array"
127168version = "0.14.7"
@@ -180,6 +221,26 @@ dependencies = [
180221 "sha2 0.11.1",
181222]
182223
224추가: [[package]]
225추가: name = "miniz_oxide"
226추가: version = "0.8.9"
227추가: source = "registry+https://github.com/rust-lang/crates.io-index"
228추가: checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
229추가: dependencies = [
230추가: "adler2",
231추가: "simd-adler32",
232추가: ]
233추가:
234추가: [[package]]
235추가: name = "miniz_oxide"
236추가: version = "0.9.1"
237추가: source = "registry+https://github.com/rust-lang/crates.io-index"
238추가: checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
239추가: dependencies = [
240추가: "adler2",
241추가: "simd-adler32",
242추가: ]
243추가:
183244[[package]]
184245name = "pbkdf2"
185246version = "0.12.2"
@@ -190,6 +251,19 @@ dependencies = [
190251 "hmac",
191252]
192253
254추가: [[package]]
255추가: name = "png"
256추가: version = "0.18.1"
257추가: source = "registry+https://github.com/rust-lang/crates.io-index"
258추가: checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
259추가: dependencies = [
260추가: "bitflags",
261추가: "crc32fast",
262추가: "fdeflate",
263추가: "flate2",
264추가: "miniz_oxide 0.8.9",
265추가: ]
266추가:
193267[[package]]
194268name = "sha1"
195269version = "0.10.7"
@@ -223,6 +297,12 @@ dependencies = [
223297 "digest 0.11.3",
224298]
225299
300추가: [[package]]
301추가: name = "simd-adler32"
302추가: version = "0.3.10"
303추가: source = "registry+https://github.com/rust-lang/crates.io-index"
304추가: checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
305추가:
226306[[package]]
227307name = "subtle"
228308version = "2.6.1"
@@ -256,11 +336,14 @@ dependencies = [
256336 "hmac",
257337 "lzma-rust2",
258338 "pbkdf2",
339추가: "png",
259340 "sha1",
260341 "sha2 0.10.9",
261342 "subtle",
262343 "zeroize",
263344 "zlib-rs",
345추가: "zune-core",
346추가: "zune-jpeg",
264347]
265348
266349[[package]]
@@ -275,3 +358,18 @@ name = "zlib-rs"
275358version = "0.6.8"
276359source = "registry+https://github.com/rust-lang/crates.io-index"
277360checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
361추가:
362추가: [[package]]
363추가: name = "zune-core"
364추가: version = "0.5.3"
365추가: source = "registry+https://github.com/rust-lang/crates.io-index"
366추가: checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
367추가:
368추가: [[package]]
369추가: name = "zune-jpeg"
370추가: version = "0.5.15"
371추가: source = "registry+https://github.com/rust-lang/crates.io-index"
372추가: checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
373추가: dependencies = [
374추가: "zune-core",
375추가: ]
수정tests/rust-zip64-compat/Cargo.lock+98-0
@@ -2,6 +2,12 @@
22# It is not intended for manual editing.
33version = 4
44
5추가: [[package]]
6추가: name = "adler2"
7추가: version = "2.0.1"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
10추가:
511[[package]]
612name = "aes"
713version = "0.8.4"
@@ -14,6 +20,12 @@ dependencies = [
1420 "zeroize",
1521]
1622
23추가: [[package]]
24추가: name = "bitflags"
25추가: version = "2.13.2"
26추가: source = "registry+https://github.com/rust-lang/crates.io-index"
27추가: checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
28추가:
1729[[package]]
1830name = "block-buffer"
1931version = "0.10.4"
@@ -81,6 +93,15 @@ dependencies = [
8193 "libc",
8294]
8395
96추가: [[package]]
97추가: name = "crc32fast"
98추가: version = "1.5.5"
99추가: source = "registry+https://github.com/rust-lang/crates.io-index"
100추가: checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
101추가: dependencies = [
102추가: "cfg-if",
103추가: ]
104추가:
84105[[package]]
85106name = "crypto-common"
86107version = "0.1.7"
@@ -122,6 +143,26 @@ dependencies = [
122143 "crypto-common 0.2.2",
123144]
124145
146추가: [[package]]
147추가: name = "fdeflate"
148추가: version = "0.3.7"
149추가: source = "registry+https://github.com/rust-lang/crates.io-index"
150추가: checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
151추가: dependencies = [
152추가: "simd-adler32",
153추가: ]
154추가:
155추가: [[package]]
156추가: name = "flate2"
157추가: version = "1.1.11"
158추가: source = "registry+https://github.com/rust-lang/crates.io-index"
159추가: checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
160추가: dependencies = [
161추가: "crc32fast",
162추가: "miniz_oxide 0.9.1",
163추가: "zlib-rs",
164추가: ]
165추가:
125166[[package]]
126167name = "generic-array"
127168version = "0.14.7"
@@ -180,6 +221,26 @@ dependencies = [
180221 "sha2 0.11.1",
181222]
182223
224추가: [[package]]
225추가: name = "miniz_oxide"
226추가: version = "0.8.9"
227추가: source = "registry+https://github.com/rust-lang/crates.io-index"
228추가: checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
229추가: dependencies = [
230추가: "adler2",
231추가: "simd-adler32",
232추가: ]
233추가:
234추가: [[package]]
235추가: name = "miniz_oxide"
236추가: version = "0.9.1"
237추가: source = "registry+https://github.com/rust-lang/crates.io-index"
238추가: checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
239추가: dependencies = [
240추가: "adler2",
241추가: "simd-adler32",
242추가: ]
243추가:
183244[[package]]
184245name = "pbkdf2"
185246version = "0.12.2"
@@ -190,6 +251,19 @@ dependencies = [
190251 "hmac",
191252]
192253
254추가: [[package]]
255추가: name = "png"
256추가: version = "0.18.1"
257추가: source = "registry+https://github.com/rust-lang/crates.io-index"
258추가: checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
259추가: dependencies = [
260추가: "bitflags",
261추가: "crc32fast",
262추가: "fdeflate",
263추가: "flate2",
264추가: "miniz_oxide 0.8.9",
265추가: ]
266추가:
193267[[package]]
194268name = "sha1"
195269version = "0.10.7"
@@ -223,6 +297,12 @@ dependencies = [
223297 "digest 0.11.3",
224298]
225299
300추가: [[package]]
301추가: name = "simd-adler32"
302추가: version = "0.3.10"
303추가: source = "registry+https://github.com/rust-lang/crates.io-index"
304추가: checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
305추가:
226306[[package]]
227307name = "subtle"
228308version = "2.6.1"
@@ -256,11 +336,14 @@ dependencies = [
256336 "hmac",
257337 "lzma-rust2",
258338 "pbkdf2",
339추가: "png",
259340 "sha1",
260341 "sha2 0.10.9",
261342 "subtle",
262343 "zeroize",
263344 "zlib-rs",
345추가: "zune-core",
346추가: "zune-jpeg",
264347]
265348
266349[[package]]
@@ -275,3 +358,18 @@ name = "zlib-rs"
275358version = "0.6.8"
276359source = "registry+https://github.com/rust-lang/crates.io-index"
277360checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
361추가:
362추가: [[package]]
363추가: name = "zune-core"
364추가: version = "0.5.3"
365추가: source = "registry+https://github.com/rust-lang/crates.io-index"
366추가: checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
367추가:
368추가: [[package]]
369추가: name = "zune-jpeg"
370추가: version = "0.5.15"
371추가: source = "registry+https://github.com/rust-lang/crates.io-index"
372추가: checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
373추가: dependencies = [
374추가: "zune-core",
375추가: ]