1use 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#[derive(Deserialize, Serialize, Debug)]
15pub struct Seed {
16 pub peers: Vec<SeedPeer>,
18}
19
20#[derive(Clone, Deserialize, Serialize, PartialEq, Eq)]
22pub struct SeedPeer {
23 pub did: String,
25 pub url: String,
27 #[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#[derive(Debug, thiserror::Error, Eq, PartialEq)]
46pub enum SeedPeerError {
47 #[error("seed peer did is not a DID: {0}")]
49 NotADid(String),
50 #[error("seed peer {did} has an unusable endpoint: {reason}")]
52 UnusableEndpoint {
53 did: Did,
55 reason: String,
57 },
58 #[error("seed peer {0} is listed with conflicting entries")]
60 ConflictingEntries(Did),
61 #[error("seed endpoint {0} is listed under two DIDs")]
63 EndpointUnderTwoDids(RemoteRpcEndpoint),
64}
65
66#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
69enum Overlap {
70 SameEndpoint,
72 SameDid,
74 Verbatim,
76}
77
78pub(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#[derive(Eq, PartialEq)]
110pub(crate) struct ValidatedSeedPeer {
111 did: Did,
112 endpoint: RemoteRpcEndpoint,
113 api_token: Option<String>,
114}
115
116impl ValidatedSeedPeer {
117 pub(crate) fn did(&self) -> Did {
119 self.did
120 }
121
122 pub(crate) fn endpoint(&self) -> &RemoteRpcEndpoint {
124 &self.endpoint
125 }
126
127 pub(crate) fn api_token(&self) -> Option<&str> {
129 self.api_token.as_deref()
130 }
131
132 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 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 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 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 #[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 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 #[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 #[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}