use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use futures::future::BoxFuture;
use futures::{SinkExt, StreamExt};
use serde::Serialize;
use serde_json::{json, Value};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::{mpsc, watch};
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::{header::AUTHORIZATION, HeaderValue};
use tokio_tungstenite::tungstenite::Message;
use super::host::ChildPeer;
use super::link::{unavailable, Conn, Counters, SubKey};
use super::pairing::{commitment, key_fingerprint, pairing_code, KnownHosts};
use super::spec::{check_ws_url, is_insecure_ws, INSECURE_TRANSPORT};
use super::upcall::{HOST_CALL, HOST_CALL_UNSUB};
use super::ws::{key_proof, principal_of, read_seed};
use ed25519_dalek::Signer;
use super::Backoff;
use crate::plexus::plexus::Activation;
use crate::plexus::streaming::PlexusStream;
use crate::plexus::types::PlexusStreamItem;
#[derive(Debug, Clone)]
pub struct DialOut {
pub url: String,
pub key: PathBuf,
pub agent: String,
pub mount: Option<String>,
pub trust: Option<String>,
pub backoff: Backoff,
pub timeout: Duration,
pub insecure_ws: bool,
pub tls_roots: Option<PathBuf>,
}
impl DialOut {
pub fn new(url: impl Into<String>, key: impl Into<PathBuf>) -> Self {
Self {
url: url.into(),
key: key.into(),
agent: "plexus-service".into(),
mount: None,
trust: None,
backoff: Backoff { initial: Duration::from_millis(250), max: Duration::from_secs(10), per_minute: usize::MAX },
timeout: Duration::from_secs(10),
insecure_ws: false,
tls_roots: None,
}
}
pub fn mount(mut self, name: impl Into<String>) -> Self {
self.mount = Some(name.into());
self
}
pub fn trust(mut self, principal: impl Into<String>) -> Self {
self.trust = Some(principal.into());
self
}
pub fn agent(mut self, agent: impl Into<String>) -> Self {
self.agent = agent.into();
self
}
pub fn insecure_ws(mut self, on: bool) -> Self {
self.insecure_ws = on;
self
}
pub fn tls_roots(mut self, roots: impl Into<PathBuf>) -> Self {
self.tls_roots = Some(roots.into());
self
}
#[cfg(not(target_arch = "wasm32"))]
pub fn configured(mut self, c: &crate::plexus::config::Config) -> Self {
use crate::plexus::config::{settings::{TRANSPORT_INSECURE_WS, TRANSPORT_TLS_ROOTS}, Source};
if c.source(&TRANSPORT_INSECURE_WS) != Source::Default {
self.insecure_ws = c.get(&TRANSPORT_INSECURE_WS);
}
if c.source(&TRANSPORT_TLS_ROOTS) != Source::Default {
self.tls_roots = c.get(&TRANSPORT_TLS_ROOTS).map(Into::into);
}
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum DialState {
Connecting,
Mounted {
mount: String,
path: String,
service: String,
relay: String,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
insecure: bool,
},
Down { why: String },
Refused { why: String },
Stopped,
}
struct Live {
conn: Arc<Conn>,
service: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FirstContact {
pub url: String,
pub key: String,
pub fingerprint: String,
pub code: Option<String>,
}
type Ask = Arc<dyn Fn(FirstContact) -> BoxFuture<'static, bool> + Send + Sync>;
#[derive(Clone)]
struct First {
hosts: KnownHosts,
ask: Option<Ask>,
}
struct ExposedInner {
opts: DialOut,
live: Mutex<Option<Live>>,
state: watch::Sender<DialState>,
task: Mutex<Option<tokio::task::AbortHandle>>,
counters: Arc<Counters>,
first: Mutex<Option<First>>,
code: Mutex<Option<String>>,
pending: AtomicBool,
pending_for: Mutex<Duration>,
}
impl Drop for ExposedInner {
fn drop(&mut self) {
if let Some(t) = self.task.lock().unwrap().take() {
t.abort();
}
}
}
#[derive(Clone)]
pub struct Exposed {
inner: Arc<ExposedInner>,
}
impl std::fmt::Debug for Exposed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Exposed").field("url", &self.inner.opts.url).field("state", &self.state()).finish()
}
}
impl Exposed {
pub fn new(opts: DialOut) -> Self {
Self {
inner: Arc::new(ExposedInner {
opts,
live: Mutex::new(None),
state: watch::channel(DialState::Connecting).0,
task: Mutex::new(None),
counters: Arc::new(Counters::default()),
first: Mutex::new(None),
code: Mutex::new(None),
pending: AtomicBool::new(false),
pending_for: Mutex::new(Duration::from_secs(600)),
}),
}
}
pub fn with_first_contact<F, Fut>(self, known_hosts: impl Into<PathBuf>, ask: F) -> Self
where
F: Fn(FirstContact) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = bool> + Send + 'static,
{
let ask: Ask = Arc::new(move |c| Box::pin(ask(c)));
*self.inner.first.lock().unwrap() = Some(First { hosts: KnownHosts::new(known_hosts), ask: Some(ask) });
self
}
pub fn with_known_hosts(self, known_hosts: impl Into<PathBuf>) -> Self {
*self.inner.first.lock().unwrap() = Some(First { hosts: KnownHosts::new(known_hosts), ask: None });
self
}
pub fn with_pending_for(self, wait: Duration) -> Self {
*self.inner.pending_for.lock().unwrap() = wait;
self
}
pub fn pending(&self) -> Option<String> {
self.inner.pending.load(Ordering::Acquire).then(|| self.code()).flatten()
}
pub fn code(&self) -> Option<String> {
self.inner.code.lock().unwrap().clone()
}
pub fn options(&self) -> &DialOut {
&self.inner.opts
}
pub fn principal(&self) -> Result<String, String> {
read_seed(&self.inner.opts.key).map(|k| principal_of(&k))
}
pub fn state(&self) -> DialState {
self.inner.state.borrow().clone()
}
pub fn watch(&self) -> watch::Receiver<DialState> {
self.inner.state.subscribe()
}
pub async fn mounted(&self, timeout: Duration) -> Result<String, String> {
let mut rx = self.watch();
let settled = tokio::time::timeout(timeout, async {
rx.wait_for(|s| matches!(s, DialState::Mounted { .. } | DialState::Refused { .. } | DialState::Stopped)).await.map(|s| s.clone())
})
.await;
match settled {
Ok(Ok(DialState::Mounted { path, .. })) => Ok(path),
Ok(Ok(other)) => Err(format!("{other:?}")),
Ok(Err(_)) => Err("stopped".into()),
Err(_) => Err(format!("not mounted in {timeout:?} ({:?})", self.state())),
}
}
pub fn serve<A: Activation + Clone>(&self, activation: A) {
let weak = Arc::downgrade(&self.inner);
let task = tokio::spawn(async move {
let mut failures = 0usize;
loop {
let Some(inner) = weak.upgrade() else { return };
inner.state.send_replace(DialState::Connecting);
let outcome = session(&inner, activation.clone()).await;
inner.live.lock().unwrap().take();
let backoff = inner.opts.backoff;
match outcome {
Outcome::Refused(why) => {
tracing::warn!(target: "plexus::dial", url = %inner.opts.url, "the offer was refused: {why}");
inner.state.send_replace(DialState::Refused { why });
return;
}
Outcome::Dropped { why, was_mounted } => {
tracing::warn!(target: "plexus::dial", url = %inner.opts.url, "{why}; dialing again");
inner.state.send_replace(DialState::Down { why });
failures = if was_mounted { 0 } else { failures + 1 };
}
}
drop(inner);
tokio::time::sleep(backoff.delay(failures)).await;
}
});
if let Some(old) = self.inner.task.lock().unwrap().replace(task.abort_handle()) {
old.abort();
}
}
pub fn stop(&self) {
if let Some(t) = self.inner.task.lock().unwrap().take() {
t.abort();
}
if let Some(live) = self.inner.live.lock().unwrap().take() {
live.conn.shutdown.notify_one();
}
self.inner.state.send_replace(DialState::Stopped);
}
pub async fn call(&self, method: &str, params: Value) -> PlexusStream {
let one = |item: PlexusStreamItem| -> PlexusStream { Box::pin(futures::stream::iter([item])) };
let live = self.inner.live.lock().unwrap().as_ref().map(|l| (Arc::clone(&l.conn), l.service.clone()));
let Some((conn, service)) = live else {
return one(unavailable("relay", &format!("not connected to {} ({:?})", self.inner.opts.url, self.state())));
};
match conn.open(&format!("{service}.call"), json!({ "method": method, "params": params }), self.inner.opts.timeout, None).await {
Ok((sid, rx)) => Box::pin(Items { rx, sid, conn, over: false }),
Err(item) => one(item),
}
}
}
struct Items {
rx: mpsc::Receiver<PlexusStreamItem>,
sid: SubKey,
conn: Arc<Conn>,
over: bool,
}
impl futures::Stream for Items {
type Item = PlexusStreamItem;
fn poll_next(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<PlexusStreamItem>> {
if self.over {
return std::task::Poll::Ready(None);
}
match self.rx.poll_recv(cx) {
std::task::Poll::Ready(Some(item)) => {
self.over = matches!(item, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
std::task::Poll::Ready(Some(item))
}
std::task::Poll::Ready(None) => {
self.over = true;
std::task::Poll::Ready(Some(unavailable("relay", "the connection closed")))
}
std::task::Poll::Pending => std::task::Poll::Pending,
}
}
}
impl Drop for Items {
fn drop(&mut self) {
if !self.over {
self.conn.unsubscribe(&self.sid);
}
}
}
enum Outcome {
Refused(String),
Dropped { why: String, was_mounted: bool },
}
fn nonce() -> [u8; 32] {
let mut n = [0u8; 32];
n[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
n[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
n
}
const OFFER_ID: &str = "offer";
async fn session<A: Activation + Clone>(inner: &Arc<ExposedInner>, activation: A) -> Outcome {
let opts = &inner.opts;
let dropped = |why: String| Outcome::Dropped { why, was_mounted: false };
if let Err(why) = check_ws_url(&opts.url, opts.insecure_ws) {
return Outcome::Refused(format!("{INSECURE_TRANSPORT}: {why}"));
}
let first = inner.first.lock().unwrap().clone();
let pinned: Option<String> = match (&opts.trust, &first) {
(Some(_), _) | (None, None) => match trusted_key(opts.trust.as_deref()) {
Ok(k) => Some(k),
Err(why) => return Outcome::Refused(why),
},
(None, Some(f)) => match f.hosts.get(&opts.url) {
Ok(Some(k)) => Some(k),
Ok(None) if f.ask.is_some() => None,
Ok(None) => return Outcome::Refused(format!("no key is known for {} in {} (and no first contact is asked): a dial-out names its relay by key", opts.url, f.hosts.path().display())),
Err(why) => return Outcome::Refused(format!("the known hosts: {why}")),
},
};
if opts.url.starts_with("wss://") && !cfg!(feature = "child-wss") {
return Outcome::Refused("a wss:// relay needs plexus-core's `child-wss` feature (TLS)".into());
}
let mut req = match opts.url.as_str().into_client_request() {
Ok(r) => r,
Err(e) => return Outcome::Refused(format!("`{}`: {e}", opts.url)),
};
let signer = match read_seed(&opts.key) {
Ok(k) => k,
Err(e) => return Outcome::Refused(e),
};
let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
let proof = key_proof(&signer, super::ws::LOGIN_CONTEXT, opts.url.trim_end_matches('/'), &opts.agent, &nonce(), ts);
let me = principal_of(&signer);
match HeaderValue::from_str(&format!("Bearer {proof}")) {
Ok(v) => req.headers_mut().insert(AUTHORIZATION, v),
Err(e) => return Outcome::Refused(e.to_string()),
};
#[cfg(feature = "child-wss")]
let connecting = {
let tls = match opts.url.starts_with("wss://") {
true => match super::ws::tls_config(opts.tls_roots.as_deref()) {
Ok(c) => Some(tokio_tungstenite::Connector::Rustls(c)),
Err(why) => return Outcome::Refused(why),
},
false => None,
};
tokio_tungstenite::connect_async_tls_with_config(req, None, true, tls)
};
#[cfg(not(feature = "child-wss"))]
let connecting = tokio_tungstenite::connect_async_with_config(req, None, true);
let socket = match tokio::time::timeout(opts.timeout, connecting).await {
Err(_) => return dropped(format!("dialing {}: no answer to the upgrade in {:?}", opts.url, opts.timeout)),
Ok(Ok((s, _))) => s,
Ok(Err(tokio_tungstenite::tungstenite::Error::Http(resp))) => return dropped(format!("the upgrade to {} was refused: HTTP {}", opts.url, resp.status())),
Ok(Err(e)) => return dropped(format!("dialing {}: {e}", opts.url)),
};
let (mut sink, mut stream) = socket.split();
let (out, mut out_rx) = mpsc::unbounded_channel::<Vec<u8>>();
let conn = Conn::new("relay", None, out.clone(), 64, Arc::clone(&inner.counters));
let (mut host_in, host_r) = tokio::io::duplex(1 << 16);
let (host_w, host_out) = tokio::io::duplex(1 << 16);
let proven = Arc::new(AtomicBool::new(false));
let mut host: Option<tokio::task::JoinHandle<std::io::Result<()>>> = None;
let out_host = out.clone();
let host_lines = tokio::spawn(async move {
let mut lines = BufReader::new(host_out).lines();
while let Ok(Some(l)) = lines.next_line().await {
if out_host.send(host_request_out(l.into_bytes())).is_err() {
break;
}
}
});
let shutdown = Arc::clone(&conn);
let writer = tokio::spawn(async move {
loop {
tokio::select! {
first = out_rx.recv() => {
let Some(first) = first else { break };
let mut ok = sink.feed(Message::text(String::from_utf8_lossy(&first).into_owned())).await.is_ok();
while let (true, Ok(more)) = (ok, out_rx.try_recv()) {
ok = sink.feed(Message::text(String::from_utf8_lossy(&more).into_owned())).await.is_ok();
}
if !ok || sink.flush().await.is_err() {
break;
}
}
_ = shutdown.shutdown.notified() => {
let _ = sink.close().await;
break;
}
}
}
});
let (offer_tx, mut offer_rx) = mpsc::unbounded_channel::<Value>();
let reader_conn = Arc::clone(&conn);
let (reader_proven, refuse_out) = (Arc::clone(&proven), out.clone());
let reader = tokio::spawn(async move {
let why = loop {
let text = match stream.next().await {
Some(Ok(Message::Text(t))) => t.as_bytes().to_vec(),
Some(Ok(Message::Binary(b))) => b.to_vec(),
Some(Ok(Message::Close(f))) => break format!("the relay closed the socket ({})", f.map(|f| f.code.to_string()).unwrap_or_else(|| "no code".into())),
Some(Ok(_)) => continue,
Some(Err(e)) => break format!("the socket: {e}"),
None => break "the relay closed the socket".to_string(),
};
let shape: Value = match serde_json::from_slice(&text) {
Ok(v) => v,
Err(_) => continue,
};
let (method, id) = (shape.get("method"), shape.get("id"));
let method_is = |m: &str| method.and_then(Value::as_str) == Some(m);
let to_host = (method_is(HOST_CALL) && id.is_none()) || (method.is_none() && id.and_then(Value::as_str).is_some_and(|i| i.starts_with("h:")));
if to_host {
if !reader_proven.load(Ordering::Acquire) {
continue;
}
let mut line = host_answer_in(shape);
line.push(b'\n');
if host_in.write_all(&line).await.is_err() {
break "the host stopped".to_string();
}
} else if method_is(super::dial_in::OFFER_PENDING) && id.is_none() {
let _ = offer_tx.send(shape);
} else if method.is_some() && id.is_some() {
if !reader_proven.load(Ordering::Acquire) {
let refusal = json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "the relay has not proved its key", "data": { "error_kind": "forbidden" } } });
let _ = refuse_out.send(serde_json::to_vec(&refusal).unwrap_or_default());
continue;
}
let mut line = text;
line.push(b'\n');
if host_in.write_all(&line).await.is_err() {
break "the host stopped".to_string();
}
} else if method.is_none() && id.and_then(Value::as_str) == Some(OFFER_ID) {
let _ = offer_tx.send(shape);
} else {
reader_conn.on_message(&text).await;
}
};
reader_conn.on_gone(&why);
reader_conn.shutdown.notify_one();
why
});
let ended = |host: Option<tokio::task::JoinHandle<std::io::Result<()>>>, why: String, was_mounted: bool| {
if let Some(h) = host {
h.abort();
}
host_lines.abort();
writer.abort();
Outcome::Dropped { why, was_mounted }
};
let asked = crate::plexus::peer_token::random_nonce();
let node_nonce = crate::plexus::peer_token::random_nonce();
let info = async {
let (_, mut rx) = conn.open("_info", json!({ "nonce": asked, "commit": commitment(&node_nonce) }), opts.timeout, None).await.map_err(|e| format!("{e:?}"))?;
while let Some(item) = rx.recv().await {
if let PlexusStreamItem::Data { content, .. } = item {
let content = content.into_value();
if let Some(b) = content.get("backend").and_then(Value::as_str) {
let field = |k: &str| content.get(k).and_then(Value::as_str).map(str::to_string);
return Ok((b.to_string(), field("key"), field("proof"), field("host_nonce")));
}
}
}
Err::<_, String>("its `_info` names no backend".into())
};
let (service, key, key_proof, host_nonce) = match tokio::time::timeout(opts.timeout, info).await {
Ok(Ok(s)) => s,
Ok(Err(why)) => {
reader.abort();
return ended(host, format!("asking the relay's `_info`: {why}"), false);
}
Err(_) => {
reader.abort();
return ended(host, format!("the relay did not answer `_info` in {:?}", opts.timeout), false);
}
};
let from_file = opts.trust.is_none() && pinned.is_some();
if let (true, Some(p), Some(k)) = (from_file, &pinned, &key) {
if p != k {
reader.abort();
ended(host, String::new(), false);
let file = first.as_ref().map(|f| f.hosts.path().display().to_string()).unwrap_or_default();
let why = format!("host_key_changed: {} presents the key {k} ({}), not the one pinned in {file} ({p}): refused — someone may be in the middle; remove that line by hand only if the host's key really changed", opts.url, key_fingerprint(k).unwrap_or_default());
tracing::error!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
return Outcome::Refused(why);
}
}
let trusted = match pinned.clone().or_else(|| key.clone()) {
Some(t) => t,
None => {
reader.abort();
ended(host, String::new(), false);
return Outcome::Refused(format!("the relay at {} proved no key at `_info`: nothing to trust", opts.url));
}
};
if let Err(why) = relay_proved(&trusted, &service, &asked, &me, key.as_deref(), key_proof.as_deref()) {
reader.abort();
ended(host, String::new(), false);
tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
return Outcome::Refused(why);
}
let code = host_nonce.as_deref().map(|h| pairing_code(&trusted, &me, &node_nonce, h));
*inner.code.lock().unwrap() = code.clone();
if pinned.is_none() && code.is_none() {
reader.abort();
ended(host, String::new(), false);
let why = format!("no_pairing_code: {} answered `_info` with no `host_nonce`, so first contact has no pairing code to compare: refused (a host trusted by `--trust`, or pinned already, is reached without one)", opts.url);
tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
return Outcome::Refused(why);
}
if pinned.is_none() {
let f = first.as_ref().expect("first contact is asked only with a known-hosts file");
let shown = FirstContact { url: opts.url.clone(), key: trusted.clone(), fingerprint: key_fingerprint(&trusted).unwrap_or_default(), code: code.clone() };
let yes = match &f.ask {
Some(ask) => ask(shown).await,
None => false,
};
if !yes {
reader.abort();
ended(host, String::new(), false);
return Outcome::Refused(format!("first contact refused: the key {trusted} of {} was not accepted", opts.url));
}
if let Err(why) = f.hosts.add(&opts.url, &trusted) {
reader.abort();
ended(host, String::new(), false);
return Outcome::Refused(format!("first contact: the known hosts: {why}"));
}
tracing::warn!(target: "plexus::audit", url = %opts.url, key = %trusted, "first contact: the host's key pinned in the known hosts");
}
let _ = conn.ns.set(service.clone());
let _ = conn.peer_key.set(trusted.clone());
let own = crate::plexus::peer_token::PeerKey::from_seed(signer.to_bytes());
let serving = super::host::ServeChild { peer: ChildPeer::connection(trusted.clone(), [trusted.clone()]), key: Some(own), tokens: None };
host = Some(tokio::spawn(super::host::serve(activation.clone(), host_r, host_w, serving)));
proven.store(true, Ordering::Release);
let ns = activation.namespace().to_string();
let schema_hash = activation.plugin_schema().hash;
let mut params = json!({ "namespace": ns, "activations": [ns], "schema_hash": schema_hash, "schema": null });
if let Some(m) = &opts.mount {
params["mount"] = json!(m);
}
if let Some(h) = &host_nonce {
let mount = opts.mount.clone().unwrap_or_else(|| ns.clone());
let input = super::dial_in::possession_input(&trusted, &me, &node_nonce, h, &service, &mount);
params["pairing_nonce"] = json!(node_nonce);
params["possession"] = json!(base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, signer.sign(input.as_bytes()).to_bytes()));
}
drop(signer);
let _ = out.send(serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": OFFER_ID, "method": format!("{service}.offer"), "params": params })).unwrap_or_default());
let mut wait = opts.timeout * 2;
let answer = loop {
match tokio::time::timeout(wait, offer_rx.recv()).await {
Ok(Some(a)) if a.get("method").is_some() => {
inner.pending.store(true, Ordering::Release);
tracing::warn!(target: "plexus::dial", url = %opts.url, code = ?code, "the host holds the offer pending its operator");
wait = *inner.pending_for.lock().unwrap();
}
Ok(Some(a)) => break a,
Ok(None) => {
inner.pending.store(false, Ordering::Release);
let why = reader.await.unwrap_or_else(|_| "the socket".into());
return ended(host, format!("before the offer was answered: {why}"), false);
}
Err(_) => {
inner.pending.store(false, Ordering::Release);
reader.abort();
return ended(host, format!("the offer was not answered in {wait:?}"), false);
}
}
};
inner.pending.store(false, Ordering::Release);
if let Some(e) = answer.get("error") {
reader.abort();
ended(host, String::new(), false);
let kind = e.pointer("/data/error_kind").and_then(Value::as_str).unwrap_or("refused");
let message = e.get("message").and_then(Value::as_str).unwrap_or("");
return Outcome::Refused(format!("{kind}: {message}"));
}
let result = answer.get("result").cloned().unwrap_or(Value::Null);
let mount = result.get("mount").and_then(Value::as_str).unwrap_or(&ns).to_string();
let path = result.get("path").and_then(Value::as_str).unwrap_or(&mount).to_string();
let relay = result.pointer("/service/principal").and_then(Value::as_str).unwrap_or("").to_string();
if relay != trusted {
reader.abort();
ended(host, String::new(), false);
let why = format!("the relay proved {trusted} but names {} as the service acting: refused, as another key is", if relay.is_empty() { "no principal" } else { &relay });
tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
return Outcome::Refused(why);
}
*inner.live.lock().unwrap() = Some(Live { conn: Arc::clone(&conn), service: service.clone() });
let insecure = is_insecure_ws(&opts.url);
if insecure {
tracing::warn!(target: "plexus::dial", url = %opts.url, "insecure: dialed out over plain ws:// beyond loopback (transport.insecure_ws); the key proof and every hop cross in clear");
}
tracing::info!(target: "plexus::dial", url = %opts.url, %path, %relay, insecure, "mounted at the relay");
inner.state.send_replace(DialState::Mounted { mount, path, service, relay, insecure });
let why = reader.await.unwrap_or_else(|_| "the socket".into());
ended(host, why, true)
}
fn host_request_out(line: Vec<u8>) -> Vec<u8> {
let Ok(mut v) = serde_json::from_slice::<Value>(&line) else { return line };
let is_host = v.get("method").and_then(Value::as_str).is_some_and(|m| m == HOST_CALL || m == HOST_CALL_UNSUB);
match (is_host, v.get("id").and_then(Value::as_u64)) {
(true, Some(n)) => {
v["id"] = json!(format!("h:{n}"));
serde_json::to_vec(&v).unwrap_or(line)
}
_ => line,
}
}
fn host_answer_in(mut v: Value) -> Vec<u8> {
if let Some(n) = v.get("id").and_then(Value::as_str).and_then(|i| i.strip_prefix("h:")).and_then(|n| n.parse::<u64>().ok()) {
v["id"] = json!(n);
}
serde_json::to_vec(&v).unwrap_or_default()
}
fn trusted_key(trust: Option<&str>) -> Result<String, String> {
let Some(t) = trust else {
return Err("no trusted key: a dial-out names its relay by key (`DialOut::trust`, `key:<64 hex>`), which the relay proves at each connect; without one nothing it sends could be believed".into());
};
match crate::plexus::peer_token::key_of(t) {
Some(_) => Ok(t.to_string()),
None => Err(format!("the trusted relay `{t}` is not a key (`key:<64 hex>`): a relay is named by the key it proves")),
}
}
fn relay_proved(trusted: &str, backend: &str, nonce: &str, me: &str, key: Option<&str>, proof: Option<&str>) -> Result<(), String> {
let Some(key) = key else {
return Err(format!("the relay proved no key at `_info` (trusted: {trusted})"));
};
if key != trusted {
return Err(format!("the relay proved another key ({key}) than the one trusted ({trusted})"));
}
crate::plexus::peer_token::check_key_proof_for(key, proof.unwrap_or_default(), nonce, backend, me)
.map(|_| ())
.map_err(|e| format!("the relay's `_info` names the key {key} without proving it: {e}"))
}
pub fn key_principal(path: &std::path::Path) -> Result<String, String> {
read_seed(path).map(|k| principal_of(&k))
}