Skip to main content

agentmux_srv_core/backend/vault/
sync_record.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Vault entry as the body of a sync record (docs/specs/SPEC_VAULT_SHARED_ACROSS_MACHINES_LAN_AND_CLOUD_2026_11_01.md
5//! sections 6.1 and 6.6): what goes inside the seal of [`super::sync_seal`], and what a machine that receives one makes
6//! of it.
7//!
8//! The body holds the entry's kind, label, plain fields, tags and secret parts, and when it was made and last changed.
9//! It leaves out what is the machine's own: who a login is shared with (the agents of one machine, `shares::SHARED`),
10//! when the entry was last used here, and the grants (a table of their own, which never syncs). The values are in clear
11//! inside the body, so the body is wiped when dropped and never printed.
12
13use std::collections::BTreeMap;
14
15use serde::{Deserialize, Serialize};
16use zeroize::Zeroize;
17
18use super::seal::Parts;
19use super::shares;
20use super::signins::{PERSONAL, PROFILE};
21use crate::backend::browser_profiles_store::BrowserProfile;
22use crate::backend::storage::vault::VaultRow;
23
24/// The plain fields that name this machine's agents, which a synced entry neither sends nor overwrites.
25pub const LOCAL_FIELDS: [&str; 1] = [shares::SHARED];
26
27/// The plain field that names the browser profile a sign-in belongs to, in place of `profile`: a profile's id is made on
28/// one machine and means nothing on another, its name is what the person sees on both.
29pub const PROFILE_NAME: &str = "profile_name";
30/// On a sign-in received for a profile this machine does not have: the name of that profile. The sign-in is shown under
31/// Personal, marked with it.
32pub const PROFILE_FROM: &str = "profile_from";
33
34/// The person's browser profiles of one machine, by id and by name.
35pub trait Profiles {
36    /// The name of the person's profile `id`; `None` for an agent's own profile and for one that does not exist.
37    fn name_of(&self, id: &str) -> Option<String>;
38    /// The id of the person's profile called `name` (the same name in any case), if this machine has one.
39    fn id_of(&self, name: &str) -> Option<String>;
40}
41
42/// The profiles of this machine, as `browser_profiles_store::read_profiles` lists them.
43pub struct Known<'a>(pub &'a [BrowserProfile]);
44
45impl Profiles for Known<'_> {
46    fn name_of(&self, id: &str) -> Option<String> {
47        self.0.iter().find(|p| p.id == id && p.owner_agent.is_none()).map(|p| p.name.clone())
48    }
49    fn id_of(&self, name: &str) -> Option<String> {
50        self.0.iter().find(|p| p.owner_agent.is_none() && p.name.eq_ignore_ascii_case(name)).map(|p| p.id.clone())
51    }
52}
53
54/// An entry as a sync record carries it.
55#[derive(Clone, PartialEq, Serialize, Deserialize)]
56pub struct EntryBody {
57    pub kind: String,
58    pub label: String,
59    pub fields: BTreeMap<String, String>,
60    pub tags: Vec<String>,
61    /// The secret parts by name, empty for a link and for an entry backed by AWS Secrets Manager: such an entry is sent
62    /// as the reference only, and each machine that can reads the secret itself.
63    pub parts: BTreeMap<String, String>,
64    pub created_at: i64,
65    pub updated_at: i64,
66    /// The entry's link ids (`sync_links`): its own first, then its aliases. Empty from a machine that sends none.
67    #[serde(default, skip_serializing_if = "Vec::is_empty")]
68    pub link_ids: Vec<String>,
69}
70
71impl Drop for EntryBody {
72    fn drop(&mut self) {
73        self.parts.values_mut().for_each(|v| v.zeroize());
74    }
75}
76
77/// What a log may say of a body: its label and which parts it holds, never a value.
78impl std::fmt::Debug for EntryBody {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        f.debug_struct("EntryBody").field("kind", &self.kind).field("label", &self.label).field("parts", &self.parts.keys().collect::<Vec<_>>()).finish_non_exhaustive()
81    }
82}
83
84impl EntryBody {
85    /// The body of `row`, whose parts are `parts` (opened with this machine's key by the caller).
86    pub fn of_row(row: &VaultRow, parts: &Parts, profiles: &dyn Profiles) -> EntryBody {
87        let mut fields: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
88        for name in LOCAL_FIELDS {
89            fields.remove(name);
90        }
91        // A machine's profile id never leaves it: the profile goes by name (a sign-in that can't be named stays here, see
92        // `stays_here`, so none arrives without one).
93        let from = fields.remove(PROFILE_FROM);
94        if let Some(id) = fields.get(PROFILE).and_then(|p| p.strip_prefix("profile:")).map(str::to_string) {
95            fields.remove(PROFILE);
96            if let Some(name) = profiles.name_of(&id) {
97                fields.insert(PROFILE_NAME.to_string(), name);
98            }
99        } else if let Some(name) = from {
100            // A sign-in that arrived for a profile this machine lacks is still that profile's: it goes on by its name, so
101            // an edit made here does not move it to Personal for every machine that has the profile.
102            fields.remove(PROFILE);
103            fields.insert(PROFILE_NAME.to_string(), name);
104        }
105        EntryBody {
106            kind: row.kind.clone(),
107            label: row.label.clone(),
108            fields,
109            tags: serde_json::from_str(&row.tags).unwrap_or_default(),
110            parts: parts.0.clone(),
111            created_at: row.created_at,
112            updated_at: row.updated_at,
113            link_ids: Vec::new(),
114        }
115    }
116
117    /// This body carrying the entry's link ids, from [`super::sync_links::Links::ids`].
118    pub fn with_link_ids(mut self, ids: Vec<String>) -> EntryBody {
119        self.link_ids = ids;
120        self
121    }
122
123    /// The row this body makes on this machine, in the Vault `vault_id`. `sealed` is its parts sealed with this
124    /// machine's own key (`seal::seal`), and `local` the row it replaces, if there is one: the fields that are this
125    /// machine's own and the time of its last use here stay as they were.
126    pub fn into_row(&self, id: &str, vault_id: &str, sealed: Vec<u8>, local: Option<&VaultRow>, profiles: &dyn Profiles) -> VaultRow {
127        let mut fields = self.fields.clone();
128        for name in LOCAL_FIELDS {
129            fields.remove(name);
130        }
131        // The profile by name: the profile of that name here, or Personal marked with the name. A raw profile id in a
132        // body is another machine's and is not trusted.
133        fields.remove(PROFILE_FROM);
134        let named = fields.remove(PROFILE_NAME);
135        if fields.get(PROFILE).is_some_and(|p| p != PERSONAL) {
136            fields.remove(PROFILE);
137        }
138        if let Some(name) = named {
139            match profiles.id_of(&name) {
140                Some(pid) => {
141                    fields.insert(PROFILE.to_string(), format!("profile:{pid}"));
142                }
143                None => {
144                    fields.insert(PROFILE.to_string(), PERSONAL.to_string());
145                    fields.insert(PROFILE_FROM.to_string(), name);
146                }
147            }
148        }
149        let kept: BTreeMap<String, String> = local.map(|r| serde_json::from_str(&r.fields).unwrap_or_default()).unwrap_or_default();
150        for name in LOCAL_FIELDS {
151            if let Some(own) = kept.get(name) {
152                fields.insert(name.to_string(), own.clone());
153            }
154        }
155        VaultRow {
156            id: id.to_string(),
157            kind: self.kind.clone(),
158            label: self.label.clone(),
159            fields: serde_json::to_string(&fields).unwrap_or_else(|_| "{}".to_string()),
160            tags: serde_json::to_string(&self.tags).unwrap_or_else(|_| "[]".to_string()),
161            sealed,
162            created_at: self.created_at,
163            updated_at: self.updated_at,
164            last_used_at: local.map_or(0, |r| r.last_used_at),
165            vault_id: vault_id.to_string(),
166        }
167    }
168}
169
170/// Whether `row` is one this machine keeps to itself: a sign-in in the own browsing profile of an agent, or in a profile
171/// that has no name here. Such an entry would land under Personal on another machine, where more of the person's tabs may
172/// use it than the profile it was saved for, so it does not go.
173pub fn stays_here(row: &VaultRow, profiles: &dyn Profiles) -> bool {
174    let fields: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
175    fields.get(PROFILE).and_then(|p| p.strip_prefix("profile:")).is_some_and(|id| profiles.name_of(id).is_none())
176}
177
178#[cfg(test)]
179#[path = "sync_record_tests.rs"]
180mod tests;