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
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use wildland_corex::{utils, MnemonicPhrase};

use super::cargo_user::CargoUser;
use crate::errors::{CreateMnemonicError, UserCreationError, UserRetrievalError};
use crate::user::{generate_random_mnemonic, CreateUserInput, UserService};

#[derive(Clone)]
pub struct MnemonicPayload(MnemonicPhrase);

/// Wrapper to check the mnemonic.
/// Accepts string. Returns Ok if the mnemonic is valid or Err otherwise
/// throws [`CreateMnemonicError`] if the mnemonic is invalid
pub fn check_phrase_mnemonic(phrase: &str) -> Result<(), CreateMnemonicError> {
    match utils::new_mnemonic_from_phrase(phrase) {
        Ok(_) => Ok(()),
        Err(_) => Err(CreateMnemonicError::InvalidMnemonicWords),
    }
}

impl MnemonicPayload {
    pub fn stringify(&self) -> String {
        self.0.join(" ")
    }

    pub fn get_vec(&self) -> Vec<String> {
        self.0.clone().into()
    }
}

impl From<MnemonicPhrase> for MnemonicPayload {
    fn from(mnemonic: MnemonicPhrase) -> Self {
        Self(mnemonic)
    }
}

/// User management API
///
/// [`CargoUser`] can be created with the following methods:
/// - [`UserApi::create_user_from_entropy`]
/// - [`UserApi::create_user_from_mnemonic`]
///
///  Creating a new user means:
/// - checking if one does not exist yet
/// - generating forest identity
/// - generating device identity
/// - saving forest in CatLib
/// - saving forest uuid (CatLib key) in LSS
/// - saving forest and device identities (keypairs) in LSS
///
#[derive(Clone)]
pub struct UserApi {
    user_service: UserService,
}

impl UserApi {
    pub(crate) fn new(user_service: UserService) -> Self {
        Self { user_service }
    }

    #[tracing::instrument(level = "debug", skip_all)]
    pub fn generate_mnemonic(&self) -> Result<MnemonicPayload, CreateMnemonicError> {
        tracing::trace!("generating mnemonic");
        generate_random_mnemonic()
            .map_err(|_| CreateMnemonicError::InvalidMnemonicWords)
            .map(MnemonicPayload::from)
    }

    /// Creates [`MnemonicPayload`] basing on a vector of words. The result may be used for creation
    /// User with [`UserApi::create_user_from_mnemonic`].
    ///
    /// It validates provided words
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn create_mnemonic_from_vec(
        &self,
        words: Vec<String>,
    ) -> Result<MnemonicPayload, CreateMnemonicError> {
        tracing::trace!("creating mnemonic from vec");
        check_phrase_mnemonic(words.join(" ").as_str())?;
        Ok(MnemonicPayload(
            MnemonicPhrase::try_from(words)
                .map_err(|_| CreateMnemonicError::InvalidMnemonicWords)?,
        ))
    }

    /// Creates [`MnemonicPayload`] basing on a space separated 12-word string. The result may be used for creation
    /// User with [`UserApi::create_user_from_mnemonic`].
    ///
    /// It validates provided words
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn create_mnemonic_from_string(
        &self,
        words: String,
    ) -> Result<MnemonicPayload, CreateMnemonicError> {
        tracing::trace!("creating mnemonic from vec");
        check_phrase_mnemonic(words.as_str())?;
        Ok(MnemonicPayload(
            MnemonicPhrase::try_from(words.split(' ').map(|w| w.to_owned()).collect::<Vec<_>>())
                .map_err(|_| CreateMnemonicError::InvalidMnemonicWords)?,
        ))
    }

    /// Creates user from entropy.
    ///
    /// Assumes high quality entropy of arbitrary length (>= 32 bytes) what is validated.
    #[tracing::instrument(level = "debug", skip_all)]
    pub fn create_user_from_entropy(
        &self,
        entropy: Vec<u8>,
        device_name: String,
    ) -> Result<CargoUser, UserCreationError> {
        tracing::debug!("creating new user");
        self.user_service
            .create_user(CreateUserInput::Entropy(entropy), device_name)
    }

    #[tracing::instrument(level = "debug", skip_all)]
    pub fn create_user_from_mnemonic(
        &self,
        mnemonic: &MnemonicPayload,
        device_name: String,
    ) -> Result<CargoUser, UserCreationError> {
        tracing::debug!("creating new user");
        self.user_service.create_user(
            CreateUserInput::Mnemonic(Box::new(mnemonic.0.clone())),
            device_name,
        )
    }

