diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..46b5a88 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,30 @@ +name: Device Core qualification + +on: + push: + branches: [main] + workflow_dispatch: + +jobs: + qualify: + runs-on: nodedc-node22-build + timeout-minutes: 45 + steps: + - name: Check the exact pushed commit + env: + SOURCE_COMMIT: ${{ gitea.sha }} + run: | + set -eu + python3 -c 'import os,re; assert re.fullmatch("[0-9a-f]{40}", os.environ["SOURCE_COMMIT"]), "full commit SHA required"' + job_root=$(mktemp -d) + trap 'rm -rf "$job_root"' EXIT + source_root="$job_root/NODEDC_DEVICE_CORE" + mkdir "$source_root" + git -C "$source_root" init --quiet + git -C "$source_root" remote add origin https://git.dcserve.ru/SILVER/NODEDC_DEVICE_CORE.git + git -C "$source_root" fetch --quiet --depth=1 origin "$SOURCE_COMMIT" + 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" + # Production activation is separate: this job has no production access. + # Do not label a successful qualification as a successful deployment. diff --git a/README.md b/README.md index e6fb4fa..3bbfa35 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,11 @@ platform runner registry is validated separately in `NODEDC_PLATFORM`. ## Deployment ownership +The accepted Device Core policy is automatic deployment after a push to `main` +passes its checks. See [Continuous deployment](docs/CONTINUOUS_DEPLOYMENT.md) +for the pinned source qualification workflow, Synology setup and activation +status. Automatic production installation is not enabled yet. + Artifact builders in `infra/deploy-runner` emit data-only tarballs. They never orchestrate Docker or mutate a live host. Promotion remains the established two-step workflow: diff --git a/docs/CONTINUOUS_DEPLOYMENT.md b/docs/CONTINUOUS_DEPLOYMENT.md new file mode 100644 index 0000000..f23b52a --- /dev/null +++ b/docs/CONTINUOUS_DEPLOYMENT.md @@ -0,0 +1,109 @@ +# Device Core: deploy from main + +Decision, 2026-09-29: a push to `SILVER/NODEDC_DEVICE_CORE:main` must trigger +qualification and automatic deployment after the gates pass. No separate +`DEPLOY` branch or approval for each release. This decision is specific to +Device Core; other repositories keep their existing policy until onboarded. + +## Current implementation status + +The source qualification workflow is implemented in `.gitea/workflows/ci.yml`. +It does **not** deploy. The persistent Synology runner, deployment controller, +normal recurring release transition and live end-to-end acceptance are still +pending. A green qualification is not a deployment receipt. + +Live inspection on 2026-09-29 found Gitea 1.27.2, Device Core Actions disabled +and no repo-level runners. The instance-wide runner list was not accessible +with the current account (403); no conclusion about global runners is implied. + +## Host and network + +The first runner lives on Synology. No additional listening ports, DSM reverse +proxy route, firewall opening or webhook receiver are required. It polls the +existing Gitea HTTPS endpoint. Disable the runner cache server and metrics +listener initially. Start with one job at a time and an explicit CPU/RAM limit, +chosen after reading the live host baseline. + +Use container jobs, no host-execution labels, no privileged jobs, no arbitrary +host volumes and no Docker socket inside jobs. The runner daemon's own Docker +access is privileged infrastructure and belongs to Platform. Repository jobs +must not receive production paths, databases, runtime secrets or deploy keys. + +Build qualification and production installation are separate responsibilities. +A Platform-owned controller polls completed Gitea runs and drives the canonical +root-owned `nodedc-deploy` on the same NAS. It does not expose an HTTP server. +The application workflow cannot supply shell commands, target paths or service +names to this controller. Adding another repo requires an explicit registry +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. +`infra/ci/sources.lock.json` pins Design Guideline and Platform to full commits; +following their current `main` branches would make old releases unreproducible. +Dependencies are fetched into fresh sibling directories. Existing directories +are rejected, never reset or deleted by the qualification script. + +From a fresh exact Device Core checkout in a disposable parent directory: + +```sh +python3 infra/ci/qualify.py fetch-dependencies --commit +python3 infra/ci/qualify.py check --commit --report ../qualification.json +``` + +The checks reject dirty or wrong checkouts and mismatched toolchain versions. +They install lockfile dependencies, build the two required Design Guideline +packages, run Device Core unit and CI tests, compile the UI and run the existing +artifact contract suite against the pinned Platform runner source. The report +is created only after all checks pass and records all source SHAs, lockfile +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. + +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. + +## Production activation contract still to implement + +1. Verify the installed runner digest, applied journals, current manager/core + release descriptors and preserved runtime state on Synology. +2. Introduce a versioned **normal update** transition for repeat releases. + Historical recovery descriptors and fixed predecessor guards remain intact. + Reusing the v13 manager or v4 core recovery identity is not a CI strategy. +3. Persist each admitted `main` revision, run identity and artifact digest in a + durable queue. Serialize production transitions. Handle duplicate events + idempotently; never install an older revision after a newer one. A missed + poll must not lose a push. Do not depend on Gitea job completion order. +4. Link exact source commits to immutable data-only deploy artifacts. Retain + existing `manifest.env`, `files.txt`, `payload/...` validation and fixed + component/service selection. Exclude secrets, DB state and executable hooks. +5. Under the deploy lock, check the current predecessor, obtain and validate a + fresh canonical plan, then apply that exact digest automatically. Record + commit, run, artifact, plan, receipt and backup. The controller's allowlist + is root-owned and cannot be expanded by a workflow artifact. +6. Before activation verify push success, failed tests, wrong SHA/repo/branch, + duplicate events, overlapping pushes, restart recovery and failed-health + rollback. Verify that no new host ports or production mounts are exposed. + +Build/test failures leave production untouched. Runtime installation failures +follow the canonical runner's rollback policy; an ambiguous or failed rollback +stops subsequent applies for diagnosis. Never call an unconfirmed release +deployed. User/device data and tokens survive application updates. + +## Operator view + +Normal use after activation: push to `main`, then watch Gitea **Actions**. +Deployment status must separately show the installed commit and receipt. A red +check means the candidate did not qualify; it must not show a green deploy. +For emergency pause, stop admitting new deployments without cancelling an +in-progress apply. Recovery/rollback remains a recorded canonical transition. + +Track shared infrastructure in Ops **DCPLATFORM-37**, root deploy contracts in +**DCPLATFORM-21**, and B2 server/contour integration in **MISSIONCOR-86**. +This deployment mechanism does not mix Device Core and Mission Core inventories. + +References: [Gitea Actions](https://docs.gitea.com/usage/actions/overview/), +[runner configuration](https://docs.gitea.com/runner/configuration/). diff --git a/infra/ci/qualify.py b/infra/ci/qualify.py new file mode 100644 index 0000000..7c3a1d7 --- /dev/null +++ b/infra/ci/qualify.py @@ -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() diff --git a/infra/ci/sources.lock.json b/infra/ci/sources.lock.json new file mode 100644 index 0000000..e39a59d --- /dev/null +++ b/infra/ci/sources.lock.json @@ -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" + } + } +} diff --git a/infra/ci/test_qualify.py b/infra/ci/test_qualify.py new file mode 100644 index 0000000..3f71771 --- /dev/null +++ b/infra/ci/test_qualify.py @@ -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()