Add bounded Gitea CI build runner bootstrap for Synology

This commit is contained in:
Codex
2026-09-29 13:26:20 +03:00
parent 11b73e6468
commit f775929093
7 changed files with 750 additions and 1 deletions
+94
View File
@@ -0,0 +1,94 @@
# Synology CI foundation
This additive `gitea-ci` component creates only the Gitea build runner. It does
not activate automatic production apply, change Gitea itself, recreate Device
Core, open a port or modify application databases. Track activation in
DCPLATFORM-37; the canonical runner extension belongs to DCPLATFORM-21.
Initial policy: Device Core push to main automatically qualifies, then deploys
once the separate production controller and recurring release contract have
been accepted. Later repositories receive explicit registrations/policies.
## Reviewed contract
- Root: `/volume1/docker/nodedc-gitea-ci`.
- Compose project: `nodedc-gitea-ci`; selected service: `build-runner`.
- Three fixed data files: Compose, runner config, versioned descriptor.
- Runner and Node images use official Linux amd64 manifest digests (not mutable
tags), resolved from Docker Hub on 2026-09-29. The deploy runner pulls exactly
these two digests. No repository-provided image names or commands.
- Runner: 0.5 CPU, 512 MiB RAM, 128 PIDs, readonly root filesystem. Build jobs:
one at a time, 1 CPU, 2 GiB RAM, 256 PIDs, no privileged mode, no host bind
mounts, no host execution label and no Docker socket in job containers.
- No published ports or host networking. Runner cache and metrics listeners
are disabled. Communication uses outbound HTTPS to the existing Gitea.
- Only the trusted runner daemon mounts the Docker socket. That daemon is
privileged infrastructure even with dropped Linux capabilities: access to
Docker is host authority. It is not passed to repository jobs.
- The first worker is registered for `SILVER/NODEDC_DEVICE_CORE`; sharing with
other repositories requires a reviewed enrollment/registry transition.
## Enrollment, separately from the artifact
Use the authenticated Gitea API to obtain the Device Core repository runner
registration token. Do not copy a personal Git token into the runner.
Prepare `/volume1/docker/nodedc-deploy/runtime/gitea-ci/enrollment.pending.json`
as a private regular single-link file (mode 0600), containing only the exact
repository identity and its registration token. Never put this file in Git,
inbox, artifact payload, logs, Ops text or chat. The canonical runner imports
the token into a root-owned runtime file and mounts it readonly. Gitea creates
the persistent `/data/.runner` identity on first start. Its content is secret.
The bootstrap accepts no existing installed CI descriptor or CI container.
Preflight also checks at least 8 GiB free disk and 3 GiB currently available
memory. If that capacity is unavailable, review smaller fixed limits or another
worker placement; do not bypass the preflight.
## Build and install
From a clean Platform commit:
```sh
python3 -m unittest discover -s infra/gitea-ci -p 'test_*.py'
python3 infra/gitea-ci/build_artifact.py --patch-id gitea-ci-bootstrap-v1-<unique-id> --source-commit <full-sha> --output-dir <output-dir>
```
The first use requires promotion of the reviewed root runner through the
separate atomic administrative gate and fresh `verify-install`. Stage the
immutable `.tgz` in the canonical inbox and inspect its lifecycle. Obtain a
fresh `nodedc-deploy plan`, review exact scope, then apply that artifact once.
`apply` snapshots the source partition and identities of all preexisting
containers. Acceptance checks the pinned image, Compose identity, mounts,
resource limits, privileges and absence of port publications. It requires
registration plus ten seconds of stable daemon operation and unchanged
preexisting container identities. All secrets and application data are outside
the artifact/backup source partition.
If startup or acceptance fails, rollback removes only `build-runner` and
restores only the three source paths. Runner registration and enrollment are
preserved for diagnosis. A failed attempt may leave an offline registration in
Gitea; do not create another token or delete persistent identity blindly.
The global failed-artifact replay rule remains in force.
After `deploy-ok`, verify online registration and a real qualification job via
Gitea API/UI. This is separate functional acceptance; do not ask an operator
to re-prove Docker/runtime checks with NAS shell commands. Do not describe the
runner bootstrap or a green build as a completed automatic production deploy.
## Validation baseline
Installed predecessor confirmed by the operator on 2026-09-29:
`f21936f131365bd3993e2d746e332538d628ba50ef62c1cce833161171ffde47`,
Python 3.8.15, `verify-install-ok`. This matches Platform commit
`11b73e64681f83aa2ebfd89ef266d3be2869f7e1`. The older SMB runner copy is not the
installed authority. Historical Gitea recovery guards remain unchanged.
Tests cover deterministic packaging, exact runtime/payload boundaries, secret
file handling, bootstrap reuse rejection, preserved container identity, real
synthetic-host apply receipts, and failed-health source rollback with runtime
registration retained. Existing Platform/Device/Gitea regression suites are
also required before promotion.
References: [official runner configuration](https://docs.gitea.com/runner/configuration/),
[Docker installation](https://docs.gitea.com/runner/installation/docker/).
+11
View File
@@ -0,0 +1,11 @@
{
"schemaVersion": "nodedc.gitea-ci.bootstrap.v1",
"releaseId": "__PATCH_ID__",
"action": "bootstrap-build-runner",
"repository": "SILVER/NODEDC_DEVICE_CORE",
"instance": "https://git.dcserve.ru",
"runnerName": "synology-device-core-build",
"productionDeployEnabled": false,
"publishedPorts": [],
"capacity": 1
}
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Build the immutable, data-only Gitea CI bootstrap artifact from a clean commit."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import re
import subprocess
import tarfile
ROOT = Path(__file__).resolve().parents[2]
SOURCE = Path(__file__).resolve().parent
ENTRIES = ("docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v1.json")
def bundle(patch_id, source=SOURCE):
if not re.fullmatch(r"gitea-ci-bootstrap-v1-[a-zA-Z0-9._-]{1,65}", patch_id):
raise ValueError("invalid_bootstrap_identity")
descriptor = json.loads((source / "bootstrap-v1.json").read_text())
if descriptor["releaseId"] != "__PATCH_ID__":
raise ValueError("bootstrap_template_identity_mismatch")
descriptor["releaseId"] = patch_id
files = {
"manifest.env": ("id=" + patch_id + "\ncomponent=gitea-ci\ntype=app-overlay\n").encode(),
"files.txt": ("\n".join(ENTRIES) + "\n").encode(),
"payload/docker-compose.gitea-ci.yml": (source / ENTRIES[0]).read_bytes(),
"payload/runner.yaml": (source / ENTRIES[1]).read_bytes(),
"payload/deployment/bootstrap-v1.json": (json.dumps(descriptor, indent=2) + "\n").encode(),
}
result = io.BytesIO()
with gzip.GzipFile(fileobj=result, mode="wb", filename="", mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode="w", format=tarfile.USTAR_FORMAT) as archive:
for name, content in sorted(files.items()):
info = tarfile.TarInfo(name)
info.size = len(content)
info.mode = 0o644
info.mtime = 0
archive.addfile(info, io.BytesIO(content))
return result.getvalue()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--patch-id", required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--source-commit", required=True)
args = parser.parse_args()
actual = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
if not re.fullmatch(r"[a-f0-9]{40}", args.source_commit) or actual != args.source_commit:
raise SystemExit("source_commit_mismatch")
dirty = subprocess.check_output(["git", "status", "--porcelain"], cwd=ROOT, text=True).strip()
if dirty:
raise SystemExit("clean_committed_source_required")
data = bundle(args.patch_id)
args.output_dir.mkdir(parents=True, exist_ok=True)
path = args.output_dir / ("nodedc-gitea-ci-" + args.patch_id + ".tgz")
with path.open("xb") as output:
output.write(data)
print(json.dumps({
"artifact": str(path.resolve()), "patchId": args.patch_id,
"component": "gitea-ci", "sourceCommit": actual,
"sha256": hashlib.sha256(data).hexdigest(), "entries": ENTRIES,
"services": ["build-runner"], "publishedPorts": [],
"productionDeployEnabled": False,
}))
if __name__ == "__main__":
main()
@@ -0,0 +1,41 @@
services:
build-runner:
image: docker.io/gitea/runner@sha256:05e100d9c2268fb300f929cab014e9930591a2d66822454e175c1099d1464b14
platform: linux/amd64
pull_policy: never
restart: unless-stopped
read_only: true
cpus: 0.5
mem_limit: 512m
pids_limit: 128
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
tmpfs:
- /tmp:rw,nosuid,nodev,size=134217728
environment:
HOME: /data
XDG_CACHE_HOME: /data/.cache
CONFIG_FILE: /config/runner.yaml
GITEA_INSTANCE_URL: https://git.dcserve.ru
GITEA_RUNNER_NAME: synology-device-core-build
GITEA_RUNNER_REGISTRATION_TOKEN_FILE: /run/secrets/registration-token
volumes:
- type: bind
source: /volume1/docker/nodedc-gitea-ci/runner.yaml
target: /config/runner.yaml
read_only: true
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/data
target: /data
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/secrets/registration-token
target: /run/secrets/registration-token
read_only: true
bind: {create_host_path: false}
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
read_only: true
bind: {create_host_path: false}
+26
View File
@@ -0,0 +1,26 @@
log:
level: info
runner:
file: /data/.runner
capacity: 1
timeout: 1h
shutdown_timeout: 45m
insecure: false
fetch_interval: 5s
env_file: ""
envs:
NODE_OPTIONS: --max-old-space-size=1536
labels:
- nodedc-node22-build:docker://docker.io/library/node@sha256:9887ee8a5e5aa4fb02e09f03cdf81ef1b52184665549836fe3943eb0c2eaefdb
cache:
enabled: false
container:
network: ""
privileged: false
options: --cpus=1 --memory=2g --memory-swap=2g --pids-limit=256 --cap-drop=ALL --security-opt=no-new-privileges
valid_volumes: []
docker_host: "-"
force_pull: false
bind_workdir: false
metrics:
enabled: false
+232
View File
@@ -0,0 +1,232 @@
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import io
import importlib.machinery
import importlib.util
import json
from pathlib import Path
import tarfile
import tempfile
import unittest
from unittest import mock
import build_artifact
SOURCE = Path(__file__).resolve().parent
loader = importlib.machinery.SourceFileLoader("gitea_ci_runner_test", str(SOURCE.parent / "deploy-runner/nodedc-deploy"))
spec = importlib.util.spec_from_loader(loader.name, loader)
RUNNER = importlib.util.module_from_spec(spec)
loader.exec_module(RUNNER)
def container_info():
return {
"Config": {"Image": RUNNER.GITEA_CI_IMAGE, "Labels": {
"com.docker.compose.project": "nodedc-gitea-ci",
"com.docker.compose.service": "build-runner",
}},
"State": {"Running": True},
"HostConfig": {
"PortBindings": {}, "NetworkMode": "nodedc-gitea-ci_default",
"ReadonlyRootfs": True, "Memory": 512 * 1024 ** 2,
"NanoCpus": 500000000, "PidsLimit": 128,
"CapDrop": ["ALL"], "SecurityOpt": ["no-new-privileges:true"],
},
"NetworkSettings": {"Ports": {}},
"Mounts": [{"Destination": dest, "Source": source, "RW": rw, "Type": "bind"}
for dest, source, rw in [
("/config/runner.yaml", str(RUNNER.GITEA_CI_ROOT / "runner.yaml"), False),
("/data", str(RUNNER.GITEA_CI_ROOT / "data"), True),
("/run/secrets/registration-token", str(RUNNER.GITEA_CI_ROOT / "secrets/registration-token"), False),
("/var/run/docker.sock", "/var/run/docker.sock", False),
]],
}
class BootstrapTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name).resolve()
self.patch = "gitea-ci-bootstrap-v1-test-001"
self.artifact = self.root / "bootstrap.tgz"
self.artifact.write_bytes(build_artifact.bundle(self.patch))
self.extracted = self.root / "extracted"
self.extracted.mkdir()
def load(self):
return RUNNER.load_artifact(self.artifact, self.extracted)
def test_deterministic_data_bundle_accepted_by_canonical_runner(self):
self.assertEqual(self.artifact.read_bytes(), build_artifact.bundle(self.patch))
manifest, entries, _ = self.load()
self.assertEqual(manifest["component"], "gitea-ci")
self.assertEqual(tuple(entries), RUNNER.GITEA_CI_ENTRIES)
self.assertEqual(RUNNER.component_services("gitea-ci", entries), ("build-runner",))
self.assertEqual(RUNNER.component_builds("gitea-ci", entries), ())
self.assertTrue(RUNNER.component_compose_no_deps("gitea-ci", entries))
with tarfile.open(self.artifact) as archive:
self.assertEqual(len(archive.getmembers()), 5)
self.assertTrue(all(m.isfile() and m.mode == 0o644 for m in archive))
def test_changed_ports_or_privileges_in_source_are_rejected(self):
_, entries, payload = self.load()
compose = payload / RUNNER.GITEA_CI_ENTRIES[0]
compose.write_text(compose.read_text() + ' ports: ["9999:9999"]\n')
with self.assertRaisesRegex(RUNNER.DeployError, "immutable configuration"):
RUNNER.validate_gitea_ci_payload(payload, entries, self.patch)
def test_partial_update_and_production_activation_are_rejected(self):
_, entries, payload = self.load()
with self.assertRaisesRegex(RUNNER.DeployError, "entry set"):
RUNNER.validate_gitea_ci_payload(payload, entries[:1], self.patch)
descriptor_path = payload / RUNNER.GITEA_CI_ENTRIES[2]
descriptor = json.loads(descriptor_path.read_text())
descriptor["productionDeployEnabled"] = True
descriptor_path.write_text(json.dumps(descriptor))
with self.assertRaisesRegex(RUNNER.DeployError, "descriptor mismatch"):
RUNNER.validate_gitea_ci_payload(payload, entries, self.patch)
def test_credentials_hooks_and_extra_services_are_not_payload_paths(self):
for path in ("secrets/token", "data/.runner", "install.sh", "other.yml", "controller.py"):
with self.subTest(path=path), self.assertRaises(RUNNER.DeployError):
RUNNER.allowed_payload_path("gitea-ci", path)
def test_runtime_accepts_exact_isolated_daemon(self):
RUNNER.accept_gitea_ci_container(container_info())
def test_runtime_rejects_port_privilege_unbounded_memory_or_wrong_service(self):
for field, value in (
("PortBindings", {"8080/tcp": [{"HostPort": "8080"}]}),
("PublishAllPorts", True), ("NetworkMode", "host"),
("Privileged", True), ("Memory", 0), ("NanoCpus", 0),
("PidsLimit", 0), ("CapAdd", ["SYS_ADMIN"]),
("CapDrop", []), ("SecurityOpt", []),
):
info = container_info()
info["HostConfig"][field] = value
with self.subTest(field=field), self.assertRaises(RUNNER.DeployError):
RUNNER.accept_gitea_ci_container(info)
def test_runtime_rejects_production_volume_mount(self):
info = container_info()
info["Mounts"].append({"Destination": "/production", "Source": "/volume1/docker/nodedc-device-plane", "RW": True, "Type": "bind"})
with self.assertRaisesRegex(RUNNER.DeployError, "mount boundary"):
RUNNER.accept_gitea_ci_container(info)
def test_enrollment_must_be_private_and_is_not_logged_in_error(self):
pending = self.root / "enrollment.json"
pending.write_text(json.dumps({"repository": "SILVER/NODEDC_DEVICE_CORE", "token": "sensitive" * 6}))
with mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", pending):
pending.chmod(0o644)
with self.assertRaisesRegex(RUNNER.DeployError, "private regular"):
RUNNER.read_gitea_ci_enrollment()
pending.chmod(0o600)
self.assertEqual(RUNNER.read_gitea_ci_enrollment(), "sensitive" * 6)
pending.write_text('{"token":"sensitive", malformed')
with self.assertRaises(RUNNER.DeployError) as error:
RUNNER.read_gitea_ci_enrollment()
self.assertNotIn("sensitive", str(error.exception))
def test_symlink_enrollment_rejected(self):
actual = self.root / "actual"
actual.write_text("secret")
link = self.root / "link"
link.symlink_to(actual)
with mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", link):
with self.assertRaises(RUNNER.DeployError):
RUNNER.read_gitea_ci_enrollment()
def test_preflight_rejects_reusing_bootstrap_for_an_installed_release(self):
(self.root / RUNNER.GITEA_CI_ENTRIES[0]).write_text("installed")
with mock.patch.object(RUNNER, "GITEA_CI_ROOT", self.root):
with self.assertRaisesRegex(RUNNER.DeployError, "versioned upgrade"):
RUNNER.preflight_gitea_ci()
def test_inventory_preserves_only_non_ci_container_identities(self):
old = {"Image": "old", "State": {"Running": True, "StartedAt": "before"}, "Config": {"Labels": {}}}
own = copy.deepcopy(old)
own["Config"]["Labels"]["com.docker.compose.project"] = "nodedc-gitea-ci"
with mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=["old", "own"]), mock.patch.object(RUNNER, "inspect_container", side_effect=[old, own]):
self.assertEqual(RUNNER.gitea_ci_inventory(), {"old": {"image": "old", "startedAt": "before", "running": True}})
def test_rollback_removes_only_ci_service_and_restores_only_source(self):
with mock.patch.object(RUNNER, "stop_and_remove_compose_services") as stop, mock.patch.object(RUNNER, "restore_overlay_source") as restore, mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=[]):
RUNNER.rollback_gitea_ci(self.root, self.root / "backup", RUNNER.GITEA_CI_ENTRIES, "stamp", True)
stop.assert_called_once_with("gitea-ci", ("build-runner",))
restore.assert_called_once_with(self.root, self.root / "backup", RUNNER.GITEA_CI_ENTRIES, "stamp")
def apply_in_synthetic_host(self, fail_health=False):
host = self.root / "host"
host.mkdir()
names = {name: host / name.lower() for name in (
"INBOX", "APPLIED_DIR", "FAILED_DIR", "BACKUPS_DIR", "STATE_DIR", "TMP_DIR", "RUNTIME_DIR",
)}
for directory in names.values():
directory.mkdir()
names.update({
"STATE_FILE": names["STATE_DIR"] / "applied.jsonl",
"FAILED_STATE_FILE": names["STATE_DIR"] / "failed.jsonl",
"LOCK_DIR": names["STATE_DIR"] / "deploy.lock",
"DOCKER": Path("/usr/bin/true"),
})
app = host / "gitea-ci"
registry = {**RUNNER.COMPONENTS["gitea-ci"], "payload_root": app,
"compose_root": app, "compose_files": (app / "docker-compose.gitea-ci.yml",)}
candidate = names["INBOX"] / "candidate.tgz"
candidate.write_bytes(self.artifact.read_bytes())
def start_runtime(*args):
self.assertEqual(args, ("gitea-ci", list(RUNNER.GITEA_CI_ENTRIES), ("build-runner",)))
(app / "data").mkdir()
(app / "data" / "registration-marker").write_text("preserve-on-rollback")
with ExitStack() as stack:
for name, value in names.items():
stack.enter_context(mock.patch.object(RUNNER, name, value))
stack.enter_context(mock.patch.dict(RUNNER.COMPONENTS, {"gitea-ci": registry}))
stack.enter_context(mock.patch.object(RUNNER, "require_root"))
stack.enter_context(mock.patch.object(RUNNER.os, "chown"))
stack.enter_context(mock.patch.object(RUNNER, "preflight_gitea_ci", return_value={}))
stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_inventory", return_value={}))
stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=[]))
stack.enter_context(mock.patch.object(RUNNER, "run_component_runtime", side_effect=start_runtime))
stop = stack.enter_context(mock.patch.object(RUNNER, "stop_and_remove_compose_services"))
stack.enter_context(mock.patch.object(RUNNER, "accept_gitea_ci",
side_effect=RUNNER.DeployError("synthetic health failure") if fail_health else None))
output = stack.enter_context(redirect_stdout(io.StringIO()))
stack.enter_context(redirect_stderr(io.StringIO()))
if fail_health:
with self.assertRaisesRegex(RUNNER.DeployError, "synthetic health failure"):
RUNNER.apply_artifact(candidate)
stop.assert_called_once_with("gitea-ci", ("build-runner",))
else:
RUNNER.apply_artifact(candidate)
stop.assert_not_called()
return names, app, candidate, output.getvalue()
def test_apply_records_commit_independent_artifact_receipt_only_after_acceptance(self):
paths, app, candidate, output = self.apply_in_synthetic_host()
self.assertFalse(candidate.exists())
row = json.loads(paths["STATE_FILE"].read_text())
self.assertEqual(row["status"], "ok")
self.assertEqual(row["component"], "gitea-ci")
self.assertTrue((paths["APPLIED_DIR"] / candidate.name).is_file())
self.assertTrue((paths["BACKUPS_DIR"] / row["backup_id"] / "ci-runtime-before.json").is_file())
self.assertIn("deploy-ok", output)
self.assertTrue((app / "runner.yaml").is_file())
def test_failed_health_restores_source_preserves_registration_and_archives_failure(self):
paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True)
self.assertFalse(paths["STATE_FILE"].exists())
row = json.loads(paths["FAILED_STATE_FILE"].read_text())
self.assertEqual(row["rollback_status"], "ok:gitea-ci-bootstrap")
self.assertTrue((paths["FAILED_DIR"] / row["artifact"]).is_file())
self.assertFalse((app / "runner.yaml").exists())
self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback")
self.assertNotIn("deploy-ok", output)
if __name__ == "__main__":
unittest.main()