agentmux_srv_core/backend/vault/
kdbx_export.rs1use 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
35fn default_kdf() -> KdfConfig {
38 KdfConfig::Argon2 { iterations: 10, memory: 64 * 1024 * 1024, parallelism: 2, version: argon2::Version::Version13 }
39}
40
41pub 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
61pub(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
77fn 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 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 if linked::is_linked(&e.fields) {
155 entry.set_unprotected(linked::KIND_TITLE, e.kind.clone());
156 }
157}
158
159fn 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;