Compare commits

..
34 Commits
Author SHA1 Message Date
noah b610ce3d7f Validate SDK archive contents in Rust before install 2026-10-17 11:13:17 -06:00
noah 1a5dcd17a9 Verify SDK release archives from checksum sidecar 2026-10-17 10:11:15 -06:00
noah 3b1b1fa63e Document running build verification and lock CLI dependency 2026-10-17 10:08:34 -06:00
noah 7880b14e47 Expose running build verification in toolkit CLI 2026-10-17 10:03:34 -06:00
noah 5bbf5b71b7 Verify running board build marker against CI artifact 2026-10-17 10:01:04 -06:00
noah cfec9606a4 Require observed MTD geometry before resolving flash target 2026-10-17 09:02:13 -06:00
noah e8d7cdc77a Parse MTD layouts before board flash planning 2026-10-17 08:02:02 -06:00
noah 8ba585679a Add bounded read-only SSH board probes 2026-10-17 07:02:01 -06:00
noah ea102130ac docs: shorten Toolkit entry guide 2026-10-17 01:42:10 -06:00
noah e656402ec8 Publish Toolkit benchmarks on the standing Alkane runner 2026-10-17 01:21:27 -06:00
noah 80f3c22582 Validate public benchmark page before upload 2026-10-16 08:47:42 -06:00
noah a79ac3e09e Publish Toolkit benchmarks to public Pages site 2026-10-16 07:20:03 -06:00
noah 6580005e77 Bound queued Toolkit CI attempts per branch 2026-10-16 07:08:58 -06:00
noah 2734c8e356 Average benchmark improvements equally in Toolkit badge 2026-10-16 06:02:55 -06:00
noah 0c2897ce37 Require complete Toolkit benchmarks before release 2026-10-16 05:12:21 -06:00
noah fbc903fa6a Benchmark health diagnostics on representative miners 2026-10-15 20:19:36 -06:00
noah fe9617ab56 Guard UTF-8 naming and repair headless screenshots 2026-10-15 20:10:42 -06:00
noah 1e9e4f16b5 Stage verified flash images before device writes 2026-10-15 19:10:45 -06:00
noah 6a6a5e7ded Grade Toolkit code quality from static checks 2026-10-15 19:04:10 -06:00
noah e20b6890d3 Simplify Toolkit docs and update installer status 2026-10-15 14:37:27 -06:00
noah 17bee91248 Clean candidate build after prerelease decision 2026-10-15 12:43:24 -06:00
noah 63d0de8ae3 Clean generated Toolkit builds after CI and local GUI builds 2026-10-15 11:52:21 -06:00
noah 9a8efc807a Parse Rust test harness benchmark output 2026-10-15 04:06:52 -06:00
noah 9879a0eb25 Compare toolkit benchmarks on matching CPU classes 2026-10-15 03:37:30 -06:00
noah 03c19ef7c6 Derive toolkit quality grade from measured coverage 2026-10-15 03:34:41 -06:00
noah 2540801140 Revalidate artifacts and guard complete flash streams 2026-10-14 20:54:42 -06:00
noah dd28fa233c Use Gitea-compatible pinned artifact upload 2026-10-14 20:51:35 -06:00
noah e5ca519df0 Publish measured toolkit badges from main CI 2026-10-14 20:45:03 -06:00
noah 06c8e01eb5 Guard verified artifact writes with recovery checks 2026-10-14 20:40:35 -06:00
noah 990439985d Verify toolkit firmware artifacts before install 2026-10-14 20:31:26 -06:00
noah 54136b71ef Record private toolkit benchmark history 2026-10-14 20:21:38 -06:00
noah 5d18304f0f Standardize toolkit CI badges and scoped release auth 2026-10-14 20:06:48 -06:00
noah 8bbf844bb6 Merge branch 'tooling-standard' into next 2026-10-13 12:10:34 -06:00
noah 97607a0a91 Point next CI badge at next attempts 2026-10-13 11:54:38 -06:00
33 changed files with 867 additions and 972 deletions
+5 -4
View File
@@ -1,9 +1,8 @@
name: public-benchmark-pages
on:
workflow_run:
workflows: [build-test-release]
types: [completed]
schedule:
- cron: '*/15 * * * *'
workflow_dispatch:
concurrency:
@@ -18,7 +17,9 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Install SSH client
run: bash ci/ensure-build-deps.sh ssh
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends openssh-client
- name: Render measured benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
+1 -3
View File
@@ -7,9 +7,7 @@ on:
jobs:
publish:
runs-on: alkane-fast
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
runs-on: alkane-ci
permissions:
actions: read
contents: write
+9 -34
View File
@@ -14,46 +14,27 @@ permissions:
jobs:
candidate:
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_PREFIX: /root/.cache/wx-3.3.3-linux
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check runner image pins
run: python3 ci/check-runner-image.py
- name: Install build dependencies
run: bash ci/ensure-build-deps.sh base
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxWidgets cache key
id: wx-key
run: bash ci/wx-cache-key.sh
- name: Check prebuilt wxWidgets
id: wx-image
run: bash ci/check-wx-image-prefix.sh
- id: wx-cache
if: steps.wx-image.outputs.available != 'true'
uses: actions/cache/restore@v4
continue-on-error: true
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends libssl-dev pkg-config ca-certificates
- uses: actions/cache@v4
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
key: wx-3.3.3-${{ runner.os }}-${{ hashFiles('thirdparty/wx-rs/VERSION') }}
- name: Build wxWidgets
id: wx-build
run: bash ci/ensure-wx-prefix.sh
- name: Save vendored wxWidgets build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
run: |
if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then
bash scripts/build-wx-linux.sh
fi
- name: Build release candidate
run: cargo build --release -p alkane-gui -p alkane-artifacts -p alkane-flash -p alkane-cli --offline
- name: Select candidate version
@@ -70,12 +51,6 @@ jobs:
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/release-rc.py "${{ steps.version.outputs.tag }}" true "dist/alkane-toolkit-${{ steps.version.outputs.version }}-linux-x86_64.tar.gz"
- name: Rust compiler cache statistics
if: always()
run: |
if [ -n "${SCCACHE_DIR:-}" ]; then
sccache --show-stats
fi
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+35 -52
View File
@@ -17,11 +17,8 @@ permissions:
jobs:
release:
runs-on: alkane-ci
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_PREFIX: /root/.cache/wx-3.3.3-linux
# Set once for the whole job so build/clippy/test/bench steps don't each
# re-export it (round 18 #12).
@@ -32,9 +29,6 @@ jobs:
with:
fetch-depth: 0
- name: Check runner image pins
run: python3 ci/check-runner-image.py
- name: Compute version
id: ver
run: bash ci/compute-version.sh | tee -a "$GITHUB_OUTPUT"
@@ -52,45 +46,31 @@ jobs:
run: python3 ci/test-bench-badge.py
- name: Install build dependencies
run: bash ci/ensure-build-deps.sh all
- name: Configure bounded Rust compiler cache
run: bash ci/configure-rust-cache.sh
- name: Compute wxWidgets cache key
id: wx-key
run: bash ci/wx-cache-key.sh
- name: Check prebuilt wxWidgets
id: wx-image
run: bash ci/check-wx-image-prefix.sh
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends \
libssl-dev pkg-config ca-certificates >/dev/null
echo "libssl-dev + pkg-config installed (openssl-sys needs them)"
- name: Cache vendored wxWidgets build
if: steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
uses: actions/cache@v4
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
key: wx-3.3.3-${{ runner.os }}-${{ hashFiles('thirdparty/wx-rs/VERSION') }}
- name: Build wxWidgets (once, then cached)
id: wx-build
run: bash ci/ensure-wx-prefix.sh
- name: Save vendored wxWidgets build
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
run: |
if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then
bash scripts/build-wx-linux.sh
else
echo "wx prefix restored from cache"
fi
- name: Clippy (our crate, warnings are errors)
run: |
rustup component add clippy >/dev/null 2>&1 || true
cargo clippy -p alkane-gui --no-deps --release --bins --offline -- -D warnings
cargo clippy --workspace --exclude alkane-gui --exclude wx-rs --all-targets --offline -- -D warnings
cargo clippy -p alkane-artifacts -p alkane-flash -p alkane-cli --all-targets --offline -- -D warnings
- name: Set crate version to ${{ steps.ver.outputs.version }}
if: steps.ver.outputs.release == 'true'
@@ -106,7 +86,7 @@ jobs:
run: |
set -o pipefail
cargo test -p alkane-gui --offline 2>&1 | tee tests-gui.txt
cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline 2>&1 | tee tests-core.txt
cargo test -p alkane-artifacts -p alkane-flash -p alkane-cli --offline 2>&1 | tee tests-core.txt
cat tests-gui.txt tests-core.txt > tests-current.txt
- name: Load previous main benchmark measurement
@@ -123,8 +103,19 @@ jobs:
python3 ci/bench-badge.py --current bench-current.txt \
--baseline badges/bench-baseline.json --no-write
- name: Record private benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py publish
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: alkane-toolkit-benchmark-site-preview
path: bench-site/index.html
- name: Headless UI self-test
run: |
apt-get update -qq && apt-get install -y -qq --no-install-recommends \
xvfb xauth dbus-x11 fonts-dejavu-core >/dev/null
BIN=target/release/alkane-toolkit
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 "$BIN"
@@ -137,13 +128,6 @@ jobs:
echo "cargo-audit not installed on this runner; skipping"
fi
- name: Rust compiler cache statistics
if: always()
run: |
if [ -n "${SCCACHE_DIR:-}" ]; then
sccache --show-stats
fi
# Merge coverage from unit tests and the headless UI self-test. A failed
# measurement must not publish a stale badge or create a release.
- name: Coverage
@@ -151,7 +135,15 @@ jobs:
run: |
set -euo pipefail
rustup component add llvm-tools-preview >/dev/null 2>&1 || true
[ "$(cargo llvm-cov --version)" = 'cargo-llvm-cov 0.8.7' ]
if ! command -v cargo-llvm-cov >/dev/null 2>&1; then
V=0.8.7
URL="https://github.com/taiki-e/cargo-llvm-cov/releases/download/v${V}/cargo-llvm-cov-x86_64-unknown-linux-gnu.tar.gz"
DEST="${CARGO_HOME:-$HOME/.cargo}/bin"
mkdir -p "$DEST"
curl -fsSL "$URL" | tar -xz -C "$DEST"
export PATH="$DEST:$PATH"
fi
command -v cargo-llvm-cov >/dev/null
PCT=$(bash ci/coverage.sh --summary-only \
| awk '/^TOTAL/{gsub(/%/,"",$10); print $10}')
[ -n "$PCT" ] || { echo "coverage report produced no TOTAL line" >&2; exit 1; }
@@ -188,15 +180,6 @@ jobs:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/publish-metrics.py
- name: Record private benchmark history
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 ci/bench_history.py publish
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7
with:
name: alkane-toolkit-benchmark-site-preview
path: bench-site/index.html
- name: Package artifact
if: steps.ver.outputs.release == 'true'
id: pkg
-27
View File
@@ -1,27 +0,0 @@
name: source
on:
pull_request:
branches: [next]
workflow_dispatch:
concurrency:
group: alkane-toolkit-source-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
runs-on: alkane-fast
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
env:
CARGO_BUILD_JOBS: 2
steps:
- uses: actions/checkout@v4
- name: Check runner image pins
run: python3 ci/check-runner-image.py
- name: Source checks
run: cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+24 -121
View File
@@ -1,157 +1,67 @@
name: verify
# Full quality gate for pull requests to main.
# Pre-merge quality gate: clippy + build + tests + microbenchmarks + the headless
# UI self-test, plus a best-effort dependency audit. Runs on pull requests and on
# pushes to any branch EXCEPT main (main is gated by release.yml, which repeats
# these checks before it cuts a release -- so no work is duplicated on main).
on:
pull_request:
branches: [main]
concurrency:
group: alkane-toolkit-verify-${{ github.ref }}
cancel-in-progress: true
branches-ignore: [next]
push:
branches-ignore: [main, next]
jobs:
verify:
runs-on: alkane-verify
container:
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
runs-on: alkane-ci
env:
CARGO_TARGET_DIR: target
CARGO_BUILD_JOBS: 2
WX_PREFIX: /root/.cache/wx-3.3.3-linux
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Check runner image pins
run: python3 ci/check-runner-image.py
- name: Detect changed surface
id: surface
run: python3 ci/pr-surface.py >> "$GITHUB_OUTPUT"
- name: Check documentation change
if: steps.surface.outputs.surface == 'documentation'
run: |
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
git diff --check "$base" HEAD
if git grep -nIE '^[[:space:]]*-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----[[:space:]]*$' --; then
echo "private key material found in tracked source" >&2
exit 1
else
status=$?
[ "$status" -eq 1 ]
fi
- name: Check CI change surface
if: steps.surface.outputs.surface != 'documentation'
run: python3 ci/test-pr-surface.py
- name: Check workflow-only change
if: steps.surface.outputs.surface == 'workflow'
run: |
python3 - <<'PY'
from pathlib import Path
import yaml
for path in Path('.gitea/workflows').glob('*.yml'):
yaml.load(path.read_text(), Loader=yaml.BaseLoader)
PY
python3 ci/check-runner-image.py
for script in ci/*.sh; do bash -n "$script"; done
base="$(git merge-base HEAD "origin/$GITHUB_BASE_REF")"
git diff --check "$base" HEAD
if git grep -nIE '^[[:space:]]*-----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----[[:space:]]*$' --; then
echo "private key material found in tracked source" >&2
exit 1
else
status=$?
[ "$status" -eq 1 ]
fi
- name: Install build dependencies
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
run: bash ci/ensure-build-deps.sh base
- name: Configure bounded Rust compiler cache
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
run: bash ci/configure-rust-cache.sh
- name: Compute wxWidgets cache key
id: wx-key
if: steps.surface.outputs.surface == 'full'
run: bash ci/wx-cache-key.sh
- name: Check prebuilt wxWidgets
id: wx-image
if: steps.surface.outputs.surface == 'full'
run: bash ci/check-wx-image-prefix.sh
run: |
apt-get update -qq
apt-get install -y -qq --no-install-recommends \
libssl-dev pkg-config ca-certificates >/dev/null
- name: Cache vendored wxWidgets build
if: steps.surface.outputs.surface == 'full' && steps.wx-image.outputs.available != 'true'
id: wx-cache
uses: actions/cache/restore@v4
continue-on-error: true
uses: actions/cache@v4
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
key: wx-3.3.3-${{ runner.os }}-${{ hashFiles('thirdparty/wx-rs/VERSION') }}
- name: Build wxWidgets (once, then cached)
if: steps.surface.outputs.surface == 'full'
id: wx-build
run: bash ci/ensure-wx-prefix.sh
- name: Save vendored wxWidgets build
if: steps.surface.outputs.surface == 'full' && steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
uses: actions/cache/save@v4
continue-on-error: true
with:
path: /root/.cache/wx-3.3.3-linux
key: ${{ steps.wx-key.outputs.key }}
run: |
if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then
bash scripts/build-wx-linux.sh
else
echo "wx prefix restored from cache"
fi
- name: Clippy (our crate, warnings are errors)
if: steps.surface.outputs.surface == 'full'
run: |
rustup component add clippy >/dev/null 2>&1 || true
cargo clippy -p alkane-gui --no-deps --release --bins --offline -- -D warnings
cargo clippy --workspace --exclude alkane-gui --exclude wx-rs --all-targets --offline -- -D warnings
- name: Headless crate checks
if: steps.surface.outputs.surface == 'headless'
env:
PACKAGES: ${{ steps.surface.outputs.packages }}
run: |
rustup component add clippy >/dev/null 2>&1 || true
args=()
for package in $PACKAGES; do
case "$package" in
alkane-access|alkane-artifacts|alkane-cli|alkane-flash) args+=(-p "$package") ;;
*) echo "unrecognized crate: $package" >&2; exit 1 ;;
esac
done
[ "${#args[@]}" -gt 0 ]
cargo clippy "${args[@]}" --all-targets --offline -- -D warnings
cargo test "${args[@]}" --offline
cargo clippy -p alkane-artifacts -p alkane-flash -p alkane-cli --all-targets --offline -- -D warnings
- name: Build
if: steps.surface.outputs.surface == 'full'
run: cargo build --release -p alkane-gui --offline
- name: Unit tests
if: steps.surface.outputs.surface == 'full'
run: |
cargo test -p alkane-gui --offline
cargo test --workspace --exclude alkane-gui --exclude wx-rs --offline
cargo test -p alkane-artifacts -p alkane-flash -p alkane-cli --offline
- name: Microbenchmarks
if: steps.surface.outputs.surface == 'full'
run: cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ --test-threads=1
- name: Headless UI self-test
if: steps.surface.outputs.surface == 'full'
run: |
bash ci/ensure-build-deps.sh ui
apt-get update -qq && apt-get install -y -qq --no-install-recommends \
xvfb xauth dbus-x11 fonts-dejavu-core >/dev/null
BIN=target/release/alkane-toolkit
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 "$BIN"
@@ -160,7 +70,6 @@ jobs:
# runner must not fail the gate on it. Accepted advisories live in
# .cargo/audit.toml.
- name: Dependency audit (best-effort)
if: steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full'
continue-on-error: true
run: |
if command -v cargo-audit >/dev/null 2>&1; then
@@ -168,12 +77,6 @@ jobs:
else
echo "cargo-audit not installed on this runner; skipping"
fi
- name: Rust compiler cache statistics
if: always() && (steps.surface.outputs.surface == 'headless' || steps.surface.outputs.surface == 'full')
run: |
if [ -n "${SCCACHE_DIR:-}" ]; then
sccache --show-stats
fi
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
Generated
+3
View File
@@ -40,7 +40,9 @@ name = "alkane-artifacts"
version = "0.1.0"
dependencies = [
"alkane-core",
"flate2",
"sha2",
"tar",
"thiserror",
]
@@ -48,6 +50,7 @@ dependencies = [
name = "alkane-cli"
version = "0.1.0"
dependencies = [
"alkane-access",
"alkane-artifacts",
"alkane-core",
]
+21 -8
View File
@@ -1,6 +1,6 @@
# Alkane Toolkit
[![CI](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/main.svg)](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
[![CI](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/next.svg)](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
![tests](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/tests.svg)
![coverage](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/coverage.svg)
![bench](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/bench.svg)
@@ -11,8 +11,8 @@
![license](https://gitea.bluefla.re/blueflare/alkane-toolkit/raw/branch/ci-badges/badges/license.svg)
Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through
a patched [wx-rs bridge](thirdparty/wx-rs). In-app image flashing is disabled
while that path is reworked.
a patched [wx-rs bridge](thirdparty/wx-rs). Firmware installation is under
development.
## Run locally
@@ -31,12 +31,10 @@ use the matching `scripts/build-gui-*.sh` script.
- Discover miners by CIDR or IP range with vendored [asic-rs](vendor/asic-rs).
- Show model, firmware, health, hashrate, temperatures, fans, PSU, and workers.
- Filter and sort the desktop table; inspect probes with `miner_probe`.
- Use controls supported by the selected firmware and restore supported
aftermarket firmware to stock.
Discovery is read-only. Control and restore actions change miners. Check the
selected devices before applying them. See the [implementation plan](docs/IMPLEMENTATION-PLAN.md)
and [firmware matrix](docs/aftermarket-parity-roadmap.md) for planned coverage.
Discovery is read-only. The installer and operator actions remain in the
[implementation plan](docs/IMPLEMENTATION-PLAN.md) and
[firmware matrix](docs/aftermarket-parity-roadmap.md).
## Development
@@ -57,6 +55,21 @@ Installation must follow the [SDK install rules](https://gitea.bluefla.re/bluefl
use the exact board's packer and boot-switch procedure, verify through an
independent channel, and never write bootloader or secure regions.
After an Alkane image boots, compare its build marker with the verified
archive from a separate host:
```sh
alkane-cli verify-sdk-release <SHA256SUMS> <downloaded-board-archive>
alkane-cli verify-running-build <ip> <ssh-user> <absolute-known-hosts-file> <board> <sdk-commit> <os-commit>
```
The first command checks the release checksum, inner file list, checksums,
and SDK and OS revisions for a board archive. It prints the revisions to use
in the second command. The QEMU research archive has no board revision
metadata, so only its release checksum is checked. The second command reads
`/etc/alkane-build` over SSH and fails on a mismatch. Neither command installs
firmware or establishes the recovery path.
## License
[MIT](LICENSE). Vendored dependencies keep their own terms.
+9 -9
View File
@@ -1,11 +1,11 @@
{
"bench_parse_line_near_max_addrs": 807160.0,
"bench_parse_targets_many_ranges_near_cap": 54465485.0,
"bench_render_cells": 3503112.0,
"bench_sort_by_each_column": 486975.0,
"bench_targets_to_cidrs_large_range": 482167.0,
"bench_upsert_cold_start_population": 8315814.0,
"bench_view_pipeline": 191794.0,
"bench_view_pipeline_default_sort": 193214.0,
"bench_view_pipeline_with_filter": 253085.0
"bench_parse_line_near_max_addrs": 644187.0,
"bench_parse_targets_many_ranges_near_cap": 49565223.0,
"bench_render_cells": 3037944.0,
"bench_sort_by_each_column": 816884.0,
"bench_targets_to_cidrs_large_range": 443875.0,
"bench_upsert_cold_start_population": 8871040.0,
"bench_view_pipeline": 177652.0,
"bench_view_pipeline_default_sort": 203830.0,
"bench_view_pipeline_with_filter": 187371.0
}
+7 -7
View File
@@ -1,19 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="128.0" height="20" role="img" aria-label="bench coverage: 7%">
<title>bench coverage: 7%</title>
<svg xmlns="http://www.w3.org/2000/svg" width="160.5" height="20" role="img" aria-label="bench coverage: pending">
<title>bench coverage: pending</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="128.0" height="20" rx="3" fill="#fff"/></clipPath>
<clipPath id="r"><rect width="160.5" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="103.0" height="20" fill="#555"/>
<rect x="103.0" width="25.0" height="20" fill="#e05d44"/>
<rect width="128.0" height="20" fill="url(#s)"/>
<rect x="103.0" width="57.5" height="20" fill="#9f9f9f"/>
<rect width="160.5" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="51.5" y="15" fill="#010101" fill-opacity=".3">bench coverage</text>
<text x="51.5" y="14">bench coverage</text>
<text x="115.5" y="15" fill="#010101" fill-opacity=".3">7%</text>
<text x="115.5" y="14">7%</text>
<text x="131.8" y="15" fill="#010101" fill-opacity=".3">pending</text>
<text x="131.8" y="14">pending</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 946 B

After

Width:  |  Height:  |  Size: 966 B

+7 -7
View File
@@ -1,19 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" width="141.0" height="20" role="img" aria-label="bench: +7.4% vs prev">
<title>bench: +7.4% vs prev</title>
<svg xmlns="http://www.w3.org/2000/svg" width="147.5" height="20" role="img" aria-label="bench: -79.9% vs prev">
<title>bench: -79.9% vs prev</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="r"><rect width="141.0" height="20" rx="3" fill="#fff"/></clipPath>
<clipPath id="r"><rect width="147.5" height="20" rx="3" fill="#fff"/></clipPath>
<g clip-path="url(#r)">
<rect width="44.5" height="20" fill="#555"/>
<rect x="44.5" width="96.5" height="20" fill="#dfb317"/>
<rect width="141.0" height="20" fill="url(#s)"/>
<rect x="44.5" width="103.0" height="20" fill="#4c1"/>
<rect width="147.5" height="20" fill="url(#s)"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="22.2" y="15" fill="#010101" fill-opacity=".3">bench</text>
<text x="22.2" y="14">bench</text>
<text x="92.8" y="15" fill="#010101" fill-opacity=".3">+7.4% vs prev</text>
<text x="92.8" y="14">+7.4% vs prev</text>
<text x="96.0" y="15" fill="#010101" fill-opacity=".3">-79.9% vs prev</text>
<text x="96.0" y="14">-79.9% vs prev</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 950 B

After

Width:  |  Height:  |  Size: 952 B

+4 -4
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="141.0" height="20" role="img" aria-label="lines of code: 13.7K">
<title>lines of code: 13.7K</title>
<svg xmlns="http://www.w3.org/2000/svg" width="141.0" height="20" role="img" aria-label="lines of code: 13.7k">
<title>lines of code: 13.7k</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -13,7 +13,7 @@
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text x="48.2" y="15" fill="#010101" fill-opacity=".3">lines of code</text>
<text x="48.2" y="14">lines of code</text>
<text x="118.8" y="15" fill="#010101" fill-opacity=".3">13.7K</text>
<text x="118.8" y="14">13.7K</text>
<text x="118.8" y="15" fill="#010101" fill-opacity=".3">13.7k</text>
<text x="118.8" y="14">13.7k</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 952 B

After

Width:  |  Height:  |  Size: 952 B

+1 -1
View File
@@ -14,7 +14,7 @@ _DUR = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*(ns|\u00b5s|us|ms|s)(?![a-zA-Z])")
_UNIT_NS = {"ns": 1.0, "us": 1e3, "\u00b5s": 1e3, "ms": 1e6, "s": 1e9}
_NAME = re.compile(r"^(?:test [A-Za-z0-9_:]+ \.\.\. )?(bench_[A-Za-z0-9_]+)\s*:")
EXPECTED_BENCHES = {
"bench_verify_artifact", "bench_naming_transforms",
"bench_naming_transforms",
"bench_parse_line_near_max_addrs", "bench_parse_targets_many_ranges_near_cap",
"bench_targets_to_cidrs_large_range", "bench_view_pipeline",
"bench_render_cells", "bench_health_diagnostics",
+9 -70
View File
@@ -15,7 +15,6 @@ import subprocess
import importlib.util
from urllib.error import HTTPError
from urllib.parse import quote
import yaml
from badge_store import BADGE_BRANCH, publish_file, request_json
from bench_host import identity as benchmark_host
@@ -27,12 +26,6 @@ bench_spec.loader.exec_module(bench_badge)
INDEX = "history/index.json"
MAX_INDEX_ENTRIES = 50
BENCH_INPUT_PATHS = (
"Cargo.toml", "Cargo.lock", ".cargo", "crates", "thirdparty", "vendor",
"rust-toolchain.toml", "ci/bench-badge.py", "ci/bench_host.py",
"ci/ensure-build-deps.sh", "ci/ensure-wx-prefix.sh",
"ci/configure-rust-cache.sh", "ci/wx-cache-key.sh",
)
def read_artifact(api: str, repo: str, token: str, filename: str):
@@ -58,8 +51,6 @@ def valid_benches(metrics: dict) -> dict[str, float]:
def git_distance(ancestor: str, sha: str) -> int | None:
if not re.fullmatch(r"[0-9a-f]{40}", ancestor) or not re.fullmatch(r"[0-9a-f]{40}", sha):
return None
result = subprocess.run(("git", "rev-list", "--count", f"{ancestor}..{sha}"),
capture_output=True, text=True, check=False)
if result.returncode != 0:
@@ -69,7 +60,7 @@ def git_distance(ancestor: str, sha: str) -> int | None:
return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None
def previous_entry(index: dict, sha: str, distance=None, host=None) -> dict | None:
def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
distance = distance or git_distance
choices = []
for entry in index.get("entries", []):
@@ -82,41 +73,8 @@ def previous_entry(index: dict, sha: str, distance=None, host=None) -> dict | No
if gap is not None and gap > 0:
choices.append((gap, entry))
if not choices:
return None
return min(choices, key=lambda item: item[0])[1]
def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
entry = previous_entry(index, sha, distance, host)
return valid_benches(entry["metrics"]) if entry else {}
def benchmark_build_settings(sha: str, root: Path | str = ".") -> dict:
source = subprocess.check_output(
("git", "show", f"{sha}:.gitea/workflows/release.yml"),
cwd=root, text=True)
job = yaml.load(source, Loader=yaml.BaseLoader)["jobs"]["release"]
commands = {step.get("name", ""): step.get("run") for step in job["steps"]}
selected = ("Install build dependencies", "Configure bounded Rust compiler cache",
"Build wxWidgets (once, then cached)", "Build release", "Microbenchmarks")
return {"image": job["container"]["image"], "env": job.get("env", {}),
"commands": {name: commands.get(name) for name in selected}}
def same_benchmark_inputs(ancestor: str, sha: str, root: Path | str = ".") -> bool:
"""Identify changes that only reroute CI without changing benchmark inputs."""
if not re.fullmatch(r"[0-9a-f]{40}", ancestor) or not re.fullmatch(r"[0-9a-f]{40}", sha):
raise ValueError("invalid benchmark comparison commit")
diff = subprocess.run(("git", "diff", "--quiet", ancestor, sha, "--",
*BENCH_INPUT_PATHS), cwd=root, check=False)
if diff.returncode not in (0, 1):
raise ValueError("cannot inspect benchmark input changes")
if diff.returncode == 1:
return False
try:
return benchmark_build_settings(ancestor, root) == benchmark_build_settings(sha, root)
except (KeyError, TypeError, subprocess.CalledProcessError, yaml.YAMLError):
return False
return {}
return valid_benches(min(choices, key=lambda item: item[0])[1]["metrics"])
def updated_index(index: dict, sha: str, metrics: dict, timestamp: str) -> dict:
@@ -143,12 +101,6 @@ def render_html(index: dict) -> str:
host = entry["metrics"].get("bench_host", {})
host_label = host.get("cpu_model", "unknown") if isinstance(host, dict) else "unknown"
cells.append(f'<td>{html.escape(str(host_label))}</td>')
context = entry["metrics"].get("bench_context", {})
if isinstance(context, dict) and context.get("schema") == 1:
context_label = "same inputs" if context.get("same_inputs") else "changed inputs"
else:
context_label = "unclassified"
cells.append(f'<td>{context_label}</td>')
cells += [f'<td>{values[name]:.3f}</td>' if name in values else '<td>new</td>'
for name in names]
rows.append("<tr>" + "".join(cells) + "</tr>")
@@ -163,14 +115,12 @@ def render_html(index: dict) -> str:
"th{background:#edf2f6;position:sticky;top:0}a{color:#145a9a}"
".scroll{overflow-x:auto}small{color:#55616d}</style></head><body>"
"<h1>Alkane Toolkit microbenchmarks</h1>"
"<p>Measured on main CI. Lower ns/op is faster. Runner load affects results. "
"Same inputs marks a repeat of the benchmark source and build settings. "
"A new benchmark has no earlier comparison.</p>"
"<p>Measured on main CI. Lower ns/op is faster. Results depend on runner load and are "
"not board performance. A new benchmark has no earlier comparison.</p>"
f"<p><small>Most recent {len(entries)} measured commits. Full per-commit JSON is retained "
"in the private ci-badges branch.</small></p>"
f"<div class=\"scroll\"><table><thead><tr><th scope=\"col\">Commit</th>"
f"<th scope=\"col\">UTC</th><th scope=\"col\">CPU</th>"
f"<th scope=\"col\">Inputs</th>{headings}</tr></thead><tbody>{''.join(rows)}"
f"<th scope=\"col\">UTC</th><th scope=\"col\">CPU</th>{headings}</tr></thead><tbody>{''.join(rows)}"
"</tbody></table></div></body></html>\n")
@@ -186,16 +136,10 @@ def main() -> None:
if index.get("schema") != 1 or not isinstance(index.get("entries"), list):
raise ValueError("unsupported benchmark history index")
if args.action == "prepare":
entry = previous_entry(index, sha, host=benchmark_host())
baseline = valid_benches(entry["metrics"]) if entry else {}
same_inputs = same_benchmark_inputs(entry["sha"], sha) if entry else False
baseline = previous_measurement(index, sha, host=benchmark_host())
Path("badges").mkdir(exist_ok=True)
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
Path("badges/bench-context.json").write_text(
json.dumps({"schema": 1, "same_inputs": same_inputs,
"baseline_sha": entry["sha"] if entry else None}) + "\n")
print(f"Loaded {len(baseline)} prior benchmark measurements; "
f"same inputs: {str(same_inputs).lower()}")
print(f"Loaded {len(baseline)} prior benchmark measurements")
return
if args.action == "render":
if not index["entries"]:
@@ -204,13 +148,8 @@ def main() -> None:
Path("bench-site/index.html").write_text(render_html(index))
print(f"Rendered {len(index['entries'])} measured benchmark commits")
return
context = json.loads(Path("badges/bench-context.json").read_text())
if (not isinstance(context, dict) or context.get("schema") != 1 or
not isinstance(context.get("same_inputs"), bool)):
raise ValueError("invalid benchmark comparison context")
metrics = {"bench_ns_per_op": bench_badge.require_suite(bench_badge.parse_bench(
Path("bench-current.txt").read_text())), "bench_host": benchmark_host(),
"bench_context": context}
Path("bench-current.txt").read_text())), "bench_host": benchmark_host()}
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
index = updated_index(index, sha, metrics, timestamp)
record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n"
-64
View File
@@ -1,64 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Keep Toolkit CI on the verified Alkane runner image."""
from pathlib import Path
import re
import sys
import yaml
ROOT = Path(__file__).resolve().parents[1]
IMAGE = (ROOT / "ci/runner-image.txt").read_text().strip()
def main() -> int:
if not re.fullmatch(
r"gitea\.bluefla\.re/blueflare/alkane-ci@sha256:[0-9a-f]{64}", IMAGE
):
print("Runner image must be pinned by Gitea registry digest", file=sys.stderr)
return 1
for path in sorted((ROOT / ".gitea/workflows").glob("*.yml")):
workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader)
for name, job in workflow.get("jobs", {}).items():
if job.get("runs-on") not in {"alkane-ci", "alkane-fast", "alkane-verify"}:
continue
if job.get("container", {}).get("image") != IMAGE:
print(f"{path.name}: {name} has a different runner image", file=sys.stderr)
return 1
pages = yaml.load(
(ROOT / ".gitea/workflows/bench-pages.yml").read_text(),
Loader=yaml.BaseLoader,
)
if (pages["on"]["workflow_run"]["workflows"] != ["build-test-release"]
or pages["jobs"]["publish"].get("runs-on") != "alkane-pages"):
print("Benchmark Pages must follow main CI on the Pages runner", file=sys.stderr)
return 1
release = yaml.load(
(ROOT / ".gitea/workflows/release.yml").read_text(),
Loader=yaml.BaseLoader,
)
if release["jobs"]["release"].get("runs-on") != "alkane-ci":
print("Main release must use the dedicated Alkane build pool", file=sys.stderr)
return 1
if any("ci/publish-bench-pages.py" in step.get("run", "")
for step in release["jobs"]["release"]["steps"]):
print("Main release must not publish Pages from GARM", file=sys.stderr)
return 1
source = yaml.load(
(ROOT / ".gitea/workflows/source.yml").read_text(),
Loader=yaml.BaseLoader,
)
triggers = source["on"]
if (triggers.get("pull_request", {}).get("branches") != ["next"]
or "push" in triggers or "workflow_dispatch" not in triggers):
print("Source checks must not duplicate main pull request verification",
file=sys.stderr)
return 1
print("Toolkit runner image pins: PASS")
return 0
if __name__ == "__main__":
raise SystemExit(main())
-16
View File
@@ -1,16 +0,0 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Avoid a runner-local cache download when the pinned image has this source.
set -euo pipefail
prefix="${WX_PREFIX:?WX_PREFIX is required}"
expected="$(awk '$1 == "sha256:" {print $2}' thirdparty/wxwidgets/VERSION)"
[[ "$expected" =~ ^[0-9a-f]{64}$ ]]
available=false
if [ ! -L "$prefix" ] && [ ! -L "$prefix/.alkane-source-sha256" ] &&
[ -x "$prefix/bin/wx-config" ] &&
[ -s "$prefix/lib/libwx_gtk3u-3.3.a" ] &&
[ "$(cat "$prefix/.alkane-source-sha256" 2>/dev/null || true)" = "$expected" ]; then
available=true
fi
printf 'available=%s\n' "$available" >> "${GITHUB_OUTPUT:?GITHUB_OUTPUT is required}"
-11
View File
@@ -11,7 +11,6 @@ import sys
ROOT = Path(__file__).resolve().parents[1]
DIRECTORIES = ("target", "dist", "coverage", "bench-site")
FILES = ("bench-current.txt",)
BADGE_FILES = ("bench-baseline.json", "bench-context.json")
def cleanup() -> None:
@@ -33,16 +32,6 @@ def cleanup() -> None:
if path.is_file():
path.unlink()
print(f"Removed generated file: {name}")
badge_dir = ROOT / "badges"
if badge_dir.is_symlink():
raise ValueError("unsafe generated badge directory")
for name in BADGE_FILES:
path = badge_dir / name
if path.is_symlink() or path.parent.resolve() != badge_dir.resolve():
raise ValueError(f"unsafe generated badge file: {path}")
if path.is_file():
path.unlink()
print(f"Removed generated badge file: {name}")
if __name__ == "__main__":
-37
View File
@@ -1,37 +0,0 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Reuse Rust compiler results on persistent CI runners.
set -euo pipefail
[ "$(sccache --version)" = 'sccache 0.18.0' ] || {
echo 'CI image has an unexpected sccache version' >&2
exit 1
}
toolcache="${RUNNER_TOOL_CACHE:-}"
if [ -z "$toolcache" ] || [ -L "$toolcache" ] ||
[ ! -d "$toolcache" ] || [ ! -w "$toolcache" ]; then
echo 'Persistent runner tool cache is unavailable; compiling without sccache'
exit 0
fi
cache_dir="$toolcache/alkane-toolkit-rust-sccache"
if [ -L "$cache_dir" ]; then
echo 'Rust cache path is a symlink' >&2
exit 1
fi
umask 077
mkdir -p "$cache_dir"
if [ ! -d "$cache_dir" ] || [ ! -w "$cache_dir" ]; then
echo 'Rust cache directory is unavailable' >&2
exit 1
fi
chmod 0700 "$cache_dir"
{
printf 'RUSTC_WRAPPER=%s\n' "$(command -v sccache)"
printf 'SCCACHE_DIR=%s\n' "$cache_dir"
printf 'SCCACHE_CACHE_SIZE=2G\n'
printf 'CARGO_INCREMENTAL=0\n'
} >> "${GITHUB_ENV:?GITHUB_ENV is required}"
echo 'Bounded Rust compiler cache configured for Alkane Toolkit'
+2 -2
View File
@@ -26,10 +26,10 @@ fi
cargo llvm-cov clean --workspace
# 1. Unit tests for the GUI and all first-party headless crates.
# 1. Unit tests for the GUI and the artifact/flash/CLI crates.
cargo llvm-cov --no-report "${CARGO_FLAGS[@]}" -p alkane-gui --bin alkane-toolkit
cargo llvm-cov --no-report "${CARGO_FLAGS[@]}" \
--workspace --exclude alkane-gui --exclude wx-rs
-p alkane-artifacts -p alkane-flash -p alkane-cli
# 2. Headless UI self-test, under the same instrumentation, its coverage appended.
xvfb-run -a env GDK_BACKEND=x11 ALKANE_SELFTEST=1 \
-29
View File
@@ -1,29 +0,0 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Use the preinstalled CI image or install missing packages on older runners.
set -euo pipefail
mode="${1:?usage: ensure-build-deps.sh base|ui|all|ssh}"
case "$mode" in
base) packages=(libssl-dev pkg-config ca-certificates) ;;
ui) packages=(xvfb xauth dbus-x11 fonts-dejavu-core) ;;
ssh) packages=(openssh-client) ;;
all) packages=(libssl-dev pkg-config ca-certificates openssh-client
xvfb xauth dbus-x11 fonts-dejavu-core) ;;
*) echo "unknown dependency set: $mode" >&2; exit 2 ;;
esac
installed="$(dpkg-query -W -f='${Package} ${Status}\n' "${packages[@]}" 2>/dev/null || true)"
missing=()
for package in "${packages[@]}"; do
if ! grep -Fxq "$package install ok installed" <<< "$installed"; then
missing+=("$package")
fi
done
if [ "${#missing[@]}" -eq 0 ]; then
printf 'Build packages already installed: %s\n' "$mode"
exit 0
fi
printf 'Installing %s missing build packages\n' "${#missing[@]}"
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends "${packages[@]}"
-43
View File
@@ -1,43 +0,0 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Use the matching image or cache prefix; rebuild after a vendored source bump.
set -euo pipefail
prefix="${WX_PREFIX:?WX_PREFIX is required}"
if [ -L "$prefix" ] || [ -L "$prefix/.alkane-source-sha256" ]; then
echo 'refusing symlinked wxWidgets prefix or source marker' >&2
exit 1
fi
expected="$(awk '$1 == "sha256:" {print $2}' thirdparty/wxwidgets/VERSION)"
[[ "$expected" =~ ^[0-9a-f]{64}$ ]] || {
echo 'invalid pinned wxWidgets source digest' >&2
exit 1
}
marker="$prefix/.alkane-source-sha256"
if [ -e "$marker" ] && [ "$(cat "$marker")" != "$expected" ]; then
python3 - "$prefix" <<'PY'
from pathlib import Path
import shutil
import sys
prefix = Path(sys.argv[1])
allowed = Path('/root/.cache/wx-3.3.3-linux')
if prefix != allowed or prefix.is_symlink():
raise SystemExit('refusing unsafe wxWidgets prefix reset')
if prefix.is_dir():
shutil.rmtree(prefix)
PY
fi
built=false
if [ ! -x "$prefix/bin/wx-config" ] ||
[ ! -s "$prefix/lib/libwx_gtk3u-3.3.a" ]; then
bash scripts/build-wx-linux.sh
built=true
else
echo 'wx prefix available from matching image or cache'
fi
[ -s "$prefix/lib/libwx_gtk3u-3.3.a" ]
printf '%s\n' "$expected" > "$marker"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
printf 'built=%s\n' "$built" >> "$GITHUB_OUTPUT"
fi
+2 -15
View File
@@ -11,10 +11,8 @@ Metrics not passed on the command line are computed here (LOC from the source
tree, dependency count from Cargo.lock, license from Cargo.toml).
"""
import argparse
import json
import math
import os
from pathlib import Path
import re
import sys
@@ -198,14 +196,6 @@ def main() -> int:
write("bench-coverage", "bench coverage",
f"{args.bench_coverage:.0f}%" if args.bench_coverage is not None else "pending",
cov_color(args.bench_coverage) if args.bench_coverage is not None else "lightgrey")
context_path = Path(args.root) / args.out / "bench-context.json"
same_inputs = False
if context_path.is_file():
context = json.loads(context_path.read_text())
if (not isinstance(context, dict) or context.get("schema") != 1 or
not isinstance(context.get("same_inputs"), bool)):
raise ValueError("invalid benchmark comparison context")
same_inputs = context["same_inputs"]
# Bench badge: prefer the mean per-benchmark improvement vs the previous
# release. Use the static label when no comparison is available.
delta = None
@@ -216,11 +206,8 @@ def main() -> int:
delta = None
if delta is not None:
# Positive = faster than the previous release.
msg = f"{'+' if delta > 0 else ''}{delta:.1f}%"
if same_inputs:
write("bench", "bench", msg + " same inputs", "lightgrey")
else:
write("bench", "bench", msg + " vs prev", bench_color(delta))
msg = f"{'+' if delta > 0 else ''}{delta:.1f}% vs prev"
write("bench", "bench", msg, bench_color(delta))
elif args.bench_delta == "NEW":
write("bench", "bench", "baseline set", "blue")
elif args.bench is not None:
-122
View File
@@ -1,122 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Classify a pull request for scoped CI checks."""
import os
from pathlib import Path
import subprocess
import sys
import tomllib
ROOT = Path(__file__).resolve().parents[1]
DOC_FILES = {"README.md", "CONTRIBUTING.md", "CHANGELOG.md"}
HEADLESS_CRATES = {"alkane-access", "alkane-artifacts", "alkane-cli", "alkane-flash"}
def documentation_only(paths: list[str]) -> bool:
return bool(paths) and all(
path in DOC_FILES or
(path.startswith("docs/") and Path(path).suffix in {".md", ".txt"})
for path in paths
)
def workflow_only(paths: list[str]) -> bool:
"""Limit the cheap PR check to workflow YAML, never policy code."""
return bool(paths) and all(
path.startswith(".gitea/workflows/") and
len(Path(path).parts) == 3 and Path(path).suffix == ".yml"
for path in paths
)
def headless_packages(paths: list[str]) -> list[str]:
"""Return tested reverse dependents for code outside the GUI graph."""
changed: set[str] = set()
if not paths:
return []
for path in paths:
parts = Path(path).parts
if (len(parts) < 4 or parts[0] != "crates" or
parts[1] not in HEADLESS_CRATES or
parts[2] not in {"src", "tests"} or
Path(path).suffix != ".rs"):
return []
changed.add(parts[1])
try:
manifests = {}
for path in (ROOT / "crates").glob("*/Cargo.toml"):
manifest = tomllib.loads(path.read_text())
name = manifest["package"]["name"]
if name != path.parent.name:
return []
manifests[name] = manifest
if not changed <= manifests.keys() or "alkane-gui" not in manifests:
return []
def dependencies(value: object) -> set[str]:
found: set[str] = set()
if isinstance(value, dict):
for key, nested in value.items():
if key in {"dependencies", "dev-dependencies", "build-dependencies"}:
for dep_name, spec in nested.items():
found.add(spec.get("package", dep_name) if isinstance(spec, dict)
else dep_name)
else:
found.update(dependencies(nested))
return found & manifests.keys()
graph = {name: dependencies(manifest) for name, manifest in manifests.items()}
affected = changed.copy()
while True:
added = {name for name, deps in graph.items() if deps & affected} - affected
if not added:
break
affected.update(added)
return [] if "alkane-gui" in affected else sorted(affected)
except (OSError, KeyError, TypeError, ValueError):
return []
def changed_paths() -> list[str]:
if os.environ.get("GITHUB_EVENT_NAME") != "pull_request":
raise ValueError("not a pull request")
if os.environ.get("GITHUB_BASE_REF") != "main":
raise ValueError("unknown base branch")
merge_base = subprocess.check_output(
["git", "-C", str(ROOT), "merge-base", "HEAD",
"refs/remotes/origin/main"],
stderr=subprocess.DEVNULL, text=True,
).strip()
if len(merge_base) != 40:
raise ValueError("missing merge base")
raw = subprocess.check_output(
["git", "-C", str(ROOT), "diff", "--no-renames", "--name-only", "-z",
merge_base, "HEAD"], stderr=subprocess.DEVNULL,
)
return [path.decode("utf-8", "surrogateescape")
for path in raw.split(b"\0") if path]
def main() -> None:
try:
paths = changed_paths()
docs = documentation_only(paths)
workflow = workflow_only(paths) if not docs else False
packages = headless_packages(paths) if not docs and not workflow else []
except (OSError, subprocess.CalledProcessError, ValueError):
paths = []
docs = False
workflow = False
packages = []
surface = ("documentation" if docs else "workflow" if workflow else
"headless" if packages else "full")
print(f"surface={surface}")
print(f"packages={' '.join(packages)}")
print(f"Changed paths: {len(paths)}", file=sys.stderr)
if __name__ == "__main__":
main()
-1
View File
@@ -1 +0,0 @@
gitea.bluefla.re/blueflare/alkane-ci@sha256:9d2a992bbcb91014af3c85d2e1ec8c5990701cecf83fd06c8d46f9ef13dbd948
+1 -1
View File
@@ -33,7 +33,7 @@ class BenchBadgeTests(unittest.TestCase):
lines = [f"test tests::{name} ... {name}: 10ms/op"
for name in sorted(badge.EXPECTED_BENCHES)]
values = badge.require_suite(badge.parse_bench("\n".join(lines)))
self.assertEqual(len(values), 12)
self.assertEqual(len(values), len(badge.EXPECTED_BENCHES))
with self.assertRaisesRegex(ValueError, "declared suite"):
badge.require_suite(badge.parse_bench("\n".join(lines[:-1])))
with self.assertRaisesRegex(ValueError, "duplicate"):
+2 -62
View File
@@ -3,15 +3,11 @@
"""Exercise benchmark history selection and safe site rendering."""
import sys
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
from bench_history import (bench_badge, git_distance, previous_measurement, render_html,
same_benchmark_inputs, updated_index)
from bench_history import bench_badge, previous_measurement, render_html, updated_index
class HistoryTests(unittest.TestCase):
@@ -45,7 +41,6 @@ class HistoryTests(unittest.TestCase):
self.assertEqual(updated["entries"][-1]["metrics"]["bench_ns_per_op"]["hash"], 7.5)
def test_invalid_measurement_and_sha_rejected(self):
self.assertIsNone(git_distance("--bad", "a" * 40))
with self.assertRaises(ValueError):
updated_index({}, "bad", {"bench_ns_per_op": {"hash": 1}}, "now")
with self.assertRaises(ValueError):
@@ -61,69 +56,14 @@ class HistoryTests(unittest.TestCase):
{"hash": 10.0})
self.assertEqual(previous_measurement(index, "b" * 40, distance, other), {})
def test_routing_change_is_marked_same_inputs_but_code_or_build_change_is_not(self):
with tempfile.TemporaryDirectory(prefix="alkane-bench-inputs-") as directory:
root = Path(directory)
workflow = root / ".gitea/workflows/release.yml"
workflow.parent.mkdir(parents=True)
code = root / "crates/alkane-gui/src/main.rs"
code.parent.mkdir(parents=True)
code.write_text("fn main() {}\n")
workflow.write_text(
"jobs:\n release:\n runs-on: alkane-verify\n"
" container:\n image: pinned-image\n"
" env:\n RUSTFLAGS: stable\n steps:\n"
" - name: Build release\n run: cargo build --release\n"
" - name: Microbenchmarks\n run: cargo test --release bench_\n")
def git(*args):
return subprocess.check_output(("git", "-C", str(root), *args),
text=True, stderr=subprocess.DEVNULL).strip()
git("init", "-q")
git("config", "user.name", "CI Test")
git("config", "user.email", "ci@example.invalid")
git("add", ".")
git("commit", "-qm", "base")
base = git("rev-parse", "HEAD")
workflow.write_text(workflow.read_text().replace("alkane-verify", "alkane-ci"))
git("commit", "-qam", "route")
route = git("rev-parse", "HEAD")
self.assertTrue(same_benchmark_inputs(base, route, root))
code.write_text("fn main() { println!(\"changed\"); }\n")
git("commit", "-qam", "code")
changed_code = git("rev-parse", "HEAD")
self.assertFalse(same_benchmark_inputs(route, changed_code, root))
workflow.write_text(workflow.read_text().replace("RUSTFLAGS: stable", "RUSTFLAGS: tuned"))
git("commit", "-qam", "flags")
flags = git("rev-parse", "HEAD")
self.assertFalse(same_benchmark_inputs(changed_code, flags, root))
def test_badge_keeps_raw_delta_and_marks_identical_inputs(self):
with tempfile.TemporaryDirectory(prefix="alkane-bench-badge-context-") as directory:
root = Path(directory)
badges = root / "badges"
badges.mkdir()
(badges / "bench-context.json").write_text(
json.dumps({"schema": 1, "same_inputs": True, "baseline_sha": "a" * 40}))
command = (sys.executable, str(Path(__file__).with_name("gen-badges.py")),
"--root", str(root), "--bench-delta=-36.4")
subprocess.run(command, check=True, capture_output=True)
self.assertIn("-36.4% same inputs", (badges / "bench.svg").read_text())
(badges / "bench-context.json").unlink()
subprocess.run(command, check=True, capture_output=True)
self.assertIn("-36.4% vs prev", (badges / "bench.svg").read_text())
def test_site_escapes_history_content(self):
entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>",
"metrics": {"bench_ns_per_op": {"hash": 10.0},
"bench_host": {"cpu_model": "<script>cpu</script>"},
"bench_context": {"schema": 1, "same_inputs": True}}}
"bench_host": {"cpu_model": "<script>cpu</script>"}}}
page = render_html({"entries": [entry]})
self.assertIn("&lt;script&gt;", page)
self.assertNotIn("<script>", page)
self.assertIn("10.000", page)
self.assertIn("same inputs", page)
if __name__ == "__main__":
-193
View File
@@ -1,193 +0,0 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Check that unknown changes cannot take a scoped CI path."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import importlib.util
import yaml
SCRIPT = Path(__file__).with_name("pr-surface.py")
ROOT = SCRIPT.parents[1]
spec = importlib.util.spec_from_file_location("pr_surface", SCRIPT)
assert spec and spec.loader
pr_surface = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pr_surface)
def git(directory: Path, *args: str) -> str:
return subprocess.check_output(
["git", "-C", str(directory), *args], text=True,
stderr=subprocess.DEVNULL,
).strip()
def check_workflow_contract() -> None:
"""Keep the short workflow check from silently dropping release gates."""
required = {
"release.yml": ("main", "release", (
"Check runner image pins", "Clippy (our crate, warnings are errors)",
"Build release", "Unit tests", "Microbenchmarks",
"Headless UI self-test", "Coverage", "Microbenchmark coverage",
"Generate measured badges", "Publish measured badges",
"Record private benchmark history", "Create Gitea release + upload artifact",
"Clean generated Toolkit build",
)),
"next.yml": ("next", "candidate", (
"Check runner image pins", "Build release candidate",
"Create private prerelease", "Clean generated Toolkit build",
)),
"verify.yml": ("main", "verify", (
"Check runner image pins", "Detect changed surface",
"Check CI change surface", "Check workflow-only change",
"Clippy (our crate, warnings are errors)", "Build", "Unit tests",
"Microbenchmarks", "Headless UI self-test", "Clean generated Toolkit build",
)),
}
for filename, (branch, job_name, gates) in required.items():
path = ROOT / ".gitea/workflows" / filename
workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader)
event = "pull_request" if filename == "verify.yml" else "push"
assert workflow["on"][event]["branches"] == [branch], path
job = workflow["jobs"][job_name]
assert job["runs-on"] in {"alkane-ci", "alkane-verify"}, path
steps = job["steps"]
names = [step.get("name") for step in steps]
positions = [names.index(gate) for gate in gates]
assert positions == sorted(positions), path
assert steps[positions[-1]].get("if") == "always()", path
for gate, position in zip(gates[:-1], positions[:-1]):
condition = steps[position].get("if")
if gate in {"Create Gitea release + upload artifact",
"Create private prerelease"}:
assert condition is not None and "release == 'true'" in condition, path
elif filename == "verify.yml" and gate in {
"Build", "Unit tests", "Microbenchmarks",
"Clippy (our crate, warnings are errors)",
"Headless UI self-test"}:
assert condition == "steps.surface.outputs.surface == 'full'", path
elif filename == "verify.yml" and gate == "Check CI change surface":
assert condition == "steps.surface.outputs.surface != 'documentation'", path
elif filename == "verify.yml" and gate == "Check workflow-only change":
assert condition == "steps.surface.outputs.surface == 'workflow'", path
else:
assert condition is None, path
def main() -> None:
check_workflow_contract()
with tempfile.TemporaryDirectory(prefix="alkane-toolkit-workflow-policy-") as directory:
global ROOT
saved_root = ROOT
ROOT = Path(directory)
(ROOT / ".gitea/workflows").mkdir(parents=True)
for filename in ("release.yml", "next.yml", "verify.yml"):
shutil.copyfile(saved_root / ".gitea/workflows" / filename,
ROOT / ".gitea/workflows" / filename)
release = ROOT / ".gitea/workflows/release.yml"
original = release.read_text()
release.write_text(original.replace("- name: Coverage", "- name: Skipped coverage", 1))
try:
check_workflow_contract()
except ValueError:
pass
else:
raise AssertionError("removing the coverage gate passed workflow policy")
ROOT = saved_root
assert pr_surface.documentation_only(["README.md", "docs/setup.md"])
assert pr_surface.workflow_only([".gitea/workflows/release.yml"])
for paths in ([], ["ci/pr-surface.py"], ["ci/coverage.sh"],
["ci/check-runner-image.py"],
[".gitea/workflows/release.yml", "ci/check-runner-image.py"],
[".gitea/workflows/release.yml", "crates/alkane-gui/src/main.rs"],
[".gitea/workflows/../release.yml"]):
assert not pr_surface.workflow_only(paths), paths
for paths in ([], ["docs/generated.json"], ["src/main.rs"],
["README.md", "ci/pr-surface.py"]):
assert not pr_surface.documentation_only(paths), paths
assert pr_surface.headless_packages(["crates/alkane-cli/src/main.rs"]) == ["alkane-cli"]
assert pr_surface.headless_packages(["crates/alkane-artifacts/src/lib.rs"]) == [
"alkane-artifacts", "alkane-cli", "alkane-flash",
]
assert pr_surface.headless_packages([
"crates/alkane-access/src/lib.rs", "crates/alkane-flash/tests/update.rs",
]) == ["alkane-access", "alkane-flash"]
for paths in ([], ["crates/alkane-core/src/lib.rs"],
["crates/alkane-discovery/src/lib.rs"],
["crates/alkane-gui/src/main.rs"],
["crates/alkane-artifacts/Cargo.toml"],
["crates/alkane-cli/src/main.rs", "Cargo.lock"],
["crates/alkane-cli/src/main.rs", "ci/pr-surface.py"],
["crates/alkane-cli/README.md"]):
assert pr_surface.headless_packages(paths) == [], paths
with tempfile.TemporaryDirectory(prefix="alkane-toolkit-graph-") as directory:
root = Path(directory)
for name, extra in (
("alkane-gui", ""),
("alkane-artifacts", ""),
("alkane-flash", 'alkane-artifacts = { path = "../alkane-artifacts" }\n'),
):
crate = root / "crates" / name
crate.mkdir(parents=True)
(crate / "Cargo.toml").write_text(
f'[package]\nname = "{name}"\nversion = "0.1.0"\n'
f'[dependencies]\n{extra}'
)
saved_root = pr_surface.ROOT
try:
pr_surface.ROOT = root
changed = ["crates/alkane-artifacts/src/lib.rs"]
assert pr_surface.headless_packages(changed) == [
"alkane-artifacts", "alkane-flash",
]
with (root / "crates/alkane-gui/Cargo.toml").open("a") as stream:
stream.write('alkane-flash = { path = "../alkane-flash" }\n')
assert pr_surface.headless_packages(changed) == []
finally:
pr_surface.ROOT = saved_root
with tempfile.TemporaryDirectory(prefix="alkane-toolkit-pr-surface-") as directory:
repo = Path(directory)
git(repo, "init", "-q")
git(repo, "config", "user.name", "CI Test")
git(repo, "config", "user.email", "ci@example.invalid")
(repo / "README.md").write_text("initial\n")
git(repo, "add", "README.md")
git(repo, "commit", "-qm", "base")
base = git(repo, "rev-parse", "HEAD")
git(repo, "update-ref", "refs/remotes/origin/main", base)
(repo / "README.md").write_text("documentation change\n")
git(repo, "commit", "-qam", "docs")
saved_root = pr_surface.ROOT
saved_env = dict(os.environ)
try:
pr_surface.ROOT = repo
os.environ["GITHUB_EVENT_NAME"] = "pull_request"
os.environ["GITHUB_BASE_REF"] = "main"
assert pr_surface.changed_paths() == ["README.md"]
git(repo, "checkout", "-q", "-b", "rename-check", base)
git(repo, "mv", "README.md", "code.rs")
git(repo, "commit", "-qm", "rename")
assert set(pr_surface.changed_paths()) == {"README.md", "code.rs"}
os.environ.pop("GITHUB_BASE_REF")
try:
pr_surface.changed_paths()
except ValueError:
pass
else:
raise AssertionError("missing base must fall back to full checks")
finally:
pr_surface.ROOT = saved_root
os.environ.clear()
os.environ.update(saved_env)
print("Toolkit PR change surface: documentation, workflow, headless, and fallback PASS")
if __name__ == "__main__":
main()
-25
View File
@@ -1,25 +0,0 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Key the native wxWidgets prefix to its tracked source and build toolchain.
set -euo pipefail
material="$({
git rev-parse HEAD:thirdparty/wxwidgets/wxWidgets-3.3.3
git rev-parse HEAD:scripts/build-wx-linux.sh
cat thirdparty/wx-rs/VERSION
gcc -dumpmachine
gcc -dumpfullversion
pkg-config --modversion gtk+-3.0
mapfile -t modules < <(pkg-config --list-all | awk '{print $1}' | LC_ALL=C sort -u)
for module in "${modules[@]}"; do
printf '%s=%s\n' "$module" "$(pkg-config --modversion "$module" 2>/dev/null || printf unavailable)"
done
getconf GNU_LIBC_VERSION
} )"
digest="$(printf '%s\n' "$material" | sha256sum | cut -c1-24)"
key="wx-3.3.3-$digest"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
printf 'key=%s\n' "$key" >> "$GITHUB_OUTPUT"
else
printf '%s\n' "$key"
fi
+318
View File
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: MIT
//! Bounded, read-only SSH probes for board identification.
use std::collections::HashSet;
use std::fs;
use std::io::{self, Read};
use std::net::IpAddr;
@@ -17,6 +18,228 @@ pub enum Probe {
KernelRelease,
MtdTable,
DeviceTreeModel,
AlkaneBuildMarker,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AlkaneBuildMarker {
pub board: String,
pub sdk_revision: String,
pub os_revision: String,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BuildMarkerError {
InvalidFormat,
InvalidBoard,
InvalidRevision,
UnexpectedBuild,
}
/// A running board must report the identity embedded in the CI artifact.
/// This parser accepts the exact three-line marker emitted by the SDK.
pub fn parse_build_marker(bytes: &[u8]) -> Result<AlkaneBuildMarker, BuildMarkerError> {
if bytes.len() > 256 {
return Err(BuildMarkerError::InvalidFormat);
}
let text = std::str::from_utf8(bytes).map_err(|_| BuildMarkerError::InvalidFormat)?;
let mut lines = text.lines();
let board = lines
.next()
.and_then(|line| line.strip_prefix("board="))
.ok_or(BuildMarkerError::InvalidFormat)?;
let sdk_revision = lines
.next()
.and_then(|line| line.strip_prefix("sdk_revision="))
.ok_or(BuildMarkerError::InvalidFormat)?;
let os_revision = lines
.next()
.and_then(|line| line.strip_prefix("os_revision="))
.ok_or(BuildMarkerError::InvalidFormat)?;
if lines.next().is_some() || !text.ends_with('\n') {
return Err(BuildMarkerError::InvalidFormat);
}
if !matches!(
board,
"am335x-bb"
| "zynq-7010"
| "cv1835"
| "a113d"
| "allwinner-h3"
| "allwinner-h6"
| "allwinner-h616"
) {
return Err(BuildMarkerError::InvalidBoard);
}
for revision in [sdk_revision, os_revision] {
if revision.len() != 40
|| !revision
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
{
return Err(BuildMarkerError::InvalidRevision);
}
}
Ok(AlkaneBuildMarker {
board: board.to_owned(),
sdk_revision: sdk_revision.to_owned(),
os_revision: os_revision.to_owned(),
})
}
pub fn verify_build_marker(
observed: &AlkaneBuildMarker,
expected: &AlkaneBuildMarker,
) -> Result<(), BuildMarkerError> {
if observed == expected {
Ok(())
} else {
Err(BuildMarkerError::UnexpectedBuild)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MtdPartition {
pub index: u32,
pub size_bytes: u64,
pub erase_bytes: u64,
pub name: String,
}
/// The partition identity and geometry required by an SDK flash plan.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MtdRequirement {
pub index: u32,
pub name: String,
pub size_bytes: u64,
pub erase_bytes: u64,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MtdTarget {
pub device: PathBuf,
pub size_bytes: u64,
}
#[derive(Debug, Eq, PartialEq)]
pub enum MtdMatchError {
MissingIndex,
AmbiguousIndex,
NameMismatch,
SizeMismatch,
EraseMismatch,
}
/// Resolve a character device only after comparing the observed partition
/// with the expected identity and geometry. This does not authorize a write.
pub fn resolve_mtd_target(
observed: &[MtdPartition],
expected: &MtdRequirement,
) -> Result<MtdTarget, MtdMatchError> {
let mut matches = observed
.iter()
.filter(|entry| entry.index == expected.index);
let entry = matches.next().ok_or(MtdMatchError::MissingIndex)?;
if matches.next().is_some() {
return Err(MtdMatchError::AmbiguousIndex);
}
if entry.name != expected.name {
return Err(MtdMatchError::NameMismatch);
}
if entry.size_bytes != expected.size_bytes {
return Err(MtdMatchError::SizeMismatch);
}
if entry.erase_bytes != expected.erase_bytes {
return Err(MtdMatchError::EraseMismatch);
}
Ok(MtdTarget {
device: PathBuf::from(format!("/dev/mtd{}", entry.index)),
size_bytes: entry.size_bytes,
})
}
#[derive(Debug, Eq, PartialEq)]
pub enum MtdError {
InvalidHeader,
InvalidEntry(usize),
DuplicateIndex,
DuplicateName,
TooManyEntries,
}
/// Parse `/proc/mtd` as data. A flash plan must match both partition index
/// and name against its board-specific layout before using a device path.
pub fn parse_mtd_table(bytes: &[u8]) -> Result<Vec<MtdPartition>, MtdError> {
if bytes.len() > MAX_PROBE_BYTES {
return Err(MtdError::TooManyEntries);
}
let text = std::str::from_utf8(bytes).map_err(|_| MtdError::InvalidHeader)?;
let mut lines = text.lines();
if lines
.next()
.map(str::split_whitespace)
.map(Iterator::collect::<Vec<_>>)
!= Some(vec!["dev:", "size", "erasesize", "name"])
{
return Err(MtdError::InvalidHeader);
}
let mut entries = Vec::new();
let mut indices = HashSet::new();
let mut names = HashSet::new();
for (offset, line) in lines.enumerate() {
if line.trim().is_empty() {
continue;
}
let line_number = offset + 2;
if entries.len() >= 128 {
return Err(MtdError::TooManyEntries);
}
let invalid = || MtdError::InvalidEntry(line_number);
let start = line.find('"').ok_or_else(invalid)?;
let end = line.rfind('"').ok_or_else(invalid)?;
if start == end || !line[end + 1..].trim().is_empty() {
return Err(invalid());
}
let fields: Vec<_> = line[..start].split_whitespace().collect();
if fields.len() != 3 {
return Err(invalid());
}
let index = fields[0]
.strip_prefix("mtd")
.and_then(|value| value.strip_suffix(':'))
.and_then(|value| value.parse::<u32>().ok())
.ok_or_else(invalid)?;
let size_bytes = u64::from_str_radix(fields[1], 16).map_err(|_| invalid())?;
let erase_bytes = u64::from_str_radix(fields[2], 16).map_err(|_| invalid())?;
let name = &line[start + 1..end];
if size_bytes == 0
|| erase_bytes == 0
|| name.is_empty()
|| name.len() > 128
|| !name
.bytes()
.all(|byte| byte.is_ascii_graphic() || byte == b' ')
|| name.contains('"')
{
return Err(invalid());
}
if !indices.insert(index) {
return Err(MtdError::DuplicateIndex);
}
if !names.insert(name.to_owned()) {
return Err(MtdError::DuplicateName);
}
entries.push(MtdPartition {
index,
size_bytes,
erase_bytes,
name: name.to_owned(),
});
}
if entries.is_empty() {
return Err(MtdError::InvalidHeader);
}
Ok(entries)
}
impl Probe {
@@ -25,6 +248,7 @@ impl Probe {
Self::KernelRelease => "uname -r",
Self::MtdTable => "cat /proc/mtd",
Self::DeviceTreeModel => "cat /proc/device-tree/model",
Self::AlkaneBuildMarker => "cat /etc/alkane-build",
}
}
}
@@ -216,4 +440,98 @@ mod tests {
Err(AccessError::Timeout)
));
}
#[test]
fn parses_captured_mtd_layout_and_rejects_duplicate_targets() {
let captured = b"dev: size erasesize name\n\
mtd0: 02800000 00020000 \"BOOT.bin-dts-marker-kernel\"\n\
mtd1: 02000000 00020000 \"ramfs\"\n";
let entries = parse_mtd_table(captured).unwrap();
assert_eq!(entries[0].index, 0);
assert_eq!(entries[0].size_bytes, 0x0280_0000);
assert_eq!(entries[0].erase_bytes, 0x0002_0000);
assert_eq!(entries[0].name, "BOOT.bin-dts-marker-kernel");
let duplicate = b"dev: size erasesize name\n\
mtd0: 00020000 00020000 \"boot\"\n\
mtd0: 00020000 00020000 \"root\"\n";
assert_eq!(parse_mtd_table(duplicate), Err(MtdError::DuplicateIndex));
assert_eq!(
parse_mtd_table(b"mtd0: 1 1 \"boot\"\n"),
Err(MtdError::InvalidHeader)
);
}
#[test]
fn flash_target_requires_captured_identity_and_geometry() {
let observed = parse_mtd_table(
b"dev: size erasesize name\n\
mtd0: 02800000 00020000 \"BOOT.bin-dts-marker-kernel\"\n\
mtd1: 02000000 00020000 \"ramfs\"\n",
)
.unwrap();
let mut required = MtdRequirement {
index: 0,
name: "BOOT.bin-dts-marker-kernel".to_owned(),
size_bytes: 0x0280_0000,
erase_bytes: 0x0002_0000,
};
assert_eq!(
resolve_mtd_target(&observed, &required).unwrap().device,
Path::new("/dev/mtd0")
);
required.name = "ramfs".to_owned();
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::NameMismatch)
);
required.name = observed[0].name.clone();
required.size_bytes -= 1;
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::SizeMismatch)
);
required.size_bytes = observed[0].size_bytes;
required.erase_bytes *= 2;
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::EraseMismatch)
);
required.index = 2;
assert_eq!(
resolve_mtd_target(&observed, &required),
Err(MtdMatchError::MissingIndex)
);
}
#[test]
fn running_build_marker_must_match_the_artifact() {
let sha = "0123456789abcdef0123456789abcdef01234567";
let marker = format!("board=am335x-bb\nsdk_revision={sha}\nos_revision={sha}\n");
let expected = parse_build_marker(marker.as_bytes()).unwrap();
assert_eq!(verify_build_marker(&expected, &expected), Ok(()));
let other = AlkaneBuildMarker {
board: "zynq-7010".to_owned(),
..expected.clone()
};
assert_eq!(
verify_build_marker(&expected, &other),
Err(BuildMarkerError::UnexpectedBuild)
);
assert_eq!(
parse_build_marker(
marker
.replace("board=am335x-bb", "board=unknown")
.as_bytes()
),
Err(BuildMarkerError::InvalidBoard)
);
assert_eq!(
parse_build_marker(marker.replace(sha, "not-a-commit").as_bytes()),
Err(BuildMarkerError::InvalidRevision)
);
assert_eq!(
parse_build_marker(format!("{marker}extra=value\n").as_bytes()),
Err(BuildMarkerError::InvalidFormat)
);
}
}
+2
View File
@@ -8,3 +8,5 @@ license.workspace = true
alkane-core = { path = "../alkane-core" }
sha2.workspace = true
thiserror.workspace = true
flate2 = "1"
tar = "0.4"
+345 -1
View File
@@ -1,8 +1,9 @@
// SPDX-License-Identifier: MIT
//! Verify local firmware artifacts before an install path consumes them.
use flate2::read::GzDecoder;
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Component, Path, PathBuf};
@@ -10,6 +11,26 @@ use thiserror::Error;
const SEED: &str = include_str!("../data/manifest-seed.csv");
const HEADER: &str = "sha256,size_bytes,path,family,format,applicability";
const SDK_RELEASE_ASSETS: [&str; 8] = [
"alkane-sdk-a113d.tar.gz",
"alkane-sdk-allwinner-h3.tar.gz",
"alkane-sdk-allwinner-h6.tar.gz",
"alkane-sdk-allwinner-h616.tar.gz",
"alkane-sdk-am335x-bb.tar.gz",
"alkane-sdk-cv1835.tar.gz",
"alkane-sdk-qemu-zynq-research.tar.gz",
"alkane-sdk-zynq-7010.tar.gz",
];
const MAX_SDK_FILES: usize = 64;
const MAX_SDK_FILE_BYTES: u64 = 1024 * 1024 * 1024;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SdkArchiveInfo {
pub board: String,
pub sdk_revision: String,
pub os_revision: String,
pub artifact_count: usize,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ArtifactRecord {
@@ -35,6 +56,10 @@ pub enum VerifyError {
Digest,
#[error("artifact format is not recognized")]
UnsupportedFormat,
#[error("release asset name or path is invalid")]
ReleasePath,
#[error("SDK release archive contents are invalid")]
ReleaseContents,
}
/// A verified, rewound descriptor. Consumers should read this descriptor
@@ -108,6 +133,205 @@ pub fn parse_manifest(text: &str) -> Result<Vec<ArtifactRecord>, VerifyError> {
Ok(records)
}
/// Verify one archive against the complete checksum sidecar from its SDK
/// release. Keep the returned descriptor for any subsequent guarded use.
pub fn verify_sdk_release_archive(
checksums: &Path,
archive: &Path,
) -> Result<VerifiedArtifact, VerifyError> {
if std::fs::metadata(checksums)?.len() > 4096 {
return Err(VerifyError::Manifest(1));
}
let name = archive
.file_name()
.and_then(|value| value.to_str())
.ok_or(VerifyError::ReleasePath)?;
let listed = parse_sdk_release_checksums(&std::fs::read_to_string(checksums)?)?;
let sha256 = listed
.into_iter()
.find_map(|(entry, digest)| (entry == name).then_some(digest))
.ok_or(VerifyError::ReleasePath)?;
let record = ArtifactRecord {
sha256,
size_bytes: std::fs::metadata(archive)?.len(),
path: PathBuf::from(name),
family: name
.strip_prefix("alkane-sdk-")
.and_then(|value| value.strip_suffix(".tar.gz"))
.ok_or(VerifyError::ReleasePath)?
.to_owned(),
format: "tar-gzip".to_owned(),
applicability: "sdk-release".to_owned(),
};
verify_file(archive, &record)
}
/// Check the inner file list and revisions of a previously verified SDK archive.
/// This reads the verified descriptor; it never extracts archive paths.
pub fn inspect_sdk_release_archive(
verified: &mut VerifiedArtifact,
) -> Result<SdkArchiveInfo, VerifyError> {
let board = verified
.record
.family
.strip_prefix("qemu-")
.unwrap_or(&verified.record.family)
.to_owned();
let prefix = format!("alkane-sdk-{board}/");
verified.file.seek(SeekFrom::Start(0))?;
let decoder = GzDecoder::new(&mut verified.file);
let mut archive = tar::Archive::new(decoder);
let mut digests = HashMap::new();
let mut metadata = HashMap::new();
let mut count = 0;
for entry in archive.entries()?.raw(true) {
let mut entry = entry?;
count += 1;
if count > MAX_SDK_FILES {
return Err(VerifyError::ReleaseContents);
}
let path = entry.path_bytes().into_owned();
if count == 1 {
if !entry.header().entry_type().is_dir()
|| path.as_slice() != prefix.trim_end_matches('/').as_bytes()
&& path.as_slice() != prefix.as_bytes()
{
return Err(VerifyError::ReleaseContents);
}
continue;
}
if !entry.header().entry_type().is_file()
|| entry.size() > MAX_SDK_FILE_BYTES
|| !path.starts_with(prefix.as_bytes())
{
return Err(VerifyError::ReleaseContents);
}
let name =
std::str::from_utf8(&path[prefix.len()..]).map_err(|_| VerifyError::ReleaseContents)?;
if name.is_empty()
|| name == "."
|| name == ".."
|| !name.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'+' | b'-')
})
|| digests.contains_key(name)
{
return Err(VerifyError::ReleaseContents);
}
let mut hasher = Sha256::new();
let mut contents = Vec::new();
let is_metadata = matches!(name, "SDK-REVISION" | "OS-REVISION" | "SHA256SUMS");
if is_metadata && entry.size() > 100_000 {
return Err(VerifyError::ReleaseContents);
}
let mut buffer = [0_u8; 64 * 1024];
let mut read_bytes = 0_u64;
loop {
let length = entry.read(&mut buffer)?;
if length == 0 {
break;
}
read_bytes += length as u64;
hasher.update(&buffer[..length]);
if is_metadata {
contents.extend_from_slice(&buffer[..length]);
}
}
if read_bytes != entry.size() {
return Err(VerifyError::ReleaseContents);
}
if is_metadata {
metadata.insert(name.to_owned(), contents);
}
digests.insert(name.to_owned(), format!("{:x}", hasher.finalize()));
}
let mut decoder = archive.into_inner();
// Drain the gzip trailer to check its CRC, with a bound on tar padding.
if std::io::copy(
&mut decoder.by_ref().take(1024 * 1024 + 1),
&mut std::io::sink(),
)? > 1024 * 1024
{
return Err(VerifyError::ReleaseContents);
}
drop(decoder);
verified.revalidate()?;
let revision = |key| -> Result<String, VerifyError> {
let bytes = metadata.get(key).ok_or(VerifyError::ReleaseContents)?;
if bytes.len() != 41 || bytes[40] != b'\n' || !bytes[..40].iter().all(u8::is_ascii_hexdigit)
{
return Err(VerifyError::ReleaseContents);
}
let text = std::str::from_utf8(&bytes[..40]).map_err(|_| VerifyError::ReleaseContents)?;
if !text
.bytes()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
{
return Err(VerifyError::ReleaseContents);
}
Ok(text.to_owned())
};
let sdk_revision = revision("SDK-REVISION")?;
let os_revision = revision("OS-REVISION")?;
let checksums = metadata
.get("SHA256SUMS")
.ok_or(VerifyError::ReleaseContents)?;
let text = std::str::from_utf8(checksums).map_err(|_| VerifyError::ReleaseContents)?;
if !text.ends_with('\n') {
return Err(VerifyError::ReleaseContents);
}
let mut listed = HashMap::new();
for line in text.lines() {
let (digest, name) = line
.split_once(" ./")
.ok_or(VerifyError::ReleaseContents)?;
if digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
|| !digests.contains_key(name)
|| listed.insert(name.to_owned(), digest.to_owned()).is_some()
{
return Err(VerifyError::ReleaseContents);
}
}
digests.remove("SHA256SUMS");
if listed != digests || digests.len() < 3 {
return Err(VerifyError::ReleaseContents);
}
Ok(SdkArchiveInfo {
board,
sdk_revision,
os_revision,
artifact_count: digests.len() - 2,
})
}
fn parse_sdk_release_checksums(text: &str) -> Result<Vec<(String, String)>, VerifyError> {
let mut entries = Vec::new();
let mut names = HashSet::new();
for (index, line) in text.lines().enumerate() {
let line_number = index + 1;
let (digest, name) = line
.split_once(" ")
.ok_or(VerifyError::Manifest(line_number))?;
if digest.len() != 64
|| !digest
.bytes()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
|| !SDK_RELEASE_ASSETS.contains(&name)
|| !names.insert(name.to_owned())
{
return Err(VerifyError::Manifest(line_number));
}
entries.push((name.to_owned(), digest.to_owned()));
}
if !text.ends_with('\n') || entries.len() != SDK_RELEASE_ASSETS.len() {
return Err(VerifyError::Manifest(1));
}
Ok(entries)
}
fn signature_matches(format: &str, first: &[u8]) -> Result<bool, VerifyError> {
let prefix: &[u8] = match format {
"IMAGEWTY-SD" | "update-zip" | "zip-installer" => b"PK\x03\x04",
@@ -116,6 +340,7 @@ fn signature_matches(format: &str, first: &[u8]) -> Result<bool, VerifyError> {
"wm-package-0x9a5ba57c" => b"\x7c\xa5\x5b\x9a",
"bmu" => b"\x26\x01",
"bin-AES-container" => b"\x3f\x0a\x64\xae",
"tar-gzip" => b"\x1f\x8b",
_ => return Err(VerifyError::UnsupportedFormat),
};
Ok(first.starts_with(prefix))
@@ -228,6 +453,125 @@ mod tests {
std::fs::remove_file(path).unwrap();
}
#[test]
fn sdk_release_requires_every_asset_and_exact_archive_digest() {
let directory =
std::env::temp_dir().join(format!("alkane-sdk-release-test-{}", std::process::id()));
std::fs::create_dir(&directory).unwrap();
let archive = directory.join(SDK_RELEASE_ASSETS[0]);
let checksums = directory.join("SHA256SUMS");
let bytes = b"\x1f\x8bfixture";
std::fs::write(&archive, bytes).unwrap();
let digest: String = Sha256::digest(bytes)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
let manifest = SDK_RELEASE_ASSETS
.iter()
.map(|name| format!("{digest} {name}\n"))
.collect::<String>();
std::fs::write(&checksums, &manifest).unwrap();
let mut verified = verify_sdk_release_archive(&checksums, &archive).unwrap();
verified.revalidate().unwrap();
std::fs::write(&archive, b"\x1f\x8bfixturX").unwrap();
assert!(matches!(verified.revalidate(), Err(VerifyError::Digest)));
assert!(matches!(
verify_sdk_release_archive(&checksums, &archive),
Err(VerifyError::Digest)
));
std::fs::write(
&checksums,
manifest.lines().take(7).collect::<Vec<_>>().join("\n") + "\n",
)
.unwrap();
assert!(matches!(
verify_sdk_release_archive(&checksums, &archive),
Err(VerifyError::Manifest(1))
));
std::fs::remove_file(archive).unwrap();
std::fs::remove_file(checksums).unwrap();
std::fs::remove_dir(directory).unwrap();
}
fn board_archive(files: &[(&str, &[u8])]) -> Vec<u8> {
let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
let mut builder = tar::Builder::new(encoder);
let mut directory = tar::Header::new_gnu();
directory.set_entry_type(tar::EntryType::Directory);
directory.set_size(0);
directory.set_mode(0o755);
directory.set_cksum();
builder
.append_data(&mut directory, "alkane-sdk-am335x-bb/", std::io::empty())
.unwrap();
for &(name, contents) in files {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
header.set_mode(0o644);
header.set_cksum();
builder
.append_data(
&mut header,
format!("alkane-sdk-am335x-bb/{name}"),
contents,
)
.unwrap();
}
builder.into_inner().unwrap().finish().unwrap()
}
#[test]
fn sdk_inner_archive_requires_safe_files_and_matching_checksums() {
let directory =
std::env::temp_dir().join(format!("alkane-sdk-inner-test-{}", std::process::id()));
std::fs::create_dir(&directory).unwrap();
let archive = directory.join("alkane-sdk-am335x-bb.tar.gz");
let sdk = format!("{}\n", "a".repeat(40));
let os = format!("{}\n", "b".repeat(40));
let artifact = b"image".as_slice();
let files = [
("SDK-REVISION", sdk.as_bytes()),
("OS-REVISION", os.as_bytes()),
("image.bin", artifact),
];
let checksums = files
.iter()
.map(|(name, data)| format!("{:x} ./{name}\n", Sha256::digest(data)))
.collect::<String>();
let mut members = files.to_vec();
members.push(("SHA256SUMS", checksums.as_bytes()));
let good = board_archive(&members);
let record = ArtifactRecord {
sha256: format!("{:x}", Sha256::digest(&good)),
size_bytes: good.len() as u64,
path: PathBuf::from("alkane-sdk-am335x-bb.tar.gz"),
family: "am335x-bb".to_owned(),
format: "tar-gzip".to_owned(),
applicability: "sdk-release".to_owned(),
};
std::fs::write(&archive, &good).unwrap();
let mut verified = verify_file(&archive, &record).unwrap();
let info = inspect_sdk_release_archive(&mut verified).unwrap();
assert_eq!(info.board, "am335x-bb");
assert_eq!(info.sdk_revision, "a".repeat(40));
assert_eq!(info.os_revision, "b".repeat(40));
assert_eq!(info.artifact_count, 1);
members[2] = ("image.bin", b"other");
let changed = board_archive(&members);
std::fs::write(&archive, &changed).unwrap();
let mut changed_record = record.clone();
changed_record.sha256 = format!("{:x}", Sha256::digest(&changed));
changed_record.size_bytes = changed.len() as u64;
let mut verified = verify_file(&archive, &changed_record).unwrap();
assert!(matches!(
inspect_sdk_release_archive(&mut verified),
Err(VerifyError::ReleaseContents)
));
std::fs::remove_file(archive).unwrap();
std::fs::remove_dir(directory).unwrap();
}
#[test]
#[ignore = "microbenchmark"]
fn bench_verify_artifact() {
+1
View File
@@ -7,3 +7,4 @@ license.workspace = true
[dependencies]
alkane-core = { path = "../alkane-core" }
alkane-artifacts = { path = "../alkane-artifacts" }
alkane-access = { path = "../alkane-access" }
+59 -3
View File
@@ -1,14 +1,46 @@
// SPDX-License-Identifier: MIT
//! Headless entry point for read-only artifact verification.
use alkane_artifacts::{seed_manifest, verify_file};
use alkane_access::{parse_build_marker, verify_build_marker, Probe, SshTarget};
use alkane_artifacts::{
inspect_sdk_release_archive, seed_manifest, verify_file, verify_sdk_release_archive,
};
use std::io;
use std::net::IpAddr;
use std::path::Path;
fn run() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
if args.len() != 4 || args[1] != "verify-artifact" {
return Err("usage: alkane-cli verify-artifact <manifest-path> <local-file>".into());
match args.get(1).map(String::as_str) {
Some("verify-artifact") if args.len() == 4 => verify_artifact(&args),
Some("verify-sdk-release") if args.len() == 4 => verify_sdk_release(&args),
Some("verify-running-build") if args.len() == 8 => verify_running_build(&args),
_ => Err("usage: alkane-cli verify-artifact <manifest-path> <local-file>\n alkane-cli verify-sdk-release <SHA256SUMS> <archive>\n alkane-cli verify-running-build <ip> <user> <known-hosts> <board> <sdk-sha> <os-sha>".into()),
}
}
fn verify_sdk_release(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let mut verified = verify_sdk_release_archive(Path::new(&args[2]), Path::new(&args[3]))?;
if verified.record().family == "qemu-zynq-research" {
println!(
"verified checksum for SDK research archive {}; no board revision metadata is present",
verified.record().path.display()
);
return Ok(());
}
let info = inspect_sdk_release_archive(&mut verified)?;
println!(
"verified SDK release archive {} board={} sdk={} os={} artifacts={}",
verified.record().path.display(),
info.board,
info.sdk_revision,
info.os_revision,
info.artifact_count
);
Ok(())
}
fn verify_artifact(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let record = seed_manifest()?
.into_iter()
.find(|item| item.path == Path::new(&args[2]))
@@ -23,6 +55,30 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn verify_running_build(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let address: IpAddr = args[2].parse()?;
let expected_text = format!(
"board={}\nsdk_revision={}\nos_revision={}\n",
args[5], args[6], args[7]
);
let expected = parse_build_marker(expected_text.as_bytes())
.map_err(|error| io::Error::other(format!("invalid expected build: {error:?}")))?;
let target = SshTarget::new(address, 22, &args[3], Path::new(&args[4]))
.map_err(|error| io::Error::other(format!("SSH target: {error:?}")))?;
let raw = target
.probe(Probe::AlkaneBuildMarker)
.map_err(|error| io::Error::other(format!("running build read: {error:?}")))?;
let observed = parse_build_marker(&raw)
.map_err(|error| io::Error::other(format!("running build marker: {error:?}")))?;
verify_build_marker(&observed, &expected)
.map_err(|error| io::Error::other(format!("build comparison: {error:?}")))?;
println!(
"verified running build {} {} {}",
observed.board, observed.sdk_revision, observed.os_revision
);
Ok(())
}
fn main() {
if let Err(error) = run() {
eprintln!("artifact verification failed: {error}");