ctb_io_csc/
index_meta.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//! Metadata and encryption key management for password-protected Turso indexes
21//! using companion `*.cscidxmeta` files.
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use aes_gcm::{
31    Aes256Gcm, Nonce,
32    aead::{Aead, KeyInit, Payload},
33};
34use base64::Engine;
35use base64::prelude::BASE64_STANDARD;
36use ctb_utilities::password::Password;
37use serde::{Deserialize, Serialize};
38use std::io::IsTerminal;
39use std::io::Read;
40use std::path::{Path, PathBuf};
41
42const DEK_AAD: &[u8] = b"ctb-fsindex-dek-v1";
43const DEFAULT_M_COST: u32 = 19456;
44const DEFAULT_T_COST: u32 = 2;
45const DEFAULT_P_COST: u32 = 1;
46const TURSO_CIPHER: &str = "aegis256";
47const KDF_ALGO: &str = "argon2id";
48
49/// Metadata stored in companion `*.cscidxmeta` files for password-protected indexes.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct FsIndexMeta {
52    /// Format version for index metadata (current: 1).
53    pub format_version: u32,
54    /// Cipher used for Turso page-level encryption (e.g. "aegis256").
55    pub cipher: String,
56    /// Key derivation function used (e.g. "argon2id").
57    pub kdf: String,
58    /// Argon2id KEK derivation parameters.
59    pub kek_params: IndexKekParams,
60    /// Base64-encoded wrapped DEK (12-byte nonce + 32-byte ciphertext + 16-byte GCM tag).
61    pub wrapped_dek: String,
62    /// Creation timestamp (Unix epoch in seconds).
63    pub created_at_sec: i64,
64}
65
66/// Parameters for Argon2id key derivation stored in `*.cscidxmeta`.
67#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
68pub struct IndexKekParams {
69    /// Base64-encoded 16-byte random salt.
70    pub salt_base64: String,
71    /// Argon2 memory cost in KiB.
72    pub m_cost: u32,
73    /// Argon2 time cost / iterations.
74    pub t_cost: u32,
75    /// Argon2 parallelism degree.
76    pub p_cost: u32,
77}
78
79/// Inspects the first 5 bytes of a file to check if it matches Turso's encrypted
80/// page header (`b"Turso"`). Returns false if the file does not exist or has
81/// fewer than 5 bytes.
82pub fn is_database_encrypted(db_path: &Path) -> Result<bool> {
83    if !db_path.exists() {
84        return Ok(false);
85    }
86    let mut file = std::fs::File::open(db_path).with_context(|| {
87        format!(
88            "Failed to open database for header check: {}",
89            db_path.display()
90        )
91    })?;
92    let mut header = [0u8; 5];
93    let count = file.read(&mut header)?;
94    if count >= 5 && &header[..5] == b"Turso" {
95        Ok(true)
96    } else {
97        Ok(false)
98    }
99}
100
101/// Computes the expected companion *.cscidxmeta path for a given database path.
102/// E.g. `foo.cscindex.sqlite` -> `foo.cscidxmeta`, `bar.db` -> `bar.cscidxmeta`.
103#[must_use]
104pub fn resolve_meta_path(db_path: &Path) -> PathBuf {
105    let path_str = db_path.to_string_lossy();
106    if let Some(prefix) = path_str.strip_suffix(".cscindex.sqlite") {
107        PathBuf::from(format!("{prefix}.cscidxmeta"))
108    } else if let Some(prefix) = path_str.strip_suffix(".sqlite") {
109        PathBuf::from(format!("{prefix}.cscidxmeta"))
110    } else if let Some(prefix) = path_str.strip_suffix(".db") {
111        PathBuf::from(format!("{prefix}.cscidxmeta"))
112    } else {
113        let mut meta = db_path.as_os_str().to_os_string();
114        meta.push(".cscidxmeta");
115        PathBuf::from(meta)
116    }
117}
118
119/// Discovers an existing *.cscidxmeta file for the database.
120/// Checks the standard `<stem>.cscidxmeta` first, then `<db_path>.cscidxmeta`.
121#[must_use]
122pub fn find_meta_path(db_path: &Path) -> Option<PathBuf> {
123    let standard = resolve_meta_path(db_path);
124    if standard.exists() {
125        return Some(standard);
126    }
127    let direct = PathBuf::from(format!("{}.cscidxmeta", db_path.display()));
128    if direct.exists() {
129        return Some(direct);
130    }
131    None
132}
133
134/// Saves index metadata as formatted JSON to the specified path.
135pub fn save_index_meta(meta_path: &Path, meta: &FsIndexMeta) -> Result<()> {
136    if let Some(parent) = meta_path.parent() {
137        std::fs::create_dir_all(parent)?;
138    }
139    let json = serde_json::to_string_pretty(meta)
140        .context("Failed to serialize index metadata to JSON")?;
141    std::fs::write(meta_path, json.as_bytes()).with_context(|| {
142        format!("Failed to write index metadata to {}", meta_path.display())
143    })?;
144    Ok(())
145}
146
147/// Loads and parses index metadata from the specified path.
148pub fn load_index_meta(meta_path: &Path) -> Result<FsIndexMeta> {
149    let bytes = std::fs::read(meta_path).with_context(|| {
150        format!("Failed to read index metadata from {}", meta_path.display())
151    })?;
152    let meta: FsIndexMeta =
153        serde_json::from_slice(&bytes).with_context(|| {
154            format!(
155                "Failed to parse index metadata from {}",
156                meta_path.display()
157            )
158        })?;
159    Ok(meta)
160}
161
162/// Securely generates a new random DEK, derives an Argon2id KEK from the password,
163/// wraps the DEK under AES-256-GCM, and returns both the metadata structure and raw DEK.
164pub fn create_encrypted_index_meta(
165    password: &Password,
166) -> Result<(FsIndexMeta, Vec<u8>)> {
167    // 1. Generate 32-byte cryptographically secure DEK
168    let dek = ctb_utilities::rand_bytes(32)
169        .context("Failed to generate random DEK")?;
170
171    // 2. Generate 16-byte random salt
172    let salt = ctb_utilities::rand_bytes(16)
173        .context("Failed to generate random salt")?;
174
175    // 3. Derive 32-byte KEK using Argon2id
176    let mut kek = vec![0u8; 32];
177    let argon2_params = argon2::Params::new(
178        DEFAULT_M_COST,
179        DEFAULT_T_COST,
180        DEFAULT_P_COST,
181        Some(kek.len()),
182    )
183    .map_err(|e| anyhow::anyhow!("Invalid Argon2 parameters: {e:?}"))?;
184
185    let hasher = argon2::Argon2::new(
186        argon2::Algorithm::Argon2id,
187        argon2::Version::V0x13,
188        argon2_params,
189    );
190    hasher
191        .hash_password_into(&password.password, &salt, &mut kek)
192        .map_err(|e| {
193            anyhow::anyhow!("Failed to derive KEK with Argon2id: {e:?}")
194        })?;
195
196    // 4. Wrap DEK using AES-256-GCM
197    let nonce_bytes = ctb_utilities::rand_bytes(12)
198        .context("Failed to generate AES-GCM nonce")?;
199    let nonce = Nonce::try_from(nonce_bytes.as_slice())
200        .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
201
202    let cipher = Aes256Gcm::new_from_slice(&kek).map_err(|e| {
203        anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
204    })?;
205
206    let payload = Payload {
207        msg: &dek,
208        aad: DEK_AAD,
209    };
210    let ciphertext = cipher
211        .encrypt(&nonce, payload)
212        .map_err(|e| anyhow::anyhow!("Failed to encrypt DEK: {e:?}"))?;
213
214    let mut wrapped = nonce_bytes;
215    wrapped.extend_from_slice(&ciphertext);
216
217    // 5. Build metadata struct
218    // Reason for fallback: system time before UNIX epoch or integer overflow defaults to timestamp 0
219    let now_sec = std::time::SystemTime::now()
220        .duration_since(std::time::UNIX_EPOCH)
221        .ok()
222        .and_then(|d| i64::try_from(d.as_secs()).ok())
223        .unwrap_or(0);
224
225    let meta = FsIndexMeta {
226        format_version: 1,
227        cipher: TURSO_CIPHER.to_string(),
228        kdf: KDF_ALGO.to_string(),
229        kek_params: IndexKekParams {
230            salt_base64: BASE64_STANDARD.encode(&salt),
231            m_cost: DEFAULT_M_COST,
232            t_cost: DEFAULT_T_COST,
233            p_cost: DEFAULT_P_COST,
234        },
235        wrapped_dek: BASE64_STANDARD.encode(&wrapped),
236        created_at_sec: now_sec,
237    };
238
239    Ok((meta, dek))
240}
241
242/// Derives the KEK from the password using the salt and parameters stored in `meta`,
243/// then unwraps and authenticates the DEK using AES-256-GCM.
244pub fn unlock_index_dek(
245    meta: &FsIndexMeta,
246    password: &Password,
247) -> Result<Vec<u8>> {
248    // 1. Decode salt
249    let salt = BASE64_STANDARD
250        .decode(&meta.kek_params.salt_base64)
251        .context("Failed to decode salt from metadata")?;
252
253    // 2. Derive KEK using Argon2id with stored params
254    let mut kek = vec![0u8; 32];
255    let argon2_params = argon2::Params::new(
256        meta.kek_params.m_cost,
257        meta.kek_params.t_cost,
258        meta.kek_params.p_cost,
259        Some(kek.len()),
260    )
261    .map_err(|e| {
262        anyhow::anyhow!("Invalid Argon2 parameters in metadata: {e:?}")
263    })?;
264
265    let hasher = argon2::Argon2::new(
266        argon2::Algorithm::Argon2id,
267        argon2::Version::V0x13,
268        argon2_params,
269    );
270    hasher
271        .hash_password_into(&password.password, &salt, &mut kek)
272        .map_err(|e| {
273            anyhow::anyhow!("Failed to derive KEK with Argon2id: {e:?}")
274        })?;
275
276    // 3. Decode wrapped DEK
277    let wrapped = BASE64_STANDARD
278        .decode(&meta.wrapped_dek)
279        .context("Failed to decode wrapped DEK from metadata")?;
280
281    if wrapped.len() < 12 {
282        anyhow::bail!(
283            "Corrupt metadata: wrapped DEK is shorter than 12-byte nonce"
284        );
285    }
286
287    let (nonce_bytes, ciphertext) = wrapped.split_at(12);
288    let nonce = Nonce::try_from(nonce_bytes)
289        .map_err(|_| anyhow::anyhow!("Invalid nonce length"))?;
290
291    let cipher = Aes256Gcm::new_from_slice(&kek).map_err(|e| {
292        anyhow::anyhow!("Failed to initialize AES-GCM cipher: {e:?}")
293    })?;
294
295    let payload = Payload {
296        msg: ciphertext,
297        aad: DEK_AAD,
298    };
299
300    let dek = cipher.decrypt(&nonce, payload).map_err(|_| {
301        anyhow::anyhow!("Incorrect password for encrypted index")
302    })?;
303
304    Ok(dek)
305}
306
307/// Securely acquires a password from CLI flags, environment variable, or terminal prompt.
308pub fn acquire_password(
309    password_file: Option<&Path>,
310    password_stdin: bool,
311    confirm: bool,
312    db_name: &str,
313) -> Result<Password> {
314    if let Some(file_path) = password_file {
315        let content =
316            std::fs::read_to_string(file_path).with_context(|| {
317                format!("Failed to read password file: {}", file_path.display())
318            })?;
319        let pass_str = content.trim_end_matches(['\r', '\n']);
320        anyhow::ensure!(
321            !pass_str.is_empty(),
322            "Password file is empty: {}",
323            file_path.display()
324        );
325        return Ok(Password::from_string(pass_str));
326    }
327
328    if password_stdin {
329        let mut line = String::new();
330        std::io::stdin()
331            .read_line(&mut line)
332            .context("Failed to read password from standard input")?;
333        let pass_str = line.trim_end_matches(['\r', '\n']);
334        anyhow::ensure!(
335            !pass_str.is_empty(),
336            "Password received from stdin is empty"
337        );
338        return Ok(Password::from_string(pass_str));
339    }
340
341    if let Ok(env_pass) = std::env::var("CSC_PASSWORD")
342        .or_else(|_| std::env::var("CSC_INDEX_PASSWORD"))
343    {
344        let trimmed = env_pass.trim_end_matches(['\r', '\n']);
345        if !trimmed.is_empty() {
346            return Ok(Password::from_string(trimmed));
347        }
348    }
349
350    if std::io::stdin().is_terminal() {
351        use std::io::Write;
352        if confirm {
353            print!("Enter password to protect index '{db_name}': ");
354            std::io::stdout().flush()?;
355            let mut p1 = String::new();
356            std::io::stdin().read_line(&mut p1)?;
357            let p1 = p1.trim_end_matches(['\r', '\n']);
358            anyhow::ensure!(!p1.is_empty(), "Password cannot be empty");
359
360            print!("Confirm password: ");
361            std::io::stdout().flush()?;
362            let mut p2 = String::new();
363            std::io::stdin().read_line(&mut p2)?;
364            let p2 = p2.trim_end_matches(['\r', '\n']);
365
366            anyhow::ensure!(p1 == p2, "Passwords do not match");
367            Ok(Password::from_string(p1))
368        } else {
369            print!("Enter password for index '{db_name}': ");
370            std::io::stdout().flush()?;
371            let mut p = String::new();
372            std::io::stdin().read_line(&mut p)?;
373            let p = p.trim_end_matches(['\r', '\n']);
374            anyhow::ensure!(!p.is_empty(), "Password cannot be empty");
375            Ok(Password::from_string(p))
376        }
377    } else {
378        anyhow::bail!(
379            "Index '{db_name}' requires a password, but standard input is not a terminal. Please provide a password via --password-file <PATH>, --password-stdin, or the CSC_PASSWORD environment variable."
380        );
381    }
382}
383
384/// Opens or creates a Turso SQLite database, automatically detecting whether
385/// encryption is present or requested, loading companion `*.cscidxmeta` metadata,
386/// and configuring page-level AEAD encryption.
387pub async fn open_index_database(
388    db_path: &Path,
389    encrypt_if_new: bool,
390    password_file: Option<&Path>,
391    password_stdin: bool,
392) -> Result<turso::Database> {
393    let db_path_str = db_path.to_string_lossy().to_string();
394    let exists = db_path.exists();
395    // Reason for fallback: nameless or non-UTF-8 path defaults to standard database identifier "index"
396    let db_name = db_path
397        .file_name()
398        .and_then(|n| n.to_str())
399        .unwrap_or("index");
400
401    if exists {
402        let is_enc = is_database_encrypted(db_path)?;
403        if is_enc {
404            let meta_path = find_meta_path(db_path).ok_or_else(|| {
405                anyhow::anyhow!(
406                    "Encrypted database found at {}, but companion metadata file (*.cscidxmeta) is missing",
407                    db_path.display()
408                )
409            })?;
410            let meta = load_index_meta(&meta_path)?;
411            let password = acquire_password(
412                password_file,
413                password_stdin,
414                false,
415                db_name,
416            )?;
417            let dek = unlock_index_dek(&meta, &password)?;
418            let builder = turso::Builder::new_local(&db_path_str)
419                .experimental_encryption(true)
420                .with_encryption(turso::EncryptionOpts {
421                    cipher: meta.cipher,
422                    hexkey: bin2hex(dek.as_slice()),
423                })
424                .experimental_index_method(true);
425            drop(dek);
426            drop(password);
427            Ok(builder.build().await?)
428        } else {
429            if encrypt_if_new {
430                anyhow::bail!(
431                    "Cannot encrypt an existing unencrypted database: {}. Please specify a new database path.",
432                    db_path.display()
433                );
434            }
435            Ok(turso::Builder::new_local(&db_path_str)
436                .experimental_index_method(true)
437                .build()
438                .await?)
439        }
440    } else if encrypt_if_new {
441        let password =
442            acquire_password(password_file, password_stdin, true, db_name)?;
443        let (meta, dek) = create_encrypted_index_meta(&password)?;
444        let meta_path = resolve_meta_path(db_path);
445        save_index_meta(&meta_path, &meta)?;
446
447        let builder = turso::Builder::new_local(&db_path_str)
448            .experimental_encryption(true)
449            .with_encryption(turso::EncryptionOpts {
450                cipher: meta.cipher,
451                hexkey: bin2hex(dek.as_slice()),
452            })
453            .experimental_index_method(true);
454        drop(dek);
455        drop(password);
456        Ok(builder.build().await?)
457    } else {
458        Ok(turso::Builder::new_local(&db_path_str)
459            .experimental_index_method(true)
460            .build()
461            .await?)
462    }
463}
464#[cfg(test)]
465#[allow(
466    clippy::panic,
467    clippy::expect_used,
468    clippy::unwrap_used,
469    clippy::unwrap_in_result,
470    clippy::panic_in_result_fn,
471    clippy::indexing_slicing,
472    clippy::arithmetic_side_effects,
473    reason = "Standard repository test boilerplate"
474)]
475mod tests {
476    use super::*;
477    use tempfile::tempdir;
478
479    #[crate::ctb_test("tokio")]
480    async fn test_file_entity_type_and_sqlite_check_constraint() {
481        use ctb_io::file::entity::FileEntityType;
482        use turso::Builder;
483
484        // Verify parsing shortcuts and canonical names
485        assert_eq!(
486            FileEntityType::parse("f").unwrap(),
487            FileEntityType::Regular
488        );
489        assert_eq!(
490            FileEntityType::parse("file").unwrap(),
491            FileEntityType::Regular
492        );
493        assert_eq!(
494            FileEntityType::parse("regular").unwrap(),
495            FileEntityType::Regular
496        );
497        assert_eq!(
498            FileEntityType::parse("d").unwrap(),
499            FileEntityType::Directory
500        );
501        assert_eq!(
502            FileEntityType::parse("dir").unwrap(),
503            FileEntityType::Directory
504        );
505        assert_eq!(
506            FileEntityType::parse("l").unwrap(),
507            FileEntityType::Symlink
508        );
509        assert_eq!(
510            FileEntityType::parse("symlink").unwrap(),
511            FileEntityType::Symlink
512        );
513        assert_eq!(
514            FileEntityType::parse("h").unwrap(),
515            FileEntityType::Hardlink
516        );
517        assert_eq!(FileEntityType::parse("p").unwrap(), FileEntityType::Fifo);
518        assert_eq!(
519            FileEntityType::parse("c").unwrap(),
520            FileEntityType::CharDevice
521        );
522        assert_eq!(
523            FileEntityType::parse("chardev").unwrap(),
524            FileEntityType::CharDevice
525        );
526        assert_eq!(
527            FileEntityType::parse("b").unwrap(),
528            FileEntityType::BlockDevice
529        );
530        assert_eq!(
531            FileEntityType::parse("blockdev").unwrap(),
532            FileEntityType::BlockDevice
533        );
534        assert_eq!(FileEntityType::parse("s").unwrap(), FileEntityType::Socket);
535        assert_eq!(
536            FileEntityType::parse("door").unwrap(),
537            FileEntityType::Door
538        );
539        assert_eq!(
540            FileEntityType::parse("bundle").unwrap(),
541            FileEntityType::Bundle
542        );
543        assert!(FileEntityType::parse("invalid_kind").is_err());
544
545        // Verify SQLite CHECK constraint rejects invalid kinds
546        let temp = tempdir().expect("create tempdir");
547        let db_path = temp.path().join("check_test.sqlite");
548        let db = Builder::new_local(db_path.to_str().expect("valid path"))
549            .experimental_index_method(true)
550            .build()
551            .await
552            .expect("open db");
553        let conn = db.connect().expect("connect db");
554
555        crate::index_engine::init_database_schema(&conn)
556            .await
557            .expect("init database schema");
558
559        // Insert a valid source
560        conn.execute("INSERT INTO sources (name, journal_path, indexed_at) VALUES ('test', '/test.cscjournal', 0)", ())
561            .await
562            .expect("insert source");
563
564        // Inserting valid kind 'regular' must succeed
565        conn.execute(
566            "INSERT INTO entries (source_id, path, filename, parent_dir, kind, size, mtime_sec, mtime_nsec, ctime_sec, ctime_nsec, mode, nlink) \
567             VALUES (1, 'test.txt', 'test.txt', '', 'regular', 10, 0, 0, 0, 0, 420, 1)",
568            (),
569        )
570        .await
571        .expect("insert valid kind");
572
573        // Inserting invalid kind 'not_a_kind' must be rejected by the CHECK constraint
574        let bad_insert = conn.execute(
575            "INSERT INTO entries (source_id, path, filename, parent_dir, kind, size, mtime_sec, mtime_nsec, ctime_sec, ctime_nsec, mode, nlink) \
576             VALUES (1, 'bad.txt', 'bad.txt', '', 'not_a_kind', 10, 0, 0, 0, 0, 420, 1)",
577            (),
578        )
579        .await;
580
581        assert!(
582            bad_insert.is_err(),
583            "CHECK constraint should reject invalid kind"
584        );
585    }
586}