Files
leleka/desktop-core/src/remote_install.rs
T

281 lines
8.3 KiB
Rust

//! Digest-pinned, per-user installation. Does not launch or replace serving models.
use crate::{managed_worker::Profile, remote::SshProfile};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
fs::File,
io::{Read, Seek, SeekFrom},
path::{Path, PathBuf},
};
mod exec;
const SCRIPT: &str = include_str!("remote_install.sh");
const MAX_BINARY: u64 = 256 * 1024 * 1024;
const MAX_PROFILE: u64 = 1024 * 1024;
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Target {
pub ssh: SshProfile,
pub slot: String,
pub os: String,
pub arch: String,
}
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Install {
pub schema_version: u32,
pub target: Target,
pub runtime: PathBuf,
pub runtime_sha256: String,
pub worker_profile: PathBuf,
}
#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Activate {
pub schema_version: u32,
pub target: Target,
pub runtime_sha256: String,
pub profile_sha256: String,
}
#[derive(Serialize)]
pub struct Receipt {
pub schema_version: u32,
pub slot: String,
pub release: String,
pub runtime_sha256: String,
pub profile_sha256: String,
pub outcome: String,
pub serving_changed: bool,
}
fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn hex_hash(bytes: &[u8]) -> String {
to_hex(&Sha256::digest(bytes))
}
fn valid_hash(s: &str) -> bool {
s.len() == 64
&& s.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
impl Target {
fn platform(&self) -> Result<(&'static str, &'static str), String> {
if self.slot.is_empty()
|| self.slot.len() > 64
|| !self
.slot
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
{
return Err("invalid installation slot".into());
}
let os = match self.os.as_str() {
"linux" => "Linux",
"macos" => "Darwin",
_ => return Err("unsupported remote installation OS".into()),
};
let arch = match (os, self.arch.as_str()) {
(_, "x86_64") => "x86_64",
("Linux", "aarch64") => "aarch64",
("Darwin", "aarch64") => "arm64",
_ => return Err("unsupported installation architecture".into()),
};
Ok((os, arch))
}
}
fn regular(path: &Path, limit: u64) -> Result<File, String> {
if !path.is_absolute() {
return Err("installation files must use absolute paths".into());
}
let file = File::open(path).map_err(|_| "cannot open installation file")?;
let meta = file
.metadata()
.map_err(|_| "cannot inspect installation file")?;
if !meta.is_file() || meta.len() == 0 || meta.len() > limit {
return Err("installation file size/type is invalid".into());
}
Ok(file)
}
struct Prepared {
binary: File,
size: u64,
profile: Vec<u8>,
}
fn prepare(config: &Install) -> Result<Prepared, String> {
let mut binary = regular(&config.runtime, MAX_BINARY)?;
let size = binary
.metadata()
.map_err(|_| "cannot inspect runtime")?
.len();
verify_runtime(&mut binary, size, &config.runtime_sha256)?;
binary
.seek(SeekFrom::Start(0))
.map_err(|_| "cannot rewind runtime")?;
let profile = read_profile(&config.worker_profile)?;
Ok(Prepared {
binary,
size,
profile,
})
}
/// Streams the runtime once: bounded, of the expected size and with the pinned SHA-256.
fn verify_runtime(binary: &mut File, size: u64, pin: &str) -> Result<(), String> {
let mut digest = Sha256::new();
let mut buf = [0u8; 65536];
let mut count = 0;
loop {
let n = binary.read(&mut buf).map_err(|_| "cannot read runtime")?;
if n == 0 {
break;
}
count += n as u64;
if count > MAX_BINARY {
return Err("runtime grew beyond size limit".into());
}
digest.update(&buf[..n]);
}
if count != size || to_hex(&digest.finalize()) != pin {
return Err("runtime SHA-256 mismatch".into());
}
Ok(())
}
fn read_profile(path: &Path) -> Result<Vec<u8>, String> {
let mut profile = Vec::new();
regular(path, MAX_PROFILE)?
.take(MAX_PROFILE + 1)
.read_to_end(&mut profile)
.map_err(|_| "cannot read worker profile")?;
if profile.len() as u64 > MAX_PROFILE {
return Err("worker profile too large".into());
}
// Paths belong to the target OS: validate semantic/path constraints there.
serde_json::from_slice::<Profile>(&profile).map_err(|_| "invalid worker profile JSON")?;
Ok(profile)
}
pub async fn install(config: Install) -> Result<Receipt, String> {
validate(
&config.target,
config.schema_version,
&config.runtime_sha256,
None,
)?;
let input = config.clone();
let prepared = tokio::task::spawn_blocking(move || prepare(&input))
.await
.map_err(|_| "artifact validation interrupted")??;
let profile_hash = hex_hash(&prepared.profile);
execute(
&config.target,
&config.runtime_sha256,
&profile_hash,
Some(prepared),
)
.await
}
pub async fn activate(config: Activate) -> Result<Receipt, String> {
validate(
&config.target,
config.schema_version,
&config.runtime_sha256,
Some(&config.profile_sha256),
)?;
execute(
&config.target,
&config.runtime_sha256,
&config.profile_sha256,
None,
)
.await
}
fn validate(
target: &Target,
version: u32,
binary: &str,
profile: Option<&str>,
) -> Result<(), String> {
target.platform()?;
target.ssh.arguments()?;
if version != 1 || !valid_hash(binary) || profile.is_some_and(|p| !valid_hash(p)) {
return Err("invalid installation schema or SHA-256 pin".into());
}
Ok(())
}
fn quote(s: &str) -> String {
format!("'{}'", s.replace('\'', "'\\''"))
}
async fn execute(
target: &Target,
binary_hash: &str,
profile_hash: &str,
prepared: Option<Prepared>,
) -> Result<Receipt, String> {
let (os, arch) = target.platform()?;
let release = exec::release(os, arch, binary_hash, profile_hash);
let pins = exec::Pins {
os,
arch,
binary_hash,
profile_hash,
release: &release,
};
let remote_command = exec::remote_command(target, &pins, prepared.as_ref());
let args = exec::ssh_args(target, remote_command)?;
let (bytes, status) = exec::run(args, prepared).await?;
let outcome = exec::outcome(status.success(), &bytes)?;
Ok(Receipt {
schema_version: 1,
slot: target.slot.clone(),
release,
runtime_sha256: binary_hash.into(),
profile_sha256: profile_hash.into(),
outcome: outcome.into(),
serving_changed: false,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn target() -> Target {
Target {
ssh: SshProfile {
schema_version: 1,
id: "fixture".into(),
host: "localhost".into(),
user: None,
port: None,
identity_file: None,
},
slot: "test".into(),
os: "macos".into(),
arch: "aarch64".into(),
}
}
#[test]
fn reject_untrusted_arguments_before_ssh() {
let mut t = target();
assert!(validate(&t, 1, &"a".repeat(64), None).is_ok());
for slot in ["../other", "a b", "$(id)", "", "a;id"] {
t.slot = slot.into();
assert!(t.platform().is_err());
}
t = target();
t.os = "windows".into();
assert!(t.platform().is_err());
assert!(!valid_hash(&"A".repeat(64)));
assert!(validate(&target(), 2, &"a".repeat(64), None).is_err());
assert!(validate(&target(), 1, &"a".repeat(64), Some("x")).is_err());
}
#[test]
fn reject_bad_artifact_pin_and_unbounded_input() {
assert!(regular(Path::new("relative"), MAX_BINARY).is_err());
assert!(!valid_hash("deadbeef"));
assert_eq!(
hex_hash(b"abc"),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(quote("a'b"), "'a'\\''b'");
}
}