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
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// https://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.

//! SAFE App.

#![doc(
    html_logo_url = "https://raw.githubusercontent.com/maidsafe/QA/master/Images/
maidsafe_logo.png",
    html_favicon_url = "http://maidsafe.net/img/favicon.ico",
    test(attr(forbid(warnings)))
)]
// For explanation of lint checks, run `rustc -W help`.
#![deny(unsafe_code)]
#![warn(
    missing_docs,
    trivial_casts,
    trivial_numeric_casts,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications,
    unused_results
)]

// Public exports. See https://github.com/maidsafe/safe_client_libs/wiki/Export-strategy.

// Re-export functions used in FFI so that they are accessible through the Rust API.

pub use safe_core::core_structs::AppKeys;
pub use safe_core::{
    app_container_name, immutable_data, ipc, mdata_info, utils, Client, ClientKeys, CoreError,
    MDataInfo, DIR_TAG, MAIDSAFE_TAG,
};
pub use safe_nd::PubImmutableData;

// Export public app interface.

pub use crate::errors::AppError;
pub use client::AppClient;

pub mod cipher_opt;
pub mod permissions;

/// Utility functions to test apps functionality.
#[cfg(any(test, feature = "testing"))]
pub mod test_utils;

mod client;
pub mod errors;
#[cfg(test)]
mod tests;

use bincode::deserialize;
use futures::{
    channel::{mpsc as futures_mpsc, mpsc::UnboundedSender},
    lock::Mutex,
    Future,
};
use std::sync::Arc;

#[cfg(feature = "mock-network")]
use safe_core::ConnectionManager;
use safe_core::{
    core_structs::{access_container_enc_key, AccessContInfo, AccessContainerEntry},
    crypto::shared_secretbox,
    ipc::{AuthGranted, BootstrapConfig},
    NetworkEvent,
};
use std::collections::HashMap;
use std::pin::Pin;
/// Network observer for diconnection notifications
type AppNetworkDisconnectFuture = Pin<Box<dyn Future<Output = Result<(), ()>> + Sync + Send>>;

/// Handle to an application instance.
pub struct App {
    /// Client to perform the operations against the network
    pub client: AppClient,
    /// Application context, i.e. registered or unregistered app
    pub context: AppContext,
    /// Network disconnection events observer
    pub network_observer: AppNetworkDisconnectFuture,
}

impl App {
    /// Create unregistered app.
    pub async fn unregistered<N>(
        disconnect_notifier: N,
        config: Option<BootstrapConfig>,
    ) -> Result<Self, AppError>
    where
        N: FnMut() + Send + Sync + 'static,
    {
        let (net_tx, network_observer) = Self::setup_network_observer(disconnect_notifier);
        let client = AppClient::unregistered(net_tx, config).await?;
        let context = AppContext::unregistered();
        Ok(Self {
            client,
            context,
            network_observer,
        })
    }

    /// Create registered app.
    pub async fn registered<N>(
        app_id: String,
        auth_granted: AuthGranted,
        disconnect_notifier: N,
    ) -> Result<Self, AppError>
    where
        N: FnMut() + Send + Sync + 'static,
    {
        let (net_tx, network_observer) = Self::setup_network_observer(disconnect_notifier);

        let AuthGranted {
            app_keys,
            access_container_info,
            bootstrap_config,
            ..
        } = auth_granted;
        let enc_key = app_keys.enc_key.clone();
        let owner_key = *app_keys.app_full_id.public_id().owner().public_key();

        let client = AppClient::from_keys(app_keys, owner_key, net_tx, bootstrap_config).await?;
        let context = AppContext::registered(app_id, enc_key, access_container_info);

        Ok(Self {
            client,
            context,
            network_observer,
        })
    }

    fn setup_network_observer<N>(
        mut disconnect_notifier: N,
    ) -> (UnboundedSender<NetworkEvent>, AppNetworkDisconnectFuture)
    where
        N: FnMut() + Send + Sync + 'static,
    {
        let (net_tx, mut net_rx) = futures_mpsc::unbounded();

        let observer = Box::pin(async move {
            if let Ok(Some(NetworkEvent::Disconnected)) = net_rx.try_next() {
                disconnect_notifier();
            };
            Ok(())
        });

        (net_tx, observer)
    }

