Skip to main content

agentmux_srv_core/backend/user_sync/
seal.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! Sealing a record's body (SPEC_USER_DATA_SYNC_LAYER ยง3.1). A body leaves a machine sealed with the collection's key
5//! at the record's key epoch: ChaCha20-Poly1305, with the collection id, record id, version, base version and key
6//! epoch as associated data, so a body cannot be replayed under another record, version, base or epoch, nor moved into
7//! another collection. The seal is the Vault's (`vault::sync_seal`) under this module's associated-data prefix, so
8//! there is one implementation. The layer treats a body as opaque bytes: the caller seals before a record is written
9//! ([`sealer`] with `log::append_local_with`) and opens after one is applied ([`open`]).
10//!
11//! The ids in the associated data are letters, digits and `._-` only (at most 128 characters): a collection or record
12//! id with anything else is refused, so no two places can have the same associated data.
13
14use std::collections::BTreeMap;
15
16use ring::rand::{SecureRandom, SystemRandom};
17use zeroize::Zeroizing;
18
19use super::hlc::Version;
20use super::log::SealAt;
21use super::record::Header;
22use crate::backend::vault::seal::Key;
23use crate::backend::vault::sync_seal::{self, Place};
24
25/// The associated data's first part for a Kanban board's records.
26pub const AAD_PREFIX: &str = "agentmux-sync-v1";
27
28/// A new random collection key, made on the machine that founds a collection or rotates it.
29pub fn generate_key() -> Option<Key> {
30    let mut bytes = [0u8; 32];
31    SystemRandom::new().fill(&mut bytes).ok()?;
32    Some(Zeroizing::new(bytes))
33}
34
35/// The keys a member holds for one collection, one per epoch it has been in, so it opens earlier records too.
36#[derive(Default)]
37pub struct KeyRing {
38    keys: BTreeMap<u32, Key>,
39}
40
41impl KeyRing {
42    pub fn new() -> KeyRing {
43        KeyRing::default()
44    }
45
46    pub fn insert(&mut self, epoch: u32, key: Key) {
47        self.keys.insert(epoch, key);
48    }
49
50    pub fn get(&self, epoch: u32) -> Option<&Key> {
51        self.keys.get(&epoch)
52    }
53
54    /// The newest epoch this ring has a key for.
55    pub fn latest(&self) -> Option<u32> {
56        self.keys.keys().next_back().copied()
57    }
58}
59
60/// Why a body would not open.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum OpenError {
63    /// The ring has no key for the record's epoch.
64    NoKey,
65    /// Malformed, altered, or sealed for another place (collection, record, version, base or epoch); or an id the
66    /// seal does not take.
67    Failed(String),
68}
69
70fn old_version(v: &Version) -> sync_seal::Version {
71    sync_seal::Version::new(v.wall_ms, v.counter, &v.machine)
72}
73
74/// `body` sealed for the place `at` names, under the key the ring holds for that epoch.
75pub fn seal(ring: &KeyRing, at: &SealAt, body: &[u8]) -> Result<Vec<u8>, String> {
76    let key = ring.get(at.epoch).ok_or_else(|| format!("no key for epoch {}", at.epoch))?;
77    let (version, base) = (old_version(&at.version), at.base.as_ref().map(old_version));
78    let place = Place { vault: &at.collection, record: &at.record, version: &version, base: base.as_ref(), epoch: at.epoch };
79    sync_seal::seal_raw_with(AAD_PREFIX, key, &place, body)
80}
81
82/// The body of a record, opened with the key its header's epoch names. The header must be the verified one: its
83/// fields are the associated data, so a body altered, or moved to another record, version, base or epoch, fails.
84pub fn open(ring: &KeyRing, header: &Header, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, OpenError> {
85    let key = ring.get(header.epoch).ok_or(OpenError::NoKey)?;
86    let (version, base) = (old_version(&header.version), header.base.as_ref().map(old_version));
87    let place = Place { vault: &header.collection, record: &header.record, version: &version, base: base.as_ref(), epoch: header.epoch };
88    sync_seal::open_raw_with(AAD_PREFIX, key, &place, sealed).map_err(OpenError::Failed)
89}
90
91/// For `log::append_local_with`: seals `body` under the ring's key at the epoch the record will carry.
92pub fn sealer<'a>(ring: &'a KeyRing, body: &'a [u8]) -> impl FnOnce(&SealAt) -> Result<Vec<u8>, String> + 'a {
93    move |at| seal(ring, at, body)
94}