Skip to main content

rings_node/
seed.rs

1//! Seed and SeedLoader use for getting peers from endpoint.
2
3use std::str::FromStr;
4
5use rings_core::dht::Did;
6use rings_rpc::protos::rings_node::ConnectWithSeedRequest;
7use serde::Deserialize;
8use serde::Serialize;
9
10use crate::error::Error;
11use crate::remote_endpoint::RemoteRpcEndpoint;
12
13/// A list contains SeedPeer.
14#[derive(Deserialize, Serialize, Debug)]
15pub struct Seed {
16    /// Peers loaded from seed configuration.
17    pub peers: Vec<SeedPeer>,
18}
19
20/// SeedPeer contain `Did` and `endpoint`.
21#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)]
22pub struct SeedPeer {
23    /// an unique identify.
24    pub did: String,
25    /// remote client endpoint
26    pub url: String,
27    /// Optional Bearer token for a seed peer that gates its handshake; absent by default,
28    /// since the external handshake is public.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub api_token: Option<String>,
31}
32
33impl std::fmt::Debug for SeedPeer {
34    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        formatter
36            .debug_struct("SeedPeer")
37            .field("did", &self.did)
38            .field("url", &self.url)
39            .field("api_token", &self.api_token.as_ref().map(|_| "[REDACTED]"))
40            .finish()
41    }
42}
43
44/// Why a seed entry cannot be dialed.
45#[derive(Debug, thiserror::Error, Eq, PartialEq)]
46pub enum SeedPeerError {
47    /// The entry's `did` does not parse.
48    #[error("seed peer did is not a DID: {0}")]
49    NotADid(String),
50    /// The entry's `url` fails the remote RPC endpoint policy.
51    #[error("seed peer {did} has an unusable endpoint: {reason}")]
52    UnusableEndpoint {
53        /// The entry's DID.
54        did: Did,
55        /// The policy's refusal.
56        reason: String,
57    },
58    /// The DID is listed again with a different endpoint or token.
59    #[error("seed peer {0} is listed with conflicting entries")]
60    ConflictingEntries(Did),
61    /// The endpoint is listed again under a different DID.
62    #[error("seed endpoint {0} is listed under two DIDs")]
63    EndpointUnderTwoDids(RemoteRpcEndpoint),
64}
65
66/// How two validated seed peers overlap, ordered by agreement: a verbatim repeat agrees more
67/// than a shared DID, which agrees more than a shared endpoint.
68#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
69enum Overlap {
70    /// Same endpoint claimed for another DID.
71    SameEndpoint,
72    /// Same DID behind another endpoint or token.
73    SameDid,
74    /// Same DID, endpoint and token: one peer listed twice.
75    Verbatim,
76}
77
78/// Validate `peers` as a set: every entry validates, an entry repeated verbatim is merged, and
79/// a DID listed with a different endpoint or token, or an endpoint listed under two DIDs, is
80/// refused as ambiguous, since one endpoint answers as exactly one DID. Endpoint identity is
81/// the full URL: two nodes may share an origin behind path routing, and an entry whose
82/// endpoint answers as another node is refused at dial time by the DID pin. Against the peers
83/// already accepted, the overlap of highest agreement decides.
84pub(crate) fn validate_seed_peers(
85    peers: impl IntoIterator<Item = SeedPeer>,
86) -> Result<Vec<ValidatedSeedPeer>, SeedPeerError> {
87    let mut validated: Vec<ValidatedSeedPeer> = Vec::new();
88    for peer in peers {
89        let peer = ValidatedSeedPeer::try_from(peer)?;
90        match validated
91            .iter()
92            .filter_map(|known| known.overlap(&peer))
93            .max()
94        {
95            Some(Overlap::Verbatim) => continue,
96            Some(Overlap::SameDid) => return Err(SeedPeerError::ConflictingEntries(peer.did)),
97            Some(Overlap::SameEndpoint) => {
98                return Err(SeedPeerError::EndpointUnderTwoDids(peer.endpoint));
99            }
100            None => validated.push(peer),
101        }
102    }
103    Ok(validated)
104}
105
106/// A seed entry that passed validation: a parsed DID and a public HTTP(S) handshake endpoint.
107/// The proof travels as a type, so every dial of a seed peer runs the same checks once, where
108/// the entry enters.
109#[derive(Eq, PartialEq)]
110pub(crate) struct ValidatedSeedPeer {
111    did: Did,
112    endpoint: RemoteRpcEndpoint,
113    api_token: Option<String>,
114}
115
116impl ValidatedSeedPeer {
117    /// DID the endpoint must answer as.
118    pub(crate) fn did(&self) -> Did {
119        self.did
120    }
121
122    /// Validated handshake endpoint.
123    pub(crate) fn endpoint(&self) -> &RemoteRpcEndpoint {
124        &self.endpoint
125    }
126
127    /// Bearer token for a peer that gates its handshake, never logged.
128    pub(crate) fn api_token(&self) -> Option<&str> {
129        self.api_token.as_deref()
130    }
131
132    /// How `other` overlaps with this peer, if at all.
133    fn overlap(&self, other: &Self) -> Option<Overlap> {
134        if self == other {
135            Some(Overlap::Verbatim)
136        } else if self.did == other.did {
137            Some(Overlap::SameDid)
138        } else if self.endpoint == other.endpoint {
139            Some(Overlap::SameEndpoint)
140        } else {
141            None
142        }
143    }
144}
145
146impl std::fmt::Debug for ValidatedSeedPeer {
147    /// Render every field but the bearer token, which is replaced by `[REDACTED]`.
148    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        formatter
150            .debug_struct("ValidatedSeedPeer")
151            .field("did", &self.did)
152            .field("endpoint", &self.endpoint.as_str())
153            .field("api_token", &self.api_token.as_ref().map(|_| "[REDACTED]"))
154            .finish()
155    }
156}
157
158impl TryFrom<SeedPeer> for ValidatedSeedPeer {
159    type Error = SeedPeerError;
160
161    /// Parse the DID and apply the remote RPC endpoint policy to the URL.
162    fn try_from(peer: SeedPeer) -> Result<Self, SeedPeerError> {
163        let did = Did::from_str(peer.did.as_str()).map_err(|_| SeedPeerError::NotADid(peer.did))?;
164        let endpoint = RemoteRpcEndpoint::parse(peer.url.as_str()).map_err(|error| {
165            SeedPeerError::UnusableEndpoint {
166                did,
167                reason: error.to_string(),
168            }
169        })?;
170        Ok(Self {
171            did,
172            endpoint,
173            api_token: peer.api_token,
174        })
175    }
176}
177
178impl TryFrom<ConnectWithSeedRequest> for Seed {
179    type Error = Error;
180
181    fn try_from(req: ConnectWithSeedRequest) -> Result<Self, Error> {
182        let mut peers = Vec::new();
183
184        for peer in req.peers {
185            peers.push(SeedPeer {
186                did: peer.did,
187                url: peer.url,
188                api_token: peer.api_token,
189            });
190        }
191
192        Ok(Seed { peers })
193    }
194}
195
196impl Seed {
197    /// Converts this seed list into the RPC request used by `connectWithSeed`.
198    pub fn into_connect_with_seed_request(self) -> ConnectWithSeedRequest {
199        let mut peers = Vec::new();
200
201        for peer in self.peers {
202            peers.push(rings_rpc::protos::rings_node::SeedPeer {
203                did: peer.did,
204                url: peer.url,
205                api_token: peer.api_token,
206            });
207        }
208
209        ConnectWithSeedRequest { peers }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    /// The `Debug` rendering of a validated seed peer never contains its bearer token.
218    #[test]
219    fn validated_seed_peer_debug_redacts_the_token() {
220        let peer = ValidatedSeedPeer::try_from(SeedPeer {
221            did: Did::from(1).to_string(),
222            url: "https://seed.example.com/".to_string(),
223            api_token: Some("0123456789abcdef".to_string()),
224        })
225        .expect("a token-bearing peer validates");
226        let rendered = format!("{peer:?}");
227        assert!(!rendered.contains("0123456789abcdef"));
228        assert!(rendered.contains("[REDACTED]"));
229    }
230
231    /// A seed entry for `did` at `url`.
232    fn entry(did: Did, url: &str) -> SeedPeer {
233        SeedPeer {
234            did: did.to_string(),
235            url: url.to_string(),
236            api_token: None,
237        }
238    }
239
240    /// Distinct peers validate; a verbatim repeat merges; a DID with two endpoints and an
241    /// endpoint under two DIDs are refused; against several accepted peers the overlap of
242    /// highest agreement names the refusal.
243    #[test]
244    fn seed_peer_sets_merge_repeats_and_refuse_conflicts() {
245        let a = entry(Did::from(1), "https://a.example.com/");
246        let b = entry(Did::from(2), "https://b.example.com/");
247        assert_eq!(
248            validate_seed_peers([a.clone(), b.clone(), a.clone()])
249                .expect("distinct peers validate")
250                .len(),
251            2,
252            "a verbatim repeat is merged"
253        );
254        assert_eq!(
255            validate_seed_peers([a.clone(), entry(Did::from(1), "https://other.example.com/")])
256                .err(),
257            Some(SeedPeerError::ConflictingEntries(Did::from(1)))
258        );
259        assert_eq!(
260            validate_seed_peers([a.clone(), entry(Did::from(3), "https://a.example.com/")]).err(),
261            Some(SeedPeerError::EndpointUnderTwoDids(
262                RemoteRpcEndpoint::parse("https://a.example.com/").expect("a public endpoint")
263            ))
264        );
265        assert_eq!(
266            validate_seed_peers([a, b, entry(Did::from(2), "https://a.example.com/")]).err(),
267            Some(SeedPeerError::ConflictingEntries(Did::from(2))),
268            "a shared DID outranks a shared endpoint"
269        );
270    }
271
272    /// A malformed DID and a non-public endpoint are refused by typed reason.
273    #[test]
274    fn validated_seed_peer_refuses_bad_did_and_local_endpoint() {
275        let entry = |did: &str, url: &str| SeedPeer {
276            did: did.to_string(),
277            url: url.to_string(),
278            api_token: None,
279        };
280        assert_eq!(
281            ValidatedSeedPeer::try_from(entry("not-a-did", "https://seed.example.com/")).err(),
282            Some(SeedPeerError::NotADid("not-a-did".to_string()))
283        );
284        assert!(matches!(
285            ValidatedSeedPeer::try_from(entry(&Did::from(1).to_string(), "http://127.0.0.1:50001/")),
286            Err(SeedPeerError::UnusableEndpoint { did, .. }) if did == Did::from(1)
287        ));
288    }
289
290    #[test]
291    fn seed_debug_output_redacts_remote_api_token() {
292        let secret = "0123456789abcdef0123456789abcdef";
293        let seed = Seed {
294            peers: vec![SeedPeer {
295                did: "did:ring:test".to_string(),
296                url: "https://example.com:50001/".to_string(),
297                api_token: Some(secret.to_string()),
298            }],
299        };
300        let debug = format!("{seed:?}");
301        assert!(!debug.contains(secret));
302        assert!(debug.contains("[REDACTED]"));
303    }
304}