Skip to main content

agent_protocols/mail/
mod.rs

1//! Agent Mail 1.0: signed cards and letters, HPKE packets, and explicit local state.
2//!
3//! Relays never receive decryption keys. A verified letter is untrusted content,
4//! not authorization to execute a task. State helpers are in-memory models;
5//! applications must persist snapshots atomically before acknowledging delivery.
6//! Relay paths are fixed at `{route}/v1/mailboxes`.
7mod state;
8mod types;
9pub use state::*;
10pub use types::*;
11#[cfg(feature = "http-client")]
12mod client;
13#[cfg(feature = "http-client")]
14pub use client::MailClient;
15
16use crate::identity::{self, AgentId, AgentSigner, Envelope, Event};
17use crate::{Result, SdkError};
18use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
19use hpke::{
20    aead::ChaCha20Poly1305, kdf::HkdfSha256, kem::X25519HkdfSha256, Deserializable, Kem as _,
21    OpModeR, OpModeS, Serializable,
22};
23use serde::Serialize;
24use serde_json::{json, Value};
25use sha3::{Digest, Sha3_256};
26use std::{
27    collections::BTreeMap,
28    sync::{Mutex, OnceLock},
29};
30use zeroize::Zeroizing;
31
32pub const PROTOCOL: &str = "agent-mail/1.0";
33pub const MAX_TTL_MS: i64 = 30 * 86_400_000;
34pub const FUTURE_SKEW_MS: i64 = 300_000;
35pub const MAX_PACKET_BYTES: usize = 1_048_576;
36pub const SCHEMA_JSON: &str = include_str!("schema.json");
37/// HPKE `info`: the header, including `card_hash`, is bound as AAD.
38const INFO: &[u8] = PROTOCOL.as_bytes();
39type Kem = X25519HkdfSha256;
40type PrivateKey = <Kem as hpke::Kem>::PrivateKey;
41type PublicKey = <Kem as hpke::Kem>::PublicKey;
42
43pub(crate) fn fail(code: &'static str, message: impl Into<String>) -> SdkError {
44    SdkError::protocol(code, message)
45}
46pub fn canonical_bytes<T: Serialize>(value: &T) -> Result<Vec<u8>> {
47    serde_jcs::to_vec(value).map_err(|e| SdkError::CanonicalJson(e.to_string()))
48}
49pub fn hash_bytes(bytes: &[u8]) -> String {
50    URL_SAFE_NO_PAD.encode(Sha3_256::digest(bytes))
51}
52pub fn encode_bytes(bytes: &[u8]) -> String {
53    URL_SAFE_NO_PAD.encode(bytes)
54}
55pub fn decode_bytes(value: &str) -> Result<Vec<u8>> {
56    let bytes = URL_SAFE_NO_PAD
57        .decode(value)
58        .map_err(|_| fail("invalid_event", "noncanonical base64url"))?;
59    if URL_SAFE_NO_PAD.encode(&bytes) != value {
60        return Err(fail("invalid_event", "noncanonical base64url"));
61    }
62    Ok(bytes)
63}
64pub(crate) fn fixed_bytes(value: &str, size: usize) -> Result<Vec<u8>> {
65    let bytes = decode_bytes(value)?;
66    if bytes.len() != size {
67        return Err(fail("invalid_event", "invalid encoded byte length"));
68    }
69    Ok(bytes)
70}
71pub fn random_id() -> Result<String> {
72    let mut bytes = [0; 16];
73    getrandom::fill(&mut bytes).map_err(|e| SdkError::Random(e.to_string()))?;
74    Ok(encode_bytes(&bytes))
75}
76/// Parse `did:agent:<key>/mail/<mailbox_id>[?route=<origin>...]` (Mail Section 3.3).
77pub fn parse_mail_address(value: &str) -> Result<MailAddress> {
78    let url = identity::parse_agent_url(value)?;
79    let mailbox_id = match (url.protocol.as_deref(), url.resource) {
80        (Some("mail"), Some(mailbox_id)) => mailbox_id,
81        _ => return Err(fail("invalid_url", "not a mailbox address")),
82    };
83    fixed_bytes(&mailbox_id, 16).map_err(|_| fail("invalid_url", "mailbox_id must be an id16"))?;
84    Ok(MailAddress {
85        owner: url.agent_id,
86        mailbox_id,
87        routes: url.routes,
88    })
89}
90/// Format the stable address, or a contact address when routes are given.
91pub fn format_mail_address(owner: &AgentId, mailbox_id: &str, routes: &[String]) -> Result<String> {
92    fixed_bytes(mailbox_id, 16).map_err(|_| fail("invalid_url", "mailbox_id must be an id16"))?;
93    identity::format_agent_url(&identity::AgentUrl {
94        agent_id: owner.clone(),
95        protocol: Some("mail".into()),
96        resource: Some(mailbox_id.into()),
97        routes: routes.to_vec(),
98    })
99}
100/// Validate a named structural definition; signatures and semantics are separate.
101pub fn validate_mail_schema(value: &Value, definition: &str) -> Result<()> {
102    static VALIDATORS: OnceLock<Mutex<BTreeMap<String, jsonschema::Validator>>> = OnceLock::new();
103    let mut validators = VALIDATORS
104        .get_or_init(|| Mutex::new(BTreeMap::new()))
105        .lock()
106        .map_err(|_| fail("invalid_event", "schema cache unavailable"))?;
107    if !validators.contains_key(definition) {
108        let schema: Value = serde_json::from_str(SCHEMA_JSON)?;
109        if schema["$defs"].get(definition).is_none() {
110            return Err(fail("invalid_event", "unknown Mail schema definition"));
111        }
112        let validator = jsonschema::options()
113            .with_draft(jsonschema::Draft::Draft202012)
114            .build(&json!({"$ref":format!("#/$defs/{definition}"),"$defs":schema["$defs"]}))
115            .map_err(|e| fail("invalid_event", e.to_string()))?;
116        validators.insert(definition.into(), validator);
117    }
118    validators[definition]
119        .validate(value)
120        .map_err(|e| fail("invalid_event", e.to_string()))
121}
122pub(crate) fn normalized(value: &Value) -> Value {
123    match value {
124        Value::Number(n) if n.as_i64().is_none() && n.as_u64().is_none() => n
125            .as_f64()
126            .filter(|f| f.fract() == 0.0 && f.abs() <= identity::MAX_SAFE_NONCE as f64)
127            .map(|f| json!(f as i64))
128            .unwrap_or(value.clone()),
129        Value::Array(a) => Value::Array(a.iter().map(normalized).collect()),
130        Value::Object(o) => {
131            Value::Object(o.iter().map(|(k, v)| (k.clone(), normalized(v))).collect())
132        }
133        _ => value.clone(),
134    }
135}
136fn signed(value: &Value, definition: &str) -> Result<Envelope<Value>> {
137    identity::parse_strict_json(&serde_json::to_string(value)?)?;
138    validate_mail_schema(value, definition)?;
139    let envelope: Envelope<Value> = serde_json::from_value(normalized(value))?;
140    identity::validate_event_fields(&envelope.event, &[])?;
141    identity::validate_nonce(envelope.event.nonce)?;
142    identity::verify_envelope(&envelope)?;
143    Ok(envelope)
144}
145pub(crate) fn lifetime(created: i64, expires: i64) -> Result<()> {
146    if created < 0
147        || expires <= created
148        || expires > created.saturating_add(MAX_TTL_MS)
149        || expires as u64 > identity::MAX_SAFE_NONCE
150    {
151        return Err(fail("invalid_event", "invalid lifetime"));
152    }
153    Ok(())
154}
155pub(crate) fn clock(now: i64) -> Result<()> {
156    if now < 0 || now as u64 > identity::MAX_SAFE_NONCE {
157        return Err(fail("invalid_request", "invalid clock"));
158    }
159    Ok(())
160}
161/// Historical verification: checks intrinsic validity, not live-write freshness.
162pub fn validate_card(value: &Value) -> Result<MailboxCard> {
163    let envelope = signed(value, "mailboxCardEnvelope")?;
164    let card: MailboxCard = serde_json::from_value(serde_json::to_value(envelope)?)?;
165    let p = &card.event.payload;
166    lifetime(card.event.created_at, p.expires_at)?;
167    if p.receive_until < p.expires_at || p.receive_until > p.expires_at.saturating_add(MAX_TTL_MS) {
168        return Err(fail("invalid_event", "invalid receive_until"));
169    }
170    for route in &p.routes {
171        identity::validate_origin(route)?;
172    }
173    let probe_enc = <Kem as hpke::Kem>::EncappedKey::from_bytes(&fixed_bytes(&p.public_key, 32)?)
174        .map_err(|_| fail("invalid_event", "invalid X25519 key"))?;
175    // The maintained KEM rejects low-order/all-zero DH results. A fixed public
176    // probe secret is only validation input, never used for actual encryption.
177    let probe =
178        PrivateKey::from_bytes(&[42; 32]).map_err(|_| fail("invalid_event", "invalid key"))?;
179    Kem::decap(&probe, None, &probe_enc)
180        .map_err(|_| fail("invalid_event", "unusable X25519 key"))?;
181    Ok(card)
182}
183pub fn validate_card_for_sending(value: &Value, owner: &AgentId, now: i64) -> Result<MailboxCard> {
184    let card = validate_card(value)?;
185    check_card_usable(&card, owner, now)?;
186    Ok(card)
187}
188pub(crate) fn check_card_usable(card: &MailboxCard, owner: &AgentId, now: i64) -> Result<()> {
189    clock(now)?;
190    if &card.event.actor != owner {
191        return Err(fail("invalid_actor", "unexpected mailbox owner"));
192    }
193    if card.event.created_at > now.saturating_add(FUTURE_SKEW_MS) {
194        return Err(SdkError::TimestampOutOfWindow);
195    }
196    if card.event.payload.routes.is_empty() {
197        return Err(fail("mailbox_unavailable", "mailbox closed"));
198    }
199    if now >= card.event.payload.expires_at {
200        return Err(fail("stale_card", "card expired"));
201    }
202    Ok(())
203}
204/// Verify a letter as a historical object. Freshness/deduplication is performed
205/// by `MailInbox`, so a delayed low-nonce letter is never rejected here.
206pub fn validate_letter(value: &Value) -> Result<Letter> {
207    let e = signed(value, "messageEnvelope")?;
208    let p: MessagePayload = serde_json::from_value(normalized(&e.event.payload))?;
209    lifetime(e.event.created_at, p.expires_at)?;
210    for part in &p.parts {
211        let bytes = decode_bytes(&part.data)?;
212        if part.media_type.starts_with("text/") {
213            std::str::from_utf8(&bytes)
214                .map_err(|_| fail("invalid_event", "text part is not UTF-8"))?;
215        }
216    }
217    if let Some(reply) = &p.reply_card {
218        let card = validate_card(reply)?;
219        if card.event.actor != e.event.actor {
220            return Err(fail(
221                "invalid_actor",
222                "reply card owner differs from sender",
223            ));
224        }
225    }
226    Ok(e)
227}
228pub fn parse_card(text: &str) -> Result<MailboxCard> {
229    validate_card(&identity::parse_strict_json(text)?)
230}
231pub fn parse_letter(text: &str) -> Result<Letter> {
232    validate_letter(&identity::parse_strict_json(text)?)
233}
234pub fn sign_card(
235    signer: &AgentSigner,
236    payload: MailboxCardPayload,
237    created_at: i64,
238    nonce: u64,
239) -> Result<MailboxCard> {
240    let envelope = signer.sign_event(Event::new(
241        PROTOCOL,
242        "mailbox.publish",
243        signer.agent_id(),
244        created_at,
245        nonce,
246        payload,
247    ))?;
248    validate_card(&serde_json::to_value(&envelope)?)?;
249    Ok(envelope)
250}
251pub fn sign_message(
252    signer: &AgentSigner,
253    payload: MessagePayload,
254    created_at: i64,
255    nonce: u64,
256) -> Result<Letter> {
257    let envelope = signer.sign_event(Event::new(
258        PROTOCOL,
259        "mail.message",
260        signer.agent_id(),
261        created_at,
262        nonce,
263        serde_json::to_value(payload)?,
264    ))?;
265    validate_letter(&serde_json::to_value(&envelope)?)?;
266    Ok(envelope)
267}
268/// Bind a reply to a known parent: participants, parent letter ID, and thread.
269pub fn validate_reply(reply: &Letter, parent: &Letter) -> Result<()> {
270    validate_letter(&serde_json::to_value(reply)?)?;
271    validate_letter(&serde_json::to_value(parent)?)?;
272    if reply.event.payload["to"] != parent.event.actor.as_str()
273        || parent.event.payload["to"] != reply.event.actor.as_str()
274        || reply.event.payload["in_reply_to"] != parent.hash
275        || reply.event.payload["thread_id"] != parent.event.payload["thread_id"]
276    {
277        return Err(fail("invalid_event", "reply binding mismatch"));
278    }
279    Ok(())
280}
281/// Independent X25519 secret. Debug output and implicit serialization are absent.
282/// `export_secret` is explicit and returns a buffer zeroized on drop.
283pub struct MailEncryptionKey(PrivateKey);
284impl MailEncryptionKey {
285    pub fn generate() -> Result<Self> {
286        let mut bytes = Zeroizing::new([0; 32]);
287        getrandom::fill(bytes.as_mut()).map_err(|e| SdkError::Random(e.to_string()))?;
288        Self::from_secret(bytes.as_ref())
289    }
290    pub fn from_secret(bytes: &[u8]) -> Result<Self> {
291        Ok(Self(PrivateKey::from_bytes(bytes).map_err(|_| {
292            fail("invalid_event", "X25519 secret must contain 32 bytes")
293        })?))
294    }
295    pub fn public_key(&self) -> String {
296        encode_bytes(&Kem::sk_to_pk(&self.0).to_bytes())
297    }
298    pub fn export_secret(&self) -> Zeroizing<Vec<u8>> {
299        Zeroizing::new(self.0.to_bytes().to_vec())
300    }
301}
302/// Exact framing, also useful for boundary conformance tests. Inputs are bounded.
303pub fn frame_bytes(bytes: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
304    if bytes.is_empty() || bytes.len() > MAX_PACKET_BYTES {
305        return Err(fail("invalid_packet", "invalid frame length"));
306    }
307    let size = (4 + bytes.len()).div_ceil(1024) * 1024;
308    let mut frame = Zeroizing::new(vec![0; size]);
309    frame[..4].copy_from_slice(&(bytes.len() as u32).to_be_bytes());
310    frame[4..4 + bytes.len()].copy_from_slice(bytes);
311    Ok(frame)
312}
313fn unframe(bytes: &[u8]) -> Result<Value> {
314    if bytes.len() < 1024 || bytes.len() % 1024 != 0 {
315        return Err(fail("invalid_packet", "invalid frame length"));
316    }
317    let n = u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize;
318    if n == 0
319        || n > bytes.len() - 4
320        || (4 + n).div_ceil(1024) * 1024 != bytes.len()
321        || bytes[4 + n..].iter().any(|b| *b != 0)
322    {
323        return Err(fail("invalid_packet", "invalid frame padding"));
324    }
325    let data = &bytes[4..4 + n];
326    let text = std::str::from_utf8(data).map_err(|_| fail("invalid_packet", "invalid UTF-8"))?;
327    let value = identity::parse_strict_json(text)?;
328    if canonical_bytes(&value)? != data {
329        return Err(fail("invalid_packet", "noncanonical plaintext"));
330    }
331    Ok(value)
332}
333/// Validate a packet and return it with its canonical bytes, computed once for ID and size checks.
334pub(crate) fn checked_packet(value: &Value) -> Result<(Packet, Vec<u8>)> {
335    validate_mail_schema(value, "packet").map_err(|e| fail("invalid_packet", e.to_string()))?;
336    let packet: Packet = serde_json::from_value(normalized(value))?;
337    fixed_bytes(&packet.enc, 32)?;
338    let n = decode_bytes(&packet.ciphertext)?.len();
339    let bytes = canonical_bytes(&packet)?;
340    if n < 1040 || n % 1024 != 16 || bytes.len() > MAX_PACKET_BYTES {
341        return Err(fail(
342            "invalid_packet",
343            "invalid ciphertext or packet length",
344        ));
345    }
346    Ok((packet, bytes))
347}
348pub fn validate_packet(value: &Value) -> Result<Packet> {
349    Ok(checked_packet(value)?.0)
350}
351pub fn parse_packet(text: &str) -> Result<Packet> {
352    if text.len() > 2 * MAX_PACKET_BYTES {
353        return Err(fail("payload_too_large", "raw packet body too large"));
354    }
355    validate_packet(&identity::parse_strict_json(text)?)
356}
357pub fn packet_id(packet: &Packet) -> Result<String> {
358    Ok(hash_bytes(&canonical_bytes(packet)?))
359}
360/// Production encryption: fresh system randomness, one HPKE context per packet.
361/// Caller should observe the card with `CardCache` before using it.
362pub fn encrypt_letter(letter: &Letter, card: &MailboxCard, now: i64) -> Result<Packet> {
363    let letter = validate_letter(&serde_json::to_value(letter)?)?;
364    let owner: AgentId = serde_json::from_value(letter.event.payload["to"].clone())?;
365    validate_card_for_sending(&serde_json::to_value(card)?, &owner, now)?;
366    let expiry = letter.event.payload["expires_at"].as_i64().unwrap();
367    if letter.event.created_at > now.saturating_add(FUTURE_SKEW_MS) || expiry <= now {
368        return Err(fail("packet_expired", "letter is expired or future-dated"));
369    }
370    if expiry > card.event.payload.receive_until {
371        return Err(fail("invalid_packet", "letter exceeds receive_until"));
372    }
373    let header = PacketHeader {
374        protocol: PROTOCOL.into(),
375        mailbox_id: card.event.payload.mailbox_id.clone(),
376        card_hash: card.hash.clone(),
377        expires_at: expiry,
378    };
379    let json = Zeroizing::new(canonical_bytes(&letter)?);
380    let plaintext = frame_bytes(&json)?;
381    // Bound allocation/output before doing expensive public-key encryption.
382    let projected = Packet {
383        header: header.clone(),
384        enc: encode_bytes(&[0; 32]),
385        ciphertext: encode_bytes(&vec![0; plaintext.len() + 16]),
386    };
387    if canonical_bytes(&projected)?.len() > card.event.payload.max_packet_bytes {
388        return Err(fail("payload_too_large", "packet exceeds card limit"));
389    }
390    let pk = PublicKey::from_bytes(&fixed_bytes(&card.event.payload.public_key, 32)?)
391        .map_err(|_| fail("invalid_packet", "invalid key"))?;
392    let (enc, ciphertext) = hpke::single_shot_seal::<ChaCha20Poly1305, HkdfSha256, Kem>(
393        &OpModeS::Base,
394        &pk,
395        INFO,
396        &plaintext,
397        &canonical_bytes(&header)?,
398    )
399    .map_err(|_| fail("invalid_packet", "encryption failed"))?;
400    Ok(Packet {
401        header,
402        enc: encode_bytes(&enc.to_bytes()),
403        ciphertext: encode_bytes(&ciphertext),
404    })
405}
406/// Stateless authenticated opening of a historical packet. This verifies shape,
407/// cryptography and future skew; callers must enforce new-acceptance expiry and
408/// durable deduplication (`MailInbox` implements those state transitions).
409pub fn decrypt_packet(
410    packet: &Packet,
411    card: &MailboxCard,
412    key: &MailEncryptionKey,
413    owner: &AgentId,
414    now: i64,
415) -> Result<Letter> {
416    clock(now)?;
417    let (packet, bytes) = checked_packet(&serde_json::to_value(packet)?)?;
418    let card = validate_card(&serde_json::to_value(card)?)?;
419    open_verified(&packet, &bytes, &card, key, owner, now)
420}
421/// Open with a card already verified as a historical object (`MailKeyring` verifies at `add`).
422pub(crate) fn open_verified(
423    packet: &Packet,
424    bytes: &[u8],
425    card: &MailboxCard,
426    key: &MailEncryptionKey,
427    owner: &AgentId,
428    now: i64,
429) -> Result<Letter> {
430    let h = &packet.header;
431    let p = &card.event.payload;
432    if &card.event.actor != owner
433        || h.card_hash != card.hash
434        || h.mailbox_id != p.mailbox_id
435        || h.expires_at > p.receive_until
436        || bytes.len() > p.max_packet_bytes
437        || key.public_key() != p.public_key
438    {
439        return Err(fail("invalid_packet", "recipient/card/key binding"));
440    }
441    let enc = <Kem as hpke::Kem>::EncappedKey::from_bytes(&fixed_bytes(&packet.enc, 32)?)
442        .map_err(|_| fail("invalid_packet", "invalid encapsulated key"))?;
443    let plaintext = Zeroizing::new(
444        hpke::single_shot_open::<ChaCha20Poly1305, HkdfSha256, Kem>(
445            &OpModeR::Base,
446            &key.0,
447            &enc,
448            INFO,
449            &decode_bytes(&packet.ciphertext)?,
450            &canonical_bytes(h)?,
451        )
452        .map_err(|_| fail("invalid_packet", "unable to decrypt packet"))?,
453    );
454    let letter = validate_letter(&unframe(&plaintext)?)?;
455    if letter.event.payload["to"] != owner.as_str()
456        || letter.event.payload["expires_at"] != h.expires_at
457    {
458        return Err(fail(
459            "invalid_packet",
460            "letter recipient or expiration binding",
461        ));
462    }
463    if letter.event.created_at > now.saturating_add(FUTURE_SKEW_MS) {
464        return Err(SdkError::TimestampOutOfWindow);
465    }
466    Ok(letter)
467}
468/// Informational discovery document; it never supplies delivery paths.
469pub fn validate_discovery(value: &Value, origin: &str) -> Result<()> {
470    validate_mail_schema(value, "discoveryDocument")?;
471    identity::validate_origin(origin)?;
472    if value["service"] != origin {
473        return Err(fail("invalid_response", "discovery origin mismatch"));
474    }
475    Ok(())
476}
477pub(crate) fn owner_claims(
478    token: &str,
479    origin: &str,
480    now: i64,
481) -> Result<identity::RequestJwtClaims> {
482    clock(now)?;
483    identity::verify_request_jwt(
484        token,
485        &identity::RequestAuthContext {
486            audience: origin.into(),
487            now_secs: now / 1000,
488            max_ttl_secs: identity::DEFAULT_REQUEST_JWT_TTL_SECS,
489        },
490    )
491    .map_err(|e| fail("invalid_token", e.to_string()))
492}
493/// Identity request JWT for this relay origin whose subject is the mailbox owner.
494pub fn verify_owner_jwt(token: &str, owner: &AgentId, origin: &str, now: i64) -> Result<()> {
495    identity::validate_origin(origin)?;
496    if &owner_claims(token, origin, now)?.iss != owner {
497        return Err(SdkError::PermissionDenied);
498    }
499    Ok(())
500}