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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! # Account Manager
//!
//! The Account Manager is responsible for managing user accounts in the Citadel Protocol.
//! It provides a unified interface for account creation, storage, retrieval, and management
//! across different backend storage systems.
//!
//! ## Features
//!
//! * **Account Management**
//!   - User registration and authentication
//!   - Personal and impersonal account modes
//!   - Account metadata management
//!   - Account deletion and purging
//!
//! * **Storage Backend Support**
//!   - In-memory storage
//!   - File system persistence
//!   - SQL database integration
//!   - Redis database support
//!
//! * **Peer Management**
//!   - HyperLAN peer registration
//!   - P2P connection handling
//!   - Peer list synchronization
//!   - User information lookup
//!
//! * **Security**
//!   - Argon2id password hashing
//!   - Secure credential management
//!   - Ratchet-based cryptography
//!
//! ## Usage Example
//!
//! ```rust, no_run
//! use citadel_user::prelude::*;
//! use citadel_user::backend::BackendType;
//! use citadel_user::account_manager::AccountManager;
//! use citadel_crypt::ratchets::stacked::StackedRatchet;
//! use citadel_crypt::endpoint_crypto_container::PeerSessionCrypto;
//! use citadel_user::auth::proposed_credentials::ProposedCredentials;
//!
//! # fn gen_crypto_state() -> PeerSessionCrypto<StackedRatchet> { todo!() }
//! async fn example() -> Result<(), Box<dyn std::error::Error>> {
//!     // Initialize account manager with in-memory backend
//!     let manager = AccountManager::<StackedRatchet>::new(
//!         BackendType::InMemory,
//!         None,
//!         None,
//!         None
//!     ).await?;
//!
//!     // Register a new client account
//!     let conn_info = ConnectionInfo::new("127.0.0.1:12345")?;
//!
//!     let creds = ProposedCredentials::transient("some-unique-id");
//!
//!     let crypto_state = gen_crypto_state();
//!
//!     let account = manager.register_impersonal_hyperlan_client_network_account(
//!         conn_info,
//!         creds,
//!         crypto_state
//!     ).await?;
//!
//!     // Retrieve peer information
//!     if let Some(peers) = manager.get_hyperlan_peer_list(account.get_cid()).await? {
//!         for peer_cid in peers {
//!             println!("Connected to peer: {}", peer_cid);
//!         }
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! ## Important Notes
//!
//! * Account manager must be initialized with appropriate backend configuration
//! * Username uniqueness is not guaranteed - use CIDs for unique identification
//! * Proper error handling is essential for backend operations
//! * Account operations are thread-safe and async-compatible
//! * Backend connections are verified during initialization
//!
//! ## Related Components
//!
//! * `ClientNetworkAccount` - Individual client account management
//! * `PersistenceHandler` - Backend storage interface
//! * `ServicesHandler` - External service integration
//! * `BackendType` - Storage backend configuration
//! * `ProposedCredentials` - Account creation parameters
//!

use crate::auth::proposed_credentials::ProposedCredentials;
use crate::auth::DeclaredAuthenticationMode;
use crate::backend::memory::MemoryBackend;
use crate::backend::{BackendType, PersistenceHandler};
use crate::client_account::ClientNetworkAccount;
use crate::external_services::{ServicesConfig, ServicesHandler};
use crate::misc::{AccountError, CNACMetadata};
use crate::prelude::ConnectionInfo;
use crate::server_misc_settings::ServerMiscSettings;
use citadel_crypt::argon::argon_container::{ArgonDefaultServerSettings, ArgonSettings};
use citadel_crypt::endpoint_crypto_container::PeerSessionCrypto;
use citadel_crypt::ratchets::mono::MonoRatchet;
use citadel_crypt::ratchets::stacked::StackedRatchet;
use citadel_crypt::ratchets::Ratchet;
use citadel_types::prelude::PeerInfo;
use citadel_types::user::MutualPeer;
use citadel_types::user::UserIdentifier;
use futures::stream::FuturesOrdered;
use futures::StreamExt;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;

