//! 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
)>,
}
#[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>,
produces: BTreeMap>,
}
#[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,
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,
}
/// 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 {
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>> {
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())
}