feat: single component release transaction (marqdo#96 M1) #98
No files matched your search
@@ -0,0 +1,88 @@
|
||||
# Component release kit(唯一实现)
|
||||
|
||||
本目录是 Marqdo 生态**标准库与扩展库共用的组件独立发行事务**的唯一实现,
|
||||
落实 [marqdo#96](https://git.cflmy.cn/cflmy/marqdo/issues/96) M1。各功能仓不复制
|
||||
第二份打包/证据/发布代码,只在 `.woodpecker/publish.yml` 中引导本文件并登记自身
|
||||
的发布路径;普通 push/PR 使用同一入口做确定性打包自检。
|
||||
|
||||
## 1. 它负责什么
|
||||
|
||||
| 步骤 | 行为 |
|
||||
| --- | --- |
|
||||
| 打包 | 从精确 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`、测试、缓存、凭证或工作树改动 |
|
||||
| 证据 | 生成现行 `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 不随重定向转发 |
|
||||
|
||||
它不枚举依赖图、不修改 gitlink、不自动晋升、不自动通知合并。发行是组件事实;
|
||||
根推荐/接受、消费者接入是另外的事实。
|
||||
|
||||
## 2. 组件仓接线
|
||||
|
||||
普通 CI(`.woodpecker/ci.yml`)在真实测试后追加确定性打包自检:
|
||||
|
||||
```yaml
|
||||
- |
|
||||
set -eu
|
||||
kit=$(mktemp -d); trap 'rm -rf "$kit"' EXIT
|
||||
base="https://git.cflmy.cn/cflmy/marqdo/raw/commit/<ROOT_COMMIT>"
|
||||
curl -fsSL --retry 3 "$base/scripts/component-release/release.py" -o "$kit/release.py"
|
||||
echo "<RELEASE_PY_SHA256> $kit/release.py" | sha256sum -c -
|
||||
python3 "$kit/release.py" check \
|
||||
--repository "$CI_REPO" --component-id <component-id> --kind stdlib \
|
||||
--allow modules --allow README.md
|
||||
```
|
||||
|
||||
受保护发布流水线(`.woodpecker/publish.yml`)只在 tag 事件运行:
|
||||
|
||||
```yaml
|
||||
when:
|
||||
event: [tag]
|
||||
```
|
||||
|
||||
模板见 [templates/publish.yml](templates/publish.yml)。`GITEA_PUBLISH_TOKEN`
|
||||
只授予该 tag 工作流,普通 PR/push 不得持有发布凭据(各仓 Woodpecker secret
|
||||
已按 `manual,tag` 事件隔离)。
|
||||
|
||||
`<ROOT_COMMIT>` 与 `<RELEASE_PY_SHA256>` 是**唯一实现**的不可变 pin:升级 kit 时在
|
||||
根仓评审、合并,再以新的根提交与文件摘要更新各组件仓的 pin 与相应 tag/证据。
|
||||
pin 变更本身是普通组件 PR,不改变任何已发布资产。
|
||||
|
||||
## 3. 发布路径与产物
|
||||
|
||||
- stdlib:`modules/`(Bundle 根相对路径)与 `README.md`;产物
|
||||
`marqdo-<repo>-<version>-source.tar.gz`,`target=source`。
|
||||
- extension:`index.mq.md`、`marqdo.yaml`、`modules/`、`README.md`;产物
|
||||
`marqdo-<repo>-<version>-package.tar.gz`,`target=source`。
|
||||
- 版本由组件仓自己决定(SemVer,tag `v<version>`),与 CLI/Bundle/MQDH 版本无关。
|
||||
- 依赖只登记**测试时实际使用**的精确组件身份(当前 stdlib 为 `cli` 的已发布源
|
||||
SHA 与归档摘要);不得把设计输入或目录关系写成测试依赖。
|
||||
|
||||
## 4. 命令
|
||||
|
||||
```sh
|
||||
# 同 SHA 确定性打包自检(不联网、不写发布)
|
||||
python3 release.py check --repository cflmy/marqdo-std-text --component-id std-text \
|
||||
--kind stdlib --allow modules --allow README.md
|
||||
|
||||
# 受保护发布(GITEA_PUBLISH_TOKEN 只在此使用)
|
||||
GITEA_PUBLISH_TOKEN=... python3 release.py publish \
|
||||
--repository cflmy/marqdo-std-text --component-id std-text \
|
||||
--kind stdlib --allow modules --allow README.md \
|
||||
--tag v0.1.0 \
|
||||
--dependency "id=cli,source_sha=<cli-source-sha>,asset_sha256=<cli-archive-sha256>"
|
||||
```
|
||||
|
||||
`publish` 校验:HEAD 必须等于发布 commit;tag 若已在本地存在必须指向该 commit;
|
||||
版本字符串决定渠道(含 `-` 后缀即 prerelease,与 Gitea 标记一致);同 SHA 的
|
||||
`ci` 流水线必须成功;全部资产回读摘要一致后才公开。
|
||||
|
||||
## 5. 边界
|
||||
|
||||
- 不取代 `scripts/reconcile-releases.py` 的独立核验:发布后仍由根对账做
|
||||
tag→SHA、同 SHA CI、资产逐字节回读与依赖一致性检查。
|
||||
- 不发布根推荐状态,不写消费者锁,不触发自动安装。
|
||||
- 历史已发布的 std-text `v0.0.0-ci10.1` 演练发行不计为合格发行;本入口产生的
|
||||
新发行使用真实同 SHA CI 证据。
|
||||
- 规则变更走根仓 PR + 集成测试(`tests/integration/test_component_release.py`),
|
||||
不在单个组件仓另行维护规则。
|
||||
@@ -0,0 +1,872 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish one independent Marqdo stdlib/extension component release.
|
||||
|
||||
This is the single implementation of the component release transaction used by
|
||||
every active library repository (marqdo#96 M1). A component repository only
|
||||
needs Python 3 and git (the bootstrap in ``.woodpecker/publish.yml`` downloads
|
||||
this file at a pinned root commit) and never checks out the root repository or a
|
||||
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.
|
||||
|
||||
Evidence
|
||||
--------
|
||||
``release-evidence.json`` follows the ecosystem-wide schema already verified by
|
||||
``scripts/reconcile-releases.py``::
|
||||
|
||||
repository, component_id, tag, source_sha,
|
||||
ci: {pipeline_number, url, source_sha},
|
||||
assets: [{name, size, target, sha256}],
|
||||
dependencies: [{id, source_sha[, asset_sha256]}]
|
||||
|
||||
No parallel stdlib/ext release manifest is introduced. The same-SHA Woodpecker
|
||||
pipeline of the ``ci`` workflow is discovered through the public read-only API.
|
||||
Selection is deterministic (the lowest successful same-SHA pipeline number), so
|
||||
re-running the transaction reproduces the same evidence instead of picking a
|
||||
newer pipeline that appeared later. A release is never published without a
|
||||
successful same-SHA component CI.
|
||||
|
||||
Publish transaction
|
||||
-------------------
|
||||
Gitea Release is used as the immutable asset store: create/reuse a *draft*,
|
||||
upload the payload assets first and ``release-evidence.json`` last, re-read every
|
||||
byte and compare sha256, then make the release public. Published releases are
|
||||
never deleted or overwritten. Re-running with identical bytes is idempotent;
|
||||
different bytes for the same tag fail closed. An interrupted draft can be
|
||||
discarded explicitly with ``--reset-draft``. The remote tag is checked before
|
||||
publishing: an existing tag must already point at the released commit.
|
||||
|
||||
Commands
|
||||
--------
|
||||
release.py check --repository cflmy/marqdo-std-text --component-id std-text \
|
||||
--kind stdlib --allow modules --allow README.md
|
||||
release.py publish --repository cflmy/marqdo-std-text --component-id std-text \
|
||||
--kind stdlib --allow modules --allow README.md \
|
||||
--tag v0.1.0 \
|
||||
--dependency "id=cli,source_sha=<sha>,asset_sha256=<digest>"
|
||||
|
||||
Environment for ``publish``: ``GITEA_PUBLISH_TOKEN`` holds the protected
|
||||
publishing token; ordinary push/PR lanes never receive it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unicodedata
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
FORGE = "https://git.cflmy.cn"
|
||||
CI = "https://ci.cflmy.cn"
|
||||
INDEX = "release-evidence.json"
|
||||
WORKFLOW = "ci"
|
||||
SHA_RE = re.compile(r"[0-9a-f]{40}")
|
||||
DIGEST_RE = re.compile(r"[0-9a-f]{64}")
|
||||
VERSION_RE = re.compile(
|
||||
r"(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)"
|
||||
r"(-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?"
|
||||
)
|
||||
BASENAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,254}")
|
||||
MAX_INDEX_BYTES = 1024 * 1024
|
||||
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"}
|
||||
FIXED_MTIME = 0
|
||||
FIXED_MODE = 0o644
|
||||
PATHSPEC_MAGIC = set("*?[")
|
||||
|
||||
|
||||
class ReleaseError(Exception):
|
||||
"""A release precondition, artifact or transaction failed."""
|
||||
|
||||
|
||||
def require(condition: object, message: str) -> None:
|
||||
if not condition:
|
||||
raise ReleaseError(message)
|
||||
|
||||
|
||||
def sha256_bytes(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def git(root: Path, *args: str, binary: bool = False):
|
||||
result = subprocess.run(
|
||||
["git", "-C", str(root), *args], capture_output=True
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise ReleaseError(
|
||||
f"git {' '.join(args)} failed: {result.stderr.decode(errors='replace').strip()}"
|
||||
)
|
||||
return result.stdout if binary else result.stdout.decode().strip()
|
||||
|
||||
|
||||
def resolved_head(root: Path) -> str:
|
||||
value = git(root, "rev-parse", "HEAD")
|
||||
require(SHA_RE.fullmatch(value) is not None, "HEAD is not a full commit SHA")
|
||||
return value
|
||||
|
||||
|
||||
def commit_exists(root: Path, revision: str) -> bool:
|
||||
result = subprocess.run(
|
||||
["git", "-C", str(root), "cat-file", "-e", f"{revision}^{{commit}}"],
|
||||
capture_output=True,
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def safe_relative(entry: str) -> bool:
|
||||
if not entry or entry.startswith(("/", "\\")) or entry == ".":
|
||||
return False
|
||||
if any(character in PATHSPEC_MAGIC for character in entry):
|
||||
return False
|
||||
parts = Path(entry).parts
|
||||
return bool(parts) and not any(part in ("", ".", "..") for part in parts)
|
||||
|
||||
|
||||
def validate_version(tag: str) -> str:
|
||||
require(tag.startswith("v"), f"tag {tag!r} must start with 'v'")
|
||||
version = tag[1:]
|
||||
require(VERSION_RE.fullmatch(version) is not None, f"invalid release version {version!r}")
|
||||
return version
|
||||
|
||||
|
||||
def artifact_name(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]}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Deterministic archive built from the exact Git objects
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def released_files(root: Path, source_sha: str, allow: list[str]) -> list[tuple[str, bytes]]:
|
||||
"""Return ``(repository_path, bytes)`` for the allowlisted files of one commit."""
|
||||
for entry in allow:
|
||||
require(safe_relative(entry), f"unsafe release path: {entry!r}")
|
||||
listing = git(root, "ls-tree", "-r", "-z", source_sha, "--", *allow, binary=True)
|
||||
records = [record for record in listing.split(b"\0") if record]
|
||||
require(records, "release paths match no file at the tagged commit")
|
||||
selected: dict[str, bytes] = {}
|
||||
folded: dict[str, str] = {}
|
||||
total = 0
|
||||
for record in records:
|
||||
header, _, raw_path = record.partition(b"\t")
|
||||
fields = header.decode("ascii", "strict").split()
|
||||
require(len(fields) == 3, "invalid git tree record")
|
||||
mode, kind, blob = fields
|
||||
path = raw_path.decode("utf-8")
|
||||
require(kind == "blob", f"released path is not a regular file: {path} ({mode})")
|
||||
require(mode in ("100644", "100755"), f"released path has unsupported mode: {path}")
|
||||
require(safe_relative(path), f"unsafe released path: {path}")
|
||||
require(
|
||||
any(path == entry or path.startswith(entry.rstrip("/") + "/") for entry in allow),
|
||||
f"released path outside the reviewed allow list: {path}",
|
||||
)
|
||||
normalised = unicodedata.normalize("NFC", path)
|
||||
key = normalised.casefold()
|
||||
require(key not in folded,
|
||||
f"case/NFC collision between released paths: {folded.get(key)!r} and {path!r}")
|
||||
require(path not in selected, f"duplicate released path: {path}")
|
||||
folded[key] = path
|
||||
data = git(root, "cat-file", "blob", blob, binary=True)
|
||||
total += len(data)
|
||||
require(total <= MAX_TREE_BYTES, "released tree exceeds the size limit")
|
||||
selected[path] = data
|
||||
return [(path, selected[path]) for path in sorted(selected)]
|
||||
|
||||
|
||||
def build_archive(prefix: str, files: list[tuple[str, bytes]]) -> bytes:
|
||||
"""Build the reproducible tar.gz stream from resolved file bytes."""
|
||||
require(files, "archive would be empty")
|
||||
tar_buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=tar_buffer, mode="w", format=tarfile.PAX_FORMAT) as archive:
|
||||
for relative, data in files:
|
||||
info = tarfile.TarInfo(name=f"{prefix}/{relative}")
|
||||
info.size = len(data)
|
||||
info.mtime = FIXED_MTIME
|
||||
info.uid = 0
|
||||
info.gid = 0
|
||||
info.uname = ""
|
||||
info.gname = ""
|
||||
info.mode = FIXED_MODE
|
||||
archive.addfile(info, io.BytesIO(data))
|
||||
output = io.BytesIO()
|
||||
with gzip.GzipFile(fileobj=output, mode="wb", compresslevel=9,
|
||||
mtime=0, filename="") as compressed:
|
||||
compressed.write(tar_buffer.getvalue())
|
||||
payload = output.getvalue()
|
||||
require(payload.startswith(b"\x1f\x8b\x08\x00\x00\x00\x00\x00"),
|
||||
"archive is not a reproducible gzip stream")
|
||||
return payload
|
||||
|
||||
|
||||
def check_archive(payload: bytes, prefix: str, files: list[tuple[str, bytes]]) -> None:
|
||||
"""Verify the archive is exactly the released commit tree, byte for byte."""
|
||||
expected = {f"{prefix}/{relative}": data for relative, data in files}
|
||||
seen: dict[str, bytes] = {}
|
||||
with tarfile.open(fileobj=io.BytesIO(payload), mode="r:gz") as archive:
|
||||
members = archive.getmembers()
|
||||
require(members, "archive is empty")
|
||||
for member in members:
|
||||
name = member.name
|
||||
require(not name.startswith(("/", "\\")), f"absolute archive path: {name}")
|
||||
require("\\" not in name, f"backslash in archive path: {name}")
|
||||
require(all(ord(character) >= 32 for character in name),
|
||||
f"control character in archive path: {name!r}")
|
||||
parts = name.split("/")
|
||||
require(all(part not in ("", ".", "..") for part in parts),
|
||||
f"traversal archive path: {name}")
|
||||
require(member.isfile(), f"unexpected archive member: {name} ({member.type!r})")
|
||||
require(not member.issym() and not member.islnk(), f"link in archive: {name}")
|
||||
require(name in expected, f"archive member outside the released tree: {name}")
|
||||
require(name not in seen, f"duplicate archive member: {name}")
|
||||
handle = archive.extractfile(member)
|
||||
require(handle is not None, f"cannot read archive member: {name}")
|
||||
seen[name] = handle.read()
|
||||
require(set(seen) == set(expected),
|
||||
"archive does not contain exactly the released commit files")
|
||||
for name, data in expected.items():
|
||||
require(seen[name] == data, f"archive 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,
|
||||
) -> dict:
|
||||
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"
|
||||
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")
|
||||
return {
|
||||
"archive": archive,
|
||||
"checksum": checksum,
|
||||
"name": name,
|
||||
"size": len(first),
|
||||
"sha256": digest,
|
||||
"prefix": prefix,
|
||||
"source_sha": source_sha,
|
||||
"files": len(files),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Evidence
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def parse_dependency(raw: str) -> dict:
|
||||
fields: dict[str, str] = {}
|
||||
for part in raw.split(","):
|
||||
require("=" in part, f"invalid dependency field: {raw!r}")
|
||||
key, value = part.split("=", 1)
|
||||
key = key.strip()
|
||||
require(key in {"id", "source_sha", "asset_sha256"},
|
||||
f"unknown dependency field: {key!r}")
|
||||
require(key not in fields, f"duplicate dependency field: {key!r}")
|
||||
fields[key] = value.strip()
|
||||
component = fields.get("id", "")
|
||||
source_sha = fields.get("source_sha", "")
|
||||
require(component != "" and "/" not in component, f"invalid dependency id: {raw!r}")
|
||||
require(SHA_RE.fullmatch(source_sha) is not None,
|
||||
f"dependency {component} needs a full source_sha: {raw!r}")
|
||||
record = {"id": component, "source_sha": source_sha}
|
||||
asset = fields.get("asset_sha256")
|
||||
if asset:
|
||||
require(DIGEST_RE.fullmatch(asset) is not None,
|
||||
f"dependency {component} has an invalid asset_sha256")
|
||||
record["asset_sha256"] = asset
|
||||
return record
|
||||
|
||||
|
||||
def build_evidence(*, repository: str, component_id: str, tag: str, source_sha: str,
|
||||
ci: dict, assets: list[dict], dependencies: list[dict]) -> dict:
|
||||
require(component_id != "" and "/" not in component_id, "invalid component id")
|
||||
require(tag != "" and " " not in tag, "invalid tag")
|
||||
names: set[str] = set()
|
||||
records = []
|
||||
for asset in assets:
|
||||
name = asset["name"]
|
||||
require(BASENAME_RE.fullmatch(name) is not None, f"unsafe asset name: {name!r}")
|
||||
require(name != INDEX, "release-evidence.json must not describe itself")
|
||||
require(name not in names, f"duplicate asset: {name}")
|
||||
require(type(asset["size"]) is int and asset["size"] > 0, f"empty asset: {name}")
|
||||
require(DIGEST_RE.fullmatch(asset["sha256"]) is not None, f"invalid digest: {name}")
|
||||
names.add(name)
|
||||
records.append({"name": name, "size": asset["size"],
|
||||
"target": "source", "sha256": asset["sha256"]})
|
||||
require(records, "a release needs at least one payload asset")
|
||||
require(len(records) <= 127, "too many release assets")
|
||||
seen: set[str] = set()
|
||||
deps = []
|
||||
for dependency in dependencies:
|
||||
require(dependency["id"] not in seen, f"duplicate dependency: {dependency['id']}")
|
||||
require(dependency["id"] != component_id, "a component cannot depend on itself")
|
||||
require(len(deps) < MAX_DEPENDENCIES, "too many release dependencies")
|
||||
seen.add(dependency["id"])
|
||||
record = {"id": dependency["id"], "source_sha": dependency["source_sha"]}
|
||||
if "asset_sha256" in dependency:
|
||||
record["asset_sha256"] = dependency["asset_sha256"]
|
||||
deps.append(record)
|
||||
return {
|
||||
"repository": repository,
|
||||
"component_id": component_id,
|
||||
"tag": tag,
|
||||
"source_sha": source_sha,
|
||||
"ci": ci,
|
||||
"assets": records,
|
||||
"dependencies": deps,
|
||||
}
|
||||
|
||||
|
||||
def write_evidence(evidence: dict, out: Path) -> Path:
|
||||
payload = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
|
||||
require(len(payload.encode()) <= MAX_INDEX_BYTES, "release-evidence.json exceeds 1 MiB")
|
||||
out.write_text(payload, encoding="utf-8")
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTTP clients
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
"""Never forward the publish token to another URL or host via a redirect."""
|
||||
|
||||
def redirect_request(self, request, fp, code, message, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
OPENER = urllib.request.build_opener(NoRedirect)
|
||||
|
||||
|
||||
def api_request(url: str, token: str, *, method: str = "GET", payload: dict | None = None,
|
||||
raw: bytes | None = None, content_type: str = "application/json"):
|
||||
headers = {"Accept": "application/json"}
|
||||
if token:
|
||||
headers["Authorization"] = f"token {token}"
|
||||
data = raw
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = content_type
|
||||
elif raw is not None:
|
||||
headers["Content-Type"] = content_type
|
||||
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with OPENER.open(request, timeout=120) as response:
|
||||
return response.status, response.read(), dict(response.headers)
|
||||
except urllib.error.HTTPError as error:
|
||||
if 300 <= error.code < 400:
|
||||
raise ReleaseError(f"unexpected redirect from {url}") from error
|
||||
return error.code, error.read(), dict(error.headers)
|
||||
except (urllib.error.URLError, TimeoutError) as error:
|
||||
raise ReleaseError(f"request failed: {url}: {error}") from error
|
||||
|
||||
|
||||
def read_json(url: str, token: str = "") -> object:
|
||||
status, body, _ = api_request(url, token)
|
||||
require(status == 200, f"GET {url} returned HTTP {status}")
|
||||
try:
|
||||
return json.loads(body)
|
||||
except ValueError as error:
|
||||
raise ReleaseError(f"GET {url} did not return JSON: {error}") from error
|
||||
|
||||
|
||||
def ci_repository(repository: str, token: str) -> int:
|
||||
forge = read_json(f"{FORGE}/api/v1/repos/{repository}", token)
|
||||
ci = read_json(f"{CI}/api/repos/lookup/{repository}")
|
||||
require(isinstance(forge, dict) and type(forge.get("id")) is int,
|
||||
"Gitea does not identify the canonical repository")
|
||||
require(isinstance(ci, dict) and ci.get("full_name") == repository
|
||||
and type(ci.get("id")) is int and ci["id"] > 0
|
||||
and ci.get("forge_remote_id") == str(forge["id"]),
|
||||
"Woodpecker does not identify the canonical repository")
|
||||
return ci["id"]
|
||||
|
||||
|
||||
def discover_ci(repository: str, source_sha: str, workflow: str, token: str) -> dict:
|
||||
"""Find the deterministic same-SHA component CI pipeline for the release."""
|
||||
require(SHA_RE.fullmatch(source_sha) is not None, "release SHA must be a full commit")
|
||||
repo_id = ci_repository(repository, token)
|
||||
pipelines: list[dict] = []
|
||||
for page in range(1, 5):
|
||||
listing = read_json(f"{CI}/api/repos/{repo_id}/pipelines?per_page=50&page={page}")
|
||||
require(isinstance(listing, list), "Woodpecker pipeline listing is malformed")
|
||||
pipelines.extend(item for item in listing if isinstance(item, dict))
|
||||
if len(listing) < 50:
|
||||
break
|
||||
candidates = sorted(
|
||||
(item for item in pipelines
|
||||
if item.get("commit") == source_sha and item.get("status") == "success"
|
||||
and item.get("event") in ALLOWED_EVENTS
|
||||
and type(item.get("number")) is int and item["number"] > 0),
|
||||
key=lambda item: item["number"],
|
||||
)
|
||||
require(candidates, f"no successful same-SHA Woodpecker pipeline for {source_sha}")
|
||||
# Deterministic: the oldest successful same-SHA run cannot change later, so
|
||||
# re-running the transaction reproduces the same evidence.
|
||||
number = candidates[0]["number"]
|
||||
detail = read_json(f"{CI}/api/repos/{repo_id}/pipelines/{number}")
|
||||
require(isinstance(detail, dict) and detail.get("number") == number
|
||||
and detail.get("commit") == source_sha and detail.get("status") == "success",
|
||||
f"Woodpecker pipeline {number} identity changed while verifying")
|
||||
require(any(
|
||||
isinstance(item, dict) and item.get("name") == workflow
|
||||
and item.get("state") == "success"
|
||||
and any(isinstance(step, dict) and step.get("type") == "commands"
|
||||
and step.get("state") == "success" for step in item.get("children", []))
|
||||
for item in detail.get("workflows", [])
|
||||
), f"same-SHA pipeline {number} has no successful {workflow!r} workflow")
|
||||
return {
|
||||
"pipeline_number": number,
|
||||
"url": f"{CI}/repos/{repo_id}/pipeline/{number}",
|
||||
"source_sha": source_sha,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gitea release transaction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def release_api(repository: str, tag: str = "") -> str:
|
||||
base = f"{FORGE}/api/v1/repos/{repository}/releases"
|
||||
return f"{base}/tags/{urllib.parse.quote(tag, safe='')}" if tag else base
|
||||
|
||||
|
||||
def remote_tag_commit(repository: str, tag: str, token: str) -> str | None:
|
||||
status, body, _ = api_request(
|
||||
f"{FORGE}/api/v1/repos/{repository}/tags/{urllib.parse.quote(tag, safe='')}", token)
|
||||
if status == 404:
|
||||
return None
|
||||
require(status == 200, f"tag lookup for {tag} returned HTTP {status}")
|
||||
try:
|
||||
data = json.loads(body)
|
||||
except ValueError as error:
|
||||
raise ReleaseError(f"tag lookup for {tag} is not JSON: {error}") from error
|
||||
commit = ((data.get("commit") if isinstance(data, dict) else None) or {}).get("sha")
|
||||
require(isinstance(commit, str) and SHA_RE.fullmatch(commit) is not None,
|
||||
f"remote tag {tag} has no verifiable commit identity")
|
||||
return commit
|
||||
|
||||
|
||||
def find_release(repository: str, tag: str, token: str) -> dict | None:
|
||||
status, body, _ = api_request(release_api(repository, tag), token)
|
||||
if status == 404:
|
||||
return None
|
||||
require(status == 200, f"release lookup for {tag} returned HTTP {status}")
|
||||
try:
|
||||
release = json.loads(body)
|
||||
except ValueError as error:
|
||||
raise ReleaseError(f"release lookup for {tag} is not JSON: {error}") from error
|
||||
require(isinstance(release, dict) and type(release.get("id")) is int,
|
||||
f"release lookup for {tag} is malformed")
|
||||
return release
|
||||
|
||||
|
||||
def release_assets(repository: str, tag: str, token: str) -> dict:
|
||||
"""Return name -> release asset record, verifying canonical download URLs."""
|
||||
release = find_release(repository, tag, token)
|
||||
require(release is not None, f"release {tag} is missing after publish")
|
||||
assets: dict[str, dict] = {}
|
||||
for asset in release.get("assets") or []:
|
||||
name = asset.get("name")
|
||||
require(isinstance(name, str) and BASENAME_RE.fullmatch(name) is not None,
|
||||
"release carries an unsafe asset name")
|
||||
expected = (
|
||||
f"{FORGE}/{repository}/releases/download/"
|
||||
f"{urllib.parse.quote(tag, safe='')}/{urllib.parse.quote(name, safe='')}"
|
||||
)
|
||||
require(asset.get("browser_download_url") == expected,
|
||||
f"asset {name} has a non-canonical download URL")
|
||||
require(name not in assets, f"duplicate release asset {name}")
|
||||
assets[name] = asset
|
||||
return assets
|
||||
|
||||
|
||||
def download_verified(asset: dict, token: str) -> bytes:
|
||||
headers = {"Accept": "application/octet-stream"}
|
||||
if token:
|
||||
headers["Authorization"] = f"token {token}"
|
||||
request = urllib.request.Request(asset["browser_download_url"], headers=headers)
|
||||
try:
|
||||
with OPENER.open(request, timeout=120) as response:
|
||||
data = response.read(MAX_ASSET_BYTES + 1)
|
||||
except urllib.error.HTTPError as error:
|
||||
raise ReleaseError(
|
||||
f"asset download {asset['name']} returned HTTP {error.code}") from error
|
||||
except (urllib.error.URLError, TimeoutError) as error:
|
||||
raise ReleaseError(f"asset download {asset['name']} failed: {error}") from error
|
||||
require(len(data) <= MAX_ASSET_BYTES, f"asset {asset['name']} exceeds the size limit")
|
||||
require(len(data) == int(asset.get("size") or -1),
|
||||
f"asset {asset['name']} size differs from its release record")
|
||||
return data
|
||||
|
||||
|
||||
def published_matches(repository: str, tag: str, expected: list[dict], token: str) -> bool:
|
||||
try:
|
||||
assets = release_assets(repository, tag, token)
|
||||
if set(assets) != {item["name"] for item in expected}:
|
||||
return False
|
||||
for item in expected:
|
||||
data = download_verified(assets[item["name"]], token)
|
||||
if sha256_bytes(data) != item["sha256"]:
|
||||
return False
|
||||
return True
|
||||
except ReleaseError:
|
||||
return False
|
||||
|
||||
|
||||
def create_draft(repository: str, tag: str, body: str, target: str,
|
||||
prerelease: bool, token: str) -> dict:
|
||||
payload = {"tag_name": tag, "name": tag, "body": body, "draft": True,
|
||||
"prerelease": prerelease, "target_commitish": target}
|
||||
status, response, _ = api_request(
|
||||
release_api(repository), token, method="POST", payload=payload)
|
||||
require(status in (200, 201),
|
||||
f"creating draft release {tag} returned HTTP {status}: {response[:200]!r}")
|
||||
try:
|
||||
release = json.loads(response)
|
||||
except ValueError as error:
|
||||
raise ReleaseError("draft release response is not JSON") from error
|
||||
require(isinstance(release, dict) and type(release.get("id")) is int,
|
||||
"draft release response is malformed")
|
||||
return release
|
||||
|
||||
|
||||
def patch_release(repository: str, release_id: int, payload: dict, token: str) -> dict:
|
||||
status, response, _ = api_request(
|
||||
f"{release_api(repository)}/{release_id}", token, method="PATCH", payload=payload)
|
||||
require(status == 200, f"updating release {release_id} returned HTTP {status}")
|
||||
try:
|
||||
release = json.loads(response)
|
||||
except ValueError as error:
|
||||
raise ReleaseError("release update response is not JSON") from error
|
||||
require(isinstance(release, dict), "release update response is malformed")
|
||||
return release
|
||||
|
||||
|
||||
def delete_release(repository: str, release_id: int, token: str) -> None:
|
||||
status, response, _ = api_request(
|
||||
f"{release_api(repository)}/{release_id}", token, method="DELETE")
|
||||
require(status in (200, 204),
|
||||
f"deleting draft release {release_id} returned HTTP {status}: {response[:200]!r}")
|
||||
|
||||
|
||||
def upload_asset(repository: str, release_id: int, path: Path, token: str) -> dict:
|
||||
name = path.name
|
||||
require(path.stat().st_size <= MAX_ASSET_BYTES, f"asset {name} exceeds the size limit")
|
||||
existing = read_json(f"{release_api(repository)}/{release_id}/assets", token)
|
||||
require(isinstance(existing, list), "release asset listing is malformed")
|
||||
for asset in existing:
|
||||
if asset.get("name") == name:
|
||||
raise ReleaseError(
|
||||
f"asset {name} already exists on release {release_id}; refusing to overwrite")
|
||||
boundary = f"----marqdo{uuid.uuid4().hex}"
|
||||
content_type = mimetypes.guess_type(name)[0] or "application/octet-stream"
|
||||
body = bytearray()
|
||||
body.extend(f"--{boundary}\r\n".encode())
|
||||
body.extend(f'Content-Disposition: form-data; name="attachment"; filename="{name}"\r\n'.encode())
|
||||
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode())
|
||||
body.extend(path.read_bytes())
|
||||
body.extend(f"\r\n--{boundary}--\r\n".encode())
|
||||
status, response, _ = api_request(
|
||||
f"{release_api(repository)}/{release_id}/assets?"
|
||||
f"name={urllib.parse.quote(name, safe='')}",
|
||||
token, method="POST", raw=bytes(body),
|
||||
content_type=f"multipart/form-data; boundary={boundary}")
|
||||
require(status in (200, 201),
|
||||
f"uploading {name} returned HTTP {status}: {response[:200]!r}")
|
||||
try:
|
||||
asset = json.loads(response)
|
||||
except ValueError as error:
|
||||
raise ReleaseError(f"upload response for {name} is not JSON") from error
|
||||
require(isinstance(asset, dict) and asset.get("name") == name,
|
||||
f"upload response for {name} is malformed")
|
||||
return asset
|
||||
|
||||
|
||||
def publish_release(*, repository: str, tag: str, source_sha: str, body: str,
|
||||
prerelease: bool, assets: list[Path], token: str,
|
||||
reset_draft: bool = False) -> dict:
|
||||
require(token, "GITEA_PUBLISH_TOKEN is required to publish")
|
||||
require(assets, "no assets to publish")
|
||||
index_assets = [path for path in assets if path.name == INDEX]
|
||||
payload_assets = [path for path in assets if path.name != INDEX]
|
||||
require(len(index_assets) == 1, "exactly one release-evidence.json is required")
|
||||
ordered = payload_assets + index_assets
|
||||
expected = [{"name": path.name, "size": path.stat().st_size,
|
||||
"sha256": sha256_file(path)} for path in ordered]
|
||||
|
||||
existing = find_release(repository, tag, token)
|
||||
if existing is not None and not existing.get("draft"):
|
||||
require(existing.get("tag_name") == tag, f"tag {tag} does not identify its own release")
|
||||
require(existing.get("prerelease") == prerelease,
|
||||
f"published release {tag} has a different channel than the version string")
|
||||
if published_matches(repository, tag, expected, token):
|
||||
return {"status": "idempotent", "release_id": existing["id"], "tag": tag,
|
||||
"url": existing.get("html_url"), "assets": expected}
|
||||
raise ReleaseError(
|
||||
f"published release {tag} already exists with different bytes; refusing to overwrite")
|
||||
|
||||
if existing is not None and existing.get("draft"):
|
||||
if reset_draft:
|
||||
delete_release(repository, int(existing["id"]), token)
|
||||
existing = None
|
||||
else:
|
||||
for asset in existing.get("assets") or []:
|
||||
if asset.get("name") in {path.name for path in ordered}:
|
||||
raise ReleaseError(
|
||||
f"draft release {tag} already carries {asset.get('name')}; "
|
||||
"use --reset-draft to recreate the draft")
|
||||
|
||||
if existing is not None:
|
||||
release = patch_release(repository, int(existing["id"]), {
|
||||
"name": tag, "body": body, "draft": True,
|
||||
"prerelease": prerelease, "target_commitish": source_sha}, token)
|
||||
else:
|
||||
release = create_draft(repository, tag, body, source_sha, prerelease, token)
|
||||
|
||||
release_id = int(release["id"])
|
||||
remote = {asset.get("name") for asset in read_json(
|
||||
f"{release_api(repository)}/{release_id}/assets", token)}
|
||||
for path in ordered:
|
||||
if path.name in remote:
|
||||
continue
|
||||
upload_asset(repository, release_id, path, token)
|
||||
|
||||
if not published_matches(repository, tag, expected, token):
|
||||
raise ReleaseError("draft release assets did not round-trip byte for byte")
|
||||
published = patch_release(repository, release_id, {
|
||||
"draft": False, "prerelease": prerelease, "name": tag, "body": body}, token)
|
||||
require(published.get("draft") is False, "release remained a draft after publishing")
|
||||
if not published_matches(repository, tag, expected, token):
|
||||
raise ReleaseError("published release assets did not round-trip byte for byte")
|
||||
final = find_release(repository, tag, token)
|
||||
require(final is not None and final.get("draft") is False,
|
||||
"published release cannot be re-read")
|
||||
return {"status": "published", "release_id": final["id"], "tag": tag,
|
||||
"url": final.get("html_url"), "assets": expected}
|
||||
|
||||
|
||||
def default_body(*, repository: str, component_id: str, kind: str, tag: str,
|
||||
source_sha: str, ci: dict, assets: list[dict], dependencies: list[dict]) -> str:
|
||||
lines = [
|
||||
f"Independent {kind} component release for `{component_id}` (`{repository}`) `{tag}`.",
|
||||
"",
|
||||
f"- Component: `{component_id}` ({kind})",
|
||||
f"- Source commit: `{source_sha}`",
|
||||
f"- Same-SHA component CI: {ci['url']}",
|
||||
"- Assets: " + ", ".join(
|
||||
f"`{item['name']}` ({item['size']} bytes, sha256 `{item['sha256']}`)"
|
||||
for item in assets),
|
||||
"- Tested dependencies: " + (
|
||||
", ".join(f"`{item['id']}@{item['source_sha'][:12]}`" for item in dependencies)
|
||||
or "none"),
|
||||
"",
|
||||
"This is a component release. Root recommendation/acceptance and consumer "
|
||||
"updates are separate facts tracked by the ecosystem reconcile flow; "
|
||||
"installing it does not grant permissions or update any runtime.",
|
||||
]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CLI
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def common_parser(parser: argparse.ArgumentParser) -> None:
|
||||
parser.add_argument("--root", default=".", help="component repository root")
|
||||
parser.add_argument("--repository", required=True, help="owner/name on the authoritative forge")
|
||||
parser.add_argument("--component-id", required=True)
|
||||
parser.add_argument("--kind", choices=sorted(KIND_SUFFIX), required=True)
|
||||
parser.add_argument("--allow", action="append", default=[], required=True,
|
||||
help="released path relative to the repository root (repeatable)")
|
||||
parser.add_argument("--source-sha", default=None,
|
||||
help="exact commit to release (default: HEAD)")
|
||||
parser.add_argument("--out-dir", default=None,
|
||||
help="output directory for the packaged assets")
|
||||
|
||||
|
||||
def resolve_source(root: Path, args) -> str:
|
||||
if args.source_sha:
|
||||
require(SHA_RE.fullmatch(args.source_sha) is not None,
|
||||
"source SHA must be 40 lowercase hex")
|
||||
require(commit_exists(root, args.source_sha),
|
||||
"source SHA is not a commit in this repository")
|
||||
return args.source_sha
|
||||
return resolved_head(root)
|
||||
|
||||
|
||||
def command_check(args) -> int:
|
||||
root = Path(args.root).resolve()
|
||||
source_sha = resolve_source(root, args)
|
||||
with tempfile.TemporaryDirectory(prefix="mq-release-check-") as temporary:
|
||||
result = package_assets(root, source_sha, args.repository, args.component_id,
|
||||
"0.0.0", args.kind, list(args.allow), Path(temporary))
|
||||
payload = {
|
||||
"status": "PASS",
|
||||
"component_id": args.component_id,
|
||||
"repository": args.repository,
|
||||
"kind": args.kind,
|
||||
"source_sha": source_sha,
|
||||
"artifact": {key: result[key] for key in ("name", "size", "sha256")},
|
||||
"files": result["files"],
|
||||
"released_paths": sorted(args.allow),
|
||||
}
|
||||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def command_publish(args) -> int:
|
||||
token = os.environ.get("GITEA_PUBLISH_TOKEN", "")
|
||||
require(token, "GITEA_PUBLISH_TOKEN is required to publish")
|
||||
require(args.tag, "publish requires --tag")
|
||||
version = validate_version(args.tag)
|
||||
prerelease = "-" in version
|
||||
root = Path(args.root).resolve()
|
||||
source_sha = resolve_source(root, args)
|
||||
require(resolved_head(root) == source_sha,
|
||||
"publish must run on the exact checked-out release commit")
|
||||
local_tag = subprocess.run(
|
||||
["git", "-C", str(root), "rev-parse", "-q", "--verify",
|
||||
f"refs/tags/{args.tag}^{{commit}}"], capture_output=True)
|
||||
if local_tag.returncode == 0:
|
||||
require(local_tag.stdout.decode().strip() == source_sha,
|
||||
f"local tag {args.tag} does not point at the released commit")
|
||||
remote_sha = remote_tag_commit(args.repository, args.tag, token)
|
||||
if remote_sha is not None:
|
||||
require(remote_sha == source_sha,
|
||||
f"remote tag {args.tag} points at {remote_sha}, not the released commit "
|
||||
f"{source_sha}; refusing to publish a mismatched release")
|
||||
dependencies = [parse_dependency(item) for item in args.dependency]
|
||||
|
||||
if args.out_dir:
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
return _publish(args, root, source_sha, version, prerelease, dependencies,
|
||||
out_dir, token)
|
||||
with tempfile.TemporaryDirectory(prefix="mq-release-") as temporary:
|
||||
return _publish(args, root, source_sha, version, prerelease, dependencies,
|
||||
Path(temporary), token)
|
||||
|
||||
|
||||
def _publish(args, root, source_sha, version, prerelease, dependencies, out_dir, token) -> int:
|
||||
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)
|
||||
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"])}],
|
||||
dependencies=dependencies)
|
||||
evidence_path = write_evidence(evidence, out_dir / INDEX)
|
||||
body = args.body or default_body(
|
||||
repository=args.repository, component_id=args.component_id, kind=args.kind,
|
||||
tag=args.tag, source_sha=source_sha, ci=ci, assets=evidence["assets"],
|
||||
dependencies=evidence["dependencies"])
|
||||
if args.note:
|
||||
body = body.rstrip("\n") + "\n\n" + "\n".join(f"- {note}" for note in args.note) + "\n"
|
||||
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,
|
||||
reset_draft=args.reset_draft)
|
||||
print(json.dumps({
|
||||
"status": result["status"],
|
||||
"repository": args.repository,
|
||||
"component_id": args.component_id,
|
||||
"tag": args.tag,
|
||||
"version": version,
|
||||
"channel": "prerelease" if prerelease else "stable",
|
||||
"source_sha": source_sha,
|
||||
"ci": ci,
|
||||
"url": result.get("url"),
|
||||
"assets": [{"name": item["name"], "size": item["size"],
|
||||
"sha256": item["sha256"]} for item in result["assets"]],
|
||||
"dependencies": evidence["dependencies"],
|
||||
}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
check = commands.add_parser(
|
||||
"check", help="package the exact commit twice and verify the artifact in CI")
|
||||
common_parser(check)
|
||||
|
||||
publish = commands.add_parser(
|
||||
"publish", help="package, evidence and publish one immutable Gitea release")
|
||||
common_parser(publish)
|
||||
publish.add_argument("--tag", required=True, help="release tag, e.g. v0.1.0")
|
||||
publish.add_argument("--dependency", action="append", default=[],
|
||||
help="tested dependency: id=<id>,source_sha=<sha>[,asset_sha256=<digest>]")
|
||||
publish.add_argument("--body", default="", help="release body (default: generated)")
|
||||
publish.add_argument("--note", action="append", default=[],
|
||||
help="extra fact appended to the generated release body (repeatable)")
|
||||
publish.add_argument("--reset-draft", action="store_true",
|
||||
help="delete an interrupted draft release before recreating it")
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if args.command == "check":
|
||||
return command_check(args)
|
||||
return command_publish(args)
|
||||
except ReleaseError as error:
|
||||
print(f"component-release: FAIL: {error}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,42 @@
|
||||
# Protected component publish lane: tag events only.
|
||||
#
|
||||
# TEMPLATE - copy into a component repository, replace every <...> placeholder
|
||||
# and keep the pinned root commit / release.py sha256 in sync with the reviewed
|
||||
# root copy (`scripts/component-release/`). Ordinary push/PR never receives the
|
||||
# publish token; only this protected tag workflow does.
|
||||
#
|
||||
# Extension releases additionally need one --dependency per actual runtime
|
||||
# dependency (the root catalog design inputs are not test dependencies; see
|
||||
# marqdo#99 for that boundary). stdlib releases use the cli dependency below.
|
||||
#
|
||||
# The root reconcile flow verifies the published release independently
|
||||
# (tag -> full SHA, same-SHA Woodpecker CI, byte-for-byte asset readback and
|
||||
# dependency identity); this lane is the producer, not the authority.
|
||||
when:
|
||||
event: [tag]
|
||||
|
||||
steps:
|
||||
publish:
|
||||
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.7@sha256:<shell-image-digest>
|
||||
environment:
|
||||
GITEA_PUBLISH_TOKEN:
|
||||
from_secret: gitea_publish_token
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
test -n "${CI_COMMIT_TAG:?publish requires a tag event}"
|
||||
kit=$(mktemp -d)
|
||||
trap 'rm -rf "$kit"' EXIT
|
||||
base="https://git.cflmy.cn/cflmy/marqdo/raw/commit/<ROOT_COMMIT>"
|
||||
curl -fsSL --retry 3 "$base/scripts/component-release/release.py" -o "$kit/release.py"
|
||||
echo "<RELEASE_PY_SHA256> $kit/release.py" | sha256sum -c -
|
||||
exec python3 "$kit/release.py" publish \
|
||||
--repository "$CI_REPO" \
|
||||
--component-id <component-id> \
|
||||
--kind <stdlib|extension> \
|
||||
--allow modules \
|
||||
--allow README.md \
|
||||
--tag "$CI_COMMIT_TAG" \
|
||||
--source-sha "$CI_COMMIT_SHA" \
|
||||
--dependency "id=cli,source_sha=<cli-source-sha>,asset_sha256=<cli-archive-sha256>" \
|
||||
--note "Tested by the same-SHA Woodpecker component lane with the shared marqdo-ci-shell:3.0.0-rc.6 image."
|
||||
@@ -0,0 +1,331 @@
|
||||
"""Contract tests for the single component-release implementation (marqdo#96 M1).
|
||||
|
||||
The kit is exercised through its real packaging path with temporary Git
|
||||
repositories. Network paths are replaced by fakes; the deterministic archive,
|
||||
evidence schema and publish transaction ordering are real code.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPT = ROOT / "scripts" / "component-release" / "release.py"
|
||||
SPEC = importlib.util.spec_from_file_location("component_release", SCRIPT)
|
||||
kit = importlib.util.module_from_spec(SPEC)
|
||||
sys.modules["component_release"] = kit
|
||||
SPEC.loader.exec_module(kit)
|
||||
|
||||
GIT_ENV = {
|
||||
"GIT_AUTHOR_NAME": "test",
|
||||
"GIT_AUTHOR_EMAIL": "test@example.invalid",
|
||||
"GIT_COMMITTER_NAME": "test",
|
||||
"GIT_COMMITTER_EMAIL": "test@example.invalid",
|
||||
}
|
||||
|
||||
|
||||
def git(cwd, *args):
|
||||
env = os.environ.copy()
|
||||
env.update(GIT_ENV)
|
||||
result = subprocess.run(["git", "-C", str(cwd), *args], capture_output=True, env=env)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError(result.stderr.decode(errors="replace"))
|
||||
return result.stdout.decode().strip()
|
||||
|
||||
|
||||
def write(path, data):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data if isinstance(data, bytes) else data.encode())
|
||||
|
||||
|
||||
def repository(tmp: Path) -> str:
|
||||
repo = tmp / "repo"
|
||||
repo.mkdir()
|
||||
git(repo, "init", "-q")
|
||||
write(repo / "modules" / "text.mq.md", "# text\n")
|
||||
write(repo / "modules" / "text" / "utf8.mq.md", "# utf8\n")
|
||||
write(repo / "tests" / "text.mq.md", "# dev-only test\n")
|
||||
write(repo / "README.md", "# component\n")
|
||||
write(repo / "scripts" / "test.sh", "#!/bin/sh\n")
|
||||
git(repo, "add", "-A")
|
||||
git(repo, "commit", "-q", "-m", "fixture")
|
||||
return git(repo, "rev-parse", "HEAD")
|
||||
|
||||
|
||||
class PackageTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.tmp = Path(self._tmp.name)
|
||||
self.repo = self.tmp / "repo"
|
||||
self.sha = repository(self.tmp)
|
||||
|
||||
def tearDown(self):
|
||||
self._tmp.cleanup()
|
||||
|
||||
def package(self, out: str, allow=("modules", "README.md")):
|
||||
target = self.tmp / out
|
||||
target.mkdir()
|
||||
return kit.package_assets(self.repo, self.sha, "cflmy/marqdo-std-text",
|
||||
"std-text", "0.1.0", "stdlib", list(allow), target)
|
||||
|
||||
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")
|
||||
|
||||
def test_archive_contains_only_released_paths(self):
|
||||
result = self.package("out")
|
||||
with tarfile.open(result["archive"], "r:gz") as archive:
|
||||
names = sorted(member.name for member in archive.getmembers())
|
||||
self.assertEqual(names, [
|
||||
"marqdo-std-text-0.1.0/README.md",
|
||||
"marqdo-std-text-0.1.0/modules/text.mq.md",
|
||||
"marqdo-std-text-0.1.0/modules/text/utf8.mq.md",
|
||||
])
|
||||
self.assertEqual(result["files"], 3)
|
||||
self.assertNotIn("tests/text.mq.md", " ".join(names))
|
||||
self.assertNotIn(".git", " ".join(names))
|
||||
|
||||
def test_archive_ignores_git_export_attributes(self):
|
||||
write(self.repo / ".gitattributes", "modules export-ignore\n")
|
||||
git(self.repo, "add", "-A")
|
||||
git(self.repo, "commit", "-q", "-m", "attributes")
|
||||
sha = git(self.repo, "rev-parse", "HEAD")
|
||||
out = self.tmp / "attrout"
|
||||
out.mkdir()
|
||||
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:
|
||||
names = sorted(member.name for member in archive.getmembers())
|
||||
self.assertIn("marqdo-std-text-0.1.0/modules/text/utf8.mq.md", names)
|
||||
|
||||
def test_refuses_case_and_nfc_collisions(self):
|
||||
write(self.repo / "modules" / "Case.mq.md", "a")
|
||||
write(self.repo / "modules" / "case.mq.md", "b")
|
||||
git(self.repo, "add", "-A")
|
||||
git(self.repo, "commit", "-q", "-m", "collision")
|
||||
sha = git(self.repo, "rev-parse", "HEAD")
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
kit.released_files(self.repo, sha, ["modules"])
|
||||
|
||||
def test_refuses_backslash_member(self):
|
||||
payload = io.BytesIO()
|
||||
with tarfile.open(fileobj=payload, mode="w:gz") as archive:
|
||||
info = tarfile.TarInfo("prefix/modules/..\\..\\escape.mq.md")
|
||||
body = b"x"
|
||||
info.size = len(body)
|
||||
archive.addfile(info, io.BytesIO(body))
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
kit.check_archive(payload.getvalue(), "prefix", [("modules/a.mq.md", b"x")])
|
||||
|
||||
def test_refuses_unsafe_or_empty_paths(self):
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
self.package("bad", allow=("../escape",))
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
self.package("bad2", allow=("missing",))
|
||||
|
||||
def test_refuses_archive_member_outside_released_tree(self):
|
||||
payload = io.BytesIO()
|
||||
with tarfile.open(fileobj=payload, mode="w:gz") as archive:
|
||||
info = tarfile.TarInfo("prefix/tests/secret.mq.md")
|
||||
body = b"x"
|
||||
info.size = len(body)
|
||||
archive.addfile(info, io.BytesIO(body))
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
kit.check_archive(payload.getvalue(), "prefix", [("modules/a.mq.md", b"x")])
|
||||
|
||||
|
||||
class IdentityTests(unittest.TestCase):
|
||||
def test_version_and_channel(self):
|
||||
self.assertEqual(kit.validate_version("v0.1.0"), "0.1.0")
|
||||
self.assertEqual(kit.validate_version("v0.1.0-rc.1"), "0.1.0-rc.1")
|
||||
for tag in ("0.1.0", "v1", "v1.2", "v01.2.3", "v1.2.3-"):
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
kit.validate_version(tag)
|
||||
|
||||
def test_dependency_spec(self):
|
||||
self.assertEqual(
|
||||
kit.parse_dependency("id=cli,source_sha=" + "a" * 40),
|
||||
{"id": "cli", "source_sha": "a" * 40},
|
||||
)
|
||||
self.assertEqual(
|
||||
kit.parse_dependency("id=cli,source_sha=" + "a" * 40 + ",asset_sha256=" + "b" * 64),
|
||||
{"id": "cli", "source_sha": "a" * 40, "asset_sha256": "b" * 64},
|
||||
)
|
||||
for raw in ("cli", "id=cli", "id=cli,source_sha=" + "A" * 40,
|
||||
"id=cli,source_sha=" + "a" * 40 + ",asset_sha256=short",
|
||||
"id=cli,id=cli,source_sha=" + "a" * 40,
|
||||
"id=cli,source_sha=" + "a" * 40 + ",unknown=1"):
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
kit.parse_dependency(raw)
|
||||
|
||||
|
||||
class EvidenceTests(unittest.TestCase):
|
||||
ASSETS = [{"name": "a.tar.gz", "size": 3, "sha256": "a" * 64}]
|
||||
|
||||
def evidence(self, **overrides):
|
||||
data = dict(
|
||||
repository="cflmy/marqdo-std-text",
|
||||
component_id="std-text",
|
||||
tag="v0.1.0",
|
||||
source_sha="b" * 40,
|
||||
ci={"pipeline_number": 1, "url": "u", "source_sha": "b" * 40},
|
||||
assets=self.ASSETS,
|
||||
dependencies=[{"id": "cli", "source_sha": "c" * 40}],
|
||||
)
|
||||
data.update(overrides)
|
||||
return kit.build_evidence(**data)
|
||||
|
||||
def test_shape(self):
|
||||
evidence = self.evidence()
|
||||
self.assertEqual(evidence["assets"], [
|
||||
{"name": "a.tar.gz", "size": 3, "target": "source", "sha256": "a" * 64}])
|
||||
self.assertEqual(evidence["dependencies"], [{"id": "cli", "source_sha": "c" * 40}])
|
||||
|
||||
def test_guards(self):
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
self.evidence(assets=[{"name": "release-evidence.json", "size": 3,
|
||||
"sha256": "a" * 64, "target": "source"}])
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
self.evidence(dependencies=[{"id": "std-text", "source_sha": "c" * 40}])
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
self.evidence(dependencies=[{"id": "cli", "source_sha": "c" * 40},
|
||||
{"id": "cli", "source_sha": "d" * 40}])
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
self.evidence(assets=[])
|
||||
|
||||
|
||||
class PublishTransactionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.tmp = Path(self._tmp.name)
|
||||
self.archive = self.tmp / "a.tar.gz"
|
||||
self.archive.write_bytes(b"payload")
|
||||
self.checksum = self.tmp / "a.tar.gz.sha256"
|
||||
self.checksum.write_text("digest a.tar.gz\n")
|
||||
self.index = self.tmp / "release-evidence.json"
|
||||
self.index.write_text("{}\n")
|
||||
self.assets = [self.archive, self.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"}
|
||||
|
||||
def tearDown(self):
|
||||
self._tmp.cleanup()
|
||||
|
||||
def publish(self):
|
||||
return kit.publish_release(
|
||||
repository="cflmy/marqdo-std-text", tag="v0.1.0",
|
||||
source_sha="a" * 40, body="body", prerelease=False,
|
||||
assets=self.assets, token="token")
|
||||
|
||||
def test_identical_published_release_is_idempotent(self):
|
||||
with patch.object(kit, "find_release", return_value=self.release), \
|
||||
patch.object(kit, "published_matches", return_value=True):
|
||||
result = self.publish()
|
||||
self.assertEqual(result["status"], "idempotent")
|
||||
self.assertEqual(result["release_id"], 7)
|
||||
|
||||
def test_different_published_bytes_are_refused(self):
|
||||
with patch.object(kit, "find_release", return_value=self.release), \
|
||||
patch.object(kit, "published_matches", return_value=False):
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
self.publish()
|
||||
|
||||
def test_evidence_is_uploaded_last_and_published(self):
|
||||
uploaded = []
|
||||
|
||||
def fake_upload(repository, release_id, path, token):
|
||||
uploaded.append(path.name)
|
||||
return {"name": path.name}
|
||||
|
||||
with patch.object(kit, "find_release", return_value=None), \
|
||||
patch.object(kit, "create_draft", return_value={"id": 8}), \
|
||||
patch.object(kit, "read_json", return_value=[]), \
|
||||
patch.object(kit, "upload_asset", side_effect=fake_upload), \
|
||||
patch.object(kit, "published_matches", return_value=True), \
|
||||
patch.object(kit, "patch_release",
|
||||
return_value={"id": 8, "draft": False}), \
|
||||
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"])
|
||||
|
||||
|
||||
class CiDiscoveryTests(unittest.TestCase):
|
||||
SHA = "a" * 40
|
||||
|
||||
def listing(self, **overrides):
|
||||
pipeline = {"number": 12, "commit": self.SHA, "status": "success", "event": "push"}
|
||||
pipeline.update(overrides)
|
||||
return [pipeline]
|
||||
|
||||
def test_selects_lowest_successful_pipeline_deterministically(self):
|
||||
lane = [{"number": 41, "commit": self.SHA, "status": "success", "event": "manual"},
|
||||
{"number": 39, "commit": self.SHA, "status": "success", "event": "push"},
|
||||
{"number": 40, "commit": self.SHA, "status": "success", "event": "push"}]
|
||||
detail = {"number": 39, "commit": self.SHA, "status": "success", "workflows": [
|
||||
{"name": "ci", "state": "success",
|
||||
"children": [{"type": "commands", "state": "success"}]}]}
|
||||
with patch.object(kit, "ci_repository", return_value=8), \
|
||||
patch.object(kit, "read_json", side_effect=[lane, detail]):
|
||||
evidence = kit.discover_ci("cflmy/marqdo-std-text", self.SHA, "ci", "")
|
||||
self.assertEqual(evidence["pipeline_number"], 39)
|
||||
|
||||
def test_requires_successful_same_sha_ci(self):
|
||||
with patch.object(kit, "ci_repository", return_value=8), \
|
||||
patch.object(kit, "read_json", return_value=self.listing()):
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
kit.discover_ci("cflmy/marqdo-std-text", "b" * 40, "ci", "")
|
||||
with patch.object(kit, "ci_repository", return_value=8), \
|
||||
patch.object(kit, "read_json", return_value=self.listing(event="tag")):
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
kit.discover_ci("cflmy/marqdo-std-text", self.SHA, "ci", "")
|
||||
|
||||
def test_successful_ci_evidence(self):
|
||||
detail = {"number": 12, "commit": self.SHA, "status": "success", "workflows": [
|
||||
{"name": "ci", "state": "success",
|
||||
"children": [{"type": "commands", "state": "success"}]}]}
|
||||
with patch.object(kit, "ci_repository", return_value=8), \
|
||||
patch.object(kit, "read_json", side_effect=[self.listing(), detail]):
|
||||
evidence = kit.discover_ci("cflmy/marqdo-std-text", self.SHA, "ci", "")
|
||||
self.assertEqual(evidence, {
|
||||
"pipeline_number": 12,
|
||||
"url": f"{kit.CI}/repos/8/pipeline/12",
|
||||
"source_sha": self.SHA,
|
||||
})
|
||||
|
||||
def test_workflow_must_be_successful(self):
|
||||
detail = {"number": 12, "commit": self.SHA, "status": "success", "workflows": [
|
||||
{"name": "ci", "state": "failure",
|
||||
"children": [{"type": "commands", "state": "failure"}]}]}
|
||||
with patch.object(kit, "ci_repository", return_value=8), \
|
||||
patch.object(kit, "read_json", side_effect=[self.listing(), detail]):
|
||||
with self.assertRaises(kit.ReleaseError):
|
||||
kit.discover_ci("cflmy/marqdo-std-text", self.SHA, "ci", "")
|
||||
|
||||
|
||||
class RemoteTagTests(unittest.TestCase):
|
||||
def test_remote_tag_identity(self):
|
||||
body = json.dumps({"name": "v0.1.0", "commit": {"sha": "b" * 40}}).encode()
|
||||
with patch.object(kit, "api_request", return_value=(200, body, {})):
|
||||
self.assertEqual(kit.remote_tag_commit("cflmy/marqdo-std-text", "v0.1.0", "t"),
|
||||
"b" * 40)
|
||||
with patch.object(kit, "api_request", return_value=(404, b"{}", {})):
|
||||
self.assertIsNone(kit.remote_tag_commit("cflmy/marqdo-std-text", "v0.1.0", "t"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user