ockam_api 0.48.0

Ockam's request-response API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use miette::IntoDiagnostic;
use std::sync::Arc;
use std::time::Duration;

use ockam::compat::sync::Mutex;
use ockam::identity::Identifier;
use ockam::remote::{RemoteRelay, RemoteRelayOptions};
use ockam::Result;
use ockam_core::api::{Error, Request, RequestHeader, Response};
use ockam_core::errcode::{Kind, Origin};
use ockam_core::{async_trait, Address, AsyncTryClone};
use ockam_multiaddr::proto::Project;
use ockam_multiaddr::{MultiAddr, Protocol};
use ockam_node::tokio::time::timeout;
use ockam_node::Context;

use crate::error::ApiError;
use crate::nodes::connection::Connection;
use crate::nodes::models::relay::{CreateRelay, RelayInfo};
use crate::nodes::models::secure_channel::{
    CreateSecureChannelRequest, CreateSecureChannelResponse,
};
use crate::nodes::service::in_memory_node::InMemoryNode;
use crate::nodes::BackgroundNode;
use crate::session::sessions::{Replacer, Session};
use crate::session::sessions::{MAX_CONNECT_TIME, MAX_RECOVERY_TIME};

use super::{NodeManager, NodeManagerWorker};

impl NodeManagerWorker {
    pub async fn create_relay(
        &self,
        ctx: &Context,
        req: &RequestHeader,
        create_relay: CreateRelay,
    ) -> Result<Response<RelayInfo>, Response<Error>> {
        let CreateRelay {
            address,
            alias,
            at_rust_node,
            authorized,
        } = create_relay;
        match self
            .node_manager
            .create_relay(ctx, &address, alias, at_rust_node, authorized)
            .await
        {
            Ok(body) => Ok(Response::ok(req).body(body)),
            Err(err) => Err(Response::internal_error(
                req,
                &format!("Failed to create relay: {}", err),
            )),
        }
    }

    /// This function removes an existing relay based on its remote address
    pub async fn delete_relay(
        &self,
        ctx: &Context,
        req: &RequestHeader,
        remote_address: &str,
    ) -> Result<Response<Option<RelayInfo>>, Response<Error>> {
        debug!(%remote_address , "Handling DeleteRelay request");

        match self
            .node_manager
            .delete_relay_impl(ctx, remote_address)
            .await
        {
            Ok(body) => Ok(Response::ok(req).body(body)),
            Err(err) => match err.code().kind {
                Kind::NotFound => Err(Response::not_found(
                    req,
                    &format!("Relay with address {} not found.", remote_address),
                )),
                _ => Err(Response::internal_error(
                    req,
                    &format!("Failed to delete relay at {}: {}", remote_address, err),
                )),
            },
        }
    }

    pub async fn show_relay(
        &self,
        req: &RequestHeader,
        remote_address: &str,
    ) -> Result<Response<Option<RelayInfo>>, Response<Error>> {
        self.node_manager.show_relay(req, remote_address).await
    }

    pub async fn get_relays(
        &self,
        req: &RequestHeader,
    ) -> Result<Response<Vec<RelayInfo>>, Response<Error>> {
        debug!("Handling GetRelays request");
        Ok(Response::ok(req).body(self.node_manager.get_relays().await))
    }
}

impl NodeManager {
    /// This function returns a representation of the relays currently
    /// registered on this node
    pub async fn get_relays(&self) -> Vec<RelayInfo> {
        let relays = self
            .registry
            .relays
            .entries()
            .await
            .iter()
            .map(|(_, registry_info)| RelayInfo::from(registry_info.to_owned()))
            .collect();
        trace!(?relays, "Relays retrieved");
        relays
    }

    /// Create a new Relay
    /// The Connection encapsulates the list of workers required on the relay route.
    /// This route is monitored in the `InMemoryNode` and the workers are restarted if necessary
    /// when the route is unresponsive
    pub async fn create_relay(
        &self,
        ctx: &Context,
        connection: Connection,
        at_rust_node: bool,
        alias: Option<String>,
    ) -> Result<RelayInfo> {
        let route = connection.route(self.tcp_transport()).await?;
        let options = RemoteRelayOptions::new();

        let relay = if at_rust_node {
            if let Some(alias) = alias {
                RemoteRelay::create_static_without_heartbeats(ctx, route, alias, options).await
            } else {
                RemoteRelay::create(ctx, route, options).await
            }
        } else if let Some(alias) = alias {
            RemoteRelay::create_static(ctx, route, alias, options).await
        } else {
            RemoteRelay::create(ctx, route, options).await
        };

        match relay {
            Ok(info) => {
                let registry_info = info.clone();
                let registry_remote_address = registry_info.remote_address().to_string();
                let relay_info = RelayInfo::from(info);
                self.registry
                    .relays
                    .insert(registry_remote_address, registry_info)
                    .await;

                debug!(
                    forwarding_route = %relay_info.forwarding_route(),
                    remote_address = %relay_info.remote_address_ma()?,
                    "CreateRelay request processed, sending back response"
                );
                Ok(relay_info)
            }
            Err(err) => {
                error!(?err, "Failed to create relay");
                Err(err)
            }
        }
    }

