Import CI enrollment into private NAS runtime during bootstrap
This commit is contained in:
@@ -32,12 +32,28 @@ been accepted. Later repositories receive explicit registrations/policies.
|
||||
|
||||
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
|
||||
Stage `/volume1/docker/nodedc-deploy/runtime/gitea-ci/enrollment.pending.json`
|
||||
through the operator's authenticated SMB session, 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.
|
||||
inbox, artifact payload, logs, Ops text or chat. This is a temporary handoff,
|
||||
not the runtime secret. The NAS owner must be `dctouch` or root. The v2
|
||||
preflight opens it with `O_NOFOLLOW`, rejects symlinks/hardlinks/special files,
|
||||
limits the input to 2048 bytes, validates its schema and checks for concurrent
|
||||
changes. Plan reports only safe filesystem metadata and does not change rights.
|
||||
|
||||
On 2026-09-29 the first v1 plan rejected this file's NAS metadata even though
|
||||
the Mac SMB mount displayed 0700/regular/nlink1. A Mac `chmod 600` and a
|
||||
successful Mac stat are not proof of the actual NAS permissions. V1's strict
|
||||
private-file check is retained; use the explicit v2 import transition for SMB.
|
||||
|
||||
V2 apply creates the private file on NAS as root: `secrets/registration-token`
|
||||
is 0600, its directory is 0700. Publication is atomic without overwriting an
|
||||
existing identity, file and directory entries are fsynced, then the private
|
||||
copy is revalidated. Only after that is the staging input removed. A mismatch
|
||||
with an existing private copy is rejected. An interrupted apply can reuse the
|
||||
same verified private copy after the canonical failure/retry review. Gitea
|
||||
creates the persistent `/data/.runner` identity on first start. Neither private
|
||||
file is part of the artifact, source backup, journal or diagnostic output.
|
||||
|
||||
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
|
||||
@@ -50,7 +66,7 @@ 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>
|
||||
python3 infra/gitea-ci/build_artifact.py --patch-id gitea-ci-bootstrap-v2-<unique-id> --source-commit <full-sha> --output-dir <output-dir>
|
||||
```
|
||||
|
||||
The first use requires promotion of the reviewed root runner through the
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"schemaVersion": "nodedc.gitea-ci.bootstrap.v2",
|
||||
"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,
|
||||
"enrollment": "import-dctouch-staging-to-root-private-runtime"
|
||||
}
|
||||
@@ -14,21 +14,23 @@ 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")
|
||||
V2_ENTRIES = ("docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v2.json")
|
||||
|
||||
|
||||
def bundle(patch_id, source=SOURCE):
|
||||
if not re.fullmatch(r"gitea-ci-bootstrap-v1-[a-zA-Z0-9._-]{1,65}", patch_id):
|
||||
if not re.fullmatch(r"gitea-ci-bootstrap-v[12]-[a-zA-Z0-9._-]{1,65}", patch_id):
|
||||
raise ValueError("invalid_bootstrap_identity")
|
||||
descriptor = json.loads((source / "bootstrap-v1.json").read_text())
|
||||
entries = V2_ENTRIES if patch_id.startswith("gitea-ci-bootstrap-v2-") else ENTRIES
|
||||
descriptor = json.loads((source / Path(entries[2]).name).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(),
|
||||
"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(),
|
||||
"payload/" + entries[2]: (json.dumps(descriptor, indent=2) + "\n").encode(),
|
||||
}
|
||||
result = io.BytesIO()
|
||||
with gzip.GzipFile(fileobj=result, mode="wb", filename="", mtime=0) as compressed:
|
||||
@@ -62,7 +64,8 @@ def main():
|
||||
print(json.dumps({
|
||||
"artifact": str(path.resolve()), "patchId": args.patch_id,
|
||||
"component": "gitea-ci", "sourceCommit": actual,
|
||||
"sha256": hashlib.sha256(data).hexdigest(), "entries": ENTRIES,
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
"entries": V2_ENTRIES if args.patch_id.startswith("gitea-ci-bootstrap-v2-") else ENTRIES,
|
||||
"services": ["build-runner"], "publishedPorts": [],
|
||||
"productionDeployEnabled": False,
|
||||
}))
|
||||
|
||||
@@ -157,7 +157,11 @@ class BootstrapTests(unittest.TestCase):
|
||||
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):
|
||||
def apply_in_synthetic_host(self, fail_health=False, version="v1"):
|
||||
expected_entries = RUNNER.GITEA_CI_ENTRIES
|
||||
if version == "v2":
|
||||
expected_entries = RUNNER.GITEA_CI_V2_ENTRIES
|
||||
self.artifact.write_bytes(build_artifact.bundle("gitea-ci-bootstrap-v2-test-001"))
|
||||
host = self.root / "host"
|
||||
host.mkdir()
|
||||
names = {name: host / name.lower() for name in (
|
||||
@@ -178,7 +182,7 @@ class BootstrapTests(unittest.TestCase):
|
||||
candidate.write_bytes(self.artifact.read_bytes())
|
||||
|
||||
def start_runtime(*args):
|
||||
self.assertEqual(args, ("gitea-ci", list(RUNNER.GITEA_CI_ENTRIES), ("build-runner",)))
|
||||
self.assertEqual(args, ("gitea-ci", list(expected_entries), ("build-runner",)))
|
||||
(app / "data").mkdir()
|
||||
(app / "data" / "registration-marker").write_text("preserve-on-rollback")
|
||||
|
||||
@@ -227,6 +231,19 @@ class BootstrapTests(unittest.TestCase):
|
||||
self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback")
|
||||
self.assertNotIn("deploy-ok", output)
|
||||
|
||||
def test_v2_apply_records_distinct_descriptor_and_receipt(self):
|
||||
paths, app, candidate, output = self.apply_in_synthetic_host(version="v2")
|
||||
self.assertTrue((app / "deployment/bootstrap-v2.json").is_file())
|
||||
self.assertFalse((app / "deployment/bootstrap-v1.json").exists())
|
||||
self.assertEqual(json.loads(paths["STATE_FILE"].read_text())["status"], "ok")
|
||||
self.assertIn("deploy-ok patch=gitea-ci-bootstrap-v2-test-001", output)
|
||||
|
||||
def test_v2_failed_health_preserves_identity_and_rolls_back_source(self):
|
||||
paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True, version="v2")
|
||||
self.assertFalse((app / "deployment/bootstrap-v2.json").exists())
|
||||
self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback")
|
||||
self.assertEqual(json.loads(paths["FAILED_STATE_FILE"].read_text())["rollback_status"], "ok:gitea-ci-bootstrap")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from contextlib import ExitStack, redirect_stdout
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import tempfile
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
import build_artifact
|
||||
from test_bootstrap import RUNNER
|
||||
|
||||
|
||||
class EnrollmentV2Tests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name).resolve()
|
||||
self.app = self.root / "ci"
|
||||
self.pending = self.root / "enrollment.pending.json"
|
||||
self.token = "fixture-not-a-real-token-1234567890"
|
||||
self.pending.write_text(json.dumps({
|
||||
"repository": "SILVER/NODEDC_DEVICE_CORE", "token": self.token,
|
||||
}))
|
||||
self.pending.chmod(0o666) # Simulate NAS permissions hidden by SMB's 0700 view.
|
||||
self.stack = ExitStack()
|
||||
self.addCleanup(self.stack.close)
|
||||
self.stack.enter_context(mock.patch.object(RUNNER, "GITEA_CI_ROOT", self.app))
|
||||
self.stack.enter_context(mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", self.pending))
|
||||
self.stack.enter_context(mock.patch.object(RUNNER.pwd, "getpwnam", return_value=SimpleNamespace(pw_uid=os.getuid())))
|
||||
|
||||
def emulate_root_ownership(self):
|
||||
fstat = os.fstat
|
||||
|
||||
def root_stat(fd):
|
||||
original = fstat(fd)
|
||||
fields = {key: getattr(original, key) for key in dir(original) if key.startswith("st_")}
|
||||
fields["st_uid"] = 0
|
||||
return SimpleNamespace(**fields)
|
||||
|
||||
self.stack.enter_context(mock.patch.object(RUNNER.os, "fstat", side_effect=root_stat))
|
||||
chown = self.stack.enter_context(mock.patch.object(RUNNER.os, "chown"))
|
||||
fchown = self.stack.enter_context(mock.patch.object(RUNNER.os, "fchown"))
|
||||
return chown, fchown
|
||||
|
||||
def test_v1_private_guard_still_rejects_shared_staging(self):
|
||||
with self.assertRaisesRegex(RUNNER.DeployError, "private regular"):
|
||||
RUNNER.read_gitea_ci_enrollment()
|
||||
|
||||
def test_v2_preflight_reports_metadata_without_mutation_or_secret(self):
|
||||
before = self.pending.stat()
|
||||
result = RUNNER.preflight_gitea_ci_v2_enrollment()
|
||||
self.assertIn("mode=0666", result)
|
||||
self.assertNotIn(self.token, result)
|
||||
self.assertEqual(self.pending.stat(), before)
|
||||
self.assertFalse(self.app.exists())
|
||||
|
||||
def test_v2_import_is_private_atomic_and_retryable_without_staging(self):
|
||||
chown, fchown = self.emulate_root_ownership()
|
||||
output = io.StringIO()
|
||||
with redirect_stdout(output):
|
||||
self.assertEqual(RUNNER.import_gitea_ci_v2_enrollment(), self.token)
|
||||
private = self.app / "secrets" / "registration-token"
|
||||
self.assertEqual(private.read_text(), self.token + "\n")
|
||||
self.assertEqual(stat.S_IMODE(private.stat().st_mode), 0o600)
|
||||
self.assertEqual(stat.S_IMODE(private.parent.stat().st_mode), 0o700)
|
||||
self.assertEqual(private.stat().st_nlink, 1)
|
||||
self.assertFalse(self.pending.exists())
|
||||
self.assertEqual(list(private.parent.iterdir()), [private])
|
||||
chown.assert_called_with(str(private.parent), 0, 0)
|
||||
self.assertEqual(fchown.call_args.args[1:], (0, 0))
|
||||
self.assertNotIn(self.token, output.getvalue())
|
||||
original_inode = private.stat().st_ino
|
||||
self.assertEqual(RUNNER.preflight_gitea_ci_v2_enrollment(), "reuse-root-private-runtime")
|
||||
with redirect_stdout(output):
|
||||
RUNNER.import_gitea_ci_v2_enrollment()
|
||||
self.assertEqual(private.stat().st_ino, original_inode)
|
||||
|
||||
def test_durability_failure_keeps_staging_for_recovery(self):
|
||||
self.emulate_root_ownership()
|
||||
# First fsync persists file bytes; the second publishes its directory entry.
|
||||
with mock.patch.object(RUNNER.os, "fsync", side_effect=[None, OSError("disk")]):
|
||||
with self.assertRaises(OSError):
|
||||
RUNNER.import_gitea_ci_v2_enrollment()
|
||||
self.assertTrue(self.pending.exists())
|
||||
self.assertEqual((self.app / "secrets/registration-token").read_text(), self.token + "\n")
|
||||
with redirect_stdout(io.StringIO()):
|
||||
RUNNER.import_gitea_ci_v2_enrollment()
|
||||
self.assertFalse(self.pending.exists())
|
||||
|
||||
def test_different_private_identity_is_never_overwritten(self):
|
||||
self.emulate_root_ownership()
|
||||
private = self.app / "secrets/registration-token"
|
||||
private.parent.mkdir(parents=True)
|
||||
private.write_text("different-fixture-token-1234567890\n")
|
||||
private.chmod(0o600)
|
||||
with self.assertRaisesRegex(RUNNER.DeployError, "differs"):
|
||||
RUNNER.import_gitea_ci_v2_enrollment()
|
||||
self.assertTrue(self.pending.exists())
|
||||
self.assertEqual(private.read_text(), "different-fixture-token-1234567890\n")
|
||||
|
||||
def test_wrong_operator_owner_rejected(self):
|
||||
with mock.patch.object(RUNNER.pwd, "getpwnam", return_value=SimpleNamespace(pw_uid=os.getuid() + 1)):
|
||||
with self.assertRaisesRegex(RUNNER.DeployError, "metadata rejected"):
|
||||
RUNNER.read_gitea_ci_v2_input()
|
||||
|
||||
def test_symlink_and_hardlink_rejected(self):
|
||||
actual = self.root / "actual"
|
||||
self.pending.rename(actual)
|
||||
self.pending.symlink_to(actual)
|
||||
with self.assertRaises(RUNNER.DeployError):
|
||||
RUNNER.read_gitea_ci_v2_input()
|
||||
self.pending.unlink()
|
||||
os.link(actual, self.pending)
|
||||
with self.assertRaisesRegex(RUNNER.DeployError, "nlink=2"):
|
||||
RUNNER.read_gitea_ci_v2_input()
|
||||
|
||||
def test_special_and_oversized_files_rejected_without_blocking(self):
|
||||
self.pending.unlink()
|
||||
os.mkfifo(self.pending)
|
||||
with self.assertRaises(RUNNER.DeployError):
|
||||
RUNNER.read_gitea_ci_v2_input()
|
||||
self.pending.unlink()
|
||||
self.pending.write_text("x" * 2049)
|
||||
with self.assertRaisesRegex(RUNNER.DeployError, "metadata rejected"):
|
||||
RUNNER.read_gitea_ci_v2_input()
|
||||
|
||||
def test_runtime_copy_requires_root_and_exact_private_mode(self):
|
||||
self.emulate_root_ownership()
|
||||
private = self.app / "secrets/registration-token"
|
||||
private.parent.mkdir(parents=True)
|
||||
private.write_text(self.token)
|
||||
private.chmod(0o644)
|
||||
with self.assertRaisesRegex(RUNNER.DeployError, "runtime=True;mode=0644"):
|
||||
RUNNER.read_gitea_ci_v2_input(runtime=True)
|
||||
|
||||
def test_wrong_repository_and_malformed_json_never_echo_secret(self):
|
||||
for value in [self.token + "!", json.dumps({"repository": "other", "token": self.token})]:
|
||||
self.pending.write_text(value)
|
||||
with self.assertRaises(RUNNER.DeployError) as error:
|
||||
RUNNER.read_gitea_ci_v2_input()
|
||||
self.assertNotIn(self.token, str(error.exception))
|
||||
|
||||
def test_v2_artifact_has_own_identity_and_no_secret_paths(self):
|
||||
patch = "gitea-ci-bootstrap-v2-test-001"
|
||||
data = build_artifact.bundle(patch)
|
||||
self.assertEqual(data, build_artifact.bundle(patch))
|
||||
artifact = self.root / "v2.tgz"
|
||||
artifact.write_bytes(data)
|
||||
extracted = self.root / "extracted"
|
||||
extracted.mkdir()
|
||||
manifest, entries, payload = RUNNER.load_artifact(artifact, extracted)
|
||||
self.assertEqual(tuple(entries), RUNNER.GITEA_CI_V2_ENTRIES)
|
||||
self.assertEqual(RUNNER.component_services("gitea-ci", entries), ("build-runner",))
|
||||
with self.assertRaisesRegex(RUNNER.DeployError, "release identity"):
|
||||
RUNNER.validate_gitea_ci_payload(payload, entries, patch.replace("v2", "v1"))
|
||||
with self.assertRaisesRegex(RUNNER.DeployError, "entry set"):
|
||||
RUNNER.validate_gitea_ci_payload(payload, list(entries) + [RUNNER.GITEA_CI_ENTRIES[2]], patch)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user