/// The default manager for handling the list of users stored locally. It also allows for user creation, and is used especially
/// for when creating a new user via the registration service.
#[derive(Clone)]
pub struct AccountManager<R: Ratchet = StackedRatchet, Fcm: Ratchet = MonoRatchet> {
    services_handler: ServicesHandler,
    persistence_handler: PersistenceHandler<R, Fcm>,
    node_argon_settings: ArgonSettings,
    server_misc_settings: ServerMiscSettings,
    backend_ty: BackendType,
    /// Serializes the username-exists check and the subsequent CNAC save during registration so two
    /// concurrent registrations of the same username cannot both pass the existence check and race
    /// to save (last-writer-wins / duplicate account). Shared across clones via `Arc`.
    registration_lock: std::sync::Arc<citadel_io::tokio::sync::Mutex<()>>,
}

impl<R: Ratchet, Fcm: Ratchet> AccountManager<R, Fcm> {
    /// `bind_addr`: Required for determining the local save directories for this instance
    /// `home_dir`: Optional. Overrides the default storage location for files
    /// `server_argon_settings`: Security settings used for saving the password to the backend. The AD will be replaced each time a new user is created, so it can be empty
    #[allow(unused_results)]
    pub async fn new(
        backend_type: BackendType,
        server_argon_settings: Option<ArgonDefaultServerSettings>,
        _services_cfg: Option<ServicesConfig>,
        server_misc_settings: Option<ServerMiscSettings>,
    ) -> Result<Self, AccountError> {
        // The below map should locally store: impersonal mode CNAC's, as well as personal remote server CNAC's
        #[cfg(feature = "google-services")]
        let services_handler = _services_cfg
            .unwrap_or_default()
            .into_services_handler()
            .await?;

        #[cfg(not(feature = "google-services"))]
        let services_handler = ServicesHandler;

        let persistence_handler = match &backend_type {
            BackendType::InMemory => {
                let backend = MemoryBackend::default();
                PersistenceHandler::create(backend).await?
            }

            #[cfg(all(feature = "filesystem", not(target_family = "wasm")))]
            BackendType::Filesystem(dir) => {
                use crate::backend::file_io_backend::FileIOBackend;
                use crate::backend::std_file_io::StdFileIO;
                let file_io = std::sync::Arc::new(StdFileIO);
                let backend = FileIOBackend::new(dir.clone(), file_io);
                PersistenceHandler::create(backend).await?
            }

            #[cfg(feature = "opfs")]
            BackendType::Opfs(dir) => {
                use crate::backend::file_io_backend::FileIOBackend;
                use crate::backend::opfs_file_io::OpfsFileIO;
                let file_io = std::sync::Arc::new(OpfsFileIO::new());
                let backend = FileIOBackend::new(dir.clone(), file_io);
                PersistenceHandler::create(backend).await?
            }

            #[cfg(all(feature = "sql", not(coverage)))]
            BackendType::SQLDatabase(..) => {
                use crate::backend::sql_backend::SqlBackend;
                let backend = SqlBackend::try_from(backend_type.clone())
                    .map_err(|_| citadel_io::error!(citadel_io::ErrorCode::BackendUrlInvalid))?;
                PersistenceHandler::create(backend).await?
            }

            #[cfg(all(feature = "redis", not(coverage)))]
            BackendType::Redis(url, opts) => {
                use crate::backend::redis_backend::RedisBackend;
                let backend = RedisBackend::new(url.clone(), opts.clone());
                PersistenceHandler::create(backend).await?
            }
        };

        if !persistence_handler.is_connected().await? {
            return Err(citadel_io::error!(
                citadel_io::ErrorCode::BackendNotConnected
            ));
        }

        log::info!(target: "citadel", "Successfully established connection to backend {backend_type:?}...");

        let this = Self {
            backend_ty: backend_type,
            persistence_handler,
            services_handler,
            node_argon_settings: server_argon_settings.unwrap_or_default().into(),
            server_misc_settings: server_misc_settings.unwrap_or_default(),
            registration_lock: std::sync::Arc::new(citadel_io::tokio::sync::Mutex::new(())),
        };

        // Allow the local node to use the backend to store arbitrary data
        this.setup_local_only_account().await?;

        Ok(this)
    }

