Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
370 lines
11 KiB
Rust
370 lines
11 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},
|
|
process::Stdio,
|
|
time::Duration,
|
|
};
|
|
use tokio::{
|
|
io::{AsyncReadExt, AsyncWriteExt},
|
|
process::Command,
|
|
};
|
|
|
|
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();
|
|
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()) != config.runtime_sha256 {
|
|
return Err("runtime SHA-256 mismatch".into());
|
|
}
|
|
binary
|
|
.seek(SeekFrom::Start(0))
|
|
.map_err(|_| "cannot rewind runtime")?;
|
|
let mut profile = Vec::new();
|
|
regular(&config.worker_profile, 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(Prepared {
|
|
binary,
|
|
size,
|
|
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 = hex_hash(format!("v1:{os}:{arch}:{binary_hash}:{profile_hash}").as_bytes());
|
|
let action = if prepared.is_some() {
|
|
"install"
|
|
} else {
|
|
"activate"
|
|
};
|
|
let (size, profile_size) = prepared
|
|
.as_ref()
|
|
.map(|p| (p.size, p.profile.len()))
|
|
.unwrap_or_default();
|
|
let remote_command = format!(
|
|
"sh -c {} strata-install {action} {} {os} {arch} {binary_hash} {profile_hash} {release} {size} {profile_size}",
|
|
quote(SCRIPT),
|
|
target.slot
|
|
);
|
|
let mut args = target.ssh.arguments()?;
|
|
args.truncate(args.len() - 4);
|
|
for option in [
|
|
"ControlMaster=no",
|
|
"ControlPath=none",
|
|
"ControlPersist=no",
|
|
"ForwardX11=no",
|
|
"ServerAliveInterval=10",
|
|
"ServerAliveCountMax=3",
|
|
] {
|
|
args.extend(["-o".into(), option.into()]);
|
|
}
|
|
args.extend(["--".into(), target.ssh.host.clone(), remote_command]);
|
|
let mut child = Command::new("ssh")
|
|
.args(args)
|
|
.stdin(Stdio::piped())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::null())
|
|
.kill_on_drop(true)
|
|
.spawn()
|
|
.map_err(|_| "cannot start SSH installer")?;
|
|
let mut stdin = child.stdin.take().ok_or("missing SSH stdin")?;
|
|
let stdout = child.stdout.take().ok_or("missing SSH stdout")?;
|
|
let result = tokio::time::timeout(Duration::from_secs(180), async {
|
|
let upload = async move {
|
|
if let Some(p) = prepared {
|
|
let mut file = tokio::fs::File::from_std(p.binary).take(p.size);
|
|
let copied = tokio::io::copy(&mut file, &mut stdin).await?;
|
|
if copied != p.size {
|
|
return Err(std::io::Error::other("runtime truncated during transfer"));
|
|
}
|
|
stdin.write_all(&p.profile).await?;
|
|
}
|
|
stdin.shutdown().await
|
|
};
|
|
let receive = async move {
|
|
let mut data = Vec::new();
|
|
stdout.take(8193).read_to_end(&mut data).await?;
|
|
if data.len() > 8192 {
|
|
return Err(std::io::Error::other("installer output too large"));
|
|
}
|
|
Ok(data)
|
|
};
|
|
tokio::join!(upload, receive, child.wait())
|
|
})
|
|
.await;
|
|
let (bytes, status) = match result {
|
|
Ok((uploaded, Ok(bytes), Ok(status))) if uploaded.is_ok() || !status.success() => {
|
|
(bytes, status)
|
|
}
|
|
_ => {
|
|
let _ = child.kill().await;
|
|
let _ = child.wait().await;
|
|
return Err("SSH installation interrupted; activation outcome unknown, retry with the same pins".into());
|
|
}
|
|
};
|
|
if !status.success() {
|
|
for code in [
|
|
"target_os",
|
|
"target_arch",
|
|
"directory_symlink",
|
|
"directory_create",
|
|
"directory_type",
|
|
"directory_permissions",
|
|
"runtime_type",
|
|
"profile_type",
|
|
"runtime_digest",
|
|
"profile_digest",
|
|
"profile_validation",
|
|
"slot_locked",
|
|
"marker_symlink",
|
|
"marker_type",
|
|
"stale_marker",
|
|
"disk_probe",
|
|
"disk_capacity",
|
|
"upload_size",
|
|
"runtime_size",
|
|
"profile_size",
|
|
"release_missing",
|
|
] {
|
|
if bytes == format!("error:{code}\n").as_bytes() {
|
|
return Err(format!("remote installation rejected: {code}"));
|
|
}
|
|
}
|
|
}
|
|
let outcome = match (status.success(), bytes.as_slice()) {
|
|
(true, b"ok:installed\n") => "installed",
|
|
(true, b"ok:reused\n") => "reused",
|
|
(true, b"ok:activated\n") => "activated",
|
|
_ => return Err("remote installation failed; inspect target permissions, capacity, platform and worker profile; activation may require reconciliation".into()),
|
|
};
|
|
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'");
|
|
}
|
|
}
|