| 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 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 | "Cargo.toml": b'[package]\nname = "sample"\nversion = "1.0.0"\nauthors = ["Fixture author"]\n'}) |
| 119 | url = "https://raw.githubusercontent.com/example/sample/" + revision + "/LICENSE" |
| 120 | original = "Fixture permission text\\r\\n" |
| 121 | data = {"packages": [{"name": "sample", "version": "1.0.0", "license": license, |
| 122 | "rev": revision, "upstream_ref": revision, "files": [url]}], |
| 123 | "files": {url: {"url": url, "text": original, |
| 124 | "sha256": hashlib.sha256(original.encode()).hexdigest()}}} |
| 125 | path = self.root / "supplements.json" |
| 126 | path.write_text(json.dumps(data)) |
| 127 | return path, data, url |
| 128 | |
| 129 | def test_supplement_preserves_fixed_source_and_original(self): |
| 130 | path, data, url = self.supplement_fixture() |
| 131 | records = LICENSES.supplemental_files(self.package, path) |
| 132 | self.assertEqual(records[0]["path"], url) |
| 133 | self.assertEqual(records[0]["text"], data["files"][url]["text"]) |
| 134 | |
| 135 | def test_supplement_spdx_must_match_metadata(self): |
| 136 | path, _, _ = self.supplement_fixture(license="Apache-2.0") |
| 137 | with self.assertRaisesRegex(ValueError, "SPDX 불일치"): |
| 138 | LICENSES.supplemental_files(self.package, path) |
| 139 | |
| 140 | def test_supplement_revision_must_match_published_crate(self): |
| 141 | path, _, _ = self.supplement_fixture(revision="b" * 40) |
| 142 | with self.assertRaisesRegex(ValueError, "커밋 불일치"): |
| 143 | LICENSES.supplemental_files(self.package, path) |
| 144 | |
| 145 | def test_supplement_content_hash_is_verified(self): |
| 146 | path, data, url = self.supplement_fixture() |
| 147 | data["files"][url]["text"] += "changed" |
| 148 | path.write_text(json.dumps(data)) |
| 149 | with self.assertRaisesRegex(ValueError, "해시 불일치"): |
| 150 | LICENSES.supplemental_files(self.package, path) |
| 151 | |
| 152 | def test_supplement_requires_fixed_upstream_url(self): |
| 153 | path, data, _ = self.supplement_fixture() |
| 154 | data["packages"][0]["upstream_ref"] = "main" |
| 155 | path.write_text(json.dumps(data)) |
| 156 | with self.assertRaisesRegex(ValueError, "출처 고정 오류"): |
| 157 | LICENSES.supplemental_files(self.package, path) |
| 158 | |
| 159 | def test_real_supplement_spdx_matches_offline_metadata(self): |
| 160 | manifests = [ROOT / "experiments" / crate / "Cargo.toml" |
| 161 | for crate in ["rust-ui-memory-app", "rust-archive-worker"]] |
| 162 | records = LICENSES.inventory(manifests) |
| 163 | declared = {LICENSES.identity(p): p["license"] |
| 164 | for manifest in manifests for p in LICENSES.metadata(manifest)} |
| 165 | self.assertEqual({(r["name"], r["version"], r["source"]): r["license"] |
| 166 | for r in records}, declared) |
| 167 | supplement = json.loads((ROOT / "packaging/license-supplements.json").read_text()) |
| 168 | for row in supplement["packages"]: |
| 169 | matches = [r for r in records if (r["name"], r["version"]) == (row["name"], row["version"])] |
| 170 | self.assertEqual(len(matches), 1) |
| 171 | self.assertEqual(matches[0]["license"], row["license"]) |
| 172 | self.assertTrue(matches[0]["files"]) |
| 173 | |
| 174 | def standard_fixture(self): |
| 175 | path, data, _ = self.supplement_fixture() |
| 176 | source = "crate:sample-1.0.0/Cargo.toml" |
| 177 | content = (self.registry / "Cargo.toml").read_text() |
| 178 | url = "https://raw.githubusercontent.com/spdx/license-list-data/v3.26.0/text/MIT.txt" |
| 179 | data["standards"] = {"MIT": url} |
| 180 | for location, text in [(source, content), (url, "Fixture standard MIT text")]: |
| 181 | data["files"][location] = {"url": location, "text": text, |
| 182 | "sha256": hashlib.sha256(text.encode()).hexdigest()} |
| 183 | data["packages"][0].update(standard_license="MIT", attribution_source=source, |
| 184 | authors=["Fixture author"]) |
| 185 | path.write_text(json.dumps(data)) |
| 186 | return path, data |
| 187 | |
| 188 | def test_standard_supplement_records_authors_source_and_reason(self): |
| 189 | path, _ = self.standard_fixture() |
| 190 | files = LICENSES.supplemental_files(self.package, path) |
| 191 | self.assertIn("upstream에 원문이 없어 표준 원문으로 보충함", files[0]["note"]) |
| 192 | self.assertIn("Fixture author", files[0]["note"]) |
| 193 | self.assertIn("crate:sample-1.0.0/Cargo.toml", files[0]["note"]) |
| 194 | |
| 195 | def test_standard_supplement_rejects_wrong_license_choice(self): |
| 196 | path, data = self.standard_fixture() |
| 197 | data["packages"][0]["standard_license"] = "Apache-2.0" |
| 198 | path.write_text(json.dumps(data)) |
| 199 | with self.assertRaisesRegex(ValueError, "SPDX 선택 불일치"): |
| 200 | LICENSES.supplemental_files(self.package, path) |
| 201 | |
| 202 | def test_standard_supplement_rejects_changed_attribution(self): |
| 203 | path, data = self.standard_fixture() |
| 204 | data["packages"][0]["authors"] = ["Invented author"] |
| 205 | path.write_text(json.dumps(data)) |
| 206 | with self.assertRaisesRegex(ValueError, "저자 고지 불일치"): |
| 207 | LICENSES.supplemental_files(self.package, path) |
| 208 | |
| 209 | def test_complete_notice_has_zero_omissions_against_metadata(self): |
| 210 | manifests = [ROOT / "experiments" / crate / "Cargo.toml" |
| 211 | for crate in ["rust-ui-memory-app", "rust-archive-worker"]] |
| 212 | records = LICENSES.inventory(manifests) |
| 213 | expected = {LICENSES.identity(p) for manifest in manifests for p in LICENSES.metadata(manifest)} |
| 214 | self.assertEqual({(r["name"], r["version"], r["source"]) for r in records}, expected) |
| 215 | text = LICENSES.render(records) |
| 216 | self.assertEqual(text.count("\nCrate: "), len(expected)) |
| 217 | self.assertTrue(all(r["files"] for r in records)) |
| 218 | self.assertEqual(text.count("upstream에 원문이 없어 표준 원문으로 보충함"), 12) |
| 219 | |
| 220 | def test_both_packagers_stop_before_build_on_missing_licenses(self): |
| 221 | for builder, binaries in [(WINDOWS, WINDOWS), (UBUNTU, UBUNTU.WINDOWS)]: |
| 222 | with self.subTest(builder=builder.__name__): |
| 223 | output = self.root / builder.__name__ |
| 224 | args = SimpleNamespace(output=output, target_dir=self.root / "target", profile="release", |
| 225 | app_manifest=self.manifest, worker_manifest=self.manifest) |
| 226 | with patch.object(binaries.LICENSES, "generate", side_effect=ValueError("원문 누락")): |
| 227 | with patch.object(binaries, "build_binary") as build_binary: |
| 228 | with self.assertRaisesRegex(ValueError, "원문 누락"): |
| 229 | builder.build(args) |
| 230 | build_binary.assert_not_called() |
| 231 | |
| 232 | |
| 233 | if __name__ == "__main__": |
| 234 | unittest.main() |