diff --git a/README.md b/README.md index 46cdff1..3f2b78f 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,20 @@ Accepted deployment: terra, https://mirror.nw-sys.ru/archipelago/ (D-071). Source registries: `Archipelago/core`, `Archipelago/purposes`; contracts: `Archipelago/rfc`. +Temporary hardware-testing topology/retention and publication procedure: +[`deploy/HARDWARE-TEST.md`](deploy/HARDWARE-TEST.md). Builds/tests now run on +yabloko; repositories and published artifacts remain on terra. The hardware-test +publisher is separate from testing/stable release gates. + ## Standalone web deployment 1. Copy `.env.example` to `.env`, set an immutable Caddy image and `PUBLIC_ROOT`. -2. Create public `iso`, `ostree/layers`, `ostree/images`, `v1` directories. -3. Initialize `PUBLIC_ROOT/releases.json` from `deploy/releases.empty.json` only on +2. Create a generation under `PUBLIC_ROOT/.generations/initial` with `iso`, + `ostree/layers`, `ostree/images`, `v1` directories and a relative `current` symlink. + Initialize both native archive repositories and `history.json` as + `{"core": [], "gnome": []}`; alternatively let the hardware-test publisher + create the first complete generation before starting the web service. +3. Initialize `PUBLIC_ROOT/current/releases.json` from `deploy/releases.empty.json` only on a fresh deployment. Never overwrite a populated catalog during code deployment. 4. `docker compose up -d web` serves the complete `/archipelago/` prefix on localhost port 8098. Put your HTTPS reverse proxy in front; no mirror dependency is required. @@ -21,9 +30,9 @@ restores the original configuration on reload failure. Existing `/archlinux` and rsync routes are preserved. The web container mounts public artifacts read-only and never receives a Docker socket, signing key, private staging or build workspace. -The homepage is public; private experimental ISOs must not be copied into public -storage. The initial empty catalog accurately represents the lack of eligible -testing/stable releases. Source-only Material You-inspired styling and original +The homepage is public; only explicitly accepted hardware-test candidates or +eligible testing/stable releases may enter public storage. An empty catalog +represents the absence of publications. Source-only Material You-inspired styling and original artwork require no remote fonts, scripts or upstream logo redistribution. ## External ingress diff --git a/STATUS.md b/STATUS.md index 828e84d..761f6ce 100644 --- a/STATUS.md +++ b/STATUS.md @@ -27,9 +27,58 @@ Recorded 2026-11-05. Acceptance of D-071–D-074 is separate from implementation ## In progress -First full daily-driver run with firmware on terra; retained state/logs under -`/opt/archipelago/data/private/daily/`. No successful ISO/VM result is claimed here -until that run completes. The cron file is prepared, not installed yet. +### Current operational checkpoint + +Signed rollout `20261105T164634Z` supersedes the initial pair described below. +Core clean installation and GNOME update-with-nano/Wayland/rollback passed; the +GNOME check used an existing installation. Both signed repositories and ISOs are +published. `/v1/releases.json`, variant catalogs and exact-version endpoints were +verified over HTTPS, including current/previous ISO HEAD sizes and checksum files. +The API retains up to three ISO builds per variant; the portal shows only current. + +Infrastructure CLI is deployed on terra. Real systemd lifecycle tests on yabloko +passed successful/failed request persistence, exit codes, timestamps, logs, status +and empty-reason rejection. Evidence archived on terra at +`/opt/archipelago/evidence/control-lifecycle-20261105/`. +The new clean-GNOME acceptance path is under validation; +scheduled execution remains disabled. See `deploy/OPERATIONS.md`. + +The latest configurable updater passed signed local-repository discovery/plan in +the guest under `unshare --net`; full disconnected build/install is not established. +These newer bindings are not included in the published `20261105T164634Z` ISOs. + +### Earlier publication evidence + +The earlier Core firmware retry passed on terra. Current hardware-test Core +candidate `20261105T155059Z` built on yabloko; fresh VM acceptance passed in +9m33s without swap, including firmware and the Host Extensions sequence. +GNOME `20261105T131221Z` passed clean packaged overlay/rollback, nano activation, +failed-extension state preservation, GDM/Wayland login and Calculator interaction. +Its evidence remains under `/opt/archipelago/data/private/gnome/` on terra. + +The user temporarily moved build/validation execution to yabloko. Direct transfer +of the pinned tools image and bootstrap passed identity checks, and an offline +locked CLI release build passed there. Repositories/publication stay on terra. + +The hardware-test publisher passed real OSTree tests for four publications, +three-version GC, latest-only ISO retention, corrupt-input rejection and preservation +of the previous publication after an injected summary-generation failure. Its +updated Caddy configuration validated on terra. Both hardware-test candidates +are now published. HTTPS checks from yabloko through mirror.nw-sys.ru returned +200 for both ISOs; checksum files matched the catalog, and public layer/image +refs matched the accepted commits. This is endpoint/identity verification, not +a full installed-host network update test. + +- Core ISO: `4ebeb2a4020e0c25d6ee747ff5c3522dee0ce5587c2b202f1e41b579cb171416`; + image `3684d8feead9b995ae572936546f66696bffdab22bbdad9d6e682c8953b04a31`. +- GNOME ISO: `dba0a263bc5f7d82ae4d017f64f103289d48508c2f12d38561cc355252fb3610`; + image `542f6482a38eb99a19104a50bbde6c5422d0e6313f3f12c52c0aa22f70c1519d`. + +Public refs: `hardware-test/core` and `hardware-test/gnome`, in both repositories. +One current ISO per variant; publisher retains at most three layer/image versions +per variant. First publication contains one version of each. +See `deploy/HARDWARE-TEST.md`. The cron file is not installed. + Driver uses the existing monolithic CLI/nspawn backend, records source and artifact identities and runs the VM harness. It does not implement independent Layer v1 build/composition or authenticated installed-host registry updates yet. @@ -39,7 +88,8 @@ build/composition or authenticated installed-host registry updates yet. - Snapshot creation/bulk copying disabled by D-073. Empty `tank/archipelago` and `tank/archipelago/mirror-capture` datasets exist; no mirror data or snapshots were created. Future monthly limit is three; retirement requires reference checks. -- Signed release/channel schemas, trust key custody, reproducibility evidence, - public release publication and GUI/PackageKit integration remain pending. +- General signed release/channel schemas, key rotation/revocation, reproducibility + evidence, testing/stable release gates and GUI/PackageKit integration remain pending. + Temporary hardware-test OpenPGP custody and commit/summary signing are implemented. - `195.46.165.145` is terra's second physical uplink, confirmed by the user. Its unavailability is expected; routing configuration is shared and needs no change. diff --git a/deploy/Caddyfile b/deploy/Caddyfile index f8ca811..8d10b14 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -13,21 +13,21 @@ respond "ok" 200 } handle_path /archipelago/iso/* { - root * /srv/artifacts/iso + root * /srv/artifacts/current/iso file_server } handle_path /archipelago/ostree/* { - root * /srv/artifacts/ostree + root * /srv/artifacts/current/ostree header Cache-Control "no-cache" file_server } handle_path /archipelago/v1/* { - root * /srv/artifacts/v1 + root * /srv/artifacts/current/v1 header Cache-Control "no-cache" file_server } handle /archipelago/releases.json { - root * /srv/artifacts + root * /srv/artifacts/current rewrite * /releases.json header Cache-Control "no-cache" file_server diff --git a/deploy/HARDWARE-TEST.md b/deploy/HARDWARE-TEST.md new file mode 100644 index 0000000..9cf73ba --- /dev/null +++ b/deploy/HARDWARE-TEST.md @@ -0,0 +1,77 @@ +# Temporary hardware-test publication (2026-11-05) + +User-directed topology: yabloko builds and validates; terra retains source +repositories, evidence, ISO artifacts, OSTree repositories and the portal. +Transfers between these hosts are direct. The experimental distribution is named +`hardware-test`; it is not testing/stable acceptance or a working OS update client. +Toolbx first-use network testing remains explicitly deferred. + +Retention supersedes the previous three-ISO proposal: one current ISO per variant +on the portal, at most three commits per variant in each of the layer/image repos. +The current prototype's GNOME layer is monolithic; publishing it does not imply +independent Layer v1 composition support. The precise long-term cycle is pending +hardware testing. Private diagnostic evidence is separate from public retention. + +## Publisher + +D-078 now requires a separate terra-only OpenPGP key for commits and summaries. +Pass `--gpg-home PRIVATE_GNUPGHOME --gpg-key FINGERPRINT` to the publisher. +Current fingerprint: `CF0FED7A412E57010527CD68BFAA5E80EEEACCA2`. +The public key is embedded by `system/src/updates.rs`; the private key is never +transferred to yabloko. Root-only, unattended signing uses the protected terra +key directory. General key rotation/revocation and replay policy remain open. + +`python3 pipeline/publish-hardware.py PUBLIC_ROOT CANDIDATES.json` runs on terra +with OSTree tooling, or in the pinned tools container with the same absolute input +and output paths mounted. Candidate JSON is an array with exactly `core` and +`gnome` records. Each record contains `variant`, `version`, `repo`, `iso`, `sha256`, +`image_commit`, `layer_commit`, `acceptance` (a private JSON file). + +Acceptance must contain the same identities, `scope: hardware-test`, +`accepted: true`, and nonempty `checks: [{path, sha256}]`. This is an explicit +operator acceptance of the recorded hardware-test scope, not an automatic assertion +that all architecture release gates passed. Keep the acceptance/evidence private. + +The publisher verifies identities/evidence, imports objects into isolated copies, +updates history and refs, prunes to three versions, runs fsck and writes summaries. +It copies only the two current ISOs, verifies hashes, syncs and atomically swaps +`PUBLIC_ROOT/current`. Failures before the swap preserve the previous publication. +Refs are `hardware-test/core`, `hardware-test/gnome`, and `history/VARIANT/VERSION`. +Old public generations are removed after the switch. In-progress downloads spanning +a publication may need a retry; clients must verify the published ISO SHA-256. + +Deploy the updated Caddyfile only after the first successful publication creates +`current`. The web container mounts the public parent directory, not the symlink +target. Source/keys/private staging remain outside its mount. + +`tests/publish-hardware.py` uses real disposable OSTree repos to check four +publications, three-version object GC, two-ISO retention and unchanged publication +after rejection of a corrupt ISO. Passed on yabloko in the pinned tools image. + +Scheduled execution remains disabled until the dual-variant build/validation path +is exercised. The requested start time is 00:00 UTC / 03:00 MSK. + +## Unattended update rollout + +`pipeline/finish-update-rollout.py` is a one-shot terra coordinator for the current +lab binding. It waits for earlier builds, stops the retained GNOME VM, builds both +final images on yabloko, runs Core ISO acceptance, imports candidate artifacts to +terra and makes only the signed GNOME candidate objects available before testing. +Public channel refs/catalog are unchanged during candidate validation. + +`test-lab/probes/update_rollout_guest.py` then exercises that exact signed candidate +on the retained GNOME installation: full nano reapplication, reboot, integrity, +account/home/Flatpak persistence, stale-plan rejection, native Wayland login and +explicit rollback. This is not a fresh native GIS installation test for the new ISO. +The candidate plan is an explicit pre-publication test input; public channel +discovery remains unchanged until acceptance passes. + +Only successful evidence unlocks signed publication of both variants, followed by +HTTPS identity/link checks. Failure before publication retains existing ISO/ref +selection; logs and state are archived under terra's +`/opt/archipelago/data/private/update-rollout/`. A post-publication HTTP failure is +recorded with `published: true`, not misreported as an unpublished transaction. + +Current standalone execution is `archipelago-finish-update-rollout.service` on +terra, with a 12-hour limit and durable `worker.log`. It survives workstation/SSH +disconnects. This does not enable a recurring cron job. diff --git a/deploy/NEXT-STABLE.md b/deploy/NEXT-STABLE.md new file mode 100644 index 0000000..b165c66 --- /dev/null +++ b/deploy/NEXT-STABLE.md @@ -0,0 +1,69 @@ +# Next stable ISO acceptance plan + +User requirements recorded 2026-11-05. The D-079 exception authorizes promotion of +the existing `20261105T164634Z` pair only, not a newly built ISO. + +## Required before a new stable ISO + +Latest user revision: default GNOME applications are native Arch packages in the +OS image, also the policy for future KDE. Optional parallel Flatpak versions are +allowed. This supersedes the Flatpak seeding/offline-delivery item below; application +delivery acceptance verifies native package presence on the installed VM instead. + +- [ ] Production CLI: organized help and command groups; remove experimental build + commands from the public interface; isolate laboratory fixtures; consistent + errors and machine-readable results; Russian human-facing output selected by + standard locale environment, with stable JSON identifiers independent of locale. + Initial help/Russian presentation and `build iso --purpose gnome` are implemented; + the fixture command is gated by the non-default `lab-fixtures` build feature. + Replace fixture-dependent release tests with the production Managed Overlay + workflow before claiming inherited overlay acceptance; translating help alone + is not completion of CLI localization. +- [ ] GNOME Software OS updater: discover the signed candidate, show an OS update + and package changes (old/new versions, additions/removals), execute the same + Archipelago plan/apply transaction as CLI, show pending/reboot state, preserve + Host Extensions and reject stale plans. Explicit reboot only. +- [ ] GUI integration tests: actual Software window and backend transaction; + authorization denial, network/signature failure, conflicting operation, repeated + request and reboot. Stock PackageKit ALPM must never mutate the live host. +- [ ] All glibc locales in Core and inherited Desktop images. Generation added to + the shared builder; coverage and native Russian onboarding still need testing. +- [ ] GNOME artwork/backgrounds. `gnome-backgrounds` added to the manifest; validate + installed settings defaults, actual files and light/dark desktop rendering. +- [ ] Plymouth in every Desktop Purpose. GNOME and KDE package declarations added; + GNOME initramfs hook/theme and installer splash arguments implemented. Verify + packaged hook compatibility, splash→GDM handoff, Escape diagnostics and tty access. +- [ ] NTP enabled by default; skewed-RTC regression must recover clock/keyring and + permit verified package/Flatpak downloads. No disabled signature/TLS checks. +- [ ] Default Flatpak applications complete and launch from a clean installation. + Ship apps and their runtime/translation dependencies on installation media; + delivery acceptance checks installed apps/runtimes on the deployed VM, per the + user's narrowed check; separate offline/RTC/per-app-launch scenarios are omitted. + Prototype + upstream `flatpak create-usb` sideload delivery per `builder/FLATPAK-OFFLINE.md`. + Current online retry stalls downloading the first GL runtime; builder acquisition + and target offline import must both pass before acceptance. +- [ ] Expanded Desktop hardware/integration coverage: SOF/ALSA firmware, native + multimedia codecs, CJK fonts, VPN plugins, scanner backend, accessibility and + browser connector. Package declarations do not prove service/device integration. +- [ ] Chromebook XKB model and labelled top-row keys on hardware. Correct command: + `localectl --no-convert set-x11-keymap us chromebook`; the third positional + argument is a layout variant, not the keyboard model. +- [ ] Full inherited Core + GNOME gates and independent reproducibility evidence. + +## Upstream study and implementation boundaries + +Reviewed GNOME Software's `plugins/rpm-ostree/gs-plugin-rpm-ostree.c` (upstream main, +2026-11-05). It uses a native plugin, explicitly conflicts with PackageKit, represents +old/new package versions as related apps, marks updates as requiring reboot, and +delegates privileged work to rpm-ostreed transactions. Reuse these principles, not +the RPM package model or a second mutation path. + +The exact GNOME Software integration must be pinned to our packaged version before +implementation. Stock Arch GNOME Software lacks its PackageKit plugin; merely +unmasking PackageKit cannot implement system updates. Candidate approaches are a +native Software plugin or rebuilt Software + an Archipelago PackageKit backend. +Both must delegate to the unified Rust transaction engine. Public D-Bus/JSON API +formats are not frozen by this implementation plan. + +Source: https://github.com/GNOME/gnome-software/blob/main/plugins/rpm-ostree/gs-plugin-rpm-ostree.c diff --git a/deploy/OPERATIONS.md b/deploy/OPERATIONS.md new file mode 100644 index 0000000..bcd5c23 --- /dev/null +++ b/deploy/OPERATIONS.md @@ -0,0 +1,103 @@ +# Infrastructure operations — incremental implementation + +The full operating contract is conditional on approval of the current release +cycle. Present management/API commands are implemented independently of that final +acceptance. Automatic execution must never require an LLM or interactive approval. +Unrecognized validator state/timeouts fail closed with durable evidence. + +## Coordinator commands + +Install the unified binary and `/etc/archipelago/infrastructure.json`; the supplied +`infrastructure.terra.json` is this deployment's profile, not a portable default. +`ARCHIPELAGO_INFRA_CONFIG` selects another explicit control configuration. + +```sh +sudo archipelago pipeline status +sudo archipelago pipeline run --reason 'Security: CVE-YYYY-NNNN in PACKAGE' +sudo archipelago pipeline logs REQUEST_ID +sudo archipelago release plan /PRIVATE/candidates.json --reason 'Review tested pair' +sudo archipelago release publish /PRIVATE/candidates.json --reason 'Publish tested pair' +``` + +`run` and `publish` start the configured systemd job and return its request ID. +Requests, reason, log path, terminal exit status and times are persisted under +`control_root`. `plan` verifies candidate identities/evidence without publication. +Publication updates catalogs/refs from candidate records; neither portal edits nor +an LLM are involved. Invalid checks stop publication. `pipeline run` currently uses +the existing rollout adapter: generic DAG retry/cancel/resume is not implemented. + +The rollout adapter now prepares fresh GNOME VMs for candidate installation and +for baseline-to-candidate update/rollback. The baseline ISO is selected from the +accepted catalog and checksum-verified before use. This new path is undergoing +end-to-end validation; clean-room autonomy is not yet claimed. There is no enabled +cron schedule yet. + +## Download API + +All endpoints are ordinary versioned JSON GET resources, generated atomically with +publication and served by the static web service: + +- `GET /archipelago/v1/releases.json`: all retained ISO builds. +- `GET /archipelago/v1/releases/core.json`: retained Core builds, newest first. +- `GET /archipelago/v1/releases/gnome.json`: retained GNOME builds, newest first. +- `GET /archipelago/v1/releases/VARIANT/VERSION.json`: exact build metadata. + +Envelope: `apiVersion: archipelago.releases/v1`; records contain variant, version, +architecture, channel, `current`, SHA-256, byte size, image/layer commits, versioned +download URL and checksum URL. Missing/retired resources return HTTP 404. Three +successful ISO builds per variant are retained provisionally. Portal cards continue +to show only current versions via the compatibility `releases.json` catalog. +Downloads use `/archipelago/iso/VARIANT/VERSION/archipelago-VARIANT.iso`. +Latest aliases remain available; clients should use versioned URLs plus SHA-256. + +## Deployment bindings and air-gap + +- Updater: `/etc/archipelago/update.json` overrides the packaged + `/usr/lib/archipelago/update.json`. Configure `version: 1`, `url`, `refs` keyed by + `core`/`gnome`, and absolute `public_key_file`. HTTP(S) and local `file:///` repos + are accepted; both commit and summary verification remain mandatory. No fallback + to the distribution URL/key. Changing bindings invalidates existing plans. +- ISO builder: `ARCHIPELAGO_UPDATE_PROFILE` and `ARCHIPELAGO_UPDATE_PUBLIC_KEY` + supply the image's update defaults. The profile's key path must point to packaged + `/usr/share/archipelago/keys/ostree.asc`. `ARCHIPELAGO_MIRROR_URL` selects the Arch + repository URL template (`$repo`, `$arch`); inputs must remain checksum pinned. +- Desktop: `ARCHIPELAGO_FLATPAK_REMOTE_FILE`, `ARCHIPELAGO_FLATPAK_POLICY` and + `ARCHIPELAGO_TOOLBOX_CONFIG` supply mirrored workload bindings. A Flatpak seed + policy may use `enabled: false` to avoid seeding. Runtime policy override is + `/etc/archipelago/flatpak-apps.json`, read before initial seeding; existing + user workloads are not rewritten. GPG verification is not disabled. +- Coordinator/worker/paths/signing/public endpoint: `/etc/archipelago/rollout.json` + (or `ARCHIPELAGO_ROLLOUT_CONFIG`). Copy the terra profile and change all bindings. +- Publisher `--url-prefix`, `--core-ref`, `--gnome-ref` select the externally served + path and channel refs. The supplied terra control profile explicitly sets these; + the rollout derives the path from `public_url` and refs from `update_refs`. + Local public-key source for legacy baseline validation is `public_key_file`. + Temporary bootstrap files are confined to disposable test VMs. + +Air-gap operation also requires offline bootstrap/tools images/Cargo cache/package +archives and signed DBs, plus selected OCI/Flatpak objects. Providing configurable +bindings alone is not proof that a complete disconnected installation/build passed. + +## Execution dependencies and adoption status + +| Role | Required tools / inputs | +|---|---| +| Coordinator | unified CLI, systemd, Python 3, OpenSSH, rsync, Docker; pinned tools image; public archive; private signing home and exported public key | +| Worker | systemd, Python 3 + pexpect, OpenSSH, rsync, Docker, KVM/QEMU, OVMF; CLI binary; bootstrap and package/Cargo caches; source tree | +| Tools image | OSTree, GnuPG, Python 3 and publisher scripts; immutable image ID recorded by deployment | +| Distribution | static HTTP server for current generation, catalogs and native OSTree repositories; no application daemon required | +| Desktop validation | native GIS/GDM at the tested 1280×800 profile, target SSH, configured package and Flatpak transports | + +Manual and scheduled requests use the same `pipeline run --reason ...` workflow. +Coordinator and worker phases execute in bounded systemd jobs. A disconnected +client does not own their lifetime. Errors/timeouts retain evidence and block the +publication step. Urgency is a reason/priority choice, never permission to skip a +mandatory check. No runtime stage asks an LLM or operator to evaluate screenshots. + +The user's immediate requirements are implemented incrementally: usable control, +autonomous acceptance, configurable infrastructure, API history and durable logs. +Full operating-contract adoption remains conditional on approval of the release +cycle. The agreed daily time is 00:00 UTC (03:00 MSK); scheduling remains disabled +until the new unattended path passes. Laptop hardware checks are deferred to daily +use after migration and do not block this experimental cycle. Homelab migration is +a subsequent strategic target, not an acceptance claim for current artifacts. diff --git a/deploy/infrastructure.terra.json b/deploy/infrastructure.terra.json new file mode 100644 index 0000000..c2d387d --- /dev/null +++ b/deploy/infrastructure.terra.json @@ -0,0 +1,20 @@ +{ + "version": 1, + "unit": "archipelago-managed-job", + "control_root": "/opt/archipelago/data/private/control", + "candidate_root": "/opt/archipelago/data/private", + "job_runner": "/opt/archipelago/src/infrastructure/pipeline/control-job.py", + "run_command": ["python3", "/opt/archipelago/src/infrastructure/pipeline/finish-update-rollout.py"], + "publish_command": [ + "docker", "run", "--rm", "--network=none", "--env", "ARCHIPELAGO_RELEASE_REASON", + "--mount", "type=bind,src=/opt/archipelago/data,dst=/opt/archipelago/data", + "--mount", "type=bind,src=/opt/archipelago/src/infrastructure/pipeline,dst=/pipeline,readonly", + "--mount", "type=bind,src=/opt/archipelago/keys/hardware-test-ostree,dst=/signing", + "sha256:a7f09cdadffecf35297700c8f3513479c92d9a6a14cb6c0f95c71fdfb058a814", + "python3", "/pipeline/publish-hardware.py", "/opt/archipelago/data/public", "{candidates}", + "--gpg-home", "/signing", "--gpg-key", "CF0FED7A412E57010527CD68BFAA5E80EEEACCA2", + "--url-prefix", "/archipelago", "--core-ref", "stable/core", "--gnome-ref", "stable/gnome", + "--channel", "stable", "--release-exception", "/opt/archipelago/data/private/stable-cycle-20261105T164634Z.json", + "--compat-core-ref", "hardware-test/core", "--compat-gnome-ref", "hardware-test/gnome" + ] +} diff --git a/deploy/rollout.terra.json b/deploy/rollout.terra.json new file mode 100644 index 0000000..54eef37 --- /dev/null +++ b/deploy/rollout.terra.json @@ -0,0 +1,20 @@ +{ + "coordinator_root": "/opt/archipelago", + "worker": "yabloko", + "worker_root": "/opt/archipelago", + "clock_regression_rtc": "2000-01-01T00:00:00", + "public_key_file": "/opt/archipelago/src/system/hardware-test-ostree.asc", + "update_refs": {"core": "stable/core", "gnome": "stable/gnome"}, + "release_channel": "stable", + "release_exception": "/opt/archipelago/data/private/stable-cycle-20261105T164634Z.json", + "signing_home": "/opt/archipelago/keys/hardware-test-ostree", + "signing_key": "CF0FED7A412E57010527CD68BFAA5E80EEEACCA2", + "public_url": "https://mirror.nw-sys.ru/archipelago", + "bootstrap": "/opt/archipelago/cache/bootstrap/archlinux-bootstrap-2026.11.01-x86_64.tar.zst", + "ovmf_code": "/usr/share/OVMF/OVMF_CODE_4M.fd", + "ovmf_vars": "/usr/share/OVMF/OVMF_VARS_4M.fd", + "build_environment": { + "ARCHIPELAGO_PACKAGE_CACHE": "/opt/archipelago/cache/packages", + "ARCHIPELAGO_TOOLBOX_PACKAGE": "/opt/archipelago/build/toolbox-package/toolbox-0.3-2.1-x86_64.pkg.tar.zst" + } +} diff --git a/deploy/stable-cycle-20261105T164634Z.json b/deploy/stable-cycle-20261105T164634Z.json new file mode 100644 index 0000000..29e5c14 --- /dev/null +++ b/deploy/stable-cycle-20261105T164634Z.json @@ -0,0 +1,16 @@ +{ + "channel": "stable", + "decision": "D-079", + "reason": "User explicitly approved stable/core and stable/gnome and a release-gate exception for this cycle after successful target-hardware use (2026-11-05).", + "limitations": [ + "Full reproducibility evidence is incomplete.", + "Clean GNOME onboarding, Wayland and nano activation passed; default Flatpak population timed out downloading its runtime.", + "GUI OS updates and general Managed Overlay update support remain incomplete.", + "Published ISO requires enabling NTP on machines with incorrect clocks; the builder fix is not in this image.", + "This exception does not authorize other artifact identities or claim missing checks passed." + ], + "candidates": [ + {"variant":"core","version":"20261105T164634Z","sha256":"1de7e1082d210432d19d3fcd353b3252ab07dfb50875d2b5613a4219aad28643","image_commit":"9f25a9d966fbf12a43056ed991466f2b795c48f95f856f69ff874e329e14f35f","layer_commit":"dc1926bf1990e5b3f7ad83335cf8329601245e3081b6fd469211475a6c216c63"}, + {"variant":"gnome","version":"20261105T164634Z","sha256":"765a5a5d784fd7e814f089568b228b0c237718e02123c867f2afe58256f2e083","image_commit":"14bcd04f6057042e45961a4ee325bbf646dcc167ad2859905ac7c729bfe7035d","layer_commit":"b59dc47cdb513ebe4672cb34809a1f883d1f0517f2c680c4b730406f2f7460c7"} + ] +} diff --git a/pipeline/control-job.py b/pipeline/control-job.py new file mode 100644 index 0000000..6ae8363 --- /dev/null +++ b/pipeline/control-job.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +"""Persist terminal state for an infrastructure CLI request; no interactive steps.""" +import json +from pathlib import Path +import subprocess +import sys +import signal +from datetime import datetime, timezone + +path = Path(sys.argv[1]) +record = json.loads(path.read_text()) + + +def save(state, **extra): + record.update(state=state, **extra) + temp = path.with_suffix('.tmp') + temp.write_text(json.dumps(record, indent=2) + '\n') + temp.replace(path) + + +def interrupted(signum, frame): + raise InterruptedError('Job interrupted by signal ' + str(signum)) + + +signal.signal(signal.SIGTERM, interrupted) +signal.signal(signal.SIGINT, interrupted) +save('running', started=datetime.now(timezone.utc).isoformat()) +try: + result = subprocess.run(record['command'], check=False, timeout=11 * 3600) + save('complete' if result.returncode == 0 else 'failed', exit_code=result.returncode, + finished=datetime.now(timezone.utc).isoformat()) + sys.exit(result.returncode) +except Exception as error: + save('failed', error=str(error), finished=datetime.now(timezone.utc).isoformat()) + raise diff --git a/pipeline/daily-core.py b/pipeline/daily-core.py index 55d76da..dda80ce 100644 --- a/pipeline/daily-core.py +++ b/pipeline/daily-core.py @@ -74,7 +74,7 @@ def main(): stage('pinning-sources') source = run / 'source' source.mkdir() - for component in ['cli', 'builder', 'contracts', 'composer', 'installer', 'registry', 'system', 'rfc', 'test-lab']: + for component in ['cli', 'builder', 'contracts', 'composer', 'installer', 'registry', 'system', 'rfc', 'test-lab', 'purposes']: shutil.copytree(Path(config['source_root']) / component, source / component, ignore=shutil.ignore_patterns('.git', 'target', '__pycache__', '*.pyc')) call(['git', 'clone', '--depth=1', 'https://git.fasoley.net/Archipelago/core.git', source / 'core'], 'source.log') diff --git a/pipeline/finish-update-rollout.py b/pipeline/finish-update-rollout.py new file mode 100644 index 0000000..7cd9ea1 --- /dev/null +++ b/pipeline/finish-update-rollout.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""One-shot unattended hardware-test update rollout, run as a terra systemd job. + +Builds on a configured worker, validates clean Core/GNOME plus update/rollback, archives on +terra, signs and publishes only after success. No daily schedule is enabled here. +""" +from datetime import datetime, timezone +import fcntl +import json +from pathlib import Path +import shlex +import shutil +import subprocess +import time +import urllib.request +import urllib.parse +import os + +CONFIG = json.loads(Path(os.environ.get('ARCHIPELAGO_ROLLOUT_CONFIG', '/etc/archipelago/rollout.json')).read_text()) +BASE = Path(CONFIG['coordinator_root']) +WORKER = CONFIG['worker'] +WORKER_ROOT = CONFIG['worker_root'] +STAMP = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') +RUN = BASE / 'data/private/update-rollout' / STAMP +REMOTE = WORKER_ROOT + '/build/update-rollout/' + STAMP +SIGNING = Path(CONFIG['signing_home']) +KEY = CONFIG['signing_key'] +PUBLIC_URL = CONFIG['public_url'].rstrip('/') +BUILD_ENV = 'env ' + ' '.join(shlex.quote(k + '=' + v) for k, v in CONFIG['build_environment'].items()) +SCRIPTS = Path(__file__).resolve().parent +IMAGE = (BASE / 'evidence/storage-image.id').read_text().strip() +RUN.mkdir(parents=True) +shutil.copytree(SCRIPTS, RUN / 'pipeline', ignore=shutil.ignore_patterns('__pycache__')) +SCRIPTS = RUN / 'pipeline' +(RUN / 'rollout-config.json').write_text(json.dumps(CONFIG, indent=2) + '\n') +lock = (RUN.parent / 'rollout.lock').open('a') +fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) +state = {'run': STAMP, 'state': 'starting', 'published': False, + 'reason': os.environ.get('ARCHIPELAGO_RELEASE_REASON', 'scheduled candidate')} +remote_step = 0 + + +def phase(name): + state['state'] = name + temp = RUN / 'state.tmp' + temp.write_text(json.dumps(state, indent=2) + '\n') + temp.replace(RUN / 'state.json') + print(name, flush=True) + + +def call(args, timeout=21600): + subprocess.run([str(a) for a in args], check=True, timeout=timeout) + + +def remote(script, timeout=21600): + global remote_step + remote_step += 1 + command = ['systemd-run', '--collect', '--wait', '--pipe', + '--unit=archipelago-worker-' + STAMP + '-' + str(remote_step), + '--property=RuntimeMaxSec=' + str(max(1, timeout - 30)), 'bash', '-euc', script] + call(['ssh', '-o', 'BatchMode=yes', '-o', 'ServerAliveInterval=15', WORKER, + shlex.join(command)], timeout) + + +def tools(args, signing=False): + cmd = ['docker', 'run', '--rm', '--network=none', '--env', 'ARCHIPELAGO_RELEASE_REASON', '--mount', + f'type=bind,src={BASE}/data,dst={BASE}/data', '--mount', + f'type=bind,src={SCRIPTS},dst=/pipeline,readonly'] + if signing: + cmd += ['--mount', f'type=bind,src={SIGNING},dst=/signing'] + return cmd + [IMAGE] + [str(a) for a in args] + + +def revision(repo, ref): + return subprocess.check_output(tools(['ostree', '--repo=' + str(repo), 'rev-parse', ref]), text=True).strip() + + +try: + phase('waiting-for-earlier-builds') + if CONFIG.get('wait_unit'): + remote('for i in $(seq 1 720); do if ! systemctl is-active --quiet ' + shlex.quote(CONFIG['wait_unit']) + '; then exit 0; fi; sleep 30; done; exit 1') + phase('pinning-update-baseline') + catalog = json.loads((BASE / 'data/public/current/v1/releases/gnome.json').read_text()) + baseline = next(r for r in catalog['releases'] if r['current']) + # Source bytes come from the accepted local archive, never an unverified URL. + baseline_iso = (BASE / 'data/public/current/iso/gnome' / baseline['version'] / 'archipelago-gnome.iso').resolve(strict=True) + (RUN / 'baseline.json').write_text(json.dumps(baseline, indent=2) + '\n') + remote('mkdir -p ' + shlex.quote(REMOTE)) + call(['rsync', '-a', baseline_iso, f'{WORKER}:{REMOTE}/baseline.iso']) + remote('printf "%s %s\\n" ' + shlex.quote(baseline['sha256']) + ' ' + shlex.quote(REMOTE + '/baseline.iso') + ' | sha256sum -c -') + phase('building-final-images') + remote(f'''mkdir -p {REMOTE} +cp {WORKER_ROOT}/build/desktop/target/release/archipelago {REMOTE}/archipelago +cp -a {WORKER_ROOT}/src/test-lab/probes {REMOTE}/probes +tar --exclude=.git --exclude=target -C {WORKER_ROOT}/build/desktop -cf {REMOTE}/source.tar src +sha256sum {REMOTE}/archipelago {REMOTE}/source.tar > {REMOTE}/inputs.sha256 +find {REMOTE}/probes -type f -name '*.py' -exec sha256sum {{}} + >> {REMOTE}/inputs.sha256 +for variant in core gnome; do + mkdir -p {REMOTE}/$variant + purpose=(); if [ "$variant" = gnome ]; then purpose=(--purpose gnome); fi + {BUILD_ENV} {REMOTE}/archipelago build iso "${{purpose[@]}}" {REMOTE}/$variant/build {shlex.quote(CONFIG['bootstrap'])} > {REMOTE}/$variant/build.log 2>&1 +done''') + phase('core-acceptance') + remote(f'''mkdir -p {REMOTE}/core/vms +python3 {REMOTE}/probes/core_iso_acceptance.py --iso {REMOTE}/core/build/output/archipelago-core-latest.iso --workdir {REMOTE}/core/vms --extensions-sequence --firmware --ovmf-code {shlex.quote(CONFIG['ovmf_code'])} --ovmf-vars {shlex.quote(CONFIG['ovmf_vars'])} > {REMOTE}/core/acceptance.log 2>&1''') + def native_acceptance(iso, name): + directory = REMOTE + '/gnome/' + name + command = ['python3', REMOTE + '/probes/gnome_native_acceptance.py', + '--iso', iso, '--workdir', directory, '--unit', 'archipelago-native-' + STAMP + '-' + name, + '--ovmf-code', CONFIG['ovmf_code'], '--ovmf-vars', CONFIG['ovmf_vars']] + if name == 'clean-install' and CONFIG.get('clock_regression_rtc'): + command += ['--rtc-base', CONFIG['clock_regression_rtc'], '--require-time-sync'] + remote(shlex.join(command)) + data = subprocess.check_output(['ssh', '-o', 'BatchMode=yes', WORKER, + 'cat ' + shlex.quote(directory + '/native-acceptance.json')], text=True) + verdict = json.loads(data) + if verdict.get('passed') is not True: + raise RuntimeError('Native GNOME acceptance failed: ' + name) + (RUN / (name + '.json')).write_text(data) + return verdict['vm'] + + phase('gnome-clean-install-acceptance') + clean_vm = native_acceptance(REMOTE + '/gnome/build/output/archipelago-gnome-probe.iso', 'clean-install') + remote(shlex.join(['python3', REMOTE + '/probes/qmp_command.py', clean_vm + '/qmp.sock', 'system_powerdown'])) + remote('for i in $(seq 1 120); do if ! systemctl is-active --quiet ' + + shlex.quote('archipelago-native-' + STAMP + '-clean-install') + '; then exit 0; fi; sleep 2; done; exit 1') + phase('gnome-clean-update-baseline') + vm = native_acceptance(REMOTE + '/baseline.iso', 'update-baseline') + if json.loads((RUN / 'update-baseline.json').read_text())['iso_sha256'] != baseline['sha256']: + raise RuntimeError('Baseline identity changed during validation') + phase('archiving-candidates') + for variant in ('core', 'gnome'): + (RUN / variant / 'build').mkdir(parents=True) + for name in ('output', 'repo', 'evidence'): + call(['rsync', '-a', f'{WORKER}:{REMOTE}/{variant}/build/{name}', RUN / variant / 'build/']) + call(['rsync', '-a', f'{WORKER}:{REMOTE}/{variant}/build.log', RUN / variant]) + call(['rsync', '-a', f'{WORKER}:{REMOTE}/archipelago', f'{WORKER}:{REMOTE}/source.tar', f'{WORKER}:{REMOTE}/inputs.sha256', str(RUN) + '/']) + call(['rsync', '-a', '--exclude=__pycache__', f'{WORKER}:{REMOTE}/probes', str(RUN) + '/']) + call(['rsync', '-a', '--include=*/', '--include=*.json', '--include=*.jsonl', '--include=*.serial', '--exclude=*', + f'{WORKER}:{REMOTE}/core/vms/', str(RUN / 'core/vm-evidence') + '/']) + call(['rsync', '-a', f'{WORKER}:{REMOTE}/core/acceptance.log', RUN / 'core']) + for name in ('clean-install', 'update-baseline'): + call(['rsync', '-a', '--include=*/', '--include=*.json', '--include=*.log', + '--include=*.serial', '--include=*.png', '--exclude=*', + f'{WORKER}:{REMOTE}/gnome/{name}/', str(RUN / 'gnome' / name) + '/']) + summaries = list((RUN / 'core/vm-evidence').glob('*/summary.json')) + if len(summaries) != 1 or not json.loads(summaries[0].read_text()).get('passed'): + raise RuntimeError('Core acceptance not successful') + candidate = revision(RUN / 'gnome/build/repo', 'core') + phase('publishing-signed-candidate-objects-only') + # Objects precede channel pointers. No refs/summary/catalog are advanced here. + public_repo = BASE / 'data/public/current/ostree/images' + call(tools(['ostree', '--repo=' + str(public_repo), 'pull-local', '--depth=0', RUN / 'gnome/build/repo', candidate])) + call(tools(['ostree', '--repo=' + str(public_repo), 'gpg-sign', '--gpg-homedir=/signing', candidate, KEY], signing=True)) + phase('gnome-update-and-rollback') + bootstrap = {'version': 1, 'url': PUBLIC_URL + '/ostree/images', + 'refs': CONFIG['update_refs'], 'public_key_file': '/var/tmp/rollout-update.asc'} + (RUN / 'update-profile.json').write_text(json.dumps(bootstrap) + '\n') + call(['rsync', '-a', RUN / 'update-profile.json', f'{WORKER}:{REMOTE}/update-profile.json']) + call(['rsync', '-a', CONFIG['public_key_file'], f'{WORKER}:{REMOTE}/update-key.asc']) + remote(shlex.join(['python3', REMOTE + '/probes/update_rollout_guest.py', + '--vm', vm, '--binary', REMOTE + '/archipelago', '--candidate', candidate, + '--evidence', REMOTE + '/gnome/update-evidence', + '--bootstrap-update-profile', REMOTE + '/update-profile.json', + '--bootstrap-update-key', REMOTE + '/update-key.asc'])) + call(['rsync', '-a', f'{WORKER}:{REMOTE}/gnome/update-evidence', RUN / 'gnome']) + verdict = json.loads((RUN / 'gnome/update-evidence/summary.json').read_text()) + if verdict.get('passed') is not True or verdict.get('candidate') != candidate: + raise RuntimeError('GNOME update acceptance not successful') + phase('preparing-publication') + config = {'output': str(RUN / 'candidates.json'), 'candidates': [ + dict(variant='core', version=STAMP, directory=str(RUN / 'core'), iso_name='archipelago-core-latest.iso', + core_summary=str(summaries[0]), checks=[{'path': str(summaries[0])}, + {'path': str(RUN / 'core/acceptance.log'), 'contains': 'acceptance-passed'}]), + dict(variant='gnome', version=STAMP, directory=str(RUN / 'gnome'), iso_name='archipelago-gnome-probe.iso', + native_summary=str(RUN / 'clean-install.json'), + expected_image_commit=candidate, checks=[{'path': str(RUN / 'clean-install.json')}, + {'path': str(RUN / 'update-baseline.json')}, {'path': str(RUN / 'gnome/update-evidence/summary.json')}, + {'path': str(RUN / 'gnome/update-evidence/guest.log')}], + limitations=['Hardware-test only', 'Toolbx first-use network test deferred', + 'PackageKit and general Managed Overlay updates not implemented'])]} + (RUN / 'reviewed-pair.json').write_text(json.dumps(config, indent=2)) + call(tools(['python3', '/pipeline/prepare-hardware-pair.py', RUN / 'reviewed-pair.json'])) + call(tools(['python3', '/pipeline/publish-hardware.py', BASE / 'data/public', RUN / 'candidates.json', + '--gpg-home', '/signing', '--gpg-key', KEY, + '--url-prefix', urllib.parse.urlsplit(PUBLIC_URL).path, + '--core-ref', CONFIG['update_refs']['core'], '--gnome-ref', CONFIG['update_refs']['gnome'], + '--channel', CONFIG['release_channel'], '--release-exception', CONFIG['release_exception'], + '--compat-core-ref', 'hardware-test/core', '--compat-gnome-ref', 'hardware-test/gnome'], signing=True)) + state['published'] = True + phase('https-verification') + with urllib.request.urlopen(PUBLIC_URL + '/releases.json', timeout=60) as response: + catalog = json.load(response) + assert len(catalog['releases']) == 2 and all(r['version'] == STAMP for r in catalog['releases']) + for release in catalog['releases']: + url = urllib.parse.urljoin(PUBLIC_URL + '/', release['url']) + with urllib.request.urlopen(urllib.request.Request(url, method='HEAD'), timeout=60) as response: + assert response.status == 200 + with urllib.request.urlopen(url + '.sha256', timeout=60) as response: + assert response.read().decode().split()[0] == release['sha256'] + phase('complete') +except BaseException as error: + state['error'] = str(error) + phase('failed') + # Archive compact diagnostics even when the validator failed remotely. + subprocess.run(['rsync', '-a', '--include=*/', '--include=*.log', '--include=*.json', + '--include=*.jsonl', '--exclude=*', f'{WORKER}:{REMOTE}/', str(RUN / 'failure-evidence') + '/']) + raise +finally: + # These units belong exclusively to this run; no unrelated VM is selected. + try: + cleanup = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', WORKER, + shlex.join(['systemctl', 'stop', 'archipelago-native-' + STAMP + '-clean-install', + 'archipelago-native-' + STAMP + '-update-baseline'])], + timeout=120, check=False) + if cleanup.returncode: + print('VM cleanup returned nonzero; units may not have been created', flush=True) + except Exception as cleanup_error: + print('VM cleanup requires retry: ' + str(cleanup_error), flush=True) diff --git a/pipeline/prepare-hardware-pair.py b/pipeline/prepare-hardware-pair.py new file mode 100644 index 0000000..b45bbee --- /dev/null +++ b/pipeline/prepare-hardware-pair.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Bind explicitly reviewed evidence to ISO/OSTree identities for publication.""" +import hashlib +import json +from pathlib import Path +import subprocess +import sys + + +def digest(path): + with Path(path).open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def prepare(config): + records = [] + for item in config['candidates']: + root = Path(item['directory']) + iso = root / 'build/output' / item['iso_name'] + repo = root / 'build/repo' + sha = digest(iso) + if item['variant'] == 'core': + summary = json.loads(Path(item['core_summary']).read_text()) + if summary.get('passed') is not True or summary.get('iso_sha256') != sha: + raise ValueError('Core VM acceptance missing or mismatched') + if item.get('native_summary'): + summary = json.loads(Path(item['native_summary']).read_text()) + if summary.get('passed') is not True or summary.get('iso_sha256') != sha: + raise ValueError('Native GNOME acceptance missing or mismatched') + checks = [] + for check in item['checks']: + path = Path(check['path']) + if check.get('contains') and check['contains'] not in path.read_text(): + raise ValueError('Missing check marker: ' + str(path)) + checks.append(dict(path=str(path), sha256=digest(path))) + def resolve(ref): + return subprocess.check_output(['ostree', '--repo=' + str(repo), 'rev-parse', ref], text=True).strip() + record = dict(variant=item['variant'], version=item['version'], iso=str(iso), repo=str(repo), + sha256=sha, image_commit=resolve('core'), layer_commit=resolve('layers/core'), + acceptance=str(root / 'hardware-test-acceptance.json')) + if item.get('expected_image_commit') and record['image_commit'] != item['expected_image_commit']: + raise ValueError('Reviewed image differs from repository') + Path(record['acceptance']).write_text(json.dumps(record | dict(scope='hardware-test', + accepted=True, checks=checks, limitations=item.get('limitations', [])), indent=2) + '\n') + records.append(record) + Path(config['output']).write_text(json.dumps(records, indent=2) + '\n') + + +if __name__ == '__main__': + prepare(json.loads(Path(sys.argv[1]).read_text())) diff --git a/pipeline/publish-hardware.py b/pipeline/publish-hardware.py new file mode 100644 index 0000000..5e219d0 --- /dev/null +++ b/pipeline/publish-hardware.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Atomic, evidence-validated hardware-test publication; not testing/stable.""" +import argparse +import fcntl +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile + + +def digest(path): + with Path(path).open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def ostree(repo, *args): + return subprocess.check_output(['ostree', '--repo=' + str(repo), *args], text=True).strip() + + +def publish(public, records, gpg_home=None, gpg_key=None, archives=None, validate_only=False, + url_prefix='', refs=None, channel='hardware-test', exception=None, compatibility=None): + compatibility = compatibility or {'core': [], 'gnome': []} + if channel not in ('hardware-test', 'testing', 'stable'): + raise ValueError('Invalid release channel') + if channel != 'hardware-test': + identities = [{k: r[k] for k in ('variant', 'version', 'sha256', 'image_commit', 'layer_commit')} for r in records] + if not exception or exception.get('channel') != channel or not exception.get('decision') or not exception.get('reason') or not exception.get('limitations') or sorted(exception.get('candidates', []), key=lambda r: r['variant']) != sorted(identities, key=lambda r: r['variant']): + raise ValueError('This interim publisher requires an exact, explicitly approved release exception for production channels') + if url_prefix and not re.fullmatch(r'(?:/[A-Za-z0-9_-]+)+', url_prefix): + raise ValueError('URL prefix must be an absolute path without trailing slash') + refs = refs or {'core': 'hardware-test/core', 'gnome': 'hardware-test/gnome'} + if set(refs) != {'core', 'gnome'} or len(set(refs.values())) != 2: + raise ValueError('Distinct Core and GNOME refs required') + if set(compatibility) != {'core', 'gnome'}: + raise ValueError('Invalid compatibility ref map') + all_refs = list(refs.values()) + [ref for values in compatibility.values() for ref in values] + if len(set(all_refs)) != len(all_refs): + raise ValueError('Publication refs must be distinct') + for ref in all_refs: + if not re.fullmatch(r'[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*', ref) or any(p in ('.', '..') for p in ref.split('/')) or ref.startswith('history/'): + raise ValueError('Invalid publication ref') + archives = archives or [] + if bool(gpg_home) != bool(gpg_key): + raise ValueError('Signing home and fingerprint must be supplied together') + if len(records) != 2 or {r['variant'] for r in records} != {'core', 'gnome'}: + raise ValueError('Exactly one Core and one GNOME candidate required') + for r in records + archives: + if r['variant'] not in ('core', 'gnome'): + raise ValueError('Invalid variant') + if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,127}', r['version']): + raise ValueError('Invalid version') + for key in ('sha256', 'image_commit', 'layer_commit'): + if not re.fullmatch(r'[0-9a-f]{64}', r[key]): + raise ValueError('Invalid ' + key) + if digest(r['iso']) != r['sha256']: + raise ValueError('ISO checksum mismatch') + acceptance = json.loads(Path(r['acceptance']).read_text()) + if acceptance.get('scope') != 'hardware-test' or acceptance.get('accepted') is not True: + raise ValueError('Explicit hardware-test acceptance required') + for key in ('variant', 'version', 'sha256', 'image_commit', 'layer_commit'): + if acceptance.get(key) != r[key]: + raise ValueError('Acceptance identity mismatch: ' + key) + if not acceptance.get('checks'): + raise ValueError('Acceptance must identify checks') + for check in acceptance['checks']: + if digest(check['path']) != check['sha256']: + raise ValueError('Evidence checksum mismatch') + for key in ('image_commit', 'layer_commit'): + ostree(r['repo'], 'show', r[key]) + linked = ostree(r['repo'], 'show', '--print-metadata-key=archipelago.layer-core', r['image_commit']) + if linked != "'" + r['layer_commit'] + "'": + raise ValueError('Image/layer provenance mismatch') + if validate_only: + print(json.dumps({'valid': True, 'variants': [r['variant'] for r in records]})) + return + public.mkdir(parents=True, exist_ok=True) + with (public / '.publish.lock').open('a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + generations = public / '.generations' + generations.mkdir(exist_ok=True) + previous = (public / 'current').resolve() if (public / 'current').is_symlink() else None + if (public / 'current').exists() and previous is None: + raise ValueError('current must be a managed symlink') + stage = Path(tempfile.mkdtemp(prefix='hardware-', dir=generations)) + stage.chmod(0o755) + switched = False + try: + for directory in ('iso', 'v1', 'ostree'): + (stage / directory).mkdir() + history = json.loads((previous / 'history.json').read_text()) if previous else {'core': [], 'gnome': []} + for kind in ('images', 'layers'): + repo = stage / 'ostree' / kind + if previous: + subprocess.run(['cp', '-a', '--reflink=auto', str(previous / 'ostree' / kind), str(repo)], check=True) + old_refs_file = previous / 'publication-refs.json' + old_refs = json.loads(old_refs_file.read_text()) if old_refs_file.exists() else { + 'core': 'hardware-test/core', 'gnome': 'hardware-test/gnome'} + old_alias_file = previous / 'compatibility-refs.json' + old_aliases = json.loads(old_alias_file.read_text()) if old_alias_file.exists() else {} + old_names = set(old_refs.values()) | {ref for values in old_aliases.values() for ref in values} + for old_ref in old_names - set(all_refs): + ostree(repo, 'refs', '--delete', old_ref) + else: + ostree(repo, 'init', '--mode=archive') + releases = [] + api_releases = [] + for r in records: + variant = r['variant'] + entry = {k: r[k] for k in ('version', 'image_commit', 'layer_commit', 'sha256')} + entry['channel'] = channel + if exception: + entry['release_exception'] = {k: exception[k] for k in ('decision', 'reason', 'limitations')} + old = history[variant] + if any(e['version'] == r['version'] and any(e.get(k, r[k]) != r[k] + for k in ('image_commit', 'layer_commit', 'sha256')) for e in old): + raise ValueError('Version identity cannot change') + history[variant] = ([e for e in old if e['version'] != r['version']] + [entry])[-3:] + for kind, key in (('images', 'image_commit'), ('layers', 'layer_commit')): + repo = stage / 'ostree' / kind + ostree(repo, 'pull-local', '--depth=0', r['repo'], r[key]) + for ref in ostree(repo, 'refs').splitlines(): + if ref.startswith('history/' + variant + '/'): + ostree(repo, 'refs', '--delete', ref) + for e in history[variant]: + ostree(repo, 'refs', '--create=history/' + variant + '/' + e['version'], e[key]) + ostree(repo, 'refs', '--force', '--create=' + refs[variant], r[key]) + for alias in compatibility[variant]: + ostree(repo, 'refs', '--force', '--create=' + alias, r[key]) + name = 'archipelago-' + variant + '.iso' + available = [] + for e in history[variant]: + relative = Path('iso') / variant / e['version'] / name + target = stage / relative + source_record = next((a for a in records + archives + if a['variant'] == variant and a['version'] == e['version']), None) + if source_record: + if any(source_record[k] != e[k] for k in ('image_commit', 'layer_commit')): + raise ValueError('Archive identity mismatch') + if e.get('sha256') and source_record['sha256'] != e['sha256']: + raise ValueError('Archive ISO identity cannot change') + source = Path(source_record['iso']) + e['sha256'] = source_record['sha256'] + elif previous and (previous / relative).is_file() and e.get('sha256'): + source = previous / relative + else: + # Old history can retain commits without ISO bytes. + continue + target.parent.mkdir(parents=True, exist_ok=True) + if previous and source.is_relative_to(previous): + os.link(source, target) + else: + shutil.copyfile(source, target) + if digest(target) != e['sha256']: + raise ValueError('Archived ISO checksum mismatch') + target.with_suffix('.iso.sha256').write_text(e['sha256'] + ' ' + name + '\n') + item = dict(variant=variant, architecture='x86_64', channel=e.get('channel', 'hardware-test'), + version=e['version'], sha256=e['sha256'], image_commit=e['image_commit'], + layer_commit=e['layer_commit'], size_bytes=target.stat().st_size, + current=e['version'] == r['version'], + url=url_prefix + '/' + relative.as_posix(), + checksum_url=url_prefix + '/' + relative.as_posix() + '.sha256') + if e.get('release_exception'): + item['release_exception'] = e['release_exception'] + available.append(item) + detail = stage / 'v1/releases' / variant / (e['version'] + '.json') + detail.parent.mkdir(parents=True, exist_ok=True) + detail.write_text(json.dumps(dict(apiVersion='archipelago.releases/v1', release=item), indent=2) + '\n') + available.reverse() + api_releases.extend(available) + (stage / 'v1/releases' / (variant + '.json')).write_text(json.dumps( + dict(apiVersion='archipelago.releases/v1', releases=available), indent=2) + '\n') + os.link(stage / 'iso' / variant / r['version'] / name, stage / 'iso' / name) + (stage / 'iso' / (name + '.sha256')).write_text(r['sha256'] + ' ' + name + '\n') + # Expose identities/check names, not private evidence paths. + (stage / 'v1' / (variant + '.json')).write_text(json.dumps(entry, indent=2) + '\n') + releases.append(dict(variant={'core': 'Arch Core', 'gnome': 'GNOME Desktop'}[variant], + architecture='x86_64', channel=channel, version=r['version'], + sha256=r['sha256'], image_commit=r['image_commit'], url=url_prefix + '/iso/' + name)) + if exception: + releases[-1]['release_exception'] = entry['release_exception'] + for kind in ('images', 'layers'): + repo = stage / 'ostree' / kind + ostree(repo, 'prune', '--refs-only', '--depth=0') + ostree(repo, 'fsck') + if gpg_key: + commits = {ostree(repo, 'rev-parse', ref) for ref in ostree(repo, 'refs').splitlines()} + for commit in commits: + ostree(repo, 'gpg-sign', '--delete', '--gpg-homedir=' + str(gpg_home), commit, gpg_key) + ostree(repo, 'gpg-sign', '--gpg-homedir=' + str(gpg_home), commit, gpg_key) + ostree(repo, 'summary', '--update', '--gpg-sign=' + gpg_key, + '--gpg-homedir=' + str(gpg_home)) + else: + ostree(repo, 'summary', '--update') + (stage / 'history.json').write_text(json.dumps(history, indent=2) + '\n') + (stage / 'publication-refs.json').write_text(json.dumps(refs, indent=2) + '\n') + (stage / 'compatibility-refs.json').write_text(json.dumps(compatibility, indent=2) + '\n') + (stage / 'v1/releases.json').write_text(json.dumps(dict( + apiVersion='archipelago.releases/v1', retention_per_variant=3, + releases=api_releases), indent=2) + '\n') + (stage / 'releases.json').write_text(json.dumps(dict(version=1, releases=releases, + reason=os.environ.get('ARCHIPELAGO_RELEASE_REASON', '')), indent=2) + '\n') + subprocess.run(['sync', '-f', str(stage)], check=True) + link = public / '.next-publication' + link.unlink(missing_ok=True) + link.symlink_to(stage.relative_to(public)) + os.replace(link, public / 'current') + switched = True + subprocess.run(['sync', '-f', str(public)], check=True) + if previous and previous.parent == generations.resolve(): + shutil.rmtree(previous) + finally: + if not switched: + shutil.rmtree(stage) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('public_root', type=Path) + parser.add_argument('candidates', type=Path) + parser.add_argument('--gpg-home', type=Path, required=True) + parser.add_argument('--gpg-key', required=True) + parser.add_argument('--archive-candidates', type=Path) + parser.add_argument('--check-only', action='store_true') + parser.add_argument('--url-prefix', default='') + parser.add_argument('--core-ref', default='hardware-test/core') + parser.add_argument('--gnome-ref', default='hardware-test/gnome') + parser.add_argument('--channel', default='hardware-test') + parser.add_argument('--release-exception', type=Path) + parser.add_argument('--compat-core-ref', action='append', default=[]) + parser.add_argument('--compat-gnome-ref', action='append', default=[]) + args = parser.parse_args() + publish(args.public_root.resolve(), json.loads(args.candidates.read_text()), args.gpg_home, args.gpg_key, + json.loads(args.archive_candidates.read_text()) if args.archive_candidates else None, + args.check_only, args.url_prefix, {'core': args.core_ref, 'gnome': args.gnome_ref}, + args.channel, json.loads(args.release_exception.read_text()) if args.release_exception else None, + {'core': args.compat_core_ref, 'gnome': args.compat_gnome_ref}) diff --git a/pipeline/resume-update-rollout.py b/pipeline/resume-update-rollout.py new file mode 100644 index 0000000..fc3909c --- /dev/null +++ b/pipeline/resume-update-rollout.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Resume the recorded GNOME boot validation and publication, without rebuilding.""" +import fcntl +import json +from pathlib import Path +import re +import shutil +import subprocess +import sys +import urllib.request + +stamp = sys.argv[1] +if not re.fullmatch(r'[0-9]{8}T[0-9]{6}Z', stamp): + raise ValueError('Invalid run identity') +base = Path('/opt/archipelago') +root = base / 'data/private/update-rollout' / stamp +remote = str(base / 'build/update-rollout' / stamp) +lock = (root.parent / 'rollout.lock').open('a') +fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) +shutil.copy2(root / 'state.json', root / 'state-before-resume.json') +state = json.loads((root / 'state.json').read_text()) +state.pop('error', None) + + +def phase(value): + state['state'] = value + temp = root / 'state.tmp' + temp.write_text(json.dumps(state, indent=2) + '\n') + temp.replace(root / 'state.json') + print(value, flush=True) + + +def call(args): + subprocess.run([str(a) for a in args], check=True, timeout=7200) + + +image = (base / 'evidence/storage-image.id').read_text().strip() +scripts = Path(__file__).resolve().parent +docker = ['docker', 'run', '--rm', '--network=none', '--mount', + f'type=bind,src={base}/data,dst={base}/data', '--mount', + f'type=bind,src={scripts},dst=/pipeline,readonly', '--mount', + f'type=bind,src={base}/keys/hardware-test-ostree,dst=/signing', image] +try: + phase('resuming-gnome-validation') + verdict_path = root / 'failure-evidence/gnome/update-evidence/summary.json' + previous = json.loads(verdict_path.read_text()) + candidate = previous['candidate'] + if not re.fullmatch('[0-9a-f]{64}', candidate): raise ValueError('Invalid candidate') + call(['ssh', '-o', 'BatchMode=yes', 'yabloko', 'python3', + '/opt/archipelago/src/test-lab/probes/update_rollout_guest.py', '--resume', + '--vm', '/opt/archipelago/migration/gnome-sfyobspe', '--binary', remote + '/archipelago', + '--candidate', candidate, '--evidence', remote + '/gnome/update-evidence']) + call(['rsync', '-a', 'yabloko:' + remote + '/gnome/update-evidence', root / 'gnome']) + verdict = json.loads((root / 'gnome/update-evidence/summary.json').read_text()) + assert verdict.get('passed') is True and verdict['candidate'] == candidate + summaries = list((root / 'core/vm-evidence').glob('*/summary.json')) + assert len(summaries) == 1 and json.loads(summaries[0].read_text())['passed'] is True + config = {'output': str(root / 'candidates.json'), 'candidates': [ + dict(variant='core', version=stamp, directory=str(root / 'core'), iso_name='archipelago-core-latest.iso', + core_summary=str(summaries[0]), checks=[{'path': str(summaries[0])}, + {'path': str(root / 'core/acceptance.log'), 'contains': 'acceptance-passed'}]), + dict(variant='gnome', version=stamp, directory=str(root / 'gnome'), iso_name='archipelago-gnome-probe.iso', + expected_image_commit=candidate, checks=[{'path': str(root / 'gnome/update-evidence/summary.json')}, + {'path': str(root / 'gnome/update-evidence/guest.log')}], + limitations=['Hardware-test only', 'Toolbx first-use download deferred', + 'GNOME native update and rollback tested; new ISO native GIS not retested', + 'PackageKit and custom Managed Overlay updates not implemented'])]} + (root / 'reviewed-pair.json').write_text(json.dumps(config, indent=2)) + phase('publishing') + call(docker + ['python3', '/pipeline/prepare-hardware-pair.py', root / 'reviewed-pair.json']) + call(docker + ['python3', '/pipeline/publish-hardware.py', base / 'data/public', root / 'candidates.json', + '--gpg-home', '/signing', '--gpg-key', 'CF0FED7A412E57010527CD68BFAA5E80EEEACCA2']) + state['published'] = True + phase('https-verification') + with urllib.request.urlopen('https://mirror.nw-sys.ru/archipelago/releases.json', timeout=60) as response: + catalog = json.load(response) + assert len(catalog['releases']) == 2 and all(r['version'] == stamp for r in catalog['releases']) + for item in catalog['releases']: + url = 'https://mirror.nw-sys.ru' + item['url'] + with urllib.request.urlopen(urllib.request.Request(url, method='HEAD'), timeout=60) as response: + assert response.status == 200 + with urllib.request.urlopen(url + '.sha256', timeout=60) as response: + assert response.read().decode().split()[0] == item['sha256'] + phase('complete') +except BaseException as error: + state['error'] = str(error) + phase('failed') + raise diff --git a/portal/index.html b/portal/index.html index 7844db4..dde1fe7 100644 --- a/portal/index.html +++ b/portal/index.html @@ -13,7 +13,7 @@

