diff --git a/.gitea/workflows/build-and-package.yml b/.gitea/workflows/build-and-package.yml index 8dc4a5f..451e54d 100644 --- a/.gitea/workflows/build-and-package.yml +++ b/.gitea/workflows/build-and-package.yml @@ -7,7 +7,7 @@ on: workflow_dispatch: inputs: runtime_run_id: - description: 'Optional runtime workflow run ID; defaults to the MUSRFLOW_RUNTIME_RUN_ID repository variable' + description: 'Optional Actions runtime override; otherwise use the committed registry pin (legacy variable during migration)' required: false permissions: @@ -25,7 +25,8 @@ jobs: shell: bash env: ELECTRON_SKIP_BINARY_DOWNLOAD: '1' - RUNTIME_RUN_ID: ${{ inputs.runtime_run_id || vars.MUSRFLOW_RUNTIME_RUN_ID }} + RUNTIME_RUN_OVERRIDE: ${{ inputs.runtime_run_id }} + LEGACY_RUNTIME_RUN_ID: ${{ vars.MUSRFLOW_RUNTIME_RUN_ID }} PACKAGE_RUN_ID: ${{ gitea.run_id }} GITEA_EVENT_NAME: ${{ gitea.event_name }} GITEA_REF: ${{ gitea.ref }} @@ -46,11 +47,11 @@ jobs: - name: Check runtime selection run: | - [[ "$RUNTIME_RUN_ID" =~ ^[1-9][0-9]*$ ]] || { echo 'Set the MUSRFLOW_RUNTIME_RUN_ID repository variable or enter a numeric runtime_run_id' >&2; exit 1; } - echo "Selected runtime workflow run: $RUNTIME_RUN_ID" + node scripts/ci-runtime-registry.js select packaging/runtime/runtime-source.json echo "Packaging run ID for Publish packages: $PACKAGE_RUN_ID" - name: Download selected runtime + if: ${{ env.RUNTIME_SOURCE == 'artifact' }} uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: musrflow-runtime-linux-x64 @@ -59,6 +60,14 @@ jobs: repository: ${{ gitea.repository }} github-token: ${{ secrets.GITEA_TOKEN }} + - name: Download pinned registry runtime + if: ${{ env.RUNTIME_SOURCE == 'registry' }} + env: + GITEA_SERVER_URL: ${{ gitea.server_url }} + GITEA_REPOSITORY: ${{ gitea.repository }} + RUNTIME_TOKEN: ${{ secrets.PACKAGES_TOKEN || secrets.GITEA_TOKEN }} + run: node scripts/ci-runtime-registry.js download packaging/runtime/runtime-source.json runtime-download + - name: Install dependencies run: npm ci --no-audit --no-fund @@ -99,6 +108,7 @@ jobs: cp "$RUNTIME_DIR/runtime-manifest.json" artifacts/ printf 'runtime_workflow_run=%s\nmuSRFlow=%s\n' "$RUNTIME_RUN_ID" "$(git rev-parse HEAD)" > artifacts/build-source.txt cp .ci-release-context.json artifacts/release-context.json + if [ "$RUNTIME_SOURCE" = registry ]; then cp packaging/runtime/runtime-source.json artifacts/runtime-source.json; fi - name: Upload packages uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 diff --git a/.gitea/workflows/build-runtime.yml b/.gitea/workflows/build-runtime.yml index 0cc15e7..17032e3 100644 --- a/.gitea/workflows/build-runtime.yml +++ b/.gitea/workflows/build-runtime.yml @@ -10,6 +10,7 @@ on: permissions: contents: read + packages: write jobs: build-runtime: @@ -103,6 +104,26 @@ jobs: compression-level: 0 retention-days: 30 + - name: Set up Node.js for registry publication + uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: '22.23.2' + + - name: Publish durable runtime bundle + env: + GITEA_SERVER_URL: ${{ gitea.server_url }} + GITEA_REPOSITORY: ${{ gitea.repository }} + PACKAGES_TOKEN: ${{ secrets.PACKAGES_TOKEN || secrets.GITEA_TOKEN }} + run: node scripts/ci-runtime-registry.js publish dist/runtime-downloads runtime-source.json + + - name: Upload candidate runtime pin + uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: runtime-pin + path: runtime-source.json + if-no-files-found: error + retention-days: 30 + - name: Upload build diagnostics if: ${{ always() }} uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 diff --git a/.gitea/workflows/publish-runtime.yml b/.gitea/workflows/publish-runtime.yml new file mode 100644 index 0000000..cbded62 --- /dev/null +++ b/.gitea/workflows/publish-runtime.yml @@ -0,0 +1,71 @@ +name: Publish runtime + +on: + workflow_dispatch: + inputs: + runtime_run_id: + description: 'Existing runtime workflow run ID to preserve without recompiling' + required: true + +permissions: + contents: read + actions: read + packages: write + +jobs: + publish-runtime: + runs-on: ubuntu-latest-full + timeout-minutes: 90 + defaults: + run: + shell: bash + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: '1' + steps: + - name: Check out publisher + uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + github-server-url: ${{ gitea.server_url }} + persist-credentials: false + + - name: Check runtime run ID + env: + RUNTIME_RUN_ID: ${{ inputs.runtime_run_id }} + run: '[[ "$RUNTIME_RUN_ID" =~ ^[1-9][0-9]*$ ]]' + + - name: Download existing runtime + uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: musrflow-runtime-linux-x64 + path: runtime-download + run-id: ${{ inputs.runtime_run_id }} + repository: ${{ gitea.repository }} + github-token: ${{ secrets.GITEA_TOKEN }} + + - name: Set up Node.js + uses: https://github.com/actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: '22.23.2' + + - name: Verify archived runtime + run: | + npm ci --no-audit --no-fund + node scripts/ci-restore-runtime.js runtime-download .ci-runtime + + - name: Validate restored tools + run: bash packaging/runtime/validate-runtime.sh "$RUNTIME_DIR" --arch x64 + + - name: Publish durable runtime bundle + env: + GITEA_SERVER_URL: ${{ gitea.server_url }} + GITEA_REPOSITORY: ${{ gitea.repository }} + PACKAGES_TOKEN: ${{ secrets.PACKAGES_TOKEN || secrets.GITEA_TOKEN }} + run: node scripts/ci-runtime-registry.js publish runtime-download runtime-source.json + + - name: Upload candidate runtime pin + uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: runtime-pin + path: runtime-source.json + if-no-files-found: error + retention-days: 30 diff --git a/docs/DESKTOP_DEPLOYMENT.md b/docs/DESKTOP_DEPLOYMENT.md index 4a159b1..26bf5c2 100644 --- a/docs/DESKTOP_DEPLOYMENT.md +++ b/docs/DESKTOP_DEPLOYMENT.md @@ -101,19 +101,18 @@ for 14 days, subject to PSI's storage policy. Keep release copies separately. ### Package a selected runtime -**One-time setup:** in the repository's **Settings -> Actions -> Variables**, -set **MUSRFLOW_RUNTIME_RUN_ID** to the approved successful runtime workflow run -ID. Keep the working **PACKAGES_TOKEN** Actions secret configured for registry -publication. Variables are non-secret configuration; the token must remain a -secret. See [Gitea configuration variables](https://docs.gitea.com/usage/actions/actions-variables/). +**Preferred setup:** commit an approved registry runtime pin as +`packaging/runtime/runtime-source.json` (see the migration steps below). +Keep the working **PACKAGES_TOKEN** Actions secret configured for registry +download/publication. No runtime run ID is needed after the pin is committed. 1. After a successful runtime build, open **Actions -> Build and package -> Run workflow**. -2. Leave **runtime_run_id** empty to use **MUSRFLOW_RUNTIME_RUN_ID**, or enter - a runtime workflow run ID to override it for this build. There is no automatic +2. Leave **runtime_run_id** empty to use the committed pin, or enter + a runtime workflow run ID to override it for a manual build. There is no automatic "latest runtime" selection and no fallback to files from an earlier job. -3. The workflow downloads **musrflow-runtime-linux-x64** from this repository - using the job token's Actions read permission. It verifies and restores the bundle +3. The workflow downloads the pinned descriptor and archive from the package + registry, verifies both hashes and the recorded runtime identity, and restores the bundle in a job-local directory, then validates the scientific tools before building. 4. After tests and packaging succeed, the workflow saves **musrflow-linux-packages** as a run artifact, then **automatically publishes** the application and runtime @@ -131,8 +130,38 @@ the complete artifact is saved, so a registry failure can be retried without recompiling (see below). The same workflow also runs for version-tag pushes, as described below. -Durable runtime reuse is not enabled yet: runtime artifacts still expire -according to their retention policy; saving an ID in a variable does not extend it. +Registry runtimes are independent of Actions artifact retention. During migration, +an empty pin still permits the **MUSRFLOW_RUNTIME_RUN_ID** repository variable; +that legacy artifact path retains its expiry limit. A committed pin takes priority +over this variable. A broken/missing pinned package fails rather than silently +falling back to a different runtime. + +### Preserve and approve a durable runtime + +1. Open **Actions -> Publish runtime -> Run workflow** and enter the existing + runtime build ID (for example, `403788`). This is a one-time migration or a + retry of runtime publication, not a rebuild of ROOT/musrfit. +2. The workflow restores and validates that artifact, then publishes its archive, + descriptor, and checksum to the linked **musrflow-runtime-bundle** Generic + package. The registry version includes `linux-x64` and the full archive SHA-256. +3. Download the **runtime-pin** artifact from the completed run. Review its + `runtime-source.json`: ROOT version, musrfit source revision, runtime identity, + descriptor URL, and descriptor/archive SHA-256 hashes. +4. Replace `packaging/runtime/runtime-source.json` with that reviewed file, + commit, and push. Subsequent builds/tags use it automatically; remove the + legacy repository variable if no longer needed. + +New **Build runtime** runs also publish this durable bundle and emit a candidate +pin. They never change the approved pin automatically. The archive includes the +full manifest (tool fingerprints, source revision, build options, base-image +identity, platform, and architecture), so different builds cannot overwrite each +other. Only clean, source-pinned Linux x64 bundles are accepted by this publisher. +The checked-in initial pin is deliberately empty: do not substitute the older +local development runtime for the validated CI runtime. + +Package cleanup policies still apply: exclude approved runtime bundles from +automatic registry cleanup. If a runtime package or its credentials become +unavailable, the release fails clearly without using a cached or latest runtime. The old `build_runtime=false` option is removed: skipping a build does not supply a runtime on a fresh runner. The two workflow files are @@ -151,8 +180,9 @@ download does not require a personal token; PSI registry publication uses the ### Release automatically from a version tag -**Prerequisites:** set **MUSRFLOW_RUNTIME_RUN_ID** to an approved, unexpired -runtime artifact and keep **PACKAGES_TOKEN** configured. The tagged commit must +**Prerequisites:** commit an approved runtime pin (or, during migration, set +**MUSRFLOW_RUNTIME_RUN_ID** to an unexpired artifact) and keep **PACKAGES_TOKEN** +configured. The tagged commit must contain this workflow. Restrict who can push `v*` tags: those pushes publish packages using repository secrets. diff --git a/package.json b/package.json index c32b868..68c3988 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "checksums:md5": "sh -c 'd=dist; [ -d \"$d\" ] || exit 0; for f in \"$d\"/*; do [ -f \"$f\" ] || continue; case \"$f\" in *.rpm|*.AppImage) base=$(basename \"$f\"); (cd \"$d\" && md5sum \"$base\" > \"$base.md5\");; esac; done'", "checksums:sha256": "sh -c 'd=dist; [ -d \"$d\" ] || exit 0; for f in \"$d\"/*; do [ -f \"$f\" ] || continue; case \"$f\" in *.rpm|*.AppImage) base=$(basename \"$f\"); (cd \"$d\" && sha256sum \"$base\" > \"$base.sha256\");; esac; done'", "checksums": "npm run checksums:md5 && npm run checksums:sha256", - "test:electron": "node tests/log-highlighting.test.js && node tests/action-state.test.js && node tests/electron-missing-data.test.js && node tests/electron-run-data.test.js && node tests/electron-msr-title.test.js && node tests/electron-musrfit-threads.test.js && node tests/electron-t0-prompt-peak.test.js && node tests/window-layering.test.js && node tests/msr-generation.test.js && node tests/root-plot-clean.test.js && node tests/parameter-plot.test.js && node tests/help-window.test.js && node tests/release-packaging.test.js && node tests/ci-publish-packages.test.js && node tests/ci-release.test.js && node tests/runtime-validation.test.js && node tests/local-runtime.test.js && node tests/addrun.test.js && node tests/fit-statistic.test.js && node tests/series-fit-planner.test.js && node tests/series-fit-result.test.js && node tests/series-fit-inventory.test.js && node tests/series-fit-msr-preparation.test.js && node tests/series-artifact-contract.test.js && node tests/series-global-merge.test.js && node tests/series-fit-staging.test.js && node tests/series-fit-runner.test.js && node tests/series-runner-adapters.test.js && node tests/series-fit-routing.test.js && node tests/series-action-chips.test.js && node tests/singlehist-parity.test.js && node tests/url-parameters.test.js && node tests/run-naming.test.js && node tests/electron-portable-naming.test.js && node tests/shared-configuration.test.js && node tests/session-persistence.test.js && node tests/reference-fixtures.test.js && node tests/electron-bridge.test.js && node tests/electron-bundled-runtime.test.js && node tests/wsl-runtime.test.js" + "test:electron": "node tests/log-highlighting.test.js && node tests/action-state.test.js && node tests/electron-missing-data.test.js && node tests/electron-run-data.test.js && node tests/electron-msr-title.test.js && node tests/electron-musrfit-threads.test.js && node tests/electron-t0-prompt-peak.test.js && node tests/window-layering.test.js && node tests/msr-generation.test.js && node tests/root-plot-clean.test.js && node tests/parameter-plot.test.js && node tests/help-window.test.js && node tests/release-packaging.test.js && node tests/ci-publish-packages.test.js && node tests/ci-release.test.js && node tests/ci-runtime-registry.test.js && node tests/runtime-validation.test.js && node tests/local-runtime.test.js && node tests/addrun.test.js && node tests/fit-statistic.test.js && node tests/series-fit-planner.test.js && node tests/series-fit-result.test.js && node tests/series-fit-inventory.test.js && node tests/series-fit-msr-preparation.test.js && node tests/series-artifact-contract.test.js && node tests/series-global-merge.test.js && node tests/series-fit-staging.test.js && node tests/series-fit-runner.test.js && node tests/series-runner-adapters.test.js && node tests/series-fit-routing.test.js && node tests/series-action-chips.test.js && node tests/singlehist-parity.test.js && node tests/url-parameters.test.js && node tests/run-naming.test.js && node tests/electron-portable-naming.test.js && node tests/shared-configuration.test.js && node tests/session-persistence.test.js && node tests/reference-fixtures.test.js && node tests/electron-bridge.test.js && node tests/electron-bundled-runtime.test.js && node tests/wsl-runtime.test.js" }, "repository": { "type": "git", diff --git a/packaging/runtime/runtime-source.json b/packaging/runtime/runtime-source.json new file mode 100644 index 0000000..d83da92 --- /dev/null +++ b/packaging/runtime/runtime-source.json @@ -0,0 +1,6 @@ +{ + "schemaVersion": 1, + "runtimes": { + "linux-x64": null + } +} diff --git a/scripts/ci-publish-packages.js b/scripts/ci-publish-packages.js index a41e954..8cb0e13 100644 --- a/scripts/ci-publish-packages.js +++ b/scripts/ci-publish-packages.js @@ -59,6 +59,20 @@ async function publishPackages(directory, env = process.env, request = fetch) { } } + return publishRegistryFiles(directory, groups, registryVersion, env, request); +} + +// Shared by application releases, durable runtime bundles, and Windows builds. +async function publishRegistryFiles(directory, groups, registryVersion, env = process.env, request = fetch) { + const { GITEA_SERVER_URL, GITEA_REPOSITORY, PACKAGES_TOKEN } = env; + if (!PACKAGES_TOKEN) throw new Error('A package write token is required'); + if (!/^[\w.-]+\/[\w.-]+$/.test(GITEA_REPOSITORY || '')) throw new Error('Expected owner/repository'); + const server = new URL(GITEA_SERVER_URL); + if (server.protocol !== 'https:' || server.username || server.password || server.search || server.hash) { + throw new Error('Gitea must use an HTTPS server URL without credentials, query, or fragment'); + } + const base = server.href.replace(/\/$/, ''); + const [owner, repository] = GITEA_REPOSITORY.split('/').map(encodeURIComponent); const headers = { Authorization: `token ${PACKAGES_TOKEN}` }; for (const [name, names] of Object.entries(groups)) { for (const file of names) { @@ -120,7 +134,7 @@ async function publishPackages(directory, env = process.env, request = fetch) { return registryVersion; } -module.exports = { publishPackages }; +module.exports = { publishPackages, publishRegistryFiles }; if (require.main === module) { publishPackages(process.argv[2] || 'artifacts').catch(error => { diff --git a/scripts/ci-runtime-registry.js b/scripts/ci-runtime-registry.js new file mode 100644 index 0000000..cdf0b7f --- /dev/null +++ b/scripts/ci-runtime-registry.js @@ -0,0 +1,154 @@ +// Copyright (C) 2026 Zaher Salman +// SPDX-License-Identifier: GPL-3.0-or-later + +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const { Transform } = require('stream'); +const { pipeline } = require('stream/promises'); +const { publishRegistryFiles } = require('./ci-publish-packages'); + +function validateDescriptor(descriptor) { + const { runtime, artifact } = descriptor; + if (descriptor.schemaVersion !== 1 || descriptor.kind !== 'musrflow-runtime-download' + || runtime?.platform !== 'linux' || runtime?.arch !== 'x64' + || typeof runtime.runtimeId !== 'string' || !runtime.runtimeId + || !/^[0-9a-f]{40}$/.test(runtime.build?.sourceRevision || '') || runtime.build?.sourceDirty !== false + || typeof runtime.root?.version !== 'string' + || artifact?.format !== 'tar.gz' || artifact.rootDirectory !== 'runtime' + || !/^[A-Za-z0-9][A-Za-z0-9._-]*\.tar\.gz$/.test(artifact.filename || '') + || !/^[0-9a-f]{64}$/.test(artifact.sha256 || '') + || !Number.isSafeInteger(artifact.size) || artifact.size <= 0 || artifact.size > 8 * 1024 ** 3) { + throw new Error('Expected a clean, source-pinned Linux x64 runtime bundle'); + } +} + +function selectRuntime(configFile, env = process.env) { + const config = JSON.parse(fs.readFileSync(configFile, 'utf8')); + if (config.schemaVersion !== 1 || !Object.hasOwn(config.runtimes || {}, 'linux-x64')) throw new Error('Invalid runtime pin configuration'); + const pin = config.runtimes['linux-x64']; + // An explicit manual override wins; the old repository variable is used + // only until the first reviewed registry pin has been committed. + const override = env.RUNTIME_RUN_OVERRIDE || (!pin && env.LEGACY_RUNTIME_RUN_ID); + if (override) { + if (!/^[1-9][0-9]*$/.test(override)) throw new Error('Runtime workflow run ID must be numeric'); + console.log('Using Actions runtime artifact ' + override + '; its retention limit still applies'); + return { source: 'artifact', runId: override }; + } + if (!pin) throw new Error('No approved runtime pin. Run Publish runtime and commit its runtime-source.json, or supply a manual runtime_run_id'); + if (!/^[0-9a-f]{64}$/.test(pin.descriptorSha256 || '') || !/^[0-9a-f]{64}$/.test(pin.archiveSha256 || '')) { + throw new Error('Invalid runtime pin checksums'); + } + console.log('Using pinned runtime: ' + pin.runtimeId); + return { source: 'registry', runId: '', pin }; +} + +async function publishRuntime(directory, env = process.env, request = fetch) { + const descriptors = []; + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + const file = path.join(directory, entry.name); + if (entry.isFile() && entry.name === 'runtime-download.json') descriptors.push(file); + if (entry.isDirectory() && fs.existsSync(path.join(file, 'runtime-download.json'))) descriptors.push(path.join(file, 'runtime-download.json')); + } + if (descriptors.length !== 1) throw new Error('Expected exactly one runtime bundle'); + const descriptorFile = descriptors[0]; + const bytes = fs.readFileSync(descriptorFile); + if (bytes.length > 1024 ** 2) throw new Error('Runtime descriptor is too large'); + const descriptor = JSON.parse(bytes); + validateDescriptor(descriptor); + const { runtime, artifact } = descriptor; + const bundle = path.dirname(descriptorFile); + const archive = path.join(bundle, artifact.filename); + if (!fs.lstatSync(archive).isFile() || fs.statSync(archive).size !== artifact.size) throw new Error('Runtime archive size mismatch'); + const hash = crypto.createHash('sha256'); + for await (const chunk of fs.createReadStream(archive)) hash.update(chunk); + if (hash.digest('hex') !== artifact.sha256) throw new Error('Runtime archive checksum mismatch'); + if (fs.readFileSync(archive + '.sha256', 'utf8').trim() !== `${artifact.sha256} ${artifact.filename}`) throw new Error('Runtime checksum sidecar mismatch'); + // The content hash includes the manifest, source revision, build options, + // base image, architecture, and tool files, not the GUI release version. + const version = `linux-x64-${artifact.sha256}`; + await publishRegistryFiles(bundle, { 'musrflow-runtime-bundle': [artifact.filename, artifact.filename + '.sha256', 'runtime-download.json'] }, version, env, request); + const owner = env.GITEA_REPOSITORY.split('/')[0]; + return { schemaVersion: 1, runtimes: { 'linux-x64': { + descriptorUrl: `${env.GITEA_SERVER_URL.replace(/\/$/, '')}/api/packages/${owner}/generic/musrflow-runtime-bundle/${version}/runtime-download.json`, + descriptorSha256: crypto.createHash('sha256').update(bytes).digest('hex'), + archiveSha256: artifact.sha256, runtimeId: runtime.runtimeId, + sourceRevision: runtime.build.sourceRevision, rootVersion: runtime.root.version + } } }; +} + +async function downloadRuntime(configFile, destination, env = process.env, request = fetch) { + const selected = selectRuntime(configFile, { ...env, RUNTIME_RUN_OVERRIDE: '', LEGACY_RUNTIME_RUN_ID: '' }); + const pin = selected.pin; + const url = new URL(pin.descriptorUrl); + const server = new URL(env.GITEA_SERVER_URL); + const owner = String(env.GITEA_REPOSITORY || '').split('/')[0]; + const expectedPath = `${server.pathname.replace(/\/$/, '')}/api/packages/${owner}/generic/musrflow-runtime-bundle/linux-x64-${pin.archiveSha256}/runtime-download.json`; + if (url.protocol !== 'https:' || url.origin !== server.origin || url.pathname !== expectedPath + || url.username || url.password || url.search || url.hash) throw new Error('Pinned runtime must use this Gitea owner and its content-addressed registry path'); + if (!env.RUNTIME_TOKEN) throw new Error('A package read token is required'); + const output = path.resolve(destination); + if (fs.existsSync(output)) throw new Error('Runtime download destination already exists'); + fs.mkdirSync(path.dirname(output), { recursive: true }); + const stage = fs.mkdtempSync(path.join(path.dirname(output), '.runtime-download-')); + let descriptor; + try { + for (const kind of ['descriptor', 'archive']) { + const filename = kind === 'descriptor' ? 'runtime-download.json' : descriptor.artifact.filename; + const expectedHash = kind === 'descriptor' ? pin.descriptorSha256 : pin.archiveSha256; + const limit = kind === 'descriptor' ? 1024 ** 2 : descriptor.artifact.size; + const target = kind === 'descriptor' ? url : new URL(filename, url); + const response = await request(target.href, { + headers: { Authorization: `token ${env.RUNTIME_TOKEN}` }, redirect: 'error', + signal: AbortSignal.timeout(30 * 60 * 1000) + }); + if (response.status !== 200) throw new Error(`Download runtime ${kind}: HTTP ${response.status}`); + let size = 0; + const hash = crypto.createHash('sha256'); + const verifier = new Transform({ transform(chunk, encoding, callback) { + size += chunk.length; + if (size > limit) return callback(new Error('Runtime download exceeds expected size')); + hash.update(chunk); + callback(null, chunk); + } }); + await pipeline(response.body, verifier, fs.createWriteStream(path.join(stage, filename), { flags: 'wx' })); + if (hash.digest('hex') !== expectedHash || (kind === 'archive' && size !== limit)) throw new Error(`Runtime ${kind} checksum or size mismatch`); + if (kind === 'descriptor') { + descriptor = JSON.parse(fs.readFileSync(path.join(stage, filename), 'utf8')); + validateDescriptor(descriptor); + const runtime = descriptor.runtime; + if (descriptor.artifact.sha256 !== pin.archiveSha256 || runtime.runtimeId !== pin.runtimeId + || runtime.build.sourceRevision !== pin.sourceRevision || runtime.root.version !== pin.rootVersion) { + throw new Error('Runtime identity does not match the committed pin'); + } + } + } + fs.writeFileSync(path.join(stage, descriptor.artifact.filename + '.sha256'), `${pin.archiveSha256} ${descriptor.artifact.filename}\n`); + fs.renameSync(stage, output); + return output; + } finally { + fs.rmSync(stage, { recursive: true, force: true }); + } +} + +module.exports = { selectRuntime, publishRuntime, downloadRuntime }; + +if (require.main === module) { + (async () => { + const [command, source, destination] = process.argv.slice(2); + if (command === 'select') { + if (!process.env.GITHUB_ENV) throw new Error('GITHUB_ENV is required'); + const selected = selectRuntime(source); + fs.appendFileSync(process.env.GITHUB_ENV, `RUNTIME_SOURCE=${selected.source}\nRUNTIME_RUN_ID=${selected.runId}\n`); + } else if (command === 'publish') { + const pin = await publishRuntime(source); + fs.writeFileSync(destination || 'runtime-source.json', JSON.stringify(pin, null, 2) + '\n'); + console.log('Review and commit the generated runtime-source.json as packaging/runtime/runtime-source.json'); + } else if (command === 'download') { + if (!destination) throw new Error('A download destination is required'); + await downloadRuntime(source, destination); + } else { + throw new Error('Usage: ci-runtime-registry.js select | publish | download '); + } + })().catch(error => { console.error(error.message); process.exitCode = 1; }); +} diff --git a/tests/ci-runtime-registry.test.js b/tests/ci-runtime-registry.test.js new file mode 100644 index 0000000..7d4d869 --- /dev/null +++ b/tests/ci-runtime-registry.test.js @@ -0,0 +1,88 @@ +// Copyright (C) 2026 Zaher Salman +// SPDX-License-Identifier: GPL-3.0-or-later + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const crypto = require('crypto'); +const { selectRuntime, publishRuntime, downloadRuntime } = require('../scripts/ci-runtime-registry'); + +async function main() { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'musrflow-registry-runtime-')); + const env = { GITEA_SERVER_URL: 'https://gitea.example.test', GITEA_REPOSITORY: 'owner/muSRFlow', + PACKAGES_TOKEN: 'token', RUNTIME_TOKEN: 'token' }; + const contents = Buffer.from('archive fixture'); + const sha = crypto.createHash('sha256').update(contents).digest('hex'); + const descriptor = { schemaVersion: 1, kind: 'musrflow-runtime-download', + runtime: { platform: 'linux', arch: 'x64', runtimeId: 'test-runtime', root: { version: '6.38.00' }, + build: { sourceRevision: 'a'.repeat(40), sourceDirty: false } }, + artifact: { filename: 'runtime-fixture.tar.gz', sha256: sha, size: contents.length, format: 'tar.gz', rootDirectory: 'runtime' } }; + const stored = new Map(); + let requests = 0; + async function registry(url, options) { + requests++; + assert.strictEqual(options.headers.Authorization, 'token token'); + assert.strictEqual(options.redirect, 'error'); + if (options.method === 'POST') return new Response(null, { status: 201 }); + if (options.method === 'PUT') { + const chunks = []; + for await (const chunk of options.body) chunks.push(chunk); + if (stored.has(url)) return new Response(null, { status: 409 }); + stored.set(url, Buffer.concat(chunks)); + return new Response(null, { status: 201 }); + } + assert(stored.has(url), 'Unknown registry URL: ' + url); + return new Response(stored.get(url)); + } + try { + const bundle = path.join(directory, 'bundle'); + fs.mkdirSync(bundle); + fs.writeFileSync(path.join(bundle, 'runtime-download.json'), JSON.stringify(descriptor)); + fs.writeFileSync(path.join(bundle, descriptor.artifact.filename), contents); + fs.writeFileSync(path.join(bundle, descriptor.artifact.filename + '.sha256'), `${sha} ${descriptor.artifact.filename}\n`); + const pin = await publishRuntime(bundle, env, registry); + assert.strictEqual(stored.size, 3); + assert(pin.runtimes['linux-x64'].descriptorUrl.includes('linux-x64-' + sha)); + assert.deepStrictEqual(await publishRuntime(bundle, env, registry), pin); + const config = path.join(directory, 'runtime-source.json'); + fs.writeFileSync(config, JSON.stringify(pin)); + assert.strictEqual(selectRuntime(config, { LEGACY_RUNTIME_RUN_ID: '123' }).source, 'registry'); + assert.strictEqual(selectRuntime(config, { RUNTIME_RUN_OVERRIDE: '123' }).runId, '123'); + assert.throws(() => selectRuntime(config, { RUNTIME_RUN_OVERRIDE: '../bad' }), /numeric/); + const output = path.join(directory, 'download'); + await downloadRuntime(config, output, env, registry); + assert(fs.readFileSync(path.join(output, descriptor.artifact.filename)).equals(contents)); + await assert.rejects(downloadRuntime(config, output, env, registry), /already exists/); + const failureOutput = path.join(directory, 'failure'); + const goodDescriptor = stored.get(pin.runtimes['linux-x64'].descriptorUrl); + stored.set(pin.runtimes['linux-x64'].descriptorUrl, Buffer.from('{}')); + await assert.rejects(downloadRuntime(config, failureOutput, env, registry), /checksum/); + assert(!fs.existsSync(failureOutput)); + stored.set(pin.runtimes['linux-x64'].descriptorUrl, goodDescriptor); + const archiveUrl = new URL(descriptor.artifact.filename, pin.runtimes['linux-x64'].descriptorUrl).href; + stored.set(archiveUrl, Buffer.from('corrupt')); + await assert.rejects(downloadRuntime(config, failureOutput, env, registry), /checksum or size/); + stored.set(archiveUrl, Buffer.alloc(contents.length + 1)); + await assert.rejects(downloadRuntime(config, failureOutput, env, registry), /exceeds expected size/); + assert(!fs.existsSync(failureOutput)); + await assert.rejects(downloadRuntime(config, failureOutput, env, async () => new Response(null, { status: 401 })), /HTTP 401/); + const altered = structuredClone(pin); + altered.runtimes['linux-x64'].descriptorUrl = 'https://other.example.test/runtime-download.json'; + fs.writeFileSync(config, JSON.stringify(altered)); + const before = requests; + await assert.rejects(downloadRuntime(config, failureOutput, env, registry), /this Gitea owner/); + assert.strictEqual(requests, before, 'never send tokens to a different origin'); + fs.writeFileSync(config, JSON.stringify({ schemaVersion: 1, runtimes: { 'linux-x64': null } })); + assert.throws(() => selectRuntime(config, {}), /No approved runtime pin/); + assert.strictEqual(selectRuntime(config, { LEGACY_RUNTIME_RUN_ID: '123' }).runId, '123'); + fs.writeFileSync(path.join(bundle, descriptor.artifact.filename), Buffer.from('changed')); + await assert.rejects(publishRuntime(bundle, env, registry), /size mismatch/); + assert.strictEqual(requests, before); + console.log('Durable runtime registry and pin tests passed'); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/release-packaging.test.js b/tests/release-packaging.test.js index 0a87bda..b16ec1b 100644 --- a/tests/release-packaging.test.js +++ b/tests/release-packaging.test.js @@ -96,7 +96,11 @@ assert(packageWorkflow.includes('--publish never')); assert(packageWorkflow.indexOf('node scripts/ci-restore-runtime.js') < packageWorkflow.indexOf('npx --yes electron-builder')); assert(packageWorkflow.includes('cp "dist/$file" "dist/$file.md5" "dist/$file.sha256" artifacts/')); assert(!packageWorkflow.includes('|| true')); -assert(packageWorkflow.includes('inputs.runtime_run_id || vars.MUSRFLOW_RUNTIME_RUN_ID')); +assert(packageWorkflow.includes('RUNTIME_RUN_OVERRIDE: ${{ inputs.runtime_run_id }}')); +assert(packageWorkflow.includes('LEGACY_RUNTIME_RUN_ID: ${{ vars.MUSRFLOW_RUNTIME_RUN_ID }}')); +assert(packageWorkflow.includes('node scripts/ci-runtime-registry.js select packaging/runtime/runtime-source.json')); +assert(packageWorkflow.includes('node scripts/ci-runtime-registry.js download packaging/runtime/runtime-source.json runtime-download')); +assert(runtimeWorkflow.includes('node scripts/ci-runtime-registry.js publish dist/runtime-downloads runtime-source.json')); assert(packageWorkflow.includes('run-id: ${{ env.RUNTIME_RUN_ID }}')); assert(packageWorkflow.includes('packages: write')); assert(packageWorkflow.includes('PACKAGE_RUN_ID: ${{ gitea.run_id }}'));