    /// Delete a relay.
    ///
    /// This function removes a relay from the node registry and stops the relay worker.
    pub async fn delete_relay_impl(
        &self,
        ctx: &Context,
        remote_address: &str,
    ) -> Result<Option<RelayInfo>, ockam::Error> {
        if let Some(relay_to_delete) = self.registry.relays.remove(remote_address).await {
            debug!(%remote_address, "Successfully removed relay from node registry");

            match ctx
                .stop_worker(relay_to_delete.worker_address().clone())
                .await
            {
                Ok(_) => {
                    debug!(%remote_address, "Successfully stopped relay");
                    Ok(Some(RelayInfo::from(relay_to_delete.to_owned())))
                }
                Err(err) => {
                    error!(%remote_address, ?err, "Failed to delete relay from node registry");
                    Err(err)
                }
            }
        } else {
            error!(%remote_address, "Relay not found in the node registry");
            Err(ockam::Error::new(
                Origin::Api,
                Kind::NotFound,
                format!("Relay with address {} not found.", remote_address),
            ))
        }
    }

    /// This function finds an existing relay and returns its configuration
    pub(super) async fn show_relay(
        &self,
        req: &RequestHeader,
        remote_address: &str,
    ) -> Result<Response<Option<RelayInfo>>, Response<Error>> {
        debug!("Handling ShowRelay request");
        if let Some(relay) = self.registry.relays.get(remote_address).await {
            debug!(%remote_address, "Relay not found in node registry");
            Ok(Response::ok(req).body(Some(RelayInfo::from(relay.to_owned()))))
        } else {
            error!(%remote_address, "Relay not found in the node registry");
            Err(Response::not_found(
                req,
                &format!("Relay with address {} not found.", remote_address),
            ))
        }
    }
}

impl InMemoryNode {
    pub async fn create_relay(
        &self,
        ctx: &Context,
        address: &MultiAddr,
        alias: Option<String>,
        at_rust_node: bool,
        authorized: Option<Identifier>,
    ) -> Result<RelayInfo> {
        debug!(addr = %address, alias = ?alias, at_rust_node = ?at_rust_node, "Handling CreateRelay request");
        let connection_ctx = Arc::new(ctx.async_try_clone().await?);
        let connection = self
            .make_connection(
                connection_ctx.clone(),
                &address.clone(),
                None,
                authorized.clone(),
                None,
                None,
            )
            .await?;
        connection.add_default_consumers(connection_ctx.clone());

        // Add all Hop workers as consumers for Demo purposes
        // Production nodes should not run any Hop workers
        for hop in self.registry.hop_services.keys().await {
            connection.add_consumer(connection_ctx.clone(), &hop);
        }

        let relay = self
            .node_manager
            .create_relay(
                ctx,
                connection.clone(),
                at_rust_node,
                alias.clone().map(|a| a.to_string()),
            )
            .await?;

        if !at_rust_node && !connection.transport_route().is_empty() {
            let ping_route = connection.transport_route().clone();
            let repl = Self::relay_replacer(
                self.node_manager.clone(),
                Arc::new(ctx.async_try_clone().await?),
                connection,
                address.clone(),
                alias,
                authorized,
            );
            let mut session = Session::new(ping_route, format!("relay-{}", relay.remote_address()));
            session.set_replacer(repl);
            self.add_session(session);
        };
        Ok(relay)
    }

    pub async fn delete_relay(
        &self,
        ctx: &Context,
        remote_address: &str,
    ) -> Result<Option<RelayInfo>, ockam::Error> {
        if let Some(relay) = self.registry.relays.remove(remote_address).await {
            let session_id = format!("relay-{}", relay.remote_address());
            self.remove_session(&session_id);
        }
        self.delete_relay_impl(ctx, remote_address).await
    }

