fix(ci): qualify on the pinned Python and retain immutable release bundles
Device Core qualification / qualify (push) Successful in 5m51s

This commit is contained in:
DCCONSTRUCTIONS
2026-09-29 18:04:12 +03:00
parent 784a371e3e
commit 415d5e73d7
7 changed files with 456 additions and 4 deletions
+13
View File
@@ -5,6 +5,9 @@ on:
branches: [main]
workflow_dispatch:
permissions:
contents: read
jobs:
qualify:
runs-on: nodedc-node22-build
@@ -13,6 +16,8 @@ jobs:
- name: Check the exact pushed commit
env:
SOURCE_COMMIT: ${{ gitea.sha }}
SOURCE_RUN_ID: ${{ gitea.run_id }}
SOURCE_RUN_NUMBER: ${{ gitea.run_number }}
run: |
set -eu
python3 -c 'import os,re; assert re.fullmatch("[0-9a-f]{40}", os.environ["SOURCE_COMMIT"]), "full commit SHA required"'
@@ -26,5 +31,13 @@ jobs:
git -C "$source_root" checkout --quiet --detach FETCH_HEAD
python3 "$source_root/infra/ci/qualify.py" fetch-dependencies --commit "$SOURCE_COMMIT"
python3 "$source_root/infra/ci/qualify.py" check --commit "$SOURCE_COMMIT" --report "$job_root/qualification.json"
python3 "$source_root/infra/ci/package_release.py" --report "$job_root/qualification.json" --run-id "$SOURCE_RUN_ID" --run-number "$SOURCE_RUN_NUMBER" --output-dir "$GITHUB_WORKSPACE/release"
- name: Retain the qualified release in this Gitea run
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5
with:
name: device-core-release
path: release
if-no-files-found: error
retention-days: 30
# Production activation is separate: this job has no production access.
# Do not label a successful qualification as a successful deployment.
+21 -2
View File
@@ -45,8 +45,12 @@ entry, branch policy, release contract and acceptance tests.
## Reproduce source qualification
Runner label: `nodedc-node22-build`; Node 22.21.0, npm 10.9.4, Python >=3.9 and
Git must be available in the reviewed build image. The workflow does not
download third-party Actions. It fetches the exact pushed SHA from our Gitea.
Git must be available in the reviewed build image. The workflow fetches the
exact pushed SHA from our Gitea. After qualification it uses the upstream
`actions/upload-artifact` v3 implementation pinned to commit
`ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5` to retain the bundle in **our Gitea**.
The upload uses the job's short-lived artifact credential, not a production
credential. The workflow's repository token has read-only content access.
`infra/ci/sources.lock.json` pins Design Guideline, Platform and Launcher to full commits;
following their current `main` branches would make old releases unreproducible.
Launcher sources are required by the existing Hub trust/session artifact tests;
@@ -73,6 +77,21 @@ hashes and the UI output hash. It contains `deployed: false` deliberately.
The qualification report is evidence, not an authorization token or substitute
for independently checking Gitea job identity and the deploy artifact.
`infra/ci/package_release.py` runs only after all qualification steps pass. It
checks the source and build hashes again, then emits a deterministic `.tgz`
and `release.json` receipt. The archive declares `device-core-release.v1` with
the exact source SHA, run id/number and file digests. It cannot choose Compose
files, host roots, install commands or database operations. This new artifact
type still needs the reviewed Platform runner extension before installation.
Bundles remain in Gitea for 30 days; installed releases will additionally be
retained by the canonical NAS journal/archive. Expiry is not a successful
deployment and must never be silently ignored by the controller.
Linux qualification also exercises the standalone Edge/VPS archive readers.
These materialize validated regular files explicitly, without `extractall`,
so they work with the pinned image's Python while retaining path/link/mode
checks. No Edge/VPS runtime is changed by running these tests.
Local focused tests: `python3 -m unittest discover -s infra/ci -p 'test_*.py'`.
The full artifact suite belongs on the bounded Linux build worker; there is no
requirement to start Docker or run load tests on an operator Mac.
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Produce a deterministic data-only release from the exact qualified checkout."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path, PurePosixPath
import re
import stat
import tarfile
import qualify
ENTRY = "deployment/device-core-release-v1.json"
ENTRIES = (
".dockerignore", "package.json", "package-lock.json",
"packages/device-protocol-contract", "packages/device-edge-channel-contract",
"packages/infrastructure-telemetry-contract", "services/device-control-core",
"services/device-manager", ENTRY,
)
STEPS = [
"design-install", "design-core", "design-react", "device-install",
"unit-tests", "ci-contract", "build", "artifact-contracts",
]
EXCLUDED = {"node_modules", ".git", ".DS_Store", "test", "__pycache__"}
DENIED = {"secrets", "credentials", "runtime", "runtime-data", "uploads", "logs", "data"}
def encoded(value):
return (json.dumps(value, sort_keys=True, indent=2) + "\n").encode()
def source_files(path, destination):
"""Do not traverse ignored trees; reject links and unexpected state elsewhere."""
result = {}
mode = path.lstat()
if stat.S_ISLNK(mode.st_mode) or (stat.S_ISREG(mode.st_mode) and mode.st_nlink != 1):
raise ValueError("linked_source:" + destination)
if stat.S_ISDIR(mode.st_mode):
for child in sorted(path.iterdir()):
name = child.name
if name in EXCLUDED or name.endswith((".test.mjs", ".map", ".tsbuildinfo")):
continue
if name in DENIED or name.startswith((".env", "._")) or name.endswith((".pem", ".key", ".sqlite", ".db", ".log")):
raise ValueError("runtime_source_rejected:" + destination + "/" + name)
result.update(source_files(child, destination + "/" + name))
elif stat.S_ISREG(mode.st_mode):
if mode.st_size > 16 * 1024 * 1024:
raise ValueError("oversized_source:" + destination)
result[destination] = path.read_bytes()
else:
raise ValueError("nonregular_source:" + destination)
return result
def bundle(root, report, run_id, run_number):
if type(run_id) is not int or type(run_number) is not int or not 0 < run_id < 2**53 or not 0 < run_number < 2**53:
raise ValueError("invalid_run_identity")
commit = report.get("sourceCommit", "")
if not re.fullmatch(r"[0-9a-f]{40}", commit):
raise ValueError("invalid_source_commit")
lock = qualify.read_lock(root)
if (report.get("schema") != "nodedc.device-core.qualification.v1"
or report.get("status") != "qualified" or report.get("deployed") is not False
or report.get("steps") != STEPS or report.get("sources") != lock):
raise ValueError("qualification_required")
for name, path in (
("sourceLockSha256", root / "infra/ci/sources.lock.json"),
("packageLockSha256", root / "package-lock.json"),
):
if report.get(name) != hashlib.sha256(path.read_bytes()).hexdigest():
raise ValueError("qualification_source_changed:" + name)
if report.get("managerDistSha256") != qualify.tree_digest(root / "apps/device-manager/dist"):
raise ValueError("qualified_dist_changed")
files = {}
for entry in ENTRIES[:-2]:
files.update(source_files(root / entry, entry))
for source, target in (
("services/device-manager/Dockerfile", "services/device-manager/Dockerfile"),
("apps/device-manager/server", "services/device-manager/server"),
("apps/device-manager/dist", "services/device-manager/dist"),
):
files.update(source_files(root / source, target))
if sum(map(len, files.values())) > 64 * 1024 * 1024:
raise ValueError("release_too_large")
release_id = "device-core-release-v1-r" + str(run_id) + "-" + commit
descriptor = {
"schemaVersion": "nodedc.device-core.release.v1",
"releaseId": release_id,
"repository": "SILVER/NODEDC_DEVICE_CORE",
"repositoryId": 38,
"branch": "main",
"sourceCommit": commit,
"runId": run_id,
"runNumber": run_number,
"qualification": report,
"filesSha256": {name: hashlib.sha256(value).hexdigest() for name, value in sorted(files.items())},
}
files[ENTRY] = encoded(descriptor)
members = {
"manifest.env": ("id=" + release_id + "\ncomponent=device-core-release\ntype=app-overlay\n").encode(),
"files.txt": ("\n".join(ENTRIES) + "\n").encode(),
**{"payload/" + name: value for name, value in files.items()},
}
output = io.BytesIO()
with gzip.GzipFile(fileobj=output, mode="wb", filename="", mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode="w", format=tarfile.PAX_FORMAT) as archive:
directories = {"payload"}
for name in members:
directories.update(str(p) for p in PurePosixPath(name).parents if str(p) != ".")
for name in sorted(directories):
info = tarfile.TarInfo(name)
info.type, info.mode = tarfile.DIRTYPE, 0o755
archive.addfile(info)
for name, value in sorted(members.items()):
info = tarfile.TarInfo(name)
info.mode, info.size = 0o644, len(value)
archive.addfile(info, io.BytesIO(value))
return release_id, output.getvalue()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--report", type=Path, required=True)
parser.add_argument("--run-id", type=int, required=True)
parser.add_argument("--run-number", type=int, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
args = parser.parse_args()
root = Path(__file__).resolve().parents[2]
report = json.loads(args.report.read_text())
qualify.verify_sources(root, report["sourceCommit"], qualify.read_lock(root))
output = args.output_dir.resolve()
for checkout in (root, *(root.parent / name for name in qualify.DEPENDENCIES)):
if output == checkout or checkout in output.parents:
raise ValueError("release_output_must_be_outside_sources")
identity, data = bundle(root, report, args.run_id, args.run_number)
output.mkdir(parents=True, exist_ok=True)
path = output / ("nodedc-" + identity + ".tgz")
with path.open("xb") as stream:
stream.write(data)
receipt = {"artifact": path.name, "sha256": hashlib.sha256(data).hexdigest(),
"sourceCommit": report["sourceCommit"], "runId": args.run_id,
"runNumber": args.run_number, "deployed": False}
with (output / "release.json").open("xb") as stream:
stream.write(encoded(receipt))
print(json.dumps(receipt))
if __name__ == "__main__":
main()
+114
View File
@@ -0,0 +1,114 @@
import hashlib
import io
import json
import os
from pathlib import Path
import tarfile
import tempfile
import unittest
import package_release as release
import qualify
class ReleaseTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
lock = qualify.read_lock(Path(__file__).resolve().parents[2])
self.write("infra/ci/sources.lock.json", json.dumps(lock))
for name in (".dockerignore", "package.json", "package-lock.json",
"services/device-manager/Dockerfile", "apps/device-manager/server/app.mjs",
"apps/device-manager/dist/index.html", "services/device-control-core/src/app.mjs",
"packages/device-protocol-contract/package.json",
"packages/device-edge-channel-contract/package.json",
"packages/infrastructure-telemetry-contract/package.json"):
self.write(name, "fixture")
self.report = {
"schema": "nodedc.device-core.qualification.v1", "status": "qualified",
"deployed": False, "steps": release.STEPS, "sources": lock,
"sourceCommit": "a" * 40,
"sourceLockSha256": self.digest("infra/ci/sources.lock.json"),
"packageLockSha256": self.digest("package-lock.json"),
"managerDistSha256": qualify.tree_digest(self.root / "apps/device-manager/dist"),
}
def write(self, path, value):
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(value)
return target
def digest(self, path):
return hashlib.sha256((self.root / path).read_bytes()).hexdigest()
def build(self):
return release.bundle(self.root, self.report, 14, 9)
def test_exact_deterministic_payload_without_runtime_authority(self):
identity, first = self.build()
os.utime(self.root / "apps/device-manager/server/app.mjs", (100, 100))
self.assertEqual(first, self.build()[1])
with tarfile.open(fileobj=io.BytesIO(first), mode="r:gz") as archive:
names = archive.getnames()
self.assertEqual(archive.extractfile("files.txt").read().decode().splitlines(), list(release.ENTRIES))
descriptor = json.load(archive.extractfile("payload/" + release.ENTRY))
self.assertEqual(descriptor["releaseId"], identity)
self.assertEqual(descriptor["runId"], 14)
self.assertEqual(descriptor["runNumber"], 9)
self.assertEqual(descriptor["repositoryId"], 38)
for member in archive.getmembers():
self.assertTrue(member.isfile() or member.isdir())
self.assertEqual(member.mtime, 0)
self.assertEqual(member.uid, 0)
files = descriptor["filesSha256"]
for name, digest in files.items():
self.assertEqual(hashlib.sha256(archive.extractfile("payload/" + name).read()).hexdigest(), digest)
self.assertIn("payload/services/device-manager/server/app.mjs", names)
self.assertFalse(any("compose" in name or (name.startswith("payload/") and name.endswith(".env")) for name in names))
def test_incomplete_or_forged_qualification_rejected(self):
for key, value in [("status", "failed"), ("deployed", True), ("steps", release.STEPS[:-1]),
("sourceCommit", "../main"), ("sources", {}), ("packageLockSha256", "0" * 64)]:
with self.subTest(key=key):
previous = self.report[key]
self.report[key] = value
with self.assertRaises(ValueError): self.build()
self.report[key] = previous
def test_dist_modified_after_tests_rejected(self):
self.write("apps/device-manager/dist/index.html", "changed")
with self.assertRaisesRegex(ValueError, "qualified_dist_changed"): self.build()
def test_source_symlink_rejected(self):
(self.root / "services/device-control-core/src/escape").symlink_to("/etc/passwd")
with self.assertRaisesRegex(ValueError, "linked_source"): self.build()
def test_hardlink_rejected(self):
os.link(self.root / "package.json", self.root / "services/device-control-core/src/linked")
with self.assertRaisesRegex(ValueError, "linked_source"): self.build()
def test_runtime_files_rejected_instead_of_bundled(self):
for name in [".env.production", "secrets/key", "data/device.json", "local.pem", "snapshot.db"]:
with self.subTest(name=name):
target = self.write("services/device-control-core/" + name, "private-fixture")
with self.assertRaisesRegex(ValueError, "runtime_source_rejected"): self.build()
target.unlink()
if target.parent.name in release.DENIED: target.parent.rmdir()
def test_tests_and_dependencies_not_in_runtime_bundle(self):
self.write("services/device-control-core/test/example.mjs", "test")
self.write("services/device-control-core/node_modules/lib/index.mjs", "dependency")
self.write("apps/device-manager/server/app.test.mjs", "test")
with tarfile.open(fileobj=io.BytesIO(self.build()[1]), mode="r:gz") as archive:
self.assertFalse(any("test" in name or "node_modules" in name for name in archive.getnames()))
def test_run_identity_strict(self):
for value in [True, 0, -1, "1", 2**53]:
with self.subTest(value=value):
with self.assertRaises(ValueError): release.bundle(self.root, self.report, value, 1)
if __name__ == "__main__":
unittest.main()
+36 -1
View File
@@ -550,6 +550,41 @@ def validate_payload(payload: Path, phase: str):
return descriptor
def extract_validated_files(archive, extraction_root):
"""Materialize only regular data, also on Python before tar filters existed."""
if extraction_root.is_symlink() or not extraction_root.is_dir() or any(extraction_root.iterdir()):
die("artifact extraction requires an empty private directory")
root = extraction_root.resolve(strict=True)
members = archive.getmembers()
if len(members) > 65536 or sum(item.size for item in members) > MAX_ARTIFACT_BYTES:
die("artifact expanded size/count rejected")
normalized = set()
files = set()
for member in members:
safe_tar_member(member)
path = PurePosixPath(member.name)
name = path.as_posix()
if member.name.rstrip("/") != name or name in normalized:
die("artifact contains noncanonical or duplicate paths")
normalized.add(name)
if member.isfile():
files.add(name)
for member in members:
if any(str(parent) in files for parent in PurePosixPath(member.name).parents):
die("artifact file is used as a directory")
# All members are checked before any output. Never apply archive ownership,
# links, devices or special mode bits; never invoke extract/extractall.
for member in members:
destination = root.joinpath(*PurePosixPath(member.name).parts)
if member.isdir():
destination.mkdir(parents=True, exist_ok=True, mode=0o755)
else:
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
with archive.extractfile(member) as source, destination.open("xb") as output:
shutil.copyfileobj(source, output)
destination.chmod(0o755 if member.mode & 0o111 else 0o644)
def load_artifact(artifact: Path, extraction_root: Path):
artifact = artifact.resolve(strict=True)
if artifact.parent != INBOX_ROOT.resolve(strict=True):
@@ -570,7 +605,7 @@ def load_artifact(artifact: Path, extraction_root: Path):
die("artifact top-level contract is incomplete")
if any(name.split("/", 1)[0] not in required for name in seen):
die("artifact contains an unexpected top-level member")
archive.extractall(extraction_root, filter="data")
extract_validated_files(archive, extraction_root)
manifest = parse_manifest(
(extraction_root / "manifest.env").read_text(encoding="utf-8")
+36 -1
View File
@@ -228,6 +228,41 @@ def safe_tar_member(member: tarfile.TarInfo):
die("artifact contains AppleDouble metadata")
def extract_validated_files(archive, extraction_root):
"""Materialize only regular data, also on Python before tar filters existed."""
if extraction_root.is_symlink() or not extraction_root.is_dir() or any(extraction_root.iterdir()):
die("artifact extraction requires an empty private directory")
root = extraction_root.resolve(strict=True)
members = archive.getmembers()
if len(members) > 65536 or sum(item.size for item in members) > MAX_ARTIFACT_BYTES:
die("artifact expanded size/count rejected")
normalized = set()
files = set()
for member in members:
safe_tar_member(member)
path = PurePosixPath(member.name)
name = path.as_posix()
if member.name.rstrip("/") != name or name in normalized:
die("artifact contains noncanonical or duplicate paths")
normalized.add(name)
if member.isfile():
files.add(name)
for member in members:
if any(str(parent) in files for parent in PurePosixPath(member.name).parents):
die("artifact file is used as a directory")
# All members are checked before any output. Never apply archive ownership,
# links, devices or special mode bits; never invoke extract/extractall.
for member in members:
destination = root.joinpath(*PurePosixPath(member.name).parts)
if member.isdir():
destination.mkdir(parents=True, exist_ok=True, mode=0o755)
else:
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
with archive.extractfile(member) as source, destination.open("xb") as output:
shutil.copyfileobj(source, output)
destination.chmod(0o755 if member.mode & 0o111 else 0o644)
def load_artifact(artifact: Path, extraction_root: Path):
artifact = artifact.resolve(strict=True)
if artifact.parent != INBOX_ROOT.resolve(strict=True):
@@ -248,7 +283,7 @@ def load_artifact(artifact: Path, extraction_root: Path):
die("artifact top-level contract is incomplete")
if any(name.split("/", 1)[0] not in required for name in seen):
die("artifact contains an unexpected top-level member")
archive.extractall(extraction_root, filter="data")
extract_validated_files(archive, extraction_root)
manifest = parse_manifest(
(extraction_root / "manifest.env").read_text(encoding="utf-8")
@@ -0,0 +1,84 @@
"""Exercise the real standalone loaders without Python's newer tar filter API."""
import importlib.machinery
import importlib.util
import io
from pathlib import Path
import tarfile
import tempfile
import unittest
from unittest.mock import patch
def load(name):
loader = importlib.machinery.SourceFileLoader(name, str(Path(__file__).parent / name))
spec = importlib.util.spec_from_loader(name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNERS = [load("nodedc-edge-deploy"), load("nodedc-b2-vps-deploy")]
def archive(items):
buffer = io.BytesIO()
with tarfile.open(fileobj=buffer, mode="w") as output:
for name, kind in items:
info = tarfile.TarInfo(name)
info.type, info.mode, info.uid, info.gid = kind, 0o6777, 123, 456
info.linkname = "/tmp/outside"
if kind == tarfile.REGTYPE:
info.size = 4
output.addfile(info, io.BytesIO(b"data"))
else:
output.addfile(info)
buffer.seek(0)
return tarfile.open(fileobj=buffer, mode="r")
class PortableExtractionTests(unittest.TestCase):
def test_no_extractall_and_no_special_modes(self):
for runner in RUNNERS:
with self.subTest(runner=runner.__name__), tempfile.TemporaryDirectory() as directory:
with archive([("payload", tarfile.DIRTYPE), ("payload/app.mjs", tarfile.REGTYPE)]) as value:
with patch.object(tarfile.TarFile, "extractall", side_effect=AssertionError("unfiltered extraction forbidden")):
runner.extract_validated_files(value, Path(directory))
target = Path(directory) / "payload/app.mjs"
self.assertEqual(target.read_bytes(), b"data")
self.assertEqual(target.stat().st_mode & 0o7777, 0o755)
def test_every_member_checked_before_any_write(self):
for runner in RUNNERS:
for name, kind in [("../escape", tarfile.REGTYPE), ("/absolute", tarfile.REGTYPE),
("payload/link", tarfile.SYMTYPE), ("payload/link", tarfile.LNKTYPE),
("payload/pipe", tarfile.FIFOTYPE), ("payload/.env", tarfile.REGTYPE),
("payload//alias", tarfile.REGTYPE), ("payload/./alias", tarfile.REGTYPE),
("payload/a", tarfile.REGTYPE), ("payload/a/child", tarfile.REGTYPE)]:
with self.subTest(runner=runner.__name__, name=name, kind=kind), tempfile.TemporaryDirectory() as directory:
with archive([("payload/a", tarfile.REGTYPE), (name, kind)]) as value:
with self.assertRaises(runner.DeployError): runner.extract_validated_files(value, Path(directory))
self.assertEqual(list(Path(directory).iterdir()), [])
def test_existing_output_and_symlink_root_rejected(self):
for runner in RUNNERS:
with self.subTest(runner=runner.__name__), tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "existing").write_text("preserve")
with archive([("payload/a", tarfile.REGTYPE)]) as value:
with self.assertRaises(runner.DeployError): runner.extract_validated_files(value, root)
(root / "target").mkdir()
(root / "linked").symlink_to(root / "target", target_is_directory=True)
with archive([("payload/a", tarfile.REGTYPE)]) as value:
with self.assertRaises(runner.DeployError): runner.extract_validated_files(value, root / "linked")
self.assertEqual((root / "existing").read_text(), "preserve")
def test_expanded_size_bounded(self):
for runner in RUNNERS:
with self.subTest(runner=runner.__name__), tempfile.TemporaryDirectory() as directory:
with archive([("payload/a", tarfile.REGTYPE)]) as value, patch.object(runner, "MAX_ARTIFACT_BYTES", 3):
with self.assertRaises(runner.DeployError): runner.extract_validated_files(value, Path(directory))
self.assertFalse(list(Path(directory).iterdir()))
if __name__ == "__main__":
unittest.main()