diff --git a/.gitea/workflows/next.yml b/.gitea/workflows/next.yml index c98483df..db8b05f9 100644 --- a/.gitea/workflows/next.yml +++ b/.gitea/workflows/next.yml @@ -31,7 +31,7 @@ jobs: bash scripts/build-wx-linux.sh fi - name: Build release candidate - run: cargo build --release -p alkane-gui --offline + run: cargo build --release -p alkane-gui -p alkane-artifacts -p alkane-cli --offline - name: Select candidate version id: version run: bash ci/compute-rc-version.sh >> "$GITHUB_OUTPUT" diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 5533ccff..c9ff6dab 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -76,6 +76,7 @@ jobs: - name: Unit tests run: | cargo test -p alkane-gui --offline + cargo test -p alkane-artifacts -p alkane-cli --offline - name: Load previous main benchmark measurement env: @@ -88,7 +89,7 @@ jobs: # #1) while keeping the step a hard gate: pipefail preserves cargo's exit # code (each bench asserts its own absolute ceiling) even through tee. set -o pipefail - cargo test -p alkane-gui --release --offline -- --ignored --nocapture bench_ \ + cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ \ | tee bench-current.txt - name: Record private benchmark history diff --git a/.gitea/workflows/verify.yml b/.gitea/workflows/verify.yml index 70585d37..26c14f49 100644 --- a/.gitea/workflows/verify.yml +++ b/.gitea/workflows/verify.yml @@ -49,10 +49,12 @@ jobs: run: cargo build --release -p alkane-gui --offline - name: Unit tests - run: cargo test -p alkane-gui --offline + run: | + cargo test -p alkane-gui --offline + cargo test -p alkane-artifacts -p alkane-cli --offline - name: Microbenchmarks - run: cargo test -p alkane-gui --release --offline -- --ignored --nocapture bench_ + run: cargo test -p alkane-gui -p alkane-artifacts --release --offline -- --ignored --nocapture bench_ - name: Headless UI self-test run: | diff --git a/Cargo.lock b/Cargo.lock index 6a2ca8e1..be0d342d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -40,12 +40,15 @@ name = "alkane-artifacts" version = "0.1.0" dependencies = [ "alkane-core", + "sha2", + "thiserror", ] [[package]] name = "alkane-cli" version = "0.1.0" dependencies = [ + "alkane-artifacts", "alkane-core", ] diff --git a/ci/bench-coverage.sh b/ci/bench-coverage.sh index b6df4e4c..14f40408 100644 --- a/ci/bench-coverage.sh +++ b/ci/bench-coverage.sh @@ -3,6 +3,6 @@ set -euo pipefail export WX_RS_WXCONFIG="${WX_RS_WXCONFIG:-$HOME/.cache/wx-3.3.3-linux/bin/wx-config}" cargo llvm-cov clean --workspace -cargo llvm-cov --no-report --offline --release -p alkane-gui -- \ +cargo llvm-cov --no-report --offline --release -p alkane-gui -p alkane-artifacts -- \ --ignored --nocapture bench_ cargo llvm-cov report --release --ignore-filename-regex '(thirdparty|vendor)/' "$@" diff --git a/crates/alkane-artifacts/Cargo.toml b/crates/alkane-artifacts/Cargo.toml index 62307ec1..6b9d5412 100644 --- a/crates/alkane-artifacts/Cargo.toml +++ b/crates/alkane-artifacts/Cargo.toml @@ -6,3 +6,5 @@ license.workspace = true [dependencies] alkane-core = { path = "../alkane-core" } +sha2.workspace = true +thiserror.workspace = true diff --git a/crates/alkane-artifacts/src/lib.rs b/crates/alkane-artifacts/src/lib.rs index febec870..ef72dd1d 100644 --- a/crates/alkane-artifacts/src/lib.rs +++ b/crates/alkane-artifacts/src/lib.rs @@ -1 +1,241 @@ -// alkane-artifacts +// SPDX-License-Identifier: MIT +//! Verify local firmware artifacts before an install path consumes them. + +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::path::{Component, Path, PathBuf}; +use thiserror::Error; + +const SEED: &str = include_str!("../data/manifest-seed.csv"); +const HEADER: &str = "sha256,size_bytes,path,family,format,applicability"; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ArtifactRecord { + pub sha256: String, + pub size_bytes: u64, + pub path: PathBuf, + pub family: String, + pub format: String, + pub applicability: String, +} + +#[derive(Debug, Error)] +pub enum VerifyError { + #[error("artifact I/O: {0}")] + Io(#[from] std::io::Error), + #[error("manifest line {0} is invalid")] + Manifest(usize), + #[error("artifact size differs from manifest")] + Size, + #[error("artifact signature does not match its declared format")] + Signature, + #[error("artifact SHA-256 differs from manifest")] + Digest, + #[error("artifact format is not recognized")] + UnsupportedFormat, +} + +/// A verified, rewound descriptor. Consumers should read this descriptor +/// directly instead of reopening the path after verification. +pub struct VerifiedArtifact { + file: File, + record: ArtifactRecord, +} + +impl VerifiedArtifact { + pub fn record(&self) -> &ArtifactRecord { + &self.record + } + + pub fn reader(&mut self) -> &mut File { + &mut self.file + } +} + +pub fn seed_manifest() -> Result, VerifyError> { + parse_manifest(SEED) +} + +pub fn parse_manifest(text: &str) -> Result, VerifyError> { + let mut lines = text.lines(); + if lines.next() != Some(HEADER) { + return Err(VerifyError::Manifest(1)); + } + let mut paths = HashSet::new(); + let mut records = Vec::new(); + for (line_number, line) in lines.enumerate() { + let line_number = line_number + 2; + let parts: Vec<_> = line.splitn(6, ',').collect(); + if parts.len() != 6 || parts.iter().any(|part| part.trim().is_empty()) { + return Err(VerifyError::Manifest(line_number)); + } + let digest = parts[0]; + let path = PathBuf::from(parts[2]); + if digest.len() != 64 + || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) + || !path + .components() + .all(|part| matches!(part, Component::Normal(_))) + || !paths.insert(path.clone()) + { + return Err(VerifyError::Manifest(line_number)); + } + let size_bytes = parts[1] + .parse::() + .map_err(|_| VerifyError::Manifest(line_number))?; + if size_bytes == 0 { + return Err(VerifyError::Manifest(line_number)); + } + records.push(ArtifactRecord { + sha256: digest.to_ascii_lowercase(), + size_bytes, + path, + family: parts[3].to_owned(), + format: parts[4].to_owned(), + applicability: parts[5].to_owned(), + }); + } + if records.is_empty() { + return Err(VerifyError::Manifest(1)); + } + Ok(records) +} + +fn signature_matches(format: &str, first: &[u8]) -> Result { + let prefix: &[u8] = match format { + "IMAGEWTY-SD" | "update-zip" | "zip-installer" => b"PK\x03\x04", + "ubifs" => b"\x31\x18\x10\x06", + "swu" => b"070702", + "wm-package-0x9a5ba57c" => b"\x7c\xa5\x5b\x9a", + "bmu" => b"\x26\x01", + "bin-AES-container" => b"\x3f\x0a\x64\xae", + _ => return Err(VerifyError::UnsupportedFormat), + }; + Ok(first.starts_with(prefix)) +} + +pub fn verify_file(path: &Path, record: &ArtifactRecord) -> Result { + let mut file = File::open(path)?; + if file.metadata()?.len() != record.size_bytes { + return Err(VerifyError::Size); + } + let mut first = [0_u8; 16]; + let length = file.read(&mut first)?; + if !signature_matches(&record.format, &first[..length])? { + return Err(VerifyError::Signature); + } + file.seek(SeekFrom::Start(0))?; + let mut hasher = Sha256::new(); + let mut buffer = [0_u8; 64 * 1024]; + let mut read_bytes = 0_u64; + loop { + let length = file.read(&mut buffer)?; + if length == 0 { + break; + } + read_bytes += length as u64; + hasher.update(&buffer[..length]); + } + if read_bytes != record.size_bytes { + return Err(VerifyError::Size); + } + let digest = hasher.finalize(); + let actual: String = digest.iter().map(|byte| format!("{byte:02x}")).collect(); + if actual != record.sha256 { + return Err(VerifyError::Digest); + } + file.seek(SeekFrom::Start(0))?; + Ok(VerifiedArtifact { + file, + record: record.clone(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + #[test] + fn manifest_has_unique_safe_records() { + let records = seed_manifest().unwrap(); + assert_eq!(records.len(), 14); + let traversal = format!("{HEADER}\n{},12,../escape,bin,bmu,all\n", "0".repeat(64)); + assert!(matches!( + parse_manifest(&traversal), + Err(VerifyError::Manifest(2)) + )); + } + + #[test] + fn checks_size_signature_and_digest_before_consumption() { + let path = + std::env::temp_dir().join(format!("alkane-artifact-test-{}", std::process::id())); + let bytes = b"PK\x03\x04example"; + let mut file = File::create(&path).unwrap(); + file.write_all(bytes).unwrap(); + drop(file); + let mut record = ArtifactRecord { + sha256: Sha256::digest(bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(), + size_bytes: bytes.len() as u64, + path: PathBuf::from("fixture.zip"), + family: "test".to_owned(), + format: "update-zip".to_owned(), + applicability: "test".to_owned(), + }; + let mut verified = verify_file(&path, &record).unwrap(); + let mut replay = Vec::new(); + verified.reader().read_to_end(&mut replay).unwrap(); + assert_eq!(replay, bytes); + record.size_bytes += 1; + assert!(matches!( + verify_file(&path, &record), + Err(VerifyError::Size) + )); + record.size_bytes -= 1; + record.format = "ubifs".to_owned(); + assert!(matches!( + verify_file(&path, &record), + Err(VerifyError::Signature) + )); + record.format = "update-zip".to_owned(); + record.sha256 = "0".repeat(64); + assert!(matches!( + verify_file(&path, &record), + Err(VerifyError::Digest) + )); + std::fs::remove_file(path).unwrap(); + } + + #[test] + #[ignore = "microbenchmark"] + fn bench_verify_artifact() { + let path = + std::env::temp_dir().join(format!("alkane-artifact-bench-{}", std::process::id())); + let mut bytes = vec![0x42_u8; 65_536]; + bytes[..4].copy_from_slice(b"PK\x03\x04"); + std::fs::write(&path, &bytes).unwrap(); + let record = ArtifactRecord { + sha256: Sha256::digest(&bytes) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect(), + size_bytes: bytes.len() as u64, + path: PathBuf::from("bench.zip"), + family: "test".to_owned(), + format: "update-zip".to_owned(), + applicability: "test".to_owned(), + }; + let started = std::time::Instant::now(); + for _ in 0..100 { + std::hint::black_box(verify_file(&path, &record).unwrap()); + } + println!("bench_verify_artifact: {:?}", started.elapsed() / 100); + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/alkane-cli/Cargo.toml b/crates/alkane-cli/Cargo.toml index 75584240..64a6fc75 100644 --- a/crates/alkane-cli/Cargo.toml +++ b/crates/alkane-cli/Cargo.toml @@ -6,3 +6,4 @@ license.workspace = true [dependencies] alkane-core = { path = "../alkane-core" } +alkane-artifacts = { path = "../alkane-artifacts" } diff --git a/crates/alkane-cli/src/main.rs b/crates/alkane-cli/src/main.rs index 56e67f69..039c54bf 100644 --- a/crates/alkane-cli/src/main.rs +++ b/crates/alkane-cli/src/main.rs @@ -1,4 +1,31 @@ -//! Headless driver over the same engine the GUI uses. +// SPDX-License-Identifier: MIT +//! Headless entry point for read-only artifact verification. + +use alkane_artifacts::{seed_manifest, verify_file}; +use std::path::Path; + +fn run() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + if args.len() != 4 || args[1] != "verify-artifact" { + return Err("usage: alkane-cli verify-artifact ".into()); + } + let record = seed_manifest()? + .into_iter() + .find(|item| item.path == Path::new(&args[2])) + .ok_or("artifact path is absent from the seed manifest")?; + let verified = verify_file(Path::new(&args[3]), &record)?; + println!( + "verified {} {} {} bytes", + verified.record().family, + verified.record().format, + verified.record().size_bytes + ); + Ok(()) +} + fn main() { - println!("alkane-toolkit-cli: scaffold"); + if let Err(error) = run() { + eprintln!("artifact verification failed: {error}"); + std::process::exit(1); + } }