From 476c04f6fea1b001b172c949dd3a62547fc70263 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 3 Dec 2026 08:54:34 +0800 Subject: [PATCH 1/2] feat: publish deterministic tar.gz and zip archives for platform-independent libraries (marqdo#106) Every platform-independent stdlib/extension release now ships the same reviewed file set as both a deterministic tar.gz (Linux/POSIX convention) and a deterministic zip (Windows convention) with per-format sha256 sidecars. The zip uses fixed DOS timestamps, create_system=3, regular-file 0644 attributes, UTF-8 name flags and deterministic deflate; both archives are double-built, verified as identical on disk to the exact commit blobs, and cross-checked against each other. Existing releases stay immutable; the rule applies to new versions. Tests updated for the dual-format artifact contract. The website projection is extended in a follow-up commit to classify .zip as an archive. --- scripts/component-release/README.md | 6 +- scripts/component-release/release.py | 140 +++++++++++++++----- tests/integration/test_component_release.py | 43 ++++-- 3 files changed, 141 insertions(+), 48 deletions(-) diff --git a/scripts/component-release/README.md b/scripts/component-release/README.md index 729c043..8e55c07 100644 --- a/scripts/component-release/README.md +++ b/scripts/component-release/README.md @@ -9,7 +9,7 @@ | 步骤 | 行为 | | --- | --- | -| 打包 | 从精确 tag commit 的 Git 对象(`git ls-tree` + `git cat-file`)重建**受评审路径**,固定 tar 元数据(mtime 0、uid/gid 0、mode 0644、排序路径)与 gzip 头(mtime 0、无文件名);连续打包两次必须逐字节一致,并在上传前把归档成员集合与字节回验到 commit blob。不使用 `git archive`,因此 `export-ignore`/`export-subst` 等 attributes 不能静默丢文件或改写内容;不含 `.git`、测试、缓存、凭证或工作树改动 | +| 打包 | 从精确 tag commit 的 Git 对象(`git ls-tree` + `git cat-file`)重建**受评审路径**,同时生成**确定性 `.tar.gz` 与 `.zip`**:tar 固定 mtime 0/uid/gid 0/mode 0644/排序路径,gzip 头 mtime 0 且无文件名;zip 固定 DOS 时间戳 1980-01-01、`create_system=3`、0644 常规文件属性、UTF-8 文件名标志与确定 deflate,排序写入。两者连续打包两次必须逐字节一致,并在上传前把成员集合与字节回验到 commit blob,且两种格式解压内容必须完全一致。不使用 `git archive`,因此 `export-ignore`/`export-subst` 等 attributes 不能静默丢文件或改写内容;不含 `.git`、测试、缓存、凭证或工作树改动 | | 证据 | 生成现行 `release-evidence.json`(字段与 `scripts/reconcile-releases.py` 校验一致),不新增 stdlib/ext 专用清单 | | CI 证据 | 通过 Woodpecker 公开只读 API 找到**同 SHA** 成功的 `ci` workflow,并**确定性地选择编号最小的一次**(重跑会复现已发布的同一份证据);没有同 SHA CI 时拒绝发布 | | 发布 | Gitea Release 草稿事务:发布前校验远端 tag 已存在时必须指向发布 commit;先传 payload、最后传证据索引、逐字节回读 sha256、再公开;已公开的同 tag 不同字节拒绝覆盖,相同字节且渠道一致时幂等成功;中断草稿可用 `--reset-draft` 显式重建;token 不随重定向转发 | @@ -51,9 +51,9 @@ pin 变更本身是普通组件 PR,不改变任何已发布资产。 ## 3. 发布路径与产物 - stdlib:`modules/`(Bundle 根相对路径)与 `README.md`;产物 - `marqdo---source.tar.gz`,`target=source`。 + `marqdo---source.tar.gz` 与 `...-source.zip`,`target=source`;各自带 `.sha256`。 - extension:`index.mq.md`、`marqdo.yaml`、`modules/`、`README.md`;产物 - `marqdo---package.tar.gz`,`target=source`。 + `marqdo---package.tar.gz` 与 `...-package.zip`,`target=source`;各自带 `.sha256`。 - 版本由组件仓自己决定(SemVer,tag `v`),与 CLI/Bundle/MQDH 版本无关。 - 依赖只登记**测试时实际使用**的精确组件身份(当前 stdlib 为 `cli` 的已发布源 SHA 与归档摘要);不得把设计输入或目录关系写成测试依赖。 diff --git a/scripts/component-release/release.py b/scripts/component-release/release.py index 390c4f4..90bf519 100644 --- a/scripts/component-release/release.py +++ b/scripts/component-release/release.py @@ -9,16 +9,20 @@ sibling component. Artifact -------- -The published asset is a deterministic archive of *only* the reviewed release -paths of the exact tagged commit. The tree and bytes are read from the Git -object database with ``git ls-tree`` / ``git cat-file`` (never ``git archive``, -never the working tree), so attributes such as ``export-ignore`` / -``export-subst`` cannot silently drop or rewrite released files. The tar -metadata is fixed (mtime 0, uid/gid 0, mode 0644, sorted paths) and the gzip -stream is written with mtime 0 and no filename. Packaging twice must produce -identical bytes in the same Python/zlib environment; that property is checked on -every run. The archive member set and bytes are compared back to the exact -commit blobs before anything is uploaded. +The published assets are deterministic ``tar.gz`` and ``zip`` archives of +*only* the reviewed release paths of the exact tagged commit. The tree and +bytes are read from the Git object database with ``git ls-tree`` / ``git +cat-file`` (never ``git archive``, never the working tree), so attributes such +as ``export-ignore`` / ``export-subst`` cannot silently drop or rewrite released +files. The tar metadata is fixed (mtime 0, uid/gid 0, mode 0644, sorted paths) +and the gzip stream is written with mtime 0 and no filename; the zip uses a +fixed DOS timestamp, ``create_system=3``, regular-file 0644 attributes and UTF-8 +name flags. Both formats carry exactly the same file set and bytes (tar.gz is +the Linux/POSIX convention, zip the Windows one; the content is platform +independent). Packaging twice must produce identical bytes in the same +Python/zlib environment; that property is checked per format on every run. The +archive member set and bytes are compared back to the exact commit blobs before +anything is uploaded. Evidence -------- @@ -75,6 +79,7 @@ import sys import tarfile import tempfile import unicodedata +import zipfile import urllib.error import urllib.parse import urllib.request @@ -97,7 +102,9 @@ MAX_ASSET_BYTES = 1024 * 1024 * 1024 MAX_TREE_BYTES = 256 * 1024 * 1024 MAX_DEPENDENCIES = 256 ALLOWED_EVENTS = {"push", "pull_request", "manual"} -KIND_SUFFIX = {"stdlib": "-source.tar.gz", "extension": "-package.tar.gz"} +KIND_SUFFIX = {"stdlib": "-source", "extension": "-package"} +ARCHIVE_FORMATS = ("tar.gz", "zip") +ZIP_MIN_TIME = (1980, 1, 1, 0, 0, 0) FIXED_MTIME = 0 FIXED_MODE = 0o644 PATHSPEC_MAGIC = set("*?[") @@ -165,7 +172,7 @@ def validate_version(tag: str) -> str: return version -def artifact_name(repository: str, version: str, kind: str) -> str: +def artifact_stem(repository: str, version: str, kind: str) -> str: name = repository.split("/", 1)[-1] require(BASENAME_RE.fullmatch(name) is not None, "repository name is not a safe basename") return f"{name}-{version}{KIND_SUFFIX[kind]}" @@ -265,6 +272,51 @@ def check_archive(payload: bytes, prefix: str, files: list[tuple[str, bytes]]) - require(seen[name] == data, f"archive bytes differ from the commit blob: {name}") +def build_zip(prefix: str, files: list[tuple[str, bytes]]) -> bytes: + """Build the reproducible Windows-friendly zip of the same released tree.""" + require(files, "zip would be empty") + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED, + compresslevel=9) as archive: + for relative, data in files: + info = zipfile.ZipInfo(f"{prefix}/{relative}", date_time=ZIP_MIN_TIME) + info.compress_type = zipfile.ZIP_DEFLATED + info.create_system = 3 # Unix, fixed for cross-host reproducibility + info.external_attr = 0o100644 << 16 # regular file, 0644, no exec bit + info.flag_bits |= 0x800 # UTF-8 names + archive.writestr(info, data) + return buffer.getvalue() + + +def check_zip(payload: bytes, prefix: str, files: list[tuple[str, bytes]]) -> None: + """Verify the zip is exactly the released commit tree, byte for byte.""" + expected = {f"{prefix}/{relative}": data for relative, data in files} + seen: dict[str, bytes] = {} + with zipfile.ZipFile(io.BytesIO(payload)) as archive: + infos = archive.infolist() + require(infos, "zip is empty") + for info in infos: + name = info.filename + require(not name.startswith(("/", "\\")), f"absolute zip path: {name}") + require("\\" not in name, f"backslash in zip path: {name}") + require(all(ord(character) >= 32 for character in name), + f"control character in zip path: {name!r}") + parts = name.split("/") + require(all(part not in ("", ".", "..") for part in parts), + f"traversal zip path: {name}") + require(not info.is_dir(), f"unexpected zip directory entry: {name}") + require(name in expected, f"zip member outside the released tree: {name}") + require(name not in seen, f"duplicate zip member: {name}") + require(info.create_system == 3, f"zip member {name} has an unstable creator system") + mode = (info.external_attr >> 16) & 0o170000 + require(mode in (0, 0o100000), f"zip member {name} is not a regular file") + seen[name] = archive.read(info) + require(set(seen) == set(expected), + "zip does not contain exactly the released commit files") + for name, data in expected.items(): + require(seen[name] == data, f"zip bytes differ from the commit blob: {name}") + + def package_assets( root: Path, source_sha: str, repository: str, component_id: str, version: str, kind: str, allow: list[str], out_dir: Path, @@ -272,28 +324,39 @@ def package_assets( require(SHA_RE.fullmatch(source_sha) is not None, "source SHA must be 40 lowercase hex") require(commit_exists(root, source_sha), "source SHA is not a commit in this repository") require(component_id != "" and "/" not in component_id, "invalid component id") - name = artifact_name(repository, version, kind) - archive = out_dir / name - checksum = out_dir / f"{name}.sha256" + stem = artifact_stem(repository, version, kind) prefix = f"{repository.split('/', 1)[-1]}-{version}" files = released_files(root, source_sha, allow) - first = build_archive(prefix, files) - second = build_archive(prefix, files) - require(first == second, "packaging the same commit twice produced different bytes") - check_archive(first, prefix, files) - require(len(first) > 0, "archive is empty") - archive.write_bytes(first) - digest = sha256_bytes(first) - checksum.write_text(f"{digest} {name}\n", encoding="utf-8") + tar_payload = build_archive(prefix, files) + require(tar_payload == build_archive(prefix, files), + "packaging the same commit twice produced different tar.gz bytes") + check_archive(tar_payload, prefix, files) + zip_payload = build_zip(prefix, files) + require(zip_payload == build_zip(prefix, files), + "packaging the same commit twice produced different zip bytes") + check_zip(zip_payload, prefix, files) + artifacts = [] + for extension, payload in (("tar.gz", tar_payload), ("zip", zip_payload)): + name = f"{stem}.{extension}" + path = out_dir / name + checksum = out_dir / f"{name}.sha256" + path.write_bytes(payload) + digest = sha256_bytes(payload) + checksum.write_text(f"{digest} {name}\n", encoding="utf-8") + artifacts.append({ + "format": extension, + "path": path, + "checksum": checksum, + "name": name, + "size": len(payload), + "sha256": digest, + }) return { - "archive": archive, - "checksum": checksum, - "name": name, - "size": len(first), - "sha256": digest, + "stem": stem, "prefix": prefix, "source_sha": source_sha, "files": len(files), + "artifacts": artifacts, } @@ -755,7 +818,8 @@ def command_check(args) -> int: "repository": args.repository, "kind": args.kind, "source_sha": source_sha, - "artifact": {key: result[key] for key in ("name", "size", "sha256")}, + "artifacts": [{key: artifact[key] for key in ("format", "name", "size", "sha256")} + for artifact in result["artifacts"]], "files": result["files"], "released_paths": sorted(args.allow), } @@ -800,14 +864,18 @@ def _publish(args, root, source_sha, version, prerelease, dependencies, out_dir, payload = package_assets(root, source_sha, args.repository, args.component_id, version, args.kind, list(args.allow), out_dir) ci = discover_ci(args.repository, source_sha, WORKFLOW, token) + asset_records = [] + publish_paths = [] + for artifact in payload["artifacts"]: + asset_records.append({"name": artifact["name"], "size": artifact["size"], + "sha256": artifact["sha256"]}) + asset_records.append({"name": artifact["checksum"].name, + "size": artifact["checksum"].stat().st_size, + "sha256": sha256_file(artifact["checksum"])}) + publish_paths.extend([artifact["path"], artifact["checksum"]]) evidence = build_evidence( repository=args.repository, component_id=args.component_id, tag=args.tag, - source_sha=source_sha, ci=ci, - assets=[{"name": payload["name"], "size": payload["size"], - "sha256": payload["sha256"]}, - {"name": f"{payload['name']}.sha256", - "size": payload["checksum"].stat().st_size, - "sha256": sha256_file(payload["checksum"])}], + source_sha=source_sha, ci=ci, assets=asset_records, dependencies=dependencies) evidence_path = write_evidence(evidence, out_dir / INDEX) body = args.body or default_body( @@ -819,7 +887,7 @@ def _publish(args, root, source_sha, version, prerelease, dependencies, out_dir, result = publish_release( repository=args.repository, tag=args.tag, source_sha=source_sha, body=body, prerelease=prerelease, - assets=[payload["archive"], payload["checksum"], evidence_path], token=token, + assets=[*publish_paths, evidence_path], token=token, reset_draft=args.reset_draft) print(json.dumps({ "status": result["status"], diff --git a/tests/integration/test_component_release.py b/tests/integration/test_component_release.py index ba12aa7..92cc66c 100644 --- a/tests/integration/test_component_release.py +++ b/tests/integration/test_component_release.py @@ -76,18 +76,30 @@ class PackageTests(unittest.TestCase): return kit.package_assets(self.repo, self.sha, "cflmy/marqdo-std-text", "std-text", "0.1.0", "stdlib", list(allow), target) + @staticmethod + def artifact(result, extension): + return next(item for item in result["artifacts"] if item["format"] == extension) + def test_same_commit_packages_identical_bytes(self): first = self.package("a") second = self.package("b") - self.assertEqual(first["sha256"], second["sha256"]) - self.assertEqual(first["archive"].read_bytes(), second["archive"].read_bytes()) - self.assertEqual(first["name"], "marqdo-std-text-0.1.0-source.tar.gz") - checksum = first["checksum"].read_text() - self.assertEqual(checksum, f"{first['sha256']} {first['name']}\n") + self.assertEqual([item["format"] for item in first["artifacts"]], ["tar.gz", "zip"]) + for extension in ("tar.gz", "zip"): + left = self.artifact(first, extension) + right = self.artifact(second, extension) + self.assertEqual(left["sha256"], right["sha256"]) + self.assertEqual(left["path"].read_bytes(), right["path"].read_bytes()) + self.assertEqual(left["checksum"].read_text(), + f"{left['sha256']} {left['name']}\n") + self.assertEqual(self.artifact(first, "tar.gz")["name"], + "marqdo-std-text-0.1.0-source.tar.gz") + self.assertEqual(self.artifact(first, "zip")["name"], + "marqdo-std-text-0.1.0-source.zip") def test_archive_contains_only_released_paths(self): result = self.package("out") - with tarfile.open(result["archive"], "r:gz") as archive: + targz = self.artifact(result, "tar.gz") + with tarfile.open(targz["path"], "r:gz") as archive: names = sorted(member.name for member in archive.getmembers()) self.assertEqual(names, [ "marqdo-std-text-0.1.0/README.md", @@ -97,6 +109,10 @@ class PackageTests(unittest.TestCase): self.assertEqual(result["files"], 3) self.assertNotIn("tests/text.mq.md", " ".join(names)) self.assertNotIn(".git", " ".join(names)) + import zipfile + with zipfile.ZipFile(self.artifact(result, "zip")["path"]) as archive: + zipped = sorted(info.filename for info in archive.infolist()) + self.assertEqual(zipped, names) def test_archive_ignores_git_export_attributes(self): write(self.repo / ".gitattributes", "modules export-ignore\n") @@ -108,9 +124,13 @@ class PackageTests(unittest.TestCase): result = kit.package_assets(self.repo, sha, "cflmy/marqdo-std-text", "std-text", "0.1.0", "stdlib", ["modules", "README.md"], out) - with tarfile.open(result["archive"], "r:gz") as archive: + with tarfile.open(self.artifact(result, "tar.gz")["path"], "r:gz") as archive: names = sorted(member.name for member in archive.getmembers()) self.assertIn("marqdo-std-text-0.1.0/modules/text/utf8.mq.md", names) + import zipfile + with zipfile.ZipFile(self.artifact(result, "zip")["path"]) as archive: + self.assertIn("marqdo-std-text-0.1.0/modules/text/utf8.mq.md", + archive.namelist()) def test_refuses_case_and_nfc_collisions(self): write(self.repo / "modules" / "Case.mq.md", "a") @@ -216,9 +236,13 @@ class PublishTransactionTests(unittest.TestCase): self.archive.write_bytes(b"payload") self.checksum = self.tmp / "a.tar.gz.sha256" self.checksum.write_text("digest a.tar.gz\n") + self.zip = self.tmp / "a.zip" + self.zip.write_bytes(b"zippayload") + self.zip_checksum = self.tmp / "a.zip.sha256" + self.zip_checksum.write_text("digest a.zip\n") self.index = self.tmp / "release-evidence.json" self.index.write_text("{}\n") - self.assets = [self.archive, self.checksum, self.index] + self.assets = [self.archive, self.checksum, self.zip, self.zip_checksum, self.index] self.release = {"id": 7, "tag_name": "v0.1.0", "draft": False, "prerelease": False, "html_url": "https://git.cflmy.cn/cflmy/marqdo-std-text/releases/tag/v0.1.0"} @@ -261,7 +285,8 @@ class PublishTransactionTests(unittest.TestCase): patch.object(kit, "find_release", side_effect=[None, self.release]): result = self.publish() self.assertEqual(result["status"], "published") - self.assertEqual(uploaded, ["a.tar.gz", "a.tar.gz.sha256", "release-evidence.json"]) + self.assertEqual(uploaded, ["a.tar.gz", "a.tar.gz.sha256", "a.zip", + "a.zip.sha256", "release-evidence.json"]) class CiDiscoveryTests(unittest.TestCase): From 507305c9d73d3f6114466234f8261dc3bea6a282 Mon Sep 17 00:00:00 2001 From: cflmy Date: Thu, 3 Dec 2026 08:56:40 +0800 Subject: [PATCH 2/2] feat: classify .zip library archives as archives in the public projection (marqdo#106) The projection lists both tar.gz and zip for platform-independent library releases; .zip must map to the archive asset kind so the website can offer it as a download format. Add coverage in the independent-release projection test. --- scripts/project-release.py | 2 +- tests/integration/test_project_release.py | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/scripts/project-release.py b/scripts/project-release.py index f8dfe68..a56aa80 100644 --- a/scripts/project-release.py +++ b/scripts/project-release.py @@ -356,7 +356,7 @@ def release_id(component_id: str, version: str) -> str: def asset_kind(name: str) -> str: - if name.endswith(".tar.gz"): + if name.endswith(".tar.gz") or name.endswith(".zip"): return "archive" if name.endswith(".sha256"): return "checksum" diff --git a/tests/integration/test_project_release.py b/tests/integration/test_project_release.py index 735c182..2cc8f3b 100644 --- a/tests/integration/test_project_release.py +++ b/tests/integration/test_project_release.py @@ -425,7 +425,9 @@ class ProjectReleaseTests(unittest.TestCase): ci={"pipeline_number": 27, "url": "https://ci.cflmy.cn/repos/10/pipeline/27", "source_sha": independent_sha}, assets=[{"name": "marqdo-std-data-0.1.1-source.tar.gz", "size": 6763, - "target": "source", "sha256": "9" * 64}], + "target": "source", "sha256": "9" * 64}, + {"name": "marqdo-std-data-0.1.1-source.zip", "size": 7000, + "target": "source", "sha256": "8" * 64}], dependencies=[], published_at="2026-12-03T00:20:00+00:00", ) @@ -444,6 +446,8 @@ class ProjectReleaseTests(unittest.TestCase): self.assertEqual(pending["integration_state"], "pending") self.assertEqual(pending["distribution_state"], "available") self.assertEqual(pending["channel"], "stable") + self.assertEqual([asset["kind"] for asset in pending["assets"]], + ["archive", "archive"]) self.assertEqual([offer["product"] for offer in snapshot["offers"]], ["marqdo"]) self.assertEqual([item["offer_id"] for item in snapshot["recommendations"]], [snapshot["offers"][0]["offer_id"]])