ARCH LINUX · OSTREE · DECLARATIVE

Ваша система.
Ваш набор слоёв.

Archipelago объединяет экосистему Arch Linux с декларативной композицией и управляемыми образами ОС. От минимального Core до рабочего стола — с явными обновлениями и возможностью отката.

Выбрать образ Изучить архитектуру ↗
01

Описывайте намерение

Версионированные YAML-манифесты определяют состав системы. Точные входы сборки закрепляются отдельно.

02

Обновляйте целиком

Новый deployment готовится отдельно. Текущая система продолжает работать до вашей явной перезагрузки.

03

Расширяйте локально

Host Extensions предназначены для локальных пакетов и аппаратных адаптаций. Такие композиции находятся вне официальной поддержки.

-

ISO PORTAL

Начните с Core

Проект в разработке

Публичные образы появляются после обязательных проверок и подтверждения воспроизводимости. Экспериментальные лабораторные сборки не являются релизами testing/stable.

Проверяем каталог релизов…

Core · x86_64 · UEFIGNOME · планируетсяKDE Plasma · планируется
+

ISO PORTAL

Arch Core и GNOME Desktop

Проверка на железе

Hardware-test — экспериментальные образы после указанных VM-проверок, предназначенные для тестирования на физических машинах. Полная воспроизводимость и все критерии testing/stable ещё не подтверждены. На портале хранится только актуальный ISO каждой редакции; в OSTree — до трёх версий. Штатный клиент обновления ОС пока не реализован.

