diff --git a/infra/deploy-runner/nodedc-deploy b/infra/deploy-runner/nodedc-deploy index 0581c45..907860b 100755 --- a/infra/deploy-runner/nodedc-deploy +++ b/infra/deploy-runner/nodedc-deploy @@ -70,6 +70,15 @@ GITEA_CI_V4_SOURCE_SHA256 = { "docker-compose.gitea-ci.yml": "dd218ef77a6505042484bbdb5cb329da043801a42e13af746fc8ba23c05e0f9c", "runner.yaml": "94d8e4d8345b2b5bc7c8923bff7c31ff59083ec7115d633af10152b93bcd9da6", } +GITEA_ACTIONS_ROOT = Path("/volume1/docker/nodedc-gitea-actions") +GITEA_ACTIONS_ENTRY = "deployment/actions-enable-v1.json" +GITEA_ACTIONS_LEGACY = Path("/volume1/docker/gitea-clean-standalone-v1") +GITEA_ACTIONS_CONFIG = Path("/volume1/docker/gitea-clean-20260820/config/app.ini") +GITEA_ACTIONS_CONTAINER = "clean-gitea-20260820" +GITEA_ACTIONS_IMAGE = "docker.gitea.com/gitea:1.27.2-rootless@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c" +GITEA_ACTIONS_BEFORE = "38a60b2fff6b40de6bb97959eb0abd1c7797aba9b1e9760f66f25f79cd337336" +GITEA_ACTIONS_AFTER = "67d22244db2fd6217072d928969d1b694d89b8b0f5c73b4ff628733e72136b27" +GITEA_ACTIONS_PING = "/api/actions/ping.v1.PingService/Ping" MAP_GATEWAY_SECRET_DIR = Path("/volume1/docker/nodedc-platform/secrets") MAP_GATEWAY_SECRET_FILE = MAP_GATEWAY_SECRET_DIR / "map-gateway-admin-secret" MAP_EGRESS_PROXY_SECRET_FILE = MAP_GATEWAY_SECRET_DIR / "map-egress-proxy-token" @@ -3092,6 +3101,16 @@ COMPONENTS = { # separately registers the third stateless service. "services": ("device-control-core", "device-gateway"), }, + "gitea-actions-config": { + "payload_root": GITEA_ACTIONS_ROOT, + "compose_root": GITEA_ACTIONS_LEGACY, + "compose_project": "clean-gitea", + "compose_files": (GITEA_ACTIONS_LEGACY / "compose.yaml",), + "compose_env_file": GITEA_ACTIONS_LEGACY / "production.env", + "bootstrap_root": True, + "compose_no_deps": True, + "services": ("gitea",), + }, "gitea-ci": { "payload_root": GITEA_CI_ROOT, "compose_root": GITEA_CI_ROOT, @@ -4938,6 +4957,10 @@ def allowed_payload_path(component, rel): if reason: die(f"path rejected: {rel}: {reason}") + if component == "gitea-actions-config": + if rel in ("deployment", GITEA_ACTIONS_ENTRY): + return True + die("Gitea Actions accepts only its activation descriptor") if component == "gitea-ci": if rel in GITEA_CI_ENTRIES + GITEA_CI_V2_ENTRIES + GITEA_CI_V3_ENTRIES + GITEA_CI_V4_ENTRIES or rel == "deployment": return True @@ -11544,6 +11567,8 @@ def load_artifact(artifact, work_dir): die(f"files.txt entry missing in payload: {rel}") validate_payload_tree(manifest["component"], payload_dir, entries) + if manifest["component"] == "gitea-actions-config": + validate_gitea_actions_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "gitea-ci": validate_gitea_ci_payload(payload_dir, entries, manifest["id"]) if manifest["component"] == "mission-core-map-access": @@ -31405,6 +31430,236 @@ def rollback_map_access(root, backup_dir, entries, current_stamp): die("Map access rollback policy verification failed") +def validate_gitea_actions_payload(payload_dir, entries, release_id): + if tuple(entries) != (GITEA_ACTIONS_ENTRY,) or not re.fullmatch( + r"gitea-actions-enable-v1-[a-zA-Z0-9._-]{1,65}", release_id): + die("Gitea Actions transition identity mismatch") + expected = {"schemaVersion": "nodedc.gitea.actions-enable.v1", "releaseId": release_id, + "action": "enable-instance-actions", "service": "gitea", + "productionDeployEnabled": False} + if read_strict_json(payload_dir / GITEA_ACTIONS_ENTRY, "Gitea Actions descriptor") != expected: + die("Gitea Actions descriptor mismatch") + + +def gitea_actions_read_config(): + for parent in GITEA_ACTIONS_CONFIG.parents: + if parent.is_symlink(): + die("Gitea Actions config parent symlink rejected") + fd = os.open(str(GITEA_ACTIONS_CONFIG), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + 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 0 < info.st_size < 65536: + die("Gitea Actions config metadata rejected") + data = stream.read(65536) + return data, info + + +def gitea_actions_transform(data): + # Never parse/re-serialize the full INI: unrelated settings and secrets retain exact bytes. + if hashlib.sha256(data).hexdigest() != GITEA_ACTIONS_BEFORE: + die("Gitea Actions config predecessor mismatch") + matches = list(re.finditer(rb"(?ms)^\[actions\][ \t]*\r?\n(.*?)(?=^\[|\Z)", data)) + if len(matches) != 1: + die("Gitea Actions section mismatch") + match = matches[0] + section, count = re.subn(rb"(?m)^(ENABLED[ \t]*=[ \t]*)false([ \t]*\r?)$", + rb"\g<1>true\2", match.group(1)) + target = data[:match.start(1)] + section + data[match.end(1):] + if count != 1 or hashlib.sha256(target).hexdigest() != GITEA_ACTIONS_AFTER: + die("Gitea Actions exact target mismatch") + return target + + +def gitea_actions_http(base, path, ping=False): + request = urllib.request.Request(base + path) + if ping: + request = urllib.request.Request(base + path, data=b'{"data":"nodedc-ci-probe"}', + headers={"Content-Type": "application/json", "Connect-Protocol-Version": "1"}) + # Instance/paths are constants in this runner; no credential or arbitrary URL is accepted. + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + try: + with opener.open(request, timeout=8) as response: + if response.geturl() != base + path: + die("Gitea Actions endpoint redirected") + raw = response.read(4097) + if len(raw) > 4096: + die("Gitea Actions response too large") + return response.status, json.loads(raw) + except urllib.error.HTTPError as error: + return error.code, None + except (urllib.error.URLError, OSError, ValueError): + die("Gitea Actions endpoint unavailable (DNS/TLS/network/JSON)") + + +def require_gitea_actions_ping(base="https://git.dcserve.ru"): + status, value = gitea_actions_http(base, GITEA_ACTIONS_PING, ping=True) + if status != 200 or value != {"data": "Hello, nodedc-ci-probe!"}: + die(f"Gitea Actions RPC unavailable: HTTP {status}; enable instance Actions before CI bootstrap") + + +def gitea_actions_container(require_running=True): + info = inspect_container(GITEA_ACTIONS_CONTAINER) + config = info.get("Config", {}) + labels = config.get("Labels", {}) + if (info.get("Name") != "/" + GITEA_ACTIONS_CONTAINER + or config.get("Image") != GITEA_ACTIONS_IMAGE + or labels.get("com.docker.compose.project") != "clean-gitea" + or labels.get("com.docker.compose.service") != "gitea" + or (require_running and not info.get("State", {}).get("Running")) + or config.get("Cmd") != ["web", "--config", "/etc/gitea/app.ini"] + or any(x.upper().startswith("GITEA__ACTIONS__") for x in config.get("Env", []))): + die("Gitea Actions existing container identity mismatch") + ports = info.get("HostConfig", {}).get("PortBindings") + if ports != {"3000/tcp": [{"HostIp": "172.22.0.222", "HostPort": "3000"}], + "2222/tcp": [{"HostIp": "0.0.0.0", "HostPort": "4022"}]}: + die("Gitea Actions existing port bindings mismatch") + mounts = {x.get("Destination"): (x.get("Source"), x.get("RW")) for x in info.get("Mounts", [])} + if (mounts.get("/etc/gitea/app.ini") != (str(GITEA_ACTIONS_CONFIG), False) + or mounts.get("/var/lib/gitea") != (str(GITEA_ACTIONS_CONFIG.parent.parent / "data"), True)): + die("Gitea Actions existing data/config mounts mismatch") + networks = info.get("NetworkSettings", {}).get("Networks", {}) + network = networks.get("clean-gitea_clean_gitea", {}) + if (set(networks) != {"clean-gitea_clean_gitea"} + or (info.get("State", {}).get("Running") and network.get("IPAddress") != "172.22.27.2")): + die("Gitea Actions existing network mismatch") + return info + + +def gitea_actions_fingerprint(info): + fields = {key: info.get(key) for key in ("Id", "Image", "Config", "HostConfig", "Mounts")} + fields["networks"] = sorted(info.get("NetworkSettings", {}).get("Networks", {})) + return hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest() + + +def preflight_gitea_actions(): + expected = {"compose.yaml": "c21ef87833f87623f8352477d2b541d0a0f48769d8f9f79251d58033e90197ff", + "production.env": "9ebbf8638e035dddca25fd455b2ac4d4b6db306e1a6a4debd973b133fdeb5bb7"} + for rel, digest in expected.items(): + path = GITEA_ACTIONS_LEGACY / rel + if any(parent.is_symlink() for parent in (path, *path.parents)) or sha256_file(path) != digest: + die("Gitea Actions effective Compose context mismatch") + if (GITEA_ACTIONS_ROOT / GITEA_ACTIONS_ENTRY).exists(): + die("Gitea Actions activation is already installed") + data, metadata = gitea_actions_read_config() + gitea_actions_transform(data) + info = gitea_actions_container() + if info.get("Image") != inspect_local_image(GITEA_ACTIONS_IMAGE, "Gitea Actions preserved image"): + die("Gitea Actions existing image digest mismatch") + if info.get("State", {}).get("Health", {}).get("Status") != "healthy": + die("Gitea Actions predecessor must be healthy") + status, version = gitea_actions_http("http://172.22.27.2:3000", "/api/v1/version") + if status != 200 or version != {"version": "1.27.2"}: + die("Gitea Actions predecessor version mismatch") + status, _ = gitea_actions_http("http://172.22.27.2:3000", GITEA_ACTIONS_PING, ping=True) + if status != 404: + die("Gitea Actions predecessor must have inactive RPC") + inventory = gitea_ci_inventory() + inventory.pop(info["Id"], None) + return {"config": data, "metadata": metadata, "containerId": info["Id"], + "fingerprint": gitea_actions_fingerprint(info), "inventory": inventory} + + +def gitea_actions_replace(expected_sha, data, metadata): + current, current_stat = gitea_actions_read_config() + if (hashlib.sha256(current).hexdigest() != expected_sha + or (current_stat.st_uid, current_stat.st_gid, stat.S_IMODE(current_stat.st_mode)) != + (metadata.st_uid, metadata.st_gid, stat.S_IMODE(metadata.st_mode))): + die("Gitea Actions config changed before atomic replacement") + fd, name = tempfile.mkstemp(prefix=".actions-enable-", dir=str(GITEA_ACTIONS_CONFIG.parent)) + try: + with os.fdopen(fd, "wb") as stream: + os.fchown(stream.fileno(), metadata.st_uid, metadata.st_gid) + os.fchmod(stream.fileno(), stat.S_IMODE(metadata.st_mode)) + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + if sha256_file(GITEA_ACTIONS_CONFIG) != expected_sha: + die("Gitea Actions config changed during replacement") + os.replace(name, str(GITEA_ACTIONS_CONFIG)) + fsync_directory(GITEA_ACTIONS_CONFIG.parent) + finally: + if os.path.exists(name): + os.unlink(name) + + +def apply_gitea_actions(before, backup_dir): + private = RUNTIME_DIR / "gitea-actions" / backup_dir.name + for parent in (private, *private.parents): + if parent.is_symlink(): + die("Gitea Actions private backup parent symlink rejected") + private.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + os.chown(str(private.parent), 0, 0) + private.parent.chmod(0o700) + private.mkdir(mode=0o700) + fd = os.open(str(private / "app.ini.before"), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fd, "wb") as stream: + os.fchown(stream.fileno(), 0, 0) + stream.write(before["config"]) + stream.flush() + os.fsync(stream.fileno()) + fsync_directory(private) + fsync_directory(private.parent) + fsync_directory(RUNTIME_DIR) + receipt = {key: before[key] for key in ("containerId", "fingerprint", "inventory")} + receipt.update({"configBeforeSha256": GITEA_ACTIONS_BEFORE, "configAfterSha256": GITEA_ACTIONS_AFTER}) + (backup_dir / "gitea-actions-before.json").write_text(json.dumps(receipt, sort_keys=True) + "\n") + if gitea_actions_fingerprint(gitea_actions_container()) != before["fingerprint"]: + die("Gitea Actions runtime changed before mutation") + gitea_actions_replace(GITEA_ACTIONS_BEFORE, gitea_actions_transform(before["config"]), before["metadata"]) + subprocess.run([str(DOCKER), "restart", "--time", "60", before["containerId"]], + check=True, capture_output=True, timeout=90) + + +def accept_gitea_actions(before, enabled=True): + deadline = time.monotonic() + 120 + while True: + try: + info = gitea_actions_container() + if gitea_actions_fingerprint(info) != before["fingerprint"]: + die("Gitea Actions runtime configuration drift") + expected = GITEA_ACTIONS_AFTER if enabled else GITEA_ACTIONS_BEFORE + if sha256_file(GITEA_ACTIONS_CONFIG) != expected: + die("Gitea Actions config acceptance mismatch") + status, version = gitea_actions_http("http://172.22.27.2:3000", "/api/v1/version") + if status != 200 or version != {"version": "1.27.2"}: + die("Gitea Actions version acceptance mismatch") + status, ping = gitea_actions_http("http://172.22.27.2:3000", GITEA_ACTIONS_PING, ping=True) + if enabled: + if status != 200 or ping != {"data": "Hello, nodedc-ci-probe!"}: + die("Gitea Actions RPC acceptance mismatch") + elif status != 404: + die("Gitea Actions rollback RPC acceptance mismatch") + if info.get("State", {}).get("Health", {}).get("Status") != "healthy": + die("Gitea Actions waiting for health") + inventory = gitea_ci_inventory() + inventory.pop(before["containerId"], None) + if inventory != before["inventory"]: + die("Gitea Actions preserved inventory mismatch") + print("gitea_actions_accept=" + ("enabled" if enabled else "restored-disabled") + ";data-and-other-services=preserved") + return + except DeployError: + if time.monotonic() >= deadline: + raise + time.sleep(2) + + +def rollback_gitea_actions(root, backup_dir, entries, current_stamp, before, runtime_started): + if runtime_started: + info = gitea_actions_container(require_running=False) + if gitea_actions_fingerprint(info) != before["fingerprint"]: + die("Gitea Actions rollback runtime drift") + current = sha256_file(GITEA_ACTIONS_CONFIG) + if current == GITEA_ACTIONS_AFTER: + gitea_actions_replace(GITEA_ACTIONS_AFTER, before["config"], before["metadata"]) + elif current != GITEA_ACTIONS_BEFORE: + die("Gitea Actions rollback refuses unrelated config drift") + if current == GITEA_ACTIONS_AFTER or not info.get("State", {}).get("Running"): + subprocess.run([str(DOCKER), "restart", "--time", "60", before["containerId"]], + check=True, capture_output=True, timeout=90) + accept_gitea_actions(before, enabled=False) + restore_overlay_source(root, backup_dir, entries, current_stamp) + + def validate_gitea_ci_payload(payload_dir, entries, release_id): v2 = tuple(entries) == GITEA_CI_V2_ENTRIES v3 = tuple(entries) == GITEA_CI_V3_ENTRIES @@ -31648,6 +31903,7 @@ def preflight_gitea_ci(entries=GITEA_CI_ENTRIES): if any((GITEA_CI_ROOT / rel).exists() for rel in GITEA_CI_ENTRIES + GITEA_CI_V2_ENTRIES + GITEA_CI_V3_ENTRIES + GITEA_CI_V4_ENTRIES): die("Gitea CI bootstrap requires no installed release; use a versioned upgrade") gitea_ci_host_capabilities(entries) + require_gitea_actions_ping() if gitea_ci_container_ids(own=True): die("Gitea CI bootstrap requires no existing CI containers") if tuple(entries) in (GITEA_CI_V2_ENTRIES, GITEA_CI_V3_ENTRIES, GITEA_CI_V4_ENTRIES): @@ -31779,8 +32035,37 @@ def accept_gitea_ci(entries=GITEA_CI_ENTRIES): time.sleep(2) +def capture_gitea_ci_diagnostics(backup_dir): + # Logs can contain tokens. Retain only fixed categories and counts, never raw text. + report = {"containers": [], "rawLogsSaved": False} + try: + for container_id in gitea_ci_container_ids(own=True): + result = subprocess.run([str(DOCKER), "logs", "--tail", "60", container_id], + capture_output=True, text=True, timeout=10) + text = (result.stdout + result.stderr).lower() + signatures = {"dns": ("no such host", "server misbehaving"), + "tls": ("x509", "tls handshake"), + "network": ("connection refused", "i/o timeout", "no route to host"), + "actions-disabled-or-route": ("404", "not found"), + "token-rejected": ("registration token", "unauthenticated"), + "filesystem": ("permission denied", "read-only file system"), + "configuration": ("unmarshal", "yaml:", "invalid config"), + "registered": ("runner registered successfully",)} + reasons = [key for key, patterns in signatures.items() if any(p in text for p in patterns)] + report["containers"].append({"id": container_id, "categories": reasons or ["unclassified"], + "logLines": len(text.splitlines())}) + except Exception: + report["diagnosticStatus"] = "unavailable" + (backup_dir / "ci-startup-diagnostics.json").write_text(json.dumps(report, sort_keys=True) + "\n") + print("ci_startup_diagnostics=" + json.dumps(report, sort_keys=True)) + + def rollback_gitea_ci(root, backup_dir, entries, current_stamp, runtime_started): if runtime_started: + try: + capture_gitea_ci_diagnostics(backup_dir) + except Exception: + print("ci_startup_diagnostics=unavailable") stop_and_remove_compose_services("gitea-ci", ("build-runner",)) restore_overlay_source(root, backup_dir, entries, current_stamp) if gitea_ci_container_ids(own=True): @@ -31849,6 +32134,8 @@ def plan_artifact(artifact): preflight_map_access(payload_dir, entries) if manifest["component"] == "gitea-ci": preflight_gitea_ci(entries) + if manifest["component"] == "gitea-actions-config": + preflight_gitea_actions() reject_failed_artifact_replay(manifest, sha) reject_terminal_engine_l2_failed_artifact(manifest, sha) reject_terminal_device_plane_foundation_artifact(manifest, sha) @@ -32432,6 +32719,14 @@ def plan_artifact(artifact): print(f"component={component}") print(f"type={manifest['type']}") print(f"payload_root={root}") + if component == "gitea-actions-config": + print("gitea_actions_transition=disabled-to-enabled;production_deploy=false") + print("gitea_actions_runtime=restart-existing-clean-gitea-20260820;brief-web-and-ssh-interruption") + print("gitea_actions_config=one-boolean-only;owner-and-mode=preserved") + print(f"gitea_actions_config_before={GITEA_ACTIONS_BEFORE}") + print(f"gitea_actions_config_after={GITEA_ACTIONS_AFTER}") + print("gitea_actions_preserved=images,ports,mounts,databases,repositories,LFS,other-containers") + print("gitea_actions_rollback=private-root0600-config-copy;restore-flag-and-restart-same-container") if component == "gitea-ci": print("ci_transition=bootstrap-build-runner;production_deploy=false") print("ci_ports=none;cache=false;metrics=false;capacity=1") @@ -37984,6 +38279,11 @@ process.stdout.write('engine-l2-closed-loop:0.7.0:cas+safe-profile+external-plan def run_healthchecks(component, entries=None, services=None): + if component == "gitea-actions-config": + if tuple(services or ()) != ("gitea",) or tuple(entries or ()) != (GITEA_ACTIONS_ENTRY,): + die("Gitea Actions service/entry set mismatch") + # Context-aware acceptance runs in apply immediately after the restart. + return if component == "gitea-ci": if tuple(services or ()) != ("build-runner",): die("Gitea CI service set mismatch") @@ -39091,6 +39391,7 @@ def apply_artifact(artifact): engine_backend_initial_mode = None runtime_started = False gitea_ci_before = None + gitea_actions_before = None current_stamp = stamp() with DeployLock(): @@ -39137,6 +39438,8 @@ def apply_artifact(artifact): preflight_map_access(payload_dir, entries) if component == "gitea-ci": gitea_ci_before = preflight_gitea_ci(entries) + if component == "gitea-actions-config": + gitea_actions_before = preflight_gitea_actions() artifact_only = component_artifact_only(component) defer_bootstrap_root = is_gitea_bootstrap_slice( component, @@ -39749,6 +40052,10 @@ def apply_artifact(artifact): # can be safely reconciled by recreating on that runtime. engine_backend_recreated = True run_compose(component, services, entries) + elif component == "gitea-actions-config": + runtime_started = True + apply_gitea_actions(gitea_actions_before, backup_dir) + accept_gitea_actions(gitea_actions_before) elif component == "device-plane": def mark_device_plane_runtime_started(): nonlocal runtime_started @@ -39858,7 +40165,14 @@ def apply_artifact(artifact): and backup_dir is not None and root is not None ): - if component == "gitea-ci": + if component == "gitea-actions-config": + try: + rollback_gitea_actions(root, backup_dir, entries, current_stamp, + gitea_actions_before, runtime_started) + rollback_status = "ok:gitea-actions-config" + except Exception as rollback_exc: + rollback_status = f"failed:{type(rollback_exc).__name__}" + elif component == "gitea-ci": try: rollback_gitea_ci(root, backup_dir, entries, current_stamp, runtime_started) if gitea_ci_inventory() != gitea_ci_before: diff --git a/infra/gitea-ci/README.md b/infra/gitea-ci/README.md index 70d2a68..b9562de 100644 --- a/infra/gitea-ci/README.md +++ b/infra/gitea-ci/README.md @@ -88,6 +88,43 @@ rolled-back v2 attempt is reused. Neither v2 nor v3 is the next install target. ## Build and install +Before installing the runner, enable Actions at the **instance** level. On +2026-09-29, bootstrap v4 started correctly but could not register: the current +Gitea configuration explicitly contained `[actions] ENABLED=false`. The public +Actions Ping RPC returned 404 even though the REST registration-token endpoint +worked. The v4 attempt ended with `ok:gitea-ci-bootstrap` rollback; do not reuse +`gitea-ci-bootstrap-v4-20260929-004`. Increasing its registration deadline would +not enable the missing server routes. + +The separate `gitea-actions-config` transition has exactly one data descriptor, +`deployment/actions-enable-v1.json`, built by `build_actions_artifact.py`. It +targets the existing `clean-gitea-20260820` container, using the verified +`/volume1/docker/gitea-clean-standalone-v1/compose.yaml` and `production.env` +context. The exact predecessor INI digest is registered in the root runner; +only the Actions boolean changes. Image, command, ports, bind mounts, +repositories, database and LFS remain in place. The existing Gitea container +restarts once, briefly interrupting Git web/SSH service. No Compose recreation, +image pull, new container, new listener or database rewrite occurs. + +Plan verifies the effective source hashes, running container/mount/network/image +identity, healthy Gitea 1.27.2 and inactive Actions RPC. Apply keeps a root-only +configuration rollback copy under `nodedc-deploy/runtime/gitea-actions/`; +the shared source archive, artifact, Git, logs and Ops never receive its secrets. +The INI replacement preserves its owner and mode. Acceptance proves healthy +Gitea, the Actions Ping response, unchanged runtime configuration and the +unchanged identities/uptimes of every other container. Failure restores the +exact predecessor and restarts the same container; unrelated drift is rejected. + +Install this transition first through runner promotion, fresh plan and apply. +Verify public Actions Ping after `deploy-ok`, then install a new CI bootstrap +patch on the unchanged v4 resource profile. CI preflight now requires the actual +public Actions Ping before runtime mutation. CI rollback records only fixed +startup-error categories/counts, never raw container logs or tokens. + +```sh +python3 infra/gitea-ci/build_actions_artifact.py --patch-id gitea-actions-enable-v1- --source-commit --output-dir +``` + From a clean Platform commit: ```sh diff --git a/infra/gitea-ci/actions-enable-v1.json b/infra/gitea-ci/actions-enable-v1.json new file mode 100644 index 0000000..9a8c334 --- /dev/null +++ b/infra/gitea-ci/actions-enable-v1.json @@ -0,0 +1,7 @@ +{ + "schemaVersion": "nodedc.gitea.actions-enable.v1", + "releaseId": "__PATCH_ID__", + "action": "enable-instance-actions", + "service": "gitea", + "productionDeployEnabled": false +} diff --git a/infra/gitea-ci/build_actions_artifact.py b/infra/gitea-ci/build_actions_artifact.py new file mode 100644 index 0000000..6efdf7b --- /dev/null +++ b/infra/gitea-ci/build_actions_artifact.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +"""Build the data-only, fixed Gitea Actions activation transition.""" +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 +ENTRY = "deployment/actions-enable-v1.json" + + +def bundle(patch_id): + if not re.fullmatch(r"gitea-actions-enable-v1-[a-zA-Z0-9._-]{1,65}", patch_id): + raise ValueError("invalid_actions_transition_identity") + descriptor = json.loads((SOURCE / "actions-enable-v1.json").read_text()) + descriptor["releaseId"] = patch_id + files = { + "manifest.env": ("id=" + patch_id + "\ncomponent=gitea-actions-config\ntype=app-overlay\n").encode(), + "files.txt": (ENTRY + "\n").encode(), + "payload/" + ENTRY: (json.dumps(descriptor, indent=2) + "\n").encode(), + } + output = io.BytesIO() + with gzip.GzipFile(fileobj=output, mode="wb", filename="", mtime=0) as compressed: + with tarfile.open(fileobj=compressed, mode="w", format=tarfile.USTAR_FORMAT) as archive: + for name, data in sorted(files.items()): + info = tarfile.TarInfo(name) + info.size, info.mode, info.mtime = len(data), 0o644, 0 + archive.addfile(info, io.BytesIO(data)) + return output.getvalue() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--patch-id", required=True) + parser.add_argument("--source-commit", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + args = parser.parse_args() + actual = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip() + if actual != args.source_commit or subprocess.check_output(["git", "status", "--porcelain"], cwd=ROOT, text=True).strip(): + raise SystemExit("clean_matching_commit_required") + data = bundle(args.patch_id) + args.output_dir.mkdir(parents=True, exist_ok=True) + path = args.output_dir / ("nodedc-" + args.patch_id + ".tgz") + with path.open("xb") as stream: + stream.write(data) + print(json.dumps({"artifact": str(path.resolve()), "patchId": args.patch_id, + "component": "gitea-actions-config", "sourceCommit": actual, + "sha256": hashlib.sha256(data).hexdigest(), "entries": [ENTRY], + "services": ["gitea"], "newPorts": [], "productionDeployEnabled": False})) + + +if __name__ == "__main__": + main() diff --git a/infra/gitea-ci/test_actions_enable.py b/infra/gitea-ci/test_actions_enable.py new file mode 100644 index 0000000..af117cd --- /dev/null +++ b/infra/gitea-ci/test_actions_enable.py @@ -0,0 +1,244 @@ +import copy +from contextlib import ExitStack, redirect_stdout +import hashlib +import io +import json +import os +from pathlib import Path +import stat +import subprocess +import tempfile +from types import SimpleNamespace +import unittest +from unittest import mock + +import build_actions_artifact +from test_bootstrap import RUNNER + + +class ActionsEnableTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() + self.config = self.root / "instance/config/app.ini" + self.config.parent.mkdir(parents=True) + self.original = b"APP_NAME = Gitea\n[security]\nSECRET_KEY = fixture-keep-private\n[actions]\nENABLED = false\n[server]\nHTTP_PORT = 3000\n" + self.target = self.original.replace(b"ENABLED = false", b"ENABLED = true") + self.config.write_bytes(self.original) + self.config.chmod(0o640) + self.backup = self.root / "backup" + self.backup.mkdir() + self.metadata = self.config.stat() + self.stack = ExitStack() + self.addCleanup(self.stack.close) + for name, value in {"GITEA_ACTIONS_CONFIG": self.config, + "GITEA_ACTIONS_ROOT": self.root / "meta", + "RUNTIME_DIR": self.root / "runtime", + "GITEA_ACTIONS_BEFORE": hashlib.sha256(self.original).hexdigest(), + "GITEA_ACTIONS_AFTER": hashlib.sha256(self.target).hexdigest()}.items(): + self.stack.enter_context(mock.patch.object(RUNNER, name, value)) + self.info = {"Id": "verified-id", "Name": "/clean-gitea-20260820", "Image": "sha256:fixture", + "Config": {"Image": RUNNER.GITEA_ACTIONS_IMAGE, + "Cmd": ["web", "--config", "/etc/gitea/app.ini"], + "Env": ["HOME=/var/lib/gitea/git"], + "Labels": {"com.docker.compose.project": "clean-gitea", "com.docker.compose.service": "gitea"}}, + "HostConfig": {"NetworkMode": "clean-gitea_clean_gitea", "PortBindings": {"3000/tcp": [{"HostIp": "172.22.0.222", "HostPort": "3000"}], "2222/tcp": [{"HostIp": "0.0.0.0", "HostPort": "4022"}]}}, + "State": {"Running": True, "Health": {"Status": "healthy"}}, + "Mounts": [{"Source": str(self.config), "Destination": "/etc/gitea/app.ini", "RW": False}, + {"Source": str(self.config.parent.parent / "data"), "Destination": "/var/lib/gitea", "RW": True}], + "NetworkSettings": {"Networks": {"clean-gitea_clean_gitea": {"IPAddress": "172.22.27.2"}}}} + self.before = {"config": self.original, "metadata": self.metadata, "containerId": self.info["Id"], + "fingerprint": RUNNER.gitea_actions_fingerprint(self.info), "inventory": {"other": {"running": True}}} + + def test_bundle_selects_one_service_and_only_data_descriptor(self): + patch = "gitea-actions-enable-v1-test-001" + artifact = self.root / "test.tgz" + artifact.write_bytes(build_actions_artifact.bundle(patch)) + self.assertEqual(artifact.read_bytes(), build_actions_artifact.bundle(patch)) + work = self.root / "work" + work.mkdir() + manifest, entries, payload = RUNNER.load_artifact(artifact, work) + self.assertEqual(manifest["component"], "gitea-actions-config") + self.assertEqual(entries, [RUNNER.GITEA_ACTIONS_ENTRY]) + self.assertEqual(RUNNER.component_services(manifest["component"], entries), ("gitea",)) + self.assertEqual(RUNNER.component_builds(manifest["component"], entries), ()) + path = payload / entries[0] + value = json.loads(path.read_text()) + value["service"] = "postgres" + path.write_text(json.dumps(value)) + with self.assertRaisesRegex(RUNNER.DeployError, "descriptor mismatch"): + RUNNER.validate_gitea_actions_payload(payload, entries, patch) + for rel in ("app.ini", "secrets/token", "data/gitea.db", "compose.yaml"): + with self.subTest(rel=rel), self.assertRaises(RUNNER.DeployError): + RUNNER.allowed_payload_path(manifest["component"], rel) + + def test_exact_boolean_change_and_unrelated_drift_rejection(self): + self.assertEqual(RUNNER.gitea_actions_transform(self.original), self.target) + with self.assertRaisesRegex(RUNNER.DeployError, "predecessor"): + RUNNER.gitea_actions_transform(self.original + b"# unrelated change\n") + with self.assertRaises(RUNNER.DeployError): + RUNNER.gitea_actions_transform(self.target) + + def test_atomic_update_preserves_permissions_and_rejects_concurrent_edit(self): + RUNNER.gitea_actions_replace(RUNNER.GITEA_ACTIONS_BEFORE, self.target, self.metadata) + self.assertEqual(self.config.read_bytes(), self.target) + self.assertEqual(stat.S_IMODE(self.config.stat().st_mode), 0o640) + self.assertEqual(self.config.stat().st_uid, self.metadata.st_uid) + with self.assertRaisesRegex(RUNNER.DeployError, "changed before"): + RUNNER.gitea_actions_replace(RUNNER.GITEA_ACTIONS_BEFORE, self.target, self.metadata) + + def test_runtime_rejects_wrong_identity_mounts_and_actions_env_override(self): + for field, value in (("Image", "other-image"), ("Cmd", ["other"]), ("Env", ["GITEA__actions__ENABLED=false"])): + info = copy.deepcopy(self.info) + info["Config"][field] = value + with mock.patch.object(RUNNER, "inspect_container", return_value=info): + with self.subTest(field=field), self.assertRaises(RUNNER.DeployError): + RUNNER.gitea_actions_container() + info = copy.deepcopy(self.info) + info["Mounts"][0]["RW"] = True + with mock.patch.object(RUNNER, "inspect_container", return_value=info): + with self.assertRaisesRegex(RUNNER.DeployError, "mounts"): + RUNNER.gitea_actions_container() + + def test_config_links_are_rejected(self): + sibling = self.config.with_name('other.ini') + os.link(self.config, sibling) + with self.assertRaisesRegex(RUNNER.DeployError, "metadata"): + RUNNER.gitea_actions_read_config() + self.config.unlink() + self.config.symlink_to(sibling) + with self.assertRaises(OSError): + RUNNER.gitea_actions_read_config() + + def test_preflight_binds_healthy_runtime_to_image_and_inactive_rpc(self): + sources = {"compose.yaml": "c21ef87833f87623f8352477d2b541d0a0f48769d8f9f79251d58033e90197ff", + "production.env": "9ebbf8638e035dddca25fd455b2ac4d4b6db306e1a6a4debd973b133fdeb5bb7"} + with mock.patch.object(RUNNER, "sha256_file", side_effect=lambda p:sources[p.name]), mock.patch.object(RUNNER, "inspect_container", return_value=self.info), mock.patch.object(RUNNER, "inspect_local_image", return_value=self.info["Image"]), mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}), (404,None)]), mock.patch.object(RUNNER, "gitea_ci_inventory", return_value={**self.before["inventory"],self.info["Id"]:{"running":True}}): + before = RUNNER.preflight_gitea_actions() + self.assertEqual(before["inventory"], self.before["inventory"]) + self.assertEqual(before["config"], self.original) + self.assertEqual(before["fingerprint"], self.before["fingerprint"]) + + def test_preservation_acceptance_rejects_changed_container_configuration(self): + info = copy.deepcopy(self.info) + info["HostConfig"]["Memory"] = 123 + with mock.patch.object(RUNNER, "gitea_actions_container", return_value=info), mock.patch.object(RUNNER.time, "monotonic", side_effect=[0,121]): + with self.assertRaisesRegex(RUNNER.DeployError, "runtime configuration drift"): + RUNNER.accept_gitea_actions(self.before) + + def test_rpc_preflight_rejects_rest_only_instance(self): + with mock.patch.object(RUNNER, "gitea_actions_http", return_value=(404, None)): + with self.assertRaisesRegex(RUNNER.DeployError, "HTTP 404"): + RUNNER.require_gitea_actions_ping() + with mock.patch.object(RUNNER, "gitea_actions_http", return_value=(200, {"data": "Hello, nodedc-ci-probe!"})): + RUNNER.require_gitea_actions_ping() + with mock.patch.object(RUNNER, "GITEA_CI_ROOT", self.root / "empty-ci"), mock.patch.object(RUNNER, "gitea_ci_host_capabilities"), mock.patch.object(RUNNER, "require_gitea_actions_ping", side_effect=RUNNER.DeployError("HTTP 404")), mock.patch.object(RUNNER, "gitea_ci_container_ids") as containers: + with self.assertRaisesRegex(RUNNER.DeployError, "HTTP 404"): + RUNNER.preflight_gitea_ci(RUNNER.GITEA_CI_V4_ENTRIES) + containers.assert_not_called() + + def test_apply_private_snapshot_and_failed_restart_can_restore_stopped_container(self): + with mock.patch.object(RUNNER.os, "chown"), mock.patch.object(RUNNER.os, "fchown"), mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER.subprocess, "run", side_effect=subprocess.CalledProcessError(1, ["docker", "restart"])): + with self.assertRaises(subprocess.CalledProcessError): + RUNNER.apply_gitea_actions(self.before, self.backup) + self.assertEqual(self.config.read_bytes(), self.target) + private = RUNNER.RUNTIME_DIR / "gitea-actions" / self.backup.name / "app.ini.before" + self.assertEqual(private.read_bytes(), self.original) + self.assertEqual(stat.S_IMODE(private.stat().st_mode), 0o600) + self.assertNotIn("fixture-keep-private", (self.backup / "gitea-actions-before.json").read_text()) + stopped = copy.deepcopy(self.info) + stopped["State"]["Running"] = False + stopped["NetworkSettings"]["Networks"]["clean-gitea_clean_gitea"]["IPAddress"] = "" + with mock.patch.object(RUNNER, "inspect_container", return_value=stopped), mock.patch.object(RUNNER.subprocess, "run") as restart, mock.patch.object(RUNNER, "accept_gitea_actions") as accept, mock.patch.object(RUNNER, "restore_overlay_source"): + RUNNER.rollback_gitea_actions(self.root, self.backup, [RUNNER.GITEA_ACTIONS_ENTRY], "stamp", self.before, True) + restart.assert_called_once() + accept.assert_called_once_with(self.before, enabled=False) + self.assertEqual(self.config.read_bytes(), self.original) + + def test_rollback_refuses_to_overwrite_unrelated_changes(self): + self.config.write_bytes(self.target + b"# concurrent change") + with mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER.subprocess, "run") as restart: + with self.assertRaisesRegex(RUNNER.DeployError, "unrelated config drift"): + RUNNER.rollback_gitea_actions(self.root, self.backup, [RUNNER.GITEA_ACTIONS_ENTRY], "stamp", self.before, True) + restart.assert_not_called() + + def test_acceptance_proves_rpc_version_runtime_and_other_containers(self): + self.config.write_bytes(self.target) + with mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}), (200,{"data":"Hello, nodedc-ci-probe!"})]), mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=self.before["inventory"]), redirect_stdout(io.StringIO()): + RUNNER.accept_gitea_actions(self.before) + + def test_startup_diagnostics_never_save_raw_tokens_or_logs(self): + result = SimpleNamespace(stdout="runner registration token fixture-SECRET 404 not found", stderr="Authorization: another-secret") + with mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=["ci-container"]), mock.patch.object(RUNNER.subprocess, "run", return_value=result), redirect_stdout(io.StringIO()) as output: + RUNNER.capture_gitea_ci_diagnostics(self.backup) + data = (self.backup / "ci-startup-diagnostics.json").read_text() + for secret in ("fixture-SECRET", "another-secret", "Authorization"): + self.assertNotIn(secret, data + output.getvalue()) + self.assertIn("actions-disabled-or-route", data) + + def full_apply(self, fail_acceptance=False): + host = self.root / "host" + host.mkdir() + paths = {name: host / name.lower() for name in ( + "INBOX", "APPLIED_DIR", "FAILED_DIR", "BACKUPS_DIR", "STATE_DIR", "TMP_DIR", "RUNTIME_DIR")} + for path in paths.values(): + path.mkdir() + paths.update({"STATE_FILE": paths["STATE_DIR"] / "applied.jsonl", + "FAILED_STATE_FILE": paths["STATE_DIR"] / "failed.jsonl", + "LOCK_DIR": paths["STATE_DIR"] / "deploy.lock", "DOCKER": Path("/usr/bin/true")}) + legacy = host / "legacy" + legacy.mkdir() + for name in ("compose.yaml", "production.env"): + (legacy / name).write_text("fixture") + root = host / "metadata" + registry = {**RUNNER.COMPONENTS["gitea-actions-config"], "payload_root": root, + "compose_root": legacy, "compose_files": (legacy / "compose.yaml",), + "compose_env_file": legacy / "production.env"} + artifact = paths["INBOX"] / "actions.tgz" + artifact.write_bytes(build_actions_artifact.bundle("gitea-actions-enable-v1-full-test")) + with ExitStack() as stack: + for name, value in paths.items(): + stack.enter_context(mock.patch.object(RUNNER, name, value)) + stack.enter_context(mock.patch.dict(RUNNER.COMPONENTS, {"gitea-actions-config": 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.os, "fchown")) + stack.enter_context(mock.patch.object(RUNNER, "preflight_gitea_actions", return_value=self.before)) + stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info)) + stack.enter_context(mock.patch.object(RUNNER.subprocess, "run")) + if fail_acceptance: + accept = stack.enter_context(mock.patch.object(RUNNER, "accept_gitea_actions", side_effect=[RUNNER.DeployError("synthetic RPC failure"), None])) + else: + stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}), (200,{"data":"Hello, nodedc-ci-probe!"})])) + stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=self.before["inventory"])) + with redirect_stdout(io.StringIO()): + if fail_acceptance: + with self.assertRaisesRegex(RUNNER.DeployError, "synthetic RPC"): + RUNNER.apply_artifact(artifact) + self.assertEqual(accept.call_count, 2) + else: + RUNNER.apply_artifact(artifact) + return paths, root + + def test_full_apply_receipt_only_after_success_and_no_secrets_in_source_backup(self): + paths, root = self.full_apply() + row = json.loads(paths["STATE_FILE"].read_text()) + self.assertEqual(row["status"], "ok") + self.assertEqual(self.config.read_bytes(), self.target) + self.assertTrue((root / RUNNER.GITEA_ACTIONS_ENTRY).is_file()) + for file in (paths["BACKUPS_DIR"] / row["backup_id"]).iterdir(): + if file.is_file(): + self.assertNotIn(b"fixture-keep-private", file.read_bytes()) + + def test_full_failed_acceptance_restores_flag_and_descriptor_and_records_rollback(self): + paths, root = self.full_apply(fail_acceptance=True) + row = json.loads(paths["FAILED_STATE_FILE"].read_text()) + self.assertEqual(row["rollback_status"], "ok:gitea-actions-config") + self.assertEqual(self.config.read_bytes(), self.original) + self.assertFalse((root / RUNNER.GITEA_ACTIONS_ENTRY).exists()) + self.assertFalse(paths["STATE_FILE"].exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/infra/gitea-ci/test_synology_v3.py b/infra/gitea-ci/test_synology_v3.py index 4b13d88..5d6864c 100644 --- a/infra/gitea-ci/test_synology_v3.py +++ b/infra/gitea-ci/test_synology_v3.py @@ -102,6 +102,7 @@ class SynologyV3Tests(unittest.TestCase): ("gitea-ci-bootstrap-v1-20260929-001", "ba942839c5815d09ac8f3c8dc23acdcf53ad9ef098a74c26b14c8b81afcf6a20"), ("gitea-ci-bootstrap-v2-20260929-002", "f9381e1ca59372f75277b6a6207ac9e35acaf29fd8ffa5dcf6afafa2daf80630"), ("gitea-ci-bootstrap-v3-20260929-003", "9df6c741e2432c0cac9fe2f2c7d90348a61d75b28098146018467050ef21ab9a"), + ("gitea-ci-bootstrap-v4-20260929-004", "866771bd94c82bee6d8143574fd7cc6292b0a516a2c4f082a4565bc13ccf2fb8"), ): self.assertEqual(hashlib.sha256(build_artifact.bundle(patch)).hexdigest(), sha)