← history for src/vault.rs
35bda350src/vault.rs52 lines⬡ raw↓ download
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * Config Vault - cfgvault
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Paolo Lulli <kevwe.com>
 * @copyright Paolo Lulli 2026
 */

use crate::config::AppConfig;
use keepass::db::NodeRef;
use keepass::error::DatabaseOpenError;
use keepass::{Database, DatabaseKey};
use std::fs::File;
use std::sync::OnceLock;

static DB: OnceLock<Database> = OnceLock::new();
pub struct RetrievalError {/* ... */}

pub fn retrieve_entry(entry_name: &str) -> Result<String, RetrievalError> {
    let db = DB.get().expect("Database not initialized");
    for node in &db.root {
        match node {
            NodeRef::Group(_g) => {
                //println!("Saw group '{0}'", g.name);
            }
            NodeRef::Entry(entry) => {
                if entry.get_title().unwrap_or("No such entry name)") == entry_name {
                    return Ok(String::from(entry.get_password().unwrap()));
                }
            }
        }
    }
    Err(RetrievalError {})
}

pub fn unlock(config: &AppConfig) {
    let db = open_database(&config.keystore, &config.secretkey).expect("Failed to unlock database");

    // set exactly once at startup
    DB.set(db).expect("Database already initialized");
}

fn open_database(
    kdbx_filename: &String,
    key_filename: &String,
) -> Result<Database, DatabaseOpenError> {
    let key = DatabaseKey::new().with_keyfile(&mut File::open(key_filename)?)?;
    let db = Database::open(&mut File::open(kdbx_filename)?, key)?;
    Ok(db)
}