From e08ac37a64a69d0dedd2df9d25daf3df3b1b89a2 Mon Sep 17 00:00:00 2001 From: mashagua <993498039@qq.com> Date: Sun, 22 Nov 2026 22:37:56 +0800 Subject: [PATCH] =?UTF-8?q?fix(catalog):=20=E5=8B=BF=E5=B0=86=20licenses/?= =?UTF-8?q?=20=E7=9B=AE=E5=BD=95=E8=AF=AF=E5=88=A4=E4=B8=BA=E6=8D=9F?= =?UTF-8?q?=E5=9D=8F=E7=9A=84=E6=A0=B9=20LICENSE=20(#334)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 独立工具修订,不合并。对应失败草稿 #323 的前置修复:当前 `main` 上的审核器会把根目录名为 `licenses/` 的普通目录误判为损坏的 LICENSE 文件(“根许可或 Notice 不是普通文件”)。该目录在 #323 的旧 pin `79d2fc05405c76bc0a8f71b9c10355135da4747b` 和新 pin `87889b8729da8a02a4159bc7274c92be52464031` 上均存在,因此即使用当前审核器重放已准入旧 pin 也会失败。这不是上游缺失 LICENSE。根 LICENSE 本身是普通不变的 MIT 文件(blob `2d476d24fa5a9ae2ab35e5fd121494049eb2ee5d`)。 本 PR 的最小行为变化: - `root_evidence()` 跳过根上名为 LICENSE*/NOTICE*/COPYING* 的普通目录,不再把它们当成损坏许可文件。 - 这些根名上的符号链接、子模块或其他非普通文件,以及目录内的非普通文件,仍硬拦截。 - 根 LICENSE/NOTICE/COPYING **文件**的内容变化仍检测;这些文件被删除仍不可接受。 - `licenses/` 等许可目录被删除不可接受。 - 目录内第三方许可文本变化(含内容相同的重命名)不得被伪称为未变化;需在专项复核中提供新快照的 `acceptedRootLicenseDirectoryManifestSha256`(目录清单的规范 JSON 的 SHA-256)。该字段不削弱对根 LICENSE 文件删除的保护,也不能用来跳过符号链接/子模块拦截。 - 既有安装范围内 NOTICE 精确追加政策不退化。 已加回归测试:合法 MIT LICENSE + `licenses/` 目录在新旧 pin 上可通过;LICENSE 或目录内符号链接/非普通文件仍拒绝;LICENSE 内容变化仍检测;目录内第三方文本变化在无正确清单哈希时不能通过;目录删除不可接受;存在 `licenses/` 时,既有 NOTICE 精确追加仍可用。catalog/audit/collection 单测 107 passed(含 182 subtests),catalog 与 i18n validate 0 error。 #323 的正式快照 PR 将以本分支为 base 叠放,并清楚标明依赖。在本工具修订合入 `main` 之前,不要把基于 `main` 的快照 PR 声称可以复现已通过的审核。本 PR 本身不含 #323 快照,也不自行合并。 --- schemas/special-review.v1.schema.json | 17 +++- scripts/catalog/audit_skill_update.py | 64 +++++++++++- scripts/catalog/test_audit_skill_update.py | 111 +++++++++++++++++++++ 3 files changed, 187 insertions(+), 5 deletions(-) diff --git a/schemas/special-review.v1.schema.json b/schemas/special-review.v1.schema.json index b47453e..603ad26 100644 --- a/schemas/special-review.v1.schema.json +++ b/schemas/special-review.v1.schema.json @@ -66,8 +66,21 @@ } } } + }, + "acceptedRootLicenseDirectoryManifestSha256": { + "type": "object", + "description": "Map of a repo-root LICENSE*/NOTICE*/COPYING* directory name (for example licenses) to the SHA-256 of the canonical JSON manifest of regular files under that directory at the *new* snapshot (sorted path to file SHA-256). Required when those directory file sets change, including renames. This does not accept changes to, replacements of, or deletions of root LICENSE/NOTICE/COPYING files (deletions remain forbidden; file changes still use acceptedRootEvidenceSha256). Symlinks, submodules, and other non-regular files at those root names or inside the directory remain blocked.", + "additionalProperties": { "type": "string", "pattern": "^[a-f0-9]{64}$" } } }, - "if": { "required": ["acceptedScopedNotice"] }, - "then": { "required": ["reviewedBy", "reviewedAt", "notes"] } + "allOf": [ + { + "if": { "required": ["acceptedScopedNotice"] }, + "then": { "required": ["reviewedBy", "reviewedAt", "notes"] } + }, + { + "if": { "required": ["acceptedRootLicenseDirectoryManifestSha256"] }, + "then": { "required": ["reviewedBy", "reviewedAt", "notes"] } + } + ] } diff --git a/scripts/catalog/audit_skill_update.py b/scripts/catalog/audit_skill_update.py index c32a2fc..2fa8843 100644 --- a/scripts/catalog/audit_skill_update.py +++ b/scripts/catalog/audit_skill_update.py @@ -76,23 +76,59 @@ def blob(repo: Path, ref: str, path: str) -> bytes: return git(repo, 'show', f'{ref}:{path}') +LICENSE_NAME_PREFIXES = ('LICENSE', 'NOTICE', 'COPYING') + + def root_evidence(repo: Path, ref: str) -> dict[str, str]: - # 只读根目录,避免整个上游仓库的无关文件消耗预算。 + # 只读根目录的普通许可文件。名为 licenses/ 的目录不是损坏的 LICENSE 文件。 result = {} for record in git(repo, 'ls-tree', '-z', ref).split(b'\0'): if not record: continue meta, name = record.split(b'\t', 1) path = name.decode() - if not path.upper().startswith(('LICENSE', 'NOTICE', 'COPYING')): + if not path.upper().startswith(LICENSE_NAME_PREFIXES): continue mode, kind, _ = meta.decode().split() + if kind == 'tree' and mode == '040000': + continue if kind != 'blob' or mode not in ('100644', '100755'): raise AuditBlocked('根许可或 Notice 不是普通文件') result[path] = hashlib.sha256(blob(repo, ref, path)).hexdigest() return result +def root_license_directory_files(repo: Path, ref: str) -> dict[str, dict[str, str]]: + """普通文件清单,按根上 LICENSE*/NOTICE*/COPYING* 目录分组。目录内的符号链接或子模块仍硬拦截。""" + grouped: dict[str, dict[str, str]] = {} + for record in git(repo, 'ls-tree', '-z', ref).split(b'\0'): + if not record: + continue + meta, name = record.split(b'\t', 1) + path = name.decode() + if not path.upper().startswith(LICENSE_NAME_PREFIXES): + continue + mode, kind, _ = meta.decode().split() + if kind != 'tree' or mode != '040000': + continue + files: dict[str, str] = {} + for child in git(repo, 'ls-tree', '-rz', ref, '--', path).split(b'\0'): + if not child: + continue + cmeta, cname = child.split(b'\t', 1) + cpath = cname.decode() + cmode, ckind, _ = cmeta.decode().split() + if ckind != 'blob' or cmode not in ('100644', '100755'): + raise AuditBlocked('根许可或 Notice 不是普通文件') + files[cpath] = hashlib.sha256(blob(repo, ref, cpath)).hexdigest() + grouped[path] = files + return grouped + + +def license_directory_manifest_sha256(files: dict[str, str]) -> str: + return hashlib.sha256(json.dumps(files, sort_keys=True, ensure_ascii=False).encode()).hexdigest() + + def stable_frontmatter(fm: dict) -> dict: result = copy.deepcopy(fm) for key in ('version', 'updated_at'): @@ -305,7 +341,27 @@ def audit_snapshots(repo: Path, entry: dict, sidecar: dict, result: dict, or any(not isinstance(key, str) or not isinstance(value, str) for key, value in accepted_root.items()) or accepted_root != expected_root): raise AuditBlocked('根许可证或 Notice 有变化,需专项复核') - licenses = new_root + old_license_dirs = root_license_directory_files(repo, old) + new_license_dirs = root_license_directory_files(repo, new) + if set(old_license_dirs) - set(new_license_dirs): + raise AuditBlocked('根许可目录被删除,需专项复核') + expected_dir_manifests = { + directory: license_directory_manifest_sha256(files) + for directory, files in new_license_dirs.items() + if old_license_dirs.get(directory) != files + } + if expected_dir_manifests: + accepted_dirs = review.get('acceptedRootLicenseDirectoryManifestSha256') or {} + if (not isinstance(accepted_dirs, dict) + or any(not isinstance(key, str) or not isinstance(value, str) for key, value in accepted_dirs.items()) + or accepted_dirs != expected_dir_manifests): + raise AuditBlocked('根许可目录内的第三方许可文本有变化,需专项复核') + if not all(isinstance(review.get(key), str) and review[key].strip() + for key in ('reviewedBy', 'reviewedAt', 'notes')): + raise AuditBlocked('根许可目录专项复核必须包含审核人、日期和理由') + licenses = dict(new_root) + for files in new_license_dirs.values(): + licenses.update(files) # 安装范围内的嵌套许可同样影响再分发,不能只核对根许可证。 def scoped_evidence(ref, files): return {path: hashlib.sha256(blob(repo, ref, path)).hexdigest() @@ -463,6 +519,8 @@ def audit_snapshots(repo: Path, entry: dict, sidecar: dict, result: dict, report['limitations'].append('根许可证/Notice 或合集成员如有变化,已按专项复核记录中的接受哈希或路径集合核对,不代表与旧快照逐字节或成员集合相同。') if review.get('acceptedScopedNotice'): report['limitations'].append('安装范围内的 Notice 如有变化,已按专项复核记录中绑定的快照、路径和哈希核对,且新文件必须完整保留旧 Notice 字节;不代表与旧快照逐字节相同,也不接受嵌套许可证变更。') + if review.get('acceptedRootLicenseDirectoryManifestSha256'): + report['limitations'].append('根 licenses/ 等许可目录内的第三方许可文本如有变化,已按专项复核记录中的目录清单哈希核对,不代表与旧快照逐文件相同;不接受根 LICENSE/NOTICE/COPYING 文件被删除或改成非普通文件。') if exclude_paths: report['limitations'].append('excludePaths 只从本仓库的自动审核树遍历中省略路径;DesireCore 安装器在支持该字段前仍会从上游 pin 安装这些文件。') errors = validate_record(metadata, report) diff --git a/scripts/catalog/test_audit_skill_update.py b/scripts/catalog/test_audit_skill_update.py index e95e82e..1c69a19 100644 --- a/scripts/catalog/test_audit_skill_update.py +++ b/scripts/catalog/test_audit_skill_update.py @@ -548,6 +548,117 @@ class AuditTests(unittest.TestCase): hashlib.sha256(old_text.encode()).hexdigest(), hashlib.sha256(prepended.encode()).hexdigest())) + + def _rebind_old(self, sha): + self.old = sha + self.entry['source']['ref'] = sha + self.metadata['provenance']['content']['ref'] = sha + self.metadata['governance']['compliance']['reviewedRef'] = sha + + def test_root_licenses_directory_is_not_a_broken_license_file(self): + """A normal licenses/ directory plus an unchanged MIT LICENSE must pass (old and new pins).""" + self.write('licenses/thirdparty-MIT.txt', 'Permission is hereby granted, MIT third-party text.\n') + self._rebind_old(self.commit()) + # Unchanged directory already present on the admitted old pin should not block a script change. + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + entry, metadata, report = self.audit() + self.assertEqual(entry['source']['ref'], metadata['governance']['compliance']['reviewedRef']) + self.assertTrue(report['checks']['licenseAndNoticeUnchanged']) + self.assertIn('LICENSE', report['licenseEvidenceSha256']) + self.assertIn('licenses/thirdparty-MIT.txt', report['licenseEvidenceSha256']) + + def test_root_license_symlink_or_nonregular_still_blocked(self): + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + (self.repo / 'LICENSE').unlink() + (self.repo / 'LICENSE').symlink_to('skills/sample/SKILL.md') + with self.assertRaisesRegex(AuditBlocked, '根许可或 Notice 不是普通文件'): + self.audit() + self.run_git('reset', '--hard', self.old) + self.run_git('clean', '-fd') + self.write('licenses/thirdparty-MIT.txt', 'MIT third-party text\n') + self._rebind_old(self.commit()) + (self.repo / 'licenses' / 'alias').symlink_to('thirdparty-MIT.txt') + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + with self.assertRaisesRegex(AuditBlocked, '根许可或 Notice 不是普通文件'): + self.audit() + + def test_root_license_file_content_change_still_detected(self): + self.write('licenses/thirdparty-MIT.txt', 'MIT third-party text\n') + self._rebind_old(self.commit()) + self.write('LICENSE', 'different terms, no longer the admitted MIT text\n') + with self.assertRaisesRegex(AuditBlocked, '许可证|Notice'): + self.audit() + + def test_root_license_directory_changes_are_not_claimed_unchanged(self): + from audit_skill_update import license_directory_manifest_sha256, root_license_directory_files + self.write('licenses/ghidra-12.1.4.txt', 'Ghidra license text\n') + self._rebind_old(self.commit()) + (self.repo / 'licenses' / 'ghidra-12.1.4.txt').unlink() + self.write('licenses/ghidra-12.2.txt', 'Ghidra license text\n') + self.write('licenses/microsoft-uf2-MIT.txt', 'UF2 MIT notice\n') + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + new = self.commit() + with self.assertRaisesRegex(AuditBlocked, '根许可目录内的第三方许可文本有变化'): + audit_snapshots(self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, '2026-10-31T01:02:03Z') + digest = license_directory_manifest_sha256(root_license_directory_files(self.repo, new)['licenses']) + with self.assertRaisesRegex(AuditBlocked, '根许可目录专项复核必须包含审核人、日期和理由'): + audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, '2026-10-31T01:02:03Z', + special_review={'schemaVersion': 1, 'acceptedRootLicenseDirectoryManifestSha256': {'licenses': digest}}) + with self.assertRaisesRegex(AuditBlocked, '根许可目录内的第三方许可文本有变化'): + audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, '2026-10-31T01:02:03Z', + special_review={ + 'schemaVersion': 1, + 'reviewedBy': 'mashagua', + 'reviewedAt': '2026-11-22', + 'notes': 'wrong digest must not pass', + 'acceptedRootLicenseDirectoryManifestSha256': {'licenses': 'b' * 64}, + }) + entry, metadata, report = audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, '2026-10-31T01:02:03Z', + special_review={ + 'schemaVersion': 1, + 'reviewedBy': 'mashagua', + 'reviewedAt': '2026-11-22', + 'notes': 'Reviewed ghidra 12.1.4 to 12.2 rename with identical text and the added UF2 MIT notice.', + 'acceptedRootLicenseDirectoryManifestSha256': {'licenses': digest}, + }) + self.assertEqual(report['licenseEvidenceSha256']['licenses/ghidra-12.2.txt'], + __import__('hashlib').sha256(b'Ghidra license text\n').hexdigest()) + self.assertNotIn('licenses/ghidra-12.1.4.txt', report['licenseEvidenceSha256']) + self.assertIn('licenses/microsoft-uf2-MIT.txt', report['licenseEvidenceSha256']) + self.assertTrue(any('许可目录' in item for item in report['limitations'])) + self.assertEqual(metadata['governance']['compliance']['reviewedRef'], entry['source']['ref']) + + def test_deleted_root_license_directory_is_not_accepted(self): + self.write('licenses/thirdparty-MIT.txt', 'MIT third-party text\n') + self._rebind_old(self.commit()) + (self.repo / 'licenses' / 'thirdparty-MIT.txt').unlink() + (self.repo / 'licenses').rmdir() + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + with self.assertRaisesRegex(AuditBlocked, '根许可目录被删除'): + self.audit() + + def test_scoped_notice_append_still_works_with_licenses_directory(self): + import hashlib + self.write('licenses/thirdparty-MIT.txt', 'MIT third-party text\n') + path = 'skills/sample/NOTICE' + old_text = 'retained vendor attribution\n' + new_text = old_text + 'appended Unicode-3.0 notice\n' + self.write(path, old_text) + self._rebind_old(self.commit()) + self.write(path, new_text) + new = self.commit() + previous = hashlib.sha256(old_text.encode()).hexdigest() + digest = hashlib.sha256(new_text.encode()).hexdigest() + _, _, report = audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, '2026-10-31T01:02:03Z', + special_review=self._scoped_notice_review(self.old, new, path, previous, digest)) + self.assertEqual(report['licenseEvidenceSha256'][path], digest) + self.assertIn('licenses/thirdparty-MIT.txt', report['licenseEvidenceSha256']) + self.assertTrue(any('安装范围内的 Notice' in item for item in report['limitations'])) + def test_disallows_non_github_fetch_targets(self): self.entry['source']['repoUrl'] = 'file:///private/source' with self.assertRaisesRegex(AuditBlocked, 'HTTPS'): audit_update(self.entry, self.metadata, {})