use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
use anyhow::{Context, Result, bail};
use super::transfer;
use crate::serve::client::{self, Hello, StartReason};
use crate::serve::endpoint;
use crate::serve::machines::install;
use crate::serve::proto::Version;
pub const HELLO: &str = concat!(
env!("CARGO_PKG_VERSION"),
" ",
env!("DEVSANDBOX_BUILD_GIT"),
" ",
env!("DEVSANDBOX_BUILD_KIND"),
" ",
env!("DEVSANDBOX_BUILD_PLATFORM")
);
pub fn hello_of(hub: bool, fleet: Option<&str>) -> &'static str {
static SAID: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
let role = if hub { "hub" } else { "member" };
let mut hello = format!("{HELLO} {role} {}", fleet.unwrap_or("-"));
if hello.len() > u8::MAX as usize {
hello = format!("{HELLO} {role} -");
}
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if let Some(s) = said.iter().find(|s| **s == hello) {
return s;
}
let s: &'static str = Box::leak(hello.into_boxed_str());
said.push(s);
s
}
pub fn hello_for(hub: &super::member::Hub, own: Option<&str>) -> &'static str {
use super::member::Hub;
match hub {
Hub::None => hello_of(false, None),
Hub::This => hello_of(true, own),
Hub::Other(name) => hello_of(false, Some(name)),
}
}
pub fn is_hub(hello: &str) -> bool {
hello.split_whitespace().nth(4) == Some("hub")
}
pub fn hub_of(hello: &str) -> Option<&str> {
hello.split_whitespace().nth(5).filter(|w| *w != "-")
}
pub fn same_fleet(peer: &str, ours: &str, theirs: &str) -> Result<(), String> {
match (hub_of(ours), hub_of(theirs)) {
(Some(ours), Some(theirs)) if ours != theirs => {
Err(format!("`{peer}` is in `{theirs}`'s fleet, this host in `{ours}`'s: a link between two fleets is refused"))
}
_ => Ok(()),
}
}
fn build_words(hello: &str) -> impl Iterator<Item = &str> {
hello.split_whitespace().take(4)
}
#[cfg(test)]
pub const PLATFORM: &str = env!("DEVSANDBOX_BUILD_PLATFORM");
pub const BINARY_KIND: &str = "binary";
pub const BINARY_LIMIT: u64 = 256 << 20;
pub fn platform_of(hello: &str) -> &str {
hello.split_whitespace().nth(3).unwrap_or("unknown")
}
pub const REPO: &str = "Nemikolh/devsandboxes";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Build {
pub semver: String,
pub git: String,
pub published: bool,
}
impl Build {
pub fn parse(hello: &str) -> Build {
let mut words = hello.split_whitespace();
let semver = words.next().unwrap_or("").to_string();
let git = words.next().unwrap_or("unknown").to_string();
let published = words.next() == Some("published");
Build { semver, git, published }
}
pub fn label(&self) -> String {
format!("{} ({}, {})", self.semver, if self.published { "published" } else { "dev" }, self.git)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
Same,
Download { build: Build },
Receive,
Stop(String),
}
pub fn decide(ours: &Build, hub: &Build, our_platform: &str, hub_platform: &str, dev_builds: bool) -> Decision {
if ours == hub {
Decision::Same
} else if hub.published {
match platform_target(our_platform) {
Some(_) => Decision::Download { build: hub.clone() },
None => Decision::Stop(format!("published build: no devsandbox release is built for {our_platform} (the hub runs {})", hub.label())),
}
} else if hub_platform != our_platform {
Decision::Stop(format!("dev build: can't run on {our_platform} (the hub runs {} for {hub_platform})", hub.label()))
} else if !dev_builds {
Decision::Stop(format!(
"dev build: not taken (`dev-builds = true` in member.toml or `devsandbox machine trust full` takes it; the hub runs {})",
hub.label()
))
} else {
Decision::Receive
}
}
pub fn hub_pushes(hub: &str, worker: &str) -> bool {
decide(&Build::parse(worker), &Build::parse(hub), platform_of(worker), platform_of(hub), true) == Decision::Receive
}
pub fn push(socket: &Path, binary: &Path) -> Result<()> {
let open = || std::fs::File::open(binary).with_context(|| format!("cannot read {}", binary.display()));
let (size, sha256) = transfer::digest(open()?).with_context(|| format!("cannot read {}", binary.display()))?;
let header = transfer::Header { kind: BINARY_KIND.into(), name: "devsandbox".into(), size, sha256, to: None, repo: None, refs: None };
let stream = super::link::connect(socket, crate::devsbd::proto::channel::TRANSFER).with_context(|| format!("cannot connect to {}", socket.display()))?;
transfer::send(stream, &header, open()?)
}
pub fn release_target(os: &str, arch: &str) -> Option<&'static str> {
match (os, arch) {
("linux", "x86_64") => Some("x86_64-unknown-linux-musl"),
("linux", "aarch64") => Some("aarch64-unknown-linux-musl"),
("macos", "aarch64") => Some("aarch64-apple-darwin"),
_ => None,
}
}
pub fn platform_target(platform: &str) -> Option<&'static str> {
let (os, arch) = platform.split_once('/')?;
release_target(os, arch)
}
pub fn asset_name(version: &str, target: &str) -> String {
format!("devsandbox-{version}-{target}.tar.gz")
}
pub fn release_url(version: &str, file: &str) -> Result<String> {
let ok = !version.is_empty() && version.bytes().all(|b| b.is_ascii_alphanumeric() || b".-+".contains(&b));
if !ok {
bail!("`{version}` isn't a version");
}
Ok(format!("https://github.com/{REPO}/releases/download/v{version}/{file}"))
}
pub const SUMS: &str = "SHA256SUMS";
pub const SUMS_SIG: &str = "SHA256SUMS.sig";
pub const RELEASE_KEY: [u8; 32] = parse_key(include_str!("../../../release-signing.pub"));
const fn parse_key(text: &str) -> [u8; 32] {
const fn digit(c: u8) -> u8 {
match c {
b'0'..=b'9' => c - b'0',
b'a'..=b'f' => c - b'a' + 10,
_ => panic!("release-signing.pub: not lowercase hex"),
}
}
let bytes = text.as_bytes();
let len = if !bytes.is_empty() && bytes[bytes.len() - 1] == b'\n' { bytes.len() - 1 } else { bytes.len() };
if len != 64 {
panic!("release-signing.pub: not 64 hex digits");
}
let mut out = [0u8; 32];
let mut i = 0;
while i < 32 {
out[i] = digit(bytes[2 * i]) << 4 | digit(bytes[2 * i + 1]);
i += 1;
}
out
}
pub fn verify_sums(sums: &[u8], sig: &[u8], key: &[u8; 32]) -> Result<()> {
let Ok(sig) = <[u8; 64]>::try_from(sig) else {
bail!("{SUMS_SIG} is {} bytes, not a 64-byte ed25519 signature", sig.len());
};
let key = ed25519_dalek::VerifyingKey::from_bytes(key).map_err(|_| anyhow::anyhow!("the release key isn't an ed25519 public key"))?;
key.verify_strict(sums, &ed25519_dalek::Signature::from_bytes(&sig))
.map_err(|_| anyhow::anyhow!("{SUMS}'s signature doesn't verify against the release key"))
}
pub fn sum_of(sums: &[u8], name: &str) -> Result<[u8; 32]> {
let sums = std::str::from_utf8(sums).map_err(|_| anyhow::anyhow!("{SUMS} isn't text"))?;
let mut found = None;
for (n, line) in sums.lines().enumerate().filter(|(_, l)| !l.is_empty()) {
let bad = || anyhow::anyhow!("{SUMS} line {} isn't `<sha256> <name>`", n + 1);
let (hex, file) = line.split_once(' ').ok_or_else(bad)?;
let file = file.strip_prefix(' ').or_else(|| file.strip_prefix('*')).ok_or_else(bad)?;
let mut sum = [0u8; 32];
if hex.len() != 64 || hex::decode_to_slice(hex, &mut sum).is_err() {
return Err(bad());
}
if file == name && found.replace(sum).is_some() {
bail!("{SUMS} lists {name} more than once");
}
}
found.with_context(|| format!("{SUMS} doesn't list {name}"))
}
fn check_sum(archive: &Path, name: &str, want: &[u8; 32]) -> Result<()> {
let file = std::fs::File::open(archive).with_context(|| format!("cannot read {}", archive.display()))?;
let (_, got) = transfer::digest(file).with_context(|| format!("cannot read {}", archive.display()))?;
if got != hex::encode(want) {
bail!("{name}'s sha256 is {got}, not {SUMS}'s {}", hex::encode(want));
}
Ok(())
}
pub trait Steps: Send + Sync {
fn download(&self, url: &str, out: &Path) -> Result<()>;
fn unpack(&self, archive: &Path, into: &Path) -> Result<PathBuf>;
fn release_key(&self) -> [u8; 32];
fn build(&self, binary: &Path) -> Result<String>;
fn dest(&self) -> Result<PathBuf>;
fn install(&self, binary: &Path, dest: &Path) -> Result<()>;
fn handoff(&self) -> Result<()>;
}
pub fn update(steps: &dyn Steps, hub: &Build, os: &str, arch: &str, scratch: &Path) -> Result<()> {
let target = release_target(os, arch).with_context(|| format!("no devsandbox release is built for {os}/{arch}"))?;
let name = asset_name(&hub.semver, target);
let dir = scratch_dir(scratch)?;
let installed = (|| {
let binary = fetch_verified(steps, &hub.semver, &name, &dir)?;
check_release(steps, &binary, hub, "the downloaded binary")?;
let dest = steps.dest()?;
steps.install(&binary, &dest)?;
check_release(steps, &dest, hub, "the installed binary")
})();
let _ = std::fs::remove_dir_all(&dir);
installed?;
steps.handoff().context("cannot hand this daemon off to it")
}
pub fn install_received(steps: &dyn Steps, binary: &Path, hub: &str) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(binary, std::fs::Permissions::from_mode(0o755))
.with_context(|| format!("cannot make {} executable", binary.display()))?;
check_build(steps, binary, hub, "the hub's binary")?;
let dest = steps.dest()?;
steps.install(binary, &dest)?;
check_build(steps, &dest, hub, "the installed binary")?;
steps.handoff().context("cannot hand this daemon off to it")
}
fn fetch_verified(steps: &dyn Steps, version: &str, name: &str, dir: &Path) -> Result<PathBuf> {
let get = |file: &str| -> Result<PathBuf> {
let url = release_url(version, file)?;
let out = dir.join(file);
steps.download(&url, &out).with_context(|| format!("cannot download {url}"))?;
Ok(out)
};
let read = |path: &Path| std::fs::read(path).with_context(|| format!("cannot read {}", path.display()));
let sums = read(&get(SUMS)?)?;
let sig = read(&get(SUMS_SIG)?)?;
verify_sums(&sums, &sig, &steps.release_key()).with_context(|| format!("release v{version} isn't signed by the release key"))?;
let want = sum_of(&sums, name).with_context(|| format!("release v{version}'s checksums"))?;
let archive = get(name)?;
check_sum(&archive, name, &want)?;
steps.unpack(&archive, dir)
}
fn check_build(steps: &dyn Steps, binary: &Path, want: &str, what: &str) -> Result<()> {
let got = steps.build(binary).with_context(|| format!("{what} ({}) doesn't run", binary.display()))?;
if !build_words(&got).eq(build_words(want)) {
bail!("{what} ({}) reports {:?}, not {want:?}", binary.display(), got.trim());
}
Ok(())
}
fn check_release(steps: &dyn Steps, binary: &Path, want: &Build, what: &str) -> Result<()> {
let got = steps.build(binary).with_context(|| format!("{what} ({}) doesn't run", binary.display()))?;
let got = Build::parse(&got);
if got != *want {
bail!("{what} ({}) is devsandbox {}, not the hub's {}", binary.display(), got.label(), want.label());
}
Ok(())
}
pub fn scratch_dir(parent: &Path) -> Result<PathBuf> {
use std::os::unix::fs::DirBuilderExt;
static SEQ: AtomicU32 = AtomicU32::new(0);
let dir = parent.join(format!("devsandbox-update-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&dir);
std::fs::DirBuilder::new().mode(0o700).create(&dir).with_context(|| format!("cannot create {}", dir.display()))?;
Ok(dir)
}
pub const DOWNLOAD_MAX_TIME: &str = "600";
pub fn curl_argv(url: &str, out: &Path) -> Vec<OsString> {
let mut argv: Vec<OsString> = [
"curl",
"--fail",
"--location",
"--proto",
"=https",
"--proto-redir",
"=https",
"--tlsv1.2",
"--silent",
"--show-error",
"--connect-timeout",
"15",
"--speed-limit",
"1",
"--speed-time",
"30",
"--max-time",
DOWNLOAD_MAX_TIME,
"-o",
]
.map(OsString::from)
.into();
argv.push(out.into());
argv.push(url.into());
argv
}
pub struct Release {
pub socket_dir: PathBuf,
}
impl Steps for Release {
fn download(&self, url: &str, out: &Path) -> Result<()> {
run(&curl_argv(url, out)).map(drop)
}
fn unpack(&self, archive: &Path, into: &Path) -> Result<PathBuf> {
let unpack: Vec<OsString> = vec!["tar".into(), "-xzf".into(), archive.into(), "-C".into(), into.into(), "devsandbox".into()];
run(&unpack)?;
let binary = into.join("devsandbox");
if !binary.is_file() {
bail!("the archive has no devsandbox binary");
}
Ok(binary)
}
fn release_key(&self) -> [u8; 32] {
RELEASE_KEY
}
fn build(&self, binary: &Path) -> Result<String> {
Ok(run(&[binary.into(), "fleet-hello".into()])?.trim().to_string())
}
fn dest(&self) -> Result<PathBuf> {
let exe = crate::exe::devsandbox().context("cannot locate this devsandbox binary")?;
if exe.to_string_lossy().ends_with(" (deleted)") {
bail!("this daemon's binary {} is gone", exe.display());
}
Ok(exe)
}
fn install(&self, binary: &Path, dest: &Path) -> Result<()> {
install::install_local(dest, binary).map(drop)
}
fn handoff(&self) -> Result<()> {
let mut stream = endpoint::connect(&self.socket_dir).context("cannot connect to this daemon")?;
stream.set_read_timeout(Some(client::START_TIMEOUT)).context("cannot set a read timeout")?;
match client::hello_with(&mut stream, &Version::current(), "fleet-update", true)? {
Hello::Handoff => crate::serve::install::lazy_start(&self.socket_dir, StartReason::Handoff),
Hello::Ready(_) => bail!("the daemon refused the forced handoff"),
Hello::Closed => bail!("the daemon closed the connection before answering"),
}
}
}
fn run(argv: &[OsString]) -> Result<String> {
let (program, args) = argv.split_first().context("empty argv")?;
let name = program.to_string_lossy();
let out = Command::new(program)
.args(args)
.stdin(Stdio::null())
.output()
.with_context(|| format!("cannot run {name}"))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr);
match stderr.lines().rev().find(|l| !l.trim().is_empty()) {
Some(line) => bail!("{name}: {}", line.trim()),
None => bail!("{name} exited with {}", out.status),
}
}
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
#[cfg(test)]
pub(crate) mod tests {
use std::sync::Mutex;
use super::*;
fn build(semver: &str, git: &str, published: bool) -> Build {
Build { semver: semver.into(), git: git.into(), published }
}
#[test]
fn hellos_parse() {
assert_eq!(Build::parse("0.7.0 1a2b3c published"), build("0.7.0", "1a2b3c", true));
assert_eq!(Build::parse("0.7.0 1a2b3c dev"), build("0.7.0", "1a2b3c", false));
assert_eq!(Build::parse("0.7.0"), build("0.7.0", "unknown", false));
assert_eq!(Build::parse(""), build("", "unknown", false));
let ours = Build::parse(HELLO);
assert_eq!(ours.semver, env!("CARGO_PKG_VERSION"));
assert_eq!(Build::parse(HELLO), ours);
assert!(HELLO.len() <= u8::MAX as usize, "fits a `Hello` hash");
assert_eq!(platform_of(HELLO), PLATFORM);
assert_eq!(PLATFORM, format!("{}/{}", std::env::consts::OS, std::env::consts::ARCH));
assert_eq!(platform_of("0.7.0 1a2b dev"), "unknown");
assert_eq!(Build::parse("0.7.0 1a2b dev linux/x86_64"), build("0.7.0", "1a2b", false), "the platform isn't the build");
assert_eq!(build("0.7.0", "1a2b", true).label(), "0.7.0 (published, 1a2b)");
assert_eq!(hello_of(true, Some("box")), format!("{HELLO} hub box"));
assert_eq!(hello_of(false, Some("box")), format!("{HELLO} member box"));
assert_eq!(hello_of(false, None), format!("{HELLO} member -"));
assert!(std::ptr::eq(hello_of(false, Some("box")), hello_of(false, Some("box"))), "leaked once");
assert!(hello_of(true, Some("box")).len() <= u8::MAX as usize, "fits a `Hello` hash");
assert_eq!(hello_of(true, Some(&"x".repeat(250))), format!("{HELLO} hub -"), "too long a name isn't said");
assert!(is_hub(hello_of(true, None)) && !is_hub(hello_of(false, Some("hub"))));
assert!(!is_hub(HELLO), "a hello without the flag never says hub");
assert!(!is_hub("0.7.0 1a2b dev hub"), "the fifth word, not any");
assert_eq!((Build::parse(hello_of(true, None)), platform_of(hello_of(false, None))), (ours, PLATFORM));
assert_eq!((hub_of(hello_of(true, Some("k"))), hub_of(hello_of(false, Some("k")))), (Some("k"), Some("k")));
assert_eq!((hub_of(hello_of(false, None)), hub_of(HELLO), hub_of("0.7.0 a dev x/y hub")), (None, None, None));
use crate::serve::fleet::member::Hub;
assert_eq!(hello_for(&Hub::This, Some("k")), hello_of(true, Some("k")));
assert_eq!(hello_for(&Hub::Other("k".into()), Some("lap")), hello_of(false, Some("k")));
assert_eq!(hello_for(&Hub::None, Some("lap")), hello_of(false, None));
}
#[test]
fn two_fleets_never_link() {
let (k, l, none) = (hello_of(true, Some("k")), hello_of(false, Some("l")), hello_of(false, None));
assert_eq!(same_fleet("box", k, l), Err("`box` is in `l`'s fleet, this host in `k`'s: a link between two fleets is refused".into()));
assert!(same_fleet("box", l, k).unwrap_err().starts_with("`box` is in `k`'s fleet, this host in `l`'s"));
assert_eq!(same_fleet("box", k, hello_of(false, Some("k"))), Ok(()), "the same hub");
assert_eq!(same_fleet("box", k, none), Ok(()), "one end in no fleet");
assert_eq!(same_fleet("box", none, l), Ok(()));
assert_eq!(same_fleet("box", none, none), Ok(()));
assert_eq!(same_fleet("box", k, HELLO), Ok(()), "a hello without the words");
}
#[test]
fn the_worker_follows_its_hub_exactly() {
let (lx, mac) = ("linux/x86_64", "macos/aarch64");
let d = |ours: &Build, hub: &Build| decide(ours, hub, lx, lx, false);
let ours = build("0.8.0", "aaaa", true);
assert_eq!(d(&ours, &ours.clone()), Decision::Same);
assert_eq!(decide(&ours, &ours.clone(), lx, mac, false), Decision::Same, "one release, many platforms");
let newer = build("0.9.0", "bbbb", true);
assert_eq!(d(&ours, &newer), Decision::Download { build: newer.clone() });
assert_eq!(decide(&ours, &newer, lx, mac, false), Decision::Download { build: newer.clone() }, "each its asset");
let older = build("0.7.0", "cccc", true);
assert_eq!(d(&ours, &older), Decision::Download { build: older.clone() }, "a downgrade too");
let dev = build("0.8.0", "dddd", false);
assert_eq!(d(&dev, &ours), Decision::Download { build: ours.clone() });
assert_eq!(d(&ours, &build("0.8.0", "ffff", true)), Decision::Download { build: build("0.8.0", "ffff", true) });
assert_eq!(d(&dev, &dev.clone()), Decision::Same);
assert_eq!(decide(&dev, &dev.clone(), lx, mac, false), Decision::Same);
}
#[test]
fn a_published_hub_build_needs_a_release_for_our_platform() {
let ours = build("0.8.0", "aaaa", true);
let newer = build("0.9.0", "bbbb", true);
for platform in ["linux/x86_64", "linux/aarch64", "macos/aarch64"] {
assert_eq!(decide(&ours, &newer, platform, "linux/x86_64", false), Decision::Download { build: newer.clone() }, "{platform}");
}
assert_eq!(
decide(&ours, &newer, "macos/x86_64", "macos/aarch64", true),
Decision::Stop("published build: no devsandbox release is built for macos/x86_64 (the hub runs 0.9.0 (published, bbbb))".into())
);
assert!(matches!(decide(&ours, &newer, "unknown", "linux/x86_64", true), Decision::Stop(_)), "no platform word");
assert_eq!(decide(&ours, &ours.clone(), "macos/x86_64", "linux/x86_64", false), Decision::Same, "the same build needs none");
assert!(!hub_pushes("0.9.0 bbbb published linux/x86_64", "0.8.0 aaaa published macos/x86_64"), "nothing to push");
assert_eq!(platform_target("linux/aarch64"), Some("aarch64-unknown-linux-musl"));
assert_eq!((platform_target("macos/x86_64"), platform_target("unknown"), platform_target("")), (None, None, None));
}
#[test]
fn a_dev_hub_build_needs_the_platform_then_dev_builds() {
let (lx, mac) = ("linux/x86_64", "macos/aarch64");
let ours = build("0.8.0", "aaaa", true);
let dev = build("0.8.0", "dddd", false);
assert_eq!(decide(&ours, &dev, lx, lx, true), Decision::Receive);
assert_eq!(decide(&build("0.8.0", "eeee", false), &dev, lx, lx, true), Decision::Receive, "another dev build");
assert_eq!(
decide(&ours, &dev, lx, lx, false),
Decision::Stop(
"dev build: not taken (`dev-builds = true` in member.toml or `devsandbox machine trust full` takes it; the hub runs 0.8.0 (dev, dddd))"
.into()
)
);
let mismatch = Decision::Stop("dev build: can't run on linux/x86_64 (the hub runs 0.8.0 (dev, dddd) for macos/aarch64)".into());
assert_eq!(decide(&ours, &dev, lx, mac, true), mismatch);
assert_eq!(decide(&ours, &dev, lx, mac, false), mismatch, "the platform first: dev-builds can't help");
assert!(matches!(decide(&ours, &dev, lx, "unknown", true), Decision::Stop(_)), "no platform word");
}
#[test]
fn the_hub_pushes_to_a_worker_that_would_receive() {
let hub = "0.8.0 dddd dev linux/x86_64";
assert!(hub_pushes(hub, "0.8.0 aaaa published linux/x86_64"));
assert!(hub_pushes(hub, "0.7.0 eeee dev linux/x86_64"));
assert!(!hub_pushes(hub, hub), "the same build");
assert!(!hub_pushes(hub, "0.8.0 aaaa published macos/aarch64"), "another platform");
assert!(!hub_pushes("0.8.0 dddd published linux/x86_64", "0.7.0 eeee dev linux/x86_64"), "a release is downloaded");
}
#[test]
fn a_push_is_one_binary_transfer() {
let dir = scratch("push");
let socket = dir.join("t.sock");
let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
let binary = dir.join("exe");
std::fs::write(&binary, b"the hub's build").unwrap();
let into = dir.join("in");
let receiver = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut ch = [0u8; 1];
std::io::Read::read_exact(&mut stream, &mut ch).unwrap();
assert_eq!(ch[0], crate::devsbd::proto::channel::TRANSFER, "a `TRANSFER` stream");
transfer::receive(stream, BINARY_LIMIT, |h| Ok(into.join(&h.name)))
});
push(&socket, &binary).unwrap();
let got = receiver.join().unwrap().unwrap();
assert_eq!((got.header.kind.as_str(), got.header.name.as_str(), got.header.size), (BINARY_KIND, "devsandbox", 15));
assert_eq!(std::fs::read(&got.path).unwrap(), b"the hub's build");
assert!(format!("{:#}", push(&socket, &dir.join("nope")).unwrap_err()).starts_with("cannot read"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn targets_follow_the_release_assets() {
assert_eq!(release_target("linux", "x86_64"), Some("x86_64-unknown-linux-musl"));
assert_eq!(release_target("linux", "aarch64"), Some("aarch64-unknown-linux-musl"));
assert_eq!(release_target("macos", "aarch64"), Some("aarch64-apple-darwin"));
assert_eq!(release_target("macos", "x86_64"), None, "no Intel Mac release");
assert_eq!(release_target("windows", "x86_64"), None);
assert_eq!(release_target("linux", "arm"), None);
}
#[test]
fn asset_urls() {
assert_eq!(
release_url("0.7.0", &asset_name("0.7.0", "aarch64-apple-darwin")).unwrap(),
"https://github.com/Nemikolh/devsandboxes/releases/download/v0.7.0/devsandbox-0.7.0-aarch64-apple-darwin.tar.gz"
);
assert!(release_url("0.7.0-rc.1", SUMS).is_ok());
for bad in ["", "0.7.0/../../x", "0.7 0", "0.7.0?x"] {
assert!(release_url(bad, SUMS).is_err(), "{bad:?}");
}
}
#[test]
fn the_curl_argv_is_https_only() {
let argv = curl_argv("https://x/y", Path::new("/t/a.tar.gz"));
let words: Vec<_> = argv.iter().map(|a| a.to_string_lossy().into_owned()).collect();
for want in [["--proto", "=https"], ["--proto-redir", "=https"], ["--max-time", "600"], ["--speed-time", "30"]] {
assert!(words.windows(2).any(|w| w == want), "{words:?}");
}
assert!(words.contains(&"--fail".into()) && words.contains(&"--tlsv1.2".into()) && words.contains(&"--location".into()));
assert_eq!(words[words.len() - 3..], ["-o", "/t/a.tar.gz", "https://x/y"]);
}
fn test_key() -> ed25519_dalek::SigningKey {
ed25519_dalek::SigningKey::from_bytes(&[7; 32])
}
const ARCHIVE: &[u8] = b"a release archive";
fn honest_sums(version: &str) -> Vec<u8> {
let sum = hex::encode(<sha2::Sha256 as sha2::Digest>::digest(ARCHIVE));
let targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-musl", "x86_64-unknown-linux-musl"];
targets.iter().map(|t| format!("{sum} {}\n", asset_name(version, t))).collect::<String>().into_bytes()
}
#[derive(Default)]
pub(crate) struct Fake {
pub calls: Mutex<Vec<String>>,
pub received_build: String,
pub installed_build: String,
pub fail: Option<&'static str>,
pub tamper: Option<&'static str>,
}
impl Fake {
pub(crate) fn building(hello: &str) -> Fake {
Fake { received_build: hello.into(), installed_build: hello.into(), ..Fake::default() }
}
fn step(&self, name: &str, detail: String) -> Result<()> {
self.calls.lock().unwrap().push(format!("{name} {detail}"));
if self.fail == Some(name) {
bail!("{name} broke");
}
Ok(())
}
pub(crate) fn calls(&self) -> Vec<String> {
self.calls.lock().unwrap().clone()
}
}
impl Steps for Fake {
fn download(&self, url: &str, out: &Path) -> Result<()> {
use ed25519_dalek::Signer as _;
self.step("fetch", url.into())?;
let mut words = url.rsplit('/');
let (file, version) = (words.next().unwrap(), words.next().unwrap().trim_start_matches('v'));
let tamper = |what| self.tamper == Some(what);
let body = match file {
SUMS => {
let mut sums = honest_sums(version);
if tamper("sums") {
sums[0] ^= 1;
}
sums
}
SUMS_SIG => {
let sig = test_key().sign(&honest_sums(version)).to_bytes().to_vec();
if tamper("sig") { sig[..63].to_vec() } else { sig }
}
_ if tamper("archive") => b"another archive".to_vec(),
_ => ARCHIVE.to_vec(),
};
std::fs::write(out, body).unwrap();
Ok(())
}
fn unpack(&self, archive: &Path, into: &Path) -> Result<PathBuf> {
self.step("unpack", archive.file_name().unwrap().to_string_lossy().into_owned())?;
assert_eq!(std::fs::read(archive).unwrap(), ARCHIVE, "unpacks only what was checked");
let binary = into.join("devsandbox");
std::fs::write(&binary, "new").unwrap();
Ok(binary)
}
fn release_key(&self) -> [u8; 32] {
let key = if self.tamper == Some("key") { ed25519_dalek::SigningKey::from_bytes(&[8; 32]) } else { test_key() };
key.verifying_key().to_bytes()
}
fn build(&self, binary: &Path) -> Result<String> {
let installed = binary == Path::new("/dest/devsandbox");
self.step("build", if installed { "dest".into() } else { "received".into() })?;
Ok(if installed { self.installed_build.clone() } else { self.received_build.clone() })
}
fn dest(&self) -> Result<PathBuf> {
Ok("/dest/devsandbox".into())
}
fn install(&self, binary: &Path, dest: &Path) -> Result<()> {
assert!(binary.is_file(), "installs what was fetched");
self.step("install", dest.display().to_string())
}
fn handoff(&self) -> Result<()> {
self.step("handoff", String::new())
}
}
fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("dsv-update-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn empty(dir: &Path) -> bool {
std::fs::read_dir(dir).unwrap().next().is_none()
}
fn hub() -> Build {
build("0.7.0", "aaaa", true)
}
const ASSET: &str = "0.7.0 aaaa published linux/x86_64";
#[test]
fn an_update_installs_checks_and_hands_off() {
let dir = scratch("ok");
let fake = Fake::building(ASSET);
update(&fake, &Build::parse("0.7.0 aaaa published macos/aarch64 hub k"), "linux", "x86_64", &dir).unwrap();
let base = "https://github.com/Nemikolh/devsandboxes/releases/download/v0.7.0";
let asset = "devsandbox-0.7.0-x86_64-unknown-linux-musl.tar.gz";
assert_eq!(
fake.calls(),
[
format!("fetch {base}/SHA256SUMS"),
format!("fetch {base}/SHA256SUMS.sig"),
format!("fetch {base}/{asset}"),
format!("unpack {asset}"),
"build received".into(),
"install /dest/devsandbox".into(),
"build dest".into(),
"handoff ".into()
]
);
assert!(empty(&dir), "the scratch dir is gone");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_failed_download_installs_nothing() {
let dir = scratch("fetch");
let fake = Fake { fail: Some("fetch"), ..Fake::building(ASSET) };
let err = update(&fake, &hub(), "linux", "aarch64", &dir).unwrap_err();
assert!(format!("{err:#}").starts_with("cannot download https://github.com/"), "{err:#}");
assert!(format!("{err:#}").ends_with("/SHA256SUMS: fetch broke"), "{err:#}");
assert_eq!(fake.calls().len(), 1);
assert!(empty(&dir));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_unverified_release_is_never_unpacked() {
let dir = scratch("verify");
let cases = [
("sums", "release v0.7.0 isn't signed by the release key: SHA256SUMS's signature doesn't verify against the release key", 2),
("sig", "release v0.7.0 isn't signed by the release key: SHA256SUMS.sig is 63 bytes, not a 64-byte ed25519 signature", 2),
("key", "release v0.7.0 isn't signed by the release key: SHA256SUMS's signature doesn't verify against the release key", 2),
];
for (tamper, want, fetches) in cases {
let fake = Fake { tamper: Some(tamper), ..Fake::building(ASSET) };
let err = update(&fake, &hub(), "linux", "x86_64", &dir).unwrap_err();
assert_eq!(format!("{err:#}"), want, "{tamper}");
assert_eq!(fake.calls().len(), fetches, "{tamper}: the archive isn't even downloaded: {:?}", fake.calls());
assert!(empty(&dir));
}
let fake = Fake { tamper: Some("archive"), ..Fake::building(ASSET) };
let err = format!("{:#}", update(&fake, &hub(), "linux", "x86_64", &dir).unwrap_err());
assert!(err.starts_with("devsandbox-0.7.0-x86_64-unknown-linux-musl.tar.gz's sha256 is "), "{err}");
assert!(err.contains(", not SHA256SUMS's "), "{err}");
assert!(!fake.calls().iter().any(|c| c.starts_with("unpack")), "{:?}", fake.calls());
assert!(empty(&dir));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn sums_verify_only_with_their_key_and_bytes() {
use ed25519_dalek::Signer as _;
let sums = honest_sums("0.7.0");
let sig = test_key().sign(&sums).to_bytes();
let key = test_key().verifying_key().to_bytes();
verify_sums(&sums, &sig, &key).unwrap();
let mut flipped = sums.clone();
flipped[70] ^= 0x20;
assert!(verify_sums(&flipped, &sig, &key).is_err(), "a flipped byte");
let mut bad_sig = sig;
bad_sig[0] ^= 1;
assert!(verify_sums(&sums, &bad_sig, &key).is_err(), "a flipped signature byte");
assert_eq!(format!("{:#}", verify_sums(&sums, &sig[..63], &key).unwrap_err()), "SHA256SUMS.sig is 63 bytes, not a 64-byte ed25519 signature");
assert!(verify_sums(&sums, &[sig.as_slice(), &[0]].concat(), &key).is_err(), "65 bytes");
assert!(verify_sums(&sums, &[], &key).is_err(), "empty");
let other = ed25519_dalek::SigningKey::from_bytes(&[8; 32]).verifying_key().to_bytes();
assert_eq!(
format!("{:#}", verify_sums(&sums, &sig, &other).unwrap_err()),
"SHA256SUMS's signature doesn't verify against the release key"
);
assert!(verify_sums(&sums, &sig, &RELEASE_KEY).is_err(), "not the real key's");
}
#[test]
fn openssl_signatures_verify() {
let key: [u8; 32] = hex::decode(OPENSSL_PUB).unwrap().try_into().unwrap();
let sig = hex::decode(OPENSSL_SIG).unwrap();
verify_sums(OPENSSL_SUMS.as_bytes(), &sig, &key).unwrap();
let name = "devsandbox-0.9.0-aarch64-apple-darwin.tar.gz";
assert_eq!(hex::encode(sum_of(OPENSSL_SUMS.as_bytes(), name).unwrap()), OPENSSL_SUMS[..64]);
assert!(verify_sums(OPENSSL_SUMS.replace("0.9.0", "0.9.1").as_bytes(), &sig, &key).is_err());
}
const OPENSSL_PUB: &str = "b33161fae07cbbe9dfd5454999d2367ac3a1a0cf20cb17fbdfdfa886f1525066";
const OPENSSL_SIG: &str = "111bff9864e46e0890e1066f87a384820be8909fbd554eb57cb3596dcced7b5bd18c91824dd224282cb117342971cd02f69240264734152b58d88a7b28f3160b";
const OPENSSL_SUMS: &str = "19afaf54e1c73ed8d742a22e5ad23c0fc9875c0697df22365652435250dd2496 devsandbox-0.9.0-aarch64-apple-darwin.tar.gz\nf984e7480c12bb81a839eaad8d5036fbb7f0621371ec7186eeec726ada4eaf6f devsandbox-0.9.0-x86_64-pc-windows-msvc.zip\n45e66ed30407ff38e59c2f40bb7bccf71fd854a42bb0c37ec6b380852d2778cf devsandbox-0.9.0-x86_64-unknown-linux-musl.tar.gz\n";
#[test]
fn the_release_key_is_an_ed25519_key() {
assert!(ed25519_dalek::VerifyingKey::from_bytes(&RELEASE_KEY).is_ok());
assert_eq!(hex::encode(RELEASE_KEY), include_str!("../../../release-signing.pub").trim_end());
assert_eq!(parse_key("00".repeat(32).as_str()), [0; 32], "no newline is fine");
}
#[test]
fn a_sums_line_is_found_once_by_exact_name() {
let (a, b) = ("ab".repeat(32), "cd".repeat(32));
let sums = format!("{a} devsandbox-0.7.0-x.tar.gz\n{b} *devsandbox-0.7.0-y.tar.gz\n");
assert_eq!(sum_of(sums.as_bytes(), "devsandbox-0.7.0-x.tar.gz").unwrap(), [0xab; 32]);
assert_eq!(sum_of(sums.as_bytes(), "devsandbox-0.7.0-y.tar.gz").unwrap(), [0xcd; 32], "binary mode");
let err = |sums: &str, name| format!("{:#}", sum_of(sums.as_bytes(), name).unwrap_err());
assert_eq!(err(&sums, "devsandbox-0.7.0-x.tar"), "SHA256SUMS doesn't list devsandbox-0.7.0-x.tar", "exact names only");
assert_eq!(err(&sums, "x.tar.gz"), "SHA256SUMS doesn't list x.tar.gz");
assert_eq!(err("", "x"), "SHA256SUMS doesn't list x");
let twice = format!("{sums}{b} devsandbox-0.7.0-x.tar.gz\n");
assert_eq!(err(&twice, "devsandbox-0.7.0-x.tar.gz"), "SHA256SUMS lists devsandbox-0.7.0-x.tar.gz more than once");
for bad in [format!("{a} x"), format!("{} x", &a[1..]), format!("{} x", "zz".repeat(32)), "nonsense".into()] {
assert!(err(&bad, "x").contains("line 1 isn't"), "{bad}");
}
assert_eq!(format!("{:#}", sum_of(&[0xff], "x").unwrap_err()), "SHA256SUMS isn't text");
}
#[test]
fn a_wrong_build_is_a_failure_and_no_handoff() {
let dir = scratch("version");
for asset in ["0.6.9 aaaa published linux/x86_64", "0.7.0 bbbb published linux/x86_64", "0.7.0 aaaa dev linux/x86_64"] {
let fake = Fake::building(asset);
let err = format!("{:#}", update(&fake, &hub(), "linux", "x86_64", &dir).unwrap_err());
assert!(err.ends_with("not the hub's 0.7.0 (published, aaaa)"), "{err}");
assert!(err.starts_with("the downloaded binary ("), "{err}");
assert!(!fake.calls().iter().any(|c| c.starts_with("install")), "{asset}");
}
let fake = Fake { installed_build: "0.8.0 cccc published linux/x86_64".into(), ..Fake::building(ASSET) };
let err = update(&fake, &hub(), "linux", "x86_64", &dir).unwrap_err();
assert_eq!(
format!("{err:#}"),
"the installed binary (/dest/devsandbox) is devsandbox 0.8.0 (published, cccc), not the hub's 0.7.0 (published, aaaa)"
);
assert!(!fake.calls().iter().any(|c| c.starts_with("handoff")));
let fake = Fake { fail: Some("build"), ..Fake::building(ASSET) };
let err = format!("{:#}", update(&fake, &hub(), "linux", "x86_64", &dir).unwrap_err());
assert!(err.starts_with("the downloaded binary (") && err.ends_with("doesn't run: build broke"), "{err}");
let fake = Fake { fail: Some("handoff"), ..Fake::building(ASSET) };
let err = update(&fake, &hub(), "linux", "x86_64", &dir).unwrap_err();
assert_eq!(format!("{err:#}"), "cannot hand this daemon off to it: handoff broke");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_received_build_is_made_executable_checked_installed_and_handed_off_to() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch("received");
let binary = dir.join("devsandbox");
let received = || {
std::fs::write(&binary, "new").unwrap();
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o600)).unwrap();
};
let hub = "0.8.0 dddd dev linux/x86_64";
received();
let fake = Fake::building(hub);
install_received(&fake, &binary, hub).unwrap();
assert_eq!(std::fs::metadata(&binary).unwrap().permissions().mode() & 0o777, 0o755);
assert_eq!(fake.calls(), ["build received", "install /dest/devsandbox", "build dest", "handoff "]);
received();
let fake = Fake::building(hub);
install_received(&fake, &binary, &format!("{hub} hub")).unwrap();
assert_eq!(fake.calls().len(), 4);
received();
let fake = Fake { received_build: "0.8.0 eeee dev linux/x86_64".into(), ..Fake::building(hub) };
let err = format!("{:#}", install_received(&fake, &binary, hub).unwrap_err());
assert!(err.contains("reports \"0.8.0 eeee dev linux/x86_64\", not \"0.8.0 dddd dev linux/x86_64\""), "{err}");
assert_eq!(fake.calls(), ["build received"]);
let fake = Fake { fail: Some("build"), ..Fake::building(hub) };
let err = format!("{:#}", install_received(&fake, &binary, hub).unwrap_err());
assert!(err.starts_with("the hub's binary (") && err.ends_with("doesn't run: build broke"), "{err}");
let fake = Fake { installed_build: "0.8.0 dddd dev".into(), ..Fake::building(hub) };
let err = format!("{:#}", install_received(&fake, &binary, hub).unwrap_err());
assert!(err.starts_with("the installed binary (/dest/devsandbox) reports"), "{err}");
assert!(!fake.calls().iter().any(|c| c.starts_with("handoff")));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn no_release_no_fetch() {
let dir = scratch("target");
let fake = Fake::building(ASSET);
let err = update(&fake, &hub(), "macos", "x86_64", &dir).unwrap_err();
assert_eq!(format!("{err:#}"), "no devsandbox release is built for macos/x86_64");
assert!(fake.calls().is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
}