Проверяем каталог образов…

Core · x86_64 · UEFIGNOME Desktop · x86_64 · UEFIKDE Plasma · планируется

OPEN BY DESIGN

Архитектура обсуждается открыто

Контракты, решения и исходники доступны в организации Archipelago. Готовность отдельных компонентов подтверждается проверками, а не только наличием спецификации.

RFC и реестр контрактов ↗
diff --git a/portal/portal.js b/portal/portal.js index 2039766..61ec5ea 100644 --- a/portal/portal.js +++ b/portal/portal.js @@ -9,14 +9,16 @@ if (catalog.version !== 1 || !Array.isArray(catalog.releases)) throw new Error("unknown catalog"); if (!catalog.releases.length) { message("Публичных ISO пока нет. Идут экспериментальные проверки Core; релизы появятся здесь после прохождения всех обязательных критериев."); return; } const cards = catalog.releases.map(release => { - if (!['testing','stable'].includes(release.channel) || !/^[0-9a-f]{64}$/.test(release.sha256)) throw new Error("invalid release"); + if (!['hardware-test','testing','stable'].includes(release.channel) || !/^[0-9a-f]{64}$/.test(release.sha256)) throw new Error("invalid release"); const url = new URL(release.url, location.href); if (url.origin !== location.origin || !url.pathname.startsWith('/archipelago/iso/')) throw new Error("invalid artifact URL"); const card = document.createElement('article'); card.className = 'release'; const title = document.createElement('h3'); title.textContent = `${release.variant} · ${release.architecture} · ${release.channel}`; const link = document.createElement('a'); link.href = url.href; link.textContent = `Скачать ISO · ${release.version}`; const hash = document.createElement('p'); const code = document.createElement('code'); code.textContent = `SHA-256: ${release.sha256}`; hash.append(code); - card.append(title,link,hash); return card; + const note = document.createElement('p'); + if (release.channel === 'hardware-test') note.textContent = 'Экспериментальный образ для проверки на железе. Не testing/stable; штатное обновление ОС ещё не готово.'; + card.append(title,note,link,hash); return card; }); list.replaceChildren(...cards); } catch { message("Каталог релизов временно недоступен. Непроверенные ссылки на скачивание не отображаются."); } diff --git a/tests/control-lifecycle.py b/tests/control-lifecycle.py new file mode 100644 index 0000000..890af0c --- /dev/null +++ b/tests/control-lifecycle.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +"""Exercise real systemd submission, terminal evidence and logs in a private profile.""" +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time + +binary = sys.argv[1] +runner = str(Path(__file__).resolve().parents[1] / 'pipeline/control-job.py') +root = Path(tempfile.mkdtemp(prefix='archipelago-control-test-')) +profile = root / 'profile.json' +env = dict(os.environ, ARCHIPELAGO_INFRA_CONFIG=str(profile)) +unit = 'archipelago-control-test-' + str(os.getpid()) + + +def cli(*args, check=True): + return subprocess.run([binary, *args], env=env, check=check, capture_output=True, text=True) + + +for code in (0, 17): + profile.write_text(json.dumps(dict(version=1, unit=unit, control_root=str(root / 'requests'), + job_runner=runner, run_command=['python3', '-c', + f'import sys; print("LIFECYCLE_{code}", flush=True); sys.exit({code})']))) + record = json.loads(cli('pipeline', 'run', '--reason', 'Lifecycle verification').stdout) + deadline = time.monotonic() + 30 + path = root / 'requests' / (record['id'] + '.json') + while time.monotonic() < deadline: + record = json.loads(path.read_text()) + if record['state'] in ('complete', 'failed'): break + time.sleep(.2) + assert record['state'] == ('complete' if code == 0 else 'failed'), record + assert record['exit_code'] == code and record['started'] and record['finished'], record + assert f'LIFECYCLE_{code}' in cli('pipeline', 'logs', record['id']).stdout + # The wrapper's terminal record precedes systemd's unit cleanup. + while time.monotonic() < deadline: + active = subprocess.run(['systemctl', 'is-active', '--quiet', unit]).returncode == 0 + if not active: break + time.sleep(.2) + assert not active +status = json.loads(cli('pipeline', 'status').stdout) +assert len(status['requests']) == 2 +assert cli('pipeline', 'run', '--reason', ' ', check=False).returncode != 0 +print(json.dumps({'passed': True, 'evidence': str(root), 'cases': ['success', 'failure', 'logs', 'status', 'empty-reason']})) diff --git a/tests/publish-hardware.py b/tests/publish-hardware.py new file mode 100644 index 0000000..423fde4 --- /dev/null +++ b/tests/publish-hardware.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Exercise publication, rejection and three-version GC against real OSTree.""" +import importlib.util +import json +from pathlib import Path +import tempfile +import subprocess + +spec = importlib.util.spec_from_file_location('publisher', Path(__file__).parents[1] / 'pipeline/publish-hardware.py') +m = importlib.util.module_from_spec(spec) +spec.loader.exec_module(m) +with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + repo = root / 'input' + m.ostree(repo, 'init', '--mode=archive') + payload = root / 'payload' + payload.mkdir() + public = root / 'public' + first = [] + for generation in range(4): + records = [] + for variant in ('core', 'gnome'): + (payload / 'marker').write_text(variant + str(generation)) + layer = m.ostree(repo, 'commit', '--orphan', '--branch=layer-' + variant, + '--tree=dir=' + str(payload)) + commit = m.ostree(repo, 'commit', '--orphan', '--branch=' + variant, + '--tree=dir=' + str(payload), '--add-metadata-string=archipelago.layer-core=' + layer) + if generation == 0: + first.extend([commit, layer]) + iso = root / (variant + '.iso') + iso.write_text('fixture ISO ' + commit) + evidence = root / (variant + '.log') + evidence.write_text('fixture acceptance ' + commit) + r = dict(variant=variant, version=str(generation), repo=str(repo), + iso=str(iso), sha256=m.digest(iso), image_commit=commit, + layer_commit=layer, acceptance=str(root / (variant + '.json'))) + Path(r['acceptance']).write_text(json.dumps(r | dict(scope='hardware-test', accepted=True, + checks=[dict(path=str(evidence), sha256=m.digest(evidence))]))) + records.append(r) + m.publish(public, records) + current = (public / 'current').resolve() + assert len(list((current / 'iso').glob('*.iso'))) == 2 + api = json.loads((current / 'v1/releases.json').read_text()) + assert len(api['releases']) == 2 * min(generation + 1, 3) + assert sum(r['current'] for r in api['releases']) == 2 + for release in api['releases']: + artifact = current / release['url'].removeprefix('/') + assert artifact.is_file() and m.digest(artifact) == release['sha256'] + detail = current / 'v1/releases' / release['variant'] / (release['version'] + '.json') + assert json.loads(detail.read_text())['release'] == release + if generation == 3: + assert not (current / 'iso/core/0').exists() + assert len(list((public / '.generations').iterdir())) == 1 + history = json.loads((current / 'history.json').read_text()) + assert all(len(entries) == min(generation + 1, 3) for entries in history.values()) + for kind in ('images', 'layers'): + target = current / 'ostree' / kind + assert m.ostree(target, 'rev-parse', 'hardware-test/core') == records[0]['image_commit' if kind == 'images' else 'layer_commit'] + before = (public / 'current').readlink() + real_ostree = m.ostree + def fail_summary(repo, *args): + if args[0] == 'summary': + raise RuntimeError('injected summary failure after staging') + return real_ostree(repo, *args) + m.ostree = fail_summary + try: + m.publish(public, records) + except RuntimeError: + pass + else: + raise AssertionError('Injected failure was ignored') + finally: + m.ostree = real_ostree + assert (public / 'current').readlink() == before + assert len(list((public / '.generations').iterdir())) == 1 + Path(records[0]['iso']).write_text('corrupt') + try: + m.publish(public, records) + except ValueError: + pass + else: + raise AssertionError('Corrupt ISO was published') + assert (public / 'current').readlink() == before + for kind in ('images', 'layers'): + for commit in first: + assert not (current / 'ostree' / kind / 'objects' / commit[:2] / (commit[2:] + '.commit')).exists() + print('PUBLICATION_RETENTION_FAILURE_PRESERVATION_PASS') + home = root / 'gpg' + home.mkdir(mode=0o700) + subprocess.run(['gpg', '--homedir', str(home), '--batch', '--pinentry-mode', 'loopback', + '--passphrase', '', '--quick-generate-key', 'Archipelago disposable test', + 'ed25519', 'sign', '1d'], check=True, capture_output=True) + keys = subprocess.check_output(['gpg', '--homedir', str(home), '--with-colons', '--list-keys'], text=True) + key = next(line.split(':')[9] for line in keys.splitlines() if line.startswith('fpr:')) + Path(records[0]['iso']).write_text('fixture ISO ' + records[0]['image_commit']) + m.publish(public, records, home, key) + m.publish(public, records, home, key, url_prefix='/offline/os', + refs={'core': 'lab/core', 'gnome': 'lab/desktop'}) + current = (public / 'current').resolve() + catalog = json.loads((current / 'v1/releases.json').read_text()) + assert all(r['url'].startswith('/offline/os/iso/') for r in catalog['releases']) + for kind in ('images', 'layers'): + refs = m.ostree(current / 'ostree' / kind, 'refs').splitlines() + assert 'lab/core' in refs and 'lab/desktop' in refs + assert not any(ref.startswith('hardware-test/') for ref in refs) + assert (current / 'ostree/images/summary.sig').is_file() + public_key = root / 'test.asc' + public_key.write_bytes(subprocess.check_output(['gpg', '--homedir', str(home), '--export', key])) + client = root / 'client' + m.ostree(client, 'init', '--mode=archive') + m.ostree(client, 'remote', 'add', '--gpg-import=' + str(public_key), + '--set=gpg-verify-summary=true', 'test', (current / 'ostree/images').as_uri()) + refs = m.ostree(client, 'remote', 'summary', 'test') + print(refs) + m.ostree(client, 'pull', 'test', records[0]['image_commit']) + (current / 'ostree/images/summary.sig').write_bytes(b'invalid signature') + try: + m.ostree(client, 'remote', 'summary', 'test') + except subprocess.CalledProcessError: + pass + else: + raise AssertionError('Invalid summary signature accepted') + print('SIGNED_PUBLICATION_PULL_PASS') + previous = (public / 'current').resolve() + try: + m.publish(public, records, home, key, channel='stable') + except ValueError: + pass + else: + raise AssertionError('Unapproved stable publication accepted') + assert (public / 'current').resolve() == previous + exception = dict(channel='stable', decision='fixture', reason='Explicit test exception', + limitations=['No production evidence'], candidates=[{k:r[k] for k in + ('variant', 'version', 'sha256', 'image_commit', 'layer_commit')} for r in records]) + m.publish(public, records, home, key, channel='stable', exception=exception, + refs={'core':'stable/core','gnome':'stable/gnome'}, + compatibility={'core':['hardware-test/core'], 'gnome':['hardware-test/gnome']}) + current = (public / 'current').resolve() + catalog = json.loads((current / 'v1/releases.json').read_text()) + assert all(r['channel'] == 'stable' and r['release_exception']['decision'] == 'fixture' + for r in catalog['releases'] if r['current']) + assert all(r['channel'] == 'hardware-test' for r in catalog['releases'] if not r['current']) + for kind in ('images', 'layers'): + repo = current / 'ostree' / kind + for variant in ('core', 'gnome'): + assert m.ostree(repo, 'rev-parse', 'stable/' + variant) == m.ostree(repo, 'rev-parse', 'hardware-test/' + variant) + exception['candidates'][0]['sha256'] = '0' * 64 + try: + m.publish(public, records, home, key, channel='stable', exception=exception) + except ValueError: + pass + else: + raise AssertionError('Exception accepted for different bytes') + assert (public / 'current').resolve() == current + print('SCOPED_STABLE_PROMOTION_COMPATIBILITY_PASS')