Skip to main content

agentmux_srv_core/backend/
jekt_seal.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A cloud file's key, sealed to the install that receives it
5//! (`docs/specs/SPEC_JEKT_FILE_TRANSFER_2026_10_05.md` §7, Phase 5).
6//!
7//! Without sealing, a cloud manifest carries each file's AES key as plain
8//! base64, so the relay, which stores the manifest with the message, could
9//! read every file. Here each key is sealed to the receiving agent on the
10//! install that runs it:
11//!
12//! - **The key.** An X25519 key derived from the agent's WAN seed with HKDF,
13//!   so it is not the signing key itself (the curve library's advice), and
14//!   nothing new is stored: the same seed always gives the same key.
15//! - **The offer.** The install signs that key with the agent's WAN key and
16//!   offers it in the agent's lease ([`offer`]). The relay only passes it on.
17//! - **The check.** The sender fetches the agent's record from the account's
18//!   key directory, whose chain the install's instance key anchors, and
19//!   checks the offer's signature against it ([`check_offer`]). The relay
20//!   can't substitute a key without that install's instance key.
21//! - **The seal.** Per file: an ephemeral X25519 key, HKDF-SHA256 over the
22//!   shared secret, both public keys, the file's hash and its blob id, and
23//!   AES-256-GCM over the file key ([`wrap`], [`unwrap`]).
24//!
25//! What stays readable: an older receiver's lease offers no key, and its
26//! files go as before. A cloud that actively adds an install to the
27//! account's directory could be offered files, the residual WAN verification
28//! already accepts (`SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md` §2.6).
29
30use agentmux_common::jekt_files::SEALED_KEY_PREFIX;
31use agentmux_common::jekt_sign::{self, WanKeyRecord};
32use base64::Engine;
33use curve25519_dalek::montgomery::MontgomeryPoint;
34use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM, NONCE_LEN};
35use ring::hkdf;
36use ring::rand::{SecureRandom, SystemRandom};
37
38/// Salt for deriving the sealing key from a WAN seed, and the leading field
39/// of the offer's signed material.
40const SEAL_KEY_DOMAIN: &str = "amx-jekt-files-seal-key-v1";
41/// Salt for each file's wrapping key.
42const WRAP_DOMAIN: &str = "amx-jekt-files-seal-v1";
43const FIELD_SEP: char = '\u{1}';
44const TAG_LEN: usize = 16;
45/// Ephemeral public key, wrapped key, tag.
46const SEALED_LEN: usize = 32 + 32 + TAG_LEN;
47
48const STD: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
49const URL: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE_NO_PAD;
50
51/// The key an install wants one agent's file keys sealed to, as its lease
52/// carries it. `instance` and `key_fp` find the agent's record in the key
53/// directory; `key` is the X25519 public key and `sig` the agent's WAN key
54/// over it, both standard base64.
55#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
56pub struct SealOffer {
57    pub instance: String,
58    pub key_fp: String,
59    pub key: String,
60    pub sig: String,
61}
62
63/// Where a sender seals to: the receiver's X25519 key, checked, and the
64/// fingerprint of the WAN key it came from.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct Recipient {
67    pub key: [u8; 32],
68    pub key_fp: String,
69}
70
71struct Len32;
72
73impl hkdf::KeyType for Len32 {
74    fn len(&self) -> usize {
75        32
76    }
77}
78
79/// The X25519 secret for an agent's WAN seed.
80fn seal_secret(wan_seed: &[u8; 32]) -> Option<[u8; 32]> {
81    let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, SEAL_KEY_DOMAIN.as_bytes()).extract(wan_seed);
82    let mut out = [0u8; 32];
83    prk.expand(&[b"x25519"], Len32).ok()?.fill(&mut out).ok()?;
84    Some(out)
85}
86
87/// The X25519 public key an install's WAN seed seals to: the key its offers carry, and the box key it lists in a
88/// collection's membership chain.
89pub fn box_public(wan_seed: &[u8; 32]) -> Option<[u8; 32]> {
90    Some(MontgomeryPoint::mul_base_clamped(seal_secret(wan_seed)?).to_bytes())
91}
92
93fn offer_material(agent_id: &str, instance: &str, key_fp: &str, key_b64: &str) -> String {
94    let agent_id = agent_id.to_ascii_lowercase();
95    format!("{SEAL_KEY_DOMAIN}{FIELD_SEP}{agent_id}{FIELD_SEP}{instance}{FIELD_SEP}{key_fp}{FIELD_SEP}{key_b64}")
96}
97
98/// This install's offer for `agent_id`, whose WAN keypair is `wan_public`
99/// and `wan_seed`; `None` for a malformed key.
100pub fn offer(instance_id: &str, agent_id: &str, wan_public: &[u8; 32], wan_seed: &[u8; 32]) -> Option<SealOffer> {
101    let signing = ed25519_dalek::SigningKey::from_bytes(wan_seed);
102    if signing.verifying_key().to_bytes() != *wan_public {
103        return None;
104    }
105    let key = STD.encode(MontgomeryPoint::mul_base_clamped(seal_secret(wan_seed)?).to_bytes());
106    let key_fp = jekt_sign::wan_key_fingerprint(wan_public);
107    let material = offer_material(agent_id, instance_id, &key_fp, &key);
108    let sig = STD.encode(ed25519_dalek::Signer::sign(&signing, material.as_bytes()).to_bytes());
109    Some(SealOffer { instance: instance_id.to_string(), key_fp, key, sig })
110}
111
112/// The key `offer` names, if `record` (the agent's entry in the key
113/// directory) proves it: the record's chain holds, it is `agent_id`'s record
114/// for the offer's install and key, and that key signed the offer. `Err`
115/// says why not, to follow the agent's name.
116pub fn check_offer(offer: &SealOffer, record: &WanKeyRecord, agent_id: &str) -> Result<Recipient, &'static str> {
117    let wan_public = record.check_chain().ok_or("has a key record whose certificate doesn't check out")?;
118    if record.instance_id != offer.instance || record.key_fp != offer.key_fp || !record.agent_id.eq_ignore_ascii_case(agent_id) {
119        return Err("offered a sealing key for a different key record");
120    }
121    let verifying = ed25519_dalek::VerifyingKey::from_bytes(&wan_public).map_err(|_| "has a malformed WAN key")?;
122    let sig: [u8; 64] = STD
123        .decode(&offer.sig)
124        .ok()
125        .and_then(|s| s.try_into().ok())
126        .ok_or("offered a malformed sealing key signature")?;
127    let material = offer_material(agent_id, &offer.instance, &offer.key_fp, &offer.key);
128    verifying
129        .verify_strict(material.as_bytes(), &ed25519_dalek::Signature::from_bytes(&sig))
130        .map_err(|_| "offered a sealing key its WAN key didn't sign")?;
131    let key: [u8; 32] = STD
132        .decode(&offer.key)
133        .ok()
134        .and_then(|k| k.try_into().ok())
135        .ok_or("offered a malformed sealing key")?;
136    Ok(Recipient { key, key_fp: offer.key_fp.clone() })
137}
138
139/// The AES key that wraps one file's key: HKDF over the shared secret and
140/// everything the seal is for.
141fn wrapping_key(shared: &[u8; 32], ephemeral: &[u8; 32], recipient: &[u8; 32], sha256: &str, blob_id: &str) -> Option<LessSafeKey> {
142    let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, WRAP_DOMAIN.as_bytes()).extract(shared);
143    let sep = [FIELD_SEP as u8];
144    let info: [&[u8]; 7] = [ephemeral, &sep, recipient, &sep, sha256.as_bytes(), &sep, blob_id.as_bytes()];
145    let okm = prk.expand(&info, &AES_256_GCM).ok()?;
146    Some(LessSafeKey::new(UnboundKey::from(okm)))
147}
148
149/// X25519, refusing the all-zero result a low-order public key gives.
150fn agree(secret: [u8; 32], public: &[u8; 32]) -> Option<[u8; 32]> {
151    let shared = MontgomeryPoint(*public).mul_clamped(secret).to_bytes();
152    (shared != [0u8; 32]).then_some(shared)
153}
154
155/// `file_key` sealed to `to`, for the file `sha256` stored as `blob_id`.
156pub fn wrap(file_key: &[u8; 32], to: &Recipient, sha256: &str, blob_id: &str) -> Option<String> {
157    let mut secret = [0u8; 32];
158    SystemRandom::new().fill(&mut secret).ok()?;
159    let ephemeral = MontgomeryPoint::mul_base_clamped(secret).to_bytes();
160    let shared = agree(secret, &to.key)?;
161    // Each wrapping key comes from a fresh ephemeral key, so it seals once:
162    // a fixed nonce is safe.
163    let mut sealed = file_key.to_vec();
164    wrapping_key(&shared, &ephemeral, &to.key, sha256, blob_id)?
165        .seal_in_place_append_tag(Nonce::assume_unique_for_key([0u8; NONCE_LEN]), Aad::empty(), &mut sealed)
166        .ok()?;
167    let mut body = ephemeral.to_vec();
168    body.extend_from_slice(&sealed);
169    Some(format!("{SEALED_KEY_PREFIX}{}.{}", to.key_fp, URL.encode(body)))
170}
171
172/// Why a sealed key didn't open.
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub enum UnwrapError {
175    /// Sealed to another key: another install's copy of this agent, after
176    /// its lease moved.
177    OtherKey,
178    /// Malformed, altered, or for another file.
179    Failed,
180}
181
182/// The file key `sealed` holds, opened with the agent's WAN seed.
183pub fn unwrap(sealed: &str, wan_public: &[u8; 32], wan_seed: &[u8; 32], sha256: &str, blob_id: &str) -> Result<[u8; 32], UnwrapError> {
184    let (key_fp, body) = sealed
185        .strip_prefix(SEALED_KEY_PREFIX)
186        .and_then(|rest| rest.split_once('.'))
187        .ok_or(UnwrapError::Failed)?;
188    if key_fp != jekt_sign::wan_key_fingerprint(wan_public) {
189        return Err(UnwrapError::OtherKey);
190    }
191    let body = URL.decode(body).map_err(|_| UnwrapError::Failed)?;
192    if body.len() != SEALED_LEN {
193        return Err(UnwrapError::Failed);
194    }
195    let (ephemeral, wrapped) = body.split_at(32);
196    let ephemeral: [u8; 32] = ephemeral.try_into().map_err(|_| UnwrapError::Failed)?;
197    let secret = seal_secret(wan_seed).ok_or(UnwrapError::Failed)?;
198    let own = MontgomeryPoint::mul_base_clamped(secret).to_bytes();
199    let shared = agree(secret, &ephemeral).ok_or(UnwrapError::Failed)?;
200    let mut buf = wrapped.to_vec();
201    let key = wrapping_key(&shared, &ephemeral, &own, sha256, blob_id)
202        .ok_or(UnwrapError::Failed)?
203        .open_in_place(Nonce::assume_unique_for_key([0u8; NONCE_LEN]), Aad::empty(), &mut buf)
204        .map_err(|_| UnwrapError::Failed)?;
205    key.try_into().map_err(|_| UnwrapError::Failed)
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    const SHA: &str = "2c17a5b7c1f2e3d4c5b6a79881726354a5b6c7d8e9f0a1b2c3d4e5f60718293a";
213    const BLOB: &str = "blob-0123abcd-0000-4000-8000-0123456789ab";
214
215    fn agent(seed: u8) -> ([u8; 32], [u8; 32]) {
216        jekt_sign::generate_wan_keypair([seed; 32])
217    }
218
219    /// The directory record an install with instance seed `instance` would
220    /// publish for `agent_id`'s key.
221    fn record(instance: u8, agent_id: &str, wan_public: &[u8; 32]) -> WanKeyRecord {
222        WanKeyRecord::certify(&[instance; 32], agent_id, "stable", wan_public, "starpower", 1_792_000_000).unwrap()
223    }
224
225    fn recipient(seed: u8) -> (Recipient, [u8; 32], [u8; 32]) {
226        let (public, private) = agent(seed);
227        let rec = record(9, "jf-mac", &public);
228        let offered = offer(&rec.instance_id, "jf-mac", &public, &private).unwrap();
229        (check_offer(&offered, &rec, "JF-Mac").unwrap(), public, private)
230    }
231
232    #[test]
233    fn a_sealed_key_opens_only_for_its_agent_and_its_file() {
234        let (to, public, private) = recipient(1);
235        let file_key = [7u8; 32];
236        let sealed = wrap(&file_key, &to, SHA, BLOB).unwrap();
237        assert!(agentmux_common::jekt_files::is_sealed_key(&sealed), "{sealed}");
238        assert_eq!(unwrap(&sealed, &public, &private, SHA, BLOB), Ok(file_key));
239
240        let (other_public, other_private) = agent(2);
241        assert_eq!(unwrap(&sealed, &other_public, &other_private, SHA, BLOB), Err(UnwrapError::OtherKey));
242        // The right fingerprint but not the key behind it.
243        assert_eq!(unwrap(&sealed, &public, &other_private, SHA, BLOB), Err(UnwrapError::Failed));
244        assert_eq!(unwrap(&sealed, &public, &private, &SHA.replace('2', "3"), BLOB), Err(UnwrapError::Failed), "another file");
245        assert_eq!(unwrap(&sealed, &public, &private, SHA, &BLOB.replace('1', "2")), Err(UnwrapError::Failed), "another blob");
246        let mut tampered = sealed.clone().into_bytes();
247        let at = tampered.len() - 5;
248        tampered[at] = if tampered[at] == b'A' { b'B' } else { b'A' };
249        assert_eq!(unwrap(std::str::from_utf8(&tampered).unwrap(), &public, &private, SHA, BLOB), Err(UnwrapError::Failed));
250        assert_eq!(unwrap("A".repeat(43).as_str(), &public, &private, SHA, BLOB), Err(UnwrapError::Failed));
251    }
252
253    #[test]
254    fn every_seal_is_fresh() {
255        let (to, ..) = recipient(1);
256        assert_ne!(wrap(&[7; 32], &to, SHA, BLOB), wrap(&[7; 32], &to, SHA, BLOB));
257    }
258
259    #[test]
260    fn the_sealing_key_is_not_the_signing_key() {
261        let (to, public, _) = recipient(1);
262        let signing_as_x25519 = ed25519_dalek::VerifyingKey::from_bytes(&public).unwrap().to_montgomery().to_bytes();
263        assert_ne!(to.key, signing_as_x25519);
264        assert_eq!(recipient(1).0, to, "the same seed always gives the same key");
265    }
266
267    #[test]
268    fn an_offer_is_taken_only_with_the_record_that_proves_it() {
269        let (public, private) = agent(1);
270        let rec = record(9, "jf-mac", &public);
271        let offered = offer(&rec.instance_id, "jf-mac", &public, &private).unwrap();
272        assert!(check_offer(&offered, &rec, "jf-mac").is_ok());
273
274        // A relay swapping in its own key: signed by a key the record doesn't name.
275        let (_, relay_private) = agent(3);
276        let (relay_public, _) = agent(3);
277        let forged = offer(&rec.instance_id, "jf-mac", &relay_public, &relay_private).unwrap();
278        let forged = SealOffer { key_fp: offered.key_fp.clone(), ..forged };
279        assert!(check_offer(&forged, &rec, "jf-mac").unwrap_err().contains("didn't sign"));
280        let swapped_key = SealOffer { key: forged.key.clone(), ..offered.clone() };
281        assert!(check_offer(&swapped_key, &rec, "jf-mac").unwrap_err().contains("didn't sign"));
282
283        // Another agent's, another install's, or a broken record.
284        assert!(check_offer(&offered, &rec, "lark").is_err());
285        let other_install = record(8, "jf-mac", &public);
286        assert!(check_offer(&offered, &other_install, "jf-mac").unwrap_err().contains("different key record"));
287        let mut broken = rec.clone();
288        broken.host_hint = "elsewhere".into();
289        assert!(check_offer(&offered, &broken, "jf-mac").unwrap_err().contains("certificate"));
290
291        // An offer signed for one agent can't be replayed as another's.
292        let lark_rec = record(9, "lark", &public);
293        assert!(check_offer(&offered, &lark_rec, "lark").unwrap_err().contains("didn't sign"));
294    }
295
296    #[test]
297    fn an_offer_needs_a_matching_keypair() {
298        let (public, _) = agent(1);
299        let (_, other_private) = agent(2);
300        assert_eq!(offer("i", "jf-mac", &public, &other_private), None);
301    }
302
303    #[test]
304    fn a_low_order_key_is_refused() {
305        let to = Recipient { key: [0u8; 32], key_fp: "x".repeat(43) };
306        assert_eq!(wrap(&[7; 32], &to, SHA, BLOB), None);
307    }
308}