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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! File system paths for application level folders
//! and user-specific account folders.
use crate::{Error, Result};
use app_dirs2::{get_app_root, AppDataType, AppInfo};
#[cfg(feature = "audit")]
use async_once_cell::OnceCell;
use once_cell::sync::Lazy;
use std::{
    path::{Path, PathBuf},
    sync::RwLock,
};

use crate::{
    constants::{
        ACCOUNT_EVENTS, APP_AUTHOR, APP_NAME, AUDIT_FILE_NAME, DEVICE_EVENTS,
        DEVICE_FILE, EVENT_LOG_EXT, FILES_DIR, FILE_EVENTS, IDENTITY_DIR,
        JSON_EXT, LOCAL_DIR, LOGS_DIR, PREFERENCES_FILE, REMOTES_FILE,
        REMOTE_DIR, TRANSFERS_FILE, VAULTS_DIR, VAULT_EXT,
    },
    vault::{secret::SecretId, VaultId},
    vfs,
};

#[cfg(feature = "audit")]
use tokio::sync::Mutex;

#[cfg(feature = "audit")]
use crate::audit::{AuditEvent, AuditLogFile, AuditProvider};

const APP_INFO: AppInfo = AppInfo {
    name: APP_NAME,
    author: APP_AUTHOR,
};

static DATA_DIR: Lazy<RwLock<Option<PathBuf>>> =
    Lazy::new(|| RwLock::new(None));

#[cfg(feature = "audit")]
static AUDIT_LOG: OnceCell<Mutex<AuditLogFile>> = OnceCell::new();

/// File system paths.
///
/// Clients and servers may be configured to run on the same machine
/// and point to the same data directory so different prefixes are
/// used to distinguish.
///
/// Clients write to a `local` directory whilst servers write to a
/// `remote` directory.
///
/// Several functions require a user identifier and will panic if
/// a user identifier has not been set, see the function documentation
/// for details.
#[derive(Default, Debug, Clone)]
pub struct Paths {
    /// User identifier.
    user_id: String,
    /// Top-level documents folder.
    documents_dir: PathBuf,
    /// Directory for identity vaults.
    identity_dir: PathBuf,
    /// Directory for local storage.
    local_dir: PathBuf,
    /// Directory for application logs.
    logs_dir: PathBuf,
    /// File for local audit logs.
    audit_file: PathBuf,
    /// User segregated storage.
    user_dir: PathBuf,
    /// User file storage.
    files_dir: PathBuf,
    /// User vault storage.
    vaults_dir: PathBuf,
    /// User devices storage.
    device_file: PathBuf,
}

impl Paths {
    /// Create new paths for a client.
    pub fn new(
        documents_dir: impl AsRef<Path>,
        user_id: impl AsRef<str>,
    ) -> Self {
        Self::new_with_prefix(documents_dir, user_id, LOCAL_DIR)
    }

    /// Create new paths for a server.
    pub fn new_server(
        documents_dir: impl AsRef<Path>,
        user_id: impl AsRef<str>,
    ) -> Self {
        Self::new_with_prefix(documents_dir, user_id, REMOTE_DIR)
    }

    /// Create new paths for a client with an empty user identifier.
    ///
    /// Used to get application level paths when a user identifier
    /// is not available.
    pub fn new_global(documents_dir: impl AsRef<Path>) -> Self {
        Self::new(documents_dir, "")
    }

    /// Create new paths for a client with an empty user identifier.
    ///
    /// Used to get application level paths when a user identifier
    /// is not available.
    pub fn new_global_server(documents_dir: impl AsRef<Path>) -> Self {
        Self::new_server(documents_dir, "")
    }

    fn new_with_prefix(
        documents_dir: impl AsRef<Path>,
        user_id: impl AsRef<str>,
        prefix: impl AsRef<Path>,
    ) -> Self {
        let documents_dir = documents_dir.as_ref().to_path_buf();
        let local_dir = documents_dir.join(prefix);
        let logs_dir = documents_dir.join(LOGS_DIR);
        let identity_dir = documents_dir.join(IDENTITY_DIR);
        let audit_file = local_dir.join(AUDIT_FILE_NAME);
        let user_dir = local_dir.join(user_id.as_ref());
        let files_dir = user_dir.join(FILES_DIR);
        let vaults_dir = user_dir.join(VAULTS_DIR);
        let device_file =
            user_dir.join(format!("{}.{}", DEVICE_FILE, VAULT_EXT));
        Self {
            user_id: user_id.as_ref().to_owned(),
            documents_dir,
            identity_dir,
            local_dir,
            logs_dir,
            audit_file,
            user_dir,
            files_dir,
            vaults_dir,
            device_file,
        }
    }