    /// Allows customising the mock Connection Manager before registering a new account.
    #[cfg(feature = "mock-network")]
    pub fn registered_with_hook<N, F>(
        app_id: String,
        auth_granted: AuthGranted,
        disconnect_notifier: N,
        connection_manager_wrapper_fn: F,
    ) -> Result<Self, AppError>
    where
        N: FnMut() + Send + Sync + 'static,
        F: Fn(ConnectionManager) -> ConnectionManager + 'static,
    {
        let AuthGranted {
            app_keys,
            access_container_info,
            bootstrap_config,
            ..
        } = auth_granted;
        let enc_key = app_keys.enc_key.clone();
        let owner_key = *app_keys.app_full_id.public_id().owner().public_key();

        let (net_tx, network_observer) = Self::setup_network_observer(disconnect_notifier);

        let client = futures::executor::block_on(AppClient::from_keys_with_hook(
            app_keys,
            owner_key,
            net_tx,
            bootstrap_config,
            connection_manager_wrapper_fn,
        ))?;

        let context = AppContext::registered(app_id, enc_key, access_container_info);

        Ok(Self {
            client,
            context,
            network_observer,
        })
    }
}

/// Application context (data associated with the app).
#[derive(Clone)]
pub enum AppContext {
    /// Context of unregistered app.
    Unregistered(Arc<Unregistered>),
    /// Context of registered app.
    Registered(Arc<Registered>),
}

#[allow(missing_docs)]
pub struct Unregistered {}

#[allow(missing_docs)]
pub struct Registered {
    app_id: String,
    sym_enc_key: shared_secretbox::Key,
    access_container_info: AccessContInfo,
    access_info: Mutex<AccessContainerEntry>,
}

impl AppContext {
    fn unregistered() -> Self {
        Self::Unregistered(Arc::new(Unregistered {}))
    }

    fn registered(
        app_id: String,
        sym_enc_key: shared_secretbox::Key,
        access_container_info: AccessContInfo,
    ) -> Self {
        Self::Registered(Arc::new(Registered {
            app_id,
            sym_enc_key,
            access_container_info,
            access_info: Mutex::new(HashMap::new()),
        }))
    }

    /// Symmetric encryption/decryption key.
    pub fn sym_enc_key(&self) -> Result<&shared_secretbox::Key, AppError> {
        Ok(&self.as_registered()?.sym_enc_key)
    }

    /// Refresh access info by fetching it from the network.
    pub async fn refresh_access_info(&self, client: &AppClient) -> Result<(), AppError> {
        let reg = Arc::clone(self.as_registered()?);
        refresh_access_info(reg, client).await
    }

    /// Fetch a list of containers that this app has access to
    pub async fn get_access_info(
        &self,
        client: &AppClient,
    ) -> Result<AccessContainerEntry, AppError> {
        let reg: Arc<Registered> = self.as_registered()?.clone();
        // let reg = Arc::clone(self.as_registered()?);

        fetch_access_info(Arc::clone(&reg), client).await?;
        let access_info = reg.access_info.lock().await;
        Ok(access_info.clone())
    }

    fn as_registered(&self) -> Result<&Arc<Registered>, AppError> {
        match *self {
            Self::Registered(ref a) => Ok(a),
            Self::Unregistered(_) => Err(AppError::OperationForbidden),
        }
    }
}

async fn refresh_access_info(context: Arc<Registered>, client: &AppClient) -> Result<(), AppError> {
    let entry_key = access_container_enc_key(
        &context.app_id,
        &context.sym_enc_key,
        &context.access_container_info.nonce,
    )?;

    let value = client
        .get_seq_mdata_value(
            context.access_container_info.id,
            context.access_container_info.tag,
            entry_key,
        )
        .await?;

    let encoded = utils::symmetric_decrypt(&value.data, &context.sym_enc_key)?;
    let decoded = deserialize(&encoded)?;

    *context.access_info.lock().await = decoded;

    Ok(())
}

async fn fetch_access_info(context: Arc<Registered>, client: &AppClient) -> Result<(), AppError> {
    if context.access_info.lock().await.is_empty() {
        refresh_access_info(context, client).await
    } else {
        Ok(())
    }
}