use std::borrow::Cow;
use std::time::{Duration, Instant};
use std::{error, fmt, mem};
use futures_timer::Delay;
use futures_util::future::{self, BoxFuture, Either, FutureExt};
use hmac::{Hmac, KeyInit, Mac};
use serde::Serialize;
use serde_json::Value;
use sha2::Sha256;
use tracing::field::{self, Empty};
use tracing::{Instrument, Span};
use crate::backend::{Backend, Ending, Progress, Streams};
use crate::host::{self, Host, Tool};
mod output;
use self::output::{split_budget, to_text, truncate_text};
pub struct Sandbox<H, B: Backend> {
builder: Builder<H, B>,
state: Option<State<B>>,
last_run_id: u64,
unreported_restart: bool,
}
pub struct Builder<H, B> {
host: H,
tools: Vec<Tool>,
backend: B,
execute_wait: Duration,
poll_wait: Duration,
limits: Limits,
signing_key: Option<[u8; 32]>,
}
const TAG_BYTES: usize = 32;
const DUMP_FORMAT_VERSION: u8 = 1;
const HEADER_BYTES: usize = 10;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
pub run_time: Duration,
pub memory_bytes: usize,
pub recursion_depth: usize,
pub calls_per_execute: usize,
pub call_timeout: Option<Duration>,
pub idle_timeout: Option<Duration>,
pub output_chars: usize,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "status", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Status {
#[non_exhaustive]
Finished {
value: Value,
#[serde(skip_serializing_if = "Option::is_none")]
stdout: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
stderr: Option<String>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
restarted: bool,
},
#[non_exhaustive]
Running {
run_id: u64,
},
#[non_exhaustive]
Failed {
error: String,
calls: Vec<host::Call>,
#[serde(skip_serializing_if = "Option::is_none")]
stdout: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
stderr: Option<String>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
restarted: bool,
},
}
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
RunOpen {
run_id: u64,
},
Dump(Box<dyn error::Error + Send + Sync>),
Restore(Box<dyn error::Error + Send + Sync>),
SignatureMismatch,
}
enum State<B: Backend> {
Idle(B::Session),
Suspended(Run<B>),
}
struct Run<B: Backend> {
answered_calls: Vec<host::Call>,
call: host::Call,
suspension: B::Suspension,
answer: BoxFuture<'static, Option<Result<Value, host::Error>>>,
idle_since: Instant,
}
impl Default for Limits {
fn default() -> Self {
Self {
run_time: Duration::from_secs(30),
memory_bytes: 256 * 1024 * 1024,
recursion_depth: 1000,
calls_per_execute: 100,
call_timeout: None,
idle_timeout: None,
output_chars: 40_000,
}
}
}
macro_rules! trace_step {
($name:literal, $step:expr) => {{
let span = tracing::info_span!(
$name,
run_id = Empty,
status = Empty,
call_count = Empty,
duration = Empty
);
let started = Instant::now();
let status: Status = $step.instrument(span.clone()).await;
record_end(&span, status.as_str(), started);
status
}};
}
impl<H: Host, B: Backend> Sandbox<H, B> {
pub fn tools(&self) -> &[Tool] {
&self.builder.tools
}
pub async fn execute(&mut self, code: &str, restart: bool) -> Status {
trace_step!("execute", async {
if let Some(status) = self.expire_idle_run().await {
return status;
}
if restart || self.state.is_none() {
self.reset().await;
}
let session = match self.take_session() {
Ok(session) => session,
Err(error) => return Status::failed(error.to_string()),
};
self.last_run_id += 1;
Span::current()
.record("run_id", self.last_run_id)
.record("call_count", 0);
let progress = self
.builder
.backend
.feed_start(session, code, &self.builder.tools)
.await;
if let Some(status) = self.suspend_or_end(Vec::new(), progress).await {
return status;
}
self.wait_timeout(self.builder.execute_wait).await
})
}
pub async fn poll(&mut self, run_id: u64) -> Status {
trace_step!("poll", async {
Span::current().record("run_id", run_id);
if !self.is_open_run(run_id) {
return Status::failed(format!("no run {run_id}"));
}
match self.expire_idle_run().await {
Some(status) => status,
None => self.wait_timeout(self.builder.poll_wait).await,
}
})
}
pub async fn cancel(&mut self, run_id: u64) -> bool {
let span = tracing::info_span!("cancel", run_id, status = Empty, duration = Empty);
let started = Instant::now();
let is_open = self.is_open_run(run_id);
let Some(run) = self.take_run_if(|_| is_open) else {
record_end(&span, "not_open", started);
return false;
};
let message = format!("run {run_id} was cancelled");
let ending = self.builder.backend.abandon(run.suspension, message).await;
self.state = Some(State::Idle(ending.session));
self.unreported_restart |= ending.lost_globals;
record_end(&span, "cancelled", started);
true
}
pub async fn reset(&mut self) {
self.state = Some(State::Idle(
self.builder.backend.new_session(&self.builder.limits).await,
));
self.unreported_restart = true;
}
pub async fn dump(&mut self) -> Result<Vec<u8>, Error> {
if self.state.is_none() {
self.reset().await;
}
let mut session = self.take_session()?;
let (dump, lost_globals) = self.builder.backend.dump(&mut session).await;
self.state = Some(State::Idle(session));
self.unreported_restart |= lost_globals;
let mut bytes = vec![DUMP_FORMAT_VERSION, u8::from(self.unreported_restart)];
bytes.extend(self.last_run_id.to_le_bytes());
bytes.extend(dump.map_err(Error::Dump)?);
if let Some(key) = self.builder.signing_key {
let tag = compute_hmac(&key, &bytes).finalize().into_bytes();
bytes.extend_from_slice(&tag);
}
Ok(bytes)
}
fn take_session(&mut self) -> Result<B::Session, Error> {
match self.state.take() {
Some(State::Idle(session)) => Ok(session),
suspended => {
self.state = suspended;
Err(Error::RunOpen {
run_id: self.last_run_id,
})
}
}
}
fn is_open_run(&self, run_id: u64) -> bool {
matches!(self.state, Some(State::Suspended(_))) && run_id == self.last_run_id
}
fn take_run_if(&mut self, condition: impl FnOnce(&Run<B>) -> bool) -> Option<Run<B>> {
match self.state.take() {
Some(State::Suspended(run)) if condition(&run) => Some(run),
state => {
self.state = state;
None
}
}
}
async fn wait_timeout(&mut self, wait: Duration) -> Status {
let mut timer = Delay::new(wait);
loop {
let Some(State::Suspended(run)) = &mut self.state else {
panic!("wait_timeout without a suspended run");
};
let answer = match future::select(&mut run.answer, &mut timer).await {
Either::Left((answer, _)) => answer,
Either::Right(_) => {
run.idle_since = Instant::now();
Span::current().record("call_count", run.answered_calls.len());
return Status::Running {
run_id: self.last_run_id,
};
}
};
let Some(State::Suspended(run)) = self.state.take() else {
panic!("wait_timeout without a suspended run");
};
let Run {
mut answered_calls,
call,
suspension,
..
} = run;
let progress = match answer {
Some(answer) => {
answered_calls.push(output::truncate_args(call, &self.builder.limits));
Span::current().record("call_count", answered_calls.len());
self.builder
.backend
.resume(suspension, answer, &self.builder.tools)
.await
}
None => {
let message = format!("{} passed the call timeout", call.tool_id);
let ending = self.builder.backend.abort(suspension, message).await;
return self.end_run(ending, answered_calls);
}
};
if let Some(status) = self.suspend_or_end(answered_calls, progress).await {
return status;
}
}
}
async fn suspend_or_end(
&mut self,
answered_calls: Vec<host::Call>,
progress: Progress<B>,
) -> Option<Status> {
let call_limit = self.builder.limits.calls_per_execute;
let ending = match progress {
Progress::Call { call, suspension } if answered_calls.len() < call_limit => {
let answer = self.call_host(&call);
self.state = Some(State::Suspended(Run {
answered_calls,
call,
suspension,
answer,
idle_since: Instant::now(),
}));
return None;
}
Progress::Call { suspension, .. } => {
let message = format!("the script reached the call limit of {call_limit}");
self.builder.backend.abort(suspension, message).await
}
Progress::Ended(ending) => ending,
};
Some(self.end_run(ending, answered_calls))
}
async fn expire_idle_run(&mut self) -> Option<Status> {
let idle_timeout = self.builder.limits.idle_timeout?;
if let Some(State::Suspended(run)) = &mut self.state
&& let Some(answer) = (&mut run.answer).now_or_never()
{
let host_answered = answer.is_some();
run.answer = future::ready(answer).boxed();
if host_answered {
return None;
}
}
let run = self.take_run_if(|run| run.idle_since.elapsed() >= idle_timeout)?;
Span::current().record("run_id", self.last_run_id);
let message = format!("run {} expired", self.last_run_id);
let ending = self.builder.backend.abandon(run.suspension, message).await;
Some(self.end_run(ending, run.answered_calls))
}
fn end_run(&mut self, ending: Ending<B>, answered_calls: Vec<host::Call>) -> Status {
let Ending {
result,
streams,
session,
lost_globals,
} = ending;
self.state = Some(State::Idle(session));
let result_text = match &result {
Ok(value) => to_text(value),
Err(error) => Cow::Borrowed(error.as_str()),
};
let result_chars = result_text.chars().count();
let Streams { stdout, stderr } = streams;
let (stdout_chars, stderr_chars) = (stdout.chars().count(), stderr.chars().count());
let (result_share, streams_share) = split_budget(
self.builder.limits.output_chars,
result_chars,
stdout_chars + stderr_chars,
);
let (stdout_share, stderr_share) = split_budget(streams_share, stdout_chars, stderr_chars);
let result_truncated = truncate_text(&result_text, result_chars, result_share);
drop(result_text);
let stdout = (!stdout.is_empty())
.then(|| truncate_text(&stdout, stdout_chars, stdout_share).unwrap_or(stdout));
let stderr = (!stderr.is_empty())
.then(|| truncate_text(&stderr, stderr_chars, stderr_share).unwrap_or(stderr));
let restarted = mem::replace(&mut self.unreported_restart, lost_globals);
match result {
Ok(value) => Status::Finished {
value: result_truncated.map_or(value, Value::String),
stdout,
stderr,
restarted,
},
Err(error) => Status::Failed {
error: result_truncated.unwrap_or(error),
calls: answered_calls,
stdout,
stderr,
restarted,
},
}
}
fn call_host(
&self,
call: &host::Call,
) -> BoxFuture<'static, Option<Result<Value, host::Error>>> {
let run_id = self.last_run_id;
let span = tracing::info_span!(parent: None, "call", run_id, tool_id = %call.tool_id, status = Empty, duration = Empty);
let answer = self.builder.host.call(call);
let timeout = self.builder.limits.call_timeout.map(Delay::new);
let mut trace = CallTrace {
span: span.clone(),
started: Instant::now(),
status: "dropped",
};
async move {
let answer = match timeout {
Some(timeout) => match future::select(answer, timeout).await {
Either::Left((answer, _)) => Some(answer),
Either::Right(_) => None,
},
None => Some(answer.await),
};
trace.status = match &answer {
Some(Ok(_)) => "answered",
Some(Err(host::Error::Refused(_))) => "refused",
Some(Err(host::Error::Failed(_))) => "failed",
None => "timed_out",
};
drop(trace);
answer
}
.instrument(span)
.boxed()
}
}
impl<H: Host, B: Backend> Builder<H, B> {
pub fn new(host: H, backend: B) -> Self {
let tools = host.tools();
Self {
host,
tools,
backend,
execute_wait: Duration::from_secs(30),
poll_wait: Duration::from_secs(10),
limits: Limits::default(),
signing_key: None,
}
}
pub fn execute_wait(mut self, wait: Duration) -> Self {
self.execute_wait = wait;
self
}
pub fn poll_wait(mut self, wait: Duration) -> Self {
self.poll_wait = wait;
self
}
pub fn limits(mut self, limits: Limits) -> Self {
self.limits = limits;
self
}
pub fn signing_key(mut self, key: [u8; 32]) -> Self {
self.signing_key = Some(key);
self
}
pub async fn build(self) -> Sandbox<H, B> {
let session = self.backend.new_session(&self.limits).await;
self.build_with_session(session, 0, false)
}
pub async fn restore(self, bytes: &[u8]) -> Result<Sandbox<H, B>, (Error, Box<Self>)> {
match Self::read_dump(&self.backend, &self.limits, self.signing_key, bytes).await {
Ok((session, last_run_id, unreported_restart)) => {
Ok(self.build_with_session(session, last_run_id, unreported_restart))
}
Err(error) => Err((error, Box::new(self))),
}
}
async fn read_dump(
backend: &B,
limits: &Limits,
signing_key: Option<[u8; 32]>,
bytes: &[u8],
) -> Result<(B::Session, u64, bool), Error> {
let dump = match signing_key {
Some(key) => {
let (dump, tag) = bytes
.split_last_chunk::<TAG_BYTES>()
.ok_or(Error::SignatureMismatch)?;
compute_hmac(&key, dump)
.verify_slice(tag)
.map_err(|_| Error::SignatureMismatch)?;
dump
}
None => bytes,
};
let ([version, restart_byte, last_run_id_bytes @ ..], session_bytes) = dump
.split_first_chunk::<HEADER_BYTES>()
.ok_or_else(|| Error::Restore("the bytes are too short to be a dump".into()))?;
if *version != DUMP_FORMAT_VERSION {
return Err(Error::Restore(
format!("the dump is format version {version}, not version {DUMP_FORMAT_VERSION}")
.into(),
));
}
let session = backend
.restore(session_bytes, limits)
.await
.map_err(Error::Restore)?;
Ok((
session,
u64::from_le_bytes(*last_run_id_bytes),
*restart_byte != 0,
))
}
fn build_with_session(
self,
session: B::Session,
last_run_id: u64,
unreported_restart: bool,
) -> Sandbox<H, B> {
Sandbox {
builder: self,
state: Some(State::Idle(session)),
last_run_id,
unreported_restart,
}
}
}
impl<H, B: Backend> fmt::Debug for Sandbox<H, B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Sandbox")
.field("builder", &self.builder)
.field("last_run_id", &self.last_run_id)
.finish_non_exhaustive()
}
}
impl<H, B> fmt::Debug for Builder<H, B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Builder")
.field("tools", &self.tools)
.field("execute_wait", &self.execute_wait)
.field("poll_wait", &self.poll_wait)
.field("limits", &self.limits)
.finish_non_exhaustive()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::RunOpen { run_id } => write!(f, "run {run_id} is still running"),
Self::Dump(_) => f.write_str("can't dump the session"),
Self::Restore(_) => f.write_str("can't restore the session"),
Self::SignatureMismatch => f.write_str("the signing key didn't sign these bytes"),
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::RunOpen { .. } | Self::SignatureMismatch => None,
Self::Dump(error) | Self::Restore(error) => Some(error.as_ref()),
}
}
}
impl Status {
fn failed(error: String) -> Self {
Self::Failed {
error,
calls: Vec::new(),
stdout: None,
stderr: None,
restarted: false,
}
}
fn as_str(&self) -> &'static str {
match self {
Self::Finished { .. } => "finished",
Self::Running { .. } => "running",
Self::Failed { .. } => "failed",
}
}
}
fn compute_hmac(key: &[u8], bytes: &[u8]) -> Hmac<Sha256> {
let mut hmac =
Hmac::<Sha256>::new_from_slice(key).expect("HMAC-SHA256 takes a key of any length");
hmac.update(bytes);
hmac
}
struct CallTrace {
span: Span,
started: Instant,
status: &'static str,
}
impl Drop for CallTrace {
fn drop(&mut self) {
record_end(&self.span, self.status, self.started);
}
}
fn record_end(span: &Span, status: &'static str, started: Instant) {
span.record("status", status);
span.record("duration", field::debug(started.elapsed()));
}