    /// Ensure the local storage directory exists.
    ///
    /// If a user identifier is available this will
    /// also create some user-specific directories.
    pub async fn ensure(&self) -> Result<()> {
        vfs::create_dir_all(&self.local_dir).await?;
        if !self.is_global() {
            vfs::create_dir_all(&self.user_dir).await?;
            vfs::create_dir_all(&self.files_dir).await?;
            vfs::create_dir_all(&self.vaults_dir).await?;
        }
        Ok(())
    }

    /// User identifier.
    pub fn user_id(&self) -> &str {
        &self.user_id
    }

    /// Top-level storage directory.
    pub fn documents_dir(&self) -> &PathBuf {
        &self.documents_dir
    }

    /// Determine if the paths are global.
    ///
    /// Paths are global when a user identifier
    /// is not available.
    pub fn is_global(&self) -> bool {
        self.user_id.is_empty()
    }

    /// Path to the identity vault directory.
    pub fn identity_dir(&self) -> &PathBuf {
        &self.identity_dir
    }

    /// Path to the local storage.
    pub fn local_dir(&self) -> &PathBuf {
        &self.local_dir
    }

    /// Path to the logs directory.
    pub fn logs_dir(&self) -> &PathBuf {
        &self.logs_dir
    }

    /// Path to the audit file.
    pub fn audit_file(&self) -> &PathBuf {
        &self.audit_file
    }

