diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index 58d99b3..3d1cbf5 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -49,6 +49,9 @@ GITEA_CI_JOB_IMAGE = "docker.io/library/node@sha256:9887ee8a5e5aa4fb02e09f03cdf8 GITEA_CI_ENTRIES = ( "docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v1.json", ) +GITEA_CI_V2_ENTRIES = ( + "docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v2.json", +) GITEA_CI_SOURCE_SHA256 = { "docker-compose.gitea-ci.yml": "851d22ae9823c30508a552ec6abb7f547ceda671f3ca77552fb7032bc807ae09", "runner.yaml": "8634e5427986423ccd8fe18e3bf5072c53addbf17f1efc1395b3a473671d78fe", @@ -4922,7 +4925,7 @@ def allowed_payload_path(component, rel): die(f"path rejected: {rel}: {reason}") if component == "gitea-ci": - if rel in GITEA_CI_ENTRIES or rel == "deployment": + if rel in GITEA_CI_ENTRIES + GITEA_CI_V2_ENTRIES or rel == "deployment": return True die("Gitea CI accepts only its exact bootstrap contract") @@ -31389,16 +31392,18 @@ def rollback_map_access(root, backup_dir, entries, current_stamp): def validate_gitea_ci_payload(payload_dir, entries, release_id): - if tuple(entries) != GITEA_CI_ENTRIES: + v2 = tuple(entries) == GITEA_CI_V2_ENTRIES + if tuple(entries) not in (GITEA_CI_ENTRIES, GITEA_CI_V2_ENTRIES): die("Gitea CI bootstrap entry set mismatch") - if not release_id.startswith("gitea-ci-bootstrap-v1-"): + version = "v2" if v2 else "v1" + if not release_id.startswith("gitea-ci-bootstrap-" + version + "-"): die("Gitea CI bootstrap release identity mismatch") for rel, expected in GITEA_CI_SOURCE_SHA256.items(): if sha256_file(payload_dir / rel) != expected: die(f"Gitea CI immutable configuration mismatch: {rel}") - descriptor = read_strict_json(payload_dir / GITEA_CI_ENTRIES[2], "Gitea CI bootstrap") - if descriptor != { - "schemaVersion": "nodedc.gitea-ci.bootstrap.v1", + descriptor = read_strict_json(payload_dir / entries[2], "Gitea CI bootstrap") + expected = { + "schemaVersion": "nodedc.gitea-ci.bootstrap." + version, "releaseId": release_id, "action": "bootstrap-build-runner", "repository": "SILVER/NODEDC_DEVICE_CORE", @@ -31407,7 +31412,10 @@ def validate_gitea_ci_payload(payload_dir, entries, release_id): "productionDeployEnabled": False, "publishedPorts": [], "capacity": 1, - }: + } + if v2: + expected["enrollment"] = "import-dctouch-staging-to-root-private-runtime" + if descriptor != expected: die("Gitea CI bootstrap descriptor mismatch") return descriptor @@ -31440,6 +31448,106 @@ def read_gitea_ci_enrollment(): return value["token"] +def read_gitea_ci_v2_input(runtime=False): + """Read a bounded operator handoff or the private NAS copy, never SMB modes.""" + path = (GITEA_CI_ROOT / "secrets" / "registration-token" + if runtime else GITEA_CI_ENROLLMENT) + for parent in path.parents: + if parent.is_symlink(): + die("Gitea CI enrollment path contains a symlink") + try: + operator_uid = pwd.getpwnam("dctouch").pw_uid + except KeyError: + die("Gitea CI staging account dctouch is missing") + try: + fd = os.open(str(path), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError: + die("Gitea CI enrollment input cannot be opened safely") + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 + or not 1 <= info.st_size <= 2048 + or info.st_uid not in ((0,) if runtime else (0, operator_uid)) + or (runtime and stat.S_IMODE(info.st_mode) != 0o600)): + die("Gitea CI enrollment metadata rejected: " + f"runtime={runtime};mode={stat.S_IMODE(info.st_mode):04o};" + f"uid={info.st_uid};nlink={info.st_nlink};size={info.st_size}") + raw = stream.read(2049) + after = os.fstat(stream.fileno()) + if (info.st_size, info.st_mtime_ns, info.st_ctime_ns) != ( + after.st_size, after.st_mtime_ns, after.st_ctime_ns): + die("Gitea CI enrollment changed while reading") + try: + if runtime: + token = raw.decode("ascii").strip() + else: + value = json.loads(raw) + if (not isinstance(value, dict) or set(value) != {"repository", "token"} + or value["repository"] != "SILVER/NODEDC_DEVICE_CORE"): + raise ValueError() + token = value["token"] + if not isinstance(token, str) or not re.fullmatch(r"[A-Za-z0-9_-]{20,256}", token): + raise ValueError() + except (ValueError, UnicodeError): + die("Gitea CI enrollment format is invalid") + return token, info + + +def preflight_gitea_ci_v2_enrollment(): + private = GITEA_CI_ROOT / "secrets" / "registration-token" + if GITEA_CI_ENROLLMENT.exists() or GITEA_CI_ENROLLMENT.is_symlink(): + token, info = read_gitea_ci_v2_input() + if private.exists() or private.is_symlink(): + if read_gitea_ci_v2_input(runtime=True)[0] != token: + die("Gitea CI existing runtime enrollment differs") + return f"import-staging;mode={stat.S_IMODE(info.st_mode):04o};uid={info.st_uid};nlink={info.st_nlink};size={info.st_size}" + read_gitea_ci_v2_input(runtime=True) + return "reuse-root-private-runtime" + + +def import_gitea_ci_v2_enrollment(): + """The v2 apply transition owns private creation; plan never changes rights.""" + preflight_gitea_ci_v2_enrollment() + pending = GITEA_CI_ENROLLMENT.exists() + token, source_info = read_gitea_ci_v2_input(runtime=not pending) + directory = GITEA_CI_ROOT / "secrets" + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + if directory.is_symlink(): + die("Gitea CI private directory cannot be a symlink") + os.chown(str(directory), 0, 0) + directory.chmod(0o700) + target = directory / "registration-token" + if not target.exists(): + fd, temporary = tempfile.mkstemp(prefix=".enrollment-", dir=str(directory)) + try: + with os.fdopen(fd, "w") as stream: + os.fchown(stream.fileno(), 0, 0) + os.fchmod(stream.fileno(), 0o600) + stream.write(token + "\n") + stream.flush() + os.fsync(stream.fileno()) + # Atomic publication without replacing an existing identity. + os.link(temporary, str(target)) + finally: + os.unlink(temporary) + if read_gitea_ci_v2_input(runtime=True)[0] != token: + die("Gitea CI private enrollment import verification failed") + for path in (directory, GITEA_CI_ROOT): + fd = os.open(str(path), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + os.fsync(fd) + finally: + os.close(fd) + if pending: + current = GITEA_CI_ENROLLMENT.lstat() + if (current.st_dev, current.st_ino, current.st_mtime_ns, current.st_size) != ( + source_info.st_dev, source_info.st_ino, source_info.st_mtime_ns, source_info.st_size): + die("Gitea CI enrollment staging changed before cleanup") + GITEA_CI_ENROLLMENT.unlink() + print("ci_enrollment=root-owned-private-runtime;staging=removed") + return token + + def gitea_ci_container_ids(own=False): command = [str(DOCKER), "ps", "-aq", "--no-trunc"] if own: @@ -31465,15 +31573,18 @@ def gitea_ci_inventory(): return result -def preflight_gitea_ci(): +def preflight_gitea_ci(entries=GITEA_CI_ENTRIES): for parent in (GITEA_CI_ROOT, *GITEA_CI_ROOT.parents): if parent.is_symlink(): die("Gitea CI root contains a symlink") - if any((GITEA_CI_ROOT / rel).exists() for rel in GITEA_CI_ENTRIES): + if any((GITEA_CI_ROOT / rel).exists() for rel in GITEA_CI_ENTRIES + GITEA_CI_V2_ENTRIES): die("Gitea CI bootstrap requires no installed release; use a versioned upgrade") if gitea_ci_container_ids(own=True): die("Gitea CI bootstrap requires no existing CI containers") - read_gitea_ci_enrollment() + if tuple(entries) == GITEA_CI_V2_ENTRIES: + preflight_gitea_ci_v2_enrollment() + else: + read_gitea_ci_enrollment() if shutil.disk_usage(GITEA_CI_ROOT.parent).free < 8 * 1024 ** 3: die("Gitea CI requires 8 GiB free disk before image preparation") memory = {} @@ -31486,8 +31597,9 @@ def preflight_gitea_ci(): return gitea_ci_inventory() -def prepare_gitea_ci(): - token = read_gitea_ci_enrollment() +def prepare_gitea_ci(entries=GITEA_CI_ENTRIES): + token = (import_gitea_ci_v2_enrollment() if tuple(entries) == GITEA_CI_V2_ENTRIES + else read_gitea_ci_enrollment()) for directory in (GITEA_CI_ROOT / "data", GITEA_CI_ROOT / "secrets"): if directory.is_symlink(): die("Gitea CI runtime directory cannot be a symlink") @@ -31655,7 +31767,7 @@ def plan_artifact(artifact): if manifest["component"] == "mission-core-map-access": preflight_map_access(payload_dir, entries) if manifest["component"] == "gitea-ci": - preflight_gitea_ci() + preflight_gitea_ci(entries) reject_failed_artifact_replay(manifest, sha) reject_terminal_engine_l2_failed_artifact(manifest, sha) reject_terminal_device_plane_foundation_artifact(manifest, sha) @@ -32246,6 +32358,9 @@ def plan_artifact(artifact): print(f"ci_runner_image={GITEA_CI_IMAGE}") print(f"ci_job_image={GITEA_CI_JOB_IMAGE}") print("ci_pull=exact-digests-only;registration=separate-runtime-enrollment") + if tuple(entries) == GITEA_CI_V2_ENTRIES: + print("ci_enrollment=" + preflight_gitea_ci_v2_enrollment()) + print("ci_enrollment_apply=copy-to-root0600;private-directory0700;remove-staging-after-verification") print("ci_preserved=all-existing-containers,databases,volumes;rollback=bootstrap-source-and-runner-only") if component == "mission-core-map-access": print("access=local-forward:dctouch:127.0.0.1:18103") @@ -36360,7 +36475,7 @@ def prepare_component_runtime(component, entries=None): def run_component_runtime(component, entries, services): if component == "gitea-ci": - prepare_gitea_ci() + prepare_gitea_ci(entries) run_compose(component, services, entries) return if component == "platform" and is_platform_provider_catalog_only(entries): @@ -38933,7 +39048,7 @@ def apply_artifact(artifact): if component == "mission-core-map-access": preflight_map_access(payload_dir, entries) if component == "gitea-ci": - gitea_ci_before = preflight_gitea_ci() + gitea_ci_before = preflight_gitea_ci(entries) artifact_only = component_artifact_only(component) defer_bootstrap_root = is_gitea_bootstrap_slice( component, diff --git a/infra/gitea-ci/README.md b/infra/gitea-ci/README.md index 058f8bc..8058b5f 100644 --- a/infra/gitea-ci/README.md +++ b/infra/gitea-ci/README.md @@ -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- --source-commit --output-dir +python3 infra/gitea-ci/build_artifact.py --patch-id gitea-ci-bootstrap-v2- --source-commit --output-dir ``` The first use requires promotion of the reviewed root runner through the diff --git a/infra/gitea-ci/bootstrap-v2.json b/infra/gitea-ci/bootstrap-v2.json new file mode 100644 index 0000000..b2e59cb --- /dev/null +++ b/infra/gitea-ci/bootstrap-v2.json @@ -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" +} diff --git a/infra/gitea-ci/build_artifact.py b/infra/gitea-ci/build_artifact.py index 7cbd81d..72bb48e 100644 --- a/infra/gitea-ci/build_artifact.py +++ b/infra/gitea-ci/build_artifact.py @@ -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, })) diff --git a/infra/gitea-ci/test_bootstrap.py b/infra/gitea-ci/test_bootstrap.py index a4bd774..b0b186d 100644 --- a/infra/gitea-ci/test_bootstrap.py +++ b/infra/gitea-ci/test_bootstrap.py @@ -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() diff --git a/infra/gitea-ci/test_enrollment_v2.py b/infra/gitea-ci/test_enrollment_v2.py new file mode 100644 index 0000000..405ae6c --- /dev/null +++ b/infra/gitea-ci/test_enrollment_v2.py @@ -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()