Skip to main content

weirdnet_agent/remote/
share.rs

1//! Pool share links: how someone with a different Weirdnet identity finds a pool (since 0.5.9).
2//!
3//! A [`PoolShare`] names the pool's owner (a Weirdnet user id), an optional label, the pool's
4//! inference nodes (peer ids and addresses to dial them, direct or relay circuit) and an
5//! optional expiry. It holds no secret: no root seed, no keys, no certificates. Whoever holds the
6//! link can *dial* the nodes; only the owner's nodes decide who may *use* them, by the guest's
7//! own certificate and the owner's synced guest policy (`serve::GuestAuth`), re-checked on every
8//! request, so revoking a guest there takes effect at once and the link needs no revocation.
9//!
10//! The string forms follow the Weirdnet token conventions (a prefix and base64url JSON, safe to
11//! paste anywhere):
12//!
13//! ```text
14//! token  wnet-pool1:<base64url(JSON), no padding>
15//! link   weirdnet-pool://share/<the same base64url>
16//! JSON   {"v":1,"owner":"<32 hex>","name":"...","nodes":[{"peer_id":"12D3Koo...","addrs":["/ip4/.../p2p/..."]}],"expires_at":<ms>}
17//! ```
18//!
19//! `name` and `expires_at` are left out when unset; unknown fields are ignored, so later 0.5.x
20//! versions can add some without a new `v`. A link with a higher `v` is refused.
21//!
22//! Over Weirdnet (the `pool` feature), `pool::connect_shared` turns a share into a
23//! [`Pool`](crate::remote::pool::Pool) that presents the guest's own certificate.
24
25use std::fmt;
26use std::str::FromStr;
27
28use base64::Engine;
29use serde::{Deserialize, Serialize};
30
31/// The token prefix.
32pub const SHARE_PREFIX: &str = "wnet-pool1:";
33/// The link prefix (the app scheme `weirdnet-pool://`, never the reserved bare `weirdnet://`).
34pub const SHARE_LINK: &str = "weirdnet-pool://share/";
35/// The share format version this crate writes and reads.
36pub const SHARE_VERSION: u32 = 1;
37/// The longest token or link read (bytes, before decoding).
38pub const MAX_SHARE_LEN: usize = 16 * 1024;
39/// The most nodes a share may list.
40pub const MAX_SHARE_NODES: usize = 64;
41
42/// Why a share could not be read or used.
43#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
44#[error("pool share: {0}")]
45pub struct ShareError(pub String);
46
47fn err(m: impl Into<String>) -> ShareError {
48    ShareError(m.into())
49}
50
51/// One inference node of a shared pool: its peer id and addresses to dial it (the shape of
52/// `weirdnet_net::PeerHint`). Addresses may be empty when the guest's node finds the peer some
53/// other way (a relay or discovery).
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55#[non_exhaustive]
56pub struct SharedNode {
57    pub peer_id: String,
58    #[serde(default, skip_serializing_if = "Vec::is_empty")]
59    pub addrs: Vec<String>,
60}
61
62impl SharedNode {
63    pub fn new(peer_id: impl Into<String>, addrs: Vec<String>) -> Self {
64        Self { peer_id: peer_id.into(), addrs }
65    }
66}
67
68/// A pool share link. See the [module docs](self) for the wire and string forms.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70#[non_exhaustive]
71pub struct PoolShare {
72    /// The format version ([`SHARE_VERSION`]).
73    pub v: u32,
74    /// The pool owner's Weirdnet user id (32 lowercase hex characters,
75    /// `weirdnet_net::user::user_id` of the owner's key).
76    pub owner: String,
77    /// A label for people (for example "Ymir at home").
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub name: Option<String>,
80    /// The pool's inference nodes, best first.
81    pub nodes: Vec<SharedNode>,
82    /// When the link stops being offered (Unix ms). A hint for the guest's app: the owner's guest
83    /// policy, not this field, decides who is let in.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub expires_at: Option<i64>,
86}
87
88fn b64() -> base64::engine::GeneralPurpose {
89    base64::engine::general_purpose::URL_SAFE_NO_PAD
90}
91
92impl PoolShare {
93    /// A share of `owner`'s pool, with no nodes yet.
94    pub fn new(owner: impl Into<String>) -> Self {
95        Self { v: SHARE_VERSION, owner: owner.into(), name: None, nodes: Vec::new(), expires_at: None }
96    }
97
98    pub fn with_name(mut self, name: impl Into<String>) -> Self {
99        self.name = Some(name.into());
100        self
101    }
102
103    /// Adds an inference node (a peer id and the addresses that reach it).
104    pub fn with_node(mut self, peer_id: impl Into<String>, addrs: Vec<String>) -> Self {
105        self.nodes.push(SharedNode::new(peer_id, addrs));
106        self
107    }
108
109    pub fn with_expires_at(mut self, at_ms: i64) -> Self {
110        self.expires_at = Some(at_ms);
111        self
112    }
113
114    /// The nodes' peer ids, in order (a [`NodeSource`](crate::remote::pool::NodeSource) as a
115    /// `Vec<String>`).
116    pub fn node_ids(&self) -> Vec<String> {
117        self.nodes.iter().map(|n| n.peer_id.clone()).collect()
118    }
119
120    /// Past its expiry at `now_ms`.
121    pub fn is_expired(&self, now_ms: i64) -> bool {
122        self.expires_at.is_some_and(|at| now_ms >= at)
123    }
124
125    /// The version is known, the owner is a user id, and there are 1 to [`MAX_SHARE_NODES`]
126    /// nodes with non-empty, distinct peer ids. (Peer ids and addresses are parsed when dialing.)
127    pub fn validate(&self) -> Result<(), ShareError> {
128        if self.v == 0 || self.v > SHARE_VERSION {
129            return Err(err(format!("version {} is not supported (this reads up to {SHARE_VERSION})", self.v)));
130        }
131        if self.owner.len() != 32 || !self.owner.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
132            return Err(err("the owner is not a Weirdnet user id (32 lowercase hex characters)"));
133        }
134        if self.nodes.is_empty() {
135            return Err(err("no inference nodes"));
136        }
137        if self.nodes.len() > MAX_SHARE_NODES {
138            return Err(err(format!("more than {MAX_SHARE_NODES} nodes")));
139        }
140        for (i, n) in self.nodes.iter().enumerate() {
141            if n.peer_id.trim().is_empty() || n.peer_id.trim() != n.peer_id {
142                return Err(err("a node has no peer id"));
143            }
144            if self.nodes[..i].iter().any(|m| m.peer_id == n.peer_id) {
145                return Err(err(format!("node {} is listed twice", n.peer_id)));
146            }
147        }
148        Ok(())
149    }
150
151    fn body(&self) -> Result<String, ShareError> {
152        self.validate()?;
153        let json = serde_json::to_vec(self).map_err(|e| err(e.to_string()))?;
154        Ok(b64().encode(json))
155    }
156
157    /// The token form, `wnet-pool1:<base64url>`.
158    pub fn to_token(&self) -> Result<String, ShareError> {
159        Ok(format!("{SHARE_PREFIX}{}", self.body()?))
160    }
161
162    /// The link form, `weirdnet-pool://share/<base64url>`.
163    pub fn to_link(&self) -> Result<String, ShareError> {
164        Ok(format!("{SHARE_LINK}{}", self.body()?))
165    }
166
167    /// Reads a token or a link (whitespace and line breaks ignored, a trailing `/` allowed) and
168    /// validates it.
169    pub fn parse(input: &str) -> Result<Self, ShareError> {
170        if input.len() > MAX_SHARE_LEN {
171            return Err(err("too long"));
172        }
173        let s: String = input.split_whitespace().collect();
174        let body = if let Some(b) = s.strip_prefix(SHARE_PREFIX) {
175            b
176        } else if let Some(b) = s.get(..SHARE_LINK.len()).filter(|h| h.eq_ignore_ascii_case(SHARE_LINK)).map(|_| &s[SHARE_LINK.len()..]) {
177            b.trim_end_matches('/')
178        } else {
179            return Err(err(format!("not a pool share (they start with `{SHARE_PREFIX}` or `{SHARE_LINK}`)")));
180        };
181        let raw = b64().decode(body).map_err(|_| err("damaged (base64)"))?;
182        let share: PoolShare = serde_json::from_slice(&raw).map_err(|e| err(format!("damaged ({e})")))?;
183        share.validate()?;
184        Ok(share)
185    }
186
187    /// Does this look like a pool share (rather than something else pasted)?
188    pub fn is_share(input: &str) -> bool {
189        let t = input.trim_start();
190        t.starts_with(SHARE_PREFIX) || t.get(..SHARE_LINK.len()).is_some_and(|h| h.eq_ignore_ascii_case(SHARE_LINK))
191    }
192}
193
194impl fmt::Display for PoolShare {
195    /// The token form; an invalid share shows as `wnet-pool1:<invalid>`.
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        match self.to_token() {
198            Ok(t) => f.write_str(&t),
199            Err(_) => write!(f, "{SHARE_PREFIX}<invalid>"),
200        }
201    }
202}
203
204impl FromStr for PoolShare {
205    type Err = ShareError;
206
207    fn from_str(s: &str) -> Result<Self, ShareError> {
208        Self::parse(s)
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    const OWNER: &str = "0123456789abcdef0123456789abcdef";
217
218    fn share() -> PoolShare {
219        PoolShare::new(OWNER)
220            .with_name("Ymir at home")
221            .with_node("12D3KooWA", vec!["/ip4/192.0.2.1/udp/4001/quic-v1/p2p/12D3KooWA".into()])
222            .with_node("12D3KooWB", vec![])
223            .with_expires_at(1_900_000_000_000)
224    }
225
226    #[test]
227    fn token_and_link_round_trip() {
228        let s = share();
229        let token = s.to_token().unwrap();
230        assert!(token.starts_with(SHARE_PREFIX));
231        assert_eq!(PoolShare::parse(&token).unwrap(), s);
232        assert_eq!(token.parse::<PoolShare>().unwrap(), s);
233        assert_eq!(s.to_string(), token);
234        let link = s.to_link().unwrap();
235        assert!(link.starts_with(SHARE_LINK));
236        assert_eq!(PoolShare::parse(&link).unwrap(), s);
237        assert_eq!(PoolShare::parse(&format!("{link}/")).unwrap(), s, "a trailing slash");
238        assert_eq!(PoolShare::parse(&format!("WEIRDNET-POOL://SHARE/{}", &link[SHARE_LINK.len()..])).unwrap(), s, "the scheme is not");
239        let wrapped: String = token.chars().collect::<Vec<_>>().chunks(20).map(|c| c.iter().collect::<String>() + "\n  ").collect();
240        assert_eq!(PoolShare::parse(&wrapped).unwrap(), s, "line breaks and spaces are ignored");
241        assert!(PoolShare::is_share(&token) && PoolShare::is_share(&link) && !PoolShare::is_share("wnet-x1-offer:abc"));
242        assert_eq!(s.node_ids(), ["12D3KooWA", "12D3KooWB"]);
243    }
244
245    #[test]
246    fn json_is_compact_and_unset_fields_are_left_out() {
247        let s = PoolShare::new(OWNER).with_node("p", vec![]);
248        let json = String::from_utf8(b64().decode(&s.to_token().unwrap()[SHARE_PREFIX.len()..]).unwrap()).unwrap();
249        assert_eq!(json, format!(r#"{{"v":1,"owner":"{OWNER}","nodes":[{{"peer_id":"p"}}]}}"#));
250    }
251
252    #[test]
253    fn unknown_fields_are_ignored_and_newer_versions_refused() {
254        let with = |json: String| format!("{SHARE_PREFIX}{}", b64().encode(json));
255        let extra = with(format!(r#"{{"v":1,"owner":"{OWNER}","nodes":[{{"peer_id":"p","addrs":[],"relay":true}}],"later":"x"}}"#));
256        assert_eq!(PoolShare::parse(&extra).unwrap().nodes, [SharedNode::new("p", vec![])]);
257        let newer = with(format!(r#"{{"v":2,"owner":"{OWNER}","nodes":[{{"peer_id":"p"}}]}}"#));
258        assert!(PoolShare::parse(&newer).unwrap_err().0.contains("version 2"));
259    }
260
261    #[test]
262    fn damaged_or_invalid_shares_are_refused() {
263        for (input, why) in [
264            ("wnet-x1-offer:abc".to_string(), "not a pool share"),
265            (format!("{SHARE_PREFIX}!!!"), "base64"),
266            (format!("{SHARE_PREFIX}{}", b64().encode("not json")), "damaged"),
267            ("weirdnet://share/abc".to_string(), "not a pool share"),
268            ("x".repeat(MAX_SHARE_LEN + 1), "too long"),
269        ] {
270            let e = PoolShare::parse(&input).unwrap_err();
271            assert!(e.0.contains(why), "{input:.40}: {e}");
272        }
273        assert!(PoolShare::new("ABC").with_node("p", vec![]).to_token().unwrap_err().0.contains("user id"));
274        assert!(PoolShare::new(OWNER.to_uppercase()).with_node("p", vec![]).validate().is_err());
275        assert!(PoolShare::new(OWNER).to_token().unwrap_err().0.contains("no inference nodes"));
276        assert!(PoolShare::new(OWNER).with_node("p", vec![]).with_node("p", vec![]).validate().unwrap_err().0.contains("twice"));
277        assert!(PoolShare::new(OWNER).with_node(" ", vec![]).validate().is_err());
278        let many = (0..=MAX_SHARE_NODES).fold(PoolShare::new(OWNER), |s, i| s.with_node(format!("p{i}"), vec![]));
279        assert!(many.validate().is_err());
280        assert_eq!(PoolShare::new("bad").to_string(), "wnet-pool1:<invalid>");
281    }
282
283    #[test]
284    fn expiry() {
285        let s = share();
286        assert!(!s.is_expired(1_899_999_999_999));
287        assert!(s.is_expired(1_900_000_000_000));
288        assert!(!PoolShare::new(OWNER).is_expired(i64::MAX));
289    }
290}