Skip to main content

agentmux_srv_core/backend/vault/
plain_export.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Export the Vault as a plain, unencrypted CSV or JSON file, for a person leaving for another
5//! manager (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md ยง8.3).
6//!
7//! The file holds every secret in the clear, so everything around it is careful: only the host
8//! asks for it, after the person typed a confirmation and the OS confirmed them (like Reveal), to
9//! a path they chose in the native dialog; the file is private to its owner where the OS has such
10//! a thing; the bytes are wiped after the write; and the Activity log says it happened.
11//!
12//! - **CSV** uses Bitwarden's column layout, which nearly every manager reads. A login is a row
13//!   with its address, user name, password and one-time-code seed. Every other kind is a secure
14//!   note whose text lists its parts by their names (`SSN: 123-45-6789`), because a column layout
15//!   made for logins has nowhere else to put a card or an identity.
16//! - **JSON** is the `.vault` file's own contents, unencrypted: every kind, part, detail and tag.
17//!   AgentMux imports it back.
18
19use std::io::Write as _;
20use std::path::Path;
21
22use zeroize::Zeroizing;
23
24use super::import::Incoming;
25use super::kdbx_names::{self, COMPANIONS, DETAILS};
26use super::transfer::{gather, plain_json, wipe, ExportResult};
27use super::{record, PERSON};
28use crate::backend::storage::store::Store;
29
30/// Bitwarden's CSV columns, in its order.
31const HEADER: [&str; 11] = ["folder", "favorite", "type", "name", "notes", "fields", "reprompt", "login_uri", "login_username", "login_password", "login_totp"];
32
33/// Writes the chosen entries (all when `ids` is `None`) to `path` as plain `csv` or `json`.
34pub fn export(store: &Store, ids: Option<&[String]>, format: &str, path: &Path) -> Result<ExportResult, String> {
35    let json = match format {
36        "csv" => false,
37        "json" => true,
38        other => return Err(format!("unknown plain export format {other:?}")),
39    };
40    let entries = gather(store, ids)?;
41    let count = entries.len();
42    let bytes = if json { plain_json(&entries) } else { csv_bytes(&entries) };
43    wipe(entries);
44    write_private(path, &bytes?)?;
45    let file_name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
46    record(store, "", "", PERSON, "exported", &file_name, &format!("{count} entries, unencrypted {}", format.to_uppercase()));
47    Ok(ExportResult { count, file_name, links_only: false })
48}
49
50/// The CSV's bytes.
51pub(super) fn csv_bytes(entries: &[Incoming]) -> Result<Zeroizing<Vec<u8>>, String> {
52    let mut out = Zeroizing::new(Vec::new());
53    {
54        let mut w = csv::WriterBuilder::new().terminator(csv::Terminator::CRLF).from_writer(&mut *out);
55        w.write_record(HEADER).map_err(|e| e.to_string())?;
56        for e in entries {
57            let row = row(e);
58            let result = w.write_record(row.iter().map(|c| c.as_str()));
59            result.map_err(|e| format!("couldn't write the CSV: {e}"))?;
60        }
61        w.flush().map_err(|e| e.to_string())?;
62    }
63    Ok(out)
64}
65
66/// One entry as a row of [`HEADER`]'s columns.
67fn row(e: &Incoming) -> Vec<Zeroizing<String>> {
68    let part = |name: &str| e.parts.get(name).map(String::as_str).unwrap_or("");
69    let field = |name: &str| e.fields.get(name).map(String::as_str).unwrap_or("");
70    let z = |s: &str| Zeroizing::new(s.to_string());
71    let folder = z(e.tags.first().map(String::as_str).unwrap_or(""));
72    if e.kind == "login" {
73        let mut notes = field("notes").to_string();
74        // A part this layout has no column for goes in the notes, so nothing is dropped.
75        for (name, value) in &e.parts {
76            if !matches!(name.as_str(), "password" | "totp") && !value.is_empty() {
77                notes = format!("{name}: {value}\n{notes}");
78            }
79        }
80        return vec![folder, z("0"), z("login"), z(&e.label), Zeroizing::new(notes), z(""), z("0"), z(field("site")), z(field("username")), z(part("password")), z(part("totp"))];
81    }
82    vec![folder, z("0"), z("note"), z(&e.label), Zeroizing::new(note_text(e)), z(""), z("0"), z(""), z(""), z(""), z("")]
83}
84
85/// The text of a secure note holding everything an entry has: a note's own text, or one line per
86/// part and detail, by the names a KeePass export uses, then the entry's notes.
87fn note_text(e: &Incoming) -> String {
88    if e.kind == "note" {
89        return e.parts.get("text").cloned().unwrap_or_default();
90    }
91    let mut lines: Vec<String> = Vec::new();
92    let mut used: Vec<&str> = Vec::new();
93    let mut add = |title: &str, value: &str| {
94        if !value.is_empty() {
95            lines.push(format!("{title}: {value}"));
96        }
97    };
98    if let Some(p) = kdbx_names::primary_for(&e.kind) {
99        add(p.title, e.parts.get(p.part).map(String::as_str).unwrap_or(""));
100        used.push(p.part);
101    }
102    for c in COMPANIONS.iter().filter(|c| c.kind == e.kind) {
103        add(c.title, e.parts.get(c.part).map(String::as_str).unwrap_or(""));
104        used.push(c.part);
105    }
106    for d in DETAILS {
107        add(d.title, e.fields.get(d.name).map(String::as_str).unwrap_or(""));
108    }
109    // Whatever else the entry has, under its own name.
110    for (name, value) in &e.parts {
111        if !used.contains(&name.as_str()) {
112            add(name, value);
113        }
114    }
115    let mut text = lines.join("\n");
116    if let Some(notes) = e.fields.get("notes").filter(|n| !n.is_empty()) {
117        if !text.is_empty() {
118            text.push_str("\n\n");
119        }
120        text.push_str(notes);
121    }
122    text
123}
124
125/// The file appears whole or not at all, and is readable by its owner alone where the OS has such
126/// a thing (a plain copy of every secret is not for other accounts on the machine).
127fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
128    let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
129    let tmp = dir.join(format!(".{}.tmp", uuid::Uuid::new_v4().simple()));
130    let mut options = std::fs::OpenOptions::new();
131    options.write(true).create_new(true);
132    #[cfg(unix)]
133    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
134    let written = options.open(&tmp).and_then(|mut f| f.write_all(bytes).and_then(|_| f.sync_all()));
135    if let Err(e) = written {
136        // A write that stopped part way (a full disk) leaves part of the secrets beside the destination.
137        let _ = std::fs::remove_file(&tmp);
138        return Err(format!("couldn't write the file: {e}"));
139    }
140    std::fs::rename(&tmp, path).map_err(|e| {
141        let _ = std::fs::remove_file(&tmp);
142        format!("couldn't save the file there: {e}")
143    })
144}
145
146#[cfg(test)]
147#[path = "plain_export_tests.rs"]
148mod tests;