use std::path::PathBuf;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::api::ApiError;
use super::attaches::Origin;
use super::forwards;
use crate::devsbd::bridge::Opener;
use crate::open::{self, ForwardTarget, Forwarder, Loopback, OnDone, OpenDone, OpenJob, Outcome};
pub type OpenHere = Arc<dyn Fn(OpenJob) + Send + Sync>;
pub type CallMember = Arc<dyn Fn(&str, &str, Value) -> Result<Value, String> + Send + Sync>;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeliverParams {
pub instance: String,
pub root: PathBuf,
pub url: String,
pub profile: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Route {
Here,
Member(String),
}
pub fn route(latest: Option<Origin>) -> Route {
match latest {
None | Some(Origin::Here) => Route::Here,
Some(Origin::Member(m)) => Route::Member(m),
}
}
#[derive(Clone)]
pub struct Sender {
pub prepare: Arc<dyn Fn(&str, &str, &str) -> OpenJob + Send + Sync>,
pub latest: Arc<dyn Fn(&str) -> Option<Origin> + Send + Sync>,
pub call_member: CallMember,
pub open_here: OpenHere,
pub done: OnDone,
pub log: fn(&str),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DoneParams {
pub instance: String,
pub url: String,
pub profile: Option<String>,
pub outcome: &'static str,
pub why: Option<String>,
pub line: String,
}
impl DoneParams {
pub fn new(done: &OpenDone) -> DoneParams {
DoneParams {
instance: done.instance.clone(),
url: done.url.clone(),
profile: done.profile.clone(),
outcome: done.kind(),
why: done.why(),
line: done.line(),
}
}
}
fn failed(instance: &str, url: &str, profile: Option<String>, why: String) -> OpenDone {
OpenDone { instance: instance.to_string(), url: url.to_string(), profile, outcome: Outcome::Failed(why) }
}
pub fn opener(sender: Sender) -> Opener {
Arc::new(move |instance: &str, instance_id: &str, url: &str| {
let (log, done) = (sender.log, Arc::clone(&sender.done));
let (s, i, id, u) = (sender.clone(), instance.to_string(), instance_id.to_string(), url.to_string());
let spawned = std::thread::Builder::new().name("serve-open".into()).spawn(move || send(&s, &i, &id, &u));
if let Err(e) = spawned {
log(&format!("cannot start an open's thread: {e}"));
done(failed(instance, url, None, format!("cannot start an open's thread: {e}")));
}
})
}
pub fn send(s: &Sender, instance: &str, instance_id: &str, url: &str) {
let job = (s.prepare)(instance, instance_id, url);
match route((s.latest)(instance_id)) {
Route::Here => (s.open_here)(job),
Route::Member(m) => {
let delivered = deliver_params(&job).and_then(|p| {
let params = serde_json::to_value(p).map_err(|e| e.to_string())?;
(s.call_member)(&m, "open.deliver", params)
});
if let Err(why) = delivered {
let why = open::printable(&why);
(s.log)(&format!("{instance}: cannot deliver {url} to {m}: {why}"));
(s.done)(failed(instance, url, job.profile, format!("cannot deliver to {m}: {why}")));
}
}
}
}
fn deliver_params(job: &OpenJob) -> Result<DeliverParams, String> {
let target = job.target.as_ref().map_err(Clone::clone)?;
Ok(DeliverParams { instance: target.instance.clone(), root: target.dir.clone(), url: job.url.clone(), profile: job.profile.clone() })
}
const MAX_URL: usize = crate::devsbd::notify::MAX_RECORD;
const MAX_INSTANCE: usize = 256;
const MAX_PROFILE: usize = 64;
fn valid_instance(name: &str) -> bool {
let mut chars = name.chars();
chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
&& chars.all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
}
pub fn receive(
params: Value,
peer: &str,
now: u64,
limit: impl FnOnce(&str) -> bool,
attached: impl FnOnce(&str) -> bool,
) -> Result<OpenJob, ApiError> {
let p: DeliverParams = super::api::parse(params)?;
if p.instance.is_empty() || p.instance.len() > MAX_INSTANCE {
return Err(ApiError::invalid(format!("`instance`: 1 to {MAX_INSTANCE} bytes")));
}
if !valid_instance(&p.instance) {
return Err(ApiError::invalid(format!("`instance`: not an instance name: {}", open::printable(&p.instance))));
}
if p.url.len() > MAX_URL {
return Err(ApiError::invalid(format!("`url`: at most {MAX_URL} bytes")));
}
if open::has_bad_chars(&p.url) {
return Err(ApiError::invalid(open::Verdict::BadChars.log_line(&p.instance, &p.url).unwrap_or_default()));
}
if !p.root.is_absolute() {
return Err(ApiError::invalid(format!("`root` must be absolute: {}", p.root.display())));
}
if let Some(profile) = &p.profile {
if profile.len() > MAX_PROFILE {
return Err(ApiError::invalid(format!("`profile`: at most {MAX_PROFILE} bytes")));
}
crate::config::check_profile_name(profile).map_err(|e| ApiError::invalid(format!("{e:#}")))?;
}
if !attached(&p.instance) {
return Err(ApiError::denied(format!(
"`{peer}` asked to open {} for `{}`, which this host hasn't attached to in the last {} min",
p.url,
p.instance,
open::OPEN_ATTACH_WINDOW.as_secs() / 60
)));
}
let verdict = open::decide(&p.url, now, now, || limit(&p.instance));
if let Some(line) = verdict.log_line(&p.instance, &p.url) {
let code = if matches!(verdict, open::Verdict::BadScheme(_) | open::Verdict::BadChars) { "invalid" } else { "denied" };
return Err(ApiError { code, message: line });
}
let target = ForwardTarget { machine: Some(peer.to_string()), dir: p.root, instance: p.instance.clone() };
Ok(OpenJob { instance: p.instance, url: p.url, profile: p.profile, target: Ok(target) })
}
pub fn forwarder(forwards: Option<forwards::Handle>) -> Forwarder {
Arc::new(move |target: &ForwardTarget, lb: Loopback| {
let Some(forwards) = &forwards else { return Err(Some("no forwards registry in this daemon".into())) };
let req = forwards::OpenRequest {
machine: target.machine.clone(),
dir: target.dir.clone(),
instance: target.instance.clone(),
container_port: lb.port,
callback: lb.callback,
};
forwards
.open_forward(req)
.map(|o| o.host_port)
.map_err(|e| (!(lb.callback && e.code == "bind-failed")).then_some(e.message))
})
}
pub fn open_here(forward: Forwarder, log: fn(&str), done: OnDone) -> OpenHere {
Arc::new(move |job: OpenJob| {
let (forward, d) = (Arc::clone(&forward), Arc::clone(&done));
let (instance, url, profile) = (job.instance.clone(), job.url.clone(), job.profile.clone());
let spawned = std::thread::Builder::new().name("serve-open".into()).spawn(move || open::open_here(job, &forward, log, &d));
if let Err(e) = spawned {
log(&format!("cannot start an open's thread: {e}"));
done(failed(&instance, &url, profile, format!("cannot start an open's thread: {e}")));
}
})
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use serde_json::json;
use super::*;
#[test]
fn the_last_attach_decides() {
assert_eq!(route(None), Route::Here, "nothing attached yet");
assert_eq!(route(Some(Origin::Here)), Route::Here);
assert_eq!(route(Some(Origin::Member("lap".into()))), Route::Member("lap".into()));
}
fn job(target: Result<ForwardTarget, String>) -> OpenJob {
OpenJob { instance: "web-1".into(), url: "http://localhost:3000/".into(), profile: Some("work".into()), target }
}
fn local() -> ForwardTarget {
ForwardTarget { machine: None, dir: "/cfg".into(), instance: "web-1".into() }
}
type Calls = Arc<Mutex<Vec<(String, String, Value)>>>;
type Dones = Arc<Mutex<Vec<OpenDone>>>;
fn sender(
target: Result<ForwardTarget, String>,
latest: Option<Origin>,
answer: Result<Value, String>,
) -> (Sender, Calls, Arc<Mutex<Vec<OpenJob>>>, Dones) {
let (calls, opened, dones): (Calls, Arc<Mutex<Vec<OpenJob>>>, Dones) = Default::default();
let (c, o, d) = (Arc::clone(&calls), Arc::clone(&opened), Arc::clone(&dones));
let s = Sender {
prepare: Arc::new(move |_, _, _| job(target.clone())),
latest: Arc::new(move |id| {
assert_eq!(id, "id-1");
latest.clone()
}),
call_member: Arc::new(move |m, method, params| {
c.lock().unwrap().push((m.into(), method.into(), params));
answer.clone()
}),
open_here: Arc::new(move |j| o.lock().unwrap().push(j)),
done: Arc::new(move |done| d.lock().unwrap().push(done)),
log: record,
};
(s, calls, opened, dones)
}
static LINES: Mutex<Vec<String>> = Mutex::new(Vec::new());
fn record(line: &str) {
LINES.lock().unwrap().push(line.to_string());
}
fn logged(needle: &str) -> bool {
LINES.lock().unwrap().iter().any(|l| l.contains(needle))
}
#[test]
fn an_open_with_no_member_attach_opens_here() {
for latest in [None, Some(Origin::Here)] {
let (s, calls, opened, dones) = sender(Ok(local()), latest, Ok(json!({"ok": true})));
send(&s, "web-1", "id-1", "http://localhost:3000/");
assert_eq!(*opened.lock().unwrap(), vec![job(Ok(local()))]);
assert!(calls.lock().unwrap().is_empty());
assert!(dones.lock().unwrap().is_empty(), "`open_here` tells its own");
}
}
#[test]
fn an_open_after_a_member_attach_is_delivered_there() {
let (s, calls, opened, dones) = sender(Ok(local()), Some(Origin::Member("lap".into())), Ok(json!({"ok": true})));
send(&s, "web-1", "id-1", "http://localhost:3000/");
let want = json!({"instance": "web-1", "root": "/cfg", "url": "http://localhost:3000/", "profile": "work"});
assert_eq!(*calls.lock().unwrap(), vec![("lap".to_string(), "open.deliver".to_string(), want)]);
assert!(opened.lock().unwrap().is_empty());
assert!(dones.lock().unwrap().is_empty(), "taken: the member tells its own");
}
#[test]
fn a_failed_delivery_is_logged_and_never_opens_here() {
let (s, _, opened, dones) =
sender(Ok(local()), Some(Origin::Member("lap".into())), Err("open.deliver: nope (denied)".into()));
send(&s, "web-1", "id-1", "https://a.example/");
assert!(logged("web-1: cannot deliver https://a.example/ to lap: open.deliver: nope (denied)"));
assert!(opened.lock().unwrap().is_empty(), "no fallback");
let told = dones.lock().unwrap().clone();
assert_eq!(
told,
vec![OpenDone {
instance: "web-1".into(),
url: "https://a.example/".into(),
profile: Some("work".into()),
outcome: Outcome::Failed("cannot deliver to lap: open.deliver: nope (denied)".into()),
}]
);
assert_eq!(told[0].line(), "web-1: open failed: cannot deliver to lap: open.deliver: nope (denied)");
let (s, calls, opened, dones) = sender(Err("not in state.toml".into()), Some(Origin::Member("lap".into())), Ok(json!({})));
send(&s, "gone", "id-1", "https://b.example/");
assert!(logged("gone: cannot deliver https://b.example/ to lap: not in state.toml"));
assert!(calls.lock().unwrap().is_empty() && opened.lock().unwrap().is_empty());
assert_eq!(dones.lock().unwrap()[0].line(), "gone: open failed: cannot deliver to lap: not in state.toml");
}
fn params() -> Value {
json!({"instance": "web-1", "root": "/home/u/cfg", "url": "http://localhost:3000/", "profile": "work"})
}
fn with_none() -> Value {
Value::Null
}
fn take(params: Value) -> Result<OpenJob, ApiError> {
receive(params, "box", 1_790_000_000, |_| true, |i| i == "web-1")
}
#[test]
fn a_delivery_for_an_attached_instance_is_taken() {
let target = ForwardTarget { machine: Some("box".into()), dir: "/home/u/cfg".into(), instance: "web-1".into() };
assert_eq!(
take(params()).unwrap(),
OpenJob {
instance: "web-1".into(),
url: "http://localhost:3000/".into(),
profile: Some("work".into()),
target: Ok(target)
}
);
let mut p = params();
p["profile"] = Value::Null;
assert_eq!(take(p).unwrap().profile, None);
}
#[test]
fn a_delivery_is_checked_in_order() {
let code = |p: Value| take(p).unwrap_err().code;
assert_eq!(code(with_none()), "invalid", "no params");
let with = |k: &str, v: Value| {
let mut p = params();
p[k] = v;
p
};
assert_eq!(code(with("machine", json!("lap"))), "invalid", "strict: no `machine`");
assert_eq!(code(with("extra", json!(1))), "invalid");
assert_eq!(code(json!({"instance": "web-1"})), "invalid");
assert_eq!(code(with("instance", json!(""))), "invalid");
assert_eq!(code(with("root", json!("rel"))), "invalid");
assert_eq!(code(with("profile", json!("Work Profile"))), "invalid");
assert_eq!(code(with("profile", json!("x".repeat(65)))), "invalid");
assert_eq!(code(with("url", json!(format!("https://x/{}", "a".repeat(MAX_URL))))), "invalid");
let e = take(with("url", json!("ssh://x"))).unwrap_err();
assert_eq!((e.code, e.message.as_str()), ("invalid", "web-1: open refused, scheme `ssh` (http and https only): ssh://x"));
let e = receive(params(), "box", 1, |_| false, |_| true).unwrap_err();
assert_eq!(e.code, "denied", "rate-limited: {}", e.message);
let e = take(with("instance", json!("web-2"))).unwrap_err();
assert_eq!(
(e.code, e.message.as_str()),
("denied", "`box` asked to open http://localhost:3000/ for `web-2`, which this host hasn't attached to in the last 10 min")
);
receive(with("url", json!("ssh://x")), "box", 1, |_| panic!("not asked"), |_| true).unwrap_err();
receive(params(), "box", 1, |_| panic!("not asked"), |_| false).unwrap_err();
}
#[test]
fn a_delivery_takes_only_an_instance_name_and_a_clean_url() {
let with = |k: &str, v: Value| {
let mut p = params();
p[k] = v;
p
};
for name in ["web 1", "-web", ".web", "_web", "web\n1", "wéb", "web/1", "web\u{1b}[2J"] {
let e = take(with("instance", json!(name))).unwrap_err();
assert_eq!(e.code, "invalid", "{name:?}");
assert!(!e.message.contains(['\n', '\u{1b}']), "{:?}", e.message);
}
for name in ["web-1", "Web_2.x", "9"] {
let e = receive(with("instance", json!(name)), "box", 1_790_000_000, |_| true, |_| false).unwrap_err();
assert_eq!(e.code, "denied", "{name}: a name, just not attached");
}
let e = receive(with("url", json!("https://x/\r\nweb-1: opened")), "box", 1, |_| panic!("not asked"), |_| panic!("not asked"))
.unwrap_err();
assert_eq!(
(e.code, e.message.as_str()),
("invalid", "web-1: open refused, control characters or whitespace in the URL: https://x/\\r\\nweb-1: opened")
);
assert_eq!(take(with("url", json!("https://x/a b"))).unwrap_err().code, "invalid");
}
#[test]
fn a_members_error_is_one_line_here() {
let (s, _, _, dones) = sender(Ok(local()), Some(Origin::Member("lap".into())), Err("nope\nweb-1: opened https://evil".into()));
send(&s, "web-1", "id-1", "https://c.example/");
assert!(logged("web-1: cannot deliver https://c.example/ to lap: nope\\nweb-1: opened https://evil"));
assert!(!dones.lock().unwrap()[0].line().contains('\n'));
}
}