    /// Gets user if it exists
    ///
    pub fn get_user(&self) -> Result<CargoUser, UserRetrievalError> {
        tracing::debug!("getting user");
        let user = self.user_service.get_user()?;
        match user {
            Some(user) => Ok(user),
            None => Err(UserRetrievalError::UserNotFound),
        }
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use wildland_corex::catlib_service::CatLibService;
    use wildland_corex::{ContainerManager, LocalSecureStorage, LssService};
    use wildland_databases::redis_client::RedisClient;

    use super::UserApi;
    use crate::api::cargo_lib::DfsApi;
    use crate::api::config::FoundationStorageApiConfig;
    use crate::errors::UserRetrievalError;
    use crate::user::UserService;
    use crate::utils::test::{
        catlib_service,
        container_manager,
        dfs_api_mock,
        lss_stub,
        multidevice_client,
    };

    #[rstest]
    fn create_mnemonic_from_string_with_valid_words_should_succeed(
        catlib_service: CatLibService,
        multidevice_client: &RedisClient,
        container_manager: ContainerManager,
        lss_stub: Box<dyn LocalSecureStorage>,
        dfs_api_mock: DfsApi,
    ) {
        let api = UserApi::new(UserService::new(
            LssService::new(lss_stub),
            catlib_service,
            multidevice_client.clone(),
            FoundationStorageApiConfig::default(),
            container_manager,
            dfs_api_mock,
        ));
        let words = "wise exile kingdom cabbage improve also ridge fortune when joke market argue";

        assert!(api.create_mnemonic_from_string(words.to_owned()).is_ok());
    }

    #[rstest]
    fn create_mnemonic_from_string_with_invalid_words_should_return_err(
        catlib_service: CatLibService,
        multidevice_client: &RedisClient,
        container_manager: ContainerManager,
        lss_stub: Box<dyn LocalSecureStorage>,
        dfs_api_mock: DfsApi,
    ) {
        let api = UserApi::new(UserService::new(
            LssService::new(lss_stub),
            catlib_service,
            multidevice_client.clone(),
            FoundationStorageApiConfig::default(),
            container_manager,
            dfs_api_mock,
        ));
        let words =
            "wise exile kingdom cabbage improve also ridge fortune when joke market invalid_word";

        assert!(api.create_mnemonic_from_string(words.to_owned()).is_err());
    }

    #[rstest]
    fn create_mnemonic_from_vec_with_valid_words_should_succeed(
        catlib_service: CatLibService,
        multidevice_client: &RedisClient,
        container_manager: ContainerManager,
        lss_stub: Box<dyn LocalSecureStorage>,
        dfs_api_mock: DfsApi,
    ) {
        let api = UserApi::new(UserService::new(
            LssService::new(lss_stub),
            catlib_service,
            multidevice_client.clone(),
            FoundationStorageApiConfig::default(),
            container_manager,
            dfs_api_mock,
        ));
        let words = "wise exile kingdom cabbage improve also ridge fortune when joke market argue";

        assert!(api
            .create_mnemonic_from_vec(words.split(' ').map(ToOwned::to_owned).collect::<Vec<_>>())
            .is_ok());
    }

    #[rstest]
    fn create_mnemonic_from_vec_with_invalid_words_should_return_err(
        catlib_service: CatLibService,
        multidevice_client: &RedisClient,
        container_manager: ContainerManager,
        lss_stub: Box<dyn LocalSecureStorage>,
        dfs_api_mock: DfsApi,
    ) {
        let api = UserApi::new(UserService::new(
            LssService::new(lss_stub),
            catlib_service,
            multidevice_client.clone(),
            FoundationStorageApiConfig::default(),
            container_manager,
            dfs_api_mock,
        ));
        let words =
            "wise exile kingdom cabbage improve also ridge fortune when joke market invalid_word";

        assert!(api
            .create_mnemonic_from_vec(words.split(' ').map(ToOwned::to_owned).collect::<Vec<_>>())
            .is_err());
    }

    #[rstest]
    fn get_user_should_return_none_if_it_does_not_exist(
        catlib_service: CatLibService,
        multidevice_client: &RedisClient,
        container_manager: ContainerManager,
        lss_stub: Box<dyn LocalSecureStorage>,
        dfs_api_mock: DfsApi,
    ) {
        let lss_service = LssService::new(lss_stub);
        let user_service = UserService::new(
            lss_service,
            catlib_service,
            multidevice_client.clone(),
            FoundationStorageApiConfig::default(),
            container_manager,
            dfs_api_mock,
        );
        let user_api = UserApi::new(user_service);

        let user_result = user_api.get_user();
        assert_eq!(
            user_result.unwrap_err(),
            UserRetrievalError::ForestNotFound("Forest identity keypair not found".to_owned())
        )
    }

    #[rstest]
    fn create_user_should_return_user_structure(
        catlib_service: CatLibService,
        multidevice_client: &RedisClient,
        container_manager: ContainerManager,
        lss_stub: Box<dyn LocalSecureStorage>,
        dfs_api_mock: DfsApi,
    ) {
        let lss_service = LssService::new(lss_stub);
        let user_service = UserService::new(
            lss_service,
            catlib_service,
            multidevice_client.clone(),
            FoundationStorageApiConfig::default(),
            container_manager,
            dfs_api_mock,
        );
        let user_api = UserApi::new(user_service);

        let mnemonic = user_api.generate_mnemonic().unwrap();
        let device_name = "device name".to_string();
        let user = user_api
            .create_user_from_mnemonic(&mnemonic, device_name.clone())
            .unwrap();

        assert_eq!(user.this_device(), device_name);
        assert_eq!(user.all_devices(), [device_name]);
    }

    #[rstest]
    fn get_user_should_return_some_if_it_was_created(
        catlib_service: CatLibService,
        multidevice_client: &RedisClient,
        container_manager: ContainerManager,
        lss_stub: Box<dyn LocalSecureStorage>,
        dfs_api_mock: DfsApi,
    ) {
        let lss_service = LssService::new(lss_stub);
        let user_service = UserService::new(
            lss_service,
            catlib_service,
            multidevice_client.clone(),
            FoundationStorageApiConfig::default(),
            container_manager,
            dfs_api_mock,
        );
        let user_api = UserApi::new(user_service);

        let mnemonic = user_api.generate_mnemonic().unwrap();
        let device_name = "device name".to_string();
        let _ = user_api
            .create_user_from_mnemonic(&mnemonic, device_name.clone())
            .unwrap();

        let user = user_api.get_user().unwrap();
        assert_eq!(user.this_device(), device_name);
        assert_eq!(user.all_devices(), [device_name]);
    }
}