1use std::path::PathBuf;
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::sync::{Arc, Mutex};
29use std::time::Duration;
30
31use futures::{SinkExt, StreamExt};
32use serde::Serialize;
33use serde_json::{json, Value};
34use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
35use tokio::sync::{mpsc, oneshot, watch};
36use tokio_tungstenite::tungstenite::client::IntoClientRequest;
37use tokio_tungstenite::tungstenite::http::{header::AUTHORIZATION, HeaderValue};
38use tokio_tungstenite::tungstenite::Message;
39
40use super::host::{serve_child_on, ChildPeer};
41use super::link::{unavailable, Conn, Counters, SubKey};
42use super::spec::{check_ws_url, is_insecure_ws, INSECURE_TRANSPORT};
43use super::ws::{key_proof, principal_of, read_seed};
44use super::Backoff;
45use crate::plexus::plexus::Activation;
46use crate::plexus::streaming::PlexusStream;
47use crate::plexus::types::PlexusStreamItem;
48
49#[derive(Debug, Clone)]
52pub struct DialOut {
53 pub url: String,
55 pub key: PathBuf,
58 pub agent: String,
60 pub mount: Option<String>,
63 pub trust: Option<String>,
70 pub backoff: Backoff,
72 pub timeout: Duration,
74 pub insecure_ws: bool,
79 pub tls_roots: Option<PathBuf>,
83}
84
85impl DialOut {
86 pub fn new(url: impl Into<String>, key: impl Into<PathBuf>) -> Self {
88 Self {
89 url: url.into(),
90 key: key.into(),
91 agent: "plexus-service".into(),
92 mount: None,
93 trust: None,
94 backoff: Backoff { initial: Duration::from_millis(250), max: Duration::from_secs(10), per_minute: usize::MAX },
95 timeout: Duration::from_secs(10),
96 insecure_ws: false,
97 tls_roots: None,
98 }
99 }
100
101 pub fn mount(mut self, name: impl Into<String>) -> Self {
103 self.mount = Some(name.into());
104 self
105 }
106
107 pub fn trust(mut self, principal: impl Into<String>) -> Self {
110 self.trust = Some(principal.into());
111 self
112 }
113
114 pub fn agent(mut self, agent: impl Into<String>) -> Self {
116 self.agent = agent.into();
117 self
118 }
119
120 pub fn insecure_ws(mut self, on: bool) -> Self {
122 self.insecure_ws = on;
123 self
124 }
125
126 pub fn tls_roots(mut self, roots: impl Into<PathBuf>) -> Self {
129 self.tls_roots = Some(roots.into());
130 self
131 }
132
133 #[cfg(not(target_arch = "wasm32"))]
137 pub fn configured(mut self, c: &crate::plexus::config::Config) -> Self {
138 use crate::plexus::config::{settings::{TRANSPORT_INSECURE_WS, TRANSPORT_TLS_ROOTS}, Source};
139 if c.source(&TRANSPORT_INSECURE_WS) != Source::Default {
140 self.insecure_ws = c.get(&TRANSPORT_INSECURE_WS);
141 }
142 if c.source(&TRANSPORT_TLS_ROOTS) != Source::Default {
143 self.tls_roots = c.get(&TRANSPORT_TLS_ROOTS).map(Into::into);
144 }
145 self
146 }
147}
148
149#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
151#[serde(tag = "state", rename_all = "snake_case")]
152pub enum DialState {
153 Connecting,
155 Mounted {
159 mount: String,
160 path: String,
161 service: String,
162 relay: String,
163 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
164 insecure: bool,
165 },
166 Down { why: String },
168 Refused { why: String },
170 Stopped,
172}
173
174struct Live {
175 conn: Arc<Conn>,
176 service: String,
177}
178
179struct ExposedInner {
180 opts: DialOut,
181 live: Mutex<Option<Live>>,
182 state: watch::Sender<DialState>,
183 task: Mutex<Option<tokio::task::AbortHandle>>,
184 counters: Arc<Counters>,
185}
186
187impl Drop for ExposedInner {
188 fn drop(&mut self) {
189 if let Some(t) = self.task.lock().unwrap().take() {
190 t.abort();
191 }
192 }
193}
194
195#[derive(Clone)]
199pub struct Exposed {
200 inner: Arc<ExposedInner>,
201}
202
203impl std::fmt::Debug for Exposed {
204 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205 f.debug_struct("Exposed").field("url", &self.inner.opts.url).field("state", &self.state()).finish()
206 }
207}
208
209impl Exposed {
210 pub fn new(opts: DialOut) -> Self {
213 Self {
214 inner: Arc::new(ExposedInner {
215 opts,
216 live: Mutex::new(None),
217 state: watch::channel(DialState::Connecting).0,
218 task: Mutex::new(None),
219 counters: Arc::new(Counters::default()),
220 }),
221 }
222 }
223
224 pub fn options(&self) -> &DialOut {
226 &self.inner.opts
227 }
228
229 pub fn principal(&self) -> Result<String, String> {
232 read_seed(&self.inner.opts.key).map(|k| principal_of(&k))
233 }
234
235 pub fn state(&self) -> DialState {
237 self.inner.state.borrow().clone()
238 }
239
240 pub fn watch(&self) -> watch::Receiver<DialState> {
242 self.inner.state.subscribe()
243 }
244
245 pub async fn mounted(&self, timeout: Duration) -> Result<String, String> {
247 let mut rx = self.watch();
248 let settled = tokio::time::timeout(timeout, async {
249 rx.wait_for(|s| matches!(s, DialState::Mounted { .. } | DialState::Refused { .. } | DialState::Stopped)).await.map(|s| s.clone())
250 })
251 .await;
252 match settled {
253 Ok(Ok(DialState::Mounted { path, .. })) => Ok(path),
254 Ok(Ok(other)) => Err(format!("{other:?}")),
255 Ok(Err(_)) => Err("stopped".into()),
256 Err(_) => Err(format!("not mounted in {timeout:?} ({:?})", self.state())),
257 }
258 }
259
260 pub fn serve<A: Activation + Clone>(&self, activation: A) {
263 let weak = Arc::downgrade(&self.inner);
264 let task = tokio::spawn(async move {
265 let mut failures = 0usize;
266 loop {
267 let Some(inner) = weak.upgrade() else { return };
268 inner.state.send_replace(DialState::Connecting);
269 let outcome = session(&inner, activation.clone()).await;
270 inner.live.lock().unwrap().take();
271 let backoff = inner.opts.backoff;
272 match outcome {
273 Outcome::Refused(why) => {
274 tracing::warn!(target: "plexus::dial", url = %inner.opts.url, "the offer was refused: {why}");
275 inner.state.send_replace(DialState::Refused { why });
276 return;
277 }
278 Outcome::Dropped { why, was_mounted } => {
279 tracing::warn!(target: "plexus::dial", url = %inner.opts.url, "{why}; dialing again");
280 inner.state.send_replace(DialState::Down { why });
281 failures = if was_mounted { 0 } else { failures + 1 };
282 }
283 }
284 drop(inner);
285 tokio::time::sleep(backoff.delay(failures)).await;
286 }
287 });
288 if let Some(old) = self.inner.task.lock().unwrap().replace(task.abort_handle()) {
289 old.abort();
290 }
291 }
292
293 pub fn stop(&self) {
295 if let Some(t) = self.inner.task.lock().unwrap().take() {
296 t.abort();
297 }
298 if let Some(live) = self.inner.live.lock().unwrap().take() {
299 live.conn.shutdown.notify_one();
300 }
301 self.inner.state.send_replace(DialState::Stopped);
302 }
303
304 pub async fn call(&self, method: &str, params: Value) -> PlexusStream {
308 let one = |item: PlexusStreamItem| -> PlexusStream { Box::pin(futures::stream::iter([item])) };
309 let live = self.inner.live.lock().unwrap().as_ref().map(|l| (Arc::clone(&l.conn), l.service.clone()));
310 let Some((conn, service)) = live else {
311 return one(unavailable("relay", &format!("not connected to {} ({:?})", self.inner.opts.url, self.state())));
312 };
313 match conn.open(&format!("{service}.call"), json!({ "method": method, "params": params }), self.inner.opts.timeout).await {
314 Ok((sid, rx)) => Box::pin(Items { rx, sid, conn, over: false }),
315 Err(item) => one(item),
316 }
317 }
318}
319
320struct Items {
322 rx: mpsc::Receiver<PlexusStreamItem>,
323 sid: SubKey,
324 conn: Arc<Conn>,
325 over: bool,
326}
327
328impl futures::Stream for Items {
329 type Item = PlexusStreamItem;
330
331 fn poll_next(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<PlexusStreamItem>> {
332 if self.over {
333 return std::task::Poll::Ready(None);
334 }
335 match self.rx.poll_recv(cx) {
336 std::task::Poll::Ready(Some(item)) => {
337 self.over = matches!(item, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
338 std::task::Poll::Ready(Some(item))
339 }
340 std::task::Poll::Ready(None) => {
341 self.over = true;
342 std::task::Poll::Ready(Some(unavailable("relay", "the connection closed")))
343 }
344 std::task::Poll::Pending => std::task::Poll::Pending,
345 }
346 }
347}
348
349impl Drop for Items {
350 fn drop(&mut self) {
351 if !self.over {
352 self.conn.unsubscribe(&self.sid);
353 }
354 }
355}
356
357enum Outcome {
358 Refused(String),
359 Dropped { why: String, was_mounted: bool },
360}
361
362fn nonce() -> [u8; 32] {
363 let mut n = [0u8; 32];
364 n[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
365 n[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
366 n
367}
368
369const OFFER_ID: &str = "offer";
372
373async fn session<A: Activation + Clone>(inner: &Arc<ExposedInner>, activation: A) -> Outcome {
375 let opts = &inner.opts;
376 let dropped = |why: String| Outcome::Dropped { why, was_mounted: false };
377 if let Err(why) = check_ws_url(&opts.url, opts.insecure_ws) {
380 return Outcome::Refused(format!("{INSECURE_TRANSPORT}: {why}"));
381 }
382 let trusted = match trusted_key(opts.trust.as_deref()) {
385 Ok(k) => k,
386 Err(why) => return Outcome::Refused(why),
387 };
388 if opts.url.starts_with("wss://") && !cfg!(feature = "child-wss") {
389 return Outcome::Refused("a wss:// relay needs plexus-core's `child-wss` feature (TLS)".into());
390 }
391 let mut req = match opts.url.as_str().into_client_request() {
392 Ok(r) => r,
393 Err(e) => return Outcome::Refused(format!("`{}`: {e}", opts.url)),
394 };
395 let key = match read_seed(&opts.key) {
396 Ok(k) => k,
397 Err(e) => return Outcome::Refused(e),
398 };
399 let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
400 let proof = key_proof(&key, opts.url.trim_end_matches('/'), &opts.agent, &nonce(), ts);
401 drop(key);
402 match HeaderValue::from_str(&format!("Bearer {proof}")) {
403 Ok(v) => req.headers_mut().insert(AUTHORIZATION, v),
404 Err(e) => return Outcome::Refused(e.to_string()),
405 };
406 #[cfg(feature = "child-wss")]
409 let connecting = {
410 let tls = match opts.url.starts_with("wss://") {
411 true => match super::ws::tls_config(opts.tls_roots.as_deref()) {
412 Ok(c) => Some(tokio_tungstenite::Connector::Rustls(c)),
413 Err(why) => return Outcome::Refused(why),
414 },
415 false => None,
416 };
417 tokio_tungstenite::connect_async_tls_with_config(req, None, true, tls)
419 };
420 #[cfg(not(feature = "child-wss"))]
421 let connecting = tokio_tungstenite::connect_async_with_config(req, None, true);
422 let socket = match tokio::time::timeout(opts.timeout, connecting).await {
423 Err(_) => return dropped(format!("dialing {}: no answer to the upgrade in {:?}", opts.url, opts.timeout)),
424 Ok(Ok((s, _))) => s,
425 Ok(Err(tokio_tungstenite::tungstenite::Error::Http(resp))) => return dropped(format!("the upgrade to {} was refused: HTTP {}", opts.url, resp.status())),
426 Ok(Err(e)) => return dropped(format!("dialing {}: {e}", opts.url)),
427 };
428 let (mut sink, mut stream) = socket.split();
429
430 let (out, mut out_rx) = mpsc::unbounded_channel::<Vec<u8>>();
432 let conn = Conn::new("relay", None, out.clone(), 64, Arc::clone(&inner.counters));
433 let (mut host_in, host_r) = tokio::io::duplex(1 << 16);
436 let (host_w, host_out) = tokio::io::duplex(1 << 16);
437 let proven = Arc::new(AtomicBool::new(false));
438 let mut host: Option<tokio::task::JoinHandle<std::io::Result<()>>> = None;
439
440 let out_host = out.clone();
442 let host_lines = tokio::spawn(async move {
443 let mut lines = BufReader::new(host_out).lines();
444 while let Ok(Some(l)) = lines.next_line().await {
445 if out_host.send(l.into_bytes()).is_err() {
446 break;
447 }
448 }
449 });
450 let shutdown = Arc::clone(&conn);
451 let writer = tokio::spawn(async move {
452 loop {
453 tokio::select! {
454 first = out_rx.recv() => {
455 let Some(first) = first else { break };
456 let mut ok = sink.feed(Message::text(String::from_utf8_lossy(&first).into_owned())).await.is_ok();
457 while let (true, Ok(more)) = (ok, out_rx.try_recv()) {
458 ok = sink.feed(Message::text(String::from_utf8_lossy(&more).into_owned())).await.is_ok();
459 }
460 if !ok || sink.flush().await.is_err() {
461 break;
462 }
463 }
464 _ = shutdown.shutdown.notified() => {
465 let _ = sink.close().await;
466 break;
467 }
468 }
469 }
470 });
471
472 let (offer_tx, offer_rx) = oneshot::channel::<Value>();
475 let reader_conn = Arc::clone(&conn);
476 let (reader_proven, refuse_out) = (Arc::clone(&proven), out.clone());
477 let reader = tokio::spawn(async move {
478 let mut offer_tx = Some(offer_tx);
479 let why = loop {
480 let text = match stream.next().await {
481 Some(Ok(Message::Text(t))) => t.as_bytes().to_vec(),
482 Some(Ok(Message::Binary(b))) => b.to_vec(),
483 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())),
484 Some(Ok(_)) => continue,
485 Some(Err(e)) => break format!("the socket: {e}"),
486 None => break "the relay closed the socket".to_string(),
487 };
488 let shape: Value = match serde_json::from_slice(&text) {
489 Ok(v) => v,
490 Err(_) => continue,
491 };
492 let (method, id) = (shape.get("method"), shape.get("id"));
493 if method.is_some() && id.is_some() {
494 if !reader_proven.load(Ordering::Acquire) {
497 let refusal = json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "the relay has not proved its key", "data": { "error_kind": "forbidden" } } });
498 let _ = refuse_out.send(serde_json::to_vec(&refusal).unwrap_or_default());
499 continue;
500 }
501 let mut line = text;
502 line.push(b'\n');
503 if host_in.write_all(&line).await.is_err() {
504 break "the host stopped".to_string();
505 }
506 } else if method.is_none() && id.and_then(Value::as_str) == Some(OFFER_ID) {
507 if let Some(tx) = offer_tx.take() {
508 let _ = tx.send(shape);
509 }
510 } else {
511 reader_conn.on_message(&text).await;
512 }
513 };
514 reader_conn.on_gone(&why);
515 reader_conn.shutdown.notify_one();
516 why
517 });
518
519 let ended = |host: Option<tokio::task::JoinHandle<std::io::Result<()>>>, why: String, was_mounted: bool| {
520 if let Some(h) = host {
521 h.abort();
522 }
523 host_lines.abort();
524 writer.abort();
525 Outcome::Dropped { why, was_mounted }
526 };
527
528 let asked = crate::plexus::peer_token::random_nonce();
531 let info = async {
532 let (_, mut rx) = conn.open("_info", json!({ "nonce": asked }), opts.timeout).await.map_err(|e| format!("{e:?}"))?;
533 while let Some(item) = rx.recv().await {
534 if let PlexusStreamItem::Data { content, .. } = item {
535 let content = content.into_value();
536 if let Some(b) = content.get("backend").and_then(Value::as_str) {
537 let field = |k: &str| content.get(k).and_then(Value::as_str).map(str::to_string);
538 return Ok((b.to_string(), field("key"), field("proof")));
539 }
540 }
541 }
542 Err::<_, String>("its `_info` names no backend".into())
543 };
544 let (service, key, key_proof) = match tokio::time::timeout(opts.timeout, info).await {
545 Ok(Ok(s)) => s,
546 Ok(Err(why)) => {
547 reader.abort();
548 return ended(host, format!("asking the relay's `_info`: {why}"), false);
549 }
550 Err(_) => {
551 reader.abort();
552 return ended(host, format!("the relay did not answer `_info` in {:?}", opts.timeout), false);
553 }
554 };
555 if let Err(why) = relay_proved(&trusted, &service, &asked, key.as_deref(), key_proof.as_deref()) {
556 reader.abort();
557 ended(host, String::new(), false);
558 tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
559 return Outcome::Refused(why);
560 }
561 let _ = conn.ns.set(service.clone());
562 let _ = conn.peer_key.set(trusted.clone());
563 host = Some(tokio::spawn(serve_child_on(activation.clone(), host_r, host_w, ChildPeer::connection(trusted.clone(), [trusted.clone()]))));
564 proven.store(true, Ordering::Release);
565
566 let ns = activation.namespace().to_string();
568 let schema_hash = activation.plugin_schema().hash;
569 let mut params = json!({ "namespace": ns, "activations": [ns], "schema_hash": schema_hash, "schema": null });
570 if let Some(m) = &opts.mount {
571 params["mount"] = json!(m);
572 }
573 let _ = out.send(serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": OFFER_ID, "method": format!("{service}.offer"), "params": params })).unwrap_or_default());
574 let answer = match tokio::time::timeout(opts.timeout * 2, offer_rx).await {
575 Ok(Ok(a)) => a,
576 Ok(Err(_)) => {
577 let why = reader.await.unwrap_or_else(|_| "the socket".into());
578 return ended(host, format!("before the offer was answered: {why}"), false);
579 }
580 Err(_) => {
581 reader.abort();
582 return ended(host, format!("the offer was not answered in {:?}", opts.timeout * 2), false);
583 }
584 };
585 if let Some(e) = answer.get("error") {
586 reader.abort();
587 ended(host, String::new(), false);
588 let kind = e.pointer("/data/error_kind").and_then(Value::as_str).unwrap_or("refused");
589 let message = e.get("message").and_then(Value::as_str).unwrap_or("");
590 return Outcome::Refused(format!("{kind}: {message}"));
591 }
592 let result = answer.get("result").cloned().unwrap_or(Value::Null);
593 let mount = result.get("mount").and_then(Value::as_str).unwrap_or(&ns).to_string();
594 let path = result.get("path").and_then(Value::as_str).unwrap_or(&mount).to_string();
595 let relay = result.pointer("/service/principal").and_then(Value::as_str).unwrap_or("").to_string();
596 if relay != trusted {
599 reader.abort();
600 ended(host, String::new(), false);
601 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 });
602 tracing::warn!(target: "plexus::audit", url = %opts.url, "dial-out refused: {why}");
603 return Outcome::Refused(why);
604 }
605 *inner.live.lock().unwrap() = Some(Live { conn: Arc::clone(&conn), service: service.clone() });
606 let insecure = is_insecure_ws(&opts.url);
607 if insecure {
608 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");
609 }
610 tracing::info!(target: "plexus::dial", url = %opts.url, %path, %relay, insecure, "mounted at the relay");
611 inner.state.send_replace(DialState::Mounted { mount, path, service, relay, insecure });
612
613 let why = reader.await.unwrap_or_else(|_| "the socket".into());
614 ended(host, why, true)
615}
616
617fn trusted_key(trust: Option<&str>) -> Result<String, String> {
620 let Some(t) = trust else {
621 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());
622 };
623 match crate::plexus::peer_token::key_of(t) {
624 Some(_) => Ok(t.to_string()),
625 None => Err(format!("the trusted relay `{t}` is not a key (`key:<64 hex>`): a relay is named by the key it proves")),
626 }
627}
628
629fn relay_proved(trusted: &str, backend: &str, nonce: &str, key: Option<&str>, proof: Option<&str>) -> Result<(), String> {
631 let Some(key) = key else {
632 return Err(format!("the relay proved no key at `_info` (trusted: {trusted})"));
633 };
634 if key != trusted {
635 return Err(format!("the relay proved another key ({key}) than the one trusted ({trusted})"));
636 }
637 crate::plexus::peer_token::check_key_proof(key, proof.unwrap_or_default(), nonce, backend)
638 .map(|_| ())
639 .map_err(|e| format!("the relay's `_info` names the key {key} without proving it: {e}"))
640}
641
642pub fn key_principal(path: &std::path::Path) -> Result<String, String> {
645 read_seed(path).map(|k| principal_of(&k))
646}