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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
|
//! The protocol of validators, renderers, converters and steps (docs/design.md, 5.2).
//!
//! `PROGRAM IN OUT`, standard input `/dev/null`, an empty environment, in `IN`. `IN`
//! holds `invocation.json` and the slots given at `channels/CHANNEL/SLOT`; `OUT` is
//! empty. Objections are JSON lines on standard output; an exit status but 0 is a
//! failure.
//!
//! In a sandbox (`Runner`), by bubblewrap: everything read-only but `OUT`, no network,
//! namespaces of its own, no capabilities. `IN` is read-only (for its owner) also
//! without.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use anyhow::{Context, Result, anyhow, bail};
use serde::{Deserialize, Serialize};
use crate::content;
use crate::name::Address;
use crate::scratch::Scratch;
pub const PROTOCOL: u32 = 1;
pub const INVOCATION: &str = "invocation.json";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
Validator,
Renderer,
Converter,
Step,
}
/// What a program is given: slots, by address, with their types and entries (none for
/// an unfilled one).
pub struct Given<'a> {
pub slots: BTreeMap<Address, (&'a str, Option<&'a [u8]>)>,
}
#[derive(Serialize)]
struct Invocation<'a> {
protocol: u32,
program: Role,
#[serde(skip_serializing_if = "Option::is_none")]
view: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
validator: Option<&'a str>,
slots: BTreeMap<String, SlotType<'a>>,
produces: BTreeMap<String, SlotType<'a>>,
}
#[derive(Serialize)]
struct SlotType<'a> {
#[serde(rename = "type")]
media_type: &'a str,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Objection {
pub address: Address,
pub message: String,
}
/// What a program did: its objections, and what it wrote, in `OUT`.
pub struct Outcome {
pub objections: Vec<Objection>,
pub out: Scratch,
}
/// Where and how programs run: their scratch directories, and the sandbox.
#[derive(Debug, Clone)]
pub struct Runner {
pub scratch: PathBuf,
/// bubblewrap (`bwrap`), to run programs in a sandbox: everything read-only but
/// `OUT`, no network, namespaces of their own, no capabilities. None runs them as
/// they are.
pub sandbox: Option<PathBuf>,
}
/// Runs `program` as `role`, named `name` (a view's or validator's), on `given`, by
/// `runner`.
pub fn run(
program: &Path,
role: Role,
name: &str,
given: &Given,
runner: &Runner,
) -> Result<Outcome> {
let scratch = runner.scratch.as_path();
let what = format!("{} {name} ({})", role_name(role), program.display());
let input = Scratch::new(scratch, "in-")?;
let out = Scratch::new(scratch, "out-")?;
let invocation = Invocation {
protocol: PROTOCOL,
program: role,
view: (role == Role::Renderer).then_some(name),
validator: (role == Role::Validator).then_some(name),
slots: given
.slots
.iter()
.map(|(address, (media_type, _))| (address.to_string(), SlotType { media_type }))
.collect(),
produces: BTreeMap::new(),
};
content::write_file(
&input.path().join(INVOCATION),
&serde_json::to_vec_pretty(&invocation)?,
0o600,
)?;
for (address, (_, bytes)) in &given.slots {
let Some(bytes) = bytes else { continue };
let dir = input.path().join("channels").join(&address.channel);
std::fs::create_dir_all(&dir)?;
content::write_file(&dir.join(&address.slot), bytes, 0o600)?;
}
input.set_modes(0o400)?;
let program = std::path::absolute(program).unwrap_or_else(|_| program.to_owned());
let mut command = match &runner.sandbox {
None => {
let mut command = Command::new(&program);
command.current_dir(input.path());
command
}
Some(bwrap) => {
// By name, from our PATH: the command's environment is empty.
let mut command = Command::new(in_path(bwrap));
command
.args(["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc"])
.args(["--tmpfs", "/tmp"])
// After /tmp, in case they are below it.
.arg("--ro-bind")
.args([input.path(), input.path()])
.arg("--bind")
.args([out.path(), out.path()])
.args(["--unshare-all", "--die-with-parent", "--new-session"])
.args(["--cap-drop", "ALL", "--chdir"])
.arg(input.path())
.arg("--")
.arg(&program);
command
}
};
let output = command
.arg(input.path())
.arg(out.path())
.env_clear()
.stdin(Stdio::null())
.output()
.with_context(|| format!("running {what}"))?;
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success() {
return Err(ProgramFailed {
what,
status: output.status.to_string(),
stderr: stderr.trim_end().to_owned(),
}
.into());
}
let mut objections = Vec::new();
let stdout = String::from_utf8(output.stdout)
.map_err(|_| anyhow!("{what}: its standard output is not UTF-8"))?;
for line in stdout.lines().filter(|line| !line.trim().is_empty()) {
let objection: Objection = serde_json::from_str(line)
.with_context(|| format!("{what}: not an objection: {line}"))?;
if !given
.slots
.keys()
.any(|address| address.overlaps(&objection.address))
{
bail!(
"{what} objects to {}, which it wasn't given",
objection.address
);
}
objections.push(objection);
}
Ok(Outcome { objections, out })
}
fn role_name(role: Role) -> &'static str {
match role {
Role::Validator => "validator",
Role::Renderer => "renderer",
Role::Converter => "converter",
Role::Step => "step",
}
}
/// A program that didn't exit with 0: no item is to blame.
#[derive(Debug)]
pub struct ProgramFailed {
pub what: String,
pub status: String,
pub stderr: String,
}
impl std::fmt::Display for ProgramFailed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} failed ({})", self.what, self.status)?;
if !self.stderr.is_empty() {
write!(f, ":\n{}", self.stderr)?;
}
Ok(())
}
}
impl std::error::Error for ProgramFailed {}
/// The regular files below `dir`, by path relative to it; anything but regular files
/// and directories is an error.
pub fn files_below(dir: &Path) -> Result<BTreeMap<PathBuf, Vec<u8>>> {
let mut files = BTreeMap::new();
let mut pending = vec![PathBuf::new()];
while let Some(relative) = pending.pop() {
let path = dir.join(&relative);
for entry in
std::fs::read_dir(&path).with_context(|| format!("reading {}", path.display()))?
{
let entry = entry?;
let kind = entry.file_type()?;
let relative = relative.join(entry.file_name());
if kind.is_dir() {
pending.push(relative);
} else if kind.is_file() {
files.insert(relative, std::fs::read(entry.path())?);
} else {
bail!(
"{}: neither a regular file nor a directory",
entry.path().display()
);
}
}
}
Ok(files)
}
/// `program`, if it is a name without a directory, as found in `PATH`; else as it is.
fn in_path(program: &Path) -> PathBuf {
if program.components().count() != 1 {
return program.to_owned();
}
std::env::var_os("PATH")
.iter()
.flat_map(std::env::split_paths)
.map(|dir| dir.join(program))
.find(|path| path.is_file())
.unwrap_or_else(|| program.to_owned())
}
|