Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b610ce3d7f | ||
|
|
1a5dcd17a9 | ||
|
|
3b1b1fa63e | ||
|
|
7880b14e47 | ||
|
|
5bbf5b71b7 | ||
|
|
cfec9606a4 | ||
|
|
e8d7cdc77a | ||
|
|
8ba585679a | ||
|
|
ea102130ac | ||
|
|
e656402ec8 | ||
|
|
80f3c22582 | ||
|
|
a79ac3e09e | ||
|
|
6580005e77 | ||
|
|
2734c8e356 | ||
|
|
0c2897ce37 | ||
|
|
fbc903fa6a | ||
|
|
fe9617ab56 | ||
|
|
1e9e4f16b5 | ||
|
|
6a6a5e7ded | ||
|
|
e20b6890d3 | ||
|
|
17bee91248 | ||
|
|
63d0de8ae3 | ||
|
|
9a8efc807a | ||
|
|
9879a0eb25 | ||
|
|
03c19ef7c6 | ||
|
|
2540801140 | ||
|
|
dd28fa233c | ||
|
|
e5ca519df0 | ||
|
|
06c8e01eb5 | ||
|
|
990439985d | ||
|
|
54136b71ef | ||
|
|
5d18304f0f | ||
|
|
8bbf844bb6 | ||
|
|
97607a0a91 |
@@ -0,0 +1,34 @@
|
||||
name: public-benchmark-pages
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '*/15 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: alkane-toolkit-public-benchmark-pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-pages
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install SSH client
|
||||
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 }}
|
||||
run: python3 ci/bench_history.py render
|
||||
- name: Publish public benchmark page
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
BENCH_PAGES_DEPLOY_KEY: ${{ secrets.BENCH_PAGES_DEPLOY_KEY }}
|
||||
run: python3 ci/publish-bench-pages.py toolkit
|
||||
- name: Clean generated page
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
@@ -4,6 +4,10 @@ on:
|
||||
push:
|
||||
branches: [next]
|
||||
|
||||
concurrency:
|
||||
group: alkane-toolkit-next
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
|
||||
@@ -6,6 +6,10 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
group: alkane-toolkit-main
|
||||
cancel-in-progress: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
actions: write
|
||||
@@ -38,6 +42,9 @@ jobs:
|
||||
- name: Benchmark history checks
|
||||
run: python3 ci/test-bench-history.py
|
||||
|
||||
- name: Benchmark suite checks
|
||||
run: python3 ci/test-bench-badge.py
|
||||
|
||||
- name: Install build dependencies
|
||||
run: |
|
||||
apt-get update -qq
|
||||
@@ -89,12 +96,12 @@ jobs:
|
||||
|
||||
- name: Microbenchmarks
|
||||
run: |
|
||||
# Capture the bench stdout for the weighted-average delta badge (round 19
|
||||
# #1) while keeping the step a hard gate: pipefail preserves cargo's exit
|
||||
# code (each bench asserts its own absolute ceiling) even through tee.
|
||||
# Require every declared benchmark before publishing history or a release.
|
||||
set -o pipefail
|
||||
cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ --test-threads=1 \
|
||||
| tee bench-current.txt
|
||||
python3 ci/bench-badge.py --current bench-current.txt \
|
||||
--baseline badges/bench-baseline.json --no-write
|
||||
|
||||
- name: Record private benchmark history
|
||||
env:
|
||||
@@ -105,7 +112,6 @@ jobs:
|
||||
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 \
|
||||
|
||||
Generated
+3
@@ -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",
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Alkane Toolkit
|
||||
|
||||
[](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
|
||||
[](https://gitea.bluefla.re/blueflare/alkane-toolkit/actions)
|
||||

|
||||

|
||||

|
||||
@@ -10,9 +10,9 @@
|
||||

|
||||

|
||||
|
||||
Desktop fleet discovery and monitoring for ASIC miners. The Rust GUI uses
|
||||
wxWidgets through a patched [wx-rs bridge](thirdparty/wx-rs). Firmware
|
||||
installation is under development.
|
||||
Desktop miner discovery and monitoring. The Rust GUI uses wxWidgets through
|
||||
a patched [wx-rs bridge](thirdparty/wx-rs). Firmware installation is under
|
||||
development.
|
||||
|
||||
## Run locally
|
||||
|
||||
@@ -22,48 +22,53 @@ scripts/build-gui-linux.sh
|
||||
ALKANE_FAKE_SCAN=1 ~/.cache/alkane-tk-target/release/alkane-toolkit
|
||||
```
|
||||
|
||||
The first command builds wxWidgets 3.3.3 once. Linux runtime needs GTK 3
|
||||
(`libgtk-3-0` on Debian/Ubuntu). The fake scan uses offline fixtures and
|
||||
does not contact hardware. Windows and macOS use their respective
|
||||
`scripts/build-gui-*.sh` scripts and platform toolchains.
|
||||
The first command builds wxWidgets 3.3.3 once. Linux needs GTK 3. Fake scan
|
||||
uses offline fixtures and does not contact hardware. For Windows and macOS,
|
||||
use the matching `scripts/build-gui-*.sh` script.
|
||||
|
||||
## Current scope
|
||||
|
||||
- Discover miners by CIDR or IP range with vendored
|
||||
[asic-rs](vendor/asic-rs), and show model, firmware, health, hashrate,
|
||||
temperatures, fans, PSU, and pool workers.
|
||||
- Filter, sort, and reorder columns in the desktop table.
|
||||
- Probe discovery, telemetry, presets, and write actions with the
|
||||
`miner_probe` CLI. Run it without arguments for the verb list.
|
||||
- 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`.
|
||||
|
||||
The installer and some operator actions remain roadmap items; see the
|
||||
Discovery is read-only. The installer and operator actions remain in the
|
||||
[implementation plan](docs/IMPLEMENTATION-PLAN.md) and
|
||||
[firmware parity matrix](docs/aftermarket-parity-roadmap.md). A listed
|
||||
firmware or board is not an install claim. Discovery is read-only.
|
||||
[firmware matrix](docs/aftermarket-parity-roadmap.md).
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
export WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config"
|
||||
export CARGO_TARGET_DIR="$HOME/.cache/alkane-tk-target"
|
||||
cargo test -p alkane-gui --offline
|
||||
cargo clippy -p alkane-gui --no-deps --bins -- -D warnings
|
||||
scripts/ui-selftest.sh
|
||||
ci/coverage.sh --summary-only
|
||||
WX_RS_WXCONFIG="$HOME/.cache/wx-3.3.3-linux/bin/wx-config" \
|
||||
CARGO_TARGET_DIR="$HOME/.cache/alkane-tk-target" \
|
||||
cargo test -p alkane-gui --offline
|
||||
```
|
||||
|
||||
Keep build output off the source share. `main` runs the full CI gate and
|
||||
publishes qualifying releases; `next` builds `-rc` candidates. Badges
|
||||
report host tests and benchmarks, not installation support. Benchmark
|
||||
comparisons require the same CPU class. The code quality letter reports the
|
||||
Clippy gate; the separate coverage badge reports exercised lines.
|
||||
Keep build output off the source share. `main` runs full CI and publishes
|
||||
qualifying releases; `next` builds `-rc` candidates. Badges measure host
|
||||
code, not installation support. See the public
|
||||
[benchmark history](https://blueflare.gitea.bluefla.re/alkane-benchmarks/toolkit/).
|
||||
|
||||
## Firmware safety
|
||||
|
||||
The [SDK install rules](https://gitea.bluefla.re/blueflare/alkane-sdk/src/branch/main/docs/install-methods.md) require
|
||||
serial and recovery checks for risky writes. Installation must never write
|
||||
the bootloader or secure region, must verify over an independent channel,
|
||||
and must use the packer and boot-switch procedure for the exact board.
|
||||
Installation must follow the [SDK install rules](https://gitea.bluefla.re/blueflare/alkane-sdk/src/branch/main/docs/install-methods.md):
|
||||
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
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
@@ -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
@@ -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 |
+57
-45
@@ -1,27 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compute the weighted-average microbenchmark delta versus the previous release.
|
||||
|
||||
Reads the captured stdout of `cargo test ... --ignored --nocapture bench_` (whose
|
||||
timings are Rust `Duration` Debug strings: "12.3ms", "512us"/"512µs", "840ns",
|
||||
"1.2s"), compares each bench to a committed baseline of the previous release's
|
||||
numbers, and prints the time-weighted average change as a signed percentage:
|
||||
|
||||
(sum(current) / sum(baseline) - 1) * 100 over benches present in both
|
||||
|
||||
Weighting by duration means the slow benches dominate, so the number tracks
|
||||
overall wall-time change rather than giving a tiny bench equal say. Then the
|
||||
baseline is rewritten with the current numbers, so the next release compares
|
||||
against this one ("the previous commit").
|
||||
|
||||
Usage:
|
||||
bench-badge.py --current bench-current.txt --baseline badges/bench-baseline.json
|
||||
|
||||
Prints the delta as a plain number (e.g. "-3.2", or "NEW" when there is no
|
||||
usable baseline) to stdout. The baseline JSON lives under badges/ so committing
|
||||
it back does not trip compute-version.sh's path-based release bump.
|
||||
"""
|
||||
"""Check the Toolkit benchmark suite and compare it with the prior release."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
@@ -29,9 +10,17 @@ import sys
|
||||
# A Duration Debug token: a number immediately followed by a time unit, with the
|
||||
# multi-char units listed before the bare "s" so alternation prefers them. The
|
||||
# trailing (?![a-zA-Z]) stops "s" in words like "rows"/"cidrs" from matching.
|
||||
_DUR = re.compile(r"([0-9]+(?:\.[0-9]+)?)\s*(ns|µs|us|ms|s)(?![a-zA-Z])")
|
||||
_UNIT_NS = {"ns": 1.0, "us": 1e3, "µs": 1e3, "ms": 1e6, "s": 1e9}
|
||||
_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_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",
|
||||
"bench_view_pipeline_default_sort", "bench_sort_by_each_column",
|
||||
"bench_view_pipeline_with_filter", "bench_upsert_cold_start_population",
|
||||
}
|
||||
|
||||
|
||||
def parse_bench(text: str) -> dict:
|
||||
@@ -44,12 +33,33 @@ def parse_bench(text: str) -> dict:
|
||||
continue
|
||||
durs = _DUR.findall(line)
|
||||
if not durs:
|
||||
continue
|
||||
raise ValueError(f"missing timing for {m.group(1)}")
|
||||
val, unit = durs[-1]
|
||||
out[m.group(1)] = float(val) * _UNIT_NS[unit]
|
||||
elapsed = float(val) * _UNIT_NS[unit]
|
||||
if m.group(1) in out or not math.isfinite(elapsed) or elapsed <= 0:
|
||||
raise ValueError(f"duplicate or invalid timing for {m.group(1)}")
|
||||
out[m.group(1)] = elapsed
|
||||
return out
|
||||
|
||||
|
||||
def require_suite(results: dict) -> dict:
|
||||
if results.keys() != EXPECTED_BENCHES:
|
||||
raise ValueError("microbenchmark results differ from the declared suite")
|
||||
return results
|
||||
|
||||
|
||||
def benchmark_delta(current: dict, baseline: dict) -> float | None:
|
||||
"""Average each comparable benchmark's percentage improvement."""
|
||||
if not baseline:
|
||||
return None
|
||||
changes = [(baseline[name] - current[name]) / baseline[name]
|
||||
for name in baseline]
|
||||
delta = math.fsum(changes) / len(changes) * 100
|
||||
if not math.isfinite(delta):
|
||||
raise ValueError("benchmark comparison is not finite")
|
||||
return delta
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--current", required=True, help="captured bench stdout")
|
||||
@@ -59,32 +69,34 @@ def main() -> int:
|
||||
|
||||
try:
|
||||
with open(args.current, encoding="utf-8") as fh:
|
||||
current = parse_bench(fh.read())
|
||||
except OSError as e:
|
||||
current = require_suite(parse_bench(fh.read()))
|
||||
except (OSError, ValueError) as e:
|
||||
print(f"bench-badge: cannot read current results: {e}", file=sys.stderr)
|
||||
print("NEW")
|
||||
return 0
|
||||
|
||||
if not current:
|
||||
print("bench-badge: no bench lines parsed from current results", file=sys.stderr)
|
||||
print("NEW")
|
||||
return 0
|
||||
return 1
|
||||
|
||||
baseline = {}
|
||||
try:
|
||||
with open(args.baseline, encoding="utf-8") as fh:
|
||||
baseline = {k: float(v) for k, v in json.load(fh).items()}
|
||||
except (OSError, ValueError):
|
||||
baseline = {}
|
||||
baseline = json.load(fh)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except (OSError, ValueError) as e:
|
||||
print(f"bench-badge: invalid baseline: {e}", file=sys.stderr)
|
||||
return 1
|
||||
if (not isinstance(baseline, dict)
|
||||
or not set(baseline).issubset(current)
|
||||
or any(not isinstance(value, (int, float)) or isinstance(value, bool)
|
||||
or not math.isfinite(value) or value <= 0
|
||||
for value in baseline.values())):
|
||||
print("bench-badge: invalid or retired benchmark in baseline", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
common = [k for k in current if k in baseline and baseline[k] > 0]
|
||||
if common:
|
||||
sum_new = sum(current[k] for k in common)
|
||||
sum_old = sum(baseline[k] for k in common)
|
||||
delta = (sum_new / sum_old - 1.0) * 100.0 if sum_old > 0 else 0.0
|
||||
print(f"{delta:.1f}")
|
||||
else:
|
||||
print("NEW")
|
||||
try:
|
||||
delta = benchmark_delta(current, baseline)
|
||||
except ValueError as error:
|
||||
print(f"bench-badge: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print("NEW" if delta is None else f"{delta:.1f}")
|
||||
|
||||
if not args.no_write:
|
||||
os.makedirs(os.path.dirname(args.baseline) or ".", exist_ok=True)
|
||||
|
||||
+10
-3
@@ -126,7 +126,7 @@ def render_html(index: dict) -> str:
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=("prepare", "publish"))
|
||||
parser.add_argument("action", choices=("prepare", "publish", "render"))
|
||||
args = parser.parse_args()
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
@@ -141,8 +141,15 @@ def main() -> None:
|
||||
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
|
||||
print(f"Loaded {len(baseline)} prior benchmark measurements")
|
||||
return
|
||||
metrics = {"bench_ns_per_op": bench_badge.parse_bench(
|
||||
Path("bench-current.txt").read_text()), "bench_host": benchmark_host()}
|
||||
if args.action == "render":
|
||||
if not index["entries"]:
|
||||
raise ValueError("no measured benchmark history to publish")
|
||||
Path("bench-site").mkdir(exist_ok=True)
|
||||
Path("bench-site/index.html").write_text(render_html(index))
|
||||
print(f"Rendered {len(index['entries'])} measured benchmark commits")
|
||||
return
|
||||
metrics = {"bench_ns_per_op": bench_badge.require_suite(bench_badge.parse_bench(
|
||||
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"
|
||||
|
||||
@@ -9,7 +9,7 @@ import sys
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DIRECTORIES = ("target", "dist", "coverage")
|
||||
DIRECTORIES = ("target", "dist", "coverage", "bench-site")
|
||||
FILES = ("bench-current.txt",)
|
||||
|
||||
|
||||
|
||||
+10
-11
@@ -108,13 +108,13 @@ def loc_color(n: int) -> str:
|
||||
|
||||
|
||||
def bench_color(delta_pct: float) -> str:
|
||||
# Negative delta = faster than the previous release. A +/-2% dead band absorbs
|
||||
# the run-to-run jitter of microbenchmarks on a shared CI runner.
|
||||
if delta_pct <= -2.0:
|
||||
# Positive delta means faster than the previous release. A +/-2% band
|
||||
# absorbs run-to-run jitter on the dedicated CI runner.
|
||||
if delta_pct >= 2.0:
|
||||
return "brightgreen"
|
||||
if delta_pct < 2.0:
|
||||
if delta_pct > -2.0:
|
||||
return "blue"
|
||||
if delta_pct < 10.0:
|
||||
if delta_pct > -10.0:
|
||||
return "yellow"
|
||||
return "orange"
|
||||
|
||||
@@ -161,9 +161,8 @@ def main() -> int:
|
||||
ap.add_argument("--coverage", type=float, default=None)
|
||||
ap.add_argument("--bench-coverage", type=float, default=None)
|
||||
ap.add_argument("--bench", default=None)
|
||||
# Weighted-average microbench delta vs the previous release, as a signed
|
||||
# percentage string (e.g. "-3.2"), or "NEW"/"" when there is no baseline yet
|
||||
# (round 19 #1). Takes precedence over --bench for the bench badge.
|
||||
# Mean per-benchmark improvement vs the previous release, as a signed
|
||||
# percentage string, or "NEW" when there is no baseline.
|
||||
ap.add_argument("--bench-delta", default=None)
|
||||
ap.add_argument("--clippy", choices=("clean", "failed"))
|
||||
args = ap.parse_args()
|
||||
@@ -197,8 +196,8 @@ 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")
|
||||
# Bench badge: prefer the weighted-average delta vs the previous release; fall
|
||||
# back to the static label (first run, or when the delta could not be computed).
|
||||
# Bench badge: prefer the mean per-benchmark improvement vs the previous
|
||||
# release. Use the static label when no comparison is available.
|
||||
delta = None
|
||||
if args.bench_delta not in (None, "", "NEW"):
|
||||
try:
|
||||
@@ -206,7 +205,7 @@ def main() -> int:
|
||||
except ValueError:
|
||||
delta = None
|
||||
if delta is not None:
|
||||
# Negative = faster than the previous release (good).
|
||||
# Positive = faster than the previous release.
|
||||
msg = f"{'+' if delta > 0 else ''}{delta:.1f}% vs prev"
|
||||
write("bench", "bench", msg, bench_color(delta))
|
||||
elif args.bench_delta == "NEW":
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Publish a measured benchmark page to the public, data-only Pages repo."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import tempfile
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
PAGES_REPO = "ssh://git@gitea.bluefla.re:2222/blueflare/alkane-benchmarks.git"
|
||||
GUARD_REPO = "https://gitea.bluefla.re/blueflare/alkane-benchmarks.git"
|
||||
GUARD_COMMIT = "ea160545c49bc419a245692deda8dd7db7a611eb"
|
||||
PAGES_HOST = "gitea.bluefla.re"
|
||||
PAGES_HOST_FINGERPRINT = "SHA256:lqB5cmC9E5HNeg/lkzdOwQ++I8A70Wx7lnNs6liN24g"
|
||||
PAGES_HOST_KEY = "[gitea.bluefla.re]:2222 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO1II6NkmRW+QAd+Wj+7qbNrA8Oo+/N/WRog4hELskn/"
|
||||
|
||||
|
||||
def run(*args: str, env: dict[str, str] | None = None,
|
||||
cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(args, env=env, cwd=cwd, text=True,
|
||||
capture_output=True, check=True)
|
||||
|
||||
|
||||
def current_main_sha() -> str:
|
||||
api = os.environ["GITHUB_API_URL"].rstrip("/")
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
token = os.environ["GITEA_TOKEN"]
|
||||
request = Request(f"{api}/repos/{repo}/branches/main",
|
||||
headers={"Authorization": f"token {token}"})
|
||||
with urlopen(request, timeout=20) as response:
|
||||
branch = json.load(response)
|
||||
return branch["commit"]["id"]
|
||||
|
||||
|
||||
def publish(site: str) -> None:
|
||||
if os.environ.get("GITHUB_REF") != "refs/heads/main":
|
||||
raise ValueError("benchmark Pages publication requires main")
|
||||
sha = os.environ["GITHUB_SHA"]
|
||||
if current_main_sha() != sha:
|
||||
print("Skipping benchmark page from a superseded main commit")
|
||||
return
|
||||
page = Path("bench-site/index.html").read_bytes()
|
||||
if not page.startswith(b"<!doctype html>") or len(page) > 1_048_576:
|
||||
raise ValueError("invalid benchmark page")
|
||||
with tempfile.TemporaryDirectory(prefix="alkane-pages-") as directory:
|
||||
temporary = Path(directory)
|
||||
guard_checkout = temporary / "guard"
|
||||
run("git", "clone", "--quiet", "--single-branch", "--branch", "next",
|
||||
GUARD_REPO, str(guard_checkout))
|
||||
guard_source = run("git", "show", f"{GUARD_COMMIT}:ci/validate_site.py",
|
||||
cwd=guard_checkout).stdout
|
||||
guard_script = temporary / "validate_site.py"
|
||||
guard_script.write_text(guard_source)
|
||||
run("python3", str(guard_script), "--page", site,
|
||||
str(Path("bench-site/index.html").resolve()))
|
||||
key = os.environ["BENCH_PAGES_DEPLOY_KEY"]
|
||||
if not key.startswith("-----BEGIN OPENSSH PRIVATE KEY-----"):
|
||||
raise ValueError("missing benchmark Pages deploy key")
|
||||
key_path = temporary / "deploy_key"
|
||||
key_path.write_text(key.rstrip("\n") + "\n")
|
||||
key_path.chmod(0o600)
|
||||
known_hosts = temporary / "known_hosts"
|
||||
known_hosts.write_text(PAGES_HOST_KEY + "\n")
|
||||
fingerprint = run("ssh-keygen", "-lf", str(known_hosts)).stdout.split()[1]
|
||||
if fingerprint != PAGES_HOST_FINGERPRINT:
|
||||
raise ValueError("benchmark Pages SSH host key changed")
|
||||
git_env = os.environ.copy()
|
||||
ssh_command = (f"ssh -i {shlex.quote(str(key_path))} -o IdentitiesOnly=yes "
|
||||
f"-o UserKnownHostsFile={shlex.quote(str(known_hosts))} "
|
||||
"-o StrictHostKeyChecking=yes -o ConnectTimeout=10")
|
||||
git_env["GIT_SSH_COMMAND"] = ssh_command
|
||||
git_env["GIT_TERMINAL_PROMPT"] = "0"
|
||||
checkout = temporary / "site"
|
||||
run("git", "clone", "--quiet", "--single-branch", "--branch", "gh-pages",
|
||||
PAGES_REPO, str(checkout), env=git_env)
|
||||
run("git", "config", "user.name", "Alkane CI", cwd=checkout)
|
||||
run("git", "config", "user.email", "ci@bluefla.re", cwd=checkout)
|
||||
for attempt in range(3):
|
||||
if current_main_sha() != sha:
|
||||
print("Skipping benchmark page from a superseded main commit")
|
||||
return
|
||||
run("git", "fetch", "--quiet", "origin", "gh-pages", env=git_env,
|
||||
cwd=checkout)
|
||||
run("git", "checkout", "-q", "-B", "bench-publish", "origin/gh-pages",
|
||||
cwd=checkout)
|
||||
destination = checkout / site / "index.html"
|
||||
destination.parent.mkdir(exist_ok=True)
|
||||
destination.write_bytes(page)
|
||||
run("git", "add", f"{site}/index.html", cwd=checkout)
|
||||
changed = subprocess.run(("git", "diff", "--cached", "--quiet"),
|
||||
cwd=checkout, check=False)
|
||||
if changed.returncode == 0:
|
||||
print(f"{site} benchmark page is already current")
|
||||
return
|
||||
if changed.returncode != 1:
|
||||
raise RuntimeError("cannot compare benchmark page")
|
||||
run("git", "commit", "-q", "-m",
|
||||
f"Update {site} benchmarks for {sha[:10]} [skip ci]", cwd=checkout)
|
||||
pushed = subprocess.run(("git", "push", "--quiet", "origin",
|
||||
"HEAD:gh-pages"), env=git_env, cwd=checkout,
|
||||
text=True, capture_output=True, check=False)
|
||||
if pushed.returncode == 0:
|
||||
print(f"Published {site} benchmark page for {sha[:10]}")
|
||||
return
|
||||
if attempt == 2:
|
||||
raise RuntimeError(f"benchmark Pages push failed: {pushed.stderr.strip()}")
|
||||
raise RuntimeError("benchmark Pages publication did not complete")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("site", choices=("sdk", "os", "toolkit"))
|
||||
publish(parser.parse_args().site)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Check that every Toolkit benchmark contributes to the release badge."""
|
||||
|
||||
import importlib.util
|
||||
import re
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location("bench_badge", ROOT / "ci/bench-badge.py")
|
||||
assert spec is not None and spec.loader is not None
|
||||
badge = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(badge)
|
||||
badge_spec = importlib.util.spec_from_file_location("gen_badges", ROOT / "ci/gen-badges.py")
|
||||
assert badge_spec is not None and badge_spec.loader is not None
|
||||
gen_badges = importlib.util.module_from_spec(badge_spec)
|
||||
badge_spec.loader.exec_module(gen_badges)
|
||||
|
||||
|
||||
class BenchBadgeTests(unittest.TestCase):
|
||||
def test_declared_suite_matches_rust_benchmarks(self):
|
||||
names = set()
|
||||
for directory in (ROOT / "crates/alkane-gui/src", ROOT / "crates/alkane-artifacts/src"):
|
||||
for path in directory.rglob("*.rs"):
|
||||
names.update(re.findall(
|
||||
r'#\[test\]\s*#\[ignore(?:\s*=\s*"[^"]*")?\]\s*'
|
||||
r'fn (bench_[A-Za-z0-9_]+)\s*\(', path.read_text()))
|
||||
self.assertEqual(names, badge.EXPECTED_BENCHES)
|
||||
|
||||
def test_incomplete_duplicate_and_malformed_results_fail(self):
|
||||
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), 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"):
|
||||
badge.parse_bench("\n".join(lines + [lines[0]]))
|
||||
with self.assertRaisesRegex(ValueError, "missing timing"):
|
||||
badge.parse_bench(lines[0].replace("10ms/op", "missing"))
|
||||
|
||||
def test_badge_averages_each_benchmark_improvement(self):
|
||||
current = {"short": 50.0, "long": 900.0}
|
||||
baseline = {"short": 100.0, "long": 1000.0}
|
||||
self.assertEqual(badge.benchmark_delta(current, baseline), 30.0)
|
||||
self.assertAlmostEqual(badge.benchmark_delta(baseline, current), -55.5555556)
|
||||
self.assertIsNone(badge.benchmark_delta(current, {}))
|
||||
self.assertEqual(gen_badges.bench_color(30.0), "brightgreen")
|
||||
self.assertEqual(gen_badges.bench_color(-55.5555556), "orange")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1 +1,537 @@
|
||||
// alkane-access
|
||||
// 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;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const MAX_PROBE_BYTES: usize = 64 * 1024;
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(12);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
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 {
|
||||
fn command(self) -> &'static str {
|
||||
match self {
|
||||
Self::KernelRelease => "uname -r",
|
||||
Self::MtdTable => "cat /proc/mtd",
|
||||
Self::DeviceTreeModel => "cat /proc/device-tree/model",
|
||||
Self::AlkaneBuildMarker => "cat /etc/alkane-build",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AccessError {
|
||||
InvalidTarget,
|
||||
InvalidKnownHosts,
|
||||
Timeout,
|
||||
OutputTooLarge,
|
||||
RemoteFailure,
|
||||
Io(io::Error),
|
||||
}
|
||||
|
||||
impl From<io::Error> for AccessError {
|
||||
fn from(error: io::Error) -> Self {
|
||||
Self::Io(error)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SshTarget {
|
||||
address: IpAddr,
|
||||
port: u16,
|
||||
user: String,
|
||||
known_hosts: PathBuf,
|
||||
}
|
||||
|
||||
impl SshTarget {
|
||||
pub fn new(
|
||||
address: IpAddr,
|
||||
port: u16,
|
||||
user: &str,
|
||||
known_hosts: &Path,
|
||||
) -> Result<Self, AccessError> {
|
||||
if port == 0
|
||||
|| user.is_empty()
|
||||
|| !user
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
|
||||
{
|
||||
return Err(AccessError::InvalidTarget);
|
||||
}
|
||||
if !known_hosts.is_absolute()
|
||||
|| !fs::metadata(known_hosts).is_ok_and(|metadata| metadata.is_file())
|
||||
{
|
||||
return Err(AccessError::InvalidKnownHosts);
|
||||
}
|
||||
Ok(Self {
|
||||
address,
|
||||
port,
|
||||
user: user.to_owned(),
|
||||
known_hosts: known_hosts.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
fn command(&self, probe: Probe) -> Command {
|
||||
let mut command = Command::new("ssh");
|
||||
command
|
||||
.arg("-F")
|
||||
.arg("none")
|
||||
.arg("-o")
|
||||
.arg("BatchMode=yes")
|
||||
.arg("-o")
|
||||
.arg("StrictHostKeyChecking=yes")
|
||||
.arg("-o")
|
||||
.arg("GlobalKnownHostsFile=none")
|
||||
.arg("-o")
|
||||
.arg(format!("UserKnownHostsFile={}", self.known_hosts.display()))
|
||||
.arg("-o")
|
||||
.arg("ConnectTimeout=5")
|
||||
.arg("-o")
|
||||
.arg("ServerAliveInterval=5")
|
||||
.arg("-o")
|
||||
.arg("ServerAliveCountMax=1")
|
||||
.arg("-o")
|
||||
.arg("RequestTTY=no")
|
||||
.arg("-p")
|
||||
.arg(self.port.to_string())
|
||||
.arg(format!("{}@{}", self.user, self.address))
|
||||
.arg(probe.command());
|
||||
command
|
||||
}
|
||||
|
||||
pub fn probe(&self, probe: Probe) -> Result<Vec<u8>, AccessError> {
|
||||
run_bounded(self.command(probe))
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_bounded<R: Read + Send + 'static>(
|
||||
mut reader: R,
|
||||
) -> thread::JoinHandle<Result<Vec<u8>, AccessError>> {
|
||||
thread::spawn(move || {
|
||||
let mut data = Vec::new();
|
||||
let mut chunk = [0_u8; 4096];
|
||||
loop {
|
||||
let count = reader.read(&mut chunk)?;
|
||||
if count == 0 {
|
||||
return Ok(data);
|
||||
}
|
||||
if data.len() + count > MAX_PROBE_BYTES {
|
||||
return Err(AccessError::OutputTooLarge);
|
||||
}
|
||||
data.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn run_bounded(command: Command) -> Result<Vec<u8>, AccessError> {
|
||||
run_bounded_with_timeout(command, PROBE_TIMEOUT)
|
||||
}
|
||||
|
||||
fn run_bounded_with_timeout(
|
||||
mut command: Command,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<u8>, AccessError> {
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
let mut child = command.spawn()?;
|
||||
let stdout = collect_bounded(child.stdout.take().expect("piped stdout"));
|
||||
let stderr = collect_bounded(child.stderr.take().expect("piped stderr"));
|
||||
let deadline = Instant::now() + timeout;
|
||||
let result = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status.success();
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
let _ = stdout.join();
|
||||
let _ = stderr.join();
|
||||
return Err(AccessError::Timeout);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
let output = stdout.join().map_err(|_| AccessError::RemoteFailure)??;
|
||||
let error_output = stderr.join().map_err(|_| AccessError::RemoteFailure)??;
|
||||
if !result || !error_output.is_empty() {
|
||||
return Err(AccessError::RemoteFailure);
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn target_rejects_injected_user_and_unknown_host_file() {
|
||||
let address = "127.0.0.1".parse().unwrap();
|
||||
assert!(matches!(
|
||||
SshTarget::new(
|
||||
address,
|
||||
22,
|
||||
"root;id",
|
||||
Path::new("/etc/ssh/ssh_known_hosts")
|
||||
),
|
||||
Err(AccessError::InvalidTarget)
|
||||
));
|
||||
assert!(matches!(
|
||||
SshTarget::new(address, 22, "root", Path::new("relative-known-hosts")),
|
||||
Err(AccessError::InvalidKnownHosts)
|
||||
));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn bounded_runner_rejects_excess_output_and_failed_command() {
|
||||
let mut success = Command::new("/bin/sh");
|
||||
success.args(["-c", "printf board"]);
|
||||
assert_eq!(run_bounded(success).unwrap(), b"board");
|
||||
let mut overflow = Command::new("/bin/sh");
|
||||
overflow.args(["-c", "head -c 70000 /dev/zero"]);
|
||||
assert!(matches!(
|
||||
run_bounded(overflow),
|
||||
Err(AccessError::OutputTooLarge)
|
||||
));
|
||||
let mut failed = Command::new("/bin/sh");
|
||||
failed.args(["-c", "exit 7"]);
|
||||
assert!(matches!(
|
||||
run_bounded(failed),
|
||||
Err(AccessError::RemoteFailure)
|
||||
));
|
||||
let mut hanging = Command::new("/bin/sleep");
|
||||
hanging.arg("1");
|
||||
assert!(matches!(
|
||||
run_bounded_with_timeout(hanging, Duration::from_millis(20)),
|
||||
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)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,3 +8,5 @@ license.workspace = true
|
||||
alkane-core = { path = "../alkane-core" }
|
||||
sha2.workspace = true
|
||||
thiserror.workspace = true
|
||||
flate2 = "1"
|
||||
tar = "0.4"
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -7,3 +7,4 @@ license.workspace = true
|
||||
[dependencies]
|
||||
alkane-core = { path = "../alkane-core" }
|
||||
alkane-artifacts = { path = "../alkane-artifacts" }
|
||||
alkane-access = { path = "../alkane-access" }
|
||||
|
||||
@@ -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}");
|
||||
|
||||
Reference in New Issue
Block a user