From e55fb6ea3efe1117151a0d8cbc051ba363fe8953 Mon Sep 17 00:00:00 2001 From: Sekiph82 Date: Thu, 3 Dec 2026 23:24:48 +0300 Subject: [PATCH 1/5] feat(ops): PL-0516 server backup/restore, Studio update/rollback, SBOM, ops runbook - packlab_server.backup: SQLite online-backup snapshot + content-addressed objects, SHA-256 manifest, verify (integrity_check, referenced assets present, no unlisted files, optional off-band manifest digest), restore only into an empty target via verified sibling temp + rename. - tools/release/install_update.py: side-by-side stage, hash-verified atomic activate via state.json os.replace, one-step rollback, keeps current+previous only. - tools/release/sbom.py: deterministic CycloneDX 1.5 from uv.lock; licences only from the licence registry, others UNREVIEWED; runtime vs dev scope. - docs/ecosystem/PL-0516_OPERATIONS.md: runbooks, GitHub-blocked operation, private registry migration plan. Public builds stay blocked by the licence gate; signing and installer remain external gates. Co-Authored-By: Claude Opus 5.5 --- docs/ecosystem/PL-0516_OPERATIONS.md | 169 +++++++++++++++++++ server/src/packlab_server/backup.py | 232 +++++++++++++++++++++++++++ tests/server/test_backup.py | 116 ++++++++++++++ tests/tools/test_install_update.py | 64 ++++++++ tests/tools/test_sbom.py | 48 ++++++ tools/release/install_update.py | 227 ++++++++++++++++++++++++++ tools/release/sbom.py | 127 +++++++++++++++ 7 files changed, 983 insertions(+) create mode 100644 docs/ecosystem/PL-0516_OPERATIONS.md create mode 100644 server/src/packlab_server/backup.py create mode 100644 tests/server/test_backup.py create mode 100644 tests/tools/test_install_update.py create mode 100644 tests/tools/test_sbom.py create mode 100644 tools/release/install_update.py create mode 100644 tools/release/sbom.py diff --git a/docs/ecosystem/PL-0516_OPERATIONS.md b/docs/ecosystem/PL-0516_OPERATIONS.md new file mode 100644 index 00000000..f2ea885d --- /dev/null +++ b/docs/ecosystem/PL-0516_OPERATIONS.md @@ -0,0 +1,169 @@ +# PL-0516: Operations — backup/restore, update/rollback, GitHub-blocked operation, SBOM, private registry + +Status: local, testable parts implemented 2026-12-03. **Public builds stay blocked by the licence +gate** (`tools/packaging/windows_component_license_registry.json`, +`docs/architecture/DEPENDENCY_LICENSE_REGISTER.md`: OpenMVS AGPL-3.0, OCP/OCCT native notices, +OpenCV/FFmpeg). Real installer signing, a signed Windows installer, the company artifact +registry and factory-LAN deployment are **external gates**: none is claimed here. Nothing below +was run against real company infrastructure; all evidence is local temp-directory tests. + +| Part | Code | Tests | +|---|---|---| +| Server backup/verify/restore | `server/src/packlab_server/backup.py` | `tests/server/test_backup.py` | +| Studio side-by-side update/rollback | `tools/release/install_update.py` | `tests/tools/test_install_update.py` | +| CycloneDX SBOM from `uv.lock` | `tools/release/sbom.py` | `tests/tools/test_sbom.py` | + +All three are stdlib-only (no new dependency) and exit 0 PASS, 1 verification failed, +2 refused precondition. + +## 1. PackLab Server backup / restore runbook + +A backup is a directory with `library.sqlite3`, the content-addressed `objects/aa/bb/` +files and `manifest.json` (SHA-256 + size of every file). + +- The database is copied with the **SQLite online backup API** (`sqlite3.Connection.backup`), + not a file copy, so it is a consistent snapshot while the server keeps serving. It is + taken *before* the objects; objects are immutable and never deleted by the store, so every + object the snapshot references exists when the object copy runs. `verify` re-checks this + (every `revisions.assets` hash must be in the backup). +- In-progress resumable uploads (`uploads/`) are not backed up; clients resume or restart them. +- Object files are checked against their content address while copying. + +``` +python -m packlab_server.backup create D:\packlab-data E:\backups\2026-12-03 +# -> BACKUP_CREATED manifest_sha256= record this hex off-band (work record / ticket) +python -m packlab_server.backup verify E:\backups\2026-12-03 --expect-manifest-sha256 +python -m packlab_server.backup restore E:\backups\2026-12-03 D:\packlab-data-restored --expect-manifest-sha256 +``` + +(`PYTHONPATH=server/src` when running from a source checkout.) + +Restore rules: the backup is verified, copied into a sibling temp directory, the copy is verified +again, then renamed into place. The target must not exist or must be an empty directory, so a +live data directory is never overwritten. To put a restored copy into service: stop the server, +rename the old data directory aside (keep it until the restore is accepted), rename the restored +directory to the configured `--data` path, start the server. Clients see the feed +`high_watermark` below their cursor and resync (existing PL-0503 behaviour). + +The manifest self-check catches corruption. A deliberate rewrite of a file *and* the manifest is +caught only by `--expect-manifest-sha256`, so keep that value outside the backup medium. +Encryption at rest, off-site/cloud copy and retention schedule belong to the deployment +(POVU handoff: LAN primary + encrypted cloud DR); they are not implemented here. + +## 2. Studio update / rollback runbook + +Generalizes the OwnerDev `releases/` + `current`/`previous` pattern +(`tools/dev/update_owner_dev_runtime.ps1`, `update_owner_dev_current_runtime.ps1`; those scripts +and the owner's OwnerDev folder are unchanged and untouched by the tests). + +Layout: `INSTALL_ROOT\releases\\` (immutable, with `install-manifest.json`) and +`INSTALL_ROOT\state.json` = `{"current": "", "previous": ""}`. A launcher starts +`releases\`. Switching is a single atomic `os.replace` of `state.json`. + +``` +# build side, on the payload that will ship +python -m tools.release.install_update manifest build\PackLab-1.2.0 --version 1.2.0 # -> sha256 +# target machine +python -m tools.release.install_update stage C:\PackLab \\share\PackLab-1.2.0 --expect-manifest-sha256 +python -m tools.release.install_update activate C:\PackLab 1.2.0 +python -m tools.release.install_update rollback C:\PackLab # one step back +python -m tools.release.install_update status C:\PackLab +``` + +- `stage` verifies the payload, copies it side by side, verifies the copy, then renames it into + `releases\`; an existing version is refused, links/junctions are refused. +- `activate` / `rollback` re-verify the release they switch to; on failure `state.json` is + unchanged. +- After `activate` only `current` and `previous` are kept. A release staged but not yet + activated is pruned by the next `activate` of a different version: stage and activate one + version at a time. Files locked by a still-running old version are left and reported. +- Close Studio before `activate`/`rollback`; the tool does not stop processes. +- Data is never inside a release directory (projects and the sync cache live in user data), so + rollback does not roll back data. A data format change must stay additive/readable by the + previous version or ship with its own migration and backup step. +- The `--expect-manifest-sha256` value is the integrity anchor until real code signing exists; + it must come from the release record, not from the same share as the payload. + +## 3. GitHub-blocked operation + +Production must run, install, update and recover with GitHub (and public PyPI) unreachable. + +**At runtime nothing is downloaded.** The Studio, the server and the sync agent make no calls to +GitHub, raw URLs or package indexes; updates arrive as staged payloads (section 2). + +**Offline wheelhouse from `uv.lock`** (on a connected build host, then carried in): + +``` +uv export --frozen --no-emit-project --format requirements-txt -o requirements.lock.txt +python -m pip download --require-hashes --only-binary=:all: --platform win_amd64 \ + --python-version 3.12 -r requirements.lock.txt -d wheelhouse +# on the isolated host +uv venv --python 3.12 .venv +uv pip sync --offline --no-index --find-links wheelhouse --require-hashes requirements.lock.txt +``` + +`uv export --frozen` was run locally for this task (hashes come from `uv.lock`); the download and +offline sync were **not** executed here (no network test was done). Hashes in the exported file +pin every wheel, so a tampered wheelhouse fails the install. + +**Non-Python inputs the build pulls from GitHub today** (`.github/workflows/windows-studio-build.yml`) +must be mirrored into the private artifact store with their recorded SHA-256 before GitHub can be +dropped: OCP `OCP_src_stubs_Windows.zip` 7.9.3.1.1, OCCT source archive +`a016080bf6738d6aeae020badee4e888ad1540a5`, Inno Setup 6.7.3, plus the controlled OCP/COLMAP/OpenMVS +inputs pinned in `tools/packaging/*.json`. + +**Verifying a CI-less build** (GitHub Actions unavailable): + +1. Clean checkout of the exact commit; `uv sync --locked` from the wheelhouse/private index. +2. Run the same gates locally: `ruff format --check`, `ruff check core apps server tools tests`, + `mypy --no-incremental core apps server tools`, `pytest`, + `python -m tools.ci.ci_data_safety --repository . --check-signing-secrets` and + `--tracked --check-workflows --check-environment`. +3. Build, then `install_update manifest` the payload and record commit SHA, `uv.lock` SHA-256, + SBOM and manifest SHA-256 in the release record (`tools/release/offline_release_manifest.py` + stays `NOT_RELEASE_AUTHORIZED` until the licence and signing gates clear). + +## 4. SBOM + +``` +python -m tools.release.sbom --output packlab.cdx.json +``` + +CycloneDX 1.5 JSON with every `uv.lock` package: name, version, `pkg:pypi` purl, dependency graph, +scope `required` (runtime closure of the project dependencies) or `excluded` (dev/workflow +tools). A licence is stated only where the licence registry records one; all others carry +`packlab:licence_status=UNREVIEWED`. Output is byte-identical for the same lock and registry +(no timestamp; serial number derived from the `uv.lock` SHA-256). Scope: Python packages only — +native payloads (OCCT, Qt DLLs inside wheels, COLMAP/OpenMVS, MSVC runtime) are covered by the +PL-0350 native inventory, not this SBOM. The SBOM is evidence, not licence clearance. + +## 5. Private registry migration plan + +Target: company-hosted, S3-compatible-backed artifact service (e.g. a PyPI-compatible proxy such +as devpi/Nexus/Artifactory, chosen at commissioning; no provider is selected or purchased now). + +1. **Mirror**: populate a private PyPI-compatible index from the wheelhouse above (all hashes from + `uv.lock`), and a raw artifact area for the native/tool inputs listed in section 3. +2. **Point uv at it**: add an `[[tool.uv.index]]` (name `packlab-private`, `default = true`) in + `pyproject.toml`, credentials only through environment/keyring (`UV_INDEX_PACKLAB_PRIVATE_USERNAME` + / `_PASSWORD`), never in Git. Re-lock with `uv lock`; the **package hashes must be identical** + to the current lock (only the `source.registry` URL changes) — diff the lock and refuse any + hash change. +3. **Workflows**: replace `Invoke-WebRequest https://github.com/...` inputs with the private + artifact URLs, keeping the same SHA-256 checks. Do not weaken the licence/public-build gates + while doing so. +4. **Releases**: staged payloads + `install-manifest.json` + SBOM published to the private + artifact store; clients update with `install_update stage/activate` from there. +5. **Source/history export**: `git bundle create packlab.bundle --all`, verified with + `git bundle verify`, stored in the private store; repository visibility/deletion is an owner + decision, not part of this task. +6. **Cutover check**: on a host with GitHub and pypi.org blocked at the firewall, run section 3 + step 1-3 end to end, a server backup/restore and an update + rollback. That real-infra run is + the acceptance evidence still outstanding. + +## Limits + +- No signing, no installer build, no public build, no network service added. +- Backup encryption, retention, off-site copy and scheduling are deployment work. +- The update tool is not wired into the OwnerDev launcher or the Inno Setup installer yet. +- Offline wheelhouse and private-registry steps are documented, not executed on real infrastructure. diff --git a/server/src/packlab_server/backup.py b/server/src/packlab_server/backup.py new file mode 100644 index 00000000..1dc90b31 --- /dev/null +++ b/server/src/packlab_server/backup.py @@ -0,0 +1,232 @@ +"""PL-0516: PackLab Server backup, verification and restore. + + python -m packlab_server.backup create DATA_DIR NEW_BACKUP_DIR + python -m packlab_server.backup verify BACKUP_DIR [--expect-manifest-sha256 HEX] + python -m packlab_server.backup restore BACKUP_DIR EMPTY_TARGET [--expect-manifest-sha256 HEX] + +A backup is ``library.sqlite3`` (taken with the SQLite online backup API, so it is a consistent +snapshot while the server keeps running) plus every content-addressed file under ``objects/``, +and ``manifest.json`` with the SHA-256 and size of each file. The database is snapshotted +first: objects are immutable and never deleted, so every object the snapshot references is +already on disk when the object copy starts. In-progress resumable uploads are not backed up. + +``restore`` verifies the backup, copies it into a sibling temp directory, verifies the copy, +then renames it into place; it refuses any target that exists and is not an empty directory, +so it can never overwrite a live data directory. The manifest digest catches corruption; a +deliberate rewrite of both a file and the manifest is caught only by passing the +``manifest_sha256`` recorded off-band at create time as ``--expect-manifest-sha256``. +Exit codes: 0 PASS, 1 verification failed, 2 refused precondition. Stdlib only. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import sqlite3 +import sys +import time +import uuid +from pathlib import Path +from typing import Any + +FORMAT = "packlab.server-backup.v1" +MANIFEST = "manifest.json" +DB_NAME = "library.sqlite3" +_OBJECT = re.compile(r"[0-9a-f]{64}\Z") +_ALLOWED = re.compile(r"(library\.sqlite3|objects/[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{64})\Z") +_SHA256 = re.compile(r"[0-9a-f]{64}\Z") + + +class BackupError(Exception): + """A refused precondition: nothing was published at the destination.""" + + +class VerificationError(Exception): + """The backup does not match its manifest (or the manifest digest expected off-band).""" + + +def _file_sha256(path: Path) -> str: + with open(path, "rb") as handle: + return hashlib.file_digest(handle, "sha256").hexdigest() + + +def _sibling_temp(path: Path) -> Path: + return path.with_name(f".{path.name}.tmp-{uuid.uuid4().hex}") + + +def _free_target(path: Path) -> None: + if path.is_symlink() or (path.exists() and (not path.is_dir() or any(path.iterdir()))): + raise BackupError(f"target exists and is not an empty directory: {path}") + + +def create(data_dir: Path, backup_dir: Path) -> str: + """Write a new backup of ``data_dir``; returns the manifest SHA-256 to record off-band.""" + data_dir, backup_dir = Path(data_dir), Path(backup_dir) + source_db = data_dir / DB_NAME + if not source_db.is_file(): + raise BackupError(f"not a PackLab Server data directory (no {DB_NAME}): {data_dir}") + if backup_dir.exists(): + raise BackupError(f"backup destination already exists: {backup_dir}") + stage = _sibling_temp(backup_dir) + stage.mkdir(parents=True) + try: + src = sqlite3.connect(source_db) + dst = sqlite3.connect(stage / DB_NAME) + try: + src.backup(dst) + dst.execute("PRAGMA journal_mode=DELETE") # one self-contained file, no -wal + finally: + dst.close() + src.close() + files = {DB_NAME: _entry(stage / DB_NAME)} + objects = data_dir / "objects" + for path in sorted(objects.rglob("*")) if objects.is_dir() else []: + if path.is_symlink(): + raise BackupError(f"refusing a link in the object store: {path}") + if not path.is_file() or not _OBJECT.match(path.name): + continue # directories and put_object temp files + rel = path.relative_to(data_dir).as_posix() + if not _ALLOWED.match(rel): + continue + target = stage / rel + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, target) + entry = _entry(target) + if entry["sha256"] != path.name: + raise BackupError(f"object content does not match its address: {rel}") + files[rel] = entry + manifest = {"format": FORMAT, "created_at": time.time(), "files": files} + raw = (json.dumps(manifest, sort_keys=True, indent=1) + "\n").encode("utf-8") + (stage / MANIFEST).write_bytes(raw) # bytes: the digest must not depend on newline mode + verify(stage) + os.replace(stage, backup_dir) + except BaseException: + shutil.rmtree(stage, ignore_errors=True) + raise + return hashlib.sha256(raw).hexdigest() + + +def _entry(path: Path) -> dict[str, Any]: + return {"sha256": _file_sha256(path), "size": path.stat().st_size} + + +def verify(backup_dir: Path, expect_manifest_sha256: str | None = None) -> dict[str, Any]: + """Raise ``VerificationError`` unless every file matches the manifest, nothing extra is + present, the database passes ``integrity_check`` and every referenced asset is present.""" + backup_dir = Path(backup_dir) + try: + raw = (backup_dir / MANIFEST).read_bytes() + manifest = json.loads(raw) + except (OSError, ValueError) as error: + raise VerificationError(f"unreadable manifest: {error}") from error + if expect_manifest_sha256 is not None: + if hashlib.sha256(raw).hexdigest() != expect_manifest_sha256.lower(): + raise VerificationError("manifest digest differs from the expected value") + if not isinstance(manifest, dict) or manifest.get("format") != FORMAT: + raise VerificationError("unknown backup format") + files = manifest.get("files") + if not isinstance(files, dict) or DB_NAME not in files: + raise VerificationError("manifest lists no database") + problems = [] + for rel, entry in sorted(files.items()): + if not isinstance(rel, str) or not _ALLOWED.match(rel): + raise VerificationError(f"manifest names a disallowed path: {rel!r}") + if ( + not isinstance(entry, dict) + or not isinstance(entry.get("sha256"), str) + or not _SHA256.match(entry["sha256"]) + ): + raise VerificationError(f"malformed manifest entry: {rel}") + path = backup_dir / rel + if path.is_symlink() or not path.is_file(): + problems.append(f"missing: {rel}") + continue + if path.stat().st_size != entry.get("size") or _file_sha256(path) != entry["sha256"]: + problems.append(f"content differs: {rel}") + elif rel != DB_NAME and path.name != entry["sha256"]: + problems.append(f"object address differs from its content: {rel}") + for path in backup_dir.rglob("*"): + rel = path.relative_to(backup_dir).as_posix() + if (path.is_file() or path.is_symlink()) and rel != MANIFEST and rel not in files: + problems.append(f"unlisted file: {rel}") + if problems: + raise VerificationError("; ".join(problems)) + db = sqlite3.connect(f"{(backup_dir / DB_NAME).resolve().as_uri()}?mode=ro", uri=True) + try: + check = db.execute("PRAGMA integrity_check").fetchone()[0] + assets = { + sha + for (text,) in db.execute("SELECT assets FROM revisions") + for sha in json.loads(text) + } + items = db.execute("SELECT COUNT(*) FROM items").fetchone()[0] + feed = db.execute("SELECT COALESCE(MAX(seq), 0) FROM feed").fetchone()[0] + except sqlite3.DatabaseError as error: + raise VerificationError(f"database unreadable: {error}") from error + finally: + db.close() + if check != "ok": + raise VerificationError(f"database integrity_check: {check}") + stored = {rel.rsplit("/", 1)[-1] for rel in files if rel != DB_NAME} + if missing := sorted(assets - stored): + raise VerificationError(f"revisions reference missing objects: {', '.join(missing)}") + return {"items": items, "feed_high_watermark": feed, "objects": len(stored)} + + +def restore(backup_dir: Path, target: Path, expect_manifest_sha256: str | None = None) -> None: + """Restore into ``target``, which must not exist or be an empty directory.""" + backup_dir, target = Path(backup_dir), Path(target) + _free_target(target) + verify(backup_dir, expect_manifest_sha256) + stage = _sibling_temp(target) + try: + shutil.copytree(backup_dir, stage) + verify(stage, expect_manifest_sha256) + (stage / MANIFEST).unlink() + (stage / "uploads").mkdir() + _free_target(target) # re-check: nothing appeared while we copied + if target.exists(): + target.rmdir() + os.replace(stage, target) + except BaseException: + shutil.rmtree(stage, ignore_errors=True) + raise + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="packlab_server.backup") + sub = parser.add_subparsers(dest="command", required=True) + p_create = sub.add_parser("create") + p_create.add_argument("data_dir", type=Path) + p_create.add_argument("backup_dir", type=Path) + for name in ("verify", "restore"): + p = sub.add_parser(name) + p.add_argument("backup_dir", type=Path) + if name == "restore": + p.add_argument("target", type=Path) + p.add_argument("--expect-manifest-sha256") + args = parser.parse_args(argv) + try: + if args.command == "create": + print(f"BACKUP_CREATED manifest_sha256={create(args.data_dir, args.backup_dir)}") + elif args.command == "verify": + summary = verify(args.backup_dir, args.expect_manifest_sha256) + print(f"BACKUP_VERIFIED {json.dumps(summary, sort_keys=True)}") + else: + restore(args.backup_dir, args.target, args.expect_manifest_sha256) + print(f"BACKUP_RESTORED {args.target}") + except BackupError as error: + print(f"REFUSED: {error}", file=sys.stderr) + return 2 + except VerificationError as error: + print(f"VERIFY_FAILED: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/server/test_backup.py b/tests/server/test_backup.py new file mode 100644 index 00000000..f2b87a2c --- /dev/null +++ b/tests/server/test_backup.py @@ -0,0 +1,116 @@ +"""PL-0516: server backup/verify/restore round trip and refusals.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from packlab_server import backup +from packlab_server.store import LibraryStore + + +def _seed(root: Path) -> LibraryStore: + """A live store with a released item, a draft, an observation and two objects.""" + store = LibraryStore(root) + mesh = store.put_object(b"synthetic mesh bytes") + label = store.put_object(b"synthetic label bytes") + item = store.create_item("ann", "bottle", "HDPE 1L", {"height_mm": 240.0}, [mesh]) + store.release("ann", item["id"], item["version"], "DESIGN_NOMINAL") + store.add_observation("wes", "warehouse", item["id"], 1, "fit", "fits carton 12x") + store.create_item("ann", "label", "Front label", {"width_mm": 80.0}, [label]) + return store + + +def _snapshot(store: LibraryStore) -> dict[str, Any]: + return { + "items": store.list_items(include_drafts=True), + "feed": store.feed(0, limit=1000), + "objects": { + sha: store.object_path(sha).read_bytes() + for item in store.list_items(include_drafts=True) + for rev in item["revisions"] + for sha in rev["assets"] + }, + } + + +def test_round_trip_restores_items_revisions_feed_and_objects(tmp_path: Path) -> None: + live = _seed(tmp_path / "live") + try: # backup taken while the store is open (online) + digest = backup.create(tmp_path / "live", tmp_path / "bk") + expected = _snapshot(live) + finally: + live.close() + summary = backup.verify(tmp_path / "bk", expect_manifest_sha256=digest) + assert summary == {"items": 2, "feed_high_watermark": 4, "objects": 2} + backup.restore(tmp_path / "bk", tmp_path / "restored", expect_manifest_sha256=digest) + restored = LibraryStore(tmp_path / "restored") + try: + assert _snapshot(restored) == expected + assert len(expected["objects"]) == 2 + finally: + restored.close() + + +def test_tampered_object_is_refused_and_nothing_is_restored(tmp_path: Path) -> None: + _seed(tmp_path / "live").close() + backup.create(tmp_path / "live", tmp_path / "bk") + obj = next(p for p in (tmp_path / "bk" / "objects").rglob("*") if p.is_file()) + obj.write_bytes(b"tampered") + with pytest.raises(backup.VerificationError, match="content differs"): + backup.restore(tmp_path / "bk", tmp_path / "restored") + assert {p.name for p in tmp_path.iterdir()} == {"bk", "live"} # no target, no temp left + + +def test_rewritten_manifest_is_caught_only_by_the_off_band_digest(tmp_path: Path) -> None: + _seed(tmp_path / "live").close() + digest = backup.create(tmp_path / "live", tmp_path / "bk") + manifest_path = tmp_path / "bk" / backup.MANIFEST + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + manifest["created_at"] = 0.0 + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + backup.verify(tmp_path / "bk") # still self-consistent + with pytest.raises(backup.VerificationError, match="expected value"): + backup.verify(tmp_path / "bk", expect_manifest_sha256=digest) + + +def test_unlisted_file_and_unsafe_manifest_path_are_refused(tmp_path: Path) -> None: + _seed(tmp_path / "live").close() + backup.create(tmp_path / "live", tmp_path / "bk") + (tmp_path / "bk" / "extra.bin").write_bytes(b"x") + with pytest.raises(backup.VerificationError, match="unlisted file"): + backup.verify(tmp_path / "bk") + (tmp_path / "bk" / "extra.bin").unlink() + manifest_path = tmp_path / "bk" / backup.MANIFEST + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + manifest["files"]["../escape"] = {"sha256": "0" * 64, "size": 0} + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + with pytest.raises(backup.VerificationError, match="disallowed path"): + backup.verify(tmp_path / "bk") + + +def test_restore_refuses_a_live_data_dir_and_create_refuses_existing_dest(tmp_path: Path) -> None: + _seed(tmp_path / "live").close() + backup.create(tmp_path / "live", tmp_path / "bk") + before = (tmp_path / "live" / "library.sqlite3").read_bytes() + with pytest.raises(backup.BackupError, match="not an empty directory"): + backup.restore(tmp_path / "bk", tmp_path / "live") + assert (tmp_path / "live" / "library.sqlite3").read_bytes() == before + with pytest.raises(backup.BackupError, match="already exists"): + backup.create(tmp_path / "live", tmp_path / "bk") + (tmp_path / "empty").mkdir() + backup.restore(tmp_path / "bk", tmp_path / "empty") # an empty directory is fine + assert (tmp_path / "empty" / "library.sqlite3").is_file() + + +def test_cli_exit_codes(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + _seed(tmp_path / "live").close() + assert backup.main(["create", str(tmp_path / "live"), str(tmp_path / "bk")]) == 0 + digest = capsys.readouterr().out.strip().split("manifest_sha256=")[1] + assert backup.main(["verify", str(tmp_path / "bk"), "--expect-manifest-sha256", digest]) == 0 + assert backup.main(["verify", str(tmp_path / "bk"), "--expect-manifest-sha256", "0" * 64]) == 1 + assert backup.main(["restore", str(tmp_path / "bk"), str(tmp_path / "live")]) == 2 + assert backup.main(["restore", str(tmp_path / "bk"), str(tmp_path / "new")]) == 0 diff --git a/tests/tools/test_install_update.py b/tests/tools/test_install_update.py new file mode 100644 index 00000000..9fd32642 --- /dev/null +++ b/tests/tools/test_install_update.py @@ -0,0 +1,64 @@ +"""PL-0516: side-by-side stage, atomic activate, one-step rollback, hash refusal (temp dirs only).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from tools.release import install_update as iu + + +def _payload(tmp: Path, version: str, body: str) -> Path: + payload = tmp / f"payload-{version}" + (payload / "app").mkdir(parents=True) + (payload / "app" / "PackLab.exe").write_text(body, encoding="utf-8") + (payload / "README.txt").write_text(version, encoding="utf-8") + iu.write_manifest(payload, version) + return payload + + +def test_update_then_rollback_keeps_one_previous(tmp_path: Path) -> None: + root = tmp_path / "install" + for n, version in enumerate(["1.0.0", "1.1.0", "1.2.0"]): + assert iu.stage(root, _payload(tmp_path, version, f"build {n}")) == version + assert iu.activate(root, version) == [] + assert iu.read_state(root) == {"current": "1.2.0", "previous": "1.1.0"} + assert sorted(p.name for p in (root / "releases").iterdir()) == ["1.1.0", "1.2.0"] + assert iu.rollback(root) == "1.1.0" + assert iu.read_state(root) == {"current": "1.1.0", "previous": "1.2.0"} + current = root / "releases" / iu.read_state(root)["current"] # type: ignore[operator] + assert (current / "app" / "PackLab.exe").read_text(encoding="utf-8") == "build 1" + + +def test_tampered_payload_and_staged_release_are_refused(tmp_path: Path) -> None: + root = tmp_path / "install" + payload = _payload(tmp_path, "2.0.0", "good") + (payload / "app" / "PackLab.exe").write_text("evil", encoding="utf-8") + with pytest.raises(iu.VerificationError, match="content differs"): + iu.stage(root, payload) + assert not (root / "releases" / "2.0.0").exists() + + iu.stage(root, _payload(tmp_path, "2.0.1", "good")) + iu.activate(root, "2.0.1") + iu.stage(root, _payload(tmp_path, "2.0.2", "good too")) + (root / "releases" / "2.0.2" / "extra.dll").write_bytes(b"x") + with pytest.raises(iu.VerificationError, match="unlisted file"): + iu.activate(root, "2.0.2") + assert iu.read_state(root)["current"] == "2.0.1" # state untouched + + +def test_expected_manifest_digest_and_refusals(tmp_path: Path) -> None: + root = tmp_path / "install" + payload = _payload(tmp_path, "3.0.0", "x") + digest = iu.write_manifest(payload, "3.0.0") + with pytest.raises(iu.VerificationError, match="expected value"): + iu.stage(root, payload, expect_manifest_sha256="0" * 64) + iu.stage(root, payload, expect_manifest_sha256=digest) + with pytest.raises(iu.InstallError, match="already staged"): + iu.stage(root, payload) + with pytest.raises(iu.InstallError, match="no previous"): + iu.rollback(root) + with pytest.raises(iu.InstallError, match="unsafe version"): + iu.activate(root, "..") + assert iu.main(["status", str(root)]) == 0 + assert iu.main(["activate", str(root), "9.9.9"]) == 2 diff --git a/tests/tools/test_sbom.py b/tests/tools/test_sbom.py new file mode 100644 index 00000000..3eaeef3f --- /dev/null +++ b/tests/tools/test_sbom.py @@ -0,0 +1,48 @@ +"""PL-0516: CycloneDX SBOM from uv.lock is deterministic, complete and never over-claims licences.""" + +from __future__ import annotations + +import tomllib +from pathlib import Path + +from tools.release import sbom + +REPO = Path(__file__).resolve().parents[2] + + +def test_sbom_covers_the_lock_deterministically() -> None: + lock = REPO / "uv.lock" + first = sbom.render(sbom.generate(lock)) + assert first == sbom.render(sbom.generate(lock)) + bom = sbom.generate(lock) + assert bom["bomFormat"] == "CycloneDX" and bom["specVersion"] == "1.5" + locked = {(p["name"], p["version"]) for p in tomllib.loads(lock.read_text("utf-8"))["package"]} + listed = {(c["name"], c["version"]) for c in bom["components"]} + assert listed | {("packlab", bom["metadata"]["component"]["version"])} == locked + by_name = {c["name"]: c for c in bom["components"]} + assert by_name["pyside6-essentials"]["scope"] == "required" # runtime closure + assert by_name["shiboken6"]["scope"] == "required" # transitive + assert by_name["pytest"]["scope"] == "excluded" # dev only + assert by_name["pyside6-essentials"]["licenses"] == [{"expression": "LGPL-3.0-only"}] + assert by_name["pyside6-essentials"]["purl"].startswith("pkg:pypi/pyside6-essentials@") + unreviewed = [c for c in bom["components"] if "licenses" not in c] + assert unreviewed and all( + c["properties"] == [{"name": "packlab:licence_status", "value": "UNREVIEWED"}] + for c in unreviewed + ) + refs = {c["bom-ref"] for c in bom["components"]} | {bom["metadata"]["component"]["bom-ref"]} + assert all(set(d["dependsOn"]) <= refs for d in bom["dependencies"]) + + +def test_licence_comes_only_from_the_registry(tmp_path: Path) -> None: + lock = tmp_path / "uv.lock" + lock.write_text( + 'version = 1\n[[package]]\nname = "app"\nversion = "1.0"\nsource = { editable = "." }\n' + 'dependencies = [{ name = "dep_a" }]\n' + '[[package]]\nname = "dep_a"\nversion = "2.0"\nsource = { registry = "x" }\n', + encoding="utf-8", + ) + bom = sbom.generate(lock, None) + (dep,) = bom["components"] + assert dep["purl"] == "pkg:pypi/dep-a@2.0" and "licenses" not in dep + assert dep["scope"] == "required" diff --git a/tools/release/install_update.py b/tools/release/install_update.py new file mode 100644 index 00000000..80b5ddae --- /dev/null +++ b/tools/release/install_update.py @@ -0,0 +1,227 @@ +"""PL-0516: side-by-side install, atomic switch and one-step rollback for a Windows Studio install. + +Generalizes the OwnerDev ``releases/`` + ``current``/``previous`` pattern +(``tools/dev/update_owner_dev_*.ps1``) into a hash-verified, testable tool: + + python -m tools.release.install_update manifest PAYLOAD_DIR --version V + python -m tools.release.install_update stage INSTALL_ROOT PAYLOAD_DIR [--expect-manifest-sha256 HEX] + python -m tools.release.install_update activate INSTALL_ROOT V + python -m tools.release.install_update rollback INSTALL_ROOT + python -m tools.release.install_update status INSTALL_ROOT + +Layout under INSTALL_ROOT: ``releases//`` (immutable, each with ``install-manifest.json`` +listing SHA-256 and size of every file) and ``state.json`` ``{"current", "previous"}``. A +launcher starts ``releases/``. The switch is one ``os.replace`` of +``state.json``, so a crash leaves either the old or the new state, never a mix. Activate and +rollback re-verify the release they switch to. Only ``current`` and ``previous`` are kept. + +This never builds, signs or downloads anything; signing and the real installer stay external +gates. Exit codes: 0 PASS, 1 verification failed, 2 refused precondition. Stdlib only. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import sys +import uuid +from pathlib import Path +from typing import Any + +MANIFEST = "install-manifest.json" +STATE = "state.json" +FORMAT = "packlab.install-manifest.v1" +_VERSION = re.compile(r"[0-9A-Za-z][0-9A-Za-z._+-]{0,127}\Z") + + +class InstallError(Exception): + """A refused precondition; the install state was not changed.""" + + +class VerificationError(Exception): + """Release files do not match their manifest.""" + + +def _sha256(path: Path) -> str: + with open(path, "rb") as handle: + return hashlib.file_digest(handle, "sha256").hexdigest() + + +def _files(root: Path) -> list[Path]: + out = [] + for path in sorted(root.rglob("*")): + if path.is_symlink() or (path.is_dir() and path.is_junction()): + raise InstallError(f"refusing a link: {path}") + if path.is_file() and path.relative_to(root).as_posix() != MANIFEST: + out.append(path) + return out + + +def _version(value: str) -> str: + if not _VERSION.match(value) or value in {".", ".."}: + raise InstallError(f"unsafe version name: {value!r}") + return value + + +def write_manifest(payload: Path, version: str) -> str: + """Build side: record every payload file; returns the manifest SHA-256.""" + payload = Path(payload) + files = { + p.relative_to(payload).as_posix(): {"sha256": _sha256(p), "size": p.stat().st_size} + for p in _files(payload) + } + raw = json.dumps( + {"format": FORMAT, "version": _version(version), "files": files}, sort_keys=True, indent=1 + ).encode("utf-8") + (payload / MANIFEST).write_bytes(raw + b"\n") + return hashlib.sha256(raw + b"\n").hexdigest() + + +def verify(release: Path, expect_manifest_sha256: str | None = None) -> dict[str, Any]: + release = Path(release) + try: + raw = (release / MANIFEST).read_bytes() + manifest = json.loads(raw) + except (OSError, ValueError) as error: + raise VerificationError(f"unreadable manifest: {error}") from error + if expect_manifest_sha256 and hashlib.sha256(raw).hexdigest() != expect_manifest_sha256.lower(): + raise VerificationError("manifest digest differs from the expected value") + if not isinstance(manifest, dict) or manifest.get("format") != FORMAT: + raise VerificationError("unknown manifest format") + _version(str(manifest.get("version"))) + listed = manifest.get("files") + if not isinstance(listed, dict): + raise VerificationError("manifest lists no files") + present = {p.relative_to(release).as_posix(): p for p in _files(release)} + problems = [f"unlisted file: {rel}" for rel in sorted(set(present) - set(listed))] + for rel, entry in sorted(listed.items()): + path = present.get(rel) + if path is None: + problems.append(f"missing: {rel}") + elif ( + not isinstance(entry, dict) + or path.stat().st_size != entry.get("size") + or _sha256(path) != entry.get("sha256") + ): + problems.append(f"content differs: {rel}") + if problems: + raise VerificationError("; ".join(problems)) + return manifest + + +def read_state(root: Path) -> dict[str, str | None]: + path = Path(root) / STATE + if not path.exists(): + return {"current": None, "previous": None} + state = json.loads(path.read_text(encoding="utf-8")) + return {"current": state.get("current"), "previous": state.get("previous")} + + +def _write_state(root: Path, current: str, previous: str | None) -> None: + tmp = root / f".{STATE}.tmp-{uuid.uuid4().hex}" + tmp.write_bytes(json.dumps({"current": current, "previous": previous}).encode() + b"\n") + os.replace(tmp, root / STATE) + + +def stage(root: Path, payload: Path, expect_manifest_sha256: str | None = None) -> str: + """Copy a payload side by side into ``releases/``; returns the version.""" + root, payload = Path(root), Path(payload) + version = _version(str(verify(payload, expect_manifest_sha256)["version"])) + releases = root / "releases" + target = releases / version + if target.exists(): + raise InstallError(f"release already staged: {version}") + releases.mkdir(parents=True, exist_ok=True) + tmp = releases / f".stage-{uuid.uuid4().hex}" + try: + shutil.copytree(payload, tmp, symlinks=True) + verify(tmp, expect_manifest_sha256) # the copy is what will run + os.replace(tmp, target) + except BaseException: + shutil.rmtree(tmp, ignore_errors=True) + raise + return version + + +def activate(root: Path, version: str) -> list[str]: + """Switch ``current`` to a staged release; returns releases that could not be pruned.""" + root = Path(root) + release = root / "releases" / _version(version) + if not release.is_dir(): + raise InstallError(f"release not staged: {version}") + verify(release) + state = read_state(root) + if state["current"] == version: + return [] + _write_state(root, version, state["current"]) + return _prune(root) + + +def rollback(root: Path) -> str: + """Swap ``current`` and ``previous``; returns the version now current.""" + root = Path(root) + state = read_state(root) + previous = state["previous"] + if not previous or not (root / "releases" / _version(previous)).is_dir(): + raise InstallError("no previous release to roll back to") + verify(root / "releases" / previous) + _write_state(root, previous, state["current"]) + return previous + + +def _prune(root: Path) -> list[str]: + state = read_state(root) + keep = {state["current"], state["previous"]} + left = [] + for path in (root / "releases").iterdir(): + if path.name not in keep and not path.name.startswith("."): + # ponytail: a release still running keeps locked files on Windows; retried next activate + shutil.rmtree(path, ignore_errors=True) + if path.exists(): + left.append(path.name) + return left + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="install_update") + sub = parser.add_subparsers(dest="command", required=True) + p = sub.add_parser("manifest") + p.add_argument("payload", type=Path) + p.add_argument("--version", required=True) + p = sub.add_parser("stage") + p.add_argument("root", type=Path) + p.add_argument("payload", type=Path) + p.add_argument("--expect-manifest-sha256") + p = sub.add_parser("activate") + p.add_argument("root", type=Path) + p.add_argument("version") + for name in ("rollback", "status"): + sub.add_parser(name).add_argument("root", type=Path) + args = parser.parse_args(argv) + try: + if args.command == "manifest": + print(f"MANIFEST_WRITTEN sha256={write_manifest(args.payload, args.version)}") + elif args.command == "stage": + print(f"STAGED {stage(args.root, args.payload, args.expect_manifest_sha256)}") + elif args.command == "activate": + left = activate(args.root, args.version) + print(f"ACTIVE {args.version}" + (f" (not pruned: {', '.join(left)})" if left else "")) + elif args.command == "rollback": + print(f"ROLLED_BACK_TO {rollback(args.root)}") + else: + print(json.dumps(read_state(args.root), sort_keys=True)) + except InstallError as error: + print(f"REFUSED: {error}", file=sys.stderr) + return 2 + except VerificationError as error: + print(f"VERIFY_FAILED: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/release/sbom.py b/tools/release/sbom.py new file mode 100644 index 00000000..adc986f8 --- /dev/null +++ b/tools/release/sbom.py @@ -0,0 +1,127 @@ +"""PL-0516: deterministic CycloneDX 1.5 JSON SBOM from ``uv.lock``. + + python -m tools.release.sbom [--lock uv.lock] [--registry REGISTRY_JSON] [--output FILE] + +Every locked package becomes a component (name, version, ``pkg:pypi`` purl). Packages reached +from the project's runtime dependencies are scope ``required``; dev/workflow-only tools are +``excluded``. A licence is stated only where ``windows_component_license_registry.json`` +records one; everything else is left without a licence claim and marked +``packlab:licence_status=UNREVIEWED`` — this SBOM never clears redistribution, and public builds +stay blocked by the licence gate. Python packages only: native payloads (OCCT, Qt DLLs, +COLMAP/OpenMVS) are covered by the PL-0350 native inventory, not here. No timestamp: the same +lock and registry always give byte-identical output. Stdlib only. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +import tomllib +import uuid +from pathlib import Path +from typing import Any + +REPO = Path(__file__).resolve().parents[2] +DEFAULT_REGISTRY = REPO / "tools" / "packaging" / "windows_component_license_registry.json" + + +def _purl(name: str, version: str) -> str: + return f"pkg:pypi/{name.lower().replace('_', '-')}@{version}" + + +def generate(lock_path: Path, registry_path: Path | None = DEFAULT_REGISTRY) -> dict[str, Any]: + raw = Path(lock_path).read_bytes() + packages = tomllib.loads(raw.decode("utf-8"))["package"] + licences: dict[str, str] = {} + if registry_path is not None: + registry = json.loads(Path(registry_path).read_text(encoding="utf-8")) + licences = { + name: entry["license_identifier"] + for name, entry in registry.get("supplemental_evidence", {}).items() + if isinstance(entry, dict) and entry.get("license_identifier") + } + roots = [p for p in packages if "editable" in p["source"] or "virtual" in p["source"]] + if len(roots) != 1: + raise ValueError(f"expected one project package in the lock, found {len(roots)}") + root = roots[0] + by_name = {p["name"]: p for p in packages} + runtime: set[str] = set() + pending = [d["name"] for d in root.get("dependencies", [])] + while pending: # transitive closure of the runtime dependencies + name = pending.pop() + if name not in runtime: + runtime.add(name) + pending.extend(d["name"] for d in by_name[name].get("dependencies", [])) + + def ref(p: dict[str, Any]) -> str: + return _purl(p["name"], p["version"]) + + components = [] + for p in sorted(packages, key=lambda p: (p["name"], p["version"])): + if p is root: + continue + component: dict[str, Any] = { + "type": "library", + "bom-ref": ref(p), + "name": p["name"], + "version": p["version"], + "purl": ref(p), + "scope": "required" if p["name"] in runtime else "excluded", + } + if p["name"] in licences: + component["licenses"] = [{"expression": licences[p["name"]]}] + else: + component["properties"] = [{"name": "packlab:licence_status", "value": "UNREVIEWED"}] + components.append(component) + dependencies = [] + for p in sorted(packages, key=lambda p: (p["name"], p["version"])): + names = {d["name"] for d in p.get("dependencies", [])} + for group in p.get("dev-dependencies", {}).values(): + names |= {d["name"] for d in group} + dependencies.append( + {"ref": ref(p), "dependsOn": sorted(ref(by_name[n]) for n in names if n in by_name)} + ) + lock_sha = hashlib.sha256(raw).hexdigest() + project = {"type": "application", "bom-ref": ref(root), "name": root["name"]} + project |= {"version": root["version"], "purl": ref(root)} + if root["name"] in licences: + project["licenses"] = [{"expression": licences[root["name"]]}] + return { + "bomFormat": "CycloneDX", + "specVersion": "1.5", + "serialNumber": f"urn:uuid:{uuid.uuid5(uuid.NAMESPACE_URL, 'uv.lock:' + lock_sha)}", + "version": 1, + "metadata": { + "component": project, + "properties": [ + {"name": "packlab:uv_lock_sha256", "value": lock_sha}, + {"name": "packlab:release_authorization", "value": "NOT_RELEASE_AUTHORIZED"}, + ], + }, + "components": components, + "dependencies": dependencies, + } + + +def render(bom: dict[str, Any]) -> bytes: + return (json.dumps(bom, indent=2, sort_keys=True) + "\n").encode("utf-8") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="sbom") + parser.add_argument("--lock", type=Path, default=REPO / "uv.lock") + parser.add_argument("--registry", type=Path, default=DEFAULT_REGISTRY) + parser.add_argument("--output", type=Path) + args = parser.parse_args(argv) + data = render(generate(args.lock, args.registry)) + if args.output is None: + sys.stdout.buffer.write(data) + else: + args.output.write_bytes(data) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 84491d3dad98f7ab9c7a4d560d4956c717f228e4 Mon Sep 17 00:00:00 2001 From: Sekiph82 Date: Thu, 3 Dec 2026 23:38:46 +0300 Subject: [PATCH 2/5] fix(ops): PL-0516 review fixes (version-tied SBOM licences, link refusal, state checks) - sbom: a registry licence counts only when its recorded version (version field or .../tree/ in upstream_reference) equals the locked one; else UNREVIEWED. - backup: refuse any symlink/junction in the backup tree incl. root and directories; close the source connection if opening the destination fails. - install_update: corrupt state.json -> InstallError (exit 2); activate/rollback check manifest version equals the directory name; `is not None` digest check; root link refused. - docs: server --tokens/--oidc/jwks_file live outside --data and need their own protected backup. - tests: link refusal (both tools), missing referenced objects, failure after the staged copy (both tools), corrupt state, renamed release, version-tied licences. Co-Authored-By: Claude Opus 5.5 --- docs/ecosystem/PL-0516_OPERATIONS.md | 14 ++++++-- server/src/packlab_server/backup.py | 18 ++++++++--- tests/server/test_backup.py | 48 ++++++++++++++++++++++++++++ tests/tools/test_install_update.py | 47 +++++++++++++++++++++++++++ tests/tools/test_sbom.py | 36 +++++++++++++++++++++ tools/release/install_update.py | 32 +++++++++++++++---- tools/release/sbom.py | 27 ++++++++++++---- 7 files changed, 203 insertions(+), 19 deletions(-) diff --git a/docs/ecosystem/PL-0516_OPERATIONS.md b/docs/ecosystem/PL-0516_OPERATIONS.md index f2ea885d..6aaa330c 100644 --- a/docs/ecosystem/PL-0516_OPERATIONS.md +++ b/docs/ecosystem/PL-0516_OPERATIONS.md @@ -27,6 +27,11 @@ files and `manifest.json` (SHA-256 + size of every file). object the snapshot references exists when the object copy runs. `verify` re-checks this (every `revisions.assets` hash must be in the backup). - In-progress resumable uploads (`uploads/`) are not backed up; clients resume or restart them. +- **Server configuration is not in the backup.** The `--tokens` file, the `--oidc` config and + any `jwks_file` it names live outside `--data` and hold credentials/trust anchors. Back them + up separately into protected (access-controlled, encrypted) storage, never next to the data + backup on shared media and never in Git; a restore needs them to start the server. +- A symlink or junction anywhere in a backup (the root, any directory or file) is refused. - Object files are checked against their content address while copying. ``` @@ -72,8 +77,9 @@ python -m tools.release.install_update status C:\PackLab - `stage` verifies the payload, copies it side by side, verifies the copy, then renames it into `releases\`; an existing version is refused, links/junctions are refused. -- `activate` / `rollback` re-verify the release they switch to; on failure `state.json` is - unchanged. +- `activate` / `rollback` re-verify the release they switch to, including that its manifest + version equals its directory name; on failure `state.json` is unchanged. A corrupt + `state.json` is refused (exit 2), not guessed at. - After `activate` only `current` and `previous` are kept. A release staged but not yet activated is pruned by the next `activate` of a different version: stage and activate one version at a time. Files locked by a still-running old version are left and reported. @@ -131,7 +137,9 @@ python -m tools.release.sbom --output packlab.cdx.json CycloneDX 1.5 JSON with every `uv.lock` package: name, version, `pkg:pypi` purl, dependency graph, scope `required` (runtime closure of the project dependencies) or `excluded` (dev/workflow -tools). A licence is stated only where the licence registry records one; all others carry +tools). A licence is stated only where the licence registry records one for the locked version +(registry `version`, or a version in `upstream_reference` `.../tree/`, must equal the +lock; entries pinned only to a commit are accepted as recorded); all others carry `packlab:licence_status=UNREVIEWED`. Output is byte-identical for the same lock and registry (no timestamp; serial number derived from the `uv.lock` SHA-256). Scope: Python packages only — native payloads (OCCT, Qt DLLs inside wheels, COLMAP/OpenMVS, MSVC runtime) are covered by the diff --git a/server/src/packlab_server/backup.py b/server/src/packlab_server/backup.py index 1dc90b31..69414204 100644 --- a/server/src/packlab_server/backup.py +++ b/server/src/packlab_server/backup.py @@ -58,6 +58,13 @@ def _sibling_temp(path: Path) -> Path: return path.with_name(f".{path.name}.tmp-{uuid.uuid4().hex}") +def _refuse_links(root: Path) -> None: + """No symlink or junction anywhere in the tree (directories included), nor the root.""" + for path in [root, *root.rglob("*")]: + if path.is_symlink() or path.is_junction(): + raise VerificationError(f"refusing a link or junction: {path}") + + def _free_target(path: Path) -> None: if path.is_symlink() or (path.exists() and (not path.is_dir() or any(path.iterdir()))): raise BackupError(f"target exists and is not an empty directory: {path}") @@ -75,12 +82,14 @@ def create(data_dir: Path, backup_dir: Path) -> str: stage.mkdir(parents=True) try: src = sqlite3.connect(source_db) - dst = sqlite3.connect(stage / DB_NAME) try: - src.backup(dst) - dst.execute("PRAGMA journal_mode=DELETE") # one self-contained file, no -wal + dst = sqlite3.connect(stage / DB_NAME) + try: + src.backup(dst) + dst.execute("PRAGMA journal_mode=DELETE") # one self-contained file, no -wal + finally: + dst.close() finally: - dst.close() src.close() files = {DB_NAME: _entry(stage / DB_NAME)} objects = data_dir / "objects" @@ -118,6 +127,7 @@ def verify(backup_dir: Path, expect_manifest_sha256: str | None = None) -> dict[ """Raise ``VerificationError`` unless every file matches the manifest, nothing extra is present, the database passes ``integrity_check`` and every referenced asset is present.""" backup_dir = Path(backup_dir) + _refuse_links(backup_dir) try: raw = (backup_dir / MANIFEST).read_bytes() manifest = json.loads(raw) diff --git a/tests/server/test_backup.py b/tests/server/test_backup.py index f2b87a2c..5cc93edd 100644 --- a/tests/server/test_backup.py +++ b/tests/server/test_backup.py @@ -114,3 +114,51 @@ def test_cli_exit_codes(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> N assert backup.main(["verify", str(tmp_path / "bk"), "--expect-manifest-sha256", "0" * 64]) == 1 assert backup.main(["restore", str(tmp_path / "bk"), str(tmp_path / "live")]) == 2 assert backup.main(["restore", str(tmp_path / "bk"), str(tmp_path / "new")]) == 0 + + +def test_link_or_junction_anywhere_in_the_backup_is_refused(tmp_path: Path) -> None: + from tests.ci.test_library_backup import _link + + _seed(tmp_path / "live").close() + backup.create(tmp_path / "live", tmp_path / "bk") + (tmp_path / "elsewhere").mkdir() + _link(tmp_path / "bk" / "objects" / "zz", tmp_path / "elsewhere") # an (empty) linked dir + with pytest.raises(backup.VerificationError, match="link or junction"): + backup.verify(tmp_path / "bk") + with pytest.raises(backup.VerificationError, match="link or junction"): + backup.restore(tmp_path / "bk", tmp_path / "restored") + assert not (tmp_path / "restored").exists() + + +def test_revision_referencing_a_missing_object_is_refused(tmp_path: Path) -> None: + _seed(tmp_path / "live").close() + backup.create(tmp_path / "live", tmp_path / "bk") + manifest_path = tmp_path / "bk" / backup.MANIFEST + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + rel = next(r for r in manifest["files"] if r.startswith("objects/")) + del manifest["files"][rel] + (tmp_path / "bk" / rel).unlink() + manifest_path.write_text(json.dumps(manifest), encoding="utf-8") + with pytest.raises(backup.VerificationError, match="reference missing objects"): + backup.verify(tmp_path / "bk") + + +def test_restore_fails_closed_when_the_staged_copy_is_bad( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import shutil + + _seed(tmp_path / "live").close() + backup.create(tmp_path / "live", tmp_path / "bk") + real_copytree = shutil.copytree + + def corrupting_copytree(src: Path, dst: Path) -> object: + monkeypatch.undo() # copytree recurses through the module global + result = real_copytree(src, dst) + next(p for p in Path(dst, "objects").rglob("*") if p.is_file()).write_bytes(b"bad") + return result + + monkeypatch.setattr(shutil, "copytree", corrupting_copytree) + with pytest.raises(backup.VerificationError, match="content differs"): + backup.restore(tmp_path / "bk", tmp_path / "restored") + assert {p.name for p in tmp_path.iterdir()} == {"bk", "live"} # no target, no temp left diff --git a/tests/tools/test_install_update.py b/tests/tools/test_install_update.py index 9fd32642..594cd361 100644 --- a/tests/tools/test_install_update.py +++ b/tests/tools/test_install_update.py @@ -62,3 +62,50 @@ def test_expected_manifest_digest_and_refusals(tmp_path: Path) -> None: iu.activate(root, "..") assert iu.main(["status", str(root)]) == 0 assert iu.main(["activate", str(root), "9.9.9"]) == 2 + + +def test_links_in_payload_are_refused(tmp_path: Path) -> None: + from tests.ci.test_library_backup import _link + + payload = _payload(tmp_path, "4.0.0", "x") + (tmp_path / "elsewhere").mkdir() + _link(payload / "linked", tmp_path / "elsewhere") + with pytest.raises(iu.InstallError, match="link"): + iu.stage(tmp_path / "install", payload) + assert iu.main(["stage", str(tmp_path / "install"), str(payload)]) == 2 + + +def test_stage_fails_closed_when_the_copy_is_bad( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + root = tmp_path / "install" + real_copytree = iu.shutil.copytree + + def corrupting_copytree(src: Path, dst: Path, **kwargs: bool) -> object: + monkeypatch.undo() # copytree recurses through the module global + result = real_copytree(src, dst, **kwargs) + Path(dst, "app", "PackLab.exe").write_text("bad", encoding="utf-8") + return result + + monkeypatch.setattr(iu.shutil, "copytree", corrupting_copytree) + with pytest.raises(iu.VerificationError, match="content differs"): + iu.stage(root, _payload(tmp_path, "5.0.0", "good")) + assert list((root / "releases").iterdir()) == [] # nothing staged, no temp left + + +def test_corrupt_state_and_renamed_release_are_refused(tmp_path: Path) -> None: + import shutil + + root = tmp_path / "install" + iu.stage(root, _payload(tmp_path, "6.0.0", "x")) + iu.activate(root, "6.0.0") + shutil.copytree(root / "releases" / "6.0.0", root / "releases" / "6.0.1") + with pytest.raises(iu.VerificationError, match="differs from directory"): + iu.activate(root, "6.0.1") + assert iu.read_state(root)["current"] == "6.0.0" + for corrupt in ("{not json", "[1]", '{"current": "../evil"}'): + (root / iu.STATE).write_text(corrupt, encoding="utf-8") + with pytest.raises(iu.InstallError, match="corrupt"): + iu.read_state(root) + assert iu.main(["status", str(root)]) == 2 + assert iu.main(["rollback", str(root)]) == 2 diff --git a/tests/tools/test_sbom.py b/tests/tools/test_sbom.py index 3eaeef3f..71df945c 100644 --- a/tests/tools/test_sbom.py +++ b/tests/tools/test_sbom.py @@ -46,3 +46,39 @@ def test_licence_comes_only_from_the_registry(tmp_path: Path) -> None: (dep,) = bom["components"] assert dep["purl"] == "pkg:pypi/dep-a@2.0" and "licenses" not in dep assert dep["scope"] == "required" + + +def test_licence_claim_is_tied_to_the_locked_version(tmp_path: Path) -> None: + import json + + lock = tmp_path / "uv.lock" + lock.write_text( + 'version = 1\n[[package]]\nname = "app"\nversion = "1.0"\nsource = { editable = "." }\n' + + "".join( + f'[[package]]\nname = "{n}"\nversion = "2.0"\nsource = {{ registry = "x" }}\n' + for n in ("exact", "stale", "tree-ok", "tree-stale", "commit") + ), + encoding="utf-8", + ) + tree = "https://example.invalid/p/tree/" + entries = { + "exact": {"version": "2.0"}, + "stale": {"version": "1.9"}, + "tree-ok": {"upstream_reference": tree + "2.0"}, + "tree-stale": {"upstream_reference": tree + "v1.9"}, + "commit": {"upstream_reference": tree + "ab" * 20}, + } + registry = tmp_path / "registry.json" + registry.write_text( + json.dumps( + { + "supplemental_evidence": { + n: {"license_identifier": "MIT"} | e for n, e in entries.items() + } + } + ), + encoding="utf-8", + ) + bom = sbom.generate(lock, registry) + licensed = {c["name"] for c in bom["components"] if "licenses" in c} + assert licensed == {"exact", "tree-ok", "commit"} diff --git a/tools/release/install_update.py b/tools/release/install_update.py index 80b5ddae..b4e5d9a9 100644 --- a/tools/release/install_update.py +++ b/tools/release/install_update.py @@ -51,10 +51,16 @@ def _sha256(path: Path) -> str: return hashlib.file_digest(handle, "sha256").hexdigest() +def _is_link(path: Path) -> bool: + return path.is_symlink() or path.is_junction() + + def _files(root: Path) -> list[Path]: + if _is_link(root): + raise InstallError(f"refusing a link: {root}") out = [] for path in sorted(root.rglob("*")): - if path.is_symlink() or (path.is_dir() and path.is_junction()): + if _is_link(path): raise InstallError(f"refusing a link: {path}") if path.is_file() and path.relative_to(root).as_posix() != MANIFEST: out.append(path) @@ -88,7 +94,10 @@ def verify(release: Path, expect_manifest_sha256: str | None = None) -> dict[str manifest = json.loads(raw) except (OSError, ValueError) as error: raise VerificationError(f"unreadable manifest: {error}") from error - if expect_manifest_sha256 and hashlib.sha256(raw).hexdigest() != expect_manifest_sha256.lower(): + if ( + expect_manifest_sha256 is not None + and hashlib.sha256(raw).hexdigest() != expect_manifest_sha256.lower() + ): raise VerificationError("manifest digest differs from the expected value") if not isinstance(manifest, dict) or manifest.get("format") != FORMAT: raise VerificationError("unknown manifest format") @@ -117,8 +126,17 @@ def read_state(root: Path) -> dict[str, str | None]: path = Path(root) / STATE if not path.exists(): return {"current": None, "previous": None} - state = json.loads(path.read_text(encoding="utf-8")) - return {"current": state.get("current"), "previous": state.get("previous")} + try: + state = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(state, dict): + raise ValueError("not an object") + values = {key: state.get(key) for key in ("current", "previous")} + for value in values.values(): + if value is not None: + _version(str(value)) + except (OSError, ValueError, InstallError) as error: + raise InstallError(f"corrupt {STATE}: {error}") from error + return values def _write_state(root: Path, current: str, previous: str | None) -> None: @@ -153,7 +171,8 @@ def activate(root: Path, version: str) -> list[str]: release = root / "releases" / _version(version) if not release.is_dir(): raise InstallError(f"release not staged: {version}") - verify(release) + if verify(release).get("version") != version: + raise VerificationError(f"release manifest version differs from directory {version}") state = read_state(root) if state["current"] == version: return [] @@ -168,7 +187,8 @@ def rollback(root: Path) -> str: previous = state["previous"] if not previous or not (root / "releases" / _version(previous)).is_dir(): raise InstallError("no previous release to roll back to") - verify(root / "releases" / previous) + if verify(root / "releases" / previous).get("version") != previous: + raise VerificationError(f"release manifest version differs from directory {previous}") _write_state(root, previous, state["current"]) return previous diff --git a/tools/release/sbom.py b/tools/release/sbom.py index adc986f8..488fc9e9 100644 --- a/tools/release/sbom.py +++ b/tools/release/sbom.py @@ -17,12 +17,14 @@ import argparse import hashlib import json +import re import sys import tomllib import uuid from pathlib import Path from typing import Any +_TREE_VERSION = re.compile(r"/tree/v?([0-9]+(?:\.[0-9]+)+[0-9A-Za-z.+-]*)(?:/|$)") REPO = Path(__file__).resolve().parents[2] DEFAULT_REGISTRY = REPO / "tools" / "packaging" / "windows_component_license_registry.json" @@ -31,17 +33,30 @@ def _purl(name: str, version: str) -> str: return f"pkg:pypi/{name.lower().replace('_', '-')}@{version}" +def _evidence_version_matches(entry: dict[str, Any], locked: str | None) -> bool: + """A licence claim counts only for the version it was reviewed at: an explicit + ``version``, else a version-like ``.../tree/`` in ``upstream_reference``. Entries + pinned only to a commit carry no version to compare and are accepted.""" + if "version" in entry: + return str(entry["version"]) == locked + match = _TREE_VERSION.search(str(entry.get("upstream_reference", ""))) + return match is None or match.group(1) == locked + + def generate(lock_path: Path, registry_path: Path | None = DEFAULT_REGISTRY) -> dict[str, Any]: raw = Path(lock_path).read_bytes() packages = tomllib.loads(raw.decode("utf-8"))["package"] - licences: dict[str, str] = {} + registry: dict[str, Any] = {} if registry_path is not None: registry = json.loads(Path(registry_path).read_text(encoding="utf-8")) - licences = { - name: entry["license_identifier"] - for name, entry in registry.get("supplemental_evidence", {}).items() - if isinstance(entry, dict) and entry.get("license_identifier") - } + locked = {p["name"]: p["version"] for p in packages} + licences = { + name: entry["license_identifier"] + for name, entry in registry.get("supplemental_evidence", {}).items() + if isinstance(entry, dict) + and entry.get("license_identifier") + and _evidence_version_matches(entry, locked.get(name)) + } roots = [p for p in packages if "editable" in p["source"] or "virtual" in p["source"]] if len(roots) != 1: raise ValueError(f"expected one project package in the lock, found {len(roots)}") From 742754606ea553d120d46f4915aacac8aff198de Mon Sep 17 00:00:00 2001 From: Sekiph82 Date: Thu, 3 Dec 2026 23:51:50 +0300 Subject: [PATCH 3/5] fix(ops): PL-0516 round-2 review fixes (SBOM licences need a version, state types, junctions) - sbom: a licence counts only when the registry entry records a version (version field or tree ref) equal to the locked one; commit pins and tag refs are UNREVIEWED. - licence registry: record version for pyside6, pyside6-addons, pyside6-essentials, shiboken6 (6.11.2) and cadquery-ocp-novtk, cadquery-ocp-proxy (7.9.3.1.1), as already recorded in license_file and source_evidence. The same 11 components stay licensed. - install_update: non-string state.json values are corrupt (exit 2, no TypeError). - backup create: refuse junctions in the object store too. - tests: commit pin unlicensed, non-string previous in state, payload root that is a junction. Co-Authored-By: Claude Opus 5.5 --- docs/ecosystem/PL-0516_OPERATIONS.md | 3 ++- server/src/packlab_server/backup.py | 4 ++-- tests/tools/test_install_update.py | 17 ++++++++++++++++- tests/tools/test_sbom.py | 2 +- .../windows_component_license_registry.json | 6 ++++++ tools/release/install_update.py | 4 +++- tools/release/sbom.py | 4 ++-- 7 files changed, 32 insertions(+), 8 deletions(-) diff --git a/docs/ecosystem/PL-0516_OPERATIONS.md b/docs/ecosystem/PL-0516_OPERATIONS.md index 6aaa330c..d7ba405c 100644 --- a/docs/ecosystem/PL-0516_OPERATIONS.md +++ b/docs/ecosystem/PL-0516_OPERATIONS.md @@ -139,7 +139,8 @@ CycloneDX 1.5 JSON with every `uv.lock` package: name, version, `pkg:pypi` purl, scope `required` (runtime closure of the project dependencies) or `excluded` (dev/workflow tools). A licence is stated only where the licence registry records one for the locked version (registry `version`, or a version in `upstream_reference` `.../tree/`, must equal the -lock; entries pinned only to a commit are accepted as recorded); all others carry +lock; entries with neither, such as commit pins or tag refs, are not tied to a version and +count as unreviewed); all others carry `packlab:licence_status=UNREVIEWED`. Output is byte-identical for the same lock and registry (no timestamp; serial number derived from the `uv.lock` SHA-256). Scope: Python packages only — native payloads (OCCT, Qt DLLs inside wheels, COLMAP/OpenMVS, MSVC runtime) are covered by the diff --git a/server/src/packlab_server/backup.py b/server/src/packlab_server/backup.py index 69414204..8baef983 100644 --- a/server/src/packlab_server/backup.py +++ b/server/src/packlab_server/backup.py @@ -94,8 +94,8 @@ def create(data_dir: Path, backup_dir: Path) -> str: files = {DB_NAME: _entry(stage / DB_NAME)} objects = data_dir / "objects" for path in sorted(objects.rglob("*")) if objects.is_dir() else []: - if path.is_symlink(): - raise BackupError(f"refusing a link in the object store: {path}") + if path.is_symlink() or path.is_junction(): + raise BackupError(f"refusing a link or junction in the object store: {path}") if not path.is_file() or not _OBJECT.match(path.name): continue # directories and put_object temp files rel = path.relative_to(data_dir).as_posix() diff --git a/tests/tools/test_install_update.py b/tests/tools/test_install_update.py index 594cd361..8f5cab82 100644 --- a/tests/tools/test_install_update.py +++ b/tests/tools/test_install_update.py @@ -75,6 +75,16 @@ def test_links_in_payload_are_refused(tmp_path: Path) -> None: assert iu.main(["stage", str(tmp_path / "install"), str(payload)]) == 2 +def test_payload_root_that_is_a_link_is_refused(tmp_path: Path) -> None: + from tests.ci.test_library_backup import _link + + real = _payload(tmp_path, "4.1.0", "x") # valid on its own + _link(tmp_path / "linked-payload", real) + with pytest.raises(iu.InstallError, match="link"): + iu.stage(tmp_path / "install", tmp_path / "linked-payload") + assert not (tmp_path / "install" / "releases" / "4.1.0").exists() + + def test_stage_fails_closed_when_the_copy_is_bad( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -103,7 +113,12 @@ def test_corrupt_state_and_renamed_release_are_refused(tmp_path: Path) -> None: with pytest.raises(iu.VerificationError, match="differs from directory"): iu.activate(root, "6.0.1") assert iu.read_state(root)["current"] == "6.0.0" - for corrupt in ("{not json", "[1]", '{"current": "../evil"}'): + for corrupt in ( + "{not json", + "[1]", + '{"current": "../evil"}', + '{"current": "6.0.0", "previous": 7}', + ): (root / iu.STATE).write_text(corrupt, encoding="utf-8") with pytest.raises(iu.InstallError, match="corrupt"): iu.read_state(root) diff --git a/tests/tools/test_sbom.py b/tests/tools/test_sbom.py index 71df945c..e1a87ddc 100644 --- a/tests/tools/test_sbom.py +++ b/tests/tools/test_sbom.py @@ -81,4 +81,4 @@ def test_licence_claim_is_tied_to_the_locked_version(tmp_path: Path) -> None: ) bom = sbom.generate(lock, registry) licensed = {c["name"] for c in bom["components"] if "licenses" in c} - assert licensed == {"exact", "tree-ok", "commit"} + assert licensed == {"exact", "tree-ok"} # commit pins carry no version: UNREVIEWED diff --git a/tools/packaging/windows_component_license_registry.json b/tools/packaging/windows_component_license_registry.json index 27922c11..a56ffd04 100644 --- a/tools/packaging/windows_component_license_registry.json +++ b/tools/packaging/windows_component_license_registry.json @@ -8,6 +8,7 @@ "reason": "The exact staged distribution includes its release license file; package metadata omits a normalized SPDX identifier." }, "cadquery-ocp-novtk": { + "version": "7.9.3.1.1", "license_identifier": "Apache-2.0", "license_file": "tools/packaging/windows_licenses/OCP-7.9.3.1.1/LICENSE.txt", "license_sha256": "a13caea71627202ad33cc4cafafdd18e667e16716488f8d9c568127121fb89fd", @@ -53,6 +54,7 @@ ] }, "cadquery-ocp-proxy": { + "version": "7.9.3.1.1", "license_identifier": "Apache-2.0", "license_file": "tools/packaging/windows_licenses/OCP-7.9.3.1.1/LICENSE.txt", "license_sha256": "a13caea71627202ad33cc4cafafdd18e667e16716488f8d9c568127121fb89fd", @@ -100,6 +102,7 @@ "reason": "Only exact pyi_rth_*.py files under the locked distribution rthooks directory are classified here; upstream marks runtime hooks Apache-2.0. Standard analysis hooks remain build-only." }, "pyside6": { + "version": "6.11.2", "license_identifier": "LGPL-3.0-only", "license_file": "tools/packaging/windows_licenses/Qt-PySide6-6.11.2/LGPL-3.0-only.txt", "license_sha256": "da7eabb7bafdf7d3ae5e9f223aa5bdc1eece45ac569dc21b3b037520b4464768", @@ -110,6 +113,7 @@ "provenance_class": "PROJECT_OFFICIAL_BINARY" }, "pyside6-addons": { + "version": "6.11.2", "license_identifier": "LGPL-3.0-only", "license_file": "tools/packaging/windows_licenses/Qt-PySide6-6.11.2/LGPL-3.0-only.txt", "license_sha256": "da7eabb7bafdf7d3ae5e9f223aa5bdc1eece45ac569dc21b3b037520b4464768", @@ -200,6 +204,7 @@ } }, "pyside6-essentials": { + "version": "6.11.2", "license_identifier": "LGPL-3.0-only", "license_file": "tools/packaging/windows_licenses/Qt-PySide6-6.11.2/LGPL-3.0-only.txt", "license_sha256": "da7eabb7bafdf7d3ae5e9f223aa5bdc1eece45ac569dc21b3b037520b4464768", @@ -292,6 +297,7 @@ } }, "shiboken6": { + "version": "6.11.2", "license_identifier": "LGPL-3.0-only", "license_file": "tools/packaging/windows_licenses/Qt-PySide6-6.11.2/LGPL-3.0-only.txt", "license_sha256": "da7eabb7bafdf7d3ae5e9f223aa5bdc1eece45ac569dc21b3b037520b4464768", diff --git a/tools/release/install_update.py b/tools/release/install_update.py index b4e5d9a9..8d66a1a6 100644 --- a/tools/release/install_update.py +++ b/tools/release/install_update.py @@ -133,7 +133,9 @@ def read_state(root: Path) -> dict[str, str | None]: values = {key: state.get(key) for key in ("current", "previous")} for value in values.values(): if value is not None: - _version(str(value)) + if not isinstance(value, str): + raise ValueError(f"version is not a string: {value!r}") + _version(value) except (OSError, ValueError, InstallError) as error: raise InstallError(f"corrupt {STATE}: {error}") from error return values diff --git a/tools/release/sbom.py b/tools/release/sbom.py index 488fc9e9..77180ecb 100644 --- a/tools/release/sbom.py +++ b/tools/release/sbom.py @@ -36,11 +36,11 @@ def _purl(name: str, version: str) -> str: def _evidence_version_matches(entry: dict[str, Any], locked: str | None) -> bool: """A licence claim counts only for the version it was reviewed at: an explicit ``version``, else a version-like ``.../tree/`` in ``upstream_reference``. Entries - pinned only to a commit carry no version to compare and are accepted.""" + with neither (commit pins, tag refs) are not tied to a version: UNREVIEWED.""" if "version" in entry: return str(entry["version"]) == locked match = _TREE_VERSION.search(str(entry.get("upstream_reference", ""))) - return match is None or match.group(1) == locked + return match is not None and match.group(1) == locked def generate(lock_path: Path, registry_path: Path | None = DEFAULT_REGISTRY) -> dict[str, Any]: From 7b321aab8a438874570ab422582165cc650bcf6f Mon Sep 17 00:00:00 2001 From: Sekiph82 Date: Thu, 3 Dec 2026 23:52:04 +0300 Subject: [PATCH 4/5] docs(coordination): PR #108 round-2 peer review record (PL-0516 V02) Co-Authored-By: Claude Opus 5.5 --- .../M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md diff --git a/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md b/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md new file mode 100644 index 00000000..a9b9fd1b --- /dev/null +++ b/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md @@ -0,0 +1,16 @@ +# CLAUDE_PEER_REVIEW PL-0516 V02 (PR #108, round 2) +Reviewer: independent Claude reviewer subagent (not implementer). Base e55fb6ea -> head 84491d3dad98f7ab9c7a4d560d4956c717f228e4. +Verdict: PASS_WITH_FIXES — M1 must be fixed before merge (CHANGES_REQUIRED for round-1 item 1); items 2-7 PASS. +Evidence (run by reviewer in an isolated worktree, since removed): +- pytest tests/server: 81 passed; tests/tools/test_install_update.py + tests/tools/test_sbom.py + tests/server/test_backup.py: 18 passed, 0 skipped (junction-based link tests really executed). +- ruff check core apps server tools tests: pass. mypy --no-incremental core apps server tools: 0 issues / 348 files. +- Not run: GitHub Actions, full suite. +Findings: +- MEDIUM M1 tools/release/sbom.py:43 — entries without `version` and without a parsable /tree/ (commit pins, tag refs like openssl-3.0.16) are accepted, so a licence attaches to any locked version. Today 5 components (cadquery-ocp-novtk, cadquery-ocp-proxy, pyside6-addons, pyside6-essentials, shiboken6) are licensed only via this path; a PySide6 bump would silently keep LGPL-3.0-only. Fix: `match is not None and match.group(1) == locked`; add "version" (6.11.2 for pyside6/pyside6-addons/pyside6-essentials/shiboken6, 7.9.3.1.1 for cadquery-ocp-novtk/-proxy — the versions the registry already records in license_file / source_evidence); update test_sbom.py:84 and the docs SBOM sentence. Reviewer trial: same 11 licensed components, inventory and engine-bundle tests pass. +- LOW L1 tools/release/install_update.py:133-136 — non-string state values (e.g. "previous": 7) pass validation; rollback then raises uncaught TypeError (reproduced). Require isinstance str. +- LOW L2 server/src/packlab_server/backup.py:97 — create checks the object store for symlinks only; also refuse junctions. +- LOW L3 install_update.py:59-60 — root-is-link refusal has no test. +Round-1 items 2 (docs config backup), 3 (backup link refusal), 4 (tests), 5 (state/version checks), 6 (is not None), 7 (src close) verified PASS. +Limits: no physical/factory evidence involved; review covers source, diff and local test runs only. + +Fixes: 742754606ea553d120d46f4915aacac8aff198de From b56217b1f63fca4a845a6e1874dab8d5852ce785 Mon Sep 17 00:00:00 2001 From: Sekiph82 Date: Thu, 3 Dec 2026 23:56:32 +0300 Subject: [PATCH 5/5] PL-0516: peer review V02 fix verification addendum (PASS) Co-Authored-By: Claude Opus 5.5 --- .../sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md b/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md index a9b9fd1b..a38236b1 100644 --- a/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md +++ b/coordination/sessions/M21-C001/CLAUDE_PEER_REVIEW_PL0516_V02.md @@ -14,3 +14,11 @@ Round-1 items 2 (docs config backup), 3 (backup link refusal), 4 (tests), 5 (sta Limits: no physical/factory evidence involved; review covers source, diff and local test runs only. Fixes: 742754606ea553d120d46f4915aacac8aff198de + +## Addendum: fix verification (head 7b321aab8a438874570ab422582165cc650bcf6f, fix 742754606ea553d120d46f4915aacac8aff198de) +Verdict: PASS — M1, L1, L2, L3 resolved; no open findings from rounds 1-2. +- M1: sbom.py rule `match is not None and match.group(1) == locked`; registry `version` added (6.11.2 for pyside6/pyside6-addons/pyside6-essentials/shiboken6, 7.9.3.1.1 for cadquery-ocp-novtk/-proxy). Real SBOM still licenses the same 11 components. +- L1: read_state rejects non-str state values (InstallError, exit 2). L2: backup.create refuses junctions in the object store. L3: payload-root link test added. +- Reviewer evidence (isolated worktree, PYTHONPATH=".;core/src;server/src;apps/windows-studio/src", imports confirmed from the worktree): tests/server 81 passed; test_install_update + test_sbom + test_windows_redistribution_inventory + test_engine_bundle 35 passed, 0 skipped; ruff pass; mypy 0 issues/348 files. +- Mutation checks: reverting each of the root-link refusal, the state type check and the SBOM rule makes its corresponding test fail (tests are not tautological). +- Info: no direct test for the backup.create junction refusal (one-line change mirroring tested logic). Actions not run by reviewer.