Skip to main content

agentmux_srv_core/backend/vault/
shares.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shares: a login the person lets an agent's own browser profile use
5//! (docs/specs/SPEC_VAULT_AGENTS_ENTER_CREDENTIALS_WHEREVER_ASKED_2026_11_16.md ยง5).
6//!
7//! A login's `shared` field lists the agents by permanent uid, comma separated, or
8//! holds `*` for every agent. Only the person writes it (`inspect::person_only`
9//! refuses an agent's update of it). It changes nothing else about the entry. A
10//! share lets the agent ask: each first use is still approved as a `Browser`
11//! `signin` is (browser_signin.rs).
12//!
13//! A sign-in for a site's HTTP prompt or a proxy (A11) is shared the same way. The
14//! browser answers that prompt itself, in the agent's own profile
15//! ([`signins::find_shared`]); the person is asked at each use unless they chose
16//! "Always" for it, which is kept under [`prompt_grant_key`].
17
18use std::collections::BTreeMap;
19
20use agentmux_common::time::now_ms;
21
22use super::signins::{fields_of, REALM, SITE, USERNAME};
23use super::{history, inspect, record, record_line, signins, Line, PERSON};
24use crate::backend::storage::store::Store;
25
26/// The login field that lists the agents (by uid) an entry is shared with.
27pub const SHARED: &str = "shared";
28/// In [`SHARED`]: every agent.
29pub const EVERY_AGENT: &str = "*";
30const MAX_SHARES: usize = 32;
31
32/// Whether `name` is the share field of a `kind` entry. It is not among the kind's listed fields, which are what the
33/// Vault pane's forms offer: a share is made with the Share button, never typed as a field.
34pub fn is_field(kind: &str, name: &str) -> bool {
35    kind == "login" && name == SHARED
36}
37
38/// Who `fields` are shared with: agent uids, or [`EVERY_AGENT`].
39pub fn listed(fields: &BTreeMap<String, String>) -> Vec<String> {
40    fields.get(SHARED).map(|v| v.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()).unwrap_or_default()
41}
42
43/// Whether `fields` are shared with the agent whose permanent uid is `uid`.
44pub fn names(fields: &BTreeMap<String, String>, uid: &str) -> bool {
45    !uid.is_empty() && listed(fields).iter().any(|w| w == uid || w == EVERY_AGENT)
46}
47
48/// What an "Always" the person gave `uid` for a shared login starts with: `grant_key` in
49/// browser_signin.rs names the agent by uid for a shared login, never by a name.
50pub fn grant_prefix(uid: &str) -> String {
51    format!("signin:{uid}|")
52}
53
54/// The key the person's "Always" for a shared HTTP-prompt sign-in is kept under: [`grant_prefix`], so it is listed and
55/// ended as any sign-in's "Always" is, then the agent's own browser profile and the origin, kind of prompt and realm
56/// the person was shown. A login whose site or realm is edited afterwards has another key, so its next use asks again
57/// (A6); no form sign-in's key ends this way, so neither kind of "Always" stands for the other.
58pub fn prompt_grant_key(uid: &str, profile: &str, origin: &str, realm: &str, proxy: bool) -> String {
59    format!("{}{profile}|{origin}|prompt:{}|{realm}", grant_prefix(uid), if proxy { "proxy" } else { "site" })
60}
61
62/// Whether a login with these `fields` is a sign-in for a site's HTTP prompt (it names a realm) or for a proxy: the
63/// browser answers that prompt itself, and such a login is never typed into a form.
64pub fn answers_prompt(fields: &BTreeMap<String, String>) -> bool {
65    fields.contains_key(REALM) || fields.contains_key(super::signins::PROXY)
66}
67
68/// An agent's permanent uid, as a share can name it: never the "every agent" mark or a list.
69pub(super) fn is_uid(v: &str) -> bool {
70    !v.is_empty() && v != EVERY_AGENT && v.len() <= 64 && v.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
71}
72
73fn joined(list: &[String]) -> String {
74    list.join(",")
75}
76
77/// Share entry `id` with `who` (an agent's uid, or [`EVERY_AGENT`]), as the person: a login saved for a site.
78/// Returns false when it already was.
79pub fn add(store: &Store, id: &str, who: &str) -> Result<bool, String> {
80    add_shown(store, id, who, None)
81}
82
83/// [`add`], for a share the person allowed when shown `ask`: made only if the login is still the one they were shown.
84fn add_shown(store: &Store, id: &str, who: &str, shown: Option<&Ask>) -> Result<bool, String> {
85    if who != EVERY_AGENT && !is_uid(who) {
86        return Err("name the agent by its permanent uid, or * for every agent".into());
87    }
88    // A new share starts by asking: an "Always" this agent holds for the entry from before, or one answered while an
89    // earlier share was being removed, goes first.
90    revoke_always(store, id, who, None)?;
91    change(store, id, who, "shared", true, shown, |list| {
92        if list.iter().any(|w| w == who) {
93            return Ok(false);
94        }
95        if list.len() >= MAX_SHARES {
96            return Err(format!("an entry is shared with at most {MAX_SHARES} agents"));
97        }
98        list.push(who.to_string());
99        Ok(true)
100    })
101}
102
103/// Stop sharing entry `id` with `who`. Ends the "Always" the agent holds for it and returns whether a share was removed.
104pub fn remove(store: &Store, id: &str, who: &str) -> Result<bool, String> {
105    // A removal needs no eligibility: a login that has since lost its site, or gained a realm, can still be unshared.
106    let removed = change(store, id, who, "unshared", false, None, |list| {
107        let before = list.len();
108        list.retain(|w| w != who);
109        Ok(list.len() != before)
110    })?;
111    end_always(store, id, who)?;
112    Ok(removed)
113}
114
115/// Whether an entry of `kind` with these `fields` can be shared: a login saved for a site. One for a site's HTTP prompt
116/// or a proxy is shared too ([`answers_prompt`]): the browser answers the prompt with it, and it is typed into no form.
117pub fn check_shareable(kind: &str, fields: &BTreeMap<String, String>) -> Result<(), String> {
118    if kind != "login" || !fields.contains_key(SITE) {
119        return Err("only a login saved for a site can be shared".into());
120    }
121    Ok(())
122}
123
124fn change(store: &Store, id: &str, who: &str, action: &str, eligible: bool, shown: Option<&Ask>, edit: impl Fn(&mut Vec<String>) -> Result<bool, String>) -> Result<bool, String> {
125    for _ in 0..3 {
126        let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
127        let mut fields = fields_of(&row);
128        if eligible {
129            check_shareable(&row.kind, &fields)?;
130        }
131        // Checked on the row this write is made over, so no edit of the login can land between the check and the write.
132        if let Some(ask) = shown {
133            if &asked_of(&row, &fields, &ask.reason) != ask {
134                return Err(format!("{} changed while the person was asked, so nothing was shared: ask again", ask.label));
135            }
136        }
137        let mut list = listed(&fields);
138        if !edit(&mut list)? {
139            return Ok(false);
140        }
141        if list.is_empty() {
142            fields.remove(SHARED);
143        } else {
144            fields.insert(SHARED.to_string(), joined(&list));
145        }
146        // Written only if the fields are still as read, so two overlapping share changes can't each succeed on what the
147        // other has undone (one removing an agent while another adds one must not bring the removed share back).
148        let new_fields = serde_json::to_string(&fields).map_err(|e| e.to_string())?;
149        if store.vault_set_fields_if(&row.id, row.created_at, &row.sealed, &row.fields, &new_fields, now_ms()).map_err(|e| e.to_string())? {
150            // The line names no agent: an agent may read an entry's history, and who a login is shared with is not
151            // for it (A8). The entry's card lists each share for the person.
152            record(store, &row.id, &row.label, PERSON, action, if who == EVERY_AGENT { "every agent" } else { "an agent" }, "done");
153            return Ok(true);
154        }
155    }
156    Err(format!("the entry {id} kept changing: try again"))
157}
158
159/// Ends every "Always" `who` holds for entry `id` through a share: an agent's uid, or for
160/// [`EVERY_AGENT`] those of every agent the entry is no longer shared with.
161pub fn end_always(store: &Store, id: &str, who: &str) -> Result<(), String> {
162    let row = store.vault_get(id).map_err(|e| e.to_string())?;
163    let still = row.as_ref().map(fields_of).unwrap_or_default();
164    revoke_always(store, id, who, Some(&still))
165}
166
167/// [`end_always`] for the entry as `still` has it: an agent `still` names keeps its own. `None` ends them all.
168fn revoke_always(store: &Store, id: &str, who: &str, still: Option<&BTreeMap<String, String>>) -> Result<(), String> {
169    let keys = store.vault_grants().map_err(|e| e.to_string())?.remove(id).unwrap_or_default();
170    for key in keys {
171        let Some(rest) = key.strip_prefix("signin:") else { continue };
172        let mut parts = rest.splitn(3, '|');
173        let (agent, profile) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
174        // A share is used in the agent's own profile, never Personal's or a named one's.
175        if !profile.starts_with("profile:agent-") || still.is_some_and(|f| names(f, agent)) {
176            continue;
177        }
178        if who == EVERY_AGENT || agent == who {
179            store.vault_grant_revoke(id, &key).map_err(|e| e.to_string())?;
180        }
181    }
182    Ok(())
183}
184
185/// What an agent's `Vault share` asks the person, as the card shows it: the login, its site and its user name masked.
186/// `created_at` binds it to this login: one deleted and made again is another.
187#[derive(Debug, Clone, PartialEq)]
188pub struct Ask {
189    pub entry_id: String,
190    pub label: String,
191    pub site: String,
192    pub user: String,
193    pub created_at: i64,
194    pub reason: String,
195    /// The login answers a site's HTTP prompt or a proxy's ([`answers_prompt`]): `realm` is the realm it names and
196    /// `proxy` whether it is a proxy's. A login that became one, or stopped being one, while the person was asked is
197    /// not the login they were shown.
198    pub prompt: bool,
199    pub realm: String,
200    pub proxy: bool,
201}
202
203/// What `plan_ask` found.
204#[derive(Debug, PartialEq)]
205pub enum Asked {
206    /// The login is shared with the agent already: nobody is asked. Its label.
207    Already(String),
208    Ask(Ask),
209}
210
211fn asked_of(row: &super::VaultRow, fields: &BTreeMap<String, String>, reason: &str) -> Ask {
212    Ask {
213        entry_id: row.id.clone(),
214        label: row.label.clone(),
215        site: fields.get(SITE).cloned().unwrap_or_default(),
216        user: signins::mask(fields.get(USERNAME).map(String::as_str).unwrap_or("")),
217        created_at: row.created_at,
218        reason: reason.to_string(),
219        prompt: answers_prompt(fields),
220        realm: fields.get(REALM).cloned().unwrap_or_default(),
221        proxy: fields.contains_key(super::signins::PROXY),
222    }
223}
224
225/// Every check of an agent's `Vault share`, with nothing written: the reason, that the agent may use the entry (anything
226/// else is "no entry"), that it is a login that can be shared, and that it is not shared with the agent already. `uid`
227/// is the agent's permanent uid, proven by the caller: an agent asks for a share for itself only.
228pub fn plan_ask(store: &Store, id: &str, agent: &str, uid: &str, reason: Option<&str>) -> Result<Asked, String> {
229    let reason = history::require_reason(reason)?;
230    if !is_uid(uid) {
231        return Err("this agent has no permanent identity a share could name".into());
232    }
233    let row = inspect::entry_for(store, id, Some(agent))?;
234    let fields = fields_of(&row);
235    check_shareable(&row.kind, &fields)?;
236    if names(&fields, uid) {
237        return Ok(Asked::Already(row.label));
238    }
239    Ok(Asked::Ask(asked_of(&row, &fields, &reason)))
240}
241
242/// The person allowed `ask`: shares the login with the agent `uid`, if it is still the login they were shown.
243pub fn grant_asked(store: &Store, ask: &Ask, uid: &str) -> Result<(), String> {
244    add_shown(store, &ask.entry_id, uid, Some(ask)).map(|_| ())
245}
246
247/// The person answered "Always" to `ask` for an HTTP-prompt sign-in: [`grant_asked`], and the browser then answers
248/// the prompt in the agent's own `profile` without asking again. Only a login that answers a prompt has this: a form
249/// login's "Always" is given at its first `signin`, never with the share (A6).
250pub fn grant_asked_always(store: &Store, ask: &Ask, uid: &str, profile: &str) -> Result<(), String> {
251    if !ask.prompt {
252        return Err("only a sign-in for a site's HTTP prompt or a proxy is shared with an Always".into());
253    }
254    grant_asked(store, ask, uid)?;
255    let key = prompt_grant_key(uid, profile, &ask.site, &ask.realm, ask.proxy);
256    store.vault_grant_add(&ask.entry_id, &key, now_ms(), ask.created_at).map_err(|e| e.to_string())
257}
258
259/// Whether the person gave agent `uid` an "Always" for the shared HTTP-prompt sign-in `row`, used in `profile`: the
260/// login is still shared with it and still names the site and realm the "Always" was given for.
261pub fn prompt_always(store: &Store, row: &super::VaultRow, uid: &str, profile: &str) -> bool {
262    let fields = fields_of(row);
263    if !answers_prompt(&fields) || !names(&fields, uid) {
264        return false;
265    }
266    let get = |k: &str| fields.get(k).map(String::as_str).unwrap_or("");
267    let key = prompt_grant_key(uid, profile, get(SITE), get(REALM), fields.contains_key(super::signins::PROXY));
268    store.vault_grant_check(&row.id, &key).unwrap_or(false)
269}
270
271/// The history line of an ask that did not end in a share: `outcome` is `denied`, `expired` or the like.
272pub fn note_ask(store: &Store, ask: &Ask, agent: &str, outcome: &str) {
273    record_line(store, Line { entry_id: &ask.entry_id, label: &ask.label, actor: agent, action: ASKED_TO_BE_SHARED, target: &ask.site, outcome, reason: &ask.reason });
274}
275
276/// The history action of an agent's request to be given a login.
277pub const ASKED_TO_BE_SHARED: &str = "asked to be given it";
278
279/// Agent `uid` is gone: its shares go, and the "Always" it held with them (A9).
280pub fn forget_agent(store: &Store, uid: &str) -> Result<usize, String> {
281    if !is_uid(uid) {
282        return Ok(0);
283    }
284    let mut removed = 0;
285    for row in store.vault_list().map_err(|e| e.to_string())? {
286        if listed(&fields_of(&row)).iter().any(|w| w == uid) {
287            // One entry that can't be changed now does not leave the others shared: the rest still go.
288            match remove(store, &row.id, uid) {
289                Ok(true) => removed += 1,
290                Ok(false) => {}
291                Err(e) => tracing::warn!(entry = %row.id, error = %e, "vault: couldn't remove a deleted agent's share"),
292            }
293        }
294    }
295    // Always held for it by an entry it was no longer named on.
296    let prefix = grant_prefix(uid);
297    for (entry, keys) in store.vault_grants().map_err(|e| e.to_string())? {
298        for key in keys.into_iter().filter(|k| k.starts_with(&prefix)) {
299            if let Err(e) = store.vault_grant_revoke(&entry, &key) {
300                tracing::warn!(entry = %entry, error = %e, "vault: couldn't end a deleted agent's Always");
301            }
302        }
303    }
304    Ok(removed)
305}
306
307#[cfg(test)]
308#[path = "shares_tests.rs"]
309mod tests;
310
311#[cfg(test)]
312#[path = "shares_prompt_tests.rs"]
313mod prompt_tests;