Compare commits

...
6 Commits
17 changed files with 261 additions and 19 deletions
+4
View File
@@ -11,6 +11,7 @@ jobs:
candidate: candidate:
runs-on: alkane-ci runs-on: alkane-ci
env: env:
CARGO_TARGET_DIR: target
WX_PREFIX: /root/.cache/wx-3.3.3-linux WX_PREFIX: /root/.cache/wx-3.3.3-linux
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
steps: steps:
@@ -46,3 +47,6 @@ jobs:
env: env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} 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" run: python3 ci/release-rc.py "${{ steps.version.outputs.tag }}" true "dist/alkane-toolkit-${{ steps.version.outputs.version }}-linux-x86_64.tar.gz"
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+5 -1
View File
@@ -14,6 +14,7 @@ jobs:
release: release:
runs-on: alkane-ci runs-on: alkane-ci
env: env:
CARGO_TARGET_DIR: target
WX_PREFIX: /root/.cache/wx-3.3.3-linux WX_PREFIX: /root/.cache/wx-3.3.3-linux
# Set once for the whole job so build/clippy/test/bench steps don't each # Set once for the whole job so build/clippy/test/bench steps don't each
# re-export it (round 18 #12). # re-export it (round 18 #12).
@@ -92,7 +93,7 @@ jobs:
# #1) while keeping the step a hard gate: pipefail preserves cargo's exit # #1) while keeping the step a hard gate: pipefail preserves cargo's exit
# code (each bench asserts its own absolute ceiling) even through tee. # code (each bench asserts its own absolute ceiling) even through tee.
set -o pipefail set -o pipefail
cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ \ cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ --test-threads=1 \
| tee bench-current.txt | tee bench-current.txt
- name: Record private benchmark history - name: Record private benchmark history
@@ -203,3 +204,6 @@ jobs:
- name: No release needed - name: No release needed
if: steps.ver.outputs.release != 'true' if: steps.ver.outputs.release != 'true'
run: echo "No backend/UI change since ${{ steps.ver.outputs.last_tag }} - skipping release." run: echo "No backend/UI change since ${{ steps.ver.outputs.last_tag }} - skipping release."
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
+5 -1
View File
@@ -14,6 +14,7 @@ jobs:
verify: verify:
runs-on: alkane-ci runs-on: alkane-ci
env: env:
CARGO_TARGET_DIR: target
WX_PREFIX: /root/.cache/wx-3.3.3-linux WX_PREFIX: /root/.cache/wx-3.3.3-linux
WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config WX_RS_WXCONFIG: /root/.cache/wx-3.3.3-linux/bin/wx-config
steps: steps:
@@ -55,7 +56,7 @@ jobs:
cargo test -p alkane-artifacts -p alkane-flash -p alkane-cli --offline cargo test -p alkane-artifacts -p alkane-flash -p alkane-cli --offline
- name: Microbenchmarks - name: Microbenchmarks
run: cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ run: cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ --test-threads=1
- name: Headless UI self-test - name: Headless UI self-test
run: | run: |
@@ -76,3 +77,6 @@ jobs:
else else
echo "cargo-audit not installed on this runner; skipping" echo "cargo-audit not installed on this runner; skipping"
fi fi
- name: Clean generated Toolkit build
if: always()
run: python3 ci/cleanup-generated.py
Generated
+1
View File
@@ -74,6 +74,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"alkane-artifacts", "alkane-artifacts",
"alkane-core", "alkane-core",
"sha2",
"thiserror", "thiserror",
] ]
+6
View File
@@ -12,6 +12,12 @@
The CI badge shows the last completed attempt for this branch while newer The CI badge shows the last completed attempt for this branch while newer
runs are queued. Badge SVGs are stored in a private, machine-maintained branch. runs are queued. Badge SVGs are stored in a private, machine-maintained branch.
The code-quality letter requires warnings-denied Clippy and measured test plus
UI self-test line coverage: A at 90%, B at 80%, C at 70%, D at 60%, and F
below 60%. A missing coverage measurement displays pending.
The benchmark delta compares an earlier commit only when its CPU class
matches the current dedicated runner; otherwise it establishes a new
baseline. Main CI runs microbenchmarks serially to avoid test contention.
A cross-platform desktop toolkit for discovering, monitoring, and re-flashing A cross-platform desktop toolkit for discovering, monitoring, and re-flashing
ASIC miners. It scans a fleet over the network, shows live health and hashrate ASIC miners. It scans a fleet over the network, shows live health and hashrate
+1 -1
View File
@@ -31,7 +31,7 @@ import sys
# trailing (?![a-zA-Z]) stops "s" in words like "rows"/"cidrs" from matching. # 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])") _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} _UNIT_NS = {"ns": 1.0, "us": 1e3, "µs": 1e3, "ms": 1e6, "s": 1e9}
_NAME = re.compile(r"^(bench_[A-Za-z0-9_]+)\s*:") _NAME = re.compile(r"^(?:test [A-Za-z0-9_:]+ \.\.\. )?(bench_[A-Za-z0-9_]+)\s*:")
def parse_bench(text: str) -> dict: def parse_bench(text: str) -> dict:
+10 -4
View File
@@ -17,6 +17,7 @@ from urllib.error import HTTPError
from urllib.parse import quote from urllib.parse import quote
from badge_store import BADGE_BRANCH, publish_file, request_json from badge_store import BADGE_BRANCH, publish_file, request_json
from bench_host import identity as benchmark_host
bench_spec = importlib.util.spec_from_file_location( bench_spec = importlib.util.spec_from_file_location(
"bench_badge", Path(__file__).with_name("bench-badge.py")) "bench_badge", Path(__file__).with_name("bench-badge.py"))
@@ -59,13 +60,15 @@ def git_distance(ancestor: str, sha: str) -> int | None:
return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None return int(result.stdout.strip()) if ancestor_check.returncode == 0 else None
def previous_measurement(index: dict, sha: str, distance=None) -> dict: def previous_measurement(index: dict, sha: str, distance=None, host=None) -> dict:
distance = distance or git_distance distance = distance or git_distance
choices = [] choices = []
for entry in index.get("entries", []): for entry in index.get("entries", []):
ancestor = entry.get("sha") ancestor = entry.get("sha")
if ancestor == sha or not isinstance(ancestor, str): if ancestor == sha or not isinstance(ancestor, str):
continue continue
if host is not None and entry.get("metrics", {}).get("bench_host") != host:
continue
gap = distance(ancestor, sha) gap = distance(ancestor, sha)
if gap is not None and gap > 0: if gap is not None and gap > 0:
choices.append((gap, entry)) choices.append((gap, entry))
@@ -95,6 +98,9 @@ def render_html(index: dict) -> str:
cells = [f'<td><a href="https://gitea.bluefla.re/blueflare/alkane-toolkit/commit/{sha}">{sha[:10]}</a></td>', cells = [f'<td><a href="https://gitea.bluefla.re/blueflare/alkane-toolkit/commit/{sha}">{sha[:10]}</a></td>',
f'<td>{html.escape(entry["timestamp"])}</td>'] f'<td>{html.escape(entry["timestamp"])}</td>']
values = valid_benches(entry["metrics"]) values = valid_benches(entry["metrics"])
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>')
cells += [f'<td>{values[name]:.3f}</td>' if name in values else '<td>new</td>' cells += [f'<td>{values[name]:.3f}</td>' if name in values else '<td>new</td>'
for name in names] for name in names]
rows.append("<tr>" + "".join(cells) + "</tr>") rows.append("<tr>" + "".join(cells) + "</tr>")
@@ -114,7 +120,7 @@ def render_html(index: dict) -> str:
f"<p><small>Most recent {len(entries)} measured commits. Full per-commit JSON is retained " f"<p><small>Most recent {len(entries)} measured commits. Full per-commit JSON is retained "
"in the private ci-badges branch.</small></p>" "in the private ci-badges branch.</small></p>"
f"<div class=\"scroll\"><table><thead><tr><th scope=\"col\">Commit</th>" f"<div class=\"scroll\"><table><thead><tr><th scope=\"col\">Commit</th>"
f"<th scope=\"col\">UTC</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") "</tbody></table></div></body></html>\n")
@@ -130,13 +136,13 @@ def main() -> None:
if index.get("schema") != 1 or not isinstance(index.get("entries"), list): if index.get("schema") != 1 or not isinstance(index.get("entries"), list):
raise ValueError("unsupported benchmark history index") raise ValueError("unsupported benchmark history index")
if args.action == "prepare": if args.action == "prepare":
baseline = previous_measurement(index, sha) baseline = previous_measurement(index, sha, host=benchmark_host())
Path("badges").mkdir(exist_ok=True) Path("badges").mkdir(exist_ok=True)
Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n") Path("badges/bench-baseline.json").write_text(json.dumps(baseline) + "\n")
print(f"Loaded {len(baseline)} prior benchmark measurements") print(f"Loaded {len(baseline)} prior benchmark measurements")
return return
metrics = {"bench_ns_per_op": bench_badge.parse_bench( metrics = {"bench_ns_per_op": bench_badge.parse_bench(
Path("bench-current.txt").read_text())} Path("bench-current.txt").read_text()), "bench_host": benchmark_host()}
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds") timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
index = updated_index(index, sha, metrics, timestamp) index = updated_index(index, sha, metrics, timestamp)
record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n" record = json.dumps(index["entries"][-1], indent=2).encode() + b"\n"
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Identify the CPU class used for comparable CI microbenchmark baselines."""
import os
import platform
from pathlib import Path
def identity() -> dict[str, object]:
model = "unknown"
cpuinfo = Path("/proc/cpuinfo")
if cpuinfo.is_file():
for line in cpuinfo.read_text(errors="replace").splitlines():
if line.startswith(("model name\t", "Hardware\t", "Processor\t")):
model = line.partition(":")[2].strip()[:160]
break
return {"architecture": platform.machine(), "cpu_model": model,
"logical_cpus": os.cpu_count() or 1}
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Remove generated Toolkit CI work after the release asset is uploaded."""
import os
from pathlib import Path
import shutil
import sys
ROOT = Path(__file__).resolve().parents[1]
DIRECTORIES = ("target", "dist", "coverage")
FILES = ("bench-current.txt",)
def cleanup() -> None:
if not os.environ.get("GITHUB_RUN_ID"):
raise ValueError("cleanup is restricted to CI runs")
for name in DIRECTORIES:
path = ROOT / name
if path.is_symlink() or path.parent.resolve() != ROOT.resolve():
raise ValueError(f"unsafe generated directory: {path}")
if path.is_dir():
shutil.rmtree(path)
print(f"Removed generated directory: {name}")
elif path.exists():
raise ValueError(f"expected a generated directory: {path}")
for name in FILES:
path = ROOT / name
if path.is_symlink() or path.parent.resolve() != ROOT.resolve():
raise ValueError(f"unsafe generated file: {path}")
if path.is_file():
path.unlink()
print(f"Removed generated file: {name}")
if __name__ == "__main__":
try:
cleanup()
except (OSError, ValueError) as error:
print(f"ERROR: Toolkit cleanup: {error}", file=sys.stderr)
raise SystemExit(1)
+19 -2
View File
@@ -11,6 +11,7 @@ Metrics not passed on the command line are computed here (LOC from the source
tree, dependency count from Cargo.lock, license from Cargo.toml). tree, dependency count from Cargo.lock, license from Cargo.toml).
""" """
import argparse import argparse
import math
import os import os
import re import re
import sys import sys
@@ -130,6 +131,17 @@ def cov_color(pct: float) -> str:
return "red" return "red"
def quality_grade(clippy: str, coverage: float | None) -> str:
if clippy != "clean":
return "F"
if coverage is None:
return "pending"
for minimum, grade in ((90, "A"), (80, "B"), (70, "C"), (60, "D")):
if coverage >= minimum:
return grade
return "F"
def human(n: int) -> str: def human(n: int) -> str:
suffixes = ("", "K", "M", "G") suffixes = ("", "K", "M", "G")
value = float(n) value = float(n)
@@ -160,6 +172,9 @@ def main() -> int:
ap.add_argument("--bench-delta", default=None) ap.add_argument("--bench-delta", default=None)
ap.add_argument("--clippy", default="clean") ap.add_argument("--clippy", default="clean")
args = ap.parse_args() args = ap.parse_args()
for value in (args.coverage, args.bench_coverage):
if value is not None and (not math.isfinite(value) or not 0 <= value <= 100):
ap.error("coverage must be a finite percentage between 0 and 100")
os.makedirs(os.path.join(args.root, args.out), exist_ok=True) os.makedirs(os.path.join(args.root, args.out), exist_ok=True)
@@ -176,8 +191,10 @@ def main() -> int:
write("loc", "lines of code", human(loc), loc_color(loc)) write("loc", "lines of code", human(loc), loc_color(loc))
write("license", "license", lic, "blue") write("license", "license", lic, "blue")
write("dependencies", "dependencies", str(deps), "blue") write("dependencies", "dependencies", str(deps), "blue")
grade = "A" if args.clippy == "clean" else "F" grade = quality_grade(args.clippy, args.coverage)
write("quality", "code quality", grade, "brightgreen" if grade == "A" else "red") write("quality", "code quality", grade,
{"A": "brightgreen", "B": "yellowgreen", "C": "yellow",
"D": "orange", "F": "red", "pending": "lightgrey"}[grade])
if args.tests is not None: if args.tests is not None:
write("tests", "tests", f"{args.tests} passing", "brightgreen") write("tests", "tests", f"{args.tests} passing", "brightgreen")
if args.coverage is not None: if args.coverage is not None:
+26 -2
View File
@@ -7,10 +7,23 @@ from pathlib import Path
import unittest import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parent))
from bench_history import previous_measurement, render_html, updated_index from bench_history import bench_badge, previous_measurement, render_html, updated_index
class HistoryTests(unittest.TestCase): class HistoryTests(unittest.TestCase):
def test_cargo_nocapture_benchmark_lines_are_parsed(self):
output = (
"test tests::bench_verify_artifact ... bench_verify_artifact: 208.302µs\n"
"test model::tests::bench_render_cells ... bench_render_cells: "
"5000 rows x 10 cols = 8.007185ms/full-render (bytes=13553600)\n"
"bench_direct: 12ns/op\n"
)
self.assertEqual(bench_badge.parse_bench(output), {
"bench_verify_artifact": 208_302.0,
"bench_render_cells": 8_007_185.0,
"bench_direct": 12.0,
})
def test_retry_uses_previous_commit(self): def test_retry_uses_previous_commit(self):
first = "a" * 40 first = "a" * 40
second = "b" * 40 second = "b" * 40
@@ -33,9 +46,20 @@ class HistoryTests(unittest.TestCase):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
updated_index({}, "a" * 40, {"bench_ns_per_op": {"hash": -1}}, "now") updated_index({}, "a" * 40, {"bench_ns_per_op": {"hash": -1}}, "now")
def test_baseline_must_match_cpu_class(self):
host = {"architecture": "x86_64", "cpu_model": "A", "logical_cpus": 8}
other = {"architecture": "x86_64", "cpu_model": "B", "logical_cpus": 8}
index = {"entries": [{"sha": "a" * 40, "metrics": {
"bench_ns_per_op": {"hash": 10.0}, "bench_host": host}}]}
distance = lambda _ancestor, _sha: 1
self.assertEqual(previous_measurement(index, "b" * 40, distance, host),
{"hash": 10.0})
self.assertEqual(previous_measurement(index, "b" * 40, distance, other), {})
def test_site_escapes_history_content(self): def test_site_escapes_history_content(self):
entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>", entry = {"sha": "a" * 40, "timestamp": "<script>alert(1)</script>",
"metrics": {"bench_ns_per_op": {"hash": 10.0}}} "metrics": {"bench_ns_per_op": {"hash": 10.0},
"bench_host": {"cpu_model": "<script>cpu</script>"}}}
page = render_html({"entries": [entry]}) page = render_html({"entries": [entry]})
self.assertIn("&lt;script&gt;", page) self.assertIn("&lt;script&gt;", page)
self.assertNotIn("<script>", page) self.assertNotIn("<script>", page)
+20 -4
View File
@@ -52,6 +52,11 @@ impl VerifiedArtifact {
pub fn reader(&mut self) -> &mut File { pub fn reader(&mut self) -> &mut File {
&mut self.file &mut self.file
} }
/// Recheck the same descriptor immediately before a guarded write.
pub fn revalidate(&mut self) -> Result<(), VerifyError> {
verify_open_file(&mut self.file, &self.record)
}
} }
pub fn seed_manifest() -> Result<Vec<ArtifactRecord>, VerifyError> { pub fn seed_manifest() -> Result<Vec<ArtifactRecord>, VerifyError> {
@@ -118,9 +123,18 @@ fn signature_matches(format: &str, first: &[u8]) -> Result<bool, VerifyError> {
pub fn verify_file(path: &Path, record: &ArtifactRecord) -> Result<VerifiedArtifact, VerifyError> { pub fn verify_file(path: &Path, record: &ArtifactRecord) -> Result<VerifiedArtifact, VerifyError> {
let mut file = File::open(path)?; let mut file = File::open(path)?;
verify_open_file(&mut file, record)?;
Ok(VerifiedArtifact {
file,
record: record.clone(),
})
}
fn verify_open_file(file: &mut File, record: &ArtifactRecord) -> Result<(), VerifyError> {
if file.metadata()?.len() != record.size_bytes { if file.metadata()?.len() != record.size_bytes {
return Err(VerifyError::Size); return Err(VerifyError::Size);
} }
file.seek(SeekFrom::Start(0))?;
let mut first = [0_u8; 16]; let mut first = [0_u8; 16];
let length = file.read(&mut first)?; let length = file.read(&mut first)?;
if !signature_matches(&record.format, &first[..length])? { if !signature_matches(&record.format, &first[..length])? {
@@ -147,10 +161,7 @@ pub fn verify_file(path: &Path, record: &ArtifactRecord) -> Result<VerifiedArtif
return Err(VerifyError::Digest); return Err(VerifyError::Digest);
} }
file.seek(SeekFrom::Start(0))?; file.seek(SeekFrom::Start(0))?;
Ok(VerifiedArtifact { Ok(())
file,
record: record.clone(),
})
} }
#[cfg(test)] #[cfg(test)]
@@ -189,9 +200,14 @@ mod tests {
applicability: "test".to_owned(), applicability: "test".to_owned(),
}; };
let mut verified = verify_file(&path, &record).unwrap(); let mut verified = verify_file(&path, &record).unwrap();
verified.revalidate().unwrap();
let mut replay = Vec::new(); let mut replay = Vec::new();
verified.reader().read_to_end(&mut replay).unwrap(); verified.reader().read_to_end(&mut replay).unwrap();
assert_eq!(replay, bytes); assert_eq!(replay, bytes);
std::fs::write(&path, b"PK\x03\x04changed").unwrap();
assert!(matches!(verified.revalidate(), Err(VerifyError::Digest)));
std::fs::write(&path, bytes).unwrap();
verified.revalidate().unwrap();
record.size_bytes += 1; record.size_bytes += 1;
assert!(matches!( assert!(matches!(
verify_file(&path, &record), verify_file(&path, &record),
+1
View File
@@ -7,4 +7,5 @@ license.workspace = true
[dependencies] [dependencies]
alkane-core = { path = "../alkane-core" } alkane-core = { path = "../alkane-core" }
alkane-artifacts = { path = "../alkane-artifacts" } alkane-artifacts = { path = "../alkane-artifacts" }
sha2.workspace = true
thiserror.workspace = true thiserror.workspace = true
+77 -4
View File
@@ -3,6 +3,7 @@
//! Board transport adapters must supply serial, recovery and readback evidence. //! Board transport adapters must supply serial, recovery and readback evidence.
use alkane_artifacts::VerifiedArtifact; use alkane_artifacts::VerifiedArtifact;
use sha2::{Digest, Sha256};
use std::io::{Read, Seek, SeekFrom}; use std::io::{Read, Seek, SeekFrom};
use thiserror::Error; use thiserror::Error;
@@ -65,6 +66,10 @@ pub enum FlashError {
ReadbackMismatch, ReadbackMismatch,
#[error("verified image has an invalid digest")] #[error("verified image has an invalid digest")]
InvalidDigest, InvalidDigest,
#[error("image changed since verification")]
ArtifactChanged,
#[error("writer did not consume the complete image")]
IncompleteWrite,
#[error("write transport: {0}")] #[error("write transport: {0}")]
Write(String), Write(String),
#[error("readback transport: {0}")] #[error("readback transport: {0}")]
@@ -85,6 +90,24 @@ fn digest_bytes(hex: &str) -> Result<[u8; 32], FlashError> {
Ok(result) Ok(result)
} }
struct DigestReader<'a> {
inner: &'a mut dyn Read,
remaining: u64,
digest: Sha256,
}
impl Read for DigestReader<'_> {
fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
let limit = buffer
.len()
.min(usize::try_from(self.remaining).unwrap_or(usize::MAX));
let length = self.inner.read(&mut buffer[..limit])?;
self.remaining -= length as u64;
self.digest.update(&buffer[..length]);
Ok(length)
}
}
/// Stop before reboot. The caller must still prove live boot and persistence. /// Stop before reboot. The caller must still prove live boot and persistence.
pub fn write_verified<W: Writer, R: IndependentReadback>( pub fn write_verified<W: Writer, R: IndependentReadback>(
partition: &PartitionSpec, partition: &PartitionSpec,
@@ -119,6 +142,9 @@ pub fn write_verified<W: Writer, R: IndependentReadback>(
return Err(FlashError::RecoveryRequired); return Err(FlashError::RecoveryRequired);
} }
} }
artifact
.revalidate()
.map_err(|_| FlashError::ArtifactChanged)?;
let backup = writer let backup = writer
.backup(partition) .backup(partition)
.map_err(|e| FlashError::Write(e.to_string()))?; .map_err(|e| FlashError::Write(e.to_string()))?;
@@ -133,9 +159,21 @@ pub fn write_verified<W: Writer, R: IndependentReadback>(
.reader() .reader()
.seek(SeekFrom::Start(0)) .seek(SeekFrom::Start(0))
.map_err(|e| FlashError::ArtifactIo(e.to_string()))?; .map_err(|e| FlashError::ArtifactIo(e.to_string()))?;
let mut stream = DigestReader {
inner: artifact.reader(),
remaining: size,
digest: Sha256::new(),
};
writer writer
.write(partition, artifact.reader(), size) .write(partition, &mut stream, size)
.map_err(|e| FlashError::Write(e.to_string()))?; .map_err(|e| FlashError::Write(e.to_string()))?;
if stream.remaining != 0 {
return Err(FlashError::IncompleteWrite);
}
let written_digest: [u8; 32] = stream.digest.finalize().into();
if written_digest != expected {
return Err(FlashError::ArtifactChanged);
}
let actual = readback let actual = readback
.sha256(partition, size) .sha256(partition, size)
.map_err(|e| FlashError::Readback(e.to_string()))?; .map_err(|e| FlashError::Readback(e.to_string()))?;
@@ -162,6 +200,7 @@ mod tests {
serial: bool, serial: bool,
recovery: bool, recovery: bool,
backup_bytes: u64, backup_bytes: u64,
max_read: Option<u64>,
writes: usize, writes: usize,
contents: Vec<u8>, contents: Vec<u8>,
} }
@@ -192,9 +231,16 @@ mod tests {
_: u64, _: u64,
) -> Result<(), Self::Error> { ) -> Result<(), Self::Error> {
self.writes += 1; self.writes += 1;
image if let Some(limit) = self.max_read {
.read_to_end(&mut self.contents) image
.map_err(|_| "read failed")?; .take(limit)
.read_to_end(&mut self.contents)
.map_err(|_| "read failed")?;
} else {
image
.read_to_end(&mut self.contents)
.map_err(|_| "read failed")?;
}
Ok(()) Ok(())
} }
} }
@@ -236,6 +282,7 @@ mod tests {
serial: true, serial: true,
recovery: true, recovery: true,
backup_bytes: 4096, backup_bytes: 4096,
max_read: None,
writes: 0, writes: 0,
contents: Vec::new(), contents: Vec::new(),
} }
@@ -322,4 +369,30 @@ mod tests {
assert_eq!(writer.contents, IMAGE); assert_eq!(writer.contents, IMAGE);
std::fs::remove_file(path).unwrap(); std::fs::remove_file(path).unwrap();
} }
#[test]
fn refuses_changed_or_partially_consumed_artifacts() {
let (path, mut image) = artifact("changed");
let target = partition();
let mut writer = writer();
let mut readback = MockReadback {
channel: "serial",
digest: digest_bytes(SHA).unwrap(),
};
std::fs::write(&path, b"PK\x03\x04changed").unwrap();
assert!(matches!(
write_verified(&target, &mut image, &mut writer, &mut readback),
Err(FlashError::ArtifactChanged)
));
assert_eq!(writer.writes, 0);
std::fs::write(&path, IMAGE).unwrap();
writer.max_read = Some(4);
assert!(matches!(
write_verified(&target, &mut image, &mut writer, &mut readback),
Err(FlashError::IncompleteWrite)
));
assert_eq!(writer.writes, 1);
std::fs::remove_file(path).unwrap();
}
} }
+1
View File
@@ -5,6 +5,7 @@
# scripts/build-wx-linux.sh to produce it). # scripts/build-wx-linux.sh to produce it).
set -e set -e
REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
trap 'bash "$REPO/scripts/clean-old-builds.sh" || true' 0
WX_PREFIX="${1:-$HOME/.cache/wx-3.3.3-linux}" WX_PREFIX="${1:-$HOME/.cache/wx-3.3.3-linux}"
if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then if [ ! -x "$WX_PREFIX/bin/wx-config" ]; then
"$REPO/scripts/build-wx-linux.sh" "$REPO/scripts/build-wx-linux.sh"
+15
View File
@@ -6,6 +6,21 @@ REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
SRC="$REPO/thirdparty/wxwidgets/wxWidgets-3.3.3" SRC="$REPO/thirdparty/wxwidgets/wxWidgets-3.3.3"
BUILD="$HOME/.cache/wxbuild/wxWidgets-3.3.3" BUILD="$HOME/.cache/wxbuild/wxWidgets-3.3.3"
PREFIX="$HOME/.cache/wx-3.3.3-linux" PREFIX="$HOME/.cache/wx-3.3.3-linux"
cleanup_wx_build() {
python3 - "$BUILD" "$HOME/.cache/wxbuild" <<'PY'
from pathlib import Path
import shutil
import sys
build, parent = map(Path, sys.argv[1:])
if (build.name != "wxWidgets-3.3.3" or build.parent != parent
or build.is_symlink() or parent.is_symlink()):
raise SystemExit("refusing unsafe wxWidgets build cleanup path")
if build.is_dir():
shutil.rmtree(build)
PY
}
trap cleanup_wx_build 0
[ -d "$BUILD" ] || { mkdir -p "$HOME/.cache/wxbuild"; cp -r "$SRC" "$BUILD"; } [ -d "$BUILD" ] || { mkdir -p "$HOME/.cache/wxbuild"; cp -r "$SRC" "$BUILD"; }
[ -d "$BUILD" ] || { echo "thirdparty wxWidgets tree missing"; exit 1; } [ -d "$BUILD" ] || { echo "thirdparty wxWidgets tree missing"; exit 1; }
chmod +x "$BUILD/configure" "$BUILD/config.guess" "$BUILD/config.sub" "$BUILD/install-sh" 2>/dev/null || true chmod +x "$BUILD/configure" "$BUILD/config.guess" "$BUILD/config.sub" "$BUILD/install-sh" 2>/dev/null || true
+9
View File
@@ -18,6 +18,15 @@
set -uo pipefail set -uo pipefail
TARGET="${CARGO_TARGET_DIR:-$HOME/.cache/alkane-tk-target}" TARGET="${CARGO_TARGET_DIR:-$HOME/.cache/alkane-tk-target}"
REPO="$(cd "$(dirname "$0")/.." && pwd)"
case "$(realpath -m "$TARGET")" in
"$HOME/.cache/alkane-tk-target"|"$REPO/target") ;;
*) echo "clean-old-builds: refusing unexpected target $TARGET" >&2; exit 1 ;;
esac
if [ -L "$TARGET" ]; then
echo "clean-old-builds: refusing symlink target $TARGET" >&2
exit 1
fi
if [ ! -d "$TARGET" ]; then if [ ! -d "$TARGET" ]; then
echo "clean-old-builds: no target dir at $TARGET (nothing to do)" echo "clean-old-builds: no target dir at $TARGET (nothing to do)"
exit 0 exit 0