use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path, PathBuf};
use serde_json::Value;
use crate::serve::api::ApiError;
use crate::serve::fleet::identity::PublicKey;
use crate::serve::fleet::member::{self, Member};
use crate::serve::fleet::membership::Stored;
use crate::serve::machines::forward as fwd;
use crate::serve::verbs;
use crate::state::State;
use crate::worker_policy::Trust;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Peer {
pub name: String,
pub fleet_root: Option<PathBuf>,
pub env: Option<BTreeMap<String, String>>,
pub agent: Option<PathBuf>,
pub key: Option<PublicKey>,
pub introduced_by: Option<String>,
}
pub const PEER_NAME_MAX: usize = 255;
pub fn attach_peer(params: &Value) -> Result<String, ApiError> {
let Some(name) = params.get("peer").and_then(Value::as_str) else {
return Err(ApiError::invalid("`link.attach` needs `peer`, the link peer's machine name"));
};
if name.is_empty() || name.len() > PEER_NAME_MAX || name.chars().any(char::is_control) {
return Err(ApiError::invalid(format!(
"`peer` must be 1 to {PEER_NAME_MAX} bytes without control characters"
)));
}
Ok(name.to_string())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Channel {
Api,
Pty,
Tunnel,
Transfer,
Agent,
Route,
}
impl Channel {
pub fn parse(s: &str) -> Option<Channel> {
Some(match s {
"api" => Channel::Api,
"pty" => Channel::Pty,
"tunnel" => Channel::Tunnel,
"transfer" => Channel::Transfer,
"agent" => Channel::Agent,
"route" => Channel::Route,
_ => return None,
})
}
pub fn as_str(self) -> &'static str {
match self {
Channel::Api => "api",
Channel::Pty => "pty",
Channel::Tunnel => "tunnel",
Channel::Transfer => "transfer",
Channel::Agent => "agent",
Channel::Route => "route",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attach {
pub name: String,
pub channel: Channel,
pub key: PublicKey,
pub introduced_by: Option<String>,
}
pub fn attach_params(params: &Value) -> Result<Attach, ApiError> {
let name = attach_peer(params)?;
let channel = match params.get("channel") {
None | Some(Value::Null) => return Err(ApiError::invalid("`link.attach` needs `channel`")),
Some(Value::String(s)) => Channel::parse(s)
.ok_or_else(|| ApiError::invalid(format!("no channel `{s}` (api, pty, tunnel, transfer, agent or route)")))?,
Some(_) => return Err(ApiError::invalid("`channel` must be a string")),
};
crate::serve::machines::check_name(&name).map_err(|e| ApiError::invalid(format!("`peer`: {e:#}")))?;
let key = match params.get("key") {
None | Some(Value::Null) => {
return Err(ApiError::invalid("`link.attach` needs `key`, the member key the link proved for the peer"));
}
Some(Value::String(s)) => s.parse::<PublicKey>().map_err(|e| ApiError::invalid(format!("`key`: {e:#}")))?,
Some(_) => return Err(ApiError::invalid("`key` must be a string")),
};
let introduced_by = match params.get("introduced_by") {
None | Some(Value::Null) => None,
Some(Value::String(s)) => {
member::check_member_name(s).map_err(|e| ApiError::invalid(format!("`introduced_by`: {e:#}")))?;
Some(s.clone())
}
Some(_) => return Err(ApiError::invalid("`introduced_by` must be a string")),
};
Ok(Attach { name, channel, key, introduced_by })
}
pub fn peer_fleet_root(data: &Path, peer: &str) -> anyhow::Result<PathBuf> {
use anyhow::Context;
crate::serve::machines::check_name(peer)?;
let root = data.join("fleet").join(peer);
std::fs::create_dir_all(&root).with_context(|| format!("cannot create {}", root.display()))?;
std::fs::canonicalize(&root).with_context(|| format!("cannot resolve {}", root.display()))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Files {
pub state: PathBuf,
pub member: Option<PathBuf>,
pub home: Option<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reach {
pub trust: Trust,
pub fleet_root: Option<PathBuf>,
pub own: BTreeSet<PathBuf>,
}
pub fn own_roots(state: &State, home: Option<&Path>, data: Option<&Path>) -> BTreeSet<PathBuf> {
let recorded = state.instances.values().filter_map(|i| i.config_dir.clone());
let home = home.map(|h| h.join(".devsandboxes")).filter(|d| d.is_dir());
let mesh = data.map(crate::serve::fleet::mesh::roots).unwrap_or_default();
recorded.chain(home).chain(mesh).map(|r| std::fs::canonicalize(&r).unwrap_or(r)).collect()
}
pub fn listed_roots(member: Option<&Member>, state: &State, home: Option<&Path>, data: Option<&Path>) -> BTreeSet<PathBuf> {
let mut own = own_roots(state, home, data);
if let Some(m) = member {
own.extend(m.roots.iter().map(|r| std::fs::canonicalize(r).unwrap_or_else(|_| r.clone())));
}
own
}
impl Reach {
pub fn of(member: Option<&Member>, state: &State, home: Option<&Path>, data: Option<&Path>, fleet_root: Option<&Path>) -> Reach {
let own = listed_roots(member, state, home, data);
let trust = member.map(|m| m.trust).unwrap_or_default();
Reach { trust, fleet_root: fleet_root.map(Path::to_path_buf), own }
}
pub fn load(files: &Files, fleet_root: Option<&Path>) -> (Reach, Option<String>) {
let mut warning = None;
let member = match files.member.as_deref().map(member::load) {
None | Some(Ok(None)) => None,
Some(Ok(Some(m))) => Some(m),
Some(Err(e)) => {
warning = Some(format!("{e:#}; taken as `trust = \"worker\"`, no `roots`"));
None
}
};
let state = State::load_at(&files.state).unwrap_or_else(|e| {
warning = Some(format!("{e:#}; taken as no instances"));
State::default()
});
let data = files.member.as_deref().and_then(Path::parent);
(Reach::of(member.as_ref(), &state, files.home.as_deref(), data, fleet_root), warning)
}
pub fn admits(&self, real: &Path) -> bool {
self.trust == Trust::Full || self.in_fleet_root(real) || self.own.contains(real)
}
pub fn in_fleet_root(&self, real: &Path) -> bool {
self.fleet_root.as_deref().is_some_and(|r| real.starts_with(r))
}
pub fn admits_recorded(&self, dir: &Path) -> bool {
if dir.components().any(|c| c == Component::ParentDir) {
return false;
}
self.admits(&std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Gate {
Hello,
Subscribe,
Watch,
Unwatch,
Quick,
Capacity,
Code,
Mesh,
Fetch,
Roots,
Verb,
Open,
}
pub fn decide(method: &str, params: &Value) -> Result<Gate, ApiError> {
if fwd::machine_of(params)?.is_some() {
return Err(ApiError::denied("a remote caller can't reach past this member (`machine`)"));
}
if fwd::federated(params) && method != "instances.watch" {
return Err(ApiError::denied("a remote caller can't reach past this member (`machines`)"));
}
let gate = match method {
"hello" => Gate::Hello,
"subscribe" | "unsubscribe" => {
let topics = params.get("topics").and_then(Value::as_array);
if topics.is_some_and(|t| t.iter().any(|t| !matches!(t.as_str(), Some("instances" | "roots")))) {
return Err(ApiError::denied("a remote caller subscribes to `instances` and `roots` only"));
}
Gate::Subscribe
}
"instances.watch" => Gate::Watch,
"instances.unwatch" => Gate::Unwatch,
m if fwd::is_quick(m) => Gate::Quick,
"capacity.get" => Gate::Capacity,
"code.haves" => Gate::Code,
"mesh.folders" => Gate::Mesh,
"instances.fetch" => Gate::Fetch,
"roots.list" => Gate::Roots,
"open.deliver" => Gate::Open,
"gc" => return Err(ApiError::denied(format!(
"`gc` is host maintenance: not open to remote callers under this member's `worker` trust ({FULL_HINT})"
))),
m if verbs::is_verb(m) => Gate::Verb,
m => return Err(ApiError::denied(format!("`{m}` isn't open to remote callers under this member's `worker` trust ({FULL_HINT})"))),
};
Ok(gate)
}
const FULL_HINT: &str = "`devsandbox machine trust full` there opens it";
fn instance_keys(method: &str) -> &'static [&'static str] {
match method {
"instances.cancel" | "instances.signal" | "instances.rename" | "instances.setProfile" | "instances.done"
| "instances.buildLog" | "sessions.list" | "sessions.rm" => &["instance"],
"rebuild" | "start" | "stop" | "rm" => &["instance"],
_ => &[],
}
}
fn needs_instance(method: &str) -> bool {
matches!(method, "rebuild" | "start" | "stop" | "rm")
}
pub fn confine_path(reach: &Reach, path: &Path, exists: bool) -> Result<PathBuf, ApiError> {
if !path.is_absolute() {
return Err(ApiError::invalid(format!("`{}` must be absolute", path.display())));
}
if path.components().any(|c| c == Component::ParentDir) {
return Err(ApiError::denied(format!("`{}` has a `..`", path.display())));
}
let real = match std::fs::canonicalize(path) {
Ok(real) => real,
Err(_) if !exists => path.to_path_buf(),
Err(_) => return Err(ApiError::not_found(format!("no directory {}", path.display()))),
};
if !reach.admits(&real) {
return Err(ApiError::denied(format!(
"`{}` isn't one of this member's roots (`devsandbox machine roots add <path>` there adds one)",
path.display()
)));
}
Ok(real)
}
pub(crate) fn root_under(dir: &Path, root: &Path) -> bool {
if dir.components().any(|c| c == Component::ParentDir) {
return false;
}
std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf()).starts_with(root)
}
pub fn lent_instances(state: &State, reach: &Reach) -> Lent {
let mut lent = Lent::default();
for (name, i) in &state.instances {
if i.config_dir.as_deref().is_some_and(|d| reach.admits_recorded(d)) {
lent.names.insert(name.clone());
lent.ids.insert(i.instance_id.clone());
lent.containers.insert(i.container.clone());
if let Some(dir) = &i.config_dir {
lent.roots.insert(dir.clone());
}
}
}
lent
}
#[derive(Debug, Default)]
pub struct Lent {
pub names: BTreeSet<String>,
pub ids: BTreeSet<String>,
pub containers: BTreeSet<String>,
pub roots: BTreeSet<PathBuf>,
}
impl Lent {
fn projects(&self) -> BTreeSet<String> {
self.roots.iter().filter_map(|d| crate::commands::services::project_id(d).ok()).collect()
}
}
#[derive(Debug, Clone, Copy)]
pub struct Log<'a> {
pub stored: &'a Stored,
pub own: &'a str,
pub key: Option<PublicKey>,
}
pub const FLEET_METHODS: &[&str] =
&["fleet.leave", "fleet.forget", "fleet.rm", "fleet.place", "fleet.propose", "fleet.sync", "fleet.report", "fleet.graph"];
pub fn admit_fleet(method: &str, params: &Value, from: Option<&Peer>, log: Option<Log>) -> Result<(), ApiError> {
let Some(peer) = from else {
return Err(ApiError::denied(format!(
"`{method}` comes over a fleet link: here `devsandbox machine rm|unlink|approve` (`machines.*`, `membership.*`)"
)));
};
if !FLEET_METHODS.contains(&method) {
return Err(ApiError::unknown_method(method));
}
let from = peer.name.as_str();
let Some(key) = peer.key else {
return Err(ApiError::denied(format!("`{method}` from `{from}`, which proved no member key")));
};
let Some((log, m)) = log.and_then(|l| Some((l, l.stored.log.membership()?))) else {
return Err(ApiError::denied(format!("`{method}`: this host is in no fleet's membership log")));
};
let member = m.key_of(from) == Some(key);
let introduced = peer.introduced_by.is_some() || log.stored.introductions.iter().any(|i| i.name == from && i.key == key);
let name = || -> Result<&str, ApiError> {
params.get("name").and_then(Value::as_str).ok_or_else(|| ApiError::invalid(format!("`{method}` needs `name`")))
};
match method {
"fleet.leave" | "fleet.forget" => {
if m.control_plane != from || m.control_plane_key() != Some(key) {
return Err(ApiError::denied(format!(
"`{method}` is taken from this host's control plane only (by its key in the log), and `{from}` isn't it"
)));
}
if method == "fleet.leave" {
if !log.key.is_some_and(|k| m.revoked.contains(&k)) {
return Err(ApiError::denied(format!(
"`fleet.leave` follows a revoke of this host's key, and this host's membership log has none \
(the authority `{}` signs it)",
m.authority.0
)));
}
} else {
let name = name()?;
if !log.stored.log.revoked_name(name) {
return Err(ApiError::denied(format!(
"`fleet.forget` of `{name}` follows a revoke of its key, and this host's membership log has none \
(the authority `{}` signs it)",
m.authority.0
)));
}
}
Ok(())
}
"fleet.propose" => {
if m.authority.0 != log.own || log.key != Some(m.authority.1) {
return Err(ApiError::denied(format!(
"`fleet.propose` goes to the fleet's authority `{}`, and this host isn't it",
m.authority.0
)));
}
if member {
Ok(())
} else if introduced {
Err(ApiError::denied(format!("`fleet.propose` from `{from}`: an introduced member (capped) proposes no membership change")))
} else {
Err(ApiError::denied(format!("`fleet.propose` is taken from the fleet's members (by their keys in the log), and `{from}` isn't one")))
}
}
"fleet.sync" | "fleet.graph" if member || introduced => Ok(()),
"fleet.sync" | "fleet.graph" => {
Err(ApiError::denied(format!("`{method}` from `{from}`, which is neither a member nor introduced")))
}
_ if m.control_plane != log.own => Err(ApiError::denied(format!("`{method}` runs on the control plane, and this host isn't it"))),
"fleet.rm" if member => {
let name = name()?;
if name == from || log.stored.log.revoked_name(name) {
Ok(())
} else {
Err(ApiError::denied(format!(
"`fleet.rm` of `{name}`: its key isn't revoked in the control plane's membership log \
(the authority `{}` signs that: `devsandbox machine rm {name}` there)",
m.authority.0
)))
}
}
"fleet.place" | "fleet.report" if member => Ok(()),
"fleet.place" | "fleet.report" if log.stored.introductions.iter().any(|i| i.name == from && i.key == key) => Ok(()),
"fleet.rm" if introduced || log.stored.introductions.iter().any(|i| i.name == from) => Err(ApiError::denied(format!(
"`{method}` from `{from}`: an introduced member (capped) changes no one's membership"
))),
_ => Err(ApiError::denied(format!("`{method}` is taken from the fleet's members (by their keys in the log), and `{from}` isn't one"))),
}
}
pub fn admit(method: &str, mut params: Value, peer: &Peer, reach: &Reach, state: &Path) -> Result<Value, ApiError> {
if ["member.", "membership.", "graph.", "link.", "links.", "placements.", "access.", "credentials."].iter().any(|p| method.starts_with(p)) {
return Err(ApiError::denied(format!("`{method}` is this member's own: local clients only")));
}
if method == "subscribe" && params.get("topics").and_then(Value::as_array).is_some_and(|t| t.iter().any(|t| t == "access")) {
return Err(ApiError::denied("`access` is this member's own: local clients only"));
}
if method.starts_with("fleet.") {
return Err(ApiError::denied(format!("`{method}` goes by this host's control plane, not its trust table")));
}
if reach.trust == Trust::Full {
if verbs::is_verb(method)
&& let Some(obj) = params.as_object_mut()
{
peer_env(obj, peer)?;
}
return Ok(params);
}
let gate = decide(method, ¶ms)?;
if gate == Gate::Open {
return Ok(params);
}
let Some(obj) = params.as_object_mut() else {
return Ok(params);
};
for key in ["root", "dir"] {
let Some(v) = obj.get(key) else { continue };
let Some(path) = v.as_str() else {
return Err(ApiError::invalid(format!("`{key}` must be a path")));
};
let real = confine_path(reach, Path::new(path), gate != Gate::Unwatch)?;
if matches!(method, "config.migrate" | "config.ack") && !reach.in_fleet_root(&real) {
return Err(ApiError::denied(format!(
"`{method}` edits this member's own config at {}: that needs `devsandbox machine trust full` on it",
real.display()
)));
}
obj.insert(key.into(), Value::String(real.to_string_lossy().into_owned()));
}
let path_key = match gate {
Gate::Watch | Gate::Unwatch => Some("dir"),
Gate::Verb | Gate::Mesh => Some("root"),
Gate::Quick if method == "instances.list" => Some("dir"),
Gate::Quick
if method.starts_with("sandboxes.")
|| method.starts_with("config.")
|| method.starts_with("sessions.")
|| method == "services.get" =>
{
Some("root")
}
_ => None,
};
if let Some(key) = path_key
&& !obj.contains_key(key)
{
return Err(ApiError::invalid(format!("`{method}` needs `{key}`")));
}
if gate == Gate::Fetch {
fetch_in_fleet_root(obj, reach, state)?;
}
let keys = instance_keys(method);
let named_container = matches!(method, "containers.logs" | "containers.inspect");
let all = gate == Gate::Verb && obj.get("all").and_then(Value::as_bool) == Some(true);
if !keys.is_empty() || method == "instances.procs" || named_container || all {
let state = State::load_at(state).map_err(ApiError::internal)?;
let lent = lent_instances(&state, reach);
let unknown = |what: &str| ApiError::not_found(format!("no instance `{what}`"));
for key in keys {
let Some(name) = obj.get(*key).and_then(Value::as_str) else {
if needs_instance(method) && !all {
return Err(ApiError::invalid(format!("`{method}` from a remote caller needs `{key}`")));
}
continue;
};
if gate == Gate::Verb {
let matches = crate::commands::instance_matches(&state, name);
if matches.iter().any(|m| !lent.names.contains(m)) {
return Err(unknown(name));
}
} else if !lent.names.contains(name) && !lent.ids.contains(name) {
return Err(unknown(name));
}
}
if method == "instances.procs"
&& let Some(names) = obj.get("instances").and_then(Value::as_array)
&& let Some(bad) = names.iter().filter_map(Value::as_str).find(|n| !lent.names.contains(*n))
{
return Err(unknown(bad));
}
if named_container
&& let Some(c) = obj.get("container").and_then(Value::as_str)
&& !lent.containers.contains(c)
&& !lent.projects().iter().any(|p| c.starts_with(&crate::commands::services::service_container(p, "")))
{
return Err(ApiError::not_found(format!("no container `{c}` in this member's reach")));
}
if all && state.instances.len() != lent.names.len() {
return Err(ApiError::denied(format!(
"`{method}` with `all` reaches instances outside this member's roots ({FULL_HINT})"
)));
}
}
if gate == Gate::Verb {
peer_env(obj, peer)?;
}
Ok(params)
}
fn fetch_in_fleet_root(obj: &serde_json::Map<String, Value>, reach: &Reach, state: &Path) -> Result<(), ApiError> {
let Some(name) = obj.get("instance").and_then(Value::as_str) else {
return Err(ApiError::invalid("`instances.fetch` needs `instance`"));
};
let state = State::load_at(state).map_err(ApiError::internal)?;
let under = |p: &Path| !p.components().any(|c| c == Component::ParentDir) && reach.in_fleet_root(&std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()));
match crate::serve::fleet::code::fetch::find_instance(&state, name) {
Some((_, i)) if i.config_dir.as_deref().is_some_and(under) && under(&i.folder) => Ok(()),
_ => Err(ApiError::not_found(format!("no instance `{name}` under this member's fleet root for the caller"))),
}
}
fn peer_env(obj: &mut serde_json::Map<String, Value>, peer: &Peer) -> Result<(), ApiError> {
if let Some(env) = &peer.env {
let mut env = env.clone();
if let Some(agent) = peer.agent.as_deref().filter(|a| std::os::unix::net::UnixStream::connect(a).is_ok()) {
env.insert("SSH_AUTH_SOCK".into(), agent.to_string_lossy().into_owned());
}
obj.insert("env".into(), serde_json::to_value(env).map_err(|e| ApiError::internal(e.into()))?);
}
Ok(())
}
pub fn filter_answer(method: &str, mut answer: Value, reach: &Reach) -> Result<Value, ApiError> {
if reach.trust == Trust::Full {
return Ok(answer);
}
match method {
"instances.list" => filter_snapshot(&mut answer, reach),
"instances.resolve" => {
let found: Vec<Value> = answer
.get("found")
.and_then(Value::as_array)
.map(|f| f.iter().filter(|f| row_lent(f, reach)).cloned().collect())
.unwrap_or_default();
if found.is_empty() {
return Err(ApiError::not_found("no instance matches"));
}
let names: Vec<Value> = found.iter().filter_map(|f| f.get("name").cloned()).collect();
answer["found"] = Value::Array(found);
answer["matches"] = Value::Array(names);
}
_ => {}
}
Ok(answer)
}
pub fn with_fleet_root(mut answer: Value, reach: &Reach) -> Value {
let (Some(root), Some(rows)) = (&reach.fleet_root, answer.as_array_mut()) else { return answer };
match rows.iter_mut().find(|r| r.get("root").and_then(Value::as_str) == root.to_str()) {
Some(row) => {
if let Some(row) = row.as_object_mut() {
row.insert("fleet".into(), Value::Bool(true));
}
}
None => rows.push(serde_json::json!({ "root": root, "sandboxes": [], "error": null, "fleet": true })),
}
answer
}
fn row_lent(row: &Value, reach: &Reach) -> bool {
row.get("root").and_then(Value::as_str).is_some_and(|r| reach.admits_recorded(Path::new(r)))
}
pub fn filter_snapshot(snapshot: &mut Value, reach: &Reach) {
if reach.trust == Trust::Full {
return;
}
let remote = |r: &Value| r.get("machine").is_some_and(|m| !m.is_null());
let mut kept = BTreeSet::new();
let mut ids = BTreeSet::new();
if let Some(rows) = snapshot.get_mut("instances").and_then(Value::as_array_mut) {
rows.retain(|r| remote(r) || row_lent(r, reach));
let own = rows.iter().filter(|r| !remote(r));
for r in own {
kept.extend(r.get("name").and_then(Value::as_str).map(String::from));
ids.extend(r.get("instance_id").and_then(Value::as_str).map(String::from));
}
}
let keep = |v: &Value| v.as_str().is_some_and(|n| kept.contains(n));
let lent_container = |c: &Value| {
let name = c.get(0).and_then(Value::as_str).unwrap_or_default();
ids.iter().any(|id| name.contains(&format!("-{id}-")))
};
if let Some(services) = snapshot.get_mut("services").and_then(Value::as_array_mut) {
for s in services.iter_mut().filter(|s| !remote(s)) {
if let Some(used) = s.get_mut("used_by").and_then(Value::as_array_mut) {
used.retain(keep);
}
if s.get("scope").and_then(Value::as_str) == Some("isolated")
&& let Some(containers) = s.get_mut("containers").and_then(Value::as_array_mut)
{
containers.retain(lent_container);
}
}
}
if let Some(owners) = snapshot.get_mut("thread_children").and_then(Value::as_object_mut) {
for children in owners.values_mut() {
if let Some(c) = children.as_object_mut() {
c.retain(|_, child| keep(child));
}
}
owners.retain(|_, c| c.as_object().is_some_and(|c| !c.is_empty()));
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("dsv-lent-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::canonicalize(&dir).unwrap()
}
fn worker(root: &Path, own: &[&Path]) -> Reach {
Reach { trust: Trust::Worker, fleet_root: Some(root.to_path_buf()), own: own.iter().map(|p| p.to_path_buf()).collect() }
}
fn fleet(root: &Path) -> Reach {
worker(root, &[])
}
#[test]
fn the_allow_list() {
use Gate::*;
let p = json!({});
let cases: &[(&str, Value, Result<Gate, &str>)] = &[
("hello", p.clone(), Ok(Hello)),
("subscribe", json!({"topics": ["instances"]}), Ok(Subscribe)),
("unsubscribe", json!({"topics": ["instances"]}), Ok(Subscribe)),
("subscribe", json!({"topics": ["instances", "roots"]}), Ok(Subscribe)),
("subscribe", json!({"topics": ["instances", "inbox"]}), Err("denied")),
("subscribe", json!({"topics": ["forwards"]}), Err("denied")),
("instances.watch", json!({"dir": "/x"}), Ok(Watch)),
("instances.watch", json!({"dir": "/x", "machines": true}), Ok(Watch)),
("instances.unwatch", json!({"dir": "/x"}), Ok(Unwatch)),
("instances.list", json!({"dir": "/x"}), Ok(Quick)),
("instances.resolve", json!({"name": "a"}), Ok(Quick)),
("instances.resolve", json!({"name": "a", "machines": true}), Err("denied")),
("containers.logs", json!({"container": "c"}), Ok(Quick)),
("containers.inspect", json!({"machine": "m"}), Err("denied")),
("sandboxes.list", json!({"root": "/x"}), Ok(Quick)),
("config.migrate", json!({"root": "/x"}), Ok(Quick)),
("capacity.get", p.clone(), Ok(Capacity)),
("capacity.get", json!({"machine": "m"}), Err("denied")),
("code.haves", json!({"repos": []}), Ok(Code)),
("code.haves", json!({"repos": [], "machine": "m"}), Err("denied")),
("mesh.folders", json!({"root": "/x", "sandbox": "web"}), Ok(Mesh)),
("mesh.folders", json!({"root": "/x", "machine": "m"}), Err("denied")),
("instances.fetch", json!({"instance": "web-2"}), Ok(Fetch)),
("instances.fetch", json!({"instance": "web-2", "machine": "m"}), Err("denied")),
("placements.fetch", json!({"instance": "web-2"}), Err("denied")),
("run", json!({"root": "/x"}), Ok(Verb)),
("rm", json!({"root": "/x"}), Ok(Verb)),
("services.rebuild", json!({"root": "/x"}), Ok(Verb)),
("gc", json!({"root": "/x"}), Err("denied")),
("gc", json!({"root": "/x", "force": true}), Err("denied")),
("stop", json!({"root": "/x", "all": true}), Ok(Verb)),
("stop", json!({"root": "/x", "machine": "m"}), Err("denied")),
("instances.list", json!({"dir": "/x", "machine": "m"}), Err("denied")),
("instances.list", json!({"machine": 3}), Err("invalid")),
("machines.list", p.clone(), Err("denied")),
("machines.get", json!({"name": "m"}), Err("denied")),
("member.get", p.clone(), Err("denied")),
("member.set", json!({"trust": "full"}), Err("denied")),
("member.set", json!({"allow": {"gpus": true}}), Err("denied")),
("membership.get", p.clone(), Err("denied")),
("shutdown", p.clone(), Err("denied")),
("helper.call", p.clone(), Err("denied")),
("forwards.add", p.clone(), Err("denied")),
("forwards.list", p.clone(), Err("denied")),
("roots.list", p.clone(), Ok(Roots)),
("roots.list", json!({"machine": "m"}), Err("denied")),
("bridges.ensure", p.clone(), Err("denied")),
("inbox.threads.list", p.clone(), Err("denied")),
("instances.attach", json!({"instance": "w"}), Err("denied")),
("open.deliver", json!({"instance": "w", "root": "/x", "url": "https://x", "profile": null}), Ok(Open)),
("open.deliver", json!({"instance": "w", "machine": "m"}), Err("denied")),
("nope", p.clone(), Err("denied")),
];
for (method, params, want) in cases {
let got = decide(method, params).map_err(|e| e.code);
assert_eq!(got, *want, "{method} {params}");
}
let e = decide("machines.list", &p).unwrap_err();
assert_eq!(
e.message,
"`machines.list` isn't open to remote callers under this member's `worker` trust (`devsandbox machine trust full` there opens it)"
);
let e = decide("gc", &json!({"root": "/x"})).unwrap_err();
assert_eq!(
e.message,
"`gc` is host maintenance: not open to remote callers under this member's `worker` trust (`devsandbox machine trust full` there opens it)"
);
for m in fwd::QUICK {
assert_eq!(decide(m, &p).unwrap(), Quick, "{m}");
}
for m in ["run", "rebuild", "start", "stop", "rm", "services.rebuild"] {
assert!(verbs::is_verb(m));
assert_eq!(decide(m, &p).unwrap(), Verb, "{m}");
}
}
#[test]
fn an_attach_names_its_peer() {
assert_eq!(attach_peer(&json!({"peer": "lap.local"})).unwrap(), "lap.local");
let long = "x".repeat(PEER_NAME_MAX + 1);
for bad in [json!({}), json!({"peer": 3}), json!({"peer": ""}), json!({"peer": "a\nb"}), json!({"peer": long})] {
assert_eq!(attach_peer(&bad).unwrap_err().code, "invalid", "{bad}");
}
}
#[test]
fn an_attach_names_a_channel_a_machine_name_and_its_key() {
let key = pk(1);
for c in ["api", "pty", "tunnel", "transfer", "agent", "route"] {
let a = attach_params(&json!({"peer": "lap.local", "channel": c, "key": key.to_string()})).unwrap();
assert_eq!(a, Attach { name: "lap.local".into(), channel: Channel::parse(c).unwrap(), key, introduced_by: None });
}
let a = attach_params(&json!({"peer": "pi", "channel": "api", "key": key.to_string(), "introduced_by": "lap"})).unwrap();
assert_eq!(a.introduced_by.as_deref(), Some("lap"));
let k = key.to_string();
for bad in [
json!({"peer": "lap", "key": k}),
json!({"peer": "lap", "channel": null, "key": k}),
json!({"peer": "lap", "channel": "rpc", "key": k}),
json!({"peer": "lap", "channel": 1, "key": k}),
json!({"peer": "lap/../x", "channel": "api", "key": k}),
json!({"peer": "..", "channel": "pty", "key": k}),
json!({"peer": "a b", "channel": "transfer", "key": k}),
json!({"channel": "api", "key": k}),
json!({"peer": "lap", "channel": "api"}),
json!({"peer": "lap", "channel": "api", "key": null}),
json!({"peer": "lap", "channel": "api", "key": "ed25519:00"}),
json!({"peer": "lap", "channel": "api", "key": 1}),
json!({"peer": "lap", "channel": "api", "key": k, "introduced_by": 1}),
json!({"peer": "lap", "channel": "api", "key": k, "introduced_by": "a/b"}),
] {
assert_eq!(attach_params(&bad).unwrap_err().code, "invalid", "{bad}");
}
}
#[test]
fn a_peers_fleet_root_is_created_under_fleet() {
let data = scratch("peer-root");
let root = peer_fleet_root(&data, "lap").unwrap();
assert_eq!(root, std::fs::canonicalize(data.join("fleet/lap")).unwrap());
assert!(root.is_dir());
assert_eq!(peer_fleet_root(&data, "lap").unwrap(), root, "again: the same");
assert!(peer_fleet_root(&data, "..").is_err());
assert!(peer_fleet_root(&data, "a/b").is_err());
let _ = std::fs::remove_dir_all(&data);
}
#[test]
fn paths_are_confined_to_the_fleet_root() {
let base = scratch("paths");
let root = base.join("fleet/control_plane");
std::fs::create_dir_all(root.join("cfg/sub")).unwrap();
std::fs::create_dir_all(base.join("mine")).unwrap();
std::os::unix::fs::symlink(base.join("mine"), root.join("escape")).unwrap();
std::os::unix::fs::symlink(root.join("cfg"), base.join("into")).unwrap();
let reach = fleet(&root);
assert_eq!(confine_path(&reach, &root.join("cfg"), true).unwrap(), root.join("cfg"));
assert_eq!(confine_path(&reach, &root, true).unwrap(), root, "the root itself");
assert_eq!(confine_path(&reach, &base.join("into/sub"), true).unwrap(), root.join("cfg/sub"));
let code = |p: &Path, exists| confine_path(&reach, p, exists).unwrap_err().code;
assert_eq!(code(&base.join("mine"), true), "denied", "outside");
assert_eq!(code(&root.join("escape"), true), "denied", "a symlink out");
assert_eq!(code(&root.join("cfg/../../../mine"), true), "denied", "`..`");
assert_eq!(code(&root.join("cfg/.."), true), "denied", "`..` even when it stays inside");
assert_eq!(code(Path::new("rel"), true), "invalid");
assert_eq!(code(&root.join("gone"), true), "not-found");
assert_eq!(confine_path(&reach, &root.join("gone"), false).unwrap(), root.join("gone"), "an unwatch");
assert_eq!(code(&base.join("gone"), false), "denied");
std::fs::create_dir_all(base.join("fleet/control_plane2")).unwrap();
assert_eq!(code(&base.join("fleet/control_plane2"), true), "denied");
let _ = std::fs::remove_dir_all(&base);
}
fn state_with(base: &Path, root: &Path) -> PathBuf {
let state = base.join("state.toml");
let inst = |name: &str, dir: &Path| {
format!(
"[instance.{name}]\ninstance_id = \"id-{name}\"\nsandbox = \"web\"\ncontainer = \"devsandbox-{name}\"\n\
folder = \"/w\"\nworkspace = \"/w\"\ncreated_unix = 1\nconfig_dir = {:?}\n",
dir.to_str().unwrap()
)
};
std::fs::write(&state, inst("in", &root.join("cfg")) + &inst("own", &base.join("mine"))).unwrap();
state
}
fn peer(root: &Path) -> Peer {
Peer {
name: "me@control_plane".into(),
fleet_root: Some(root.to_path_buf()),
env: Some(BTreeMap::from([("PATH".into(), "/worker/bin".into())])),
agent: None,
key: None,
introduced_by: None,
}
}
#[test]
fn admit_confines_paths_instances_and_containers() {
let base = scratch("admit");
let root = base.join("fleet/control_plane");
std::fs::create_dir_all(root.join("cfg")).unwrap();
std::fs::create_dir_all(base.join("mine")).unwrap();
let state = state_with(&base, &root);
let (s, r) = (peer(&root), fleet(&root));
let ok = |m: &str, p: Value| admit(m, p, &s, &r, &state).unwrap();
let code = |m: &str, p: Value| admit(m, p, &s, &r, &state).unwrap_err().code;
let admit = |m: &str, p: Value, s: &Peer, state: &Path| admit(m, p, s, &r, state);
let cfg = root.join("cfg");
assert_eq!(ok("instances.list", json!({"dir": cfg})), json!({"dir": cfg}));
assert_eq!(code("instances.list", json!({"dir": base.join("mine")})), "denied");
assert_eq!(code("instances.list", json!({})), "invalid", "a path is needed");
assert_eq!(code("sandboxes.list", json!({"root": 3})), "invalid");
assert_eq!(code("config.findings", json!({"root": base.join("mine")})), "denied");
assert!(admit("instances.done", json!({"instance": "in", "done": true}), &s, &state).is_ok());
assert!(admit("instances.buildLog", json!({"instance": "id-in"}), &s, &state).is_ok(), "by id");
assert_eq!(code("instances.done", json!({"instance": "own", "done": true})), "not-found");
assert_eq!(code("instances.buildLog", json!({"instance": "id-own"})), "not-found");
assert_eq!(code("instances.signal", json!({"instance": "own", "pid": "1", "signal": "TERM"})), "not-found");
assert!(admit("instances.setProfile", json!({"instance": "in", "profile": "work"}), &s, &state).is_ok());
assert_eq!(code("instances.setProfile", json!({"instance": "own", "profile": "work"})), "not-found");
assert!(admit("instances.procs", json!({"instances": ["in"]}), &s, &state).is_ok());
assert_eq!(code("instances.procs", json!({"instances": ["in", "own"]})), "not-found");
assert!(admit("containers.logs", json!({"container": "devsandbox-in"}), &s, &state).is_ok());
assert_eq!(code("containers.inspect", json!({"container": "devsandbox-own"})), "not-found");
let svc = |dir: &Path, rest: &str| {
crate::commands::services::service_container(&crate::commands::services::project_id(dir).unwrap(), rest)
};
assert!(admit("containers.logs", json!({"container": svc(&cfg, "db")}), &s, &state).is_ok());
assert!(admit("containers.inspect", json!({"container": svc(&cfg, "id-in-db")}), &s, &state).is_ok());
assert_eq!(code("containers.logs", json!({"container": svc(&base.join("mine"), "db")})), "not-found");
let e = admit("stop", json!({"root": cfg, "all": true}), &s, &state).unwrap_err();
assert_eq!(e.code, "denied");
assert!(e.message.contains("machine trust full"), "{}", e.message);
assert_eq!(ok("sessions.list", json!({"root": cfg, "instance": "id-in"})), json!({"root": cfg, "instance": "id-in"}));
assert!(admit("sessions.rm", json!({"root": cfg, "instance": "in", "id": "1700000000-ab12"}), &s, &state).is_ok());
assert_eq!(code("sessions.list", json!({"root": cfg, "instance": "own"})), "not-found");
assert_eq!(code("sessions.rm", json!({"root": base.join("mine"), "instance": "own", "id": "x"})), "denied");
assert_eq!(code("sessions.list", json!({"instance": "in"})), "invalid", "a root is needed");
assert_eq!(code("stop", json!({"root": base.join("mine"), "instance": "in"})), "denied");
assert_eq!(code("stop", json!({"root": cfg, "instance": "own"})), "not-found");
assert_eq!(code("stop", json!({"root": cfg, "instance": "web"})), "not-found", "matches `own` too");
assert_eq!(code("rm", json!({"root": cfg})), "invalid");
assert_eq!(code("start", json!({"root": cfg, "instance": null})), "invalid");
assert!(admit("run", json!({"root": cfg, "sandbox": "web", "env": {}}), &s, &state).is_ok(), "run names none");
let open = json!({"instance": "own", "root": base.join("mine"), "url": "https://x", "profile": null});
assert_eq!(ok("open.deliver", open.clone()), open);
let open = json!({"instance": "x", "root": "/no/such/dir", "url": "https://x", "profile": "work"});
assert_eq!(ok("open.deliver", open.clone()), open);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_fetch_reaches_the_callers_fleet_root_only() {
let base = scratch("fetch");
let root = base.join("fleet/control_plane");
for d in ["fleet/control_plane/roots/h/cfg", "fleet/control_plane/roots/h/web", "mine/cfg", "mine/web"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
let state = base.join("state.toml");
let inst = |name: &str, cfg: &Path, folder: &Path| {
format!(
"[instance.{name}]\ninstance_id = \"id-{name}\"\nsandbox = \"web\"\ncontainer = \"devsandbox-{name}\"\n\
folder = {:?}\nworkspace = \"/w\"\ncreated_unix = 1\nconfig_dir = {:?}\n",
folder.to_str().unwrap(),
cfg.to_str().unwrap()
)
};
let placed = (root.join("roots/h/cfg"), root.join("roots/h/web"));
let own = (base.join("mine/cfg"), base.join("mine/web"));
let text = inst("placed", &placed.0, &placed.1) + &inst("own", &own.0, &own.1) + &inst("mixed", &placed.0, &own.1);
std::fs::write(&state, text).unwrap();
let r = Reach { own: [own.0.canonicalize().unwrap()].into(), ..fleet(&root) };
let s = peer(&root);
let fetch = |name: &str, r: &Reach| admit("instances.fetch", json!({"instance": name}), &s, r, &state);
assert!(fetch("placed", &r).is_ok());
assert!(fetch("id-placed", &r).is_ok(), "by id");
assert!(admit("instances.done", json!({"instance": "own", "done": true}), &s, &r, &state).is_ok());
for name in ["own", "mixed", "nope"] {
assert_eq!(fetch(name, &r).unwrap_err().code, "not-found", "{name}");
}
assert_eq!(admit("instances.fetch", json!({}), &s, &r, &state).unwrap_err().code, "invalid");
let full = Reach { trust: Trust::Full, ..r.clone() };
assert!(fetch("own", &full).is_ok());
for r in [&r, &full] {
assert_eq!(admit("placements.fetch", json!({"instance": "x"}), &s, r, &state).unwrap_err().code, "denied");
}
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn a_verbs_env_is_this_hosts() {
let base = scratch("env");
let root = base.join("fleet/control_plane");
std::fs::create_dir_all(root.join("cfg")).unwrap();
let state = state_with(&base, &root);
let p = json!({"root": root.join("cfg"), "instance": "in", "env": {"PATH": "/control_plane/bin", "SSH_AUTH_SOCK": "/control_plane/agent"}});
let r = fleet(&root);
let got = admit("stop", p.clone(), &peer(&root), &r, &state).unwrap();
assert_eq!(got["env"], json!({"PATH": "/worker/bin"}));
let got = admit("run", json!({"root": root.join("cfg"), "sandbox": "web"}), &peer(&root), &r, &state).unwrap();
assert_eq!(got["env"], json!({"PATH": "/worker/bin"}));
let got = admit("sandboxes.list", json!({"root": root.join("cfg"), "env": {"A": "b"}}), &peer(&root), &r, &state).unwrap();
assert_eq!(got["env"], json!({"A": "b"}));
let haves = json!({"repos": ["0123456789abcdef"]});
assert_eq!(admit("code.haves", haves.clone(), &peer(&root), &r, &state).unwrap(), haves);
let full_reach = Reach { trust: Trust::Full, ..r.clone() };
assert_eq!(admit("code.haves", haves.clone(), &peer(&root), &full_reach, &state).unwrap(), haves);
let got = admit("mesh.folders", json!({"root": root.join("cfg"), "sandbox": "web"}), &peer(&root), &r, &state).unwrap();
assert_eq!(got["root"], json!(root.join("cfg").canonicalize().unwrap()));
assert_eq!(admit("mesh.folders", json!({"sandbox": "web"}), &peer(&root), &r, &state).unwrap_err().code, "invalid");
assert_eq!(admit("mesh.folders", json!({"root": base, "sandbox": "web"}), &peer(&root), &r, &state).unwrap_err().code, "denied");
let as_sent = Peer { env: None, ..peer(&root) };
assert_eq!(admit("stop", p.clone(), &as_sent, &r, &state).unwrap()["env"], p["env"]);
let full = Reach { trust: Trust::Full, ..r.clone() };
assert_eq!(admit("stop", p.clone(), &as_sent, &full, &state).unwrap()["env"], p["env"]);
assert_eq!(admit("stop", p.clone(), &peer(&root), &full, &state).unwrap()["env"], json!({"PATH": "/worker/bin"}));
let sock = base.join("agent-link-lap.sock");
let linked = Peer { agent: Some(sock.clone()), ..peer(&root) };
assert_eq!(admit("stop", p.clone(), &linked, &r, &state).unwrap()["env"], json!({"PATH": "/worker/bin"}), "not bound");
let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let want = json!({"PATH": "/worker/bin", "SSH_AUTH_SOCK": sock});
assert_eq!(admit("stop", p, &linked, &r, &state).unwrap()["env"], want);
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn worker_admits_own_roots_exactly() {
let base = scratch("own");
let root = base.join("fleet/control_plane");
std::fs::create_dir_all(root.join("cfg")).unwrap();
std::fs::create_dir_all(base.join("mine/nested")).unwrap();
std::fs::create_dir_all(base.join("other")).unwrap();
let state = state_with(&base, &root);
let (s, r) = (peer(&root), worker(&root, &[&base.join("mine")]));
let ok = |m: &str, p: Value| admit(m, p, &s, &r, &state).unwrap();
let code = |m: &str, p: Value| admit(m, p, &s, &r, &state).unwrap_err().code;
let mine = base.join("mine");
assert_eq!(ok("sandboxes.list", json!({"root": mine})), json!({"root": mine}), "an own root");
assert_eq!(code("sandboxes.list", json!({"root": mine.join("nested")})), "denied", "not what's nested in one");
assert_eq!(code("sandboxes.list", json!({"root": base.join("other")})), "denied", "nor another path");
assert_eq!(code("sandboxes.list", json!({"root": mine.join("nested/..")})), "denied", "`..`");
assert!(admit("start", json!({"root": mine, "all": true}), &s, &r, &state).is_ok());
let ssh = Reach { fleet_root: None, ..r.clone() };
let own = own_roots(&State::load_at(&state).unwrap(), None, None);
let ssh = Reach { own: ssh.own.union(&own).cloned().collect(), ..ssh };
assert!(admit("stop", json!({"root": root.join("cfg"), "all": true}), &s, &ssh, &state).is_ok());
let attached = Peer { name: "lap".into(), fleet_root: None, env: None, agent: None, key: None, introduced_by: None };
let sent = json!({"root": mine, "instance": "own", "env": {"SSH_AUTH_SOCK": "/run/agent-machine_lap.sock"}});
assert_eq!(admit("stop", sent.clone(), &attached, &ssh, &state).unwrap(), sent);
assert_eq!(admit("config.migrate", json!({"root": mine}), &s, &ssh, &state).unwrap_err().code, "denied");
assert!(admit("instances.done", json!({"instance": "own", "done": true}), &s, &r, &state).is_ok());
assert!(admit("stop", json!({"root": mine, "instance": "web"}), &s, &r, &state).is_ok(), "both matches reached");
for m in ["config.migrate", "config.ack"] {
let e = admit(m, json!({"root": mine}), &s, &r, &state).unwrap_err();
assert_eq!(e.code, "denied", "{m}");
assert!(e.message.contains("machine trust full"), "{}", e.message);
assert!(admit(m, json!({"root": root.join("cfg")}), &s, &r, &state).is_ok(), "{m} under the fleet root");
}
assert!(admit("config.findings", json!({"root": mine}), &s, &r, &state).is_ok(), "reading is fine");
assert_eq!(ok("roots.list", json!({})), json!({}));
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn full_skips_the_table_but_not_member_or_link() {
let base = scratch("full");
let root = base.join("fleet/control_plane");
std::fs::create_dir_all(&root).unwrap();
let state = base.join("absent.toml");
let (s, r) = (peer(&root), Reach { trust: Trust::Full, ..fleet(&root) });
for (m, p) in [
("sandboxes.list", json!({"root": "/anywhere/at/all"})),
("config.migrate", json!({"root": "/etc"})),
("machines.list", json!({})),
("shutdown", json!({})),
("instances.done", json!({"instance": "nobody"})),
("stop", json!({"all": true})),
("instances.list", json!({"machine": "m"})),
("gc", json!({"root": "/anywhere", "force": true})),
] {
let as_sent = Peer { env: None, ..s.clone() };
assert_eq!(admit(m, p.clone(), &as_sent, &r, &state).unwrap(), p, "{m}: as sent");
}
let gc = json!({"root": root, "env": {"PATH": "/control_plane/bin"}});
assert_eq!(admit("gc", gc.clone(), &s, &r, &state).unwrap()["env"], json!({"PATH": "/worker/bin"}));
let e = admit("gc", gc, &s, &fleet(&root), &state).unwrap_err();
assert_eq!(e.code, "denied");
assert!(e.message.contains("host maintenance"), "{}", e.message);
for m in ["member.get", "member.set", "membership.get", "membership.adopt", "membership.sign", "link.attach", "link.anything", "links.inbound", "fleet.leave", "fleet.rm", "access.pending", "access.decide", "credentials.login"] {
for reach in [&r, &fleet(&root)] {
assert_eq!(admit(m, json!({}), &s, reach, &state).unwrap_err().code, "denied", "{m}");
}
}
for reach in [&r, &fleet(&root)] {
let e = admit("subscribe", json!({"topics": ["instances", "access"]}), &s, reach, &state).unwrap_err();
assert_eq!(e.code, "denied");
}
let p = json!({"topics": ["instances", "forwards"]});
assert_eq!(admit("subscribe", p.clone(), &s, &r, &state).unwrap(), p);
let _ = std::fs::remove_dir_all(&base);
}
fn sk(n: u8) -> crate::serve::fleet::identity::SigningKey {
crate::serve::fleet::identity::SigningKey::from_seed([n; 32])
}
fn pk(n: u8) -> PublicKey {
crate::serve::fleet::identity::Signer::public_key(&sk(n))
}
fn proved(name: &str, n: u8) -> Peer {
Peer { name: name.into(), fleet_root: None, env: None, agent: None, key: Some(pk(n)), introduced_by: None }
}
fn fleet_log() -> Stored {
use crate::serve::fleet::membership::Introduction;
let mut s = crate::serve::fleet::membership_api::test_support::fleet("lap", &sk(1), "box", &[("box", pk(2)), ("pi", pk(3))]);
let genesis = s.log.membership().unwrap().genesis;
s.introduce(Introduction::sign(&genesis, "new", pk(5), "pi", &sk(3))).unwrap();
s
}
fn own_key(own: &str) -> Option<PublicKey> {
match own {
"lap" => Some(pk(1)),
"box" => Some(pk(2)),
"pi" => Some(pk(3)),
"new" => Some(pk(5)),
_ => None,
}
}
#[test]
fn fleet_calls_go_by_the_proven_key() {
let stored = fleet_log();
let mut revoked = stored.clone();
revoked.log.append(crate::serve::fleet::membership::Op::Revoke { name: "pi".into(), key: pk(3) }, "lap", &sk(1)).unwrap();
let on = |own| Some(Log { stored: &stored, own, key: own_key(own) });
let after = |own| Some(Log { stored: &revoked, own, key: own_key(own) });
let none = json!({});
let pi = json!({"name": "pi"});
let code = |m: &str, p: &Peer, log: Option<Log>| admit_fleet(m, &pi, Some(p), log).unwrap_err().code;
let capped = Peer { introduced_by: Some("pi".into()), ..proved("new", 5) };
for (m, params) in [("fleet.leave", &none), ("fleet.forget", &pi)] {
assert_eq!(admit_fleet(m, params, Some(&proved("box", 2)), after("pi")), Ok(()), "{m} from the control plane, after the revoke");
let e = admit_fleet(m, params, Some(&proved("box", 2)), on("pi")).unwrap_err();
assert!(e.code == "denied" && e.message.contains("follows a revoke"), "{m}: no revoke yet: {}", e.message);
assert_eq!(code(m, &proved("box", 9), after("pi")), "denied", "{m}: the control plane's name, another key");
assert_eq!(code(m, &proved("lap", 2), after("pi")), "denied", "{m}: the control plane's key, another name");
assert_eq!(code(m, &proved("lap", 1), after("pi")), "denied", "{m}: the authority isn't the control plane");
assert_eq!(code(m, &capped, after("pi")), "denied");
assert_eq!(code(m, &Peer { key: None, ..proved("box", 2) }, after("pi")), "denied", "{m}: no key");
assert_eq!(admit_fleet(m, params, Some(&proved("box", 2)), None).unwrap_err().code, "denied", "{m}: no log");
assert_eq!(admit_fleet(m, params, None, after("pi")).unwrap_err().code, "denied", "{m}: a local client");
}
assert_eq!(code("fleet.leave", &proved("box", 2), after("lap")), "denied");
assert_eq!(admit_fleet("fleet.forget", &none, Some(&proved("box", 2)), after("lap")).unwrap_err().code, "invalid");
for m in ["fleet.rm", "fleet.place"] {
let log = if m == "fleet.rm" { after("box") } else { on("box") };
assert_eq!(admit_fleet(m, &pi, Some(&proved("pi", 3)), on("box")), Ok(()), "{m} from a member (`rm` of itself)");
assert_eq!(admit_fleet(m, &pi, Some(&proved("lap", 1)), log), Ok(()), "{m} from the authority");
let e = admit_fleet(m, &pi, Some(&proved("pi", 3)), on("lap")).unwrap_err();
assert_eq!((e.code, e.message), ("denied", format!("`{m}` runs on the control plane, and this host isn't it")));
assert_eq!(code(m, &proved("pi", 1), on("box")), "denied", "{m}: a member's name, another's key");
assert_eq!(code(m, &proved("stranger", 9), on("box")), "denied");
assert_eq!(code(m, &Peer { key: None, ..proved("pi", 3) }, on("box")), "denied", "{m}: no key");
assert_eq!(admit_fleet(m, &pi, None, on("box")).unwrap_err().code, "denied");
}
let e = admit_fleet("fleet.rm", &pi, Some(&proved("lap", 1)), on("box")).unwrap_err();
assert!(e.code == "denied" && e.message.contains("isn't revoked in the control plane's membership log"), "{}", e.message);
assert_eq!(admit_fleet("fleet.place", &none, Some(&capped), on("box")), Ok(()));
assert_eq!(admit_fleet("fleet.place", &none, Some(&Peer { key: Some(pk(9)), ..capped.clone() }), on("box")).unwrap_err().code, "denied");
let e = admit_fleet("fleet.rm", &pi, Some(&capped), on("box")).unwrap_err();
assert_eq!(e.code, "denied");
assert!(e.message.contains("capped"), "{}", e.message);
assert_eq!(admit_fleet("fleet.other", &none, Some(&proved("box", 2)), on("pi")).unwrap_err().code, "unknown-method");
}
#[test]
fn the_control_plane_only_calls_follow_the_logs_control_plane() {
use crate::serve::fleet::membership::Op;
let mut before = fleet_log();
before.log.append(Op::Add { name: "zed".into(), key: pk(4) }, "lap", &sk(1)).unwrap();
before.log.append(Op::Revoke { name: "zed".into(), key: pk(4) }, "lap", &sk(1)).unwrap();
let mut moved = before.clone();
moved.log.append(Op::ControlPlane { name: "pi".into() }, "lap", &sk(1)).unwrap();
let (zed, none) = (json!({"name": "zed"}), json!({}));
fn at<'a>(stored: &'a Stored, own: &'a str) -> Option<Log<'a>> {
Some(Log { stored, own, key: own_key(own) })
}
assert_eq!(admit_fleet("fleet.forget", &zed, Some(&proved("box", 2)), at(&before, "lap")), Ok(()));
assert_eq!(admit_fleet("fleet.forget", &zed, Some(&proved("pi", 3)), at(&before, "lap")).unwrap_err().code, "denied");
assert_eq!(admit_fleet("fleet.forget", &zed, Some(&proved("pi", 3)), at(&moved, "lap")), Ok(()), "the new control plane's key");
let e = admit_fleet("fleet.forget", &zed, Some(&proved("box", 2)), at(&moved, "lap")).unwrap_err();
assert!(e.code == "denied" && e.message.contains("`box` isn't it"), "the old control plane's key: {}", e.message);
for (m, params) in [("fleet.rm", &zed), ("fleet.place", &none), ("fleet.report", &none)] {
assert_eq!(admit_fleet(m, params, Some(&proved("lap", 1)), at(&before, "box")), Ok(()), "{m} on the control plane");
assert_eq!(admit_fleet(m, params, Some(&proved("lap", 1)), at(&moved, "pi")), Ok(()), "{m} on the new control plane");
let e = admit_fleet(m, params, Some(&proved("lap", 1)), at(&moved, "box")).unwrap_err();
assert_eq!((e.code, e.message), ("denied", format!("`{m}` runs on the control plane, and this host isn't it")), "{m} on the old control plane");
}
}
#[test]
fn proposals_go_to_the_authority_and_syncs_come_from_members() {
let stored = fleet_log();
let on = |own| Some(Log { stored: &stored, own, key: own_key(own) });
let p = json!({"op": {"kind": "revoke", "name": "pi"}});
let capped = Peer { introduced_by: Some("pi".into()), ..proved("new", 5) };
assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("pi", 3)), on("lap")), Ok(()));
assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("box", 2)), on("lap")), Ok(()), "the control plane is a member too");
let e = admit_fleet("fleet.propose", &p, Some(&proved("pi", 3)), on("box")).unwrap_err();
assert_eq!((e.code, e.message.as_str()), ("denied", "`fleet.propose` goes to the fleet's authority `lap`, and this host isn't it"));
let impostor = Some(Log { stored: &stored, own: "lap", key: Some(pk(9)) });
assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("pi", 3)), impostor).unwrap_err().code, "denied");
let e = admit_fleet("fleet.propose", &p, Some(&capped), on("lap")).unwrap_err();
assert!(e.code == "denied" && e.message.contains("capped"), "{}", e.message);
assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("pi", 9)), on("lap")).unwrap_err().code, "denied");
assert_eq!(admit_fleet("fleet.propose", &p, Some(&proved("stranger", 9)), on("lap")).unwrap_err().code, "denied");
let sync = json!({"entries": []});
for own in ["lap", "box", "pi"] {
assert_eq!(admit_fleet("fleet.sync", &sync, Some(&proved("box", 2)), on(own)), Ok(()), "on {own}");
}
assert_eq!(admit_fleet("fleet.sync", &sync, Some(&capped), on("pi")), Ok(()), "from an introduced peer");
assert_eq!(admit_fleet("fleet.sync", &sync, Some(&proved("stranger", 9)), on("pi")).unwrap_err().code, "denied");
assert_eq!(admit_fleet("fleet.sync", &sync, None, on("pi")).unwrap_err().code, "denied");
}
#[test]
fn link_reports_go_to_the_control_plane_and_graphs_come_from_members() {
let stored = fleet_log();
let on = |own| Some(Log { stored: &stored, own, key: own_key(own) });
let p = json!({});
let capped = Peer { introduced_by: Some("pi".into()), ..proved("new", 5) };
for from in [proved("pi", 3), proved("lap", 1), capped.clone()] {
assert_eq!(admit_fleet("fleet.report", &p, Some(&from), on("box")), Ok(()), "{} to the control plane", from.name);
for own in ["lap", "box", "pi"] {
assert_eq!(admit_fleet("fleet.graph", &p, Some(&from), on(own)), Ok(()), "{} on {own}", from.name);
}
}
let e = admit_fleet("fleet.report", &p, Some(&proved("pi", 3)), on("lap")).unwrap_err();
assert_eq!((e.code, e.message.as_str()), ("denied", "`fleet.report` runs on the control plane, and this host isn't it"));
for m in ["fleet.report", "fleet.graph"] {
let on = if m == "fleet.report" { on("box") } else { on("pi") };
assert_eq!(admit_fleet(m, &p, Some(&proved("pi", 9)), on).unwrap_err().code, "denied", "{m}: a member's name, another key");
assert_eq!(admit_fleet(m, &p, Some(&proved("stranger", 9)), on).unwrap_err().code, "denied", "{m}");
assert_eq!(admit_fleet(m, &p, Some(&Peer { key: None, ..proved("pi", 3) }), on).unwrap_err().code, "denied", "{m}: no key");
assert_eq!(admit_fleet(m, &p, Some(&proved("pi", 3)), None).unwrap_err().code, "denied", "{m}: no log");
assert_eq!(admit_fleet(m, &p, None, on).unwrap_err().code, "denied", "{m}: a local client");
}
let e = admit_fleet("fleet.report", &p, Some(&proved("new", 9)), on("box")).unwrap_err();
assert_eq!(e.code, "denied");
let r = Reach { trust: Trust::Full, fleet_root: None, own: BTreeSet::new() };
let e = admit("graph.get", json!({}), &proved("pi", 3), &r, Path::new("/nonexistent")).unwrap_err();
assert_eq!(e.code, "denied");
}
#[test]
fn the_reach_comes_from_member_toml_and_state_toml() {
let base = scratch("load");
let root = base.join("fleet/control_plane");
std::fs::create_dir_all(root.join("cfg")).unwrap();
std::fs::create_dir_all(base.join("mine")).unwrap();
std::fs::create_dir_all(base.join("picked")).unwrap();
std::fs::create_dir_all(base.join("home/.devsandboxes")).unwrap();
let state = state_with(&base, &root);
let files = Files { state, member: Some(base.join("member.toml")), home: Some(base.join("home")) };
let (r, warn) = Reach::load(&files, Some(&root));
assert_eq!(warn, None);
assert_eq!(r.trust, Trust::Worker, "no member.toml");
let own = |p: &[&str]| p.iter().map(|p| base.join(p)).collect::<BTreeSet<_>>();
assert_eq!(r.own, [root.join("cfg")].into_iter().chain(own(&["mine", "home/.devsandboxes"])).collect());
member::write_for_test(
files.member.as_ref().unwrap(),
&Member { trust: Trust::Full, roots: vec![base.join("picked"), base.join("gone")], ..Default::default() },
);
let (r, warn) = Reach::load(&files, Some(&root));
assert_eq!((r.trust, warn), (Trust::Full, None));
assert!(r.own.is_superset(&own(&["picked", "gone"])), "picked ones, a missing one as written");
std::fs::write(files.member.as_ref().unwrap(), "trust = 1\n").unwrap();
let (r, warn) = Reach::load(&files, Some(&root));
assert_eq!(r.trust, Trust::Worker);
assert!(!r.own.contains(&base.join("picked")));
assert!(warn.unwrap().contains("trust = \"worker\""));
let (r, _) = Reach::load(&Files { member: None, ..files }, None);
assert_eq!((r.trust, r.fleet_root), (Trust::Worker, None));
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn an_installed_mesh_copy_is_an_own_root() {
use crate::serve::fleet::mesh;
let base = scratch("mesh");
let (data, src) = (base.join("data"), base.join("src/cfg"));
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("devsandboxes.toml"), "[sandbox.a]\n").unwrap();
let b = mesh::collect(&src).unwrap();
let state = data.join("state.toml");
let files = Files { state: state.clone(), member: Some(data.join("member.toml")), home: None };
assert!(Reach::load(&files, None).0.own.is_empty(), "nothing installed");
mesh::install(&data, "cfg", &b.tar().unwrap(), &b.hash()).unwrap();
let copy = std::fs::canonicalize(mesh::tree_path(&data, "cfg")).unwrap();
std::fs::create_dir_all(copy.join("nested")).unwrap();
assert_eq!(own_roots(&State::default(), None, Some(&data)), BTreeSet::from([copy.clone()]));
let (r, _) = Reach::load(&files, None);
assert_eq!(r.trust, Trust::Worker);
assert!(r.admits(©));
assert!(!r.admits(©.join("nested")) && !r.admits(&data.join("mesh")));
let s = peer(&base.join("fleet/control_plane"));
assert!(admit("start", json!({"root": copy, "all": true}), &s, &r, &state).is_ok());
let _ = std::fs::remove_dir_all(&base);
}
#[test]
fn rows_are_cut_to_the_fleet_root() {
let root = Path::new("/nonexistent/fleet/control_plane");
let mut snap = json!({
"instances": [
{"name": "in", "root": "/nonexistent/fleet/control_plane/cfg", "instance_id": "i1"},
{"name": "own", "root": "/nonexistent/mine", "instance_id": "o1"},
{"name": "sneaky", "root": "/nonexistent/fleet/control_plane/../../mine"},
{"name": "old", "root": null},
],
"services": [
{"name": "db", "used_by": ["in", "own"]},
{"name": "cache", "scope": "isolated", "used_by": ["in", "own"], "containers": [
["devsandbox-svc-p-i1-cache", {"Running": "Up"}], ["devsandbox-svc-p-o1-cache", {"Running": "Up"}]]},
{"name": "pg", "scope": "global", "used_by": ["in"], "containers": [["devsandbox-svc-p-pg", {"Running": "Up"}]]},
],
"sandboxes": [{"name": "web"}],
"thread_children": {"id-own": {"k": "own"}, "id-in": {"k": "in", "j": "own"}},
});
let full = Reach { trust: Trust::Full, ..fleet(root) };
let mut whole = snap.clone();
filter_snapshot(&mut whole, &full);
assert_eq!(whole, snap, "nothing cut under `full`");
let mut own = snap.clone();
filter_snapshot(&mut own, &worker(root, &[Path::new("/nonexistent/mine")]));
let names: Vec<&str> = own["instances"].as_array().unwrap().iter().map(|r| r["name"].as_str().unwrap()).collect();
assert_eq!(names, ["in", "own"], "an own root's rows kept, the others dropped");
assert_eq!(own["thread_children"], json!({"id-own": {"k": "own"}, "id-in": {"k": "in", "j": "own"}}));
let root = &fleet(root);
filter_snapshot(&mut snap, root);
assert_eq!(snap["instances"], json!([{"name": "in", "root": "/nonexistent/fleet/control_plane/cfg", "instance_id": "i1"}]));
assert_eq!(snap["services"][0]["used_by"], json!(["in"]));
assert_eq!(snap["services"][1]["containers"], json!([["devsandbox-svc-p-i1-cache", {"Running": "Up"}]]), "another root's isolated copy cut");
assert_eq!(snap["services"][2]["containers"].as_array().unwrap().len(), 1, "a global one kept");
assert_eq!(snap["thread_children"], json!({"id-in": {"k": "in"}}));
assert_eq!(snap["sandboxes"], json!([{"name": "web"}]), "the root's own config, as is");
let resolved = json!({"matches": ["in", "own"], "found": [
{"name": "in", "root": "/nonexistent/fleet/control_plane/cfg"}, {"name": "own", "root": "/nonexistent/mine"}]});
let got = filter_answer("instances.resolve", resolved, root).unwrap();
assert_eq!(got, json!({"matches": ["in"], "found": [{"name": "in", "root": "/nonexistent/fleet/control_plane/cfg"}]}));
let own = json!({"matches": ["own"], "found": [{"name": "own", "root": "/nonexistent/mine"}]});
assert_eq!(filter_answer("instances.resolve", own, root).unwrap_err().code, "not-found");
assert_eq!(filter_answer("sandboxes.list", json!({"a": 1}), root).unwrap(), json!({"a": 1}));
}
#[test]
fn a_federated_push_keeps_other_machines_rows() {
let root = Path::new("/nonexistent/fleet/control_plane");
let mut snap = json!({
"instances": [
{"name": "in", "root": "/nonexistent/fleet/control_plane/cfg", "instance_id": "i1"},
{"name": "own", "root": "/nonexistent/mine", "instance_id": "o1"},
{"name": "own", "root": "/x/cfg", "machine": "x", "instance_id": "x1"},
],
"services": [
{"name": "db", "used_by": ["in", "own"]},
{"name": "db", "used_by": ["own"], "machine": "x", "root": "/x/cfg"},
],
"machines": [{"name": "x"}],
});
filter_snapshot(&mut snap, &fleet(root));
let rows: Vec<(&str, Option<&str>)> =
snap["instances"].as_array().unwrap().iter().map(|r| (r["name"].as_str().unwrap(), r["machine"].as_str())).collect();
assert_eq!(rows, [("in", None), ("own", Some("x"))]);
assert_eq!(snap["services"][0]["used_by"], json!(["in"]), "x's `own` isn't this host's");
assert_eq!(snap["services"][1]["used_by"], json!(["own"]), "x's service as x has it");
assert_eq!(snap["machines"], json!([{"name": "x"}]));
}
#[test]
fn a_peers_roots_listing_gets_its_fleet_root_once() {
let reach = worker(Path::new("/d/fleet/control_plane"), &[]);
let own = json!([{"root": "/own", "sandboxes": [{"name": "web"}], "error": null}]);
let got = with_fleet_root(own.clone(), &reach);
assert_eq!(got, json!([own[0], {"root": "/d/fleet/control_plane", "sandboxes": [], "error": null, "fleet": true}]));
assert_eq!(with_fleet_root(got.clone(), &reach), got, "listed already");
let listed = json!([{"root": "/d/fleet/control_plane", "sandboxes": [], "error": null, "fleet": false}]);
assert_eq!(with_fleet_root(listed, &reach), json!([{"root": "/d/fleet/control_plane", "sandboxes": [], "error": null, "fleet": true}]));
let relay = Reach { fleet_root: None, ..reach.clone() };
assert_eq!(with_fleet_root(own.clone(), &relay), own, "no fleet root: as is");
assert_eq!(with_fleet_root(json!({"x": 1}), &reach), json!({"x": 1}), "not a listing");
}
}