ZIP64 디스크립터와 대용량 경계 검증을 수정함
- 작성자
- 시로사키 하나
- 작성 시각
- 커밋
608bf6f53f6b28736c0d184fd8da751555119a7e- 부모
- 65ada9b
변경된 파일 8개
+237-81| @@ -471,7 +471,6 @@ fn zip( | ||
| 471 | 471 | } |
| 472 | 472 | let name = std::str::from_utf8(&raw).map_err(|_| ErrorCode::Integrity)?; |
| 473 | 473 | let (aes, large) = extra(&bytes(source, cursor + 46 + nn, ne as usize)?)?; |
| 474 | 삭제: let central_zip64 = large.is_some(); | |
| 475 | 474 | let mut large = large.as_deref().unwrap_or(&[]); |
| 476 | 475 | let size = large_value(u32at(&h, 24), &mut large)?; |
| 477 | 476 | let compressed = large_value(u32at(&h, 20), &mut large)?; |
| @@ -542,9 +541,7 @@ fn zip( | ||
| 542 | 541 | if local_aes != aes { |
| 543 | 542 | return Err(ErrorCode::Integrity); |
| 544 | 543 | } |
| 545 | 삭제: let zip64 = central_zip64 | |
| 546 | 삭제: || local_large.is_some() | |
| 547 | 삭제: || u32at(&h, 20) == u32::MAX | |
| 544 | 추가: let size_zip64 = u32at(&h, 20) == u32::MAX | |
| 548 | 545 | || u32at(&h, 24) == u32::MAX |
| 549 | 546 | || u32at(&lh, 18) == u32::MAX |
| 550 | 547 | || u32at(&lh, 22) == u32::MAX; |
| @@ -561,7 +558,7 @@ fn zip( | ||
| 561 | 558 | return Err(ErrorCode::Integrity); |
| 562 | 559 | } |
| 563 | 560 | if flags & 8 != 0 { |
| 564 | 삭제: let descriptor_len = if zip64 { 20 } else { 12 }; | |
| 561 | 추가: let descriptor_len = if size_zip64 { 20 } else { 12 }; | |
| 565 | 562 | if add(stop, descriptor_len)? > central { |
| 566 | 563 | return Err(ErrorCode::Integrity); |
| 567 | 564 | } |
| @@ -573,7 +570,7 @@ fn zip( | ||
| 573 | 570 | return Err(ErrorCode::Integrity); |
| 574 | 571 | } |
| 575 | 572 | let d = bytes(source, stop, descriptor_len as usize)?; |
| 576 | 삭제: let (pc, ps) = if zip64 { | |
| 573 | 추가: let (pc, ps) = if size_zip64 { | |
| 577 | 574 | (u64at(&d, 4), u64at(&d, 12)) |
| 578 | 575 | } else { |
| 579 | 576 | (u32at(&d, 4) as u64, u32at(&d, 8) as u64) |
| @@ -21,9 +21,10 @@ class LargeArchiveFixtureTests(unittest.TestCase): | ||
| 21 | 21 | with tempfile.TemporaryDirectory(dir=ROOT / "tests/ci") as scratch: |
| 22 | 22 | directory = Path(scratch) / "corpus" |
| 23 | 23 | manifest = GENERATOR.build(directory) |
| 24 | 삭제: self.assertEqual(len(manifest["cases"]), 6) | |
| 24 | 추가: self.assertEqual(len(manifest["cases"]), 11) | |
| 25 | 25 | self.assertFalse(manifest["worker_execution_verified"]) |
| 26 | 삭제: for name, artifact in manifest["artifacts"].items(): | |
| 26 | 추가: for name in ("boundary.zip", "boundary.tar.gz"): | |
| 27 | 추가: artifact = manifest["artifacts"][name] | |
| 27 | 28 | path = directory / name |
| 28 | 29 | self.assertEqual(GENERATOR.digest(path), artifact["sha256"]) |
| 29 | 30 | if name.endswith(".zip"): |
| @@ -42,10 +43,25 @@ class LargeArchiveFixtureTests(unittest.TestCase): | ||
| 42 | 43 | self.assertGreater(decoded / artifact["archive_bytes"], 100) |
| 43 | 44 | for case in manifest["cases"]: |
| 44 | 45 | decoded = manifest["artifacts"][case["file"]]["decoded_bytes"] |
| 45 | 삭제: failed = decoded > case["limits"]["output"] | |
| 46 | 추가: exceeded = GENERATOR.violations(manifest["artifacts"][case["file"]], case["limits"]) | |
| 47 | 추가: self.assertEqual(exceeded, case["violated_limits"]) | |
| 48 | 추가: self.assertLessEqual(len(exceeded), 1) | |
| 49 | 추가: self.assertEqual(case["limits"]["input"], 2 ** 64 - 1) | |
| 50 | 추가: failed = bool(exceeded) | |
| 46 | 51 | self.assertEqual(case["expected"]["error"], "Limit" if failed else "None") |
| 47 | 52 | self.assertEqual(case["expected"]["created_count"], 0 if failed else 1) |
| 48 | 53 | |
| 54 | 추가: def test_ratio_boundary_is_exact_and_below_output_limit(self): | |
| 55 | 추가: with tempfile.TemporaryDirectory(dir=ROOT / "tests/ci") as scratch: | |
| 56 | 추가: manifest = GENERATOR.build(Path(scratch) / "corpus") | |
| 57 | 추가: for suffix, delta in (("below", -1), ("equal", 0), ("above", 1)): | |
| 58 | 추가: name = "ratio-" + suffix + ".gz" | |
| 59 | 추가: artifact = manifest["artifacts"][name] | |
| 60 | 추가: self.assertEqual(artifact["decoded_bytes"] - 1000 * artifact["ratio_input_bytes"], delta) | |
| 61 | 추가: self.assertLess(artifact["decoded_bytes"], GENERATOR.OUTPUT_LIMIT) | |
| 62 | 추가: payload = gzip.decompress((Path(scratch) / "corpus" / name).read_bytes()) | |
| 63 | 추가: self.assertEqual(payload, bytes(artifact["payload_bytes"])) | |
| 64 | 추가: | |
| 49 | 65 | def test_generator_rejects_existing_destination_without_changes(self): |
| 50 | 66 | with tempfile.TemporaryDirectory(dir=ROOT / "tests/ci") as scratch: |
| 51 | 67 | directory = Path(scratch) |
| @@ -1,33 +1,33 @@ | ||
| 1 | 1 | # 대용량 압축파일 회귀 표본 |
| 2 | 2 | |
| 3 | 삭제: Python 표준 라이브러리로 실행 시점에 표본을 생성합니다. 생성된 압축파일은 커밋하지 않습니다. 생성기는 64 KiB씩 읽고 쓰며 전체 입력이나 해제 데이터를 메모리에 보관하지 않습니다. 제품 코드와 통신 revision 2는 변경하지 않습니다. | |
| 3 | 추가: Python 표준 라이브러리로 실행할 때 합성 표본을 생성합니다. 생성 데이터는 커밋하지 않으며 읽기와 쓰기는 64 KiB로 나눕니다. revision 2의 입력 u64::MAX, 해제 총량 16 GiB, 압축비 1000:1을 기준으로 합니다. | |
| 4 | 4 | |
| 5 | 삭제: ## 현재 기대값 | |
| 5 | 추가: ## 독립된 경계 | |
| 6 | 6 | |
| 7 | 삭제: 기준은 main d6b1a45입니다. 기본 요청의 input=67108864, output=134217728, entries=10000을 사용합니다. 현재 작업자는 이보다 큰 요청 한도도 허용하지 않습니다. 별도 압축률 한도 필드는 없으므로 비율 기준으로 거부한다고 판정하지 않습니다. | |
| 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를 스트리밍 검증합니다. 제품의 해당 크기 해제 성공을 검증하는 시험은 아닙니다. | |
| 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의 분모는 헤더와 트레일러를 포함한 멤버 전체 바이트입니다. | |
| 8 | 12 | |
| 9 | 삭제: - large-input.zip: 1 GiB 단일 파일을 Store로 저장합니다. 압축파일 자체가 1 GiB 이상이므로 입력 한도에서 Failed/Limit이어야 합니다. | |
| 10 | 삭제: - large-input.tar.gz: 1 GiB 단일 파일의 USTAR를 Gzip level 0으로 저장합니다. 압축파일 자체가 1 GiB 이상이며 입력 한도에서 Failed/Limit이어야 합니다. | |
| 11 | 삭제: - large-expansion.zip과 large-expansion.tar.gz: 같은 1 GiB 영 바이트를 Deflate로 압축합니다. 입력은 64 MiB 미만이며 해제 한도로 Failed/Limit이어야 합니다. ZIP은 목록 메타데이터, TAR.GZ는 Gzip 해제 중 한도에 걸립니다. | |
| 12 | 삭제: - boundary.zip: 실제 해제 크기는 65536바이트입니다. output 한도를 65537, 65536, 65535로 설정해 각각 Completed, Completed, Failed/Limit을 요구합니다. | |
| 13 | 삭제: - boundary.tar.gz: 파일 내용은 64000바이트이고 USTAR 헤더, 패딩, 종료 블록까지 해제한 크기는 65536바이트입니다. 위와 같은 output 한도에서 같은 결과를 요구합니다. TAR.GZ 한도는 파일 내용만이 아니라 바깥 Gzip 해제 크기에도 적용됩니다. | |
| 13 | 추가: 생성 시 실제 archive_bytes, decoded_bytes, ratio_input_bytes와 요청 한도를 비교해 violated_limits가 정확히 일치하는지 검사합니다. 한 표본에서 여러 한도를 넘으면 생성을 실패시킵니다. 입력, 출력, 항목 수는 manifest의 실제 값이 모두 작업자 요청에 전달됩니다. 생성 결과만으로 검증 완료를 주장하지 않도록 worker_execution_verified=false를 기록합니다. | |
| 14 | 14 | |
| 15 | 삭제: 경계 표본도 해제/입력 비율이 100배 이상인 유효한 고압축 스트림입니다. below/equal/above는 해제 크기가 요청 한도보다 작음/같음/큼을 뜻합니다. 스트리밍 변경 뒤에는 입력 크기 거부 기대값을 별도로 갱신해야 하며, 이 기준을 새 구현의 성공 기준으로 고정하지 않습니다. | |
| 15 | 추가: ## 실행 | |
| 16 | 16 | |
| 17 | 삭제: ## 생성과 검증 | |
| 18 | 삭제: | |
| 19 | 삭제: 저장소 루트에서 실행합니다. output은 tests 아래의 존재하지 않는 경로여야 합니다. 기존 경로나 파일을 덮어쓰지 않습니다. 큰 입력 2개를 위해 약 2.1 GiB의 디스크가 필요하고, 검증 중 작은 경계 표본만 실제 파일로 해제합니다. | |
| 17 | 추가: 저장소 루트에서 실행합니다. --large는 1 GiB 성공 2건과 16 GiB 초과 거부를 포함해 총 14건을 검사합니다. 생성을 포함한 기본 실행은 tests 안의 전용 임시 디렉터리를 쓰고 종료 시 정리합니다. 압축 표본, 입력 사본과 출력에 수 GiB의 임시 디스크 공간이 필요합니다. | |
| 20 | 18 | |
| 21 | 19 | ```sh |
| 22 | 삭제: python3 tests/large-archive-fixtures/generate.py --large --output tests/large-archive-fixtures/runs/full | |
| 23 | 20 | python3 tests/ci/run_rust.py local |
| 24 | 삭제: python3 tests/large-archive-fixtures/verify.py --directory tests/large-archive-fixtures/runs/full --probe tests/ci/target/debug/zipelo-large-archive-probe --worker tests/ci/target/debug/zipelo-archive-worker | |
| 21 | 추가: python3 tests/large-archive-fixtures/verify.py --large | |
| 25 | 22 | ``` |
| 26 | 23 | |
| 27 | 삭제: CARGO_TARGET_DIR을 별도로 지정했다면 probe와 worker 경로도 그 캐시에 맞춥니다. --large를 생략하면 작은 경계 표본만 생성합니다. 전체 생성 및 실제 작업자 검증은 명시적으로 실행하며, 기본 local 자체 검사에는 작은 표본의 무결성, 경계 기대값과 생성기 경로 및 버퍼 제약 검사가 포함됩니다. | |
| 24 | 추가: CARGO_TARGET_DIR을 지정했다면 검증기도 같은 환경 값을 사용합니다. --probe와 --worker로 바이너리 경로를 따로 지정할 수도 있습니다. --large를 생략하면 작은 경계 11건만 검사합니다. 기본 local 실행에는 작은 표본의 참조 무결성, 경계 독립성과 생성기 경로 및 버퍼 제약 검사가 포함됩니다. | |
| 28 | 25 | |
| 29 | 삭제: 생성된 expectations.json에는 각 표본의 실제 크기, 해제 크기, SHA-256, 요청 한도와 기대 결과를 기록합니다. worker_execution_verified=false는 생성만으로 작업자 검증을 주장하지 않음을 뜻하며 검증기는 이 파일을 바꾸지 않습니다. | |
| 26 | 추가: 표본을 보존하려면 아래처럼 새 경로를 지정합니다. 기존 디렉터리는 생성기가 덮어쓰지 않으며, 검증기는 기존 expectations.json이 있으면 재사용합니다. | |
| 30 | 27 | |
| 31 | 삭제: 검증기는 먼저 Python ZIP/Gzip 참조 판독기로 전체 표본을 64 KiB씩 읽어 CRC와 합성 내용, TAR 헤더 및 종료 블록을 확인합니다. 디스크에 참조 해제물을 쓰지 않습니다. 이어 실제 작업자를 별도 프로세스로 실행하고 exit 0, stderr 비어 있음, 정확히 한 번의 마지막 Terminal, outcome/error/publication, 생성 개수와 Output 이벤트를 확인합니다. 거부 시 최종 출력 폴더가 비어 있어야 하며 입력은 전후 SHA-256이 같아야 합니다. 성공 경계 표본은 해제 파일 길이와 모든 바이트가 0인지 확인합니다. 파일시스템 호출 추적은 하지 않으므로 일시적인 쓰기가 전혀 없었다고 증명하지는 않습니다. 표본의 payload는 모두 합성 데이터이며 사용자 압축파일은 사용하지 않습니다. | |
| 28 | 추가: ```sh | |
| 29 | 추가: python3 tests/large-archive-fixtures/generate.py --large --output tests/large-archive-fixtures/runs/full | |
| 30 | 추가: python3 tests/large-archive-fixtures/verify.py --large --directory tests/large-archive-fixtures/runs/full | |
| 31 | 추가: ``` | |
| 32 | 32 | |
| 33 | 삭제: 이 검증은 현재 크기 제한의 거부 동작을 확인합니다. 수 GB 해제 성공이나 작업자의 고정 메모리 상한, 디스크 고갈, 고아 프로세스 정리를 검증하는 시험은 아닙니다. Windows 실행은 별도 검증이 필요합니다. | |
| 33 | 추가: 검증기는 전체 표본을 참조 판독기로 읽어 합성 내용, CRC와 TAR 구조를 확인한 후 실제 작업자의 종료 코드, Terminal, 오류, 게시 상태, Output 개수와 정리를 확인합니다. 성공 파일은 길이와 모든 바이트를 검사하며 거부한 경우 출력 폴더가 비어 있어야 합니다. 입력의 전후 SHA-256도 확인합니다. 작업자 피크 RSS, 디스크 부족과 고아 작업자 정리는 tests/rust-archive-worker/hardening.rs에서 별도로 검사합니다. Windows 실기는 별도 검증이 필요합니다. |
| @@ -1,4 +1,4 @@ | ||
| 1 | 삭제: """고정 크기 버퍼로 합성 압축파일과 현재 main의 기대값을 생성함.""" | |
| 1 | 추가: """고정 크기 버퍼로 새 스트리밍 한도의 독립 경계 표본을 생성함.""" | |
| 2 | 2 | |
| 3 | 3 | import argparse |
| 4 | 4 | import gzip |
| @@ -6,16 +6,18 @@ import hashlib | ||
| 6 | 6 | import io |
| 7 | 7 | import json |
| 8 | 8 | from pathlib import Path |
| 9 | 추가: import struct | |
| 9 | 10 | import tarfile |
| 10 | 11 | import zipfile |
| 12 | 추가: import zlib | |
| 11 | 13 | |
| 12 | 14 | |
| 13 | 15 | ROOT = Path(__file__).resolve().parents[2] |
| 14 | 16 | GIB = 1024 ** 3 |
| 15 | 17 | CHUNK = 64 * 1024 |
| 16 | 삭제: INPUT_LIMIT = 64 * 1024 ** 2 | |
| 17 | 삭제: OUTPUT_LIMIT = 128 * 1024 ** 2 | |
| 18 | 삭제: BASELINE = "d6b1a45" | |
| 18 | 추가: INPUT_LIMIT = 2 ** 64 - 1 | |
| 19 | 추가: OUTPUT_LIMIT = 16 * GIB | |
| 20 | 추가: RATIO_LIMIT = 1000 | |
| 19 | 21 | NAME = "payload.bin" |
| 20 | 22 | |
| 21 | 23 | |
| @@ -31,9 +33,10 @@ class ZeroStream(io.RawIOBase): | ||
| 31 | 33 | return bytes(count) |
| 32 | 34 | |
| 33 | 35 | |
| 34 | 삭제: def write_zip(path, size, compressed): | |
| 36 | 추가: def write_zip(path, size, compressed, level=6): | |
| 35 | 37 | info = zipfile.ZipInfo(NAME, (1980, 1, 1, 0, 0, 0)) |
| 36 | 38 | info.compress_type = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED |
| 39 | 추가: info._compresslevel = level | |
| 37 | 40 | info.create_system = 3 |
| 38 | 41 | info.external_attr = 0o100600 << 16 |
| 39 | 42 | info.file_size = size |
| @@ -65,6 +68,23 @@ def write_targz(path, size, compressed): | ||
| 65 | 68 | output.write(bytes((-size) % 512 + 1024)) |
| 66 | 69 | |
| 67 | 70 | |
| 71 | 추가: def write_ratio_gzip(path, size, packed_size): | |
| 72 | 추가: compressor = zlib.compressobj(level=6, wbits=-15) | |
| 73 | 추가: source = ZeroStream(size) | |
| 74 | 추가: crc = 0 | |
| 75 | 추가: chunks = [] | |
| 76 | 추가: while chunk := source.read(CHUNK): | |
| 77 | 추가: crc = zlib.crc32(chunk, crc) | |
| 78 | 추가: chunks.append(compressor.compress(chunk)) | |
| 79 | 추가: data = b"".join(chunks) + compressor.flush() | |
| 80 | 추가: padding = packed_size - 20 - len(data) | |
| 81 | 추가: assert 0 <= padding <= 65535 | |
| 82 | 추가: header = bytes.fromhex("1f8b08040000000000ff") + struct.pack("<H", padding) | |
| 83 | 추가: with path.open("xb") as output: | |
| 84 | 추가: output.write(header + bytes(padding) + data + struct.pack("<II", crc, size)) | |
| 85 | 추가: assert path.stat().st_size == packed_size | |
| 86 | 추가: | |
| 87 | 추가: | |
| 68 | 88 | def digest(path): |
| 69 | 89 | value = hashlib.sha256() |
| 70 | 90 | with path.open("rb") as source: |
| @@ -73,6 +93,17 @@ def digest(path): | ||
| 73 | 93 | return value.hexdigest() |
| 74 | 94 | |
| 75 | 95 | |
| 96 | 추가: def violations(artifact, limits): | |
| 97 | 추가: failed = [] | |
| 98 | 추가: if artifact["archive_bytes"] > limits["input"]: | |
| 99 | 추가: failed.append("input") | |
| 100 | 추가: if artifact["decoded_bytes"] > limits["output"]: | |
| 101 | 추가: failed.append("output") | |
| 102 | 추가: if artifact["decoded_bytes"] > artifact["ratio_input_bytes"] * RATIO_LIMIT: | |
| 103 | 추가: failed.append("ratio") | |
| 104 | 추가: return failed | |
| 105 | 추가: | |
| 106 | 추가: | |
| 76 | 107 | def build(directory, large=False): |
| 77 | 108 | directory = Path(directory).resolve() |
| 78 | 109 | directory.relative_to(ROOT / "tests") |
| @@ -80,26 +111,43 @@ def build(directory, large=False): | ||
| 80 | 111 | cases = [] |
| 81 | 112 | artifacts = {} |
| 82 | 113 | |
| 83 | 삭제: def add(name, size, compressed, category, limits): | |
| 114 | 추가: def add(name, size, compressed, category, boundaries, level=6, packed_size=None): | |
| 84 | 115 | path = directory / name |
| 85 | 116 | if name.endswith(".zip"): |
| 86 | 삭제: write_zip(path, size, compressed) | |
| 117 | 추가: write_zip(path, size, compressed, level) | |
| 87 | 118 | expanded = size |
| 88 | 삭제: else: | |
| 119 | 추가: with zipfile.ZipFile(path) as archive: | |
| 120 | 추가: ratio_input = archive.getinfo(NAME).compress_size | |
| 121 | 추가: archive_format = "Zip" | |
| 122 | 추가: elif name.endswith(".tar.gz"): | |
| 89 | 123 | write_targz(path, size, compressed) |
| 90 | 124 | expanded = tar_size(size) |
| 91 | 삭제: artifacts[name] = { | |
| 125 | 추가: ratio_input = path.stat().st_size | |
| 126 | 추가: archive_format = "TarGzip" | |
| 127 | 추가: else: | |
| 128 | 추가: write_ratio_gzip(path, size, packed_size) | |
| 129 | 추가: expanded = size | |
| 130 | 추가: ratio_input = path.stat().st_size | |
| 131 | 추가: archive_format = "Gzip" | |
| 132 | 추가: artifact = { | |
| 133 | 추가: "format": archive_format, | |
| 92 | 134 | "archive_bytes": path.stat().st_size, |
| 93 | 135 | "payload_bytes": size, |
| 94 | 136 | "decoded_bytes": expanded, |
| 137 | 추가: "ratio_input_bytes": ratio_input, | |
| 95 | 138 | "sha256": digest(path), |
| 96 | 139 | } |
| 97 | 삭제: for suffix, output_limit, failed in limits: | |
| 140 | 추가: artifacts[name] = artifact | |
| 141 | 추가: for suffix, output_limit, exceeded in boundaries: | |
| 142 | 추가: limits = {"input": INPUT_LIMIT, "output": output_limit, "entries": 10000} | |
| 143 | 추가: assert violations(artifact, limits) == exceeded, (name, suffix, artifact) | |
| 144 | 추가: failed = bool(exceeded) | |
| 98 | 145 | cases.append({ |
| 99 | 146 | "id": name + "-" + suffix, |
| 100 | 147 | "file": name, |
| 101 | 148 | "category": category, |
| 102 | 삭제: "limits": {"input": INPUT_LIMIT, "output": output_limit, "entries": 10000}, | |
| 149 | 추가: "limits": limits, | |
| 150 | 추가: "violated_limits": exceeded, | |
| 103 | 151 | "expected": { |
| 104 | 152 | "outcome": "Failed" if failed else "Completed", |
| 105 | 153 | "error": "Limit" if failed else "None", |
| @@ -112,20 +160,29 @@ def build(directory, large=False): | ||
| 112 | 160 | |
| 113 | 161 | for name, size in (("boundary.zip", CHUNK), ("boundary.tar.gz", CHUNK - 1536)): |
| 114 | 162 | add(name, size, True, "output-boundary", [ |
| 115 | 삭제: ("below", CHUNK + 1, False), | |
| 116 | 삭제: ("equal", CHUNK, False), | |
| 117 | 삭제: ("above", CHUNK - 1, True), | |
| 163 | 추가: ("below", CHUNK + 1, []), | |
| 164 | 추가: ("equal", CHUNK, []), | |
| 165 | 추가: ("above", CHUNK - 1, ["output"]), | |
| 166 | 추가: ]) | |
| 167 | 추가: 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 []), | |
| 170 | 추가: ], packed_size=2000) | |
| 171 | 추가: for extension in ("zip", "tar.gz"): | |
| 172 | 추가: add("ratio-only." + extension, 16 * 1024 ** 2, True, "ratio-limit", [ | |
| 173 | 추가: ("default", OUTPUT_LIMIT, ["ratio"]), | |
| 118 | 174 | ]) |
| 119 | 175 | if large: |
| 120 | 176 | for extension in ("zip", "tar.gz"): |
| 121 | 삭제: add("large-input." + extension, GIB, False, "input-limit", [ | |
| 122 | 삭제: ("default", OUTPUT_LIMIT, True), | |
| 123 | 삭제: ]) | |
| 124 | 삭제: add("large-expansion." + extension, GIB, True, "output-limit", [ | |
| 125 | 삭제: ("default", OUTPUT_LIMIT, True), | |
| 177 | 추가: add("large-input." + extension, GIB, False, "large-input-success", [ | |
| 178 | 추가: ("default", OUTPUT_LIMIT, []), | |
| 126 | 179 | ]) |
| 180 | 추가: add("output-only.zip", OUTPUT_LIMIT + 1, True, "hard-output-limit", [ | |
| 181 | 추가: ("default", OUTPUT_LIMIT, ["output"]), | |
| 182 | 추가: ], level=1) | |
| 127 | 183 | manifest = { |
| 128 | 삭제: "baseline_commit": BASELINE, | |
| 184 | 추가: "policy": {"revision": 2, "input": INPUT_LIMIT, "output": OUTPUT_LIMIT, "ratio": RATIO_LIMIT}, | |
| 185 | 추가: "large": large, | |
| 129 | 186 | "worker_execution_verified": False, |
| 130 | 187 | "generator_chunk_bytes": CHUNK, |
| 131 | 188 | "artifacts": artifacts, |
| @@ -140,7 +197,7 @@ def build(directory, large=False): | ||
| 140 | 197 | def main(): |
| 141 | 198 | parser = argparse.ArgumentParser() |
| 142 | 199 | parser.add_argument("--output", required=True, type=Path, help="tests 아래의 새 디렉터리") |
| 143 | 삭제: parser.add_argument("--large", action="store_true", help="1 GiB 표본 4개도 생성함") | |
| 200 | 추가: parser.add_argument("--large", action="store_true", help="1 GiB 성공과 16 GiB 초과 표본도 생성함") | |
| 144 | 201 | args = parser.parse_args() |
| 145 | 202 | manifest = build(args.output, args.large) |
| 146 | 203 | print(f"{len(manifest['cases'])} cases: {args.output / 'expectations.json'}") |
| @@ -1,4 +1,4 @@ | ||
| 1 | 삭제: """생성 표본을 실제 작업자 프로세스에 전달해 현재 main의 기대값을 검사함.""" | |
| 1 | 추가: """참조 판독기와 실제 작업자로 독립된 한도 기대값을 검사함.""" | |
| 2 | 2 | |
| 3 | 3 | import argparse |
| 4 | 4 | import gzip |
| @@ -11,8 +11,7 @@ import tempfile | ||
| 11 | 11 | import tarfile |
| 12 | 12 | import zipfile |
| 13 | 13 | |
| 14 | 삭제: from generate import CHUNK, NAME, ROOT, digest | |
| 15 | 삭제: | |
| 14 | 추가: from generate import CHUNK, NAME, ROOT, build, digest, violations | |
| 16 | 15 | |
| 17 | 16 | |
| 18 | 17 | def check_payload(source, size): |
| @@ -25,46 +24,62 @@ def check_payload(source, size): | ||
| 25 | 24 | |
| 26 | 25 | def check_reference(path, artifact): |
| 27 | 26 | size = artifact["payload_bytes"] |
| 28 | 삭제: if path.name.endswith(".zip"): | |
| 27 | 추가: if artifact["format"] == "Zip": | |
| 29 | 28 | with zipfile.ZipFile(path) as archive: |
| 30 | 29 | assert archive.namelist() == [NAME] |
| 31 | 삭제: assert archive.getinfo(NAME).file_size == size | |
| 30 | 추가: info = archive.getinfo(NAME) | |
| 31 | 추가: assert info.file_size == size | |
| 32 | 추가: assert info.compress_size == artifact["ratio_input_bytes"] | |
| 32 | 33 | with archive.open(NAME) as source: |
| 33 | 34 | check_payload(source, size) |
| 34 | 35 | assert source.read(1) == b"" |
| 35 | 36 | else: |
| 37 | 추가: assert path.stat().st_size == artifact["ratio_input_bytes"] | |
| 36 | 38 | with gzip.open(path, "rb") as source: |
| 37 | 삭제: header = source.read(512) | |
| 38 | 삭제: info = tarfile.TarInfo.frombuf(header, "utf-8", "strict") | |
| 39 | 삭제: assert info.name == NAME and info.size == size and info.isfile() | |
| 39 | 추가: if artifact["format"] == "TarGzip": | |
| 40 | 추가: header = source.read(512) | |
| 41 | 추가: info = tarfile.TarInfo.frombuf(header, "utf-8", "strict") | |
| 42 | 추가: assert info.name == NAME and info.size == size and info.isfile() | |
| 40 | 43 | check_payload(source, size) |
| 41 | 삭제: tail_size = (-size) % 512 + 1024 | |
| 42 | 삭제: assert source.read(tail_size) == bytes(tail_size) | |
| 44 | 추가: if artifact["format"] == "TarGzip": | |
| 45 | 추가: tail_size = (-size) % 512 + 1024 | |
| 46 | 추가: assert source.read(tail_size) == bytes(tail_size) | |
| 43 | 47 | assert source.read(1) == b"" |
| 44 | 48 | |
| 45 | 49 | |
| 46 | 삭제: def verify(directory, probe, worker): | |
| 50 | 추가: def verify(directory, probe, worker, large=False): | |
| 47 | 51 | directory = directory.resolve() |
| 48 | 52 | directory.relative_to(ROOT / "tests") |
| 49 | 53 | manifest = json.loads((directory / "expectations.json").read_text(encoding="utf-8")) |
| 54 | 추가: assert not large or manifest["large"] | |
| 50 | 55 | for name, artifact in manifest["artifacts"].items(): |
| 51 | 56 | assert (directory / name).stat().st_size == artifact["archive_bytes"] |
| 52 | 57 | assert digest(directory / name) == artifact["sha256"] |
| 53 | 58 | check_reference(directory / name, artifact) |
| 59 | 추가: print(f"REFERENCE {name}", flush=True) | |
| 54 | 60 | results = [] |
| 55 | 61 | for case in manifest["cases"]: |
| 56 | 62 | path = directory / case["file"] |
| 57 | 63 | artifact = manifest["artifacts"][case["file"]] |
| 64 | 추가: assert violations(artifact, case["limits"]) == case["violated_limits"] | |
| 58 | 65 | before = path.stat() |
| 59 | 삭제: with tempfile.TemporaryDirectory(prefix="extract-", dir=directory) as scratch: | |
| 60 | 삭제: destination = Path(scratch) | |
| 66 | 추가: with tempfile.TemporaryDirectory(prefix="case-", dir=directory) as scratch: | |
| 67 | 추가: destination = Path(scratch) / "output" | |
| 68 | 추가: staging = Path(scratch) / "staging" | |
| 69 | 추가: destination.mkdir(mode=0o700) | |
| 70 | 추가: staging.mkdir(mode=0o700) | |
| 61 | 71 | command = [ |
| 62 | 72 | str(probe.resolve()), str(worker.resolve()), str(path), str(destination), |
| 63 | 삭제: str(case["limits"]["output"]), case["expected"]["outcome"], | |
| 64 | 삭제: str(artifact["payload_bytes"]), | |
| 73 | 추가: str(case["limits"]["input"]), str(case["limits"]["output"]), | |
| 74 | 추가: str(case["limits"]["entries"]), case["expected"]["outcome"], | |
| 75 | 추가: str(artifact["payload_bytes"]), artifact["format"], | |
| 65 | 76 | ] |
| 77 | 추가: environment = os.environ.copy() | |
| 78 | 추가: environment["TMPDIR"] = str(staging) | |
| 79 | 추가: environment["TMP"] = str(staging) | |
| 80 | 추가: environment["TEMP"] = str(staging) | |
| 66 | 81 | process = subprocess.Popen( |
| 67 | 삭제: command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, | |
| 82 | 추가: command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment, | |
| 68 | 83 | start_new_session=(os.name == "posix"), |
| 69 | 84 | ) |
| 70 | 85 | try: |
| @@ -77,10 +92,11 @@ def verify(directory, probe, worker): | ||
| 77 | 92 | process.communicate() |
| 78 | 93 | raise |
| 79 | 94 | assert process.returncode == 0, (case["id"], stdout, stderr) |
| 95 | 추가: assert not list(staging.iterdir()) | |
| 80 | 96 | if case["expected"]["outcome"] == "Completed": |
| 81 | 삭제: with (destination / "payload.bin").open("rb") as source: | |
| 82 | 삭제: while chunk := source.read(65536): | |
| 83 | 삭제: assert not any(chunk) | |
| 97 | 추가: with (destination / NAME).open("rb") as source: | |
| 98 | 추가: check_payload(source, artifact["payload_bytes"]) | |
| 99 | 추가: assert source.read(1) == b"" | |
| 84 | 100 | else: |
| 85 | 101 | assert not list(destination.iterdir()) |
| 86 | 102 | after = path.stat() |
| @@ -92,10 +108,26 @@ def verify(directory, probe, worker): | ||
| 92 | 108 | return results |
| 93 | 109 | |
| 94 | 110 | |
| 95 | 삭제: if __name__ == "__main__": | |
| 111 | 추가: def main(): | |
| 96 | 112 | parser = argparse.ArgumentParser() |
| 97 | 삭제: parser.add_argument("--directory", required=True, type=Path) | |
| 98 | 삭제: parser.add_argument("--probe", required=True, type=Path) | |
| 99 | 삭제: parser.add_argument("--worker", required=True, type=Path) | |
| 113 | 추가: parser.add_argument("--directory", type=Path, help="기존 표본 또는 새 표본 경로") | |
| 114 | 추가: parser.add_argument("--large", action="store_true", help="1 GiB 성공과 16 GiB 초과도 검사함") | |
| 115 | 추가: target = Path(os.environ.get("CARGO_TARGET_DIR", ROOT / "tests/ci/target")) / "debug" | |
| 116 | 추가: suffix = ".exe" if os.name == "nt" else "" | |
| 117 | 추가: parser.add_argument("--probe", type=Path, default=target / ("zipelo-large-archive-probe" + suffix)) | |
| 118 | 추가: parser.add_argument("--worker", type=Path, default=target / ("zipelo-archive-worker" + suffix)) | |
| 100 | 119 | args = parser.parse_args() |
| 101 | 삭제: verify(args.directory, args.probe, args.worker) | |
| 120 | 추가: assert args.probe.is_file() and args.worker.is_file(), "local 빌드를 먼저 실행해야 함" | |
| 121 | 추가: if args.directory: | |
| 122 | 추가: if not args.directory.exists(): | |
| 123 | 추가: build(args.directory, args.large) | |
| 124 | 추가: verify(args.directory, args.probe, args.worker, args.large) | |
| 125 | 추가: else: | |
| 126 | 추가: with tempfile.TemporaryDirectory(prefix="fixture-", dir=ROOT / "tests/large-archive-fixtures") as scratch: | |
| 127 | 추가: directory = Path(scratch) / "corpus" | |
| 128 | 추가: build(directory, args.large) | |
| 129 | 추가: verify(directory, args.probe, args.worker, args.large) | |
| 130 | 추가: | |
| 131 | 추가: | |
| 132 | 추가: if __name__ == "__main__": | |
| 133 | 추가: main() |
| @@ -124,6 +124,31 @@ fn zip64_directory_and_descriptor_interoperate() { | ||
| 124 | 124 | } |
| 125 | 125 | } |
| 126 | 126 | #[test] |
| 127 | 추가: fn zip64_offset_only_keeps_32_bit_descriptors() { | |
| 128 | 추가: for kind in ["offset64-descriptor-signed", "offset64-descriptor-unsigned"] { | |
| 129 | 추가: let s = Scratch::new(); | |
| 130 | 추가: generate(&s, kind, 65536 + 19); | |
| 131 | 추가: let events = execute(Start { | |
| 132 | 추가: action: Action::List { | |
| 133 | 추가: archive: s.path("input"), | |
| 134 | 추가: }, | |
| 135 | 추가: limits: Limits::default(), | |
| 136 | 추가: }); | |
| 137 | 추가: assert_eq!( | |
| 138 | 추가: terminal(&events).outcome, | |
| 139 | 추가: Outcome::Completed, | |
| 140 | 추가: "{kind}: {events:?}" | |
| 141 | 추가: ); | |
| 142 | 추가: let events = execute(start(&s, false, Limits::default().output)); | |
| 143 | 추가: assert_eq!( | |
| 144 | 추가: terminal(&events).outcome, | |
| 145 | 추가: Outcome::Completed, | |
| 146 | 추가: "{kind}: {events:?}" | |
| 147 | 추가: ); | |
| 148 | 추가: assert_zero_file(&s.0.join("output/payload.bin"), 65536 + 19); | |
| 149 | 추가: } | |
| 150 | 추가: } | |
| 151 | 추가: #[test] | |
| 127 | 152 | fn untrusted_zip64_u64_sizes_and_offsets_never_allocate_or_publish() { |
| 128 | 153 | for (kind, error) in [ |
| 129 | 154 | ("central64-size-overflow", ErrorCode::Limit), |
| @@ -18,7 +18,33 @@ spec.loader.exec_module(fixtures) | ||
| 18 | 18 | def generate(directory, kind, size): |
| 19 | 19 | directory = Path(directory) |
| 20 | 20 | output = directory / "input" |
| 21 | 삭제: if kind.startswith("central64"): | |
| 21 | 추가: if kind.startswith("offset64-descriptor"): | |
| 22 | 추가: class Pipe(io.BytesIO): | |
| 23 | 추가: def seekable(self): | |
| 24 | 추가: return False | |
| 25 | 추가: def seek(self, *args): | |
| 26 | 추가: raise io.UnsupportedOperation() | |
| 27 | 추가: data = Pipe() | |
| 28 | 추가: with zipfile.ZipFile(data, "w", compression=zipfile.ZIP_STORED) as archive: | |
| 29 | 추가: archive.writestr(fixtures.NAME, bytes(size)) | |
| 30 | 추가: original = data.getvalue() | |
| 31 | 추가: central_at = struct.unpack_from("<I", original, len(original) - 6)[0] | |
| 32 | 추가: body = bytearray(original[:central_at]) | |
| 33 | 추가: struct.pack_into("<H", body, 4, 45) | |
| 34 | 추가: central = bytearray(original[central_at:-22]) | |
| 35 | 추가: struct.pack_into("<H", central, 6, 45) | |
| 36 | 추가: struct.pack_into("<H", central, 30, 12) | |
| 37 | 추가: struct.pack_into("<I", central, 42, 0xffffffff) | |
| 38 | 추가: central += struct.pack("<HHQ", 1, 8, 0) | |
| 39 | 추가: if kind.endswith("unsigned"): | |
| 40 | 추가: assert body[-16:-12] == b"PK\x07\x08" | |
| 41 | 추가: body = body[:-16] + body[-12:] | |
| 42 | 추가: end = bytearray(original[-22:]) | |
| 43 | 추가: struct.pack_into("<II", end, 12, len(central), len(body)) | |
| 44 | 추가: output.write_bytes(body + central + end) | |
| 45 | 추가: with zipfile.ZipFile(output) as reference: | |
| 46 | 추가: assert reference.read(fixtures.NAME) == bytes(size) | |
| 47 | 추가: elif kind.startswith("central64"): | |
| 22 | 48 | data = io.BytesIO() |
| 23 | 49 | with zipfile.ZipFile(data, "w", compression=zipfile.ZIP_STORED) as archive: |
| 24 | 50 | archive.writestr(fixtures.NAME, bytes(size)) |
| @@ -13,27 +13,30 @@ fn main() { | ||
| 13 | 13 | let args: Vec<_> = std::env::args_os().skip(1).collect(); |
| 14 | 14 | assert_eq!( |
| 15 | 15 | args.len(), |
| 16 | 삭제: 6, | |
| 17 | 삭제: "worker archive destination output_limit outcome payload_size" | |
| 16 | 추가: 9, | |
| 17 | 추가: "worker archive destination input_limit output_limit entries outcome payload_size gzip" | |
| 18 | 18 | ); |
| 19 | 19 | let source = PathBuf::from(&args[1]); |
| 20 | 20 | let destination = PathBuf::from(&args[2]); |
| 21 | 21 | assert_eq!(fs::read_dir(&destination).unwrap().count(), 0); |
| 22 | 삭제: let failed = args[4] == "Failed"; | |
| 23 | 삭제: assert!(failed || args[4] == "Completed"); | |
| 24 | 삭제: let output_limit = args[3].to_str().unwrap().parse().unwrap(); | |
| 25 | 삭제: let payload_size: u64 = args[5].to_str().unwrap().parse().unwrap(); | |
| 22 | 추가: let failed = args[6] == "Failed"; | |
| 23 | 추가: assert!(failed || args[6] == "Completed"); | |
| 24 | 추가: let input_limit = args[3].to_str().unwrap().parse().unwrap(); | |
| 25 | 추가: let output_limit = args[4].to_str().unwrap().parse().unwrap(); | |
| 26 | 추가: let entries_limit = args[5].to_str().unwrap().parse().unwrap(); | |
| 27 | 추가: let payload_size: u64 = args[7].to_str().unwrap().parse().unwrap(); | |
| 26 | 28 | let start = Start { |
| 27 | 29 | action: Action::Extract { |
| 28 | 30 | archive: NativePath::from_path(&source), |
| 29 | 31 | destination: NativePath::from_path(&destination), |
| 30 | 32 | selection: Selection::All, |
| 31 | 33 | list_id: None, |
| 32 | 삭제: gzip_output_name: None, | |
| 34 | 추가: gzip_output_name: (args[8] == "Gzip").then(|| "payload.bin".to_owned()), | |
| 33 | 35 | }, |
| 34 | 36 | limits: Limits { |
| 37 | 추가: input: input_limit, | |
| 35 | 38 | output: output_limit, |
| 36 | 삭제: ..Limits::default() | |
| 39 | 추가: entries: entries_limit, | |
| 37 | 40 | }, |
| 38 | 41 | }; |
| 39 | 42 | let mut request = Vec::new(); |