1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
//! The Python interpreters a sandbox can run its scripts in.
#[cfg(feature = "monty")]
pub use self::monty::Monty;
#[cfg(feature = "monty-pool")]
pub use self::monty::{MontyPool, WorkerOptions};
pub(crate) use self::sealed::{Ending, Progress, Streams};
mod monty;
/// Runs a sandbox's scripts in Python sessions whose globals persist from one script to the
/// next. Only this crate's backends, `Monty` and `MontyPool`, implement it.
pub trait Backend: sealed::Backend {}
impl<B: sealed::Backend> Backend for B {}
mod sealed {
//! The calls a sandbox makes into its backend, which only this crate's backends implement.
use std::{error, fmt};
use serde_json::Value;
use crate::host;
use crate::sandbox::Limits;
/// The calls a sandbox makes into its [`Backend`](super::Backend) to run its scripts. It holds
/// no session: each method takes the idle session, or the script suspended at a tool call, by
/// value, and its [`Progress`] hands that on.
pub trait Backend: Sized {
/// A Python session between scripts, holding the globals they set.
type Session: Send;
/// A script suspended at a tool call, with what it has printed so far.
type Suspension: Send;
/// An empty idle session that stops a script at `limits`' run time, memory and recursion
/// depth.
fn new_session(&self, limits: &Limits) -> impl Future<Output = Self::Session> + Send;
/// Feeds `code` to the idle `session` and runs it until it calls one of the host's tools,
/// which are `tools`, or ends.
fn feed_start(
&self,
session: Self::Session,
code: &str,
tools: &[host::Tool],
) -> impl Future<Output = Progress<Self>> + Send;
/// Answers the tool call the script is suspended at with `answer`, and runs on until the
/// next call to one of `tools`, or the end. A [`host::Error::Refused`] raises
/// `PermissionError` in the script, and a [`host::Error::Failed`] raises `RuntimeError`.
fn resume(
&self,
suspension: Self::Suspension,
answer: Result<Value, host::Error>,
tools: &[host::Tool],
) -> impl Future<Output = Progress<Self>> + Send;
/// Ends the suspended script with a `RuntimeError` carrying `message`, which the script
/// can't catch, and gives back how it ended.
fn abort(
&self,
suspension: Self::Suspension,
message: String,
) -> impl Future<Output = Ending<Self>> + Send;
/// Drops the suspended script without running it further, and gives back how it ended, with
/// `message` as its `Err` result, the idle session with the globals the script had set, and
/// what it printed. A backend that can't keep the globals sets [`Ending::lost_globals`].
fn abandon(
&self,
suspension: Self::Suspension,
message: String,
) -> impl Future<Output = Ending<Self>> + Send;
/// The bytes of the idle `session`, which [`Backend::restore`] reads back, or why the
/// backend couldn't write them, and whether the backend lost the session's globals while it
/// tried, which leaves `session` empty.
fn dump(
&self,
session: &mut Self::Session,
) -> impl Future<Output = (Result<Vec<u8>, Box<dyn error::Error + Send + Sync>>, bool)> + Send;
/// The idle session that `bytes` from [`Backend::dump`] hold, running under `limits`
/// like a [new session](Backend::new_session). A backend may keep the limits it was
/// dumped with where those are stricter, as `MontyPool` does.
fn restore(
&self,
bytes: &[u8],
limits: &Limits,
) -> impl Future<Output = Result<Self::Session, Box<dyn error::Error + Send + Sync>>> + Send;
}
/// How far a script got, from the backend to the sandbox.
pub enum Progress<B: Backend> {
/// The script is suspended at this tool call until [`Backend::resume`] gives the host's
/// answer.
Call {
/// The tool call the script made with keyword arguments, to one of the host's tools.
call: host::Call,
/// The script, suspended at `call`.
suspension: B::Suspension,
},
/// The script ended, and the session is idle again.
Ended(Ending<B>),
}
/// How a script ended, from the backend to the sandbox.
pub struct Ending<B: Backend> {
/// The value of the script's last expression, or its traceback.
pub result: Result<Value, String>,
/// What the script printed.
pub streams: Streams,
/// The idle session, with the globals the script set, or an empty session if the backend
/// lost them.
pub session: B::Session,
/// Whether the backend lost the session's globals during this run, such as to a worker
/// crash, so `session` is empty.
pub lost_globals: bool,
}
impl<B: Backend> fmt::Debug for Progress<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Call { call, .. } => f
.debug_struct("Call")
.field("call", call)
.finish_non_exhaustive(),
Self::Ended(ending) => f.debug_tuple("Ended").field(ending).finish(),
}
}
}
impl<B: Backend> fmt::Debug for Ending<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ending")
.field("result", &self.result)
.field("streams", &self.streams)
.field("lost_globals", &self.lost_globals)
.finish_non_exhaustive()
}
}
/// What a script printed, each stream in the order it was printed.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Streams {
/// What the script printed to stdout.
pub stdout: String,
/// What the script printed to stderr.
pub stderr: String,
}
}