diff --git a/.gitea/workflows/release-images.yaml b/.gitea/workflows/release-images.yaml index 60739bb..866e4f9 100644 --- a/.gitea/workflows/release-images.yaml +++ b/.gitea/workflows/release-images.yaml @@ -61,6 +61,7 @@ jobs: --repository admin/akyldash \ --commit '${{ gitea.event.workflow_run.head_sha }}' \ --run-id '${{ gitea.run_id }}' \ + --source-run-id '${{ gitea.event.workflow_run.id }}' \ --backend-digest release/backend.digest \ --opensearch-digest release/opensearch.digest \ --output release/release-manifest.json diff --git a/docs/operations/BACKUP.md b/docs/operations/BACKUP.md index b3b3ee3..45fff2e 100644 --- a/docs/operations/BACKUP.md +++ b/docs/operations/BACKUP.md @@ -2,135 +2,69 @@ ## Current status -No production data or backup existed during the 2026-10-11 audit. The repository -now contains `infra/backup/archive.py`; it is not installed or run on the VPS, -and `/var/backups/akyldash` was only a planned root-only location. The owner has -since prohibited keeping a complete archive on the VPS, including temporarily. -The local archive and full stop-create-verify-restart procedures below are -superseded and **not authorized on the VPS**. The selected destination is -externally managed Windows-controlled storage; its design and implementation -are pending, so there is no verified backup path yet. Do not treat this plan or -the uninstalled archive tool as a valid production backup. +The owner requires that a complete production archive never be written to the +VPS, even temporarily. The reviewed implementation in PR #59 streams stopped +Compose state directly from the root receiver to the owner's Windows client; +the client stores it only under `D:\Dev\akyldash\.backups`. The VPS retains +only a secret-free identity (backup ID, size, archive and manifest hashes, +manifest) in root-owned release state. The implementation has synthetic tests +only and is not installed or verified on Windows or the VPS. There is no +verified production backup, so production deployment remains blocked. -## Required release policy +## External backup flow -- Create a backup before every production change, including any future schema - or index migration. -- Include the normalized corpus, `search-users.sqlite3`, - `search-reviews.sqlite3`, the OpenSearch index/snapshot, deployment digest, - Caddy's certificate data, and required secret file in the protected backup - set. Store secrets and Caddy private keys with equivalent access controls. -- Verify archive readability, checksums, and SQLite integrity before relying - on it. Never overwrite or delete the only usable backup. -- Keep one current pre-release backup. If deployment fails, retain the backup - required to restore the previous state. -- Test restore into an isolated target before relying on the backup. Do not - restore over production as a test. +- The release receiver takes the shared deployment lock and stops the stack. +- It streams a tar/gzip archive through a bounded binary SSH session. It does + not create a local archive or temporary full-size copy on the VPS. +- The Windows receiver requires the exact D: repository, a real NTFS path, + restrictive ACLs, and the exact `/.backups/` rule in that checkout's local + `.git/info/exclude`. It writes into a private staging directory, checks the + stream size and SHA-256, verifies the archive and manifest, then publishes + the complete backup directory without overwriting an existing ID. +- Only after Windows confirms the stored archive identity does the VPS proceed + with image cutover. If backup transport or verification fails, it attempts + to restart the previous services and records a recovery journal if restart + fails. +- Rollback first challenges Windows with the root-pinned previous backup + identity. Windows verifies the local archive and streams it back; the VPS + compares its exact size and SHA-256 before stopping services. Rollback then + creates a fresh external backup of the current state before changing image + references. It restores images only, never application data or OpenSearch + state. -## Clean first deployment — superseded, not authorized on the VPS +Windows PowerShell is the intended client. The destination and ACL checks have +not yet been exercised on Windows. An owner must separately test archive +restore on an isolated target before relying on this path. Do not restore over +production as a test. -No backup is needed only when Compose has no containers and all four -persistent mounts are confirmed empty. For a first install with a preloaded -corpus and not-yet-created named volumes, use `--initial-deployment` to create -the pre-start backup. This flag is accepted only with no Compose containers and -when `DATA_ROOT` contains exactly `minjust-normalized/`; it archives absent -named volumes as empty components. In every normal backup, an absent volume is -an error because it could mean that a previous installation lost data. -Missing mount definitions, inaccessible Docker state, or partial service -containers are also errors and must stop deployment. Do not create placeholder -containers to make backup pass. +## Backup contents and limits -For the corpus-only initial case, run this before the first `up` from the -approved checkout. Replace the timestamp with one real UTC timestamp: +The existing `infra/backup/archive.py` manifest records the Git revision, +deployment-file hashes, image references and IDs, and the components included +in the archive: application data, OpenSearch, Caddy data/configuration, +`production.env`, and the review secret. Secret-bearing files and SQLite files +are archived with restrictive modes. The archive verifier rejects unsafe +members and checks SQLite integrity. SSH encrypts archive bytes in transit. +The destination contains secrets and private keys; D: encryption at rest (for +example, BitLocker) has not been verified. This PR adds no client-side +encryption or signing, so the owner must verify storage encryption and retain +the restrictive ACLs before using it. -```bash -cd /opt/akyldash/current -sudo python3 infra/backup/archive.py create \ - --compose-file deploy/production/compose.yaml \ - --env-file /etc/akyldash/production.env \ - --initial-deployment \ - --output /var/backups/akyldash/akyldash-initial-corpus-YYYYMMDDTHHMMSSZ.tar.gz -sudo python3 infra/backup/archive.py verify /var/backups/akyldash/akyldash-initial-corpus-YYYYMMDDTHHMMSSZ.tar.gz -``` +The external protocol caps control frames at 64 KiB, chunks at 1 MiB, and the +archive at 100 GiB. SSH provides transport encryption and server host-key +verification. The receiver uses a fixed SSH command and does not accept a +caller-supplied path or shell command. It relies on the existing owner SSH +configuration; no key, host entry, sudo rule, or VPS setting is added here. -## Cold backup procedure — superseded, not authorized on the VPS +## Restore -The script requires every Compose container to be stopped. Schedule downtime, -then run from the approved checkout on the VPS: +Use `infra/backup/archive.py restore` only with an archive already present in a +protected owner-controlled location, and target a new staging directory on an +isolated recovery host. Review [recovery](RECOVERY.md) and +[deployment](DEPLOYMENT.md) first. This PR does not perform or authorize a +production restore, data migration, or VPS operation. Keep the previous +external archive until the owner has verified the replacement and explicitly +approved its retention period. -```bash -cd /opt/akyldash/current -sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml stop -sudo python3 infra/backup/archive.py create \ - --compose-file deploy/production/compose.yaml \ - --env-file /etc/akyldash/production.env \ - --output /var/backups/akyldash/akyldash-YYYYMMDDTHHMMSSZ.tar.gz -sudo python3 infra/backup/archive.py verify /var/backups/akyldash/akyldash-YYYYMMDDTHHMMSSZ.tar.gz -``` - -Replace the timestamp placeholder with one real UTC timestamp before running. -On a clean first deployment, `create` exits with a clear message that backup -can be skipped. With existing data and all expected volumes present, it -archives the storage even when no Compose containers exist. A preloaded corpus -with no named volumes requires the explicit `--initial-deployment` mode; -otherwise missing volumes are rejected. Partial service containers or running -services are rejected as unsafe. The create command archives the application data, -OpenSearch volume, Caddy data/config volumes, production environment file, and -review secret. It records the checked-out Git revision, deployment-file hashes, -and image references/IDs for each stopped Compose service, writes a SHA-256 -sidecar, and refuses to overwrite an existing archive. It also runs SQLite -`quick_check`. Start the stack again only after verification succeeds: - -```bash -cd /opt/akyldash/current -sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml up -d -``` - -## Initial post-setup baseline — superseded, not authorized on the VPS - -After the first index has been loaded and validated, the initial `admin` account -has been created, and `/review` responds over HTTPS, create a second backup. -This one captures the initialized index, account database, and newly created -Caddy/OpenSearch volumes. Stop all services, create and verify the archive, -then start the stack again: - -```bash -cd /opt/akyldash/current -sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml stop -sudo python3 infra/backup/archive.py create \ - --compose-file deploy/production/compose.yaml \ - --env-file /etc/akyldash/production.env \ - --output /var/backups/akyldash/akyldash-initial-baseline-YYYYMMDDTHHMMSSZ.tar.gz -sudo python3 infra/backup/archive.py verify /var/backups/akyldash/akyldash-initial-baseline-YYYYMMDDTHHMMSSZ.tar.gz -sudo docker compose --env-file /etc/akyldash/production.env -f deploy/production/compose.yaml up -d -``` - -Use one real UTC timestamp in both archive paths. Do not treat initial -production setup as complete until this baseline archive verifies. Keep the -pre-start corpus archive as well until the baseline is verified and copied to -separately managed encrypted storage. - -The historical procedure below assumes a local VPS archive and is superseded. -Do not create or stage a full archive on the VPS, even temporarily. A restore -procedure for the selected external Windows-controlled copy is pending its -design and implementation. Until an external copy and separate-target restore -are verified, the production backup gate is unmet. The old local-archive restore -example is not authorized for production data: - -```bash -sudo python3 infra/backup/archive.py restore /var/backups/akyldash/backup.tar.gz \ - --target-dir /var/tmp/akyldash-restore-test -``` - -This validates and stages the archive. On the replacement host only, after -running bootstrap with `--recovery-target` and checking out the matching Git -revision, apply the staged data: - -```bash -sudo python3 infra/backup/apply_restore.py \ - --staging-dir /var/tmp/akyldash-restore-test -``` - -The apply command restores data and named volumes but leaves services stopped. -Test the full procedure on a separate recovery host before relying on it. Do -not run an unreviewed restore over existing data. +The former `/var/backups/akyldash` create/verify procedure is superseded and +must not be used for a full production archive on the VPS. diff --git a/docs/operations/CURRENT_STATE.md b/docs/operations/CURRENT_STATE.md index 789a5aa..e339b0e 100644 --- a/docs/operations/CURRENT_STATE.md +++ b/docs/operations/CURRENT_STATE.md @@ -2,10 +2,38 @@ 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. The selected externally managed -Windows-controlled backup destination is still pending design and -implementation; no verified external backup or restore exists, so production -deployment remains blocked by the backup gate. +`BACKUP.md` are superseded and unauthorized. PR #59 now contains a proposed +Windows-controlled external stream receiver and root-side deploy/rollback +code. It has not been installed or run on Windows or the VPS. No verified +external backup or separate-target restore exists, so production deployment +remains blocked by the backup gate. + +## Code-only deployment work — 2026-10-31 + +- Work is being prepared in the existing PR #59 branch from the then-current + `main`; no merge, VPS operation, live release, or workflow dispatch was + performed for this work. +- The release descriptor now binds both the release run and its successful CI + source run. Host-side source verification uses the installed `gitea-api` + helper contract; the PR carries the inspected helper fixture plus a bounded + binary-download patch. The installer verifies the fixture hash before + applying the patch. +- Backup bytes are streamed through a bounded SSH protocol to the fixed + Windows destination. Root release state stores only a secret-free backup + identity. The rollback handshake requires the exact previously pinned + archive and creates a fresh external backup before image references change. + Local VPS archive paths fail closed. +- Synthetic tests cover archive/protocol integrity, helper download rules, + artifact/run provenance, receiver publication, release schema, and rollback + refusal. Windows ACL, NTFS, PowerShell, SSH alias, Gitea helper against the + live instance, root helper installation, artifact redirect, production + backup/restore, and actual release/rollback remain unverified. +- Owner bootstrap blockers remain: verify a root-controlled SSH route for the + fixed commands using existing host-key checking; provision only the + necessary read-only Gitea token, exact redirect origin if needed, and + approved RU/KY canaries; confirm registry pull and retention policy; test + the Windows client and a separate-target restore. No new key, sudo rule, + Docker access, credential, or VPS setting is added by the code change. Read-only deployment recheck: 2026-10-25. Source: SSH as `codex`, direct-origin and public HTTPS probes, local `main` checkout, and Gitea API. No VPS files, @@ -157,20 +185,18 @@ Docker state, UFW rule details, and protected file metadata were not verified. The mode has not been run on a VPS. - The repository defines a root-owned read-only verifier, Compose `config` and `status` helper, guarded rollback helper, and installer with exact sudoers - command rules. None is installed on the VPS. This branch adds an owner-run - release cutover helper; it is deliberately not added to the `codex` sudoers - allowlist. CI contains no production apply job; service changes remain - owner-run. -- Digest rollback now requires release state to pin current and previous - refs/image IDs and the selected verified backup to match that previous state. - It serializes with cutover, atomically changes both protected image refs, uses - `--no-build`, and preserves a secret-free recovery journal on failure. Legacy - tag rollback remains supported. These paths have synthetic tests only; they - have not been exercised on the VPS. + command rules. None was installed on the VPS at this inventory. The current + PR adds fixed root-side release/rollback receivers without adding a `codex` + sudoers rule or Docker access. Neither receiver has been installed or run. +- The former local-VPS rollback path has been superseded and now fails closed. + The PR rollback path requires a root-pinned external archive identity, + rechecks its exact bytes through the owner client, creates a fresh external + backup before changing refs, and preserves a secret-free recovery journal on + failure. Synthetic tests only; no production rollback was performed. - The image release workflow now starts after successful CI for a push to `main`. It checks the source workflow/event/branch/conclusion and exact source - SHA, checks out that SHA, and uses the release run ID for tags and the - schema-v3 descriptor. Registry secrets `REGISTRY_USERNAME` and + SHA, checks out that SHA, and uses both release and source run IDs in the + schema-v4 descriptor. Registry secrets `REGISTRY_USERNAME` and `REGISTRY_PASSWORD` remain unconfigured/unverified; no values were created or inspected. PR image builds remain no-push. The descriptor SHA-256 is included in the artifact name, and the artifact also retains its checksum sidecar. @@ -180,13 +206,13 @@ Docker state, UFW rule details, and protected file metadata were not verified. the source run and stale-main guards. It is dry-run only. It 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. The audited - `gitea-api` helper lacks binary output and safe 302 handling, so the host - cannot yet independently retrieve and validate the descriptor. No deploy - key, fixed receiver, extra sudo rule, or Gitea CD variable has been - configured. Production apply remains blocked on a reviewed binary-safe - artifact reader and a fixed root-owned forced command; backup/data/rollback - gates still apply before any actual cutover. + not download artifact ZIPs, connect to SSH, or apply a release. 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 + Gitea CD variable has been configured. Production apply remains blocked on + owner bootstrap, external backup and separate-target restore, and the other + gates above. - A repository-scoped official `act_runner` `0.2.13` installation is configured in `infra/runner/`: rootless Docker under `akyldash-runner`, 15 GiB ext4 loop-backed image/workspace storage, capacity 1, per-job limits (2 CPU, diff --git a/docs/operations/DEPLOYMENT.md b/docs/operations/DEPLOYMENT.md index 464c17f..cc3284a 100644 --- a/docs/operations/DEPLOYMENT.md +++ b/docs/operations/DEPLOYMENT.md @@ -1,164 +1,93 @@ # Deployment -## Current status +## Status and authorization -Production deployment is not enabled or tested on the VPS. The owner completed -the root bootstrap: Docker/Compose are active and target directories exist. -The `codex` account cannot access the Docker socket. No root-owned checkout or -restricted helpers are installed; protected env/secret metadata and Docker -container/volume state remain unverified because they require root. -The unprivileged audit sees no listener on `80`, `443`, or `1500`; Cloudflare -still returns `521`. Do not deploy until the owner has reviewed root-only host -state, supplied protected configuration and the approved corpus/index, and -backup/restore have been tested. +The implementation in PR #59 is not merged, installed, or exercised against +the VPS. No release, backup, restore, or production service operation has been +performed by this change. Production deployment remains blocked until the +owner has verified host state, registry access, protected configuration, +corpus/index readiness, RU/KY canaries, an external backup, and restore on a +separate target. See [current state](CURRENT_STATE.md) and the +[owner evidence packet](DEPLOYMENT_OWNER_PACKET.md). -## First host preparation +The existing `codex` account has no Docker socket access and receives no new +privilege in this change. The external receiver requires an owner-controlled +SSH entry that runs the fixed root command; no SSH key, `authorized_keys` +entry, sudo rule, or root alias is created here. If `akyldash_vps` logs in as +`codex`, it cannot run the root-only receiver and the client fails closed. +Do not grant general sudo or Docker access to make the flow work. -1. The initial root bootstrap is complete. After reviewing and merging the - infrastructure PR, the owner must install that approved `main` checkout at - `/opt/akyldash/current` (the path was absent during the unprivileged audit): +## Release verification and image publication - ```bash - sudo git clone --branch main --single-branch https://git.vakanaut.ru/admin/akyldash.git /opt/akyldash/current - ``` +`.gitea/workflows/ci.yaml` remains the required test and image-build workflow. +The release workflow runs after successful main CI, verifies the source run and +commit, and publishes digest-pinned images plus a small release descriptor. +The descriptor records both the release workflow run ID and the successful CI +source run ID. PR builds do not publish images. Production runtime secrets are +not supplied to CI. - The checkout is root-owned by default. Then run - `sudo bash /opt/akyldash/current/infra/bootstrap/audit-host.sh`. This - read-only audit reports Docker state, protected-file metadata, UFW rules, - listeners, and ISPmanager without printing secret contents. Resolve any - existing containers, volumes, or data before proceeding; do not overwrite - or delete them. -2. After confirming the existing env and secret do not exist and reviewing the - tracked defaults, run - `sudo bash /opt/akyldash/current/infra/deploy/prepare-production-config.sh`. - It creates `/etc/akyldash/production.env` from the tracked example and - generates `/etc/akyldash/review_secret`; both are root-owned mode `0600`. - It refuses to overwrite either file and does not start services or create - volumes. Review `DATA_ROOT` and follow the - [corpus inventory and handoff gates](CORPUS_HANDOFF.md) before placing the - approved normalized corpus there. -3. After reviewing the root-owned checkout and audit output, run - `sudo bash /opt/akyldash/current/infra/deploy/install-helper.sh`. It installs - the backup reader, read-only verifier, `akyldash-compose config|status`, and - rollback helper with exact sudoers command rules. The Compose helper has no - start/stop/build operation and grants no direct Docker access. Actual - deployments remain owner-run through the documented Compose commands. -4. Confirm DNS points through Cloudflare to this origin. The owner reports UFW - already allows TCP `80` and `443`; read and document the full rules before - any firewall decision. TCP `1500` is allowed by owner report but has no - observed listener and no ISPmanager package/service was found; the owner - must identify its purpose. Do not change UFW as part of this procedure. The - Compose Caddy service obtains and renews HTTPS certificates automatically; - Cloudflare Full (strict) still needs end-to-end verification. -5. **Deployment is blocked by the backup gate.** The owner prohibits keeping a - complete archive on the VPS even temporarily. The local archive and - stop-create-verify-restart commands in `BACKUP.md` are superseded and not - authorized on the VPS. The selected externally managed Windows-controlled - backup destination is pending design and implementation; it is not yet a - verified backup. Do not start services or perform a production cutover until - that external copy and a separate-target restore have been verified. The - existing archive tool does not implement that external flow. +On the host, the fixed root receiver uses the installed `gitea-api` helper to +re-fetch and verify the exact successful CI and release runs, current `main`, +artifact name, checksum, manifest schema, builder pin, image policy, and commit +binding. Its binary `DOWNLOAD` extension accepts HTTPS and at most one +allowlisted HTTPS redirect, does not forward the token across origins, bounds +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. -Application deployment remains owner-run. The repository-scoped `act_runner` -`0.2.13` service is active under `akyldash-runner` and uses rootless Docker on a -separate loop-backed filesystem. CI run 75 and smoke run 76 succeeded on main -head `0e276ae6`. Runner job containers have neither Docker socket nor production -secrets. CI has no image publishing or production deployment step. The -repository defines sudo helpers for fixed verification, read-only Compose -`config`/`status`, and guarded rollback, but none is installed on the VPS. They -do not start or stop services. +## External backup and cutover -## Release image contract (preparation only) +The fixed root release receiver accepts only a bounded protocol request over +stdin. It does not accept a remote shell command, artifact path, or image +reference from the caller. It rechecks the release and current `main`, takes a +shared lock, captures running image IDs, and stops the stack. It streams the +cold archive directly to the owner's Windows client at +`D:\Dev\akyldash\.backups`; the VPS does not hold a full archive, including +temporarily. The Windows client requires a real NTFS destination with private +ACLs and a precise local Git exclude rule. It publishes only after hash, +archive, and manifest verification, and acknowledges the exact live session +nonce and backup identity. -`infra/deploy/validate_release.py` checks an offline JSON release manifest -against an explicitly supplied repository allowlist. Schema version 1 requires -exactly `schema_version`, `source_ref`, `commit`, and `images`; the source ref -must be `refs/heads/main`, the commit must be a 40-character lowercase Git -SHA-1, and the images must contain exactly `backend` and `opensearch` as -`repository@sha256:<64 lowercase hex>` references. The policy has schema -version 1 and one non-empty repository allowlist for each service. Unknown or -duplicate JSON keys are rejected. +Only after the acknowledgement does the host pull approved digest references, +atomically replace both image refs, and start Compose with `--no-build`. It +checks running image IDs, `/review`, and non-empty Russian and Kyrgyz search +canaries. A stale main, source mismatch, invalid archive, image mismatch, or +failed health/canary check stops cutover and attempts recovery using the +pre-change references. A recovery journal blocks another operation if +automatic recovery cannot be verified. -The validator takes the manifest path and an explicit policy path: +Rollback uses the root-pinned prior external archive and creates a fresh +external backup of current state before switching refs. It restores images +only, not data. Old local VPS backup paths and legacy release states without a +pinned external backup identity are rejected. See [backup and restore](BACKUP.md) +and [rollback](ROLLBACK.md). -```bash -python3 infra/deploy/validate_release.py release.json --policy /etc/akyldash/release-policy.json -``` +## Owner bootstrap still required -The policy shape is `{"schema_version":1,"repositories":{"backend":["registry.invalid/akyldash/backend"],"opensearch":["registry.invalid/akyldash/opensearch"]}}`. -These `registry.invalid` names are format examples only; this change does not -create a policy file or approve a registry. +After review and merge, the owner must decide whether to install the helper +from a root-owned checkout and provision, without exposing values in logs: -The repository name in the policy must be approved for the registry. No real -registry namespace or root-owned host policy is configured by this change; do -not use the synthetic `registry.invalid` names in tests as production values. -The host integration must load policy only from its fixed root-owned path. -This validator checks format and allowlist only: a manifest can claim a main -ref and commit, but is not proof of source, build provenance, signature, or -trusted publication. The release workflow now follows successful main CI and -publishes only when the existing Registry secrets are configured. +- a read-only Gitea API token in `/etc/akyldash/gitea-api-token`, root-owned + mode `0600`; +- the exact artifact redirect origin allowlist in + `/etc/akyldash/gitea-download-origins`, if the Gitea artifact endpoint + redirects; +- approved Russian and Kyrgyz search canaries in + `/etc/akyldash/release-canaries.json`, root-owned mode `0600`; +- 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. -Compose merges an image override with the existing service `build` entries. -The regression test renders fake digest references and confirms both entries -remain; any future deploy command must use `docker compose up --no-build` so -the host cannot silently build a different image. This does not make digest -rollback available: the current rollback helper expects local tags. Owner- -approved registry permissions and retention, plus manual backup/health/rollback -end-to-end validation are still required before a real production cutover. +The installer intentionally does not create credentials, SSH entries, canary +values, registry permissions, or a new privilege rule. Existing files with +unexpected owner, mode, or content cause installation to stop for owner +review. Do not run the installer or receiver from CI. The owner's first use +must be a separate-target restore check and a reviewed dry run; this PR does +not authorize a production cutover. -## Automated release and dry-run handoff - -`release-images.yaml` starts after a successful `CI` run from a push to `main`. -It verifies the upstream event, source branch, conclusion, and SHA, checks that -the source is still current `main`, and builds that exact checkout. PR image -builds remain no-push. The workflow does not receive production runtime -secrets. - -`deploy-handoff.yaml` starts after a successful release workflow and repeats -the source-run and stale-SHA checks. It is dry-run only: it may read artifact -metadata through `gitea-api` if that helper is installed in the job image, but -does not download the artifact ZIP, connect to the host, or apply a release. -When the helper is absent it reports that descriptor metadata and host handoff -are not verified. The checked-in `gitea-api` helper supports JSON GET responses -but does not provide binary output or follow the 302 redirect used by Gitea's -artifact ZIP endpoint. Do not configure a deploy key or enable a live handoff -until the host can independently fetch and validate the successful source -artifact through an approved binary-safe capability. - -For Gitea 1.25.5, metadata is read from -`GET /repos/admin/akyldash/actions/runs/{source_run_id}/artifacts`; the host -must then download -`GET /repos/admin/akyldash/actions/artifacts/{artifact_id}/zip`. The latter -redirects to a blob URL. Any future fetcher must bound response size, require -HTTPS redirects, validate the redirected destination, and never send the -`GITEA_TOKEN` to a different origin. The existing helper's accepted -`METHOD /path [JSON]` interface does not provide those binary-download -guarantees. - -The future transport contract is a dedicated SSH key whose `authorized_keys` -entry forces `sudo -n /usr/local/sbin/akyldash-release-deploy` with OpenSSH -`restrict` enabled. It accepts only `run_id`, source `commit`, and -`descriptor_sha256`; the host must fetch the named artifact itself, verify its -run, source branch/conclusion, manifest and checksum, then use the existing -root-owned policy and guarded deploy helper. No remote command or artifact path -is accepted from the job. This receiver, key, host pin, and command permission -are not configured or installed. Future repository settings are named -`AKYLDASH_DEPLOY_SSH_KEY` and `AKYLDASH_DEPLOY_KNOWN_HOSTS` (Actions secrets) -and `AKYLDASH_CD_ENABLED=true` (repository variable); do not create them until -the receiver and artifact fetcher are implemented and reviewed. Backup, -corpus/data, canary and rollback gates remain required before an actual cutover. - -## CI - -`.gitea/workflows/ci.yaml` runs the Python unit suites and builds both -production images on pull requests and pushes to `main`. It does not publish an -image or deploy production. After successful main CI, the separate -`release-images.yaml` workflow is scheduled to publish digest-pinned images; -`deploy-handoff.yaml` validates a dry-run handoff. Neither workflow has been -run with release credentials, and neither applies a production release. -`.gitea/workflows/runner-smoke.yaml` exercises the -`akyldash-ci` runner on pull requests, pushes to `main`, or manual dispatch. -Both workflows passed on main head `0e276ae6` in runs 75 and 76 respectively. -The repository runner-list endpoint is not available to the current API -principal, so its registration details cannot be independently read through -Gitea API. +The Windows client uses the existing OpenSSH host-key checking. Its configured +alias must reach a root-controlled endpoint capable of invoking the fixed +receiver; no new key or sudo permission is requested. Windows ACL and NTFS +checks, SSH host configuration, artifact redirect origin, registry pull +access, and every production health gate remain unverified until the owner +checks them. diff --git a/docs/operations/DEPLOYMENT_OWNER_PACKET.md b/docs/operations/DEPLOYMENT_OWNER_PACKET.md index 88c4fad..4ee155b 100644 --- a/docs/operations/DEPLOYMENT_OWNER_PACKET.md +++ b/docs/operations/DEPLOYMENT_OWNER_PACKET.md @@ -1,89 +1,55 @@ # Deployment owner evidence packet -No production change is authorized by this packet. Provide the following -sanitized facts before enabling registry publishing or running an owner cutover. -Never include token/password values, environment-file contents, secret material, -or raw process environments. +This packet is a list of owner-only checks. It does not authorize a production +change. Do not include token/password values, environment-file contents, +private keys, secret material, or raw process environments. -## Registry +## Required before release use -- Confirm the package names `admin/akyldash/backend` and - `admin/akyldash/opensearch` are available on `git.vakanaut.ru` and can be - linked to this repository as needed. -- Decide whether to configure repository Actions secrets - `REGISTRY_USERNAME` / `REGISTRY_PASSWORD`. Use a dedicated package writer - with only the required package write scope. Do not reuse Gitea administration, - VPS, runner, or production service credentials. -- Confirm the registry retention rule keeps all digest-pinned versions for at - least the rollback window. State the number of versions/days, not secret data. -- Confirm Gitea artifact retention also covers the rollback window. The main-only - release workflow requests 90 days for its small descriptor and checksum; - instance policy may cap that value. PR CI uploads a tiny marker for one day - to validate the runner artifact endpoint. Neither requires enabling the - runner cache service. -- The release workflow is now triggered by a successful `CI` workflow run for - a `main` push. The subsequent `deploy-handoff.yaml` is dry-run only and opens - no host connection. Do not create `AKYLDASH_DEPLOY_SSH_KEY`, - `AKYLDASH_DEPLOY_KNOWN_HOSTS`, or an `AKYLDASH_CD_ENABLED` variable yet; the - host receiver and binary-safe artifact retrieval are not implemented or - installed. -- The future host command contract is limited to the fixed forced command - `sudo -n /usr/local/sbin/akyldash-release-deploy`, with `restrict` in the - dedicated key's `authorized_keys` entry. The receiver must accept only - `run_id`, source commit, and descriptor SHA-256, independently retrieve and - validate the successful main-run artifact, then invoke the existing guarded - deploy path. It must not accept a remote command or caller-supplied file - path. No key, sudo rule, SSH change, or host command has been installed. -- The currently audited `gitea-api` helper can return JSON metadata but cannot - save a binary response or safely follow the Gitea artifact ZIP redirect. A - future owner-approved artifact reader must validate HTTPS redirects and must - not forward `GITEA_TOKEN` to another origin. The workflow will remain - dry-run-only until this capability and the fixed host receiver are reviewed. -- The release descriptor is unsigned. Decide whether Gitea run/artifact - traceability is sufficient for the first owner-run release or require a - separately provisioned signing/attestation service before publishing. +- 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. +- Confirm Gitea artifact retention covers the rollback window. The workflow + requests 90 days for the small release descriptor and checksum. +- Provide a dated, sanitized root audit: installed checkout SHA, Compose + services and image IDs, health state, volume paths/modes, protected-file + owner/mode, listener summary, and current recovery-journal state. +- Confirm a root-controlled SSH path exists for the fixed deploy and rollback + commands, using existing owner SSH configuration and verified host-key + checking. The repository `codex` account must not receive general sudo, + Docker-group membership, or a Docker socket. No SSH key or root alias is + provisioned by this PR. +- If required, install a narrowly scoped, read-only Gitea API token at + `/etc/akyldash/gitea-api-token` with root ownership and mode `0600`. Record + only whether it is present and its scope; never send its value. +- Verify the Gitea artifact download origin. If redirected, provision only the + exact HTTPS origin in `/etc/akyldash/gitea-download-origins` as a root-owned + mode-`0600` file. The patched helper must not send its token to that origin. +- Provide owner-approved RU and KY search canary queries in + `/etc/akyldash/release-canaries.json`, root-owned mode `0600`. Confirm they + return expected non-empty results without sending corpus documents. +- Confirm Cloudflare TLS mode, origin certificate renewal, and current public + `/review` and search health. -## Host and backup +## Backup and recovery gates -- Have the owner provide a dated, sanitized root audit: installed checkout SHA; - Compose service names, image references and image IDs; running/health state; - persistent mount paths and read-only/read-write flags; protected env/secret - owner, group, and mode only; listener/firewall summary. Exclude all env values. -- The owner prohibits keeping a complete archive on the VPS, even temporarily; - the local cold-backup and full stop-create-verify-restart procedure in - `BACKUP.md` is superseded and must not be run on the VPS. The selected - externally managed Windows-controlled backup destination is pending design - and implementation. Before cutover, verify an external copy, its checksum, - the recorded backend/OpenSearch refs and image IDs, and a restore on a - separate target. No backup implementation is included in this CD change. -- Confirm whether current data/corpus files are mounted read-only and provide - owner/mode metadata before proposing any UID, ownership, or mount changes. -- After the PR is reviewed, the owner must run the existing root-only - `infra/deploy/install-helper.sh` once from the approved root-owned checkout - to install the updated rollback helper modules (`release_refs.py`, - `release_state.py`, and `deployment_lock.py`). The installer keeps the - existing fixed sudoers command set; it does not add a deploy command for - `codex`. Do not run this installer before review or as part of CI. -- Confirm that the production host can pull the private images, or that the - published packages are intentionally public. If a pull credential is - needed, keep it in the owner-managed root Docker config; it is not a runner - secret. +- The complete archive must remain on the owner-controlled Windows destination + `D:\Dev\akyldash\.backups`; never stage a full archive on the VPS. +- Before relying on the flow, run its NTFS, ACL, D: path, and local `.git/info/exclude` + checks on Windows and verify a complete synthetic or approved backup is + published only after hash and manifest verification. +- Confirm D: encryption at rest. Archives contain production secrets and + private keys; the protocol encrypts transport but does not encrypt files at + rest. +- Restore a verified archive on an isolated separate target and check data, + SQLite integrity, OpenSearch, and required secrets. Do not use production as + a restore test. +- Confirm current data/index counts, corpus generation, and migration + compatibility. Image rollback does not restore data or undo schema changes. +- Set the archive retention period and keep the previous verified archive + throughout the rollback window. -## Search data - -- Provide the current OpenSearch alias and exact target index, expected document - and fragment inventory counts, and owner-approved Russian and Kyrgyz canary - queries. Report only counts, query text, match/no-match and service health; - do not attach corpus documents or production database files. -- Confirm that the normalized corpus generation selected for publication has - passed the repository inventory verifier and that unresolved raw-source - errors have an explicit owner disposition. - -## Edge and host recovery - -- Confirm Cloudflare SSL/TLS mode (including Full/strict) and origin certificate - renewal status from the owner control plane. Read-only HTTP 200 checks do not - prove these settings. -- Report the cause or owner-approved disposition for the failed - `akyldash-runner-restart.service`; the runner itself was active during the - latest read-only check. No restart or unit change is requested here. +The installer does not create credentials, SSH configuration, canary values, +registry access, or new sudo rules. The PR has not been installed, run on +Windows, or executed against production. Keep deployment disabled until the +owner records evidence for each gate above. diff --git a/docs/operations/ROLLBACK.md b/docs/operations/ROLLBACK.md index ec7d390..042efda 100644 --- a/docs/operations/ROLLBACK.md +++ b/docs/operations/ROLLBACK.md @@ -1,54 +1,34 @@ # Rollback -## Current status +The current rollback implementation is code only. PR #59 has not been merged, +installed, or run against the VPS. No current production release state or +external backup has been verified; production rollback is therefore not +available yet. -On 2026-10-25 the public `/review` endpoint and direct origin returned HTTP -200, but current containers, data/index state, and a verified backup remain -unknown. The repository rollback helper and installer are not confirmed -installed on the VPS. This document describes code-level procedures only. +After owner installation and separate-target restore validation, rollback is +an owner-controlled Windows-to-VPS session. The Windows client reads the exact +previous backup identity pinned in root-owned release state, validates the +saved archive and sidecar, then sends it over SSH. The VPS accepts the bytes +only when size and SHA-256 match that root-pinned identity. It verifies the +current deployment against release state, stops Compose, and streams a fresh +cold backup to Windows before changing either image reference. -Before a release, the owner must verify a cold backup whose recorded backend -and OpenSearch image references and image IDs match the current deployment, -and check data compatibility with the target and prior versions. The -owner-run `infra/deploy/deploy_release.py` verifies the manifest allowlist, -backup, current image IDs, and registry digests; serializes against rollback -using `/run/akyldash-deploy.lock`; atomically replaces both image refs; -and starts Compose with `--no-build`. It is not installed as a `codex` sudo -command and was not run on the VPS. +The rollback helper verifies deployment-file hashes, previous image refs and +image IDs, and that the fresh backup matches the current image IDs. It does not +restore application data, OpenSearch contents, or secrets. It uses the shared +deployment lock, atomically switches both image references, starts Compose +with `--no-build`, verifies running image IDs and the local `/review` health +route, then records the new release state. Failures attempt to restore the +pre-rollback references and services; unresolved recovery is recorded in a +root-owned journal and blocks subsequent release/rollback operations. -After a successful release, the owner can run the restricted rollback helper -with the exact verified backup recorded as the previous release: +The former `akyldash-rollback ` interface now fails closed and performs +no Docker operation. Local `/var/backups/akyldash` archives cannot authorize a +rollback. Legacy release states without a verified external `previous_backup` +identity also cannot authorize this rollback path. -```bash -sudo -n /usr/local/sbin/akyldash-rollback \ - /var/backups/akyldash/.tar.gz --data-compatible -``` - -The helper takes the same deployment lock, validates the selected archive -against the separately pinned previous refs and image IDs, verifies image -availability, makes and verifies a second cold backup, and switches both -protected image refs atomically. Digest references are never retagged; legacy -tag images are restored by image ID. Compose runs with `--no-build`, followed -by a check that both running container image IDs equal the selected restore -plan, followed by healthcheck and local HTTPS validation. A mismatch fails the -rollback, restores the prior references when they can be verified, and keeps a -secret-free recovery journal; it never records the expected IDs as if they -were running. A failed cutover or rollback blocks another release until an -owner resolves the journal. A legacy deployment without release state can still roll back -matching legacy tags, but digest rollback is refused until the state is -established by the reviewed release helper. - -It refuses if the current Compose/Caddyfile differs from the backup or the -backup's image records do not match release state. This does not restore data or -automatically undo a release with an unknown schema change. The application -has no formal migration framework; compatibility must be checked for every -change. If it is uncertain, stop and ask the owner. - -The initial owner-run deployment must record its running backend image ID in -`/opt/akyldash/deployed-image.txt` with mode `0600`; the rollback helper updates -that record after a successful rollback, and `infra/bootstrap/verify.sh` checks -it against the running container. - -Any data restore requires the owner, a verified pre-change backup, and a -maintenance window. Preserve the failed release and both backups until recovery -is confirmed. +The application has no formal migration framework. Check schema and index +compatibility before rollback. If compatibility is uncertain, stop; do not +attempt a data restore as part of an image rollback. A data restore requires a +separate owner-approved recovery plan and maintenance window. See +[backup and restore](BACKUP.md) and [deployment](DEPLOYMENT.md). diff --git a/infra/backup/archive.py b/infra/backup/archive.py index 8175fcc..dd3c227 100644 --- a/infra/backup/archive.py +++ b/infra/backup/archive.py @@ -17,6 +17,7 @@ import sys import tarfile import tempfile from pathlib import Path, PurePosixPath +from typing import BinaryIO COMPONENTS = { "data", @@ -68,7 +69,7 @@ def read_manifest(archive: tarfile.TarFile) -> dict: stream = archive.extractfile("manifest.json") if stream is None: raise ValueError("backup manifest is unreadable") - manifest = json.load(stream) + manifest = json.loads(stream.read().decode("utf-8"), object_pairs_hook=unique_json_object) components = manifest.get("components") if isinstance(manifest, dict) else None if ( not isinstance(manifest, dict) @@ -90,6 +91,15 @@ def read_manifest(archive: tarfile.TarFile) -> dict: return manifest +def unique_json_object(pairs: list[tuple[str, object]]) -> dict: + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"duplicate backup manifest field: {key}") + result[key] = value + return result + + def verify_archive(path: Path) -> dict: checksum_path = Path(f"{path}.sha256") expected = checksum_path.read_text(encoding="ascii").split()[0] @@ -99,6 +109,31 @@ def verify_archive(path: Path) -> dict: return read_manifest(archive) +def verify_external_archive(path: Path, *, expected_sha256: str, expected_manifest_sha256: str) -> dict: + if path.is_symlink() or not path.is_file(): + raise ValueError("external backup must be a regular file") + if not re.fullmatch(r"[0-9a-f]{64}", expected_sha256) or digest(path) != expected_sha256: + raise ValueError("external backup SHA-256 does not match the live session") + with tarfile.open(path, "r:gz") as archive: + manifest_member = next(member for member in checked_members(archive) if member.name == "manifest.json") + stream = archive.extractfile(manifest_member) + if stream is None: + raise ValueError("external backup manifest is unreadable") + manifest_bytes = stream.read(1024 * 1024 + 1) + manifest = read_manifest(archive) + canonical_manifest = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8") + if len(manifest_bytes) > 1024 * 1024 or hashlib.sha256(canonical_manifest).hexdigest() != expected_manifest_sha256: + raise ValueError("external backup manifest does not match the live session") + for member in archive.getmembers(): + if member.isfile(): + stream = archive.extractfile(member) + if stream is None: + raise ValueError(f"external backup member is unreadable: {member.name}") + while stream.read(1024 * 1024): + pass + return manifest + + def parse_sources(values: list[str], required: set[str] = COMPONENTS) -> dict[str, Path]: sources: dict[str, Path] = {} for value in values: @@ -277,43 +312,14 @@ def create_backup( for name in ("production-env", "review-secret"): if sources[name] is None or not sources[name].is_file(): raise ValueError(f"sensitive component must be a regular file: {name}") - if sources["data"] is not None and sources["data"].is_dir(): - check_sqlite(sources["data"]) - - manifest = { - "format": 1, - "created_at": dt.datetime.now(dt.timezone.utc).isoformat(), - "git_revision": revision, - "images": images or {}, - "deployment_files": deployment_files or {}, - "components": sorted(sources), - } + manifest = backup_manifest(sources, revision, images, deployment_files) with tempfile.NamedTemporaryFile(dir=parent, prefix=".akyldash-backup-", delete=False) as temp: temporary = Path(temp.name) os.chmod(temporary, 0o600) checksum_temp = Path(f"{temporary}.sha256") try: with tarfile.open(temporary, "w:gz") as archive: - encoded = json.dumps(manifest, sort_keys=True).encode("utf-8") - info = tarfile.TarInfo("manifest.json") - info.size = len(encoded) - info.mode = 0o600 - archive.addfile(info, io.BytesIO(encoded)) - for name, source in sorted(sources.items()): - if source is None: - info = tarfile.TarInfo(f"{name}/") - info.type = tarfile.DIRTYPE - info.mode = 0o700 - archive.addfile(info) - continue - def protect_secrets(member: tarfile.TarInfo) -> tarfile.TarInfo: - if name in {"production-env", "review-secret"}: - member.mode = 0o600 - if member.name.endswith((".sqlite3", ".sqlite3-wal", ".sqlite3-shm")): - member.mode = 0o600 - return member - - archive.add(source, arcname=name, recursive=True, filter=protect_secrets) + write_backup(archive, sources, manifest) with tarfile.open(temporary, "r:gz") as archive: read_manifest(archive) checksum_fd = os.open(checksum_temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) @@ -330,6 +336,65 @@ def create_backup( checksum_temp.unlink(missing_ok=True) +def backup_manifest( + sources: dict[str, Path | None], revision: str, images: dict | None, deployment_files: dict[str, str] | None +) -> dict: + for name, source in sources.items(): + if source is not None and (source.is_symlink() or not (source.is_dir() or source.is_file())): + raise ValueError(f"source must be a regular file or directory: {name}") + for name in ("production-env", "review-secret"): + if sources[name] is None or not sources[name].is_file(): + raise ValueError(f"sensitive component must be a regular file: {name}") + if sources["data"] is not None and sources["data"].is_dir(): + check_sqlite(sources["data"]) + return { + "format": 1, + "created_at": dt.datetime.now(dt.timezone.utc).isoformat(), + "git_revision": revision, + "images": images or {}, + "deployment_files": deployment_files or {}, + "components": sorted(sources), + } + + +def write_backup(archive: tarfile.TarFile, sources: dict[str, Path | None], manifest: dict) -> None: + encoded = json.dumps(manifest, sort_keys=True).encode("utf-8") + info = tarfile.TarInfo("manifest.json") + info.size = len(encoded) + info.mode = 0o600 + archive.addfile(info, io.BytesIO(encoded)) + for name, source in sorted(sources.items()): + if source is None: + info = tarfile.TarInfo(f"{name}/") + info.type = tarfile.DIRTYPE + info.mode = 0o700 + archive.addfile(info) + continue + + def protect_secrets(member: tarfile.TarInfo) -> tarfile.TarInfo: + if name in {"production-env", "review-secret"}: + member.mode = 0o600 + if member.name.endswith((".sqlite3", ".sqlite3-wal", ".sqlite3-shm")): + member.mode = 0o600 + return member + + archive.add(source, arcname=name, recursive=True, filter=protect_secrets) + + +def create_backup_stream( + output: BinaryIO, sources: dict[str, Path | None], revision: str, + images: dict | None = None, deployment_files: dict[str, str] | None = None, + manifest: dict | None = None, +) -> dict: + if os.geteuid() != 0: + raise ValueError("external production backup must run as root") + manifest = manifest or backup_manifest(sources, revision, images, deployment_files) + with tarfile.open(fileobj=output, mode="w|gz") as archive: + write_backup(archive, sources, manifest) + output.flush() + return manifest + + def restore_to_staging(backup: Path, target: Path) -> None: if not target.name.startswith("akyldash-restore-"): raise ValueError("restore target must be a new akyldash-restore-* staging directory") diff --git a/infra/backup/external_session.py b/infra/backup/external_session.py new file mode 100644 index 0000000..1513c06 --- /dev/null +++ b/infra/backup/external_session.py @@ -0,0 +1,338 @@ +"""Bounded binary protocol for one live owner-controlled external backup session.""" + +from __future__ import annotations + +import hashlib +import json +import re +import secrets +import struct +import datetime as dt +from typing import BinaryIO + +MAGIC = b"AKYL" +ACK_MAGIC = b"AKYA" +CHALLENGE_MAGIC = b"AKYB" +RESULT_MAGIC = b"AKYR" +VERSION = 1 +CHUNK_BYTES = 1024 * 1024 +MAX_CONTROL_BYTES = 64 * 1024 +MAX_ARCHIVE_BYTES = 100 * 1024**3 +BACKUP_ID_RE = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}\Z") +SHA256_RE = re.compile(r"[0-9a-f]{64}\Z") +NONCE_RE = re.compile(r"[0-9a-f]{64}\Z") + + +def nonce() -> str: + return secrets.token_hex(32) + + +def _json_frame(writer: BinaryIO, magic: bytes, value: dict) -> None: + payload = json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + if len(payload) > MAX_CONTROL_BYTES: + raise ValueError("external backup control message exceeds its size limit") + writer.write(magic + struct.pack("!I", len(payload)) + payload) + writer.flush() + + +def _read_exact(reader: BinaryIO, length: int) -> bytes: + parts = bytearray() + while len(parts) < length: + block = reader.read(length - len(parts)) + if not block: + raise ValueError("external backup session ended before a complete protocol frame") + parts.extend(block) + return bytes(parts) + + +def _read_json_frame(reader: BinaryIO, magic: bytes) -> dict: + if _read_exact(reader, len(magic)) != magic: + raise ValueError("external backup protocol version or frame type is invalid") + return _read_json_after_magic(reader) + + +def _read_json_after_magic(reader: BinaryIO) -> dict: + size = struct.unpack("!I", _read_exact(reader, 4))[0] + if size > MAX_CONTROL_BYTES: + raise ValueError("external backup control message exceeds its size limit") + try: + value = json.loads(_read_exact(reader, size), object_pairs_hook=_unique_object) + except (UnicodeError, json.JSONDecodeError) as error: + raise ValueError("external backup control message is invalid JSON") from error + if not isinstance(value, dict): + raise ValueError("external backup control message must be a JSON object") + return value + + +def _unique_object(pairs: list[tuple[str, object]]) -> dict: + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"duplicate external backup field: {key}") + result[key] = value + return result + + +def write_request(writer: BinaryIO, request: dict) -> None: + validate_request(request) + _json_frame(writer, MAGIC, request) + + +def read_request(reader: BinaryIO) -> dict: + request = _read_json_frame(reader, MAGIC) + validate_request(request) + return request + + +def validate_request(request: object) -> dict: + if (not isinstance(request, dict) or type(request.get("version")) is not int + or request["version"] != VERSION): + raise ValueError("external backup request has an unsupported version") + if request.get("action") == "release" and set(request) == { + "version", "action", "run_id", "commit", "descriptor_sha256" + }: + if (not isinstance(request["run_id"], str) or not request["run_id"].isdigit() + or not isinstance(request["commit"], str) or not re.fullmatch(r"[0-9a-f]{40}", request["commit"]) + or not isinstance(request["descriptor_sha256"], str) + or not SHA256_RE.fullmatch(request["descriptor_sha256"])): + raise ValueError("external deployment request identity is invalid") + return request + if request.get("action") == "rollback" and set(request) == { + "version", "action", "data_compatible" + } and request["data_compatible"] is True: + return request + raise ValueError("external deployment request has unexpected fields or action") + + +def read_header(reader: BinaryIO) -> dict: + header = _read_json_frame(reader, MAGIC) + return validate_header(header) + + +def validate_header(header: object) -> dict: + if not isinstance(header, dict): + raise ValueError("external backup header is invalid") + if set(header) != {"version", "nonce", "backup_id", "manifest", "manifest_sha256", "context"}: + raise ValueError("external backup header has unexpected fields") + if (type(header["version"]) is not int or header["version"] != VERSION + or not isinstance(header["nonce"], str) + or not NONCE_RE.fullmatch(header["nonce"]) or not isinstance(header["backup_id"], str) + or not BACKUP_ID_RE.fullmatch(header["backup_id"]) or not isinstance(header["manifest"], dict) + or not isinstance(header["manifest_sha256"], str) + or not SHA256_RE.fullmatch(header["manifest_sha256"])): + raise ValueError("external backup header is invalid") + canonical = json.dumps(header["manifest"], sort_keys=True, separators=(",", ":")).encode("utf-8") + if hashlib.sha256(canonical).hexdigest() != header["manifest_sha256"]: + raise ValueError("external backup manifest identity does not match its header") + if not isinstance(header["context"], dict): + raise ValueError("external backup context is invalid") + return header + + +def read_response(reader: BinaryIO) -> tuple[str, dict]: + magic = _read_exact(reader, 4) + value = _read_json_after_magic(reader) if magic in {MAGIC, RESULT_MAGIC} else None + if magic == MAGIC: + return "header", validate_header(value) + if magic == RESULT_MAGIC: + result = value + if (set(result) != {"version", "status", "message"} or type(result["version"]) is not int + or result["version"] != VERSION + or result["status"] not in {"success", "error"} or not isinstance(result["message"], str)): + raise ValueError("external backup final result is invalid") + return "result", result + raise ValueError("external deployment response frame is invalid") + + +def write_header(writer: BinaryIO, *, session_nonce: str, backup_id: str, manifest: dict, + context: dict | None = None) -> str: + if not NONCE_RE.fullmatch(session_nonce) or not BACKUP_ID_RE.fullmatch(backup_id): + raise ValueError("external backup session identity is invalid") + manifest_bytes = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8") + manifest_sha256 = hashlib.sha256(manifest_bytes).hexdigest() + _json_frame(writer, MAGIC, { + "version": VERSION, + "nonce": session_nonce, + "backup_id": backup_id, + "manifest": manifest, + "manifest_sha256": manifest_sha256, + "context": context or {}, + }) + return manifest_sha256 + + +class ArchiveFrameWriter: + def __init__(self, writer: BinaryIO, *, maximum: int = MAX_ARCHIVE_BYTES): + self.writer = writer + self.maximum = maximum + self.size = 0 + self.digest = hashlib.sha256() + self.buffer = bytearray() + self.closed = False + + def write(self, data: bytes) -> int: + if self.closed: + raise ValueError("external backup stream is already closed") + self.size += len(data) + if self.size > self.maximum: + raise ValueError("external backup archive exceeds its size limit") + self.digest.update(data) + remaining = memoryview(data) + while remaining: + take = min(CHUNK_BYTES - len(self.buffer), len(remaining)) + self.buffer.extend(remaining[:take]) + remaining = remaining[take:] + if len(self.buffer) == CHUNK_BYTES: + self._flush_chunk(CHUNK_BYTES) + return len(data) + + def _flush_chunk(self, size: int) -> None: + block = bytes(self.buffer[:size]) + del self.buffer[:size] + self.writer.write(struct.pack("!I", len(block))) + self.writer.write(block) + + def finish(self) -> tuple[int, str]: + if self.closed: + raise ValueError("external backup stream is already closed") + if self.buffer: + self._flush_chunk(len(self.buffer)) + digest = self.digest.hexdigest() + self.writer.write(struct.pack("!I", 0) + struct.pack("!Q", self.size) + bytes.fromhex(digest)) + self.writer.flush() + self.closed = True + return self.size, digest + + +def receive_archive(reader: BinaryIO, output: BinaryIO, *, maximum: int = MAX_ARCHIVE_BYTES) -> tuple[int, str]: + digest = hashlib.sha256() + size = 0 + while True: + length = struct.unpack("!I", _read_exact(reader, 4))[0] + if length == 0: + expected_size = struct.unpack("!Q", _read_exact(reader, 8))[0] + expected_digest = _read_exact(reader, 32).hex() + break + if length > CHUNK_BYTES or size + length > maximum: + raise ValueError("external backup archive frame exceeds its size limit") + chunk = _read_exact(reader, length) + output.write(chunk) + digest.update(chunk) + size += length + output.flush() + actual_digest = digest.hexdigest() + if size != expected_size or actual_digest != expected_digest: + raise ValueError("external backup byte count or SHA-256 does not match its stream trailer") + return size, actual_digest + + +def write_ack(writer: BinaryIO, *, session_nonce: str, backup_id: str, size: int, + archive_sha256: str, manifest_sha256: str, verified: bool) -> None: + if (not NONCE_RE.fullmatch(session_nonce) or not BACKUP_ID_RE.fullmatch(backup_id) + or type(size) is not int or not 0 < size <= MAX_ARCHIVE_BYTES + or not SHA256_RE.fullmatch(archive_sha256) or not SHA256_RE.fullmatch(manifest_sha256) + or verified is not True): + raise ValueError("external backup acknowledgement is invalid") + _json_frame(writer, ACK_MAGIC, { + "version": VERSION, + "nonce": session_nonce, + "backup_id": backup_id, + "size": size, + "archive_sha256": archive_sha256, + "manifest_sha256": manifest_sha256, + "verified": verified, + }) + + +def write_challenge(writer: BinaryIO, identity: dict, *, session_nonce: str) -> None: + if (not NONCE_RE.fullmatch(session_nonce) or not isinstance(identity, dict) + or set(identity) != {"backup_id", "size", "archive_sha256", "manifest_sha256", "manifest"}): + raise ValueError("external rollback challenge is invalid") + if (not isinstance(identity["backup_id"], str) or not BACKUP_ID_RE.fullmatch(identity["backup_id"]) + or type(identity["size"]) is not int or not 0 < identity["size"] <= MAX_ARCHIVE_BYTES + or not isinstance(identity["archive_sha256"], str) or not SHA256_RE.fullmatch(identity["archive_sha256"]) + or not isinstance(identity["manifest_sha256"], str) or not SHA256_RE.fullmatch(identity["manifest_sha256"]) + or not isinstance(identity["manifest"], dict)): + raise ValueError("external rollback backup identity is invalid") + canonical = json.dumps(identity["manifest"], sort_keys=True, separators=(",", ":")).encode("utf-8") + if hashlib.sha256(canonical).hexdigest() != identity["manifest_sha256"]: + raise ValueError("external rollback manifest identity is inconsistent") + _json_frame(writer, CHALLENGE_MAGIC, {"version": VERSION, "nonce": session_nonce, **identity}) + + +def read_challenge(reader: BinaryIO) -> dict: + value = _read_json_frame(reader, CHALLENGE_MAGIC) + if (set(value) != {"version", "nonce", "backup_id", "size", "archive_sha256", "manifest_sha256", "manifest"} + or type(value["version"]) is not int or value["version"] != VERSION + or not isinstance(value["nonce"], str) + or not NONCE_RE.fullmatch(value["nonce"]) or not isinstance(value["backup_id"], str) + or not BACKUP_ID_RE.fullmatch(value["backup_id"]) or type(value["size"]) is not int + or not 0 < value["size"] <= MAX_ARCHIVE_BYTES + or not isinstance(value["archive_sha256"], str) or not SHA256_RE.fullmatch(value["archive_sha256"]) + or not isinstance(value["manifest_sha256"], str) or not SHA256_RE.fullmatch(value["manifest_sha256"]) + or not isinstance(value["manifest"], dict)): + raise ValueError("external rollback challenge is invalid") + canonical = json.dumps(value["manifest"], sort_keys=True, separators=(",", ":")).encode("utf-8") + if hashlib.sha256(canonical).hexdigest() != value["manifest_sha256"]: + raise ValueError("external rollback challenge manifest identity is inconsistent") + return value + + +def read_ack(reader: BinaryIO, *, session_nonce: str, backup_id: str, size: int, + archive_sha256: str, manifest_sha256: str) -> dict: + ack = _read_json_frame(reader, ACK_MAGIC) + if (set(ack) != {"version", "nonce", "backup_id", "size", "archive_sha256", "manifest_sha256", "verified"} + or type(ack.get("version")) is not int or type(ack.get("size")) is not int + or ack.get("verified") is not True): + raise ValueError("external backup acknowledgement is invalid") + expected = { + "version": VERSION, "nonce": session_nonce, "backup_id": backup_id, + "size": size, "archive_sha256": archive_sha256, + "manifest_sha256": manifest_sha256, "verified": True, + } + if ack != expected: + raise ValueError("external backup acknowledgement does not match this live session") + return ack + + +def write_result(writer: BinaryIO, *, status: str, message: str = "") -> None: + if status not in {"success", "error"} or len(message.encode("utf-8")) > 4096: + raise ValueError("external backup result is invalid") + _json_frame(writer, RESULT_MAGIC, {"version": VERSION, "status": status, "message": message}) + + +def read_result(reader: BinaryIO) -> dict: + result = _read_json_frame(reader, RESULT_MAGIC) + if (set(result) != {"version", "status", "message"} or type(result["version"]) is not int + or result["version"] != VERSION or result["status"] not in {"success", "error"} + or not isinstance(result["message"], str)): + raise ValueError("external backup final result is invalid") + return result + + +def send_backup_session(writer: BinaryIO, reader: BinaryIO, *, sources: dict, revision: str, + images: dict, deployment_files: dict[str, str], context: dict) -> dict: + from archive import backup_manifest, create_backup_stream + + manifest = backup_manifest(sources, revision, images, deployment_files) + session_nonce = nonce() + backup_id = "akyldash-" + dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + session_nonce[:8] + manifest_sha256 = write_header( + writer, session_nonce=session_nonce, backup_id=backup_id, manifest=manifest, context=context + ) + framed = ArchiveFrameWriter(writer) + create_backup_stream( + framed, sources, revision, images, deployment_files, manifest=manifest + ) + size, archive_sha256 = framed.finish() + read_ack( + reader, session_nonce=session_nonce, backup_id=backup_id, size=size, + archive_sha256=archive_sha256, manifest_sha256=manifest_sha256, + ) + return { + "backup_id": backup_id, + "archive_sha256": archive_sha256, + "manifest_sha256": manifest_sha256, + "size": size, + "manifest": manifest, + } diff --git a/infra/backup/receive_external.py b/infra/backup/receive_external.py new file mode 100644 index 0000000..9ff1bc3 --- /dev/null +++ b/infra/backup/receive_external.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python3 +"""Receive and verify one cold backup from the fixed owner SSH session to D:.""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +import tempfile +import threading +from pathlib import Path + +from archive import verify_external_archive +from external_session import (ArchiveFrameWriter, read_challenge, read_response, read_result, + receive_archive, write_ack, write_request) + +DEFAULT_REPOSITORY = Path(r"D:\Dev\akyldash") +MAX_ERROR_BYTES = 8192 + + +def _reparse(path: Path) -> bool: + if path.is_symlink(): + return True + try: + return bool(path.stat().st_file_attributes & 0x400) + except AttributeError: + return False + except FileNotFoundError: + return False + + +def check_private_acl(path: Path) -> None: + command = r""" +$ErrorActionPreference = 'Stop' +$acl = Get-Acl -LiteralPath $env:AKYLDASH_ACL_PATH +$drive = ([System.IO.Path]::GetPathRoot($env:AKYLDASH_ACL_PATH)).Substring(0,1) +$volume = Get-Volume -DriveLetter $drive +if ($volume.FileSystem -ne 'NTFS') { exit 5 } +$owner = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value +$allowed = @($owner, 'S-1-5-18', 'S-1-5-32-544') +$ownerAllowed = $false +foreach ($rule in $acl.Access) { + $sid = $rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value + if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow -or $sid -notin $allowed) { exit 2 } + if (($rule.FileSystemRights -band [System.Security.AccessControl.FileSystemRights]::FullControl) -ne [System.Security.AccessControl.FileSystemRights]::FullControl) { exit 3 } + if ($sid -eq $owner) { $ownerAllowed = $true } +} +if (-not $ownerAllowed) { exit 4 } +""" + environment = { + "SystemRoot": os.environ.get("SystemRoot", r"C:\Windows"), + "AKYLDASH_ACL_PATH": str(path), + } + result = subprocess.run( + ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", command], + env=environment, text=True, capture_output=True, + ) + if result.returncode: + raise ValueError(f"backup path ACL is not private (PowerShell status {result.returncode})") + + +def check_repository_target(repository: Path, backup_id: str, *, allow_existing: bool = False) -> tuple[Path, Path]: + if not repository.is_absolute() or not repository.is_dir() or _reparse(repository): + raise ValueError("repository must be an existing real directory on the selected Windows volume") + if os.name == "nt" and repository.drive.upper() != "D:": + raise ValueError("external backup destination is restricted to D:\\Dev\\akyldash") + if os.name == "nt" and repository.resolve().as_posix().lower() != "d:/dev/akyldash": + raise ValueError("external backup destination is restricted to D:\\Dev\\akyldash") + for parent in repository.parents: + if _reparse(parent): + raise ValueError("backup destination has a reparse-point parent") + git_dir = subprocess.run( + ["git", "-C", str(repository), "rev-parse", "--absolute-git-dir"], + check=True, text=True, capture_output=True, + ).stdout.strip() + exclude = Path(git_dir) / "info" / "exclude" + if _reparse(exclude) or not exclude.is_file(): + raise ValueError("the repository's local .git/info/exclude file is unavailable or unsafe") + root = repository / ".backups" + final = root / backup_id + target_file = final / "backup.tar.gz" + relative = target_file.relative_to(repository).as_posix() + result = subprocess.run( + ["git", "-C", str(repository), "check-ignore", "--no-index", "-v", "--", relative], + text=True, capture_output=True, + ) + if result.returncode: + raise ValueError("the exact D: backup target is not ignored by local Git metadata") + try: + source, _line, pattern = result.stdout.split("\t", 1)[0].rsplit(":", 2) + except ValueError as error: + raise ValueError("git check-ignore returned an unrecognized source record") from error + source_path = Path(source) + if not source_path.is_absolute(): + source_path = repository / source_path + if source_path.resolve() != exclude.resolve() or pattern != "/.backups/": + raise ValueError("the exact D: backup target must be ignored by .git/info/exclude") + if root.exists(): + if _reparse(root) or not root.is_dir(): + raise ValueError("D: backup root must be a real directory") + else: + root.mkdir() + check_private_acl(root) + if final.exists() or _reparse(final): + if not allow_existing or _reparse(final) or not final.is_dir(): + raise ValueError("backup ID already exists or resolves through a reparse point") + elif allow_existing: + raise ValueError("the pinned external backup is missing from D:") + return root, final + + +def open_previous_backup(repository: Path, challenge: dict) -> Path: + _root, directory = check_repository_target(repository, challenge["backup_id"], allow_existing=True) + check_private_acl(directory) + archive_path = directory / "backup.tar.gz" + sidecar = directory / "backup.tar.gz.sha256" + for path in (archive_path, sidecar): + if _reparse(path) or not path.is_file(): + raise ValueError("pinned external backup files must be regular files") + check_private_acl(path) + if archive_path.stat().st_size != challenge["size"]: + raise ValueError("pinned external backup size does not match root-owned release state") + expected_sidecar = f"{challenge['archive_sha256']} backup.tar.gz\n" + if sidecar.read_text(encoding="ascii") != expected_sidecar: + raise ValueError("pinned external backup checksum sidecar does not match root-owned release state") + manifest = verify_external_archive( + archive_path, + expected_sha256=challenge["archive_sha256"], + expected_manifest_sha256=challenge["manifest_sha256"], + ) + if manifest != challenge["manifest"]: + raise ValueError("pinned external backup contents differ from root-owned release state") + return archive_path + + +def _drain_stderr(stream, output: bytearray) -> None: + while True: + chunk = stream.read(1024) + if not chunk: + return + if len(output) < MAX_ERROR_BYTES: + output.extend(chunk[: MAX_ERROR_BYTES - len(output)]) + + +def receive_backup(reader, writer, *, repository: Path, request: dict, expected_context: dict | None = None) -> dict: + frame, value = read_response(reader) + if frame == "result": + raise ValueError(value["message"] or "remote deploy preflight failed") + header = value + context = header["context"] + if request["action"] == "release": + expected_context = {key: request[key] for key in ("action", "run_id", "commit", "descriptor_sha256")} + if context != expected_context: + raise ValueError("source backup session does not match the requested release tuple") + elif expected_context is None or context != expected_context: + raise ValueError("rollback backup session does not match the pinned previous backup") + + root, final = check_repository_target(repository, header["backup_id"]) + staging = Path(tempfile.mkdtemp(prefix=".staging-", dir=root)) + try: + check_private_acl(staging) + archive_path = staging / "backup.tar.gz" + with archive_path.open("xb") as archive_file: + size, archive_sha256 = receive_archive(reader, archive_file) + archive_file.flush() + os.fsync(archive_file.fileno()) + os.chmod(archive_path, 0o600) + check_private_acl(archive_path) + manifest = verify_external_archive( + archive_path, + expected_sha256=archive_sha256, + expected_manifest_sha256=header["manifest_sha256"], + ) + if manifest != header["manifest"]: + raise ValueError("saved backup contents differ from the source-generated session manifest") + sidecar = staging / "backup.tar.gz.sha256" + with sidecar.open("x", encoding="ascii", newline="\n") as stream: + stream.write(f"{archive_sha256} backup.tar.gz\n") + stream.flush() + os.fsync(stream.fileno()) + os.chmod(sidecar, 0o600) + check_private_acl(sidecar) + os.rename(staging, final) + write_ack( + writer, session_nonce=header["nonce"], backup_id=header["backup_id"], size=size, + archive_sha256=archive_sha256, manifest_sha256=header["manifest_sha256"], verified=True, + ) + return {"backup_id": header["backup_id"], "archive_sha256": archive_sha256, "size": size} + except Exception: + if staging.exists(): + shutil.rmtree(staging) + raise + + +def run_release(request: dict, *, repository: Path = DEFAULT_REPOSITORY, ssh: str = "ssh", + ssh_alias: str = "akyldash_vps") -> None: + if shutil.which(ssh) is None: + raise ValueError("OpenSSH client is unavailable") + if not ssh_alias or any(character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-" for character in ssh_alias): + raise ValueError("SSH alias must name an existing owner-controlled host entry") + process = subprocess.Popen( + [ssh, "-T", ssh_alias, "/usr/local/sbin/akyldash-release-deploy"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + ) + errors = bytearray() + thread = threading.Thread(target=_drain_stderr, args=(process.stderr, errors), daemon=True) + thread.start() + try: + write_request(process.stdin, request) + process.stdin.flush() + saved = receive_backup(process.stdout, process.stdin, repository=repository, request=request) + final = read_result(process.stdout) + if process.stdout.read(1): + raise ValueError("unexpected trailing bytes after external deployment result") + process.stdin.close() + return_code = process.wait() + thread.join() + if return_code or final["status"] != "success": + message = final.get("message", "remote deployment failed") + raise ValueError(f"remote deployment failed (ssh status {return_code}): {message}") + print(f"PASS release completed; verified external backup {saved['backup_id']} ({saved['size']} bytes)") + except Exception: + if process.poll() is None: + process.kill() + process.wait() + thread.join() + raise + + +def run_rollback(*, repository: Path = DEFAULT_REPOSITORY, ssh: str = "ssh", + ssh_alias: str = "akyldash_vps") -> None: + if shutil.which(ssh) is None: + raise ValueError("OpenSSH client is unavailable") + if not ssh_alias or any(character not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-" for character in ssh_alias): + raise ValueError("SSH alias must name an existing owner-controlled host entry") + process = subprocess.Popen( + [ssh, "-T", ssh_alias, "/usr/local/sbin/akyldash-release-rollback"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + ) + errors = bytearray() + thread = threading.Thread(target=_drain_stderr, args=(process.stderr, errors), daemon=True) + thread.start() + request = {"version": 1, "action": "rollback", "data_compatible": True} + try: + write_request(process.stdin, request) + process.stdin.flush() + challenge = read_challenge(process.stdout) + archive_path = open_previous_backup(repository, challenge) + framed = ArchiveFrameWriter(process.stdin, maximum=challenge["size"]) + with archive_path.open("rb") as archive_file: + for chunk in iter(lambda: archive_file.read(1024 * 1024), b""): + framed.write(chunk) + size, digest = framed.finish() + if size != challenge["size"] or digest != challenge["archive_sha256"]: + raise ValueError("D: previous backup changed during the live rollback session") + write_ack(process.stdin, session_nonce=challenge["nonce"], backup_id=challenge["backup_id"], + size=size, archive_sha256=digest, manifest_sha256=challenge["manifest_sha256"], verified=True) + receive_backup(process.stdout, process.stdin, repository=repository, request=request, + expected_context={key: challenge[key] for key in + ("backup_id", "archive_sha256", "manifest_sha256")} | {"action": "rollback"}) + final = read_result(process.stdout) + if process.stdout.read(1): + raise ValueError("unexpected trailing bytes after external rollback result") + process.stdin.close() + return_code = process.wait() + thread.join() + if return_code or final["status"] != "success": + raise ValueError(f"remote rollback failed (ssh status {return_code}): {final.get('message', 'error')}") + print(f"PASS rollback completed; fresh external backup saved for {challenge['backup_id']}") + except Exception: + if process.poll() is None: + process.kill() + process.wait() + thread.join() + raise + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--rollback", action="store_true") + parser.add_argument("--data-compatible", action="store_true") + parser.add_argument("--run-id") + parser.add_argument("--commit") + parser.add_argument("--descriptor-sha256") + parser.add_argument("--ssh-alias", default="akyldash_vps") + args = parser.parse_args() + try: + if 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) + else: + if not args.run_id or not args.commit or not args.descriptor_sha256 or args.data_compatible: + raise ValueError("release requires --run-id, --commit, and --descriptor-sha256") + request = { + "version": 1, "action": "release", "run_id": args.run_id, + "commit": args.commit, "descriptor_sha256": args.descriptor_sha256, + } + run_release(request, ssh_alias=args.ssh_alias) + except (OSError, ValueError, subprocess.SubprocessError, json.JSONDecodeError) as error: + print(f"ERROR: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/infra/backup/test_archive.py b/infra/backup/test_archive.py index 837c698..2488054 100644 --- a/infra/backup/test_archive.py +++ b/infra/backup/test_archive.py @@ -1,4 +1,5 @@ import hashlib +import io import json import sqlite3 import tarfile @@ -8,7 +9,7 @@ from pathlib import Path from types import SimpleNamespace from unittest.mock import patch -from archive import COMPONENTS, compose_sources, create_backup, restore_to_staging, verify_archive +from archive import COMPONENTS, compose_sources, create_backup, create_backup_stream, restore_to_staging, verify_archive, verify_external_archive class BackupArchiveTests(unittest.TestCase): @@ -50,6 +51,39 @@ class BackupArchiveTests(unittest.TestCase): self.assertEqual((target / "review-secret").stat().st_mode & 0o777, 0o600) self.assertEqual(verify_archive(self.backup)["components"], sorted(COMPONENTS)) + def test_external_stream_uses_no_local_archive_and_verifies_received_bytes(self): + stream = io.BytesIO() + with patch("archive.os.geteuid", return_value=0): + manifest = create_backup_stream(stream, self.sources, "a" * 40) + self.assertFalse(self.backup.exists()) + received = self.private / "received.tar.gz" + received.write_bytes(stream.getvalue()) + verified = verify_external_archive( + received, + expected_sha256=hashlib.sha256(stream.getvalue()).hexdigest(), + expected_manifest_sha256=hashlib.sha256( + json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest(), + ) + self.assertEqual(verified["git_revision"], "a" * 40) + + def test_external_archive_rejects_changed_manifest_and_duplicate_keys(self): + stream = io.BytesIO() + with tarfile.open(fileobj=stream, mode="w:gz") as archive: + info = tarfile.TarInfo("manifest.json") + raw = b'{"format":1,"format":1,"components":[],"images":{},"deployment_files":{}}' + info.size = len(raw) + archive.addfile(info, io.BytesIO(raw)) + for name in COMPONENTS: + info = tarfile.TarInfo(name + "/") + info.type = tarfile.DIRTYPE + archive.addfile(info) + received = self.private / "duplicate.tar.gz" + received.write_bytes(stream.getvalue()) + with self.assertRaisesRegex(ValueError, "duplicate backup manifest"): + verify_external_archive(received, expected_sha256=hashlib.sha256(stream.getvalue()).hexdigest(), + expected_manifest_sha256="0" * 64) + def test_rejects_checksum_mismatch_without_creating_staging(self): create_backup(self.backup, self.sources, "abc123") self.backup.write_bytes(self.backup.read_bytes() + b"tamper") diff --git a/infra/backup/test_external_session.py b/infra/backup/test_external_session.py new file mode 100644 index 0000000..1cb41e7 --- /dev/null +++ b/infra/backup/test_external_session.py @@ -0,0 +1,139 @@ +import hashlib +import io +import json +import struct +import unittest + +from external_session import ( + ArchiveFrameWriter, CHUNK_BYTES, read_ack, read_challenge, read_header, read_request, read_result, + receive_archive, write_ack, write_challenge, write_header, write_request, write_result, +) +from external_session import ACK_MAGIC, MAGIC + + +class ExternalSessionTests(unittest.TestCase): + def setUp(self): + self.nonce = "a" * 64 + self.backup_id = "backup-20261031T120000Z" + self.manifest = {"format": 1, "git_revision": "b" * 40, "images": {}} + + def make_stream(self, payload=b"tar\x00bytes" * 100): + stream = io.BytesIO() + manifest_sha = write_header( + stream, session_nonce=self.nonce, backup_id=self.backup_id, manifest=self.manifest + ) + framed = ArchiveFrameWriter(stream, maximum=4096) + framed.write(payload[:37]) + framed.write(payload[37:]) + size, digest = framed.finish() + stream.seek(0) + return stream, payload, manifest_sha, size, digest + + def test_binary_archive_round_trip_and_live_ack_binding(self): + stream, payload, manifest_sha, size, digest = self.make_stream() + header = read_header(stream) + target = io.BytesIO() + self.assertEqual(receive_archive(stream, target, maximum=4096), (size, digest)) + self.assertEqual(target.getvalue(), payload) + self.assertEqual(hashlib.sha256(payload).hexdigest(), digest) + + ack = io.BytesIO() + write_ack(ack, session_nonce=self.nonce, backup_id=self.backup_id, + size=size, archive_sha256=digest, manifest_sha256=manifest_sha, verified=True) + ack.seek(0) + self.assertEqual(read_ack( + ack, session_nonce=header["nonce"], backup_id=header["backup_id"], size=size, + archive_sha256=digest, manifest_sha256=manifest_sha, + )["verified"], True) + + def test_single_large_write_is_split_into_bounded_frames(self): + payload = b"x" * (CHUNK_BYTES * 2 + 13) + stream = io.BytesIO() + writer = ArchiveFrameWriter(stream) + writer.write(payload) + size, digest = writer.finish() + stream.seek(0) + target = io.BytesIO() + self.assertEqual(receive_archive(stream, target), (size, digest)) + self.assertEqual(target.getvalue(), payload) + + def test_rejects_wrong_nonce_replay_and_unverified_ack(self): + stream, _payload, manifest_sha, size, digest = self.make_stream() + ack = io.BytesIO() + write_ack(ack, session_nonce="c" * 64, backup_id=self.backup_id, + size=size, archive_sha256=digest, manifest_sha256=manifest_sha, verified=True) + ack.seek(0) + with self.assertRaisesRegex(ValueError, "does not match"): + read_ack(ack, session_nonce=self.nonce, backup_id=self.backup_id, size=size, + archive_sha256=digest, manifest_sha256=manifest_sha) + + def test_rejects_corrupt_digest_truncated_stream_and_oversized_chunk(self): + stream, _payload, _manifest_sha, _size, _digest = self.make_stream() + read_header(stream) + corrupted = bytearray(stream.getvalue()) + corrupted[-1] ^= 1 + corrupted_stream = io.BytesIO(corrupted) + read_header(corrupted_stream) + with self.assertRaisesRegex(ValueError, "SHA-256"): + receive_archive(corrupted_stream, io.BytesIO(), maximum=4096) + truncated = io.BytesIO(stream.getvalue()[:-3]) + read_header(truncated) + with self.assertRaisesRegex(ValueError, "ended before"): + receive_archive(truncated, io.BytesIO(), maximum=4096) + with self.assertRaisesRegex(ValueError, "size limit"): + receive_archive(io.BytesIO(b"\x00\x10\x00\x01"), io.BytesIO(), maximum=4096) + + def test_final_result_is_bounded_and_typed(self): + stream = io.BytesIO() + write_result(stream, status="error", message="backup verification failed") + stream.seek(0) + self.assertEqual(read_result(stream)["status"], "error") + with self.assertRaisesRegex(ValueError, "invalid"): + write_result(io.BytesIO(), status="maybe") + + def test_rollback_challenge_pins_external_archive_identity(self): + identity = { + "backup_id": self.backup_id, "size": 128, "archive_sha256": "c" * 64, + "manifest_sha256": hashlib.sha256( + json.dumps(self.manifest, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest(), "manifest": self.manifest, + } + stream = io.BytesIO() + write_challenge(stream, identity, session_nonce=self.nonce) + stream.seek(0) + self.assertEqual(read_challenge(stream), {"version": 1, "nonce": self.nonce, **identity}) + identity["size"] = 0 + with self.assertRaisesRegex(ValueError, "identity"): + write_challenge(io.BytesIO(), identity, session_nonce=self.nonce) + + def test_release_request_is_strictly_typed_and_rejects_extra_commands(self): + request = { + "version": 1, "action": "release", "run_id": "301", "commit": "b" * 40, + "descriptor_sha256": "c" * 64, + } + stream = io.BytesIO() + write_request(stream, request) + stream.seek(0) + self.assertEqual(read_request(stream), request) + with self.assertRaisesRegex(ValueError, "unexpected fields"): + write_request(io.BytesIO(), request | {"shell": "id"}) + + def test_protocol_rejects_boolean_integers_and_non_boolean_ack(self): + payload = json.dumps({"version": True, "action": "rollback", "data_compatible": True}).encode() + request = io.BytesIO(MAGIC + struct.pack("!I", len(payload)) + payload) + with self.assertRaisesRegex(ValueError, "unsupported version"): + read_request(request) + ack_value = { + "version": 1, "nonce": self.nonce, "backup_id": self.backup_id, + "size": 128, "archive_sha256": "c" * 64, + "manifest_sha256": "d" * 64, "verified": 1, + } + payload = json.dumps(ack_value).encode() + ack = io.BytesIO(ACK_MAGIC + struct.pack("!I", len(payload)) + payload) + with self.assertRaisesRegex(ValueError, "acknowledgement is invalid"): + read_ack(ack, session_nonce=self.nonce, backup_id=self.backup_id, size=128, + archive_sha256="c" * 64, manifest_sha256="d" * 64) + + +if __name__ == "__main__": + unittest.main() diff --git a/infra/backup/test_receive_external.py b/infra/backup/test_receive_external.py new file mode 100644 index 0000000..4294427 --- /dev/null +++ b/infra/backup/test_receive_external.py @@ -0,0 +1,136 @@ +import io +import json +import tarfile +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import receive_external +from archive import COMPONENTS +from external_session import ArchiveFrameWriter, read_ack, write_header + + +class ExternalReceiverTests(unittest.TestCase): + def setUp(self): + self.request = { + "version": 1, "action": "release", "run_id": "301", "commit": "a" * 40, + "descriptor_sha256": "b" * 64, + } + self.manifest = { + "format": 1, "created_at": "2026-10-31T12:00:00+00:00", "git_revision": "c" * 40, + "images": {"backend": {"configured": "backend:old", "image_id": "sha256:" + "d" * 64}}, + "deployment_files": {"deploy/production/compose.yaml": "e" * 64}, + "components": sorted(COMPONENTS), + } + + def source_stream(self, context=None): + archive_stream = io.BytesIO() + with tarfile.open(fileobj=archive_stream, mode="w:gz") as archive: + manifest_bytes = json.dumps(self.manifest, sort_keys=True).encode("utf-8") + member = tarfile.TarInfo("manifest.json") + member.size = len(manifest_bytes) + archive.addfile(member, io.BytesIO(manifest_bytes)) + for component in COMPONENTS: + member = tarfile.TarInfo(component + "/") + member.type = tarfile.DIRTYPE + archive.addfile(member) + payload = archive_stream.getvalue() + stream = io.BytesIO() + manifest_sha = write_header( + stream, session_nonce="f" * 64, backup_id="backup-20261031T120000Z", + manifest=self.manifest, + context=context or {key: self.request[key] for key in ("action", "run_id", "commit", "descriptor_sha256")}, + ) + framed = ArchiveFrameWriter(stream) + framed.write(payload) + size, digest = framed.finish() + stream.seek(0) + return stream, manifest_sha, size, digest + + def test_verified_archive_is_atomically_published_before_ack(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + final = root / "backup-20261031T120000Z" + stream, manifest_sha, size, digest = self.source_stream() + ack = io.BytesIO() + with patch.object(receive_external, "check_repository_target", return_value=(root, final)), \ + patch.object(receive_external, "check_private_acl"): + result = receive_external.receive_backup( + stream, ack, repository=root, request=self.request + ) + self.assertEqual(result, {"backup_id": final.name, "archive_sha256": digest, "size": size}) + self.assertTrue((final / "backup.tar.gz").is_file()) + self.assertEqual((final / "backup.tar.gz").stat().st_mode & 0o777, 0o600) + self.assertEqual((final / "backup.tar.gz.sha256").read_text(), f"{digest} backup.tar.gz\n") + ack.seek(0) + self.assertTrue(read_ack( + ack, session_nonce="f" * 64, backup_id=final.name, size=size, + archive_sha256=digest, manifest_sha256=manifest_sha, + )["verified"]) + + def test_mismatched_release_binding_never_publishes_or_acks(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + final = root / "backup-20261031T120000Z" + stream, _manifest_sha, _size, _digest = self.source_stream( + context={"action": "release", "run_id": "999", "commit": "a" * 40, + "descriptor_sha256": "b" * 64} + ) + ack = io.BytesIO() + with patch.object(receive_external, "check_repository_target", return_value=(root, final)), \ + patch.object(receive_external, "check_private_acl"): + with self.assertRaisesRegex(ValueError, "does not match"): + receive_external.receive_backup(stream, ack, repository=root, request=self.request) + self.assertFalse(final.exists()) + self.assertEqual(ack.getvalue(), b"") + + def test_invalid_saved_stream_is_removed_without_publication(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + final = root / "backup-20261031T120000Z" + stream, _manifest_sha, _size, _digest = self.source_stream() + raw = bytearray(stream.getvalue()) + raw[-1] ^= 1 + ack = io.BytesIO() + with patch.object(receive_external, "check_repository_target", return_value=(root, final)), \ + patch.object(receive_external, "check_private_acl"): + with self.assertRaisesRegex(ValueError, "SHA-256"): + receive_external.receive_backup(io.BytesIO(raw), ack, repository=root, request=self.request) + self.assertFalse(final.exists()) + self.assertEqual(list(root.iterdir()), []) + self.assertEqual(ack.getvalue(), b"") + + def test_target_requires_exact_local_git_exclude_rule(self): + with tempfile.TemporaryDirectory() as directory: + repository = Path(directory) + exclude = repository / ".git/info/exclude" + exclude.parent.mkdir(parents=True) + exclude.write_text("/.backups/\n", encoding="utf-8") + responses = [ + type("Result", (), {"stdout": str(repository / ".git"), "returncode": 0})(), + type("Result", (), { + "stdout": f"{exclude}:1:/.backups/\t.backups/backup-id/backup.tar.gz\n", + "returncode": 0, + })(), + ] + with patch.object(receive_external.subprocess, "run", side_effect=responses), \ + patch.object(receive_external, "check_private_acl"): + root, final = receive_external.check_repository_target( + repository, "backup-id" + ) + self.assertEqual(root, repository / ".backups") + self.assertEqual(final, root / "backup-id") + + def test_windows_acl_probe_does_not_inherit_credentials(self): + result = type("Result", (), {"returncode": 0})() + with patch.dict("os.environ", {"GITEA_TOKEN": "must-not-pass"}, clear=True), \ + patch.object(receive_external.subprocess, "run", return_value=result) as run_mock: + receive_external.check_private_acl(Path(r"D:\Dev\akyldash\.backups")) + child_env = run_mock.call_args.kwargs["env"] + self.assertNotIn("GITEA_TOKEN", child_env) + self.assertEqual(child_env["AKYLDASH_ACL_PATH"], r"D:\Dev\akyldash\.backups") + + +if __name__ == "__main__": + unittest.main() diff --git a/infra/deploy/akyldash-release-deploy.sh b/infra/deploy/akyldash-release-deploy.sh new file mode 100644 index 0000000..40bbfd0 --- /dev/null +++ b/infra/deploy/akyldash-release-deploy.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $EUID -ne 0 || $# -ne 0 ]]; then + echo "This fixed receiver is owner-run as root and accepts its request only on stdin." >&2 + exit 1 +fi + +helper=/usr/local/lib/akyldash/gitea-api +token_file=/etc/akyldash/gitea-api-token +origins_file=/etc/akyldash/gitea-download-origins +if [[ -L $helper || ! -x $helper || $(stat -c %U:%a "$helper") != root:750 ]]; then + echo "The reviewed root-owned Gitea helper is not installed." >&2 + exit 1 +fi +if [[ -L $token_file || ! -f $token_file || $(stat -c %U:%a "$token_file") != root:600 ]]; then + echo "A root-owned mode-0600 read-only Gitea API token file is required." >&2 + exit 1 +fi +GITEA_TOKEN=$(< "$token_file") +if [[ ! $GITEA_TOKEN =~ ^[A-Za-z0-9_-]+$ ]]; then + echo "The Gitea API token file is empty or has an invalid format." >&2 + exit 1 +fi + +GITEA_DOWNLOAD_ORIGINS= +if [[ -e $origins_file || -L $origins_file ]]; then + if [[ -L $origins_file || ! -f $origins_file || $(stat -c %U:%a "$origins_file") != root:600 ]]; then + echo "Gitea artifact redirect origins must be a root-owned mode-0600 file." >&2 + exit 1 + fi + while IFS= read -r origin || [[ -n $origin ]]; do + [[ -z $origin ]] && continue + if [[ ! $origin =~ ^https://[A-Za-z0-9.-]+(:[0-9]+)?$ ]]; then + echo "Gitea artifact redirect origin configuration is invalid." >&2 + exit 1 + fi + if [[ -n $GITEA_DOWNLOAD_ORIGINS ]]; then + GITEA_DOWNLOAD_ORIGINS+=, + fi + GITEA_DOWNLOAD_ORIGINS+=$origin + done < "$origins_file" +fi + +export GITEA_URL=https://git.vakanaut.ru +export GITEA_TOKEN GITEA_DOWNLOAD_ORIGINS +export PATH=/usr/local/lib/akyldash:/usr/bin:/bin +exec /usr/bin/python3 /usr/local/lib/akyldash/external_deploy.py diff --git a/infra/deploy/akyldash-release-rollback.sh b/infra/deploy/akyldash-release-rollback.sh new file mode 100644 index 0000000..d641689 --- /dev/null +++ b/infra/deploy/akyldash-release-rollback.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $EUID -ne 0 || $# -ne 0 ]]; then + echo "This fixed receiver is owner-run as root and accepts its request only on stdin." >&2 + exit 1 +fi +export PATH=/usr/local/lib/akyldash:/usr/bin:/bin +exec /usr/bin/python3 /usr/local/lib/akyldash/external_rollback.py diff --git a/infra/deploy/create_release_manifest.py b/infra/deploy/create_release_manifest.py index 9f41ce9..c7da766 100644 --- a/infra/deploy/create_release_manifest.py +++ b/infra/deploy/create_release_manifest.py @@ -19,21 +19,24 @@ def digest(path: Path) -> str: return value -def create(repository: str, commit: str, run_id: str, backend: Path, opensearch: Path) -> dict: +def create(repository: str, commit: str, source_run_id: str, run_id: str, backend: Path, opensearch: Path) -> dict: if not re.fullmatch(r"[a-z0-9][a-z0-9-]*/[a-z0-9][a-z0-9._-]*", repository): raise ValueError("repository must be lowercase owner/repository") if not re.fullmatch(r"[0-9a-f]{40}", commit): raise ValueError("commit must be a 40-character lowercase Git SHA-1") if not re.fullmatch(r"[0-9]+", run_id): raise ValueError("run_id must be numeric") + if not re.fullmatch(r"[0-9]+", source_run_id): + raise ValueError("source_run_id must be numeric") registry = "git.vakanaut.ru/" + repository return { - "schema_version": 3, + "schema_version": 4, "source_ref": "refs/heads/main", "repository": repository, "commit": commit, "workflow": ".gitea/workflows/release-images.yaml", "run_id": run_id, + "source_run_id": source_run_id, "builder": {"name": "Kaniko", "image": BUILDER_IMAGE}, "images": { "backend": f"{registry}/backend@{digest(backend)}", @@ -47,12 +50,13 @@ def main() -> int: parser.add_argument("--repository", required=True) parser.add_argument("--commit", required=True) parser.add_argument("--run-id", required=True) + parser.add_argument("--source-run-id", required=True) parser.add_argument("--backend-digest", required=True, type=Path) parser.add_argument("--opensearch-digest", required=True, type=Path) parser.add_argument("--output", required=True, type=Path) args = parser.parse_args() try: - manifest = create(args.repository, args.commit, args.run_id, args.backend_digest, args.opensearch_digest) + manifest = create(args.repository, args.commit, args.source_run_id, args.run_id, args.backend_digest, args.opensearch_digest) args.output.write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8") except (OSError, UnicodeError, ValueError) as error: print(f"ERROR: {error}", file=sys.stderr) diff --git a/infra/deploy/deploy_release.py b/infra/deploy/deploy_release.py index 6f2413d..22aab9b 100644 --- a/infra/deploy/deploy_release.py +++ b/infra/deploy/deploy_release.py @@ -41,7 +41,7 @@ def compose(*args: str, capture: bool = False) -> str: return run(["docker", "compose", "--env-file", str(ENV_FILE), "-f", str(COMPOSE_FILE), *args], capture) -def image_ids() -> dict[str, dict[str, str]]: +def image_ids(*, allow_stopped: bool = False) -> dict[str, dict[str, str]]: configured = read_images(ENV_FILE)[1] records = {} for service, key in (("backend", "BACKEND_IMAGE"), ("opensearch", "OPENSEARCH_IMAGE")): @@ -52,8 +52,8 @@ def image_ids() -> dict[str, dict[str, str]]: ["docker", "inspect", "--format", "{{.State.Running}}\t{{.Image}}", container], capture=True ) running, separator, image_id = inspection.partition("\t") - if not separator or running != "true": - raise ValueError(f"{service} is not running; refusing release cutover") + if not separator or (running != "true" and not (allow_stopped and running == "false")): + raise ValueError(f"{service} container state is not approved for the release operation") if not re.fullmatch(r"sha256:[0-9a-f]{64}", image_id): raise ValueError(f"invalid running image ID for {service}") records[service] = {"configured": configured[key], "image_id": image_id} @@ -80,27 +80,6 @@ def write_deployed_backend_image(image_id: str) -> None: temporary.unlink(missing_ok=True) -def backup_manifest(path: Path) -> dict: - if not path.is_file() or path.is_symlink() or path.resolve().parent != BACKUP_DIR.resolve(): - raise ValueError(f"verified backup must be a regular file directly under {BACKUP_DIR}") - if path.stat().st_uid != 0 or path.stat().st_mode & 0o777 != 0o600: - raise ValueError("release backup must be root-owned mode 0600") - checksum = Path(f"{path}.sha256") - if checksum.is_symlink() or not checksum.is_file() or checksum.stat().st_uid != 0 or checksum.stat().st_mode & 0o777 != 0o600: - raise ValueError("release backup checksum must be root-owned mode 0600") - sys.path.insert(0, str(BACKUP_TOOL.parent)) - from archive import digest, verify_archive - - manifest = verify_archive(path) - current_files = { - name: digest(ROOT / name) - for name in ("deploy/production/compose.yaml", "deploy/production/Caddyfile") - } - if manifest.get("deployment_files") != current_files: - raise ValueError("backup does not match the checked out Compose and Caddy configuration") - return manifest - - def require_backup_matches_current(current: dict, backup: dict) -> None: if current != backup: raise ValueError("backup image references or image IDs do not match the current deployment") @@ -147,114 +126,131 @@ def check_search_canary(language: str, query: str) -> None: validate_search_response(payload, language) -def deploy(manifest_path: Path, backup_path: Path, policy_path: Path, canary_ru: str, canary_ky: str) -> None: +def deploy_external( + manifest_value: dict, policy_value: dict, backup_value: dict, backup_identity: dict, + descriptor_sha256: str, current_before_stop: dict, canary_ru: str, canary_ky: str, +) -> None: if os.geteuid() != 0: raise ValueError("production cutover is owner-run and requires root") - manifest = validate_manifest(read_manifest_json(manifest_path), read_manifest_json(policy_path)) + manifest = validate_manifest(manifest_value, policy_value) if manifest["builder"] != {"name": "Kaniko", "image": BUILDER_IMAGE}: raise ValueError("release descriptor uses an unapproved builder") - manifest_sha = hashlib.sha256(manifest_path.read_bytes()).hexdigest() + from release_state import validate_backup_identity - with deployment_lock(): - if JOURNAL_FILE.exists() or JOURNAL_FILE.is_symlink(): - raise ValueError(f"recovery journal exists at {JOURNAL_FILE}; resolve it before another release") - current = image_ids() - backup = backup_manifest(backup_path) - previous = app_images(backup, "backup images") - require_backup_matches_current(current, previous) - pinned = None - if STATE_FILE.exists() or STATE_FILE.is_symlink(): - pinned = validate_state(read_json(STATE_FILE)) - if pinned["current"] != current: - raise ValueError("current deployment does not match the recorded release state") + backup_identity = validate_backup_identity({ + key: backup_identity[key] + for key in ("backup_id", "size", "archive_sha256", "manifest_sha256", "manifest") + }) + if backup_identity is None or backup_identity["manifest"] != backup_value: + raise ValueError("release requires a source-generated, live-verified external backup") + if not re.fullmatch(r"[0-9a-f]{64}", descriptor_sha256): + raise ValueError("release descriptor digest is invalid") + from release_handoff import latest_main_sha + if latest_main_sha() != manifest["commit"]: + raise ValueError("main advanced after the external backup; refusing a stale release cutover") + if not isinstance(current_before_stop, dict) or image_ids(allow_stopped=True) != current_before_stop: + raise ValueError("stopped services do not match the pre-backup image snapshot") + if app_images(backup_value, "external backup images") != current_before_stop: + raise ValueError("external backup image identities do not match the current deployment") + repository_revision = run(["git", "-C", str(ROOT), "rev-parse", "HEAD"], capture=True) + if repository_revision != manifest["commit"]: + raise ValueError("host checkout does not match the verified release commit") + current_files = { + name: hashlib.sha256((ROOT / name).read_bytes()).hexdigest() + for name in ("deploy/production/compose.yaml", "deploy/production/Caddyfile") + } + if backup_value.get("deployment_files") != current_files: + raise ValueError("external backup configuration does not match the checked out Compose and Caddy files") + pinned = None + if STATE_FILE.exists() or STATE_FILE.is_symlink(): + pinned = validate_state(read_json(STATE_FILE)) + if pinned["current"] != current_before_stop: + raise ValueError("current deployment does not match the recorded release state") + + backup_record = { + "backup_id": backup_identity["backup_id"], + "size": backup_identity["size"], + "archive_sha256": backup_identity["archive_sha256"], + "manifest_sha256": backup_identity["manifest_sha256"], + "manifest": backup_value, + } + backup_record = validate_backup_identity(backup_record) + + old_env = {"BACKEND_IMAGE": current_before_stop["backend"]["configured"], "OPENSEARCH_IMAGE": current_before_stop["opensearch"]["configured"]} + new_env = {"BACKEND_IMAGE": manifest["images"]["backend"], "OPENSEARCH_IMAGE": manifest["images"]["opensearch"]} + journal = read_json(JOURNAL_FILE) + state_written = False + try: for service in SERVICES: reference = manifest["images"][service] run(["docker", "pull", reference]) pulled_id = run(["docker", "image", "inspect", "--format", "{{.Id}}", reference], capture=True) if not re.fullmatch(r"sha256:[0-9a-f]{64}", pulled_id): raise ValueError(f"registry returned an invalid image ID for {service}") - target = { service: {"configured": manifest["images"][service], "image_id": run( ["docker", "image", "inspect", "--format", "{{.Id}}", manifest["images"][service]], capture=True )} for service in SERVICES } - old_env = {"BACKEND_IMAGE": current["backend"]["configured"], "OPENSEARCH_IMAGE": current["opensearch"]["configured"]} - new_env = {"BACKEND_IMAGE": target["backend"]["configured"], "OPENSEARCH_IMAGE": target["opensearch"]["configured"]} - journal = { - "schema_version": 1, "status": "prepared", "commit": manifest["commit"], - "manifest_sha256": manifest_sha, "backup": str(backup_path), - "previous": current, "target": target, - } + journal.update({"status": "external-backup-verified", "target": target}) write_json_atomic(JOURNAL_FILE, journal) - state_written = False - try: - compose("stop") - replace_images(ENV_FILE, old_env, new_env) - journal["status"] = "references-switched" - write_json_atomic(JOURNAL_FILE, journal) - compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") - actual = image_ids() - if actual != target: - raise ValueError("started image IDs do not match the release descriptor") - run(["curl", "--fail", "--silent", "--show-error", "--resolve", "akyldash.kg:443:127.0.0.1", - "https://akyldash.kg/review", "--output", "/dev/null"]) - check_search_canary("ru", canary_ru) - check_search_canary("ky", canary_ky) - write_deployed_backend_image(actual["backend"]["image_id"]) - state = { - "schema_version": 1, "commit": manifest["commit"], - "manifest_sha256": manifest_sha, "current": actual, "previous": current, - } - write_json_atomic(STATE_FILE, state) - state_written = True - JOURNAL_FILE.unlink() - print(f"PASS deployed release {manifest['commit']} with --no-build") - except Exception as error: - if state_written: - journal["status"] = "release-active-journal-cleanup-needed" - journal["error_type"] = type(error).__name__ - journal["recovery"] = "target refs, release state, and health check completed; verify host and resolve journal" - write_json_atomic(JOURNAL_FILE, journal) - raise ValueError(f"release is active; recovery journal preserved at {JOURNAL_FILE}") from error - journal["status"] = "cutover-failed" + replace_images(ENV_FILE, old_env, new_env) + journal["status"] = "references-switched" + write_json_atomic(JOURNAL_FILE, journal) + compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") + actual = image_ids() + if actual != target: + raise ValueError("started image IDs do not match the release descriptor") + run(["curl", "--fail", "--silent", "--show-error", "--resolve", "akyldash.kg:443:127.0.0.1", + "https://akyldash.kg/review", "--output", "/dev/null"]) + check_search_canary("ru", canary_ru) + check_search_canary("ky", canary_ky) + write_deployed_backend_image(actual["backend"]["image_id"]) + state = { + "schema_version": 2, "commit": manifest["commit"], + "manifest_sha256": descriptor_sha256, "current": actual, + "previous": current_before_stop, "previous_backup": backup_record, + } + write_json_atomic(STATE_FILE, state) + state_written = True + JOURNAL_FILE.unlink() + print(f"PASS deployed release {manifest['commit']} with --no-build", file=sys.stderr) + except Exception as error: + if state_written: + journal["status"] = "release-active-journal-cleanup-needed" journal["error_type"] = type(error).__name__ - try: - restore_previous_references(old_env, new_env) - compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") - restored = image_ids() - if restored != current: - raise ValueError("restored running image IDs do not match the previous release") - write_deployed_backend_image(current["backend"]["image_id"]) - if pinned is not None: - write_json_atomic(STATE_FILE, pinned) - elif (STATE_FILE.exists() or STATE_FILE.is_symlink()) and not STATE_FILE.is_symlink(): - STATE_FILE.unlink() - journal["recovery"] = "previous references and running image IDs restored and verified" - except Exception as recovery_error: - journal["recovery"] = ( - f"manual recovery required ({type(recovery_error).__name__}); " - "references, release state, and backup are recorded; services were not restarted unless previous refs were verified" - ) + journal["recovery"] = "release is active; verify host and resolve the recovery journal" write_json_atomic(JOURNAL_FILE, journal) - raise ValueError(f"cutover failed; recovery journal preserved at {JOURNAL_FILE}") from error + raise ValueError(f"release is active; recovery journal preserved at {JOURNAL_FILE}") from error + journal["status"] = "cutover-failed" + journal["error_type"] = type(error).__name__ + try: + restore_previous_references(old_env, new_env) + compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") + restored = image_ids() + if restored != current_before_stop: + raise ValueError("restored running image IDs do not match the previous release") + write_deployed_backend_image(current_before_stop["backend"]["image_id"]) + if pinned is not None: + write_json_atomic(STATE_FILE, pinned) + elif (STATE_FILE.exists() or STATE_FILE.is_symlink()) and not STATE_FILE.is_symlink(): + STATE_FILE.unlink() + journal["recovery"] = "previous references and running image IDs restored and verified" + except Exception as recovery_error: + journal["recovery"] = ( + f"manual recovery required ({type(recovery_error).__name__}); " + "references, release state, and external backup identity are recorded" + ) + write_json_atomic(JOURNAL_FILE, journal) + raise ValueError(f"cutover failed; recovery journal preserved at {JOURNAL_FILE}") from error def main() -> int: parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("manifest", type=Path) - parser.add_argument("backup", type=Path) - parser.add_argument("--policy", required=True, type=Path) - parser.add_argument("--canary-ru", required=True, help="known query expected to return a Russian search result") - parser.add_argument("--canary-ky", required=True, help="known query expected to return a Kyrgyz search result") - args = parser.parse_args() - try: - deploy(args.manifest, args.backup, args.policy, args.canary_ru, args.canary_ky) - except Exception as error: - print(f"ERROR: {error}", file=sys.stderr) - return 1 - return 0 + argparse.ArgumentParser(description=__doc__).parse_args() + print("ERROR: local backup paths are disabled; use the fixed external session receiver", file=sys.stderr) + return 1 if __name__ == "__main__": diff --git a/infra/deploy/external_deploy.py b/infra/deploy/external_deploy.py new file mode 100644 index 0000000..1e1bc31 --- /dev/null +++ b/infra/deploy/external_deploy.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Fixed root-side Gitea release receiver and external-backup cutover.""" + +from __future__ import annotations + +import json +import os +import sys +from pathlib import Path + +from archive import compose_sources +from deployment_lock import deployment_lock +from deploy_release import JOURNAL_FILE, ROOT, SERVICES, compose, deploy_external, image_ids +from external_session import read_request, send_backup_session, validate_request, write_result +from release_source import fetch_release +from release_state import read_json, validate_state, write_json_atomic + +POLICY_FILE = Path("/etc/akyldash/release-policy.json") +CANARIES_FILE = Path("/etc/akyldash/release-canaries.json") +COMPOSE_FILE = ROOT / "deploy/production/compose.yaml" +ENV_FILE = Path("/etc/akyldash/production.env") + + +def owner_canaries() -> tuple[str, str]: + info = CANARIES_FILE.lstat() + if (CANARIES_FILE.is_symlink() or not CANARIES_FILE.is_file() or info.st_uid != 0 + or info.st_mode & 0o777 != 0o600): + raise ValueError("release canaries must be stored in a root-owned mode-0600 file") + value = json.loads(CANARIES_FILE.read_text(encoding="utf-8")) + if not isinstance(value, dict) or set(value) != {"ru", "ky"}: + raise ValueError("release canary configuration must contain exactly ru and ky") + queries = (value["ru"], value["ky"]) + if any(not isinstance(query, str) or not query.strip() or len(query) > 256 for query in queries): + raise ValueError("release canaries must be non-empty strings of at most 256 characters") + return queries + + +def restart_current(current: dict) -> None: + compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") + if image_ids() != current: + raise ValueError("restarted service image IDs do not match the pre-backup deployment") + + +def execute(request: dict, *, reader, writer, policy: dict | None = None, api=None, + current_main: str | None = None, canaries: tuple[str, str] | None = None) -> dict: + if os.geteuid() != 0: + raise ValueError("the fixed external deployment receiver must run as root") + validate_request(request) + policy = policy if policy is not None else read_json(POLICY_FILE) + canary_ru, canary_ky = canaries or owner_canaries() + if JOURNAL_FILE.exists() or JOURNAL_FILE.is_symlink(): + raise ValueError(f"recovery journal exists at {JOURNAL_FILE}; resolve it before another release") + manifest, _manifest_bytes = fetch_release(request, policy=policy, current_main=current_main, **({"api": api} if api is not None else {})) + + with deployment_lock(): + if JOURNAL_FILE.exists() or JOURNAL_FILE.is_symlink(): + raise ValueError(f"recovery journal exists at {JOURNAL_FILE}; resolve it before another release") + current = image_ids() + current_record = {service: current[service] for service in SERVICES} + revision = deploy_release_revision() + if revision != manifest["commit"]: + raise ValueError("installed host checkout does not match the verified release commit") + previous_state = None + if STATE_FILE.exists() or STATE_FILE.is_symlink(): + previous_state = validate_state(read_json(STATE_FILE)) + if previous_state["current"] != current_record: + raise ValueError("current deployment does not match the recorded release state") + try: + compose("stop") + sources, stopped_revision, stopped_images, deployment_files = compose_sources(COMPOSE_FILE, ENV_FILE) + if stopped_revision != revision or stopped_images.get("backend") != current["backend"] or stopped_images.get("opensearch") != current["opensearch"]: + raise ValueError("stopped production inventory does not match its pre-backup snapshot") + backup_identity = send_backup_session( + writer, reader, sources=sources, revision=stopped_revision, + images=stopped_images, deployment_files=deployment_files, + context={key: request[key] for key in ("action", "run_id", "commit", "descriptor_sha256")}, + ) + except Exception as error: + try: + restart_current(current) + except Exception as recovery_error: + write_json_atomic(JOURNAL_FILE, { + "schema_version": 2, "status": "external-backup-failed", + "error_type": type(error).__name__, + "recovery_error_type": type(recovery_error).__name__, + "previous": current_record, + }) + raise ValueError(f"external backup failed and current services need recovery; journal at {JOURNAL_FILE}") from error + raise + + backup_record = {key: backup_identity[key] for key in + ("backup_id", "size", "archive_sha256", "manifest_sha256", "manifest")} + journal = { + "schema_version": 2, "status": "external-backup-verified", "commit": manifest["commit"], + "manifest_sha256": request["descriptor_sha256"], "backup": backup_record, + "previous": current_record, + } + write_json_atomic(JOURNAL_FILE, journal) + try: + deploy_external( + manifest, policy, backup_identity["manifest"], backup_record, + request["descriptor_sha256"], current_record, canary_ru, canary_ky, + ) + except Exception as error: + current_journal = read_json(JOURNAL_FILE) if JOURNAL_FILE.exists() else {} + if current_journal.get("status") == "external-backup-verified": + try: + restart_current(current) + JOURNAL_FILE.unlink() + except Exception as recovery_error: + current_journal["status"] = "pre-cutover-recovery-needed" + current_journal["error_type"] = type(error).__name__ + current_journal["recovery_error_type"] = type(recovery_error).__name__ + write_json_atomic(JOURNAL_FILE, current_journal) + raise ValueError(f"pre-cutover recovery failed; journal at {JOURNAL_FILE}") from error + raise + return {"backup_id": backup_record["backup_id"], "commit": manifest["commit"]} + + +def deploy_release_revision() -> str: + from deploy_release import run + return run(["git", "-C", str(ROOT), "rev-parse", "HEAD"], capture=True) + + +STATE_FILE = Path("/opt/akyldash/release-state.json") + + +def main() -> int: + try: + request = read_request(sys.stdin.buffer) + result = execute(request, reader=sys.stdin.buffer, writer=sys.stdout.buffer) + write_result(sys.stdout.buffer, status="success", message=result["backup_id"]) + except Exception as error: + print(f"ERROR: {type(error).__name__}: {error}", file=sys.stderr) + try: + write_result(sys.stdout.buffer, status="error", message=f"deployment failed ({type(error).__name__})") + except (BrokenPipeError, OSError): + pass + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/infra/deploy/external_rollback.py b/infra/deploy/external_rollback.py new file mode 100644 index 0000000..2a97f4e --- /dev/null +++ b/infra/deploy/external_rollback.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Root-side rollback using a pinned external backup and a fresh external backup.""" + +from __future__ import annotations + +import os +import sys + +from archive import compose_sources +from deployment_lock import deployment_lock +from deploy_release import COMPOSE_FILE, ENV_FILE, JOURNAL_FILE, ROOT, compose, image_ids +from external_session import (nonce, read_ack, read_request, + receive_archive, send_backup_session, write_challenge, + write_result) +from release_state import (read_json, validate_state, write_json_atomic) +from rollback import rollback_external + +STATE_FILE = ROOT.parent / "release-state.json" + + +class Discard: + def write(self, chunk: bytes) -> int: + return len(chunk) + + def flush(self) -> None: + pass + + +def execute(*, reader, writer) -> str: + if os.geteuid() != 0: + raise ValueError("the fixed external rollback receiver must run as root") + request = read_request(reader) + if request != {"version": 1, "action": "rollback", "data_compatible": True}: + raise ValueError("external rollback request is invalid") + if JOURNAL_FILE.exists() or JOURNAL_FILE.is_symlink(): + raise ValueError(f"recovery journal exists at {JOURNAL_FILE}; resolve it before rollback") + + with deployment_lock(): + state = validate_state(read_json(STATE_FILE)) + if state["schema_version"] != 2 or state["previous_backup"] is None: + raise ValueError("release state has no verified external previous backup") + target = state["previous_backup"] + session_nonce = nonce() + write_challenge(writer, target, session_nonce=session_nonce) + size, digest = receive_archive(reader, Discard(), maximum=target["size"]) + if size != target["size"] or digest != target["archive_sha256"]: + raise ValueError("rollback bytes do not match the root-pinned external backup") + read_ack(reader, session_nonce=session_nonce, backup_id=target["backup_id"], size=size, + archive_sha256=digest, manifest_sha256=target["manifest_sha256"]) + + current = image_ids() + if current != state["current"]: + raise ValueError("current deployment does not match root-pinned release state") + try: + compose("stop") + sources, revision, stopped_images, deployment_files = compose_sources(COMPOSE_FILE, ENV_FILE) + if any(stopped_images.get(service) != record for service, record in current.items()): + raise ValueError("stopped deployment does not match its pre-rollback snapshot") + fresh = send_backup_session( + writer, reader, sources=sources, revision=revision, images=stopped_images, + deployment_files=deployment_files, + context={"action": "rollback", "backup_id": target["backup_id"], + "archive_sha256": target["archive_sha256"], + "manifest_sha256": target["manifest_sha256"]}, + ) + except Exception as error: + try: + compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") + if image_ids() != current: + raise ValueError("restarted image IDs differ from the pre-rollback deployment") + except Exception as recovery_error: + write_json_atomic(JOURNAL_FILE, { + "schema_version": 2, "status": "external-backup-failed", + "error_type": type(error).__name__, + "recovery_error_type": type(recovery_error).__name__, + "previous": current, + }) + raise ValueError(f"rollback backup failed and services need recovery; journal at {JOURNAL_FILE}") from error + raise + + fresh_record = {key: fresh[key] for key in + ("backup_id", "size", "archive_sha256", "manifest_sha256", "manifest")} + write_json_atomic(JOURNAL_FILE, { + "schema_version": 2, "status": "external-backup-verified", + "backup": fresh_record, "previous": current, + }) + try: + rollback_external(state=state, target_identity=target, current=current, + fresh_backup=fresh_record, data_compatible=True) + except Exception as error: + journal = read_json(JOURNAL_FILE) if JOURNAL_FILE.exists() else {} + if journal.get("status") == "external-backup-verified": + try: + compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") + if image_ids() != current: + raise ValueError("restarted image IDs differ from the pre-rollback deployment") + JOURNAL_FILE.unlink() + except Exception as recovery_error: + journal.update({ + "status": "pre-cutover-recovery-needed", + "error_type": type(error).__name__, + "recovery_error_type": type(recovery_error).__name__, + }) + write_json_atomic(JOURNAL_FILE, journal) + raise ValueError(f"rollback preflight failed and services need recovery; journal at {JOURNAL_FILE}") from error + raise + return fresh_record["backup_id"] + + +def main() -> int: + try: + result = execute(reader=sys.stdin.buffer, writer=sys.stdout.buffer) + write_result(sys.stdout.buffer, status="success", message=result) + return 0 + except Exception as error: + print(f"ERROR: {type(error).__name__}: {error}", file=sys.stderr) + try: + write_result(sys.stdout.buffer, status="error", message=f"rollback failed ({type(error).__name__})") + except OSError: + pass + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/infra/deploy/gitea-api-base.fixture b/infra/deploy/gitea-api-base.fixture new file mode 100644 index 0000000..e1b00a7 --- /dev/null +++ b/infra/deploy/gitea-api-base.fixture @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [ -z "${GITEA_URL:-}" ]; then + echo "gitea-api: GITEA_URL is not set" >&2 + exit 1 +fi + +if [ -z "${GITEA_TOKEN:-}" ]; then + echo "gitea-api: GITEA_TOKEN is not set" >&2 + exit 1 +fi + +method="${1:-GET}" +path="${2:-}" +body="${3:-}" + +if [ -z "$path" ]; then + echo "Usage: gitea-api METHOD /path [JSON]" >&2 + exit 2 +fi + +base="${GITEA_URL%/}/api/v1" +tmp="$(mktemp)" + +cleanup() { + rm -f "$tmp" +} +trap cleanup EXIT + +args=( + -sS + -o "$tmp" + -w "%{http_code}" + -X "$method" + -H "Authorization: token ${GITEA_TOKEN}" + -H "Accept: application/json" +) + +if [ -n "$body" ]; then + args+=( + -H "Content-Type: application/json" + --data "$body" + ) +fi + +http_code="$(curl "${args[@]}" "${base}${path}")" +curl_status=$? + +cat "$tmp" + +if [ "$curl_status" -ne 0 ]; then + echo >&2 + echo "gitea-api: curl failed with exit code $curl_status" >&2 + exit "$curl_status" +fi + +case "$http_code" in + 2??) + exit 0 + ;; + *) + echo >&2 + echo "gitea-api: HTTP $http_code" >&2 + exit 1 + ;; +esac diff --git a/infra/deploy/gitea-api-binary-download.patch b/infra/deploy/gitea-api-binary-download.patch new file mode 100644 index 0000000..e52691a --- /dev/null +++ b/infra/deploy/gitea-api-binary-download.patch @@ -0,0 +1,92 @@ +--- a/gitea-api ++++ b/gitea-api +@@ -13,0 +14,5 @@ ++if [[ ! "$GITEA_TOKEN" =~ ^[A-Za-z0-9_-]+$ ]]; then ++ echo "gitea-api: GITEA_TOKEN contains unsupported characters" >&2 ++ exit 1 ++fi ++ +@@ -30,0 +36,78 @@ ++if [ "$method" = "DOWNLOAD" ]; then ++ output="$body" ++ max_bytes=10485760 ++ if [ -z "$output" ] || [ ! -d "$(dirname "$output")" ] || [ -e "$output" ] || [ -L "$output" ]; then ++ echo "Usage: gitea-api DOWNLOAD /path /new/output-file" >&2 ++ exit 2 ++ fi ++ case "$GITEA_URL" in ++ https://*) gitea_host="${GITEA_URL#https://}"; gitea_host="${gitea_host%%/*}"; gitea_origin="https://${gitea_host}" ;; ++ *) echo "gitea-api: binary downloads require HTTPS" >&2; exit 2 ;; ++ esac ++ if [[ ! "$gitea_origin" =~ ^https://[A-Za-z0-9.-]+(:[0-9]+)?$ ]]; then ++ echo "gitea-api: invalid Gitea origin for binary download" >&2 ++ exit 2 ++ fi ++ headers="$(mktemp)" ++ download="$(mktemp "$(dirname "$output")/.gitea-api-download.XXXXXX")" ++ chmod 600 "$download" ++ cleanup() { rm -f "$tmp" "$headers" "$download"; } ++ trap cleanup EXIT ++ ++ http_code="$(curl -sS -D "$headers" -o /dev/null -w "%{http_code}" --max-filesize 1048576 \ ++ -H "Accept: application/octet-stream" --config - "${base}${path}" <<< "header = \"Authorization: token ${GITEA_TOKEN}\"")" || { echo "gitea-api: artifact metadata request failed" >&2; exit 1; } ++ if [[ "$http_code" == 2?? ]]; then ++ set +e ++ curl -sS --fail --proto '=https' --max-filesize "$max_bytes" \ ++ --config - "$base$path" <<< "header = \"Authorization: token ${GITEA_TOKEN}\"" | head -c "$((max_bytes + 1))" > "$download" ++ statuses=("${PIPESTATUS[@]}") ++ set -e ++ size="$(wc -c < "$download")" ++ if (( size > max_bytes )); then ++ echo "gitea-api: artifact exceeds the 10 MiB download limit" >&2 ++ exit 1 ++ fi ++ if (( statuses[0] != 0 || statuses[1] != 0 )); then ++ echo "gitea-api: artifact download failed" >&2 ++ exit 1 ++ fi ++ elif [[ "$http_code" == 302 ]]; then ++ location="$(awk 'tolower(substr($0,1,9)) == "location:" { sub(/^[^:]*:[[:space:]]*/, ""); sub(/\r$/, ""); value=$0 } END { print value }' "$headers")" ++ if [[ ! "$location" =~ ^https://([A-Za-z0-9.-]+(:[0-9]+)?)(/[^#]*)?$ ]]; then ++ echo "gitea-api: artifact redirect is not an absolute HTTPS URL" >&2 ++ exit 1 ++ fi ++ redirect_origin="https://${BASH_REMATCH[1],,}" ++ gitea_origin="${gitea_origin,,}" ++ if [[ "$redirect_origin" != "$gitea_origin" && ",${GITEA_DOWNLOAD_ORIGINS:-}," != *",${redirect_origin},"* ]]; then ++ echo "gitea-api: artifact redirect origin is not allowlisted" >&2 ++ exit 1 ++ fi ++ set +e ++ curl -sS --proto '=https' --max-filesize "$max_bytes" -o - "$location" | head -c "$((max_bytes + 1))" > "$download" ++ statuses=("${PIPESTATUS[@]}") ++ set -e ++ size="$(wc -c < "$download")" ++ if (( size > max_bytes )); then ++ echo "gitea-api: artifact exceeds the 10 MiB download limit" >&2 ++ exit 1 ++ fi ++ if (( statuses[0] != 0 )); then ++ echo "gitea-api: artifact download failed" >&2 ++ exit 1 ++ fi ++ else ++ echo "gitea-api: artifact endpoint returned HTTP $http_code" >&2 ++ exit 1 ++ fi ++ size="$(wc -c < "$download")" ++ if (( size > max_bytes )); then ++ echo "gitea-api: artifact exceeds the 10 MiB download limit" >&2 ++ exit 1 ++ fi ++ chmod 600 "$download" ++ ln -- "$download" "$output" || { echo "gitea-api: output file already exists" >&2; exit 1; } ++ echo "PASS downloaded Gitea artifact (${size} bytes)" ++ exit 0 ++fi ++ +@@ -36 +118,0 @@ +- -H "Authorization: token ${GITEA_TOKEN}" +@@ -47 +129 @@ +-http_code="$(curl "${args[@]}" "${base}${path}")" ++http_code="$(curl "${args[@]}" --config - "${base}${path}" <<< "header = \"Authorization: token ${GITEA_TOKEN}\"")" diff --git a/infra/deploy/install-helper.sh b/infra/deploy/install-helper.sh index 9393e9a..6ad3fc0 100644 --- a/infra/deploy/install-helper.sh +++ b/infra/deploy/install-helper.sh @@ -14,7 +14,13 @@ deployment_lock_source=$checkout/infra/deploy/deployment_lock.py backup_source=$checkout/infra/backup/archive.py verify_source=$checkout/infra/bootstrap/verify-helper.sh compose_source=$checkout/infra/deploy/compose-helper.sh -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 ]]; then +release_deploy_source=$checkout/infra/deploy/akyldash-release-deploy.sh +release_rollback_source=$checkout/infra/deploy/akyldash-release-rollback.sh +release_controller_source=$checkout/infra/deploy/external_deploy.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 echo "Install the approved repository checkout at $checkout first." >&2 exit 1 fi @@ -46,8 +52,12 @@ if ! command -v visudo >/dev/null 2>&1; then echo "visudo is required to validate the restricted sudoers rule." >&2 exit 1 fi +if ! command -v patch >/dev/null 2>&1 || ! command -v sha256sum >/dev/null 2>&1; then + echo "patch and sha256sum are required to install the reviewed binary-safe Gitea helper." >&2 + exit 1 +fi -for path in /usr/local/sbin/akyldash-verify /usr/local/sbin/akyldash-rollback /usr/local/sbin/akyldash-compose /usr/local/lib/akyldash/archive.py /usr/local/lib/akyldash/release_refs.py /usr/local/lib/akyldash/release_state.py /usr/local/lib/akyldash/deployment_lock.py /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/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 if [[ -L $path ]]; then echo "Refusing symlink at $path." >&2 exit 1 @@ -59,9 +69,39 @@ install -o root -g root -m 0644 "$backup_source" /usr/local/lib/akyldash/archive install -o root -g root -m 0644 "$release_refs_source" /usr/local/lib/akyldash/release_refs.py install -o root -g root -m 0644 "$release_state_source" /usr/local/lib/akyldash/release_state.py install -o root -g root -m 0644 "$deployment_lock_source" /usr/local/lib/akyldash/deployment_lock.py +install -o root -g root -m 0644 "$checkout/infra/backup/external_session.py" /usr/local/lib/akyldash/external_session.py +install -o root -g root -m 0644 "$checkout/infra/deploy/create_release_manifest.py" /usr/local/lib/akyldash/create_release_manifest.py +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 "$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 +install -o root -g root -m 0644 "$checkout/infra/deploy/validate_release.py" /usr/local/lib/akyldash/validate_release.py +if [[ -e /etc/akyldash/release-policy.json ]]; then + if [[ -L /etc/akyldash/release-policy.json || $(stat -c %U:%a /etc/akyldash/release-policy.json) != root:600 || ! -f /etc/akyldash/release-policy.json || $(cat /etc/akyldash/release-policy.json) != "$(cat "$release_policy_source")" ]]; then + echo "The root-owned release policy exists with unexpected contents; review it manually." >&2 + exit 1 + fi +else + install -o root -g root -m 0600 "$release_policy_source" /etc/akyldash/release-policy.json +fi +gitea_tmp=$(mktemp -d /run/akyldash-gitea-api.XXXXXX) +trap 'rm -rf -- "$gitea_tmp"' EXIT +cp "$gitea_helper_fixture" "$gitea_tmp/gitea-api" +if [[ $(sha256sum "$gitea_tmp/gitea-api" | cut -d ' ' -f 1) != 8227332d28e27bcce9b4e3801f6b8d4323636174a82c93a0177970f560629df0 ]]; then + echo "The inspected base gitea-api helper changed; review a new patch before installing." >&2 + exit 1 +fi +patch --batch --fuzz=0 -p1 -d "$gitea_tmp" < "$gitea_helper_patch" +bash -n "$gitea_tmp/gitea-api" +install -o root -g root -m 0750 "$gitea_tmp/gitea-api" /usr/local/lib/akyldash/gitea-api +rm -rf -- "$gitea_tmp" install -o root -g root -m 0750 "$verify_source" /usr/local/sbin/akyldash-verify install -o root -g root -m 0750 "$rollback_source" /usr/local/sbin/akyldash-rollback 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 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' diff --git a/infra/deploy/release_source.py b/infra/deploy/release_source.py new file mode 100644 index 0000000..eae5770 --- /dev/null +++ b/infra/deploy/release_source.py @@ -0,0 +1,161 @@ +"""Verify a Gitea release and its exact uploaded descriptor through gitea-api.""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import stat +import subprocess +import zipfile +from pathlib import Path, PurePosixPath + +from release_handoff import descriptor_request, latest_main_sha, validate_source +from validate_release import read_json, unique_object, validate_manifest + +REPOSITORY = "admin/akyldash" +RELEASE_WORKFLOW = ".gitea/workflows/release-images.yaml" +CI_WORKFLOW = ".gitea/workflows/ci.yaml" +MAX_DESCRIPTOR_BYTES = 1024 * 1024 + + +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) + if not isinstance(value, dict): + raise ValueError("Gitea API returned a non-object response") + return value + + +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: + raise ValueError("artifact scratch directory must be a private root-owned directory") + + +def verify_run(run_id: str, *, stage: str, commit: str, api=api_json, current_main: str | None = None) -> dict: + if not run_id.isdigit() or not re.fullmatch(r"[0-9a-f]{40}", commit): + raise ValueError("Gitea run identity is invalid") + run = api(f"/repos/{REPOSITORY}/actions/runs/{run_id}") + if not isinstance(run, dict) or str(run.get("id")) != run_id: + raise ValueError("Gitea returned a different workflow run") + if run.get("status") != "success" or run.get("conclusion") not in {None, "success"}: + raise ValueError("workflow run is not successful") + workflow_id = run.get("workflow_id") + if not isinstance(workflow_id, (int, str)) or not str(workflow_id): + raise ValueError("workflow run has no workflow identity") + workflow = api(f"/repos/{REPOSITORY}/actions/workflows/{workflow_id}") + expected_workflow, path, event = ( + ("CI", CI_WORKFLOW, "push") if stage == "ci" else + ("Release production images", RELEASE_WORKFLOW, "workflow_run") + ) + if (workflow.get("name") != expected_workflow or workflow.get("path") != path + or str(workflow.get("id")) != str(workflow_id)): + raise ValueError("workflow ID does not resolve to the approved workflow name and path") + if run.get("name") not in {None, expected_workflow}: + raise ValueError("workflow run name is not approved") + if run.get("head_sha") != commit: + raise ValueError("workflow run commit does not match the release request") + branch = run.get("head_branch") + if branch != "main" or run.get("event") != event: + raise ValueError("workflow run is not the approved main event") + validate_source( + workflow=expected_workflow, workflow_path=f"{Path(path).name}@refs/heads/main", event=event, + conclusion="success", branch=branch, run_id=run_id, head_sha=commit, + repository=REPOSITORY, stage="release" if stage == "ci" else "handoff", + current_main=current_main or latest_main_sha(), + ) + return run + + +def validate_artifact_zip(path: Path, *, descriptor_sha256: str, release_run_id: str, + ci_run_id: str | None, commit: str, policy: object) -> tuple[dict, bytes]: + if not re.fullmatch(r"[0-9a-f]{64}", descriptor_sha256): + raise ValueError("requested descriptor digest is invalid") + try: + with zipfile.ZipFile(path) as archive: + members = archive.infolist() + names = [member.filename for member in members] + expected = {"release-manifest.json", "release-manifest.json.sha256"} + if len(names) != 2 or set(names) != expected: + raise ValueError("release artifact must contain exactly the manifest and checksum files") + payloads = {} + for member in members: + name = PurePosixPath(member.filename) + mode = member.external_attr >> 16 + kind = stat.S_IFMT(mode) + if (member.is_dir() or name.is_absolute() or len(name.parts) != 1 + or name.as_posix() != member.filename + or kind not in {0, stat.S_IFREG} + or member.file_size > MAX_DESCRIPTOR_BYTES + or member.compress_size > MAX_DESCRIPTOR_BYTES): + raise ValueError("release artifact contains an unsafe or oversized member") + with archive.open(member) as stream: + chunks = [] + size = 0 + while chunk := stream.read(64 * 1024): + size += len(chunk) + if size > MAX_DESCRIPTOR_BYTES: + raise ValueError("release artifact member exceeds its size limit") + chunks.append(chunk) + if size != member.file_size: + raise ValueError("release artifact member size does not match its ZIP metadata") + payloads[member.filename] = b"".join(chunks) + except (OSError, zipfile.BadZipFile, RuntimeError) as error: + raise ValueError(f"release artifact ZIP is invalid: {error}") from error + + manifest_bytes = payloads["release-manifest.json"] + if hashlib.sha256(manifest_bytes).hexdigest() != descriptor_sha256: + raise ValueError("release descriptor bytes do not match the requested SHA-256") + checksum = payloads["release-manifest.json.sha256"] + expected_sidecar = f"{descriptor_sha256} release-manifest.json\n".encode("ascii") + if checksum != expected_sidecar: + raise ValueError("release descriptor checksum sidecar is invalid") + try: + manifest = json.loads(manifest_bytes, object_pairs_hook=unique_object) + except (UnicodeError, json.JSONDecodeError) as error: + raise ValueError("release descriptor JSON is invalid") from error + validated = validate_manifest(manifest, policy) + if (validated["run_id"] != release_run_id + or (ci_run_id is not None and validated["source_run_id"] != ci_run_id) + or validated["commit"] != commit): + raise ValueError("release descriptor does not bind the verified CI and release runs") + return validated, manifest_bytes + + +def fetch_release(request: dict, *, policy: object, helper: str = "gitea-api", + temp_dir: Path = Path("/run/akyldash"), env: dict | None = None, + api=api_json, current_main: str | None = None) -> tuple[dict, bytes]: + run_id, commit, descriptor_sha256 = ( + request["run_id"], request["commit"], request["descriptor_sha256"] + ) + current_main = current_main or latest_main_sha() + release_run = verify_run(run_id, stage="handoff", commit=commit, api=api, + current_main=current_main) + metadata = api(f"/repos/{REPOSITORY}/actions/runs/{run_id}/artifacts") + tuple_data = descriptor_request(metadata, run_id=run_id, head_sha=commit) + if tuple_data["descriptor_sha256"] != descriptor_sha256: + raise ValueError("requested descriptor digest does not match the Gitea run artifact") + artifact = metadata["artifacts"][0] + artifact_id = artifact.get("id") + if not isinstance(artifact_id, (int, str)) or not str(artifact_id).isdigit(): + raise ValueError("release descriptor artifact has no numeric ID") + ensure_private_scratch(temp_dir) + from tempfile import TemporaryDirectory + with TemporaryDirectory(prefix="akyldash-release-", dir=temp_dir) as scratch: + zip_path = Path(scratch) / "artifact.zip" + result = subprocess.run( + [helper, "DOWNLOAD", f"/repos/{REPOSITORY}/actions/artifacts/{artifact_id}/zip", str(zip_path)], + check=True, text=True, capture_output=True, env=env, + ) + 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, + ) + source_run_id = manifest["source_run_id"] + verify_run(source_run_id, stage="ci", commit=commit, api=api, current_main=current_main) + return manifest, manifest_bytes diff --git a/infra/deploy/release_state.py b/infra/deploy/release_state.py index 4d1d27d..f673158 100644 --- a/infra/deploy/release_state.py +++ b/infra/deploy/release_state.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import hashlib import os import re import tempfile @@ -11,6 +12,15 @@ from pathlib import Path SERVICES = {"backend", "opensearch"} +def unique_object(pairs: list[tuple[str, object]]) -> dict: + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"duplicate release state field: {key}") + result[key] = value + return result + + def validate_images(value: object, label: str) -> dict[str, dict[str, str]]: if not isinstance(value, dict) or set(value) != SERVICES: raise ValueError(f"{label} must contain backend and opensearch") @@ -55,7 +65,7 @@ def read_json(path: Path) -> dict: if path.is_symlink() or not path.is_file(): raise ValueError(f"release state is not a regular file: {path}") try: - value = json.loads(path.read_text(encoding="utf-8")) + value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique_object) except (OSError, UnicodeError, json.JSONDecodeError) as error: raise ValueError(f"release state is unreadable: {error}") from error if not isinstance(value, dict): @@ -64,9 +74,11 @@ def read_json(path: Path) -> dict: def validate_state(state: object) -> dict: - if not isinstance(state, dict) or set(state) != { - "schema_version", "commit", "manifest_sha256", "current", "previous" - } or state.get("schema_version") != 1: + old_fields = {"schema_version", "commit", "manifest_sha256", "current", "previous"} + new_fields = old_fields | {"previous_backup"} + if (not isinstance(state, dict) or type(state.get("schema_version")) is not int + or state.get("schema_version") not in {1, 2} + or set(state) != (old_fields if state.get("schema_version") == 1 else new_fields)): raise ValueError("release state has unsupported schema") if not isinstance(state["commit"], str) or not re.fullmatch(r"[0-9a-f]{40}|rollback", state["commit"]): raise ValueError("release state commit is invalid") @@ -74,4 +86,24 @@ def validate_state(state: object) -> dict: raise ValueError("release state provenance is invalid") state["current"] = validate_images(state["current"], "current images") state["previous"] = validate_images(state["previous"], "previous images") + if state["schema_version"] == 2: + state["previous_backup"] = validate_backup_identity(state["previous_backup"]) return state + + +def validate_backup_identity(value: object) -> dict | None: + if value is None: + return None + required = {"backup_id", "size", "archive_sha256", "manifest_sha256", "manifest"} + if not isinstance(value, dict) or set(value) != required: + raise ValueError("external backup identity has an unsupported shape") + if (not isinstance(value["backup_id"], str) or not re.fullmatch(r"akyldash-[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}", value["backup_id"]) + or type(value["size"]) is not int or not 0 < value["size"] <= 100 * 1024**3 + or not isinstance(value["archive_sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", value["archive_sha256"]) + or not isinstance(value["manifest_sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", value["manifest_sha256"]) + or not isinstance(value["manifest"], dict)): + raise ValueError("external backup identity has invalid values") + canonical = json.dumps(value["manifest"], sort_keys=True, separators=(",", ":")).encode("utf-8") + if hashlib.sha256(canonical).hexdigest() != value["manifest_sha256"]: + raise ValueError("external backup manifest identity is inconsistent") + return value diff --git a/infra/deploy/rollback.py b/infra/deploy/rollback.py index 2b86a76..203c375 100644 --- a/infra/deploy/rollback.py +++ b/infra/deploy/rollback.py @@ -3,9 +3,7 @@ from __future__ import annotations -import argparse -import datetime as dt -import json +import hashlib import os import re import subprocess @@ -16,8 +14,6 @@ from pathlib import Path ROOT = Path("/opt/akyldash/current") COMPOSE_FILE = ROOT / "deploy/production/compose.yaml" ENV_FILE = Path("/etc/akyldash/production.env") -BACKUP_DIR = Path("/var/backups/akyldash") -BACKUP_TOOL = Path("/usr/local/lib/akyldash/archive.py") STATE_FILE = Path("/opt/akyldash/release-state.json") JOURNAL_FILE = Path("/opt/akyldash/release-recovery.json") DEPLOYED_IMAGE_FILE = Path("/opt/akyldash/deployed-image.txt") @@ -150,200 +146,98 @@ def require_running_image_ids(expected: dict[str, str], actual: dict[str, str], def rollback(backup: Path, data_compatible: bool) -> None: - sys.path.insert(0, str(BACKUP_TOOL.parent)) - from deployment_lock import deployment_lock - - with deployment_lock(): - _rollback_locked(backup, data_compatible) + raise ValueError("local VPS backup paths are disabled; use the owner-controlled external rollback session") -def _rollback_locked(backup: Path, data_compatible: bool) -> None: - if JOURNAL_FILE.exists() or JOURNAL_FILE.is_symlink(): - raise ValueError(f"recovery journal exists at {JOURNAL_FILE}; resolve it before rollback") +def rollback_external( + *, state: dict, target_identity: dict, current: dict, fresh_backup: dict, + data_compatible: bool, +) -> None: + if os.geteuid() != 0: + raise ValueError("external rollback must run in the root-controlled receiver") if not data_compatible: - raise ValueError("confirm data compatibility with --data-compatible before rollback") - if not backup.is_file() or backup.is_symlink() or backup.resolve().parent != BACKUP_DIR.resolve(): - raise ValueError(f"backup must be a regular file directly under {BACKUP_DIR}") - if backup.stat().st_uid != 0 or backup.stat().st_mode & 0o777 != 0o600: - raise ValueError("rollback backup must be root-owned mode 0600") - checksum = Path(f"{backup}.sha256") - if checksum.is_symlink() or not checksum.is_file() or checksum.stat().st_uid != 0 or checksum.stat().st_mode & 0o777 != 0o600: - raise ValueError("rollback checksum sidecar must be root-owned mode 0600") + raise ValueError("confirm data compatibility before external rollback") + from deploy_release import image_ids + from release_refs import read_images, replace_images + from release_state import read_json, validate_backup_identity, validate_state, write_json_atomic - sys.path.insert(0, str(BACKUP_TOOL.parent)) - from archive import digest, verify_archive - - manifest = verify_archive(backup) - deployment_files = { - relative: digest(ROOT / relative) + pinned = validate_state(state) + if pinned.get("schema_version") != 2 or pinned.get("previous_backup") is None: + raise ValueError("release state has no verified external previous backup") + target_identity = validate_backup_identity(target_identity) + fresh_backup = validate_backup_identity(fresh_backup) + if target_identity != pinned["previous_backup"]: + raise ValueError("rollback archive is not the root-pinned previous external backup") + if image_ids(allow_stopped=True) != current: + raise ValueError("stopped production images differ from the pre-rollback snapshot") + current_files = { + relative: hashlib.sha256((ROOT / relative).read_bytes()).hexdigest() for relative in ("deploy/production/compose.yaml", "deploy/production/Caddyfile") } - if deployment_files != manifest.get("deployment_files"): - raise ValueError("Compose or Caddyfile changed since this backup; restore the matching Git revision first") - rendered = json.loads(compose("config", "--format", "json", capture=True)) - configured = {service: rendered["services"][service]["image"] for service in APP_SERVICES} - current_running_ids = running_image_ids() - state = None - expected_previous = None - if STATE_FILE.exists() or STATE_FILE.is_symlink(): - from release_state import read_json as read_release_state, validate_state + if target_identity["manifest"].get("deployment_files") != current_files: + raise ValueError("previous backup deployment files differ from the current checkout") + if app_images(target_identity["manifest"], "previous external backup") != pinned["previous"]: + raise ValueError("previous backup image identities do not match root-pinned release state") + if app_images(fresh_backup["manifest"], "pre-rollback external backup") != current: + raise ValueError("fresh external backup does not match the current deployment") - state = validate_state(read_release_state(STATE_FILE)) - current_refs = {service: state["current"][service]["configured"] for service in APP_SERVICES} - if current_refs != configured: - raise ValueError("release state does not match current Compose image references") - expected_current = {service: state["current"][service]["image_id"] for service in APP_SERVICES} - try: - require_running_image_ids(expected_current, current_running_ids, "pinned release state") - except ValueError as error: - raise ValueError(f"current deployment does not match pinned release state: {error}") from error - expected_previous = state["previous"] - plan = image_restore_plan(manifest, configured, expected_previous) + env_text, configured_values = read_images(ENV_FILE) + del env_text + configured = {service: configured_values[f"{service.upper()}_IMAGE"] for service in APP_SERVICES} + plan = image_restore_plan(target_identity["manifest"], configured, pinned["previous"]) verify_previous_images(plan) - if expected_previous is None: - require_tag_rollback(plan) - - backup_name = f"akyldash-pre-rollback-{dt.datetime.now(dt.timezone.utc):%Y%m%dT%H%M%SZ}.tar.gz" - backup_output = BACKUP_DIR / backup_name before = {"BACKEND_IMAGE": configured["backend"], "OPENSEARCH_IMAGE": configured["opensearch"]} after = {"BACKEND_IMAGE": plan["backend"][1], "OPENSEARCH_IMAGE": plan["opensearch"][1]} - try: - compose("stop") - run( - [ - "python3", - str(BACKUP_TOOL), - "create", - "--compose-file", - str(COMPOSE_FILE), - "--env-file", - str(ENV_FILE), - "--output", - str(backup_output), - ] - ) - run(["python3", str(BACKUP_TOOL), "verify", str(backup_output)]) - except Exception as error: - from release_state import write_json_atomic + journal = read_json(JOURNAL_FILE) + if journal.get("status") != "external-backup-verified" or journal.get("backup") != fresh_backup: + raise ValueError("fresh external backup journal is missing or does not match this rollback") - journal = { - "schema_version": 1, "status": "rollback-backup-failed", "backup": str(backup), - "error_type": type(error).__name__, "target": before, + try: + tag_previous_images(plan) + replace_images(ENV_FILE, before, after) + journal["status"] = "rollback-references-switched" + journal["rollback_from"] = target_identity + write_json_atomic(JOURNAL_FILE, journal) + compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") + expected = {service: plan[service][0] for service in APP_SERVICES} + require_running_image_ids(expected, running_image_ids(), "verified previous external backup") + run(["curl", "--fail", "--silent", "--show-error", "--resolve", "akyldash.kg:443:127.0.0.1", + "https://akyldash.kg/review", "--output", "/dev/null"]) + record_backend_image() + restored = { + service: {"configured": plan[service][1], "image_id": plan[service][0]} + for service in APP_SERVICES } + write_json_atomic(STATE_FILE, { + "schema_version": 2, "commit": "rollback", "manifest_sha256": "rollback", + "current": restored, "previous": current, "previous_backup": fresh_backup, + }) + JOURNAL_FILE.unlink() + except Exception as error: + journal["status"] = "rollback-failed" + journal["error_type"] = type(error).__name__ try: + _text, current_env = read_images(ENV_FILE) + active = {"BACKEND_IMAGE": current_env["BACKEND_IMAGE"], "OPENSEARCH_IMAGE": current_env["OPENSEARCH_IMAGE"]} + if active == after: + replace_images(ENV_FILE, after, before) + elif active != before: + raise ValueError("image references match neither the current nor rollback release") compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") - journal["recovery"] = "current release restarted; verify service health" + require_running_image_ids({service: current[service]["image_id"] for service in APP_SERVICES}, + running_image_ids(), "pre-rollback deployment") + record_backend_image() + write_json_atomic(STATE_FILE, pinned) + journal["recovery"] = "pre-rollback references and image IDs restored" except Exception as recovery_error: journal["recovery"] = f"manual recovery required ({type(recovery_error).__name__})" write_json_atomic(JOURNAL_FILE, journal) - raise ValueError(f"rollback preflight failed; recovery journal preserved at {JOURNAL_FILE}") from error - - journal = { - "schema_version": 1, "status": "rollback-prepared", "backup": str(backup), - "previous": {service: {"configured": plan[service][1], "image_id": plan[service][0]} for service in APP_SERVICES}, - "target": {service: {"configured": configured[service]} for service in APP_SERVICES}, - } - if state is not None: - from release_state import write_json_atomic - - write_json_atomic(JOURNAL_FILE, journal) - state_written = False - try: - tag_previous_images(plan) - if state is not None: - from release_refs import replace_images - - replace_images(ENV_FILE, before, after) - journal["status"] = "rollback-references-switched" - write_json_atomic(JOURNAL_FILE, journal) - compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") - expected_restored = {service: plan[service][0] for service in APP_SERVICES} - require_running_image_ids(expected_restored, running_image_ids(), "rollback plan") - run( - [ - "curl", "--fail", "--silent", "--show-error", "--resolve", "akyldash.kg:443:127.0.0.1", - "https://akyldash.kg/review", "--output", "/dev/null", - ] - ) - record_backend_image() - if state is not None: - from release_state import write_json_atomic - - restored = { - service: {"configured": plan[service][1], "image_id": plan[service][0]} - for service in APP_SERVICES - } - write_json_atomic(STATE_FILE, { - "schema_version": 1, - "commit": "rollback", - "manifest_sha256": "rollback", - "current": restored, - "previous": state["current"], - }) - state_written = True - JOURNAL_FILE.unlink(missing_ok=True) - except Exception as error: - if state is not None: - from release_refs import read_images, replace_images - from release_state import write_json_atomic - - journal["status"] = "rollback-failed" - journal["error_type"] = type(error).__name__ - if state_written: - journal["status"] = "rollback-active-journal-cleanup-needed" - journal["recovery"] = "rollback refs, release state, and health check completed; verify host and resolve journal" - write_json_atomic(JOURNAL_FILE, journal) - raise ValueError(f"rollback is active; recovery journal preserved at {JOURNAL_FILE}") from error - try: - current_text, current_env = read_images(ENV_FILE) - del current_text - active = {"BACKEND_IMAGE": current_env["BACKEND_IMAGE"], "OPENSEARCH_IMAGE": current_env["OPENSEARCH_IMAGE"]} - if active == after: - replace_images(ENV_FILE, after, before) - elif active != before: - raise ValueError("image references match neither the rolled-back nor pre-rollback release") - _, verified_env = read_images(ENV_FILE) - if {"BACKEND_IMAGE": verified_env["BACKEND_IMAGE"], - "OPENSEARCH_IMAGE": verified_env["OPENSEARCH_IMAGE"]} != before: - raise ValueError("pre-rollback image references could not be verified") - compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") - require_running_image_ids(expected_current, running_image_ids(), "previous release state") - record_backend_image() - write_json_atomic(STATE_FILE, state) - journal["recovery"] = "current release references restored; verify service health" - except Exception as recovery_error: - journal["recovery"] = f"manual recovery required ({type(recovery_error).__name__})" - write_json_atomic(JOURNAL_FILE, journal) - else: - from release_state import write_json_atomic - - journal["status"] = "rollback-failed" - journal["error_type"] = type(error).__name__ - try: - compose("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300") - require_running_image_ids(current_running_ids, running_image_ids(), "pre-rollback deployment") - record_backend_image() - journal["recovery"] = "legacy release restarted; verify service health" - except Exception as recovery_error: - journal["recovery"] = f"manual recovery required ({type(recovery_error).__name__})" - write_json_atomic(JOURNAL_FILE, journal) - raise - print(f"PASS application images restored from {backup}; pre-rollback backup: {backup_output}") + raise ValueError(f"external rollback failed; recovery journal preserved at {JOURNAL_FILE}") from error def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("backup", type=Path) - parser.add_argument("--data-compatible", action="store_true") - args = parser.parse_args() - try: - if os.geteuid() != 0: - raise ValueError("rollback must run through the restricted root helper") - rollback(args.backup, args.data_compatible) - except Exception as error: - print(f"ERROR: {error}", file=sys.stderr) - return 1 - return 0 + print("ERROR: local VPS backup paths are disabled; use the owner-controlled external rollback session", file=sys.stderr) + return 1 if __name__ == "__main__": diff --git a/infra/deploy/test_deploy_release.py b/infra/deploy/test_deploy_release.py index ff3a2f6..b5717ec 100644 --- a/infra/deploy/test_deploy_release.py +++ b/infra/deploy/test_deploy_release.py @@ -76,49 +76,16 @@ class DeploymentCutoverTests(unittest.TestCase): deploy_release.restore_previous_references(old, new) self.assertEqual(release_refs.read_images(env_file)[1], old) - def test_failure_after_atomic_ref_switch_keeps_recovery_journal(self): - with tempfile.TemporaryDirectory() as directory: - directory = Path(directory) - manifest_file = directory / "release.json" - manifest_file.write_text("{}", encoding="utf-8") - policy_file = directory / "policy.json" - policy_file.write_text("{}", encoding="utf-8") - target = { - "backend": "registry/backend@sha256:" + "c" * 64, - "opensearch": "registry/opensearch@sha256:" + "d" * 64, - } - manifest = {"builder": {"name": "Kaniko", "image": deploy_release.BUILDER_IMAGE}, - "images": target, "commit": "e" * 40} - backup_path = deploy_release.BACKUP_DIR / "backup.tar.gz" - compose_calls = [None, subprocess.CalledProcessError(1, "compose up"), None] - run_calls = ["", "sha256:" + "c" * 64, "", "sha256:" + "d" * 64, - "sha256:" + "c" * 64, "sha256:" + "d" * 64] - with ( - patch.object(deploy_release.os, "geteuid", return_value=0), - patch.object(deployment_lock, "LOCK_FILE", directory / "deploy.lock"), - patch.object(deployment_lock.os, "fstat", return_value=SimpleNamespace( - st_mode=stat.S_IFREG | 0o600, st_uid=0 - )), - patch.object(deploy_release, "JOURNAL_FILE", directory / "recovery.json"), - patch.object(deploy_release, "STATE_FILE", directory / "state.json"), - patch.object(deploy_release, "read_manifest_json", side_effect=[{}, {}]), - patch.object(deploy_release, "validate_manifest", return_value=manifest), - patch.object(deploy_release, "image_ids", return_value=self.current), - patch.object(deploy_release, "backup_manifest", return_value={"images": self.current}), - patch.object(deploy_release, "run", side_effect=run_calls), - patch.object(deploy_release, "compose", side_effect=compose_calls) as compose, - patch.object(deploy_release, "replace_images") as replace, - patch.object(deploy_release, "restore_previous_references") as restore, - ): - with self.assertRaisesRegex(ValueError, "recovery journal preserved"): - deploy_release.deploy(manifest_file, backup_path, policy_file, "закон", "мыйзам") - self.assertEqual(replace.call_count, 1) - restore.assert_called_once() - self.assertEqual(compose.call_args_list[-1].args, ("up", "--detach", "--no-build", "--wait", "--wait-timeout", "300")) - journal = json.loads((directory / "recovery.json").read_text(encoding="utf-8")) - self.assertEqual(journal["status"], "cutover-failed") - self.assertIn("recovery", journal) - self.assertFalse((directory / "state.json").exists()) + def test_external_cutover_rejects_unvalidated_release_before_docker_operations(self): + with patch.object(deploy_release.os, "geteuid", return_value=0), patch.object(deploy_release, "run") as run_mock, patch.object(deploy_release, "compose") as compose_mock: + with self.assertRaisesRegex(ValueError, "manifest must contain exactly"): + deploy_release.deploy_external( + {}, {"schema_version": 1, "repositories": { + "backend": ["registry/backend"], "opensearch": ["registry/search"] + }}, {}, {}, "0" * 64, self.current, "ру", "кыргызча" + ) + run_mock.assert_not_called() + compose_mock.assert_not_called() if __name__ == "__main__": diff --git a/infra/deploy/test_external_rollback.py b/infra/deploy/test_external_rollback.py new file mode 100644 index 0000000..6f79ec2 --- /dev/null +++ b/infra/deploy/test_external_rollback.py @@ -0,0 +1,79 @@ +import hashlib +import io +import json +import sys +import tempfile +import unittest +from contextlib import nullcontext +from pathlib import Path +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "backup")) + +import external_rollback +from external_session import read_challenge, write_request +from release_state import read_json, validate_state + + +class ExternalRollbackTests(unittest.TestCase): + def test_release_state_rejects_boolean_schema_version(self): + with self.assertRaisesRegex(ValueError, "unsupported schema"): + validate_state({ + "schema_version": True, "commit": "a" * 40, + "manifest_sha256": "b" * 64, "current": {}, "previous": {}, + }) + + def test_release_state_rejects_duplicate_identity_fields(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "state.json" + path.write_text('{"schema_version":1,"schema_version":2}', encoding="utf-8") + with self.assertRaisesRegex(ValueError, "duplicate release state field"): + read_json(path) + + def test_unpinned_archive_stream_fails_before_service_operations(self): + manifest = {"git_revision": "a" * 40} + identity = { + "backup_id": "akyldash-20261031T120000Z-12345678", "size": 64, + "archive_sha256": "b" * 64, + "manifest_sha256": hashlib.sha256( + json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest(), + "manifest": manifest, + } + state = { + "schema_version": 2, "commit": "c" * 40, "manifest_sha256": "d" * 64, + "current": { + "backend": {"configured": "registry/backend:current", "image_id": "sha256:" + "1" * 64}, + "opensearch": {"configured": "registry/search:current", "image_id": "sha256:" + "2" * 64}, + }, + "previous": { + "backend": {"configured": "registry/backend:old", "image_id": "sha256:" + "3" * 64}, + "opensearch": {"configured": "registry/search:old", "image_id": "sha256:" + "4" * 64}, + }, + "previous_backup": identity, + } + request = io.BytesIO() + write_request(request, {"version": 1, "action": "rollback", "data_compatible": True}) + request.seek(0) + response = io.BytesIO() + with tempfile.TemporaryDirectory() as directory, \ + patch.object(external_rollback.os, "geteuid", return_value=0), \ + patch.object(external_rollback, "STATE_FILE", Path(directory) / "state.json"), \ + patch.object(external_rollback, "JOURNAL_FILE", Path(directory) / "journal.json"), \ + patch.object(external_rollback, "read_json", return_value=state), \ + patch.object(external_rollback, "deployment_lock", return_value=nullcontext()), \ + patch.object(external_rollback, "nonce", return_value="e" * 64), \ + patch.object(external_rollback, "receive_archive", return_value=(64, "f" * 64)), \ + patch.object(external_rollback, "image_ids") as image_ids, \ + patch.object(external_rollback, "compose") as compose: + with self.assertRaisesRegex(ValueError, "root-pinned"): + external_rollback.execute(reader=request, writer=response) + response.seek(0) + challenge = read_challenge(response) + self.assertEqual(challenge["backup_id"], identity["backup_id"]) + image_ids.assert_not_called() + compose.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/infra/deploy/test_gitea_api_binary.py b/infra/deploy/test_gitea_api_binary.py new file mode 100644 index 0000000..a78d50c --- /dev/null +++ b/infra/deploy/test_gitea_api_binary.py @@ -0,0 +1,155 @@ +import hashlib +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +FIXTURE = ROOT / "infra/deploy/gitea-api-base.fixture" +PATCH = ROOT / "infra/deploy/gitea-api-binary-download.patch" +FIXTURE_SHA256 = "8227332d28e27bcce9b4e3801f6b8d4323636174a82c93a0177970f560629df0" + + +FAKE_CURL = r'''#!/usr/bin/env python3 +import os +import sys +from pathlib import Path + +args = sys.argv[1:] +config = sys.stdin.read() if "--config" in args else "" +def value(flag, default=None): + return args[args.index(flag) + 1] if flag in args else default + +url = args[-1] +mode = os.environ["FAKE_CURL_MODE"] +log = Path(os.environ["FAKE_CURL_LOG"]) +log.write_text(log.read_text() + url + "\n" if log.exists() else url + "\n") +headers = value("-D") +output = value("-o") +has_token = "Authorization: token fixture-secret" in config or any(arg == "Authorization: token fixture-secret" for arg in args) +if any("fixture-secret" in arg for arg in args): + Path(os.environ["FAKE_TOKEN_ARGS"]).write_text("leaked") +if "gitea.test" in url and has_token: + Path(os.environ["FAKE_GITEA_AUTH"]).write_text("True") +if "blob.test" in url or not value("-w"): + if "blob.test" in url: + Path(os.environ["FAKE_BLOB_AUTH"]).write_text(str(has_token)) + body = b"zip-fixture-bytes" + if mode == "oversize": + body = b"x" * (10 * 1024 * 1024 + 10) + try: + if output and output != "-": + Path(output).write_bytes(body) + else: + sys.stdout.buffer.write(body) + sys.stdout.buffer.flush() + except BrokenPipeError: + raise SystemExit(23) + if value("-w"): + print("200", end="") + raise SystemExit(0) + +if value("-w"): + code = "302" if mode in {"redirect", "unlisted", "oversize"} else "200" + if headers: + location = "https://blob.test/archive.zip" if mode != "unlisted" else "https://evil.test/archive.zip" + Path(headers).write_text(f"HTTP/1.1 {code} Fixture\r\nLocation: {location}\r\n\r\n") + print(code, end="") + raise SystemExit(0) + +raise SystemExit(99) +''' + + +class GiteaApiBinaryDownloadTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.bin = self.root / "bin" + self.bin.mkdir() + self.helper = self.root / "gitea-api" + shutil.copyfile(FIXTURE, self.helper) + self.helper.chmod(0o700) + applied = subprocess.run( + ["patch", "-p1", "-i", str(PATCH)], cwd=self.root, + text=True, capture_output=True, + ) + if applied.returncode: + self.fail(applied.stderr or applied.stdout) + self.curl = self.bin / "curl" + self.curl.write_text(FAKE_CURL, encoding="utf-8") + self.curl.chmod(0o700) + self.log = self.root / "calls" + self.auth = self.root / "blob-auth" + self.gitea_auth = self.root / "gitea-auth" + self.token_args = self.root / "token-args" + + def tearDown(self): + self.temp.cleanup() + + def run_download(self, mode, output, origins="https://blob.test"): + env = { + **os.environ, + "PATH": f"{self.bin}:{os.environ['PATH']}", + "GITEA_URL": "https://gitea.test", + "GITEA_TOKEN": "fixture-secret", + "GITEA_DOWNLOAD_ORIGINS": origins, + "FAKE_CURL_MODE": mode, + "FAKE_CURL_LOG": str(self.log), + "FAKE_BLOB_AUTH": str(self.auth), + "FAKE_GITEA_AUTH": str(self.gitea_auth), + "FAKE_TOKEN_ARGS": str(self.token_args), + } + return subprocess.run( + [str(self.helper), "DOWNLOAD", "/repos/admin/akyldash/actions/artifacts/7/zip", str(output)], + env=env, text=True, capture_output=True, + ) + + def test_fixture_is_exact_audited_helper_and_patch_applies(self): + self.assertEqual(hashlib.sha256(FIXTURE.read_bytes()).hexdigest(), FIXTURE_SHA256) + + def test_downloads_allowlisted_https_redirect_without_forwarding_token(self): + output = self.root / "artifact.zip" + result = self.run_download("redirect", output) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(output.read_bytes(), b"zip-fixture-bytes") + self.assertEqual(output.stat().st_mode & 0o777, 0o600) + self.assertEqual(self.auth.read_text(), "False") + self.assertTrue(self.gitea_auth.exists()) + self.assertFalse(self.token_args.exists()) + + def test_downloads_direct_https_response_from_gitea(self): + output = self.root / "artifact.zip" + result = self.run_download("direct", output) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(output.read_bytes(), b"zip-fixture-bytes") + self.assertTrue(self.gitea_auth.exists()) + self.assertFalse(self.token_args.exists()) + + def test_refuses_unlisted_redirect_before_fetching_target(self): + output = self.root / "artifact.zip" + result = self.run_download("unlisted", output) + self.assertNotEqual(result.returncode, 0) + self.assertIn("not allowlisted", result.stderr) + self.assertFalse(output.exists()) + self.assertNotIn("evil.test", self.log.read_text()) + + def test_caps_chunked_response_and_does_not_publish_partial_file(self): + output = self.root / "artifact.zip" + result = self.run_download("oversize", output) + self.assertNotEqual(result.returncode, 0) + self.assertIn("10 MiB", result.stderr) + self.assertFalse(output.exists()) + + def test_refuses_to_overwrite_existing_output(self): + output = self.root / "artifact.zip" + output.write_bytes(b"keep") + result = self.run_download("redirect", output) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(output.read_bytes(), b"keep") + + +if __name__ == "__main__": + unittest.main() diff --git a/infra/deploy/test_release_manifest.py b/infra/deploy/test_release_manifest.py index 3344f82..2d1760e 100644 --- a/infra/deploy/test_release_manifest.py +++ b/infra/deploy/test_release_manifest.py @@ -21,12 +21,13 @@ class ReleaseManifestTests(unittest.TestCase): def setUp(self): self.policy = {"schema_version": 1, "repositories": REPOSITORIES} self.manifest = { - "schema_version": 3, + "schema_version": 4, "source_ref": "refs/heads/main", "repository": "admin/akyldash", "commit": "a" * 40, "workflow": ".gitea/workflows/release-images.yaml", "run_id": "49", + "source_run_id": "48", "builder": BUILDER, "images": { "backend": "git.vakanaut.ru/admin/akyldash/backend@sha256:" + "b" * 64, @@ -86,8 +87,8 @@ class ReleaseManifestTests(unittest.TestCase): manifest_path = Path(directory) / "manifest.json" policy_path = Path(directory) / "policy.json" manifest_path.write_text( - '{"schema_version":3,"source_ref":"refs/heads/main","repository":"admin/akyldash","commit":"' + "a" * 40 - + '","workflow":".gitea/workflows/release-images.yaml","run_id":"49","builder":{},"images":{"backend":"first","backend":"second","opensearch":"third"}}', + '{"schema_version":4,"source_ref":"refs/heads/main","repository":"admin/akyldash","commit":"' + "a" * 40 + + '","workflow":".gitea/workflows/release-images.yaml","run_id":"49","source_run_id":"48","builder":{},"images":{"backend":"first","backend":"second","opensearch":"third"}}', encoding="utf-8", ) policy_path.write_text(json.dumps(self.policy), encoding="utf-8") @@ -147,11 +148,12 @@ class ReleaseManifestTests(unittest.TestCase): backend, opensearch = Path(directory) / "backend", Path(directory) / "opensearch" backend.write_text("sha256:" + "b" * 64, encoding="ascii") opensearch.write_text("sha256:" + "c" * 64, encoding="ascii") - result = create("admin/akyldash", "a" * 40, "49", backend, opensearch) + result = create("admin/akyldash", "a" * 40, "48", "49", backend, opensearch) self.assertEqual(validate_manifest(result, self.policy), result) self.assertEqual(result["workflow"], ".gitea/workflows/release-images.yaml") self.assertEqual(result["builder"], BUILDER) self.assertEqual(result["run_id"], "49") + self.assertEqual(result["source_run_id"], "48") self.assertNotIn("run_attempt", result) def test_manifest_creation_rejects_missing_digest(self): @@ -160,7 +162,7 @@ class ReleaseManifestTests(unittest.TestCase): backend.write_text("", encoding="ascii") opensearch.write_text("sha256:" + "c" * 64, encoding="ascii") with self.assertRaisesRegex(ValueError, "invalid Kaniko digest"): - create("admin/akyldash", "a" * 40, "49", backend, opensearch) + create("admin/akyldash", "a" * 40, "48", "49", backend, opensearch) if __name__ == "__main__": diff --git a/infra/deploy/test_release_source.py b/infra/deploy/test_release_source.py new file mode 100644 index 0000000..a5b386e --- /dev/null +++ b/infra/deploy/test_release_source.py @@ -0,0 +1,173 @@ +import hashlib +import json +import stat +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest.mock import patch + +import release_source + +POLICY = { + "schema_version": 1, + "repositories": { + "backend": ["registry.test/akyldash/backend"], + "opensearch": ["registry.test/akyldash/opensearch"], + }, +} +COMMIT = "a" * 40 +RELEASE_RUN = "302" +CI_RUN = "301" +MANIFEST = { + "schema_version": 4, + "source_ref": "refs/heads/main", + "repository": "admin/akyldash", + "commit": COMMIT, + "workflow": ".gitea/workflows/release-images.yaml", + "run_id": RELEASE_RUN, + "source_run_id": CI_RUN, + "builder": {"name": "Kaniko", "image": "ghcr.io/osscontainertools/kaniko:v1.28.5-debug@sha256:c73ca67a3b494bce79a8fb6090c4f73c18997ab272d80bffc460a62343aeb412"}, + "images": { + "backend": "registry.test/akyldash/backend@sha256:" + "b" * 64, + "opensearch": "registry.test/akyldash/opensearch@sha256:" + "c" * 64, + }, +} + + +def write_artifact(path, manifest=MANIFEST, extra=()): + raw = json.dumps(manifest, sort_keys=True).encode() + digest = hashlib.sha256(raw).hexdigest() + with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive: + archive.writestr("release-manifest.json", raw) + archive.writestr("release-manifest.json.sha256", f"{digest} release-manifest.json\n") + for name, payload in extra: + archive.writestr(name, payload) + return digest, raw + + +class ReleaseSourceTests(unittest.TestCase): + def test_verify_run_binds_run_id_workflow_path_event_branch_commit_and_main(self): + def api(path): + if path.endswith("/actions/runs/301"): + return {"id": 301, "workflow_id": "ci.yaml", "name": "CI", "status": "success", + "conclusion": "success", "head_sha": COMMIT, "head_branch": "main", "event": "push"} + return {"id": "ci.yaml", "name": "CI", "path": ".gitea/workflows/ci.yaml"} + run = release_source.verify_run(CI_RUN, stage="ci", commit=COMMIT, api=api, current_main=COMMIT) + self.assertEqual(run["head_sha"], COMMIT) + with self.assertRaisesRegex(ValueError, "workflow run is not successful"): + release_source.verify_run(CI_RUN, stage="ci", commit=COMMIT, + api=lambda path: {"id": 301, "status": "failure"}, current_main=COMMIT) + + def test_zip_descriptor_checks_exact_members_digest_source_ids_and_allowlist(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "artifact.zip" + digest, _ = write_artifact(path) + manifest, raw = release_source.validate_artifact_zip( + path, descriptor_sha256=digest, release_run_id=RELEASE_RUN, + ci_run_id=CI_RUN, commit=COMMIT, policy=POLICY, + ) + self.assertEqual(manifest, MANIFEST) + self.assertEqual(hashlib.sha256(raw).hexdigest(), digest) + with self.assertRaisesRegex(ValueError, "requested SHA-256"): + release_source.validate_artifact_zip( + path, descriptor_sha256="d" * 64, release_run_id=RELEASE_RUN, + ci_run_id=CI_RUN, commit=COMMIT, policy=POLICY, + ) + with self.assertRaisesRegex(ValueError, "does not bind"): + release_source.validate_artifact_zip( + path, descriptor_sha256=digest, release_run_id=RELEASE_RUN, + ci_run_id="999", commit=COMMIT, policy=POLICY, + ) + + def test_zip_refuses_extra_traversal_duplicate_and_symlink_members(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + extras = ( + (("../outside", b"x"),), + (("release-manifest.json", b"duplicate"),), + ) + for extra in extras: + path = root / f"bad-{len(list(root.iterdir()))}.zip" + digest, _ = write_artifact(path, extra=extra) + with self.assertRaises(ValueError): + release_source.validate_artifact_zip( + path, descriptor_sha256=digest, release_run_id=RELEASE_RUN, + ci_run_id=CI_RUN, commit=COMMIT, policy=POLICY, + ) + + path = root / "symlink.zip" + raw = json.dumps(MANIFEST, sort_keys=True).encode() + digest = hashlib.sha256(raw).hexdigest() + with zipfile.ZipFile(path, "w") as archive: + info = zipfile.ZipInfo("release-manifest.json") + info.create_system = 3 + info.external_attr = (stat.S_IFLNK | 0o777) << 16 + archive.writestr(info, raw) + archive.writestr("release-manifest.json.sha256", f"{digest} release-manifest.json\n") + with self.assertRaisesRegex(ValueError, "unsafe"): + release_source.validate_artifact_zip( + path, descriptor_sha256=digest, release_run_id=RELEASE_RUN, + ci_run_id=CI_RUN, commit=COMMIT, policy=POLICY, + ) + + def test_fetch_release_rechecks_both_runs_and_uses_only_gitea_api_helper(self): + with tempfile.TemporaryDirectory() as fixture_dir: + fixture_zip = Path(fixture_dir) / "artifact.zip" + descriptor_sha, _ = write_artifact(fixture_zip) + request = {"run_id": RELEASE_RUN, "commit": COMMIT, "descriptor_sha256": descriptor_sha} + artifact_id = 77 + run_responses = { + f"/repos/admin/akyldash/actions/runs/{RELEASE_RUN}": { + "id": int(RELEASE_RUN), "workflow_id": "release-images.yaml", "name": "Release production images", + "status": "success", "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", + }, + f"/repos/admin/akyldash/actions/runs/{CI_RUN}": { + "id": int(CI_RUN), "workflow_id": "ci.yaml", "name": "CI", "status": "success", + "conclusion": "success", "head_sha": COMMIT, "head_branch": "main", "event": "push", + }, + "/repos/admin/akyldash/actions/workflows/ci.yaml": { + "id": "ci.yaml", "name": "CI", "path": ".gitea/workflows/ci.yaml", + }, + f"/repos/admin/akyldash/actions/runs/{RELEASE_RUN}/artifacts": { + "artifacts": [{ + "id": artifact_id, "name": f"release-descriptor-{RELEASE_RUN}-{descriptor_sha}", + "expired": False, + "workflow_run": {"id": int(RELEASE_RUN), "head_sha": COMMIT, + "head_branch": "main", "event": "workflow_run", "conclusion": "success"}, + }] + }, + } + with tempfile.TemporaryDirectory() as directory: + scratch = Path(directory) / "scratch" + scratch.mkdir(mode=0o700) + calls = [] + + def api(path): + calls.append(path) + return run_responses[path] + + def subprocess_run(command, **kwargs): + calls.append(command) + path = Path(command[-1]) + write_artifact(path) + return type("Result", (), {"stdout": "PASS", "returncode": 0})() + + # 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): + manifest, raw = release_source.fetch_release( + request, policy=POLICY, temp_dir=scratch, api=api, current_main=COMMIT + ) + self.assertEqual(manifest, MANIFEST) + self.assertEqual(hashlib.sha256(raw).hexdigest(), descriptor_sha) + self.assertTrue(any(isinstance(call, list) and call[1] == "DOWNLOAD" for call in calls)) + + +if __name__ == "__main__": + unittest.main() diff --git a/infra/deploy/test_rollback.py b/infra/deploy/test_rollback.py index d64e0be..f7a787b 100644 --- a/infra/deploy/test_rollback.py +++ b/infra/deploy/test_rollback.py @@ -105,232 +105,12 @@ class RollbackPlanTests(unittest.TestCase): tag_previous_images(plan) run_mock.assert_not_called() - def test_digest_rollback_fails_before_stopping_or_changing_references(self): - backend_id = "sha256:" + "a" * 64 - opensearch_id = "sha256:" + "b" * 64 - digest = "registry/backend@sha256:" + "c" * 64 - manifest = { - "images": { - "backend": {"configured": digest, "image_id": backend_id}, - "opensearch": self.manifest["images"]["opensearch"], - }, - "deployment_files": { - "deploy/production/compose.yaml": "compose-hash", - "deploy/production/Caddyfile": "caddy-hash", - }, - } - rendered = { - "services": { - "backend": {"image": digest}, - "opensearch": {"image": self.configured["opensearch"]}, - } - } - fake_archive = SimpleNamespace( - digest=lambda path: "compose-hash" if path.name == "compose.yaml" else "caddy-hash", - verify_archive=lambda _backup: manifest, - ) - with tempfile.TemporaryDirectory() as temporary: - temporary = rollback.Path(temporary) - backup_dir = temporary / "backups" - backup_dir.mkdir() - backup = backup_dir / "synthetic.tar.gz" - original_stat = rollback.Path.stat - - def stat_backup_only(path, *args, **kwargs): - if path in {backup, rollback.Path(f"{backup}.sha256")}: - return SimpleNamespace(st_uid=0, st_mode=0o100600) - return original_stat(path, *args, **kwargs) - - with ( - patch.object(deployment_lock, "LOCK_FILE", temporary / "deploy.lock"), - patch.object(rollback, "JOURNAL_FILE", temporary / "recovery.json"), - patch.object(rollback, "STATE_FILE", temporary / "release-state.json"), - patch.object(rollback, "ENV_FILE", temporary / "production.env"), - patch.object(rollback, "DEPLOYED_IMAGE_FILE", temporary / "deployed-image.txt"), - patch.object(rollback, "BACKUP_DIR", backup_dir), - patch.object(rollback, "ROOT", temporary / "checkout"), - patch.object(rollback, "COMPOSE_FILE", temporary / "checkout/deploy/production/compose.yaml"), - patch.object(rollback, "BACKUP_TOOL", temporary / "archive.py"), - patch("rollback.Path.is_file", return_value=True), - patch("rollback.Path.is_symlink", return_value=False), - patch("pathlib.Path.stat", autospec=True, side_effect=stat_backup_only), - patch("rollback.compose", return_value=json.dumps(rendered)) as compose_mock, - patch("rollback.running_image_ids", return_value={ - "backend": backend_id, - "opensearch": self.manifest["images"]["opensearch"]["image_id"], - }), - patch("rollback.run", side_effect=[backend_id, backend_id, opensearch_id]) as run_mock, - patch.dict(sys.modules, {"archive": fake_archive}), - ): - with self.assertRaisesRegex(ValueError, "not supported safely"): - rollback.rollback(backup, data_compatible=True) - compose_mock.assert_called_once_with("config", "--format", "json", capture=True) - self.assertEqual(run_mock.call_count, 3) - self.assertTrue(all(call.args[0][:3] == ["docker", "image", "inspect"] - for call in run_mock.call_args_list)) - - def test_mismatched_release_backup_is_rejected_before_stopping_services(self): - current = { - "backend": {"configured": "registry/backend@sha256:" + "d" * 64, "image_id": "sha256:" + "e" * 64}, - "opensearch": {"configured": "registry/search@sha256:" + "f" * 64, "image_id": "sha256:" + "1" * 64}, - } - previous = { - "backend": {"configured": "registry/backend@sha256:" + "a" * 64, "image_id": "sha256:" + "2" * 64}, - "opensearch": {"configured": "registry/search@sha256:" + "b" * 64, "image_id": "sha256:" + "3" * 64}, - } - manifest = { - "images": { - "backend": {"configured": "registry/backend@sha256:" + "c" * 64, "image_id": previous["backend"]["image_id"]}, - "opensearch": previous["opensearch"], - }, - "deployment_files": {"deploy/production/compose.yaml": "compose-hash", "deploy/production/Caddyfile": "caddy-hash"}, - } - state = {"schema_version": 1, "commit": "a" * 40, "manifest_sha256": "b" * 64, - "current": current, "previous": previous} - rendered = {"services": {"backend": {"image": current["backend"]["configured"]}, - "opensearch": {"image": current["opensearch"]["configured"]}}} - fake_archive = SimpleNamespace( - digest=lambda path: "compose-hash" if path.name == "compose.yaml" else "caddy-hash", - verify_archive=lambda _backup: manifest, - ) - with tempfile.TemporaryDirectory() as directory: - root = rollback.Path(directory) - backup_dir = root / "backups" - backup_dir.mkdir() - backup = backup_dir / "synthetic.tar.gz" - state_file = root / "release-state.json" - checksum = rollback.Path(f"{backup}.sha256") - original_stat = rollback.Path.stat - - def stat_backup_only(path, *args, **kwargs): - if path in {backup, checksum}: - return SimpleNamespace(st_uid=0, st_mode=0o100600) - return original_stat(path, *args, **kwargs) - - with ( - patch.object(deployment_lock, "LOCK_FILE", root / "deploy.lock"), - patch.object(rollback, "JOURNAL_FILE", root / "recovery.json"), - patch.object(rollback, "STATE_FILE", state_file), - patch.object(rollback, "ENV_FILE", root / "production.env"), - patch.object(rollback, "DEPLOYED_IMAGE_FILE", root / "deployed-image.txt"), - patch.object(rollback, "BACKUP_DIR", backup_dir), - patch.object(rollback, "ROOT", root / "checkout"), - patch.object(rollback, "COMPOSE_FILE", root / "checkout/deploy/production/compose.yaml"), - patch.object(rollback, "BACKUP_TOOL", root / "archive.py"), - patch("pathlib.Path.exists", autospec=True, side_effect=lambda path: path == state_file), - patch("pathlib.Path.is_file", return_value=True), - patch("pathlib.Path.is_symlink", return_value=False), - patch("pathlib.Path.stat", autospec=True, side_effect=stat_backup_only), - patch("rollback.compose", side_effect=lambda *args, **_kwargs: ( - json.dumps(rendered) if args[:2] == ("config", "--format") - else "backend-container" if args[-1] == "backend" - else "search-container" - )) as compose_mock, - patch("rollback.run", side_effect=lambda command, **_kwargs: "true\t" + current[ - "backend" if command[-1] == "backend-container" else "opensearch" - ]["image_id"]), - patch("release_state.read_json", return_value=state), - patch.dict(sys.modules, {"archive": fake_archive}), - ): - with self.assertRaisesRegex(ValueError, "backup does not match the pinned previous backend"): - rollback.rollback(backup, data_compatible=True) - self.assertFalse(any(call.args and call.args[0] == "stop" for call in compose_mock.call_args_list)) - - def test_mismatched_running_rollback_images_preserve_state_and_recovery_journal(self): - current = { - "backend": {"configured": "registry/backend@sha256:" + "d" * 64, "image_id": "sha256:" + "e" * 64}, - "opensearch": {"configured": "registry/search@sha256:" + "f" * 64, "image_id": "sha256:" + "1" * 64}, - } - previous = { - "backend": {"configured": "akyldash/backend:previous", "image_id": "sha256:" + "a" * 64}, - "opensearch": {"configured": "akyldash/opensearch:previous", "image_id": "sha256:" + "b" * 64}, - } - manifest = { - "images": previous, - "deployment_files": {"deploy/production/compose.yaml": "compose-hash", - "deploy/production/Caddyfile": "caddy-hash"}, - } - state = {"schema_version": 1, "commit": "a" * 40, "manifest_sha256": "b" * 64, - "current": current, "previous": previous} - current_refs = {"BACKEND_IMAGE": current["backend"]["configured"], - "OPENSEARCH_IMAGE": current["opensearch"]["configured"]} - previous_refs = {"BACKEND_IMAGE": previous["backend"]["configured"], - "OPENSEARCH_IMAGE": previous["opensearch"]["configured"]} - rendered = {"services": {"backend": {"image": current_refs["BACKEND_IMAGE"]}, - "opensearch": {"image": current_refs["OPENSEARCH_IMAGE"]}}} - fake_archive = SimpleNamespace( - digest=lambda path: "compose-hash" if path.name == "compose.yaml" else "caddy-hash", - verify_archive=lambda _backup: manifest, - ) - expected_current_ids = {service: current[service]["image_id"] for service in current} - unexpected_ids = {"backend": previous["backend"]["image_id"], - "opensearch": "sha256:" + "c" * 64} - - with tempfile.TemporaryDirectory() as directory: - root = rollback.Path(directory) - backup_dir = root / "backups" - backup_dir.mkdir() - backup = backup_dir / "verified.tar.gz" - state_file = root / "state.json" - state_file.write_text(json.dumps(state), encoding="utf-8") - env_file = root / "production.env" - env_file.write_text( - f"BACKEND_IMAGE={current_refs['BACKEND_IMAGE']}\n" - f"OPENSEARCH_IMAGE={current_refs['OPENSEARCH_IMAGE']}\n", - encoding="utf-8", - ) - checksum = rollback.Path(f"{backup}.sha256") - original_stat = rollback.Path.stat - - def stat_backup_only(path, *args, **kwargs): - if path in {backup, checksum}: - return SimpleNamespace(st_uid=0, st_mode=0o100600) - return original_stat(path, *args, **kwargs) - - original_replace = release_refs.replace_images - - def replace_without_root(path, expected, replacement): - return original_replace(path, expected, replacement, require_root=False) - - with ( - patch.object(deployment_lock, "LOCK_FILE", root / "deploy.lock"), - patch.object(rollback, "JOURNAL_FILE", root / "recovery.json"), - patch.object(rollback, "STATE_FILE", state_file), - patch.object(rollback, "ENV_FILE", env_file), - patch.object(rollback, "DEPLOYED_IMAGE_FILE", root / "deployed-image.txt"), - patch.object(rollback, "BACKUP_DIR", backup_dir), - patch.object(rollback, "ROOT", root / "checkout"), - patch.object(rollback, "COMPOSE_FILE", root / "checkout/deploy/production/compose.yaml"), - patch.object(rollback, "BACKUP_TOOL", root / "archive.py"), - patch("pathlib.Path.is_file", return_value=True), - patch("pathlib.Path.is_symlink", return_value=False), - patch("pathlib.Path.stat", autospec=True, side_effect=stat_backup_only), - patch("rollback.compose", side_effect=lambda *args, **_kwargs: ( - json.dumps(rendered) if args[:2] == ("config", "--format") - else "backend-container" if args[-1] == "backend" - else "search-container" if args[-1] == "opensearch" - else "" - )), - patch("rollback.running_image_ids", side_effect=[ - expected_current_ids, unexpected_ids, expected_current_ids - ]), - patch("rollback.run", side_effect=lambda command, **_kwargs: ( - command[-1] if command[1:3] == ["image", "inspect"] - else current["backend"]["image_id"] if command[:2] == ["docker", "inspect"] - else "" - )), - patch("release_refs.replace_images", side_effect=replace_without_root), - patch("release_state.read_json", return_value=state), - patch("release_state.write_json_atomic", wraps=release_state.write_json_atomic), - patch.dict(sys.modules, {"archive": fake_archive}), - ): - with self.assertRaisesRegex(ValueError, "rollback plan"): - rollback.rollback(backup, data_compatible=True) - journal = json.loads((root / "recovery.json").read_text(encoding="utf-8")) - self.assertEqual(journal["status"], "rollback-failed") - self.assertIn("current release references restored", journal["recovery"]) - self.assertEqual(json.loads(state_file.read_text(encoding="utf-8")), state) - self.assertEqual(release_refs.read_images(env_file)[1], current_refs) + def test_local_vps_backup_path_is_disabled_without_docker_operations(self): + with patch("rollback.compose") as compose_mock, patch("rollback.run") as run_mock: + with self.assertRaisesRegex(ValueError, "local VPS backup paths are disabled"): + rollback.rollback(rollback.Path("/var/backups/akyldash/old.tar.gz"), data_compatible=True) + compose_mock.assert_not_called() + run_mock.assert_not_called() def test_tag_rollback_keeps_existing_image_tag_operation(self): plan = image_restore_plan(self.manifest, self.configured) diff --git a/infra/deploy/validate_release.py b/infra/deploy/validate_release.py index a0ffc17..c8b9409 100644 --- a/infra/deploy/validate_release.py +++ b/infra/deploy/validate_release.py @@ -59,10 +59,10 @@ def validate_policy(policy: object) -> dict[str, list[str]]: def validate_manifest(manifest: object, policy: object) -> dict[str, object]: allowed_repositories = validate_policy(policy) if not isinstance(manifest, dict) or set(manifest) != { - "schema_version", "source_ref", "repository", "commit", "workflow", "run_id", "builder", "images" + "schema_version", "source_ref", "repository", "commit", "workflow", "run_id", "source_run_id", "builder", "images" }: raise ValueError("manifest must contain exactly the release source, builder, run, and image fields") - if type(manifest["schema_version"]) is not int or manifest["schema_version"] != 3: + if type(manifest["schema_version"]) is not int or manifest["schema_version"] != 4: raise ValueError("unsupported manifest schema_version") if manifest["source_ref"] != "refs/heads/main": raise ValueError("manifest source_ref must be refs/heads/main") @@ -75,6 +75,8 @@ def validate_manifest(manifest: object, policy: object) -> dict[str, object]: raise ValueError("manifest workflow is not the approved image release workflow") if not isinstance(manifest["run_id"], str) or not re.fullmatch(r"[0-9]+", manifest["run_id"]): raise ValueError("manifest run_id must be a numeric Gitea Actions run ID") + if not isinstance(manifest["source_run_id"], str) or not re.fullmatch(r"[0-9]+", manifest["source_run_id"]): + raise ValueError("manifest source_run_id must be a numeric Gitea CI run ID") builder = manifest["builder"] if builder != {"name": "Kaniko", "image": "ghcr.io/osscontainertools/kaniko:v1.28.5-debug@sha256:c73ca67a3b494bce79a8fb6090c4f73c18997ab272d80bffc460a62343aeb412"}: raise ValueError("manifest builder is not the pinned release builder")