    /// User specific storage directory.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn user_dir(&self) -> &PathBuf {
        if self.is_global() {
            panic!("user directory is not accessible for global paths");
        }
        &self.user_dir
    }

    /// User's files directory.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn files_dir(&self) -> &PathBuf {
        if self.is_global() {
            panic!("files directory is not accessible for global paths");
        }
        &self.files_dir
    }

    /// Expected location for the directory containing
    /// all the external files for a folder.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn file_folder_location(&self, vault_id: &VaultId) -> PathBuf {
        self.files_dir().join(vault_id.to_string())
    }

    /// Expected location for a file.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn file_location(
        &self,
        vault_id: &VaultId,
        secret_id: &SecretId,
        file_name: impl AsRef<str>,
    ) -> PathBuf {
        self.file_folder_location(vault_id)
            .join(secret_id.to_string())
            .join(file_name.as_ref())
    }

    /// User's vaults storage directory.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn vaults_dir(&self) -> &PathBuf {
        if self.is_global() {
            panic!("vaults directory is not accessible for global paths");
        }
        &self.vaults_dir
    }

    /// User's device signing key vault file.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn device_file(&self) -> &PathBuf {
        if self.is_global() {
            panic!("devices file is not accessible for global paths");
        }
        &self.device_file
    }

    /// Path to the identity vault file for this user.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn identity_vault(&self) -> PathBuf {
        if self.is_global() {
            panic!("identity vault is not accessible for global paths");
        }
        let mut identity_vault_file = self.identity_dir.join(&self.user_id);
        identity_vault_file.set_extension(VAULT_EXT);
        identity_vault_file
    }

    /// Path to the identity events log for this user.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn identity_events(&self) -> PathBuf {
        let mut events_path = self.identity_vault();
        events_path.set_extension(EVENT_LOG_EXT);
        events_path
    }

    /// Path to a vault file from it's identifier.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn vault_path(&self, id: &VaultId) -> PathBuf {
        if self.is_global() {
            panic!("vault path is not accessible for global paths");
        }
        let mut vault_path = self.vaults_dir.join(id.to_string());
        vault_path.set_extension(VAULT_EXT);
        vault_path
    }

    /// Path to an event log file from it's identifier.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn event_log_path(&self, id: &VaultId) -> PathBuf {
        if self.is_global() {
            panic!("event log path is not accessible for global paths");
        }
        let mut vault_path = self.vaults_dir.join(id.to_string());
        vault_path.set_extension(EVENT_LOG_EXT);
        vault_path
    }

    /// Path to the user's account event log file.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn account_events(&self) -> PathBuf {
        if self.is_global() {
            panic!("account events are not accessible for global paths");
        }
        let mut vault_path = self.user_dir.join(ACCOUNT_EVENTS);
        vault_path.set_extension(EVENT_LOG_EXT);
        vault_path
    }

    /// Path to the user's event log of device changes.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn device_events(&self) -> PathBuf {
        if self.is_global() {
            panic!("device events are not accessible for global paths");
        }
        let mut vault_path = self.user_dir.join(DEVICE_EVENTS);
        vault_path.set_extension(EVENT_LOG_EXT);
        vault_path
    }

    /// Path to the user's event log of external file changes.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn file_events(&self) -> PathBuf {
        if self.is_global() {
            panic!("file events are not accessible for global paths");
        }
        let mut vault_path = self.user_dir.join(FILE_EVENTS);
        vault_path.set_extension(EVENT_LOG_EXT);
        vault_path
    }

    /// Path to the file used to store remote origins.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn remote_origins(&self) -> PathBuf {
        if self.is_global() {
            panic!("remote origins are not accessible for global paths");
        }
        let mut vault_path = self.user_dir.join(REMOTES_FILE);
        vault_path.set_extension(JSON_EXT);
        vault_path
    }

    /// Path to the file used to cache file transfer operations.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn file_transfers(&self) -> PathBuf {
        if self.is_global() {
            panic!("file transfers are not accessible for global paths");
        }
        let mut vault_path = self.user_dir.join(TRANSFERS_FILE);
        vault_path.set_extension(JSON_EXT);
        vault_path
    }

    /// Path to the user's preferences.
    ///
    /// # Panics
    ///
    /// If this set of paths are global (no user identifier).
    pub fn preferences(&self) -> PathBuf {
        if self.is_global() {
            panic!("preferences are not accessible for global paths");
        }
        let mut vault_path = self.user_dir.join(PREFERENCES_FILE);
        vault_path.set_extension(JSON_EXT);
        vault_path
    }

    /// Ensure the root directories exist.
    pub async fn scaffold(data_dir: Option<PathBuf>) -> Result<()> {
        let data_dir = if let Some(data_dir) = data_dir {
            data_dir
        } else {
            Paths::data_dir()?
        };
        let paths = Self::new_global(data_dir);
        vfs::create_dir_all(paths.documents_dir()).await?;
        vfs::create_dir_all(paths.identity_dir()).await?;
        vfs::create_dir_all(paths.logs_dir()).await?;
        Ok(())
    }

    /// Set an explicit data directory used to store all
    /// application files.
    pub fn set_data_dir(path: PathBuf) {
        let mut writer = DATA_DIR.write().unwrap();
        *writer = Some(path);
    }

    /// Clear an explicitly set data directory.
    pub fn clear_data_dir() {
        let mut writer = DATA_DIR.write().unwrap();
        *writer = None;
    }

    /// Get the default root directory used for caching application data.
    ///
    /// If the `SOS_DATA_DIR` environment variable is set it is used.
    ///
    /// Otherwise if an explicit directory has been set
    /// using `set_data_dir()` then that will be used instead.
    ///
    /// Finally if no environment variable or explicit directory has been
    /// set then a path will be computed by platform convention.
    ///
    /// When running with `debug_assertions` a `debug` path is appended
    /// (except when executing tests) so that we can use different
    /// storage locations for debug and release builds.
    ///
    /// If the `SOS_TEST` environment variable is set then we use
    /// `test` rather than `debug` as the nested directory so that
    /// test data does not collide with debug data.
    pub fn data_dir() -> Result<PathBuf> {
        let dir = if let Ok(env_data_dir) = std::env::var("SOS_DATA_DIR") {
            Ok(PathBuf::from(env_data_dir))
        } else {
            let reader = DATA_DIR.read().unwrap();
            if let Some(explicit) = reader.as_ref() {
                Ok(explicit.to_path_buf())
            } else {
                default_storage_dir()
            }
        };

        let has_explicit_env = std::env::var("SOS_DATA_DIR").ok().is_some();
        if cfg!(debug_assertions) && !has_explicit_env {
            // Don't follow the convention for separating debug and
            // release data when running the integration tests as it
            // makes paths very hard to reason about when they are
            // being explicitly set in test specs.
            if !cfg!(test) {
                let sub_dir = if std::env::var("SOS_TEST").is_ok() {
                    "test"
                } else {
                    "debug"
                };
                dir.map(|dir| dir.join(sub_dir))
            } else {
                dir
            }
        } else {
            dir
        }
    }

    /// Append to the audit log.
    #[cfg(feature = "audit")]
    pub async fn append_audit_events(
        &self,
        events: Vec<AuditEvent>,
    ) -> Result<()> {
        let log_file = AUDIT_LOG
            .get_or_init(async move {
                Mutex::new(
                    AuditLogFile::new(self.audit_file())
                        .await
                        .expect("could not create audit log file"),
                )
            })
            .await;
        let mut writer = log_file.lock().await;
        writer.append_audit_events(events).await?;
        Ok(())
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn default_storage_dir() -> Result<PathBuf> {
    Ok(get_app_root(AppDataType::UserData, &APP_INFO)
        .map_err(|_| Error::NoCache)?)
}

#[cfg(target_arch = "wasm32")]
fn default_storage_dir() -> Result<PathBuf> {
    Ok(PathBuf::from(""))
}