Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(release): guard Git Runtime assets (#930)
Call Whitee4f2bd130fd7
diff --git a/.github/workflows/git-runtime-release-guard.yml b/.github/workflows/git-runtime-release-guard.ymlnew file mode 100644index 000000000..a26115093--- /dev/null+++ b/.github/workflows/git-runtime-release-guard.yml@@ -0,0 +1,141 @@+name: Guard Git Runtime release++on:+ push:+ branches: [master]+ paths:+ - "vibe/git_runtime_manifest.json"+ - "scripts/git_runtime_release_guard.py"+ - ".github/workflows/git-runtime-release-guard.yml"+ schedule:+ - cron: "17 */6 * * *"+ - cron: "47 4 * * 0"+ workflow_dispatch:++permissions:+ actions: read+ contents: write++concurrency:+ group: git-runtime-release-guard+ cancel-in-progress: false++jobs:+ guard:+ name: Verify and recover pinned assets+ runs-on: ubuntu-latest+ timeout-minutes: 20+ steps:+ - uses: actions/checkout@v4++ - name: Resolve pinned manifest identity+ id: manifest+ shell: bash+ run: |+ echo "sha256=$(sha256sum vibe/git_runtime_manifest.json | cut -d' ' -f1)" \+ >> "$GITHUB_OUTPUT"++ - name: Fetch and verify published assets+ id: probe+ continue-on-error: true+ run: |+ python3 scripts/git_runtime_release_guard.py fetch \+ --output-dir "$RUNNER_TEMP/git-runtime-release"++ - name: Recover from the latest verified backup+ if: steps.probe.outcome == 'failure'+ env:+ GH_TOKEN: ${{ github.token }}+ MANIFEST_SHA: ${{ steps.manifest.outputs.sha256 }}+ shell: bash+ run: |+ set -euo pipefail+ artifact_name="git-runtime-release-backup-$MANIFEST_SHA"+ mapfile -t backup_runs < <(+ gh run list \+ --repo "$GITHUB_REPOSITORY" \+ --workflow git-runtime-release-guard.yml \+ --status success \+ --limit 50 \+ --json databaseId \+ --jq '.[].databaseId'+ )+ backup_run=""++ restore_dir="$RUNNER_TEMP/git-runtime-restore"+ for candidate_run in "${backup_runs[@]}"; do+ rm -rf "$restore_dir"+ mkdir -p "$restore_dir"+ if gh run download "$candidate_run" \+ --repo "$GITHUB_REPOSITORY" \+ --name "$artifact_name" \+ --dir "$restore_dir"; then+ backup_run="$candidate_run"+ break+ fi+ done+ if [ -z "$backup_run" ]; then+ echo "::error::No verified backup is available for manifest $MANIFEST_SHA."+ exit 1+ fi+ python3 scripts/git_runtime_release_guard.py verify \+ --asset-dir "$restore_dir"++ release_tag="$(jq -er '.release_tag' vibe/git_runtime_manifest.json)"+ git_version="$(jq -er '.git_version' vibe/git_runtime_manifest.json)"+ release_revision="${release_tag##*-}"+ assets=("$restore_dir"/*)++ if gh release view "$release_tag" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then+ declare -A existing_assets=()+ while IFS= read -r asset_name; do+ existing_assets["$asset_name"]=1+ done < <(+ gh release view "$release_tag" \+ --repo "$GITHUB_REPOSITORY" \+ --json assets \+ --jq '.assets[].name'+ )++ missing_assets=()+ for asset in "${assets[@]}"; do+ asset_name="${asset##*/}"+ if [ -z "${existing_assets[$asset_name]:-}" ]; then+ missing_assets+=("$asset")+ fi+ done+ if [ "${#missing_assets[@]}" -eq 0 ]; then+ echo "::error::Release contains every expected asset name but failed integrity verification; refusing to overwrite pinned assets."+ exit 1+ fi+ gh release upload "$release_tag" \+ --repo "$GITHUB_REPOSITORY" \+ "${missing_assets[@]}"+ else+ gh release create "$release_tag" \+ --repo "$GITHUB_REPOSITORY" \+ --verify-tag \+ --latest=false \+ --title "Avibe local-only Git runtime $git_version (build $release_revision)" \+ --notes "Avibe-managed local-only Git runtime recovered from a manifest-verified backup." \+ "${assets[@]}"+ fi++ - name: Verify recovered release+ if: steps.probe.outcome == 'failure'+ run: |+ python3 scripts/git_runtime_release_guard.py fetch \+ --output-dir "$RUNNER_TEMP/git-runtime-release"++ - name: Preserve verified release backup+ if: >-+ github.event_name != 'schedule' ||+ github.event.schedule == '47 4 * * 0' ||+ steps.probe.outcome == 'failure'+ uses: actions/upload-artifact@v6+ with:+ name: git-runtime-release-backup-${{ steps.manifest.outputs.sha256 }}+ path: ${{ runner.temp }}/git-runtime-release+ if-no-files-found: error+ retention-days: 90+ compression-level: 0diff --git a/AGENTS.md b/AGENTS.mdindex a38154cc7..64e4100df 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -292,3 +292,4 @@ Testing guidance:- GitHub-only pre-releases should use the `gh-vX.Y.ZrcN` format (for example `gh-v2.2.8rc2`) so they stay distinct from PyPI-triggering `v*` tags- GitHub-only pre-releases must include installable artifacts in the GitHub release assets: a wheel built with `ui/dist` and bundled `vibe/show_runtime/*.tgz`, plus the sdist- releases are published automatically by workflow after tagging/push+- Published managed-runtime manifests are availability contracts. Keep their release URLs under a scheduled manifest-verified backup/recovery guard, and publish the new assets before changing a pinned manifest so the guard never restores bytes from a different release.diff --git a/scripts/git_runtime_release_guard.py b/scripts/git_runtime_release_guard.pynew file mode 100755index 000000000..b43c39288--- /dev/null+++ b/scripts/git_runtime_release_guard.py@@ -0,0 +1,274 @@+#!/usr/bin/env python3+"""Verify and materialize the manifest-pinned Git Runtime release assets."""++from __future__ import annotations++import argparse+import hashlib+import json+import re+import shutil+import sys+import tarfile+import tempfile+import time+import urllib.error+import urllib.request+from dataclasses import dataclass+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+DEFAULT_MANIFEST = REPO_ROOT / "vibe" / "git_runtime_manifest.json"+RELEASE_DOWNLOAD_ROOT = "https://github.com/avibe-bot/avibe/releases/download"+RELEASE_TAG_RE = re.compile(r"git-runtime-v[0-9]+\.[0-9]+\.[0-9]+-[1-9][0-9]*")+SHA256_RE = re.compile(r"[0-9a-f]{64}")+++class ReleaseGuardError(RuntimeError):+ """Raised when the pinned release cannot be trusted or materialized."""+++@dataclass(frozen=True)+class ArchiveSpec:+ platform: str+ name: str+ url: str+ sha256: str+ binary_sha256: str+ size: int+ bin_path: str+++@dataclass(frozen=True)+class ReleaseSpec:+ manifest_path: Path+ manifest_bytes: bytes+ release_tag: str+ git_version: str+ release_base_url: str+ archives: tuple[ArchiveSpec, ...]++ @property+ def expected_asset_names(self) -> set[str]:+ names = {"git-runtime-manifest.json"}+ for archive in self.archives:+ names.add(archive.name)+ names.add(f"{archive.name}.sha256")+ return names+++def _require_string(payload: dict, key: str, *, context: str) -> str:+ value = payload.get(key)+ if not isinstance(value, str) or not value:+ raise ReleaseGuardError(f"{context}.{key} must be a non-empty string")+ return value+++def load_release_spec(manifest_path: Path) -> ReleaseSpec:+ try:+ manifest_bytes = manifest_path.read_bytes()+ payload = json.loads(manifest_bytes)+ except (OSError, json.JSONDecodeError) as exc:+ raise ReleaseGuardError(f"cannot read Git Runtime manifest: {exc}") from exc++ if not isinstance(payload, dict) or payload.get("schema_version") != 1:+ raise ReleaseGuardError("Git Runtime manifest schema_version must be 1")+ if payload.get("release_state") != "published":+ raise ReleaseGuardError("Git Runtime manifest must describe a published release")++ release_tag = _require_string(payload, "release_tag", context="manifest")+ if RELEASE_TAG_RE.fullmatch(release_tag) is None:+ raise ReleaseGuardError(f"invalid Git Runtime release tag: {release_tag}")+ git_version = _require_string(payload, "git_version", context="manifest")+ release_base_url = f"{RELEASE_DOWNLOAD_ROOT}/{release_tag}"++ archives_payload = payload.get("archives")+ if not isinstance(archives_payload, dict) or not archives_payload:+ raise ReleaseGuardError("Git Runtime manifest must contain archives")++ archives: list[ArchiveSpec] = []+ seen_names: set[str] = set()+ for platform, raw_archive in sorted(archives_payload.items()):+ context = f"archives.{platform}"+ if not isinstance(platform, str) or not isinstance(raw_archive, dict):+ raise ReleaseGuardError(f"{context} must be an object")+ name = _require_string(raw_archive, "name", context=context)+ url = _require_string(raw_archive, "url", context=context)+ sha256 = _require_string(raw_archive, "sha256", context=context)+ binary_sha256 = _require_string(raw_archive, "binary_sha256", context=context)+ bin_path = _require_string(raw_archive, "bin_path", context=context)+ size = raw_archive.get("size")+ if name in seen_names:+ raise ReleaseGuardError(f"duplicate archive name: {name}")+ if url != f"{release_base_url}/{name}":+ raise ReleaseGuardError(f"{context}.url is outside the pinned release")+ if SHA256_RE.fullmatch(sha256) is None:+ raise ReleaseGuardError(f"{context}.sha256 is invalid")+ if SHA256_RE.fullmatch(binary_sha256) is None:+ raise ReleaseGuardError(f"{context}.binary_sha256 is invalid")+ if not isinstance(size, int) or isinstance(size, bool) or size <= 0:+ raise ReleaseGuardError(f"{context}.size must be a positive integer")+ if Path(bin_path).is_absolute() or ".." in Path(bin_path).parts:+ raise ReleaseGuardError(f"{context}.bin_path must stay inside the archive")+ seen_names.add(name)+ archives.append(+ ArchiveSpec(+ platform=platform,+ name=name,+ url=url,+ sha256=sha256,+ binary_sha256=binary_sha256,+ size=size,+ bin_path=bin_path,+ )+ )++ return ReleaseSpec(+ manifest_path=manifest_path,+ manifest_bytes=manifest_bytes,+ release_tag=release_tag,+ git_version=git_version,+ release_base_url=release_base_url,+ archives=tuple(archives),+ )+++def _sha256_file(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _verify_archive(path: Path, archive: ArchiveSpec) -> None:+ if not path.is_file():+ raise ReleaseGuardError(f"missing release archive: {archive.name}")+ if path.stat().st_size != archive.size:+ raise ReleaseGuardError(f"release archive size mismatch: {archive.name}")+ if _sha256_file(path) != archive.sha256:+ raise ReleaseGuardError(f"release archive checksum mismatch: {archive.name}")+ try:+ with tarfile.open(path, "r:gz") as bundle:+ member = bundle.getmember(archive.bin_path)+ binary = bundle.extractfile(member)+ if binary is None or not member.isfile():+ raise ReleaseGuardError(f"release archive is missing {archive.bin_path}: {archive.name}")+ binary_sha256 = hashlib.sha256(binary.read()).hexdigest()+ except (KeyError, tarfile.TarError, OSError) as exc:+ raise ReleaseGuardError(f"invalid release archive {archive.name}: {exc}") from exc+ if binary_sha256 != archive.binary_sha256:+ raise ReleaseGuardError(f"release binary checksum mismatch: {archive.name}")+++def _verify_sidecar(path: Path, archive: ArchiveSpec) -> None:+ if not path.is_file():+ raise ReleaseGuardError(f"missing checksum sidecar: {path.name}")+ try:+ fields = path.read_text(encoding="utf-8").strip().split()+ except OSError as exc:+ raise ReleaseGuardError(f"cannot read checksum sidecar {path.name}: {exc}") from exc+ if fields != [archive.sha256, archive.name]:+ raise ReleaseGuardError(f"checksum sidecar mismatch: {path.name}")+++def verify_release_assets(manifest_path: Path, asset_dir: Path) -> ReleaseSpec:+ spec = load_release_spec(manifest_path)+ if not asset_dir.is_dir():+ raise ReleaseGuardError(f"release asset directory is missing: {asset_dir}")+ entries = list(asset_dir.iterdir())+ unsafe_entries = sorted(path.name for path in entries if path.is_symlink() or not path.is_file())+ if unsafe_entries:+ raise ReleaseGuardError(f"release asset directory contains unsafe entries: {unsafe_entries}")+ actual_names = {path.name for path in entries}+ if actual_names != spec.expected_asset_names:+ missing = sorted(spec.expected_asset_names - actual_names)+ unexpected = sorted(actual_names - spec.expected_asset_names)+ raise ReleaseGuardError(f"release asset set mismatch: missing={missing}, unexpected={unexpected}")+ release_manifest = asset_dir / "git-runtime-manifest.json"+ if release_manifest.read_bytes() != spec.manifest_bytes:+ raise ReleaseGuardError("published Git Runtime manifest differs from the packaged manifest")+ for archive in spec.archives:+ _verify_archive(asset_dir / archive.name, archive)+ _verify_sidecar(asset_dir / f"{archive.name}.sha256", archive)+ return spec+++def _download_to_path(url: str, destination: Path, *, attempts: int = 3, timeout: float = 60.0) -> None:+ request = urllib.request.Request(url, headers={"User-Agent": "avibe-git-runtime-release-guard/1"})+ for attempt in range(1, attempts + 1):+ try:+ with urllib.request.urlopen(request, timeout=timeout) as response, destination.open("wb") as output:+ shutil.copyfileobj(response, output)+ return+ except urllib.error.HTTPError as exc:+ retryable = exc.code == 429 or 500 <= exc.code < 600+ if not retryable or attempt == attempts:+ raise ReleaseGuardError(f"release asset download failed ({exc.code}): {url}") from exc+ except (OSError, urllib.error.URLError) as exc:+ if attempt == attempts:+ raise ReleaseGuardError(f"release asset download failed: {url}: {exc}") from exc+ time.sleep(float(attempt))+++def fetch_release_assets(manifest_path: Path, output_dir: Path) -> ReleaseSpec:+ spec = load_release_spec(manifest_path)+ output_dir.parent.mkdir(parents=True, exist_ok=True)+ temporary_dir = Path(tempfile.mkdtemp(prefix=f".{output_dir.name}-", dir=output_dir.parent))+ try:+ for archive in spec.archives:+ _download_to_path(archive.url, temporary_dir / archive.name)+ _download_to_path(f"{archive.url}.sha256", temporary_dir / f"{archive.name}.sha256")+ _download_to_path(+ f"{spec.release_base_url}/git-runtime-manifest.json",+ temporary_dir / "git-runtime-manifest.json",+ )+ verify_release_assets(manifest_path, temporary_dir)+ if output_dir.exists():+ if output_dir.is_dir():+ shutil.rmtree(output_dir)+ else:+ output_dir.unlink()+ temporary_dir.replace(output_dir)+ finally:+ if temporary_dir.exists():+ shutil.rmtree(temporary_dir)+ return spec+++def _build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)+ subparsers = parser.add_subparsers(dest="command", required=True)+ fetch = subparsers.add_parser("fetch", help="Download and verify the published release assets.")+ fetch.add_argument("--output-dir", type=Path, required=True)+ verify = subparsers.add_parser("verify", help="Verify a previously materialized asset directory.")+ verify.add_argument("--asset-dir", type=Path, required=True)+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = _build_parser().parse_args(argv)+ try:+ if args.command == "fetch":+ spec = fetch_release_assets(args.manifest, args.output_dir)+ else:+ spec = verify_release_assets(args.manifest, args.asset_dir)+ except ReleaseGuardError as exc:+ print(json.dumps({"ok": False, "error": str(exc)}), file=sys.stderr)+ return 1+ print(+ json.dumps(+ {+ "ok": True,+ "release_tag": spec.release_tag,+ "git_version": spec.git_version,+ "asset_count": len(spec.expected_asset_names),+ }+ )+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/test_git_runtime_release_guard.py b/tests/test_git_runtime_release_guard.pynew file mode 100644index 000000000..aced73e28--- /dev/null+++ b/tests/test_git_runtime_release_guard.py@@ -0,0 +1,175 @@+from __future__ import annotations++import gzip+import hashlib+import io+import json+import tarfile+from pathlib import Path++import pytest++from scripts import git_runtime_release_guard as guard+++def _git_archive(binary: bytes) -> bytes:+ output = io.BytesIO()+ with gzip.GzipFile(fileobj=output, mode="wb", filename="", mtime=0) as compressed:+ with tarfile.open(fileobj=compressed, mode="w") as bundle:+ member = tarfile.TarInfo("bin/git")+ member.mode = 0o755+ member.size = len(binary)+ bundle.addfile(member, io.BytesIO(binary))+ return output.getvalue()+++def _manifest(tmp_path: Path, archives: dict[str, bytes]) -> tuple[Path, dict[str, bytes]]:+ release_tag = "git-runtime-v2.55.0-1"+ base_url = f"{guard.RELEASE_DOWNLOAD_ROOT}/{release_tag}"+ remote: dict[str, bytes] = {}+ archive_payload = {}+ for platform, archive_bytes in archives.items():+ name = f"git-2.55.0-{platform}.tar.gz"+ archive_sha256 = hashlib.sha256(archive_bytes).hexdigest()+ with tarfile.open(fileobj=io.BytesIO(archive_bytes), mode="r:gz") as bundle:+ binary = bundle.extractfile("bin/git")+ assert binary is not None+ binary_sha256 = hashlib.sha256(binary.read()).hexdigest()+ url = f"{base_url}/{name}"+ archive_payload[platform] = {+ "name": name,+ "url": url,+ "sha256": archive_sha256,+ "binary_sha256": binary_sha256,+ "size": len(archive_bytes),+ "bin_path": "bin/git",+ }+ remote[url] = archive_bytes+ remote[f"{url}.sha256"] = f"{archive_sha256} {name}\n".encode()++ payload = {+ "schema_version": 1,+ "git_version": "2.55.0",+ "release_tag": release_tag,+ "release_state": "published",+ "archives": archive_payload,+ }+ manifest_path = tmp_path / "git_runtime_manifest.json"+ manifest_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ remote[f"{base_url}/git-runtime-manifest.json"] = manifest_path.read_bytes()+ return manifest_path, remote+++def _fake_download(remote: dict[str, bytes]):+ def download(url: str, destination: Path, **_kwargs) -> None:+ try:+ payload = remote[url]+ except KeyError as exc:+ raise guard.ReleaseGuardError(f"missing test asset: {url}") from exc+ destination.write_bytes(payload)++ return download+++def test_fetch_materializes_and_verifies_exact_release_assets(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ manifest_path, remote = _manifest(+ tmp_path,+ {+ "linux-arm64": _git_archive(b"arm64-git"),+ "linux-x64": _git_archive(b"x64-git"),+ },+ )+ monkeypatch.setattr(guard, "_download_to_path", _fake_download(remote))++ spec = guard.fetch_release_assets(manifest_path, tmp_path / "backup")+ verified = guard.verify_release_assets(manifest_path, tmp_path / "backup")++ assert spec.release_tag == "git-runtime-v2.55.0-1"+ assert verified.expected_asset_names == {path.name for path in (tmp_path / "backup").iterdir()}+++def test_verify_rejects_archive_checksum_mismatch(tmp_path: Path) -> None:+ manifest_path, remote = _manifest(tmp_path, {"linux-arm64": _git_archive(b"arm64-git")})+ backup = tmp_path / "backup"+ backup.mkdir()+ for url, payload in remote.items():+ (backup / url.rsplit("/", 1)[-1]).write_bytes(payload)+ archive = next(backup.glob("*.tar.gz"))+ archive.write_bytes(archive.read_bytes() + b"tampered")++ with pytest.raises(guard.ReleaseGuardError, match="size mismatch"):+ guard.verify_release_assets(manifest_path, backup)+++def test_verify_rejects_unexpected_backup_asset(tmp_path: Path) -> None:+ manifest_path, remote = _manifest(tmp_path, {"linux-arm64": _git_archive(b"arm64-git")})+ backup = tmp_path / "backup"+ backup.mkdir()+ for url, payload in remote.items():+ (backup / url.rsplit("/", 1)[-1]).write_bytes(payload)+ (backup / "unexpected.txt").write_text("unexpected", encoding="utf-8")++ with pytest.raises(guard.ReleaseGuardError, match="unexpected=.*unexpected.txt"):+ guard.verify_release_assets(manifest_path, backup)+++def test_verify_rejects_non_file_backup_entry(tmp_path: Path) -> None:+ manifest_path, remote = _manifest(tmp_path, {"linux-arm64": _git_archive(b"arm64-git")})+ backup = tmp_path / "backup"+ backup.mkdir()+ for url, payload in remote.items():+ (backup / url.rsplit("/", 1)[-1]).write_bytes(payload)+ (backup / "nested").mkdir()++ with pytest.raises(guard.ReleaseGuardError, match="unsafe entries:.*nested"):+ guard.verify_release_assets(manifest_path, backup)+++def test_failed_fetch_preserves_last_verified_backup(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ manifest_path, remote = _manifest(tmp_path, {"linux-arm64": _git_archive(b"arm64-git")})+ del remote[next(url for url in remote if url.endswith(".tar.gz"))]+ monkeypatch.setattr(guard, "_download_to_path", _fake_download(remote))+ backup = tmp_path / "backup"+ backup.mkdir()+ marker = backup / "last-good"+ marker.write_text("preserve", encoding="utf-8")++ with pytest.raises(guard.ReleaseGuardError, match="missing test asset"):+ guard.fetch_release_assets(manifest_path, backup)++ assert marker.read_text(encoding="utf-8") == "preserve"+++def test_manifest_rejects_archive_url_outside_pinned_release(tmp_path: Path) -> None:+ manifest_path, _remote = _manifest(tmp_path, {"linux-arm64": _git_archive(b"arm64-git")})+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ payload["archives"]["linux-arm64"]["url"] = "https://example.test/git.tar.gz"+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")++ with pytest.raises(guard.ReleaseGuardError, match="outside the pinned release"):+ guard.load_release_spec(manifest_path)+++def test_workflow_has_scheduled_backup_and_recovery_path() -> None:+ workflow = (guard.REPO_ROOT / ".github/workflows/git-runtime-release-guard.yml").read_text(+ encoding="utf-8"+ )++ assert "schedule:" in workflow+ assert "continue-on-error: true" in workflow+ assert "gh run download" in workflow+ assert "id: manifest" in workflow+ assert "MANIFEST_SHA: ${{ steps.manifest.outputs.sha256 }}" in workflow+ assert "git-runtime-release-backup-${{ steps.manifest.outputs.sha256 }}" in workflow+ assert "hashFiles(" not in workflow+ assert "retention-days: 90" in workflow+ assert "--verify-tag" in workflow+ assert "--latest=false" in workflow+ assert "missing_assets" in workflow+ assert "--clobber" not in workflow