Skip to main content

agentmux_srv_core/backend/vault/
vaults.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Several Vaults on one computer: the person keeps some entries to one set of agents
5//! and others to another, or to none
6//! (docs/specs/SPEC_VAULT_SHARED_ACROSS_MACHINES_LAN_AND_CLOUD_2026_11_01.md ยง5).
7//!
8//! Every entry belongs to exactly one Vault. Entry ids stay global, so every route that
9//! names an entry by id works as before; a Vault only narrows which agents may ask for
10//! an entry, and an agent that may not is told the entry doesn't exist.
11
12use serde::{Deserialize, Serialize};
13
14use crate::backend::storage::store::Store;
15use crate::backend::storage::vault::{VaultInfoRow, PERSONAL_VAULT};
16
17use super::{record, PERSON};
18
19const MAX_NAME: usize = 60;
20const MAX_VAULTS: usize = 50;
21
22/// Which agents may use a Vault's entries.
23#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ts_rs::TS)]
24#[serde(tag = "mode", content = "agents", rename_all = "lowercase")]
25#[ts(export, export_to = "../../../frontend/types/rpc/")]
26pub enum VaultAgents {
27    /// Every agent on this machine (Personal's setting, today's behaviour).
28    #[default]
29    All,
30    /// None: the person uses the entries themselves (reveal, copy, a browser fill they approve).
31    None,
32    /// Only these agents, by id.
33    Named(Vec<String>),
34}
35
36/// A Vault as the pane shows it.
37#[derive(Debug, Clone, Serialize, ts_rs::TS)]
38#[ts(export, export_to = "../../../frontend/types/rpc/")]
39pub struct VaultInfo {
40    pub id: String,
41    pub name: String,
42    pub agents: VaultAgents,
43    pub entries: u32,
44}
45
46pub fn agents_of(row: &VaultInfoRow) -> VaultAgents {
47    match row.agents.as_str() {
48        "none" => VaultAgents::None,
49        "named" => VaultAgents::Named(serde_json::from_str(&row.agent_ids).unwrap_or_default()),
50        _ => VaultAgents::All,
51    }
52}
53
54fn columns(agents: &VaultAgents) -> (&'static str, String) {
55    match agents {
56        VaultAgents::All => ("all", "[]".into()),
57        VaultAgents::None => ("none", "[]".into()),
58        VaultAgents::Named(ids) => ("named", serde_json::to_string(ids).unwrap_or_else(|_| "[]".into())),
59    }
60}
61
62fn same(a: &str, b: &str) -> bool {
63    a.trim().eq_ignore_ascii_case(b.trim())
64}
65
66/// Whether `agent` may use the entries of the Vault `row`. An agent that isn't proven
67/// (`None`) is let into a Vault open to all agents only.
68pub fn may_use(row: &VaultInfoRow, agent: Option<&str>) -> bool {
69    match agents_of(row) {
70        VaultAgents::All => true,
71        VaultAgents::None => false,
72        VaultAgents::Named(ids) => agent.is_some_and(|a| ids.iter().any(|id| same(id, a))),
73    }
74}
75
76/// Whether `agent` may use the entry `entry_id`. An entry in a Vault that is gone counts
77/// as Personal's.
78pub fn entry_usable(store: &Store, entry_id: &str, agent: Option<&str>) -> Result<bool, String> {
79    let Some(row) = store.vault_get(entry_id).map_err(|e| e.to_string())? else { return Ok(false) };
80    entry_row_usable(store, &row.vault_id, agent)
81}
82
83/// [`entry_usable`] for a Vault id.
84pub fn entry_row_usable(store: &Store, vault_id: &str, agent: Option<&str>) -> Result<bool, String> {
85    Ok(store.vault_info(vault_id).map_err(|e| e.to_string())?.is_none_or(|v| may_use(&v, agent)))
86}
87
88/// The Vault a new entry made by `agent` goes to when it names none: the first Vault, in
89/// the person's order, the agent may use.
90pub fn default_for(store: &Store, agent: Option<&str>) -> Result<String, String> {
91    store
92        .vaults()
93        .map_err(|e| e.to_string())?
94        .into_iter()
95        .find(|v| may_use(v, agent))
96        .map(|v| v.id)
97        .ok_or_else(|| "no Vault is open to this agent: the person decides which agents each Vault is for, in the Vault pane".to_string())
98}
99
100/// A Vault by name or id. `agent` limits it to the Vaults that agent may use; an agent
101/// told "no such Vault" can't tell a Vault it may not use from one that isn't there.
102pub fn resolve(store: &Store, which: &str, agent: Option<Option<&str>>) -> Result<VaultInfoRow, String> {
103    let which = which.trim();
104    let vaults = store.vaults().map_err(|e| e.to_string())?;
105    let found = vaults
106        .iter()
107        .find(|v| v.id == which)
108        .or_else(|| vaults.iter().find(|v| same(&v.name, which)))
109        .filter(|v| agent.is_none_or(|a| may_use(v, a)))
110        .cloned();
111    found.ok_or_else(|| {
112        let names: Vec<&str> = vaults.iter().filter(|v| agent.is_none_or(|a| may_use(v, a))).map(|v| v.name.as_str()).collect();
113        format!("no Vault {which:?}; the Vaults are {}", if names.is_empty() { "none".to_string() } else { names.join(", ") })
114    })
115}
116
117/// Every Vault, with how many entries it holds.
118pub fn list(store: &Store) -> Result<Vec<VaultInfo>, String> {
119    let entries = store.vault_list().map_err(|e| e.to_string())?;
120    Ok(store
121        .vaults()
122        .map_err(|e| e.to_string())?
123        .into_iter()
124        .map(|v| VaultInfo { entries: entries.iter().filter(|e| e.vault_id == v.id).count() as u32, agents: agents_of(&v), id: v.id, name: v.name })
125        .collect())
126}
127
128fn clean_name(store: &Store, name: &str, besides: Option<&str>) -> Result<String, String> {
129    let name = name.trim();
130    if name.is_empty() {
131        return Err("a Vault needs a name".into());
132    }
133    if name.chars().count() > MAX_NAME {
134        return Err(format!("a Vault's name is at most {MAX_NAME} characters"));
135    }
136    if store.vaults().map_err(|e| e.to_string())?.iter().any(|v| Some(v.id.as_str()) != besides && same(&v.name, name)) {
137        return Err(format!("there is already a Vault named {name:?}"));
138    }
139    Ok(name.to_string())
140}
141
142fn clean_agents(agents: VaultAgents) -> Result<VaultAgents, String> {
143    let VaultAgents::Named(ids) = agents else { return Ok(agents) };
144    let mut out: Vec<String> = Vec::new();
145    for id in ids.iter().map(|i| i.trim()).filter(|i| !i.is_empty()) {
146        if id.chars().count() > 64 {
147            return Err("an agent id is at most 64 characters".into());
148        }
149        if !out.iter().any(|o| same(o, id)) {
150            out.push(id.to_string());
151        }
152    }
153    Ok(VaultAgents::Named(out))
154}
155
156/// Adds a Vault with a name and who may use it.
157pub fn create(store: &Store, name: &str, agents: VaultAgents) -> Result<VaultInfo, String> {
158    if store.vaults().map_err(|e| e.to_string())?.len() >= MAX_VAULTS {
159        return Err(format!("at most {MAX_VAULTS} Vaults"));
160    }
161    let name = clean_name(store, name, None)?;
162    let agents = clean_agents(agents)?;
163    let (mode, ids) = columns(&agents);
164    let id = format!("vault-{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
165    let row = VaultInfoRow { id: id.clone(), name: name.clone(), agents: mode.into(), agent_ids: ids, position: 0, created_at: agentmux_common::time::now_ms() };
166    store.vault_add(&row).map_err(|e| e.to_string())?;
167    record(store, "", &name, PERSON, "created a Vault", &name, "done");
168    Ok(VaultInfo { id, name, agents, entries: 0 })
169}
170
171/// Renames a Vault and sets who may use it.
172pub fn update(store: &Store, id: &str, name: &str, agents: VaultAgents) -> Result<(), String> {
173    store.vault_info(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no Vault {id}"))?;
174    let name = clean_name(store, name, Some(id))?;
175    let agents = clean_agents(agents)?;
176    let (mode, ids) = columns(&agents);
177    store.vault_set(id, &name, mode, &ids).map_err(|e| e.to_string())?;
178    record(store, "", &name, PERSON, "changed a Vault", &name, "done");
179    Ok(())
180}
181
182/// Removes an empty Vault. Personal stays.
183pub fn remove(store: &Store, id: &str) -> Result<(), String> {
184    if id == PERSONAL_VAULT {
185        return Err("Personal is the Vault every entry started in, and stays".into());
186    }
187    let info = store.vault_info(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no Vault {id}"))?;
188    if !store.vault_remove(id).map_err(|e| e.to_string())? {
189        return Err(format!("{} still holds entries: move them to another Vault, or delete them, first", info.name));
190    }
191    record(store, "", &info.name, PERSON, "deleted a Vault", &info.name, "done");
192    Ok(())
193}
194
195/// Puts an entry in another Vault, keeping its id, versions and grants. Only the person
196/// does this: a move can open a value to more agents.
197pub fn move_entry(store: &Store, entry_id: &str, vault_id: &str) -> Result<(), String> {
198    let row = store.vault_get(entry_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {entry_id}"))?;
199    let to = store.vault_info(vault_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no Vault {vault_id}"))?;
200    if row.vault_id == to.id {
201        return Ok(());
202    }
203    let from = store.vault_info(&row.vault_id).map_err(|e| e.to_string())?.map(|v| v.name).unwrap_or_else(|| row.vault_id.clone());
204    store.vault_move_entry(entry_id, &to.id).map_err(|e| e.to_string())?;
205    record(store, entry_id, &row.label, PERSON, "moved to another Vault", &format!("{from} -> {}", to.name), "done");
206    Ok(())
207}
208
209/// Each browser profile's sign-in Vault (`personal` or `profile:<id>`) other than Personal.
210pub fn signin_vaults(store: &Store) -> Result<std::collections::BTreeMap<String, String>, String> {
211    Ok(store.signin_vaults().map_err(|e| e.to_string())?.into_iter().collect())
212}
213
214/// Sets the Vault browser profile `profile` saves its sign-ins to and offers them from. The
215/// sign-ins it already has stay in the Vault they are in: move them, or they are not offered.
216pub fn set_signin_vault(store: &Store, profile: &str, vault_id: &str) -> Result<(), String> {
217    if !super::signins::is_profile(profile) {
218        return Err(format!("{profile:?} is not a browser profile (personal, or profile:<id>)"));
219    }
220    let to = store.vault_info(vault_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no Vault {vault_id}"))?;
221    store.signin_vault_set(profile, &to.id).map_err(|e| e.to_string())?;
222    record(store, "", &to.name, PERSON, "chose a profile's sign-in Vault", profile, "done");
223    Ok(())
224}
225
226#[cfg(test)]
227mod tests;