    /// Create a session replacer.
    ///
    /// This returns a function that accepts the previous ping address (e.g.
    /// the secure channel worker address) and constructs the whole route
    /// again.
    fn relay_replacer(
        node_manager: Arc<NodeManager>,
        ctx: Arc<Context>,
        connection: Connection,
        addr: MultiAddr,
        alias: Option<String>,
        authorized: Option<Identifier>,
    ) -> Replacer {
        let connection_arc = Arc::new(Mutex::new(connection));
        let node_manager = node_manager.clone();
        Box::new(move |prev_route| {
            let ctx = ctx.clone();
            let addr = addr.clone();
            let alias = alias.clone();
            let authorized = authorized.clone();
            let connection_arc = connection_arc.clone();
            let previous_connection = connection_arc.lock().unwrap().clone();
            let node_manager = node_manager.clone();

            Box::pin(async move {
                debug!(%prev_route, %addr, "creating new remote relay");

                let f = async {
                    for encryptor in &previous_connection.secure_channel_encryptors {
                        if let Err(error) = node_manager
                            .delete_secure_channel(&ctx.clone(), encryptor)
                            .await
                        {
                            //not much we can do about it
                            debug!("cannot delete secure channel `{encryptor}`: {error}");
                        }
                    }
                    if let Some(tcp_connection) = previous_connection.tcp_connection.as_ref() {
                        if let Err(error) = node_manager
                            .tcp_transport
                            .disconnect(tcp_connection.sender_address().clone())
                            .await
                        {
                            debug!("cannot stop tcp worker `{tcp_connection}`: {error}");
                        }
                    }

                    let connection = node_manager
                        .make_connection(
                            ctx.clone(),
                            &addr,
                            None,
                            authorized,
                            None,
                            Some(MAX_CONNECT_TIME),
                        )
                        .await?;
                    connection.add_default_consumers(ctx.clone());
                    *connection_arc.lock().unwrap() = connection.clone();

                    let route = connection.route(node_manager.tcp_transport()).await?;

                    let options = RemoteRelayOptions::new();
                    if let Some(alias) = &alias {
                        RemoteRelay::create_static(&ctx, route, alias, options).await?;
                    } else {
                        RemoteRelay::create(&ctx, route, options).await?;
                    }
                    Ok(connection.transport_route())
                };
                match timeout(MAX_RECOVERY_TIME, f).await {
                    Err(_) => {
                        warn!(%addr, "timeout creating new remote relay");
                        Err(ApiError::core("timeout"))
                    }
                    Ok(Err(e)) => {
                        warn!(%addr, err = %e, "error creating new remote relay");
                        Err(e)
                    }
                    Ok(Ok(a)) => Ok(a),
                }
            })
        })
    }
}

#[async_trait]
pub trait Relays {
    async fn create_relay(
        &self,
        ctx: &Context,
        address: &MultiAddr,
        alias: Option<String>,
        authorized: Option<Identifier>,
    ) -> miette::Result<RelayInfo>;
}

#[async_trait]
impl Relays for BackgroundNode {
    async fn create_relay(
        &self,
        ctx: &Context,
        address: &MultiAddr,
        alias: Option<String>,
        authorized: Option<Identifier>,
    ) -> miette::Result<RelayInfo> {
        let at_rust_node = !address.starts_with(Project::CODE);
        let body = CreateRelay::new(address.clone(), alias, at_rust_node, authorized);
        self.ask(ctx, Request::post("/node/forwarder").body(body))
            .await
    }
}

#[async_trait]
pub trait SecureChannelsCreation {
    async fn create_secure_channel(
        &self,
        ctx: &Context,
        addr: &MultiAddr,
        authorized: Identifier,
        identity_name: Option<String>,
        credential_name: Option<String>,
        timeout: Option<Duration>,
    ) -> miette::Result<Address>;
}

#[async_trait]
impl SecureChannelsCreation for InMemoryNode {
    async fn create_secure_channel(
        &self,
        ctx: &Context,
        addr: &MultiAddr,
        authorized: Identifier,
        identity_name: Option<String>,
        credential_name: Option<String>,
        timeout: Option<Duration>,
    ) -> miette::Result<Address> {
        self.node_manager
            .create_secure_channel(
                ctx,
                addr.clone(),
                identity_name,
                Some(vec![authorized]),
                credential_name,
                timeout,
            )
            .await
            .into_diagnostic()
            .map(|sc| sc.encryptor_address().clone())
    }
}

#[async_trait]
impl SecureChannelsCreation for BackgroundNode {
    async fn create_secure_channel(
        &self,
        ctx: &Context,
        addr: &MultiAddr,
        authorized: Identifier,
        identity_name: Option<String>,
        credential_name: Option<String>,
        timeout: Option<Duration>,
    ) -> miette::Result<Address> {
        let body = CreateSecureChannelRequest::new(
            addr,
            Some(vec![authorized]),
            identity_name,
            credential_name,
        );
        let request = Request::post("/node/secure_channel").body(body);
        let response: CreateSecureChannelResponse = if let Some(t) = timeout {
            self.ask_with_timeout(ctx, request, t).await?
        } else {
            self.ask(ctx, request).await?
        };
        Ok(response.addr)
    }
}