    /// Returns a reference to the services handler
    pub fn services_handler(&self) -> &ServicesHandler {
        &self.services_handler
    }

    /// Once a valid and decrypted stage 4 packet gets received by the server (Bob), this function should be called
    /// to create the new CNAC. The generated CNAC will be assumed to be an impersonal hyperlan client
    ///
    /// This also generates the argon-2id password hash
    pub async fn register_impersonal_hyperlan_client_network_account(
        &self,
        conn_info: ConnectionInfo,
        creds: ProposedCredentials,
        session_crypto_state: PeerSessionCrypto<R>,
    ) -> Result<ClientNetworkAccount<R, Fcm>, AccountError> {
        let reserved_cid = self
            .persistence_handler
            .get_cid_by_username(creds.username());

        if reserved_cid == 0 {
            return Err(citadel_io::error!(citadel_io::ErrorCode::RegisterCidZero));
        }

        let auth_store = creds
            .derive_server_container(&self.node_argon_settings, self.get_misc_settings())
            .await?;

        self.server_misc_settings
            .credential_requirements
            .check::<_, &str, _>(auth_store.username(), None, auth_store.full_name())?;

        let pers = &self.persistence_handler;

        // Hold the registration lock across the existence check AND the save so two concurrent
        // registrations of the same username cannot both observe "does not exist" and then race to
        // save (which on SQL/Redis is an upsert => silent last-writer-wins / duplicate account).
        let _registration_guard = self.registration_lock.lock().await;
        log::trace!(target: "citadel", "Checking username {} for correspondence ...", auth_store.username());

        let username = auth_store.username().to_string();

        if pers.username_exists(&username).await? {
            return Err(citadel_io::error!(
                citadel_io::ErrorCode::UsernameExists,
                username.clone()
            ));
        }

        // cnac gets saved below
        let new_cnac = ClientNetworkAccount::<R, Fcm>::new(
            reserved_cid,
            false,
            conn_info,
            auth_store,
            Some(session_crypto_state),
        )
        .await?;
        log::trace!(target: "citadel", "Created impersonal CNAC ...");
        self.persistence_handler.save_cnac(&new_cnac).await?;

        Ok(new_cnac)
    }

    /// whereas the HyperLAN server (Bob) runs `register_impersonal_hyperlan_client_network_account`, the registering
    /// HyperLAN Client (Alice) runs this function below
    pub async fn register_personal_hyperlan_server(
        &self,
        session_crypto_state: PeerSessionCrypto<R>,
        creds: ProposedCredentials,
        conn_info: ConnectionInfo,
    ) -> Result<ClientNetworkAccount<R, Fcm>, AccountError> {
        let valid_cid = self
            .persistence_handler
            .get_cid_by_username(creds.username());

        if valid_cid == 0 {
            return Err(citadel_io::error!(citadel_io::ErrorCode::RegisterCidZero));
        }

        let client_auth_store = creds.into_auth_store();
        let cnac = ClientNetworkAccount::<R, Fcm>::new_from_network_personal(
            valid_cid,
            Some(session_crypto_state),
            client_auth_store,
            conn_info,
        )
        .await?;
        self.persistence_handler.save_cnac(&cnac).await?;

        Ok(cnac)
    }

