agentmux_srv_core/backend/vault/import/
sticky.rs1use 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
18const MOST_DEPTH: usize = 64;
20const MOST_GROUP_DEPTH: usize = 32;
22
23pub(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 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 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 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
158fn 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}