Add pinned Device Core CI qualification for main

This commit is contained in:
DCCONSTRUCTIONS
2026-09-29 13:05:19 +03:00
parent 9ff6feebcf
commit 1900257fd3
6 changed files with 443 additions and 0 deletions
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env python3
"""Qualify exact sources in disposable CI checkouts. No production access."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
SHA = re.compile(r"[0-9a-f]{40}")
DEPENDENCIES = {
"NODEDC_DESIGN_GUIDELINE": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
"platform": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git",
}
def run(args, cwd, capture=False):
return subprocess.run(
args, cwd=cwd, check=True, text=True,
stdout=subprocess.PIPE if capture else None,
env={**os.environ, "GIT_TERMINAL_PROMPT": "0", "CI": "true"},
).stdout
def read_lock(root):
lock = json.loads((root / "infra/ci/sources.lock.json").read_text())
if lock.get("schema") != "nodedc.device-core.ci-sources.v1":
raise ValueError("unsupported_source_lock")
if set(lock.get("dependencies", {})) != set(DEPENDENCIES):
raise ValueError("unexpected_source_dependencies")
for name, url in DEPENDENCIES.items():
item = lock["dependencies"][name]
if item.get("url") != url or not SHA.fullmatch(item.get("commit", "")):
raise ValueError("invalid_dependency_identity:" + name)
if not re.fullmatch(r"v22\.\d+\.\d+", lock.get("node", "")):
raise ValueError("invalid_node_version")
if not re.fullmatch(r"10\.\d+\.\d+", lock.get("npm", "")):
raise ValueError("invalid_npm_version")
return lock
def verify_checkout(path, commit):
if not SHA.fullmatch(commit):
raise ValueError("full_commit_sha_required")
if path.is_symlink() or not path.is_dir():
raise ValueError("regular_checkout_required:" + path.name)
top = Path(run(["git", "rev-parse", "--show-toplevel"], path, True).strip())
if top.resolve() != path.resolve():
raise ValueError("independent_checkout_required:" + path.name)
actual = run(["git", "rev-parse", "HEAD"], path, True).strip()
if actual != commit:
raise ValueError("source_commit_mismatch:" + path.name)
if run(["git", "status", "--porcelain", "--untracked-files=normal"], path, True).strip():
raise ValueError("dirty_source_checkout:" + path.name)
def verify_sources(root, commit, lock):
verify_checkout(root, commit)
for name, item in lock["dependencies"].items():
verify_checkout(root.parent / name, item["commit"])
def fetch_dependencies(root, lock):
# Never reset an operator checkout or reuse an earlier job's workspace.
for name in DEPENDENCIES:
target = root.parent / name
if target.exists() or target.is_symlink():
raise ValueError("dependency_destination_exists:" + name)
for name, item in lock["dependencies"].items():
target = root.parent / name
target.mkdir()
run(["git", "init", "--quiet"], target)
run(["git", "remote", "add", "origin", item["url"]], target)
run(["git", "fetch", "--quiet", "--depth=1", "origin", item["commit"]], target)
run(["git", "checkout", "--quiet", "--detach", "FETCH_HEAD"], target)
verify_checkout(target, item["commit"])
def tree_digest(root):
"""Digest paths + lengths + bytes, independent of mtime, owner and checkout path."""
digest = hashlib.sha256()
if not root.is_dir() or root.is_symlink():
raise ValueError("build_output_missing")
count = 0
for path in sorted(root.rglob("*")):
if path.is_symlink():
raise ValueError("symlink_in_build_output")
if path.is_dir():
continue
if not path.is_file():
raise ValueError("nonregular_build_output")
data = path.read_bytes()
name = path.relative_to(root).as_posix().encode()
digest.update(len(name).to_bytes(8, "big") + name)
digest.update(len(data).to_bytes(8, "big") + data)
count += 1
if count == 0:
raise ValueError("empty_build_output")
return digest.hexdigest()
def qualify(root, commit, lock, report):
if report.exists():
raise ValueError("qualification_report_already_exists")
verify_sources(root, commit, lock)
for tool in ("node", "npm"):
if run([tool, "--version"], root, True).strip() != lock[tool]:
raise ValueError("toolchain_version_mismatch:" + tool)
design = root.parent / "NODEDC_DESIGN_GUIDELINE"
steps = [
("design-install", design, ["npm", "ci", "--ignore-scripts", "--no-audit", "--no-fund"]),
("design-core", design, ["npm", "run", "build", "--workspace", "@nodedc/ui-core"]),
("design-react", design, ["npm", "run", "build", "--workspace", "@nodedc/ui-react"]),
("device-install", root, ["npm", "ci", "--ignore-scripts", "--no-audit", "--no-fund"]),
("unit-tests", root, ["npm", "test"]),
("ci-contract", root, [sys.executable, "-m", "unittest", "discover", "-s", "infra/ci", "-p", "test_*.py"]),
("build", root, ["npm", "run", "build"]),
("artifact-contracts", root, ["npm", "run", "test:deploy"]),
]
completed = []
for name, cwd, command in steps:
print("ci_step=" + name, flush=True)
run(command, cwd)
completed.append(name)
verify_sources(root, commit, lock)
result = {
"schema": "nodedc.device-core.qualification.v1",
"status": "qualified",
"deployed": False,
"sourceCommit": commit,
"sources": lock,
"sourceLockSha256": hashlib.sha256((root / "infra/ci/sources.lock.json").read_bytes()).hexdigest(),
"packageLockSha256": hashlib.sha256((root / "package-lock.json").read_bytes()).hexdigest(),
"managerDistSha256": tree_digest(root / "apps/device-manager/dist"),
"steps": completed,
}
report.parent.mkdir(parents=True, exist_ok=True)
with report.open("x") as stream:
json.dump(result, stream, indent=2)
stream.write("\n")
print(json.dumps(result), flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("fetch-dependencies", "verify", "check"))
parser.add_argument("--commit", required=True)
parser.add_argument("--report", type=Path)
args = parser.parse_args()
root = Path(__file__).resolve().parents[2]
verify_checkout(root, args.commit)
lock = read_lock(root)
if args.action == "fetch-dependencies":
fetch_dependencies(root, lock)
elif args.action == "verify":
verify_sources(root, args.commit, lock)
else:
if args.report is None:
parser.error("check requires --report outside the source checkouts")
report = args.report.resolve()
for checkout in (root, *(root.parent / name for name in DEPENDENCIES)):
if report.is_relative_to(checkout):
raise ValueError("report_must_be_outside_sources")
qualify(root, args.commit, lock, report)
if __name__ == "__main__":
main()
+15
View File
@@ -0,0 +1,15 @@
{
"schema": "nodedc.device-core.ci-sources.v1",
"node": "v22.21.0",
"npm": "10.9.4",
"dependencies": {
"NODEDC_DESIGN_GUIDELINE": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
"commit": "1b63366d2e7a911e18a293d30cddb0c95e0ba653"
},
"platform": {
"url": "https://git.dcserve.ru/SILVER/NODEDC_PLATFORM.git",
"commit": "11b73e64681f83aa2ebfd89ef266d3be2869f7e1"
}
}
}
+112
View File
@@ -0,0 +1,112 @@
import importlib.util
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest import mock
SPEC = importlib.util.spec_from_file_location("qualify", Path(__file__).with_name("qualify.py"))
CI = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(CI)
class QualificationTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / "source"
self.root.mkdir()
self.git("init", "--quiet")
self.git("config", "user.name", "CI Test")
self.git("config", "user.email", "ci@example.invalid")
(self.root / "source.txt").write_text("committed\n")
self.git("add", "source.txt")
self.git("commit", "--quiet", "-m", "fixture")
self.commit = self.git("rev-parse", "HEAD").strip()
def git(self, *args):
return subprocess.check_output(["git", *args], cwd=self.root, text=True)
def test_clean_exact_commit_is_accepted(self):
CI.verify_checkout(self.root, self.commit)
def test_stale_commit_is_rejected(self):
with self.assertRaisesRegex(ValueError, "source_commit_mismatch"):
CI.verify_checkout(self.root, "a" * 40)
def test_branch_name_is_not_a_release_identity(self):
with self.assertRaisesRegex(ValueError, "full_commit_sha_required"):
CI.verify_checkout(self.root, "main")
def test_local_edits_cannot_be_credited_to_a_commit(self):
(self.root / "source.txt").write_text("uncommitted\n")
with self.assertRaisesRegex(ValueError, "dirty_source_checkout"):
CI.verify_checkout(self.root, self.commit)
def test_untracked_source_is_rejected(self):
(self.root / "extra.mjs").write_text("export default 1")
with self.assertRaisesRegex(ValueError, "dirty_source_checkout"):
CI.verify_checkout(self.root, self.commit)
def test_parent_git_repository_is_not_accepted_as_a_dependency(self):
child = self.root / "child"
child.mkdir()
with self.assertRaisesRegex(ValueError, "independent_checkout_required"):
CI.verify_checkout(child, self.commit)
def test_existing_operator_dependencies_are_never_overwritten(self):
dependency = self.root.parent / "NODEDC_DESIGN_GUIDELINE"
dependency.mkdir()
marker = dependency / "local-work"
marker.write_text("preserve")
with self.assertRaisesRegex(ValueError, "dependency_destination_exists"):
CI.fetch_dependencies(self.root, {})
self.assertEqual(marker.read_text(), "preserve")
def test_lock_cannot_fetch_a_different_repository(self):
lock = json.loads(Path(__file__).with_name("sources.lock.json").read_text())
lock["dependencies"]["platform"]["url"] = "https://example.invalid/other.git"
(self.root / "infra/ci").mkdir(parents=True)
(self.root / "infra/ci/sources.lock.json").write_text(json.dumps(lock))
with self.assertRaisesRegex(ValueError, "invalid_dependency_identity:platform"):
CI.read_lock(self.root)
def test_digest_is_path_independent_and_changes_with_content(self):
a, b = self.root / "a", self.root / "b"
for directory in (a, b):
directory.mkdir()
(directory / "index.html").write_text("same")
self.assertEqual(CI.tree_digest(a), CI.tree_digest(b))
(b / "index.html").write_text("different")
self.assertNotEqual(CI.tree_digest(a), CI.tree_digest(b))
def test_build_cannot_include_external_symlinks(self):
output = self.root / "dist"
output.mkdir()
(output / "index.html").symlink_to(self.root / "source.txt")
with self.assertRaisesRegex(ValueError, "symlink_in_build_output"):
CI.tree_digest(output)
def test_failed_step_never_writes_success_report_or_runs_later_steps(self):
report = self.root.parent / "result.json"
lock = {"node": "v22.21.0", "npm": "10.9.4"}
with mock.patch.object(CI, "verify_sources"), mock.patch.object(
CI, "run", side_effect=["v22.21.0\n", "10.9.4\n", subprocess.CalledProcessError(1, "npm")]
) as execute:
with self.assertRaises(subprocess.CalledProcessError):
CI.qualify(self.root, self.commit, lock, report)
self.assertEqual(execute.call_count, 3)
self.assertFalse(report.exists())
def test_existing_report_cannot_be_mistaken_for_new_success(self):
report = self.root.parent / "result.json"
report.write_text('{"sourceCommit":"old"}')
with self.assertRaisesRegex(ValueError, "qualification_report_already_exists"):
CI.qualify(self.root, self.commit, {}, report)
self.assertEqual(json.loads(report.read_text())["sourceCommit"], "old")
if __name__ == "__main__":
unittest.main()