Assemble signed offline repositories and package records into images
@@ -117,3 +117,15 @@ python3 tools/keyring.py seed "$work/new-client/root" "$trusted_fingerprint"
117117`vinix-keyring` owns the public certificate and fingerprint in `/usr/share/vpac/keyrings/`. Image assembly initializes the mutable GnuPG keybox and trust database under `/etc/vpac.d/gnupg/`. The seed operation accepts a new destination or the empty directory installed by the vpac port. The builder compares the independently supplied fingerprint before packaging and again before seeding.
118118
119119The worker used a disposable test signer in `foundation/keyring-04`. It rejected a wrong pin, installed the signed keyring, seeded an empty vpac key directory, verified the signed database and used that keyring alone for an offline vpac install of musl into another empty root. A second seed attempt preserved the existing keyring. The checksum manifest has SHA-256 `3ffb71fb6832d43af1cb2ec588d2d6a75ece24060d22bd1e70be59392a64d30d`. The target-vpac guest transaction and provisioning the release signer's public certificate remain release checks.
120+
121+### Assemble an image with an offline repository
122+
123+Start with a fresh `feed install` client that includes `vinix-keyring`. Run this on the build worker with GNU cp, GnuPG and the installed-root auditor. The resulting `$output/root` is the input to the architecture's image builder.
124+
125+```sh
126+python3 tools/stage-image.py "$arch" "$client" "$repo" "$output" "$work/audit" "$trusted_fingerprint"
127+```
128+
129+The tool audits the package-owned root, makes a separate copy, and seeds the verification keyring using the distributor's fingerprint. It copies the local package records into `/var/lib/vpac/local`, checks their versions against the signed database, and installs the repository under `/var/lib/vinix/repository/$arch`. It verifies the database, file index and each included package signature, and compares the payload hashes with the signed database. The sync cache receives independent copies of the database and signature. Assembly exposes the final root only after these checks pass.
130+
131+On both targets, the worker installed musl and the public key package, then assembled a three-package offline repository. Using the build-box vpac with its paths directed into each resulting image, it installed the third package, `netbase`, from the embedded repository and recorded its ownership in that image. The logs are in `foundation/offline-stage-01` with receipt manifest SHA-256 `98bfcbdaed3aa81690bcdac5a8b0edbdfd91f5ab6ae8a7cc9f3fdd50e6252fb1`.
@@ -0,0 +1,115 @@
1+"""Assemble an offline image root from a signed vpac client and its package repository."""
2+import argparse
3+import hashlib
4+import shutil
5+import subprocess
6+import sys
7+import tarfile
8+import tempfile
9+from pathlib import Path
10+
11+
12+def package_fields(data):
13+ fields = {}
14+ for block in data.strip().split("\n\n"):
15+ name, _, value = block.partition("\n")
16+ if name.startswith("%") and name.endswith("%"):
17+ fields[name.strip("%")] = value
18+ return fields
19+
20+
21+def write_directory(root, relative):
22+ directory = root / relative
23+ if directory.resolve() != directory:
24+ raise ValueError(f"unexpected guest symlink at {relative}")
25+ directory.mkdir(parents=True, exist_ok=True)
26+ return directory
27+
28+
29+def snapshot(repo, dest, ring, arch, gpg_home):
30+ def verify(path):
31+ subprocess.run(["gpgv", "--homedir", gpg_home, "--keyring", ring, str(path) + ".sig", path],
32+ check=True, stdout=subprocess.DEVNULL)
33+
34+ def copy(name):
35+ if Path(name).name != name or not name or name in (".", ".."):
36+ raise ValueError(f"invalid repository filename {name!r}")
37+ source = repo / name
38+ if source.resolve().parent != repo or not source.is_file():
39+ raise ValueError(f"missing or external repository file: {name}")
40+ target = dest / name
41+ if target.exists():
42+ raise ValueError(f"duplicate repository filename: {name}")
43+ shutil.copyfile(source, target)
44+ return target
45+
46+ for index in ("vinix.db", "vinix.files"):
47+ file = copy(index)
48+ copy(index + ".sig")
49+ verify(file)
50+ indexed = {}
51+ with tarfile.open(dest / "vinix.db", "r:gz") as database:
52+ for entry in database:
53+ if not entry.isfile() or Path(entry.name).name != "desc":
54+ continue
55+ info = package_fields(database.extractfile(entry).read().decode())
56+ name, version, package_arch = (info[field] for field in ("NAME", "VERSION", "ARCH"))
57+ filename = info["FILENAME"]
58+ if (name in indexed or package_arch not in (arch, "any") or
59+ filename != f"{name}-{version}-{package_arch}.pkg.tar.zst"):
60+ raise ValueError(f"invalid database record for {name}")
61+ archive = copy(filename)
62+ copy(filename + ".sig")
63+ with archive.open("rb") as stream:
64+ if hashlib.file_digest(stream, "sha256").hexdigest() != info["SHA256SUM"]:
65+ raise ValueError(f"archive differs from signed index: {filename}")
66+ verify(archive)
67+ indexed[name] = version
68+ if not indexed:
69+ raise ValueError("empty signed package index")
70+ return indexed
71+
72+
73+def stage(args):
74+ client, repo, output = args.client.resolve(), args.repo.resolve(), args.output.resolve()
75+ if any(output.is_relative_to(path) for path in (client, repo)):
76+ raise ValueError("put image output outside the client and repository")
77+ output.mkdir()
78+ audit = subprocess.check_output([args.auditor, args.arch, client], text=True)
79+ (output / "audited-root.log").write_text(audit)
80+ with tempfile.TemporaryDirectory(dir=output) as directory:
81+ root = Path(directory) / "image"
82+ subprocess.run(["cp", "-a", "--reflink=auto", client / "root", root], check=True)
83+ # This compares the installed certificate with the independently supplied pin.
84+ seed = Path(__file__).resolve().with_name("keyring.py")
85+ subprocess.run([sys.executable, seed, "seed", root, args.fingerprint], check=True)
86+ package_dir = write_directory(root, "var/lib/vinix/repository/" + args.arch)
87+ if any(package_dir.iterdir()):
88+ raise ValueError("seed repository directory is already populated")
89+ with tempfile.TemporaryDirectory() as gpg_home:
90+ indexed = snapshot(repo / args.arch, package_dir, root / "usr/share/vpac/keyrings/vinix.gpg",
91+ args.arch, gpg_home)
92+ records = client / "db/local"
93+ for description in records.glob("*/desc"):
94+ info = package_fields(description.read_text())
95+ if indexed.get(info["NAME"]) != info["VERSION"]:
96+ raise ValueError(f"installed package missing from seed at its exact version: {info['NAME']}")
97+ db = write_directory(root, "var/lib/vpac")
98+ if any(db.iterdir()):
99+ raise ValueError("package database directory is already populated")
100+ shutil.copytree(records, db / "local")
101+ sync = write_directory(root, "var/lib/vpac/sync")
102+ for name in ("vinix.db", "vinix.db.sig"):
103+ shutil.copyfile(package_dir / name, sync / name)
104+ root.rename(output / "root")
105+ print(audit, end="")
106+ print(f"staged {len(indexed)} signed seed packages and the installed database")
107+
108+
109+if __name__ == "__main__":
110+ parser = argparse.ArgumentParser(description=__doc__)
111+ parser.add_argument("arch", choices=("x86_64", "aarch64"))
112+ for arg in ("client", "repo", "output", "auditor"):
113+ parser.add_argument(arg, type=Path)
114+ parser.add_argument("fingerprint", help="trusted distributor fingerprint from outside the feed")
115+ stage(parser.parse_args())