team-ljyzipelo

공개
136줄7.3 KB
1import argparse
2import hashlib
3import json
4import pathlib
5import re
6import stat
7import sys
8import tomllib
9
10BASE = pathlib.Path(__file__).resolve().parent
11ROOT = BASE.parents[1]
12SOURCE = ROOT / "experiments/rust-file-publication"
13HEAD = "10dc446c90d3527437298cff270b26d2e196a748"
14SOURCE_MANIFEST = "cc4e4cc64a8f3b537df554c7d2895ea3722fbfb0906f1ada767d5cf9b5d8bbc6"
15FILES = {
16 "Cargo.toml", "Cargo.lock", "main.rs", "support.rs", "boundaries.rs",
17 "paths.rs", "namespace.rs", "control.rs", "concurrency.rs", "models.rs",
18 "source-pins.json", "contract.json", "run-plan.json", "static_check.py",
19 "static_check_helper_tests.py",
20}
21MODULES = ("boundaries", "paths", "namespace", "control", "concurrency", "models")
22GUARD = "최적화 모드에서는 정적 검사를 실행할 수 없음"
23
24def require(condition, message):
25 if not condition:
26 raise RuntimeError(message)
27
28def digest(raw):
29 return hashlib.sha256(raw).hexdigest()
30
31def parse_manifest(text, expected_paths):
32 rows = {}
33 for line in text.splitlines():
34 match = re.fullmatch(r"([0-9a-f]{64}) ([A-Za-z0-9_./-]+)", line)
35 require(match is not None, "잘못된 manifest 행")
36 value, name = match.groups()
37 path = pathlib.PurePosixPath(name)
38 require(not path.is_absolute() and ".." not in path.parts
39 and str(path) == name and name not in rows, "중복 또는 잘못된 경로")
40 rows[name] = value
41 require(set(rows) == set(expected_paths), "manifest 경로 불일치")
42 return rows
43
44def hashes():
45 result = {}
46 for name in sorted(FILES | {"SHA256SUMS"}):
47 path = BASE / name
48 require(not path.is_symlink() and stat.S_ISREG(path.lstat().st_mode), "일반 시험 파일 필요")
49 result[name] = digest(path.read_bytes())
50 return result
51
52def verify_sources():
53 pins = json.loads((BASE / "source-pins.json").read_text())
54 require(pins["head"] == HEAD and len(pins["files"]) == 10, "고정 source 기준 불일치")
55 names = [row["path"] for row in pins["files"]]
56 require(len(set(names)) == 10, "source 경로 중복")
57 result = {}
58 for row in pins["files"]:
59 path = ROOT / row["path"]
60 require(path.resolve().is_relative_to(SOURCE) and not path.is_symlink(), "source 경로 이탈")
61 info = path.lstat()
62 require(stat.S_ISREG(info.st_mode) and not info.st_mode & 0o111, "source mode 불일치")
63 raw = path.read_bytes()
64 require(digest(raw) == row["sha256"], "source SHA256 불일치")
65 blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()
66 require(blob == row["git_blob"] and row["mode"] == "100644", "source blob 불일치")
67 result[row["path"]] = digest(raw)
68 manifest = (SOURCE / "SHA256SUMS").read_bytes()
69 require(digest(manifest) == SOURCE_MANIFEST, "source manifest 불일치")
70 relative = {str((ROOT / name).relative_to(SOURCE)) for name in names} - {"SHA256SUMS"}
71 entries = parse_manifest(manifest.decode(), relative)
72 for name, value in entries.items():
73 require(digest((SOURCE / name).read_bytes()) == value, "source manifest 파일 불일치")
74 return result
75
76def main():
77 if sys.flags.optimize:
78 raise RuntimeError(GUARD)
79 parser = argparse.ArgumentParser()
80 parser.add_argument("--manifest-sha256", required=True)
81 parser.add_argument("--metadata", type=pathlib.Path)
82 args = parser.parse_args()
83 before = hashes()
84 require(before["SHA256SUMS"] == args.manifest_sha256, "시험 manifest 불일치")
85 rows = parse_manifest((BASE / "SHA256SUMS").read_text(), FILES)
86 require(all(before[name] == value for name, value in rows.items()), "시험 파일 변경")
87 sources = verify_sources()
88 contract = json.loads((BASE / "contract.json").read_text())
89 require(contract["source_head"] == HEAD and contract["source_manifest_sha256"] == SOURCE_MANIFEST, "계약 head 불일치")
90 names = []
91 for module in MODULES:
92 source = (BASE / (module + ".rs")).read_text()
93 found = re.findall(r"#\[test\]\s*fn ([a-z0-9_]+)\(", source)
94 require(len(found) == source.count("#[test]"), "시험 선언 분석 실패")
95 names.extend(module + "::" + name for name in found)
96 require(len(names) == len(set(names)) == contract["declared_test_count"] == 54, "선언 수 불일치")
97 require(sorted(names) == contract["test_names"] == sorted(contract["evidence_classes"]), "이름 집합 불일치")
98 for path in BASE.glob("*.rs"):
99 source = path.read_text()
100 require("#[ignore" not in source and "#[should_panic" not in source, "시험 제외 금지")
101 require(not re.search(r"include!|#\[path|Command::|execveat|\bmknod\b|\bchmod\b|\bchown\b", source), "범위 밖 Rust 경계")
102 require("\u00b7" not in source, "가운뎃점 금지")
103 require("impl Drop for Sandbox" not in (BASE / "support.rs").read_text(), "실패 증거 자동 정리 금지")
104 plan = json.loads((BASE / "run-plan.json").read_text())
105 require(plan["bounds"]["per_case_seconds"] == 30 and plan["bounds"]["channel_wait_seconds"] == 5, "시간 상한 변경")
106 manifest = tomllib.loads((BASE / "Cargo.toml").read_text())
107 require(manifest["package"]["autotests"] is False, "자동 시험 발견 금지")
108 require(manifest["test"] == [{"name": "publication_public_api", "path": "main.rs"}], "target 불일치")
109 require(manifest["dependencies"] == {
110 "publication": {"package": "zipelo-file-publication", "path": "../../experiments/rust-file-publication"},
111 "libc": {"version": "=0.2.191", "default-features": False, "features": ["std"]},
112 }, "직접 의존성 변경")
113 normal = lambda rows: sorted(rows, key=lambda row: (row["name"], row["version"]))
114 original = tomllib.loads((SOURCE / "Cargo.lock").read_text())["package"]
115 locked = tomllib.loads((BASE / "Cargo.lock").read_text())["package"]
116 package = {"name": "zipelo-file-publication-regressions", "version": "0.1.0", "dependencies": ["libc", "zipelo-file-publication"]}
117 require(normal(locked) == normal(original + [package]), "기존 lock graph 변경")
118 if args.metadata:
119 require(args.metadata.resolve().is_relative_to(BASE), "metadata 위치 이탈")
120 metadata = json.loads(args.metadata.read_text())
121 packages = {p["id"]: p for p in metadata["packages"]}
122 root_package = packages[metadata["resolve"]["root"]]
123 require(root_package["name"] == package["name"], "metadata root 불일치")
124 require(len(root_package["targets"]) == 1 and root_package["targets"][0]["kind"] == ["test"], "target 추가")
125 registry = {(p["name"], p["version"], p["checksum"]) for p in locked if "source" in p}
126 expected = {(p["name"], p["version"], p["checksum"]) for p in json.loads((SOURCE / "dependencies.json").read_text())["direct"]}
127 require(registry == expected, "registry graph 변경")
128 for node in metadata["resolve"]["nodes"]:
129 if packages[node["id"]]["name"] == "libc":
130 require(sorted(node["features"]) == ["std"], "libc feature 변경")
131 require(verify_sources() == sources and hashes() == before, "검사 중 입력 변경")
132 print(json.dumps({"head": HEAD, "source_files": 10, "declared": len(names),
133 "rust_compiled": False, "rust_executed": 0, "inputs_unchanged": True}))
134
135if __name__ == "__main__":
136 main()