team-ljyzipelo

공개

ZIP64 디스크립터와 대용량 경계 검증을 수정함

작성자
시로사키 하나
작성 시각
커밋
608bf6f53f6b28736c0d184fd8da751555119a7e
부모
65ada9b
이 시점의 파일 보기

변경된 파일 8개

+237-81
수정experiments/rust-archive-worker/src/streaming.rs+3-6
@@ -471,7 +471,6 @@ fn zip(
471471 }
472472 let name = std::str::from_utf8(&raw).map_err(|_| ErrorCode::Integrity)?;
473473 let (aes, large) = extra(&bytes(source, cursor + 46 + nn, ne as usize)?)?;
474삭제: let central_zip64 = large.is_some();
475474 let mut large = large.as_deref().unwrap_or(&[]);
476475 let size = large_value(u32at(&h, 24), &mut large)?;
477476 let compressed = large_value(u32at(&h, 20), &mut large)?;
@@ -542,9 +541,7 @@ fn zip(
542541 if local_aes != aes {
543542 return Err(ErrorCode::Integrity);
544543 }
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
548545 || u32at(&h, 24) == u32::MAX
549546 || u32at(&lh, 18) == u32::MAX
550547 || u32at(&lh, 22) == u32::MAX;
@@ -561,7 +558,7 @@ fn zip(
561558 return Err(ErrorCode::Integrity);
562559 }
563560 if flags & 8 != 0 {
564삭제: let descriptor_len = if zip64 { 20 } else { 12 };
561추가: let descriptor_len = if size_zip64 { 20 } else { 12 };
565562 if add(stop, descriptor_len)? > central {
566563 return Err(ErrorCode::Integrity);
567564 }
@@ -573,7 +570,7 @@ fn zip(
573570 return Err(ErrorCode::Integrity);
574571 }
575572 let d = bytes(source, stop, descriptor_len as usize)?;
576삭제: let (pc, ps) = if zip64 {
573추가: let (pc, ps) = if size_zip64 {
577574 (u64at(&d, 4), u64at(&d, 12))
578575 } else {
579576 (u32at(&d, 4) as u64, u32at(&d, 8) as u64)
수정tests/ci/test_large_archive_fixtures.py+19-3
@@ -21,9 +21,10 @@ class LargeArchiveFixtureTests(unittest.TestCase):
2121 with tempfile.TemporaryDirectory(dir=ROOT / "tests/ci") as scratch:
2222 directory = Path(scratch) / "corpus"
2323 manifest = GENERATOR.build(directory)
24삭제: self.assertEqual(len(manifest["cases"]), 6)
24추가: self.assertEqual(len(manifest["cases"]), 11)
2525 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]
2728 path = directory / name
2829 self.assertEqual(GENERATOR.digest(path), artifact["sha256"])
2930 if name.endswith(".zip"):
@@ -42,10 +43,25 @@ class LargeArchiveFixtureTests(unittest.TestCase):
4243 self.assertGreater(decoded / artifact["archive_bytes"], 100)
4344 for case in manifest["cases"]:
4445 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)
4651 self.assertEqual(case["expected"]["error"], "Limit" if failed else "None")
4752 self.assertEqual(case["expected"]["created_count"], 0 if failed else 1)
4853
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추가:
4965 def test_generator_rejects_existing_destination_without_changes(self):
5066 with tempfile.TemporaryDirectory(dir=ROOT / "tests/ci") as scratch:
5167 directory = Path(scratch)
수정tests/large-archive-fixtures/README.md+18-18
@@ -1,33 +1,33 @@
11# 대용량 압축파일 회귀 표본
22
3삭제: Python 표준 라이브러리로 실행 시점에 표본을 생성합니다. 생성된 압축파일은 커밋하지 않습니다. 생성기는 64 KiB씩 읽고 쓰며 전체 입력이나 해제 데이터를 메모리에 보관하지 않습니다. 제품 코드와 통신 revision 2는 변경하지 않습니다.
3추가: Python 표준 라이브러리로 실행할 때 합성 표본을 생성합니다. 생성 데이터는 커밋하지 않으며 읽기와 쓰기는 64 KiB로 나눕니다. revision 2의 입력 u64::MAX, 해제 총량 16 GiB, 압축비 1000:1을 기준으로 합니다.
44
5삭제: ## 현재 기대값
5추가: ## 독립된 경계
66
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의 분모는 헤더와 트레일러를 포함한 멤버 전체 바이트입니다.
812
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를 기록합니다.
1414
15삭제: 경계 표본도 해제/입력 비율이 100배 이상인 유효한 고압축 스트림입니다. below/equal/above는 해제 크기가 요청 한도보다 작음/같음/큼을 뜻합니다. 스트리밍 변경 뒤에는 입력 크기 거부 기대값을 별도로 갱신해야 하며, 이 기준을 새 구현의 성공 기준으로 고정하지 않습니다.
15추가: ## 실행
1616
17삭제: ## 생성과 검증
18삭제:
19삭제: 저장소 루트에서 실행합니다. output은 tests 아래의 존재하지 않는 경로여야 합니다. 기존 경로나 파일을 덮어쓰지 않습니다. 큰 입력 2개를 위해 약 2.1 GiB의 디스크가 필요하고, 검증 중 작은 경계 표본만 실제 파일로 해제합니다.
17추가: 저장소 루트에서 실행합니다. --large는 1 GiB 성공 2건과 16 GiB 초과 거부를 포함해 총 14건을 검사합니다. 생성을 포함한 기본 실행은 tests 안의 전용 임시 디렉터리를 쓰고 종료 시 정리합니다. 압축 표본, 입력 사본과 출력에 수 GiB의 임시 디스크 공간이 필요합니다.
2018
2119```sh
22삭제: python3 tests/large-archive-fixtures/generate.py --large --output tests/large-archive-fixtures/runs/full
2320python3 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
2522```
2623
27삭제: CARGO_TARGET_DIR을 별도로 지정했다면 probe와 worker 경로도 그 캐시에 맞춥니다. --large를 생략하면 작은 경계 표본만 생성합니다. 전체 생성 및 실제 작업자 검증은 명시적으로 실행하며, 기본 local 자체 검사에는 작은 표본의 무결성, 경계 기대값과 생성기 경로 및 버퍼 제약 검사가 포함됩니다.
24추가: CARGO_TARGET_DIR을 지정했다면 검증기도 같은 환경 값을 사용합니다. --probe와 --worker로 바이너리 경로를 따로 지정할 수도 있습니다. --large를 생략하면 작은 경계 11건만 검사합니다. 기본 local 실행에는 작은 표본의 참조 무결성, 경계 독립성과 생성기 경로 및 버퍼 제약 검사가 포함됩니다.
2825
29삭제: 생성된 expectations.json에는 각 표본의 실제 크기, 해제 크기, SHA-256, 요청 한도와 기대 결과를 기록합니다. worker_execution_verified=false는 생성만으로 작업자 검증을 주장하지 않음을 뜻하며 검증기는 이 파일을 바꾸지 않습니다.
26추가: 표본을 보존하려면 아래처럼 새 경로를 지정합니다. 기존 디렉터리는 생성기가 덮어쓰지 않으며, 검증기는 기존 expectations.json이 있으면 재사용합니다.
3027
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추가: ```
3232
33삭제: 이 검증은 현재 크기 제한의 거부 동작을 확인합니다. 수 GB 해제 성공이나 작업자의 고정 메모리 상한, 디스크 고갈, 고아 프로세스 정리를 검증하는 시험은 아닙니다. Windows 실행은 별도 검증이 필요합니다.
33추가: 검증기는 전체 표본을 참조 판독기로 읽어 합성 내용, CRC와 TAR 구조를 확인한 후 실제 작업자의 종료 코드, Terminal, 오류, 게시 상태, Output 개수와 정리를 확인합니다. 성공 파일은 길이와 모든 바이트를 검사하며 거부한 경우 출력 폴더가 비어 있어야 합니다. 입력의 전후 SHA-256도 확인합니다. 작업자 피크 RSS, 디스크 부족과 고아 작업자 정리는 tests/rust-archive-worker/hardening.rs에서 별도로 검사합니다. Windows 실기는 별도 검증이 필요합니다.
수정tests/large-archive-fixtures/generate.py+78-21
@@ -1,4 +1,4 @@
1삭제: """고정 크기 버퍼로 합성 압축파일과 현재 main의 기대값을 생성함."""
1추가: """고정 크기 버퍼로 새 스트리밍 한도의 독립 경계 표본을 생성함."""
22
33import argparse
44import gzip
@@ -6,16 +6,18 @@ import hashlib
66import io
77import json
88from pathlib import Path
9추가: import struct
910import tarfile
1011import zipfile
12추가: import zlib
1113
1214
1315ROOT = Path(__file__).resolve().parents[2]
1416GIB = 1024 ** 3
1517CHUNK = 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
1921NAME = "payload.bin"
2022
2123
@@ -31,9 +33,10 @@ class ZeroStream(io.RawIOBase):
3133 return bytes(count)
3234
3335
34삭제: def write_zip(path, size, compressed):
36추가: def write_zip(path, size, compressed, level=6):
3537 info = zipfile.ZipInfo(NAME, (1980, 1, 1, 0, 0, 0))
3638 info.compress_type = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED
39추가: info._compresslevel = level
3740 info.create_system = 3
3841 info.external_attr = 0o100600 << 16
3942 info.file_size = size
@@ -65,6 +68,23 @@ def write_targz(path, size, compressed):
6568 output.write(bytes((-size) % 512 + 1024))
6669
6770
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추가:
6888def digest(path):
6989 value = hashlib.sha256()
7090 with path.open("rb") as source:
@@ -73,6 +93,17 @@ def digest(path):
7393 return value.hexdigest()
7494
7595
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추가:
76107def build(directory, large=False):
77108 directory = Path(directory).resolve()
78109 directory.relative_to(ROOT / "tests")
@@ -80,26 +111,43 @@ def build(directory, large=False):
80111 cases = []
81112 artifacts = {}
82113
83삭제: def add(name, size, compressed, category, limits):
114추가: def add(name, size, compressed, category, boundaries, level=6, packed_size=None):
84115 path = directory / name
85116 if name.endswith(".zip"):
86삭제: write_zip(path, size, compressed)
117추가: write_zip(path, size, compressed, level)
87118 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"):
89123 write_targz(path, size, compressed)
90124 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,
92134 "archive_bytes": path.stat().st_size,
93135 "payload_bytes": size,
94136 "decoded_bytes": expanded,
137추가: "ratio_input_bytes": ratio_input,
95138 "sha256": digest(path),
96139 }
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)
98145 cases.append({
99146 "id": name + "-" + suffix,
100147 "file": name,
101148 "category": category,
102삭제: "limits": {"input": INPUT_LIMIT, "output": output_limit, "entries": 10000},
149추가: "limits": limits,
150추가: "violated_limits": exceeded,
103151 "expected": {
104152 "outcome": "Failed" if failed else "Completed",
105153 "error": "Limit" if failed else "None",
@@ -112,20 +160,29 @@ def build(directory, large=False):
112160
113161 for name, size in (("boundary.zip", CHUNK), ("boundary.tar.gz", CHUNK - 1536)):
114162 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"]),
118174 ])
119175 if large:
120176 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, []),
126179 ])
180추가: add("output-only.zip", OUTPUT_LIMIT + 1, True, "hard-output-limit", [
181추가: ("default", OUTPUT_LIMIT, ["output"]),
182추가: ], level=1)
127183 manifest = {
128삭제: "baseline_commit": BASELINE,
184추가: "policy": {"revision": 2, "input": INPUT_LIMIT, "output": OUTPUT_LIMIT, "ratio": RATIO_LIMIT},
185추가: "large": large,
129186 "worker_execution_verified": False,
130187 "generator_chunk_bytes": CHUNK,
131188 "artifacts": artifacts,
@@ -140,7 +197,7 @@ def build(directory, large=False):
140197def main():
141198 parser = argparse.ArgumentParser()
142199 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 초과 표본도 생성함")
144201 args = parser.parse_args()
145202 manifest = build(args.output, args.large)
146203 print(f"{len(manifest['cases'])} cases: {args.output / 'expectations.json'}")
수정tests/large-archive-fixtures/verify.py+56-24
@@ -1,4 +1,4 @@
1삭제: """생성 표본을 실제 작업자 프로세스에 전달해 현재 main의 기대값을 검사함."""
1추가: """참조 판독기와 실제 작업자로 독립된 한도 기대값을 검사함."""
22
33import argparse
44import gzip
@@ -11,8 +11,7 @@ import tempfile
1111import tarfile
1212import zipfile
1313
14삭제: from generate import CHUNK, NAME, ROOT, digest
15삭제:
14추가: from generate import CHUNK, NAME, ROOT, build, digest, violations
1615
1716
1817def check_payload(source, size):
@@ -25,46 +24,62 @@ def check_payload(source, size):
2524
2625def check_reference(path, artifact):
2726 size = artifact["payload_bytes"]
28삭제: if path.name.endswith(".zip"):
27추가: if artifact["format"] == "Zip":
2928 with zipfile.ZipFile(path) as archive:
3029 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"]
3233 with archive.open(NAME) as source:
3334 check_payload(source, size)
3435 assert source.read(1) == b""
3536 else:
37추가: assert path.stat().st_size == artifact["ratio_input_bytes"]
3638 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()
4043 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)
4347 assert source.read(1) == b""
4448
4549
46삭제: def verify(directory, probe, worker):
50추가: def verify(directory, probe, worker, large=False):
4751 directory = directory.resolve()
4852 directory.relative_to(ROOT / "tests")
4953 manifest = json.loads((directory / "expectations.json").read_text(encoding="utf-8"))
54추가: assert not large or manifest["large"]
5055 for name, artifact in manifest["artifacts"].items():
5156 assert (directory / name).stat().st_size == artifact["archive_bytes"]
5257 assert digest(directory / name) == artifact["sha256"]
5358 check_reference(directory / name, artifact)
59추가: print(f"REFERENCE {name}", flush=True)
5460 results = []
5561 for case in manifest["cases"]:
5662 path = directory / case["file"]
5763 artifact = manifest["artifacts"][case["file"]]
64추가: assert violations(artifact, case["limits"]) == case["violated_limits"]
5865 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)
6171 command = [
6272 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"],
6576 ]
77추가: environment = os.environ.copy()
78추가: environment["TMPDIR"] = str(staging)
79추가: environment["TMP"] = str(staging)
80추가: environment["TEMP"] = str(staging)
6681 process = subprocess.Popen(
67삭제: command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
82추가: command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environment,
6883 start_new_session=(os.name == "posix"),
6984 )
7085 try:
@@ -77,10 +92,11 @@ def verify(directory, probe, worker):
7792 process.communicate()
7893 raise
7994 assert process.returncode == 0, (case["id"], stdout, stderr)
95추가: assert not list(staging.iterdir())
8096 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""
84100 else:
85101 assert not list(destination.iterdir())
86102 after = path.stat()
@@ -92,10 +108,26 @@ def verify(directory, probe, worker):
92108 return results
93109
94110
95삭제: if __name__ == "__main__":
111추가: def main():
96112 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))
100119 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()
수정tests/rust-archive-worker/hardening.rs+25-0
@@ -124,6 +124,31 @@ fn zip64_directory_and_descriptor_interoperate() {
124124 }
125125}
126126#[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]
127152fn untrusted_zip64_u64_sizes_and_offsets_never_allocate_or_publish() {
128153 for (kind, error) in [
129154 ("central64-size-overflow", ErrorCode::Limit),
수정tests/rust-archive-worker/hardening_cases.py+27-1
@@ -18,7 +18,33 @@ spec.loader.exec_module(fixtures)
1818def generate(directory, kind, size):
1919 directory = Path(directory)
2020 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"):
2248 data = io.BytesIO()
2349 with zipfile.ZipFile(data, "w", compression=zipfile.ZIP_STORED) as archive:
2450 archive.writestr(fixtures.NAME, bytes(size))
수정tests/rust-large-archive-fixtures/probe.rs+11-8
@@ -13,27 +13,30 @@ fn main() {
1313 let args: Vec<_> = std::env::args_os().skip(1).collect();
1414 assert_eq!(
1515 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"
1818 );
1919 let source = PathBuf::from(&args[1]);
2020 let destination = PathBuf::from(&args[2]);
2121 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();
2628 let start = Start {
2729 action: Action::Extract {
2830 archive: NativePath::from_path(&source),
2931 destination: NativePath::from_path(&destination),
3032 selection: Selection::All,
3133 list_id: None,
32삭제: gzip_output_name: None,
34추가: gzip_output_name: (args[8] == "Gzip").then(|| "payload.bin".to_owned()),
3335 },
3436 limits: Limits {
37추가: input: input_limit,
3538 output: output_limit,
36삭제: ..Limits::default()
39추가: entries: entries_limit,
3740 },
3841 };
3942 let mut request = Vec::new();