diff --git a/.gitea/RELEASING.md b/.gitea/RELEASING.md index 1d3a23c..40a32ef 100644 --- a/.gitea/RELEASING.md +++ b/.gitea/RELEASING.md @@ -59,14 +59,15 @@ Enable Actions and add these repository secrets: | Secret | Purpose | | --- | --- | | `RELEASE_CHECKOUT_SSH_KEY` | Read-only SSH key used for root, component, and `release-feed` checkouts. Grant it access to every private component repository before cutover. | -| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot. It needs read access to every component repository plus release/tag and `release-feed` write access in this repository. | +| `RELEASE_BOT_TOKEN` | PAT owned by a dedicated bot. It needs read access to every component repository plus release/tag write access in this repository. It does not need `release-feed` write access. | | `RELEASE_TAG_ALLOWED_SIGNERS` | Complete OpenSSH `allowed_signers` lines for maintainers allowed to publish `v*` tags. | -| `RELEASE_FEED_ED25519_PRIVATE_KEY` | PEM private key matching `release-keys/echoion-release-2026-07.pub.pem`. Preserve its newlines. | +| `RELEASE_FEED_ED25519_PUBLIC_KEY` | PEM public key matching the component-feed signing key. It verifies independently published components without exposing signing authority to the product workflow. | Component checkouts use SSH with `persist-credentials: false`. Release API operations use the bot PAT, but Git fetches and pushes never rewrite remotes to -HTTPS. The feed signing key must not be stored in Git, runner images, Actions -variables, or release assets. +HTTPS. The component-feed private signing key must not be present in the +Echoion product repository, Git, runner images, Actions variables, or release +assets. ## Independent component repositories @@ -225,8 +226,9 @@ printf '\n' Add the new public key to official builds before signing any feed with it and keep the old public key embedded for at least one full update lifetime. Update -the signing key id in both release workflows and replace the private-key +the signing key id in component release workflows and replace their private-key secret only after the build containing both trust roots is installed broadly. +Replace the product workflow's public-key secret at the same cutover. Immutable version feeds are never rewritten during rotation. Never print the private key or pass it as a command-line argument. diff --git a/.gitea/workflows/nightly.yml b/.gitea/workflows/nightly.yml index 6282f95..9f1104d 100644 --- a/.gitea/workflows/nightly.yml +++ b/.gitea/workflows/nightly.yml @@ -1,4 +1,4 @@ -name: Nightly modular release +name: Nightly product integration on: schedule: @@ -98,97 +98,10 @@ jobs: set -euo pipefail scripts/release.sh \ --version "$RELEASE_VERSION" \ + --skip-component-packages \ --component-workspace "$PWD/components" \ --void-source "$PWD/dependencies/VoidLibrary" \ --void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \ --official-update-feed-url "$RELEASE_FEED_URL" \ --update-channel nightly \ --update-sequence "$RELEASE_SEQUENCE" - { - printf 'Automated nightly from %s.\n\n' "$RELEASE_TARGET" - printf 'This prerelease is retained for fourteen nightly runs.\n' - } >"$RUNNER_TEMP/release-notes.md" - - - name: Upload, download-verify, publish, and retain fourteen nightlies - shell: bash - env: - GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_BOT_TOKEN }} - API_URL: ${{ gitea.api_url }} - REPOSITORY: ${{ gitea.repository }} - run: | - set -euo pipefail - owner=${REPOSITORY%%/*} - repo=${REPOSITORY#*/} - python3 scripts/gitea_release.py \ - --api-url "$API_URL" \ - publish \ - --owner "$owner" \ - --repo "$repo" \ - --tag "$RELEASE_TAG" \ - --target "$RELEASE_TARGET" \ - --name "Echoion nightly $RELEASE_VERSION" \ - --body-file "$RUNNER_TEMP/release-notes.md" \ - --artifacts dist \ - --allow-missing-draft-tag \ - --prerelease - python3 scripts/gitea_release.py \ - --api-url "$API_URL" \ - prune-nightlies \ - --owner "$owner" \ - --repo "$repo" \ - --tag-prefix nightly- \ - --keep 14 \ - --protect-tag "$RELEASE_TAG" - - - name: Check out release-feed over SSH - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - ref: release-feed - path: feed-state - fetch-depth: 0 - ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} - ssh-user: gitea - ssh-known-hosts: >- - git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw== - - - name: Sign and push the nightly feed transaction - shell: bash - env: - FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }} - FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }} - run: | - set -euo pipefail - feed_key="$RUNNER_TEMP/echoion-feed-ed25519.pem" - commit_key="$RUNNER_TEMP/echoion-feed-commit-key" - trap 'rm -f -- "$feed_key" "$commit_key"' EXIT - umask 077 - printf '%s\n' "$FEED_PRIVATE_KEY" >"$feed_key" - printf '%s\n' "$FEED_COMMIT_SIGNING_KEY" >"$commit_key" - chmod 0600 "$feed_key" "$commit_key" - python3 scripts/publish-component-feeds.py \ - --registry components.json \ - --lock components.lock.json \ - --artifacts dist/components \ - --feed-root feed-state \ - --base-url \ - "${{ gitea.server_url }}/${{ gitea.repository }}/raw/branch/release-feed" \ - --artifact-base-url "$RELEASE_ARTIFACT_BASE_URL" \ - --channel nightly \ - --sequence "$RELEASE_SEQUENCE" \ - --valid-days 45 \ - --key-id echoion-release-2026-07 \ - --private-key "$feed_key" - git -C feed-state config user.name 'Echoion Release Bot' - git -C feed-state config user.email 'release-bot@echoion.invalid' - git -C feed-state config gpg.format ssh - git -C feed-state config user.signingkey "$commit_key" - git -C feed-state config commit.gpgsign true - git -C feed-state add feeds/nightly state - if git -C feed-state diff --cached --quiet; then - exit 0 - fi - git -C feed-state commit -S -m \ - "Feed: nightly ${RELEASE_VERSION}" - git -C feed-state cat-file commit HEAD | - grep -q '^gpgsig ' - git -C feed-state push origin HEAD:release-feed diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index e82afec..0c09dfe 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -146,12 +146,43 @@ jobs: printf 'RELEASE_FEED_URL=%s\n' "$feed_url" } >>"$GITHUB_ENV" + - name: Check out the protected release-feed branch over SSH + uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + ref: release-feed + path: feed-state + fetch-depth: 0 + ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} + ssh-user: gitea + ssh-known-hosts: >- + git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw== + + - name: Verify every locked component was independently published + shell: bash + env: + FEED_PUBLIC_KEY: ${{ secrets.RELEASE_FEED_ED25519_PUBLIC_KEY }} + run: | + set -euo pipefail + feed_key="$RUNNER_TEMP/echoion-feed-ed25519.pub.pem" + trap 'rm -f -- "$feed_key"' EXIT + printf '%s\n' "$FEED_PUBLIC_KEY" >"$feed_key" + chmod 0644 "$feed_key" + openssl pkey -pubin -in "$feed_key" -noout + python3 scripts/verify-locked-component-feeds.py \ + --registry components.json \ + --lock components.lock.json \ + --feed-root feed-state \ + --channel "$RELEASE_CHANNEL" \ + --key-id "${{ vars.ECHOION_FEED_SIGNING_KEY_ID }}" \ + --public-key "$feed_key" + - name: Build, test, and package all locked repositories in Docker shell: bash run: | set -euo pipefail scripts/release.sh \ --version "$RELEASE_VERSION" \ + --skip-component-packages \ --component-workspace "$PWD/components" \ --void-source "$PWD/dependencies/VoidLibrary" \ --void-teamspeak-source "$PWD/dependencies/VoidTeamspeak" \ @@ -184,57 +215,3 @@ jobs: --body-file "$RUNNER_TEMP/release-notes.md" \ --artifacts dist \ "${prerelease[@]}" - - - name: Check out the protected release-feed branch over SSH - uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 - with: - ref: release-feed - path: feed-state - fetch-depth: 0 - ssh-key: ${{ secrets.RELEASE_CHECKOUT_SSH_KEY }} - ssh-user: gitea - ssh-known-hosts: >- - git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw== - - - name: Sign and push the complete channel feed transaction - shell: bash - env: - FEED_PRIVATE_KEY: ${{ secrets.RELEASE_FEED_ED25519_PRIVATE_KEY }} - FEED_COMMIT_SIGNING_KEY: ${{ secrets.RELEASE_FEED_GIT_SIGNING_KEY }} - run: | - set -euo pipefail - feed_key="$RUNNER_TEMP/echoion-feed-ed25519.pem" - commit_key="$RUNNER_TEMP/echoion-feed-commit-key" - trap 'rm -f -- "$feed_key" "$commit_key"' EXIT - umask 077 - printf '%s\n' "$FEED_PRIVATE_KEY" >"$feed_key" - printf '%s\n' "$FEED_COMMIT_SIGNING_KEY" >"$commit_key" - chmod 0600 "$feed_key" "$commit_key" - openssl pkey -in "$feed_key" -noout - python3 scripts/publish-component-feeds.py \ - --registry components.json \ - --lock components.lock.json \ - --artifacts dist/components \ - --feed-root feed-state \ - --base-url \ - "${{ gitea.server_url }}/${{ gitea.repository }}/raw/branch/release-feed" \ - --artifact-base-url "$RELEASE_ARTIFACT_BASE_URL" \ - --channel "$RELEASE_CHANNEL" \ - --sequence "$RELEASE_SEQUENCE" \ - --valid-days 45 \ - --key-id echoion-release-2026-07 \ - --private-key "$feed_key" - git -C feed-state config user.name 'Echoion Release Bot' - git -C feed-state config user.email 'release-bot@echoion.invalid' - git -C feed-state config gpg.format ssh - git -C feed-state config user.signingkey "$commit_key" - git -C feed-state config commit.gpgsign true - git -C feed-state add feeds state - if git -C feed-state diff --cached --quiet; then - exit 0 - fi - git -C feed-state commit -S -m \ - "Feed: ${RELEASE_CHANNEL} ${RELEASE_VERSION}" - git -C feed-state cat-file commit HEAD | - grep -q '^gpgsig ' - git -C feed-state push origin HEAD:release-feed diff --git a/CMakeLists.txt b/CMakeLists.txt index a7a7ace..b0e5db1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -500,6 +500,12 @@ if(BUILD_TESTS AND UNIX) add_test(NAME echoion_component_feed_tests COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_publish_component_feeds.py") + add_test(NAME echoion_independent_component_release_tests + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_independent_component_release.py") + add_test(NAME echoion_prepare_component_release_tests + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/tests/test_prepare_component_release.py") if(NOT COMMAND void_add_tests AND DEFINED Void_SOURCE_DIR) include("${Void_SOURCE_DIR}/cmake/VoidTesting.cmake") diff --git a/README.md b/README.md index 8b2bcba..8bf7ea1 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,11 @@ A modern music bot for TeamSpeak 3, featuring YouTube integration, playlist support, and hot-reload capabilities. +Release operations are documented in +[Independent component releases](docs/component-releases.md). The explored, +not implemented, paid-binary design is recorded in +[ADR 0001](docs/adr/0001-paid-binary-distribution.md). + ## Features - 🎵 **YouTube Integration** - Play music directly from YouTube URLs or search queries via a native innertube client (fastest path) with yt-dlp as the resolver/fallback diff --git a/docs/adr/0001-paid-binary-distribution.md b/docs/adr/0001-paid-binary-distribution.md new file mode 100644 index 0000000..86f37aa --- /dev/null +++ b/docs/adr/0001-paid-binary-distribution.md @@ -0,0 +1,86 @@ +# ADR 0001: Future paid official-binary distribution + +Status: explored, not implemented + +## Decision + +Keep update metadata public and cryptographically signed. Keep artifact URLs +stable behind the distribution gateway. If paid access is introduced later, +authorize artifact responses at that gateway; do not put credentials or +short-lived signed URLs into immutable feeds. + +The future request path is: + +```text +billing webhook + -> Echoion entitlement service + -> account/device access token + -> distribution gateway + -> short-lived origin authorization or streamed object response +``` + +Billing authorization and update integrity are separate: + +- The gateway decides whether an account may receive the bytes. +- The updater independently verifies the feed signature, artifact SHA-256, + signed manifest, size, compatibility, and replay sequence. + +No billing, account, license, device, or gateway authorization code is part of +the current implementation. + +## Provider options + +### Stripe Billing + +Use Stripe subscriptions and Billing Entitlements webhooks while Echoion owns +the entitlement database, account model, tax configuration, support, and +gateway. This provides the most control but also leaves more commerce and +compliance work in Echoion. + +- +- + +### Paddle or Lemon Squeezy + +Prefer a merchant-of-record provider when supported jurisdictions, tax +collection/remittance, invoices, and payment operations should be delegated. +Echoion still needs a webhook-driven entitlement projection and must treat +webhooks as replayable, out-of-order external events. + +- +- + +### Keygen + +Consider Keygen in addition to a billing provider when per-device activation, +offline signed licenses, machine limits, or license-policy administration +becomes a product requirement. + +- + +## Required follow-up decisions + +Before implementation, produce a jurisdiction-specific commerce review and +lock these product choices: + +- Merchant of record versus Echoion-operated merchant account. +- Monthly, annual, perpetual, trial, and grace-period behavior. +- Device limits, device replacement, account sharing, and offline operation. +- Refund, dispute, chargeback, failed-payment, cancellation, and revocation + timing. +- Availability when billing, entitlement, or gateway dependencies are down. +- Minimal personal data, retention, account deletion, audit history, and + customer-support access. + +Webhook handlers must verify provider signatures, persist provider event IDs, +be idempotent, tolerate reordering, and derive access from stored entitlement +state rather than trusting a single webhook delivery. + +## Limits + +Echoion is public source. A download paywall can control official signed +binaries, automated updates, and paid support, but cannot prevent someone from +building and running the public source. Stronger enforcement would require +moving real product value into private components or a hosted service and is +outside this decision. + diff --git a/docs/component-releases.md b/docs/component-releases.md new file mode 100644 index 0000000..cf4076d --- /dev/null +++ b/docs/component-releases.md @@ -0,0 +1,107 @@ +# Independent component releases + +Echoion product releases and component releases are deliberately separate. +A component release never edits `components.lock.json`, creates an Echoion +product tag, or starts the Echoion product workflow. The lock is updated only +while preparing a later full Echoion release. + +## Published objects + +Every runtime component publishes the same verified package to two places: + +1. A release in the component's own Gitea repository. This is the provenance + and maintainer-facing release after that repository becomes private. +2. An immutable object-storage key exposed through the permanent distribution + gateway: + + ```text + /// + ``` + +The signed public feed refers only to the distribution URL. It never contains +Gitea credentials, object-storage credentials, presigned URLs, or private clone +URLs. Private Gitea repositories do not have independently public release +units, so public delivery must remain a separate distribution concern. + +The object origin should be private from its first deployment. The gateway may +allow anonymous `GET` requests initially; a future entitlement check can return +`401` or `403` at the same permanent URL without rewriting signed immutable +feed documents. + +## Release transaction + +The workflow on a signed `vX.Y.Z` tag publishes stable releases. A prerelease +tag publishes beta. A scheduled run publishes a nightly only when that +component's source SHA differs from its last nightly state. + +The shared release tool performs this idempotent transaction: + +1. Verify the component tag and derive the required version from the prior + stable feed state and canonical ABI contract. +2. Check out exact dependency revisions from the product dependency snapshot. +3. Configure the component with its own `ECHOION_COMPONENT_VERSION`, build, + test, install, and package it deterministically. +4. Upload with an object-store create precondition and download-verify the + result. An existing object is accepted only when its bytes match. +5. Create or reconcile the component's native Gitea release. +6. Merge that component into the signed channel feed and push one signed + `release-feed` commit. + +Gitea 1.25 does not enforce the GitHub Actions `concurrency` and `permissions` +keys. All component release jobs therefore target the dedicated +`echoion-release-serial` runner label. That label must have capacity one. +The feed push is still a compare-and-swap through Git's fast-forward rule, so a +misconfigured second runner fails instead of losing another publication. + +## Required configuration + +Set `ECHOION_RELEASE_TOOLS_REF` to the full 40-character Echoion commit that +contains the approved release tools. Workflows verify the checkout against the +exact value. + +The following Gitea Actions variables are required: + +- `ECHOION_RELEASE_TOOLS_REF` +- `ECHOION_DISTRIBUTION_BASE_URL` +- `ECHOION_FEED_BASE_URL` +- `ECHOION_FEED_SIGNING_KEY_ID` +- `COMPONENT_OBJECT_STORAGE_BUCKET` +- `COMPONENT_OBJECT_STORAGE_ENDPOINT` when using a non-AWS S3 service +- `COMPONENT_OBJECT_STORAGE_PREFIX`, normally `components` +- `COMPONENT_OBJECT_STORAGE_REGION` + +The following secrets are required in each component repository: + +- `RELEASE_CHECKOUT_SSH_KEY` +- `RELEASE_TAG_ALLOWED_SIGNERS` +- `RELEASE_BOT_TOKEN` +- `RELEASE_FEED_ED25519_PRIVATE_KEY` +- `RELEASE_FEED_GIT_SIGNING_KEY` +- `COMPONENT_OBJECT_STORAGE_ACCESS_KEY` +- `COMPONENT_OBJECT_STORAGE_SECRET_KEY` + +The Echoion product repository needs only +`RELEASE_FEED_ED25519_PUBLIC_KEY` for feed verification. It must not receive +the component-feed private key. + +Use a release-bot PAT limited to repository release and feed publication +operations. Do not share a personal administrator token. Protect `v*` tags and +the Echoion `release-feed` branch, and permit only the release identity to +publish them. + +## Manifest schema 3 + +Independent packages use manifest schema 3. The manifest carries the component +version, product compatibility range, source/tree/ABI identities, exact build +dependency provenance, platform/toolchain contract, activation policy, private +libraries, and file hashes. It does not claim the current Echoion product +version. + +The channel catalog is a merge of independently published components. Its +sequence is global and monotonic; each component state also maintains +monotonic per-channel history. Immutable release documents are never replaced +with different artifact or source identities. + +Before creating a full Echoion tag, update `components.lock.json` intentionally. +The product workflow verifies every locked component against its signed +immutable feed document before it builds or publishes the product. diff --git a/packaging/README.md b/packaging/README.md index 53a748f..804591f 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -87,8 +87,12 @@ The default command uses the version-pinned release toolchain container and does not start the bot. Installation flags and data layouts are documented in the root README. -The official workflow packages all locked components and publishes signed, -channel-separated catalogs through `scripts/publish-component-feeds.py`. +The official product workflow passes `--skip-component-packages` and verifies +that every locked component already exists in the signed stable catalog. +Each component repository packages and publishes only itself through +`scripts/release-component.sh`; the transaction merges its release into the +channel catalog without triggering an Echoion product release. See +`docs/component-releases.md`. `scripts/generate-update-feed.py` remains available only for an explicit custom `direct` source; it can produce an Ed25519-signed envelope from a key held outside the repository. diff --git a/scripts/package-component.py b/scripts/package-component.py new file mode 100755 index 0000000..933cc41 --- /dev/null +++ b/scripts/package-component.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Create one deterministic, product-independent Echoion component package.""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import tempfile +from types import ModuleType +from typing import Any, NoReturn + + +GIT_SHA = re.compile(r"^[0-9a-f]{40}$") +HASH = re.compile(r"^(?:sha256:[0-9a-f]{64}|git-sha1:[0-9a-f]{40})$") +SEMVER = re.compile( + r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)" + r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?" + r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$" +) +TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$") + + +def fail(message: str) -> NoReturn: + raise SystemExit(f"package-component: {message}") + + +def load_packaging_helpers() -> ModuleType: + path = Path(__file__).with_name("package-components.py") + specification = importlib.util.spec_from_file_location( + "echoion_package_components", path + ) + if specification is None or specification.loader is None: + fail(f"cannot load shared packaging helpers from {path}") + module = importlib.util.module_from_spec(specification) + specification.loader.exec_module(module) + return module + + +def load_json_object(path: Path, label: str) -> dict[str, Any]: + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as error: + fail(f"cannot read {label} {path}: {error}") + if not isinstance(value, dict): + fail(f"{label} must be a JSON object") + return value + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--registry", type=Path, default=Path("components.json")) + parser.add_argument("--component", required=True) + parser.add_argument("--package-root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--component-version", required=True) + parser.add_argument( + "--product-compatibility", default=">=2.0.0 <3.0.0" + ) + parser.add_argument("--source-sha", required=True) + parser.add_argument("--source-tree-hash", required=True) + parser.add_argument("--abi-hash") + parser.add_argument("--build-dependencies", type=Path) + parser.add_argument("--platform", default="linux") + parser.add_argument("--architecture", default="x86_64") + parser.add_argument( + "--toolchain-contract", + default="linux-x86_64-glibc-2.35-cxx26", + ) + arguments = parser.parse_args() + + if not TOKEN.fullmatch(arguments.component): + fail("invalid component ID") + if not SEMVER.fullmatch(arguments.component_version): + fail("--component-version must be canonical SemVer") + if ( + not arguments.product_compatibility + or len(arguments.product_compatibility) > 256 + or any( + character in arguments.product_compatibility + for character in "\r\n\0" + ) + ): + fail("--product-compatibility is invalid") + if not GIT_SHA.fullmatch(arguments.source_sha): + fail("--source-sha must be a full lowercase Git SHA") + if not HASH.fullmatch(arguments.source_tree_hash): + fail("--source-tree-hash must be a supported content hash") + if arguments.abi_hash is not None and not re.fullmatch( + r"sha256:[0-9a-f]{64}", arguments.abi_hash + ): + fail("--abi-hash must be a SHA-256 hash") + for label, value in ( + ("--platform", arguments.platform), + ("--architecture", arguments.architecture), + ("--toolchain-contract", arguments.toolchain_contract), + ): + if not TOKEN.fullmatch(value): + fail(f"{label} is invalid") + + registry = load_json_object(arguments.registry, "component registry") + definitions = registry.get("components") + if registry.get("schemaVersion") != 1 or not isinstance(definitions, dict): + fail("unsupported component registry schema") + definition = definitions.get(arguments.component) + if not isinstance(definition, dict): + fail(f"component is not registered: {arguments.component}") + package_id = definition.get("packageId") + if not isinstance(package_id, str) or not TOKEN.fullmatch(package_id): + fail("registered packageId is invalid") + + build_dependencies: dict[str, Any] = {} + if arguments.build_dependencies is not None: + build_dependencies = load_json_object( + arguments.build_dependencies, "build dependency provenance" + ) + + package_root = arguments.package_root.resolve(strict=True) + if package_root.is_symlink() or not package_root.is_dir(): + fail("--package-root must be a real directory") + output = arguments.output.resolve() + output.mkdir(parents=True, exist_ok=True) + epoch_value = os.environ.get("SOURCE_DATE_EPOCH", "0") + if not epoch_value.isdigit(): + fail("SOURCE_DATE_EPOCH must be a non-negative integer") + + helpers = load_packaging_helpers() + artifact_identity = ( + f"{package_id}-{arguments.component_version}-" + f"{arguments.platform}-{arguments.architecture}" + ) + with tempfile.TemporaryDirectory( + prefix=".component-package.", dir=output + ) as temporary: + staged = Path(temporary) / artifact_identity + shutil.copytree(package_root, staged, symlinks=True) + files = helpers.validate_tree(staged) + manifest = { + "schemaVersion": 3, + "componentId": arguments.component, + "packageId": package_id, + "kind": definition["kind"], + "productCompatibility": arguments.product_compatibility, + "componentVersion": arguments.component_version, + "sourceSha": arguments.source_sha, + "sourceTreeHash": arguments.source_tree_hash, + "abiHash": arguments.abi_hash, + "activation": definition["activation"], + "dependencies": definition["dependencies"], + "buildDependencies": build_dependencies, + "platform": arguments.platform, + "architecture": arguments.architecture, + "toolchainContract": arguments.toolchain_contract, + "artifactIdentity": artifact_identity, + "privateLibraries": helpers.private_libraries(staged), + "files": files, + } + manifest_bytes = helpers.canonical(manifest) + (staged / "manifest.json").write_bytes(manifest_bytes) + archive = output / f"{artifact_identity}.tar.zst" + helpers.create_archive(staged, archive, int(epoch_value)) + manifest_path = output / f"{artifact_identity}.manifest.json" + manifest_path.write_bytes(manifest_bytes) + + print(f"packaged {arguments.component}: {archive.name}") + + +if __name__ == "__main__": + main() diff --git a/scripts/prepare-component-release.py b/scripts/prepare-component-release.py new file mode 100755 index 0000000..f398e84 --- /dev/null +++ b/scripts/prepare-component-release.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +"""Validate and derive one component's independent release identity.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +import re +import subprocess +import sys +from typing import Any, NoReturn + + +SEMVER = re.compile( + r"^(?P0|[1-9][0-9]*)\." + r"(?P0|[1-9][0-9]*)\." + r"(?P0|[1-9][0-9]*)$" +) +RELEASE_VERSION = re.compile( + r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)" + r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$" +) + + +def fail(message: str) -> NoReturn: + raise SystemExit(f"prepare-component-release: {message}") + + +def canonical(value: Any) -> bytes: + return ( + json.dumps( + value, + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + + b"\n" + ) + + +def load_object(path: Path, label: str) -> dict[str, Any]: + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as error: + fail(f"cannot read {label} {path}: {error}") + if not isinstance(value, dict): + fail(f"{label} must be a JSON object") + return value + + +def git(repository: Path, *arguments: str) -> str: + try: + return subprocess.check_output( + ["git", "-C", str(repository), *arguments], + text=True, + stderr=subprocess.STDOUT, + ).strip() + except (OSError, subprocess.CalledProcessError) as error: + detail = getattr(error, "output", "") or str(error) + fail(f"git {' '.join(arguments)} failed: {detail.strip()}") + + +def read_contract(repository: Path, revision: str, relative: str) -> Any: + raw = git(repository, "show", f"{revision}:{relative}") + try: + value = json.loads(raw) + except json.JSONDecodeError as error: + fail(f"{relative} at {revision} is invalid JSON: {error}") + if not isinstance(value, dict) or value.get("schemaVersion") != 1: + fail(f"{relative} at {revision} has an unsupported ABI schema") + return value + + +def compatible_append(old: Any, new: Any) -> bool: + if type(old) is not type(new): + return False + if isinstance(old, dict): + return all( + key in new and compatible_append(value, new[key]) + for key, value in old.items() + ) + if isinstance(old, list): + return len(new) >= len(old) and all( + compatible_append(value, new[index]) + for index, value in enumerate(old) + ) + return old == new + + +def change_classification(old: Any, new: Any) -> str: + if canonical(old) == canonical(new): + return "patch" + return "minor" if compatible_append(old, new) else "major" + + +def bump(version: str, change: str) -> str: + match = SEMVER.fullmatch(version) + if match is None: + fail(f"previous stable version is invalid: {version!r}") + major = int(match.group("major")) + minor = int(match.group("minor")) + patch = int(match.group("patch")) + if change == "patch": + return f"{major}.{minor}.{patch + 1}" + if change == "minor": + return f"{major}.{minor + 1}.0" + if change == "major": + return f"{major + 1}.0.0" + raise AssertionError(change) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--registry", type=Path, required=True) + parser.add_argument("--configuration", type=Path, required=True) + parser.add_argument("--repository", type=Path, required=True) + parser.add_argument("--feed-root", type=Path, required=True) + parser.add_argument( + "--channel", choices=("stable", "beta", "nightly"), required=True + ) + parser.add_argument("--requested-version") + parser.add_argument("--nightly-sequence") + parser.add_argument("--output", type=Path) + arguments = parser.parse_args() + + registry = load_object(arguments.registry, "component registry") + configuration = load_object( + arguments.configuration, "component release configuration" + ) + definitions = registry.get("components") + if registry.get("schemaVersion") != 1 or not isinstance(definitions, dict): + fail("unsupported component registry schema") + if configuration.get("schemaVersion") != 1: + fail("unsupported component release configuration schema") + component_id = configuration.get("componentId") + definition = definitions.get(component_id) + if not isinstance(component_id, str) or not isinstance(definition, dict): + fail("configured component is not present in the registry") + compatibility = configuration.get("productCompatibility") + if not isinstance(compatibility, str) or not compatibility: + fail("productCompatibility is required") + if not isinstance(configuration.get("cmakeOptions"), dict): + fail("cmakeOptions must be an object") + + repository = arguments.repository.resolve(strict=True) + if git(repository, "status", "--porcelain"): + fail("component repository must be clean") + source_sha = git(repository, "rev-parse", "HEAD") + source_tree = git(repository, "rev-parse", "HEAD^{tree}") + + state_path = ( + arguments.feed_root + / "state" + / "components" + / f"{component_id}.json" + ) + state = ( + load_object(state_path, "component state") + if state_path.exists() + else {} + ) + channels = state.get("channels", {}) + if not isinstance(channels, dict): + fail("component state channels must be an object") + channel_state = channels.get(arguments.channel, {}) + if not isinstance(channel_state, dict): + fail("component channel state must be an object") + if channel_state.get("sourceSha") == source_sha: + if arguments.channel == "nightly": + print("component source is already published in nightly") + return 3 + fail(f"component source is already published in {arguments.channel}") + + previous_version = state.get("semVer") + previous_sha = state.get("lastSourceSha") + contract_path = definition.get("abiContract") + abi_hash = None + if contract_path is not None: + if not isinstance(contract_path, str) or not contract_path: + fail("registered ABI contract path is invalid") + current_contract = read_contract(repository, source_sha, contract_path) + abi_hash = "sha256:" + hashlib.sha256( + canonical(current_contract) + ).hexdigest() + else: + current_contract = None + + if previous_version is None: + expected_stable = "2.0.0" + change = "initial" + else: + if not isinstance(previous_sha, str) or not re.fullmatch( + r"[0-9a-f]{40}", previous_sha + ): + fail("stable component state has no valid source SHA") + if previous_sha == source_sha: + fail("unchanged source cannot produce another release") + if current_contract is None: + change = "patch" + else: + previous_contract = read_contract( + repository, previous_sha, contract_path + ) + change = change_classification( + previous_contract, current_contract + ) + expected_stable = bump(str(previous_version), change) + + if arguments.channel == "nightly": + if not arguments.nightly_sequence or not re.fullmatch( + r"[0-9]+", arguments.nightly_sequence + ): + fail("--nightly-sequence must be a positive integer") + version = f"{expected_stable}-nightly.{arguments.nightly_sequence}" + else: + requested = arguments.requested_version + if not isinstance(requested, str) or not RELEASE_VERSION.fullmatch( + requested + ): + fail("--requested-version must be canonical SemVer") + requested_base = requested.split("-", 1)[0] + if requested_base != expected_stable: + fail( + f"{change} change requires version {expected_stable}; " + f"received {requested}" + ) + if arguments.channel == "stable" and "-" in requested: + fail("stable release version must not have a prerelease suffix") + if arguments.channel == "beta" and "-" not in requested: + fail("beta release version must have a prerelease suffix") + version = requested + + result = { + "schemaVersion": 1, + "componentId": component_id, + "channel": arguments.channel, + "componentVersion": version, + "productCompatibility": compatibility, + "sourceSha": source_sha, + "sourceTreeHash": f"git-sha1:{source_tree}", + "abiHash": abi_hash, + "change": change, + } + encoded = canonical(result) + if arguments.output is None: + sys.stdout.buffer.write(encoded) + else: + temporary = arguments.output.with_name(arguments.output.name + ".tmp") + temporary.write_bytes(encoded) + temporary.replace(arguments.output) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/publish-component-feeds.py b/scripts/publish-component-feeds.py index a10b9d7..b7608da 100755 --- a/scripts/publish-component-feeds.py +++ b/scripts/publish-component-feeds.py @@ -213,6 +213,31 @@ class Signer: return document +class PublicKeyVerifier: + verify = Signer.verify + + def __init__(self, public_key: Path, key_id: str) -> None: + self.public_key = regular_file(public_key, "public key") + self.key_id = key_id + self.temporary = tempfile.TemporaryDirectory( + prefix="echoion-component-feed-verify." + ) + self.directory = Path(self.temporary.name) + run_openssl( + [ + "pkey", + "-pubin", + "-in", + os.fspath(self.public_key), + "-noout", + ], + "validate the feed public key", + ) + + def close(self) -> None: + self.temporary.cleanup() + + def validate_https(value: str, label: str) -> str: parsed = urlsplit(value) if ( diff --git a/scripts/publish-component-release.py b/scripts/publish-component-release.py new file mode 100755 index 0000000..763a62b --- /dev/null +++ b/scripts/publish-component-release.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +"""Merge one signed independent component release into an Echoion feed.""" + +from __future__ import annotations + +import argparse +import hashlib +import importlib.util +from pathlib import Path +import re +from types import ModuleType +from typing import Any, NoReturn +from urllib.parse import quote + + +GIT_SHA = re.compile(r"^[0-9a-f]{40}$") +SEMVER = re.compile( + r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)" + r"(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?" + r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$" +) + + +def fail(message: str) -> NoReturn: + raise SystemExit(f"publish-component-release: {message}") + + +def load_feed_helpers() -> ModuleType: + path = Path(__file__).with_name("publish-component-feeds.py") + specification = importlib.util.spec_from_file_location( + "echoion_publish_component_feeds", path + ) + if specification is None or specification.loader is None: + fail(f"cannot load shared feed helpers from {path}") + module = importlib.util.module_from_spec(specification) + specification.loader.exec_module(module) + return module + + +def validate_manifest( + helpers: ModuleType, + manifest: dict[str, Any], + definition: dict[str, Any], + component_id: str, +) -> None: + expected = { + "schemaVersion": 3, + "componentId": component_id, + "packageId": definition["packageId"], + "kind": definition["kind"], + "activation": definition["activation"], + "dependencies": definition["dependencies"], + } + for field, value in expected.items(): + if manifest.get(field) != value: + fail(f"manifest {field} does not match the registry") + if not SEMVER.fullmatch(str(manifest.get("componentVersion", ""))): + fail("manifest componentVersion is not canonical SemVer") + if not GIT_SHA.fullmatch(str(manifest.get("sourceSha", ""))): + fail("manifest sourceSha is invalid") + if not re.fullmatch( + r"(?:git-sha1:[0-9a-f]{40}|sha256:[0-9a-f]{64})", + str(manifest.get("sourceTreeHash", "")), + ): + fail("manifest sourceTreeHash is invalid") + abi_hash = manifest.get("abiHash") + if abi_hash is not None and not re.fullmatch( + r"sha256:[0-9a-f]{64}", str(abi_hash) + ): + fail("manifest abiHash is invalid") + compatibility = manifest.get("productCompatibility") + if not isinstance(compatibility, str) or not compatibility: + fail("manifest productCompatibility is missing") + if not isinstance(manifest.get("buildDependencies"), dict): + fail("manifest buildDependencies must be an object") + for field in ( + "artifactIdentity", + "platform", + "architecture", + "toolchainContract", + ): + if not isinstance(manifest.get(field), str) or not manifest[field]: + fail(f"manifest {field} is missing") + if manifest["artifactIdentity"] != ( + f"{manifest['packageId']}-{manifest['componentVersion']}-" + f"{manifest['platform']}-{manifest['architecture']}" + ): + fail("manifest artifactIdentity is inconsistent") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--registry", type=Path, default=Path("components.json")) + parser.add_argument("--component", required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--archive", type=Path, required=True) + parser.add_argument("--feed-root", type=Path, required=True) + parser.add_argument("--base-url", required=True) + parser.add_argument("--artifact-base-url", required=True) + parser.add_argument( + "--channel", choices=("stable", "beta", "nightly"), required=True + ) + parser.add_argument("--sequence", type=int, required=True) + parser.add_argument("--generated-at") + parser.add_argument("--valid-days", type=int, default=45) + parser.add_argument("--key-id", required=True) + parser.add_argument("--private-key", type=Path, required=True) + arguments = parser.parse_args() + + helpers = load_feed_helpers() + if not helpers.TOKEN.fullmatch(arguments.component): + fail("invalid component ID") + if not helpers.TOKEN.fullmatch(arguments.key_id): + fail("invalid key ID") + if arguments.sequence < 1 or arguments.sequence > (1 << 63) - 1: + fail("--sequence must be between 1 and 2^63-1") + if arguments.valid_days < 1 or arguments.valid_days > 365: + fail("--valid-days must be between 1 and 365") + base_url = helpers.validate_https(arguments.base_url, "--base-url") + artifact_base_url = helpers.validate_https( + arguments.artifact_base_url, "--artifact-base-url" + ) + + registry = helpers.load_object(arguments.registry, "component registry") + definitions = registry.get("components") + if registry.get("schemaVersion") != 1 or not isinstance(definitions, dict): + fail("unsupported component registry schema") + definition = definitions.get(arguments.component) + if not isinstance(definition, dict): + fail(f"component is not registered: {arguments.component}") + manifest_path = helpers.regular_file( + arguments.manifest, "component package manifest" + ) + archive = helpers.regular_file(arguments.archive, "component package") + manifest = helpers.load_object(manifest_path, "component package manifest") + validate_manifest(helpers, manifest, definition, arguments.component) + expected_archive = f"{manifest['artifactIdentity']}.tar.zst" + if archive.name != expected_archive: + fail(f"archive must be named {expected_archive}") + + version = manifest["componentVersion"] + if arguments.channel == "stable" and "-" in version: + fail("stable releases must not use a prerelease version") + if arguments.channel == "beta" and "-" not in version: + fail("beta releases must use a prerelease version") + if arguments.channel == "nightly" and "-nightly." not in version: + fail("nightly releases must use a -nightly.N version") + + generated = helpers.parse_time(arguments.generated_at) + generated_at = helpers.format_time(generated) + expires_at = helpers.format_time( + generated + helpers.timedelta(days=arguments.valid_days) + ) + feed_root = arguments.feed_root.resolve() + signer = helpers.Signer(arguments.private_key, arguments.key_id) + writes: dict[Path, bytes] = {} + try: + archive_sha = helpers.digest(archive) + manifest_sha = hashlib.sha256(helpers.canonical(manifest)).hexdigest() + state_path = ( + feed_root + / "state" + / "components" + / f"{arguments.component}.json" + ) + state = ( + helpers.load_object(state_path, "component state") + if state_path.exists() + else { + "schemaVersion": 2, + "componentId": arguments.component, + "channels": {}, + } + ) + channels = state.setdefault("channels", {}) + old_channel = channels.get(arguments.channel, {}) + old_sequence = old_channel.get("sequence", 0) + if not isinstance(old_sequence, int) or old_sequence >= arguments.sequence: + fail( + f"{arguments.component} {arguments.channel} sequence " + "is not monotonic" + ) + if arguments.channel == "stable": + if ( + state.get("lastSourceSha") == manifest["sourceSha"] + and state.get("artifactHash") not in (None, archive_sha) + ): + fail("changed artifact for an unchanged source SHA") + state.update( + { + "lastSourceSha": manifest["sourceSha"], + "semVer": version, + "abiSchema": manifest["abiHash"], + "artifactHash": archive_sha, + "sequence": arguments.sequence, + } + ) + channels[arguments.channel] = { + "version": version, + "artifactHash": archive_sha, + "sourceSha": manifest["sourceSha"], + "sequence": arguments.sequence, + } + + relative = helpers.component_path(registry, arguments.component) + version_path = ( + feed_root + / "feeds" + / arguments.channel + / relative + / f"{version}.json" + ) + latest_path = version_path.with_name("latest.json") + artifact_url = ( + f"{artifact_base_url}/{quote(arguments.component, safe='')}/" + f"{quote(version, safe='')}/{quote(archive.name, safe='')}" + ) + artifact = { + "name": archive.name, + "url": artifact_url, + "sha256": archive_sha, + "size": archive.stat().st_size, + "manifestSha256": manifest_sha, + "packageType": "tar.zst", + } + payload = { + "schemaVersion": 3, + "document": "echoion-component-release", + "channel": arguments.channel, + "sequence": arguments.sequence, + "generatedAt": generated_at, + "expiresAt": expires_at, + "productCompatibility": manifest["productCompatibility"], + "componentId": arguments.component, + "pluginId": definition.get("pluginId"), + "kind": definition["kind"], + "componentVersion": version, + "sourceSha": manifest["sourceSha"], + "sourceTreeHash": manifest["sourceTreeHash"], + "abiHash": manifest["abiHash"], + "artifactIdentity": manifest["artifactIdentity"], + "activation": definition["activation"], + "platform": manifest["platform"], + "architecture": manifest["architecture"], + "toolchainContract": manifest["toolchainContract"], + "dependencies": definition["dependencies"], + "buildDependencies": manifest["buildDependencies"], + "artifact": artifact, + } + envelope = signer.envelope(payload) + if version_path.exists(): + existing = signer.verify( + version_path.read_bytes(), + f"{arguments.component} version feed", + ) + immutable = { + key: value + for key, value in payload.items() + if key not in {"generatedAt", "expiresAt", "sequence"} + } + if any(existing.get(key) != value for key, value in immutable.items()): + fail(f"immutable version feed conflict: {version_path}") + else: + writes[version_path] = envelope + writes[latest_path] = envelope + writes[state_path] = helpers.canonical(state) + + catalog_path = ( + feed_root / "feeds" / arguments.channel / "catalog.json" + ) + old_components: list[dict[str, Any]] = [] + if catalog_path.exists(): + old_catalog = signer.verify( + catalog_path.read_bytes(), f"{arguments.channel} catalog" + ) + if ( + old_catalog.get("document") != "echoion-component-catalog" + or old_catalog.get("channel") != arguments.channel + ): + fail("existing catalog has the wrong document or channel") + old_catalog_sequence = old_catalog.get("sequence", 0) + if ( + not isinstance(old_catalog_sequence, int) + or old_catalog_sequence >= arguments.sequence + ): + fail("catalog sequence is not monotonic") + existing_components = old_catalog.get("components") + if not isinstance(existing_components, list): + fail("existing catalog components must be an array") + old_components = [ + item + for item in existing_components + if isinstance(item, dict) + and item.get("componentId") != arguments.component + ] + + relative_url = relative.as_posix() + old_components.append( + { + "componentId": arguments.component, + "pluginId": definition.get("pluginId"), + "kind": definition["kind"], + "componentVersion": version, + "productCompatibility": manifest["productCompatibility"], + "activation": definition["activation"], + "dependencies": definition["dependencies"], + "sequence": arguments.sequence, + "latestUrl": ( + f"{base_url}/feeds/{arguments.channel}/" + f"{relative_url}/latest.json" + ), + "artifactSha256": archive_sha, + } + ) + old_components.sort(key=lambda item: str(item.get("componentId", ""))) + catalog = { + "schemaVersion": 3, + "document": "echoion-component-catalog", + "channel": arguments.channel, + "sequence": arguments.sequence, + "generatedAt": generated_at, + "expiresAt": expires_at, + "components": old_components, + } + writes[catalog_path] = signer.envelope(catalog) + for path, content in sorted(writes.items()): + helpers.atomic_write(path, content) + finally: + signer.close() + + print( + f"published {arguments.component} {arguments.channel} " + f"at sequence {arguments.sequence}" + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/release-component.sh b/scripts/release-component.sh new file mode 100755 index 0000000..8755220 --- /dev/null +++ b/scripts/release-component.sh @@ -0,0 +1,349 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + echo "usage: $0 COMPONENT_RELEASE_JSON" >&2 + exit 2 +} + +(($# == 1)) || usage + +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P) +root=$(cd -- "$script_dir/.." && pwd -P) +source_root=$(pwd -P) +configuration=$(realpath -- "$1") + +required_commands=( + aws + cmake + cmp + ctest + find + git + jq + ninja + openssl + python3 + realpath + ssh + zstd +) +for command_name in "${required_commands[@]}"; do + command -v "$command_name" >/dev/null || + { + echo "release-component: missing command: $command_name" >&2 + exit 2 + } +done + +required_environment=( + ECHOION_COMPONENT_SSH_KEY + ECHOION_DISTRIBUTION_BASE_URL + ECHOION_FEED_BASE_URL + ECHOION_FEED_COMMIT_SIGNING_KEY + ECHOION_FEED_PRIVATE_KEY + ECHOION_FEED_REPOSITORY + ECHOION_FEED_SIGNING_KEY_ID + ECHOION_OBJECT_STORAGE_BUCKET + ECHOION_RELEASE_TAG_ALLOWED_SIGNERS + GITEA_API_URL + GITEA_RELEASE_TOKEN + GITEA_REPOSITORY +) +for variable in "${required_environment[@]}"; do + if [[ -z ${!variable:-} ]]; then + echo "release-component: $variable is required" >&2 + exit 2 + fi +done + +component_id=$(jq -er ' + if .schemaVersion == 1 and + (.componentId | type == "string" and length > 0) and + (.productCompatibility | type == "string" and length > 0) and + (.cmakeOptions | type == "object") + then .componentId + else error("invalid component release configuration") + end +' "$configuration") +if [[ ! $component_id =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$ ]]; then + echo "release-component: invalid component ID" >&2 + exit 2 +fi + +repository_name=${GITEA_REPOSITORY#*/} +if [[ $GITEA_REPOSITORY != */* || -z $repository_name ]]; then + echo "release-component: GITEA_REPOSITORY must be owner/name" >&2 + exit 2 +fi + +work_root=${RUNNER_TEMP:-"$source_root/.component-release"} +work_root=$(realpath -m -- "$work_root/echoion-$component_id") +components="$work_root/components" +dependencies="$work_root/dependencies" +build="$work_root/build" +install_root="$work_root/install" +dist="$work_root/dist" +feed_state="$work_root/feed-state" +secrets_dir="$work_root/secrets" + +mkdir -p "$work_root" +rm -rf -- "$components" "$dependencies" "$build" "$install_root" "$dist" \ + "$feed_state" "$secrets_dir" +mkdir -p "$secrets_dir" +chmod 0700 "$secrets_dir" + +cleanup() { + rm -rf -- "$secrets_dir" +} +trap cleanup EXIT + +umask 077 +ssh_key="$secrets_dir/release-ssh" +known_hosts="$secrets_dir/known-hosts" +feed_key="$secrets_dir/feed-ed25519.pem" +commit_key="$secrets_dir/feed-commit-key" +allowed_signers="$secrets_dir/tag-allowed-signers" +printf '%s\n' "$ECHOION_COMPONENT_SSH_KEY" >"$ssh_key" +printf '%s\n' "$ECHOION_FEED_PRIVATE_KEY" >"$feed_key" +printf '%s\n' "$ECHOION_FEED_COMMIT_SIGNING_KEY" >"$commit_key" +printf '%s\n' "$ECHOION_RELEASE_TAG_ALLOWED_SIGNERS" >"$allowed_signers" +printf '%s\n' \ + 'git.faumaray.ru ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCzZEz9JLrzk6oLiloSbueAN28vYL58Y/dTHBgRuBMMib9IJ1aDJShhr3kwC9sfOT0AzK0uwcMAqCAIkwJwttde8dIg0Mee0cmB/1JkoqFF4X3MUGD1r3nk8SSZNhIiPqo16hDF9Hf3FkovztIlBVntkyP9Iy9hYfP818Tiq3yRXROGdHjR7IfY4jR2QGfGrd/RtvPGExVqusxidy141240A8aRAwMFUqFdEvmXWjizrtCUqcrL/k1GEh0yJzbCdNOVUI6OuWd8tPluSBvmmeoNpKnCSl4Mkg36HObbOyrsme0asZqjcj0od65WYWApMPN0pUqhNu2CP83Nfor2VFwkdPRwe7cAZ0OD/8wyT6Hz5q1wWgf82y4tYDoDRYsd8JU86eebkJ07T5nCrEeC4Sj+qT4S5xv/kECAhxyP4QGnunORnY2fYsdNGzpPvbMN7gHe9UcIcQdOIgV3wrR1qpMVNcd8AEC2A3TRv/jzMCHSjmGGpgiy1Db2CZAjp5+PcjNmjvoPNN0NiA9X4rIVSeTfflWnDRmeNRJeZa73StjpU17EcAf97COUQPGWJQDgpJqINSpYU50fuaLBfzKnIRuiHjKQmyKe/zgRSmulnYFYM3AJfn8Ykg2VvkUQGvCt1+fqYiUa1iVFuwPP3ZigYF1mOZRpPnos5kaNmlB01q2sZw==' \ + >"$known_hosts" +chmod 0600 "$ssh_key" "$known_hosts" "$feed_key" "$commit_key" \ + "$allowed_signers" +openssl pkey -in "$feed_key" -noout +export GIT_SSH_COMMAND="ssh -i $ssh_key -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$known_hosts" + +git clone --filter=blob:none --branch release-feed --single-branch \ + "$ECHOION_FEED_REPOSITORY" "$feed_state" + +event=${GITEA_EVENT_NAME:-push} +sequence=$(python3 -c 'import time; print(time.time_ns() // 1_000_000)') +if [[ $event == schedule ]]; then + channel=nightly + release_tag="nightly-$(date -u +%Y%m%d)-${GITEA_RUN_NUMBER:-$sequence}" + requested_arguments=(--nightly-sequence "$sequence") +else + release_tag=${GITEA_REF_NAME:-} + if [[ -z $release_tag || $release_tag != v* ]]; then + echo "release-component: a v* tag is required" >&2 + exit 2 + fi + version_from_tag=${release_tag#v} + if [[ $version_from_tag == *-* ]]; then + channel=beta + else + channel=stable + fi + requested_arguments=(--requested-version "$version_from_tag") + "$script_dir/verify-gitea-release-tag.sh" \ + --tag "$release_tag" \ + --event-sha "${GITEA_SHA:-$(git rev-parse HEAD)}" \ + --allowed-signers "$allowed_signers" \ + --notes-output "$work_root/release-notes.md" >/dev/null +fi + +metadata="$work_root/release-metadata.json" +set +e +python3 "$script_dir/prepare-component-release.py" \ + --registry "$root/components.json" \ + --configuration "$configuration" \ + --repository "$source_root" \ + --feed-root "$feed_state" \ + --channel "$channel" \ + "${requested_arguments[@]}" \ + --output "$metadata" +prepare_status=$? +set -e +if ((prepare_status == 3)) && [[ $channel == nightly ]]; then + echo "release-component: $component_id has no unpublished nightly source" + exit 0 +fi +((prepare_status == 0)) || exit "$prepare_status" + +component_version=$(jq -er .componentVersion "$metadata") +source_sha=$(jq -er .sourceSha "$metadata") +source_tree_hash=$(jq -er .sourceTreeHash "$metadata") +product_compatibility=$(jq -er .productCompatibility "$metadata") +abi_hash=$(jq -r '.abiHash // empty' "$metadata") +product_version=$(python3 - "$root/CMakeLists.txt" <<'PY' +import pathlib +import re +import sys + +source = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8") +match = re.search( + r"(?m)^project\(Echoion[ \t]+VERSION[ \t]+" + r"([0-9]+\.[0-9]+\.[0-9]+)[ \t]+LANGUAGES[ \t]+CXX\)$", + source, +) +if match is None: + raise SystemExit("release-component: cannot read Echoion product version") +print(match.group(1)) +PY +) + +ECHOION_COMPONENT_SSH_KEY=$ECHOION_COMPONENT_SSH_KEY \ + "$script_dir/ci-checkout-components.sh" "$components" "$dependencies" + +build_dependencies="$work_root/build-dependencies.json" +python3 - "$root/components.json" "$root/components.lock.json" \ + "$component_id" "$build_dependencies" <<'PY' +import json +import pathlib +import sys + +registry = json.loads(pathlib.Path(sys.argv[1]).read_text()) +lock = json.loads(pathlib.Path(sys.argv[2]).read_text()) +component = registry["components"][sys.argv[3]] +result = {} +for dependency in component["dependencies"]: + value = lock["components"][dependency] + result[dependency] = { + "componentVersion": value["componentVersion"], + "revision": value["revision"], + "abiHash": value["abiHash"], + } +pathlib.Path(sys.argv[4]).write_text( + json.dumps(result, sort_keys=True, separators=(",", ":")) + "\n" +) +PY + +cmake_arguments=( + -S "$source_root" + -B "$build" + -G Ninja + -DCMAKE_BUILD_TYPE=Release + -DCMAKE_INSTALL_PREFIX="$install_root" + -DECHOION_COMPONENT_VERSION="$component_version" + -DECHOION_PRODUCT_VERSION="$product_version" + -DCPM_Void_SOURCE="$dependencies/VoidLibrary" + -DCPM_VoidTeamspeak_SOURCE="$dependencies/VoidTeamspeak" +) +while IFS= read -r dependency; do + cmake_arguments+=("-DCPM_${dependency}_SOURCE=$components/$dependency") +done < <(jq -r --arg id "$component_id" ' + .components[$id].dependencies | keys[] +' "$root/components.json") +while IFS=$'\t' read -r option value; do + cmake_arguments+=("-D${option}=${value}") +done < <(jq -r '.cmakeOptions | to_entries[] | [.key, .value] | @tsv' \ + "$configuration") + +cmake "${cmake_arguments[@]}" +cmake --build "$build" --parallel +ctest --test-dir "$build" --output-on-failure +cmake --install "$build" + +package_arguments=( + --registry "$root/components.json" + --component "$component_id" + --package-root "$install_root" + --output "$dist" + --component-version "$component_version" + --product-compatibility "$product_compatibility" + --source-sha "$source_sha" + --source-tree-hash "$source_tree_hash" + --build-dependencies "$build_dependencies" +) +if [[ -n $abi_hash ]]; then + package_arguments+=(--abi-hash "$abi_hash") +fi +SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD) \ + python3 "$script_dir/package-component.py" "${package_arguments[@]}" + +manifest=$(find "$dist" -maxdepth 1 -type f -name '*.manifest.json' -print) +archive=$(find "$dist" -maxdepth 1 -type f -name '*.tar.zst' -print) +[[ -f $manifest && -f $archive ]] || + { + echo "release-component: packaging did not produce one release" >&2 + exit 1 + } + +object_key="${ECHOION_OBJECT_STORAGE_PREFIX:-components}/$component_id/$component_version/$(basename "$archive")" +aws_arguments=() +if [[ -n ${ECHOION_OBJECT_STORAGE_ENDPOINT:-} ]]; then + aws_arguments+=(--endpoint-url "$ECHOION_OBJECT_STORAGE_ENDPOINT") +fi +set +e +aws "${aws_arguments[@]}" s3api put-object \ + --bucket "$ECHOION_OBJECT_STORAGE_BUCKET" \ + --key "$object_key" \ + --body "$archive" \ + --if-none-match '*' >/dev/null +upload_status=$? +set -e +if ((upload_status != 0)); then + existing="$work_root/existing-archive" + aws "${aws_arguments[@]}" s3api get-object \ + --bucket "$ECHOION_OBJECT_STORAGE_BUCKET" \ + --key "$object_key" "$existing" >/dev/null + cmp -- "$archive" "$existing" || + { + echo "release-component: immutable object conflict: $object_key" >&2 + exit 1 + } +fi +verified="$work_root/verified-archive" +aws "${aws_arguments[@]}" s3api get-object \ + --bucket "$ECHOION_OBJECT_STORAGE_BUCKET" \ + --key "$object_key" "$verified" >/dev/null +cmp -- "$archive" "$verified" + +if [[ $channel == nightly ]]; then + printf 'Automated %s nightly from %s.\n' "$component_id" "$source_sha" \ + >"$work_root/release-notes.md" +fi +owner=${GITEA_REPOSITORY%%/*} +prerelease=() +if [[ $channel != stable ]]; then + prerelease+=(--prerelease) +fi +missing_tag=() +if [[ $channel == nightly ]]; then + missing_tag+=(--allow-missing-draft-tag) +fi +python3 "$script_dir/gitea_release.py" \ + --api-url "$GITEA_API_URL" \ + publish \ + --owner "$owner" \ + --repo "$repository_name" \ + --tag "$release_tag" \ + --target "$source_sha" \ + --name "$component_id $component_version" \ + --body-file "$work_root/release-notes.md" \ + --artifacts "$dist" \ + "${prerelease[@]}" \ + "${missing_tag[@]}" + +python3 "$script_dir/publish-component-release.py" \ + --registry "$root/components.json" \ + --component "$component_id" \ + --manifest "$manifest" \ + --archive "$archive" \ + --feed-root "$feed_state" \ + --base-url "$ECHOION_FEED_BASE_URL" \ + --artifact-base-url "$ECHOION_DISTRIBUTION_BASE_URL" \ + --channel "$channel" \ + --sequence "$sequence" \ + --valid-days 45 \ + --key-id "$ECHOION_FEED_SIGNING_KEY_ID" \ + --private-key "$feed_key" + +git -C "$feed_state" config user.name 'Echoion Component Release Bot' +git -C "$feed_state" config user.email 'release-bot@echoion.invalid' +git -C "$feed_state" config gpg.format ssh +git -C "$feed_state" config user.signingkey "$commit_key" +git -C "$feed_state" config commit.gpgsign true +git -C "$feed_state" add feeds state +if ! git -C "$feed_state" diff --cached --quiet; then + git -C "$feed_state" commit -S -m \ + "Feed: $component_id $channel $component_version" + git -C "$feed_state" cat-file commit HEAD | grep -q '^gpgsig ' + git -C "$feed_state" push origin HEAD:release-feed +fi + +git -C "$root" diff --exit-code -- components.lock.json +echo "release-component: published $component_id $component_version" diff --git a/scripts/release.sh b/scripts/release.sh index b839d6e..c2f4a03 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -10,6 +10,9 @@ Options: --dist-dir DIR Release output directory (default: dist) --jobs N Parallel build jobs --skip-tests Skip CTest and frontend tests + --skip-component-packages + Build only the Echoion product artifacts; component + packages are published by their own repositories --no-clean Reuse the configured build directory --update-channel NAME Component package channel (default: stable) @@ -67,6 +70,7 @@ dist_dir="$source_dir/dist" jobs= run_tests=1 clean_build=1 +package_components=1 use_container=1 update_channel=stable update_sequence= @@ -101,6 +105,10 @@ while (($#)); do run_tests=0 shift ;; + --skip-component-packages) + package_components=0 + shift + ;; --no-clean) clean_build=0 shift @@ -271,6 +279,7 @@ if ((use_container)); then ) [[ -n $jobs ]] && release_args+=(--jobs "$jobs") ((run_tests)) || release_args+=(--skip-tests) + ((package_components)) || release_args+=(--skip-component-packages) ((clean_build)) || release_args+=(--no-clean) [[ -z $void_source ]] || release_args+=(--void-source /workspace-deps/VoidLibrary) @@ -561,52 +570,54 @@ install -m 0755 "$source_dir/packaging/uninstall.sh" "$stage/uninstall.sh" mkdir -p "$dist_dir" component_stage_root="$build_dir/component-staging" -safe_remove_tree "$component_stage_root" -mkdir -p "$component_stage_root" -while IFS=$'\t' read -r component_id package_id; do - component_root="$component_stage_root/$package_id" - cmake --install "$build_dir" \ - --config Release \ - --component "Package${component_id}" \ - --prefix "$component_root" +if ((package_components)); then + safe_remove_tree "$component_stage_root" + mkdir -p "$component_stage_root" + while IFS=$'\t' read -r component_id package_id; do + component_root="$component_stage_root/$package_id" + cmake --install "$build_dir" \ + --config Release \ + --component "Package${component_id}" \ + --prefix "$component_root" - component_executables=() - component_libraries=() - while IFS= read -r -d '' component_elf; do - case $(file --brief --mime-type "$component_elf") in - application/x-executable|application/x-pie-executable|application/x-sharedlib) ;; - *) continue ;; - esac - case ${component_elf#"$component_root"/} in - bin/*) component_executables+=("$component_elf") ;; - *) component_libraries+=("$component_elf") ;; - esac + component_executables=() + component_libraries=() + while IFS= read -r -d '' component_elf; do + case $(file --brief --mime-type "$component_elf") in + application/x-executable|application/x-pie-executable|application/x-sharedlib) ;; + *) continue ;; + esac + case ${component_elf#"$component_root"/} in + bin/*) component_executables+=("$component_elf") ;; + *) component_libraries+=("$component_elf") ;; + esac + done < <( + find "$component_root" -type f -print0 | LC_ALL=C sort -z + ) + if ((${#component_executables[@]} || ${#component_libraries[@]})); then + component_executable_list=$( + IFS=';' + echo "${component_executables[*]}" + ) + component_library_list=$( + IFS=';' + echo "${component_libraries[*]}" + ) + cmake \ + "-DBUNDLE_ROOT=$component_root" \ + "-DBUNDLE_EXECUTABLES=$component_executable_list" \ + "-DBUNDLE_LIBRARIES=$component_library_list" \ + "-DBUNDLE_SEARCH_DIRECTORIES=$search_directories" \ + "-DBUNDLE_SEED_FILES=$compiler_runtimes" \ + "-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \ + -P "$source_dir/cmake/BundleComponentDependencies.cmake" + fi done < <( - find "$component_root" -type f -print0 | LC_ALL=C sort -z + python3 -c \ + 'import json,sys; data=json.load(open(sys.argv[1], encoding="utf-8"))["components"]; [print(name, data[name]["packageId"], sep="\t") for name in sorted(data)]' \ + "$source_dir/components.json" ) - if ((${#component_executables[@]} || ${#component_libraries[@]})); then - component_executable_list=$( - IFS=';' - echo "${component_executables[*]}" - ) - component_library_list=$( - IFS=';' - echo "${component_libraries[*]}" - ) - cmake \ - "-DBUNDLE_ROOT=$component_root" \ - "-DBUNDLE_EXECUTABLES=$component_executable_list" \ - "-DBUNDLE_LIBRARIES=$component_library_list" \ - "-DBUNDLE_SEARCH_DIRECTORIES=$search_directories" \ - "-DBUNDLE_SEED_FILES=$compiler_runtimes" \ - "-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \ - -P "$source_dir/cmake/BundleComponentDependencies.cmake" - fi -done < <( - python3 -c \ - 'import json,sys; data=json.load(open(sys.argv[1], encoding="utf-8"))["components"]; [print(name, data[name]["packageId"], sep="\t") for name in sorted(data)]' \ - "$source_dir/components.json" -) +fi artifact_base="echoion-${version}-linux-x86_64" archive="$dist_dir/$artifact_base.tar.zst" @@ -627,19 +638,21 @@ bash "$source_dir/scripts/package-release-payload.sh" \ install -m 0644 "$stage/manifest.json" "$external_manifest" install -m 0644 "$dependency_report" "$external_report" -component_sequence=${update_sequence:-$SOURCE_DATE_EPOCH} -if [[ $component_sequence == 0 ]]; then - component_sequence=1 +if ((package_components)); then + component_sequence=${update_sequence:-$SOURCE_DATE_EPOCH} + if [[ $component_sequence == 0 ]]; then + component_sequence=1 + fi + python3 "$source_dir/scripts/package-components.py" \ + --registry "$source_dir/components.json" \ + --lock "$source_dir/components.lock.json" \ + --staging-root "$component_stage_root" \ + --output "$component_dist" \ + --channel "$update_channel" \ + --sequence "$component_sequence" \ + --product-version "$version" \ + --toolchain-contract linux-x86_64-glibc-2.35-cxx26 fi -python3 "$source_dir/scripts/package-components.py" \ - --registry "$source_dir/components.json" \ - --lock "$source_dir/components.lock.json" \ - --staging-root "$component_stage_root" \ - --output "$component_dist" \ - --channel "$update_channel" \ - --sequence "$component_sequence" \ - --product-version "$version" \ - --toolchain-contract linux-x86_64-glibc-2.35-cxx26 ( cd "$dist_dir" mapfile -t checksum_files < <( @@ -654,5 +667,5 @@ echo " $archive" echo " $installer" echo " $external_manifest" echo " $external_report" -echo " $component_dist" +((package_components)) && echo " $component_dist" echo " $dist_dir/SHA256SUMS" diff --git a/scripts/tests/test_independent_component_release.py b/scripts/tests/test_independent_component_release.py new file mode 100755 index 0000000..eea3c9d --- /dev/null +++ b/scripts/tests/test_independent_component_release.py @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +"""Offline tests for product-independent component release transactions.""" + +from __future__ import annotations + +import base64 +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PACKAGE = ROOT / "scripts" / "package-component.py" +PUBLISH = ROOT / "scripts" / "publish-component-release.py" +VERIFY = ROOT / "scripts" / "verify-locked-component-feeds.py" + + +class IndependentComponentReleaseTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory( + prefix="echoion-independent-component." + ) + self.root = Path(self.temporary.name) + self.registry = self.root / "components.json" + self.output = self.root / "dist" + self.feed = self.root / "feed" + self.key = self.root / "key.pem" + self.public_key = self.root / "public.pem" + self.registry.write_text( + json.dumps( + { + "schemaVersion": 1, + "components": { + "EchoionApi": { + "repository": "Void/EchoionApi", + "packageId": "echoion-api", + "kind": "sdk", + "activation": "restart-required", + "dependencies": {}, + }, + "EchoionWeb": { + "repository": "Void/EchoionWeb", + "packageId": "echoion-web", + "kind": "runtime-module", + "activation": "restart-required", + "dependencies": { + "EchoionApi": ">=2.0.0 <3.0.0" + }, + }, + }, + } + ) + ) + subprocess.run( + [ + "openssl", + "genpkey", + "-algorithm", + "ED25519", + "-out", + str(self.key), + ], + check=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + self.key.chmod(0o600) + subprocess.run( + [ + "openssl", + "pkey", + "-in", + str(self.key), + "-pubout", + "-out", + str(self.public_key), + ], + check=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + def tearDown(self) -> None: + self.temporary.cleanup() + + def package(self, component: str, package_id: str, version: str) -> tuple[Path, Path]: + package_root = self.root / f"stage-{component}" + package_root.mkdir() + (package_root / "payload.txt").write_text(component) + environment = os.environ.copy() + environment["SOURCE_DATE_EPOCH"] = "100" + result = subprocess.run( + [ + str(PACKAGE), + "--registry", + str(self.registry), + "--component", + component, + "--package-root", + str(package_root), + "--output", + str(self.output), + "--component-version", + version, + "--source-sha", + ("1" if component == "EchoionApi" else "2") * 40, + "--source-tree-hash", + "git-sha1:" + ("3" if component == "EchoionApi" else "4") * 40, + "--abi-hash", + "sha256:" + ("5" if component == "EchoionApi" else "6") * 64, + ], + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=environment, + ) + self.assertEqual(result.returncode, 0, result.stderr) + stem = f"{package_id}-{version}-linux-x86_64" + return ( + self.output / f"{stem}.manifest.json", + self.output / f"{stem}.tar.zst", + ) + + def publish( + self, + component: str, + manifest: Path, + archive: Path, + sequence: int, + ) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [ + str(PUBLISH), + "--registry", + str(self.registry), + "--component", + component, + "--manifest", + str(manifest), + "--archive", + str(archive), + "--feed-root", + str(self.feed), + "--base-url", + "https://updates.example.test/echoion", + "--artifact-base-url", + "https://downloads.example.test/components", + "--channel", + "stable", + "--sequence", + str(sequence), + "--generated-at", + "2026-07-29T12:00:00Z", + "--key-id", + "test-key", + "--private-key", + str(self.key), + ], + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + @staticmethod + def payload(path: Path) -> dict[str, object]: + envelope = json.loads(path.read_text()) + encoded = envelope["payload"] + raw = base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4)) + return json.loads(raw) + + def test_single_component_publication_merges_catalog(self) -> None: + api_manifest, api_archive = self.package( + "EchoionApi", "echoion-api", "2.1.0" + ) + api_result = self.publish( + "EchoionApi", api_manifest, api_archive, 100 + ) + self.assertEqual(api_result.returncode, 0, api_result.stderr) + web_manifest, web_archive = self.package( + "EchoionWeb", "echoion-web", "2.0.1" + ) + web_result = self.publish( + "EchoionWeb", web_manifest, web_archive, 101 + ) + self.assertEqual(web_result.returncode, 0, web_result.stderr) + + catalog = self.payload(self.feed / "feeds/stable/catalog.json") + self.assertEqual( + [item["componentId"] for item in catalog["components"]], + ["EchoionApi", "EchoionWeb"], + ) + api = self.payload( + self.feed / "feeds/stable/echoion-api/2.1.0.json" + ) + self.assertNotIn("productVersion", api) + for private_field in ( + "repository", + "repositoryUrl", + "cloneUrl", + "giteaReleaseUrl", + ): + self.assertNotIn(private_field, api) + self.assertEqual(api["productCompatibility"], ">=2.0.0 <3.0.0") + self.assertEqual( + api["artifact"]["url"], + "https://downloads.example.test/components/" + "EchoionApi/2.1.0/echoion-api-2.1.0-linux-x86_64.tar.zst", + ) + + def test_rejects_replay_without_mutating_lock(self) -> None: + manifest, archive = self.package( + "EchoionApi", "echoion-api", "2.0.1" + ) + first = self.publish("EchoionApi", manifest, archive, 200) + self.assertEqual(first.returncode, 0, first.stderr) + replay = self.publish("EchoionApi", manifest, archive, 200) + self.assertNotEqual(replay.returncode, 0) + self.assertIn("sequence is not monotonic", replay.stderr) + + def test_product_lock_verifies_against_independent_feeds(self) -> None: + manifests: dict[str, Path] = {} + for sequence, component, package_id, version in ( + (300, "EchoionApi", "echoion-api", "2.1.0"), + (301, "EchoionWeb", "echoion-web", "2.0.1"), + ): + manifest, archive = self.package( + component, package_id, version + ) + result = self.publish(component, manifest, archive, sequence) + self.assertEqual(result.returncode, 0, result.stderr) + manifests[component] = manifest + + locked: dict[str, object] = {} + for component, manifest_path in manifests.items(): + manifest = json.loads(manifest_path.read_text()) + locked[component] = { + "componentVersion": manifest["componentVersion"], + "revision": manifest["sourceSha"], + "sourceTreeHash": manifest["sourceTreeHash"], + "abiHash": manifest["abiHash"], + "artifactIdentity": manifest["artifactIdentity"], + } + lock = self.root / "components.lock.json" + lock.write_text( + json.dumps( + { + "schemaVersion": 2, + "productVersion": "2.0.0", + "components": locked, + } + ) + ) + result = subprocess.run( + [ + str(VERIFY), + "--registry", + str(self.registry), + "--lock", + str(lock), + "--feed-root", + str(self.feed), + "--channel", + "stable", + "--key-id", + "test-key", + "--public-key", + str(self.public_key), + ], + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("verified 2 locked components", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_prepare_component_release.py b/scripts/tests/test_prepare_component_release.py new file mode 100755 index 0000000..22f81f6 --- /dev/null +++ b/scripts/tests/test_prepare_component_release.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Tests for independent component version derivation.""" + +from __future__ import annotations + +import json +from pathlib import Path +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "scripts" / "prepare-component-release.py" + + +class PrepareComponentReleaseTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory( + prefix="echoion-prepare-component." + ) + self.root = Path(self.temporary.name) + self.repo = self.root / "repo" + self.feed = self.root / "feed" + self.repo.mkdir() + subprocess.run( + ["git", "init", "-b", "main"], + cwd=self.repo, + check=True, + stdout=subprocess.DEVNULL, + ) + subprocess.run( + ["git", "config", "user.email", "test@example.invalid"], + cwd=self.repo, + check=True, + ) + subprocess.run( + ["git", "config", "user.name", "Test"], + cwd=self.repo, + check=True, + ) + (self.repo / "abi").mkdir() + self.contract = self.repo / "abi/module.json" + self.contract.write_text( + json.dumps({"schemaVersion": 1, "functions": ["create"]}) + ) + self.commit("initial") + self.initial_sha = self.git("rev-parse", "HEAD") + self.registry = self.root / "components.json" + self.registry.write_text( + json.dumps( + { + "schemaVersion": 1, + "components": { + "EchoionExample": { + "repository": "Void/EchoionExample", + "packageId": "echoion-example", + "kind": "runtime-module", + "activation": "restart-required", + "dependencies": {}, + "abiContract": "abi/module.json", + } + }, + } + ) + ) + self.configuration = self.root / "component.release.json" + self.configuration.write_text( + json.dumps( + { + "schemaVersion": 1, + "componentId": "EchoionExample", + "productCompatibility": ">=2.0.0 <3.0.0", + "cmakeOptions": {}, + } + ) + ) + + def tearDown(self) -> None: + self.temporary.cleanup() + + def git(self, *arguments: str) -> str: + return subprocess.check_output( + ["git", *arguments], cwd=self.repo, text=True + ).strip() + + def commit(self, message: str) -> None: + subprocess.run(["git", "add", "."], cwd=self.repo, check=True) + subprocess.run( + ["git", "commit", "-m", message], + cwd=self.repo, + check=True, + stdout=subprocess.DEVNULL, + ) + + def state(self, version: str) -> None: + path = self.feed / "state/components/EchoionExample.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + json.dumps( + { + "schemaVersion": 2, + "componentId": "EchoionExample", + "lastSourceSha": self.initial_sha, + "semVer": version, + "channels": {}, + } + ) + ) + + def run_prepare( + self, version: str + ) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [ + str(SCRIPT), + "--registry", + str(self.registry), + "--configuration", + str(self.configuration), + "--repository", + str(self.repo), + "--feed-root", + str(self.feed), + "--channel", + "stable", + "--requested-version", + version, + ], + check=False, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + def test_initial_component_starts_at_2_0_0(self) -> None: + result = self.run_prepare("2.0.0") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["change"], "initial") + + def test_append_only_contract_change_requires_minor(self) -> None: + self.state("2.0.0") + self.contract.write_text( + json.dumps( + {"schemaVersion": 1, "functions": ["create", "destroy"]} + ) + ) + self.commit("append") + rejected = self.run_prepare("2.0.1") + self.assertNotEqual(rejected.returncode, 0) + accepted = self.run_prepare("2.1.0") + self.assertEqual(accepted.returncode, 0, accepted.stderr) + self.assertEqual(json.loads(accepted.stdout)["change"], "minor") + + def test_reordered_contract_requires_major(self) -> None: + self.state("2.2.0") + self.contract.write_text( + json.dumps({"schemaVersion": 1, "functions": ["destroy", "create"]}) + ) + self.commit("breaking") + accepted = self.run_prepare("3.0.0") + self.assertEqual(accepted.returncode, 0, accepted.stderr) + self.assertEqual(json.loads(accepted.stdout)["change"], "major") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/verify-locked-component-feeds.py b/scripts/verify-locked-component-feeds.py new file mode 100755 index 0000000..0009202 --- /dev/null +++ b/scripts/verify-locked-component-feeds.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Verify that a product lock is fully represented by signed component feeds.""" + +from __future__ import annotations + +import argparse +import importlib.util +from pathlib import Path +import re +from types import ModuleType +from typing import Any, NoReturn + + +def fail(message: str) -> NoReturn: + raise SystemExit(f"verify-locked-component-feeds: {message}") + + +def load_helpers() -> ModuleType: + path = Path(__file__).with_name("publish-component-feeds.py") + specification = importlib.util.spec_from_file_location( + "echoion_verify_component_feeds", path + ) + if specification is None or specification.loader is None: + fail(f"cannot load shared feed helpers from {path}") + module = importlib.util.module_from_spec(specification) + specification.loader.exec_module(module) + return module + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--registry", type=Path, default=Path("components.json")) + parser.add_argument( + "--lock", type=Path, default=Path("components.lock.json") + ) + parser.add_argument("--feed-root", type=Path, required=True) + parser.add_argument( + "--channel", choices=("stable", "beta", "nightly"), default="stable" + ) + parser.add_argument("--key-id", required=True) + parser.add_argument("--public-key", type=Path, required=True) + arguments = parser.parse_args() + + helpers = load_helpers() + registry = helpers.load_object(arguments.registry, "component registry") + lock = helpers.load_object(arguments.lock, "component lock") + definitions = registry.get("components") + locked = lock.get("components") + if ( + registry.get("schemaVersion") != 1 + or lock.get("schemaVersion") != 2 + or not isinstance(definitions, dict) + or not isinstance(locked, dict) + or set(definitions) != set(locked) + ): + fail("unsupported or inconsistent component metadata") + + feed_root = arguments.feed_root.resolve(strict=True) + verifier = helpers.PublicKeyVerifier( + arguments.public_key, arguments.key_id + ) + try: + catalog_path = ( + feed_root / "feeds" / arguments.channel / "catalog.json" + ) + catalog = verifier.verify( + catalog_path.read_bytes(), f"{arguments.channel} catalog" + ) + if ( + catalog.get("schemaVersion") != 3 + or catalog.get("document") != "echoion-component-catalog" + or catalog.get("channel") != arguments.channel + ): + fail("catalog is not an independent component catalog") + entries = catalog.get("components") + if not isinstance(entries, list): + fail("catalog components must be an array") + catalog_by_id: dict[str, dict[str, Any]] = {} + for entry in entries: + if not isinstance(entry, dict): + fail("catalog component entry must be an object") + component_id = entry.get("componentId") + if ( + not isinstance(component_id, str) + or component_id in catalog_by_id + ): + fail("catalog contains an invalid or duplicate component ID") + catalog_by_id[component_id] = entry + + for component_id in sorted(definitions): + definition = definitions[component_id] + expected = locked[component_id] + entry = catalog_by_id.get(component_id) + if entry is None: + fail(f"catalog is missing locked component {component_id}") + if entry.get("componentVersion") != expected["componentVersion"]: + fail(f"catalog version mismatch for {component_id}") + relative = helpers.component_path(registry, component_id) + release_path = ( + feed_root + / "feeds" + / arguments.channel + / relative + / f"{expected['componentVersion']}.json" + ) + release = verifier.verify( + release_path.read_bytes(), f"{component_id} release" + ) + required = { + "schemaVersion": 3, + "document": "echoion-component-release", + "channel": arguments.channel, + "componentId": component_id, + "componentVersion": expected["componentVersion"], + "sourceSha": expected["revision"], + "sourceTreeHash": expected["sourceTreeHash"], + "abiHash": expected["abiHash"], + "artifactIdentity": expected["artifactIdentity"], + "activation": definition["activation"], + "dependencies": definition["dependencies"], + } + for field, value in required.items(): + if release.get(field) != value: + fail(f"{component_id} release {field} does not match lock") + artifact = release.get("artifact") + if ( + not isinstance(artifact, dict) + or not re.fullmatch( + r"[0-9a-f]{64}", str(artifact.get("sha256", "")) + ) + or not str(artifact.get("url", "")).startswith("https://") + ): + fail(f"{component_id} release artifact is invalid") + except OSError as error: + fail(f"cannot read component feed: {error}") + finally: + verifier.close() + + print( + f"verified {len(definitions)} locked components in " + f"{arguments.channel}" + ) + + +if __name__ == "__main__": + main() diff --git a/tests/ModuleDescriptors.cpp b/tests/ModuleDescriptors.cpp index acf8a10..718d70e 100644 --- a/tests/ModuleDescriptors.cpp +++ b/tests/ModuleDescriptors.cpp @@ -10,13 +10,13 @@ namespace { - struct ModuleExpectation - { - const char* path; - std::string_view moduleId; - std::string_view version; + struct ModuleExpectation { + const char* path; + std::string_view moduleId; + std::string_view stableComponentId; + std::string_view version; }; -} +} // namespace Void::Testing::Test component_module_descriptors_are_loadable() { @@ -24,26 +24,31 @@ Void::Testing::Test component_module_descriptors_are_loadable() ModuleExpectation{ .path = ECHOION_TEST_HOST, .moduleId = "EchoionHost", + .stableComponentId = "EchoionHost", .version = "2.0.0", }, ModuleExpectation{ .path = ECHOION_TEST_CORE, .moduleId = "EchoionCore", + .stableComponentId = "EchoionCore", .version = "2.0.0", }, ModuleExpectation{ .path = ECHOION_TEST_WEB, .moduleId = "EchoionWeb", + .stableComponentId = "EchoionWeb", .version = "2.0.0", }, ModuleExpectation{ .path = ECHOION_TEST_PLUGIN_INTERNAL, .moduleId = "url-shortener-internal", + .stableComponentId = "EchoionPluginUrlShortenerInternal", .version = "2.0.0", }, ModuleExpectation{ .path = ECHOION_TEST_PLUGIN_EXTERNAL, .moduleId = "url-shortener-external", + .stableComponentId = "EchoionPluginUrlShortenerExternal", .version = "2.0.0", }, }; @@ -70,10 +75,10 @@ Void::Testing::Test component_module_descriptors_are_loadable() continue; } Void::Testing::expect(descriptor->validate().has_value()); - Void::Testing::expect_eq( - std::string_view{descriptor->module_id}, expected.moduleId); - Void::Testing::expect_eq( - descriptor->component_version.to_string(), expected.version); + Void::Testing::expect_eq(std::string_view{descriptor->module_id}, + expected.moduleId); + Void::Testing::expect_eq(descriptor->component_version.to_string(), + expected.version); auto module = descriptor->create(); Void::Testing::expect(module != nullptr); @@ -81,6 +86,42 @@ Void::Testing::Test component_module_descriptors_are_loadable() Void::Testing::expect_eq(module->name(), expected.moduleId); } module.reset(); + + const auto stableQuery = + reinterpret_cast( + dlsym(library, Echoion::Api::Module::stableQuerySymbol)); + Void::Testing::expect(stableQuery != nullptr); + if (stableQuery != nullptr) { + const echoion_module_descriptor_v1* stable = stableQuery(); + Void::Testing::expect(stable != nullptr); + if (stable != nullptr) { + Void::Testing::expect_eq(stable->struct_size, + sizeof(echoion_module_descriptor_v1)); + Void::Testing::expect_eq(stable->abi_version, + ECHOION_MODULE_ABI_VERSION); + Void::Testing::expect_eq( + std::string_view{stable->component_id.data, + stable->component_id.size}, + expected.stableComponentId); + Void::Testing::expect_eq(stable->version_major, 2U); + Void::Testing::expect_eq(stable->version_minor, 0U); + Void::Testing::expect_eq(stable->version_patch, 0U); + Void::Testing::expect(stable->api != nullptr); + if (stable->api != nullptr) { + Void::Testing::expect_eq(stable->api->struct_size, + sizeof(echoion_module_api_v1)); + Void::Testing::expect(stable->api->create != nullptr); + Void::Testing::expect(stable->api->destroy != nullptr); + echoion_module_instance_v1 instance = nullptr; + const auto status = stable->api->create(nullptr, &instance); + Void::Testing::expect_eq(status, ECHOION_STATUS_OK_V1); + Void::Testing::expect(instance != nullptr); + if (instance != nullptr) { + stable->api->destroy(instance); + } + } + } + } dlclose(library); } }