From ccd5d40c5d45caa38120dc8a0f980a7587af4cc3 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sun, 4 Oct 2026 13:34:32 +0200 Subject: [PATCH] feat(remote): add SSH preflight and gRPC agent design (STRA-51 STRA-58) --- desktop-core/REMOTE.md | 33 +++ desktop-core/examples/ssh-profile.json | 8 + desktop-core/src/hardware.rs | 2 +- desktop-core/src/lib.rs | 1 + desktop-core/src/main.rs | 9 +- desktop-core/src/remote.rs | 393 +++++++++++++++++++++++++ desktop/README.md | 4 + docs/cross-platform-application.md | 62 ++++ 8 files changed, 508 insertions(+), 4 deletions(-) create mode 100644 desktop-core/REMOTE.md create mode 100644 desktop-core/examples/ssh-profile.json create mode 100644 desktop-core/src/remote.rs diff --git a/desktop-core/REMOTE.md b/desktop-core/REMOTE.md new file mode 100644 index 00000000..cf71eb09 --- /dev/null +++ b/desktop-core/REMOTE.md @@ -0,0 +1,33 @@ +# SSH preflight + +`strata-desktop remote-inspect /absolute/private/ssh-profile.json` reads server +resources using system OpenSSH. Copy `examples/ssh-profile.json` and supply a host +or trusted SSH config alias. Null user/port/identity fields defer to OpenSSH's +configuration/agent. Identity paths must be absolute; keys are referenced, never +embedded. There is no password field. Keep real profiles outside Git. + +This command sends a fixed read-only POSIX shell script over SSH stdin. It reads +Linux OS/architecture, CPU/count/features, RAM, NVIDIA memory/driver and available +disk space on the SSH user's current/home filesystem. Recheck the actual model +destination filesystem during provisioning. Non-NVIDIA GPU/NPU and engine +capabilities remain unknown, not inferred from the client hardware. No Python, +model request, process restart, package installation or persistent agent occurs. + +Known-host verification is strict; establish and verify trust in the usual SSH +flow first. Agent forwarding, configured forwards and LocalCommand are disabled. +Batch mode avoids password prompts; the existing SSH configuration (including +ProxyJump/ProxyCommand when configured by the user) remains a trusted dependency. +The probe has a 15-second total deadline and 128 KiB stdout/stderr limits. +Unexpected banners, malformed data and unsupported remote OS/CPU return explicit +errors. Raw SSH stderr and key paths are not included in the returned inventory. + +Tests cover injected options/shell syntax, forbidden secret fields, memory and +unknown GPU parsing, output bounds, stdin EOF, timeout and host-key rejection. +On 2026-10-04 the command also read the authorized existing Linux RTX5090 host +successfully without changing its active serving session. This proves preflight, +not remote provisioning or persistent lifecycle. + +Next: STRA-52 installs the managed runtime; STRA-58/59 introduce a persistent +Rust agent and versioned gRPC control/events with epoch/sequence resume and +idempotent command reconciliation. SSH remains bootstrap and secure transport. +These capabilities are not present in this preflight command yet. diff --git a/desktop-core/examples/ssh-profile.json b/desktop-core/examples/ssh-profile.json new file mode 100644 index 00000000..60d1353b --- /dev/null +++ b/desktop-core/examples/ssh-profile.json @@ -0,0 +1,8 @@ +{ + "schema_version": 1, + "id": "server-a", + "host": "your-ssh-config-alias", + "user": null, + "port": null, + "identity_file": null +} diff --git a/desktop-core/src/hardware.rs b/desktop-core/src/hardware.rs index 502028b1..b1363d92 100644 --- a/desktop-core/src/hardware.rs +++ b/desktop-core/src/hardware.rs @@ -184,7 +184,7 @@ async fn probe(program: &str, args: &[&str], limit: Duration) -> Result Result, String> { +pub(crate) fn parse_nvidia(data: &str) -> Result, String> { data.lines() .filter(|l| !l.trim().is_empty()) .enumerate() diff --git a/desktop-core/src/lib.rs b/desktop-core/src/lib.rs index 0f2027a7..d8cb6fd2 100644 --- a/desktop-core/src/lib.rs +++ b/desktop-core/src/lib.rs @@ -3,3 +3,4 @@ pub mod gateway; pub mod hardware; pub mod planner; pub mod pool; +pub mod remote; diff --git a/desktop-core/src/main.rs b/desktop-core/src/main.rs index 7f043e26..fbdd1882 100644 --- a/desktop-core/src/main.rs +++ b/desktop-core/src/main.rs @@ -1,5 +1,5 @@ use std::{env, fs::File, io::Read}; -use strata_desktop_core::{gateway, hardware, planner}; +use strata_desktop_core::{gateway, hardware, planner, remote}; fn read_json(path: &str) -> Result> { let mut data = Vec::new(); @@ -16,6 +16,9 @@ fn read_json(path: &str) -> Result Result<(), Box> { let args: Vec<_> = env::args().skip(1).collect(); let value = match args.as_slice() { + [cmd, file] if cmd == "remote-inspect" => { + serde_json::to_value(remote::inspect(&read_json(file)?).await?)? + } [cmd, file] if cmd == "gateway" => { gateway::serve(read_json(file)?).await?; return Ok(()); @@ -30,12 +33,12 @@ async fn main() -> Result<(), Box> { } [cmd] if cmd == "--help" || cmd == "help" => { println!( - "strata-desktop hardware\nstrata-desktop plan REQUIREMENTS.json [--hardware SNAPSHOT.json]\nstrata-desktop gateway POOL.json\nInventory and planning are read-only. Gateway serves configured loopback workers; it does not start or replace models." + "strata-desktop hardware\nstrata-desktop plan REQUIREMENTS.json [--hardware SNAPSHOT.json]\nstrata-desktop remote-inspect SSH_PROFILE.json\nstrata-desktop gateway POOL.json\nInventory and planning are read-only. Gateway serves configured loopback workers; it does not start or replace models." ); return Ok(()); } _ => return Err( - "usage: strata-desktop hardware | plan REQUIREMENTS.json [--hardware SNAPSHOT.json]" + "usage: strata-desktop --help (hardware, plan, remote-inspect, gateway)" .into(), ), }; diff --git a/desktop-core/src/remote.rs b/desktop-core/src/remote.rs new file mode 100644 index 00000000..76e10e73 --- /dev/null +++ b/desktop-core/src/remote.rs @@ -0,0 +1,393 @@ +//! OpenSSH transport preflight. Does not install or start anything on the host. +use crate::hardware::{Hardware, Memory, parse_nvidia}; +use serde::{Deserialize, Serialize}; +use std::{ + path::Path, + process::Stdio, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, + process::Command, +}; + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct SshProfile { + pub schema_version: u32, + pub id: String, + pub host: String, + pub user: Option, + pub port: Option, + /// Reference only. Private key contents never enter the profile or protocol. + pub identity_file: Option, +} +#[derive(Debug, Serialize)] +pub struct RemoteInventory { + pub schema_version: u32, + pub node_id: String, + pub transport: &'static str, + pub hardware: Hardware, + /// SSH user's current/home filesystem; recheck actual model destination before install. + pub home_disk_available_bytes: Option, +} +impl SshProfile { + pub fn arguments(&self) -> Result, String> { + let ident = |s: &str| { + !s.is_empty() + && s.len() <= 128 + && s.as_bytes()[0].is_ascii_alphanumeric() + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b)) + }; + if self.schema_version != 1 + || !ident(&self.id) + || self.host.is_empty() + || self.host.len() > 253 + || !self.host.as_bytes()[0].is_ascii_alphanumeric() + || !self + .host + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"._-:".contains(&b)) + || self.user.as_ref().is_some_and(|s| !ident(s)) + || self.port == Some(0) + { + return Err("invalid SSH profile".into()); + } + let mut args = vec![ + "-T", + "-o", + "BatchMode=yes", + "-o", + "StrictHostKeyChecking=yes", + "-o", + "ForwardAgent=no", + "-o", + "ClearAllForwardings=yes", + "-o", + "PermitLocalCommand=no", + "-o", + "ConnectTimeout=8", + ] + .into_iter() + .map(str::to_owned) + .collect::>(); + if let Some(port) = self.port { + args.extend(["-p".into(), port.to_string()]); + } + if let Some(user) = &self.user { + args.extend(["-l".into(), user.clone()]); + } + if let Some(path) = &self.identity_file { + if !Path::new(path).is_absolute() + || path.len() > 4096 + || path.chars().any(char::is_control) + { + return Err("SSH identity must be an absolute key-file reference".into()); + } + args.extend(["-i".into(), path.clone()]); + } + args.extend(["--".into(), self.host.clone(), "sh".into(), "-s".into()]); + Ok(args) + } +} +// Static stdin only: no profile values interpolated into this remote shell program. +const PROBE: &str = r#"export LC_ALL=C +printf 'os\t'; uname -s +if [ "$(uname -s)" != Linux ]; then exit 0; fi +printf 'arch\t'; uname -m +printf 'cpus\t'; getconf _NPROCESSORS_ONLN +awk -F: '/^model name/ {sub(/^[ \t]+/, "", $2); print "cpu\t" $2; exit}' /proc/cpuinfo +awk -F: '/^(flags|Features)[ \t]*:/ {print "features\t" $2; exit}' /proc/cpuinfo +awk '/^MemTotal:/ {print "total_kib\t" $2} /^MemAvailable:/ {print "available_kib\t" $2}' /proc/meminfo +df -Pk . 2>/dev/null | awk 'NR==2 {print "disk_available_kib\t" $4}' +if command -v nvidia-smi >/dev/null 2>&1; then + nvidia-smi --query-gpu=name,memory.total,memory.free,driver_version --format=csv,noheader,nounits 2>/dev/null | sed 's/^/gpu\t/' +fi +printf 'end\tok\n' +"#; +async fn bounded(reader: impl AsyncRead + Unpin) -> Result, String> { + let mut data = Vec::new(); + reader + .take(128 * 1024 + 1) + .read_to_end(&mut data) + .await + .map_err(|_| "SSH read failed")?; + if data.len() > 128 * 1024 { + return Err("SSH output limit exceeded".into()); + } + Ok(data) +} +pub async fn inspect(profile: &SshProfile) -> Result { + inspect_with_program(profile, "ssh", Duration::from_secs(15)).await +} +async fn inspect_with_program( + profile: &SshProfile, + program: &str, + limit: Duration, +) -> Result { + let args = profile.arguments()?; + let mut child = Command::new(program) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .map_err(|_| "OpenSSH is unavailable")?; + let mut input = child.stdin.take().ok_or("SSH stdin missing")?; + let output = child.stdout.take().ok_or("SSH stdout missing")?; + let error = child.stderr.take().ok_or("SSH stderr missing")?; + let run = async { + let write = async move { + input + .write_all(PROBE.as_bytes()) + .await + .map_err(|_| "SSH input failed".to_string())?; + drop(input); // Close the pipe: remote `sh -s` must receive EOF. + Ok::<(), String>(()) + }; + let (_, output, error) = tokio::try_join!(write, bounded(output), bounded(error))?; + let status = child.wait().await.map_err(|_| "SSH wait failed")?; + if !status.success() { + let error = String::from_utf8_lossy(&error); + return Err(if error.contains("Host key verification failed") + || error.contains("REMOTE HOST IDENTIFICATION HAS CHANGED") + { + "SSH host identity is not trusted or has changed" + } else if error.contains("Permission denied") { + "SSH authentication failed" + } else { + "SSH preflight failed; verify connection and host configuration" + } + .to_string()); + } + parse( + profile, + &String::from_utf8(output).map_err(|_| "SSH output is not UTF-8")?, + ) + }; + match tokio::time::timeout(limit, run).await { + Ok(Ok(result)) => Ok(result), + failure => { + let _ = child.kill().await; + match failure { + Ok(Err(e)) => Err(e), + _ => Err("SSH preflight timed out".into()), + } + } + } +} +fn parse(profile: &SshProfile, data: &str) -> Result { + let mut fields = std::collections::HashMap::new(); + let mut gpus = Vec::new(); + for line in data.lines() { + let Some((key, value)) = line.split_once('\t') else { + return Err("unexpected SSH probe output".into()); + }; + if key == "gpu" { + gpus.push(value); + } else if fields.insert(key, value).is_some() { + return Err("duplicate SSH probe field".into()); + } + } + if fields.get("os") != Some(&"Linux") { + return Err("remote worker preflight currently supports Linux only".into()); + } + if fields.get("end") != Some(&"ok") { + return Err("incomplete SSH probe".into()); + } + let kib = |key: &str| { + fields + .get(key) + .and_then(|s| s.parse::().ok()) + .and_then(|n| n.checked_mul(1024)) + }; + let memory = Memory { + total_bytes: kib("total_kib"), + available_bytes: kib("available_kib"), + }; + if memory.total_bytes.is_none_or(|n| n == 0) + || matches!((memory.total_bytes,memory.available_bytes),(Some(t),Some(a)) if a>t) + { + return Err("invalid remote RAM inventory".into()); + } + let architecture = match fields.get("arch").copied() { + Some("x86_64") => "x86_64", + Some("aarch64" | "arm64") => "aarch64", + _ => return Err("unsupported remote CPU architecture".into()), + }; + let cpus = fields + .get("cpus") + .and_then(|s| s.parse::().ok()) + .filter(|n| *n > 0) + .ok_or("invalid remote CPU count")?; + let flags = fields + .get("features") + .copied() + .unwrap_or("") + .split_whitespace() + .collect::>(); + let cpu_features = [ + ("avx2", "avx2"), + ("avx512f", "avx512f"), + ("fma", "fma"), + ("asimd", "neon"), + ("asimddp", "dotprod"), + ] + .into_iter() + .filter(|(flag, _)| flags.contains(flag)) + .map(|(_, name)| name.to_owned()) + .collect(); + let mut warnings = + vec!["NPU and inference-provider support require a separate capability check.".into()]; + let accelerators = match parse_nvidia(&gpus.join("\n")) { + Ok(g) => g, + Err(e) => { + warnings.push(e); + vec![] + } + }; + if accelerators.is_empty() { + warnings.push("No NVIDIA inventory; other accelerators are not probed yet.".into()); + } + Ok(RemoteInventory { + schema_version: 1, + node_id: profile.id.clone(), + transport: "ssh", + home_disk_available_bytes: kib("disk_available_kib"), + hardware: Hardware { + schema_version: 1, + sampled_at_unix_ms: SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|t| t.as_millis() as u64) + .unwrap_or(0), + os: "linux".into(), + architecture: architecture.into(), + cpu_name: fields.get("cpu").copied().unwrap_or("unknown").into(), + logical_cpus: cpus, + cpu_features, + memory, + accelerators, + warnings, + }, + }) +} +#[cfg(test)] +mod tests { + use super::*; + fn profile() -> SshProfile { + SshProfile { + schema_version: 1, + id: "server-a".into(), + host: "gpu-server".into(), + user: None, + port: None, + identity_file: None, + } + } + #[test] + fn hostile_options_and_secrets_are_not_configuration() { + for host in [ + "-oProxyCommand=evil", + "user@host", + "host;touch x", + "host\ncommand", + "$(id)", + ] { + let mut p = profile(); + p.host = host.into(); + assert!(p.arguments().is_err()); + } + let mut p = profile(); + p.user = Some("-root".into()); + assert!(p.arguments().is_err()); + p = profile(); + p.identity_file = Some("relative-key".into()); + assert!(p.arguments().is_err()); + assert!( + serde_json::from_str::( + r#"{"schema_version":1,"id":"a","host":"h","password":"secret"}"# + ) + .is_err() + ); + let args = profile().arguments().unwrap(); + assert!(args.contains(&"StrictHostKeyChecking=yes".into())); + assert!(args.contains(&"ForwardAgent=no".into())); + } + #[test] + fn parses_server_memory_and_unknown_accelerators() { + let data = "os\tLinux\narch\tx86_64\ncpus\t8\ncpu\tFixture CPU\nfeatures\tavx2 fma\ntotal_kib\t33554432\navailable_kib\t16777216\ndisk_available_kib\t1024\nend\tok\n"; + let r = parse(&profile(), data).unwrap(); + assert_eq!( + r.hardware.memory.available_bytes, + Some(16 * 1024 * 1024 * 1024) + ); + assert!(r.hardware.accelerators.is_empty()); + assert_eq!(r.home_disk_available_bytes, Some(1024 * 1024)); + assert!(parse(&profile(), &data.replace("Linux", "Darwin")).is_err()); + assert!(parse(&profile(), &data.replace("end\tok\n", "")).is_err()); + assert!( + parse( + &profile(), + &data.replace("16777216", "9999999999999999999999") + ) + .unwrap() + .hardware + .memory + .available_bytes + .is_none() + ); + } + #[tokio::test] + async fn probe_output_is_bounded() { + assert!(bounded(&vec![b'x'; 128 * 1024 + 1][..]).await.is_err()); + } + + #[cfg(unix)] + #[tokio::test] + async fn ssh_stdin_closes_and_hung_probe_times_out() { + use std::{io::Write, os::unix::fs::PermissionsExt}; + struct Temp(std::path::PathBuf); + impl Drop for Temp { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + let path = + Temp(std::env::temp_dir().join(format!("strata-ssh-test-{}", std::process::id()))); + let script = "#!/bin/sh\ncat >/dev/null\nprintf 'os\\tLinux\\narch\\tx86_64\\ncpus\\t1\\ntotal_kib\\t1024\\nend\\tok\\n'\n"; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path.0) + .unwrap(); + file.write_all(script.as_bytes()).unwrap(); + drop(file); + std::fs::set_permissions(&path.0, std::fs::Permissions::from_mode(0o700)).unwrap(); + let p = path.0.to_str().unwrap(); + assert!( + inspect_with_program(&profile(), p, Duration::from_secs(2)) + .await + .is_ok() + ); + std::fs::write(&path.0, "#!/bin/sh\nexec sleep 5\n").unwrap(); + assert_eq!( + inspect_with_program(&profile(), p, Duration::from_millis(20)) + .await + .unwrap_err(), + "SSH preflight timed out" + ); + std::fs::write( + &path.0, + "#!/bin/sh\ncat >/dev/null\necho 'Host key verification failed' >&2\nexit 255\n", + ) + .unwrap(); + assert_eq!( + inspect_with_program(&profile(), p, Duration::from_secs(2)) + .await + .unwrap_err(), + "SSH host identity is not trusted or has changed" + ); + } +} diff --git a/desktop/README.md b/desktop/README.md index 2db76f99..03ea3e09 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -69,3 +69,7 @@ No inference code changed; no speed or model-quality claim is made. - STRA-47: signed platform distributions and native release gates. See [product architecture](../docs/cross-platform-application.md) for boundaries. + +The Rust CLI now also has an experimental [pool gateway](../desktop-core/POOL.md) +and [SSH preflight](../desktop-core/REMOTE.md). They are separate CLI capabilities; +the current desktop window still covers local inventory and memory planning. diff --git a/docs/cross-platform-application.md b/docs/cross-platform-application.md index 17ac48e6..093e71ba 100644 --- a/docs/cross-platform-application.md +++ b/docs/cross-platform-application.md @@ -519,3 +519,65 @@ isolation; STRA-57 — UI і інтеграційний gate. Автотести реальному local + 2 SSH стенді вимагає трьох перекритих у часі harness-запитів, коректних незалежних tool calls/terminal events, фактичного model attribution та виміряної concurrency. Цей розділ фіксує дизайн; pool gateway ще не реалізований. + +**Оновлення реалізації:** експериментальний Rust gateway і bounded queue вже є +у `desktop-core` (STRA-56); три паралельні fake workers та черга перевірені через +реальний loopback HTTP. Це ще не інтеграція з GUI/керованими SSH agents і не +real-model gate. Контракт і поточні обмеження: [POOL.md](../desktop-core/POOL.md). + +## Постійний node agent і gRPC — STRA-58/59 + +Рішення користувача: невеликий Rust agent залишається на кожному сервері та +керує власними workers/jobs. SSH потрібний для першого встановлення, перевірки +ідентичності й тунелю. Після bootstrap основний management transport — +версійований gRPC канал між локальним Rust service та node agent. Harness +продовжує використовувати локальний Responses HTTP/SSE endpoint. + +Один логічний канал на вузол містить окремі RPC-потоки: + +- handshake/version/capabilities та snapshot; +- типізовані команди lifecycle/job/admission/cancel і acknowledgement; +- підписку на state/job events і числові метрики; +- окремий потік inference для кожного запиту, з власним backpressure. + +Повідомлення різних запитів не складаються в одну необмежену чергу. Окремі +HTTP/2 streams і bounded application queues запобігають блокуванню control +великим потоком метрик; низькопріоритетні метрики можна об'єднувати до останнього +значення. Загальні transport limits і bandwidth залишаються спільними. +gRPC має transport flow control, але політику черг визначає застосунок. +[gRPC flow control](https://grpc.io/docs/guides/flow-control/). + +Відновлення після обриву: + +1. Клієнт позначає вузол disconnected і тимчасово припиняє новий admission. + Сам disconnect спостерігача не звільняє зайняті слоти на сервері. +2. Відновлює tunnel/channel з exponential backoff, jitter та узгодженим + keepalive; reconnect до інших вузлів незалежний. Auth/schema mismatch + має окремий стан, не нескінченний швидкий retry. +3. Передає `agent_epoch` і останній застосований `event_seq`. Сервер віддає + збережені події; за gap/нового epoch клієнт отримує узгоджений snapshot + із cursor, потім нові події. UI дедуплікує вже застосовані sequence numbers. +4. Команди мають `operation_id`, digest параметрів і збережений стан виконання. + Повтор тієї самої команди повертає її результат, інші параметри з тим самим + id відхиляються. Після втрати ack спочатку звіряється статус операції. + Для рестарту агента потрібний стійкий журнал/reconciliation процесів; + один gRPC retry не гарантує exactly-once execution. +5. Inference із неоднозначним прийманням або вже виданими токенами автоматично + не запускається заново. Resume потоку дозволяється лише за окремого + bounded replay-контракту; інакше повертається явний interrupted стан. + +Автоматичні gRPC retries не замінюють application-level reconciliation, +а keepalive лише виявляє transport failure, не доводить готовність моделі. +[gRPC retry](https://grpc.io/docs/guides/retry/), +[gRPC keepalive](https://grpc.io/docs/guides/keepalive/). + +Перший transport — gRPC на remote loopback через SSH, з окремою per-install +автентифікацією. Прямий network gRPC потребує mTLS і явного enrollment. +Agent має перелік дозволених команд; RPC «виконай довільний shell» відсутній. +Ваги завантажуються сервером або окремим bounded transfer, не event bus. +UI можна закрити, не зупиняючи remote agent чи inference за замовчуванням. + +MCP: STRA-58 — agent/protobuf/control/event service; STRA-59 — reconnect, +resume і reconciliation клієнта. STRA-52/53 використовують цей контракт для +provisioning/tunnel. gRPC agent наразі спроєктований; ще не встановлений і не +працює на користувацькому сервері.