ctb_storage/models/user/
session.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 session and cache management.
21//! Manages decrypted database encryption keys (DEKs) and active sessions.
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use crate::secret::Secret;
31use crate::user::{User, UserPublicInfo};
32use crate::utilities::password::Password;
33use anyhow::{Result, anyhow};
34use base64::Engine;
35use base64::engine::general_purpose::URL_SAFE_NO_PAD;
36use std::collections::HashMap;
37use std::path::{Path, PathBuf};
38use std::sync::{OnceLock, RwLock};
39use std::time::Instant;
40use zeroize::ZeroizeOnDrop;
41
42/// Represents an active user session.
43#[derive(ZeroizeOnDrop)]
44pub struct StorageSession {
45    token: String,
46    #[zeroize(skip)]
47    storage_dir: PathBuf,
48    user_id: u64,
49    #[zeroize(skip)]
50    expiry: Instant,
51}
52
53/// Global cache of decrypted user DEKs for database encryption, scoped by `(storage_dir, user_id)`.
54static USER_KEYS: OnceLock<RwLock<HashMap<(PathBuf, u64), Secret>>> =
55    OnceLock::new();
56
57fn user_keys() -> &'static RwLock<HashMap<(PathBuf, u64), Secret>> {
58    USER_KEYS.get_or_init(|| RwLock::new(HashMap::new()))
59}
60
61/// Global registry of active user sessions.
62static USER_SESSIONS: OnceLock<RwLock<HashMap<String, StorageSession>>> =
63    OnceLock::new();
64
65fn user_sessions() -> &'static RwLock<HashMap<String, StorageSession>> {
66    USER_SESSIONS.get_or_init(|| RwLock::new(HashMap::new()))
67}
68
69/// Get the decrypted user DEK bytes from memory cache.
70pub(crate) fn get_user_dek(user_id: u64) -> Result<Secret> {
71    let storage_dir = ctb_utilities::storage::get_storage_dir()?;
72    let keys = user_keys()
73        .read()
74        .map_err(|e| anyhow!("Keys lock poisoned: {e}"))?;
75    let secret = keys.get(&(storage_dir, user_id)).ok_or_else(|| {
76        anyhow!(
77            "Encryption key (DEK) not registered/available for user {user_id}"
78        )
79    })?;
80    let secret: Secret = secret.clone();
81    Ok(secret)
82}
83
84/// Register a user's decrypted DEK in memory for database encryption.
85pub(crate) fn register_user_dek(user_id: u64, dek: Secret) -> Result<()> {
86    let storage_dir = ctb_utilities::storage::get_storage_dir()?;
87    let mut keys = user_keys()
88        .write()
89        .map_err(|e| anyhow!("Keys lock poisoned: {e}"))?;
90    keys.insert((storage_dir, user_id), dek);
91    Ok(())
92}
93
94fn deregister_user_in_dir(storage_dir: &Path, user_id: u64) -> Result<()> {
95    // 1. Remove and drop the key (zeroizing its memory)
96    {
97        let mut keys = user_keys()
98            .write()
99            .map_err(|e| anyhow!("Keys lock poisoned: {e}"))?;
100        keys.remove(&(storage_dir.to_path_buf(), user_id));
101    }
102
103    // 2. Remove the database handles from connection pool in db
104    crate::db::close_connections_in_dir(storage_dir, user_id)?;
105
106    Ok(())
107}
108
109/// Deregister a user's decrypted DEK and close/clear their database connections.
110#[ipc_method]
111pub async fn deregister_user(user_id: u64) -> Result<()> {
112    let storage_dir = ctb_utilities::storage::get_storage_dir()?;
113    deregister_user_in_dir(&storage_dir, user_id)
114}
115
116/// Register an active session.
117pub(crate) async fn register_session(
118    token: String,
119    user_id: u64,
120    dek: Secret,
121    duration_secs: u64,
122) -> Result<()> {
123    let storage_dir = ctb_utilities::storage::get_storage_dir()?;
124    // Register the user DEK
125    register_user_dek(user_id, dek)?;
126
127    // Store the session
128    {
129        let mut sessions = user_sessions()
130            .write()
131            .map_err(|e| anyhow!("Sessions lock poisoned: {e}"))?;
132        sessions.insert(
133            token.clone(),
134            StorageSession {
135                token,
136                storage_dir,
137                user_id,
138                expiry: Instant::now()
139                    .checked_add(std::time::Duration::from_secs(duration_secs))
140                    .ok_or_else(|| anyhow!("Instant overflow"))?,
141            },
142        );
143    }
144
145    // Start background check loop if not running
146    ensure_eviction_task();
147
148    Ok(())
149}
150
151#[expect(dead_code, reason = "test helper function")]
152pub(crate) fn register_test_session(
153    token: String,
154    user_id: u64,
155    duration_secs: u64,
156) {
157    let Ok(storage_dir) = ctb_utilities::storage::get_storage_dir() else {
158        return;
159    };
160    if let Ok(mut sessions) = user_sessions().write() {
161        sessions.insert(
162            token.clone(),
163            StorageSession {
164                token,
165                storage_dir,
166                user_id,
167                expiry: Instant::now()
168                    .checked_add(std::time::Duration::from_secs(duration_secs))
169                    .unwrap_or_else(Instant::now),
170            },
171        );
172    }
173}
174
175/// Login user: verifies password, derives keys, registers session, and returns session token.
176#[ipc_method]
177pub async fn login_user(
178    username: String,
179    mut password_bytes: Vec<u8>,
180    duration_secs: u64,
181) -> Result<String> {
182    let user_info = UserPublicInfo::get_by_name(&username)?
183        .ok_or_else(|| anyhow!("User '{username}' not found"))?;
184
185    let password = Password {
186        password: password_bytes.clone(),
187    };
188    use zeroize::Zeroize;
189    password_bytes.zeroize();
190
191    let mut user = User::login(user_info, &password)?;
192
193    // Generate random 32-byte session token
194    let mut session_bytes = [0u8; 32];
195    rand::RngCore::fill_bytes(&mut rand::rng(), &mut session_bytes);
196    let token = URL_SAFE_NO_PAD.encode(session_bytes);
197    session_bytes.zeroize();
198
199    // Register session locally
200    let dek = user.take_dek().ok_or_else(|| anyhow!("User has no DEK"))?;
201    register_session(token.clone(), user.local_id(), dek, duration_secs)
202        .await?;
203
204    Ok(token)
205}
206
207/// Create user and session: creates a new user, registers session, and returns session token.
208#[ipc_method]
209pub async fn create_user_and_session(
210    username: String,
211    mut password_bytes: Vec<u8>,
212    duration_secs: u64,
213) -> Result<String> {
214    let password = Password {
215        password: password_bytes.clone(),
216    };
217    use zeroize::Zeroize;
218    password_bytes.zeroize();
219
220    let mut user = User::create(&username, &password)?;
221
222    // Generate random 32-byte session token
223    let mut session_bytes = [0u8; 32];
224    rand::RngCore::fill_bytes(&mut rand::rng(), &mut session_bytes);
225    let token = URL_SAFE_NO_PAD.encode(session_bytes);
226    session_bytes.zeroize();
227
228    // Register session locally
229    let dek = user.take_dek().ok_or_else(|| anyhow!("User has no DEK"))?;
230    register_session(token.clone(), user.local_id(), dek, duration_secs)
231        .await?;
232
233    Ok(token)
234}
235
236/// Rotate a user's password while preserving their DEK, and revoke all existing
237/// sessions for that user.
238#[ipc_method]
239pub async fn change_user_password(
240    username: String,
241    mut old_password_bytes: Vec<u8>,
242    mut new_password_bytes: Vec<u8>,
243) -> Result<()> {
244    use zeroize::Zeroize;
245
246    let mut old_password = Password {
247        password: old_password_bytes.clone(),
248    };
249    old_password_bytes.zeroize();
250
251    let mut new_password = Password {
252        password: new_password_bytes.clone(),
253    };
254    new_password_bytes.zeroize();
255
256    let change_res =
257        User::change_password(&username, &old_password, &new_password);
258    old_password.password.zeroize();
259    new_password.password.zeroize();
260    let user_id = change_res?;
261
262    let storage_dir = ctb_utilities::storage::get_storage_dir()?;
263    let tokens_to_revoke: Vec<String> = {
264        let sessions = user_sessions()
265            .read()
266            .map_err(|e| anyhow!("Sessions lock poisoned: {e}"))?;
267        sessions
268            .iter()
269            .filter(|(_, s)| {
270                s.storage_dir == storage_dir && s.user_id == user_id
271            })
272            .map(|(token, _)| token.clone())
273            .collect()
274    };
275
276    for token in tokens_to_revoke {
277        invalidate_session_internal(&token).await?;
278    }
279
280    Ok(())
281}
282
283/// Refresh an active session.
284#[ipc_method]
285pub async fn refresh_session(token: String, duration_secs: u64) -> Result<()> {
286    let mut sessions = user_sessions()
287        .write()
288        .map_err(|e| anyhow!("Sessions lock poisoned: {e}"))?;
289    if let Some(session) = sessions.get_mut(&token) {
290        session.expiry = Instant::now()
291            .checked_add(std::time::Duration::from_secs(duration_secs))
292            .ok_or_else(|| anyhow!("Instant overflow"))?;
293        Ok(())
294    } else {
295        Err(anyhow!("Session not found or expired"))
296    }
297}
298
299/// Validate a session and return the user ID.
300#[ipc_method]
301pub async fn validate_session(token: String) -> Result<Option<u64>> {
302    let storage_dir = ctb_utilities::storage::get_storage_dir()?;
303    let now = Instant::now();
304    let mut expired = false;
305    let mut user_id = None;
306
307    {
308        let sessions = user_sessions()
309            .read()
310            .map_err(|e| anyhow!("Sessions lock poisoned: {e}"))?;
311        if let Some(session) = sessions.get(&token)
312            && session.storage_dir == storage_dir
313        {
314            if now > session.expiry {
315                expired = true;
316            } else {
317                user_id = Some(session.user_id);
318            }
319        }
320    }
321
322    if expired {
323        invalidate_session_internal(&token).await?;
324        Ok(None)
325    } else {
326        Ok(user_id)
327    }
328}
329
330/// Invalidate a session.
331#[ipc_method]
332pub async fn invalidate_session(token: String) -> Result<()> {
333    invalidate_session_internal(&token).await
334}
335
336static BACKGROUND_TASK_SPAWNED: OnceLock<()> = OnceLock::new();
337
338fn ensure_eviction_task() {
339    BACKGROUND_TASK_SPAWNED.get_or_init(|| {
340        if let Ok(handle) = tokio::runtime::Handle::try_current() {
341            handle.spawn(async {
342                loop {
343                    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
344                    if let Err(e) = active_evict_expired_sessions().await {
345                        error!(format!(
346                            "Error in active session eviction loop: {e}"
347                        ));
348                    }
349                }
350            });
351        }
352    });
353}
354
355async fn active_evict_expired_sessions() -> Result<()> {
356    let now = Instant::now();
357    let expired_tokens: Vec<(String, u64)> = {
358        let sessions = user_sessions()
359            .read()
360            .map_err(|e| anyhow!("Sessions lock poisoned: {e}"))?;
361        sessions
362            .iter()
363            .filter(|(_, s)| now > s.expiry)
364            .map(|(k, s)| (k.clone(), s.user_id))
365            .collect()
366    };
367
368    for (token, user_id) in expired_tokens {
369        log!(format!(
370            "Active session eviction: session token expired for user {user_id}"
371        ));
372        if let Err(e) = invalidate_session_internal(&token).await {
373            error!(format!("Failed to invalidate expired session: {e}"));
374        }
375    }
376    Ok(())
377}
378
379async fn invalidate_session_internal(token: &str) -> Result<()> {
380    let (user_key, has_other_sessions) = {
381        let mut sessions = user_sessions()
382            .write()
383            .map_err(|e| anyhow!("Sessions lock poisoned: {e}"))?;
384        if let Some(session) = sessions.remove(token) {
385            let user_id = session.user_id;
386            let storage_dir = session.storage_dir.clone();
387            let has_other_sessions = sessions
388                .values()
389                .any(|s| s.storage_dir == storage_dir && s.user_id == user_id);
390            (Some((storage_dir, user_id)), has_other_sessions)
391        } else {
392            (None, false)
393        }
394    };
395
396    if let Some((storage_dir, user_id)) = user_key {
397        if !has_other_sessions {
398            log!(format!(
399                "No active sessions left for user {user_id}. Deregistering."
400            ));
401            if let Err(e) = deregister_user_in_dir(&storage_dir, user_id) {
402                error!(format!(
403                    "Failed to automatically deregister user {user_id}: {e}"
404                ));
405            }
406        }
407    }
408    Ok(())
409}
410
411#[cfg(test)]
412#[allow(
413    clippy::panic,
414    clippy::expect_used,
415    clippy::unwrap_used,
416    clippy::unwrap_in_result,
417    clippy::panic_in_result_fn,
418    clippy::indexing_slicing,
419    clippy::arithmetic_side_effects,
420    reason = "Standard repository test boilerplate"
421)]
422mod tests {
423    use super::*;
424
425    #[crate::ctb_test("tokio")]
426    async fn test_storage_sessions() -> Result<()> {
427        let user_id = 12345u64;
428        let token = "test_token_xyz".to_string();
429        let dek_bytes = vec![0x99u8; 32];
430
431        // 1. Register session
432        register_session(
433            token.clone(),
434            user_id,
435            Secret::new(dek_bytes.clone()),
436            2,
437        )
438        .await?;
439
440        // DEK should be cached
441        assert_eq!(get_user_dek(user_id)?, Secret::new(dek_bytes.clone()));
442
443        // Session should validate
444        assert_eq!(validate_session(token.clone()).await?, Some(user_id));
445
446        // 2. Refresh session
447        refresh_session(token.clone(), 5).await?;
448
449        // 3. Invalidate session
450        invalidate_session(token.clone()).await?;
451        assert_eq!(validate_session(token.clone()).await?, None);
452
453        // DEK should be evicted (since it was the last session)
454        get_user_dek(user_id).unwrap_err();
455
456        // 4. Test active eviction on expiration
457        let short_token = "short_token".to_string();
458        register_session(
459            short_token.clone(),
460            user_id,
461            Secret::new(dek_bytes.clone()),
462            1,
463        )
464        .await?;
465
466        // Wait 1.5 seconds for active eviction loop to run
467        tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
468
469        // Session should be evicted
470        assert_eq!(validate_session(short_token.clone()).await?, None);
471        // DEK should be evicted
472        get_user_dek(user_id).unwrap_err();
473
474        Ok(())
475    }
476}