Skip to main content

agentmux_srv_core/backend/vault/import/
sticky.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Sticky Password's XML export (spec ยง8.4): `root > Database` with its `Logins` (a username and a
5//! password each), its `Accounts` (the title, address, notes and group of a sign-in, linked to its
6//! login by `SourceLoginID`) and its `Groups` (folders, which nest). Written from the format as
7//! Bitwarden's open-source importer reads it, not from an export Sticky Password made. Only the
8//! logins are read; what else the export may hold (memos, bank cards) is not.
9
10use std::collections::HashMap;
11
12use quick_xml::events::{BytesStart, Event};
13use quick_xml::Reader;
14
15use super::shared::{add_line, label_of, Sink};
16use super::{Imported, ReadError, Source, MAX_ITEMS};
17
18/// Elements nest only a few deep in this export; more is a crafted file.
19const MOST_DEPTH: usize = 64;
20/// Groups nest; a chain longer than this is a loop.
21const MOST_GROUP_DEPTH: usize = 32;
22
23/// Whether this text is a Sticky Password export, from what its first lines hold.
24pub(super) fn looks_like(text: &str) -> bool {
25    let trimmed = text.trim_start();
26    let mut end = trimmed.len().min(4096);
27    while !trimmed.is_char_boundary(end) {
28        end -= 1;
29    }
30    trimmed.starts_with('<') && trimmed[..end].contains("<Database")
31}
32
33struct Login {
34    id: String,
35    username: String,
36    password: String,
37}
38
39#[derive(Default)]
40struct Account {
41    title: String,
42    link: String,
43    group: String,
44    notes: String,
45    logins: Vec<String>,
46}
47
48fn attr(e: &BytesStart, name: &str) -> String {
49    for a in e.attributes().flatten() {
50        if a.key.as_ref() == name.as_bytes() {
51            return match a.unescape_value() {
52                Ok(v) => v.into_owned(),
53                Err(_) => String::from_utf8_lossy(&a.value).into_owned(),
54            };
55        }
56    }
57    String::new()
58}
59
60pub(super) fn read(text: &str) -> Result<Imported, ReadError> {
61    let mut reader = Reader::from_str(text);
62    let mut path: Vec<String> = Vec::new();
63    let mut logins: Vec<Login> = Vec::new();
64    let mut accounts: Vec<Account> = Vec::new();
65    let mut open: Option<Account> = None;
66    // A group's id: its name and its parent's id.
67    let mut groups: HashMap<String, (String, String)> = HashMap::new();
68    loop {
69        let event = reader.read_event().map_err(|_| ReadError::from("this isn't a well-formed XML file"))?;
70        let (e, empty) = match event {
71            Event::Eof => break,
72            Event::End(_) => {
73                if path.join("/") == "root/Database/Accounts/Account" {
74                    accounts.extend(open.take());
75                }
76                path.pop();
77                continue;
78            }
79            Event::Start(e) => (e, false),
80            Event::Empty(e) => (e, true),
81            _ => continue,
82        };
83        if path.len() >= MOST_DEPTH {
84            return Err("this XML file nests deeper than a Sticky Password export does".into());
85        }
86        let name = String::from_utf8_lossy(e.name().as_ref()).into_owned();
87        let here = if path.is_empty() { name.clone() } else { format!("{}/{name}", path.join("/")) };
88        match here.as_str() {
89            "root/Database/Logins/Login" => {
90                if logins.len() >= MAX_ITEMS {
91                    return Err(format!("this export has more than {MAX_ITEMS} logins, more than the Vault imports").into());
92                }
93                logins.push(Login { id: attr(&e, "ID"), username: attr(&e, "Name"), password: attr(&e, "Password") });
94            }
95            "root/Database/Accounts/Account" => {
96                if accounts.len() >= MAX_ITEMS {
97                    return Err(format!("this export has more than {MAX_ITEMS} accounts, more than the Vault imports").into());
98                }
99                let account = Account {
100                    title: attr(&e, "Name"),
101                    link: attr(&e, "Link"),
102                    group: attr(&e, "ParentID"),
103                    // The export writes a line break in a note as `/n`.
104                    notes: attr(&e, "Comments").replace("/n", "\n"),
105                    logins: Vec::new(),
106                };
107                if empty {
108                    accounts.push(account);
109                } else {
110                    open = Some(account);
111                }
112            }
113            "root/Database/Accounts/Account/LoginLinks/Login" => {
114                if let Some(account) = open.as_mut() {
115                    if account.logins.len() < MAX_ITEMS {
116                        account.logins.push(attr(&e, "SourceLoginID"));
117                    }
118                }
119            }
120            "root/Database/Groups/Group" => {
121                if groups.len() < MAX_ITEMS {
122                    groups.insert(attr(&e, "ID"), (attr(&e, "Name"), attr(&e, "ParentID")));
123                }
124            }
125            _ => {}
126        }
127        if !empty {
128            path.push(name);
129        }
130    }
131    if logins.is_empty() {
132        return Err("this isn't a Sticky Password export, or it has no logins".into());
133    }
134    // A login's account: the first one that links to it.
135    let mut account_of: HashMap<&str, &Account> = HashMap::new();
136    for account in &accounts {
137        for id in &account.logins {
138            account_of.entry(id.as_str()).or_insert(account);
139        }
140    }
141    let mut sink = Sink::default();
142    for login in &logins {
143        if login.id.trim().is_empty() {
144            continue;
145        }
146        let account = account_of.get(login.id.as_str()).copied();
147        let (title, link, notes, group) = match account {
148            Some(a) => (a.title.trim(), a.link.trim(), a.notes.as_str(), group_path(&groups, &a.group)),
149            None => ("", "", "", String::new()),
150        };
151        let mut secret = String::new();
152        add_line(&mut secret, "", notes);
153        sink.login(&label_of(title, link, &login.username), &login.username, &login.password, link, "", &secret, &group);
154    }
155    sink.done(Source::StickyPassword)
156}
157
158/// A group's path from the top (`Work/Servers`), found by walking up its parents.
159fn group_path(groups: &HashMap<String, (String, String)>, id: &str) -> String {
160    let mut parts: Vec<&str> = Vec::new();
161    let mut next = id;
162    while !next.is_empty() && parts.len() < MOST_GROUP_DEPTH {
163        let Some((name, parent)) = groups.get(next) else { break };
164        if !name.trim().is_empty() {
165            parts.push(name.trim());
166        }
167        next = parent;
168    }
169    parts.reverse();
170    parts.join("/")
171}