1use std::path::PathBuf;
31use std::sync::atomic::{AtomicBool, Ordering};
32use std::sync::{Arc, Mutex};
33use std::time::Duration;
34
35use futures::future::BoxFuture;
36use futures::{SinkExt, StreamExt};
37use serde::Serialize;
38use serde_json::{json, Value};
39use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
40use tokio::sync::{mpsc, watch};
41use tokio_tungstenite::tungstenite::client::IntoClientRequest;
42use tokio_tungstenite::tungstenite::http::{header::AUTHORIZATION, HeaderValue};
43use tokio_tungstenite::tungstenite::Message;
44
45use super::host::ChildPeer;
46use super::link::{unavailable, Conn, Counters, SubKey};
47use super::pairing::{commitment, key_fingerprint, pairing_code, KnownHosts};
48use super::spec::{check_ws_url, is_insecure_ws, INSECURE_TRANSPORT};
49use super::upcall::{HOST_CALL, HOST_CALL_UNSUB};
50use super::ws::{key_proof, principal_of, read_seed};
51use ed25519_dalek::Signer;
52use super::Backoff;
53use crate::plexus::plexus::Activation;
54use crate::plexus::streaming::PlexusStream;
55use crate::plexus::types::PlexusStreamItem;
56
57#[derive(Debug, Clone)]
60pub struct DialOut {
61 pub url: String,
63 pub key: PathBuf,
66 pub agent: String,
68 pub mount: Option<String>,
71 pub trust: Option<String>,
78 pub backoff: Backoff,
80 pub timeout: Duration,
82 pub insecure_ws: bool,
87 pub tls_roots: Option<PathBuf>,
91}
92
93impl DialOut {
94 pub fn new(url: impl Into<String>, key: impl Into<PathBuf>) -> Self {
96 Self {
97 url: url.into(),
98 key: key.into(),
99 agent: "plexus-service".into(),
100 mount: None,
101 trust: None,
102 backoff: Backoff { initial: Duration::from_millis(250), max: Duration::from_secs(10), per_minute: usize::MAX },
103 timeout: Duration::from_secs(10),
104 insecure_ws: false,
105 tls_roots: None,
106 }
107 }
108
109 pub fn mount(mut self, name: impl Into<String>) -> Self {
111 self.mount = Some(name.into());
112 self
113 }
114
115 pub fn trust(mut self, principal: impl Into<String>) -> Self {
118 self.trust = Some(principal.into());
119 self
120 }
121
122 pub fn agent(mut self, agent: impl Into<String>) -> Self {
124 self.agent = agent.into();
125 self
126 }
127
128 pub fn insecure_ws(mut self, on: bool) -> Self {
130 self.insecure_ws = on;
131 self
132 }
133
134 pub fn tls_roots(mut self, roots: impl Into<PathBuf>) -> Self {
137 self.tls_roots = Some(roots.into());
138 self
139 }
140
141 #[cfg(not(target_arch = "wasm32"))]
145 pub fn configured(mut self, c: &crate::plexus::config::Config) -> Self {
146 use crate::plexus::config::{settings::{TRANSPORT_INSECURE_WS, TRANSPORT_TLS_ROOTS}, Source};
147 if c.source(&TRANSPORT_INSECURE_WS) != Source::Default {
148 self.insecure_ws = c.get(&TRANSPORT_INSECURE_WS);
149 }
150 if c.source(&TRANSPORT_TLS_ROOTS) != Source::Default {
151 self.tls_roots = c.get(&TRANSPORT_TLS_ROOTS).map(Into::into);
152 }
153 self
154 }
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
159#[serde(tag = "state", rename_all = "snake_case")]
160pub enum DialState {
161 Connecting,
163 Mounted {
167 mount: String,
168 path: String,
169 service: String,
170 relay: String,
171 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
172 insecure: bool,
173 },
174 Down { why: String },
176 Refused { why: String },
178 Stopped,
180}
181
182struct Live {
183 conn: Arc<Conn>,
184 service: String,
185}
186
187#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct FirstContact {
192 pub url: String,
193 pub key: String,
195 pub fingerprint: String,
197 pub code: Option<String>,
199}
200
201type Ask = Arc<dyn Fn(FirstContact) -> BoxFuture<'static, bool> + Send + Sync>;
202
203#[derive(Clone)]
204struct First {
205 hosts: KnownHosts,
206 ask: Option<Ask>,
207}
208
209struct ExposedInner {
210 opts: DialOut,
211 live: Mutex<Option<Live>>,
212 state: watch::Sender<DialState>,
213 task: Mutex<Option<tokio::task::AbortHandle>>,
214 counters: Arc<Counters>,
215 first: Mutex<Option<First>>,
217 code: Mutex<Option<String>>,
220 pending: AtomicBool,
221 pending_for: Mutex<Duration>,
222}
223
224impl Drop for ExposedInner {
225 fn drop(&mut self) {
226 if let Some(t) = self.task.lock().unwrap().take() {
227 t.abort();
228 }
229 }
230}
231
232#[derive(Clone)]
236pub struct Exposed {
237 inner: Arc<ExposedInner>,
238}
239
240impl std::fmt::Debug for Exposed {
241 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242 f.debug_struct("Exposed").field("url", &self.inner.opts.url).field("state", &self.state()).finish()
243 }
244}
245
246impl Exposed {
247 pub fn new(opts: DialOut) -> Self {
250 Self {
251 inner: Arc::new(ExposedInner {
252 opts,
253 live: Mutex::new(None),
254 state: watch::channel(DialState::Connecting).0,
255 task: Mutex::new(None),
256 counters: Arc::new(Counters::default()),
257 first: Mutex::new(None),
258 code: Mutex::new(None),
259 pending: AtomicBool::new(false),
260 pending_for: Mutex::new(Duration::from_secs(600)),
261 }),
262 }
263 }
264
265 pub fn with_first_contact<F, Fut>(self, known_hosts: impl Into<PathBuf>, ask: F) -> Self
273 where
274 F: Fn(FirstContact) -> Fut + Send + Sync + 'static,
275 Fut: std::future::Future<Output = bool> + Send + 'static,
276 {
277 let ask: Ask = Arc::new(move |c| Box::pin(ask(c)));
278 *self.inner.first.lock().unwrap() = Some(First { hosts: KnownHosts::new(known_hosts), ask: Some(ask) });
279 self
280 }
281
282 pub fn with_known_hosts(self, known_hosts: impl Into<PathBuf>) -> Self {
285 *self.inner.first.lock().unwrap() = Some(First { hosts: KnownHosts::new(known_hosts), ask: None });
286 self
287 }
288
289 pub fn with_pending_for(self, wait: Duration) -> Self {
292 *self.inner.pending_for.lock().unwrap() = wait;
293 self
294 }
295
296 pub fn pending(&self) -> Option<String> {
299 self.inner.pending.load(Ordering::Acquire).then(|| self.code()).flatten()
300 }
301
302 pub fn code(&self) -> Option<String> {
304 self.inner.code.lock().unwrap().clone()
305 }
306
307 pub fn options(&self) -> &DialOut {
309 &self.inner.opts
310 }
311
312 pub fn principal(&self) -> Result<String, String> {
315 read_seed(&self.inner.opts.key).map(|k| principal_of(&k))
316 }
317
318 pub fn state(&self) -> DialState {
320 self.inner.state.borrow().clone()
321 }
322
323 pub fn watch(&self) -> watch::Receiver<DialState> {
325 self.inner.state.subscribe()
326 }
327
328 pub async fn mounted(&self, timeout: Duration) -> Result<String, String> {
330 let mut rx = self.watch();
331 let settled = tokio::time::timeout(timeout, async {
332 rx.wait_for(|s| matches!(s, DialState::Mounted { .. } | DialState::Refused { .. } | DialState::Stopped)).await.map(|s| s.clone())
333 })
334 .await;
335 match settled {
336 Ok(Ok(DialState::Mounted { path, .. })) => Ok(path),
337 Ok(Ok(other)) => Err(format!("{other:?}")),
338 Ok(Err(_)) => Err("stopped".into()),
339 Err(_) => Err(format!("not mounted in {timeout:?} ({:?})", self.state())),
340 }
341 }
342
343 pub fn serve<A: Activation + Clone>(&self, activation: A) {
346 let weak = Arc::downgrade(&self.inner);
347 let task = tokio::spawn(async move {
348 let mut failures = 0usize;
349 loop {
350 let Some(inner) = weak.upgrade() else { return };
351 inner.state.send_replace(DialState::Connecting);
352 let outcome = session(&inner, activation.clone()).await;
353 inner.live.lock().unwrap().take();
354 let backoff = inner.opts.backoff;
355 match outcome {
356 Outcome::Refused(why) => {
357 tracing::warn!(target: "plexus::dial", url = %inner.opts.url, "the offer was refused: {why}");
358 inner.state.send_replace(DialState::Refused { why });
359 return;
360 }
361 Outcome::Dropped { why, was_mounted } => {
362 tracing::warn!(target: "plexus::dial", url = %inner.opts.url, "{why}; dialing again");
363 inner.state.send_replace(DialState::Down { why });
364 failures = if was_mounted { 0 } else { failures + 1 };
365 }
366 }
367 drop(inner);
368 tokio::time::sleep(backoff.delay(failures)).await;
369 }
370 });
371 if let Some(old) = self.inner.task.lock().unwrap().replace(task.abort_handle()) {
372 old.abort();
373 }
374 }
375
376 pub fn stop(&self) {
378 if let Some(t) = self.inner.task.lock().unwrap().take() {
379 t.abort();
380 }
381 if let Some(live) = self.inner.live.lock().unwrap().take() {
382 live.conn.shutdown.notify_one();
383 }
384 self.inner.state.send_replace(DialState::Stopped);
385 }
386
387 pub async fn call(&self, method: &str, params: Value) -> PlexusStream {
391 let one = |item: PlexusStreamItem| -> PlexusStream { Box::pin(futures::stream::iter([item])) };
392 let live = self.inner.live.lock().unwrap().as_ref().map(|l| (Arc::clone(&l.conn), l.service.clone()));
393 let Some((conn, service)) = live else {
394 return one(unavailable("relay", &format!("not connected to {} ({:?})", self.inner.opts.url, self.state())));
395 };
396 match conn.open(&format!("{service}.call"), json!({ "method": method, "params": params }), self.inner.opts.timeout, None).await {
397 Ok((sid, rx)) => Box::pin(Items { rx, sid, conn, over: false }),
398 Err(item) => one(item),
399 }
400 }
401}
402
403struct Items {
405 rx: mpsc::Receiver<PlexusStreamItem>,
406 sid: SubKey,
407 conn: Arc<Conn>,
408 over: bool,
409}
410
411impl futures::Stream for Items {
412 type Item = PlexusStreamItem;
413
414 fn poll_next(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<PlexusStreamItem>> {
415 if self.over {
416 return std::task::Poll::Ready(None);
417 }
418 match self.rx.poll_recv(cx) {
419 std::task::Poll::Ready(Some(item)) => {
420 self.over = matches!(item, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
421 std::task::Poll::Ready(Some(item))
422 }
423 std::task::Poll::Ready(None) => {
424 self.over = true;
425 std::task::Poll::Ready(Some(unavailable("relay", "the connection closed")))
426 }
427 std::task::Poll::Pending => std::task::Poll::Pending,
428 }
429 }
430}
431
432impl Drop for Items {
433 fn drop(&mut self) {
434 if !self.over {
435 self.conn.unsubscribe(&self.sid);
436 }
437 }
438}
439
440enum Outcome {
441 Refused(String),
442 Dropped { why: String, was_mounted: bool },
443}
444
445fn nonce() -> [u8; 32] {
446 let mut n = [0u8; 32];
447 n[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
448 n[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
449 n
450}
451
452const OFFER_ID: &str = "offer";
455
456async fn session<A: Activation + Clone>(inner: &Arc<ExposedInner>, activation: A) -> Outcome {
458 let opts = &inner.opts;
459 let dropped = |why: String| Outcome::Dropped { why, was_mounted: false };
460 if let Err(why) = check_ws_url(&opts.url, opts.insecure_ws) {
463 return Outcome::Refused(format!("{INSECURE_TRANSPORT}: {why}"));
464 }
465 let first = inner.first.lock().unwrap().clone();
470 let pinned: Option<String> = match (&opts.trust, &first) {
471 (Some(_), _) | (None, None) => match trusted_key(opts.trust.as_deref()) {
472 Ok(k) => Some(k),
473 Err(why) => return Outcome::Refused(why),
474 },
475 (None, Some(f)) => match f.hosts.get(&opts.url) {
476 Ok(Some(k)) => Some(k),
477 Ok(None) if f.ask.is_some() => None,
478 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())),
479 Err(why) => return Outcome::Refused(format!("the known hosts: {why}")),
480 },
481 };
482 if opts.url.starts_with("wss://") && !cfg!(feature = "child-wss") {
483 return Outcome::Refused("a wss:// relay needs plexus-core's `child-wss` feature (TLS)".into());
484 }
485 let mut req = match opts.url.as_str().into_client_request() {
486 Ok(r) => r,
487 Err(e) => return Outcome::Refused(format!("`{}`: {e}", opts.url)),
488 };
489 let signer = match read_seed(&opts.key) {
490 Ok(k) => k,
491 Err(e) => return Outcome::Refused(e),
492 };
493 let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
494 let proof = key_proof(&signer, super::ws::LOGIN_CONTEXT, opts.url.trim_end_matches('/'), &opts.agent, &nonce(), ts);
496 let me = principal_of(&signer);
499 match HeaderValue::from_str(&format!("Bearer {proof}")) {
500 Ok(v) => req.headers_mut().insert(AUTHORIZATION, v),
501 Err(e) => return Outcome::Refused(e.to_string()),
502 };
503 #[cfg(feature = "child-wss")]
506 let connecting = {
507 let tls = match opts.url.starts_with("wss://") {
508 true => match super::ws::tls_config(opts.tls_roots.as_deref()) {
509 Ok(c) => Some(tokio_tungstenite::Connector::Rustls(c)),
510 Err(why) => return Outcome::Refused(why),
511 },
512 false => None,
513 };
514 tokio_tungstenite::connect_async_tls_with_config(req, None, true, tls)
516 };
517 #[cfg(not(feature = "child-wss"))]
518 let connecting = tokio_tungstenite::connect_async_with_config(req, None, true);
519 let socket = match tokio::time::timeout(opts.timeout, connecting).await {
520 Err(_) => return dropped(format!("dialing {}: no answer to the upgrade in {:?}", opts.url, opts.timeout)),
521 Ok(Ok((s, _))) => s,
522 Ok(Err(tokio_tungstenite::tungstenite::Error::Http(resp))) => return dropped(format!("the upgrade to {} was refused: HTTP {}", opts.url, resp.status())),
523 Ok(Err(e)) => return dropped(format!("dialing {}: {e}", opts.url)),
524 };
525 let (mut sink, mut stream) = socket.split();
526
527 let (out, mut out_rx) = mpsc::unbounded_channel::<Vec<u8>>();
529 let conn = Conn::new("relay", None, out.clone(), 64, Arc::clone(&inner.counters));
530 let (mut host_in, host_r) = tokio::io::duplex(1 << 16);
533 let (host_w, host_out) = tokio::io::duplex(1 << 16);
534 let proven = Arc::new(AtomicBool::new(false));
535 let mut host: Option<tokio::task::JoinHandle<std::io::Result<()>>> = None;
536
537 let out_host = out.clone();
539 let host_lines = tokio::spawn(async move {
540 let mut lines = BufReader::new(host_out).lines();
541 while let Ok(Some(l)) = lines.next_line().await {
542 if out_host.send(host_request_out(l.into_bytes())).is_err() {
545 break;
546 }
547 }
548 });
549 let shutdown = Arc::clone(&conn);
550 let writer = tokio::spawn(async move {
551 loop {
552 tokio::select! {
553 first = out_rx.recv() => {
554 let Some(first) = first else { break };
555 let mut ok = sink.feed(Message::text(String::from_utf8_lossy(&first).into_owned())).await.is_ok();
556 while let (true, Ok(more)) = (ok, out_rx.try_recv()) {
557 ok = sink.feed(Message::text(String::from_utf8_lossy(&more).into_owned())).await.is_ok();
558 }
559 if !ok || sink.flush().await.is_err() {
560 break;
561 }
562 }
563 _ = shutdown.shutdown.notified() => {
564 let _ = sink.close().await;
565 break;
566 }
567 }
568 }
569 });
570
571 let (offer_tx, mut offer_rx) = mpsc::unbounded_channel::<Value>();
574 let reader_conn = Arc::clone(&conn);
575 let (reader_proven, refuse_out) = (Arc::clone(&proven), out.clone());
576 let reader = tokio::spawn(async move {
577 let why = loop {
578 let text = match stream.next().await {
579 Some(Ok(Message::Text(t))) => t.as_bytes().to_vec(),
580 Some(Ok(Message::Binary(b))) => b.to_vec(),
581 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())),
582 Some(Ok(_)) => continue,
583 Some(Err(e)) => break format!("the socket: {e}"),
584 None => break "the relay closed the socket".to_string(),
585 };
586 let shape: Value = match serde_json::from_slice(&text) {
587 Ok(v) => v,
588 Err(_) => continue,
589 };
590 let (method, id) = (shape.get("method"), shape.get("id"));
591 let method_is = |m: &str| method.and_then(Value::as_str) == Some(m);
592 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:")));
594 if to_host {
595 if !reader_proven.load(Ordering::Acquire) {
596 continue;
597 }
598 let mut line = host_answer_in(shape);
599 line.push(b'\n');
600 if host_in.write_all(&line).await.is_err() {
601 break "the host stopped".to_string();
602 }
603 } else if method_is(super::dial_in::OFFER_PENDING) && id.is_none() {
604 let _ = offer_tx.send(shape);
605 } else if method.is_some() && id.is_some() {
606 if !reader_proven.load(Ordering::Acquire) {
609 let refusal = json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "the relay has not proved its key", "data": { "error_kind": "forbidden" } } });
610 let _ = refuse_out.send(serde_json::to_vec(&refusal).unwrap_or_default());
611 continue;
612 }
613 let mut line = text;
614 line.push(b'\n');
615 if host_in.write_all(&line).await.is_err() {
616 break "the host stopped".to_string();
617 }
618 } else if method.is_none() && id.and_then(Value::as_str) == Some(OFFER_ID) {
619 let _ = offer_tx.send(shape);
620 } else {
621 reader_conn.on_message(&text).await;
622 }
623 };
624 reader_conn.on_gone(&why);
625 reader_conn.shutdown.notify_one();
626 why
627 });
628
629 let ended = |host: Option<tokio::task::JoinHandle<std::io::Result<()>>>, why: String, was_mounted: bool| {
630 if let Some(h) = host {
631 h.abort();
632 }
633 host_lines.abort();
634 writer.abort();
635 Outcome::Dropped { why, was_mounted }
636 };
637
638 let asked = crate::plexus::peer_token::random_nonce();
641 let node_nonce = crate::plexus::peer_token::random_nonce();
644 let info = async {
645 let (_, mut rx) = conn.open("_info", json!({ "nonce": asked, "commit": commitment(&node_nonce) }), opts.timeout, None).await.map_err(|e| format!("{e:?}"))?;
646 while let Some(item) = rx.recv().await {
647 if let PlexusStreamItem::Data { content, .. } = item {
648 let content = content.into_value();
649 if let Some(b) = content.get("backend").and_then(Value::as_str) {
650 let field = |k: &str| content.get(k).and_then(Value::as_str).map(str::to_string);
651 return Ok((b.to_string(), field("key"), field("proof"), field("host_nonce")));
652 }
653 }
654 }
655 Err::<_, String>("its `_info` names no backend".into())
656 };
657 let (service, key, key_proof, host_nonce) = match tokio::time::timeout(opts.timeout, info).await {
658 Ok(Ok(s)) => s,
659 Ok(Err(why)) => {
660 reader.abort();
661 return ended(host, format!("asking the relay's `_info`: {why}"), false);
662 }
663 Err(_) => {
664 reader.abort();
665 return ended(host, format!("the relay did not answer `_info` in {:?}", opts.timeout), false);
666 }
667 };
668 let from_file = opts.trust.is_none() && pinned.is_some();
671 if let (true, Some(p), Some(k)) = (from_file, &pinned, &key) {
672 if p != k {
673 reader.abort();
674 ended(host, String::new(), false);
675 let file = first.as_ref().map(|f| f.hosts.path().display().to_string()).unwrap_or_default();
676 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());
677 tracing::error!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
678 return Outcome::Refused(why);
679 }
680 }
681 let trusted = match pinned.clone().or_else(|| key.clone()) {
683 Some(t) => t,
684 None => {
685 reader.abort();
686 ended(host, String::new(), false);
687 return Outcome::Refused(format!("the relay at {} proved no key at `_info`: nothing to trust", opts.url));
688 }
689 };
690 if let Err(why) = relay_proved(&trusted, &service, &asked, &me, key.as_deref(), key_proof.as_deref()) {
691 reader.abort();
692 ended(host, String::new(), false);
693 tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
694 return Outcome::Refused(why);
695 }
696 let code = host_nonce.as_deref().map(|h| pairing_code(&trusted, &me, &node_nonce, h));
697 *inner.code.lock().unwrap() = code.clone();
698 if pinned.is_none() && code.is_none() {
703 reader.abort();
704 ended(host, String::new(), false);
705 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);
706 tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
707 return Outcome::Refused(why);
708 }
709 if pinned.is_none() {
710 let f = first.as_ref().expect("first contact is asked only with a known-hosts file");
712 let shown = FirstContact { url: opts.url.clone(), key: trusted.clone(), fingerprint: key_fingerprint(&trusted).unwrap_or_default(), code: code.clone() };
713 let yes = match &f.ask {
714 Some(ask) => ask(shown).await,
715 None => false,
716 };
717 if !yes {
718 reader.abort();
719 ended(host, String::new(), false);
720 return Outcome::Refused(format!("first contact refused: the key {trusted} of {} was not accepted", opts.url));
721 }
722 if let Err(why) = f.hosts.add(&opts.url, &trusted) {
723 reader.abort();
724 ended(host, String::new(), false);
725 return Outcome::Refused(format!("first contact: the known hosts: {why}"));
726 }
727 tracing::warn!(target: "plexus::audit", url = %opts.url, key = %trusted, "first contact: the host's key pinned in the known hosts");
728 }
729 let _ = conn.ns.set(service.clone());
730 let _ = conn.peer_key.set(trusted.clone());
731 let own = crate::plexus::peer_token::PeerKey::from_seed(signer.to_bytes());
734 let serving = super::host::ServeChild { peer: ChildPeer::connection(trusted.clone(), [trusted.clone()]), key: Some(own), tokens: None };
735 host = Some(tokio::spawn(super::host::serve(activation.clone(), host_r, host_w, serving)));
736 proven.store(true, Ordering::Release);
737
738 let ns = activation.namespace().to_string();
740 let schema_hash = activation.plugin_schema().hash;
741 let mut params = json!({ "namespace": ns, "activations": [ns], "schema_hash": schema_hash, "schema": null });
742 if let Some(m) = &opts.mount {
743 params["mount"] = json!(m);
744 }
745 if let Some(h) = &host_nonce {
748 let mount = opts.mount.clone().unwrap_or_else(|| ns.clone());
749 let input = super::dial_in::possession_input(&trusted, &me, &node_nonce, h, &service, &mount);
750 params["pairing_nonce"] = json!(node_nonce);
751 params["possession"] = json!(base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, signer.sign(input.as_bytes()).to_bytes()));
752 }
753 drop(signer);
754 let _ = out.send(serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": OFFER_ID, "method": format!("{service}.offer"), "params": params })).unwrap_or_default());
755 let mut wait = opts.timeout * 2;
756 let answer = loop {
757 match tokio::time::timeout(wait, offer_rx.recv()).await {
758 Ok(Some(a)) if a.get("method").is_some() => {
759 inner.pending.store(true, Ordering::Release);
761 tracing::warn!(target: "plexus::dial", url = %opts.url, code = ?code, "the host holds the offer pending its operator");
762 wait = *inner.pending_for.lock().unwrap();
763 }
764 Ok(Some(a)) => break a,
765 Ok(None) => {
766 inner.pending.store(false, Ordering::Release);
767 let why = reader.await.unwrap_or_else(|_| "the socket".into());
768 return ended(host, format!("before the offer was answered: {why}"), false);
769 }
770 Err(_) => {
771 inner.pending.store(false, Ordering::Release);
772 reader.abort();
773 return ended(host, format!("the offer was not answered in {wait:?}"), false);
774 }
775 }
776 };
777 inner.pending.store(false, Ordering::Release);
778 if let Some(e) = answer.get("error") {
779 reader.abort();
780 ended(host, String::new(), false);
781 let kind = e.pointer("/data/error_kind").and_then(Value::as_str).unwrap_or("refused");
782 let message = e.get("message").and_then(Value::as_str).unwrap_or("");
783 return Outcome::Refused(format!("{kind}: {message}"));
784 }
785 let result = answer.get("result").cloned().unwrap_or(Value::Null);
786 let mount = result.get("mount").and_then(Value::as_str).unwrap_or(&ns).to_string();
787 let path = result.get("path").and_then(Value::as_str).unwrap_or(&mount).to_string();
788 let relay = result.pointer("/service/principal").and_then(Value::as_str).unwrap_or("").to_string();
789 if relay != trusted {
792 reader.abort();
793 ended(host, String::new(), false);
794 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 });
795 tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
796 return Outcome::Refused(why);
797 }
798 *inner.live.lock().unwrap() = Some(Live { conn: Arc::clone(&conn), service: service.clone() });
799 let insecure = is_insecure_ws(&opts.url);
800 if insecure {
801 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");
802 }
803 tracing::info!(target: "plexus::dial", url = %opts.url, %path, %relay, insecure, "mounted at the relay");
804 inner.state.send_replace(DialState::Mounted { mount, path, service, relay, insecure });
805
806 let why = reader.await.unwrap_or_else(|_| "the socket".into());
807 ended(host, why, true)
808}
809
810fn host_request_out(line: Vec<u8>) -> Vec<u8> {
813 let Ok(mut v) = serde_json::from_slice::<Value>(&line) else { return line };
814 let is_host = v.get("method").and_then(Value::as_str).is_some_and(|m| m == HOST_CALL || m == HOST_CALL_UNSUB);
815 match (is_host, v.get("id").and_then(Value::as_u64)) {
816 (true, Some(n)) => {
817 v["id"] = json!(format!("h:{n}"));
818 serde_json::to_vec(&v).unwrap_or(line)
819 }
820 _ => line,
821 }
822}
823
824fn host_answer_in(mut v: Value) -> Vec<u8> {
827 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()) {
828 v["id"] = json!(n);
829 }
830 serde_json::to_vec(&v).unwrap_or_default()
831}
832
833fn trusted_key(trust: Option<&str>) -> Result<String, String> {
836 let Some(t) = trust else {
837 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());
838 };
839 match crate::plexus::peer_token::key_of(t) {
840 Some(_) => Ok(t.to_string()),
841 None => Err(format!("the trusted relay `{t}` is not a key (`key:<64 hex>`): a relay is named by the key it proves")),
842 }
843}
844
845fn relay_proved(trusted: &str, backend: &str, nonce: &str, me: &str, key: Option<&str>, proof: Option<&str>) -> Result<(), String> {
848 let Some(key) = key else {
849 return Err(format!("the relay proved no key at `_info` (trusted: {trusted})"));
850 };
851 if key != trusted {
852 return Err(format!("the relay proved another key ({key}) than the one trusted ({trusted})"));
853 }
854 crate::plexus::peer_token::check_key_proof_for(key, proof.unwrap_or_default(), nonce, backend, me)
855 .map(|_| ())
856 .map_err(|e| format!("the relay's `_info` names the key {key} without proving it: {e}"))
857}
858
859pub fn key_principal(path: &std::path::Path) -> Result<String, String> {
862 read_seed(path).map(|k| principal_of(&k))
863}