Skip to main content

agentmux_srv_core/backend/vault/
kdbx_export.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Export the Vault to a password-protected KeePass database (`.kdbx`, KDBX 4)
5//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §8.3), which the
6//! person can open in KeePassXC, KeePassDX or Strongbox. The file is for them to take
7//! elsewhere, so it is as plain a KeePass database as can be made:
8//! - a login is a login (title, user name, password, address, notes, and its one-time-code
9//!   seed in the `otp` field KeePassXC reads);
10//! - a note is an entry whose notes are its text;
11//! - every other kind is an entry whose secret is a protected custom field named for it
12//!   (`SSN`, `Card number`, `API key`, …: [`kdbx_names`]), with plain details as unprotected
13//!   custom fields and the entry's tags as KeePass tags and as groups (a tag `A/B` is the group
14//!   `A` > `B`, the first tag choosing the group);
15//! - a linked entry, which holds no value, is an entry with no secret field: its place, who reads the
16//!   key, when it last changed and where else it is kept are unprotected custom fields, and
17//!   `Linked entry kind` says it is a link and of which kind.
18//!
19//! The importer reads the same names, so a database leaves and comes back as the same entries.
20
21use std::collections::BTreeMap;
22use std::path::Path;
23
24use keepass::config::{DatabaseConfig, KdfConfig};
25use keepass::db::{GroupId, Value};
26use keepass::{Database, DatabaseKey};
27
28use super::import::Incoming;
29use super::kdbx_names::{self, COMPANIONS, DETAILS};
30use super::linked;
31use super::transfer::{gather, wipe, write_atomically, ExportResult, MIN_PASSPHRASE};
32use super::{record, PERSON};
33use crate::backend::storage::store::Store;
34
35/// What a database written for another app uses to stretch its password: KeePassXC's own default
36/// (Argon2d, 64 MiB, 10 iterations), well inside what the importer accepts (§8.7).
37fn default_kdf() -> KdfConfig {
38    KdfConfig::Argon2 { iterations: 10, memory: 64 * 1024 * 1024, parallelism: 2, version: argon2::Version::Version13 }
39}
40
41/// Writes the chosen entries (all when `ids` is `None`) to `path` as a KeePass database opened by
42/// `passphrase`.
43pub fn export(store: &Store, ids: Option<&[String]>, passphrase: &str, path: &Path) -> Result<ExportResult, String> {
44    export_with(store, ids, passphrase, path, default_kdf())
45}
46
47pub(super) fn export_with(store: &Store, ids: Option<&[String]>, passphrase: &str, path: &Path, kdf: KdfConfig) -> Result<ExportResult, String> {
48    if passphrase.chars().count() < MIN_PASSPHRASE {
49        return Err(format!("a passphrase is at least {MIN_PASSPHRASE} characters"));
50    }
51    let entries = gather(store, ids)?;
52    let count = entries.len();
53    let bytes = build(&entries, passphrase, kdf);
54    wipe(entries);
55    write_atomically(path, &bytes?)?;
56    let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
57    record(store, "", "", PERSON, "exported", &file_name, &format!("{count} entries to KeePass"));
58    Ok(ExportResult { count, file_name, links_only: false })
59}
60
61/// The database's bytes.
62pub(super) fn build(entries: &[Incoming], passphrase: &str, kdf: KdfConfig) -> Result<Vec<u8>, String> {
63    let mut config = DatabaseConfig::default();
64    config.kdf_config = kdf;
65    let mut db = Database::with_config(config);
66    let mut groups: BTreeMap<String, GroupId> = BTreeMap::new();
67    for e in entries {
68        let group = group_for(&mut db, &mut groups, e.tags.first().map(String::as_str).unwrap_or(""));
69        let Some(mut g) = db.group_mut(group) else { return Err("couldn't build the KeePass database".into()) };
70        g.add_entry().edit(|entry| fill(entry, e));
71    }
72    let mut out = Vec::new();
73    db.save(&mut out, DatabaseKey::new().with_password(passphrase)).map_err(|e| format!("couldn't write the KeePass database: {e}"))?;
74    Ok(out)
75}
76
77/// The group a tag path names, made on first use; the root for no tag.
78fn group_for(db: &mut Database, made: &mut BTreeMap<String, GroupId>, tag: &str) -> GroupId {
79    let mut at = db.root().id();
80    let mut so_far = String::new();
81    for name in tag.split('/').map(str::trim).filter(|n| !n.is_empty()) {
82        if !so_far.is_empty() {
83            so_far.push('/');
84        }
85        so_far.push_str(name);
86        at = match made.get(&so_far) {
87            Some(id) => *id,
88            None => {
89                let id = match db.group_mut(at) {
90                    Some(mut parent) => parent.add_group().edit(|g| g.name = name.to_string()).id(),
91                    None => at,
92                };
93                made.insert(so_far.clone(), id);
94                id
95            }
96        };
97    }
98    at
99}
100
101fn fill(entry: &mut keepass::db::Entry, e: &Incoming) {
102    let part = |name: &str| e.parts.get(name).map(String::as_str).filter(|v| !v.is_empty());
103    let field = |name: &str| e.fields.get(name).map(String::as_str).filter(|v| !v.is_empty());
104    entry.set_unprotected("Title", e.label.clone());
105    entry.tags = e.tags.iter().map(|t| t.replace([';', ','], " ")).collect();
106    if let Some(notes) = field("notes") {
107        entry.set_unprotected("Notes", notes);
108    }
109    match e.kind.as_str() {
110        "login" => {
111            if let Some(u) = field("username") {
112                entry.set_unprotected("UserName", u);
113            }
114            if let Some(s) = field("site") {
115                entry.set_unprotected("URL", s);
116            }
117            if let Some(p) = part("password") {
118                entry.set_protected("Password", p);
119            }
120            if let Some(t) = part("totp") {
121                entry.set("otp", Value::protected(otp_uri(&e.label, t)));
122            }
123        }
124        "note" => {
125            if let Some(text) = part("text") {
126                entry.set_unprotected("Notes", text);
127            }
128        }
129        kind => {
130            if let Some(p) = kdbx_names::primary_for(kind) {
131                if let Some(v) = part(p.part) {
132                    entry.set_protected(p.title, v);
133                }
134            }
135            for c in COMPANIONS.iter().filter(|c| c.kind == kind) {
136                if let Some(v) = part(c.part) {
137                    entry.set_protected(c.title, v);
138                }
139            }
140            for d in DETAILS {
141                if let Some(v) = field(d.name) {
142                    entry.set_unprotected(d.title, v);
143                }
144            }
145        }
146    }
147    // Where the entry's machine copy is: no secret, and the same for every kind.
148    for (name, title) in super::source_link::TITLES.into_iter().chain(linked::TITLES) {
149        if let Some(v) = field(name) {
150            entry.set_unprotected(title, v);
151        }
152    }
153    // A link holds no value, so no secret field says what kind of entry it is: this one does.
154    if linked::is_linked(&e.fields) {
155        entry.set_unprotected(linked::KIND_TITLE, e.kind.clone());
156    }
157}
158
159/// A one-time-code seed as the `otpauth://` address KeePassXC reads; an address stays as it is.
160fn otp_uri(label: &str, seed: &str) -> String {
161    let seed = seed.trim();
162    if seed.starts_with("otpauth://") {
163        return seed.to_string();
164    }
165    let mut name = String::new();
166    for b in label.bytes() {
167        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
168            name.push(b as char);
169        } else {
170            name.push_str(&format!("%{b:02X}"));
171        }
172    }
173    format!("otpauth://totp/{name}?secret={}", seed.replace(' ', "").to_uppercase())
174}
175
176#[cfg(test)]
177#[path = "kdbx_export_tests.rs"]
178mod tests;