Skip to main content

agentmux_srv_core/backend/vault/
sync_seal.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Vault record as it leaves the machine: sealed with the Vault's collection key, so a LAN peer's log, the relay and
5//! the cloud store see only the clear header (docs/specs/SPEC_VAULT_SHARED_ACROSS_MACHINES_LAN_AND_CLOUD_2026_11_01.md
6//! section 6.1) and never a label, a kind, a site or a value.
7//!
8//! The seal is ChaCha20-Poly1305 with a random nonce and the associated data
9//! `agentmux-vault-sync-v1:<vault>:<record>:<version>:<epoch>:<base>`, so a record replayed under another Vault, record, version
10//! key epoch or base does not open, and an old version can't be put back under the same id. This is a different seal from
11//! `seal.rs`, which keeps a value on one machine under that machine's own key: the record is opened with the collection
12//! key on arrival and sealed again with the machine key.
13//!
14//! Every function here is pure: bytes in, bytes out. Nothing reads a store, a clock or the network, so the layer that
15//! carries the records (and the cloud service that stores them) needs none of this to be built first.
16
17use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305, NONCE_LEN};
18use ring::rand::{SecureRandom, SystemRandom};
19use serde::de::DeserializeOwned;
20use serde::Serialize;
21use zeroize::Zeroizing;
22
23use super::seal::Key;
24
25/// The associated data's first part: what the seal is for and its format.
26pub const AAD_PREFIX: &str = "agentmux-vault-sync-v1";
27/// The first byte of every sealed record: its format.
28const FORMAT_V1: u8 = 1;
29/// A sealed record travels in pieces of at most this size. A record in AWS Secrets Manager is limited to 64 KB, and the
30/// pieces leave room for the framing around them.
31pub const MAX_CHUNK: usize = 48 * 1024;
32/// The most a sealed record may weigh: a Vault part is at most 1 MiB, and a file entry goes as content-addressed chunks
33/// of its own, so this bounds the record and not the file.
34pub const MAX_SEALED: usize = 8 * 1024 * 1024;
35
36/// A record's version, the layer's hybrid logical clock (`user_sync::hlc`): ordered by wall time, then counter, then machine,
37/// so any two versions are ordered and a machine with a fast clock cannot make two of its own versions equal.
38pub use crate::backend::user_sync::hlc::Version;
39
40impl Version {
41    pub fn new(wall_ms: i64, counter: u32, machine: &str) -> Self {
42        Self { wall_ms, counter, machine: machine.to_string() }
43    }
44
45    /// The version as the associated data writes it.
46    pub fn text(&self) -> String {
47        format!("{}.{}.{}", self.wall_ms, self.counter, self.machine)
48    }
49}
50
51/// Where a sealed record belongs: the Vault, the record, the version and the key epoch it was sealed at. All four are in
52/// the associated data, so a record only opens at the place it was sealed for.
53#[derive(Debug, Clone, Copy)]
54pub struct Place<'a> {
55    pub vault: &'a str,
56    pub record: &'a str,
57    pub version: &'a Version,
58    /// The version the change replaced on the machine that made it, `None` for a first version. It is in the associated
59    /// data too: the merge decides from it whether two changes were made apart, so a relay that altered it in the clear
60    /// header would otherwise hide a conflict.
61    pub base: Option<&'a Version>,
62    pub epoch: u32,
63}
64
65/// A Vault, record or machine id as it may appear in the associated data: no `:` to run two parts into one.
66fn plain_id(s: &str) -> bool {
67    !s.is_empty() && s.len() <= 128 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
68}
69
70impl Place<'_> {
71    /// The associated data under a prefix: the Vault's is [`AAD_PREFIX`], and another kind of collection seals its
72    /// records the same way under its own (see `user_sync::seal`).
73    fn aad_with(&self, prefix: &str) -> Result<Vec<u8>, String> {
74        let base_machine = self.base.map(|b| ("machine", b.machine.as_str()));
75        for (what, id) in [("Vault", self.vault), ("record", self.record), ("machine", self.version.machine.as_str())].into_iter().chain(base_machine) {
76            if !plain_id(id) {
77                return Err(format!("a synced record's {what} id is letters, digits and ._- only, at most 128 characters"));
78            }
79        }
80        let base = self.base.map_or_else(|| "-".to_string(), Version::text);
81        Ok(format!("{prefix}:{}:{}:{}:{}:{base}", self.vault, self.record, self.version.text(), self.epoch).into_bytes())
82    }
83}
84
85fn aead_key(key: &Key) -> LessSafeKey {
86    LessSafeKey::new(UnboundKey::new(&CHACHA20_POLY1305, &key[..]).expect("a 32-byte key"))
87}
88
89const CANT_OPEN: &str = "a synced record can't be opened: it was changed, it was sealed for another place, or it was sealed with another key";
90
91/// Seals `plain` for the place `at`. The plaintext is copied into a buffer that is wiped when this returns.
92pub fn seal_raw(key: &Key, at: &Place<'_>, plain: &[u8]) -> Result<Vec<u8>, String> {
93    seal_raw_with(AAD_PREFIX, key, at, plain)
94}
95
96/// [`seal_raw`] under another associated-data prefix (another kind of collection; `user_sync::seal`).
97pub fn seal_raw_with(prefix: &str, key: &Key, at: &Place<'_>, plain: &[u8]) -> Result<Vec<u8>, String> {
98    let aad = at.aad_with(prefix)?;
99    let mut nonce = [0u8; NONCE_LEN];
100    SystemRandom::new().fill(&mut nonce).map_err(|_| "the system's random source failed".to_string())?;
101    let mut buf = Zeroizing::new(plain.to_vec());
102    aead_key(key).seal_in_place_append_tag(Nonce::assume_unique_for_key(nonce), Aad::from(aad), &mut *buf).map_err(|_| "sealing a record failed".to_string())?;
103    let mut out = Vec::with_capacity(1 + NONCE_LEN + buf.len());
104    out.push(FORMAT_V1);
105    out.extend_from_slice(&nonce);
106    out.extend_from_slice(&buf);
107    if out.len() > MAX_SEALED {
108        return Err(format!("a synced record is at most {} MiB sealed", MAX_SEALED / (1024 * 1024)));
109    }
110    Ok(out)
111}
112
113/// Opens what [`seal_raw`] sealed for `at`. Fails, with one sentence for every cause, on any change to the record, on a
114/// record sealed for another Vault, record, version or epoch, and on another key. What it returns is wiped when dropped.
115pub fn open_raw(key: &Key, at: &Place<'_>, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, String> {
116    open_raw_with(AAD_PREFIX, key, at, sealed)
117}
118
119/// [`open_raw`] under another associated-data prefix.
120pub fn open_raw_with(prefix: &str, key: &Key, at: &Place<'_>, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, String> {
121    if sealed.len() < 1 + NONCE_LEN || sealed.len() > MAX_SEALED || sealed[0] != FORMAT_V1 {
122        return Err(CANT_OPEN.into());
123    }
124    let aad = at.aad_with(prefix)?;
125    let nonce = Nonce::try_assume_unique_for_key(&sealed[1..1 + NONCE_LEN]).map_err(|_| CANT_OPEN.to_string())?;
126    let mut buf = Zeroizing::new(sealed[1 + NONCE_LEN..].to_vec());
127    let plain = aead_key(key).open_in_place(nonce, Aad::from(aad), &mut *buf).map_err(|_| CANT_OPEN.to_string())?;
128    Ok(Zeroizing::new(plain.to_vec()))
129}
130
131/// [`seal_raw`] for a body: its JSON, sealed.
132pub fn seal_record<T: Serialize>(key: &Key, at: &Place<'_>, body: &T) -> Result<Vec<u8>, String> {
133    let json = Zeroizing::new(serde_json::to_vec(body).map_err(|e| e.to_string())?);
134    seal_raw(key, at, &json)
135}
136
137/// [`open_raw`] for a body. The body's own `Drop` wipes what it holds.
138pub fn open_record<T: DeserializeOwned>(key: &Key, at: &Place<'_>, sealed: &[u8]) -> Result<T, String> {
139    let plain = open_raw(key, at, sealed)?;
140    serde_json::from_slice(&plain).map_err(|_| CANT_OPEN.to_string())
141}
142
143/// A tombstone sealed for `at`: it holds nothing, so no value and no label can live on in it, but the seal still
144/// vouches for its place, its version and its base, so a relay can neither forge a delete nor change what it follows.
145pub fn seal_tombstone(key: &Key, at: &Place<'_>) -> Result<Vec<u8>, String> {
146    seal_raw(key, at, &[])
147}
148
149/// Opens a tombstone sealed by [`seal_tombstone`]. A record that holds anything is not a tombstone and is refused.
150pub fn open_tombstone(key: &Key, at: &Place<'_>, sealed: &[u8]) -> Result<(), String> {
151    if open_raw(key, at, sealed)?.is_empty() {
152        Ok(())
153    } else {
154        Err(CANT_OPEN.into())
155    }
156}
157
158/// Seals again a record under a new key and epoch, for the background pass that follows a member's removal: the new
159/// key is sealed to the members who remain, and every record is opened with the old key at the old place and sealed
160/// with the new at the new one. The version is the record's own and does not change.
161pub fn reseal(old: &Key, from: &Place<'_>, new: &Key, to: &Place<'_>, sealed: &[u8]) -> Result<Vec<u8>, String> {
162    let plain = open_raw(old, from, sealed)?;
163    seal_raw(new, to, &plain)
164}
165
166/// A sealed record in pieces of at most [`MAX_CHUNK`], in order.
167pub fn split(sealed: &[u8]) -> Vec<Vec<u8>> {
168    sealed.chunks(MAX_CHUNK).map(<[u8]>::to_vec).collect()
169}
170
171/// The sealed record back from its pieces. A piece over [`MAX_CHUNK`], a short piece before the last, and a total over
172/// [`MAX_SEALED`] are refused: a peer that sends them is not sending what [`split`] makes.
173pub fn join(chunks: &[Vec<u8>]) -> Result<Vec<u8>, String> {
174    let last = chunks.len().saturating_sub(1);
175    let odd = chunks.iter().enumerate().any(|(i, c)| c.is_empty() || c.len() > MAX_CHUNK || (i < last && c.len() != MAX_CHUNK));
176    if chunks.is_empty() || odd {
177        return Err("the pieces of a synced record are not the sizes a record is split into".into());
178    }
179    let total: usize = chunks.iter().map(Vec::len).sum();
180    if total > MAX_SEALED {
181        return Err(format!("a synced record is at most {} MiB sealed", MAX_SEALED / (1024 * 1024)));
182    }
183    Ok(chunks.concat())
184}
185
186#[cfg(test)]
187#[path = "sync_seal_tests.rs"]
188mod tests;