Author SHA1 Message Date
cflmy ff8bb2bbe2 ci: protected publish workflow (#10)
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
ci: protected publish workflow (#10)
2026-11-27 19:23:32 +08:00
cflmy 0bbaac86e4 ci: add protected component publish workflow and immutable release helpers
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Vendor the root component-release helpers, add source packaging plus
release-evidence, and split publish (tag/manual) from notify (release event).
2026-11-27 19:23:05 +08:00
14 changed files with 948 additions and 426 deletions

No files matched your search

+1
View File
@@ -14,3 +14,4 @@
# Python tooling cache # Python tooling cache
__pycache__/ __pycache__/
*.pyc *.pyc
dist/
+1 -15
View File
@@ -4,9 +4,7 @@
# released CLI/Bundle (`MARQDO_BIN`, `MARQDO_STDLIB_DIR` preset); the lane only # released CLI/Bundle (`MARQDO_BIN`, `MARQDO_STDLIB_DIR` preset); the lane only
# runs this repository's own checks. No per-run rustup/apt/CLI download. # runs this repository's own checks. No per-run rustup/apt/CLI download.
when: when:
- event: [pull_request, manual] event: [push, pull_request, manual]
- event: push
branch: master
steps: steps:
test: test:
@@ -18,20 +16,8 @@ steps:
MARQDO_TOOL_HOME: /tmp/marqdo-tool-home MARQDO_TOOL_HOME: /tmp/marqdo-tool-home
commands: commands:
- python3 tools/ci/test_release_metadata.py - python3 tools/ci/test_release_metadata.py
- python3 tools/ci/test_publish_gitea.py
- cargo fmt --all -- --check - cargo fmt --all -- --check
- cargo clippy --workspace --all-targets --locked -- -D warnings - cargo clippy --workspace --all-targets --locked -- -D warnings
- cargo test --workspace --locked - cargo test --workspace --locked
- cargo build --release --locked - cargo build --release --locked
- target/release/marqdo-knowledge --help - target/release/marqdo-knowledge --help
minimum-rust:
image: rust:1.89-bookworm
when:
- event: manual
- event: [push, pull_request]
path:
include: ['**/*.rs', '**/Cargo.toml', Cargo.lock, '.cargo/**', '.woodpecker/**']
on_empty: true
commands:
- cargo check --locked --workspace --all-targets
+33 -4
View File
@@ -1,10 +1,10 @@
# Tag-only compatibility and release artifact validation for marqdo-knowledge. # Woodpecker CI pipeline for marqdo-knowledge.
# #
# Mirrors the local lanes in scripts/ci.sh and the GitHub workflow. The core CLI # Mirrors the local lanes in scripts/ci.sh and the GitHub workflow. The core CLI
# is built from the pinned marqdo-cli commit because the Analysis contract is an # is built from the pinned marqdo-cli commit because the Analysis contract is an
# external boundary; integration tests always run against that real binary. # external boundary; integration tests always run against that real binary.
when: when:
event: [tag] event: [push, pull_request, tag]
steps: steps:
test: test:
@@ -44,14 +44,43 @@ steps:
release: release:
depends_on: [test, minimum-rust, core-analysis] depends_on: [test, minimum-rust, core-analysis]
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5 when:
event: [tag]
image: rust:1.100-bookworm
environment:
GITEA_TOKEN:
from_secret: GITEA_TOKEN
commands: commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates git build-essential python3
- | - |
set -eu set -eu
core_sha=4bbefc92449ee480c8a2c89b0308feb4cda8d0e7
work=$(mktemp -d)
git clone --quiet https://git.cflmy.cn/cflmy/marqdo-cli.git "$work/core"
( cd "$work/core" && git checkout --quiet "$core_sha" \
&& cargo build --release --locked -p marqdo-cli )
export MARQDO_BIN="$work/core/target/release/marqdo"
cargo build --release --locked cargo build --release --locked
version="$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)" version="$(cargo metadata --no-deps --format-version 1 --offline \
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-knowledge"))')"
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version" python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version"
python3 tools/release/smoke.py --archive "dist/marqdo-knowledge-$version-x86_64-unknown-linux-gnu.tar.gz" --evidence-out dist/smoke-evidence.json python3 tools/release/smoke.py --archive "dist/marqdo-knowledge-$version-x86_64-unknown-linux-gnu.tar.gz" --evidence-out dist/smoke-evidence.json
if [ -z "${GITEA_TOKEN:-}" ]; then
echo "publish: skipped (this Woodpecker instance did not inject the GITEA_TOKEN secret); the deterministic archive and smoke evidence above are the CI evidence. Publish the prerelease locally from the same tagged SHA with tools/release/publish-gitea.py."
else
python3 tools/release/publish-gitea.py \
--tag "$CI_COMMIT_TAG" \
--archive "dist/marqdo-knowledge-$version-x86_64-unknown-linux-gnu.tar.gz" \
--files dist/RELEASE_INFO.json dist/FILES.sha256 dist/smoke-evidence.json \
--body-file "docs/releases/$version.md"
fi
- cat dist/RELEASE_INFO.json - cat dist/RELEASE_INFO.json
- cat dist/*.tar.gz.sha256 - cat dist/*.tar.gz.sha256
- cat dist/smoke-evidence.json - cat dist/smoke-evidence.json
- |
if [ -f dist/gitea-release-evidence.json ]; then
cat dist/gitea-release-evidence.json
else
echo "publish: skipped (no GITEA_TOKEN secret injection on this instance)"
fi
+40
View File
@@ -0,0 +1,40 @@
when:
- event: [tag, manual]
steps:
publish:
image: git.cflmy.cn/cflmy/marqdo-ci-rust:3.0.0-rc.5
environment:
GITEA_PUBLISH_TOKEN:
from_secret: gitea_publish_token
WOODPECKER_NOTIFY_TOKEN:
from_secret: woodpecker_notify_token
commands:
- |
set -eu
test -n "${GITEA_PUBLISH_TOKEN:?}"
test -n "${CI_COMMIT_TAG:?}"
export SOURCE_SHA="${CI_COMMIT_SHA}"
export VERSION="${CI_COMMIT_TAG#v}"
scripts/ci.sh
scripts/package-release.sh
# Attach release-evidence then publish immutably.
ARCHIVE=$(ls dist/marqdo-knowledge-*.tar.gz | head -1)
python3 scripts/release/write_evidence.py \
--component-id knowledge \
--repository cflmy/marqdo-knowledge \
--tag "${CI_COMMIT_TAG}" \
--source-sha "${SOURCE_SHA}" \
--asset "$ARCHIVE" \
--asset "${ARCHIVE}.sha256" \
--out dist/release-evidence.json
python3 scripts/release/publish_gitea.py \
--repo cflmy/marqdo-knowledge \
--tag "${CI_COMMIT_TAG}" \
--target "${SOURCE_SHA}" \
--prerelease \
--body-file "docs/releases/${VERSION}.md" \
--asset "$ARCHIVE" \
--asset "${ARCHIVE}.sha256" \
--asset dist/release-evidence.json \
--evidence-out dist/gitea-publish-result.json
+6 -8
View File
@@ -1,7 +1,3 @@
# Fast-path notification: a completed Gitea release asks the root reconcile
# workflow to check it. The payload is only a hint; the root reconcile verifies
# the release/assets from the authoritative Gitea API. A lost call is recovered
# by the root `release-reconcile` cron.
when: when:
event: [release] event: [release]
@@ -9,10 +5,12 @@ steps:
notify: notify:
image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5 image: git.cflmy.cn/cflmy/marqdo-ci-shell:3.0.0-rc.5
environment: environment:
WOODPECKER_TOKEN: WOODPECKER_NOTIFY_TOKEN:
from_secret: woodpecker_token from_secret: woodpecker_notify_token
commands: commands:
- | - |
set -eu set -eu
test -n "${WOODPECKER_TOKEN:?woodpecker_token secret missing}" test -n "${WOODPECKER_NOTIFY_TOKEN:?woodpecker_notify_token secret missing}"
curl -fsS -X POST -H "Authorization: Bearer $WOODPECKER_TOKEN" -H "Content-Type: application/json" -d '{"branch":"main","workflow":"reconcile"}' https://ci.cflmy.cn/api/repos/6/pipelines python3 scripts/release/notify_root.py \
--hint-component "knowledge" \
--hint-tag "${CI_COMMIT_TAG:-}"
+21 -30
View File
@@ -1,14 +1,14 @@
# CI/CD for marqdo-knowledge # CI/CD for marqdo-knowledge
Ordinary Woodpecker checks use the existing shared image and its released CLI. The pipeline mirrors the upstream `marqdo-cli` approach: one fast Rust contract
Pull requests, default-branch pushes and manual runs share one workflow. Rust lane, one minimum-Rust lane, one lane that builds the pinned core CLI and runs
source, manifest and CI changes also check the minimum supported Rust. Release the real-Analysis integration tests, and a tag-only release lane that builds a
tags check the pinned historical core and produce the package evidence. deterministic archive, cold-installs it through a real `marqdo` binary and
publishes the checksum.
Configurations: Configurations:
- `.woodpecker/ci.yml` runs ordinary component checks. `.woodpecker/main.yml` - `.woodpecker/main.yml` — self-hosted Woodpecker (push, pull_request, tag).
runs release-tag compatibility checks, packaging and cold installation.
- `.github/workflows/ci.yml` — GitHub Actions mirror (push, pull_request, tag). - `.github/workflows/ci.yml` — GitHub Actions mirror (push, pull_request, tag).
- `scripts/ci.sh` — the same lanes locally (`test`, `minimum`, `core`, - `scripts/ci.sh` — the same lanes locally (`test`, `minimum`, `core`,
`release`, `all`). `release`, `all`).
@@ -23,11 +23,12 @@ Configurations:
## Pinned core boundary ## Pinned core boundary
Ordinary CI uses the official `3.0.0-rc.5` CLI from the shared image. The tag The core CLI is an external contract. CI does not use an already-installed
compatibility step also builds the existing `3.0.0-rc.4` core pin `marqdo`: it builds `cflmy/marqdo-cli` at
`4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` and runs the real-Analysis tests. `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` (`3.0.0-rc.4`, Analysis revision 3)
Changing the historical pin requires rerunning the tamper fixtures and and exports `MARQDO_TEST_BIN` for `tests/core_cli.rs` and
recording the new Analysis fixture evidence. `tests/compile.rs`. Changing the pin requires re-running the tamper fixtures and
recording a new Analysis fixture artifact.
## Gates executed by CI ## Gates executed by CI
@@ -42,26 +43,16 @@ recording the new Analysis fixture evidence.
| release build | `cargo build --release --locked` | | release build | `cargo build --release --locked` |
| deterministic package + cold install | `python3 tools/release/package.py ... && python3 tools/release/smoke.py --archive ...` | | deterministic package + cold install | `python3 tools/release/package.py ... && python3 tools/release/smoke.py --archive ...` |
## Reviewed forge publication ## Forge publication from the tag lane
The tag lane prepares assets without credentials. From the clean reviewed tag, The tag-only release lane builds and smoke-tests the deterministic archive and
select the successful default-branch `ci` pipeline for that exact commit. Keep then invokes `tools/release/publish-gitea.py` when `GITEA_TOKEN` is present in
the archive, its checksum, `RELEASE_INFO.json`, `FILES.sha256`, and the step environment. If the Woodpecker instance does not inject repository
`smoke-evidence.json` together. The smoke test verifies and records the released secrets into tag pipelines, the lane prints a `publish: skipped` notice, keeps
CLI identity used for the cold installation. the build/smoke evidence, and the prerelease is published from the same tagged
SHA by a reviewed local invocation with the token read from a local-only
```sh environment file. Never put the token in the repository, pipeline config, logs
python3 tools/release/publish-gitea.py --prepare \ or documentation.
--tag "$release_tag" --pipeline "$component_pipeline" --archive "$archive"
```
The maintainer verifies Gitea tag protection as part of release approval. The
approved publisher runs the same command with `--body-file` in place of
`--prepare` and a `GITEA_TOKEN` from the dedicated publisher account. The tool
checks the protected default branch and exact tag, resumes matching drafts,
verifies the bytes on the forge and publishes only a complete inventory. A
matching public release is idempotent. A changed asset blocks the operation and
needs a new release decision.
## Not gated by CI (explicit non-claims) ## Not gated by CI (explicit non-claims)
+9
View File
@@ -0,0 +1,9 @@
# Vendored from marqdo scripts/component-release
#
# Do not edit in place across repositories. Change the root copy, re-test,
# then re-run install-vendor.sh and record the hashes below.
#
# package_source.py sha256=cb18c2f7fbe807f55d49e2cf77720f0d3e57d355177d2b127ac09e119f90c6ae
# write_evidence.py sha256=bb194bfd251e39308bc1dd53f46fd9efac181082ea43f668484b067d9e54acfc
# publish_gitea.py sha256=a21a84146d9ea826eb8d0632a18a991b0c39f17005d83bd988c92fc608f67523
# notify_root.py sha256=8eee83eb2bb31b99d93981f2a97fc2f0f9a486cc3c5c072f7dc12cfb63baf025
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Ask the root Marqdo reconcile workflow to scan after a release.
The payload is only a hint. Correctness comes from the root
`scripts/reconcile-releases.py` reading authoritative Gitea releases.
Lost notifications are recovered by the root `release-reconcile` cron.
"""
from __future__ import annotations
import argparse
import json
import os
import random
import sys
import time
import urllib.error
import urllib.request
DEFAULT_URL = "https://ci.cflmy.cn/api/repos/6/pipelines"
DEFAULT_BODY = {"branch": "main", "workflow": "reconcile"}
class NotifyError(Exception):
pass
def token() -> str:
value = (
os.environ.get("WOODPECKER_NOTIFY_TOKEN")
or os.environ.get("WOODPECKER_TOKEN")
or os.environ.get("woodpecker_token")
)
if not value:
raise NotifyError("WOODPECKER_NOTIFY_TOKEN (or WOODPECKER_TOKEN) is not set")
return value
def trigger(url: str, token_value: str, body: dict, attempts: int = 3) -> dict:
payload = json.dumps(body).encode()
last_error: Exception | None = None
for attempt in range(1, attempts + 1):
request = urllib.request.Request(
url,
data=payload,
method="POST",
headers={
"Authorization": f"Bearer {token_value}",
"Content-Type": "application/json",
"Accept": "application/json",
},
)
try:
with urllib.request.urlopen(request, timeout=60) as response:
raw = response.read()
decoded = json.loads(raw) if raw else {}
return {
"status": "triggered",
"http_status": response.status,
"pipeline_id": decoded.get("id"),
"pipeline_number": decoded.get("number"),
"attempt": attempt,
}
except urllib.error.HTTPError as error:
# Auth/permission failures must not retry forever.
if error.code in (401, 403, 404):
raise NotifyError(f"trigger rejected with HTTP {error.code}") from error
last_error = error
except urllib.error.URLError as error:
last_error = error
if attempt < attempts:
delay = (2 ** (attempt - 1)) + random.uniform(0, 0.5)
time.sleep(delay)
raise NotifyError(f"trigger failed after {attempts} attempts: {last_error}")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", default=os.environ.get("MARQDO_RECONCILE_TRIGGER_URL", DEFAULT_URL))
parser.add_argument("--branch", default="main")
parser.add_argument("--workflow", default="reconcile")
parser.add_argument("--hint-component", default="")
parser.add_argument("--hint-tag", default="")
parser.add_argument("--attempts", type=int, default=3)
args = parser.parse_args(argv)
body = {"branch": args.branch, "workflow": args.workflow}
# Hints are informational only; the root reconcile never trusts them as commands.
if args.hint_component or args.hint_tag:
body["variables"] = {
"MARQDO_RELEASE_HINT_COMPONENT": args.hint_component,
"MARQDO_RELEASE_HINT_TAG": args.hint_tag,
}
try:
result = trigger(args.url, token(), body, attempts=max(1, args.attempts))
except NotifyError as error:
print(f"notify_root: FAIL: {error}", file=sys.stderr)
return 1
print(json.dumps(result, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+145
View File
@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""Build a deterministic source archive for a Marqdo component release.
Only allowlisted relative paths are included. The archive uses fixed mtime,
uid/gid, and sorted member names so the same tree always yields the same
sha256. Output is written under an isolated directory (default: dist/).
"""
from __future__ import annotations
import argparse
import hashlib
import io
import os
import sys
import tarfile
from pathlib import Path
DEFAULT_ALLOWLIST = (
"modules",
"index.mq.md",
"marqdo.yaml",
"LICENSE",
"README.md",
)
FIXED_MTIME = 0
EVIDENCE_NAME = "release-evidence.json"
class PackageError(Exception):
pass
def fail(message: str) -> None:
raise PackageError(message)
def is_safe_relative(path: str) -> bool:
if not path or path.startswith("/") or path.startswith("\\"):
return False
parts = Path(path).parts
return not any(part in (".", "..") for part in parts)
def collect_files(root: Path, allowlist: list[str]) -> list[tuple[str, Path]]:
selected: dict[str, Path] = {}
for entry in allowlist:
if not is_safe_relative(entry):
fail(f"unsafe allowlist entry: {entry!r}")
target = root / entry
if not target.exists():
continue
if target.is_file():
selected[entry.replace("\\", "/")] = target
continue
if not target.is_dir():
fail(f"allowlist entry is not a regular file or directory: {entry}")
for path in sorted(target.rglob("*")):
if not path.is_file():
continue
if path.is_symlink():
fail(f"symlinks are not publishable: {path.relative_to(root)}")
relative = path.relative_to(root).as_posix()
if not is_safe_relative(relative):
fail(f"unsafe relative path: {relative}")
selected[relative] = path
if not selected:
fail("allowlist matched no files")
return sorted(selected.items(), key=lambda item: item[0])
def archive_bytes(files: list[tuple[str, Path]]) -> bytes:
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode="w:gz", format=tarfile.PAX_FORMAT, compresslevel=9) as archive:
for relative, path in files:
data = path.read_bytes()
info = tarfile.TarInfo(name=relative)
info.size = len(data)
info.mtime = FIXED_MTIME
info.uid = 0
info.gid = 0
info.uname = ""
info.gname = ""
info.mode = 0o644
archive.addfile(info, io.BytesIO(data))
return buffer.getvalue()
def write_outputs(
root: Path,
out_dir: Path,
component_id: str,
version: str,
allowlist: list[str],
) -> dict:
files = collect_files(root, allowlist)
payload = archive_bytes(files)
digest = hashlib.sha256(payload).hexdigest()
out_dir.mkdir(parents=True, exist_ok=True)
archive_name = f"marqdo-{component_id}-{version}-source.tar.gz"
archive_path = out_dir / archive_name
sha_path = out_dir / f"{archive_name}.sha256"
archive_path.write_bytes(payload)
sha_path.write_text(f"{digest} {archive_name}\n", encoding="utf-8")
return {
"archive": str(archive_path),
"sha256_file": str(sha_path),
"name": archive_name,
"size": len(payload),
"sha256": digest,
"files": [relative for relative, _ in files],
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", default=".", help="component repository root")
parser.add_argument("--component-id", required=True)
parser.add_argument("--version", required=True, help="version without leading v")
parser.add_argument("--out-dir", default="dist")
parser.add_argument(
"--allow",
action="append",
default=[],
help="relative allowlist entry (repeatable); defaults applied when omitted",
)
args = parser.parse_args(argv)
allowlist = args.allow or list(DEFAULT_ALLOWLIST)
root = Path(args.root).resolve()
out_dir = Path(args.out_dir)
if not out_dir.is_absolute():
out_dir = root / out_dir
try:
result = write_outputs(root, out_dir, args.component_id, args.version, allowlist)
except PackageError as error:
print(f"package_source: FAIL: {error}", file=sys.stderr)
return 1
print(result["archive"])
print(result["sha256_file"])
print(f"sha256={result['sha256']} size={result['size']} files={len(result['files'])}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+352
View File
@@ -0,0 +1,352 @@
#!/usr/bin/env python3
"""Publish a Gitea release with a draft transaction and immutable public assets.
Order (issue #10 §4.2):
create/reuse draft → upload non-index assets → upload release-evidence.json last
→ re-read and verify → mark non-draft → re-confirm.
Never deletes or replaces assets on an already-published (non-draft) release.
Identical published identity is treated as idempotent success.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import mimetypes
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
DEFAULT_API = "https://git.cflmy.cn/api/v1"
INDEX_NAME = "release-evidence.json"
class PublishError(Exception):
pass
def token() -> str:
value = (
os.environ.get("GITEA_PUBLISH_TOKEN")
or os.environ.get("GITEA_TOKEN")
or os.environ.get("gitea_token")
)
if not value:
raise PublishError("GITEA_PUBLISH_TOKEN (or GITEA_TOKEN) is not set")
return value
def request(
api: str,
method: str,
path: str,
token_value: str,
payload: dict | None = None,
raw: bytes | None = None,
content_type: str = "application/json",
) -> tuple[int, bytes]:
url = f"{api}{path}"
headers = {"Authorization": f"token {token_value}", "Accept": "application/json"}
data = None
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = content_type
elif raw is not None:
data = raw
headers["Content-Type"] = content_type
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=120) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
def decode(body: bytes) -> object:
if not body:
return None
try:
return json.loads(body)
except Exception:
return None
def sha256_file(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def get_release_by_tag(api: str, repo: str, tag: str, token_value: str) -> dict | None:
status, body = request(
api,
"GET",
f"/repos/{repo}/releases/tags/{urllib.parse.quote(tag, safe='')}",
token_value,
)
if status == 404:
return None
if status != 200:
raise PublishError(f"lookup release {tag} failed with HTTP {status}")
release = decode(body)
if not isinstance(release, dict) or "id" not in release:
raise PublishError("release lookup response malformed")
return release
def create_draft(
api: str,
repo: str,
tag: str,
body: str,
token_value: str,
*,
prerelease: bool,
target: str,
) -> dict:
payload = {
"tag_name": tag,
"name": tag,
"body": body,
"draft": True,
"prerelease": prerelease,
"target_commitish": target,
}
status, response = request(api, "POST", f"/repos/{repo}/releases", token_value, payload)
if status not in (200, 201):
raise PublishError(f"creating draft release failed with HTTP {status}: {response[:200]!r}")
release = decode(response)
if not isinstance(release, dict) or "id" not in release:
raise PublishError("draft create response malformed")
return release
def patch_release(api: str, repo: str, release_id: int, token_value: str, payload: dict) -> dict:
status, response = request(
api, "PATCH", f"/repos/{repo}/releases/{release_id}", token_value, payload
)
if status != 200:
raise PublishError(f"updating release {release_id} failed with HTTP {status}")
release = decode(response)
if not isinstance(release, dict):
raise PublishError("release patch response malformed")
return release
def list_assets(api: str, repo: str, release_id: int, token_value: str) -> list[dict]:
status, response = request(
api, "GET", f"/repos/{repo}/releases/{release_id}/assets", token_value
)
if status != 200:
raise PublishError(f"listing assets failed with HTTP {status}")
assets = decode(response)
if not isinstance(assets, list):
raise PublishError("asset list malformed")
return assets
def upload_asset(
api: str, repo: str, release_id: int, path: Path, token_value: str
) -> dict:
name = path.name
if not name or "/" in name or name in (".", ".."):
raise PublishError(f"unsafe asset name: {name!r}")
existing = list_assets(api, repo, release_id, token_value)
for asset in existing:
if asset.get("name") == name:
raise PublishError(
f"asset {name} already exists on draft/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 = request(
api,
"POST",
f"/repos/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(name)}",
token_value,
raw=bytes(body),
content_type=f"multipart/form-data; boundary={boundary}",
)
if status not in (200, 201):
raise PublishError(f"uploading {name} failed with HTTP {status}: {response[:200]!r}")
result = decode(response)
if not isinstance(result, dict):
raise PublishError(f"upload response for {name} malformed")
return result
def asset_identity(path: Path) -> dict:
return {
"name": path.name,
"size": path.stat().st_size,
"sha256": sha256_file(path),
}
def published_matches(release: dict, expected: list[dict]) -> bool:
remote = {
asset.get("name"): int(asset.get("size") or -1)
for asset in (release.get("assets") or [])
}
if set(remote) != {item["name"] for item in expected}:
return False
for item in expected:
if remote.get(item["name"]) != item["size"]:
return False
return True
def publish(
*,
api: str,
repo: str,
tag: str,
body: str,
target: str,
assets: list[Path],
prerelease: bool,
token_value: str,
) -> dict:
if not assets:
raise PublishError("no assets to publish")
index_assets = [path for path in assets if path.name == INDEX_NAME]
other_assets = [path for path in assets if path.name != INDEX_NAME]
if len(index_assets) != 1:
raise PublishError("exactly one release-evidence.json is required")
ordered = other_assets + index_assets
expected = [asset_identity(path) for path in ordered]
existing = get_release_by_tag(api, repo, tag, token_value)
if existing and not existing.get("draft"):
if published_matches(existing, expected):
return {
"status": "idempotent",
"release_id": existing["id"],
"html_url": existing.get("html_url"),
"tag": tag,
"assets": expected,
}
raise PublishError(
f"published release {tag} already exists with different assets; "
"refusing to overwrite"
)
if existing and existing.get("draft"):
release = existing
# Keep draft body/target aligned when continuing an interrupted publish.
release = patch_release(
api,
repo,
int(release["id"]),
token_value,
{
"name": tag,
"body": body,
"draft": True,
"prerelease": prerelease,
"target_commitish": target,
},
)
else:
release = create_draft(
api, repo, tag, body, token_value, prerelease=prerelease, target=target
)
release_id = int(release["id"])
remote_names = {asset.get("name") for asset in list_assets(api, repo, release_id, token_value)}
for path in ordered:
if path.name in remote_names:
# Same-name asset already on this draft: require identical size, else fail.
match = next(
asset
for asset in list_assets(api, repo, release_id, token_value)
if asset.get("name") == path.name
)
if int(match.get("size") or -1) != path.stat().st_size:
raise PublishError(
f"draft asset {path.name} size mismatch; refusing to overwrite"
)
continue
upload_asset(api, repo, release_id, path, token_value)
refreshed = get_release_by_tag(api, repo, tag, token_value)
if not refreshed or not published_matches(refreshed, expected):
raise PublishError("post-upload release asset list does not match local files")
published = patch_release(
api,
repo,
release_id,
token_value,
{"draft": False, "prerelease": prerelease, "name": tag, "body": body},
)
if published.get("draft"):
raise PublishError("release remained draft after publish")
final = get_release_by_tag(api, repo, tag, token_value)
if not final or final.get("draft") or not published_matches(final, expected):
raise PublishError("final release confirmation failed")
return {
"status": "published",
"release_id": final["id"],
"html_url": final.get("html_url"),
"tag": tag,
"assets": expected,
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", DEFAULT_API))
parser.add_argument("--repo", required=True, help="owner/name")
parser.add_argument("--tag", required=True)
parser.add_argument("--target", required=True, help="full commit SHA for the tag")
parser.add_argument("--body-file", default=None)
parser.add_argument("--body", default="")
parser.add_argument("--asset", action="append", default=[], required=True)
parser.add_argument("--prerelease", action="store_true", default=False)
parser.add_argument("--evidence-out", default="dist/gitea-publish-result.json")
args = parser.parse_args(argv)
body = args.body
if args.body_file:
body = Path(args.body_file).read_text(encoding="utf-8")
assets = [Path(item) for item in args.asset]
for path in assets:
if not path.is_file():
print(f"publish_gitea: FAIL: missing asset {path}", file=sys.stderr)
return 1
try:
result = publish(
api=args.api_url.rstrip("/"),
repo=args.repo,
tag=args.tag,
body=body,
target=args.target,
assets=assets,
prerelease=args.prerelease,
token_value=token(),
)
except PublishError as error:
print(f"publish_gitea: FAIL: {error}", file=sys.stderr)
return 1
out = Path(args.evidence_out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8")
print(json.dumps(result, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env python3
"""Write the external release-evidence.json index for a component release.
The index references already-built assets. It never includes itself in
`assets[]` (no self-referential digest). Downstream discoverers hash the index
bytes separately when they download it.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
from pathlib import Path
SHA_RE = re.compile(r"^[0-9a-f]{40}$")
DIGEST_RE = re.compile(r"^[0-9a-f]{64}$")
MAX_ASSETS = 128
MAX_DEPENDENCIES = 256
INDEX_NAME = "release-evidence.json"
class EvidenceError(Exception):
pass
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while True:
chunk = handle.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
def parse_dependency(raw: str) -> dict:
# id=cli,source_sha=<40hex>[,asset_sha256=<64hex>]
fields = {}
for part in raw.split(","):
if "=" not in part:
raise EvidenceError(f"invalid dependency field: {raw!r}")
key, value = part.split("=", 1)
fields[key.strip()] = value.strip()
component_id = fields.get("id")
source_sha = fields.get("source_sha")
if not component_id or not source_sha or not SHA_RE.match(source_sha):
raise EvidenceError(f"dependency requires id and 40-hex source_sha: {raw!r}")
entry = {"id": component_id, "source_sha": source_sha}
asset = fields.get("asset_sha256")
if asset:
if not DIGEST_RE.match(asset):
raise EvidenceError(f"invalid asset_sha256 in dependency: {raw!r}")
entry["asset_sha256"] = asset
return entry
def build_evidence(
*,
component_id: str,
repository: str,
tag: str,
source_sha: str,
assets: list[Path],
dependencies: list[dict],
pipeline_number: int | None,
pipeline_url: str | None,
) -> dict:
if not component_id:
raise EvidenceError("component_id is required")
if "/" not in repository:
raise EvidenceError("repository must be owner/name")
if not tag:
raise EvidenceError("tag is required")
if not SHA_RE.match(source_sha):
raise EvidenceError("source_sha must be a 40-hex commit")
if not assets:
raise EvidenceError("at least one non-index asset is required")
if len(assets) > MAX_ASSETS:
raise EvidenceError(f"more than {MAX_ASSETS} assets")
if len(dependencies) > MAX_DEPENDENCIES:
raise EvidenceError(f"more than {MAX_DEPENDENCIES} dependencies")
asset_entries = []
seen_names: set[str] = set()
for path in assets:
if not path.is_file():
raise EvidenceError(f"asset missing: {path}")
name = path.name
if name == INDEX_NAME:
raise EvidenceError("assets must not include release-evidence.json itself")
if name in seen_names or "/" in name or name in (".", ".."):
raise EvidenceError(f"unsafe or duplicate asset name: {name!r}")
seen_names.add(name)
target = "source"
if name.endswith(".tar.gz") and "linux" in name:
target = "x86_64-unknown-linux-gnu"
asset_entries.append(
{
"name": name,
"target": target,
"size": path.stat().st_size,
"sha256": sha256_file(path),
}
)
evidence = {
"component_id": component_id,
"repository": repository,
"tag": tag,
"source_sha": source_sha,
"ci": {
"pipeline_number": pipeline_number,
"url": pipeline_url,
"source_sha": source_sha,
},
"assets": asset_entries,
"dependencies": dependencies,
}
return evidence
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--component-id", required=True)
parser.add_argument("--repository", required=True)
parser.add_argument("--tag", required=True)
parser.add_argument("--source-sha", required=True)
parser.add_argument("--asset", action="append", default=[], required=True)
parser.add_argument("--dependency", action="append", default=[])
parser.add_argument("--pipeline-number", type=int, default=None)
parser.add_argument("--pipeline-url", default=None)
parser.add_argument("--out", default=f"dist/{INDEX_NAME}")
args = parser.parse_args(argv)
try:
dependencies = [parse_dependency(item) for item in args.dependency]
evidence = build_evidence(
component_id=args.component_id,
repository=args.repository,
tag=args.tag,
source_sha=args.source_sha,
assets=[Path(item) for item in args.asset],
dependencies=dependencies,
pipeline_number=args.pipeline_number,
pipeline_url=args.pipeline_url,
)
except EvidenceError as error:
print(f"write_evidence: FAIL: {error}", file=sys.stderr)
return 1
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
if len(payload.encode()) > 1024 * 1024:
print("write_evidence: FAIL: index exceeds 1 MiB", file=sys.stderr)
return 1
out.write_text(payload, encoding="utf-8")
print(out)
return 0
if __name__ == "__main__":
raise SystemExit(main())
-103
View File
@@ -1,103 +0,0 @@
"""Publication transaction regressions, without a forge write."""
import hashlib
import importlib.util
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
SCRIPT = Path(__file__).resolve().parents[1] / "release/publish-gitea.py"
SPEC = importlib.util.spec_from_file_location("publish_gitea", SCRIPT)
publish = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(publish)
TAG = "v0.1.0-beta.4"
SOURCE = "a" * 40
INDEX = "release-evidence.json"
class Forge:
def __init__(self):
self.release = None
self.assets = {}
self.changes = []
self.tag_sha = SOURCE
def json(self, path, method="GET", payload=None, **kwargs):
if method == "POST":
self.changes.append("create")
assert payload["draft"] is True
self.release = {"id": 12, **payload}
return self.release
if method == "PATCH":
self.changes.append("publish")
self.release.update(payload)
return self.release
if path.endswith("/assets"):
return [{"name": name, "size": len(content)} for name, content in self.assets.items()]
if path.endswith(f"/releases/tags/{TAG}"):
return self.release
if path.endswith(f"/tags/{TAG}"):
return {"commit": {"sha": self.tag_sha}}
raise AssertionError(path)
def digest_attachment(self, asset, size):
return hashlib.sha256(self.assets[asset["name"]]).hexdigest()
def upload(self, service, release_path, path, record):
assert self.release["draft"]
self.changes.append(path.name)
self.assets[path.name] = path.read_bytes()
class PublishTest(unittest.TestCase):
def setUp(self):
folder = Path(self.enterContext(tempfile.TemporaryDirectory()))
self.assets = {}
for name, data in {"tool.tar.gz": b"tool", INDEX: b"evidence"}.items():
path = folder / name
path.write_bytes(data)
self.assets[name] = path, publish.asset_record(path, "x86_64-unknown-linux-gnu")
self.forge = Forge()
def run_publish(self):
return publish.publish_release(self.forge, TAG, SOURCE, self.assets, "notes")
def test_publish_verifies_draft_and_is_idempotent(self):
with patch.object(publish, "upload", self.forge.upload):
self.assertFalse(self.run_publish()["draft"])
self.run_publish()
self.assertEqual(self.forge.changes, ["create", "tool.tar.gz", INDEX, "publish"])
def test_interruption_leaves_a_draft_and_resumes_only_missing_assets(self):
def fail_index(service, path, asset, record):
if asset.name == INDEX:
raise ConnectionError("interrupted")
self.forge.upload(service, path, asset, record)
with patch.object(publish, "upload", fail_index):
with self.assertRaises(ConnectionError):
self.run_publish()
self.assertTrue(self.forge.release["draft"])
self.assertEqual(self.forge.changes, ["create", "tool.tar.gz"])
with patch.object(publish, "upload", self.forge.upload):
self.assertFalse(self.run_publish()["draft"])
self.assertEqual(self.forge.changes, ["create", "tool.tar.gz", INDEX, "publish"])
def test_rejects_changed_public_bytes_and_a_moved_tag(self):
with patch.object(publish, "upload", self.forge.upload):
self.forge.tag_sha = "b" * 40
with self.assertRaisesRegex(publish.PublicationError, "tag moved"):
self.run_publish()
self.assertTrue(self.forge.release["draft"])
self.forge.tag_sha = SOURCE
self.run_publish()
self.forge.assets["tool.tar.gz"] = b"oops"
with self.assertRaisesRegex(publish.PublicationError, "published bytes differ"):
self.run_publish()
self.assertEqual(self.forge.changes, ["create", "tool.tar.gz", INDEX, "publish"])
if __name__ == "__main__":
unittest.main()
+65 -251
View File
@@ -1,271 +1,85 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Publish the reviewed Knowledge artifact to a protected Gitea tag.""" """Compatibility wrapper: delegate to the vendored immutable publisher.
Historical knowledge releases used an overwrite-friendly uploader. New publishes
must follow issue #10 §4.2 (no overwrite of public assets; draft transaction).
"""
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import hashlib
import json
import os import os
import re
import subprocess import subprocess
import sys import sys
import urllib.error
import urllib.parse
import urllib.request
import uuid
from pathlib import Path from pathlib import Path
FORGE = "https://git.cflmy.cn"
CI = "https://ci.cflmy.cn"
REPO = "cflmy/marqdo-knowledge"
ROOT = Path(__file__).resolve().parents[2] ROOT = Path(__file__).resolve().parents[2]
TAG = re.compile(r"v[0-9]+\.[0-9]+\.[0-9]+(?:-[A-Za-z0-9.-]+)?") VENDOR = ROOT / "scripts" / "release" / "publish_gitea.py"
SHA = re.compile(r"[a-f0-9]{40}")
DIGEST = re.compile(r"[a-f0-9]{64}")
BASENAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,180}")
MAX_ASSET = 256 * 1024 * 1024
class PublicationError(Exception): def main() -> int:
pass
def require(condition, reason):
if not condition:
raise PublicationError(reason)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
class Service:
def __init__(self, token):
self.token = token
self.opener = urllib.request.build_opener(NoRedirect())
def open(self, url, method="GET", data=None, content_type=None, authenticate=False):
headers = {"Accept": "application/json"}
if authenticate and self.token:
headers["Authorization"] = f"token {self.token}"
if content_type:
headers["Content-Type"] = content_type
request = urllib.request.Request(url, headers=headers, data=data, method=method)
return self.opener.open(request, timeout=45)
def json(self, path, method="GET", payload=None, *, missing_ok=False, ci=False, upload=None):
if upload is not None:
data, content_type = upload
elif payload is not None:
data, content_type = json.dumps(payload).encode(), "application/json"
else:
data, content_type = None, None
url = (CI + "/api" if ci else FORGE + "/api/v1") + path
try:
with self.open(url, method, data, content_type, authenticate=not ci) as response:
raw = response.read(2 * 1024 * 1024 + 1)
require(len(raw) <= 2 * 1024 * 1024, f"{method} {path}: response too large")
return json.loads(raw)
except urllib.error.HTTPError as error:
if missing_ok and error.code == 404:
return None
raise PublicationError(f"{method} {path}: HTTP {error.code}") from error
def digest_attachment(self, attachment, size):
identity = uuid.UUID(attachment["uuid"])
with self.open(f"{FORGE}/attachments/{identity}", authenticate=True) as response:
return consume(response, size)
def consume(stream, limit):
digest = hashlib.sha256()
size = 0
while block := stream.read(min(1024 * 1024, limit - size + 1)):
size += len(block)
require(size <= limit, "asset exceeds its recorded size")
digest.update(block)
require(size == limit, "asset size differs from its record")
return digest.hexdigest()
def asset_record(path, target):
require(path.is_file() and BASENAME.fullmatch(path.name), f"invalid asset {path}")
size = path.stat().st_size
require(0 < size <= MAX_ASSET, f"invalid size for {path.name}")
with path.open("rb") as stream:
return {"name": path.name, "target": target, "size": size,
"sha256": consume(stream, size)}
def ready_ci(service, head, number, repo):
repository = service.json(f"/repos/lookup/{REPO}", ci=True)
require(repository["full_name"] == REPO and repository["forge_remote_id"] == str(repo["id"]),
"Woodpecker repository identity differs from the forge")
ci_id = repository["id"]
run = service.json(f"/repos/{ci_id}/pipelines/{number}", ci=True)
require(run["number"] == number and run["commit"] == head and run["status"] == "success"
and run["ref"] == f"refs/heads/{repo['default_branch']}"
and run["event"] in {"push", "manual"} and not run.get("from_fork")
and any(w["name"] == "ci" and w["state"] == "success"
and any(s["name"] == "test" and s["state"] == "success" for s in w["children"])
for w in run["workflows"]),
"release requires successful default-branch component CI for this exact SHA")
return {"pipeline_number": number, "source_sha": head,
"url": f"{CI}/repos/{ci_id}/pipeline/{number}"}
def candidate(service, tag, pipeline, paths, *, publish):
repository = service.json(f"/repos/{REPO}")
branch = repository["default_branch"]
branch_info = service.json(f"/repos/{REPO}/branches/{urllib.parse.quote(branch, safe='')}")
head = subprocess.check_output(["git", "-C", ROOT, "rev-parse", "HEAD"], text=True).strip()
status = subprocess.check_output(["git", "-C", ROOT, "status", "--porcelain"], text=True)
require(not status and SHA.fullmatch(head), "release requires a clean checkout")
tag_info = service.json(f"/repos/{REPO}/tags/{urllib.parse.quote(tag, safe='')}")
branch_sha = branch_info["commit"]["id"]
require(tag_info["name"] == tag and tag_info["commit"]["sha"] == head
and SHA.fullmatch(branch_sha), "tag and checkout do not match")
ancestry = subprocess.run(["git", "-C", ROOT, "merge-base", "--is-ancestor", head, branch_sha],
capture_output=True, check=False)
require(ancestry.returncode == 0, "tag is outside the verified default-branch history; fetch first")
if publish:
actor = service.json("/user")
require(actor["login"] == "marqdo-publisher" and actor.get("is_admin") is False,
"publication requires the non-admin publisher account")
require(branch_info["protected"] is True, "default branch must be protected")
ci = ready_ci(service, head, pipeline, repository)
archive = paths[0]
info = json.loads((archive.parent / "RELEASE_INFO.json").read_text())
smoke = json.loads((archive.parent / "smoke-evidence.json").read_text())
records = [asset_record(path, info["target"]) for path in paths]
core_sha = smoke.get("core_source_sha", "")
core_digest = smoke.get("core_binary_sha256", "")
require(info["product"] == "marqdo-knowledge" and info["source_sha"] == head
and f"v{info['product_version']}" == tag
and smoke["source_sha"] == head and smoke["version"] == info["product_version"]
and smoke["archive"] == archive.name and smoke["archive_sha256"] == records[0]["sha256"]
and SHA.fullmatch(core_sha) and DIGEST.fullmatch(core_digest),
"package or cold-install evidence does not match the candidate")
checksum = (archive.parent / f"{archive.name}.sha256").read_text().split()
require(checksum == [records[0]["sha256"], archive.name], "archive checksum sidecar mismatch")
return {"component_id": "knowledge", "repository": REPO, "tag": tag, "source_sha": head,
"ci": ci, "assets": records,
"dependencies": [{"id": "cli", "source_sha": core_sha, "asset_sha256": core_digest}]}
def inventory(service, release_path):
attachments = service.json(release_path + "/assets")
require(isinstance(attachments, list), "invalid attachment inventory")
by_name = {item["name"]: item for item in attachments}
require(len(by_name) == len(attachments), "duplicate names in the release")
return by_name
def check_assets(service, attachments, expected, complete):
require(attachments.keys() <= expected.keys(), "unexpected attachment in release")
require(not complete or attachments.keys() == expected.keys(), "incomplete release assets")
for name, remote in attachments.items():
_, record = expected[name]
require(remote["size"] == record["size"]
and service.digest_attachment(remote, record["size"]) == record["sha256"],
f"published bytes differ for {name}")
def upload(service, release_path, path, record):
with path.open("rb") as stream:
data = stream.read(record["size"] + 1)
require(len(data) == record["size"] and hashlib.sha256(data).hexdigest() == record["sha256"],
f"local asset changed: {path.name}")
boundary = uuid.uuid4().hex
header = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="attachment"; filename="{path.name}"\r\n'
"Content-Type: application/octet-stream\r\n\r\n"
).encode()
body = header + data + f"\r\n--{boundary}--\r\n".encode()
service.json(release_path + "/assets?" + urllib.parse.urlencode({"name": path.name}),
"POST", upload=(body, f"multipart/form-data; boundary={boundary}"))
def publish_release(service, tag, source, expected, notes):
releases = f"/repos/{REPO}/releases"
by_tag = releases + "/tags/" + urllib.parse.quote(tag, safe="")
release = service.json(by_tag, missing_ok=True)
if release is None:
release = service.json(releases, "POST", {
"tag_name": tag, "target_commitish": source, "name": f"marqdo-knowledge {tag[1:]}",
"body": notes, "prerelease": True, "draft": True,
})
require(release["draft"], "forge did not create a draft release")
require(release["tag_name"] == tag and release["prerelease"], "existing release identity differs")
release_path = f"{releases}/{release['id']}"
attachments = inventory(service, release_path)
check_assets(service, attachments, expected, complete=not release["draft"])
if release["draft"]:
for name, (path, record) in expected.items():
if name not in attachments:
upload(service, release_path, path, record)
check_assets(service, inventory(service, release_path), expected, complete=True)
tag_info = service.json(f"/repos/{REPO}/tags/{urllib.parse.quote(tag, safe='')}")
require(tag_info["commit"]["sha"] == source, "tag moved during draft publication")
service.json(release_path, "PATCH", {"draft": False})
confirmed = service.json(by_tag)
require(confirmed["id"] == release["id"] and not confirmed["draft"] and confirmed["prerelease"],
"public release identity changed")
check_assets(service, inventory(service, release_path), expected, complete=True)
return confirmed
def main():
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL", "https://git.cflmy.cn/api/v1"))
parser.add_argument("--repo", default="cflmy/marqdo-knowledge")
parser.add_argument("--tag", required=True) parser.add_argument("--tag", required=True)
parser.add_argument("--pipeline", type=int, required=True) parser.add_argument("--archive", required=True)
parser.add_argument("--archive", type=Path, required=True) parser.add_argument("--files", nargs="*", default=[])
parser.add_argument("--files", nargs="*", type=Path, default=[]) parser.add_argument("--body-file", required=True)
parser.add_argument("--body-file", type=Path) parser.add_argument("--evidence-out", default="dist/gitea-release-evidence.json")
parser.add_argument("--prepare", action="store_true", help="write the evidence index without using a token") parser.add_argument("--target", default=os.environ.get("SOURCE_SHA") or os.environ.get("CI_COMMIT_SHA"))
parser.add_argument("--evidence-out", type=Path, default=Path("dist/gitea-release-evidence.json")) parser.add_argument("--prerelease", action="store_true", default=True)
args = parser.parse_args() args = parser.parse_args()
if not TAG.fullmatch(args.tag) or args.pipeline < 1: if not args.target:
parser.error("expected a release tag and a positive component CI pipeline number") print("publish-gitea: FAIL: --target / SOURCE_SHA / CI_COMMIT_SHA required", file=sys.stderr)
value = "" if args.prepare else os.environ.get("GITEA_TOKEN", "")
if not args.prepare and (not value or args.body_file is None):
parser.error("publication requires GITEA_TOKEN and --body-file")
try:
archive = args.archive.resolve()
folder = archive.parent
defaults = [folder / name for name in
(archive.name + ".sha256", "RELEASE_INFO.json", "FILES.sha256", "smoke-evidence.json")]
paths = list(dict.fromkeys([archive, *defaults, *(path.resolve() for path in args.files)]))
require(len(paths) <= 20, "too many release assets")
index = folder / "release-evidence.json"
require(index.name not in {path.name for path in paths}
and len({path.name for path in paths}) == len(paths), "duplicate release asset names")
service = Service(value)
proof = candidate(service, args.tag, args.pipeline, paths, publish=not args.prepare)
index.write_text(json.dumps(proof, sort_keys=True, indent=2) + "\n", encoding="utf-8")
if args.prepare:
print(index)
return 0
expected = {record["name"]: (path, record) for path, record in
zip(paths, proof["assets"], strict=True)}
expected[index.name] = (index, asset_record(index, proof["assets"][0]["target"]))
release = publish_release(service, args.tag, proof["source_sha"], expected,
args.body_file.read_text(encoding="utf-8"))
evidence = {"schema": "marqdo.knowledge.gitea-release", "schema_version": 1,
"tag": args.tag, "release_id": release["id"], "html_url": release["html_url"],
"prerelease": True, "assets": [record for _, record in expected.values()]}
args.evidence_out.parent.mkdir(parents=True, exist_ok=True)
args.evidence_out.write_text(json.dumps(evidence, sort_keys=True, indent=2) + "\n", encoding="utf-8")
print(f"release_url: {release['html_url']}")
except (OSError, ValueError, KeyError, TypeError, PublicationError, subprocess.CalledProcessError) as error:
print(f"publish-gitea: FAIL: {error}", file=sys.stderr)
return 1 return 1
return 0 assets = [args.archive, *args.files]
cmd = [
sys.executable,
str(VENDOR),
"--api-url",
args.api_url,
"--repo",
args.repo,
"--tag",
args.tag,
"--target",
args.target,
"--body-file",
args.body_file,
"--evidence-out",
args.evidence_out,
]
if args.prerelease:
cmd.append("--prerelease")
for asset in assets:
cmd.extend(["--asset", asset])
# Ensure release-evidence.json exists or generate a minimal one from assets.
evidence = Path("dist/release-evidence.json")
if not evidence.is_file():
write = ROOT / "scripts" / "release" / "write_evidence.py"
source_sha = args.target
version = args.tag.removeprefix("v")
gen = [
sys.executable,
str(write),
"--component-id",
"knowledge",
"--repository",
args.repo,
"--tag",
args.tag,
"--source-sha",
source_sha,
"--out",
str(evidence),
]
for asset in assets:
gen.extend(["--asset", asset])
subprocess.check_call(gen)
if str(evidence) not in assets and evidence.is_file():
cmd.extend(["--asset", str(evidence)])
return subprocess.call(cmd)
if __name__ == "__main__": if __name__ == "__main__":
sys.exit(main()) raise SystemExit(main())
+7 -15
View File
@@ -58,7 +58,7 @@ def main() -> int:
parser.add_argument("--evidence-out", default="") parser.add_argument("--evidence-out", default="")
args = parser.parse_args() args = parser.parse_args()
marqdo = Path(args.marqdo_bin).resolve() marqdo = Path(args.marqdo_bin)
if not marqdo.is_file(): if not marqdo.is_file():
fail("set --marqdo-bin or MARQDO_BIN to a real core CLI binary") fail("set --marqdo-bin or MARQDO_BIN to a real core CLI binary")
archive = Path(args.archive).resolve() archive = Path(args.archive).resolve()
@@ -190,25 +190,17 @@ def main() -> int:
"query_hits": len(query_report["hits"]), "query_hits": len(query_report["hits"]),
"database": check_report["payload"]["database"], "database": check_report["payload"]["database"],
} }
print(json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False))
if args.evidence_out:
Path(args.evidence_out).write_text(
json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
encoding="utf-8",
)
finally: finally:
run([str(marqdo), "tool", "remove", "knowledge"], env=env) run([str(marqdo), "tool", "remove", "knowledge"], env=env)
remaining = run([str(marqdo), "tool", "list"], env=env) remaining = run([str(marqdo), "tool", "list"], env=env)
if "knowledge" in remaining: if "knowledge" in remaining:
fail("tool was not removed") fail("tool was not removed")
core_info_path = marqdo.with_name("RELEASE_INFO.json")
source_path = marqdo.with_name("SOURCE_SHA")
if core_info_path.is_file() and source_path.is_file():
core_info = json.loads(core_info_path.read_text(encoding="utf-8"))
core_source = source_path.read_text(encoding="utf-8").strip()
core_digest = sha256_file(marqdo)
if (core_info.get("source_sha") != core_source
or core_info.get("binaries", {}).get("marqdo", {}).get("sha256") != core_digest):
fail("core executable does not match its release metadata")
evidence.update(core_source_sha=core_source, core_binary_sha256=core_digest)
rendered = json.dumps(evidence, indent=2, sort_keys=True, ensure_ascii=False)
print(rendered)
if args.evidence_out:
Path(args.evidence_out).write_text(rendered + "\n", encoding="utf-8")
print("smoke: OK") print("smoke: OK")
return 0 return 0