    /// Sets up a local-only account that should only be accessed by a local handle. Network requests
    /// to the zero CID will be rejected by the networking layer to deter any malicious behavior. However,
    /// it is highly advisable to independently use and store an encryption key outside of the local program such
    /// that all stored data is encrypted in case of attack. This function needs to be used with caution.
    async fn setup_local_only_account(&self) -> Result<(), AccountError> {
        // Setup mock CNAC
        let cnac = ClientNetworkAccount::<R, Fcm>::new_from_network_personal(
            0,
            None,
            DeclaredAuthenticationMode::Transient {
                username: Default::default(),
                full_name: Default::default(),
            },
            ConnectionInfo::new("127.0.0.1:12345").expect("Should be valid addr"),
        )
        .await?;

        self.persistence_handler.save_cnac(&cnac).await?;

        Ok(())
    }

    /// Determines if the HyperLAN client is registered
    /// Impersonal mode
    pub async fn hyperlan_cid_is_registered(&self, cid: u64) -> Result<bool, AccountError> {
        self.persistence_handler.cid_is_registered(cid).await
    }

    /// Returns a list of impersonal cids
    pub async fn get_registered_impersonal_cids(
        &self,
        limit: Option<i32>,
    ) -> Result<Option<Vec<u64>>, AccountError> {
        self.persistence_handler
            .get_registered_impersonal_cids(limit)
            .await
    }

    /// Returns the CNAC with the supplied CID
    pub async fn get_client_by_cid(
        &self,
        cid: u64,
    ) -> Result<Option<ClientNetworkAccount<R, Fcm>>, AccountError> {
        self.persistence_handler.get_cnac_by_cid(cid).await
    }

    /// Gets username by CID
    pub async fn get_username_by_cid(&self, cid: u64) -> Result<Option<String>, AccountError> {
        self.persistence_handler.get_username_by_cid(cid).await
    }

    /// Gets full name by CID
    pub async fn get_full_name_by_cid(&self, cid: u64) -> Result<Option<String>, AccountError> {
        self.persistence_handler.get_full_name_by_cid(cid).await
    }

    /// Gets user info for all the given CIDs, omitting any invalid users from the returned values
    pub async fn get_peer_info_from_cids(&self, cids: &[u64]) -> HashMap<u64, Option<PeerInfo>> {
        let mut peer_info = HashMap::new();
        let mut queue = FuturesOrdered::<
            Pin<Box<dyn Future<Output = Result<Option<CNACMetadata>, AccountError>>>>,
        >::new();
        for cid in cids {
            queue.push_back(Box::pin(self.persistence_handler.get_client_metadata(*cid)))
        }
        let mut results = futures::executor::block_on(queue.collect::<Vec<_>>());
        let metadata: Vec<&Option<CNACMetadata>> = results
            .iter_mut()
            .map(|result| result.as_ref().unwrap_or(&None))
            .collect();
        let _: Vec<_> = cids
            .iter()
            .zip(metadata)
            .map(|(&cid, user_data)| {
                peer_info.insert(
                    cid,
                    user_data.as_ref().map(|some| PeerInfo {
                        cid: some.cid,
                        username: some.username.clone(),
                        full_name: some.full_name.clone(),
                    }),
                )
            })
            .collect();
        peer_info
    }

    /// Returns the first username detected. This is not advised to use, because overlapping usernames are entirely possible.
    /// Instead, use get_client_by_cid, as the cid is unique unlike the username
    pub async fn get_client_by_username<T: AsRef<str>>(
        &self,
        username: T,
    ) -> Result<Option<ClientNetworkAccount<R, Fcm>>, AccountError> {
        self.persistence_handler
            .get_client_by_username(username.as_ref())
            .await
    }

    /// Returns the number of accounts purged
    pub async fn purge(&self) -> Result<usize, AccountError> {
        self.persistence_handler.purge().await
    }

