build(packaging): retain qualified payloads through verified owner archives

This commit is contained in:
DCCONSTRUCTIONS
2026-11-21 20:58:24 +03:00
parent bd8af772d9
commit c45bd6b882
14 changed files with 1241 additions and 33 deletions
+6
View File
@@ -44,6 +44,12 @@ links to that record for monorepo, storage, resource and live-only telemetry rul
terminal, close only your own hold with `finish` (pin qualified/rollback terminal, close only your own hold with `finish` (pin qualified/rollback
outcomes), review its plan and apply it as part of build completion. Never outcomes), review its plan and apply it as part of build completion. Never
expire active holds by age or declare unknown legacy inputs disposable. expire active holds by age or declare unknown legacy inputs disposable.
- Node/X4 owner installers close out their exact unpacked `.deb` duplicates via
`scripts/packaging/qualified_payloads.py` after durable publication and full
hash verification. Keep the installer and `PAYLOAD_LOCATION.json`. Register a
persistent payload hold before a dependent consumer needs loose files; release
it only after that consumer ends. Read retired payloads through the helper,
not by leaving another permanent extracted copy. See `docs/STORAGE_RETENTION.md`.
- Run local Python validation through `scripts/check_python.py pytest|ruff|mypy` - Run local Python validation through `scripts/check_python.py pytest|ruff|mypy`
(pass the usual file/selection arguments). It owns temporary caches, disables (pass the usual file/selection arguments). It owns temporary caches, disables
persistent pytest/Ruff cache output, and cleans its own scratch after child persistent pytest/Ruff cache output, and cleans its own scratch after child
@@ -13,6 +13,7 @@ NODE = Path(__file__).resolve().parents[1]
REPO = NODE.parents[1] REPO = NODE.parents[1]
sys.path.insert(0, str(REPO / "scripts/packaging")) sys.path.insert(0, str(REPO / "scripts/packaging"))
from build_retention import input_hold, publish_input # noqa: E402 from build_retention import input_hold, publish_input # noqa: E402
from qualified_payloads import QualifiedPayloads # noqa: E402
DG = REPO.parent / "NODEDC_DESIGN_GUIDELINE" DG = REPO.parent / "NODEDC_DESIGN_GUIDELINE"
DG_COMMIT = "bbbfa8912f9f51914c6927e13ef32b823c536b9f" DG_COMMIT = "bbbfa8912f9f51914c6927e13ef32b823c536b9f"
@@ -73,7 +74,9 @@ def build(qualified, node_only=False, base=None):
package_name = "mission-core-insta360-x4_" + profile["version"] + "_amd64.deb" package_name = "mission-core-insta360-x4_" + profile["version"] + "_amd64.deb"
if qualified.name != package_name: if qualified.name != package_name:
raise ValueError("Unexpected model package name") raise ValueError("Unexpected model package name")
package = qualified.read_bytes() payloads = QualifiedPayloads(qualified.parent, REPO / 'plugins/insta360-x4/build', REPO)
with payloads.locked() as store:
package = store.read(qualified.name)
if len(package) != profile["bytes"] or hashlib.sha256(package).hexdigest() != profile["sha256"]: if len(package) != profile["bytes"] or hashlib.sha256(package).hexdigest() != profile["sha256"]:
raise ValueError("Qualified model package changed") raise ValueError("Qualified model package changed")
entries = {str(path.relative_to(REPO.parent)): path for path in sorted(set(paths))} entries = {str(path.relative_to(REPO.parent)): path for path in sorted(set(paths))}
@@ -92,7 +95,8 @@ def build(qualified, node_only=False, base=None):
native = json.loads((native_root / "packaging/native-runtime.json").read_text()) native = json.loads((native_root / "packaging/native-runtime.json").read_text())
native_path = native_root / "build/native-runtime" / native["file"] native_path = native_root / "build/native-runtime" / native["file"]
native_bytes = native_path.read_bytes() native_bytes = native_path.read_bytes()
if len(native_bytes) != native["bytes"] or hashlib.sha256(native_bytes).hexdigest() != native["sha256"]: if (len(native_bytes) != native["bytes"]
or hashlib.sha256(native_bytes).hexdigest() != native["sha256"]):
raise ValueError("Qualified VESC Tool runtime changed") raise ValueError("Qualified VESC Tool runtime changed")
entries[REPO.name + "/plugins/vesc/build/native-runtime/" + native["file"]] = native_path entries[REPO.name + "/plugins/vesc/build/native-runtime/" + native["file"]] = native_path
catalog = json.loads((native_root / "packaging/firmware-catalog.json").read_text()) catalog = json.loads((native_root / "packaging/firmware-catalog.json").read_text())
@@ -105,7 +109,9 @@ def build(qualified, node_only=False, base=None):
package_pin=json.loads((native_root / "packaging/package-catalog.json").read_text()) package_pin=json.loads((native_root / "packaging/package-catalog.json").read_text())
package_path=native_root / "build/package-catalog/vesc_pkg_all.rcc" package_path=native_root / "build/package-catalog/vesc_pkg_all.rcc"
package_bytes=package_path.read_bytes() package_bytes=package_path.read_bytes()
if len(package_bytes)!=package_pin["bytes"] or hashlib.sha256(package_bytes).hexdigest()!=package_pin["sha256"]:raise ValueError("Pinned extension catalogue changed") if (len(package_bytes) != package_pin["bytes"]
or hashlib.sha256(package_bytes).hexdigest() != package_pin["sha256"]):
raise ValueError("Pinned extension catalogue changed")
entries[str(package_path.relative_to(REPO.parent))]=package_path entries[str(package_path.relative_to(REPO.parent))]=package_path
usbcan_library = REPO / "plugins/usb-can/build/sdk/libcontrolcanfd.so" usbcan_library = REPO / "plugins/usb-can/build/sdk/libcontrolcanfd.so"
if hashlib.sha256(usbcan_library.read_bytes()).hexdigest() != USB_CAN_SDK_SHA256: if hashlib.sha256(usbcan_library.read_bytes()).hexdigest() != USB_CAN_SDK_SHA256:
@@ -113,13 +119,15 @@ def build(qualified, node_only=False, base=None):
entries[str(usbcan_library.relative_to(REPO.parent))] = usbcan_library entries[str(usbcan_library.relative_to(REPO.parent))] = usbcan_library
metadata = {} metadata = {}
for name, path in entries.items(): for name, path in entries.items():
data = path.read_bytes() data = package if name == virtual else path.read_bytes()
if len(data) > 100 * 1024 * 1024: if len(data) > 100 * 1024 * 1024:
raise ValueError(f"Source file exceeds the artifact bound: {name}") raise ValueError(f"Source file exceeds the artifact bound: {name}")
metadata[name] = { metadata[name] = {
"bytes": len(data), "bytes": len(data),
"sha256": hashlib.sha256(data).hexdigest(), "sha256": hashlib.sha256(data).hexdigest(),
"mode": 0o755 if path.stat().st_mode & stat.S_IXUSR else 0o644, "mode": 0o644 if name == virtual else (
0o755 if path.stat().st_mode & stat.S_IXUSR else 0o644
),
} }
entrypoint = (NODE / "packaging/linux_build_entry.py").read_bytes() entrypoint = (NODE / "packaging/linux_build_entry.py").read_bytes()
manifest = { manifest = {
@@ -146,7 +154,9 @@ def build(qualified, node_only=False, base=None):
payload_names = {name for name, item in metadata.items() payload_names = {name for name, item in metadata.items()
if baseline["files"].get(name) != item} if baseline["files"].get(name) != item}
with base.open("rb") as stream: with base.open("rb") as stream:
manifest["base"] = {"name": base.name, "sha256": hashlib.file_digest(stream, "sha256").hexdigest()} manifest["base"] = {
"name": base.name, "sha256": hashlib.file_digest(stream, "sha256").hexdigest(),
}
manifest["payload_files"] = sorted(payload_names) manifest["payload_files"] = sorted(payload_names)
raw = json.dumps(manifest, sort_keys=True, indent=2).encode() + b"\n" raw = json.dumps(manifest, sort_keys=True, indent=2).encode() + b"\n"
identifier = hashlib.sha256(raw).hexdigest()[:24] identifier = hashlib.sha256(raw).hexdigest()[:24]
@@ -165,6 +175,13 @@ def build(qualified, node_only=False, base=None):
for name, path in entries.items(): for name, path in entries.items():
if name not in payload_names: if name not in payload_names:
continue continue
if name == virtual:
# The verified package may exist only inside the owner installer.
# Stream the captured bytes into the input bundle, without a loose copy.
info = zipfile.ZipInfo('source/' + name, date_time=(2026, 9, 8, 0, 0, 0))
info.external_attr = 0o644 << 16
archive.writestr(info, package)
continue
archive.write( archive.write(
path, path,
"source/" + name, "source/" + name,
@@ -187,6 +204,8 @@ if __name__ == "__main__":
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument("--model-package", type=Path, required=True) parser.add_argument("--model-package", type=Path, required=True)
parser.add_argument("--node-only", action="store_true") parser.add_argument("--node-only", action="store_true")
parser.add_argument("--base", type=Path, help="Complete verified archive already staged in the build root") parser.add_argument(
"--base", type=Path, help="Complete verified archive already staged in the build root",
)
args = parser.parse_args() args = parser.parse_args()
print(json.dumps(build(args.model_package.resolve(), args.node_only, args.base))) print(json.dumps(build(args.model_package.resolve(), args.node_only, args.base)))
@@ -4,17 +4,29 @@ import argparse
import hashlib import hashlib
import json import json
import re import re
import zipfile import sys
from pathlib import Path from pathlib import Path
NODE_DEPENDENCIES = ('timescaledb-2-loader-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb', 'timescaledb-2-oss-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb') NODE_DEPENDENCIES = (
'timescaledb-2-loader-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb',
'timescaledb-2-oss-postgresql-16_2.29.2~ubuntu24.04-1615_amd64.deb',
)
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
REPO = ROOT.parents[1] REPO = ROOT.parents[1]
sys.path.insert(0, str(REPO / 'scripts/packaging'))
from qualified_payloads import QualifiedPayloads # noqa: E402
def build(qualified): def build(qualified):
evidence = json.loads((qualified / "qualification.json").read_text()) with QualifiedPayloads(qualified, ROOT / 'build', REPO).locked() as store:
return _build(store)
def _build(store):
qualified = store.qualified
raw_evidence = (qualified / "qualification.json").read_bytes()
evidence = json.loads(raw_evidence)
if evidence["state"] != "complete": if evidence["state"] != "complete":
raise ValueError("A completed Ubuntu qualification is required") raise ValueError("A completed Ubuntu qualification is required")
candidates = [name for name in evidence["artifacts"] if name.startswith("mission-core-node_")] candidates = [name for name in evidence["artifacts"] if name.startswith("mission-core-node_")]
@@ -26,7 +38,7 @@ def build(qualified):
) )
if not match: if not match:
raise ValueError("Invalid package name") raise ValueError("Invalid package name")
payload = (qualified / package).read_bytes() payload = store.read(package)
expected = evidence["artifacts"][package] expected = evidence["artifacts"][package]
if ( if (
len(payload) != expected["bytes"] len(payload) != expected["bytes"]
@@ -36,12 +48,20 @@ def build(qualified):
files = { files = {
package: payload, package: payload,
"install": (ROOT / "packaging/install-owner-release").read_bytes(), "install": (ROOT / "packaging/install-owner-release").read_bytes(),
"install_release.py": (ROOT / "packaging/vesc_hall_recovery.py").read_bytes() + b"\n" + (ROOT / "packaging/can_maintenance.py").read_bytes() + b"\n" + (ROOT / "packaging/install_owner_release.py").read_bytes(), "install_release.py": b"\n".join(
(ROOT / "packaging" / name).read_bytes()
for name in (
"vesc_hall_recovery.py",
"can_maintenance.py",
"k1_maintenance.py",
"install_owner_release.py",
)
),
} }
# Carry non-Ubuntu dependencies in the actual owner artifact. They were # Carry non-Ubuntu dependencies in the actual owner artifact. They were
# verified against the signed vendor index by the qualified Linux job. # verified against the signed vendor index by the qualified Linux job.
for name in NODE_DEPENDENCIES: for name in NODE_DEPENDENCIES:
data = (qualified / name).read_bytes() data = store.read(name)
info = evidence["artifacts"][name] info = evidence["artifacts"][name]
if len(data) != info["bytes"] or hashlib.sha256(data).hexdigest() != info["sha256"]: if len(data) != info["bytes"] or hashlib.sha256(data).hexdigest() != info["sha256"]:
raise ValueError("Qualified dependency changed") raise ValueError("Qualified dependency changed")
@@ -52,7 +72,7 @@ def build(qualified):
"version": match[1], "version": match[1],
"qualification_profile": "node-package-and-local-ui", "qualification_profile": "node-package-and-local-ui",
"qualification_sha256": hashlib.sha256( "qualification_sha256": hashlib.sha256(
(qualified / "qualification.json").read_bytes() raw_evidence
).hexdigest(), ).hexdigest(),
"clean_image_qualified": False, "clean_image_qualified": False,
"dependencies": list(NODE_DEPENDENCIES), "dependencies": list(NODE_DEPENDENCIES),
@@ -66,15 +86,16 @@ def build(qualified):
raw = json.dumps(manifest, indent=2, sort_keys=True).encode() + b"\n" raw = json.dumps(manifest, indent=2, sort_keys=True).encode() + b"\n"
identifier = hashlib.sha256(raw).hexdigest()[:24] identifier = hashlib.sha256(raw).hexdigest()[:24]
output = ROOT / "build" / ("mission-core-node-install-" + identifier + ".pyz") output = ROOT / "build" / ("mission-core-node-install-" + identifier + ".pyz")
with output.open("xb") as stream, zipfile.ZipFile(stream, "w") as archive: published = store.publish(output, {"__main__.py": entry, "release.json": raw, **files})
for name, data in {"__main__.py": entry, "release.json": raw, **files}.items(): store.register(published, {name: files[name] for name in [package, *NODE_DEPENDENCIES]},
archive.writestr(name, data) 'qualification.json', raw_evidence)
output.chmod(0o600) cleanup = store.closeout()
return { return {
"artifact": str(output), "artifact": str(output),
"release_id": identifier, "release_id": identifier,
"bytes": output.stat().st_size, "bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(), "sha256": published['sha256'],
"payload_cleanup": cleanup,
} }
@@ -0,0 +1,112 @@
"""Reconstruct a qualified Debian package from an exact retained owner release.
Transport only: never installs, invokes package scripts or changes system state.
Both input package and final complete package are SHA-256 verified.
"""
import argparse
import hashlib
import io
import json
import sys
import tarfile
import zipfile
from pathlib import Path
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def parts(raw):
stream, archives = io.BytesIO(raw), {}
assert stream.read(8) == b"!<arch>\n"
while header := stream.read(60):
size = int(header[48:58])
archives[header[:16].decode().strip().rstrip("/")] = stream.read(size)
if size % 2:
stream.read(1)
result = {}
for name in ("control.tar.gz", "data.tar.gz"):
with tarfile.open(fileobj=io.BytesIO(archives[name]), mode="r:gz") as archive:
result[name] = [
(m.name, archive.extractfile(m).read(), m.mode) for m in archive if m.isfile()
]
return result
def build(base, target, output):
old, new = base.read_bytes(), target.read_bytes()
before, after = parts(old), parts(new)
manifest = dict(
base_sha256=sha(old), target_sha256=sha(new), target_name=target.name, archives={}
)
repo = Path(__file__).resolve().parents[3]
with zipfile.ZipFile(output, "x", compression=zipfile.ZIP_DEFLATED) as archive:
archive.writestr("__main__.py", Path(__file__).read_bytes())
archive.writestr("debian.py", (repo / "scripts/packaging/debian.py").read_bytes())
for category, entries in after.items():
originals = {name: (data, mode) for name, data, mode in before[category]}
manifest["archives"][category] = []
for index, (name, data, mode) in enumerate(entries):
changed = originals.get(name) != (data, mode)
key = f"{category}/{index}" if changed else ""
manifest["archives"][category].append(
dict(name=name, mode=mode, key=key, sha256=sha(data))
)
if changed:
archive.writestr(key, data)
archive.writestr("delta.json", json.dumps(manifest))
print(
json.dumps(
dict(path=str(output), bytes=output.stat().st_size, sha256=sha(output.read_bytes()))
)
)
def apply(owner, output):
from debian import package
with zipfile.ZipFile(sys.argv[0]) as delta:
manifest = json.loads(delta.read("delta.json"))
if owner.is_dir():
release = json.loads((owner / "release.json").read_bytes())
candidates = [n for n in release["files"] if n.startswith("mission-core-node_")]
assert len(candidates) == 1 and Path(candidates[0]).name == candidates[0]
raw = (owner / candidates[0]).read_bytes()
else:
with zipfile.ZipFile(owner) as archive:
release = json.loads(archive.read("release.json"))
candidates = [n for n in release["files"] if n.startswith("mission-core-node_")]
assert len(candidates) == 1
raw = archive.read(candidates[0])
assert sha(raw) == manifest["base_sha256"], "Retained base does not match"
before = parts(raw)
result = {}
for category, entries in manifest["archives"].items():
originals = {name: data for name, data, _ in before[category]}
rows = []
for entry in entries:
data = delta.read(entry["key"]) if entry["key"] else originals[entry["name"]]
assert sha(data) == entry["sha256"]
rows.append((entry["name"], data, entry["mode"]))
result[category] = rows
final = package(result["control.tar.gz"], result["data.tar.gz"])
assert sha(final) == manifest["target_sha256"], "Reconstructed package differs"
target = output / manifest["target_name"]
with target.open("xb") as stream:
stream.write(final)
print(json.dumps(dict(package=str(target), sha256=sha(final), bytes=len(final))))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("build", "apply"))
parser.add_argument("base", type=Path)
parser.add_argument("target", type=Path)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.action == "build":
build(args.base, args.target, args.output)
else:
apply(args.base, args.target)
+150
View File
@@ -0,0 +1,150 @@
"""Versioned runtime/UI update over an exact qualified Node package.
Preserves every OS integration, dependency and preparation payload from the
predecessor. Only the executable, version and provenance can change.
"""
import argparse
import hashlib
import json
import re
import sys
from pathlib import Path
from node_package_delta import parts
REPO = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(REPO / "scripts/packaging"))
from debian import package # noqa: E402
from qualified_payloads import QualifiedPayloads # noqa: E402
def verify_embedded_ui(executable):
built = REPO / "apps/node-agent/ui/dist"
embedded = REPO / "apps/node-agent/web/dist"
def files(root):
return {str(p.relative_to(root)): p for p in root.rglob("*") if p.is_file()}
expected, actual = files(built), files(embedded)
if not expected or expected.keys() != actual.keys():
raise ValueError("Built and embedded Node UI inventories differ; sync UI before compiling")
for name, source in expected.items():
if (hashlib.sha256(source.read_bytes()).digest()
!= hashlib.sha256(actual[name].read_bytes()).digest()):
raise ValueError("Built and embedded Node UI differ: " + name)
# Go embed stores these bytes verbatim. Detect a binary compiled before the
# UI was copied, even when both source directories have since been synced.
index = expected["index.html"].read_bytes()
entries = re.findall(rb'<script[^>]+src="([^"]+\.js)"', index)
if not entries or index not in executable:
raise ValueError("Executable does not embed the built Node UI index")
for entry in entries:
path = entry.decode().removeprefix("/").removeprefix("./")
if path not in expected or expected[path].read_bytes() not in executable:
raise ValueError("Executable does not embed the built Node UI entry")
def build(base, base_sha, binary, version, output, uplink=False, vesc_evidence=False):
if output.exists():
raise FileExistsError("Published releases are immutable")
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+-[1-9][0-9]*", version):
raise ValueError("Invalid version")
with QualifiedPayloads(base.parent, REPO / 'apps/node-agent/build', REPO).locked() as store:
raw = store.read(base.name)
if hashlib.sha256(raw).hexdigest() != base_sha:
raise ValueError("Qualified predecessor changed")
archives = parts(raw)
executable = binary.read_bytes()
if executable[:6] != b"\x7fELF\x02\x01" or executable[18:20] != b"\x3e\x00":
raise ValueError("Expected Linux amd64 executable")
verify_embedded_ui(executable)
provenance_path = "usr/share/doc/mission-core-node/provenance.json"
previous = dict((n, d) for n, d, _ in archives["data.tar.gz"])
sources = {}
for folder in (
"apps/node-agent/internal", "apps/node-agent/ui/src", "apps/node-agent/web/dist",
"packages/router-ui/src", "packages/sensor-ui/src",
):
for path in sorted((REPO / folder).rglob("*")):
if path.is_file():
sources[str(path.relative_to(REPO))] = hashlib.sha256(path.read_bytes()).hexdigest()
provenance = dict(schema="missioncore.node.runtime-revision/v1", version=version,
predecessor_sha256=base_sha,
predecessor=json.loads(previous[provenance_path]),
binary_sha256=hashlib.sha256(executable).hexdigest(), sources=sources)
changes = {"usr/lib/mission-core-node/node-agent": executable,
provenance_path: (json.dumps(provenance, indent=2) + "\n").encode()}
if vesc_evidence:
# A diagnostic-only revision must prove that executable statements outside
# this one trace call are identical to the qualified motor controller.
import ast
target = "usr/lib/mission-core-vesc/runtime/remote_control.py"
source = REPO / "plugins/vesc/runtime/remote_control.py"
desired = source.read_bytes()
class WithoutLeaseTrace(ast.NodeTransformer):
def visit_Expr(self, node):
call = node.value
if (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
and ast.unparse(call.func) == "self.trace.add" and call.args
and isinstance(call.args[0], ast.Constant)
and call.args[0].value == "lease_expired"):
return ast.Pass()
return self.generic_visit(node)
def authority(raw):
return ast.dump(WithoutLeaseTrace().visit(ast.parse(raw)), include_attributes=False)
if authority(previous[target]) != authority(desired):
raise ValueError("VESC change exceeds diagnostic trace fields")
changes[target] = desired
sources[str(source.relative_to(REPO))] = hashlib.sha256(desired).hexdigest()
provenance["vesc_evidence_only"] = True
changes[provenance_path] = (json.dumps(provenance, indent=2) + "\n").encode()
if uplink:
packaging = REPO / 'apps/node-agent/packaging'
for path in [packaging / 'uplink_helper.py', packaging / 'qualify_uplink_namespace.py',
*sorted((packaging / 'uplink').glob('*.py'))]:
name = 'usr/lib/mission-core-node/' + str(path.relative_to(packaging))
changes[name] = path.read_bytes()
sources[str(path.relative_to(REPO))] = hashlib.sha256(path.read_bytes()).hexdigest()
provenance['scope'] = ('Runtime and reversible NetBird uplink routing; '
'qualified predecessor retained')
changes[provenance_path] = (json.dumps(provenance, indent=2) + '\n').encode()
controls = []
changed_controls = ['control']
for name, data, mode in archives["control.tar.gz"]:
if name == "control":
data, count = re.subn(rb"(?m)^Version: [^\n]+$", b"Version: " + version.encode(), data)
assert count == 1
if uplink and name == 'prerm':
replacement = (REPO / 'apps/node-agent/packaging/prerm').read_bytes()
if replacement != data:
changed_controls.append(name)
data = replacement
controls.append((name, data, mode))
payload = [(n, changes.get(n, d), m) for n, d, m in archives["data.tar.gz"]]
payload += [(n, d, 0o644) for n, d in changes.items() if n not in previous]
output.parent.mkdir(parents=True, exist_ok=True)
with output.open("xb") as stream:
stream.write(package(controls, payload))
report = dict(version=version, base_sha256=base_sha, bytes=output.stat().st_size,
sha256=hashlib.sha256(output.read_bytes()).hexdigest(),
changed_controls=changed_controls, changed_payloads=list(changes))
output.with_suffix(".json").write_text(json.dumps(report, indent=2) + "\n")
return report
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--base", type=Path, required=True)
parser.add_argument("--base-sha256", required=True)
parser.add_argument("--binary", type=Path, required=True)
parser.add_argument("--version", required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument('--uplink', action='store_true')
parser.add_argument('--vesc-evidence', action='store_true')
args = parser.parse_args()
print(json.dumps(build(args.base, args.base_sha256, args.binary, args.version, args.output,
uplink=args.uplink, vesc_evidence=args.vesc_evidence)))
@@ -0,0 +1,41 @@
"""Packaging must reject a stale local UI even after its sources were synced."""
import importlib.util
import sys
import tempfile
import unittest
from pathlib import Path
spec = importlib.util.spec_from_file_location(
"repack_runtime", Path(__file__).with_name("repack_runtime.py")
)
module = importlib.util.module_from_spec(spec)
sys.path.insert(0, str(Path(__file__).parent))
spec.loader.exec_module(module)
class EmbeddedUITest(unittest.TestCase):
def test_stale_directory_and_stale_binary_are_rejected(self):
with tempfile.TemporaryDirectory() as folder:
old_root = module.REPO
module.REPO = Path(folder)
try:
built = module.REPO / 'apps/node-agent/ui/dist'
embedded = module.REPO / 'apps/node-agent/web/dist'
for root in [built, embedded]:
(root / 'assets').mkdir(parents=True)
(root / 'index.html').write_bytes(b'<script src="/assets/app.js"></script>')
(root / 'assets/app.js').write_bytes(b'new interface')
current = b'ELF prefix' + (built / 'index.html').read_bytes() + b'new interface'
module.verify_embedded_ui(current)
with self.assertRaisesRegex(ValueError, 'Executable'):
module.verify_embedded_ui(b'old executable')
(embedded / 'assets/app.js').write_bytes(b'old interface')
with self.assertRaisesRegex(ValueError, 'UI differ'):
module.verify_embedded_ui(current)
(embedded / 'orphan.js').write_bytes(b'orphan')
with self.assertRaisesRegex(ValueError, 'inventories differ'):
module.verify_embedded_ui(current)
finally:
module.REPO = old_root
if __name__ == '__main__':
unittest.main()
+72 -1
View File
@@ -17,6 +17,7 @@ run at publication; service journal rotation runs in the owning writer.
| Imported Gaussian worlds, recordings, evidence, missions, plans, accepted maps, session map versions | Durable application data. No TTL. Deletion belongs to the owning product workflow or an explicitly reviewed archive/removal operation. | | Imported Gaussian worlds, recordings, evidence, missions, plans, accepted maps, session map versions | Durable application data. No TTL. Deletion belongs to the owning product workflow or an explicitly reviewed archive/removal operation. |
| Simulation qualifications, computation experiments/results, engineering materials | Preserve unique evidence and the exact input/configuration/result relationship. An old experiment is not a cache. Archive only with a verified destination and complete dependency inventory. | | Simulation qualifications, computation experiments/results, engineering materials | Preserve unique evidence and the exact input/configuration/result relationship. An old experiment is not a cache. Archive only with a verified destination and complete dependency inventory. |
| Qualified releases and rollback artifacts | Explicit pins; retain independently of the intermediate count. Retiring a release requires removing its pin by name and recording the reason. | | Qualified releases and rollback artifacts | Explicit pins; retain independently of the intermediate count. Retiring a release requires removing its pin by name and recording the reason. |
| Unpacked qualified `.deb` duplicates | Node/X4 owner builders automatically retire only their exact packaged payloads after atomic installer publication and full SHA-256 verification. The installer, qualification evidence and recovery pointer remain. Persistent consumer holds or an unavailable reader check defer cleanup. See qualified payload closeout below. |
| Intermediate Linux build inputs | Keep two most recently **published, completed, unpinned** inputs per line, plus every transitive base of retained inputs. Lines are `node/node-only`, `node/node-core`, `x4/native`, `x4/package`, `x4/owner`. Enforced by `scripts/packaging/build_retention.py`. | | Intermediate Linux build inputs | Keep two most recently **published, completed, unpinned** inputs per line, plus every transitive base of retained inputs. Lines are `node/node-only`, `node/node-core`, `x4/native`, `x4/package`, `x4/owner`. Enforced by `scripts/packaging/build_retention.py`. |
| Active/disconnected builds, transfers and qualifications | Persistent active hold, with owner token. No automatic expiry. Explicit terminal outcome releases the hold. Eight unfinished inputs per archive family block the next publication. Node profiles share this conservative unfinished limit. | | Active/disconnected builds, transfers and qualifications | Persistent active hold, with owner token. No automatic expiry. Explicit terminal outcome releases the hold. Eight unfinished inputs per archive family block the next publication. Node profiles share this conservative unfinished limit. |
| Old or unknown inputs | Protected as `legacy-unreviewed`; importing into the registry requires a named protective pin. Neither mtime nor lack of a reference proves that a legacy file is disposable. | | Old or unknown inputs | Protected as `legacy-unreviewed`; importing into the registry requires a named protective pin. Neither mtime nor lack of a reference proves that a legacy file is disposable. |
@@ -102,7 +103,7 @@ build log. All unknown inputs remain protected even without registry enrollment.
## Integrity, interruption and audit ## Integrity, interruption and audit
Only exact build-input filenames directly under `apps/node-agent/build` and For `build_retention.py`, only exact build-input filenames directly under `apps/node-agent/build` and
`plugins/insta360-x4/build` are eligible. Installers, `.deb` releases, qualified `plugins/insta360-x4/build` are eligible. Installers, `.deb` releases, qualified
subdirectories, rollback copies and runtime data are outside the allowlist. subdirectories, rollback copies and runtime data are outside the allowlist.
Symlinks and traversal paths are refused. Publications and maintenance share an Symlinks and traversal paths are refused. Publications and maintenance share an
@@ -132,6 +133,76 @@ presence and verified identity.
space: hardlinks/APFS clones can share blocks. Receipts report filesystem free space: hardlinks/APFS clones can share blocks. Receipts report filesystem free
space before/after; concurrent system activity can affect that delta. space before/after; concurrent system activity can affect that delta.
## Qualified payload closeout (2026-11-16)
The owner installer builders previously kept both their `.pyz` installer and
all loose `.deb` files. Input-bundle retention cannot remove these: qualified
directories deliberately sit outside its allowlist. The separate
`scripts/packaging/qualified_payloads.py` now owns this narrow output lifecycle.
It is called by the Node and X4 `build_owner_release.py` entry points; the X4
standalone Ubuntu builder carries the same helper inside its verified bundle.
It does not change the Linux input-bundle policy, installed software, runtime
data, project sources, Worker storage or retained installers.
Publication and closeout share OS locks. The builder writes a private temporary
installer, flushes it and atomically publishes without replacement. A recorded
interrupted publication can remove only its own temporary inode on the next
invocation. An existing installer is reused only if every member matches.
Before any loose payload is removed, the helper verifies the complete installer
SHA-256, each archived member, the qualification report and all loose candidates.
It durably records member names, sizes and hashes in `PAYLOAD_LOCATION.json`.
Only the exact `.deb` members admitted by that builder are eligible. Unknown
files, directories, legacy pointers without managed membership, symlinks and
changed evidence never become cleanup candidates. Hardlinks are handled without
removing another owner's path. Logical bytes are not a physical-space guarantee.
The pointer journals each unlink and the final result. If the process stops
between unlinks, retry validates the retained archive and finishes the remaining
paths. There is no age-based sweep or background timer. Normal successful
publication closes out automatically; deferred/interrupted work is retried by
the same builder, explicit `retry`, or release of a consumer hold. The builder's
JSON includes `payload_cleanup` (`complete` or `deferred` with a reason).
`QualifiedPayloads.read(name)` reads a still-present package or its verified
installer member, without recreating a persistent copy. Both owner builders use
this path, including repeated/concurrent packaging after closeout. The Node
Linux source generator also embeds the retained X4 package directly from verified
archive bytes; `repack_runtime.py` reads its retained Node predecessor the same
way. Neither recreates a loose base package. Older
one-off repack scripts that directly open a `.deb` path must use this API or
register a hold **before** installer publication. They are not silently made
archive-aware. The historical v1 recovery pointers created by the reviewed
one-time cleanup remain readable and are not automatically enrolled for deletion.
A dependent consumer spanning multiple commands uses a persistent named hold.
Under the canonical repository, set `qualified_dir` to its exact qualification
directory and `archive_dir` to `apps/node-agent/build` or
`plugins/insta360-x4/build` (canonical absolute paths):
```sh
.venv/bin/python scripts/packaging/qualified_payloads.py hold \
--repository "$PWD" --archive-root "$archive_dir" --qualified "$qualified_dir" \
--owner "dependent transfer/qualification"
# Retain the returned token; after that consumer is confirmed terminal:
.venv/bin/python scripts/packaging/qualified_payloads.py release \
--repository "$PWD" --archive-root "$archive_dir" --qualified "$qualified_dir" \
--token "$payload_token"
```
Holds survive restarts and never expire. Releasing the final hold runs closeout.
An open reader detected by `lsof`, a missing `lsof` executable, a timeout or an
ambiguous reader-check result defers removal while preserving the installer and
loose payloads. After resolving the condition, use `retry` with the same three
path arguments. Do not force-delete the files or another consumer's hold.
`tests/test_qualified_payloads.py` exercises real Node/X4 builders using tiny
payloads, concurrent/repeated publication, the standalone isolated X4 entry,
reader deferral, persistent holds, modified evidence, publication failure,
interrupted deletion, pointer-write failure, hardlinks and unsafe paths. No
production rebuild or Core service restart is needed for this operator-script
change; it takes effect on subsequent owner packaging.
## Acceptance ## Acceptance
`tests/test_build_retention.py` covers separate lines, transitive bases, release `tests/test_build_retention.py` covers separate lines, transitive bases, release
@@ -62,6 +62,9 @@ def build(report, original=None):
"build_owner_release.py", "build_owner_release.py",
) )
} }
files['qualified_payloads.py'] = (
ROOT.parents[1] / 'scripts/packaging/qualified_payloads.py'
).read_bytes()
manifest = { manifest = {
"schema": "missioncore.insta360.owner-wrapper-build/v1", "schema": "missioncore.insta360.owner-wrapper-build/v1",
"qualified": json.loads(report.read_text()), "qualified": json.loads(report.read_text()),
@@ -4,19 +4,30 @@ import argparse
import hashlib import hashlib
import json import json
import re import re
import zipfile import sys
from pathlib import Path from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
REPO = ROOT.parents[1]
# The isolated Ubuntu wrapper carries the exact same helper beside this script.
sys.path.insert(0, str(REPO / 'scripts/packaging'))
sys.path.insert(0, str(Path(__file__).resolve().parent))
from qualified_payloads import QualifiedPayloads # noqa: E402
def build(qualified, capture_stitch_input=False, verify_original=None): def build(qualified, capture_stitch_input=False, verify_original=None):
expected = json.loads((qualified / "package-result.json").read_text()) with QualifiedPayloads(qualified, ROOT / 'build', REPO).locked() as store:
return _build(store, capture_stitch_input, verify_original)
def _build(store, capture_stitch_input, verify_original):
raw_evidence = (store.qualified / "package-result.json").read_bytes()
expected = json.loads(raw_evidence)
version = expected["version"] version = expected["version"]
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[1-9][0-9]*)?", version): if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[1-9][0-9]*)?", version):
raise ValueError("Invalid qualified version") raise ValueError("Invalid qualified version")
package_name = "mission-core-insta360-x4_" + version + "_amd64.deb" package_name = "mission-core-insta360-x4_" + version + "_amd64.deb"
package = (qualified / package_name).read_bytes() package = store.read(package_name)
if ( if (
len(package) != expected["bytes"] len(package) != expected["bytes"]
or hashlib.sha256(package).hexdigest() != expected["sha256"] or hashlib.sha256(package).hexdigest() != expected["sha256"]
@@ -49,17 +60,15 @@ def build(qualified, capture_stitch_input=False, verify_original=None):
raw = json.dumps(manifest, sort_keys=True, indent=2).encode() + b"\n" raw = json.dumps(manifest, sort_keys=True, indent=2).encode() + b"\n"
ident = hashlib.sha256(raw).hexdigest()[:24] ident = hashlib.sha256(raw).hexdigest()[:24]
output = ROOT / "build" / ("mission-core-x4-install-" + ident + ".pyz") output = ROOT / "build" / ("mission-core-x4-install-" + ident + ".pyz")
with output.open("xb") as stream, zipfile.ZipFile(stream, "w") as archive: published = store.publish(output, {"__main__.py": entrypoint, "release.json": raw, **files})
for name, data in {"__main__.py": entrypoint, "release.json": raw, **files}.items(): store.register(published, {package_name: package}, 'package-result.json', raw_evidence)
info = zipfile.ZipInfo(name, date_time=(2026, 9, 8, 0, 0, 0)) cleanup = store.closeout()
info.external_attr = 0o600 << 16
archive.writestr(info, data)
output.chmod(0o600)
return { return {
"artifact": str(output), "artifact": str(output),
"release_id": ident, "release_id": ident,
"bytes": output.stat().st_size, "bytes": output.stat().st_size,
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(), "sha256": published['sha256'],
"payload_cleanup": cleanup,
} }
+4 -1
View File
@@ -30,7 +30,10 @@ def tarball(files):
item.size, item.mode, item.uid, item.gid = len(data), mode, 0, 0 item.size, item.mode, item.uid, item.gid = len(data), mode, 0, 0
item.uname = item.gname = "root" item.uname = item.gname = "root"
archive.addfile(item, io.BytesIO(data)) archive.addfile(item, io.BytesIO(data))
return gzip.compress(stream.getvalue(), mtime=0) compressed = gzip.compress(stream.getvalue(), mtime=0)
# Python 3.12 delegates this header to zlib: macOS emits OS=19, Linux=3.
# The payload is platform-neutral; use the RFC 1952 unknown-OS byte.
return compressed[:9] + b"\xff" + compressed[10:]
def ar_member(name, data): def ar_member(name, data):
+369
View File
@@ -0,0 +1,369 @@
"""Close out exact packaged .deb copies, never scan or expire build/runtime data.
Owner builders hold this lock from reading qualification through publication and
closeout. Persistent named holds cover consumers spanning multiple commands.
The installer and recovery pointer are durable before any source is unlinked.
"""
import argparse
import fcntl
import hashlib
import json
import os
import re
import shutil
import stat
import subprocess
import uuid
import zipfile
from contextlib import contextmanager
from pathlib import Path
class PayloadError(ValueError):
pass
def digest(stream):
h = hashlib.sha256()
while chunk := stream.read(1024 * 1024):
h.update(chunk)
return h.hexdigest()
def plain(path):
s = path.lstat()
if not stat.S_ISREG(s.st_mode):
raise PayloadError(f"Not a regular file: {path}")
return s
def identity(path):
s = plain(path)
# Removing another hardlink changes ctime/nlink, not this content identity.
return s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns
def checksum(path):
before = identity(path)
with path.open('rb') as stream:
value = digest(stream)
if identity(path) != before:
raise PayloadError(f"File changed while reading: {path}")
return value
def sync_directory(path):
fd = os.open(path, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def atomic_json(path, value):
if path.exists() or path.is_symlink():
plain(path)
temporary = path.with_name('.' + path.name + '.' + uuid.uuid4().hex)
try:
with temporary.open('x') as stream:
temporary.chmod(0o600)
json.dump(value, stream, indent=2)
stream.write('\n')
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
sync_directory(path.parent)
finally:
temporary.unlink(missing_ok=True)
def directory(path):
path = Path(path).absolute()
if path.resolve(strict=True) != path or not path.is_dir():
raise PayloadError(f"Directory must be canonical, without symlinks: {path}")
return path
def open_files(paths):
"""Conservatively defer on an unavailable ownership check; never guess."""
command = shutil.which('lsof')
if not command:
return 'open-file-check-unavailable'
try:
result = subprocess.run(
[command, '-nP', '-F', 'n', '--', *map(str, paths)],
capture_output=True, text=True, timeout=15,
)
except (OSError, subprocess.TimeoutExpired):
return 'open-file-check-unavailable'
if result.returncode == 0 and result.stdout.strip():
return 'payload-in-use'
if result.returncode != 1 or result.stderr.strip():
return 'open-file-check-unavailable'
return None
class QualifiedPayloads:
def __init__(self, qualified, archive_root, repository):
self.qualified = directory(qualified)
self.archive_root = directory(archive_root)
self.repository = directory(repository)
self.pointer = self.qualified / 'PAYLOAD_LOCATION.json'
self.holds = self.qualified / 'PAYLOAD_HOLDS.json'
self.verified_archives = {}
@contextmanager
def locked(self):
# One publication lock also serializes builders using the same installer
# destination from different qualification directories.
descriptors = []
try:
for p in [self.archive_root / '.payload-publication.lock',
self.qualified / '.payload-closeout.lock']:
fd = os.open(p, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
descriptors.append(fd)
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise PayloadError('Invalid payload lock')
fcntl.flock(fd, fcntl.LOCK_EX)
yield self
finally:
for fd in reversed(descriptors):
os.close(fd)
def name(self, name):
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.+~%-]*\.deb', name):
raise PayloadError('Only named .deb payloads are managed')
return name
def document(self):
if not self.pointer.exists() and not self.pointer.is_symlink():
return {'schema': 'missioncore.qualified-payload-location/v1', 'files': []}
plain(self.pointer)
doc = json.loads(self.pointer.read_text())
if doc.get('schema') != 'missioncore.qualified-payload-location/v1':
raise PayloadError('Unknown recovery pointer schema')
return doc
def relative(self, path):
if path.is_relative_to(self.repository):
return str(path.relative_to(self.repository))
return str(path)
def resolve_archive(self, record):
path = Path(record['path'])
path = path if path.is_absolute() else self.repository / path
archive_name = r'mission-core-(node|x4)-install-[a-f0-9]{24}\.pyz'
if path.parent != self.archive_root or not re.fullmatch(archive_name, path.name):
raise PayloadError('Recovery archive is outside the owner installer directory')
current = identity(path)
key = (str(path), current, record['sha256'])
if key not in self.verified_archives:
if current[2] != record['bytes'] or checksum(path) != record['sha256']:
raise PayloadError('Recovery archive changed')
self.verified_archives[key] = True
return path
def read(self, name):
name = self.name(name)
path = self.qualified / name
if path.exists() or path.is_symlink():
before = identity(path)
data = path.read_bytes()
if identity(path) != before:
raise PayloadError('Payload changed while reading')
return data
matches = [r for r in self.document()['files']
if r['path'] in (str(path), self.relative(path))]
if len(matches) != 1:
raise PayloadError(f'No unique recovery record for {name}')
record = matches[0]
if record['member'] != name:
raise PayloadError('Recovery member name changed')
archive = self.resolve_archive(record['archive'])
with zipfile.ZipFile(archive) as z:
if z.namelist().count(name) != 1 or z.getinfo(name).file_size != record['bytes']:
raise PayloadError('Invalid recovery member')
data = z.read(name)
if hashlib.sha256(data).hexdigest() != record['sha256']:
raise PayloadError('Recovery payload changed')
return data
def publish(self, output, files):
"""Publish atomically; an identical retry reuses the immutable installer."""
if output.parent != self.archive_root:
raise PayloadError('Unexpected installer destination')
for name in files:
if Path(name).name != name or name in ('.', '..'):
raise PayloadError('Unsafe installer member')
pending = self.archive_root / '.payload-publication.json'
if pending.exists() or pending.is_symlink():
plain(pending)
previous = json.loads(pending.read_text())
name = previous['temporary']
temporary_name = r'\.mission-core-(node|x4)-install-[a-f0-9]{24}\.pyz\.[a-f0-9]{32}'
if not re.fullmatch(temporary_name, name):
raise PayloadError('Unsafe interrupted publication path')
leftover = self.archive_root / name
if leftover.exists() or leftover.is_symlink():
if list(identity(leftover)[:2]) != previous['identity']:
raise PayloadError('Interrupted publication identity changed')
leftover.unlink()
pending.unlink()
sync_directory(self.archive_root)
if not output.exists() and not output.is_symlink():
temporary = output.with_name('.' + output.name + '.' + uuid.uuid4().hex)
try:
with temporary.open('xb') as stream:
temporary.chmod(0o600)
atomic_json(pending, {'temporary': temporary.name,
'identity': list(identity(temporary)[:2])})
with zipfile.ZipFile(stream, 'w') as z:
for name, data in files.items():
info = zipfile.ZipInfo(name, date_time=(2026, 9, 8, 0, 0, 0))
info.external_attr = 0o600 << 16
z.writestr(info, data)
stream.flush()
os.fsync(stream.fileno())
# Refuse replacement, including concurrent foreign writes.
os.link(temporary, output)
sync_directory(output.parent)
finally:
temporary.unlink(missing_ok=True)
pending.unlink(missing_ok=True)
sync_directory(self.archive_root)
plain(output)
with zipfile.ZipFile(output) as z:
if len(z.namelist()) != len(files) or set(z.namelist()) != set(files):
raise PayloadError('Existing installer members differ')
for name, data in files.items():
with z.open(name) as stream:
if digest(stream) != hashlib.sha256(data).hexdigest():
raise PayloadError('Published installer content differs')
return {'path': self.relative(output), 'bytes': output.stat().st_size,
'sha256': checksum(output)}
def register(self, archive, payloads, report_name, report_bytes):
"""Persist recovery before closeout; do not change foreign pointer entries."""
self.resolve_archive(archive)
if report_name not in ('qualification.json', 'package-result.json'):
raise PayloadError('Unknown qualification report')
expected_report = hashlib.sha256(report_bytes).hexdigest()
if checksum(self.qualified / report_name) != expected_report:
raise PayloadError('Qualification changed while packaging')
doc = self.document()
for name, data in payloads.items():
name = self.name(name)
path = self.qualified / name
row = {'path': self.relative(path), 'bytes': len(data),
'sha256': hashlib.sha256(data).hexdigest(),
'archive': archive, 'member': name}
doc['files'] = [r for r in doc['files'] if r['path'] not in (str(path), row['path'])]
doc['files'].append(row)
doc['managed_members'] = list(payloads)
doc['qualification'] = {'name': report_name, 'sha256': expected_report}
doc['cleanup'] = {'state': 'pending', 'removed': []}
atomic_json(self.pointer, doc)
def active_holds(self):
if not self.holds.exists() and not self.holds.is_symlink():
return {}
plain(self.holds)
return json.loads(self.holds.read_text())
def hold(self, owner):
if not owner or len(owner) > 200:
raise PayloadError('A bounded consumer name is required')
holds = self.active_holds()
token = uuid.uuid4().hex
holds[token] = owner
atomic_json(self.holds, holds)
return token
def release(self, token):
holds = self.active_holds()
if token not in holds:
raise PayloadError('Unknown consumer hold')
del holds[token]
atomic_json(self.holds, holds)
return self.closeout()
def closeout(self):
doc = self.document()
names = doc.get('managed_members', [])
if not names:
return {'state': 'unmanaged'} # Never adopt arbitrary historical directories.
report = doc['qualification']
if (report['name'] not in ('qualification.json', 'package-result.json')
or checksum(self.qualified / report['name']) != report['sha256']):
raise PayloadError('Qualification changed; closeout refused')
if self.active_holds():
doc['cleanup'] = {'state': 'deferred', 'reason': 'consumer-hold'}
atomic_json(self.pointer, doc)
return doc['cleanup']
candidates = []
recovery_identities = {}
report_path = self.qualified / report['name']
report_identity = identity(report_path)
for name in names:
path = self.qualified / self.name(name)
rows = [r for r in doc['files'] if r['path'] in (str(path), self.relative(path))]
if len(rows) != 1 or rows[0]['member'] != name:
raise PayloadError('Ambiguous closeout record')
row = rows[0]
archive = self.resolve_archive(row['archive'])
recovery_identities[archive] = identity(archive)
with zipfile.ZipFile(archive) as z:
if z.namelist().count(name) != 1 or z.getinfo(name).file_size != row['bytes']:
raise PayloadError('Recovery member changed')
with z.open(name) as stream:
if digest(stream) != row['sha256']:
raise PayloadError('Recovery member changed')
if path.exists() or path.is_symlink():
before = identity(path)
if before[2] != row['bytes'] or checksum(path) != row['sha256']:
raise PayloadError('Unpacked payload changed; closeout refused')
candidates.append((path, before))
reason = open_files([p for p, _ in candidates]) if candidates else None
if reason:
doc['cleanup'] = {'state': 'deferred', 'reason': reason}
atomic_json(self.pointer, doc)
return doc['cleanup']
removed = []
for path, before in candidates:
if identity(path) != before:
raise PayloadError('Payload changed before retirement')
if (identity(report_path) != report_identity
or any(identity(p) != stamp for p, stamp in recovery_identities.items())):
raise PayloadError('Recovery evidence changed before retirement')
doc['cleanup'] = {'state': 'removing', 'next': path.name, 'removed': removed}
atomic_json(self.pointer, doc)
path.unlink()
sync_directory(path.parent)
removed.append(path.name)
doc['cleanup'] = {'state': 'complete', 'removed': removed}
atomic_json(self.pointer, doc)
return doc['cleanup']
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['hold', 'release', 'retry'])
parser.add_argument('--qualified', type=Path, required=True)
parser.add_argument('--archive-root', type=Path, required=True)
parser.add_argument('--repository', type=Path, required=True)
parser.add_argument('--owner')
parser.add_argument('--token')
args = parser.parse_args()
with QualifiedPayloads(args.qualified, args.archive_root, args.repository).locked() as store:
if args.action == 'hold':
result = {'token': store.hold(args.owner)}
elif args.action == 'release':
result = store.release(args.token)
else:
result = store.closeout()
print(json.dumps(result))
if __name__ == '__main__':
main()
+35 -2
View File
@@ -345,7 +345,7 @@ def producer_hooks(module, store, monkeypatch):
monkeypatch.setattr(module, "input_hold", hold) monkeypatch.setattr(module, "input_hold", hold)
@pytest.mark.parametrize("kind", ["native", "package", "owner", "node"]) @pytest.mark.parametrize("kind", ["native", "package", "owner", "node", "node-archived"])
def test_actual_producers_publish_valid_archives_and_active_holds(store, monkeypatch, capsys, kind): def test_actual_producers_publish_valid_archives_and_active_holds(store, monkeypatch, capsys, kind):
# Exercise the real producer wrappers with tiny synthetic inputs. No SDK execution, # Exercise the real producer wrappers with tiny synthetic inputs. No SDK execution,
# compiler, board, network or production build is involved. # compiler, board, network or production build is involved.
@@ -397,10 +397,12 @@ def test_actual_producers_publish_valid_archives_and_active_holds(store, monkeyp
write("plugins/insta360-x4/build/native/" + name) write("plugins/insta360-x4/build/native/" + name)
for name in ( for name in (
"scripts/packaging/debian.py", "scripts/packaging/debian.py",
"tests/test_media_reconfiguration.py",
"apps/node-agent/packaging/insta360_profile.py", "apps/node-agent/packaging/insta360_profile.py",
"apps/node-agent/packaging/install_owner_release.py", "apps/node-agent/packaging/install_owner_release.py",
"apps/node-agent/packaging/can_maintenance.py", "apps/node-agent/packaging/can_maintenance.py",
"apps/node-agent/packaging/vesc_hall_recovery.py", "apps/node-agent/packaging/vesc_hall_recovery.py",
"apps/node-agent/packaging/k1_maintenance.py",
"src/k1link/__init__.py", "src/k1link/__init__.py",
"src/k1link/fleet/__init__.py", "src/k1link/fleet/__init__.py",
"src/k1link/fleet/sensors.py", "src/k1link/fleet/sensors.py",
@@ -410,6 +412,7 @@ def test_actual_producers_publish_valid_archives_and_active_holds(store, monkeyp
elif kind == "owner": elif kind == "owner":
module = load_producer("plugins/insta360-x4/packaging/build_owner_builder.py", monkeypatch) module = load_producer("plugins/insta360-x4/packaging/build_owner_builder.py", monkeypatch)
monkeypatch.setattr(module, "ROOT", xroot) monkeypatch.setattr(module, "ROOT", xroot)
write('scripts/packaging/qualified_payloads.py')
report = document( report = document(
"qualified-report.json", {"sha256": "f" * 64, "bytes": 0, "file": "qualified.deb"} "qualified-report.json", {"sha256": "f" * 64, "bytes": 0, "file": "qualified.deb"}
) )
@@ -433,12 +436,36 @@ def test_actual_producers_publish_valid_archives_and_active_holds(store, monkeyp
) )
document("apps/node-agent/packaging/linux-toolchains.json", {"files": []}) document("apps/node-agent/packaging/linux-toolchains.json", {"files": []})
document("apps/node-agent/packaging/realsense-bundle.json", {"wheels": []}) document("apps/node-agent/packaging/realsense-bundle.json", {"wheels": []})
vendor = write("apps/node-agent/build/netbird/netbird-fixture.tar.gz")
document("src/k1link/fleet/netbird/clients.lock.json", {"items": [{
"id": "linux-amd64", "filename": vendor.name, "bytes": vendor.stat().st_size,
"sha256": hashlib.sha256(vendor.read_bytes()).hexdigest(),
}]})
package = write("mission-core-insta360-x4_0.1.0_amd64.deb") package = write("mission-core-insta360-x4_0.1.0_amd64.deb")
digest = hashlib.sha256(package.read_bytes()).hexdigest() digest = hashlib.sha256(package.read_bytes()).hexdigest()
document( document(
"apps/node-agent/packaging/insta360-profile.json", "apps/node-agent/packaging/insta360-profile.json",
{"version": "0.1.0", "bytes": 7, "sha256": digest}, {"version": "0.1.0", "bytes": 7, "sha256": digest},
) )
if kind == 'node-archived':
from qualified_payloads import QualifiedPayloads
qualification = store.root / 'x4-qualified'
qualification.mkdir()
package = qualification / package.name
package.write_bytes(b'fixture')
report_bytes = b'{"version":"0.1.0","revision":1}'
(qualification / 'package-result.json').write_bytes(report_bytes)
archive_root = xroot / 'build'
archive_root.mkdir(parents=True, exist_ok=True)
payloads = QualifiedPayloads(qualification, archive_root, store.root)
monkeypatch.setattr('qualified_payloads.open_files', lambda paths: None)
with payloads.locked():
artifact = archive_root / ('mission-core-x4-install-' + 'b' * 24 + '.pyz')
published = payloads.publish(artifact, {package.name: b'fixture'})
payloads.register(published, {package.name: b'fixture'},
'package-result.json', report_bytes)
assert payloads.closeout()['state'] == 'complete'
assert not package.exists()
write("plugins/vesc/build/native-runtime/native.so") write("plugins/vesc/build/native-runtime/native.so")
document( document(
"plugins/vesc/packaging/native-runtime.json", "plugins/vesc/packaging/native-runtime.json",
@@ -451,7 +478,8 @@ def test_actual_producers_publish_valid_archives_and_active_holds(store, monkeyp
monkeypatch.setattr(module, "USB_CAN_SDK_SHA256", digest) monkeypatch.setattr(module, "USB_CAN_SDK_SHA256", digest)
write("apps/node-agent/packaging/linux_build_entry.py") write("apps/node-agent/packaging/linux_build_entry.py")
producer_hooks(module, store, monkeypatch) producer_hooks(module, store, monkeypatch)
if kind == "node": if kind in ("node", "node-archived"):
(xroot / 'build').mkdir(parents=True, exist_ok=True)
result = module.build(package, node_only=True) result = module.build(package, node_only=True)
elif kind == "owner": elif kind == "owner":
module.build(report) module.build(report)
@@ -464,6 +492,11 @@ def test_actual_producers_publish_valid_archives_and_active_holds(store, monkeyp
record = store._state()["inputs"][str(path.relative_to(store.root))] record = store._state()["inputs"][str(path.relative_to(store.root))]
assert record["state"] == "active" and record["owner"] == owner assert record["state"] == "active" and record["owner"] == owner
assert not store.plan()["errors"] and not list(path.parent.glob(".retention-*")) assert not store.plan()["errors"] and not list(path.parent.glob(".retention-*"))
if kind == 'node-archived':
with zipfile.ZipFile(path) as archive:
member = 'source/' + store.root.name + '/apps/node-agent/build/model-packages/'
assert archive.read(member + package.name) == b'fixture'
assert not package.exists()
def test_late_legacy_adoption_does_not_make_an_old_input_newest(store): def test_late_legacy_adoption_does_not_make_an_old_input_newest(store):
+23
View File
@@ -0,0 +1,23 @@
import gzip
import importlib.util
import io
import tarfile
from pathlib import Path
def test_cross_host_gzip_metadata_does_not_change_package(monkeypatch):
path = Path(__file__).parents[1] / "scripts/packaging/debian.py"
spec = importlib.util.spec_from_file_location("portable_debian", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
compress = gzip.compress
results = []
for host in (3, 19, 255):
def platform_compress(data, *, mtime, host=host):
raw = compress(data, mtime=mtime)
return raw[:9] + bytes([host]) + raw[10:]
monkeypatch.setattr(module.gzip, "compress", platform_compress)
results.append(module.tarball([("usr/lib/example/data", b"portable", 0o644)]))
assert len(set(results)) == 1
with tarfile.open(fileobj=io.BytesIO(gzip.decompress(results[0]))) as archive:
assert archive.extractfile("usr/lib/example/data").read() == b"portable"
+348
View File
@@ -0,0 +1,348 @@
"""Publication/closeout with tiny payloads; no real build, SDK or live data."""
import hashlib
import importlib.util
import json
import os
import subprocess
import sys
import zipfile
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from unittest.mock import patch
import pytest
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'scripts/packaging'))
import qualified_payloads as q # noqa: E402
@pytest.fixture
def store(tmp_path, monkeypatch):
archive_root = tmp_path / 'build'
archive_root.mkdir()
qualified = archive_root / 'qualified'
qualified.mkdir()
monkeypatch.setattr(q, 'open_files', lambda paths: None)
return q.QualifiedPayloads(qualified, archive_root, tmp_path)
def seed(store, payloads=None):
payloads = payloads or {'node.deb': b'qualified-package', 'dependency.deb': b'dependency'}
report = json.dumps({'state': 'complete', 'artifacts': {
name: {'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()}
for name, data in payloads.items()}}).encode()
(store.qualified / 'qualification.json').write_bytes(report)
for name, data in payloads.items():
(store.qualified / name).write_bytes(data)
output = store.archive_root / ('mission-core-node-install-' + 'a' * 24 + '.pyz')
with store.locked():
archive = store.publish(output, {'release.json': report, **payloads})
store.register(archive, payloads, 'qualification.json', report)
return output, payloads
def test_automatic_closeout_preserves_archive_report_and_unknown_files(store):
output, payloads = seed(store)
(store.qualified / 'foreign.deb').write_bytes(b'not admitted')
with store.locked():
result = store.closeout()
assert result['state'] == 'complete'
for name, data in payloads.items():
assert not (store.qualified / name).exists()
assert store.read(name) == data
assert store.closeout()['state'] == 'complete'
assert output.exists()
assert (store.qualified / 'foreign.deb').read_bytes() == b'not admitted'
assert (store.qualified / 'qualification.json').exists()
def test_persistent_consumer_hold_and_release_across_instances(store):
with store.locked():
token = store.hold('dependent qualification')
_, payloads = seed(store)
with store.locked():
assert store.closeout() == {'state': 'deferred', 'reason': 'consumer-hold'}
other = q.QualifiedPayloads(store.qualified, store.archive_root, store.repository)
with other.locked():
with pytest.raises(q.PayloadError, match='Unknown consumer'):
other.release('wrong-owner')
assert other.release(token)['state'] == 'complete'
assert all(not (store.qualified / n).exists() for n in payloads)
@pytest.mark.parametrize('reason', ['payload-in-use', 'open-file-check-unavailable'])
def test_active_or_unknown_reader_defers_and_retry_finishes(store, monkeypatch, reason):
_, payloads = seed(store)
monkeypatch.setattr(q, 'open_files', lambda paths: reason)
with store.locked():
assert store.closeout()['state'] == 'deferred'
assert all((store.qualified / n).exists() for n in payloads)
monkeypatch.setattr(q, 'open_files', lambda paths: None)
with store.locked():
assert store.closeout()['state'] == 'complete'
@pytest.mark.parametrize('target', ['archive', 'payload', 'qualification'])
def test_changed_inputs_block_all_unlinks(store, target):
output, payloads = seed(store)
path = {'archive': output, 'payload': store.qualified / 'dependency.deb',
'qualification': store.qualified / 'qualification.json'}[target]
path.write_bytes(b'changed')
with store.locked(), pytest.raises(q.PayloadError):
store.closeout()
assert all((store.qualified / n).exists() for n in payloads)
def test_archive_changed_during_reader_check_blocks_retirement(store, monkeypatch):
output, payloads = seed(store)
def change_archive(paths):
output.write_bytes(b'changed after verification')
monkeypatch.setattr(q, 'open_files', change_archive)
with store.locked(), pytest.raises(q.PayloadError, match='evidence changed'):
store.closeout()
assert all((store.qualified / n).exists() for n in payloads)
def test_pointer_write_failure_does_not_delete_source(store, monkeypatch):
_, payloads = seed(store)
def fail(*args):
raise OSError('disk full')
monkeypatch.setattr(q, 'atomic_json', fail)
with store.locked(), pytest.raises(OSError, match='disk full'):
store.closeout()
assert all((store.qualified / n).exists() for n in payloads)
def test_interruption_between_unlinks_is_recoverable(store, monkeypatch):
_, payloads = seed(store)
original = Path.unlink
def interrupted(path, *args, **kwargs):
if path == store.qualified / 'dependency.deb':
raise OSError('simulated shutdown')
return original(path, *args, **kwargs)
with monkeypatch.context() as m:
m.setattr(Path, 'unlink', interrupted)
with store.locked(), pytest.raises(OSError, match='shutdown'):
store.closeout()
assert not (store.qualified / 'node.deb').exists()
replacement = q.QualifiedPayloads(store.qualified, store.archive_root, store.repository)
with replacement.locked():
assert replacement.closeout()['state'] == 'complete'
for name, data in payloads.items():
assert replacement.read(name) == data
def test_hardlinks_retire_without_changing_other_owner(store):
_, payloads = seed(store, {'a.deb': b'shared', 'b.deb': b'shared'})
first, second = [store.qualified / n for n in payloads]
second.unlink()
second.hardlink_to(first)
retained = store.repository / 'other-owner.deb'
retained.hardlink_to(first)
with store.locked():
assert store.closeout()['state'] == 'complete'
assert retained.read_bytes() == b'shared'
@pytest.mark.parametrize('target', ['payload', 'archive', 'pointer'])
def test_symlinks_are_refused(store, target):
output, payloads = seed(store)
path = {'payload': store.qualified / 'node.deb', 'archive': output,
'pointer': store.pointer}[target]
retained = store.repository / 'foreign'
path.rename(retained)
path.symlink_to(retained)
with store.locked(), pytest.raises(q.PayloadError):
store.closeout()
assert retained.exists()
assert (store.qualified / 'dependency.deb').exists()
def test_legacy_pointer_is_readable_but_not_automatically_adopted(store):
_, payloads = seed(store)
doc = store.document()
doc.pop('managed_members')
doc.pop('qualification')
q.atomic_json(store.pointer, doc)
with store.locked():
assert store.closeout()['state'] == 'unmanaged'
for name, data in payloads.items():
(store.qualified / name).unlink()
assert store.read(name) == data
def test_unknown_and_traversal_records_do_not_delete_files(store):
seed(store)
doc = store.document()
doc['managed_members'] = ['../victim.deb']
q.atomic_json(store.pointer, doc)
victim = store.archive_root / 'victim.deb'
victim.write_bytes(b'foreign')
with store.locked(), pytest.raises(q.PayloadError):
store.closeout()
assert victim.read_bytes() == b'foreign'
def test_partial_publication_recovered_under_lock(store):
temporary = store.archive_root / ('.mission-core-node-install-' + 'a'*24 + '.pyz.' + 'b'*32)
temporary.write_bytes(b'incomplete transport')
q.atomic_json(store.archive_root / '.payload-publication.json',
{'temporary': temporary.name, 'identity': list(q.identity(temporary)[:2])})
output, _ = seed(store)
assert not temporary.exists()
assert not (store.archive_root / '.payload-publication.json').exists()
with zipfile.ZipFile(output) as z:
assert z.read('node.deb') == b'qualified-package'
def test_failed_publication_keeps_inputs_and_cleans_owned_scratch(store, monkeypatch):
output = store.archive_root / ('mission-core-node-install-' + 'a' * 24 + '.pyz')
source = store.qualified / 'node.deb'
source.write_bytes(b'unpublished')
def fail(*args, **kwargs):
raise OSError('simulated write failure')
monkeypatch.setattr(zipfile.ZipFile, 'writestr', fail)
with store.locked(), pytest.raises(OSError, match='write failure'):
store.publish(output, {'node.deb': b'unpublished'})
assert source.read_bytes() == b'unpublished'
assert not output.exists()
assert not (store.archive_root / '.payload-publication.json').exists()
assert not list(store.archive_root.glob('.mission-core-*.pyz.*'))
def test_interrupted_publication_does_not_remove_replaced_file(store):
temporary = store.archive_root / ('.mission-core-node-install-' + 'a'*24 + '.pyz.' + 'b'*32)
temporary.write_bytes(b'foreign replacement')
q.atomic_json(store.archive_root / '.payload-publication.json',
{'temporary': temporary.name, 'identity': [0, 0]})
output = store.archive_root / ('mission-core-node-install-' + 'a'*24 + '.pyz')
with store.locked(), pytest.raises(q.PayloadError, match='identity changed'):
store.publish(output, {'node.deb': b'payload'})
assert temporary.read_bytes() == b'foreign replacement'
assert not output.exists()
def load_builder(relative, name):
spec = importlib.util.spec_from_file_location(name, REPO / relative)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize('kind', ['node', 'x4'])
def test_real_builders_auto_retire_and_can_rebuild_from_archive(tmp_path, monkeypatch, kind):
family = 'apps/node-agent' if kind == 'node' else 'plugins/insta360-x4'
module = load_builder(
family + '/packaging/build_owner_release.py',
'payload_builder_' + kind,
)
root = tmp_path / ('apps/node-agent' if kind == 'node' else 'plugins/insta360-x4')
(root / 'build').mkdir(parents=True)
(root / 'packaging').mkdir()
for name in ['install-owner-release', 'vesc_hall_recovery.py', 'can_maintenance.py',
'k1_maintenance.py', 'install_owner_release.py', 'install', 'install_release.py',
'owner_release_entry.py']:
(root / 'packaging' / name).write_bytes(b'# fixture\n')
entry = tmp_path / 'plugins/insta360-x4/packaging/owner_release_entry.py'
entry.parent.mkdir(parents=True, exist_ok=True)
entry.write_bytes(b'# fixture entry\n')
monkeypatch.setattr(module, 'ROOT', root)
monkeypatch.setattr(module, 'REPO', tmp_path)
monkeypatch.setattr(q, 'open_files', lambda paths: None)
qualified = root / 'build/fixture'
qualified.mkdir()
name = 'mission-core-' + ('node' if kind == 'node' else 'insta360-x4') + '_1.2.3_amd64.deb'
payloads = {name: b'qualified package'}
if kind == 'node':
payloads.update({n: n.encode() for n in module.NODE_DEPENDENCIES})
evidence = {'state': 'complete', 'artifacts': {n: {
'sha256': hashlib.sha256(b).hexdigest(), 'bytes': len(b)} for n, b in payloads.items()}}
if kind == 'x4':
evidence = {'version': '1.2.3', 'revision': 1, **evidence['artifacts'][name]}
report = qualified / ('qualification.json' if kind == 'node' else 'package-result.json')
report.write_text(json.dumps(evidence))
for n, b in payloads.items():
(qualified / n).write_bytes(b)
# Concurrent publication retries serialize; second call reads retained payloads.
with ThreadPoolExecutor(max_workers=2) as executor:
results = list(executor.map(lambda _: module.build(qualified), range(2)))
assert results[0]['artifact'] == results[1]['artifact']
assert results[0]['sha256'] == results[1]['sha256']
assert all(x['payload_cleanup']['state'] == 'complete' for x in results)
assert not list(qualified.glob('*.deb'))
assert len(list((root / 'build').glob('*.pyz'))) == 1
with zipfile.ZipFile(results[0]['artifact']) as z:
assert all(z.read(n) == b for n, b in payloads.items())
def test_real_lsof_reports_open_file(tmp_path):
path = tmp_path / 'held.deb'
path.write_bytes(b'held')
with path.open('rb'):
assert q.open_files([path]) == 'payload-in-use'
def test_x4_isolated_builder_uses_bundled_helper_without_repository(tmp_path):
root = tmp_path / 'portable'
packaging = root / 'packaging'
qualified = root / 'build'
packaging.mkdir(parents=True)
qualified.mkdir()
for name in ['build_owner_release.py', 'install', 'install_release.py',
'owner_release_entry.py']:
(packaging / name).write_bytes((REPO / 'plugins/insta360-x4/packaging' / name).read_bytes())
helper = REPO / 'scripts/packaging/qualified_payloads.py'
(packaging / 'qualified_payloads.py').write_bytes(helper.read_bytes())
name = 'mission-core-insta360-x4_1.2.3_amd64.deb'
payload = b'qualified fixture'
(qualified / name).write_bytes(payload)
(qualified / 'package-result.json').write_text(json.dumps({
'version': '1.2.3', 'revision': 1, 'bytes': len(payload),
'sha256': hashlib.sha256(payload).hexdigest(),
}))
command = [sys.executable, '-B', '-I', str(packaging / 'build_owner_release.py'),
'--qualified', str(qualified)]
result = subprocess.run(command, capture_output=True, text=True, check=True,
env={**os.environ, 'PATH': str(tmp_path / 'no-tools')}, timeout=30)
receipt = json.loads(result.stdout)
assert receipt['payload_cleanup'] == {
'state': 'deferred', 'reason': 'open-file-check-unavailable',
}
assert (qualified / name).exists()
with zipfile.ZipFile(receipt['artifact']) as z:
assert z.read(name) == payload
def test_open_file_check_failure_never_guesses(tmp_path):
path = tmp_path / 'p.deb'
with patch.object(q.shutil, 'which', return_value=None):
assert q.open_files([path]) == 'open-file-check-unavailable'
@pytest.mark.parametrize('corrupt', [False, True])
def test_runtime_repack_reads_verified_retired_base(tmp_path, monkeypatch, corrupt):
monkeypatch.syspath_prepend(str(REPO / 'apps/node-agent/packaging'))
module = load_builder('apps/node-agent/packaging/repack_runtime.py', 'retired_repack')
root = tmp_path / 'apps/node-agent/build'
qualified = root / 'qualified'
qualified.mkdir(parents=True)
payloads = q.QualifiedPayloads(qualified, root, tmp_path)
monkeypatch.setattr(q, 'open_files', lambda paths: None)
archive, _ = seed(payloads, {'base.deb': b'qualified predecessor'})
with payloads.locked():
payloads.closeout()
monkeypatch.setattr(module, 'REPO', tmp_path)
seen = []
def parse(data):
seen.append(data)
raise RuntimeError('parser reached')
monkeypatch.setattr(module, 'parts', parse)
if corrupt:
archive.write_bytes(b'corrupted installer')
with pytest.raises(q.PayloadError if corrupt else RuntimeError):
module.build(qualified / 'base.deb', hashlib.sha256(b'qualified predecessor').hexdigest(),
tmp_path / 'unused-binary', '1.2.3-4', tmp_path / 'output.deb')
assert seen == ([] if corrupt else [b'qualified predecessor'])
assert not (qualified / 'base.deb').exists()