압축비 거부를 제거하고 여유 공간 검사를 추가함
- 작성자
- 시로사키 하나
- 작성 시각
- 커밋
6ede8615e4a289b589827b992d7cb678d50c0a2d- 부모
- bcc9c5c
변경된 파일 14개
+339-84| @@ -13,9 +13,11 @@ | ||
| 13 | 13 | |
| 14 | 14 | ## 스트리밍과 자원 정리 |
| 15 | 15 | |
| 16 | 삭제: 기존 revision 2의 필드와 tag를 유지하고 입력/출력 기본 한도를 변경하는 안에 frontend/backend가 공동 합의했습니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 세부 계약은 contract.json의 streaming_limits에 있습니다. | |
| 16 | 추가: 기존 revision 2의 필드와 tag 및 공동 합의한 입력/출력 기본 한도를 유지합니다. 앱이 공유하는 Limits::default()도 같은 값을 사용합니다. 압축비 거부 제거와 여유 공간 검사의 frontend 확인은 PR에서 별도로 받습니다. 세부 계약은 contract.json의 streaming_limits에 있습니다. | |
| 17 | 17 | |
| 18 | 삭제: - ZIP은 각 항목의 압축 payload 바이트에서 암호 framing을 뺀 값을 분모로 1000:1을 적용합니다. 선언 크기를 먼저 검사하고 실제 해제 크기, CRC와 AES 인증을 다시 확인합니다. GZ는 연결된 각 멤버의 실제 소비 바이트(헤더와 trailer 포함)와 해제 바이트로 비율을 검사하므로 뒤에 붙인 멤버가 앞의 폭탄 비율을 희석하지 않습니다. 연결 멤버 전체 해제량도 총량 한도에 포함하며 TAR.GZ의 헤더와 padding도 계산합니다. u64 누계/offset은 checked 연산, 비율 비교는 u128을 사용합니다. | |
| 18 | 추가: - 압축비는 거부 조건으로 사용하지 않습니다. ZIP 선언 크기와 실제 해제 크기, CRC와 AES 인증을 검사하며, GZ 연결 멤버의 전체 해제량도 16 GiB 총량 한도에 포함합니다. TAR.GZ의 헤더와 padding도 계산합니다. u64 누계와 offset은 checked 연산을 사용합니다. | |
| 19 | 추가: - 입력 캡처 전에 임시 저장소 여유 공간을 확인합니다. ZIP/7z 해제 전에는 전체 임시 해제량과 선택한 출력량을 볼륨별로 합산해 검사하고, 게시 전에도 출력 공간을 재검사합니다. 미리 해제 크기를 알 수 없는 GZ/TAR.GZ는 각 해제 청크를 쓰기 전에 임시 저장소 공간을 확인합니다. Linux 64비트는 열린 핸들의 [fstatvfs](https://man7.org/linux/man-pages/man3/fstatvfs.3.html), Windows는 핸들에서 얻은 디렉터리의 [GetDiskFreeSpaceExW](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getdiskfreespaceexw)를 사용합니다. 조회 실패와 부족은 기존 Io로 반환합니다. | |
| 20 | 추가: - 공간 검사는 논리적 파일 크기에 따른 사전 확인이며 예약이나 모든 메타데이터/할당 단위 비용의 보장이 아닙니다. 다른 작업과 경쟁해 나중에 ENOSPC가 발생하면 기존 부분 출력 정리 정책을 적용합니다. 16 GiB 안에서는 압축비가 매우 큰 파일도 디스크에 풀릴 수 있습니다. 이 정책의 frontend 계약 확인은 PR에서 별도로 받습니다. | |
| 19 | 21 | - 입력과 검증된 해제 내용은 임시 파일에 저장합니다. Linux는 [O_TMPFILE](https://man7.org/linux/man-pages/man2/open.2.html), 이를 지원하지 않는 Linux 파일시스템에서는 0600 난수 파일을 배타적으로 만든 즉시 unlink하고 링크 수 0을 확인합니다. Windows는 배타적 [DELETE_ON_CLOSE 파일](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew)을 사용합니다. 마지막 핸들이 닫히면 제거되며 임시 파일명에 아카이브 내부 이름을 사용하지 않습니다. 디스크에는 입력 사본, 해제 내용과 현재 출력 임시 파일이 동시에 필요할 수 있습니다. 임시 폴더가 tmpfs이면 해당 파일 내용은 프로세스 RSS 외의 시스템 메모리를 사용합니다. |
| 20 | 22 | - 64 MiB는 ZIP/TAR/GZ/TAR.GZ 해제 작업자 프로세스의 피크 RSS 시험 목표입니다. OS 메모리 강제 격리나 모든 아카이브의 보장을 뜻하지 않습니다. 7z와 생성은 이 RSS 목표에 포함하지 않습니다. 입력 크기와 무관한 메타데이터 예산은 유지합니다. |
| 21 | 23 | - Linux는 시작 시 부모 PID를 캡처하고 [getppid](https://man7.org/linux/man-pages/man2/getpid.2.html) 변경을 확인합니다. Windows는 부모 프로세스 핸들과 생성 시간을 확인한 뒤 [WaitForSingleObject](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject)로 생존을 검사합니다. 부모가 사라지면 checkpoint에서 Io로 중단하고 임시 출력을 정리합니다. 이미 게시한 파일/디렉터리는 유지하며 OS의 블로킹 I/O 강제 중단을 보장하지 않습니다. 기존 단발 요청을 위해 stdin EOF만으로 취소하지 않습니다. |
| @@ -143,19 +143,21 @@ | ||
| 143 | 143 | "regression": "Preserve existing format bytes and round-trip SevenZip in ListEnd/ListId." |
| 144 | 144 | }, |
| 145 | 145 | "streaming_limits": { |
| 146 | 삭제: "agreement": "Frontend/backend revision 2 agreement on 2026-11-11; field order, tags and frame encoding unchanged.", | |
| 146 | 추가: "agreement": "Revision 2 fields, tags and frame encoding unchanged. Ratio-rejection removal and disk-space advisory checks are proposed under manager decision d6bc0d37-89d1-4cd2-a00b-883b5eb23ec0; frontend confirmation pending.", | |
| 147 | 147 | "default_input_bytes": 18446744073709551615, |
| 148 | 148 | "default_output_bytes": 17179869184, |
| 149 | 149 | "default_entries": 10000, |
| 150 | 150 | "lower_limits": "Callers can lower the input, output and entry quotas. input=u64::MAX means no input-size quota; resource and duration checks still apply.", |
| 151 | 삭제: "zip_ratio": "For each ZIP entry, declared output and actual decoded bytes are bounded by 1000 times compressed payload bytes, excluding ZipCrypto/AES framing. Zero packed bytes permit only zero output. ZIP metadata is checked before allocation/decode; size and CRC/HMAC must also match.", | |
| 152 | 삭제: "gzip_ratio": "For each complete GZip member, verified decoded bytes are at most 1000 times actual consumed member bytes, including its header/trailer. Concatenating a low-ratio member cannot dilute an excessive member. Aggregate decoded bytes, including TAR headers/padding, cannot exceed output quota. During decoding the complete source length is an additional conservative ratio ceiling.", | |
| 151 | 추가: "zip_ratio": "No compression-ratio rejection. Validate declared and actual output sizes, stream end, CRC and HMAC; sum of declared output sizes must fit output quota before decoding.", | |
| 152 | 추가: "gzip_ratio": "No compression-ratio rejection, including concatenated members. Aggregate decoded bytes, including TAR headers/padding, cannot exceed output quota.", | |
| 153 | 153 | "tar_ratio": "Plain TAR copies declared nonoverlapping ranges within the captured input. The sum of file sizes cannot exceed output quota.", |
| 154 | 삭제: "arithmetic": "Checked u64 offsets/totals; ratio comparison uses u128(output) <= u128(input) * 1000 without u64 multiplication overflow.", | |
| 154 | 추가: "arithmetic": "Checked u64 offsets and totals; free-space block-to-byte conversion uses u128 to avoid multiplication overflow.", | |
| 155 | 155 | "memory_target": "ZIP/TAR/GZ/TAR.GZ List/Extract: worker process peak RSS <=64 MiB in Linux regression with independently generated 1 GiB payloads. This is a measured target, not an OS-enforced RSS cap. Metadata budget remains 8 MiB.", |
| 156 | 156 | "staging": "64 KiB buffers; immutable input capture and verified decoded content use private temporary files that are removed on last-handle close. No decoded content is published until the entire catalog and integrity checks succeed. Temporary disk usage can include the archive plus expanded content plus current destination temporary file; disk exhaustion fails with Io and closes/removes unpublished data.", |
| 157 | 157 | "legacy": "7z and ZIP creation retain separate 64 MiB input /128 MiB output caps until their streaming implementation. The slice-based archive parser also retains these legacy memory bounds.", |
| 158 | 삭제: "parent_lifetime": "Capture native parent before reading Start. At decode/read/write/password checkpoints, fail Io if parent is gone; close anonymous staging and remove current unpublished destination temp. stdin EOF alone remains valid for one-shot requests. Already published entries and directories are reported and retained. A blocked OS file operation cannot be forcibly interrupted by this cooperative guard." | |
| 158 | 추가: "parent_lifetime": "Capture native parent before reading Start. At decode/read/write/password checkpoints, fail Io if parent is gone; close anonymous staging and remove current unpublished destination temp. stdin EOF alone remains valid for one-shot requests. Already published entries and directories are reported and retained. A blocked OS file operation cannot be forcibly interrupted by this cooperative guard.", | |
| 159 | 추가: "disk_space": "Advisory free-space checks use opened Linux x86_64 filesystem handles (fstatvfs) or the Windows handle-derived directory (GetDiskFreeSpaceExW). Before ZIP/7z decoding and before publication, group remaining staging and selected output logical bytes by volume. For GZip with unknown expanded size, check staging space before each decoded chunk, then preflight selected output. Input capture also checks its snapshot space. Query failure or insufficient space returns existing Io tag 8. Checks do not reserve space or account for every metadata/block-allocation overhead; later ENOSPC still closes staging and removes current unpublished output.", | |
| 160 | 추가: "remaining_risk": "High compression ratios within 16 GiB may expand fully onto disk. Resource duration, cooperative cancellation and measured memory target remain. Free-space checks can race with other disk users; already published outputs are retained on failure." | |
| 159 | 161 | }, |
| 160 | 162 | "validation": "Implementation results belong in the PR verification record. No OS sandbox or native Windows execution claim." |
| 161 | 163 | } |
| @@ -247,6 +247,9 @@ mod platform { | ||
| 247 | 247 | Err(_) => Err(ErrorCode::UnsafePath), |
| 248 | 248 | } |
| 249 | 249 | } |
| 250 | 추가: pub(crate) fn handle(&self) -> &File { | |
| 251 | 추가: &self.file | |
| 252 | 추가: } | |
| 250 | 253 | pub fn duplicate(&self) -> Result<Self> { |
| 251 | 254 | Ok(Self { |
| 252 | 255 | file: self.file.try_clone().map_err(|_| ErrorCode::Io)?, |
| @@ -337,6 +340,9 @@ mod platform { | ||
| 337 | 340 | } |
| 338 | 341 | Ok(Self { path: p, locks }) |
| 339 | 342 | } |
| 343 | 추가: pub(crate) fn handle(&self) -> &File { | |
| 344 | 추가: self.locks.last().unwrap() | |
| 345 | 추가: } | |
| 340 | 346 | pub fn duplicate(&self) -> Result<Self> { |
| 341 | 347 | Ok(Self { |
| 342 | 348 | path: self.path.clone(), |
| @@ -417,6 +423,46 @@ pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> { | ||
| 417 | 423 | } |
| 418 | 424 | Ok(()) |
| 419 | 425 | } |
| 426 | 추가: pub(crate) fn preflight_space( | |
| 427 | 추가: root: &Dir, | |
| 428 | 추가: files: &[(String, u64)], | |
| 429 | 추가: staging: Option<(&File, u64)>, | |
| 430 | 추가: ) -> Result<()> { | |
| 431 | 추가: let mut volumes = std::collections::BTreeMap::<u64, (File, u64)>::new(); | |
| 432 | 추가: let mut charge = |file: &File, bytes: u64| -> Result<()> { | |
| 433 | 추가: crate::space::ensure(file, bytes)?; | |
| 434 | 추가: let volume = crate::space::volume(file)?; | |
| 435 | 추가: if let Some((_, total)) = volumes.get_mut(&volume) { | |
| 436 | 추가: *total = total.checked_add(bytes).ok_or(ErrorCode::Limit)?; | |
| 437 | 추가: } else { | |
| 438 | 추가: volumes.insert( | |
| 439 | 추가: volume, | |
| 440 | 추가: (file.try_clone().map_err(|_| ErrorCode::Io)?, bytes), | |
| 441 | 추가: ); | |
| 442 | 추가: } | |
| 443 | 추가: Ok(()) | |
| 444 | 추가: }; | |
| 445 | 추가: if let Some((file, bytes)) = staging { | |
| 446 | 추가: charge(file, bytes)?; | |
| 447 | 추가: } | |
| 448 | 추가: for (name, size) in files { | |
| 449 | 추가: valid_name(name, false)?; | |
| 450 | 추가: let mut parent = root.duplicate()?; | |
| 451 | 추가: let mut parts = name.split('/').collect::<Vec<_>>(); | |
| 452 | 추가: parts.pop(); | |
| 453 | 추가: for part in parts { | |
| 454 | 추가: match parent.child(part, false)? { | |
| 455 | 추가: Some(child) => parent = child, | |
| 456 | 추가: None => break, | |
| 457 | 추가: } | |
| 458 | 추가: } | |
| 459 | 추가: charge(parent.handle(), *size)?; | |
| 460 | 추가: } | |
| 461 | 추가: for (file, bytes) in volumes.values() { | |
| 462 | 추가: crate::space::ensure(file, *bytes)?; | |
| 463 | 추가: } | |
| 464 | 추가: Ok(()) | |
| 465 | 추가: } | |
| 420 | 466 | pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability)> { |
| 421 | 467 | let (d, leaf) = parent(root, name, false)?.ok_or(ErrorCode::Io)?; |
| 422 | 468 | if d.child(&leaf, false)?.is_some() { |
| @@ -481,6 +527,7 @@ pub fn publish_reader( | ||
| 481 | 527 | } |
| 482 | 528 | })?; |
| 483 | 529 | let written = (|| { |
| 530 | 추가: crate::space::ensure(&file, length)?; | |
| 484 | 531 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 485 | 532 | let mut remaining = length; |
| 486 | 533 | while remaining != 0 { |
| @@ -6,6 +6,7 @@ mod parent; | ||
| 6 | 6 | pub mod protocol; |
| 7 | 7 | pub mod runtime; |
| 8 | 8 | mod seven_zip; |
| 9 | 추가: mod space; | |
| 9 | 10 | mod spool; |
| 10 | 11 | mod streaming; |
| 11 | 12 | pub mod wire; |
| @@ -291,6 +291,40 @@ impl<W: Write> Job<W> { | ||
| 291 | 291 | { |
| 292 | 292 | return Err(ErrorCode::UnsafePath); |
| 293 | 293 | } |
| 294 | 추가: if catalog.format == Format::Gzip { | |
| 295 | 추가: let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?; | |
| 296 | 추가: let checked = archive::valid_name(&name, false) | |
| 297 | 추가: .map_err(|_| ErrorCode::InvalidRequest)?; | |
| 298 | 추가: if checked.contains('/') { | |
| 299 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 300 | 추가: } | |
| 301 | 추가: catalog.members[0].entry.name = checked; | |
| 302 | 추가: } else if gzip_output_name.is_some() { | |
| 303 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 304 | 추가: } | |
| 305 | 추가: let root = Dir::root(&destination.to_path()?)?; | |
| 306 | 추가: let output_sizes = catalog | |
| 307 | 추가: .members | |
| 308 | 추가: .iter() | |
| 309 | 추가: .filter(|m| { | |
| 310 | 추가: m.entry.kind == EntryKind::File | |
| 311 | 추가: && selected | |
| 312 | 추가: .as_ref() | |
| 313 | 추가: .is_none_or(|s| s.contains(&m.entry.entry_id)) | |
| 314 | 추가: }) | |
| 315 | 추가: .map(|m| (m.entry.name.clone(), m.entry.size)) | |
| 316 | 추가: .collect::<Vec<_>>(); | |
| 317 | 추가: let staged = if matches!(catalog.format, Format::Zip | Format::SevenZip) { | |
| 318 | 추가: Some(( | |
| 319 | 추가: &catalog.data, | |
| 320 | 추가: catalog.members.iter().try_fold(0u64, |sum, m| { | |
| 321 | 추가: sum.checked_add(m.entry.size).ok_or(ErrorCode::Limit) | |
| 322 | 추가: })?, | |
| 323 | 추가: )) | |
| 324 | 추가: } else { | |
| 325 | 추가: None | |
| 326 | 추가: }; | |
| 327 | 추가: filesystem::preflight_space(&root, &output_sizes, staged)?; | |
| 294 | 328 | let encrypted = catalog.members.iter().any(|m| m.entry.encrypted); |
| 295 | 329 | if matches!(catalog.format, Format::Zip | Format::SevenZip) { |
| 296 | 330 | for attempt in 1..=3 { |
| @@ -316,18 +350,6 @@ impl<W: Write> Job<W> { | ||
| 316 | 350 | } |
| 317 | 351 | } |
| 318 | 352 | } |
| 319 | 삭제: if catalog.format == Format::Gzip { | |
| 320 | 삭제: let name = gzip_output_name.ok_or(ErrorCode::InvalidRequest)?; | |
| 321 | 삭제: let checked = archive::valid_name(&name, false) | |
| 322 | 삭제: .map_err(|_| ErrorCode::InvalidRequest)?; | |
| 323 | 삭제: if checked.contains('/') { | |
| 324 | 삭제: return Err(ErrorCode::InvalidRequest); | |
| 325 | 삭제: } | |
| 326 | 삭제: catalog.members[0].entry.name = checked; | |
| 327 | 삭제: } else if gzip_output_name.is_some() { | |
| 328 | 삭제: return Err(ErrorCode::InvalidRequest); | |
| 329 | 삭제: } | |
| 330 | 삭제: let root = Dir::root(&destination.to_path()?)?; | |
| 331 | 353 | let offsets = catalog.offsets; |
| 332 | 354 | let mut data = catalog.data; |
| 333 | 355 | let members = catalog |
| @@ -354,6 +376,7 @@ impl<W: Write> Job<W> { | ||
| 354 | 376 | .map(|m| (m.entry.name.clone(), EntryKind::File)), |
| 355 | 377 | ); |
| 356 | 378 | filesystem::preflight(&root, &names)?; |
| 379 | 추가: filesystem::preflight_space(&root, &output_sizes, None)?; | |
| 357 | 380 | for name in dirs { |
| 358 | 381 | self.check()?; |
| 359 | 382 | let (created, durability) = filesystem::directory(&root, &name)?; |
| @@ -589,6 +612,9 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>( | ||
| 589 | 612 | ErrorCode::None => "취소됨", |
| 590 | 613 | ErrorCode::UnsupportedFeature => "암호 또는 해당 기능 미지원", |
| 591 | 614 | ErrorCode::SourceChanged => "파일이 변경됨. 다시 열어 목록을 확인해야 함", |
| 615 | 추가: ErrorCode::Io => { | |
| 616 | 추가: "파일을 읽거나 쓰지 못했습니다. 디스크 여유 공간과 접근 권한을 확인하세요" | |
| 617 | 추가: } | |
| 592 | 618 | _ => "작업 실패. 오류 코드와 게시 상태를 확인해야 함", |
| 593 | 619 | } |
| 594 | 620 | .to_owned(); |
| @@ -0,0 +1,123 @@ | ||
| 1 | 추가: use crate::protocol::*; | |
| 2 | 추가: use std::fs::File; | |
| 3 | 추가: | |
| 4 | 추가: type Result<T> = std::result::Result<T, ErrorCode>; | |
| 5 | 추가: | |
| 6 | 추가: pub(crate) fn volume(file: &File) -> Result<u64> { | |
| 7 | 추가: Ok(match crate::filesystem::object(file)? { | |
| 8 | 추가: SourceObject::Unix { device, .. } => device, | |
| 9 | 추가: SourceObject::Windows { volume_serial, .. } => volume_serial, | |
| 10 | 추가: }) | |
| 11 | 추가: } | |
| 12 | 추가: | |
| 13 | 추가: pub(crate) fn ensure(file: &File, bytes: u64) -> Result<()> { | |
| 14 | 추가: if bytes == 0 || bytes as u128 <= available(file)? { | |
| 15 | 추가: Ok(()) | |
| 16 | 추가: } else { | |
| 17 | 추가: Err(ErrorCode::Io) | |
| 18 | 추가: } | |
| 19 | 추가: } | |
| 20 | 추가: | |
| 21 | 추가: #[cfg(all(target_os = "linux", target_pointer_width = "64"))] | |
| 22 | 추가: fn available(file: &File) -> Result<u128> { | |
| 23 | 추가: use std::os::fd::AsRawFd; | |
| 24 | 추가: #[repr(C)] | |
| 25 | 추가: #[derive(Default)] | |
| 26 | 추가: struct Vfs { | |
| 27 | 추가: block_size: u64, | |
| 28 | 추가: fragment_size: u64, | |
| 29 | 추가: blocks: u64, | |
| 30 | 추가: free_blocks: u64, | |
| 31 | 추가: available_blocks: u64, | |
| 32 | 추가: files: u64, | |
| 33 | 추가: free_files: u64, | |
| 34 | 추가: available_files: u64, | |
| 35 | 추가: filesystem_id: u64, | |
| 36 | 추가: flags: u64, | |
| 37 | 추가: name_max: u64, | |
| 38 | 추가: reserved: [i32; 6], | |
| 39 | 추가: } | |
| 40 | 추가: unsafe extern "C" { | |
| 41 | 추가: fn fstatvfs(fd: i32, value: *mut Vfs) -> i32; | |
| 42 | 추가: } | |
| 43 | 추가: let mut value = Vfs::default(); | |
| 44 | 추가: if unsafe { fstatvfs(file.as_raw_fd(), &mut value) } != 0 || value.fragment_size == 0 { | |
| 45 | 추가: return Err(ErrorCode::Io); | |
| 46 | 추가: } | |
| 47 | 추가: Ok(value.available_blocks as u128 * value.fragment_size as u128) | |
| 48 | 추가: } | |
| 49 | 추가: | |
| 50 | 추가: #[cfg(all(target_os = "linux", not(target_pointer_width = "64")))] | |
| 51 | 추가: fn available(_: &File) -> Result<u128> { | |
| 52 | 추가: Err(ErrorCode::UnsupportedFeature) | |
| 53 | 추가: } | |
| 54 | 추가: | |
| 55 | 추가: #[cfg(windows)] | |
| 56 | 추가: fn available(file: &File) -> Result<u128> { | |
| 57 | 추가: use std::{ | |
| 58 | 추가: ffi::OsString, | |
| 59 | 추가: os::windows::{ | |
| 60 | 추가: ffi::{OsStrExt, OsStringExt}, | |
| 61 | 추가: io::AsRawHandle, | |
| 62 | 추가: }, | |
| 63 | 추가: path::PathBuf, | |
| 64 | 추가: }; | |
| 65 | 추가: unsafe extern "system" { | |
| 66 | 추가: fn GetFinalPathNameByHandleW( | |
| 67 | 추가: handle: *mut std::ffi::c_void, | |
| 68 | 추가: path: *mut u16, | |
| 69 | 추가: capacity: u32, | |
| 70 | 추가: flags: u32, | |
| 71 | 추가: ) -> u32; | |
| 72 | 추가: fn GetDiskFreeSpaceExW( | |
| 73 | 추가: path: *const u16, | |
| 74 | 추가: available: *mut u64, | |
| 75 | 추가: total: *mut u64, | |
| 76 | 추가: free: *mut u64, | |
| 77 | 추가: ) -> i32; | |
| 78 | 추가: } | |
| 79 | 추가: let mut buffer = vec![0u16; 32768]; | |
| 80 | 추가: let mut length = unsafe { | |
| 81 | 추가: GetFinalPathNameByHandleW( | |
| 82 | 추가: file.as_raw_handle(), | |
| 83 | 추가: buffer.as_mut_ptr(), | |
| 84 | 추가: buffer.len() as u32, | |
| 85 | 추가: 0, | |
| 86 | 추가: ) | |
| 87 | 추가: }; | |
| 88 | 추가: if length == 0 { | |
| 89 | 추가: length = unsafe { | |
| 90 | 추가: GetFinalPathNameByHandleW( | |
| 91 | 추가: file.as_raw_handle(), | |
| 92 | 추가: buffer.as_mut_ptr(), | |
| 93 | 추가: buffer.len() as u32, | |
| 94 | 추가: 1, | |
| 95 | 추가: ) | |
| 96 | 추가: }; | |
| 97 | 추가: } | |
| 98 | 추가: if length == 0 || length as usize >= buffer.len() { | |
| 99 | 추가: return Err(ErrorCode::Io); | |
| 100 | 추가: } | |
| 101 | 추가: let mut path = PathBuf::from(OsString::from_wide(&buffer[..length as usize])); | |
| 102 | 추가: if !file.metadata().map_err(|_| ErrorCode::Io)?.is_dir() && !path.pop() { | |
| 103 | 추가: return Err(ErrorCode::Io); | |
| 104 | 추가: } | |
| 105 | 추가: let mut wide: Vec<_> = path.as_os_str().encode_wide().collect(); | |
| 106 | 추가: if wide.last() != Some(&92) { | |
| 107 | 추가: wide.push(92); | |
| 108 | 추가: } | |
| 109 | 추가: wide.push(0); | |
| 110 | 추가: let mut free = 0; | |
| 111 | 추가: if unsafe { | |
| 112 | 추가: GetDiskFreeSpaceExW( | |
| 113 | 추가: wide.as_ptr(), | |
| 114 | 추가: &mut free, | |
| 115 | 추가: std::ptr::null_mut(), | |
| 116 | 추가: std::ptr::null_mut(), | |
| 117 | 추가: ) | |
| 118 | 추가: } == 0 | |
| 119 | 추가: { | |
| 120 | 추가: return Err(ErrorCode::Io); | |
| 121 | 추가: } | |
| 122 | 추가: Ok(free as u128) | |
| 123 | 추가: } |
| @@ -107,6 +107,7 @@ impl Snapshot { | ||
| 107 | 107 | source.rewind().map_err(|_| ErrorCode::Io)?; |
| 108 | 108 | let object = filesystem::object(&source)?; |
| 109 | 109 | let mut file = temporary()?; |
| 110 | 추가: crate::space::ensure(&file, before.len())?; | |
| 110 | 111 | let mut buffer = [0; 65536]; |
| 111 | 112 | let mut hash = Sha256::new(); |
| 112 | 113 | let mut len = 0u64; |
| @@ -13,15 +13,6 @@ use zlib_rs::{Inflate, InflateFlush, Status, crc32::crc32}; | ||
| 13 | 13 | |
| 14 | 14 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 15 | 15 | const CHUNK: usize = 65536; |
| 16 | 삭제: pub(crate) const RATIO: u64 = 1000; | |
| 17 | 삭제: | |
| 18 | 삭제: pub(crate) fn ratio(output: u64, input: u64) -> Result<()> { | |
| 19 | 삭제: if output as u128 > input as u128 * RATIO as u128 { | |
| 20 | 삭제: Err(ErrorCode::Limit) | |
| 21 | 삭제: } else { | |
| 22 | 삭제: Ok(()) | |
| 23 | 삭제: } | |
| 24 | 삭제: } | |
| 25 | 16 | fn at(file: &mut File, offset: u64, bytes: &mut [u8]) -> Result<()> { |
| 26 | 17 | file.seek(SeekFrom::Start(offset)) |
| 27 | 18 | .map_err(|_| ErrorCode::Io)?; |
| @@ -98,16 +89,7 @@ impl Catalog { | ||
| 98 | 89 | if magic.starts_with(&[31, 139]) { |
| 99 | 90 | let mut data = spool::temporary()?; |
| 100 | 91 | io(source.rewind())?; |
| 101 | 삭제: let expanded = inflate( | |
| 102 | 삭제: source, | |
| 103 | 삭제: len, | |
| 104 | 삭제: true, | |
| 105 | 삭제: limits.output, | |
| 106 | 삭제: Some(len), | |
| 107 | 삭제: &mut data, | |
| 108 | 삭제: check, | |
| 109 | 삭제: )? | |
| 110 | 삭제: .0; | |
| 92 | 추가: let expanded = inflate(source, len, true, limits.output, &mut data, check)?.0; | |
| 111 | 93 | let mut header = [0; 512]; |
| 112 | 94 | if expanded >= 512 { |
| 113 | 95 | at(&mut data, 0, &mut header)?; |
| @@ -248,13 +230,12 @@ fn tar( | ||
| 248 | 230 | }) |
| 249 | 231 | } |
| 250 | 232 | |
| 251 | 삭제: // 각 ZIP 항목과 각 GZip 멤버의 실제 해제량에 압축비와 누적 총량을 적용함. | |
| 233 | 추가: // ZIP 항목과 연결 GZip 스트림의 해제 총량을 제한함. | |
| 252 | 234 | fn inflate( |
| 253 | 235 | input: &mut impl Read, |
| 254 | 236 | length: u64, |
| 255 | 237 | gzip: bool, |
| 256 | 238 | limit: u64, |
| 257 | 삭제: ratio_base: Option<u64>, | |
| 258 | 239 | output: &mut File, |
| 259 | 240 | check: &mut impl FnMut() -> Result<()>, |
| 260 | 241 | ) -> Result<(u64, u32)> { |
| @@ -290,15 +271,10 @@ fn inflate( | ||
| 290 | 271 | .checked_add(n as u64) |
| 291 | 272 | .filter(|n| *n <= limit) |
| 292 | 273 | .ok_or(ErrorCode::Limit)?; |
| 293 | 삭제: if let Some(base) = ratio_base { | |
| 294 | 삭제: ratio(total, base)?; | |
| 295 | 삭제: } | |
| 296 | 274 | crc = crc32(crc, &plain[..n]); |
| 275 | 추가: crate::space::ensure(output, n as u64)?; | |
| 297 | 276 | io(output.write_all(&plain[..n]))?; |
| 298 | 277 | if status == Status::StreamEnd { |
| 299 | 삭제: if gzip { | |
| 300 | 삭제: ratio(stream.total_out(), stream.total_in())?; | |
| 301 | 삭제: } | |
| 302 | 278 | break; |
| 303 | 279 | } |
| 304 | 280 | if a == stream.total_in() && b == stream.total_out() { |
| @@ -501,10 +477,9 @@ fn zip( | ||
| 501 | 477 | } else { |
| 502 | 478 | 12 |
| 503 | 479 | }; |
| 504 | 삭제: let payload = compressed | |
| 480 | 추가: compressed | |
| 505 | 481 | .checked_sub(overhead) |
| 506 | 482 | .ok_or(ErrorCode::Integrity)?; |
| 507 | 삭제: ratio(size, payload)?; | |
| 508 | 483 | total = total |
| 509 | 484 | .checked_add(size) |
| 510 | 485 | .filter(|n| *n <= limits.output) |
| @@ -636,6 +611,9 @@ fn zip( | ||
| 636 | 611 | } |
| 637 | 612 | archive::validate_members(&members)?; |
| 638 | 613 | let mut data = spool::temporary()?; |
| 614 | 추가: if decode { | |
| 615 | 추가: crate::space::ensure(&data, total)?; | |
| 616 | 추가: } | |
| 639 | 617 | let mut offsets = Vec::new(); |
| 640 | 618 | for (member, packed) in members.iter().zip(packed) { |
| 641 | 619 | check()?; |
| @@ -667,7 +645,6 @@ fn zip( | ||
| 667 | 645 | length, |
| 668 | 646 | false, |
| 669 | 647 | member.entry.size, |
| 670 | 삭제: Some(length), | |
| 671 | 648 | &mut data, |
| 672 | 649 | check, |
| 673 | 650 | )? |
| @@ -51,7 +51,7 @@ class LargeArchiveFixtureTests(unittest.TestCase): | ||
| 51 | 51 | self.assertEqual(case["expected"]["error"], "Limit" if failed else "None") |
| 52 | 52 | self.assertEqual(case["expected"]["created_count"], 0 if failed else 1) |
| 53 | 53 | |
| 54 | 삭제: def test_ratio_boundary_is_exact_and_below_output_limit(self): | |
| 54 | 추가: def test_former_ratio_samples_all_expect_success(self): | |
| 55 | 55 | with tempfile.TemporaryDirectory(dir=ROOT / "tests/ci") as scratch: |
| 56 | 56 | manifest = GENERATOR.build(Path(scratch) / "corpus") |
| 57 | 57 | for suffix, delta in (("below", -1), ("equal", 0), ("above", 1)): |
| @@ -59,6 +59,9 @@ class LargeArchiveFixtureTests(unittest.TestCase): | ||
| 59 | 59 | artifact = manifest["artifacts"][name] |
| 60 | 60 | self.assertEqual(artifact["decoded_bytes"] - 1000 * artifact["ratio_input_bytes"], delta) |
| 61 | 61 | self.assertLess(artifact["decoded_bytes"], GENERATOR.OUTPUT_LIMIT) |
| 62 | 추가: case = next(c for c in manifest["cases"] if c["file"] == name) | |
| 63 | 추가: self.assertEqual(case["expected"]["outcome"], "Completed") | |
| 64 | 추가: self.assertIsNone(manifest["policy"]["ratio"]) | |
| 62 | 65 | payload = gzip.decompress((Path(scratch) / "corpus" / name).read_bytes()) |
| 63 | 66 | self.assertEqual(payload, bytes(artifact["payload_bytes"])) |
| 64 | 67 |
| @@ -1,14 +1,14 @@ | ||
| 1 | 1 | # 대용량 압축파일 회귀 표본 |
| 2 | 2 | |
| 3 | 삭제: Python 표준 라이브러리로 실행할 때 합성 표본을 생성합니다. 생성 데이터는 커밋하지 않으며 읽기와 쓰기는 64 KiB로 나눕니다. revision 2의 입력 u64::MAX, 해제 총량 16 GiB, 압축비 1000:1을 기준으로 합니다. | |
| 3 | 추가: Python 표준 라이브러리로 실행할 때 합성 표본을 생성합니다. 생성 데이터는 커밋하지 않으며 읽기와 쓰기는 64 KiB로 나눕니다. revision 2의 입력 u64::MAX와 해제 총량 16 GiB를 사용합니다. 압축비는 거부 조건이 아닙니다. | |
| 4 | 4 | |
| 5 | 5 | ## 독립된 경계 |
| 6 | 6 | |
| 7 | 7 | - large-input.zip과 large-input.tar.gz: 1 GiB payload를 Store ZIP과 Gzip level 0의 TAR로 저장합니다. 압축파일 자체가 1 GiB 이상이며 다른 한도 이내이므로 실제 해제가 성공해야 합니다. |
| 8 | 삭제: - output-only.zip: 유효한 ZIP64에 16 GiB + 1바이트를 level 1로 압축합니다. 해제 총량만 초과하며 항목 압축비는 1000:1 미만입니다. 요청은 Failed/Limit으로 끝나고 출력이 없어야 합니다. Python 참조 판독기가 전체 16 GiB + 1바이트와 CRC를 스트리밍 검증합니다. 제품의 해당 크기 해제 성공을 검증하는 시험은 아닙니다. | |
| 8 | 추가: - output-only.zip: 유효한 ZIP64에 16 GiB + 1바이트를 level 1로 압축합니다. 해제 총량만 초과합니다. 압축비는 관측 정보입니다. 요청은 Failed/Limit으로 끝나고 출력이 없어야 합니다. Python 참조 판독기가 전체 16 GiB + 1바이트와 CRC를 스트리밍 검증합니다. 제품의 해당 크기 해제 성공을 검증하는 시험은 아닙니다. | |
| 9 | 9 | - boundary.zip과 boundary.tar.gz: 실제 해제 크기 65536바이트에 요청 output을 65537, 65536, 65535로 설정해 경계 직전, 일치, 초과를 실제 해제로 검사합니다. TAR.GZ는 TAR 헤더와 패딩 및 종료 블록도 총량에 포함합니다. |
| 10 | 삭제: - ratio-below.gz, ratio-equal.gz, ratio-above.gz: FEXTRA를 포함한 유효한 GZ 멤버 길이를 정확히 2000바이트로 맞춥니다. 해제 크기는 각각 1999999, 2000000, 2000001바이트로, 멤버별 1000:1 경계보다 정확히 1바이트 작음, 일치, 1바이트 큼입니다. 총량은 16 GiB보다 작습니다. | |
| 11 | 삭제: - ratio-only.zip과 ratio-only.tar.gz: 16 MiB payload를 level 6으로 압축해 비율만 초과시킵니다. ZIP의 분모는 항목의 압축 payload, GZ의 분모는 헤더와 트레일러를 포함한 멤버 전체 바이트입니다. | |
| 10 | 추가: - ratio-below.gz, ratio-equal.gz, ratio-above.gz: FEXTRA를 포함한 유효한 GZ 멤버 길이를 정확히 2000바이트로 맞춥니다. 해제 크기는 각각 1999999, 2000000, 2000001바이트로, 과거 1000:1 경계보다 정확히 1바이트 작음, 일치, 1바이트 큼입니다. 세 표본 모두 총량이 16 GiB보다 작으므로 정상 해제되어야 합니다. | |
| 11 | 추가: - ratio-only.zip과 ratio-only.tar.gz: 16 MiB payload를 level 6으로 압축해 과거 비율 한도를 초과시킵니다. 두 표본 모두 정상 해제되어야 합니다. ZIP의 관측 비율 분모는 항목의 압축 payload, GZ의 분모는 헤더와 트레일러를 포함한 멤버 전체 바이트입니다. | |
| 12 | 12 | |
| 13 | 13 | 생성 시 실제 archive_bytes, decoded_bytes, ratio_input_bytes와 요청 한도를 비교해 violated_limits가 정확히 일치하는지 검사합니다. 한 표본에서 여러 한도를 넘으면 생성을 실패시킵니다. 입력, 출력, 항목 수는 manifest의 실제 값이 모두 작업자 요청에 전달됩니다. 생성 결과만으로 검증 완료를 주장하지 않도록 worker_execution_verified=false를 기록합니다. |
| 14 | 14 | |
| @@ -21,7 +21,7 @@ python3 tests/ci/run_rust.py local | ||
| 21 | 21 | python3 tests/large-archive-fixtures/verify.py --large |
| 22 | 22 | ``` |
| 23 | 23 | |
| 24 | 삭제: CARGO_TARGET_DIR을 지정했다면 검증기도 같은 환경 값을 사용합니다. --probe와 --worker로 바이너리 경로를 따로 지정할 수도 있습니다. --large를 생략하면 작은 경계 11건만 검사합니다. 기본 local 실행에는 작은 표본의 참조 무결성, 경계 독립성과 생성기 경로 및 버퍼 제약 검사가 포함됩니다. | |
| 24 | 추가: CARGO_TARGET_DIR을 지정했다면 검증기도 같은 환경 값을 사용합니다. --probe와 --worker로 바이너리 경로를 따로 지정할 수도 있습니다. --large를 생략하면 작은 경계 및 고압축 호환성 11건만 검사합니다. 기본 local 실행에는 작은 표본의 참조 무결성, 경계 독립성과 생성기 경로 및 버퍼 제약 검사가 포함됩니다. | |
| 25 | 25 | |
| 26 | 26 | 표본을 보존하려면 아래처럼 새 경로를 지정합니다. 기존 디렉터리는 생성기가 덮어쓰지 않으며, 검증기는 기존 expectations.json이 있으면 재사용합니다. |
| 27 | 27 | |
| @@ -31,3 +31,5 @@ python3 tests/large-archive-fixtures/verify.py --large --directory tests/large-a | ||
| 31 | 31 | ``` |
| 32 | 32 | |
| 33 | 33 | 검증기는 전체 표본을 참조 판독기로 읽어 합성 내용, CRC와 TAR 구조를 확인한 후 실제 작업자의 종료 코드, Terminal, 오류, 게시 상태, Output 개수와 정리를 확인합니다. 성공 파일은 길이와 모든 바이트를 검사하며 거부한 경우 출력 폴더가 비어 있어야 합니다. 입력의 전후 SHA-256도 확인합니다. 작업자 피크 RSS, 디스크 부족과 고아 작업자 정리는 tests/rust-archive-worker/hardening.rs에서 별도로 검사합니다. Windows 실기는 별도 검증이 필요합니다. |
| 34 | 추가: | |
| 35 | 추가: 압축비는 expectations.json의 거부 사유에서 제거했고 policy.ratio는 null입니다. 공간이 부족하면 실제 작업자는 기존 Io를 반환하므로, 성공 표본 검증에는 입력 사본과 해제 임시 파일 및 출력을 위한 여유 디스크가 필요합니다. |
| @@ -17,7 +17,6 @@ GIB = 1024 ** 3 | ||
| 17 | 17 | CHUNK = 64 * 1024 |
| 18 | 18 | INPUT_LIMIT = 2 ** 64 - 1 |
| 19 | 19 | OUTPUT_LIMIT = 16 * GIB |
| 20 | 삭제: RATIO_LIMIT = 1000 | |
| 21 | 20 | NAME = "payload.bin" |
| 22 | 21 | |
| 23 | 22 | |
| @@ -99,8 +98,6 @@ def violations(artifact, limits): | ||
| 99 | 98 | failed.append("input") |
| 100 | 99 | if artifact["decoded_bytes"] > limits["output"]: |
| 101 | 100 | failed.append("output") |
| 102 | 삭제: if artifact["decoded_bytes"] > artifact["ratio_input_bytes"] * RATIO_LIMIT: | |
| 103 | 삭제: failed.append("ratio") | |
| 104 | 101 | return failed |
| 105 | 102 | |
| 106 | 103 | |
| @@ -165,12 +162,12 @@ def build(directory, large=False): | ||
| 165 | 162 | ("above", CHUNK - 1, ["output"]), |
| 166 | 163 | ]) |
| 167 | 164 | for suffix, delta in (("below", -1), ("equal", 0), ("above", 1)): |
| 168 | 삭제: add("ratio-" + suffix + ".gz", 2_000_000 + delta, True, "ratio-boundary", [ | |
| 169 | 삭제: ("default", OUTPUT_LIMIT, ["ratio"] if delta > 0 else []), | |
| 165 | 추가: add("ratio-" + suffix + ".gz", 2_000_000 + delta, True, "former-ratio-boundary", [ | |
| 166 | 추가: ("default", OUTPUT_LIMIT, []), | |
| 170 | 167 | ], packed_size=2000) |
| 171 | 168 | for extension in ("zip", "tar.gz"): |
| 172 | 삭제: add("ratio-only." + extension, 16 * 1024 ** 2, True, "ratio-limit", [ | |
| 173 | 삭제: ("default", OUTPUT_LIMIT, ["ratio"]), | |
| 169 | 추가: add("ratio-only." + extension, 16 * 1024 ** 2, True, "high-ratio-success", [ | |
| 170 | 추가: ("default", OUTPUT_LIMIT, []), | |
| 174 | 171 | ]) |
| 175 | 172 | if large: |
| 176 | 173 | for extension in ("zip", "tar.gz"): |
| @@ -181,7 +178,7 @@ def build(directory, large=False): | ||
| 181 | 178 | ("default", OUTPUT_LIMIT, ["output"]), |
| 182 | 179 | ], level=1) |
| 183 | 180 | manifest = { |
| 184 | 삭제: "policy": {"revision": 2, "input": INPUT_LIMIT, "output": OUTPUT_LIMIT, "ratio": RATIO_LIMIT}, | |
| 181 | 추가: "policy": {"revision": 2, "input": INPUT_LIMIT, "output": OUTPUT_LIMIT, "ratio": None}, | |
| 185 | 182 | "large": large, |
| 186 | 183 | "worker_execution_verified": False, |
| 187 | 184 | "generator_chunk_bytes": CHUNK, |
| @@ -80,13 +80,53 @@ fn streaming_zip64_local_headers_and_chunk_boundaries() { | ||
| 80 | 80 | assert_zero_file(&s.0.join("output/payload.bin"), 9 * 1024 * 1024 + 13); |
| 81 | 81 | } |
| 82 | 82 | #[test] |
| 83 | 삭제: fn streaming_ratio_rejects_bomb_without_publication() { | |
| 83 | 추가: fn generated_zero_deflate_zip_round_trips_through_list_and_extract() { | |
| 84 | 추가: let s = Scratch::new(); | |
| 85 | 추가: fs::write(s.0.join("source"), vec![0; 2 * 1024 * 1024]).unwrap(); | |
| 86 | 추가: let events = execute(Start { | |
| 87 | 추가: action: Action::CreateZip { | |
| 88 | 추가: sources: vec![Source { | |
| 89 | 추가: path: s.path("source"), | |
| 90 | 추가: archive_name: "payload.bin".into(), | |
| 91 | 추가: }], | |
| 92 | 추가: output_file: s.path("input"), | |
| 93 | 추가: method: Method::Deflate, | |
| 94 | 추가: encryption: Encryption::None, | |
| 95 | 추가: }, | |
| 96 | 추가: limits: Limits::default(), | |
| 97 | 추가: }); | |
| 98 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 99 | 추가: let events = execute(Start { | |
| 100 | 추가: action: Action::List { | |
| 101 | 추가: archive: s.path("input"), | |
| 102 | 추가: }, | |
| 103 | 추가: limits: Limits::default(), | |
| 104 | 추가: }); | |
| 105 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 106 | 추가: let list_id = events | |
| 107 | 추가: .iter() | |
| 108 | 추가: .find_map(|e| match e { | |
| 109 | 추가: Message::ListEnd { list_id, .. } => Some(list_id.clone()), | |
| 110 | 추가: _ => None, | |
| 111 | 추가: }) | |
| 112 | 추가: .unwrap(); | |
| 113 | 추가: assert!(events.iter().any(|e| matches!(e, Message::Entry(entry) | |
| 114 | 추가: if entry.size == 2 * 1024 * 1024 && entry.size > entry.compressed_size * 1000))); | |
| 115 | 추가: let mut request = start(&s, false, Limits::default().output); | |
| 116 | 추가: if let Action::Extract { list_id: id, .. } = &mut request.action { | |
| 117 | 추가: *id = Some(list_id); | |
| 118 | 추가: } | |
| 119 | 추가: let events = execute(request); | |
| 120 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 121 | 추가: assert_zero_file(&s.0.join("output/payload.bin"), 2 * 1024 * 1024); | |
| 122 | 추가: } | |
| 123 | 추가: #[test] | |
| 124 | 추가: fn streaming_high_ratio_zip_extracts_below_total_limit() { | |
| 84 | 125 | let s = Scratch::new(); |
| 85 | 126 | generate(&s, "bomb", 16 * 1024 * 1024); |
| 86 | 127 | let events = execute(start(&s, false, Limits::default().output)); |
| 87 | 삭제: assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}"); | |
| 88 | 삭제: assert_eq!(terminal(&events).publication, Publication::None); | |
| 89 | 삭제: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 128 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 129 | 추가: assert_zero_file(&s.0.join("output/payload.bin"), 16 * 1024 * 1024); | |
| 90 | 130 | } |
| 91 | 131 | #[test] |
| 92 | 132 | fn streaming_tar_and_gzip_truncation_never_publish() { |
| @@ -204,13 +244,12 @@ fn untrusted_zip64_u64_sizes_and_offsets_never_allocate_or_publish() { | ||
| 204 | 244 | } |
| 205 | 245 | } |
| 206 | 246 | #[test] |
| 207 | 삭제: fn gzip_ratio_is_per_member_even_with_low_ratio_suffix() { | |
| 247 | 추가: fn gzip_high_ratio_members_extract_below_total_limit() { | |
| 208 | 248 | let s = Scratch::new(); |
| 209 | 249 | generate(&s, "gzip-bomb-joined", 16 * 1024 * 1024); |
| 210 | 250 | let events = execute(start(&s, true, Limits::default().output)); |
| 211 | 삭제: assert_eq!(terminal(&events).error, ErrorCode::Limit, "{events:?}"); | |
| 212 | 삭제: assert_eq!(terminal(&events).created_count, 0); | |
| 213 | 삭제: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 251 | 추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}"); | |
| 252 | 추가: assert_zero_file(&s.0.join("output/payload.bin"), 32 * 1024 * 1024); | |
| 214 | 253 | } |
| 215 | 254 | #[test] |
| 216 | 255 | fn streamed_aes_counter_survives_many_read_chunks() { |
| @@ -412,6 +451,31 @@ mod linux { | ||
| 412 | 451 | } |
| 413 | 452 | } |
| 414 | 453 | #[test] |
| 454 | 추가: fn disk_space_preflight_rejects_without_outputs_and_closes_staging() { | |
| 455 | 추가: for mode in [ | |
| 456 | 추가: "space-stage", | |
| 457 | 추가: "space-destination", | |
| 458 | 추가: "space-combined", | |
| 459 | 추가: "space-error", | |
| 460 | 추가: ] { | |
| 461 | 추가: let s = Scratch::new(); | |
| 462 | 추가: generate(&s, "store", 1024 * 1024); | |
| 463 | 추가: let request = start(&s, false, Limits::default().output); | |
| 464 | 추가: let child = spawn(&s, request, Some(mode)); | |
| 465 | 추가: assert_eq!(wait(child.id()).0, 0); | |
| 466 | 추가: let events = events(&s); | |
| 467 | 추가: let t = terminal(&events); | |
| 468 | 추가: assert_eq!(t.error, ErrorCode::Io, "{mode}: {events:?}"); | |
| 469 | 추가: assert_eq!(t.publication, Publication::None); | |
| 470 | 추가: assert_eq!(t.cleanup, Cleanup::Complete); | |
| 471 | 추가: assert_eq!(t.created_count, 0); | |
| 472 | 추가: assert!(t.detail.contains("디스크 여유 공간")); | |
| 473 | 추가: assert!(s.0.join("paused").exists()); | |
| 474 | 추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0); | |
| 475 | 추가: assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0); | |
| 476 | 추가: } | |
| 477 | 추가: } | |
| 478 | 추가: #[test] | |
| 415 | 479 | fn anonymous_tempfile_fallback_unlinks_before_use() { |
| 416 | 480 | let s = Scratch::new(); |
| 417 | 481 | generate(&s, "store", 1024 * 1024); |
| @@ -7,16 +7,20 @@ | ||
| 7 | 7 | #include <string.h> |
| 8 | 8 | #include <stdio.h> |
| 9 | 9 | #include <unistd.h> |
| 10 | 추가: #include <sys/stat.h> | |
| 11 | 추가: #include <sys/statvfs.h> | |
| 10 | 12 | |
| 11 | 13 | static ssize_t (*real_write)(int, const void *, size_t); |
| 12 | 14 | static int (*real_openat)(int, const char *, int, ...); |
| 13 | 15 | static int (*real_open64)(const char *, int, ...); |
| 16 | 추가: static int (*real_fstatvfs)(int, struct statvfs *); | |
| 14 | 17 | static int started; |
| 15 | 18 | |
| 16 | 19 | __attribute__((constructor)) static void initialize(void) { |
| 17 | 20 | real_write = dlsym(RTLD_NEXT, "write"); |
| 18 | 21 | real_openat = dlsym(RTLD_NEXT, "openat"); |
| 19 | 22 | real_open64 = dlsym(RTLD_NEXT, "open64"); |
| 23 | 추가: real_fstatvfs = dlsym(RTLD_NEXT, "fstatvfs"); | |
| 20 | 24 | } |
| 21 | 25 | |
| 22 | 26 | static int output_file(int fd) { |
| @@ -83,3 +87,20 @@ ssize_t write(int fd, const void *bytes, size_t count) { | ||
| 83 | 87 | } |
| 84 | 88 | return real_write(fd, bytes, count); |
| 85 | 89 | } |
| 90 | 추가: | |
| 91 | 추가: int fstatvfs(int fd, struct statvfs *value) { | |
| 92 | 추가: int result = real_fstatvfs(fd, value); | |
| 93 | 추가: const char *fault = getenv("ZIPELO_TEST_FAULT"); | |
| 94 | 추가: if (result || !fault || strncmp(fault, "space-", 6)) return result; | |
| 95 | 추가: struct stat st; | |
| 96 | 추가: if (fstat(fd, &st)) return -1; | |
| 97 | 추가: int affected = !strcmp(fault, "space-error") || !strcmp(fault, "space-combined") | |
| 98 | 추가: || (!strcmp(fault, "space-stage") && S_ISREG(st.st_mode)) | |
| 99 | 추가: || (!strcmp(fault, "space-destination") && S_ISDIR(st.st_mode)); | |
| 100 | 추가: if (!affected) return result; | |
| 101 | 추가: int marker = real_openat(AT_FDCWD, getenv("ZIPELO_TEST_MARKER"), O_CREAT | O_WRONLY, 0600); | |
| 102 | 추가: if (marker >= 0) close(marker); | |
| 103 | 추가: if (!strcmp(fault, "space-error")) { errno = EIO; return -1; } | |
| 104 | 추가: value->f_bavail = !strcmp(fault, "space-combined") ? (1536 * 1024) / value->f_frsize : 0; | |
| 105 | 추가: return 0; | |
| 106 | 추가: } |
| @@ -1,18 +1,7 @@ | ||
| 1 | 1 | use super::*; |
| 2 | 2 | |
| 3 | 3 | #[test] |
| 4 | 삭제: fn ratio_boundaries_do_not_overflow() { | |
| 5 | 삭제: assert!(ratio(0, 0).is_ok()); | |
| 6 | 삭제: assert_eq!(ratio(1, 0), Err(ErrorCode::Limit)); | |
| 7 | 삭제: for compressed in [1, 17, 65536, 16 * 1024 * 1024] { | |
| 8 | 삭제: assert!(ratio(compressed * 1000, compressed).is_ok()); | |
| 9 | 삭제: assert_eq!( | |
| 10 | 삭제: ratio(compressed * 1000 + 1, compressed), | |
| 11 | 삭제: Err(ErrorCode::Limit) | |
| 12 | 삭제: ); | |
| 13 | 삭제: } | |
| 14 | 삭제: assert!(ratio(u64::MAX, u64::MAX).is_ok()); | |
| 15 | 삭제: assert!(ratio(u64::MAX, u64::MAX / 1000 + 1).is_ok()); | |
| 16 | 삭제: assert_eq!(ratio(u64::MAX, u64::MAX / 1000), Err(ErrorCode::Limit)); | |
| 4 | 추가: fn offsets_do_not_overflow() { | |
| 17 | 5 | assert_eq!(add(u64::MAX, 1), Err(ErrorCode::Integrity)); |
| 6 | 추가: assert_eq!(add(u64::MAX - 1, 1), Ok(u64::MAX)); | |
| 18 | 7 | } |