    /// Does not execute the registration process between two peers; it only consolidates the changes to the local CNAC
    /// returns true if success, false otherwise
    pub async fn register_hyperlan_p2p_at_endpoints<T: Into<String>>(
        &self,
        session_cid: u64,
        peer_cid: u64,
        adjacent_username: T,
    ) -> Result<(), AccountError> {
        let adjacent_username = adjacent_username.into();
        log::trace!(target: "citadel", "Registering {} ({}) to {} (local/endpoints)", &adjacent_username, peer_cid, session_cid);
        self.persistence_handler
            .register_p2p_as_client(session_cid, peer_cid, adjacent_username)
            .await
    }

    /// Registers the two accounts together at the server
    pub async fn register_hyperlan_p2p_as_server(
        &self,
        cid0: u64,
        cid1: u64,
    ) -> Result<(), AccountError> {
        self.persistence_handler
            .register_p2p_as_server(cid0, cid1)
            .await
    }

    /// Deletes a client by cid. Returns true if a success
    #[allow(unused_results)]
    pub async fn delete_client_by_cid(&self, cid: u64) -> Result<(), AccountError> {
        self.persistence_handler.delete_cnac_by_cid(cid).await
    }

    /// Gets a list of hyperlan peers for the given peer
    pub async fn get_hyperlan_peer_list(
        &self,
        session_cid: u64,
    ) -> Result<Option<Vec<u64>>, AccountError> {
        self.persistence_handler
            .get_hyperlan_peer_list(session_cid)
            .await
    }

    /// Finds a hyperlan peer for a given user. Returns the implicated CID and mutual peer info
    pub async fn find_target_information(
        &self,
        implicated_user: impl Into<UserIdentifier>,
        target_user: impl Into<UserIdentifier>,
    ) -> Result<Option<(u64, MutualPeer)>, AccountError> {
        let session_cid = match implicated_user.into() {
            UserIdentifier::ID(id) => id,

            UserIdentifier::Username(uname) => {
                self.get_persistence_handler().get_cid_by_username(&uname)
            }
        };

        match target_user.into() {
            UserIdentifier::ID(peer_cid) => Ok(self
                .persistence_handler
                .get_hyperlan_peer_by_cid(session_cid, peer_cid)
                .await?
                .map(|r| (session_cid, r))),

            UserIdentifier::Username(uname) => Ok(self
                .persistence_handler
                .get_hyperlan_peer_by_username(session_cid, &uname)
                .await?
                .map(|r| (session_cid, r))),
        }
    }

    /// Converts a user identifier into its cid
    pub async fn find_local_user_information(
        &self,
        implicated_user: impl Into<UserIdentifier>,
    ) -> Result<Option<u64>, AccountError> {
        match implicated_user.into() {
            UserIdentifier::ID(cid) => Ok(Some(cid)),
            UserIdentifier::Username(username) => {
                let cid = self.persistence_handler.get_cid_by_username(&username);
                Ok(self
                    .persistence_handler
                    .get_client_metadata(cid)
                    .await?
                    .map(|r| r.cid))
            }
        }
    }

    /// Converts a user identifier into its cid
    pub async fn find_cnac_by_identifier(
        &self,
        implicated_user: impl Into<UserIdentifier>,
    ) -> Result<Option<ClientNetworkAccount<R, Fcm>>, AccountError> {
        match implicated_user.into() {
            UserIdentifier::ID(cid) => self.get_client_by_cid(cid).await,
            UserIdentifier::Username(username) => self.get_client_by_username(username).await,
        }
    }

    /// Returns the persistence handler
    #[doc(hidden)]
    pub fn get_persistence_handler(&self) -> &PersistenceHandler<R, Fcm> {
        &self.persistence_handler
    }

    /// Returns the misc settings
    pub fn get_misc_settings(&self) -> &ServerMiscSettings {
        &self.server_misc_settings
    }

    /// Gets the backend type
    pub fn get_backend_type(&self) -> &BackendType {
        &self.backend_ty
    }
}