Add bounded external release runtime binding
This commit is contained in:
1 parent
0630a774cf
commit
b50cfa818d
16 files changed
+803
-52
No files matched your search
@@ -1,5 +1,29 @@
|
||||
# Infrastructure current state
|
||||
|
||||
## Proposed external deployment runtime binding — 2026-11-01
|
||||
|
||||
- PR #59 now proposes a root-only read-only status endpoint and exact-literal
|
||||
SSH dispatcher for `status` and `deploy`. The status path bounds the Gitea
|
||||
run list to ten entries, verifies the selected run/workflow/current `main`,
|
||||
validates artifact metadata and ZIP bytes, and returns only a release tuple.
|
||||
It fails closed for a stale host checkout, recovery journal, incomplete
|
||||
listing, or the exact release already recorded as applied. The deploy
|
||||
receiver still independently revalidates and uses the existing lock,
|
||||
recovery journal, cold-backup ACK, cutover, and rollback protections.
|
||||
- The Windows client proposes a disabled-by-default `--once` mode with a
|
||||
fixed `D:\Dev\akyldash` target and `akyldash_release` alias. The example
|
||||
config and Task Scheduler XML are both disabled; the template uses an
|
||||
interactive least-privilege owner, ignores overlapping invocations, and
|
||||
does not wake the computer. No Windows task, SSH key, VPS command, helper,
|
||||
or trigger config has been installed or exercised. Production CD remains
|
||||
inactive.
|
||||
- Remaining owner prerequisites are exact root forced-command/SSH host-key
|
||||
setup for the dispatcher, installation of the reviewed Windows client under
|
||||
a non-user-writable path, private ACLs for its config and D: backups, a
|
||||
root-controlled checkout matching current `main`, and all previously listed
|
||||
backup/restore and production readiness gates. The status endpoint does not
|
||||
advance the host checkout and refuses to offer a stale release.
|
||||
|
||||
Owner decision recorded 2026-10-26: a complete backup must not be stored on
|
||||
the VPS, including temporarily. The local archive/full cold-backup commands in
|
||||
`BACKUP.md` are superseded and unauthorized. PR #59 now contains a proposed
|
||||
@@ -225,11 +249,10 @@ Docker state, UFW rule details, and protected file metadata were not verified.
|
||||
reads artifact metadata through `gitea-api` only if that helper is available
|
||||
in the job image; otherwise it reports metadata and host handoff as
|
||||
unverified. It does not download artifact ZIPs, connect to SSH, or apply a
|
||||
release. No repository workflow binding to a Windows runtime starts the receiver;
|
||||
external Windows runner/service inventory has not been verified. The client
|
||||
currently requires an explicit process running `receive_external.py` with
|
||||
the release tuple to open the SSH session. Image release is automated, but
|
||||
production deployment is not yet automatic CD. The original
|
||||
release. No repository workflow binding to a Windows runtime starts the
|
||||
receiver. PR #59 now proposes a separate disabled local `--once` trigger
|
||||
that queries a root-verified tuple; it is not installed or active. Image
|
||||
release is automated, but production deployment is not yet automatic CD. The original
|
||||
audited `gitea-api` helper lacks binary output and safe 302 handling; the
|
||||
current PR carries a tested patch and host-side artifact verifier, but
|
||||
neither is installed. No deploy key, fixed SSH entry, extra sudo rule, or
|
||||
|
||||
@@ -35,7 +35,44 @@ the response, and refuses to overwrite an existing file. The installer checks
|
||||
the exact audited helper fixture hash before applying its patch. The helper
|
||||
and source code are not installed on the VPS by this PR.
|
||||
|
||||
## Automation boundary: deployment is not configured
|
||||
## One-shot runtime binding proposed by PR #59
|
||||
|
||||
PR #59 adds a root-only, read-only status command and a fixed SSH dispatcher.
|
||||
The dispatcher accepts only the literal status or deploy command in
|
||||
`SSH_ORIGINAL_COMMAND`; it accepts no arguments and performs no shell
|
||||
evaluation. Status fails closed on a stale root checkout, recovery journal,
|
||||
incomplete Gitea run listing, failed source/workflow checks, invalid artifact
|
||||
metadata/ZIP, or a release already applied. The candidate response contains
|
||||
only a run ID, commit, and descriptor digest. The root receiver independently
|
||||
repeats release verification and the existing backup/ACK/cutover guards.
|
||||
|
||||
The Windows client adds a one-shot `receive_external.py --once` mode. Its
|
||||
configuration is fixed to `D:\Dev\akyldash` and the `akyldash_release` SSH
|
||||
alias, and is disabled by default. It uses BatchMode, disables forwarding,
|
||||
uses the existing host-key checking, bounds status output and time, then calls
|
||||
the existing `run_release` path. Rollback remains a separate explicit
|
||||
owner-run command. The example Task Scheduler XML is disabled, runs as the
|
||||
interactive owner at least privilege, ignores overlapping instances, and
|
||||
never wakes the computer. No task has been registered or enabled by this PR.
|
||||
|
||||
Before any activation, the owner must install the reviewed receiver and its
|
||||
`archive.py` and `external_session.py` dependencies under a non-user-writable
|
||||
`C:\Program Files\Akyldash` directory, set the config ACL so
|
||||
only the owner, SYSTEM, and Administrators have full control, fill in the real
|
||||
Python executable, owner SID, and local start time in the task template, and
|
||||
confirm SSH host-key checking and the forced-command alias. Keep `enabled`
|
||||
false and the task
|
||||
disabled until the normal backup/restore and production readiness gates are
|
||||
recorded. Do not bind a Gitea workflow or PR runner to this Windows host.
|
||||
|
||||
The root-side status endpoint requires `/opt/akyldash/current` to exactly
|
||||
match current `main`; it does not update that checkout. An owner must advance
|
||||
the root-controlled checkout through the approved installation process before
|
||||
a release built from a newer commit can be considered ready. Gitea's filtered
|
||||
workflow-run listing is bounded to ten entries; if Gitea reports more entries
|
||||
or an inconsistent page, status returns unavailable rather than guessing.
|
||||
|
||||
## Automation boundary: deployment is not active
|
||||
|
||||
The automatic chain currently ends at release publication:
|
||||
|
||||
@@ -45,27 +82,19 @@ The automatic chain currently ends at release publication:
|
||||
Its job is explicitly status-only: **NOT DEPLOYED**. It does not download
|
||||
the descriptor ZIP, call the Windows client, open SSH, or invoke the root
|
||||
receiver. A green result means only that this status check completed.
|
||||
3. The fixed receiver is physically started only when a Windows process runs
|
||||
`infra/backup/receive_external.py` with the release run ID, commit, and
|
||||
descriptor digest. That command opens the owner's SSH session to the fixed
|
||||
root receiver. No repository workflow binding starts it; external Windows
|
||||
runner/service inventory has not been verified.
|
||||
3. The fixed receiver is physically started only by an explicitly enabled
|
||||
owner-controlled Windows trigger or by the manual release CLI. The proposed
|
||||
`--once` path queries root's verified status endpoint and receives the
|
||||
fixed tuple; no repository workflow invokes it. The example scheduler and
|
||||
config remain disabled, and no Windows trigger has been installed or
|
||||
exercised.
|
||||
|
||||
Therefore production CD is not yet automatic. A runner label only routes a
|
||||
job; it does not prevent a pull-request workflow from requesting that label.
|
||||
Before unattended cutover, the owner must choose an execution design that
|
||||
demonstrably prevents untrusted PR jobs from reaching the Windows host. A
|
||||
dedicated persistent host-mode runner with D: data and SSH access is unsafe
|
||||
while general repository PR workflows can target it. Acceptable designs
|
||||
include an isolated one-job executor exposed only after an external controller
|
||||
validates the trusted release event and exact run/commit/artifact tuple, or a
|
||||
separate protected deployment repository with no untrusted PR trigger/write
|
||||
path. In either design, the fixed receiver must report its ACK and SSH result
|
||||
before deployment is marked successful. Gitea 1.25 documents Windows runner
|
||||
installation and service operation in its
|
||||
[act_runner guide](https://docs.gitea.com/1.25/usage/actions/act_runner).
|
||||
No such isolation/controller, Windows runner, registration, token, service,
|
||||
SSH credential, or workflow binding has been verified or installed by this PR.
|
||||
Production CD is still not active: no Windows task or credential is installed,
|
||||
and no VPS or live D: operation has been performed. This design avoids a
|
||||
Windows Actions runner entirely; the owner-controlled local task is not exposed
|
||||
to PR jobs. The SSH account/key must be restricted to the exact dispatcher
|
||||
commands and verified host key. Do not use an unrestricted `authorized_keys`
|
||||
entry or a persistent host-mode runner with D: and SSH access.
|
||||
|
||||
## External backup and cutover
|
||||
|
||||
@@ -116,6 +145,14 @@ from a root-owned checkout and provision, without exposing values in logs:
|
||||
- a root-only SSH path to `/usr/local/sbin/akyldash-release-deploy` and
|
||||
`/usr/local/sbin/akyldash-release-rollback` using the existing owner key and
|
||||
verified host key.
|
||||
- a dedicated SSH alias `akyldash_release` backed by a key restricted to
|
||||
`/usr/local/sbin/akyldash-release-dispatch`; its forced command must preserve
|
||||
exact `SSH_ORIGINAL_COMMAND` matching and grant no shell, forwarding, PTY,
|
||||
or arbitrary command access;
|
||||
- a protected installation of the Windows client under
|
||||
`C:\Program Files\Akyldash`, with the sample JSON and Task Scheduler XML
|
||||
reviewed and kept disabled until the owner explicitly accepts unattended
|
||||
polling.
|
||||
|
||||
The installer intentionally does not create credentials, SSH entries, canary
|
||||
values, registry permissions, or a new privilege rule. Existing files with
|
||||
|
||||
@@ -6,18 +6,38 @@ private keys, secret material, or raw process environments.
|
||||
|
||||
## Required before release use
|
||||
|
||||
- PR #59 proposes a disabled one-shot Windows trigger. No task or endpoint is
|
||||
installed. If the owner chooses to activate it after merge and all other
|
||||
gates, install the reviewed `receive_external.py`, `archive.py`, and
|
||||
`external_session.py` client files in `C:\Program Files\Akyldash` with
|
||||
write access limited to administrators/SYSTEM, copy
|
||||
`infra/deploy/windows-release-trigger.example.json` to
|
||||
`C:\ProgramData\Akyldash\release-trigger.json` and retain
|
||||
`enabled:false`, then grant only the interactive owner, SYSTEM, and
|
||||
Administrators full control on the config and its parent. Fill in the real
|
||||
Python path, owner SID, and a future local start time in the XML template.
|
||||
Review/import the task while
|
||||
disabled; it runs as that logged-on owner at least privilege, ignores a
|
||||
concurrent instance, does not wake the PC, and invokes only `--once`. Enable
|
||||
the JSON and task only after the owner separately approves unattended
|
||||
polling. Disable either one to stop future polls; an already running cold
|
||||
backup/deploy must be allowed to finish or be explicitly recovered.
|
||||
- The `akyldash_release` SSH key must be dedicated to the root forced-command
|
||||
dispatcher, with OpenSSH `restrict` (or equivalent no-PTY/no-forwarding
|
||||
options), verified host-key checking, and exact status/deploy command
|
||||
matching. Do not put an unrestricted command or shell in root's
|
||||
`authorized_keys`. The existing rollback key/path remains a separate manual
|
||||
owner action. No key is generated, copied, or installed by this PR.
|
||||
- Decide whether unattended production CD is acceptable. It currently is not
|
||||
configured: `deploy-handoff.yaml` is metadata/status-only and reports
|
||||
`NOT DEPLOYED`; the Windows receiver starts only from an explicit owner-run
|
||||
CLI command. Automatic activation requires a secure Windows execution path
|
||||
available only to a validated trusted release. A `runs-on` label is routing,
|
||||
not authorization; a persistent host-mode runner sharing D: and SSH files
|
||||
must not be exposed to general repository PR workflows. Before enabling CD,
|
||||
choose an isolated one-job executor gated by an external validator, or a
|
||||
separately protected deployment repository with no untrusted PR trigger or
|
||||
write path. Verify that it validates repository, workflow, event, branch,
|
||||
run, commit, and artifact digest, then reports receiver ACK and SSH success.
|
||||
No such runtime isolation or binding exists in this PR.
|
||||
active: `deploy-handoff.yaml` remains status-only and reports `NOT DEPLOYED`;
|
||||
the proposed local task and its config remain disabled. This avoids exposing
|
||||
the Windows host to repository PR workflows. Verify that the root status
|
||||
command is installed from a reviewed checkout, its forced-command key is
|
||||
restricted, and the host checkout exactly matches current `main`. It does
|
||||
not update that checkout automatically. The endpoint fails closed if the
|
||||
filtered workflow-run API page is incomplete (more than ten candidates or
|
||||
count mismatch), so status API behavior must be checked on the live Gitea
|
||||
before activation.
|
||||
- Confirm the registry package names and least-privilege writer/pull access for
|
||||
`admin/akyldash/backend` and `admin/akyldash/opensearch`; record digest
|
||||
retention for the rollback window.
|
||||
|
||||
@@ -6,6 +6,7 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import stat
|
||||
@@ -20,6 +21,15 @@ from external_session import (ArchiveFrameWriter, read_challenge, read_response,
|
||||
MAX_ARCHIVE_BYTES, receive_archive, write_ack, write_request)
|
||||
|
||||
DEFAULT_REPOSITORY = Path(r"D:\Dev\akyldash")
|
||||
DEFAULT_DEPLOY_SSH_ALIAS = "akyldash_release"
|
||||
TRIGGER_CONFIG = Path(r"C:\ProgramData\Akyldash\release-trigger.json")
|
||||
RELEASE_STATUS_COMMAND = "/usr/local/sbin/akyldash-release-status"
|
||||
MAX_STATUS_BYTES = 1024
|
||||
STATUS_TIMEOUT_SECONDS = 180
|
||||
NOT_READY_REASONS = {
|
||||
"recovery_journal", "host_checkout_stale", "no_current_main_release", "main_advanced",
|
||||
"already_applied",
|
||||
}
|
||||
MAX_ERROR_BYTES = 8192
|
||||
_WINDOWS = os.name == "nt"
|
||||
|
||||
@@ -179,6 +189,117 @@ def _drain_stderr(stream, output: bytearray) -> None:
|
||||
output.extend(chunk[: MAX_ERROR_BYTES - len(output)])
|
||||
|
||||
|
||||
def _unique_json_object(pairs: list[tuple[str, object]]) -> dict:
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError("release status contains duplicate JSON fields")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def validate_status_response(payload: bytes) -> dict | None:
|
||||
if not payload or len(payload) > MAX_STATUS_BYTES:
|
||||
raise ValueError("release status response is empty or exceeds its size limit")
|
||||
try:
|
||||
value = json.loads(payload.decode("utf-8"), object_pairs_hook=_unique_json_object)
|
||||
except (UnicodeError, json.JSONDecodeError) as error:
|
||||
raise ValueError("release status response is invalid JSON") from error
|
||||
if (not isinstance(value, dict) or set(value) != {"schema_version", "state", "reason", "release"}
|
||||
or type(value["schema_version"]) is not int or value["schema_version"] != 1):
|
||||
raise ValueError("release status response has an unsupported schema")
|
||||
if value["state"] == "not_ready":
|
||||
if (not isinstance(value["reason"], str) or value["reason"] not in NOT_READY_REASONS
|
||||
or value["release"] is not None):
|
||||
raise ValueError("release status not-ready response is invalid")
|
||||
return None
|
||||
if value["state"] != "candidate" or value["reason"] is not None:
|
||||
raise ValueError("release status state is invalid")
|
||||
release = value["release"]
|
||||
if not isinstance(release, dict) or set(release) != {"run_id", "commit", "descriptor_sha256"}:
|
||||
raise ValueError("release status candidate tuple is invalid")
|
||||
if (not isinstance(release["run_id"], str) or not re.fullmatch(r"[0-9]{1,20}", release["run_id"])
|
||||
or not isinstance(release["commit"], str) or not re.fullmatch(r"[0-9a-f]{40}", release["commit"])
|
||||
or not isinstance(release["descriptor_sha256"], str)
|
||||
or not re.fullmatch(r"[0-9a-f]{64}", release["descriptor_sha256"])):
|
||||
raise ValueError("release status candidate identity is invalid")
|
||||
return {"version": 1, "action": "release", **release}
|
||||
|
||||
|
||||
def load_trigger_config(path: Path = TRIGGER_CONFIG) -> dict:
|
||||
if not _WINDOWS:
|
||||
raise ValueError("automatic release trigger is available only on Windows")
|
||||
if (_reparse(path) or _reparse(path.parent) or not path.is_file()
|
||||
or not path.parent.is_dir()):
|
||||
raise ValueError("release trigger configuration is missing or unsafe")
|
||||
check_private_acl(path.parent)
|
||||
check_private_acl(path)
|
||||
try:
|
||||
with path.open("rb") as stream:
|
||||
raw = stream.read(4097)
|
||||
except OSError as error:
|
||||
raise ValueError("release trigger configuration is unreadable") from error
|
||||
if not raw or len(raw) > 4096:
|
||||
raise ValueError("release trigger configuration is empty or oversized")
|
||||
try:
|
||||
value = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_json_object)
|
||||
except (UnicodeError, json.JSONDecodeError) as error:
|
||||
raise ValueError("release trigger configuration is invalid JSON") from error
|
||||
if (not isinstance(value, dict)
|
||||
or set(value) != {"schema_version", "enabled", "repository", "ssh_alias"}
|
||||
or type(value["schema_version"]) is not int or value["schema_version"] != 1
|
||||
or type(value["enabled"]) is not bool
|
||||
or value["repository"] != str(DEFAULT_REPOSITORY)
|
||||
or value["ssh_alias"] != DEFAULT_DEPLOY_SSH_ALIAS):
|
||||
raise ValueError("release trigger configuration does not match the fixed deployment target")
|
||||
return value
|
||||
|
||||
|
||||
def query_release_status(*, ssh: str = "ssh", ssh_alias: str = DEFAULT_DEPLOY_SSH_ALIAS) -> dict | None:
|
||||
if shutil.which(ssh) is None:
|
||||
raise ValueError("OpenSSH client is unavailable")
|
||||
if ssh_alias != DEFAULT_DEPLOY_SSH_ALIAS:
|
||||
raise ValueError("automatic release status uses only the fixed deployment SSH alias")
|
||||
command = [
|
||||
ssh, "-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15",
|
||||
"-o", "ClearAllForwardings=yes", "-o", "ForwardAgent=no", "-o", "ForwardX11=no",
|
||||
ssh_alias, RELEASE_STATUS_COMMAND,
|
||||
]
|
||||
process = subprocess.Popen(
|
||||
command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
)
|
||||
output = bytearray()
|
||||
overflow = threading.Event()
|
||||
|
||||
def read_status() -> None:
|
||||
while True:
|
||||
chunk = process.stdout.read(min(4096, MAX_STATUS_BYTES + 1 - len(output)))
|
||||
if not chunk:
|
||||
return
|
||||
if len(output) + len(chunk) > MAX_STATUS_BYTES:
|
||||
overflow.set()
|
||||
process.kill()
|
||||
return
|
||||
output.extend(chunk)
|
||||
|
||||
stdout_thread = threading.Thread(target=read_status, daemon=True)
|
||||
stderr_thread = threading.Thread(target=_drain_stderr, args=(process.stderr, bytearray()), daemon=True)
|
||||
stdout_thread.start()
|
||||
stderr_thread.start()
|
||||
try:
|
||||
return_code = process.wait(timeout=STATUS_TIMEOUT_SECONDS)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
process.kill()
|
||||
process.wait()
|
||||
raise ValueError("release status request timed out") from error
|
||||
finally:
|
||||
stdout_thread.join()
|
||||
stderr_thread.join()
|
||||
if overflow.is_set() or return_code:
|
||||
raise ValueError("release status command failed or exceeded its response limit")
|
||||
return validate_status_response(bytes(output))
|
||||
|
||||
|
||||
def receive_backup(reader, writer, *, repository: Path, request: dict, expected_context: dict | None = None) -> dict:
|
||||
frame, value = read_response(reader)
|
||||
if frame == "result":
|
||||
@@ -256,7 +377,9 @@ def run_release(request: dict, *, repository: Path = DEFAULT_REPOSITORY, ssh: st
|
||||
raise ValueError("SSH alias must name an existing owner-controlled host entry")
|
||||
check_repository_target(repository, "preflight-" + secrets.token_hex(16))
|
||||
process = subprocess.Popen(
|
||||
[ssh, "-T", ssh_alias, "/usr/local/sbin/akyldash-release-deploy"],
|
||||
[ssh, "-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=15",
|
||||
"-o", "ClearAllForwardings=yes", "-o", "ForwardAgent=no", "-o", "ForwardX11=no",
|
||||
ssh_alias, "/usr/local/sbin/akyldash-release-deploy"],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
)
|
||||
errors = bytearray()
|
||||
@@ -284,6 +407,18 @@ def run_release(request: dict, *, repository: Path = DEFAULT_REPOSITORY, ssh: st
|
||||
raise
|
||||
|
||||
|
||||
def run_release_once(*, config_file: Path = TRIGGER_CONFIG, ssh: str = "ssh") -> None:
|
||||
config = load_trigger_config(config_file)
|
||||
if not config["enabled"]:
|
||||
print("Release trigger is disabled; no SSH connection opened.")
|
||||
return
|
||||
request = query_release_status(ssh=ssh, ssh_alias=config["ssh_alias"])
|
||||
if request is None:
|
||||
print("No verified current-main release is ready; deployment not started.")
|
||||
return
|
||||
run_release(request, repository=Path(config["repository"]), ssh=ssh, ssh_alias=config["ssh_alias"])
|
||||
|
||||
|
||||
def run_rollback(*, repository: Path = DEFAULT_REPOSITORY, ssh: str = "ssh",
|
||||
ssh_alias: str = "akyldash_vps") -> None:
|
||||
if shutil.which(ssh) is None:
|
||||
@@ -335,6 +470,7 @@ def run_rollback(*, repository: Path = DEFAULT_REPOSITORY, ssh: str = "ssh",
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--once", action="store_true", help="query the fixed status endpoint and deploy at most one verified release")
|
||||
parser.add_argument("--rollback", action="store_true")
|
||||
parser.add_argument("--data-compatible", action="store_true")
|
||||
parser.add_argument("--run-id")
|
||||
@@ -343,7 +479,13 @@ def main() -> int:
|
||||
parser.add_argument("--ssh-alias", default="akyldash_vps")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.rollback:
|
||||
if args.once:
|
||||
if (args.rollback or args.data_compatible or any(
|
||||
(args.run_id, args.commit, args.descriptor_sha256))
|
||||
or args.ssh_alias != "akyldash_vps"):
|
||||
raise ValueError("--once accepts no release tuple, rollback, compatibility flag, or custom SSH alias")
|
||||
run_release_once()
|
||||
elif args.rollback:
|
||||
if not args.data_compatible or any((args.run_id, args.commit, args.descriptor_sha256)):
|
||||
raise ValueError("rollback requires --data-compatible and accepts no release tuple")
|
||||
run_rollback(ssh_alias=args.ssh_alias)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import xml.etree.ElementTree as ET
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -225,6 +227,83 @@ class ExternalReceiverTests(unittest.TestCase):
|
||||
self.assertTrue(all(call.args[1].startswith("preflight-") for call in preflight.call_args_list))
|
||||
popen.assert_not_called()
|
||||
|
||||
def test_status_response_accepts_only_the_fixed_candidate_tuple(self):
|
||||
response = {"schema_version": 1, "state": "candidate", "reason": None,
|
||||
"release": {"run_id": "302", "commit": "a" * 40,
|
||||
"descriptor_sha256": "b" * 64}}
|
||||
self.assertEqual(receive_external.validate_status_response(json.dumps(response).encode()),
|
||||
{"version": 1, "action": "release", **response["release"]})
|
||||
response["reason"] = []
|
||||
with self.assertRaises(ValueError):
|
||||
receive_external.validate_status_response(json.dumps(response).encode())
|
||||
self.assertIsNone(receive_external.validate_status_response(
|
||||
b'{"schema_version":1,"state":"not_ready","reason":"already_applied","release":null}'
|
||||
))
|
||||
|
||||
def test_status_response_rejects_extra_or_duplicate_fields(self):
|
||||
payload = (b'{"schema_version":1,"state":"not_ready","reason":"recovery_journal",'
|
||||
b'"release":null,"extra":0}')
|
||||
with self.assertRaisesRegex(ValueError, "schema"):
|
||||
receive_external.validate_status_response(payload)
|
||||
with self.assertRaisesRegex(ValueError, "duplicate"):
|
||||
receive_external.validate_status_response(
|
||||
b'{"schema_version":1,"state":"not_ready","reason":"recovery_journal",'
|
||||
b'"release":null,"release":null}')
|
||||
|
||||
def test_status_query_uses_only_fixed_command_and_non_forwarding_ssh(self):
|
||||
payload = (b'{"schema_version":1,"state":"not_ready",'
|
||||
b'"reason":"no_current_main_release","release":null}\n')
|
||||
process = type("Process", (), {
|
||||
"stdout": io.BytesIO(payload), "stderr": io.BytesIO(),
|
||||
"wait": lambda self, timeout: 0,
|
||||
})()
|
||||
with patch.object(receive_external.shutil, "which", return_value="ssh"), \
|
||||
patch.object(receive_external.subprocess, "Popen", return_value=process) as popen:
|
||||
self.assertIsNone(receive_external.query_release_status())
|
||||
command = popen.call_args.args[0]
|
||||
self.assertEqual(command[-2:], ["akyldash_release", receive_external.RELEASE_STATUS_COMMAND])
|
||||
self.assertIn("ForwardAgent=no", command)
|
||||
self.assertIn("ClearAllForwardings=yes", command)
|
||||
self.assertEqual(popen.call_args.kwargs["stdin"], subprocess.DEVNULL)
|
||||
|
||||
def test_once_disabled_is_noop_and_candidate_reuses_existing_release_flow(self):
|
||||
config = {"schema_version": 1, "enabled": False,
|
||||
"repository": str(receive_external.DEFAULT_REPOSITORY),
|
||||
"ssh_alias": receive_external.DEFAULT_DEPLOY_SSH_ALIAS}
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "trigger.json"
|
||||
path.write_text(json.dumps(config), encoding="utf-8")
|
||||
with patch.object(receive_external, "_WINDOWS", True), \
|
||||
patch.object(receive_external, "check_private_acl"), \
|
||||
patch.object(receive_external, "query_release_status") as query, \
|
||||
patch.object(receive_external, "run_release") as deploy:
|
||||
receive_external.run_release_once(config_file=path)
|
||||
query.assert_not_called()
|
||||
deploy.assert_not_called()
|
||||
|
||||
config["enabled"] = True
|
||||
path.write_text(json.dumps(config), encoding="utf-8")
|
||||
candidate = {"version": 1, "action": "release", "run_id": "302",
|
||||
"commit": "a" * 40, "descriptor_sha256": "b" * 64}
|
||||
query.return_value = candidate
|
||||
receive_external.run_release_once(config_file=path)
|
||||
deploy.assert_called_once_with(
|
||||
candidate, repository=receive_external.DEFAULT_REPOSITORY,
|
||||
ssh="ssh", ssh_alias="akyldash_release")
|
||||
|
||||
def test_windows_trigger_templates_are_fixed_and_disabled(self):
|
||||
root = Path(__file__).resolve().parents[1] / "deploy"
|
||||
config = json.loads((root / "windows-release-trigger.example.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(config, {
|
||||
"schema_version": 1, "enabled": False,
|
||||
"repository": r"D:\Dev\akyldash", "ssh_alias": "akyldash_release",
|
||||
})
|
||||
task = ET.parse(root / "windows-release-trigger.example.xml").getroot()
|
||||
ns = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
|
||||
self.assertEqual(task.findtext("t:Settings/t:Enabled", namespaces=ns), "false")
|
||||
self.assertEqual(task.findtext("t:Settings/t:MultipleInstancesPolicy", namespaces=ns), "IgnoreNew")
|
||||
self.assertEqual(task.findtext("t:Principals/t:Principal/t:RunLevel", namespaces=ns), "LeastPrivilege")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if [[ $EUID -ne 0 || $# -ne 0 ]]; then
|
||||
if [[ $EUID -ne 0 || $# -gt 1 || ( $# -eq 1 && $1 != status ) ]]; then
|
||||
echo "This fixed receiver is owner-run as root and accepts its request only on stdin." >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -45,4 +45,7 @@ fi
|
||||
export GITEA_URL=https://git.vakanaut.ru
|
||||
export GITEA_TOKEN GITEA_DOWNLOAD_ORIGINS
|
||||
export PATH=/usr/local/lib/akyldash:/usr/bin:/bin
|
||||
if [[ $# -eq 1 ]]; then
|
||||
exec /usr/bin/python3 /usr/local/lib/akyldash/external_status.py
|
||||
fi
|
||||
exec /usr/bin/python3 /usr/local/lib/akyldash/external_deploy.py
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if [[ $EUID -ne 0 || $# -ne 0 ]]; then
|
||||
echo "The restricted release dispatcher accepts only its exact SSH command." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "${SSH_ORIGINAL_COMMAND:-}" in
|
||||
/usr/local/sbin/akyldash-release-status)
|
||||
exec /usr/local/sbin/akyldash-release-deploy status
|
||||
;;
|
||||
/usr/local/sbin/akyldash-release-deploy)
|
||||
exec /usr/local/sbin/akyldash-release-deploy
|
||||
;;
|
||||
*)
|
||||
echo "The restricted release dispatcher accepts only status or deploy." >&2
|
||||
exit 126
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only selector for one fully verified current-main release candidate."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from deploy_release import JOURNAL_FILE, ROOT, STATE_FILE
|
||||
from release_handoff import latest_main_sha
|
||||
from release_source import fetch_release, latest_release_request
|
||||
from release_state import read_json, validate_state
|
||||
|
||||
POLICY_FILE = Path("/etc/akyldash/release-policy.json")
|
||||
STATUS_MAX_BYTES = 1024
|
||||
SHA_RE = re.compile(r"[0-9a-f]{40}\Z")
|
||||
|
||||
|
||||
def checkout_sha(checkout: Path) -> str:
|
||||
result = subprocess.run(
|
||||
["git", "-C", str(checkout), "rev-parse", "HEAD"],
|
||||
check=True, text=True, capture_output=True, timeout=10,
|
||||
)
|
||||
value = result.stdout.strip()
|
||||
if not SHA_RE.fullmatch(value):
|
||||
raise ValueError("production checkout revision is invalid")
|
||||
return value
|
||||
|
||||
|
||||
def status_document(*, api=None, checkout: Path = ROOT, journal: Path = JOURNAL_FILE,
|
||||
policy_file: Path = POLICY_FILE, state_file: Path = STATE_FILE,
|
||||
main_lookup=latest_main_sha,
|
||||
checkout_lookup=checkout_sha) -> dict:
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("release status command must run as root")
|
||||
if journal.exists() or journal.is_symlink():
|
||||
return {"schema_version": 1, "state": "not_ready", "reason": "recovery_journal", "release": None}
|
||||
|
||||
current_main = main_lookup(checkout)
|
||||
if checkout_lookup(checkout) != current_main:
|
||||
return {"schema_version": 1, "state": "not_ready", "reason": "host_checkout_stale", "release": None}
|
||||
|
||||
api_args = {"api": api} if api is not None else {}
|
||||
request = latest_release_request(current_main=current_main, checkout=checkout, **api_args)
|
||||
if request is None:
|
||||
return {"schema_version": 1, "state": "not_ready", "reason": "no_current_main_release", "release": None}
|
||||
if state_file.exists() or state_file.is_symlink():
|
||||
state = validate_state(read_json(state_file))
|
||||
if (state["commit"] == request["commit"]
|
||||
and state["manifest_sha256"] == request["descriptor_sha256"]):
|
||||
return {"schema_version": 1, "state": "not_ready", "reason": "already_applied", "release": None}
|
||||
manifest, _raw = fetch_release(
|
||||
request, policy=read_json(policy_file), current_main=current_main, checkout=checkout,
|
||||
**api_args,
|
||||
)
|
||||
if manifest["commit"] != current_main or manifest["run_id"] != request["run_id"]:
|
||||
raise ValueError("verified release descriptor does not match the selected source")
|
||||
if main_lookup(checkout) != current_main:
|
||||
return {"schema_version": 1, "state": "not_ready", "reason": "main_advanced", "release": None}
|
||||
if journal.exists() or journal.is_symlink():
|
||||
return {"schema_version": 1, "state": "not_ready", "reason": "recovery_journal", "release": None}
|
||||
if state_file.exists() or state_file.is_symlink():
|
||||
state = validate_state(read_json(state_file))
|
||||
if (state["commit"] == request["commit"]
|
||||
and state["manifest_sha256"] == request["descriptor_sha256"]):
|
||||
return {"schema_version": 1, "state": "not_ready", "reason": "already_applied", "release": None}
|
||||
return {
|
||||
"schema_version": 1,
|
||||
"state": "candidate",
|
||||
"reason": None,
|
||||
"release": {key: request[key] for key in ("run_id", "commit", "descriptor_sha256")},
|
||||
}
|
||||
|
||||
|
||||
def write_status(value: dict, stream=None) -> None:
|
||||
payload = json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + b"\n"
|
||||
if len(payload) > STATUS_MAX_BYTES:
|
||||
raise ValueError("release status response exceeds its size limit")
|
||||
(stream or sys.stdout.buffer).write(payload)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
try:
|
||||
write_status(status_document())
|
||||
except Exception as error:
|
||||
print(f"release status unavailable ({type(error).__name__})", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -16,11 +16,13 @@ verify_source=$checkout/infra/bootstrap/verify-helper.sh
|
||||
compose_source=$checkout/infra/deploy/compose-helper.sh
|
||||
release_deploy_source=$checkout/infra/deploy/akyldash-release-deploy.sh
|
||||
release_rollback_source=$checkout/infra/deploy/akyldash-release-rollback.sh
|
||||
release_dispatch_source=$checkout/infra/deploy/akyldash-release-dispatch.sh
|
||||
release_controller_source=$checkout/infra/deploy/external_deploy.py
|
||||
release_status_source=$checkout/infra/deploy/external_status.py
|
||||
gitea_helper_fixture=$checkout/infra/deploy/gitea-api-base.fixture
|
||||
gitea_helper_patch=$checkout/infra/deploy/gitea-api-binary-download.patch
|
||||
release_policy_source=$checkout/infra/deploy/release-policy.json
|
||||
if [[ ! -d $checkout/.git || ! -f $rollback_source || ! -f $release_refs_source || ! -f $release_state_source || ! -f $deployment_lock_source || ! -f $backup_source || ! -f $verify_source || ! -f $compose_source || ! -f $release_deploy_source || ! -f $release_rollback_source || ! -f $release_controller_source || ! -f "$checkout/infra/deploy/external_rollback.py" || ! -f "$checkout/infra/backup/external_session.py" || ! -f "$checkout/infra/deploy/create_release_manifest.py" || ! -f "$checkout/infra/deploy/deploy_release.py" || ! -f "$checkout/infra/deploy/release_handoff.py" || ! -f "$checkout/infra/deploy/release_source.py" || ! -f "$checkout/infra/deploy/validate_release.py" || ! -f $gitea_helper_fixture || ! -f $gitea_helper_patch || ! -f $release_policy_source ]]; then
|
||||
if [[ ! -d $checkout/.git || ! -f $rollback_source || ! -f $release_refs_source || ! -f $release_state_source || ! -f $deployment_lock_source || ! -f $backup_source || ! -f $verify_source || ! -f $compose_source || ! -f $release_deploy_source || ! -f $release_rollback_source || ! -f $release_dispatch_source || ! -f $release_controller_source || ! -f $release_status_source || ! -f "$checkout/infra/deploy/external_rollback.py" || ! -f "$checkout/infra/backup/external_session.py" || ! -f "$checkout/infra/deploy/create_release_manifest.py" || ! -f "$checkout/infra/deploy/deploy_release.py" || ! -f "$checkout/infra/deploy/release_handoff.py" || ! -f "$checkout/infra/deploy/release_source.py" || ! -f "$checkout/infra/deploy/validate_release.py" || ! -f $gitea_helper_fixture || ! -f $gitea_helper_patch || ! -f $release_policy_source ]]; then
|
||||
echo "Install the approved repository checkout at $checkout first." >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -56,8 +58,9 @@ if ! command -v patch >/dev/null 2>&1 || ! command -v sha256sum >/dev/null 2>&1;
|
||||
echo "patch and sha256sum are required to install the reviewed binary-safe Gitea helper." >&2
|
||||
exit 1
|
||||
fi
|
||||
bash -n "$release_deploy_source" "$release_rollback_source" "$release_dispatch_source"
|
||||
|
||||
for path in /usr/local/sbin/akyldash-verify /usr/local/sbin/akyldash-rollback /usr/local/sbin/akyldash-compose /usr/local/sbin/akyldash-release-deploy /usr/local/sbin/akyldash-release-rollback /usr/local/lib/akyldash/archive.py /usr/local/lib/akyldash/external_session.py /usr/local/lib/akyldash/create_release_manifest.py /usr/local/lib/akyldash/deploy_release.py /usr/local/lib/akyldash/deployment_lock.py /usr/local/lib/akyldash/external_deploy.py /usr/local/lib/akyldash/external_rollback.py /usr/local/lib/akyldash/rollback.py /usr/local/lib/akyldash/release_handoff.py /usr/local/lib/akyldash/release_refs.py /usr/local/lib/akyldash/release_source.py /usr/local/lib/akyldash/release_state.py /usr/local/lib/akyldash/validate_release.py /usr/local/lib/akyldash/gitea-api /etc/akyldash/release-policy.json /etc/sudoers.d/akyldash-codex; do
|
||||
for path in /usr/local/sbin/akyldash-verify /usr/local/sbin/akyldash-rollback /usr/local/sbin/akyldash-compose /usr/local/sbin/akyldash-release-deploy /usr/local/sbin/akyldash-release-rollback /usr/local/sbin/akyldash-release-dispatch /usr/local/lib/akyldash/archive.py /usr/local/lib/akyldash/external_session.py /usr/local/lib/akyldash/create_release_manifest.py /usr/local/lib/akyldash/deploy_release.py /usr/local/lib/akyldash/deployment_lock.py /usr/local/lib/akyldash/external_deploy.py /usr/local/lib/akyldash/external_status.py /usr/local/lib/akyldash/external_rollback.py /usr/local/lib/akyldash/rollback.py /usr/local/lib/akyldash/release_handoff.py /usr/local/lib/akyldash/release_refs.py /usr/local/lib/akyldash/release_source.py /usr/local/lib/akyldash/release_state.py /usr/local/lib/akyldash/validate_release.py /usr/local/lib/akyldash/gitea-api /etc/akyldash/release-policy.json /etc/sudoers.d/akyldash-codex; do
|
||||
if [[ -L $path ]]; then
|
||||
echo "Refusing symlink at $path." >&2
|
||||
exit 1
|
||||
@@ -74,6 +77,7 @@ install -o root -g root -m 0644 "$checkout/infra/deploy/create_release_manifest.
|
||||
install -o root -g root -m 0644 "$checkout/infra/deploy/deploy_release.py" /usr/local/lib/akyldash/deploy_release.py
|
||||
install -o root -g root -m 0644 "$rollback_source" /usr/local/lib/akyldash/rollback.py
|
||||
install -o root -g root -m 0644 "$checkout/infra/deploy/external_deploy.py" /usr/local/lib/akyldash/external_deploy.py
|
||||
install -o root -g root -m 0644 "$release_status_source" /usr/local/lib/akyldash/external_status.py
|
||||
install -o root -g root -m 0644 "$checkout/infra/deploy/external_rollback.py" /usr/local/lib/akyldash/external_rollback.py
|
||||
install -o root -g root -m 0644 "$checkout/infra/deploy/release_handoff.py" /usr/local/lib/akyldash/release_handoff.py
|
||||
install -o root -g root -m 0644 "$checkout/infra/deploy/release_source.py" /usr/local/lib/akyldash/release_source.py
|
||||
@@ -102,6 +106,7 @@ install -o root -g root -m 0750 "$rollback_source" /usr/local/sbin/akyldash-roll
|
||||
install -o root -g root -m 0750 "$compose_source" /usr/local/sbin/akyldash-compose
|
||||
install -o root -g root -m 0750 "$release_deploy_source" /usr/local/sbin/akyldash-release-deploy
|
||||
install -o root -g root -m 0750 "$release_rollback_source" /usr/local/sbin/akyldash-release-rollback
|
||||
install -o root -g root -m 0750 "$release_dispatch_source" /usr/local/sbin/akyldash-release-dispatch
|
||||
|
||||
sudoers_file=/etc/sudoers.d/akyldash-codex
|
||||
expected=$'codex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-verify\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-rollback *\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-compose config\ncodex ALL=(root) NOPASSWD: /usr/local/sbin/akyldash-compose status'
|
||||
|
||||
@@ -21,7 +21,10 @@ def latest_main_sha(checkout: Path | None = None) -> str:
|
||||
check=True,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
)
|
||||
if len(result.stdout) > 256:
|
||||
raise ValueError("current main lookup exceeded its output limit")
|
||||
fields = result.stdout.split()
|
||||
if len(fields) != 2 or fields[1] != "refs/heads/main" or not SHA_RE.fullmatch(fields[0]):
|
||||
raise ValueError("could not determine the current main commit")
|
||||
|
||||
@@ -6,10 +6,14 @@ import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import resource
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path, PurePosixPath
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from release_handoff import descriptor_request, latest_main_sha, validate_source
|
||||
from validate_release import read_json, unique_object, validate_manifest
|
||||
@@ -18,18 +22,106 @@ REPOSITORY = "admin/akyldash"
|
||||
RELEASE_WORKFLOW = ".gitea/workflows/release-images.yaml"
|
||||
CI_WORKFLOW = ".gitea/workflows/ci.yaml"
|
||||
MAX_DESCRIPTOR_BYTES = 1024 * 1024
|
||||
MAX_API_RESPONSE_BYTES = 1024 * 1024
|
||||
MAX_API_DOWNLOAD_BYTES = 10 * 1024 * 1024
|
||||
MAX_CANDIDATE_RELEASE_RUNS = 10
|
||||
API_TIMEOUT_SECONDS = 15
|
||||
|
||||
|
||||
def run_api_helper(command: list[str], *, env: dict | None, timeout: int,
|
||||
max_stdout_bytes: int, max_file_bytes: int) -> bytes:
|
||||
def limit_files() -> None:
|
||||
_soft, hard = resource.getrlimit(resource.RLIMIT_FSIZE)
|
||||
limit = max_file_bytes + 1 if hard == resource.RLIM_INFINITY else min(max_file_bytes + 1, hard)
|
||||
resource.setrlimit(resource.RLIMIT_FSIZE, (limit, hard))
|
||||
|
||||
with tempfile.TemporaryFile() as output:
|
||||
process = subprocess.Popen(
|
||||
command, stdout=output, stderr=subprocess.DEVNULL, env=env,
|
||||
start_new_session=True, preexec_fn=limit_files,
|
||||
)
|
||||
try:
|
||||
return_code = process.wait(timeout=timeout)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
try:
|
||||
process.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
process.wait()
|
||||
raise ValueError("Gitea helper request timed out") from error
|
||||
if return_code:
|
||||
raise ValueError("Gitea helper request failed")
|
||||
output.seek(0, os.SEEK_END)
|
||||
if output.tell() > max_stdout_bytes:
|
||||
raise ValueError("Gitea helper response exceeds its size limit")
|
||||
output.seek(0)
|
||||
return output.read(max_stdout_bytes + 1)
|
||||
|
||||
|
||||
def api_json(path: str, *, helper: str = "gitea-api", env: dict | None = None) -> dict:
|
||||
result = subprocess.run(
|
||||
[helper, "GET", path], check=True, text=True, capture_output=True, env=env
|
||||
)
|
||||
value = json.loads(result.stdout, object_pairs_hook=unique_object)
|
||||
try:
|
||||
response = run_api_helper(
|
||||
[helper, "GET", path], env=env, timeout=API_TIMEOUT_SECONDS,
|
||||
max_stdout_bytes=MAX_API_RESPONSE_BYTES, max_file_bytes=MAX_API_RESPONSE_BYTES,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise ValueError("Gitea API request failed") from error
|
||||
if len(response) > MAX_API_RESPONSE_BYTES:
|
||||
raise ValueError("Gitea helper response exceeds its size limit")
|
||||
try:
|
||||
value = json.loads(response.decode("utf-8"), object_pairs_hook=unique_object)
|
||||
except (UnicodeError, json.JSONDecodeError) as error:
|
||||
raise ValueError("Gitea API response is invalid JSON") from error
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("Gitea API returned a non-object response")
|
||||
return value
|
||||
|
||||
|
||||
def latest_release_request(*, current_main: str, api=api_json,
|
||||
checkout: Path | None = None) -> dict | None:
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", current_main):
|
||||
raise ValueError("current main commit is invalid")
|
||||
query = urlencode({
|
||||
"event": "workflow_run", "branch": "main", "status": "success",
|
||||
"head_sha": current_main, "page": 1, "limit": MAX_CANDIDATE_RELEASE_RUNS,
|
||||
})
|
||||
runs_response = api(
|
||||
f"/repos/{REPOSITORY}/actions/workflows/{Path(RELEASE_WORKFLOW).name}/runs?{query}"
|
||||
)
|
||||
runs = runs_response.get("workflow_runs")
|
||||
total = runs_response.get("total_count")
|
||||
if type(total) is not int or total < 0 or not isinstance(runs, list):
|
||||
raise ValueError("Gitea release-run listing is invalid")
|
||||
if total > MAX_CANDIDATE_RELEASE_RUNS or len(runs) != total:
|
||||
raise ValueError("Gitea release-run listing is incomplete")
|
||||
if not runs:
|
||||
return None
|
||||
run_ids = []
|
||||
for run in runs:
|
||||
if not isinstance(run, dict):
|
||||
raise ValueError("Gitea release-run listing contains an invalid entry")
|
||||
run_id = run.get("id")
|
||||
if (isinstance(run_id, bool) or not isinstance(run_id, (int, str))
|
||||
or not str(run_id).isdigit() or len(str(run_id)) > 20):
|
||||
raise ValueError("Gitea release-run listing contains an invalid run ID")
|
||||
head_sha = run.get("head_sha")
|
||||
if head_sha is not None and head_sha != current_main:
|
||||
raise ValueError("Gitea release-run listing does not match current main")
|
||||
run_ids.append(str(run_id))
|
||||
run_id = max(run_ids, key=int)
|
||||
verify_run(run_id, stage="handoff", commit=current_main, api=api,
|
||||
current_main=current_main, checkout=checkout)
|
||||
metadata = api(f"/repos/{REPOSITORY}/actions/runs/{run_id}/artifacts")
|
||||
return descriptor_request(metadata, run_id=run_id, head_sha=current_main)
|
||||
|
||||
|
||||
def ensure_private_scratch(path: Path) -> None:
|
||||
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if path.is_symlink() or path.stat().st_uid != 0 or path.stat().st_mode & 0o077:
|
||||
@@ -149,11 +241,10 @@ def fetch_release(request: dict, *, policy: object, helper: str = "gitea-api",
|
||||
from tempfile import TemporaryDirectory
|
||||
with TemporaryDirectory(prefix="akyldash-release-", dir=temp_dir) as scratch:
|
||||
zip_path = Path(scratch) / "artifact.zip"
|
||||
result = subprocess.run(
|
||||
run_api_helper(
|
||||
[helper, "DOWNLOAD", f"/repos/{REPOSITORY}/actions/artifacts/{artifact_id}/zip", str(zip_path)],
|
||||
check=True, text=True, capture_output=True, env=env,
|
||||
env=env, timeout=30, max_stdout_bytes=4096, max_file_bytes=MAX_API_DOWNLOAD_BYTES,
|
||||
)
|
||||
del result
|
||||
manifest, manifest_bytes = validate_artifact_zip(
|
||||
zip_path, descriptor_sha256=tuple_data["descriptor_sha256"], release_run_id=run_id,
|
||||
ci_run_id=None, commit=commit, policy=policy,
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import ANY, patch
|
||||
|
||||
import external_status
|
||||
|
||||
|
||||
class ExternalStatusTests(unittest.TestCase):
|
||||
def test_status_is_candidate_only_after_release_descriptor_verification(self):
|
||||
commit = "a" * 40
|
||||
request = {"run_id": "302", "commit": commit, "descriptor_sha256": "b" * 64}
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
journal = root / "recovery.json"
|
||||
policy = root / "policy.json"
|
||||
state = root / "state.json"
|
||||
policy.write_text("{}", encoding="utf-8")
|
||||
with patch.object(external_status.os, "geteuid", return_value=0), \
|
||||
patch.object(external_status, "latest_main_sha", return_value=commit), \
|
||||
patch.object(external_status, "latest_release_request", return_value=request) as select, \
|
||||
patch.object(external_status, "fetch_release", return_value=({"commit": commit, "run_id": "302"}, b"descriptor")) as verify:
|
||||
value = external_status.status_document(
|
||||
api=lambda _path: {}, checkout=root, journal=journal, policy_file=policy,
|
||||
state_file=state, main_lookup=lambda _path: commit,
|
||||
checkout_lookup=lambda _path: commit,
|
||||
)
|
||||
self.assertEqual(value["state"], "candidate")
|
||||
self.assertEqual(value["release"], request)
|
||||
select.assert_called_once_with(current_main=commit, checkout=root, api=ANY)
|
||||
verify.assert_called_once()
|
||||
|
||||
def test_status_suppresses_an_exactly_applied_release(self):
|
||||
commit = "a" * 40
|
||||
request = {"run_id": "302", "commit": commit, "descriptor_sha256": "b" * 64}
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
journal, policy, state = root / "journal", root / "policy.json", root / "state.json"
|
||||
policy.write_text("{}", encoding="utf-8")
|
||||
images = {name: {"configured": f"registry.test/{name}@sha256:{'c' * 64}",
|
||||
"image_id": "sha256:" + "d" * 64}
|
||||
for name in ("backend", "opensearch")}
|
||||
state.write_text(json.dumps({
|
||||
"schema_version": 1, "commit": commit, "manifest_sha256": request["descriptor_sha256"],
|
||||
"current": images, "previous": images,
|
||||
}), encoding="utf-8")
|
||||
with patch.object(external_status.os, "geteuid", return_value=0), \
|
||||
patch.object(external_status, "latest_release_request", return_value=request), \
|
||||
patch.object(external_status, "fetch_release") as verify:
|
||||
result = external_status.status_document(
|
||||
api=lambda _path: {}, checkout=root, journal=journal, policy_file=policy,
|
||||
state_file=state, main_lookup=lambda _path: commit,
|
||||
checkout_lookup=lambda _path: commit,
|
||||
)
|
||||
self.assertEqual(result["reason"], "already_applied")
|
||||
verify.assert_not_called()
|
||||
|
||||
def test_status_fails_closed_for_root_guard_recovery_and_stale_checkout(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
journal = root / "recovery.json"
|
||||
policy = root / "policy.json"
|
||||
policy.write_text("{}", encoding="utf-8")
|
||||
with patch.object(external_status.os, "geteuid", return_value=1000):
|
||||
with self.assertRaisesRegex(ValueError, "must run as root"):
|
||||
external_status.status_document(checkout=root, journal=journal, policy_file=policy)
|
||||
with patch.object(external_status.os, "geteuid", return_value=0):
|
||||
journal.touch()
|
||||
value = external_status.status_document(checkout=root, journal=journal, policy_file=policy)
|
||||
self.assertEqual(value["reason"], "recovery_journal")
|
||||
journal.unlink()
|
||||
value = external_status.status_document(
|
||||
checkout=root, journal=journal, policy_file=policy,
|
||||
main_lookup=lambda _path: "a" * 40, checkout_lookup=lambda _path: "c" * 40,
|
||||
)
|
||||
self.assertEqual(value["reason"], "host_checkout_stale")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -3,6 +3,7 @@ import json
|
||||
import stat
|
||||
import tempfile
|
||||
import unittest
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
@@ -164,15 +165,15 @@ class ReleaseSourceTests(unittest.TestCase):
|
||||
calls.append(path)
|
||||
return run_responses[path]
|
||||
|
||||
def subprocess_run(command, **kwargs):
|
||||
def api_helper(command, **kwargs):
|
||||
calls.append(command)
|
||||
path = Path(command[-1])
|
||||
write_artifact(path)
|
||||
return type("Result", (), {"stdout": "PASS", "returncode": 0})()
|
||||
return b"PASS"
|
||||
|
||||
# The source helper requires a private root directory; this synthetic test isolates its owner check.
|
||||
with patch.object(release_source, "ensure_private_scratch"):
|
||||
with patch("release_source.subprocess.run", side_effect=subprocess_run):
|
||||
with patch("release_source.run_api_helper", side_effect=api_helper):
|
||||
manifest, raw = release_source.fetch_release(
|
||||
request, policy=POLICY, temp_dir=scratch, api=api, current_main=COMMIT
|
||||
)
|
||||
@@ -180,6 +181,88 @@ class ReleaseSourceTests(unittest.TestCase):
|
||||
self.assertEqual(hashlib.sha256(raw).hexdigest(), descriptor_sha)
|
||||
self.assertTrue(any(isinstance(call, list) and call[1] == "DOWNLOAD" for call in calls))
|
||||
|
||||
def test_latest_release_request_uses_bounded_filtered_listing_and_verifies_details(self):
|
||||
descriptor_sha = "e" * 64
|
||||
responses = {
|
||||
"/repos/admin/akyldash/actions/workflows/release-images.yaml/runs": {
|
||||
"total_count": 2,
|
||||
"workflow_runs": [
|
||||
{"id": 410, "head_sha": None, "workflow_id": None, "head_branch": None},
|
||||
{"id": 411, "head_sha": None, "workflow_id": None, "head_branch": None},
|
||||
],
|
||||
},
|
||||
"/repos/admin/akyldash/actions/runs/411": {
|
||||
"id": 411, "workflow_id": "release-images.yaml", "name": "Release production images",
|
||||
"status": "completed", "conclusion": "success", "head_sha": COMMIT,
|
||||
"head_branch": "main", "event": "workflow_run",
|
||||
},
|
||||
"/repos/admin/akyldash/actions/workflows/release-images.yaml": {
|
||||
"id": "release-images.yaml", "name": "Release production images",
|
||||
"path": ".gitea/workflows/release-images.yaml",
|
||||
},
|
||||
"/repos/admin/akyldash/actions/runs/411/artifacts": {
|
||||
"artifacts": [{
|
||||
"id": 9, "name": f"release-descriptor-411-{descriptor_sha}", "expired": False,
|
||||
"workflow_run": {"id": 411, "head_sha": COMMIT, "head_branch": "main",
|
||||
"event": "workflow_run", "conclusion": "success"},
|
||||
}]
|
||||
},
|
||||
}
|
||||
calls = []
|
||||
|
||||
def api(path):
|
||||
calls.append(path)
|
||||
parsed = urlsplit(path)
|
||||
return responses[parsed.path]
|
||||
|
||||
request = release_source.latest_release_request(current_main=COMMIT, api=api)
|
||||
self.assertEqual(request, {"run_id": "411", "commit": COMMIT, "descriptor_sha256": descriptor_sha})
|
||||
filters = parse_qs(urlsplit(calls[0]).query)
|
||||
self.assertEqual(filters, {
|
||||
"event": ["workflow_run"], "branch": ["main"], "status": ["success"],
|
||||
"head_sha": [COMMIT], "page": ["1"], "limit": ["10"],
|
||||
})
|
||||
self.assertIn("/actions/workflows/release-images.yaml/runs?", calls[0])
|
||||
self.assertIn("/repos/admin/akyldash/actions/runs/411", calls)
|
||||
|
||||
def test_latest_release_request_fails_closed_on_incomplete_listing(self):
|
||||
with self.assertRaisesRegex(ValueError, "incomplete"):
|
||||
release_source.latest_release_request(
|
||||
current_main=COMMIT,
|
||||
api=lambda _path: {"total_count": 11, "workflow_runs": [{"id": i} for i in range(10)]},
|
||||
)
|
||||
|
||||
def test_latest_release_request_rejects_wrong_detailed_source(self):
|
||||
responses = {
|
||||
"/repos/admin/akyldash/actions/workflows/release-images.yaml/runs": {
|
||||
"total_count": 1, "workflow_runs": [{"id": 411}],
|
||||
},
|
||||
"/repos/admin/akyldash/actions/runs/411": {
|
||||
"id": 411, "workflow_id": "release-images.yaml", "status": "completed",
|
||||
"conclusion": "success", "head_sha": "f" * 40,
|
||||
"head_branch": "main", "event": "workflow_run",
|
||||
},
|
||||
"/repos/admin/akyldash/actions/workflows/release-images.yaml": {
|
||||
"id": "release-images.yaml", "name": "Release production images",
|
||||
"path": ".gitea/workflows/release-images.yaml",
|
||||
},
|
||||
}
|
||||
def api(path):
|
||||
return responses[urlsplit(path).path]
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "does not match"):
|
||||
release_source.latest_release_request(current_main=COMMIT, api=api)
|
||||
|
||||
def test_api_json_caps_response_and_passes_no_token_argument(self):
|
||||
with patch.object(release_source, "run_api_helper", return_value=b'{"ok":true}') as run:
|
||||
self.assertEqual(release_source.api_json("/repos/admin/akyldash"), {"ok": True})
|
||||
command = run.call_args.args[0]
|
||||
self.assertEqual(command, ["gitea-api", "GET", "/repos/admin/akyldash"])
|
||||
self.assertEqual(run.call_args.kwargs["timeout"], release_source.API_TIMEOUT_SECONDS)
|
||||
with patch.object(release_source, "run_api_helper", return_value=b"x" * (release_source.MAX_API_RESPONSE_BYTES + 1)):
|
||||
with self.assertRaisesRegex(ValueError, "size limit"):
|
||||
release_source.api_json("/repos/admin/akyldash")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -350,6 +350,23 @@ class ReleaseWorkflowTests(unittest.TestCase):
|
||||
)
|
||||
self.assertNotEqual(rejected_dockerfile.returncode, 0)
|
||||
|
||||
def test_forced_command_dispatcher_has_only_exact_status_and_deploy_literals(self):
|
||||
dispatcher = ROOT / "infra/deploy/akyldash-release-dispatch.sh"
|
||||
installer = (ROOT / "infra/deploy/install-helper.sh").read_text(encoding="utf-8")
|
||||
source = dispatcher.read_text(encoding="utf-8")
|
||||
self.assertEqual(subprocess.run(["bash", "-n", str(dispatcher)]).returncode, 0)
|
||||
self.assertIn('/usr/local/sbin/akyldash-release-status)', source)
|
||||
self.assertIn('/usr/local/sbin/akyldash-release-deploy)', source)
|
||||
self.assertIn('[[ $EUID -ne 0 || $# -ne 0 ]]', source)
|
||||
self.assertNotIn("eval", source)
|
||||
self.assertIn('install -o root -g root -m 0750 "$release_dispatch_source" /usr/local/sbin/akyldash-release-dispatch', installer)
|
||||
self.assertIn('bash -n "$release_deploy_source" "$release_rollback_source" "$release_dispatch_source"', installer)
|
||||
rejected = subprocess.run(
|
||||
["bash", str(dispatcher)], env={**os.environ, "SSH_ORIGINAL_COMMAND": "id"},
|
||||
text=True, capture_output=True,
|
||||
)
|
||||
self.assertNotEqual(rejected.returncode, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"enabled": false,
|
||||
"repository": "D:\\Dev\\akyldash",
|
||||
"ssh_alias": "akyldash_release"
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
||||
<RegistrationInfo>
|
||||
<Description>One-shot poll for a root-verified Akyldash release. Disabled template; requires owner review.</Description>
|
||||
<URI>\Akyldash\ReleaseTrigger</URI>
|
||||
</RegistrationInfo>
|
||||
<Triggers>
|
||||
<CalendarTrigger>
|
||||
<StartBoundary>2026-11-02T09:00:00</StartBoundary>
|
||||
<Enabled>false</Enabled>
|
||||
<ScheduleByDay><DaysInterval>1</DaysInterval></ScheduleByDay>
|
||||
<Repetition>
|
||||
<Interval>PT5M</Interval>
|
||||
<Duration>P1D</Duration>
|
||||
<StopAtDurationEnd>false</StopAtDurationEnd>
|
||||
</Repetition>
|
||||
</CalendarTrigger>
|
||||
</Triggers>
|
||||
<Principals>
|
||||
<Principal id="Owner">
|
||||
<UserId>REPLACE_WITH_OWNER_SID</UserId>
|
||||
<LogonType>InteractiveToken</LogonType>
|
||||
<RunLevel>LeastPrivilege</RunLevel>
|
||||
</Principal>
|
||||
</Principals>
|
||||
<Settings>
|
||||
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
||||
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
|
||||
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
|
||||
<AllowHardTerminate>true</AllowHardTerminate>
|
||||
<StartWhenAvailable>false</StartWhenAvailable>
|
||||
<Enabled>false</Enabled>
|
||||
<Hidden>false</Hidden>
|
||||
<WakeToRun>false</WakeToRun>
|
||||
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
||||
<Priority>7</Priority>
|
||||
</Settings>
|
||||
<Actions Context="Owner">
|
||||
<Exec>
|
||||
<Command>C:\Program Files\Akyldash\python.exe</Command>
|
||||
<Arguments>C:\Program Files\Akyldash\receive_external.py --once</Arguments>
|
||||
<WorkingDirectory>C:\Program Files\Akyldash</WorkingDirectory>
|
||||
</Exec>
|
||||
</Actions>
|
||||
</Task>
|
||||
Reference in new issue
Block a user