Skip to main content

ma_core/
outbox.rs

1//! Transport-agnostic send handle to a remote ma service.
2//!
3//! An `Outbox` wraps the transport details and exposes a single `send()`
4//! method. Outboxes are lightweight and meant to be kept alive for the
5//! duration of a session — `ma-core` manages the underlying connections.
6//!
7//! `send()` takes a [`Message`], validates it, applies the message type's
8//! encryption policy, and transmits. Malformed or expired messages are
9//! rejected before anything hits the wire.
10//!
11//! Requires the `iroh` feature.
12//!
13//! ```ignore
14//! let mut outbox = ep.outbox(&resolver, "did:ma:k51qzi5uqu5d…", INBOX_PROTOCOL_ID).await?;
15//! outbox.send(&message).await?;
16//! // Keep the outbox alive — no need to close it.
17//! ```
18
19use crate::error::{Error, Result};
20use crate::{Document, Message};
21use async_trait::async_trait;
22
23#[async_trait]
24pub(crate) trait OutboxWire: Send + std::fmt::Debug {
25    async fn send_payload(&mut self, payload: &[u8]) -> Result<()>;
26    fn close_box(self: Box<Self>);
27}
28
29/// A transport-agnostic write handle to a remote service.
30///
31/// The caller doesn't need to know the underlying transport.
32#[derive(Debug)]
33pub struct Outbox {
34    inner: Option<Box<dyn OutboxWire>>,
35    recipient_document: Document,
36    local: bool,
37    did: String,
38    protocol: String,
39}
40
41impl Outbox {
42    /// Create an outbox backed by a transport implementation.
43    pub(crate) fn from_transport<T>(
44        transport: T,
45        recipient_document: Document,
46        local: bool,
47        did: String,
48        protocol: String,
49    ) -> Self
50    where
51        T: OutboxWire + 'static,
52    {
53        Self {
54            inner: Some(Box::new(transport)),
55            recipient_document,
56            local,
57            did,
58            protocol,
59        }
60    }
61
62    /// Send a ma message to the remote service.
63    ///
64    /// Validates the message headers, encrypts non-broadcast remote messages,
65    /// and transmits the resulting CBOR payload.
66    ///
67    /// Loopback (self-addressed) delivery is never encrypted: it is handed
68    /// straight to a local [`Inbox`](crate::Inbox) where the same endpoint would
69    /// only decrypt it again, and the reader verifies the signature regardless.
70    ///
71    /// # Errors
72    /// Returns an error if validation, serialization, or transport send fails.
73    pub async fn send(&mut self, message: &Message) -> Result<()> {
74        message.headers().validate()?;
75        let unencrypted =
76            self.local || message.message_type == crate::service::MESSAGE_TYPE_BROADCAST;
77        let payload = if unencrypted {
78            message.encode()?
79        } else {
80            message.enclose_for(&self.recipient_document)?.encode()?
81        };
82        match self.inner.as_mut() {
83            Some(transport) => transport.send_payload(&payload).await,
84            None => Err(Error::ConnectionClosed("outbox is closed".to_string())),
85        }
86    }
87
88    /// The DID this outbox delivers to.
89    #[must_use]
90    pub fn did(&self) -> &str {
91        &self.did
92    }
93
94    /// The protocol this outbox is connected to.
95    #[must_use]
96    pub fn protocol(&self) -> &str {
97        &self.protocol
98    }
99
100    /// Close the outbox gracefully.
101    pub fn close(mut self) {
102        if let Some(transport) = self.inner.take() {
103            transport.close_box();
104        }
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111    use crate::{generate_identity_from_secret, Did, Envelope, SigningKey};
112    use std::sync::{Arc, Mutex};
113
114    #[derive(Debug, Clone)]
115    struct CaptureWire(Arc<Mutex<Vec<u8>>>);
116
117    #[async_trait]
118    impl OutboxWire for CaptureWire {
119        async fn send_payload(&mut self, payload: &[u8]) -> Result<()> {
120            self.0
121                .lock()
122                .expect("capture lock")
123                .extend_from_slice(payload);
124            Ok(())
125        }
126
127        fn close_box(self: Box<Self>) {}
128    }
129
130    fn signing_key(identity: &crate::GeneratedIdentity) -> SigningKey {
131        let did = Did::new_url(&identity.subject_url.ipns, Some("sign")).expect("signing DID");
132        let bytes = hex::decode(&identity.signing_private_key_hex).expect("private key hex");
133        SigningKey::from_private_key_bytes(did, bytes.try_into().expect("private key length"))
134            .expect("signing key")
135    }
136
137    fn outbox(recipient_document: &Document, local: bool) -> (Outbox, Arc<Mutex<Vec<u8>>>) {
138        let captured = Arc::new(Mutex::new(Vec::new()));
139        let outbox = Outbox::from_transport(
140            CaptureWire(captured.clone()),
141            recipient_document.clone(),
142            local,
143            recipient_document.id.clone(),
144            crate::service::INBOX_PROTOCOL_ID.to_string(),
145        );
146        (outbox, captured)
147    }
148
149    fn inbox_url(identity: &crate::GeneratedIdentity) -> String {
150        format!("{}#inbox", identity.document.id)
151    }
152
153    #[tokio::test]
154    async fn remote_message_is_transmitted_as_envelope() {
155        let sender = generate_identity_from_secret([1; 32]).expect("sender identity");
156        let recipient = generate_identity_from_secret([2; 32]).expect("recipient identity");
157        let message = Message::new(
158            sender.document.id.clone(),
159            inbox_url(&recipient),
160            crate::service::MESSAGE_TYPE_MESSAGE,
161            "text/plain",
162            b"secret",
163            &signing_key(&sender),
164        )
165        .expect("message");
166        let (mut outbox, captured) = outbox(&recipient.document, false);
167
168        outbox.send(&message).await.expect("send message");
169
170        let payload = captured.lock().expect("capture lock");
171        Envelope::decode(&payload).expect("encrypted envelope");
172        assert!(
173            Message::decode(&payload).is_err(),
174            "raw message reached wire"
175        );
176    }
177
178    #[tokio::test]
179    async fn broadcast_is_transmitted_as_raw_message() {
180        let sender = generate_identity_from_secret([1; 32]).expect("sender identity");
181        let recipient = generate_identity_from_secret([2; 32]).expect("recipient identity");
182        let message = Message::new(
183            sender.document.id.clone(),
184            String::new(),
185            crate::service::MESSAGE_TYPE_BROADCAST,
186            "text/plain",
187            b"public",
188            &signing_key(&sender),
189        )
190        .expect("broadcast");
191        let (mut outbox, captured) = outbox(&recipient.document, false);
192
193        outbox.send(&message).await.expect("send broadcast");
194
195        let payload = captured.lock().expect("capture lock");
196        assert_eq!(Message::decode(&payload).expect("raw message"), message);
197    }
198
199    #[tokio::test]
200    async fn local_same_base_did_is_transmitted_as_raw_message() {
201        let identity = generate_identity_from_secret([1; 32]).expect("identity");
202        let from = format!("{}#sender", identity.document.id);
203        let to = format!("{}#recipient", identity.document.id);
204        let message = Message::new(
205            from,
206            to,
207            crate::service::MESSAGE_TYPE_MESSAGE,
208            "text/plain",
209            b"local",
210            &signing_key(&identity),
211        )
212        .expect("message");
213        let (mut outbox, captured) = outbox(&identity.document, true);
214
215        outbox.send(&message).await.expect("send local message");
216
217        let payload = captured.lock().expect("capture lock");
218        assert_eq!(Message::decode(&payload).expect("raw message"), message);
219    }
220
221    #[tokio::test]
222    async fn local_wire_bypasses_encryption_even_for_different_base_dids() {
223        let sender = generate_identity_from_secret([1; 32]).expect("sender identity");
224        let recipient = generate_identity_from_secret([2; 32]).expect("recipient identity");
225        let message = Message::new(
226            sender.document.id.clone(),
227            inbox_url(&recipient),
228            crate::service::MESSAGE_TYPE_MESSAGE,
229            "text/plain",
230            b"secret",
231            &signing_key(&sender),
232        )
233        .expect("message");
234        let (mut outbox, captured) = outbox(&recipient.document, true);
235
236        outbox.send(&message).await.expect("send message");
237
238        let payload = captured.lock().expect("capture lock");
239        assert_eq!(Message::decode(&payload).expect("raw message"), message);
240    }
241}