agentmux_srv_core/backend/agent_move/
seal.rs1use 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
27const CHUNK_DOMAIN: &str = "amx-agent-move-chunk-v1";
29const FIELD_SEP: char = '\u{1}';
30const TAG_LEN: usize = 16;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum SealError {
35 BadBinding(&'static str),
37 IndexOutOfRange { index: u64, total: u64 },
39 BadSize { index: u64, len: usize },
41 DifferentContent { index: u64 },
43 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#[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 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 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
128pub 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 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 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
157pub 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
169pub 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 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
200pub 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 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;