Skip to main content

acl_core/
sealed.rs

1//! Sealed envelopes (spec §10.1): end-to-end confidentiality through relays.
2//!
3//! `seal` takes an inner envelope and produces an outer envelope whose body
4//! is `Body::Sealed`: the inner envelope's msgpack encoding, encrypted with
5//! ChaCha20-Poly1305 under a key derived via X25519 ECDH(sender_secret,
6//! recipient_public) + HKDF-ish salt. `open` reverses it.
7
8use chacha20poly1305::aead::{Aead, KeyInit, Payload};
9use chacha20poly1305::{ChaCha20Poly1305, Nonce};
10use hkdf::Hkdf;
11use rand::Rng;
12use sha2::Sha256;
13use x25519_dalek::{PublicKey, StaticSecret};
14
15use crate::{AclError, Body, Envelope, Performative, Aid};
16
17/// Seal `inner` so only the holder of `recipient_secret`'s counterpart
18/// public key can open it. The outer envelope keeps routing metadata
19/// (from/to/performative=inform) but the payload is opaque in transit.
20pub fn seal(
21    inner: &Envelope,
22    sender_secret: &StaticSecret,
23    recipient_public: &PublicKey,
24) -> Result<Envelope, AclError> {
25    let shared = sender_secret.diffie_hellman(recipient_public);
26    let mut salt = [0u8; 12];
27    rand::rng().fill_bytes(&mut salt);
28
29    // §10.1 (v0.2): HKDF-SHA256 extraction and expansion — the raw shared
30    // secret is NEVER used directly as the symmetric key.
31    // Salt: the 12-byte random salt (domain-separated from the nonce use
32    // via the info label). Info: "acl-sealed-v1-key".
33    let hk = Hkdf::<Sha256>::new(Some(&salt), shared.as_bytes());
34    let mut key = [0u8; 32];
35    hk.expand(b"acl-sealed-v1-key", &mut key)
36        .expect("valid key length");
37    let cipher = ChaCha20Poly1305::new((&key).into());
38    let plaintext = inner.encode()?;
39    let ciphertext = cipher
40        .encrypt(
41            Nonce::from_slice(&salt),
42            Payload {
43                msg: &plaintext,
44                aad: b"acl-sealed-v1",
45            },
46        )
47        .map_err(|_| AclError::BadKey)?;
48
49    let mut env = Envelope::new(
50        inner.from.clone(),
51        inner.to.clone(),
52        Performative::Inform,
53        Body::Sealed {
54            sender_pub: PublicKey::from(sender_secret).to_bytes().to_vec(),
55            salt: salt.to_vec(),
56            ciphertext: ciphertext.into(),
57        },
58    );
59    env.msg_id = inner.msg_id.clone();
60    env.reply_with = inner.reply_with.clone();
61    Ok(env)
62}
63
64/// Open a sealed envelope. `recipient_secret` must pair with the sender
65/// public key embedded in the Sealed body.
66pub fn open(
67    sealed: &Envelope,
68    recipient_secret: &StaticSecret,
69) -> Result<Envelope, AclError> {
70    let (sender_pub, salt, ciphertext) = match &sealed.body {
71        Body::Sealed { sender_pub, salt, ciphertext } => (sender_pub, salt, ciphertext),
72        _ => return Err(AclError::BadKey),
73    };
74    let sender_pk = PublicKey::from(
75        <[u8; 32]>::try_from(sender_pub.as_slice()).map_err(|_| AclError::BadKey)?,
76    );
77    let shared = recipient_secret.diffie_hellman(&sender_pk);
78    // §10.1 (v0.2): mirror the sender's HKDF derivation using the salt
79    // embedded in the sealed body.
80    let hk = Hkdf::<Sha256>::new(Some(salt), shared.as_bytes());
81    let mut key = [0u8; 32];
82    hk.expand(b"acl-sealed-v1-key", &mut key)
83        .expect("valid key length");
84    let cipher = ChaCha20Poly1305::new((&key).into());
85    let plaintext = cipher
86        .decrypt(
87            Nonce::from_slice(salt),
88            Payload {
89                msg: ciphertext,
90                aad: b"acl-sealed-v1",
91            },
92        )
93        .map_err(|_| AclError::BadKey)?;
94    Envelope::decode(&plaintext)
95}
96
97
98/// §10.2: Derive a session-specific symmetric key from a root secret.
99/// Used to derive ephemeral keys for specific message streams (e.g. per
100/// agent-pair, per task-id) without re-running the full ECDH handshake
101/// for every message (reduces CPU overhead and exposure).
102/// `root_secret` must be the 32-byte ECDH shared secret.
103/// `session_id` is an opaque string distinguishing the channel (e.g.
104/// "agent-a-to-b-task-123").
105pub fn derive_session_key(root_secret: &[u8], session_id: &str) -> [u8; 32] {
106    let hk = Hkdf::<Sha256>::new(None, root_secret);
107    let mut key = [0u8; 32];
108    // Info binds the derivation to the exact channel identity and purpose.
109    let info = format!("acl-session-v1-{}", session_id);
110    hk.expand(info.as_bytes(), &mut key)
111        .expect("valid key length");
112    key
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use crate::Aid;
119    use rand::Rng;
120
121    fn inner() -> Envelope {
122        Envelope::new(
123            Aid::new("did:example:a"),
124            Aid::new("did:example:b"),
125            Performative::Request,
126            Body::Task {
127                description: "secret task".into(),
128                input: serde_json::json!({"text": "classified"}),
129                deadline_ms: None,
130                priority: None,
131            },
132        )
133    }
134
135    fn random_secret() -> StaticSecret {
136        let mut b = [0u8; 32];
137        rand::rng().fill_bytes(&mut b);
138        StaticSecret::from(b)
139    }
140
141    #[test]
142    fn seal_open_roundtrip() {
143        let sender = random_secret();
144        let recipient = random_secret();
145        let recipient_pub = PublicKey::from(&recipient);
146        let task = inner();
147
148        let sealed = seal(&task, &sender, &recipient_pub).unwrap();
149        // sealed body must NOT leak the plaintext
150        match &sealed.body {
151            Body::Sealed { ciphertext, .. } => {
152                assert!(!serde_json::to_string(&ciphertext).unwrap().contains("classified"));
153            }
154            _ => panic!("expected Sealed"),
155        }
156        let opened = open(&sealed, &recipient).unwrap();
157        assert_eq!(opened.msg_id, task.msg_id);
158        match &opened.body {
159            Body::Task { input, .. } => assert_eq!(input["text"], "classified"),
160            _ => panic!("expected Task"),
161        }
162    }
163
164    #[test]
165    fn wrong_key_fails() {
166        let sender = random_secret();
167        let eavesdropper = random_secret();
168        let recipient_pub = PublicKey::from(&random_secret());
169        let sealed = seal(&inner(), &sender, &recipient_pub).unwrap();
170        assert!(open(&sealed, &eavesdropper).is_err());
171    }
172
173    #[test]
174    fn tampered_ciphertext_fails() {
175        let sender = random_secret();
176        let recipient = random_secret();
177        let mut sealed = seal(&inner(), &sender, &PublicKey::from(&recipient)).unwrap();
178        if let Body::Sealed { ciphertext, .. } = &mut sealed.body {
179            ciphertext[0] ^= 0xff;
180        }
181        assert!(open(&sealed, &recipient).is_err());
182    }
183
184    #[test]
185    fn session_key_derivation_is_deterministic_and_distinct() {
186        let secret = random_secret();
187        let shared = secret.diffie_hellman(&PublicKey::from(&random_secret()));
188        let root = shared.as_bytes();
189
190        let k1 = derive_session_key(root, "session-a");
191        let k2 = derive_session_key(root, "session-a");
192        let k3 = derive_session_key(root, "session-b");
193
194        // deterministic: same input -> same key
195        assert_eq!(k1, k2);
196        // distinct sessions -> distinct keys
197        assert_ne!(k1, k3);
198    }
199}