Enable Actions on existing Gitea through an exact configuration transition

This commit is contained in:
Codex
2026-09-29 15:44:57 +03:00
parent 1650c4f221
commit 1adc0a66b3
6 changed files with 663 additions and 1 deletions
+37
View File
@@ -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/<backup-id>`;
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-<unique-id> --source-commit <full-sha> --output-dir <output-dir>
```
From a clean Platform commit:
```sh
+7
View File
@@ -0,0 +1,7 @@
{
"schemaVersion": "nodedc.gitea.actions-enable.v1",
"releaseId": "__PATCH_ID__",
"action": "enable-instance-actions",
"service": "gitea",
"productionDeployEnabled": false
}
+59
View File
@@ -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()
+244
View File
@@ -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()
+1
View File
@@ -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)