| 1 | """원문 무결성과 고지 누락 시 패키지 생성 차단을 검증함.""" |
| 2 | |
| 3 | import hashlib |
| 4 | import importlib.util |
| 5 | import io |
| 6 | import json |
| 7 | from pathlib import Path |
| 8 | import subprocess |
| 9 | import tarfile |
| 10 | import tempfile |
| 11 | import unittest |
| 12 | from types import SimpleNamespace |
| 13 | from unittest.mock import patch |
| 14 | |
| 15 | ROOT = Path(__file__).resolve().parents[2] |
| 16 | |
| 17 | |
| 18 | def 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 | |
| 25 | LICENSES = load("license_tests", "packaging/licenses.py") |
| 26 | WINDOWS = load("windows_license_tests", "packaging/windows/rust/build.py") |
| 27 | UBUNTU = load("ubuntu_license_tests", "packaging/ubuntu/rust/build.py") |
| 28 | |
| 29 | |
| 30 | class 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 checkout_fixture(self, name, license_text): |
| 92 | checkout = self.root / name |
| 93 | crate = checkout / "experiments" / "shared" |
| 94 | crate.mkdir(parents=True) |
| 95 | subprocess.run(["git", "init", "-q", str(checkout)], check=True) |
| 96 | (checkout / "LICENSE").write_text(license_text) |
| 97 | (crate / "Cargo.toml").write_text( |
| 98 | '[workspace]\n[package]\nname = "shared"\nversion = "1.0.0"\nlicense = "MIT"\n' |
| 99 | ) |
| 100 | (crate / "src").mkdir() |
| 101 | (crate / "src/lib.rs").write_text("") |
| 102 | (crate / "Cargo.lock").write_text( |
| 103 | 'version = 4\n[[package]]\nname = "shared"\nversion = "1.0.0"\n' |
| 104 | ) |
| 105 | return crate / "Cargo.toml" |
| 106 | |
| 107 | def test_separate_checkouts_preserve_each_repository_license(self): |
| 108 | app = self.checkout_fixture("app-checkout", "App copyright\n") |
| 109 | worker = self.checkout_fixture("worker-checkout", "Worker copyright\n") |
| 110 | records = LICENSES.inventory([app, worker]) |
| 111 | self.assertEqual(len(records), 1) |
| 112 | self.assertEqual( |
| 113 | {file["text"] for file in records[0]["files"]}, |
| 114 | {"App copyright\n", "Worker copyright\n"}, |
| 115 | ) |
| 116 | args = SimpleNamespace(output=self.root / "windows", target_dir=self.root / "target", |
| 117 | profile="release", app_manifest=app, worker_manifest=worker) |
| 118 | with patch.object(WINDOWS, "build_binary", side_effect=RuntimeError("compile reached")) as build: |
| 119 | with self.assertRaisesRegex(RuntimeError, "compile reached"): |
| 120 | WINDOWS.build(args) |
| 121 | self.assertEqual(build.call_args.args[0], app) |
| 122 | notice = (args.output / "payload/THIRD-PARTY-LICENSES.txt").read_text() |
| 123 | self.assertIn("App copyright", notice) |
| 124 | self.assertIn("Worker copyright", notice) |
| 125 | |
| 126 | def test_second_checkout_license_is_validated_before_deduplication(self): |
| 127 | app = self.checkout_fixture("app-checkout", "App copyright\n") |
| 128 | worker = self.checkout_fixture("worker-checkout", "Worker copyright\n") |
| 129 | worker.write_text(worker.read_text().replace('license = "MIT"', 'license = "Apache-2.0"')) |
| 130 | with self.assertRaisesRegex(ValueError, "프로젝트 라이선스 범위"): |
| 131 | LICENSES.inventory([app, worker]) |
| 132 | |
| 133 | def test_external_path_dependency_is_not_covered_by_input_license(self): |
| 134 | app = self.checkout_fixture("app-checkout", "App copyright\n") |
| 135 | foreign = self.checkout_fixture("foreign-checkout", "Foreign copyright\n") |
| 136 | package = LICENSES.metadata(app)[0] |
| 137 | package["manifest_path"] = str(foreign) |
| 138 | with patch.object(LICENSES, "metadata", return_value=[package]): |
| 139 | with self.assertRaisesRegex(ValueError, "프로젝트 라이선스 범위"): |
| 140 | LICENSES.inventory([app]) |
| 141 | |
| 142 | def test_each_input_lock_is_checked_before_merging(self): |
| 143 | app = self.checkout_fixture("app-checkout", "App copyright\n") |
| 144 | worker = self.checkout_fixture("worker-checkout", "Worker copyright\n") |
| 145 | package = LICENSES.metadata(app)[0] |
| 146 | with patch.object(LICENSES, "metadata", side_effect=[[package], []]): |
| 147 | with self.assertRaisesRegex(ValueError, "Cargo.lock/metadata 불일치"): |
| 148 | LICENSES.inventory([app, worker]) |
| 149 | |
| 150 | def test_modified_registry_license_is_rejected(self): |
| 151 | locked = self.fixture({"LICENSE": b"Fixture license"}) |
| 152 | (self.registry / "LICENSE").write_bytes(b"Modified license") |
| 153 | with self.assertRaisesRegex(ValueError, "원문 변경"): |
| 154 | LICENSES.registry_files(self.package, locked) |
| 155 | |
| 156 | def test_wrong_archive_checksum_is_rejected(self): |
| 157 | self.fixture({"LICENSE": b"Fixture license"}) |
| 158 | with self.assertRaisesRegex(ValueError, "체크섬 불일치"): |
| 159 | LICENSES.registry_files(self.package, {"checksum": "0" * 64}) |
| 160 | |
| 161 | def test_license_file_cannot_escape_package(self): |
| 162 | locked = self.fixture({"LICENSE": b"Fixture license"}) |
| 163 | self.package["license_file"] = str(self.root / "LICENSE") |
| 164 | with self.assertRaises(ValueError): |
| 165 | LICENSES.registry_files(self.package, locked) |
| 166 | |
| 167 | def test_metadata_command_is_locked_and_offline(self): |
| 168 | with patch.object(LICENSES.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, '{"packages": []}')) as run: |
| 169 | self.assertEqual(LICENSES.metadata(self.manifest), []) |
| 170 | command = run.call_args.args[0] |
| 171 | self.assertIn("--locked", command) |
| 172 | self.assertIn("--offline", command) |
| 173 | self.assertIn("--all-features", command) |
| 174 | |
| 175 | def supplement_fixture(self, license="MIT", revision="a" * 40): |
| 176 | self.fixture({".cargo_vcs_info.json": json.dumps({"git": {"sha1": "a" * 40}}).encode(), |
| 177 | "Cargo.toml": b'[package]\nname = "sample"\nversion = "1.0.0"\nauthors = ["Fixture author"]\n'}) |
| 178 | url = "https://raw.githubusercontent.com/example/sample/" + revision + "/LICENSE" |
| 179 | original = "Fixture permission text\\r\\n" |
| 180 | data = {"packages": [{"name": "sample", "version": "1.0.0", "license": license, |
| 181 | "rev": revision, "upstream_ref": revision, "files": [url]}], |
| 182 | "files": {url: {"url": url, "text": original, |
| 183 | "sha256": hashlib.sha256(original.encode()).hexdigest()}}} |
| 184 | path = self.root / "supplements.json" |
| 185 | path.write_text(json.dumps(data)) |
| 186 | return path, data, url |
| 187 | |
| 188 | def test_supplement_preserves_fixed_source_and_original(self): |
| 189 | path, data, url = self.supplement_fixture() |
| 190 | records = LICENSES.supplemental_files(self.package, path) |
| 191 | self.assertEqual(records[0]["path"], url) |
| 192 | self.assertEqual(records[0]["text"], data["files"][url]["text"]) |
| 193 | |
| 194 | def test_supplement_spdx_must_match_metadata(self): |
| 195 | path, _, _ = self.supplement_fixture(license="Apache-2.0") |
| 196 | with self.assertRaisesRegex(ValueError, "SPDX 불일치"): |
| 197 | LICENSES.supplemental_files(self.package, path) |
| 198 | |
| 199 | def test_supplement_revision_must_match_published_crate(self): |
| 200 | path, _, _ = self.supplement_fixture(revision="b" * 40) |
| 201 | with self.assertRaisesRegex(ValueError, "커밋 불일치"): |
| 202 | LICENSES.supplemental_files(self.package, path) |
| 203 | |
| 204 | def test_supplement_content_hash_is_verified(self): |
| 205 | path, data, url = self.supplement_fixture() |
| 206 | data["files"][url]["text"] += "changed" |
| 207 | path.write_text(json.dumps(data)) |
| 208 | with self.assertRaisesRegex(ValueError, "해시 불일치"): |
| 209 | LICENSES.supplemental_files(self.package, path) |
| 210 | |
| 211 | def test_supplement_requires_fixed_upstream_url(self): |
| 212 | path, data, _ = self.supplement_fixture() |
| 213 | data["packages"][0]["upstream_ref"] = "main" |
| 214 | path.write_text(json.dumps(data)) |
| 215 | with self.assertRaisesRegex(ValueError, "출처 고정 오류"): |
| 216 | LICENSES.supplemental_files(self.package, path) |
| 217 | |
| 218 | def test_real_supplement_spdx_matches_offline_metadata(self): |
| 219 | manifests = [ROOT / "experiments" / crate / "Cargo.toml" |
| 220 | for crate in ["rust-ui-memory-app", "rust-archive-worker"]] |
| 221 | records = LICENSES.inventory(manifests) |
| 222 | declared = {LICENSES.identity(p): p["license"] |
| 223 | for manifest in manifests for p in LICENSES.metadata(manifest)} |
| 224 | self.assertEqual({(r["name"], r["version"], r["source"]): r["license"] |
| 225 | for r in records}, declared) |
| 226 | supplement = json.loads((ROOT / "packaging/license-supplements.json").read_text()) |
| 227 | for row in supplement["packages"]: |
| 228 | matches = [r for r in records if (r["name"], r["version"]) == (row["name"], row["version"])] |
| 229 | self.assertEqual(len(matches), 1) |
| 230 | self.assertEqual(matches[0]["license"], row["license"]) |
| 231 | self.assertTrue(matches[0]["files"]) |
| 232 | |
| 233 | def standard_fixture(self): |
| 234 | path, data, _ = self.supplement_fixture() |
| 235 | source = "crate:sample-1.0.0/Cargo.toml" |
| 236 | content = (self.registry / "Cargo.toml").read_text() |
| 237 | url = "https://raw.githubusercontent.com/spdx/license-list-data/v3.26.0/text/MIT.txt" |
| 238 | data["standards"] = {"MIT": url} |
| 239 | for location, text in [(source, content), (url, "Fixture standard MIT text")]: |
| 240 | data["files"][location] = {"url": location, "text": text, |
| 241 | "sha256": hashlib.sha256(text.encode()).hexdigest()} |
| 242 | data["packages"][0].update(standard_license="MIT", attribution_source=source, |
| 243 | authors=["Fixture author"]) |
| 244 | path.write_text(json.dumps(data)) |
| 245 | return path, data |
| 246 | |
| 247 | def test_standard_supplement_records_authors_source_and_reason(self): |
| 248 | path, _ = self.standard_fixture() |
| 249 | files = LICENSES.supplemental_files(self.package, path) |
| 250 | self.assertIn("upstream에 원문이 없어 표준 원문으로 보충함", files[0]["note"]) |
| 251 | self.assertIn("Fixture author", files[0]["note"]) |
| 252 | self.assertIn("crate:sample-1.0.0/Cargo.toml", files[0]["note"]) |
| 253 | |
| 254 | def test_standard_supplement_rejects_wrong_license_choice(self): |
| 255 | path, data = self.standard_fixture() |
| 256 | data["packages"][0]["standard_license"] = "Apache-2.0" |
| 257 | path.write_text(json.dumps(data)) |
| 258 | with self.assertRaisesRegex(ValueError, "SPDX 선택 불일치"): |
| 259 | LICENSES.supplemental_files(self.package, path) |
| 260 | |
| 261 | def test_standard_supplement_rejects_changed_attribution(self): |
| 262 | path, data = self.standard_fixture() |
| 263 | data["packages"][0]["authors"] = ["Invented author"] |
| 264 | path.write_text(json.dumps(data)) |
| 265 | with self.assertRaisesRegex(ValueError, "저자 고지 불일치"): |
| 266 | LICENSES.supplemental_files(self.package, path) |
| 267 | |
| 268 | def test_complete_notice_has_zero_omissions_against_metadata(self): |
| 269 | manifests = [ROOT / "experiments" / crate / "Cargo.toml" |
| 270 | for crate in ["rust-ui-memory-app", "rust-archive-worker"]] |
| 271 | records = LICENSES.inventory(manifests) |
| 272 | expected = {LICENSES.identity(p) for manifest in manifests for p in LICENSES.metadata(manifest)} |
| 273 | self.assertEqual({(r["name"], r["version"], r["source"]) for r in records}, expected) |
| 274 | text = LICENSES.render(records) |
| 275 | self.assertEqual(text.count("\nCrate: "), len(expected)) |
| 276 | self.assertTrue(all(r["files"] for r in records)) |
| 277 | self.assertEqual(text.count("upstream에 원문이 없어 표준 원문으로 보충함"), 12) |
| 278 | |
| 279 | def test_both_packagers_stop_before_build_on_missing_licenses(self): |
| 280 | for builder, binaries in [(WINDOWS, WINDOWS), (UBUNTU, UBUNTU.WINDOWS)]: |
| 281 | with self.subTest(builder=builder.__name__): |
| 282 | output = self.root / builder.__name__ |
| 283 | args = SimpleNamespace(output=output, target_dir=self.root / "target", profile="release", |
| 284 | app_manifest=self.manifest, worker_manifest=self.manifest) |
| 285 | with patch.object(binaries.LICENSES, "generate", side_effect=ValueError("원문 누락")): |
| 286 | with patch.object(binaries, "build_binary") as build_binary: |
| 287 | with self.assertRaisesRegex(ValueError, "원문 누락"): |
| 288 | builder.build(args) |
| 289 | build_binary.assert_not_called() |
| 290 | |
| 291 | |
| 292 | if __name__ == "__main__": |
| 293 | unittest.main() |