1use 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
26pub const SHARED: &str = "shared";
28pub const EVERY_AGENT: &str = "*";
30const MAX_SHARES: usize = 32;
31
32pub fn is_field(kind: &str, name: &str) -> bool {
35 kind == "login" && name == SHARED
36}
37
38pub 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
43pub 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
48pub fn grant_prefix(uid: &str) -> String {
51 format!("signin:{uid}|")
52}
53
54pub 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
62pub fn answers_prompt(fields: &BTreeMap<String, String>) -> bool {
65 fields.contains_key(REALM) || fields.contains_key(super::signins::PROXY)
66}
67
68pub(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
77pub fn add(store: &Store, id: &str, who: &str) -> Result<bool, String> {
80 add_shown(store, id, who, None)
81}
82
83fn 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 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
103pub fn remove(store: &Store, id: &str, who: &str) -> Result<bool, String> {
105 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
115pub 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 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 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 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
159pub 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
167fn 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 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#[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 pub prompt: bool,
199 pub realm: String,
200 pub proxy: bool,
201}
202
203#[derive(Debug, PartialEq)]
205pub enum Asked {
206 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
225pub 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
242pub fn grant_asked(store: &Store, ask: &Ask, uid: &str) -> Result<(), String> {
244 add_shown(store, &ask.entry_id, uid, Some(ask)).map(|_| ())
245}
246
247pub 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
259pub 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
271pub 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
276pub const ASKED_TO_BE_SHARED: &str = "asked to be given it";
278
279pub 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 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 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;