team-ljyzipelo

공개
187줄9.2 KB
1"""원문 무결성과 고지 누락 시 패키지 생성 차단을 검증함."""
2
3import hashlib
4import importlib.util
5import io
6import json
7from pathlib import Path
8import subprocess
9import tarfile
10import tempfile
11import unittest
12from types import SimpleNamespace
13from unittest.mock import patch
14
15ROOT = Path(__file__).resolve().parents[2]
16
17
18def load(name, path):
19 spec = importlib.util.spec_from_file_location(name, ROOT / path)
20 module = importlib.util.module_from_spec(spec)
21 spec.loader.exec_module(module)
22 return module
23
24
25LICENSES = load("license_tests", "packaging/licenses.py")
26WINDOWS = load("windows_license_tests", "packaging/windows/rust/build.py")
27UBUNTU = load("ubuntu_license_tests", "packaging/ubuntu/rust/build.py")
28
29
30class LicenseTests(unittest.TestCase):
31 def setUp(self):
32 runs = ROOT / "tests/release-packages/runs"
33 runs.mkdir(parents=True, exist_ok=True)
34 temporary = tempfile.TemporaryDirectory(dir=runs)
35 self.addCleanup(temporary.cleanup)
36 self.root = Path(temporary.name)
37 self.manifest = self.root / "Cargo.toml"
38 self.manifest.write_text("")
39 (self.root / "LICENSE").write_text("Project fixture license\n")
40 self.registry = self.root / "registry/src/index/sample-1.0.0"
41 self.registry.mkdir(parents=True)
42 self.package = {
43 "name": "sample", "version": "1.0.0", "source": "registry+https://example.invalid/index",
44 "license": "MIT", "license_file": None, "manifest_path": str(self.registry / "Cargo.toml"),
45 }
46 self.archive = self.root / "registry/cache/index/sample-1.0.0.crate"
47 self.archive.parent.mkdir(parents=True)
48
49 def fixture(self, files):
50 with tarfile.open(self.archive, "w:gz") as archive:
51 for relative, content in files.items():
52 destination = self.registry / relative
53 destination.parent.mkdir(parents=True, exist_ok=True)
54 destination.write_bytes(content)
55 member = tarfile.TarInfo("sample-1.0.0/" + relative)
56 member.size = len(content)
57 archive.addfile(member, io.BytesIO(content))
58 checksum = hashlib.sha256(self.archive.read_bytes()).hexdigest()
59 self.manifest.with_name("Cargo.lock").write_text(
60 'version = 4\n[[package]]\nname = "sample"\nversion = "1.0.0"\n'
61 'source = "registry+https://example.invalid/index"\n' + f'checksum = "{checksum}"\n'
62 )
63 return {"checksum": checksum}
64
65 def test_inventory_matches_metadata_and_preserves_all_texts(self):
66 originals = {"LICENSE-MIT": b"Fixture MIT text\r\n", "data/NOTICE": b"Fixture attribution\n"}
67 self.fixture(originals)
68 with patch.object(LICENSES, "metadata", return_value=[self.package]):
69 records = LICENSES.inventory([self.manifest], self.root)
70 text = LICENSES.render(records)
71 self.assertEqual([(r["name"], r["version"]) for r in records], [("sample", "1.0.0")])
72 self.assertEqual(text.count("Crate: sample 1.0.0\n"), 1)
73 for content in originals.values():
74 self.assertIn(content.decode(), text)
75 self.assertIn(hashlib.sha256(content).hexdigest(), text)
76
77 def test_missing_license_prevents_output(self):
78 self.fixture({"README.md": b"No license text in fixture"})
79 output = self.root / "THIRD-PARTY-LICENSES.txt"
80 with patch.object(LICENSES, "metadata", return_value=[self.package]):
81 with self.assertRaisesRegex(ValueError, "원문 누락 1개"):
82 LICENSES.generate([self.manifest], output)
83 self.assertFalse(output.exists())
84
85 def test_metadata_omission_is_not_silently_ignored(self):
86 self.fixture({"LICENSE": b"Fixture license"})
87 with patch.object(LICENSES, "metadata", return_value=[]):
88 with self.assertRaisesRegex(ValueError, "Cargo.lock/metadata 불일치"):
89 LICENSES.inventory([self.manifest], self.root)
90
91 def test_modified_registry_license_is_rejected(self):
92 locked = self.fixture({"LICENSE": b"Fixture license"})
93 (self.registry / "LICENSE").write_bytes(b"Modified license")
94 with self.assertRaisesRegex(ValueError, "원문 변경"):
95 LICENSES.registry_files(self.package, locked)
96
97 def test_wrong_archive_checksum_is_rejected(self):
98 self.fixture({"LICENSE": b"Fixture license"})
99 with self.assertRaisesRegex(ValueError, "체크섬 불일치"):
100 LICENSES.registry_files(self.package, {"checksum": "0" * 64})
101
102 def test_license_file_cannot_escape_package(self):
103 locked = self.fixture({"LICENSE": b"Fixture license"})
104 self.package["license_file"] = str(self.root / "LICENSE")
105 with self.assertRaises(ValueError):
106 LICENSES.registry_files(self.package, locked)
107
108 def test_metadata_command_is_locked_and_offline(self):
109 with patch.object(LICENSES.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, '{"packages": []}')) as run:
110 self.assertEqual(LICENSES.metadata(self.manifest), [])
111 command = run.call_args.args[0]
112 self.assertIn("--locked", command)
113 self.assertIn("--offline", command)
114 self.assertIn("--all-features", command)
115
116 def supplement_fixture(self, license="MIT", revision="a" * 40):
117 self.fixture({".cargo_vcs_info.json": json.dumps({"git": {"sha1": "a" * 40}}).encode()})
118 url = "https://raw.githubusercontent.com/example/sample/" + revision + "/LICENSE"
119 original = "Fixture permission text\\r\\n"
120 data = {"packages": [{"name": "sample", "version": "1.0.0", "license": license,
121 "rev": revision, "upstream_ref": revision, "files": [url]}],
122 "files": {url: {"url": url, "text": original,
123 "sha256": hashlib.sha256(original.encode()).hexdigest()}}}
124 path = self.root / "supplements.json"
125 path.write_text(json.dumps(data))
126 return path, data, url
127
128 def test_supplement_preserves_fixed_source_and_original(self):
129 path, data, url = self.supplement_fixture()
130 records = LICENSES.supplemental_files(self.package, path)
131 self.assertEqual(records[0]["path"], url)
132 self.assertEqual(records[0]["text"], data["files"][url]["text"])
133
134 def test_supplement_spdx_must_match_metadata(self):
135 path, _, _ = self.supplement_fixture(license="Apache-2.0")
136 with self.assertRaisesRegex(ValueError, "SPDX 불일치"):
137 LICENSES.supplemental_files(self.package, path)
138
139 def test_supplement_revision_must_match_published_crate(self):
140 path, _, _ = self.supplement_fixture(revision="b" * 40)
141 with self.assertRaisesRegex(ValueError, "커밋 불일치"):
142 LICENSES.supplemental_files(self.package, path)
143
144 def test_supplement_content_hash_is_verified(self):
145 path, data, url = self.supplement_fixture()
146 data["files"][url]["text"] += "changed"
147 path.write_text(json.dumps(data))
148 with self.assertRaisesRegex(ValueError, "해시 불일치"):
149 LICENSES.supplemental_files(self.package, path)
150
151 def test_supplement_requires_fixed_upstream_url(self):
152 path, data, _ = self.supplement_fixture()
153 data["packages"][0]["upstream_ref"] = "main"
154 path.write_text(json.dumps(data))
155 with self.assertRaisesRegex(ValueError, "출처 고정 오류"):
156 LICENSES.supplemental_files(self.package, path)
157
158 def test_real_supplement_spdx_matches_offline_metadata(self):
159 manifests = [ROOT / "experiments" / crate / "Cargo.toml"
160 for crate in ["rust-ui-memory-app", "rust-archive-worker"]]
161 records = LICENSES.inventory(manifests)
162 declared = {LICENSES.identity(p): p["license"]
163 for manifest in manifests for p in LICENSES.metadata(manifest)}
164 self.assertEqual({(r["name"], r["version"], r["source"]): r["license"]
165 for r in records}, declared)
166 supplement = json.loads((ROOT / "packaging/license-supplements.json").read_text())
167 for row in supplement["packages"]:
168 matches = [r for r in records if (r["name"], r["version"]) == (row["name"], row["version"])]
169 self.assertEqual(len(matches), 1)
170 self.assertEqual(matches[0]["license"], row["license"])
171 self.assertTrue(matches[0]["files"])
172
173 def test_both_packagers_stop_before_build_on_missing_licenses(self):
174 for builder, binaries in [(WINDOWS, WINDOWS), (UBUNTU, UBUNTU.WINDOWS)]:
175 with self.subTest(builder=builder.__name__):
176 output = self.root / builder.__name__
177 args = SimpleNamespace(output=output, target_dir=self.root / "target", profile="release",
178 app_manifest=self.manifest, worker_manifest=self.manifest)
179 with patch.object(binaries.LICENSES, "generate", side_effect=ValueError("원문 누락")):
180 with patch.object(binaries, "build_binary") as build_binary:
181 with self.assertRaisesRegex(ValueError, "원문 누락"):
182 builder.build(args)
183 build_binary.assert_not_called()
184
185
186if __name__ == "__main__":
187 unittest.main()