feat: run sandbox transports in disposable workers

The control plane opened ssh connections itself, so a malicious ssh
server attacked the process that held the database, the master key, and
every room's keys. It now starts one worker per target and workspace.
The worker gets one target key on stdin, binds loopback behind a random
token, and serves exec, files, the pty, and the preview proxy. It has no
database and no master key, and a closed stdin ends it.

The preview HTTP client moved into the worker too. The app sees a typed
response, and the worker caps bodies, output tails, handshakes, and
transport waits.

Direct targets now reject loopback, private, link-local, multicast,
unspecified, carrier-grade NAT, and documentation addresses when a
target is created and again when its worker starts.
TOGETHER_ALLOW_PRIVATE_TARGETS=1 lifts the check for a server that runs
on one private network.
This commit is contained in:
vhaudiquet committed 2026-11-29 18:22:44 +01:00
1 parent a8f7e74ba0
commit fc684115b5
16 files changed
+1355 -208

No files matched your search

+909
View File
@@ -0,0 +1,909 @@
//! The sandbox data plane.
//!
//! The control plane never speaks ssh, and never parses a byte a
//! sandbox sends. Every room gets a disposable worker process: it holds
//! only that room's target key, listens on loopback behind a random
//! token, and serves the `rhema-sandbox` wire protocol, a pty websocket,
//! and a raw forward socket. The app reaches it with the ordinary
//! `HttpSandbox` client and proxies browser bytes.
//!
//! If a hostile sandbox exploits the ssh client or the worker's parser,
//! it lands in a process with no database, no master key, and no long
//! lived credentials beyond the one room's key. The parent kills it when
//! the room goes away, and the parent holds its stdin open so a crashed
//! app takes the worker with it.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use axum::body::Body;
use axum::extract::ws::WebSocketUpgrade;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get as get_route, post};
use axum::{Json, Router};
use base64::Engine;
use futures::TryStreamExt;
use http_body_util::{BodyExt, Full};
use hyper::body::Bytes;
use rhema_sandbox::protocol::{
Ack, ExecCall, ExecReply, FileReply, PutFile, SeedRequest, TOKEN_HEADER,
};
use rhema_sandbox::{Sandbox, SandboxError, WorkspaceSeed};
use rhema_sandbox_ssh::SshSandbox;
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::sync::Mutex;
use crate::room::agent::TargetRow;
use crate::state::Shared;
/// The largest body a file route accepts, and the largest file the
/// worker returns. The protocol's own clients cap lower per route; this
/// is the outer wall.
const FILE_CAP: usize = 32 * 1024 * 1024;
/// The output tail the wire carries. The ssh backend already tails its
/// capture; this keeps a different backend honest too.
const OUTPUT_CAP: usize = 50 * 1024;
/// A hostile sandbox can accept a connection and stop talking. The
/// worker gives every transport step a bounded wait so a room cannot
/// pin a worker forever.
const SSH_STEP_TIMEOUT: Duration = Duration::from_secs(20);
/// Everything a worker needs, and nothing else. It carries one target's
/// decrypted key; the worker never sees the master key, the database,
/// or another room.
#[derive(Clone, Serialize, Deserialize)]
pub struct WorkerConfig {
/// The room's workspace root on the far side.
pub workspace: String,
/// One sandbox target, key text included.
pub target: WorkerTarget,
/// Whether this target may be a local or private address.
#[serde(default)]
pub allow_private: bool,
}
/// One ssh destination and its credential.
#[derive(Clone, Serialize, Deserialize)]
pub struct WorkerTarget {
pub id: String,
pub host: String,
pub port: u16,
pub user_name: String,
pub private_key: String,
pub host_fingerprint: Option<String>,
}
/// One preview request, as the app hands it to the worker. The worker
/// is the only side that parses the sandbox's HTTP reply.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ProxyRequest {
pub port: u16,
pub method: String,
pub path: String,
#[serde(default)]
pub headers: std::collections::BTreeMap<String, String>,
#[serde(default)]
pub body_base64: String,
}
/// The line the worker writes on stdout once its listeners are bound.
/// The parent reads it before the worker serves anything.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Handshake {
pub port: u16,
pub token: String,
}
/// The app-side handle to one worker.
#[derive(Clone, Debug)]
pub struct WorkerClient {
pub http_port: u16,
pub token: String,
}
impl WorkerClient {
/// The worker's loopback base URL, no trailing slash.
pub fn base_url(&self) -> String {
format!("http://127.0.0.1:{}", self.http_port)
}
/// The ordinary sandbox client, pointed at this worker.
pub fn sandbox(&self) -> rhema_sandbox_http::HttpSandbox {
rhema_sandbox_http::HttpSandbox::new(self.base_url(), "room", &self.token)
}
}
/// The worker process for a room, keyed by target and workspace.
#[derive(Default)]
pub struct Workers {
inner: Mutex<HashMap<String, WorkerHandle>>,
}
struct WorkerHandle {
client: WorkerClient,
/// Kept open: the worker exits when this pipe closes, so a parent
/// crash cannot leave an orphan holding the target key.
_stdin: tokio::process::ChildStdin,
_child: tokio::process::Child,
}
impl Workers {
/// The client for `key`, spawning `build`'s worker when there is no
/// live one. The closure runs only on a miss, so a cached worker
/// does not decrypt the target again.
pub async fn client_with<F>(&self, key: &str, build: F) -> Result<WorkerClient, String>
where
F: FnOnce() -> Result<WorkerConfig, String>,
{
let mut workers = self.inner.lock().await;
if let Some(handle) = workers.get_mut(key)
&& handle
._child
.try_wait()
.map(|status| status.is_none())
.unwrap_or(false)
{
return Ok(handle.client.clone());
}
workers.remove(key);
let config = build()?;
let (client, stdin, child) = spawn_worker(config).await?;
workers.insert(
key.to_owned(),
WorkerHandle {
client: client.clone(),
_stdin: stdin,
_child: child,
},
);
Ok(client)
}
/// Drops one worker, killing its process.
pub async fn remove(&self, key: &str) {
self.inner.lock().await.remove(key);
}
/// Drops every worker whose key ends in `workspace`. The archive
/// route uses this so a room that stops running does not leave a
/// process holding its key.
pub async fn remove_workspace(&self, workspace: &str) {
let suffix = format!(":{workspace}");
let mut workers = self.inner.lock().await;
let keys: Vec<String> = workers
.keys()
.filter(|key| key.ends_with(&suffix))
.cloned()
.collect();
for key in keys {
workers.remove(&key);
}
}
/// Drops every worker that names `target`.
pub async fn remove_target(&self, target: &str) {
let prefix = format!("target:{target}:");
let mut workers = self.inner.lock().await;
let keys: Vec<String> = workers
.keys()
.filter(|key| key.starts_with(&prefix))
.cloned()
.collect();
for key in keys {
workers.remove(&key);
}
}
}
/// Starts one worker and waits for its handshake. The config rides the
/// child's stdin, never argv or the environment, so the key does not
/// show up in `ps`.
async fn spawn_worker(
config: WorkerConfig,
) -> Result<
(
WorkerClient,
tokio::process::ChildStdin,
tokio::process::Child,
),
String,
> {
let exe = match std::env::var_os("RHEMA_WORKER_BIN") {
Some(path) => std::path::PathBuf::from(path),
None => std::env::current_exe()
.map_err(|err| format!("could not find the server binary: {err}"))?,
};
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
let mut child = tokio::process::Command::new(exe)
.arg("worker")
// The worker needs no server environment. Clearing it keeps
// provider keys, the secret path, and every other TOGETHER_*
// out of a process that reads hostile bytes for a living.
.env_clear()
.env("HOME", home)
.env("PATH", "/usr/local/bin:/usr/bin:/bin")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::inherit())
.kill_on_drop(true)
.spawn()
.map_err(|err| format!("could not start a sandbox worker: {err}"))?;
let mut stdin = child
.stdin
.take()
.ok_or_else(|| "the worker has no stdin".to_owned())?;
let line = serde_json::to_string(&config)
.map_err(|err| format!("the worker config does not serialize: {err}"))?;
stdin
.write_all(line.as_bytes())
.await
.map_err(|err| format!("could not hand the worker its config: {err}"))?;
stdin
.write_all(b"\n")
.await
.map_err(|err| format!("could not hand the worker its config: {err}"))?;
stdin
.flush()
.await
.map_err(|err| format!("could not hand the worker its config: {err}"))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| "the worker has no stdout".to_owned())?;
let mut reader = tokio::io::BufReader::new(stdout);
let mut answer = String::new();
let read = tokio::time::timeout(
Duration::from_secs(10),
tokio::io::AsyncBufReadExt::read_line(&mut reader, &mut answer),
)
.await
.map_err(|_| "the sandbox worker did not start in time".to_owned())?
.map_err(|err| format!("could not read the worker handshake: {err}"))?;
if read == 0 {
return Err("the sandbox worker exited before its handshake".into());
}
let handshake: Handshake = serde_json::from_str(answer.trim())
.map_err(|err| format!("the worker handshake is malformed: {err}"))?;
Ok((
WorkerClient {
http_port: handshake.port,
token: handshake.token,
},
stdin,
child,
))
}
/// The app-side `Sandbox`: every call goes through the room's worker.
pub struct WorkerSandbox {
state: Shared,
key: String,
workspace: String,
target: TargetRow,
}
impl WorkerSandbox {
pub fn new(state: Shared, workspace: &str, target: &TargetRow) -> Self {
Self {
state,
key: format!("target:{}:{}", target.id, workspace),
workspace: workspace.to_owned(),
target: target.clone(),
}
}
/// The live worker client, spawning or replacing the worker as
/// needed.
pub async fn client(&self) -> Result<WorkerClient, SandboxError> {
let state = self.state.clone();
let workspace = self.workspace.clone();
let target = self.target.clone();
let build = move || -> Result<WorkerConfig, String> {
let key = state
.secrets
.open_str(&target.private_key_ciphertext)
.map_err(|err| err.message)?;
Ok(WorkerConfig {
workspace: workspace.clone(),
target: WorkerTarget {
id: target.id.clone(),
host: target.host.clone(),
port: u16::try_from(target.port).unwrap_or(22),
user_name: target.user_name.clone(),
private_key: key,
host_fingerprint: target.host_fingerprint.clone(),
},
allow_private: state.config.allow_private_targets,
})
};
self.state
.workers
.client_with(&self.key, build)
.await
.map_err(SandboxError::Unavailable)
}
/// Drops the worker after a transport failure, so the next call
/// starts a fresh one.
async fn forget(&self) {
self.state.workers.remove(&self.key).await;
}
}
#[async_trait::async_trait]
impl Sandbox for WorkerSandbox {
async fn run(
&self,
request: rhema_sandbox::RunRequest,
cancelled: &std::sync::atomic::AtomicBool,
progress: &mut dyn rhema_sandbox::ToolProgress,
) -> Result<rhema_sandbox::RunOutcome, SandboxError> {
for attempt in 0..2 {
let client = self.client().await?;
match client
.sandbox()
.run(request.clone(), cancelled, progress)
.await
{
Ok(outcome) => return Ok(outcome),
Err(SandboxError::Unavailable(err)) if attempt == 0 => {
tracing::warn!(worker = %self.key, error = %err, "sandbox worker unavailable, restarting");
self.forget().await;
}
Err(err) => return Err(err),
}
}
unreachable!("two attempts either return or forget")
}
async fn seed(&self, seed: &WorkspaceSeed) -> Result<(), SandboxError> {
for attempt in 0..2 {
let client = self.client().await?;
match client.sandbox().seed(seed).await {
Ok(()) => return Ok(()),
Err(SandboxError::Unavailable(err)) if attempt == 0 => {
tracing::warn!(worker = %self.key, error = %err, "sandbox worker unavailable, restarting");
self.forget().await;
}
Err(err) => return Err(err),
}
}
unreachable!("two attempts either return or forget")
}
async fn read_file(&self, path: &str) -> Result<Vec<u8>, SandboxError> {
for attempt in 0..2 {
let client = self.client().await?;
match client.sandbox().read_file(path).await {
Ok(bytes) => return Ok(bytes),
Err(SandboxError::Unavailable(err)) if attempt == 0 => {
tracing::warn!(worker = %self.key, error = %err, "sandbox worker unavailable, restarting");
self.forget().await;
}
Err(err) => return Err(err),
}
}
unreachable!("two attempts either return or forget")
}
async fn write_file(&self, path: &str, contents: &[u8]) -> Result<(), SandboxError> {
for attempt in 0..2 {
let client = self.client().await?;
match client.sandbox().write_file(path, contents).await {
Ok(()) => return Ok(()),
Err(SandboxError::Unavailable(err)) if attempt == 0 => {
tracing::warn!(worker = %self.key, error = %err, "sandbox worker unavailable, restarting");
self.forget().await;
}
Err(err) => return Err(err),
}
}
unreachable!("two attempts either return or forget")
}
}
/// The app-side client for a room's worker, for the terminal and preview
/// proxies that speak a socket rather than the `Sandbox` trait.
pub async fn client_for(
state: &Shared,
workspace: &str,
target: &TargetRow,
) -> Result<WorkerClient, String> {
WorkerSandbox::new(state.clone(), workspace, target)
.client()
.await
.map_err(|err| err.to_string())
}
// ---------------------------------------------------------------------
// The worker process itself.
// ---------------------------------------------------------------------
/// Runs the worker role. The config arrives on stdin; the handshake and
/// the sandbox routes go over loopback.
pub async fn run_worker() -> anyhow::Result<()> {
// A worker holds a target key; keep it out of core dumps and make
// sure no new privilege can be gained here. Both calls are Linux
// only; other Unix targets keep the process boundary alone.
#[cfg(target_os = "linux")]
{
let _ = nix::sys::prctl::set_dumpable(false);
let _ = nix::sys::prctl::set_no_new_privs();
}
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
let config: WorkerConfig = serde_json::from_str(line.trim())?;
if !config.allow_private {
crate::util::check_target_address(&config.target.host, config.target.port)
.await
.map_err(|err| anyhow::anyhow!(err))?;
}
let token = crate::util::random_token(32);
let http = TcpListener::bind(("127.0.0.1", 0)).await?;
let handshake = Handshake {
port: http.local_addr()?.port(),
token: token.clone(),
};
{
use std::io::Write;
let mut out = std::io::stdout();
writeln!(out, "{}", serde_json::to_string(&handshake)?)?;
out.flush()?;
}
// The parent holds the write end of stdin for the worker's life. A
// closed pipe means the server is gone, and a worker without a
// server must not linger with a target key.
tokio::spawn(async move {
let mut stdin = tokio::io::stdin();
let mut sink = [0u8; 1024];
loop {
match stdin.read(&mut sink).await {
Ok(0) | Err(_) => std::process::exit(0),
Ok(_) => {}
}
}
});
let destination = format!(
"{}@{}:{}",
config.target.user_name, config.target.host, config.target.port
);
let sandbox = SshSandbox::new(destination)
.with_workspace(config.workspace.clone())
.with_private_key(config.target.private_key.clone());
let state = Arc::new(WorkerState {
sandbox,
target: config.target,
workspace: config.workspace,
token: token.clone(),
preview: Mutex::new(None),
});
let app = Router::new()
.route("/{session}/exec", post(exec))
.route("/{session}/put", post(put))
.route("/{session}/get", post(read_file_route))
.route("/{session}/seed", post(seed))
.route("/{session}/proxy", post(proxy))
.route("/pty", get_route(pty))
.layer(axum::middleware::from_fn_with_state(state.clone(), auth))
.layer(axum::extract::DefaultBodyLimit::max(FILE_CAP + 1024 * 1024))
.with_state(state);
axum::serve(http, app).await?;
Ok(())
}
struct WorkerState {
sandbox: SshSandbox,
target: WorkerTarget,
workspace: String,
token: String,
/// The preview proxy's ssh connection, opened on first use and
/// reused by every forwarded channel. A dead handle is replaced.
preview: Mutex<Option<Arc<russh::client::Handle<crate::ssh::HostKey>>>>,
}
impl WorkerState {
fn target_row(&self) -> TargetRow {
TargetRow {
id: self.target.id.clone(),
host: self.target.host.clone(),
port: i64::from(self.target.port),
user_name: self.target.user_name.clone(),
private_key_ciphertext: String::new(),
host_fingerprint: self.target.host_fingerprint.clone(),
}
}
}
async fn auth(
State(state): State<Arc<WorkerState>>,
headers: HeaderMap,
request: axum::extract::Request,
next: axum::middleware::Next,
) -> Response {
let presented = headers
.get(TOKEN_HEADER)
.and_then(|value| value.to_str().ok())
.unwrap_or("");
if presented != state.token {
return (StatusCode::UNAUTHORIZED, "bad sandbox token").into_response();
}
next.run(request).await
}
async fn exec(
State(state): State<Arc<WorkerState>>,
Json(call): Json<ExecCall>,
) -> Result<Json<ExecReply>, (StatusCode, String)> {
let cwd = call.cwd.unwrap_or_else(|| state.workspace.clone());
if !inside(&state.workspace, &cwd) {
return Err((
StatusCode::FORBIDDEN,
"the command cwd is outside the room workspace".into(),
));
}
let request = rhema_sandbox::RunRequest {
command: call.command,
cwd: cwd.into(),
timeout: Duration::from_secs(call.timeout_secs.max(1)),
env: call.env,
};
let cancelled = std::sync::atomic::AtomicBool::new(false);
let mut progress = rhema_sandbox::OutputOnly(|_| {});
match state.sandbox.run(request, &cancelled, &mut progress).await {
Ok(outcome) => Ok(Json(ExecReply {
exit_code: outcome.code,
stdout: tail(&outcome.stdout),
stderr: tail(&outcome.stderr),
timed_out: false,
})),
Err(SandboxError::Timeout(_)) => Ok(Json(ExecReply {
exit_code: Some(124),
stdout: String::new(),
stderr: String::new(),
timed_out: true,
})),
Err(err) => Err((StatusCode::BAD_GATEWAY, err.to_string())),
}
}
#[derive(Deserialize)]
struct PathBody {
path: String,
}
async fn read_file_route(
State(state): State<Arc<WorkerState>>,
Json(body): Json<PathBody>,
) -> Json<FileReply> {
if !inside(&state.workspace, &body.path) || body.path.split('/').any(|part| part == "..") {
return Json(FileReply {
content_base64: None,
error: Some("the path is outside the room workspace".into()),
});
}
match state.sandbox.read_file(&body.path).await {
Ok(bytes) if bytes.len() <= FILE_CAP => Json(FileReply {
content_base64: Some(base64::engine::general_purpose::STANDARD.encode(bytes)),
error: None,
}),
Ok(_) => Json(FileReply {
content_base64: None,
error: Some("the file is larger than the sandbox route allows".into()),
}),
Err(err) => Json(FileReply {
content_base64: None,
error: Some(err.to_string()),
}),
}
}
async fn put(State(state): State<Arc<WorkerState>>, Json(body): Json<PutFile>) -> Json<Ack> {
if !inside(&state.workspace, &body.path) || body.path.split('/').any(|part| part == "..") {
return Json(Ack {
error: Some("the path is outside the room workspace".into()),
});
}
let bytes = match base64::engine::general_purpose::STANDARD.decode(&body.content_base64) {
Ok(bytes) => bytes,
Err(err) => {
return Json(Ack {
error: Some(format!("the file body is not base64: {err}")),
});
}
};
if bytes.len() > FILE_CAP {
return Json(Ack {
error: Some("the file is larger than the sandbox route allows".into()),
});
}
match state.sandbox.write_file(&body.path, &bytes).await {
Ok(()) => Json(Ack { error: None }),
Err(err) => Json(Ack {
error: Some(err.to_string()),
}),
}
}
async fn seed(State(state): State<Arc<WorkerState>>, Json(body): Json<SeedRequest>) -> Json<Ack> {
let seed = match body {
SeedRequest::Git { git } => WorkspaceSeed::GitClone(git),
SeedRequest::Tarball {
tarball_base64,
tarball_name,
} => WorkspaceSeed::Tarball {
name: tarball_name.unwrap_or_else(|| "room-seed".into()),
tar_gz_base64: tarball_base64,
},
};
match state.sandbox.seed(&seed).await {
Ok(()) => Json(Ack { error: None }),
Err(err) => Json(Ack {
error: Some(err.to_string()),
}),
}
}
async fn proxy(
State(state): State<Arc<WorkerState>>,
Json(request): Json<ProxyRequest>,
) -> Result<Response, (StatusCode, String)> {
const PROXY_BODY_CAP: usize = 16 * 1024 * 1024;
let body = base64::engine::general_purpose::STANDARD
.decode(&request.body_base64)
.map_err(|err| {
(
StatusCode::BAD_REQUEST,
format!("the proxy body is not base64: {err}"),
)
})?;
if body.len() > PROXY_BODY_CAP {
return Err((
StatusCode::PAYLOAD_TOO_LARGE,
"the proxy body is larger than the route allows".into(),
));
}
let method = request
.method
.parse::<Method>()
.map_err(|err| (StatusCode::BAD_REQUEST, format!("bad proxy method: {err}")))?;
let path = if request.path.starts_with('/') {
request.path.clone()
} else {
format!("/{}", request.path)
};
let remote = tokio::time::timeout(SSH_STEP_TIMEOUT, preview_channel(&state, request.port))
.await
.map_err(|_| {
(
StatusCode::GATEWAY_TIMEOUT,
"the preview did not answer in time".into(),
)
})?
.map_err(|err| (StatusCode::BAD_GATEWAY, err))?;
let io = hyper_util::rt::TokioIo::new(remote);
let (mut sender, connection) =
hyper::client::conn::http1::handshake(io)
.await
.map_err(|err| {
(
StatusCode::BAD_GATEWAY,
format!("http handshake failed: {err}"),
)
})?;
tokio::spawn(async move {
let _ = connection.await;
});
let mut builder = hyper::Request::builder().method(method).uri(path);
for (name, value) in &request.headers {
if let (Ok(name), Ok(value)) = (
HeaderName::from_bytes(name.as_bytes()),
HeaderValue::from_str(value),
) {
builder = builder.header(name, value);
}
}
// Hyper sets the length from the body; a stale browser header would
// make it disagree with the bytes.
let outbound = builder
.body(Full::new(Bytes::from(body)))
.map_err(|err| (StatusCode::BAD_REQUEST, format!("bad proxy request: {err}")))?;
let reply = sender.send_request(outbound).await.map_err(|err| {
(
StatusCode::BAD_GATEWAY,
format!("the preview did not answer: {err}"),
)
})?;
let (parts, body) = reply.into_parts();
let stream = body.into_data_stream();
let body = Body::from_stream(stream.map_err(|err| std::io::Error::other(err.to_string())));
let mut out = Response::new(body);
*out.status_mut() = parts.status;
*out.headers_mut() = parts.headers;
strip_hop_by_hop(out.headers_mut());
Ok(out)
}
async fn pty(
State(state): State<Arc<WorkerState>>,
Query(query): Query<HashMap<String, String>>,
ws: WebSocketUpgrade,
) -> Response {
let cols = query
.get("cols")
.and_then(|value| value.parse().ok())
.unwrap_or(100);
let rows = query
.get("rows")
.and_then(|value| value.parse().ok())
.unwrap_or(30);
let target = state.target_row();
let key = state.target.private_key.clone();
let workspace = state.workspace.clone();
ws.on_upgrade(move |socket| async move {
crate::ssh::terminal_with_key(socket, &target, &key, &workspace, cols, rows).await;
})
}
async fn preview_channel(
state: &WorkerState,
port: u16,
) -> Result<russh::ChannelStream<russh::client::Msg>, String> {
let mut slot = state.preview.lock().await;
if let Some(handle) = slot.as_ref() {
match tokio::time::timeout(
SSH_STEP_TIMEOUT,
handle.channel_open_direct_tcpip("127.0.0.1", u32::from(port), "127.0.0.1", 0),
)
.await
{
Ok(Ok(channel)) => return Ok(channel.into_stream()),
_ => {
*slot = None;
}
}
}
let target = state.target_row();
let (handle, _learned) = tokio::time::timeout(
SSH_STEP_TIMEOUT,
crate::ssh::connect_with_key(&target, &state.target.private_key),
)
.await
.map_err(|_| "the sandbox did not answer in time".to_owned())??;
let handle = Arc::new(handle);
let channel = tokio::time::timeout(
SSH_STEP_TIMEOUT,
handle.channel_open_direct_tcpip("127.0.0.1", u32::from(port), "127.0.0.1", 0),
)
.await
.map_err(|_| "the sandbox refused port in time".to_owned())?
.map_err(|err| format!("the sandbox refused port {port}: {err}"))?;
*slot = Some(handle);
Ok(channel.into_stream())
}
fn strip_hop_by_hop(headers: &mut HeaderMap) {
for name in [
axum::http::header::CONNECTION,
HeaderName::from_static("keep-alive"),
HeaderName::from_static("proxy-authenticate"),
HeaderName::from_static("proxy-authorization"),
axum::http::header::TE,
axum::http::header::TRAILER,
axum::http::header::TRANSFER_ENCODING,
axum::http::header::UPGRADE,
] {
headers.remove(name);
}
}
fn inside(workspace: &str, path: &str) -> bool {
let root = workspace.trim_end_matches('/');
if root.is_empty() {
return path.starts_with('/');
}
path == root || path.starts_with(&format!("{root}/"))
}
fn tail(bytes: &[u8]) -> String {
let start = bytes.len().saturating_sub(OUTPUT_CAP);
String::from_utf8_lossy(&bytes[start..]).into_owned()
}
#[cfg(test)]
mod tests {
use super::{inside, tail};
#[test]
fn workspace_paths_stay_inside() {
assert!(inside("/srv/room", "/srv/room"));
assert!(inside("/srv/room", "/srv/room/project"));
assert!(inside("/srv/room/", "/srv/room/project"));
assert!(!inside("/srv/room", "/srv/room-2"));
assert!(!inside("/srv/room", "/srv"));
assert!(!inside("/srv/room", "/etc/passwd"));
}
#[test]
fn a_root_workspace_accepts_absolute_paths() {
assert!(inside("/", "/"));
assert!(inside("/", "/tmp/project"));
}
#[test]
fn the_output_tail_is_capped() {
let text = "x".repeat(70_000);
assert_eq!(tail(text.as_bytes()).len(), 50 * 1024);
}
}
#[cfg(test)]
mod smoke {
//! A manual end-to-end check of the `WorkerSandbox` path. It needs a
//! local sshd and a key; run with
//! `cargo test worker_sandbox_round_trip -- --ignored --nocapture`.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use super::WorkerSandbox;
use crate::config::Config;
use crate::crypto::Secrets;
use crate::db::Db;
use crate::room::agent::TargetRow;
use crate::state::{AppState, Hub};
use rhema_sandbox::Sandbox;
#[tokio::test]
#[ignore]
async fn worker_sandbox_round_trip() {
let dir = PathBuf::from("/tmp/rhema-worker-test");
let key = std::fs::read_to_string(dir.join("client_ed25519")).expect("client key");
let config = Config {
allow_private_targets: true,
..Config::default()
};
let db = Db::open(&dir.join("smoke.db")).expect("db");
let secrets = Secrets::load_or_create(&dir.join("smoke.key")).expect("secrets");
let target = TargetRow {
id: "smoke".into(),
host: "127.0.0.1".into(),
port: 2223,
user_name: "vhaudiquet".into(),
private_key_ciphertext: secrets.seal_str(&key).expect("seal"),
host_fingerprint: None,
};
let state = Arc::new(AppState {
config,
db,
secrets,
hub: Hub::default(),
rooms: Default::default(),
workers: Default::default(),
presence: Default::default(),
logins: Default::default(),
});
let sandbox = WorkerSandbox::new(state, &dir.join("ws").to_string_lossy(), &target);
let cancelled = AtomicBool::new(false);
let mut progress = rhema_sandbox::OutputOnly(|_| {});
let outcome = sandbox
.run(
rhema_sandbox::RunRequest {
command: "printf worker-ok".into(),
cwd: dir.join("ws"),
timeout: Duration::from_secs(20),
env: Default::default(),
},
&cancelled,
&mut progress,
)
.await
.expect("run");
assert_eq!(String::from_utf8_lossy(&outcome.stdout).trim(), "worker-ok");
}
}