use std::sync::Arc;
use async_trait::async_trait;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine as _;
use serde::Deserialize;
use serde_json::json;
use super::agent_protocol::{self, RUN_INTERACTIVE, SIGNAL};
use crate::error::{ErrorData, Result};
use crate::traits::{CommandInput, CommandSignal, InteractiveCommand, RunCommandRequest};
use alien_error::{AlienError, Context, IntoAlienError};
const MAX_WRITE_BYTES: usize = 256 * 1024;
const WRITE_ATTEMPTS: usize = 4;
const WRITE_STDIN: &str = "sandbox.interactive.write";
const CLOSE_STDIN: &str = "sandbox.interactive.closeStdin";
#[async_trait]
pub trait BoundAgent: Send + Sync + std::fmt::Debug {
async fn request(&self, method: reqwest::Method, path: &str)
-> Result<reqwest::RequestBuilder>;
fn provider(&self) -> &'static str;
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct StdinResponse {
accepted: u64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct BarrierResponse {
accepted: u64,
generation: u64,
}
pub async fn run_interactive(
agent: Arc<dyn BoundAgent>,
request: RunCommandRequest,
) -> Result<InteractiveCommand> {
let id = uuid::Uuid::new_v4().to_string();
let mut body = agent_protocol::exec_body(&request)?;
body["id"] = json!(id);
let response = agent_protocol::send(
agent
.request(reqwest::Method::POST, "/v1/interactive")
.await?
.json(&body),
RUN_INTERACTIVE,
)
.await?;
let output = agent_protocol::frame_stream(response, agent.provider(), request.timeout);
Ok(InteractiveCommand {
input: Arc::new(AgentInput {
agent,
id,
state: tokio::sync::Mutex::new(InputState {
offset: 0,
generation: 0,
interrupted: false,
}),
}),
output,
})
}
#[derive(Debug)]
struct AgentInput {
agent: Arc<dyn BoundAgent>,
id: String,
state: tokio::sync::Mutex<InputState>,
}
#[derive(Debug)]
struct InputState {
offset: u64,
generation: u64,
interrupted: bool,
}
fn named_failure(body: &str) -> Option<&'static str> {
[
("COMMAND_NOT_RUNNING", "commandNotRunning"),
("STDIN_CLOSED", "stdinClosed"),
("STDIN_OFFSET_MISMATCH", "stdinOffsetMismatch"),
("STDIN_STALE_WRITE", "stdinStaleWrite"),
("INTERACTIVE_LIMIT_REACHED", "interactiveLimitReached"),
]
.into_iter()
.find(|(code, _)| body.starts_with(code))
.map(|(_, failure)| failure)
}
impl AgentInput {
async fn control(
&self,
path: &str,
body: serde_json::Value,
operation: &str,
) -> Result<reqwest::Response> {
let response = agent_protocol::send_raw(
self.agent
.request(reqwest::Method::POST, path)
.await?
.json(&body),
operation,
)
.await?;
if response.status().is_success() {
return Ok(response);
}
let status = response.status();
let body = agent_protocol::error_body(response, operation).await?;
if let Some(failure) = named_failure(&body) {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: failure.to_string(),
reason: format!("{operation}: {body}"),
}));
}
if status.is_server_error() {
return Err(AlienError::new(agent_protocol::unanswered(
operation,
&format!("the sandbox host returned {status}: {body}"),
)));
}
Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "agentRefused".to_string(),
reason: format!("{operation} returned {status}: {body}"),
}))
}
async fn send_repeatable<T: serde::de::DeserializeOwned>(
&self,
path: &str,
body: serde_json::Value,
operation: &str,
field: &str,
) -> Result<T> {
let mut attempt = 0;
let answer = loop {
attempt += 1;
let sent = match self.control(path, body.clone(), operation).await {
Ok(response) => agent_protocol::bounded_body(response, operation).await,
Err(error) => Err(error),
};
match sent {
Ok(answer) => break answer,
Err(error) if error.retryable && attempt < WRITE_ATTEMPTS => continue,
Err(error) => return Err(error),
}
};
serde_json::from_slice(&answer).into_alien_error().context(
ErrorData::UnexpectedResponseFormat {
provider: self.agent.provider().to_string(),
binding_name: operation.to_string(),
field: field.to_string(),
response_json: "the agent returned a body this provider cannot parse".to_string(),
},
)
}
async fn send_piece(&self, generation: u64, offset: u64, piece: &[u8]) -> Result<u64> {
let body = json!({
"id": self.id,
"generation": generation,
"offset": offset,
"data": BASE64.encode(piece),
});
let taken: StdinResponse = self
.send_repeatable("/v1/interactive/stdin", body, WRITE_STDIN, "accepted")
.await?;
Ok(taken.accepted)
}
async fn barrier(&self, generation: u64) -> Result<BarrierResponse> {
self.send_repeatable(
"/v1/interactive/stdin-barrier",
json!({ "id": self.id, "generation": generation }),
WRITE_STDIN,
"generation",
)
.await
}
}
#[async_trait]
impl CommandInput for AgentInput {
async fn write(&self, data: &[u8]) -> Result<()> {
let mut state = self.state.lock().await;
if state.interrupted {
let BarrierResponse {
accepted: taken,
generation,
} = self.barrier(state.generation + 1).await?;
state.generation = generation;
state.interrupted = false;
if taken != state.offset {
let lost = taken.saturating_sub(state.offset);
state.offset = taken.max(state.offset);
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "stdinInterrupted".to_string(),
reason: format!(
"an earlier write was cancelled or failed after the program took {lost} of \
its bytes; this write was not sent, and the next one continues after them"
),
}));
}
}
let start = state.offset;
let end = start + data.len() as u64;
state.interrupted = true;
while state.offset < end {
let from = usize::try_from(state.offset - start).expect("within data");
let piece = &data[from..(from + MAX_WRITE_BYTES).min(data.len())];
let taken = self
.send_piece(state.generation, state.offset, piece)
.await?;
if taken < state.offset || taken > end {
return Err(AlienError::new(ErrorData::SandboxCommandFailed {
failure: "stdinOffsetMismatch".to_string(),
reason: format!(
"the agent reports {taken} bytes of input taken after a write of bytes \
{}..{end}",
state.offset
),
}));
}
state.offset = taken;
}
state.interrupted = false;
Ok(())
}
async fn close_stdin(&self) -> Result<()> {
let _state = self.state.lock().await;
match self
.control(
"/v1/interactive/close-stdin",
json!({ "id": self.id }),
CLOSE_STDIN,
)
.await
{
Ok(_) => Ok(()),
Err(error)
if matches!(
&error.error,
Some(ErrorData::SandboxCommandFailed { failure, .. })
if failure == "commandNotRunning"
) =>
{
Ok(())
}
Err(error) => Err(error),
}
}
async fn signal(&self, signal: CommandSignal) -> Result<()> {
self.control(
"/v1/interactive/signal",
json!({ "id": self.id, "signal": signal }),
SIGNAL,
)
.await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::CommandOutput;
use alien_core::sandbox_capability::{
SandboxCapabilityClaims, SandboxOperationClass, SandboxSessionIdentity,
};
use alien_sandbox_agent::exec::ExecIdentity;
use alien_sandbox_agent::server::{router, AgentAuthorization, AgentState};
use ed25519_compact::{KeyPair, Seed};
use futures::StreamExt;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
const SESSION: &str = "interactive-session";
#[derive(Debug)]
struct LoopbackAgent {
url: String,
token: String,
unanswered_writes: AtomicUsize,
stalled_acks: AtomicUsize,
stall_url: String,
unanswered_signals: AtomicUsize,
_root: tempfile::TempDir,
}
fn take_one(left: &AtomicUsize) -> bool {
left.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |left| {
left.checked_sub(1)
})
.is_ok()
}
async fn stalling_server(agent_url: String) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move {
while let Ok((mut socket, _)) = listener.accept().await {
let agent_url = agent_url.clone();
tokio::spawn(async move {
let mut request = Vec::new();
let mut buffer = [0u8; 8192];
let head_end = loop {
let read = socket.read(&mut buffer).await.unwrap();
assert!(read > 0, "the client sent a whole request");
request.extend_from_slice(&buffer[..read]);
if let Some(at) = request.windows(4).position(|w| w == b"\r\n\r\n") {
break at + 4;
}
};
let head = String::from_utf8_lossy(&request[..head_end]).to_string();
let header = |name: &str| {
head.lines().find_map(|line| {
let (key, value) = line.split_once(':')?;
key.eq_ignore_ascii_case(name)
.then(|| value.trim().to_string())
})
};
let length: usize = header("content-length").unwrap().parse().unwrap();
while request.len() < head_end + length {
let read = socket.read(&mut buffer).await.unwrap();
request.extend_from_slice(&buffer[..read]);
}
let path = head.split_whitespace().nth(1).unwrap().to_string();
let answer = reqwest::Client::new()
.post(format!("{agent_url}{path}"))
.header("authorization", header("authorization").unwrap())
.header("content-type", "application/json")
.body(request[head_end..head_end + length].to_vec())
.send()
.await
.unwrap();
let status = answer.status().as_u16();
let body = answer.bytes().await.unwrap();
let mut reply = format!(
"HTTP/1.1 {status} OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n",
body.len()
)
.into_bytes();
reply.extend_from_slice(&body[..1]);
socket.write_all(&reply).await.unwrap();
tokio::time::sleep(Duration::from_secs(3600)).await;
});
}
});
url
}
#[async_trait]
impl BoundAgent for LoopbackAgent {
async fn request(
&self,
method: reqwest::Method,
path: &str,
) -> Result<reqwest::RequestBuilder> {
let base = if path == "/v1/interactive/stdin" && take_one(&self.unanswered_writes)
|| path == "/v1/interactive/signal" && take_one(&self.unanswered_signals)
{
"http://127.0.0.1:9".to_string()
} else if path == "/v1/interactive/stdin" && take_one(&self.stalled_acks) {
self.stall_url.clone()
} else {
self.url.clone()
};
Ok(reqwest::Client::new()
.request(method, format!("{base}{path}"))
.bearer_auth(&self.token))
}
fn provider(&self) -> &'static str {
"loopback-agent"
}
}
async fn agent(unanswered_writes: usize) -> Arc<LoopbackAgent> {
stalling_agent(unanswered_writes, 0).await
}
async fn stalling_agent(unanswered_writes: usize, stalled_acks: usize) -> Arc<LoopbackAgent> {
let root = tempfile::TempDir::new().unwrap();
let keys = KeyPair::from_seed(Seed::new([7u8; 32]));
let state = Arc::new(AgentState {
image_process: alien_sandbox_agent::image_command::ImageProcess::not_configured(),
#[cfg(target_os = "linux")]
gateway_egress: None,
session_root: root.path().canonicalize().unwrap(),
authorization: AgentAuthorization::Capability {
public_key: keys.pk,
identity: SandboxSessionIdentity {
session_id: SESSION.to_string(),
generation: 1,
},
},
exec_identity: {
use std::os::unix::fs::MetadataExt;
let metadata = std::fs::metadata(root.path()).unwrap();
ExecIdentity {
uid: metadata.uid(),
gid: metadata.gid(),
}
},
output_cap: 1 << 24,
jobs: Default::default(),
interactive: Default::default(),
agent_binary: std::path::PathBuf::from("/bin/false"),
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move {
axum::serve(
listener,
router(state).into_make_service_with_connect_info::<SocketAddr>(),
)
.await
.unwrap();
});
let token = alien_core::sandbox_capability_token::mint(
&SandboxCapabilityClaims {
session_id: SESSION.to_string(),
operation: SandboxOperationClass::Execute,
generation: 1,
expires_at: chrono::Utc::now().timestamp() + 300,
key_id: "k1".to_string(),
},
&keys.sk,
)
.unwrap();
let stall_url = stalling_server(url.clone()).await;
Arc::new(LoopbackAgent {
url,
token,
unanswered_writes: AtomicUsize::new(unanswered_writes),
stalled_acks: AtomicUsize::new(stalled_acks),
stall_url,
unanswered_signals: AtomicUsize::new(0),
_root: root,
})
}
fn command(program: &str, args: &[&str]) -> RunCommandRequest {
RunCommandRequest {
command: program.to_string(),
args: args.iter().map(|arg| arg.to_string()).collect(),
cwd: None,
env: Default::default(),
timeout: Duration::from_secs(30),
}
}
async fn read_until(command: &mut InteractiveCommand, stdout: &mut Vec<u8>, expected: &str) {
while !String::from_utf8_lossy(stdout).ends_with(expected) {
match tokio::time::timeout(Duration::from_secs(10), command.output.next())
.await
.expect("output arrives")
.expect("the stream is still open")
.expect("a frame")
{
CommandOutput::Stdout { data, .. } => stdout.extend(data),
CommandOutput::Stderr { .. } => {}
other => panic!("ended before {expected:?}: {other:?}"),
}
}
}
async fn finish(mut command: InteractiveCommand, stdout: &mut Vec<u8>) -> CommandOutput {
let mut terminal = None;
while let Some(item) = tokio::time::timeout(Duration::from_secs(10), command.output.next())
.await
.expect("the stream ends")
{
match item.expect("a frame") {
CommandOutput::Stdout { data, .. } => stdout.extend(data),
CommandOutput::Stderr { .. } => {}
exit => {
assert!(terminal.is_none(), "exactly one terminal frame");
terminal = Some(exit);
}
}
}
terminal.expect("a terminal frame")
}
#[tokio::test]
async fn a_program_is_driven_turn_by_turn_through_the_binding() {
let agent = agent(0).await;
let mut command = run_interactive(
agent,
command(
"/bin/sh",
&[
"-c",
"printf '> '; while read l; do echo \"=$l\"; printf '> '; done",
],
),
)
.await
.expect("starts");
let mut stdout = Vec::new();
read_until(&mut command, &mut stdout, "> ").await;
command.input.write(b"1+1\n").await.expect("writes");
read_until(&mut command, &mut stdout, "=1+1\n> ").await;
command.input.close_stdin().await.expect("closes");
command
.input
.close_stdin()
.await
.expect("closing twice is fine");
assert_eq!(
finish(command, &mut stdout).await,
CommandOutput::Exit {
code: 0,
truncated: false
}
);
assert_eq!(String::from_utf8_lossy(&stdout), "> =1+1\n> ");
}
#[tokio::test]
async fn large_input_arrives_whole_across_a_lost_request() {
let agent = agent(1).await;
let command = run_interactive(agent, command("/usr/bin/wc", &["-c"]))
.await
.expect("starts");
command
.input
.write(&vec![b'x'; 3 * MAX_WRITE_BYTES + 17])
.await
.expect("every piece is taken");
command.input.close_stdin().await.expect("closes");
let mut stdout = Vec::new();
assert!(matches!(
finish(command, &mut stdout).await,
CommandOutput::Exit { code: 0, .. }
));
assert_eq!(
String::from_utf8_lossy(&stdout).trim(),
(3 * MAX_WRITE_BYTES + 17).to_string()
);
}
#[tokio::test]
async fn a_signal_after_the_command_ended_says_it_is_not_running() {
let agent = agent(0).await;
let command = run_interactive(agent, command("/bin/sh", &["-c", "exit 3"]))
.await
.expect("starts");
let input = Arc::clone(&command.input);
let mut stdout = Vec::new();
assert!(matches!(
finish(command, &mut stdout).await,
CommandOutput::Exit { code: 3, .. }
));
let error = input
.signal(CommandSignal::Interrupt)
.await
.expect_err("nothing is running");
assert!(
matches!(&error.error, Some(ErrorData::SandboxCommandFailed { failure, .. }) if failure == "commandNotRunning"),
"{error:?}"
);
}
#[tokio::test]
async fn an_interrupt_reaches_a_running_program() {
let agent = agent(0).await;
let mut command = run_interactive(
agent,
command(
"/bin/sh",
&[
"-c",
"trap 'echo stopped; exit 130' INT; echo up; while :; do sleep 0.05; done",
],
),
)
.await
.expect("starts");
let mut stdout = Vec::new();
read_until(&mut command, &mut stdout, "up\n").await;
command
.input
.signal(CommandSignal::Interrupt)
.await
.expect("signals");
assert!(matches!(
finish(command, &mut stdout).await,
CommandOutput::Exit { code: 130, .. }
));
assert!(String::from_utf8_lossy(&stdout).ends_with("stopped\n"));
}
#[tokio::test]
async fn an_unanswered_signal_is_reported_unknown_and_not_sent_again() {
let agent = agent(0).await;
agent.unanswered_signals.store(1, Ordering::SeqCst);
let mut command = run_interactive(
Arc::clone(&agent) as Arc<dyn BoundAgent>,
command(
"/bin/sh",
&[
"-c",
"trap 'echo interrupted' INT; echo up; read line; echo done",
],
),
)
.await
.expect("starts");
let mut stdout = Vec::new();
read_until(&mut command, &mut stdout, "up\n").await;
let error = command
.input
.signal(CommandSignal::Interrupt)
.await
.expect_err("the signal went unanswered");
assert!(
matches!(&error.error, Some(ErrorData::SandboxOutcomeUnknown { .. })),
"{error:?}"
);
assert!(!error.retryable, "an unanswered signal is not to be resent");
assert_eq!(
agent.unanswered_signals.load(Ordering::SeqCst),
0,
"it was sent once, to the unanswering address"
);
command.input.write(b"\n").await.expect("writes");
command.input.close_stdin().await.expect("closes");
assert!(matches!(
finish(command, &mut stdout).await,
CommandOutput::Exit { code: 0, .. }
));
assert_eq!(
String::from_utf8_lossy(&stdout),
"up\ndone\n",
"the program never got the interrupt, which was never resent"
);
}
#[tokio::test]
async fn a_write_whose_answer_stalls_after_its_headers_is_sent_again() {
let agent = stalling_agent(0, 2).await;
let command = run_interactive(agent, command("/bin/sh", &["-c", "wc -c"]))
.await
.expect("starts");
tokio::time::timeout(
agent_protocol::AGENT_RESPONSE_TIMEOUT * 20,
command.input.write(b"hello"),
)
.await
.expect("the write does not wait on a stalled body")
.expect("the write lands on a later attempt");
command.input.close_stdin().await.expect("closes");
let mut stdout = Vec::new();
assert!(matches!(
finish(command, &mut stdout).await,
CommandOutput::Exit { code: 0, .. }
));
assert_eq!(String::from_utf8_lossy(&stdout).trim(), "5", "applied once");
}
#[tokio::test]
async fn a_write_after_a_cancelled_one_reports_the_interruption_instead_of_losing_bytes() {
let agent = agent(0).await;
let go = agent._root.path().join("go");
let command = run_interactive(
Arc::clone(&agent) as Arc<dyn BoundAgent>,
command(
"/bin/sh",
&[
"-c",
"while [ ! -e go ]; do sleep 0.05; done; tr -cd y | wc -c",
],
),
)
.await
.expect("starts");
let cancelled = tokio::time::timeout(
Duration::from_millis(100),
command.input.write(&vec![b'x'; 2 * MAX_WRITE_BYTES]),
)
.await;
assert!(
cancelled.is_err(),
"the write was still waiting on the reader"
);
let second = vec![b'y'; 3 * MAX_WRITE_BYTES];
let error = command
.input
.write(&second)
.await
.expect_err("the interruption is reported, not hidden");
assert!(
matches!(&error.error, Some(ErrorData::SandboxCommandFailed { failure, .. }) if failure == "stdinInterrupted"),
"{error:?}"
);
std::fs::write(&go, b"").expect("lets the program read");
command
.input
.write(&second)
.await
.expect("the stream continues");
command.input.close_stdin().await.expect("closes");
let mut stdout = Vec::new();
assert!(matches!(
finish(command, &mut stdout).await,
CommandOutput::Exit { code: 0, .. }
));
assert_eq!(
String::from_utf8_lossy(&stdout).trim(),
second.len().to_string(),
"the write after the report arrives whole"
);
}
}