ctb_storage/models/
user.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! User management: creation, deletion, login, metadata.
21//! This *tries* to lock the user during write operations so it won't end up in
22//! inconsistent states, etc. but that doesn't currently seem to work reliably.
23
24#[expect(unused_imports, reason = "imported module dependencies")]
25use crate::utilities::*;
26
27use crate::graph::Graph;
28use crate::secret::Secret;
29use crate::user::auth::KekParams;
30use crate::utilities::password::{Password, TEST_USER_PASS, hash, verify};
31use crate::utilities::pc_settings::ensure_pc_settings;
32use crate::utilities::resource_lock::{Lock, ResourceLock};
33use crate::{error, json, log};
34use anyhow::{Context, Result, anyhow, bail};
35use ctb_utilities::ipc::service_traits::storage::UserDto;
36use ctb_utilities::storage::get_storage_dir;
37use serde::{Deserialize, Serialize};
38use std::ffi::OsString;
39use std::fs;
40
41pub mod auth;
42pub mod session;
43
44#[derive(Debug)]
45pub struct NameAndIdLock {
46    pub name_lock: ResourceLock,
47    pub id_lock: ResourceLock,
48}
49
50impl Lock for NameAndIdLock {}
51
52impl NameAndIdLock {
53    pub fn new(name_lock: ResourceLock, id_lock: ResourceLock) -> Self {
54        Self { name_lock, id_lock }
55    }
56}
57
58#[derive(Debug, Default, Serialize, Deserialize)]
59pub struct UserLocalConfig {
60    pub default_store_location: OsString,
61}
62
63#[derive(Debug, Default, Serialize)]
64pub struct UserPublicInfo {
65    local_id: u64,
66    name: String,
67    display_name: Option<Vec<u8>>,
68    uuid: Vec<u8>,
69    picture: Option<Vec<u8>>,
70    remote_status: Option<String>,
71    #[serde(skip)]
72    #[expect(dead_code, reason = "field is used as lock handle")]
73    lock: Option<ResourceLock>,
74}
75
76impl UserPublicInfo {
77    pub fn get_by_name(name: &str) -> Result<Option<Self>> {
78        let _name_lock = ResourceLock::acquire(USER_NAME_LOCK, &name)?;
79        let dto = ipcb!(storage).get_user_by_name_b(name)?;
80        let Some(dto) = dto else {
81            return Ok(None);
82        };
83        Ok(Some(Self {
84            local_id: dto.id,
85            name: dto.username,
86            display_name: dto.display_name,
87            uuid: dto.uuid,
88            picture: dto.picture,
89            remote_status: dto.remote_status,
90            lock: None,
91        }))
92    }
93
94    pub fn get_by_id(id: u64) -> Option<Self> {
95        let dto = ipcb!(storage).get_user_by_id_b(id).ok().flatten()?;
96        Some(Self {
97            local_id: dto.id,
98            name: dto.username,
99            display_name: dto.display_name,
100            uuid: dto.uuid,
101            picture: dto.picture,
102            remote_status: dto.remote_status,
103            lock: None,
104        })
105    }
106
107    pub fn local_id(&self) -> u64 {
108        self.local_id
109    }
110    pub fn name(&self) -> &str {
111        &self.name
112    }
113    pub fn display_name(&self) -> Option<&[u8]> {
114        self.display_name.as_deref()
115    }
116    pub fn uuid(&self) -> &Vec<u8> {
117        &self.uuid
118    }
119    pub fn user_picture(&self) -> Option<&[u8]> {
120        self.picture.as_deref()
121    }
122    pub fn remote_status(&self) -> &str {
123        // Reason for fallback: user remote_status field missing in DB record defaults to "Pending"
124        self.remote_status.as_deref().unwrap_or("Pending")
125    }
126
127    pub fn list_all() -> Result<Vec<Self>> {
128        let user_ids = get_all_user_ids()?;
129        let mut users = Vec::new();
130        for id in user_ids {
131            if let Some(user) = UserPublicInfo::get_by_id(id) {
132                users.push(user);
133            }
134        }
135        Ok(users)
136    }
137}
138
139#[derive(Debug, Default)]
140pub struct User {
141    public_info: UserPublicInfo,
142    remote_id: Option<u64>,
143    local_config: UserLocalConfig,
144    graphs: Vec<Graph>,
145    dek: Option<Secret>,
146    lock: Option<NameAndIdLock>, // Guard that keeps user locked while User is alive.
147    session_token: Option<String>,
148}
149
150const USER_LOCK: &str = "user";
151const USER_NAME_LOCK: &str = "user_name";
152const USER_PUBLIC_INFO_LOCK: &str = "user_public_info";
153
154impl User {
155    pub fn name(&self) -> String {
156        self.public_info.name.clone()
157    }
158
159    pub fn local_id(&self) -> u64 {
160        self.public_info.local_id
161    }
162
163    pub fn remote_id(&self) -> Option<u64> {
164        self.remote_id
165    }
166
167    pub fn session_token(&self) -> Option<&str> {
168        self.session_token.as_deref()
169    }
170    pub fn remote_status(&self) -> &str {
171        self.public_info.remote_status()
172    }
173
174    pub fn set_remote_status(&mut self, status: String) {
175        self.public_info.remote_status = Some(status);
176    }
177
178    pub fn set_session_token(&mut self, token: Option<String>) {
179        self.session_token = token;
180    }
181
182    pub(crate) fn dek_bytes(&self) -> Option<Vec<u8>> {
183        self.dek.as_ref().map(|s| s.as_slice().to_vec())
184    }
185
186    pub(crate) fn take_dek(&mut self) -> Option<Secret> {
187        self.dek.take()
188    }
189
190    pub fn display_name(&self) -> Option<&[u8]> {
191        self.public_info.display_name.as_deref()
192    }
193
194    pub fn user_picture(&self) -> Option<&[u8]> {
195        self.public_info.picture.as_deref()
196    }
197
198    pub fn uuid(&self) -> &Vec<u8> {
199        &self.public_info.uuid
200    }
201
202    pub fn increment_and_get_user_id() -> Result<u64> {
203        ipcb!(storage).increment_and_get_user_id_b()
204    }
205
206    pub fn is_admin(&self) -> bool {
207        // Reason for fallback: unreadable settings file defaults admin check to initial settings struct
208        let settings = crate::utilities::pc_settings::PcSettings::load()
209            .unwrap_or_default();
210        match &settings.admin_users {
211            ctb_utilities::json::maybe_value::MaybeOption::Value(v) => {
212                if v.is_empty() {
213                    self.name() == "admin" || self.name() == "global"
214                } else {
215                    v.contains(&self.local_id())
216                }
217            }
218            _ => self.name() == "admin" || self.name() == "global",
219        }
220    }
221
222    /// Create a new local user.
223    pub fn create(name: &str, password: &Password) -> Result<Self> {
224        // 1) Acquire name lock first to serialize operations on this user name.
225        let name_lock = ResourceLock::acquire(USER_NAME_LOCK, &name)?;
226
227        error!(format!("Creating user '{name}'"));
228        ensure_base_layout().context("Failed to ensure base layout")?;
229
230        // 2) Check existence.
231        if get_user_id_by_name(name).is_some() {
232            return Err(anyhow!("User '{name}' already exists"));
233        }
234
235        // 3) Allocate a new user id using the file-based atomic counter.
236        let user_id = next_user_id().context("Unable to allocate user id")?;
237
238        // 4) Acquire per-user lock (exclusive) for entire creation.
239        let id_lock = lock_by_id(user_id)?;
240        let user_lock = NameAndIdLock { name_lock, id_lock };
241
242        let (mut kek, kek_params) = auth::derive_kek(password)?;
243        let dek = auth::generate_dek()?;
244        let phc = hash(password)?;
245
246        // Wrap DEK under KEK with aad=user_id
247        // AAD = "additional authenticated data" in AEAD, used to avoid reusing
248        // the key with different user ID, etc.
249        // So, to allow the user record to be copied between local machine and
250        // server, also allocate a UUID for the user and use that as the AAD.
251        // The UUID must be persistent when the user record is copied (unlike
252        // the local user ID).
253
254        // Allocate UUID for AAD
255        let uuid = uuid::Uuid::new_v4();
256        let uuid = uuid.as_bytes();
257
258        let aad = uuid;
259        let wrapped_dek = auth::wrap_key(&kek, &dek, aad)?;
260        use zeroize::Zeroize;
261        kek.zeroize();
262
263        // 5) Persist all user metadata.
264        let root = get_storage_dir().context("No storage dir")?;
265        let users_dir = root.join("users");
266        fs::create_dir_all(&users_dir).ok();
267
268        let user_dto = UserDto {
269            id: user_id,
270            username: name.to_string(),
271            uuid: uuid.to_vec(),
272            auth: Some(phc),
273            display_name: None,
274            picture: None,
275            key_encryption_key_params: Some(
276                json!(kek_params).as_bytes().to_vec(),
277            ),
278            wrapped_dek: Some(wrapped_dek),
279            pubkey: None,
280            subscription_expiry: None,
281            token_quota: None,
282            remote_status: Some("Pending".to_string()),
283        };
284        ipcb!(storage).create_user_b(user_dto)?;
285
286        ensure_pc_settings().context("Failed to ensure pc_settings.json")?;
287
288        {
289            let root = get_storage_dir().context("No storage dir")?;
290            let graphs_dir = root.join("graphs").join(user_id.to_string());
291            fs::create_dir_all(&graphs_dir).with_context(|| {
292                format!("Failed to create graphs dir {}", graphs_dir.display())
293            })?;
294        }
295
296        let mut user = User::default();
297        user.public_info.local_id = user_id;
298        user.public_info.name = name.to_string();
299        user.public_info.uuid = uuid.to_vec();
300        user.public_info.remote_status = Some("Pending".to_string());
301        user.local_config = user.local_config()?;
302        crate::user::session::register_user_dek(
303            user_id,
304            Secret::new(dek.clone()),
305        )?;
306        user.dek = Some(Secret::new(dek));
307        user.lock = Some(user_lock);
308        // Initialize user graphs with a default graph (id = 1)
309        user.graphs.push(Graph::new(1, "Default", &user));
310
311        Ok(user)
312    }
313
314    /// Register a new non-administrator local user.
315    ///
316    /// Checks that local account creation is allowed in PC settings, verifies that
317    /// the requested username is not an administrator username ("admin" or "global"),
318    /// and then creates the local user.
319    pub fn add_non_admin_user(name: &str, password: &Password) -> Result<Self> {
320        let allow = crate::utilities::pc_settings::get_bool_setting(
321            crate::utilities::pc_settings::PcSettingBoolKey::AllowLocalAccountCreation,
322        );
323        if !allow {
324            bail!("Local account creation is disallowed in PC settings");
325        }
326
327        let trimmed_name = name.trim();
328        if trimmed_name.is_empty() {
329            bail!("Username cannot be empty");
330        }
331
332        if trimmed_name.eq_ignore_ascii_case("admin")
333            || trimmed_name.eq_ignore_ascii_case("global")
334        {
335            bail!("Cannot create administrator account via adduser");
336        }
337
338        Self::create(trimmed_name, password)
339    }
340
341    /// Delete this user
342    pub fn delete(&self) -> Result<()> {
343        ensure_base_layout().context("Failed to ensure base layout")?;
344        let user_id = self.local_id();
345        let name = self.name();
346
347        // If caller already holds locks (e.g., from create), respect them and only serialize DB work.
348        if self.lock.is_some() {
349            Self::_delete_user(user_id, &name)
350        } else {
351            // Acquire locks in consistent order: name -> id -> db
352            let _name_lock = ResourceLock::acquire(USER_NAME_LOCK, &name)?;
353            let _id_lock = lock_by_id(user_id)?;
354
355            Self::_delete_user(user_id, &name)
356        }
357    }
358
359    /// Delete a user by name
360    pub fn delete_by_name(name: &str) -> Result<()> {
361        ensure_base_layout().context("Failed to ensure base layout")?;
362        log!("Deleting user '{name}'");
363
364        // Acquire locks in consistent order: name -> id -> db
365        let name_lock = ResourceLock::acquire(USER_NAME_LOCK, &name)?;
366
367        let user_id = get_user_id_by_name(name)
368            .ok_or_else(|| anyhow!("User ID not found for name {name}"))?;
369
370        let _id_lock = lock_by_id(user_id)?;
371
372        // Perform deletion .
373        let res = {
374            // Keep name_lock in scope to maintain consistent ownership while deleting mapping.
375            let _keep_name_lock = &name_lock;
376            Self::_delete_user(user_id, name)
377        };
378
379        // Verify deletion .
380        {
381            if get_user_id_by_name(name).is_some() {
382                bail!("Failed to delete user {name} with id {user_id}");
383            }
384        }
385        res
386    }
387
388    /// Internal (no-DB-lock) deletion logic extracted to avoid double-locking.
389    /// Do NOT call this without holding the DB lock. This function assumes the caller holds:
390    /// - `USER_NAME_LOCK` (for `name`)
391    /// - `USER_LOCK` (for `user_id`)
392    fn _delete_user(user_id: u64, _name: &str) -> Result<()> {
393        let root = get_storage_dir().context("No storage dir")?;
394
395        ipcb!(storage).delete_user_by_id_b(user_id)?;
396
397        // Remove user's graphs directory (filesystem, not DB)
398        let graphs_dir = root.join("graphs").join(user_id.to_string());
399        if graphs_dir.exists() {
400            fs::remove_dir_all(&graphs_dir).with_context(|| {
401                format!("Failed to remove graphs dir {graphs_dir:?}")
402            })?;
403        }
404        Ok(())
405    }
406
407    /// Login: Verify password, derive KEK, verify DEK.
408    /// TODO: Possibly this should also log in to the server and start syncing any new user data.
409    pub fn login(
410        public_info: UserPublicInfo,
411        password: &Password,
412    ) -> Result<Self> {
413        ensure_base_layout().context("Failed to ensure base layout")?;
414
415        if public_info.local_id == 0 {
416            return Err(anyhow!(
417                "UserPublicInfo.local_id was 0. Provide a valid user_id or use UserPublicInfo::get_by_name."
418            ));
419        }
420
421        let user_id = public_info.local_id;
422
423        // Acquire per-user lock for consistency while reading user metadata.
424        // Lock ordering: id lock first, DB lock only around DB calls.
425        let _user_lock = lock_by_id(user_id)?;
426
427        let (phc, kek_params, wrapped_dek, uuid) = {
428            let dto = ipcb!(storage)
429                .get_user_by_id_b(user_id)?
430                .ok_or_else(|| anyhow!("User not found: {user_id}"))?;
431
432            let phc = dto.auth.ok_or_else(|| {
433                anyhow!("Auth entry for user_id {user_id} not found")
434            })?;
435
436            let kek_params = dto
437                .key_encryption_key_params
438                .and_then(|bytes| {
439                    serde_json::from_slice::<KekParams>(&bytes).ok()
440                })
441                .ok_or_else(|| {
442                    anyhow!("KEK params not found for user_id {user_id}")
443                })?;
444
445            let wrapped_dek = dto.wrapped_dek.ok_or_else(|| {
446                anyhow!("Wrapped DEK not found for user_id {user_id}")
447            })?;
448
449            (phc, kek_params, wrapped_dek, dto.uuid)
450        };
451
452        if !(verify(password, &phc)?) {
453            return Err(anyhow!("Invalid password"));
454        }
455
456        // Derive KEK using stored parameters.
457        let mut kek = auth::derive_kek_with_params(password, &kek_params)
458            .context("Failed to derive KEK with params")?;
459
460        let dek = auth::unwrap_key(&kek, &wrapped_dek, &uuid)
461            .context("Failed to unwrap DEK")?;
462        use zeroize::Zeroize;
463        kek.zeroize();
464
465        crate::user::session::register_user_dek(
466            user_id,
467            Secret::new(dek.clone()),
468        )?;
469
470        let mut user = User::default();
471        user.public_info = public_info;
472        user.local_config = user.local_config()?;
473        user.dek = Some(Secret::new(dek));
474        // Initialize user graphs with a default graph (id = 1)
475        user.graphs.push(Graph::new(1, "Default", &user));
476        // We intentionally do not hold the user lock beyond login.
477        Ok(user)
478    }
479
480    /// Rotate a user's password while preserving their existing DEK and graphs.
481    ///
482    /// Verifies `old_password`, unwraps the existing `dek` with the old KEK,
483    /// derives a fresh KEK and Argon2 PHC hash from `new_password`, re-wraps
484    /// the same `dek` under the user's persistent UUID AAD, and updates the
485    /// user record in storage.
486    pub fn change_password(
487        name: &str,
488        old_password: &Password,
489        new_password: &Password,
490    ) -> Result<u64> {
491        use zeroize::Zeroize;
492
493        ensure_base_layout().context("Failed to ensure base layout")?;
494
495        let trimmed_name = name.trim();
496        ensure!(!trimmed_name.is_empty(), "Username cannot be empty");
497        ensure!(
498            !new_password.password.is_empty(),
499            "New password cannot be empty"
500        );
501
502        let (_name_lock, id_lock) = lock_by_name(trimmed_name)?;
503        ensure!(id_lock.is_some(), "User '{trimmed_name}' not found");
504
505        let mut dto = ipcb!(storage)
506            .get_user_by_name_b(trimmed_name)?
507            .ok_or_else(|| anyhow!("User '{trimmed_name}' not found"))?;
508        let user_id = dto.id;
509
510        let phc = dto.auth.as_deref().ok_or_else(|| {
511            anyhow!("Auth entry for user_id {user_id} not found")
512        })?;
513        let kek_params = dto
514            .key_encryption_key_params
515            .as_deref()
516            .and_then(|bytes| serde_json::from_slice::<KekParams>(bytes).ok())
517            .ok_or_else(|| {
518                anyhow!("KEK params not found for user_id {user_id}")
519            })?;
520        let wrapped_dek = dto.wrapped_dek.as_deref().ok_or_else(|| {
521            anyhow!("Wrapped DEK not found for user_id {user_id}")
522        })?;
523
524        ensure!(verify(old_password, phc)?, "Invalid password");
525
526        let mut old_kek = auth::derive_kek_with_params(old_password, &kek_params)
527            .context("Failed to derive KEK with params")?;
528        let mut dek = match auth::unwrap_key(&old_kek, wrapped_dek, &dto.uuid) {
529            Ok(dek) => {
530                old_kek.zeroize();
531                dek
532            }
533            Err(err) => {
534                old_kek.zeroize();
535                return Err(err).context("Failed to unwrap DEK");
536            }
537        };
538
539        let (mut new_kek, new_kek_params) = match auth::derive_kek(new_password)
540        {
541            Ok(res) => res,
542            Err(err) => {
543                dek.zeroize();
544                return Err(err);
545            }
546        };
547        let new_phc = match hash(new_password) {
548            Ok(phc) => phc,
549            Err(err) => {
550                new_kek.zeroize();
551                dek.zeroize();
552                return Err(err);
553            }
554        };
555        let new_wrapped_dek = auth::wrap_key(&new_kek, &dek, &dto.uuid);
556        new_kek.zeroize();
557        dek.zeroize();
558        let new_wrapped_dek = new_wrapped_dek?;
559
560        dto.auth = Some(new_phc);
561        dto.key_encryption_key_params =
562            Some(json!(new_kek_params).as_bytes().to_vec());
563        dto.wrapped_dek = Some(new_wrapped_dek);
564
565        ipcb!(storage).update_user_b(dto)?;
566
567        Ok(user_id)
568    }
569
570    /// Reconstruct a User struct from `UserPublicInfo` for an already-logged-in session.
571    pub fn from_public_info(
572        public_info: UserPublicInfo,
573        session_token: Option<String>,
574    ) -> Self {
575        let mut user = User::default();
576        user.public_info = public_info;
577        user.session_token = session_token;
578        // Reason for fallback: missing user local_config defaults to default UserConfig struct
579        user.local_config = user.local_config().unwrap_or_default();
580        // Initialize user graphs with a default graph (id = 1)
581        user.graphs.push(Graph::new(1, "Default", &user));
582        user
583    }
584
585    pub fn local_config(&self) -> Result<UserLocalConfig> {
586        let cache_dir =
587            get_storage_dir().context("Failed to resolve storage directory")?;
588        let user_cache_dir = std::path::Path::new(&cache_dir).join(self.name());
589        std::fs::create_dir_all(&user_cache_dir)
590            .context("Failed to create per-user cache directory")?;
591        let config_path = user_cache_dir.join("local_config");
592        if !config_path.exists() {
593            let default_config = UserLocalConfig {
594                default_store_location: cache_dir.into_os_string(),
595            };
596            let json = serde_json::to_string_pretty(&default_config)
597                .context("Failed to serialize default local_config")?;
598            std::fs::write(&config_path, json)
599                .context("Failed to write default local_config")?;
600            return Ok(default_config);
601        }
602        let json = std::fs::read_to_string(&config_path)
603            .context("Failed to read local_config")?;
604        serde_json::from_str(&json)
605            .context("Failed to deserialize local_config")
606    }
607
608    pub fn create_graph(&mut self, label: &str) -> Result<&Graph> {
609        let new_graph_id = if self.graphs.is_empty() {
610            1
611        } else {
612            self.graphs
613                .iter()
614                .map(|g| g.graph_id)
615                .max()
616                .ok_or_else(|| anyhow!("Failed to get max graph id"))?
617                .saturating_add(1)
618        };
619        let new_graph = Graph::new(new_graph_id, label, self);
620        self.graphs.push(new_graph);
621        self.graphs
622            .last()
623            .ok_or_else(|| anyhow!("Failed to get max graph id"))
624    }
625
626    pub fn get_graph_count(&self) -> usize {
627        self.graphs.len()
628    }
629
630    pub fn get_graph_by_id(&self, id: u128) -> Option<&Graph> {
631        self.graphs.iter().find(|g| g.graph_id == id)
632    }
633}
634
635pub fn lock_by_name(
636    name: &str,
637) -> Result<(ResourceLock, Option<ResourceLock>)> {
638    // Always acquire name lock first
639    let name_lock = ResourceLock::acquire(USER_NAME_LOCK, &name)?;
640    // Then, resolve id (if any)
641    let maybe_user = UserPublicInfo::get_by_name(name)?;
642    let mut id_lock = None;
643    if let Some(user) = maybe_user {
644        let id = user.local_id;
645        id_lock = Some(lock_by_id(id)?);
646        // Double-check mapping hasn't changed while acquiring id lock
647        let user_check = UserPublicInfo::get_by_name(name)?;
648        if let Some(user_check) = user_check
649            && id != user_check.local_id
650        {
651            log!(format!(
652                "User ID changed during get_by_name for '{}': {} -> {}",
653                name, id, user_check.local_id
654            ));
655            bail!("User ID changed during lock acquisition");
656        }
657    }
658    Ok((name_lock, id_lock))
659}
660
661pub fn lock_by_id(user_id: u64) -> Result<ResourceLock> {
662    let id_lock = ResourceLock::acquire(USER_LOCK, &user_id.to_string())?;
663    Ok(id_lock)
664}
665
666fn get_user_id_by_name(name: &str) -> Option<u64> {
667    ipcb!(storage)
668        .get_user_by_name_b(name)
669        .ok()
670        .flatten()
671        .map(|u| u.id)
672}
673
674pub fn user_exists(name: &str) -> bool {
675    get_user_id_by_name(name).is_some()
676}
677
678pub fn add_non_admin_user(name: &str, password: &Password) -> Result<User> {
679    User::add_non_admin_user(name, password)
680}
681
682pub fn create_user_and_session(
683    username: &str,
684    password_bytes: Vec<u8>,
685    duration_secs: u64,
686) -> Result<String> {
687    ipcb!(storage).create_user_and_session_b(
688        username,
689        password_bytes,
690        duration_secs,
691    )
692}
693
694pub async fn create_user_and_session_async(
695    username: &str,
696    password_bytes: Vec<u8>,
697    duration_secs: u64,
698) -> Result<String> {
699    ipc!(storage)
700        .create_user_and_session(username, password_bytes, duration_secs)
701        .await
702}
703
704pub fn login_user(
705    username: &str,
706    password_bytes: Vec<u8>,
707    duration_secs: u64,
708) -> Result<String> {
709    ipcb!(storage).login_user_b(username, password_bytes, duration_secs)
710}
711
712pub async fn login_user_async(
713    username: &str,
714    password_bytes: Vec<u8>,
715    duration_secs: u64,
716) -> Result<String> {
717    ipc!(storage)
718        .login_user(username, password_bytes, duration_secs)
719        .await
720}
721
722pub fn change_user_password(
723    username: &str,
724    old_password_bytes: Vec<u8>,
725    new_password_bytes: Vec<u8>,
726) -> Result<()> {
727    ipcb!(storage).change_user_password_b(
728        username,
729        old_password_bytes,
730        new_password_bytes,
731    )
732}
733
734pub async fn change_user_password_async(
735    username: &str,
736    old_password_bytes: Vec<u8>,
737    new_password_bytes: Vec<u8>,
738) -> Result<()> {
739    ipc!(storage)
740        .change_user_password(username, old_password_bytes, new_password_bytes)
741        .await
742}
743
744pub fn validate_session(token: &str) -> Result<Option<u64>> {
745    ipcb!(storage).validate_session_b(token)
746}
747
748pub fn refresh_session(token: &str, duration_secs: u64) -> Result<()> {
749    ipcb!(storage).refresh_session_b(token, duration_secs)
750}
751
752pub fn invalidate_session(token: &str) -> Result<()> {
753    ipcb!(storage).invalidate_session_b(token)
754}
755
756fn get_user_password_by_id(user_id: u64) -> Option<String> {
757    ipcb!(storage)
758        .get_user_by_id_b(user_id)
759        .ok()
760        .flatten()
761        .and_then(|u| u.auth)
762}
763
764fn get_user_picture_by_id(user_id: u64) -> Option<Vec<u8>> {
765    ipcb!(storage)
766        .get_user_by_id_b(user_id)
767        .ok()
768        .flatten()
769        .and_then(|u| u.picture)
770}
771
772fn get_user_kek_params_by_id(user_id: u64) -> Option<Vec<u8>> {
773    ipcb!(storage)
774        .get_user_by_id_b(user_id)
775        .ok()
776        .flatten()
777        .and_then(|u| u.key_encryption_key_params)
778}
779
780fn get_user_wrapped_dek_by_id(user_id: u64) -> Option<Vec<u8>> {
781    ipcb!(storage)
782        .get_user_by_id_b(user_id)
783        .ok()
784        .flatten()
785        .and_then(|u| u.wrapped_dek)
786}
787#[cfg(test)]
788fn get_user_pubkey_by_id(user_id: u64) -> Option<Vec<u8>> {
789    ipcb!(storage)
790        .get_user_by_id_b(user_id)
791        .ok()
792        .flatten()
793        .and_then(|u| u.pubkey)
794}
795
796pub fn get_all_user_ids() -> Result<Vec<u64>> {
797    ensure_base_layout().context("Failed to ensure base layout")?;
798    ipcb!(storage).get_all_user_ids_b()
799}
800
801// --------- Internal helpers ----------
802
803fn ensure_base_layout() -> Result<()> {
804    let root = get_storage_dir().context("No storage dir")?;
805    let config_dir = root.join("config");
806    let users_dir = root.join("users");
807    let graphs_dir = root.join("graphs");
808    fs::create_dir_all(&config_dir)?;
809    fs::create_dir_all(&users_dir)?;
810    fs::create_dir_all(&graphs_dir)?;
811    Ok(())
812}
813
814fn next_user_id() -> Result<u64> {
815    User::increment_and_get_user_id()
816}
817
818#[expect(
819    clippy::panic,
820    clippy::expect_used,
821    reason = "Test user creation helper function panics on creation error"
822)]
823pub fn get_test_user(name: &str) -> User {
824    use crate::debug;
825
826    assert!(is_in_test(), "get_test_user called outside of test");
827
828    let _ = lock_by_name(name).expect("Could not lock name");
829    debug!(
830        "Thread {} acquired lock for test user '{}'",
831        // Reason for fallback: unnamed thread in test harness logs "<unnamed>"
832        std::thread::current().name().unwrap_or("unnamed"),
833        name
834    );
835    User::delete_by_name(name).ok();
836
837    assert!(
838        get_user_id_by_name(name).is_none(),
839        "Failed to delete test user."
840    );
841    debug!(
842        "Thread {} sees that test user not exists '{}'",
843        // Reason for fallback: unnamed thread in test harness logs "<unnamed>"
844        std::thread::current().name().unwrap_or("unnamed"),
845        name
846    );
847
848    let password = get_test_password();
849    // Reason for fallback: test user creation failure triggers test assertion panic with thread details
850    let mut user = User::create(name, &password).unwrap_or_else(|err| {
851        panic!(
852            "User creation failed {} due to error: {:?}",
853            // Reason for fallback: unnamed thread in test harness logs "<unnamed>"
854            std::thread::current().name().unwrap_or("unnamed"),
855            err
856        )
857    });
858    debug!(
859        "Thread {} was able to create user '{}'",
860        // Reason for fallback: unnamed thread in test harness logs "<unnamed>"
861        std::thread::current().name().unwrap_or("unnamed"),
862        name
863    );
864
865    let token = format!("test_session_token_{name}");
866    crate::user::session::register_test_session(
867        token.clone(),
868        user.local_id(),
869        3600,
870    );
871    user.set_session_token(Some(token));
872
873    user
874}
875
876fn get_test_password() -> Password {
877    assert!(is_in_test(), "get_test_password called outside of test");
878
879    Password::from_string(TEST_USER_PASS)
880}
881
882#[cfg(test)]
883#[allow(
884    clippy::panic,
885    clippy::expect_used,
886    clippy::unwrap_used,
887    clippy::unwrap_in_result,
888    clippy::panic_in_result_fn,
889    clippy::indexing_slicing,
890    clippy::arithmetic_side_effects,
891    reason = "Standard repository test boilerplate"
892)]
893mod tests {
894    use super::*;
895    use crate::{bail_if_none, debug};
896
897    fn get_test_user(name: &str) -> User {
898        super::get_test_user(name)
899    }
900
901    #[crate::ctb_test]
902    fn test_user_name_and_local_id() {
903        let user = User {
904            public_info: UserPublicInfo {
905                local_id: 42,
906                name: "alice".to_string(),
907                ..Default::default()
908            },
909            ..Default::default()
910        };
911        assert_eq!(user.name(), "alice");
912        assert_eq!(user.local_id(), 42);
913    }
914
915    #[crate::ctb_test]
916    fn test_user_picture_none() {
917        let user = User {
918            public_info: UserPublicInfo {
919                picture: None,
920                ..Default::default()
921            },
922            ..Default::default()
923        };
924        assert!(user.user_picture().is_none());
925    }
926
927    #[crate::ctb_test]
928    fn test_user_picture_some() {
929        let pic = vec![1, 2, 3];
930        let user = User {
931            public_info: UserPublicInfo {
932                picture: Some(pic.clone()),
933                ..Default::default()
934            },
935            ..Default::default()
936        };
937        assert_eq!(user.user_picture(), Some(pic.as_slice()));
938    }
939
940    #[crate::ctb_test]
941    fn test_create_and_get_graph_by_id() -> Result<()> {
942        let mut user = User {
943            public_info: UserPublicInfo {
944                local_id: 1,
945                name: "test_graph".to_string(),
946                ..Default::default()
947            },
948            ..Default::default()
949        };
950        let label = "test_graph_label";
951        let graph = user.create_graph(label)?;
952        assert_eq!(graph.label, label);
953        let id = graph.graph_id;
954        let fetched = bail_if_none!(user.get_graph_by_id(id));
955        assert_eq!(fetched.label, label);
956        Ok(())
957    }
958
959    #[crate::ctb_test]
960    fn test_get_graph_by_id_none() {
961        let user = User::default();
962        assert!(user.get_graph_by_id(12345).is_none());
963    }
964
965    #[crate::ctb_test]
966    fn test_get_all_user_ids() -> Result<()> {
967        let user = get_test_user(format!("{}_1", function_name!()).as_str());
968        let user2 = get_test_user(format!("{}_2", function_name!()).as_str());
969        let ids = get_all_user_ids()?;
970        assert!(ids.contains(&user.local_id()));
971        assert!(ids.contains(&user2.local_id()));
972        user.delete()?;
973        user2.delete()?;
974        Ok(())
975    }
976
977    #[crate::ctb_test]
978    fn test_create_and_login_user() -> Result<()> {
979        let name = function_name!();
980        User::delete_by_name(name).ok(); // .ok() swallows error
981
982        let password = Password::from_string(TEST_USER_PASS);
983        let user = super::get_test_user(name);
984        assert_eq!(user.name(), name);
985
986        let public_info = bail_if_none!(UserPublicInfo::get_by_name(name)?);
987        let logged_in = User::login(public_info, &password)?;
988        assert_eq!(logged_in.name(), name);
989
990        // Hold the lock until cleanup is done
991        logged_in.delete()?;
992        Ok(())
993    }
994
995    #[crate::ctb_test]
996    fn test_create_and_delete_user() -> Result<()> {
997        let user = get_test_user(function_name!());
998        user.delete()?;
999        assert!(get_user_id_by_name(&user.name()).is_none());
1000        debug!(get_user_password_by_id(user.local_id()));
1001        assert!(get_user_password_by_id(user.local_id()).is_none());
1002        assert!(get_user_picture_by_id(user.local_id()).is_none());
1003        assert!(get_user_kek_params_by_id(user.local_id()).is_none());
1004        assert!(get_user_wrapped_dek_by_id(user.local_id()).is_none());
1005        assert!(get_user_pubkey_by_id(user.local_id()).is_none());
1006        assert!(!fs::exists(
1007            get_storage_dir()?
1008                .join("graphs")
1009                .join(user.local_id().to_string())
1010        )?);
1011        Ok(())
1012    }
1013
1014    #[crate::ctb_test]
1015    fn test_create_duplicate_user_fails() -> Result<()> {
1016        let name = function_name!();
1017        let _ = lock_by_name(name).expect("Could not lock name");
1018        let user = get_test_user(name);
1019        drop(user);
1020        let res = User::create(name, &get_test_password());
1021        res.unwrap_err();
1022        get_test_user(name).delete()?;
1023        Ok(())
1024    }
1025
1026    #[crate::ctb_test]
1027    fn test_login_invalid_password_fails() -> Result<()> {
1028        let user = get_test_user(function_name!());
1029
1030        // Clone the picture if it exists, to avoid holding a reference after
1031        // user is dropped. Not sure if there's an easier way to do this.
1032        let picture = user.user_picture();
1033        let new_picture: Option<Vec<u8>> = if picture.is_none() {
1034            None
1035        } else {
1036            Some(
1037                user.user_picture()
1038                    .ok_or(anyhow::anyhow!("Failed to get user picture"))?
1039                    .to_vec(),
1040            )
1041        };
1042
1043        let new_public_info = UserPublicInfo {
1044            local_id: user.local_id(),
1045            name: user.name().clone(),
1046            display_name: user.display_name().map(<[u8]>::to_vec),
1047            uuid: user.uuid().clone(),
1048            picture: new_picture,
1049            lock: None,
1050            remote_status: None,
1051        };
1052
1053        // Drop the original user (and lock) before attempting login
1054        drop(user);
1055
1056        let res = User::login(
1057            new_public_info,
1058            &Password::from_string("wrong_password"),
1059        );
1060        res.unwrap_err();
1061
1062        Ok(())
1063    }
1064
1065    #[crate::ctb_test]
1066    fn test_local_config_roundtrip() -> Result<()> {
1067        let user = get_test_user(function_name!());
1068
1069        let config = user.local_config()?;
1070        assert_eq!(
1071            config.default_store_location,
1072            get_storage_dir()?.into_os_string()
1073        );
1074        user.delete()?;
1075        Ok(())
1076    }
1077
1078    #[crate::ctb_test]
1079    fn test_add_non_admin_user_disallowed_by_default() -> Result<()> {
1080        let name = function_name!();
1081        User::delete_by_name(name).ok();
1082        let password = Password::from_string(TEST_USER_PASS);
1083
1084        // By default, allow_local_account_creation is false
1085        let mut settings = crate::utilities::pc_settings::PcSettings::load()
1086            .unwrap_or_default();
1087        settings.allow_local_account_creation =
1088            ctb_utilities::json::maybe_value::MaybeValue::Value(false);
1089        settings.save()?;
1090
1091        let res = add_non_admin_user(name, &password);
1092        assert!(res.is_err());
1093        let err_msg = res.unwrap_err().to_string();
1094        assert!(err_msg.contains("disallowed in PC settings"));
1095        Ok(())
1096    }
1097
1098    #[crate::ctb_test]
1099    fn test_add_non_admin_user_allowed_when_enabled() -> Result<()> {
1100        let name = function_name!();
1101        User::delete_by_name(name).ok();
1102        let password = Password::from_string(TEST_USER_PASS);
1103
1104        let mut settings = crate::utilities::pc_settings::PcSettings::load()
1105            .unwrap_or_default();
1106        settings.allow_local_account_creation =
1107            ctb_utilities::json::maybe_value::MaybeValue::Value(true);
1108        settings.save()?;
1109
1110        let user = add_non_admin_user(name, &password)?;
1111        assert_eq!(user.name(), name);
1112        assert!(!user.is_admin());
1113
1114        user.delete()?;
1115        Ok(())
1116    }
1117
1118    #[crate::ctb_test]
1119    fn test_add_non_admin_user_rejects_admin_and_global() -> Result<()> {
1120        let mut settings = crate::utilities::pc_settings::PcSettings::load()
1121            .unwrap_or_default();
1122        settings.allow_local_account_creation =
1123            ctb_utilities::json::maybe_value::MaybeValue::Value(true);
1124        settings.save()?;
1125
1126        let password = Password::from_string(TEST_USER_PASS);
1127
1128        let res_admin = add_non_admin_user("admin", &password);
1129        assert!(res_admin.is_err());
1130        assert!(
1131            res_admin
1132                .unwrap_err()
1133                .to_string()
1134                .contains("Cannot create administrator account")
1135        );
1136
1137        let res_global = add_non_admin_user("global", &password);
1138        assert!(res_global.is_err());
1139        assert!(
1140            res_global
1141                .unwrap_err()
1142                .to_string()
1143                .contains("Cannot create administrator account")
1144        );
1145
1146        let res_empty = add_non_admin_user("   ", &password);
1147        assert!(res_empty.is_err());
1148        assert!(
1149            res_empty
1150                .unwrap_err()
1151                .to_string()
1152                .contains("Username cannot be empty")
1153        );
1154
1155        Ok(())
1156    }
1157
1158    #[crate::ctb_test("tokio")]
1159    async fn test_change_password_preserves_dek_and_revokes_old_sessions()
1160    -> Result<()> {
1161        let name = function_name!();
1162        User::delete_by_name(name).ok();
1163
1164        let old_pass_str = "old_compromised_password";
1165        let new_pass_str = "new_rotated_secure_password";
1166
1167        let old_session_token = create_user_and_session_async(
1168            name,
1169            old_pass_str.as_bytes().to_vec(),
1170            3600,
1171        )
1172        .await?;
1173
1174        let public_info = bail_if_none!(UserPublicInfo::get_by_name(name)?);
1175        let user_id = public_info.local_id;
1176        let original_dek = crate::user::session::get_user_dek(user_id)?;
1177
1178        let graphs_dir = get_storage_dir()?
1179            .join("graphs")
1180            .join(user_id.to_string());
1181        assert!(graphs_dir.is_dir());
1182
1183        // Wrong old password must fail and leave existing session intact
1184        let bad_res = change_user_password_async(
1185            name,
1186            b"wrong_old_password".to_vec(),
1187            new_pass_str.as_bytes().to_vec(),
1188        )
1189        .await;
1190        assert!(bad_res.is_err());
1191        assert!(
1192            bad_res
1193                .unwrap_err()
1194                .to_string()
1195                .contains("Invalid password")
1196        );
1197        assert_eq!(
1198            crate::user::session::validate_session(old_session_token.clone())
1199                .await?,
1200            Some(user_id)
1201        );
1202
1203        // Rotate password with valid old password
1204        change_user_password_async(
1205            name,
1206            old_pass_str.as_bytes().to_vec(),
1207            new_pass_str.as_bytes().to_vec(),
1208        )
1209        .await?;
1210
1211        // Old session must be revoked immediately
1212        assert_eq!(
1213            crate::user::session::validate_session(old_session_token).await?,
1214            None
1215        );
1216
1217        // Login with old password must now fail
1218        let old_login = login_user_async(
1219            name,
1220            old_pass_str.as_bytes().to_vec(),
1221            3600,
1222        )
1223        .await;
1224        assert!(old_login.is_err());
1225
1226        // Login with new password must succeed and unwrap the exact same DEK
1227        let new_session_token = login_user_async(
1228            name,
1229            new_pass_str.as_bytes().to_vec(),
1230            3600,
1231        )
1232        .await?;
1233        assert_eq!(
1234            crate::user::session::validate_session(new_session_token.clone())
1235                .await?,
1236            Some(user_id)
1237        );
1238        let rotated_dek = crate::user::session::get_user_dek(user_id)?;
1239        assert_eq!(original_dek, rotated_dek);
1240        assert!(graphs_dir.is_dir());
1241
1242        crate::user::session::invalidate_session(new_session_token).await?;
1243        User::delete_by_name(name)?;
1244        Ok(())
1245    }
1246}