Install .afw OS bundles on CV1835 over the network

Parse and verify the fixed-order .afw container, add the CV1835 board
module and an SSH transport with the stock update-daemon root stage, a
read-only preflight, a held p1 backup, whole-partition read-back, live
verification and network restore. Add the headless afw CLI and offline
fixtures for good, tampered, wrong-board, truncated, traversal and
oversize bundles.

Co-Authored-By: DeepSeek Harness <noreply@deepseek.com>
This commit is contained in:
2026-11-04 14:31:35 -06:00
co-authored by DeepSeek Harness
parent 3d1fd36811
commit 628c0630a5
16 changed files with 4188 additions and 20 deletions
+611 -18
View File
@@ -1,31 +1,624 @@
// SPDX-License-Identifier: MIT
//! Headless entry point for read-only artifact verification.
//! Headless alkane engine: artifact verification and the network-only `.afw`
//! install path for CV1835.
//!
//! Credentials come only from an environment variable or a file path named on
//! the command line. This program never prints a credential value.
use alkane_artifacts::afw::{verify_afw, VerifiedAfw, VerifyOptions};
use alkane_artifacts::{seed_manifest, verify_file};
use std::path::Path;
use alkane_core::platform;
use alkane_flash::boards::cv1835::Cv1835Plan;
use alkane_flash::install::{
install, restore, verify_live, InstallOptions, InstallOutcome, RestoreOptions,
};
use alkane_flash::preflight::{preflight, PreflightOptions};
use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const DEFAULT_USER: &str = "miner";
const DEFAULT_TIMEOUT: u64 = 240;
struct Opts {
values: BTreeMap<String, String>,
flags: BTreeSet<String>,
positionals: Vec<String>,
}
impl Opts {
fn value(&self, name: &str) -> Option<&str> {
self.values.get(name).map(String::as_str)
}
fn flag(&self, name: &str) -> bool {
self.flags.contains(name)
}
}
fn parse_args(
args: &[String],
values: &[&str],
flags: &[&str],
) -> Result<Opts, Box<dyn std::error::Error>> {
let mut opts = Opts {
values: BTreeMap::new(),
flags: BTreeSet::new(),
positionals: Vec::new(),
};
let mut index = 0;
while index < args.len() {
let arg = &args[index];
if let Some(rest) = arg.strip_prefix("--") {
let (name, inline) = match rest.split_once('=') {
Some((name, value)) => (name, Some(value.to_owned())),
None => (rest, None),
};
if values.contains(&name) {
let value = match inline {
Some(value) => value,
None => {
index += 1;
args.get(index)
.cloned()
.ok_or_else(|| format!("--{name} needs a value"))?
}
};
opts.values.insert(name.to_owned(), value);
} else if flags.contains(&name) {
if inline.is_some() {
return Err(format!("--{name} does not take a value").into());
}
opts.flags.insert(name.to_owned());
} else {
return Err(format!("unknown option --{name}").into());
}
} else {
opts.positionals.push(arg.clone());
}
index += 1;
}
Ok(opts)
}
struct SecretFile {
path: Option<PathBuf>,
temporary: bool,
}
impl Drop for SecretFile {
fn drop(&mut self) {
if self.temporary {
if let Some(path) = &self.path {
let _ = fs::remove_file(path);
}
}
}
}
fn resolve_password(opts: &Opts) -> Result<SecretFile, Box<dyn std::error::Error>> {
if let Some(path) = opts
.value("password-file")
.map(PathBuf::from)
.or_else(|| std::env::var_os("ALKANE_BOARD_PASSWORD_FILE").map(PathBuf::from))
{
if !path.is_file() {
return Err(format!("password file not found: {}", path.display()).into());
}
return Ok(SecretFile {
path: Some(path),
temporary: false,
});
}
if let Some(value) = std::env::var_os("ALKANE_BOARD_PASSWORD") {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
let path =
std::env::temp_dir().join(format!("alkane-cli-pw-{}-{nanos}", std::process::id()));
platform::write_private(&path, value.to_string_lossy().as_bytes())?;
return Ok(SecretFile {
path: Some(path),
temporary: true,
});
}
Ok(SecretFile {
path: None,
temporary: false,
})
}
fn ssh_options(
opts: &Opts,
default_user: &str,
) -> Result<(SshOptions, SecretFile), Box<dyn std::error::Error>> {
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let port = opts
.value("port")
.map(str::parse::<u16>)
.transpose()?
.unwrap_or(22);
let user = opts.value("user").unwrap_or(default_user).to_owned();
let identity_file = opts
.value("identity-file")
.map(PathBuf::from)
.or_else(|| std::env::var_os("ALKANE_BOARD_IDENTITY_FILE").map(PathBuf::from));
let known_hosts = opts.value("known-hosts").map(PathBuf::from);
let root_method = opts
.value("root-method")
.map(|value| RootMethod::parse(value).ok_or_else(|| format!("unknown root method {value}")))
.transpose()?
.unwrap_or(RootMethod::Auto);
let update_daemon_port = opts
.value("update-daemon-port")
.map(str::parse::<u16>)
.transpose()?;
let secret = resolve_password(opts)?;
let options = SshOptions {
host,
port,
user,
identity_file,
password_file: secret.path.clone(),
known_hosts,
root_method,
update_daemon_port,
};
Ok((options, secret))
}
fn load_afw(path: &str, opts: &Opts) -> Result<VerifiedAfw, Box<dyn std::error::Error>> {
let allow_unsigned = opts.flag("allow-unsigned");
let verified = verify_afw(
Path::new(path),
&VerifyOptions {
allow_unsigned,
expect_board: opts.value("expect-board").map(str::to_owned),
},
)?;
if verified.manifest.signature.kind == "unsigned" {
eprintln!("WARNING: UNSIGNED .afw.");
eprintln!(
"SHA-256 proves integrity, not authenticity. Bench use only; site use needs Ed25519."
);
for image in &verified.manifest.images {
eprintln!(
"payload sha256 {} {} {}",
image.sha256, image.name, image.file
);
}
}
Ok(verified)
}
fn print_afw(verified: &VerifiedAfw) {
let manifest = &verified.manifest;
println!("verified .afw");
println!(" archive sha256 {}", verified.archive_sha256);
println!(" manifest sha256 {}", verified.manifest_sha256);
println!(
" board {} arch {} version {}",
manifest.board, manifest.arch, manifest.version
);
println!(
" bootloader {} signature {} marker {} kernel {}",
manifest.bootloader_policy.as_str(),
manifest.signature.kind,
manifest.marker,
manifest.kernel_version
);
println!(
" revisions sdk {} os {} built {}",
&manifest.sdk_revision[..12.min(manifest.sdk_revision.len())],
&manifest.os_revision[..12.min(manifest.os_revision.len())],
manifest.build_date
);
for image in &manifest.images {
println!(
" image {} role {} format {} {} B sha256 {}{}",
image.name,
image.role,
image.format,
image.size,
image.sha256,
if image.install {
format!(" -> {}", image.partition.as_deref().unwrap_or("unassigned"))
} else {
String::new()
}
);
}
for partition in &manifest.partitions {
println!(
" partition {} {} {} B secure={} boot_critical={} write_order={}{}",
partition.name,
partition.device,
partition.size,
partition.secure,
partition.boot_critical,
partition.write_order,
partition
.image
.as_deref()
.map(|image| format!(" image={image}"))
.unwrap_or_default()
);
}
}
fn run_verify(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&["expect-board", "public-key"],
&["allow-unsigned", "json", "quiet"],
)?;
let path = opts
.positionals
.first()
.ok_or("usage: alkane-cli afw verify <file> [--allow-unsigned]")?;
if opts.value("public-key").is_some() {
return Err(
"this build cannot verify Ed25519 in Rust; use ci/check-afw.py --public-key".into(),
);
}
let verified = load_afw(path, &opts)?;
if opts.flag("json") {
println!(
"{}",
serde_json::json!({
"file": path,
"archive_sha256": verified.archive_sha256,
"manifest_sha256": verified.manifest_sha256,
"manifest": verified.manifest,
})
);
} else if !opts.flag("quiet") {
print_afw(&verified);
}
Ok(())
}
fn run_inspect(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, &["expect-board"], &["allow-unsigned"])?;
let path = opts
.positionals
.first()
.ok_or("usage: alkane-cli afw inspect <file> [--allow-unsigned]")?;
let verified = load_afw(path, &opts)?;
print_afw(&verified);
println!("{}", serde_json::to_string_pretty(&verified.manifest)?);
Ok(())
}
fn ssh_values() -> &'static [&'static str] {
&[
"host",
"port",
"user",
"identity-file",
"password-file",
"known-hosts",
"root-method",
"update-daemon-port",
]
}
fn run_plan(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(args, ssh_values(), &["allow-unsigned"])?;
let path = opts
.positionals
.first()
.ok_or("usage: alkane-cli afw plan <file> --host <ip>")?;
let verified = load_afw(path, &opts)?;
let plan = Cv1835Plan::from_afw(&verified)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
let kernel =
String::from_utf8_lossy(&transport.user_command("uname -r", Duration::from_secs(15))?)
.trim()
.to_owned();
let uid = String::from_utf8_lossy(&transport.root_command("id -u", Duration::from_secs(15))?)
.trim()
.to_owned();
let p1_size = String::from_utf8_lossy(&transport.user_command(
"cat /sys/class/block/mmcblk0p1/size 2>/dev/null || true",
Duration::from_secs(15),
)?)
.trim()
.to_owned();
println!("{}", plan.render());
println!(
"current kernel {} uid {} p1 sectors {}",
kernel, uid, p1_size
);
println!(
"root channel {} (transport {}, never serial)",
transport.root_method(),
transport.channel()
);
if let Some(port) = transport.update_daemon_port() {
println!("stock update-daemon port {port} (reached through an SSH local forward)");
}
println!("plan is read-only; no write performed");
Ok(())
}
fn run_preflight(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[ssh_values(), &["held-backup", "expect-board"]].concat(),
&["allow-unsigned", "check-golden", "allow-unknown-source"],
)?;
let path = opts
.positionals
.first()
.ok_or("usage: alkane-cli afw preflight <file> --host <ip>")?;
let verified = load_afw(path, &opts)?;
let plan = Cv1835Plan::from_afw(&verified)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
let held_backup = opts.value("held-backup").map(PathBuf::from);
let report = preflight(
&plan,
&mut transport,
&PreflightOptions {
host: opts.value("host").unwrap_or(""),
held_backup: held_backup.as_deref(),
check_golden: opts.flag("check-golden"),
allow_unknown_source: opts.flag("allow-unknown-source"),
},
)?;
print!("{}", report.render());
if !report.ok() {
return Err("preflight failed; do not write".into());
}
Ok(())
}
fn run_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[
ssh_values(),
&["held-backup", "backup-dir", "confirm", "expect-board"],
]
.concat(),
&[
"allow-unsigned",
"allow-unknown-source",
"check-golden",
"dry-run",
"no-reboot",
],
)?;
let path = opts
.positionals
.first()
.ok_or("usage: alkane-cli afw install <file> --host <ip> --dry-run|--confirm FLASH")?;
let verified = load_afw(path, &opts)?;
let plan = Cv1835Plan::from_afw(&verified)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
let backup_dir = opts
.value("backup-dir")
.map(PathBuf::from)
.unwrap_or_else(|| platform::config_path("backups"));
let install_options = InstallOptions {
dry_run: opts.flag("dry-run"),
confirm: opts.value("confirm").map(str::to_owned),
no_reboot: opts.flag("no-reboot"),
backup_dir,
held_backup: opts.value("held-backup").map(PathBuf::from),
allow_unknown_source: opts.flag("allow-unknown-source"),
check_golden: opts.flag("check-golden"),
};
println!("{}", plan.render());
match install(
&verified,
&plan,
&mut transport,
&install_options,
opts.value("host").unwrap_or(""),
)? {
InstallOutcome::DryRun(report) => {
print!("{}", report.render());
println!("DRY RUN: no board write was performed.");
println!("Re-run with --confirm FLASH to write p1.");
}
InstallOutcome::Installed(receipt) => {
println!("held stock p1 {}", receipt.backup_path.display());
println!("held p1 md5 {}", receipt.backup_md5);
println!("held p1 sha256 {}", receipt.backup_sha256);
println!("wrote p1 image md5 {}", receipt.image_md5);
println!("whole-partition read-back matched before reboot");
if receipt.rebooted {
println!("reboot issued; an SSH drop here is the success signature");
println!(
"next: alkane-cli afw verify-live --host {} --timeout 300",
opts.value("host").unwrap_or("")
);
} else {
println!(
"reboot skipped (--no-reboot); verify-live will fail until the board reboots"
);
}
}
}
Ok(())
}
fn run_verify_live(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[
ssh_values(),
&["marker", "kernel-version", "timeout", "expect-board"],
]
.concat(),
&["allow-unsigned"],
)?;
let (marker, kernel_version) = if let Some(path) = opts.positionals.first() {
let verified = load_afw(path, &opts)?;
let plan = Cv1835Plan::from_afw(&verified)?;
(
opts.value("marker").unwrap_or(&plan.marker).to_owned(),
opts.value("kernel-version")
.unwrap_or(&plan.kernel_version)
.to_owned(),
)
} else {
(
opts.value("marker").unwrap_or("CVBOOT").to_owned(),
opts.value("kernel-version").unwrap_or("").to_owned(),
)
};
let host = opts.value("host").ok_or("--host is required")?.to_owned();
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let timeout = opts
.value("timeout")
.map(str::parse::<u64>)
.transpose()?
.unwrap_or(DEFAULT_TIMEOUT);
let report = verify_live(
&host,
&marker,
&kernel_version,
Duration::from_secs(timeout),
&ssh,
);
print!("{}", report.render());
if !report.ok() {
return Err("live verification failed after two channels disagreed".into());
}
println!("also confirm the DHCP lease for the board before calling it proven");
Ok(())
}
fn run_restore(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let opts = parse_args(
args,
&[ssh_values(), &["held-backup", "backup-dir", "confirm"]].concat(),
&["no-reboot"],
)?;
let (ssh, _secret) = ssh_options(&opts, DEFAULT_USER)?;
let mut transport = SshTransport::connect(ssh, true)?;
let backup = if let Some(path) = opts.value("held-backup") {
PathBuf::from(path)
} else {
let dir = opts
.value("backup-dir")
.map(PathBuf::from)
.unwrap_or_else(|| platform::config_path("backups"));
latest_backup(&dir).ok_or_else(|| {
format!(
"no held backup in {}; pass --held-backup <p1.img>",
dir.display()
)
})?
};
let receipt = restore(
&backup,
&mut transport,
&RestoreOptions {
confirm: opts.value("confirm").map(str::to_owned),
no_reboot: opts.flag("no-reboot"),
},
)?;
println!("restored stock p1 from {}", receipt.backup_path.display());
println!("image md5 {}", receipt.image_md5);
println!("whole-partition read-back matched before reboot");
if receipt.rebooted {
println!("reboot issued; the board should return to its held stock OS");
}
Ok(())
}
fn latest_backup(dir: &Path) -> Option<PathBuf> {
let mut entries: Vec<PathBuf> = fs::read_dir(dir)
.ok()?
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| {
path.extension() == Some(std::ffi::OsStr::new("img"))
&& path
.file_name()
.map(|name| name.to_string_lossy().starts_with("p1-"))
.unwrap_or(false)
})
.collect();
entries.sort();
entries.pop()
}
fn run_afw(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
let subcommand = args.first().ok_or(
"usage: alkane-cli afw <verify|inspect|plan|preflight|install|verify-live|restore>",
)?;
let rest = &args[1..];
match subcommand.as_str() {
"verify" => run_verify(rest),
"inspect" => run_inspect(rest),
"plan" => run_plan(rest),
"preflight" => run_preflight(rest),
"install" => run_install(rest),
"verify-live" => run_verify_live(rest),
"restore" => run_restore(rest),
other => Err(format!("unknown afw subcommand {other}").into()),
}
}
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());
let args: Vec<String> = std::env::args().skip(1).collect();
let command = args.first().ok_or(
"usage: alkane-cli verify-artifact <manifest-path> <local-file> | alkane-cli afw <command> ...",
)?;
if command == "verify-artifact" {
if args.len() != 3 {
return Err("usage: alkane-cli verify-artifact <manifest-path> <local-file>".into());
}
let record = seed_manifest()?
.into_iter()
.find(|item| item.path == Path::new(&args[1]))
.ok_or("artifact path is absent from the seed manifest")?;
let verified = verify_file(Path::new(&args[2]), &record)?;
println!(
"verified {} {} {} bytes",
verified.record().family,
verified.record().format,
verified.record().size_bytes
);
return Ok(());
}
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(())
if command == "afw" {
return run_afw(&args[1..]);
}
if command == "-h" || command == "--help" || command == "help" {
println!(
"usage:\n alkane-cli verify-artifact <manifest-path> <local-file>\n \
alkane-cli afw verify <file> [--allow-unsigned] [--expect-board <board>]\n \
alkane-cli afw inspect <file> [--allow-unsigned]\n \
alkane-cli afw plan <file> --host <ip> [ssh options]\n \
alkane-cli afw preflight <file> --host <ip> [ssh options] [--held-backup <p1.img>]\n \
alkane-cli afw install <file> --host <ip> --dry-run [ssh options]\n \
alkane-cli afw install <file> --host <ip> --confirm FLASH [ssh options]\n \
alkane-cli afw verify-live [<file>] --host <ip> [--timeout <secs>] [ssh options]\n \
alkane-cli afw restore --host <ip> --held-backup <p1.img> --confirm FLASH [ssh options]\n\
\nssh options: --user --port --identity-file --password-file --known-hosts \
--root-method auto|direct|update-daemon|rroot --update-daemon-port\n\
credentials: ALKANE_BOARD_PASSWORD or ALKANE_BOARD_PASSWORD_FILE; \
ALKANE_BOARD_IDENTITY_FILE"
);
return Ok(());
}
Err(format!("unknown command {command}").into())
}
fn main() {
if let Err(error) = run() {
eprintln!("artifact verification failed: {error}");
eprintln!("alkane-cli: {error}");
std::process::exit(1);
}
}