Skip to main content

agentmux_srv_core/backend/agent_move/
seal.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sealed stream of a move (SPEC_MOVE_AN_AGENT_TO_ANOTHER_COMPUTER section 6.3): an agent archive cut into 256 KiB
5//! chunks, each one encrypted and authenticated, under one content key that is made for one move attempt and sealed to
6//! the destination's key with the same construction as a cloud file's key (`jekt_seal`, one implementation).
7//!
8//! **What a chunk is bound to.** Its associated data names the move, the attempt, the manifest hash, both installs, the
9//! chunk's index, the chunk count and whether it is the last one. A chunk therefore opens only in its own move, at its
10//! own place, in a stream of its own length: a chunk replayed into another move or attempt, moved to another index,
11//! dropped from the end (a shorter stream) or spliced from a move of the same agent fails to open.
12//!
13//! **One key, one content.** The nonce is the chunk index, so a key may seal only one content at each index. [`Sealer`]
14//! remembers a hash of what it sealed at each index and refuses a different content there; the same content seals to the
15//! same bytes (a resume re-sends identical chunks). A new attempt starts a new key.
16
17use std::collections::HashMap;
18
19use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM, NONCE_LEN};
20use ring::rand::{SecureRandom, SystemRandom};
21use zeroize::Zeroizing;
22
23use crate::backend::agent_archive::manifest::CHUNK_BYTES;
24use crate::backend::jekt_seal::{self, Recipient};
25use crate::backend::memory::record::sha256_hex;
26
27/// Domain of a move chunk's associated data.
28const CHUNK_DOMAIN: &str = "amx-agent-move-chunk-v1";
29const FIELD_SEP: char = '\u{1}';
30const TAG_LEN: usize = 16;
31
32/// Why a chunk or a key did not seal or open.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum SealError {
35    /// The binding has an empty field, one with a separator in it, or a chunk count of zero.
36    BadBinding(&'static str),
37    /// The index is not in `0..total`.
38    IndexOutOfRange { index: u64, total: u64 },
39    /// A chunk that is not the last one is not exactly 256 KiB, or the last one is empty or longer than 256 KiB.
40    BadSize { index: u64, len: usize },
41    /// This key already sealed a different content at this index (it would repeat a nonce).
42    DifferentContent { index: u64 },
43    /// The chunk was altered, is for another move, attempt, place or stream length, or is not from this key.
44    Failed,
45}
46
47impl std::fmt::Display for SealError {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        match self {
50            Self::BadBinding(why) => write!(f, "the move's binding is not usable: {why}"),
51            Self::IndexOutOfRange { index, total } => write!(f, "chunk {index} is outside the {total} chunks of this move"),
52            Self::BadSize { index, len } => write!(f, "chunk {index} has {len} bytes, which its place in the stream does not allow"),
53            Self::DifferentContent { index } => write!(f, "chunk {index} was already sealed with different content under this key"),
54            Self::Failed => write!(f, "the chunk does not open"),
55        }
56    }
57}
58
59impl std::error::Error for SealError {}
60
61/// What every chunk of one move attempt is bound to.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct MoveBinding {
64    move_id: String,
65    attempt: u32,
66    manifest_hash: String,
67    source_install: String,
68    dest_install: String,
69    total: u64,
70}
71
72impl MoveBinding {
73    pub fn new(move_id: &str, attempt: u32, manifest_hash: &str, source_install: &str, dest_install: &str, total: u64) -> Result<Self, SealError> {
74        for (name, value) in [("move id", move_id), ("manifest hash", manifest_hash), ("source install", source_install), ("destination install", dest_install)] {
75            if value.is_empty() || value.contains(FIELD_SEP) {
76                return Err(SealError::BadBinding(name));
77            }
78        }
79        if total == 0 {
80            return Err(SealError::BadBinding("chunk count"));
81        }
82        Ok(Self { move_id: move_id.to_string(), attempt, manifest_hash: manifest_hash.to_string(), source_install: source_install.to_string(), dest_install: dest_install.to_string(), total })
83    }
84
85    pub fn total(&self) -> u64 {
86        self.total
87    }
88
89    pub fn attempt(&self) -> u32 {
90        self.attempt
91    }
92
93    /// The associated data of chunk `index`.
94    fn aad(&self, index: u64) -> Vec<u8> {
95        let last = u8::from(index + 1 == self.total);
96        format!(
97            "{CHUNK_DOMAIN}{s}{}{s}{}{s}{}{s}{}{s}{}{s}{index}{s}{}{s}{last}",
98            self.move_id,
99            self.attempt,
100            self.manifest_hash,
101            self.source_install,
102            self.dest_install,
103            self.total,
104            s = FIELD_SEP,
105        )
106        .into_bytes()
107    }
108
109    /// The name the content key is sealed under: the move and the attempt.
110    fn key_context(&self) -> String {
111        format!("move:{}:{}", self.move_id, self.attempt)
112    }
113
114    fn check_place(&self, index: u64, len: usize) -> Result<(), SealError> {
115        if index >= self.total {
116            return Err(SealError::IndexOutOfRange { index, total: self.total });
117        }
118        let chunk = CHUNK_BYTES as usize;
119        let ok = if index + 1 == self.total { (1..=chunk).contains(&len) } else { len == chunk };
120        if ok {
121            Ok(())
122        } else {
123            Err(SealError::BadSize { index, len })
124        }
125    }
126}
127
128/// The key of one move attempt: random, 256 bits, zeroed when dropped.
129pub struct ContentKey(Zeroizing<[u8; 32]>);
130
131impl ContentKey {
132    pub fn generate() -> Result<Self, SealError> {
133        let mut key = Zeroizing::new([0u8; 32]);
134        SystemRandom::new().fill(key.as_mut()).map_err(|_| SealError::Failed)?;
135        Ok(Self(key))
136    }
137
138    pub fn from_bytes(bytes: [u8; 32]) -> Self {
139        Self(Zeroizing::new(bytes))
140    }
141
142    /// This key sealed to the destination's key, for this move attempt.
143    pub fn seal_to(&self, binding: &MoveBinding, to: &Recipient) -> Result<String, SealError> {
144        jekt_seal::wrap(&self.0, to, &binding.manifest_hash, &binding.key_context()).ok_or(SealError::Failed)
145    }
146
147    /// The key `sealed` holds, opened with the destination's install key (`public` and `seed`).
148    pub fn open_sealed(sealed: &str, binding: &MoveBinding, public: &[u8; 32], seed: &[u8; 32]) -> Result<Self, SealError> {
149        jekt_seal::unwrap(sealed, public, seed, &binding.manifest_hash, &binding.key_context()).map(Self::from_bytes).map_err(|_| SealError::Failed)
150    }
151
152    fn aead(&self) -> Result<LessSafeKey, SealError> {
153        UnboundKey::new(&AES_256_GCM, self.0.as_ref()).map(LessSafeKey::new).map_err(|_| SealError::Failed)
154    }
155}
156
157/// Where to seal a move's key: the destination's X25519 box key (from its signed preflight answer, which the caller has
158/// checked against the pinned install key) and the fingerprint of the install key it came from.
159pub fn recipient(install_public: &[u8; 32], box_key: [u8; 32]) -> Recipient {
160    Recipient { key: box_key, key_fp: agentmux_common::jekt_sign::wan_key_fingerprint(install_public) }
161}
162
163fn nonce(index: u64) -> Nonce {
164    let mut bytes = [0u8; NONCE_LEN];
165    bytes[NONCE_LEN - 8..].copy_from_slice(&index.to_be_bytes());
166    Nonce::assume_unique_for_key(bytes)
167}
168
169/// Seals the chunks of one move attempt; remembers what it sealed at each index.
170pub struct Sealer {
171    key: ContentKey,
172    binding: MoveBinding,
173    sealed: HashMap<u64, String>,
174}
175
176impl Sealer {
177    pub fn new(key: ContentKey, binding: MoveBinding) -> Self {
178        Self { key, binding, sealed: HashMap::new() }
179    }
180
181    pub fn binding(&self) -> &MoveBinding {
182        &self.binding
183    }
184
185    /// Chunk `index` as it travels: ciphertext and tag. The same plaintext at the same index gives the same bytes; a
186    /// different plaintext at an index this key has sealed is refused.
187    pub fn seal(&mut self, index: u64, plain: &[u8]) -> Result<Vec<u8>, SealError> {
188        self.binding.check_place(index, plain.len())?;
189        let digest = sha256_hex(plain);
190        if self.sealed.get(&index).is_some_and(|seen| *seen != digest) {
191            return Err(SealError::DifferentContent { index });
192        }
193        let mut out = plain.to_vec();
194        self.key.aead()?.seal_in_place_append_tag(nonce(index), Aad::from(self.binding.aad(index)), &mut out).map_err(|_| SealError::Failed)?;
195        self.sealed.insert(index, digest);
196        Ok(out)
197    }
198}
199
200/// Opens the chunks of one move attempt.
201pub struct Opener {
202    key: ContentKey,
203    binding: MoveBinding,
204}
205
206impl Opener {
207    pub fn new(key: ContentKey, binding: MoveBinding) -> Self {
208        Self { key, binding }
209    }
210
211    /// Chunk `index`'s plaintext, when `sealed` is exactly what [`Sealer::seal`] made for this place in this move.
212    pub fn open(&self, index: u64, sealed: &[u8]) -> Result<Vec<u8>, SealError> {
213        if index >= self.binding.total {
214            return Err(SealError::IndexOutOfRange { index, total: self.binding.total });
215        }
216        if sealed.len() < TAG_LEN {
217            return Err(SealError::Failed);
218        }
219        self.binding.check_place(index, sealed.len() - TAG_LEN)?;
220        let mut buf = sealed.to_vec();
221        let plain_len = self.key.aead()?.open_in_place(nonce(index), Aad::from(self.binding.aad(index)), &mut buf).map_err(|_| SealError::Failed)?.len();
222        buf.truncate(plain_len);
223        Ok(buf)
224    }
225}
226
227#[cfg(test)]
228#[path = "seal_tests.rs"]
229mod tests;