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
use super::{Error, Result};
use sos_protocol::{
    sdk::{
        signer::{
            ecdsa::Address,
            ed25519::{self, Verifier, VerifyingKey},
        },
        storage::DiscFolder,
        vfs, Paths,
    },
    CreateSet, MergeOutcome, SyncStorage, UpdateSet,
};
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::Arc,
};
use tokio::sync::RwLock;

use crate::storage::filesystem::ServerStorage;

/// Account storage.
pub struct AccountStorage {
    pub(crate) storage: ServerStorage,
}

/// Individual account.
pub type ServerAccount = Arc<RwLock<AccountStorage>>;

/// Collection of accounts by address.
pub type Accounts = Arc<RwLock<HashMap<Address, ServerAccount>>>;

/// Backend for a server.
pub struct Backend {
    directory: PathBuf,
    accounts: Accounts,
}

impl Backend {
    /// Create a new file system backend.
    pub fn new<P: AsRef<Path>>(directory: P) -> Self {
        let directory = directory.as_ref().to_path_buf();
        Self {
            directory,
            accounts: Arc::new(RwLock::new(Default::default())),
        }
    }

    /// Directory where accounts are stored.
    pub fn directory(&self) -> &PathBuf {
        &self.directory
    }

    /// Get the accounts.
    pub fn accounts(&self) -> Accounts {
        Arc::clone(&self.accounts)
    }

    /// Read accounts and event logs into memory.
    pub(crate) async fn read_dir(&mut self) -> Result<()> {
        if !vfs::metadata(&self.directory).await?.is_dir() {
            return Err(Error::NotDirectory(self.directory.clone()));
        }

        tracing::debug!(
            directory = %self.directory.display(), "backend::read_dir");

        Paths::scaffold(Some(self.directory.clone())).await?;
        let paths = Paths::new_global_server(self.directory.clone());

        if !vfs::try_exists(paths.local_dir()).await? {
            vfs::create_dir(paths.local_dir()).await?;
        }

        let mut dir = vfs::read_dir(paths.local_dir()).await?;
        while let Some(entry) = dir.next_entry().await? {
            let path = entry.path();
            if vfs::metadata(&path).await?.is_dir() {
                if let Some(name) = path.file_stem() {
                    if let Ok(owner) =
                        name.to_string_lossy().parse::<Address>()
                    {
                        tracing::debug!(
                            account = %owner,
                            "backend::read_dir",
                        );

                        let user_paths = Paths::new_server(
                            self.directory.clone(),
                            owner.to_string(),
                        );
                        let identity_log =
                            DiscFolder::new_event_log(&user_paths).await?;

                        let account = AccountStorage {
                            storage: ServerStorage::new(
                                owner.clone(),
                                Some(self.directory.clone()),
                                identity_log,
                            )
                            .await?,
                        };

                        let mut accounts = self.accounts.write().await;
                        let account = accounts
                            .entry(owner.clone())
                            .or_insert(Arc::new(RwLock::new(account)));
                        let mut writer = account.write().await;
                        writer.storage.load_folders().await?;
                    }
                }
            }
        }
        Ok(())
    }

    /// Create an account.
    pub async fn create_account(
        &mut self,
        owner: &Address,
        account_data: CreateSet,
    ) -> Result<()> {
        {
            let accounts = self.accounts.read().await;
            let account = accounts.get(owner);

            if account.is_some() {
                return Err(Error::AccountExists(*owner));
            }
        }

        tracing::debug!(address = %owner, "backend::create_account");

        let paths =
            Paths::new_server(self.directory.clone(), owner.to_string());
        paths.ensure().await?;

        let identity_log =
            ServerStorage::initialize_account(&paths, &account_data.identity)
                .await?;

        let mut storage = ServerStorage::new(
            owner.clone(),
            Some(self.directory.clone()),
            Arc::new(RwLock::new(identity_log)),
        )
        .await?;
        storage.import_account(&account_data).await?;

        let account = AccountStorage { storage };
        let mut accounts = self.accounts.write().await;
        accounts
            .entry(owner.clone())
            .or_insert(Arc::new(RwLock::new(account)));

        Ok(())
    }

    /// Delete an account.
    pub async fn delete_account(&mut self, owner: &Address) -> Result<()> {
        tracing::debug!(address = %owner, "backend::delete_account");

        let mut accounts = self.accounts.write().await;
        let account =
            accounts.get_mut(owner).ok_or(Error::NoAccount(*owner))?;

        let mut account = account.write().await;
        account.storage.delete_account().await?;

        Ok(())
    }

    /// Update an account.
    pub async fn update_account(
        &mut self,
        owner: &Address,
        account_data: UpdateSet,
    ) -> Result<MergeOutcome> {
        tracing::debug!(address = %owner, "backend::update_account");

        let mut outcome = MergeOutcome::default();

        let mut accounts = self.accounts.write().await;
        let account =
            accounts.get_mut(owner).ok_or(Error::NoAccount(*owner))?;

        let mut account = account.write().await;
        account
            .storage
            .update_account(account_data, &mut outcome)
            .await?;
        Ok(outcome)
    }

    /// Fetch an existing account.
    pub async fn fetch_account(&self, owner: &Address) -> Result<CreateSet> {
        tracing::debug!(address = %owner, "backend::fetch_account");

        let accounts = self.accounts.read().await;
        let account = accounts.get(owner).ok_or(Error::NoAccount(*owner))?;

        let reader = account.read().await;
        let change_set = reader.storage.change_set().await?;

        Ok(change_set)
    }

    /// Verify a device is allowed to access an account.
    pub(crate) async fn verify_device(
        &self,
        owner: &Address,
        device_signature: &ed25519::Signature,
        message_body: &[u8],
    ) -> Result<()> {
        let accounts = self.accounts.read().await;
        if let Some(account) = accounts.get(owner) {
            let reader = account.read().await;
            let account_devices = reader.storage.list_device_keys();
            for device_key in account_devices {
                let verifying_key: VerifyingKey = device_key.try_into()?;
                if verifying_key
                    .verify(message_body, device_signature)
                    .is_ok()
                {
                    return Ok(());
                }
            }
            Err(Error::Forbidden)
        } else {
            Ok(())
        }
    }

    /// Determine if an account exists.
    pub async fn account_exists(&self, owner: &Address) -> Result<bool> {
        let accounts = self.accounts.read().await;
        Ok(accounts.get(owner).is_some())
    }
}