agentmux_srv_core/backend/vault/
sync_seal.rs1use 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
25pub const AAD_PREFIX: &str = "agentmux-vault-sync-v1";
27const FORMAT_V1: u8 = 1;
29pub const MAX_CHUNK: usize = 48 * 1024;
32pub const MAX_SEALED: usize = 8 * 1024 * 1024;
35
36pub 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 pub fn text(&self) -> String {
47 format!("{}.{}.{}", self.wall_ms, self.counter, self.machine)
48 }
49}
50
51#[derive(Debug, Clone, Copy)]
54pub struct Place<'a> {
55 pub vault: &'a str,
56 pub record: &'a str,
57 pub version: &'a Version,
58 pub base: Option<&'a Version>,
62 pub epoch: u32,
63}
64
65fn 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 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
91pub fn seal_raw(key: &Key, at: &Place<'_>, plain: &[u8]) -> Result<Vec<u8>, String> {
93 seal_raw_with(AAD_PREFIX, key, at, plain)
94}
95
96pub 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
113pub 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
119pub 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
131pub 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
137pub 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
143pub fn seal_tombstone(key: &Key, at: &Place<'_>) -> Result<Vec<u8>, String> {
146 seal_raw(key, at, &[])
147}
148
149pub 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
158pub 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
166pub fn split(sealed: &[u8]) -> Vec<Vec<u8>> {
168 sealed.chunks(MAX_CHUNK).map(<[u8]>::to_vec).collect()
169}
170
171pub 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;