1use alloc::collections::BTreeMap;
4use alloc::string::String;
5use alloc::sync::Arc;
6
7use alloc::vec::Vec;
8
9use crate::connect::proto::{
10 AccessToken, ConnectError, ConnectionDetails, Deployment, EndpointDescription, HmacBinding,
11 NodeId, PairingAccepted, PairingAttemptId, PairingErrorMessage, PairingRefused, PairingRequest,
12 PairingServer,
13};
14use crate::connect::tls::Fingerprint;
15use crate::types::Timestamp;
16
17use super::store::{PairedNode, PairingKey, Store};
18
19#[derive(Debug, Clone)]
29pub struct CommunicationServer {
30 pub initiate_session_url: String,
33 pub ca: Fingerprint,
36}
37
38#[derive(Debug, Clone, Default)]
40pub struct Finalized {
41 pub paired: Option<PairingKey>,
43 pub displaced: Vec<PairingKey>,
48}
49
50pub struct PairingService {
59 store: Arc<dyn Store>,
60 attempts: std::sync::Mutex<BTreeMap<NodeId, Arc<tokio::sync::Mutex<PairingServer>>>>,
62 endpoint: EndpointDescription,
63 binding: HmacBinding,
67 communication: Option<CommunicationServer>,
69}
70
71impl core::fmt::Debug for PairingService {
72 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
73 f.debug_struct("PairingService")
74 .field("endpoint", &self.endpoint)
75 .field("binding", &self.binding)
76 .finish_non_exhaustive()
77 }
78}
79
80impl PairingService {
81 #[must_use]
83 pub fn lan(
88 store: Arc<dyn Store>,
89 mut endpoint: EndpointDescription,
90 leaf: Fingerprint,
91 ) -> Self {
92 endpoint.deployment.get_or_insert(Deployment::Lan);
93 Self {
94 store,
95 attempts: std::sync::Mutex::new(BTreeMap::new()),
96 endpoint,
97 binding: leaf.binding(),
98 communication: None,
99 }
100 }
101
102 #[must_use]
104 pub fn wan(
107 store: Arc<dyn Store>,
108 mut endpoint: EndpointDescription,
109 domain: impl Into<String>,
110 ) -> Self {
111 endpoint.deployment.get_or_insert(Deployment::Wan);
112 Self {
113 store,
114 attempts: std::sync::Mutex::new(BTreeMap::new()),
115 endpoint,
116 binding: HmacBinding::DomainName(domain.into()),
117 communication: None,
118 }
119 }
120
121 #[must_use]
126 pub fn as_communication_server(mut self, communication: CommunicationServer) -> Self {
127 self.communication = Some(communication);
128 self
129 }
130
131 #[must_use]
133 pub fn store(&self) -> &Arc<dyn Store> {
134 &self.store
135 }
136
137 #[must_use]
139 pub fn endpoint(&self) -> &EndpointDescription {
140 &self.endpoint
141 }
142
143 fn target(&self, request: &PairingRequest) -> Result<NodeId, ConnectError> {
148 match (&request.node_id, &request.node_id_alias) {
149 (Some(_), Some(_)) => Err(refused(PairingErrorMessage::ParsingError)),
150 (Some(id), None) => self
151 .store
152 .node(*id)
153 .map(|n| n.id)
154 .ok_or_else(|| refused(PairingErrorMessage::NodeNotFound)),
155 (None, Some(alias)) => self
156 .store
157 .resolve_alias(alias)
158 .ok_or_else(|| refused(PairingErrorMessage::NodeNotFound)),
159 (None, None) => self
160 .store
161 .sole_node()
162 .ok_or_else(|| refused(PairingErrorMessage::NoNodeIdProvided)),
163 }
164 }
165
166 fn machine(
167 &self,
168 node: NodeId,
169 ) -> Result<Arc<tokio::sync::Mutex<PairingServer>>, ConnectError> {
170 let description = self
171 .store
172 .node(node)
173 .ok_or_else(|| refused(PairingErrorMessage::NodeNotFound))?;
174 let mut attempts = self
175 .attempts
176 .lock()
177 .map_err(|_| refused(PairingErrorMessage::Other))?;
178 Ok(attempts
179 .entry(node)
180 .or_insert_with(|| {
181 Arc::new(tokio::sync::Mutex::new(PairingServer::new(
182 description,
183 self.endpoint.clone(),
184 self.binding.clone(),
185 )))
186 })
187 .clone())
188 }
189
190 pub fn request_pairing(
204 &self,
205 request: &PairingRequest,
206 server_nonce: &[u8],
207 attempt_id: PairingAttemptId,
208 now: Timestamp,
209 ) -> Result<(NodeId, Timestamp, PairingAccepted), ConnectError> {
210 let node = self.target(request)?;
211 let token = self
212 .store
213 .pairing_token(node, now)
214 .ok_or_else(|| refused(PairingErrorMessage::NoValidPairingTokenOnPairingServer))?;
215
216 let machine = self.machine(node)?;
217 let Ok(mut guard) = machine.try_lock() else {
220 return Err(ConnectError::RateLimited);
221 };
222 let (send_after, accepted) =
223 guard.request_pairing(request, &token, server_nonce, attempt_id, now)?;
224 Ok((node, send_after, accepted))
225 }
226
227 pub async fn request_connection_details(
230 &self,
231 node: NodeId,
232 bearer: &str,
233 response: &str,
234 now: Timestamp,
235 ) -> Result<ConnectionDetails, ConnectError> {
236 let machine = self.machine(node)?;
237 let mut guard = machine.lock().await;
238 if !guard.authenticates(bearer) {
239 return Err(ConnectError::NotPaired);
240 }
241 guard.verify_client(response, now)?;
242 let communication = self
243 .communication
244 .as_ref()
245 .ok_or_else(|| refused(PairingErrorMessage::IncompatibleCommunicationProtocols))?;
246 let mut entropy = [0u8; 32];
247 super::fill_random(&mut entropy).map_err(|_| refused(PairingErrorMessage::Other))?;
248 let details = ConnectionDetails::new(
249 communication.initiate_session_url.clone(),
250 AccessToken::from_entropy(&entropy)?,
251 )
252 .with_ca_fingerprint(communication.ca.as_bytes());
253 guard.connection_details(details, now)
254 }
255
256 pub async fn post_connection_details(
258 &self,
259 node: NodeId,
260 bearer: &str,
261 response: &str,
262 details: ConnectionDetails,
263 now: Timestamp,
264 ) -> Result<(), ConnectError> {
265 let machine = self.machine(node)?;
266 let mut guard = machine.lock().await;
267 if !guard.authenticates(bearer) {
268 return Err(ConnectError::NotPaired);
269 }
270 guard.verify_client(response, now)?;
271 guard.accept_connection_details(details, now)
272 }
273
274 pub async fn finalize(
276 &self,
277 node: NodeId,
278 bearer: &str,
279 success: bool,
280 now: Timestamp,
281 ) -> Result<Finalized, ConnectError> {
282 let machine = self.machine(node)?;
283 let mut guard = machine.lock().await;
284 if !guard.authenticates(bearer) {
285 return Err(ConnectError::NotPaired);
286 }
287 let pairing = guard.finalize(crate::connect::proto::FinalizePairing { success }, now)?;
288 drop(guard);
289
290 let mut finalized = Finalized::default();
291 let Some(pairing) = pairing else {
292 return Ok(finalized);
293 };
294 let key = PairingKey {
295 local: pairing.local,
296 remote: pairing.remote.id,
297 };
298 if self.store.paired(key).is_some() {
300 finalized.displaced.push(key);
301 }
302 let local_role = self.store.node(pairing.local).map(|n| n.role);
303 self.store.pair(PairedNode {
304 local: pairing.local,
305 remote: pairing.remote.clone(),
306 tokens: crate::connect::proto::TokenStore::new(pairing.details.access_token.clone()),
307 details: Some(pairing.details),
308 revoked: false,
309 });
310 finalized.paired = Some(key);
311 if local_role == Some(crate::connect::proto::Role::Rm) {
317 for previous in self.store.pairings_of(pairing.local) {
318 if previous != key {
319 crate::trace::event!(
320 info,
321 node = %pairing.local,
322 unpaired = %previous.remote,
323 "a Resource Manager pairs with one CEM at a time"
324 );
325 self.store.unpair(previous);
326 finalized.displaced.push(previous);
327 }
328 }
329 }
330 Ok(finalized)
331 }
332}
333
334fn refused(message: PairingErrorMessage) -> ConnectError {
335 ConnectError::Refused(PairingRefused {
336 error_message: message,
337 additional_info: None,
338 })
339}