1use std::collections::BTreeMap;
32use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
33use std::sync::{Arc, Mutex, RwLock};
34use std::time::{Duration, Instant};
35
36use async_trait::async_trait;
37use futures::future::BoxFuture;
38use futures::stream::BoxStream;
39use futures::StreamExt;
40use plexus_auth_core::grants::{Gate, Grant, GrantSet, Refusal, RoleTable, Roles};
41use schemars::JsonSchema;
42use serde::{Deserialize, Serialize};
43use serde_json::{json, Value};
44use tokio::sync::{broadcast, mpsc};
45
46use super::link::{gone, meta, Conn, Kept, Shared};
47use super::{mount_schema, node_schema, Backoff, ChildOptions, ChildSpec, Inner, MountTimings, PeerIdentity, RemoteChild};
48use crate::plexus::auth::AuthContext;
49use crate::plexus::method_enum::MethodEnumSchema;
50use crate::plexus::plexus::{route_to_child, Activation, ChildRouter, PlexusError};
51use crate::plexus::schema::{Cardinality, MethodRole, MethodSchema, PluginSchema};
52use crate::plexus::streaming::PlexusStream;
53use crate::plexus::types::PlexusStreamItem;
54
55pub const OFFER_PENDING: &str = "_offer.pending";
60
61const POSSESSION_CONTEXT: &str = "plexus-dial-offer/v1";
63
64pub fn possession_input(host_key: &str, node_key: &str, node_nonce: &str, host_nonce: &str, service: &str, mount: &str) -> String {
68 format!("{POSSESSION_CONTEXT}\n{host_key}\n{node_key}\n{node_nonce}\n{host_nonce}\n{service}\n{mount}")
69}
70
71#[derive(Debug, Clone)]
73pub struct Offer {
74 pub socket: u64,
76 pub name: String,
78 pub namespace: String,
80 pub principal: String,
82 pub key_proven: bool,
86 pub from: Option<String>,
88 pub code: Option<String>,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct OfferRefused {
95 pub kind: String,
96 pub message: String,
97}
98
99impl OfferRefused {
100 pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
101 Self { kind: kind.into(), message: message.into() }
102 }
103}
104
105pub enum Decision {
107 Admit,
109 Refuse(OfferRefused),
111 Pending(BoxFuture<'static, Result<(), OfferRefused>>),
114}
115
116pub trait Admission: Send + Sync + 'static {
119 fn decide(&self, offer: &Offer) -> Decision;
121 fn vet(&self, offer: &Offer, child: &RemoteChild) -> Result<(), OfferRefused>;
123 fn mounted(&self, offer: &Offer, child: &RemoteChild, socket: &Arc<PeerSocket>) -> Result<(), OfferRefused>;
127 fn closed(&self, socket: u64, mount: Option<&str>, why: &str);
129}
130
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
133pub struct PeerInfo {
134 pub name: String,
136 pub principal: String,
138 pub namespace: String,
140 pub methods: Vec<String>,
142 pub connected_secs: u64,
144}
145
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
148#[serde(tag = "type", rename_all = "snake_case")]
149pub enum PeerEvent {
150 Mounted { name: String, principal: String, namespace: String, methods: Vec<String> },
152 Unmounted { name: String, why: String },
154}
155
156#[derive(Debug, Clone, Copy)]
158pub enum PeersMethods {}
159
160impl JsonSchema for PeersMethods {
161 fn schema_name() -> std::borrow::Cow<'static, str> {
162 "PeersMethods".into()
163 }
164
165 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
166 schemars::json_schema!({ "description": "list, watch, offer — and every peer connected, by its mount name" })
167 }
168}
169
170impl MethodEnumSchema for PeersMethods {
171 fn method_names() -> &'static [&'static str] {
172 &["list", "watch", "offer"]
173 }
174
175 fn schema_with_consts() -> Value {
176 serde_json::to_value(schemars::schema_for!(PeersMethods)).unwrap_or(Value::Null)
177 }
178}
179
180struct Entry {
182 child: RemoteChild,
183 principal: String,
184 namespace: String,
185 socket: u64,
186 since: Instant,
187 holder: std::sync::Weak<PeerSocket>,
189}
190
191impl Entry {
192 fn info(&self, name: &str) -> PeerInfo {
193 PeerInfo {
194 name: name.to_string(),
195 principal: self.principal.clone(),
196 namespace: self.namespace.clone(),
197 methods: self.child.inner.schema.methods.iter().map(|m| m.name.clone()).collect(),
198 connected_secs: self.since.elapsed().as_secs(),
199 }
200 }
201}
202
203struct PeersInner {
204 ns: String,
205 service: String,
206 principal: String,
207 gate: RwLock<Option<Arc<Gate>>>,
208 opts: ChildOptions,
209 table: RwLock<BTreeMap<String, Entry>>,
210 events: broadcast::Sender<PeerEvent>,
211 next_socket: AtomicU64,
212 on_change: RwLock<Vec<Box<dyn Fn() + Send + Sync>>>,
213 key: Option<Arc<crate::plexus::peer_token::PeerKey>>,
215 admission: RwLock<Option<Arc<dyn Admission>>>,
217}
218
219#[derive(Clone)]
222pub struct Peers {
223 inner: Arc<PeersInner>,
224}
225
226impl std::fmt::Debug for Peers {
227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228 f.debug_struct("Peers").field("ns", &self.inner.ns).field("names", &self.names()).finish()
229 }
230}
231
232fn valid_name(name: &str) -> Result<(), String> {
235 if name.is_empty() || name.len() > 64 {
236 return Err("a mount name is 1–64 characters".into());
237 }
238 if let Some(bad) = name.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '_' || *c == '-')) {
239 return Err(format!("the mount name `{name}` holds `{bad}`: only letters, digits, `_` and `-`"));
240 }
241 if matches!(name, "list" | "watch" | "offer" | "schema") {
242 return Err(format!("`{name}` is one of the peers' own methods"));
243 }
244 Ok(())
245}
246
247impl Peers {
248 pub fn new(ns: impl Into<String>, service: impl Into<String>, principal: impl Into<String>) -> Self {
252 let service = service.into();
253 let opts = ChildOptions {
254 backoff: Backoff { initial: Duration::ZERO, max: Duration::ZERO, per_minute: 0 },
256 ..ChildOptions::for_service(&service)
257 };
258 Self {
259 inner: Arc::new(PeersInner {
260 ns: ns.into(),
261 service,
262 principal: principal.into(),
263 gate: RwLock::new(None),
264 opts,
265 table: RwLock::new(BTreeMap::new()),
266 events: broadcast::channel(256).0,
267 next_socket: AtomicU64::new(1),
268 on_change: RwLock::new(Vec::new()),
269 key: None,
270 admission: RwLock::new(None),
271 }),
272 }
273 }
274
275 pub fn with_gate(self, gate: Arc<Gate>) -> Self {
279 *self.inner.gate.write().unwrap() = Some(gate);
280 self
281 }
282
283 pub fn set_gate(&self, gate: Arc<Gate>) {
286 *self.inner.gate.write().unwrap() = Some(gate);
287 }
288
289 pub fn with_timeout(self, timeout: Duration) -> Self {
292 let mut s = self;
293 if let Some(inner) = Arc::get_mut(&mut s.inner) {
294 inner.opts.timeout = timeout;
295 }
296 s
297 }
298
299 pub fn with_options(self, opts: ChildOptions) -> Self {
304 let mut s = self;
305 if let Some(inner) = Arc::get_mut(&mut s.inner) {
306 inner.opts = ChildOptions { backoff: Backoff { initial: Duration::ZERO, max: Duration::ZERO, per_minute: 0 }, ..opts };
307 }
308 s
309 }
310
311 pub fn with_admission(self, admission: Arc<dyn Admission>) -> Self {
315 *self.inner.admission.write().unwrap() = Some(admission);
316 self
317 }
318
319 pub fn with_key(self, key: crate::plexus::peer_token::PeerKey) -> Self {
326 let mut s = self;
327 if let Some(inner) = Arc::get_mut(&mut s.inner) {
328 inner.principal = key.kid().to_string();
329 inner.key = Some(Arc::new(key));
330 }
331 s
332 }
333
334 pub fn on_change(&self, f: impl Fn() + Send + Sync + 'static) {
338 self.inner.on_change.write().unwrap().push(Box::new(f));
339 }
340
341 fn moved(&self) {
344 if let Some(g) = self.inner.gate.read().unwrap().as_ref() {
345 g.generation().bump();
346 }
347 for f in self.inner.on_change.read().unwrap().iter() {
348 f();
349 }
350 }
351
352 pub fn names(&self) -> Vec<String> {
354 self.inner.table.read().unwrap().keys().cloned().collect()
355 }
356
357 pub fn list(&self) -> Vec<PeerInfo> {
359 self.inner.table.read().unwrap().iter().map(|(n, e)| e.info(n)).collect()
360 }
361
362 pub fn get(&self, name: &str) -> Option<RemoteChild> {
364 self.inner.table.read().unwrap().get(name).map(|e| e.child.clone())
365 }
366
367 pub fn events(&self) -> broadcast::Receiver<PeerEvent> {
369 self.inner.events.subscribe()
370 }
371
372 pub fn roles<R: Roles>(&self, base: R, every: Option<&str>) -> PeerRoles<R> {
380 PeerRoles { base, peers: self.clone(), every: every.map(str::to_string) }
381 }
382
383 pub fn socket(&self, auth: Option<AuthContext>) -> (Arc<PeerSocket>, mpsc::UnboundedReceiver<Vec<u8>>) {
388 self.socket_from(auth, None, None)
389 }
390
391 pub fn socket_from(&self, auth: Option<AuthContext>, from: Option<String>, close: Option<Box<dyn Fn() + Send + Sync>>) -> (Arc<PeerSocket>, mpsc::UnboundedReceiver<Vec<u8>>) {
395 let (out, rx) = mpsc::unbounded_channel();
396 let (inbound, mut in_rx) = mpsc::unbounded_channel::<Vec<u8>>();
397 let socket = Arc::new(PeerSocket {
398 peers: self.clone(),
399 id: self.inner.next_socket.fetch_add(1, Ordering::Relaxed),
400 principal: auth.as_ref().and_then(|a| a.principal()).map(|p| p.to_string()),
401 auth,
402 out,
403 inbound,
404 link: Mutex::new(None),
405 mount: Mutex::new(None),
406 from,
407 close,
408 closed: AtomicBool::new(false),
409 offering: AtomicBool::new(false),
410 pairing: Mutex::new(None),
411 });
412 let weak = Arc::downgrade(&socket);
415 tokio::spawn(async move {
416 while let Some(frame) = in_rx.recv().await {
417 let link = weak.upgrade().and_then(|s| s.link.lock().unwrap().clone());
418 if let Some((conn, _)) = link {
419 conn.on_message(&frame).await;
420 }
421 }
422 });
423 (socket, rx)
424 }
425
426 fn unmount(&self, name: &str, socket: u64, why: &str) {
427 let removed = {
428 let mut t = self.inner.table.write().unwrap();
429 match t.get(name) {
430 Some(e) if e.socket == socket => t.remove(name),
431 _ => None,
432 }
433 };
434 if let Some(e) = removed {
435 tracing::info!(target: "plexus::peers", peer = %name, "peer unmounted: {why}");
436 e.child.stop(why);
440 self.moved();
441 let _ = self.inner.events.send(PeerEvent::Unmounted { name: name.to_string(), why: why.to_string() });
442 }
443 }
444
445 fn data(&self, method: &str, content: Value) -> PlexusStreamItem {
446 let ns = &self.inner.ns;
447 PlexusStreamItem::Data { metadata: meta(ns).into(), content_type: format!("{ns}.{method}").into(), content: content.into() }
448 }
449
450 fn done(&self) -> PlexusStreamItem {
451 PlexusStreamItem::Done { metadata: meta(&self.inner.ns) }
452 }
453
454 fn own_methods(&self) -> Vec<MethodSchema> {
455 let ns = &self.inner.ns;
456 vec![
457 MethodSchema::new("list", "The peers connected now: each one's mount name, principal, namespace and methods", "")
458 .with_cardinality(Cardinality::Many)
459 .with_returns(schemars::schema_for!(PeerInfo))
460 .with_grant(format!("{ns}.list"))
461 .with_content_hash(),
462 MethodSchema::new("watch", "Peers as they come and go: those mounted now, then each mount and unmount", "")
463 .with_cardinality(Cardinality::Many)
464 .with_returns(schemars::schema_for!(PeerEvent))
465 .with_grant(format!("{ns}.watch"))
466 .with_content_hash(),
467 MethodSchema::new("offer", "Offered on a peer's own socket (`{service}.offer`, spec/14), not called: its grant decides who may be mounted, on the mount name", "")
468 .with_cardinality(Cardinality::One)
469 .with_grant(format!("{ns}.offer"))
470 .with_content_hash(),
471 ]
472 }
473}
474
475pub struct PeerRoles<R = RoleTable> {
477 base: R,
478 peers: Peers,
479 every: Option<String>,
480}
481
482#[async_trait]
483impl<R: crate::plexus::RoleStore> crate::plexus::RoleStore for PeerRoles<R> {
484 async fn set(&self, role: &plexus_auth_core::audit::RoleName, grants: GrantSet) -> Result<(), crate::plexus::StoreError> {
485 self.base.set(role, grants).await
486 }
487}
488
489impl<R: Roles> Roles for PeerRoles<R> {
490 fn grants(&self, role: &plexus_auth_core::audit::RoleName) -> Option<GrantSet> {
491 let base = self.base.grants(role);
492 if matches!(base, Some(GrantSet::All)) {
493 return base;
494 }
495 let mut set = match base {
496 Some(GrantSet::Listed(s)) => s,
497 _ => Default::default(),
498 };
499 let every = self.every.as_deref() == Some(role.as_str());
500 let ns = &self.peers.inner.ns;
501 if every {
502 for m in ["list", "watch", "offer"] {
503 set.insert(Grant::new(format!("{ns}.{m}")));
504 }
505 }
506 let mut known = every || self.base.grants(role).is_some();
507 for (name, e) in self.peers.inner.table.read().unwrap().iter() {
508 let schema = &e.child.inner.schema;
509 if every {
510 set.extend(schema.methods.iter().map(|m| Grant::new(format!("{ns}.{name}.{}", m.name))));
511 }
512 if let Some(gs) = schema.roles.get(role.as_str()) {
515 known = true;
516 set.extend(gs.iter().map(Grant::new));
517 }
518 if every || schema.roles.get(role.as_str()).is_some_and(|g| !g.is_empty()) {
521 set.insert(Grant::new(format!("{ns}.{name}")));
522 }
523 }
524 known.then_some(GrantSet::Listed(set))
525 }
526
527 fn names(&self) -> Vec<plexus_auth_core::audit::RoleName> {
528 let mut names = self.base.names();
529 if let Some(e) = &self.every {
530 names.push(plexus_auth_core::audit::RoleName::new(e));
531 }
532 names
533 }
534}
535
536pub struct PeerSocket {
539 peers: Peers,
540 id: u64,
541 auth: Option<AuthContext>,
542 principal: Option<String>,
543 out: mpsc::UnboundedSender<Vec<u8>>,
544 inbound: mpsc::UnboundedSender<Vec<u8>>,
545 link: Mutex<Option<(Arc<Conn>, Arc<Shared>)>>,
547 mount: Mutex<Option<String>>,
549 from: Option<String>,
551 close: Option<Box<dyn Fn() + Send + Sync>>,
552 closed: AtomicBool,
554 offering: AtomicBool,
556 pairing: Mutex<Option<(String, String)>>,
558}
559
560#[derive(Deserialize)]
562struct Shape {
563 #[serde(default)]
564 id: Option<Value>,
565 #[serde(default)]
566 method: Option<String>,
567 #[serde(default)]
568 params: Option<Value>,
569}
570
571fn refusal(id: &Value, code: i64, kind: &str, message: &str) -> Vec<u8> {
573 serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message, "data": { "error_kind": kind } } })).unwrap_or_default()
574}
575
576impl PeerSocket {
577 pub fn id(&self) -> u64 {
579 self.id
580 }
581
582 pub fn is_closed(&self) -> bool {
584 self.closed.load(Ordering::Acquire)
585 }
586
587 pub fn close(&self, why: &str) {
591 self.ended(why);
592 if let Some(close) = &self.close {
593 close();
594 }
595 }
596
597 pub fn principal(&self) -> Option<&str> {
599 self.principal.as_deref()
600 }
601
602 pub fn mount(&self) -> Option<String> {
604 self.mount.lock().unwrap().clone()
605 }
606
607 pub fn on_frame(self: &Arc<Self>, frame: &[u8]) -> bool {
611 let Ok(shape) = serde_json::from_slice::<Shape>(frame) else { return false };
612 match (&shape.method, &shape.id) {
613 (Some(m), Some(id)) if m == "_info" && self.peers.inner.key.is_some() && shape.params.as_ref().and_then(|p| p.get("nonce")).is_some_and(Value::is_string) => {
615 let nonce = shape.params.as_ref().and_then(|p| p.get("nonce")).and_then(Value::as_str).unwrap_or_default();
616 let commit = shape.params.as_ref().and_then(|p| p.get("commit")).and_then(Value::as_str);
617 self.prove(id, nonce, commit);
618 true
619 }
620 (Some(m), Some(_)) if m == super::upcall::HOST_CALL || m == super::upcall::HOST_CALL_UNSUB => {
623 self.mount.lock().unwrap().is_some() && self.link.lock().unwrap().is_some() && self.inbound.send(frame.to_vec()).is_ok()
624 }
625 (Some(m), Some(id)) if *m == format!("{}.offer", self.peers.inner.service) => {
626 let (me, id, params) = (Arc::clone(self), id.clone(), shape.params.unwrap_or(Value::Null));
627 tokio::spawn(async move {
628 let answer = me.offer(&id, params).await;
629 let _ = me.out.send(answer);
630 });
631 true
632 }
633 (None, Some(_)) => self.link.lock().unwrap().is_some() && self.inbound.send(frame.to_vec()).is_ok(),
636 (Some(_), None) => {
638 let item = shape.params.as_ref().is_some_and(|p| p.get("subscription").is_some() && p.get("result").is_some());
639 item && self.link.lock().unwrap().is_some() && self.inbound.send(frame.to_vec()).is_ok()
640 }
641 _ => false,
642 }
643 }
644
645 fn prove(&self, id: &Value, nonce: &str, commit: Option<&str>) {
648 let Some(key) = &self.peers.inner.key else { return };
649 let service = &self.peers.inner.service;
650 let sid = format!("info-{}", self.id);
651 let asker = self.principal.clone().unwrap_or_default();
653 let mut content = json!({ "backend": service, "key": key.kid(), "proof": key.key_proof_for(nonce, service, &asker), "asker": asker });
654 if let Some(commit) = commit {
657 let mut pairing = self.pairing.lock().unwrap();
658 if pairing.is_none() {
659 let host_nonce = crate::plexus::peer_token::random_nonce();
660 content["host_nonce"] = json!(host_nonce);
661 *pairing = Some((commit.to_string(), host_nonce));
662 }
663 }
664 let item = PlexusStreamItem::data(meta(service), "_info".into(), content);
665 let frames = [
666 json!({ "jsonrpc": "2.0", "id": id, "result": sid }),
667 json!({ "jsonrpc": "2.0", "method": "_info", "params": { "subscription": sid, "result": item } }),
668 json!({ "jsonrpc": "2.0", "method": "_info", "params": { "subscription": sid, "result": PlexusStreamItem::done(meta(service)) } }),
669 ];
670 for f in frames {
671 let _ = self.out.send(serde_json::to_vec(&f).unwrap_or_default());
672 }
673 }
674
675 pub fn on_close(&self) {
678 self.ended("its connection closed");
679 }
680
681 fn ended(&self, why: &str) {
684 let (first, name) = {
685 let mut m = self.mount.lock().unwrap();
686 (!self.closed.swap(true, Ordering::AcqRel), m.take())
687 };
688 if let Some((conn, shared)) = self.link.lock().unwrap().take() {
689 gone(&Arc::downgrade(&shared), &conn, why);
690 }
691 if let Some(name) = &name {
692 self.peers.unmount(name, self.id, why);
693 }
694 if first {
695 let admission = self.peers.inner.admission.read().unwrap().clone();
696 if let Some(a) = admission {
697 a.closed(self.id, name.as_deref(), why);
698 }
699 }
700 }
701
702 fn paired(&self, params: &Value, principal: &str, name: &str) -> Result<(Option<String>, bool), OfferRefused> {
705 let Some((commit, host_nonce)) = self.pairing.lock().unwrap().clone() else { return Ok((None, false)) };
706 let Some(node_nonce) = params.get("pairing_nonce").and_then(Value::as_str) else { return Ok((None, false)) };
707 if !super::pairing::commits_to(&commit, node_nonce) {
708 return Err(OfferRefused::new("pairing_mismatch", "the offer's nonce is not the one committed to at `_info`"));
709 }
710 let host_key = self.peers.inner.key.as_ref().map(|k| k.kid().to_string()).unwrap_or_default();
711 let code = super::pairing::pairing_code(&host_key, principal, node_nonce, &host_nonce);
712 let proven = match (params.get("possession").and_then(Value::as_str), crate::plexus::peer_token::key_of(principal)) {
713 (Some(sig), Some(vk)) => {
714 let input = possession_input(&host_key, principal, node_nonce, &host_nonce, &self.peers.inner.service, name);
715 let sig = base64::Engine::decode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, sig).ok().and_then(|b| <[u8; 64]>::try_from(b.as_slice()).ok());
716 match sig {
717 Some(sig) if vk.verify_strict(input.as_bytes(), &ed25519_dalek::Signature::from_bytes(&sig)).is_ok() => true,
718 _ => return Err(OfferRefused::new("unauthenticated", format!("the offer's `possession` is not {principal}'s signature over this connection"))),
719 }
720 }
721 _ => false,
722 };
723 Ok((Some(code), proven))
724 }
725
726 async fn offer(self: &Arc<Self>, id: &Value, params: Value) -> Vec<u8> {
727 let peers = &self.peers;
728 let Some(namespace) = params.get("namespace").and_then(Value::as_str).map(str::to_string) else {
729 return refusal(id, -32602, "invalid_params", "an offer names its `namespace`");
730 };
731 let name = params.get("mount").and_then(Value::as_str).unwrap_or(&namespace).to_string();
732 if let Err(why) = valid_name(&name).and_then(|_| valid_name(&namespace).map_err(|w| format!("its namespace: {w}"))) {
733 return refusal(id, -32602, "invalid_params", &why);
734 }
735 let Some(principal) = self.principal.clone() else {
736 return refusal(id, -32001, "unauthenticated", "sign in first: an anonymous socket offers nothing");
737 };
738 if self.offering.swap(true, Ordering::AcqRel) {
740 return refusal(id, -32602, "invalid_params", "this socket has offered already");
741 }
742 let (code, key_proven) = match self.paired(¶ms, &principal, &name) {
743 Ok(p) => p,
744 Err(r) => return refusal(id, -32001, &r.kind, &r.message),
745 };
746 let offer = Offer { socket: self.id, name: name.clone(), namespace: namespace.clone(), principal: principal.clone(), key_proven, from: self.from.clone(), code: code.clone() };
747 let admission = peers.inner.admission.read().unwrap().clone();
748 if let Some(a) = &admission {
749 let decided = match a.decide(&offer) {
750 Decision::Admit => Ok(()),
751 Decision::Refuse(r) => Err(r),
752 Decision::Pending(wait) => {
753 let notice = json!({ "jsonrpc": "2.0", "method": OFFER_PENDING, "params": { "id": id, "code": code } });
754 let _ = self.out.send(serde_json::to_vec(¬ice).unwrap_or_default());
755 tracing::info!(target: "plexus::audit", peer = %name, %principal, from = ?self.from, "dial-in offer pending");
756 wait.await
757 }
758 };
759 if let Err(r) = decided {
760 tracing::warn!(target: "plexus::audit", peer = %name, %principal, from = ?self.from, kind = %r.kind, "dial-in offer refused: {}", r.message);
761 return refusal(id, -32003, &r.kind, &r.message);
762 }
763 if self.is_closed() {
764 return refusal(id, -32000, "child_unavailable", "the socket closed while its offer waited");
765 }
766 }
767 let gate = peers.inner.gate.read().unwrap().clone();
768 if let Some(gate) = gate {
769 let grant = Grant::new(format!("{}.offer", peers.inner.ns));
770 if let Err(r) = gate.check(self.auth.as_ref(), &grant, Some(&name)) {
771 let (code, kind, message) = match r {
772 Refusal::Unauthenticated | Refusal::Ended { .. } => (-32001, "unauthenticated", r.to_string()),
773 Refusal::MissingGrant { .. } => (-32003, "forbidden", format!("{principal} holds no `{grant}` on `{name}`")),
774 };
775 return refusal(id, code, kind, &message);
776 }
777 }
778 if let Some(e) = peers.inner.table.read().unwrap().get(&name) {
779 if e.principal != principal {
780 return refusal(id, -32010, "name_taken", &format!("`{name}` is held by another principal's connection"));
781 }
782 }
783 let path = format!("{}.{name}", peers.inner.ns);
785 let spec = ChildSpec::Ws { name: path.clone(), url: format!("dial-in:{principal}") };
786 let shared = Shared::new(spec, peers.inner.opts.clone(), peers.inner.principal.clone());
787 let conn = Conn::new(&path, None, self.out.clone(), peers.inner.opts.buffer, Arc::clone(&shared.counters));
788 let _ = conn.ns.set(namespace.clone());
789 let _ = conn.up.set(Arc::clone(&shared.upcalls));
793 if key_proven {
794 let _ = conn.peer_key.set(principal.clone());
795 }
796 let _ = shared.identity.set(PeerIdentity::of(&conn));
797 shared.install(Arc::clone(&conn));
798 *self.link.lock().unwrap() = Some((Arc::clone(&conn), Arc::clone(&shared)));
799 let t0 = Instant::now();
800 let hop = json!({ "principal": peers.inner.principal, "for": [], "limit": null, "call": uuid::Uuid::new_v4().to_string() });
801 let asked = ask(&conn, &format!("{namespace}.call"), json!({ "method": format!("{namespace}.schema"), "params": {}, "hop": hop }), peers.inner.opts.timeout).await;
802 let mounted = match asked {
805 Ok(raw) => {
806 let deadline = t0 + peers.inner.opts.timeout;
807 shared.walk(&conn, &namespace, &raw, deadline).await.map(|nodes| Kept { top: raw, nodes })
808 }
809 Err(e) => Err(e),
810 };
811 let mounted = mounted.and_then(|kept| {
812 let hash = kept.hash();
813 let schema = mount_schema(&path, kept.top)?;
814 let nodes = kept.nodes.into_iter().map(|(p, raw)| node_schema(&p, raw).map(|s| (p, s))).collect::<Result<Vec<_>, _>>()?;
815 let _ = shared.mounted_hash.set(hash.clone());
816 Ok((schema, nodes, hash))
817 });
818 let (schema, nodes, hash) = match mounted {
819 Ok(m) => m,
820 Err(why) => {
821 self.link.lock().unwrap().take();
822 return refusal(id, -32000, "invalid_params", &format!("not mounted: {why}"));
823 }
824 };
825 let timings = MountTimings { spawn_ms: 0.0, schema_ms: t0.elapsed().as_secs_f64() * 1e3, merge_ms: 0.0 };
826 let methods: Vec<String> = schema.methods.iter().map(|m| m.name.clone()).collect();
827 let child = RemoteChild { inner: Arc::new(Inner::new(shared, schema, nodes, timings)) };
828 child.inner.shared.upcalls.set_needs(child.inner.needs.as_deref());
830 if let Some(a) = &admission {
831 if let Err(r) = a.vet(&offer, &child) {
832 self.link.lock().unwrap().take();
833 tracing::warn!(target: "plexus::audit", peer = %name, %principal, kind = %r.kind, "dial-in offer refused at its schema: {}", r.message);
834 return refusal(id, -32003, &r.kind, &r.message);
835 }
836 }
837 let replaced = {
838 let mut m = self.mount.lock().unwrap();
839 if self.is_closed() {
840 drop(m);
841 self.link.lock().unwrap().take();
842 return refusal(id, -32000, "child_unavailable", "the socket closed while it was mounted");
843 }
844 let replaced = peers.inner.table.write().unwrap().insert(name.clone(), Entry { child: child.clone(), principal: principal.clone(), namespace: namespace.clone(), socket: self.id, since: Instant::now(), holder: Arc::downgrade(self) });
845 *m = Some(name.clone());
846 replaced
847 };
848 if let Some(a) = &admission {
849 if let Err(r) = a.mounted(&offer, &child, self) {
850 self.mount.lock().unwrap().take();
852 if let Some((conn, shared)) = self.link.lock().unwrap().take() {
853 gone(&Arc::downgrade(&shared), &conn, &r.message);
854 }
855 {
856 let mut t = peers.inner.table.write().unwrap();
857 if t.get(&name).is_some_and(|e| e.socket == self.id) {
858 t.remove(&name);
859 }
860 if let Some(old) = replaced.filter(|e| e.holder.upgrade().is_some_and(|s| !s.is_closed())) {
863 t.entry(name.clone()).or_insert(old);
864 }
865 }
866 tracing::warn!(target: "plexus::audit", peer = %name, %principal, kind = %r.kind, "dial-in offer refused as it was mounted: {}", r.message);
867 return refusal(id, -32003, &r.kind, &r.message);
868 }
869 }
870 if replaced.is_some() {
871 let _ = peers.inner.events.send(PeerEvent::Unmounted { name: name.clone(), why: "a new connection of the same principal took the name".into() });
872 }
873 tracing::info!(target: "plexus::peers", peer = %name, %principal, %namespace, methods = methods.len(), "peer mounted");
874 peers.moved();
875 let _ = peers.inner.events.send(PeerEvent::Mounted { name: name.clone(), principal, namespace: namespace.clone(), methods });
876 serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": id, "result": {
877 "offered": namespace,
878 "mount": name,
879 "path": path,
880 "schema_hash": params.get("schema_hash").cloned().unwrap_or(Value::String(hash)),
881 "service": { "namespace": peers.inner.service, "principal": peers.inner.principal },
882 } }))
883 .unwrap_or_default()
884 }
885}
886
887async fn ask(conn: &Conn, method: &str, params: Value, timeout: Duration) -> Result<Value, String> {
889 let (_, mut rx) = conn.open(method, params, timeout, None).await.map_err(|e| match e {
890 PlexusStreamItem::Error { message, .. } => message,
891 other => format!("{other:?}"),
892 })?;
893 let deadline = tokio::time::Instant::now() + timeout;
894 let mut first = None;
895 loop {
896 match tokio::time::timeout_at(deadline, rx.recv()).await {
897 Ok(Some(PlexusStreamItem::Data { content, .. })) => {
898 first.get_or_insert(content.into_value());
899 }
900 Ok(Some(PlexusStreamItem::Error { message, .. })) => return Err(message),
901 Ok(Some(PlexusStreamItem::Done { .. })) | Ok(None) => break,
902 Ok(Some(_)) => {}
903 Err(_) => return Err(format!("no answer in {timeout:?}")),
904 }
905 }
906 first.ok_or_else(|| "it answered no data".to_string())
907}
908
909#[async_trait]
910impl Activation for Peers {
911 type Methods = PeersMethods;
912
913 fn namespace(&self) -> &str {
914 &self.inner.ns
915 }
916
917 fn version(&self) -> &str {
918 env!("CARGO_PKG_VERSION")
919 }
920
921 fn description(&self) -> &str {
922 "The peers connected now: services that dialed in and offered a surface, each mounted by name while its socket lives"
923 }
924
925 fn methods(&self) -> Vec<&str> {
926 vec!["list", "watch", "offer"]
927 }
928
929 fn method_help(&self, method: &str) -> Option<String> {
930 self.own_methods().into_iter().find(|m| m.name == method).map(|m| m.description)
931 }
932
933 async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>, raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
934 match method {
935 "schema" => {
936 let schema = self.plugin_schema();
937 let content = match params.get("method").and_then(Value::as_str) {
938 Some(m) => match schema.methods.iter().find(|x| x.name == m) {
939 Some(ms) => serde_json::to_value(ms).unwrap_or_default(),
940 None => return Err(PlexusError::MethodNotFound { activation: self.inner.ns.clone(), method: m.to_string() }),
941 },
942 None => serde_json::to_value(&schema).unwrap_or_default(),
943 };
944 let ns = &self.inner.ns;
945 let item = PlexusStreamItem::Data { metadata: meta(ns).into(), content_type: format!("{ns}.schema").into(), content: content.into() };
946 Ok(Box::pin(futures::stream::iter([item, self.done()])))
947 }
948 "list" => {
949 let items: Vec<PlexusStreamItem> = self.list().into_iter().map(|p| self.data("list", serde_json::to_value(p).unwrap_or_default())).chain([self.done()]).collect();
950 Ok(Box::pin(futures::stream::iter(items)))
951 }
952 "watch" => {
953 let mut rx = self.events();
954 let now: Vec<PeerEvent> = self
955 .list()
956 .into_iter()
957 .map(|p| PeerEvent::Mounted { name: p.name, principal: p.principal, namespace: p.namespace, methods: p.methods })
958 .collect();
959 let me = self.clone();
960 Ok(Box::pin(async_stream::stream! {
961 for e in now {
962 yield me.data("watch", serde_json::to_value(e).unwrap_or_default());
963 }
964 loop {
965 match rx.recv().await {
966 Ok(e) => yield me.data("watch", serde_json::to_value(e).unwrap_or_default()),
967 Err(broadcast::error::RecvError::Lagged(_)) => continue,
968 Err(broadcast::error::RecvError::Closed) => break,
969 }
970 }
971 yield me.done();
972 }))
973 }
974 "offer" => Err(PlexusError::ExecutionError(format!(
975 "an offer is made on the peer's own socket, as `{}.offer` (spec/14), not called",
976 self.inner.service
977 ))),
978 m if m.contains('.') => route_to_child(self, m, params, auth, raw).await,
979 m if self.get(m).is_some() => Err(PlexusError::MethodNotFound { activation: format!("{}.{m}", self.inner.ns), method: String::new() }),
980 m => Err(PlexusError::MethodNotFound { activation: self.inner.ns.clone(), method: m.to_string() }),
981 }
982 }
983
984 fn into_rpc_methods(self) -> jsonrpsee::Methods {
987 jsonrpsee::Methods::new()
988 }
989
990 fn plugin_schema(&self) -> PluginSchema {
993 let mut methods = self.own_methods();
994 let mut children = Vec::new();
995 for (name, e) in self.inner.table.read().unwrap().iter() {
996 let s = &e.child.inner.schema;
997 let description = format!("a peer: {} ({}, connected as {})", s.description, e.namespace, e.principal);
998 methods.push(MethodSchema::new(name.clone(), description.clone(), s.hash.clone()).with_role(MethodRole::StaticChild));
999 children.push(crate::plexus::schema::ChildSummary { namespace: name.clone(), description, hash: s.hash.clone() });
1001 }
1002 let mut schema = PluginSchema::leaf(self.inner.ns.clone(), self.version(), self.description(), methods);
1003 #[allow(deprecated)]
1004 if !children.is_empty() {
1005 schema.children = Some(children);
1006 }
1007 let ns = &self.inner.ns;
1008 schema.roles.insert("viewer".into(), vec![format!("{ns}.list"), format!("{ns}.watch")]);
1009 schema
1010 }
1011}
1012
1013#[async_trait]
1014impl ChildRouter for Peers {
1015 fn router_namespace(&self) -> &str {
1016 &self.inner.ns
1017 }
1018
1019 async fn router_call(&self, method: &str, params: Value, auth: Option<&AuthContext>, raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
1020 Activation::call(self, method, params, auth, raw).await
1021 }
1022
1023 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
1024 self.get(name).map(|c| Box::new(c) as Box<dyn ChildRouter>)
1025 }
1026
1027 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
1028 Some(futures::stream::iter(self.names()).boxed())
1029 }
1030}
1031
1032#[cfg(test)]
1033mod tests {
1034 use super::*;
1035
1036 #[test]
1037 fn a_mount_name_is_one_segment_and_not_a_method() {
1038 assert!(valid_name("alice").is_ok());
1039 assert!(valid_name("a-b_9").is_ok());
1040 assert!(valid_name("a.b").is_err());
1041 assert!(valid_name("").is_err());
1042 assert!(valid_name("list").is_err());
1043 }
1044}