ctb_storage/models/user/
auth.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//! Password hashing, authentication credentials, and user security models.
21
22#[expect(unused_imports, reason = "imported module dependencies")]
23use crate::utilities::*;
24
25use crate::utilities::password::Password;
26use anyhow::Result;
27use argon2::Argon2;
28#[cfg(any(debug_assertions, test))]
29use argon2::password_hash::PasswordHash;
30use argon2::password_hash::SaltString;
31use argon2::password_hash::rand_core::OsRng;
32use serde::{Deserialize, Serialize};
33use zeroize::ZeroizeOnDrop;
34
35/// KEK derivation parameters to be stored in the SQLite table
36/// `users_key_encryption_key_params` in `users.db`.
37/// For now this is a stub structure that you can later wire to Argon2id properly.
38#[derive(Debug, Clone, Serialize, Deserialize, ZeroizeOnDrop, PartialEq)]
39pub struct KekParams {
40    pub salt: Vec<u8>,
41    // Argon2id cost parameters
42    pub m_cost: u32,
43    pub t_cost: u32,
44    pub p_cost: u32,
45}
46
47/// Derive a Key Encryption Key (KEK) from a password using Argon2id.
48/// Returns the derived KEK and the salt used in the derivation.
49/// The KEK is suitable for AES-256 encryption.
50/// It's not clear if this is all correct. See:
51/// <https://docs.rs/argon2/latest/argon2/#key-derivation>
52/// <https://rustcrypto.org/key-derivation/index.html>
53/// <https://cheatsheetseries.owasp.org/cheatsheets/Key_Management_Cheat_Sheet.html#key-encryption-keys>
54/// (last two are basically blank.)
55pub fn derive_kek(password: &Password) -> Result<(Vec<u8>, KekParams)> {
56    // If in debug or test and password is TEST_USER_PASS, use hardcoded PHC
57    #[cfg(any(debug_assertions, test))]
58    {
59        if password.password == crate::user::TEST_USER_PASS.as_bytes() {
60            // Hardcoded PHC string
61
62            use crate::utilities::password::TEST_USER_PHC;
63            let parsed = PasswordHash::new(TEST_USER_PHC)
64                .map_err(|e| anyhow::anyhow!("Failed to parse PHC: {e}"))?;
65            let salt_bytes = &mut [0u8; 16];
66            let salt = parsed.salt.ok_or_else(|| {
67                anyhow::anyhow!("Could not decode test password salt")
68            })?;
69            salt.decode_b64(salt_bytes)
70                .map_err(|e| anyhow::anyhow!("Failed to decode salt: {e}"))?;
71            // Reason for fallback: Argon2 password hash output missing hash bytes defaults to empty vector
72            let output_key_material =
73                parsed.hash.as_ref().map_or_else(
74                    Vec::new,
75                    |h: &argon2::password_hash::Output| h.as_bytes().to_vec(),
76                );
77            return Ok((
78                output_key_material,
79                KekParams {
80                    // Reason for fallback: invalid or unparsed Argon2 m_cost parameter defaults to recommended 19456 KiB
81                    m_cost: parsed
82                        .params
83                        .get("m")
84                        .map_or(19456, |v| v.decimal().unwrap_or(19456)),
85                    // Reason for fallback: invalid or unparsed Argon2 t_cost parameter defaults to recommended 2 iterations
86                    t_cost: parsed
87                        .params
88                        .get("t")
89                        .map_or(2, |v| v.decimal().unwrap_or(2)),
90                    // Reason for fallback: invalid or unparsed Argon2 p_cost parameter defaults to recommended 1 parallelism degree
91                    p_cost: parsed
92                        .params
93                        .get("p")
94                        .map_or(1, |v| v.decimal().unwrap_or(1)),
95                    salt: salt_bytes.to_vec(),
96                },
97            ));
98        }
99    }
100    // 32 * 8 = 256 bits which is suitable for AES-256
101    let mut output_key_material = vec![0u8; 32];
102    let salt = SaltString::generate(&mut OsRng);
103    // Recommended length from password-hash 0.5.0 salt.rs is 16 bytes
104    let mut salt_bytes = [0u8; 16];
105    salt.decode_b64(&mut salt_bytes)
106        .map_err(|e| anyhow::anyhow!("Failed to decode salt: {e}"))?;
107    let hasher = Argon2::default();
108    let params = hasher.params();
109    hasher
110        .hash_password_into(
111            &password.password,
112            &salt_bytes,
113            &mut output_key_material,
114        )
115        .map_err(|e| anyhow::anyhow!("Failed to derive KEK: {e:?}"))?;
116    Ok((
117        output_key_material,
118        KekParams {
119            salt: salt_bytes.to_vec(),
120            m_cost: params.m_cost(),
121            t_cost: params.t_cost(),
122            p_cost: params.p_cost(),
123        },
124    ))
125}
126
127// TODO: Remaining pieces are LLM-generated; haven't checked them for correctness.
128
129/// Derive a Key Encryption Key (KEK) from a password using specific `KekParams`.
130pub fn derive_kek_with_params(
131    password: &Password,
132    params: &KekParams,
133) -> Result<Vec<u8>> {
134    // If in debug or test and password is TEST_USER_PASS, use hardcoded PHC
135    #[cfg(any(debug_assertions, test))]
136    {
137        if password.password == crate::user::TEST_USER_PASS.as_bytes() {
138            let parsed =
139                PasswordHash::new(crate::utilities::password::TEST_USER_PHC)
140                    .map_err(|e| anyhow::anyhow!("Failed to parse PHC: {e}"))?;
141            let hash = parsed
142                .hash
143                .ok_or_else(|| anyhow::anyhow!("Missing hash in PHC"))?;
144            let output_key_material = hash.as_bytes().to_vec();
145            return Ok(output_key_material);
146        }
147    }
148
149    let mut output_key_material = vec![0u8; 32];
150    let argon2_params = argon2::Params::new(
151        params.m_cost,
152        params.t_cost,
153        params.p_cost,
154        Some(output_key_material.len()),
155    )
156    .map_err(|e| anyhow::anyhow!("Invalid Argon2 params: {e:?}"))?;
157
158    let hasher = Argon2::new(
159        argon2::Algorithm::Argon2id,
160        argon2::Version::V0x13,
161        argon2_params,
162    );
163    hasher
164        .hash_password_into(
165            &password.password,
166            &params.salt,
167            &mut output_key_material,
168        )
169        .map_err(|e| anyhow::anyhow!("Failed to derive KEK: {e:?}"))?;
170
171    Ok(output_key_material)
172}
173
174/// Generate a cryptographically secure 32-byte Database Encryption Key (DEK)
175/// using the OS random number generator.
176pub fn generate_dek() -> Result<Vec<u8>> {
177    crate::utilities::rand_bytes(32)
178}
179
180/// Wrap the DEK under a KEK (Key Encryption Key) using AES-256-GCM.
181/// Additional Authenticated Data (AAD) is used to prevent key substitution.
182/// Returns the nonce (12 bytes) prepended to the ciphertext.
183pub fn wrap_key(kek: &[u8], dek: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
184    use aes_gcm::{
185        Aes256Gcm, Nonce,
186        aead::{Aead, KeyInit, Payload},
187    };
188
189    // Generate a secure 12-byte nonce
190    let nonce_bytes = crate::utilities::rand_bytes(12)?;
191    let nonce = Nonce::try_from(nonce_bytes.as_slice())
192        .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
193
194    let cipher = Aes256Gcm::new_from_slice(kek).map_err(|e| {
195        anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
196    })?;
197
198    let payload = Payload { msg: dek, aad };
199    let ciphertext = cipher
200        .encrypt(&nonce, payload)
201        .map_err(|e| anyhow::anyhow!("DEK encryption failed: {e:?}"))?;
202
203    let mut out = nonce_bytes;
204    out.extend_from_slice(&ciphertext);
205    Ok(out)
206}
207
208/// Unwrap the DEK using the KEK (Key Encryption Key) and AES-256-GCM.
209/// Expects the 12-byte nonce prepended to the ciphertext.
210pub fn unwrap_key(kek: &[u8], wrapped: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
211    use aes_gcm::{
212        Aes256Gcm, Nonce,
213        aead::{Aead, KeyInit, Payload},
214    };
215
216    if wrapped.len() < 12 {
217        anyhow::bail!("Invalid wrapped key length");
218    }
219
220    let (nonce_bytes, ciphertext) = wrapped.split_at(12);
221    let nonce = Nonce::try_from(nonce_bytes)
222        .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
223
224    let cipher = Aes256Gcm::new_from_slice(kek).map_err(|e| {
225        anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
226    })?;
227
228    let payload = Payload {
229        msg: ciphertext,
230        aad,
231    };
232    let plaintext = cipher
233        .decrypt(&nonce, payload)
234        .map_err(|e| anyhow::anyhow!("DEK decryption failed: {e:?}"))?;
235
236    Ok(plaintext)
237}
238
239/// Seal bytes (encrypt and authenticate) using AES-256-GCM.
240/// Returns the nonce (12 bytes) prepended to the ciphertext.
241pub fn seal_bytes(key: &[u8], aad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>> {
242    use aes_gcm::{
243        Aes256Gcm, Nonce,
244        aead::{Aead, KeyInit, Payload},
245    };
246
247    let nonce_bytes = crate::utilities::rand_bytes(12)?;
248    let nonce = Nonce::try_from(nonce_bytes.as_slice())
249        .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
250
251    let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| {
252        anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
253    })?;
254
255    let payload = Payload {
256        msg: plaintext,
257        aad,
258    };
259    let ciphertext = cipher
260        .encrypt(&nonce, payload)
261        .map_err(|e| anyhow::anyhow!("Encryption failed: {e:?}"))?;
262
263    let mut out = nonce_bytes;
264    out.extend_from_slice(&ciphertext);
265    Ok(out)
266}
267
268/// Open sealed bytes (decrypt and verify authentication) using AES-256-GCM.
269/// Expects the 12-byte nonce prepended to the ciphertext.
270pub fn open_bytes(
271    key: &[u8],
272    aad: &[u8],
273    ciphertext: &[u8],
274) -> Result<Vec<u8>> {
275    use aes_gcm::{
276        Aes256Gcm, Nonce,
277        aead::{Aead, KeyInit, Payload},
278    };
279
280    if ciphertext.len() < 12 {
281        anyhow::bail!("Invalid ciphertext length");
282    }
283
284    let (nonce_bytes, ciphertext_actual) = ciphertext.split_at(12);
285    let nonce = Nonce::try_from(nonce_bytes)
286        .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
287
288    let cipher = Aes256Gcm::new_from_slice(key).map_err(|e| {
289        anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
290    })?;
291
292    let payload = Payload {
293        msg: ciphertext_actual,
294        aad,
295    };
296    let plaintext = cipher
297        .decrypt(&nonce, payload)
298        .map_err(|e| anyhow::anyhow!("Decryption failed: {e:?}"))?;
299
300    Ok(plaintext)
301}