Skip to main content

plexus_core/plexus/remote_child/
dial_out.rs

1//! VISION-5 (LOCAL-5) · dial-out: a service with no listening port opens one
2//! WebSocket to another service (a relay), signs in with its key on the
3//! upgrade (spec/00), offers an activation on that socket (spec/14,
4//! `{svc}.offer`) and serves it there — the far side of spec/12, the calls
5//! coming in on the socket it opened. The same socket carries its own calls
6//! out ([`Exposed::call`]): to the relay, and through it to every other
7//! peer connected there.
8//!
9//! ```ignore
10//! let exposed = Exposed::new(DialOut::new("wss://relay.example/ws", "~/.plexus/keys/alice.key").trust("key:<relay's>").mount("alice"));
11//! exposed.serve(Greeter::new(exposed.clone()));   // reconnects, within its backoff, until stopped
12//! exposed.mounted(Duration::from_secs(10)).await?; // `peers.alice` at the relay
13//! let items = exposed.call("peers.bob.hello", json!({ "name": "alice" })).await;
14//! ```
15//!
16//! | when | then |
17//! | -- | -- |
18//! | the socket opens | `_info` names the relay's `{svc}`; the offer goes as `{svc}.offer {namespace, activations, mount?}`; the relay asks the schema over the socket and answers the offer once mounted |
19//! | no trusted key ([`DialOut::trust`]) | refused before dialing (KEEL-8) |
20//! | the socket opens | the relay proves the trusted key at `_info {nonce}` (DYNAUTH-5's proof); none, or another: refused, nothing it sends served |
21//! | the relay calls `{ns}.call {method, params, hop}` | served as a child serves (RETURNS-47's host) on a proven connection: each call in the hop's context, the hop believed only when it names the proven key |
22//! | this side calls [`Exposed::call`] | `{svc}.call {method, params}` on the same socket: decided by the relay's gate as this key |
23//! | the socket drops | every call either way ends; the state is `down`; it dials again within [`DialOut::backoff`] and offers again |
24//! | the offer is refused | the state is `refused` naming why; it does not dial again until [`Exposed::serve`] is called again |
25
26use 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/// Where a service dials out to, as whom, and under what name it asks to be
50/// mounted.
51#[derive(Debug, Clone)]
52pub struct DialOut {
53    /// The relay's socket: `ws://HOST:PORT/ws` (`wss://` with `child-wss`).
54    pub url: String,
55    /// The key file the upgrade's proof is signed with (spec/00): synapse's
56    /// `~/.plexus/keys/<name>.key`, 0600. Read at each dial, never kept.
57    pub key: PathBuf,
58    /// The proof's agent id.
59    pub agent: String,
60    /// The mount name asked for (`peers.<mount>`); none: the activation's
61    /// namespace.
62    pub mount: Option<String>,
63    /// The relay's key (`key:<64 hex>`), pinned (spec/14 rule 4). KEEL-8:
64    /// required — none, and the dial-out is refused before dialing. At each
65    /// connect the relay proves it at `_info` (the nonce signed, as a
66    /// mount's child proves its key, DYNAUTH-5); a relay that proves none,
67    /// or another, is refused and nothing it sends is served. A hop is
68    /// believed only when it names this key as the service acting.
69    pub trust: Option<String>,
70    /// Dialing again after the socket drops.
71    pub backoff: Backoff,
72    /// `_info`, the offer's answer, and each of this side's calls' opens.
73    pub timeout: Duration,
74    /// KEEL-7: dial plain `ws://` beyond loopback (`transport.insecure_ws`,
75    /// a test network's). Off: such a relay is refused before a socket opens
76    /// ([`check_ws_url`]); on: dialed, and [`DialState::Mounted`] says
77    /// `insecure`.
78    pub insecure_ws: bool,
79    /// KEEL-8 (DYNAUTH-8): a PEM file of certificate authorities a `wss://`
80    /// relay's certificate may chain to, beside the webpki roots — as a
81    /// mount's [`ChildOptions::tls_roots`](super::ChildOptions::tls_roots).
82    pub tls_roots: Option<PathBuf>,
83}
84
85impl DialOut {
86    /// Dial `url`, signed in with the key in `key`.
87    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    /// Ask to be mounted as `name`.
102    pub fn mount(mut self, name: impl Into<String>) -> Self {
103        self.mount = Some(name.into());
104        self
105    }
106
107    /// The relay's key (`key:<64 hex>`): it must prove it at each connect,
108    /// and hops are believed only from it (pinned).
109    pub fn trust(mut self, principal: impl Into<String>) -> Self {
110        self.trust = Some(principal.into());
111        self
112    }
113
114    /// The proof's agent id.
115    pub fn agent(mut self, agent: impl Into<String>) -> Self {
116        self.agent = agent.into();
117        self
118    }
119
120    /// KEEL-7: allow plain `ws://` beyond loopback ([`DialOut::insecure_ws`]).
121    pub fn insecure_ws(mut self, on: bool) -> Self {
122        self.insecure_ws = on;
123        self
124    }
125
126    /// KEEL-8: a PEM file of CAs a `wss://` relay may chain to
127    /// ([`DialOut::tls_roots`]).
128    pub fn tls_roots(mut self, roots: impl Into<PathBuf>) -> Self {
129        self.tls_roots = Some(roots.into());
130        self
131    }
132
133    /// KEEL-7: [`DialOut::insecure_ws`] as `transport.insecure_ws` in `c`
134    /// says, when it says more than its default; KEEL-8: and
135    /// [`DialOut::tls_roots`] as `transport.tls_roots` says.
136    #[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/// Where a dialed-out service stands.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
151#[serde(tag = "state", rename_all = "snake_case")]
152pub enum DialState {
153    /// Not yet dialed, or dialing.
154    Connecting,
155    /// Mounted at the relay as `path` (`peers.<mount>`). `insecure`
156    /// (KEEL-7): over plain `ws://` beyond loopback, as
157    /// [`DialOut::insecure_ws`] allowed.
158    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    /// The socket dropped or could not open; dialing again.
167    Down { why: String },
168    /// The relay refused the offer; not dialing again.
169    Refused { why: String },
170    /// [`Exposed::stop`]ped.
171    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/// A service's one outbound socket to a relay: what it serves there, and
196/// the calls it makes over it. Cheap to clone; [`Self::serve`] holds a weak
197/// reference, so the socket goes with the last clone (or [`Self::stop`]).
198#[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    /// Not dialed until [`Self::serve`]: an activation that calls out through
211    /// the relay holds a clone of this before it is served.
212    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    /// The options it dials with.
225    pub fn options(&self) -> &DialOut {
226        &self.inner.opts
227    }
228
229    /// The principal this side signs in as (its key's), or why the key does
230    /// not read.
231    pub fn principal(&self) -> Result<String, String> {
232        read_seed(&self.inner.opts.key).map(|k| principal_of(&k))
233    }
234
235    /// Where it stands now.
236    pub fn state(&self) -> DialState {
237        self.inner.state.borrow().clone()
238    }
239
240    /// Its state, watched.
241    pub fn watch(&self) -> watch::Receiver<DialState> {
242        self.inner.state.subscribe()
243    }
244
245    /// Wait until mounted (its `path` at the relay), or refused, or `timeout`.
246    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    /// Dial, offer `activation`, serve it; dial again whenever the socket
261    /// drops. Replaces a previous `serve`.
262    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    /// Close the socket and stop dialing.
294    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    /// Call `method` (a path at the relay: `peers.bob.hello`, `peers.list`)
305    /// over this side's socket, as this side's key: `{svc}.call`, decided by
306    /// the relay's gate. Not connected: one `child_unavailable` item.
307    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
320/// A call's items, until its terminal one; dropped before it, unsubscribed.
321struct 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
369/// The offer's request id: a string, so it can never be one of the client
370/// `Conn`'s numbered requests (spec/14 rule 2: ids are per direction).
371const OFFER_ID: &str = "offer";
372
373/// One socket, from dial to drop.
374async 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    // KEEL-7: the transport decided before any socket opens or the key is
378    // read — `ws://` beyond loopback only under `transport.insecure_ws`.
379    if let Err(why) = check_ws_url(&opts.url, opts.insecure_ws) {
380        return Outcome::Refused(format!("{INSECURE_TRANSPORT}: {why}"));
381    }
382    // KEEL-8: a relay is named by its key before it is dialed; the socket is
383    // never a pipe, so nothing on it is believed without that key's proof.
384    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    // KEEL-8: the TLS a mount's dial is made with (`tls_roots` honoured),
407    // and its one timeout on the upgrade (a socket accepted and left).
408    #[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        // spec/14: a client that serves must not delay small writes (Nagle).
418        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    // This side's calls out: a client `Conn` on the socket's outbound queue.
431    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    // The calls in: RETURNS-47's host, on a pipe of lines this side feeds —
434    // started only once the relay has proved the trusted key (KEEL-8).
435    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    // Writer: the client's frames and the host's lines, in the order made.
441    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    // Reader: by the frame's shape (spec/14 rule 2) — a call into this side
473    // to the host; the offer's answer to its waiter; the rest to the client.
474    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                // KEEL-8: a call before the relay proved its key is answered
495                // refused, never served.
496                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    // The relay's namespace and its key, proved: its `_info` over a nonce
529    // (DYNAUTH-5's proof, the one a mount asks of its child).
530    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    // The offer (spec/14), answered once the relay has mounted this side.
567    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    // KEEL-8: the relay acts as the key it proved, or not at all — another
597    // principal named here is refused, as a remount proving another key is.
598    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
617/// KEEL-8: the relay's key a dial-out trusts — `key:<64 hex>` — or why the
618/// dial-out may not dial.
619fn 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
629/// KEEL-8: whether the relay's `_info` proved `trusted` over `nonce`.
630fn 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
642/// The principal a key file's proof proves (`key:<64 hex>`), or why the key
643/// does not read — a service naming itself, as a relay does in its hops.
644pub fn key_principal(path: &std::path::Path) -> Result<String, String> {
645    read_seed(path).map(|k| principal_of(&k))
646}