Skip to main content

agentmux_srv_core/backend/vault/
signins.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Sign-ins a browser profile keeps (spec SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md
5//! §9): `login` entries whose `profile` field names the profile whose tabs may
6//! use them, `personal` or `profile:<id>`. A login without a site belongs to no
7//! profile. HTTP Basic/Digest sign-ins are such entries with a `realm` (and
8//! `proxy` for a proxy's), moved here from the keychain once (§5.4, §9.3).
9
10use std::collections::BTreeMap;
11
12use agentmux_common::time::now_ms;
13
14use super::{record, seal, EntryChange, NewEntry, Parts, PERSON};
15use crate::backend::storage::store::Store;
16use crate::backend::storage::vault::{VaultRow, PERSONAL_VAULT};
17
18pub const PROFILE: &str = "profile";
19pub const REALM: &str = "realm";
20pub const PROXY: &str = "proxy";
21pub const PERSONAL: &str = "personal";
22pub(super) const SITE: &str = "site";
23pub(super) const USERNAME: &str = "username";
24
25/// On a sign-in moved from the keychain: no record says which profile used it.
26pub const FROM_KEYCHAIN: &str = "moved from the old sign-in store: check the profile";
27/// On a sign-in the site turned down right after it was filled: not offered
28/// again until a new password is saved for it.
29pub const REFUSED: &str = "the site refused it: check the password";
30
31/// Whether `v` names a profile a sign-in can belong to.
32pub fn is_profile(v: &str) -> bool {
33    v == PERSONAL || v.strip_prefix("profile:").is_some_and(crate::backend::browser_profiles_store::is_profile_id)
34}
35
36/// The profile a tab browsing as `identity` (its `browser:identity`) keeps
37/// sign-ins under; `None` for Incognito, which never saves one (§9.1).
38pub fn profile_for_tab(identity: Option<&str>) -> Option<String> {
39    match identity {
40        None => Some(PERSONAL.to_string()),
41        Some(i) if i.starts_with("profile:") && is_profile(i) => Some(i.to_string()),
42        Some(_) => None,
43    }
44}
45
46/// Whether a login's saved `site` names the page origin `origin`: the one comparison every matcher of a login to a page
47/// uses (a form fill, an HTTP prompt, a share, a sign-up), so they cannot disagree. It compares origins, not strings:
48/// scheme, host in any case and port (the scheme's default when absent) must be the same; a trailing slash, a path, a
49/// query or user information in either is ignored, and none of them widens a match to another host, port or scheme.
50pub fn same_site(site: &str, origin: &str) -> bool {
51    agentmux_common::allowed_origins::same_origin(site, origin)
52}
53
54/// The origin in `origins` that `site` names, as the page showed it.
55fn page_origin<'a>(site: &str, origins: &'a [String]) -> Option<&'a String> {
56    origins.iter().find(|o| same_site(site, o))
57}
58
59/// A login's site as it is stored: one written as just an origin (`HTTPS://Example.com:443/`) is kept as `https://example.com`;
60/// a site with a path, query or user information is a login page the person saved, and is kept as it was typed.
61/// Entries saved before this keep matching without a change ([`same_site`]).
62pub(super) fn normalize_site(kind: &str, fields: &mut BTreeMap<String, String>) {
63    if kind != "login" {
64        return;
65    }
66    if let Some(site) = fields.get_mut(SITE) {
67        if let Some(origin) = agentmux_common::allowed_origins::bare_origin(site) {
68            *site = origin;
69        }
70    }
71}
72
73/// A login with a site belongs to Personal unless it names another profile; one
74/// without a site belongs to none.
75pub(super) fn settle_profile(kind: &str, fields: &mut BTreeMap<String, String>) {
76    if kind != "login" {
77        return;
78    }
79    if fields.contains_key(SITE) {
80        fields.entry(PROFILE.to_string()).or_insert_with(|| PERSONAL.to_string());
81    } else {
82        fields.remove(PROFILE);
83    }
84}
85
86/// Where an HTTP sign-in is used: the profile, the origin (a proxy's, for a
87/// proxy), and the realm the site names.
88#[derive(Debug, Clone)]
89pub struct Space {
90    pub profile: String,
91    pub origin: String,
92    pub realm: String,
93    pub proxy: bool,
94}
95
96pub fn fields_of(row: &VaultRow) -> BTreeMap<String, String> {
97    serde_json::from_str(&row.fields).unwrap_or_default()
98}
99
100pub(super) fn tags_of(row: &VaultRow) -> Vec<String> {
101    serde_json::from_str(&row.tags).unwrap_or_default()
102}
103
104fn holds(row: &VaultRow, s: &Space) -> bool {
105    let f = fields_of(row);
106    let get = |k: &str| f.get(k).map(String::as_str).unwrap_or("");
107    row.kind == "login" && get(PROFILE) == s.profile && same_site(get(SITE), &s.origin) && get(REALM) == s.realm && f.contains_key(PROXY) == s.proxy
108}
109
110/// Whether a sign-in may be offered for filling: not one the site refused, nor
111/// one made on a sign-up form and never sent (signups.rs), which the site may
112/// never have accepted. Both stay in the Vault for the person.
113pub(super) fn offered(row: &VaultRow) -> bool {
114    !tags_of(row).iter().any(|t| t == REFUSED || t == super::signups::UNCONFIRMED)
115}
116
117/// The Vault `profile` (`personal` or `profile:<id>`) keeps its sign-ins in and offers them from: the
118/// person's choice in the Vault pane, or Personal, also when the chosen Vault is gone (§5.3).
119pub fn vault_for(store: &Store, profile: &str) -> Result<String, String> {
120    let chosen = store.signin_vault(profile).map_err(|e| e.to_string())?;
121    Ok(match chosen {
122        Some(v) if store.vault_info(&v).map_err(|e| e.to_string())?.is_some() => v,
123        _ => PERSONAL_VAULT.to_string(),
124    })
125}
126
127/// The sign-ins kept for `s`, newest first.
128pub(super) fn held(store: &Store, s: &Space) -> Result<Vec<VaultRow>, String> {
129    let vault = vault_for(store, &s.profile)?;
130    let mut rows: Vec<VaultRow> = store.vault_list().map_err(|e| e.to_string())?.into_iter().filter(|r| r.vault_id == vault && holds(r, s)).collect();
131    rows.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
132    Ok(rows)
133}
134
135/// The sign-in a tab is offered for `s`: the newest that may be ([`offered`]).
136/// Returns it and its user name.
137pub fn find(store: &Store, s: &Space) -> Result<Option<(VaultRow, String)>, String> {
138    Ok(held(store, s)?
139        .into_iter()
140        .find(offered)
141        .map(|r| {
142            let user = fields_of(&r).get(USERNAME).cloned().unwrap_or_default();
143            (r, user)
144        }))
145}
146
147/// Whether `s` already holds a sign-in for `username`: `Some(true)` with this
148/// very password, `Some(false)` with another, `None` for none.
149pub fn saved_as(store: &Store, s: &Space, username: &str, password: &str) -> Result<Option<bool>, String> {
150    let Some(row) = held(store, s)?.into_iter().find(|r| fields_of(r).get(USERNAME).map(String::as_str).unwrap_or("") == username) else {
151        return Ok(None);
152    };
153    let parts = seal::open(&seal::key(false)?, &row.id, &row.sealed)?;
154    Ok(Some(parts.get("password") == Some(password)))
155}
156
157/// The sign-ins `profile` holds for exactly these frame origins that may be
158/// offered ([`offered`]), newest first: `(entry id, origin, user name)`. HTTP sign-ins (with a
159/// realm or for a proxy) go through the browser's own prompt, not a form.
160pub fn offered_for(store: &Store, profile: &str, origins: &[String]) -> Result<Vec<(String, String, String)>, String> {
161    let vault = vault_for(store, profile)?;
162    let mut rows: Vec<VaultRow> = store
163        .vault_list()
164        .map_err(|e| e.to_string())?
165        .into_iter()
166        .filter(|r| {
167            let f = fields_of(r);
168            r.kind == "login"
169                && r.vault_id == vault
170                && f.get(PROFILE).map(String::as_str) == Some(profile)
171                && f.get(SITE).is_some_and(|s| page_origin(s, origins).is_some())
172                && !f.contains_key(REALM)
173                && !f.contains_key(PROXY)
174                && offered(r)
175        })
176        .collect();
177    rows.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
178    Ok(rows.into_iter().map(|r| offered_row(r, origins)).collect())
179}
180
181/// `(entry id, the page's origin the login's site names, user name)`: the origin is the one the page showed, so what
182/// is typed and logged names the page, not the way the site happened to be written.
183fn offered_row(r: VaultRow, origins: &[String]) -> (String, String, String) {
184    let f = fields_of(&r);
185    let site = f.get(SITE).cloned().unwrap_or_default();
186    let origin = page_origin(&site, origins).cloned().unwrap_or(site);
187    (r.id, origin, f.get(USERNAME).cloned().unwrap_or_default())
188}
189
190/// The logins shared with the agent whose permanent uid is `uid`, saved for exactly these frame origins, whatever
191/// browser profile they belong to (spec §5, A4): `(entry id, origin, user name)`, newest first.
192fn shared_with(store: &Store, origins: &[String], uid: &str) -> Result<Vec<(String, String, String)>, String> {
193    let mut rows: Vec<VaultRow> = store
194        .vault_list()
195        .map_err(|e| e.to_string())?
196        .into_iter()
197        .filter(|r| {
198            let f = fields_of(r);
199            r.kind == "login" && super::shares::names(&f, uid) && f.get(SITE).is_some_and(|s| page_origin(s, origins).is_some()) && !f.contains_key(REALM) && !f.contains_key(PROXY) && offered(r)
200        })
201        .collect();
202    rows.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
203    Ok(rows.into_iter().map(|r| offered_row(r, origins)).collect())
204}
205
206/// [`offered_for`], limited to the sign-ins in Vaults `agent` may use: what an agent's own
207/// `Browser` `signin` chooses from. A sign-in in a Vault it may not use is one that is not there.
208/// `own_uid` is the agent's permanent uid when the tab is in the agent's own browser profile: the logins
209/// shared with it are offered there too, and in no other tab (A4, A5).
210/// (The key button the person presses lists every sign-in.)
211pub fn offered_for_agent(store: &Store, profile: &str, origins: &[String], agent: &str, own_uid: Option<&str>) -> Result<Vec<(String, String, String)>, String> {
212    let mut found = offered_for(store, profile, origins)?;
213    if let Some(uid) = own_uid {
214        for shared in shared_with(store, origins, uid)? {
215            if !found.iter().any(|f| f.0 == shared.0) {
216                found.push(shared);
217            }
218        }
219    }
220    let mut usable = Vec::new();
221    for found in found {
222        if super::vaults::entry_usable(store, &found.0, Some(agent))? {
223            usable.push(found);
224        }
225    }
226    Ok(usable)
227}
228
229/// Whether the entry `id` is a login `agent` may use, saved for one of `origins` and not shared with the agent whose uid is
230/// `uid`: what the agent is told to ask for with `Vault` `share` (A8).
231pub fn unshared_for(store: &Store, id: &str, origins: &[String], agent: &str, uid: &str) -> bool {
232    let Ok(Some(row)) = store.vault_get(id) else { return false };
233    let f = fields_of(&row);
234    row.kind == "login" && f.get(SITE).is_some_and(|s| page_origin(s, origins).is_some()) && !super::shares::names(&f, uid) && super::vaults::entry_usable(store, id, Some(agent)).unwrap_or(false)
235}
236
237/// What a fill of entry `id` types: `(origin, user name, password, label)`, if it
238/// is a sign-in `profile` holds for one of the frame origins the page shows a
239/// form for. Anything else is refused: a sign-in never goes to another site or
240/// another profile's tab.
241pub fn for_fill(store: &Store, id: &str, profile: &str, origins: &[String], agent: Option<(&str, Option<&str>)>) -> Result<(String, String, zeroize::Zeroizing<String>, String), String> {
242    let found = match agent {
243        Some((name, own_uid)) => offered_for_agent(store, profile, origins, name, own_uid)?,
244        None => offered_for(store, profile, origins)?,
245    };
246    let Some((_, origin, user)) = found.into_iter().find(|(e, _, _)| e == id) else {
247        return Err("that sign-in isn't saved for this page's site in this tab's profile, so nothing was typed".to_string());
248    };
249    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
250    let parts = seal::open(&seal::key(false)?, &row.id, &row.sealed)?;
251    let password = zeroize::Zeroizing::new(parts.get("password").unwrap_or("").to_string());
252    Ok((origin, user, password, row.label))
253}
254
255/// `us***@example.com` / `ab***`: enough for a person to know which saved
256/// sign-in is meant, not enough to be useful if it is shown or logged wrong.
257/// Keeps at most the first 2 characters.
258pub fn mask(username: &str) -> String {
259    let n = username.chars().count();
260    if n <= 2 {
261        return "*".repeat(n.max(1));
262    }
263    format!("{}***", username.chars().take(2).collect::<String>())
264}
265
266/// The user name and password for `s`, once the person approved their use:
267/// logged as a sign-in, the password never.
268pub fn fill(store: &Store, s: &Space) -> Result<Option<(String, zeroize::Zeroizing<String>)>, String> {
269    let Some((row, user)) = find(store, s)? else { return Ok(None) };
270    let parts = seal::open(&seal::key(false)?, &row.id, &row.sealed)?;
271    let password = zeroize::Zeroizing::new(parts.get("password").unwrap_or("").to_string());
272    record(store, &row.id, &row.label, PERSON, SIGNED_IN, &s.origin, "done");
273    if let Err(e) = store.vault_touch(&row.id, now_ms()) {
274        tracing::warn!(error = %e, "vault: couldn't note a sign-in's use");
275    }
276    Ok(Some((user, password)))
277}
278
279/// The action an HTTP sign-in's use is logged as.
280pub const SIGNED_IN: &str = "signed in";
281
282/// The agent whose own browser profile a tab is in, as the Vault knows it: the name its Vaults list it by (`names`:
283/// its slug and its id) and its permanent uid.
284#[derive(Debug, Clone)]
285pub struct ProfileOwner {
286    pub names: Vec<String>,
287    pub uid: String,
288}
289
290/// The HTTP-prompt sign-in the person shared with `owner` that answers `s`, and its user name: the newest that may be
291/// offered ([`offered`]), in a Vault the agent may use, whatever profile it is saved for (spec A4, A5, A11). Only in
292/// the agent's own profile: `s.profile` of any other profile finds none. Only a login that answers a prompt
293/// ([`super::shares::answers_prompt`]): a form login shared with the agent is never given to a prompt.
294pub fn find_shared(store: &Store, s: &Space, owner: &ProfileOwner) -> Result<Option<(VaultRow, String)>, String> {
295    if s.profile != format!("profile:{}", crate::backend::browser_profiles_store::agent_profile_id(&owner.uid)) {
296        return Ok(None);
297    }
298    let mut rows: Vec<VaultRow> = store
299        .vault_list()
300        .map_err(|e| e.to_string())?
301        .into_iter()
302        .filter(|r| {
303            let f = fields_of(r);
304            let get = |k: &str| f.get(k).map(String::as_str).unwrap_or("");
305            r.kind == "login"
306                && super::shares::answers_prompt(&f)
307                && super::shares::names(&f, &owner.uid)
308                && same_site(get(SITE), &s.origin)
309                && get(REALM) == s.realm
310                && f.contains_key(PROXY) == s.proxy
311                && offered(r)
312        })
313        .collect();
314    rows.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
315    for row in rows {
316        let mut usable = false;
317        for name in &owner.names {
318            usable = usable || super::vaults::entry_row_usable(store, &row.vault_id, Some(name))?;
319        }
320        if usable {
321            let user = fields_of(&row).get(USERNAME).cloned().unwrap_or_default();
322            return Ok(Some((row, user)));
323        }
324    }
325    Ok(None)
326}
327
328/// [`fill`] for the sign-in [`find_shared`] finds: the use is the agent's, logged under `actor`.
329pub fn fill_shared(store: &Store, s: &Space, owner: &ProfileOwner, actor: &str) -> Result<Option<(VaultRow, String, zeroize::Zeroizing<String>)>, String> {
330    let Some((row, user)) = find_shared(store, s, owner)? else { return Ok(None) };
331    let parts = seal::open(&seal::key(false)?, &row.id, &row.sealed)?;
332    let password = zeroize::Zeroizing::new(parts.get("password").unwrap_or("").to_string());
333    record(store, &row.id, &row.label, actor, SIGNED_IN, &s.origin, "done");
334    if let Err(e) = store.vault_touch(&row.id, now_ms()) {
335        tracing::warn!(error = %e, "vault: couldn't note a shared sign-in's use");
336    }
337    Ok(Some((row, user, password)))
338}
339
340/// Keeps the user name and password the person typed for `s`. The same user's
341/// entry gets the new password (the old one kept as a version); another user
342/// gets an entry of its own. Returns the entry's id.
343pub fn save(store: &Store, s: &Space, username: &str, password: &str) -> Result<String, String> {
344    save_as(store, s, username, password, None)
345}
346
347fn save_as(store: &Store, s: &Space, username: &str, password: &str, tag: Option<&str>) -> Result<String, String> {
348    let same_user = held(store, s)?.into_iter().find(|r| fields_of(r).get(USERNAME).map(String::as_str).unwrap_or("") == username);
349    if let Some(row) = same_user {
350        // A keychain copy is older than what the Vault holds for that user (the person
351        // saved it again meanwhile): it never replaces it.
352        if tag.is_some() {
353            return Ok(row.id);
354        }
355        let parts = seal::open(&seal::key(false)?, &row.id, &row.sealed)?;
356        let mut tags = tags_of(&row);
357        // A password the person saves is one they sent: a sign-up's "unconfirmed"
358        // goes with it, so a later strong password can't replace it (signups.rs).
359        let marked = |t: &String| t == REFUSED || t == super::signups::UNCONFIRMED;
360        let same = parts.get("password") == Some(password);
361        if same && !tags.iter().any(marked) {
362            return Ok(row.id);
363        }
364        tags.retain(|t| !marked(t));
365        let mut new = Parts::default();
366        if !same {
367            new.0.insert("password".to_string(), password.to_string());
368        }
369        super::update(store, EntryChange { id: row.id.clone(), label: row.label.clone(), fields: fields_of(&row), tags, parts: new, clear: Vec::new() })?;
370        return Ok(row.id);
371    }
372    let mut fields = BTreeMap::from([(SITE.to_string(), s.origin.clone()), (PROFILE.to_string(), s.profile.clone())]);
373    if !username.is_empty() {
374        fields.insert(USERNAME.to_string(), username.to_string());
375    }
376    if !s.realm.is_empty() {
377        fields.insert(REALM.to_string(), s.realm.clone());
378    }
379    if s.proxy {
380        fields.insert(PROXY.to_string(), "yes".to_string());
381    }
382    let mut parts = Parts::default();
383    parts.0.insert("password".to_string(), password.to_string());
384    let tags = tag.map(|t| vec![t.to_string()]).unwrap_or_default();
385    let entry = NewEntry { kind: "login".into(), label: label_for(s), fields, tags, parts };
386    let (action, target) = if tag.is_some() { ("moved in", "from the old sign-in store") } else { ("saved", "from a browser sign-in") };
387    super::insert_in(store, entry, PERSON, action, target, &vault_for(store, &s.profile)?)
388}
389
390/// A sign-in's label: the site's host, and the realm it names.
391pub(super) fn label_for(s: &Space) -> String {
392    let host = s.origin.split_once("://").map_or(s.origin.as_str(), |(_, h)| h);
393    let label = if s.realm.is_empty() { host.to_string() } else { format!("{host} ({})", s.realm) };
394    label.chars().take(super::MAX_LABEL).collect()
395}
396
397/// The site turned down the sign-in filled for `s`: it is kept, since it may be
398/// the person's only copy, but not offered again until a new password is saved.
399pub fn refused(store: &Store, s: &Space) -> Result<(), String> {
400    let Some((row, _)) = find(store, s)? else { return Ok(()) };
401    refused_row(store, &row, &s.origin)
402}
403
404/// [`refused`] for the sign-in `owner` was given through a share ([`find_shared`]): the same password is out of date
405/// in every profile that uses it.
406pub fn refused_shared(store: &Store, s: &Space, owner: &ProfileOwner) -> Result<(), String> {
407    let Some((row, _)) = find_shared(store, s, owner)? else { return Ok(()) };
408    refused_row(store, &row, &s.origin)
409}
410
411fn refused_row(store: &Store, row: &VaultRow, origin: &str) -> Result<(), String> {
412    let mut tags = tags_of(row);
413    if tags.len() < super::MAX_TAGS {
414        tags.push(REFUSED.to_string());
415    }
416    let changed = VaultRow { tags: serde_json::to_string(&tags).map_err(|e| e.to_string())?, updated_at: now_ms(), ..row.clone() };
417    if store.vault_update_kept(&changed, &row.sealed, &row.fields, None).map_err(|e| e.to_string())? {
418        record(store, &row.id, &row.label, PERSON, "refused by the site", origin, "done");
419    }
420    Ok(())
421}
422
423/// How many sign-ins each named profile holds, by profile id.
424pub fn counts(store: &Store) -> Result<BTreeMap<String, u32>, String> {
425    let mut out = BTreeMap::new();
426    for row in store.vault_list().map_err(|e| e.to_string())? {
427        if let Some(id) = fields_of(&row).get(PROFILE).and_then(|p| p.strip_prefix("profile:")) {
428            *out.entry(id.to_string()).or_insert(0) += 1;
429        }
430    }
431    Ok(out)
432}
433
434/// Profile `id` (named `name`) is being deleted: its sign-ins move to Personal,
435/// tagged with where they came from, or are deleted with it (§9.4). Returns how
436/// many there were. `owner` is the agent (by permanent uid) whose own profile it is: the logins shared with that
437/// agent, and the "Always" it holds, end with the profile, so the profile made for it next starts with none (A9).
438pub fn profile_deleted(store: &Store, id: &str, name: &str, keep: bool, owner: Option<&str>) -> Result<usize, String> {
439    let profile = format!("profile:{id}");
440    let rows: Vec<VaultRow> =
441        store.vault_list().map_err(|e| e.to_string())?.into_iter().filter(|r| fields_of(r).get(PROFILE) == Some(&profile)).collect();
442    for row in &rows {
443        if keep {
444            move_to_personal(store, &row.id, &profile, name)?;
445        } else {
446            super::delete(store, &row.id)?;
447        }
448    }
449    // The profile is going: it keeps no sign-in Vault of its own (reached only when every sign-in was dealt with).
450    store.signin_vault_set(&profile, PERSONAL_VAULT).map_err(|e| e.to_string())?;
451    if let Some(uid) = owner {
452        super::shares::forget_agent(store, uid)?;
453    }
454    Ok(rows.len())
455}
456
457/// Moves entry `id` from `profile` to Personal, tagged, and into the Vault Personal's tabs offer sign-ins from
458/// (the entry would not be offered there otherwise). One written meanwhile is read again; one still unmoved
459/// after that is an error, so the profile stays.
460fn move_to_personal(store: &Store, id: &str, profile: &str, name: &str) -> Result<(), String> {
461    for _ in 0..3 {
462        let Some(row) = store.vault_get(id).map_err(|e| e.to_string())? else { return Ok(()) };
463        let mut fields = fields_of(&row);
464        if fields.get(PROFILE).map(String::as_str) != Some(profile) {
465            return Ok(());
466        }
467        fields.insert(PROFILE.to_string(), PERSONAL.to_string());
468        let vault = vault_for(store, PERSONAL)?;
469        if row.vault_id != vault {
470            store.vault_move_entry(&row.id, &vault).map_err(|e| e.to_string())?;
471        }
472        let mut tags = tags_of(&row);
473        if tags.len() < super::MAX_TAGS {
474            tags.push(format!("from deleted profile {name}").chars().take(super::MAX_LABEL).collect());
475        }
476        let changed = VaultRow {
477            fields: serde_json::to_string(&fields).map_err(|e| e.to_string())?,
478            tags: serde_json::to_string(&tags).map_err(|e| e.to_string())?,
479            updated_at: now_ms(),
480            ..row.clone()
481        };
482        if store.vault_update_kept(&changed, &row.sealed, &row.fields, None).map_err(|e| e.to_string())? {
483            record(store, &row.id, &row.label, PERSON, "moved to Personal", &format!("profile {name} was deleted"), "done");
484            return Ok(());
485        }
486    }
487    Err(format!("the sign-in {id} kept changing while its profile was deleted, so the profile was kept: try again"))
488}
489
490/// Moves the HTTP sign-ins the keychain holds into the Vault, once: each goes
491/// to Personal, tagged for the person to check, and its keychain copy is then
492/// deleted. Only the ones the old store noted can be found (the keychain can't
493/// be listed). One the keychain can't read now stays for the next start.
494/// Returns how many moved.
495pub fn move_from_keychain(store: &Store) -> usize {
496    use crate::identity::browser_credential_store as old;
497    move_from(store, old::load, old::delete)
498}
499
500/// Reads or deletes a sign-in at its keychain address `(identity_id, origin, realm, is_proxy)`.
501type OldLoad = fn(&str, &str, &str, bool) -> Result<Option<crate::identity::browser_credential_store::BrowserCredential>, String>;
502type OldDelete = fn(&str, &str, &str, bool) -> Result<(), String>;
503
504/// [`move_from_keychain`], reading and deleting with `load` and `delete`.
505fn move_from(store: &Store, load: OldLoad, delete: OldDelete) -> usize {
506    let rows = match store.browser_signins_saved() {
507        Ok(rows) => rows,
508        Err(e) => {
509            tracing::warn!(error = %e, "vault: couldn't read the old browser sign-ins");
510            return 0;
511        }
512    };
513    let mut moved = 0;
514    for (identity, origin, realm, proxy) in rows {
515        let space = Space { profile: PERSONAL.to_string(), origin: origin.clone(), realm: realm.clone(), proxy };
516        match load(&identity, &origin, &realm, proxy) {
517            Ok(Some(cred)) => {
518                if let Err(e) = save_as(store, &space, &cred.username, &cred.password, Some(FROM_KEYCHAIN)) {
519                    tracing::warn!(error = %e, "vault: couldn't move a browser sign-in from the keychain");
520                    continue;
521                }
522                if let Err(e) = delete(&identity, &origin, &realm, proxy) {
523                    tracing::warn!(error = %e, "vault: moved a browser sign-in but couldn't delete its keychain copy");
524                }
525                moved += 1;
526            }
527            Ok(None) => {}
528            Err(e) => {
529                tracing::warn!(error = %e, "vault: the keychain couldn't read an old browser sign-in; trying again next start");
530                continue;
531            }
532        }
533        if let Err(e) = store.browser_signin_forget(&identity, &origin, &realm, proxy) {
534            tracing::warn!(error = %e, "vault: couldn't forget a moved browser sign-in");
535        }
536    }
537    if moved > 0 {
538        tracing::info!(moved, "vault: moved the browser's HTTP sign-ins from the keychain");
539    }
540    moved
541}
542
543#[cfg(test)]
544#[path = "signins_tests.rs"]
545mod tests;