1use chacha20poly1305::{
2 aead::{Aead, Generate, KeyInit},
3 Key, XChaCha20Poly1305, XNonce,
4};
5use ed25519_dalek::{Signature, Verifier};
6use nanoid::nanoid;
7use rand::{rand_core::UnwrapErr, rngs::SysRng};
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use web_time::{SystemTime, UNIX_EPOCH};
11
12use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret};
13
14use crate::{
15 constants,
16 did::Did,
17 doc::Document,
18 error::{MaError, MaResult as Result},
19 key::{EncryptionKey, SigningKey},
20};
21
22pub const MESSAGE_PREFIX: &str = "/ma/";
23
24pub const DEFAULT_REPLAY_WINDOW_SECS: u64 = 120;
25pub const DEFAULT_MAX_CLOCK_SKEW_SECS: u64 = 30;
26pub const DEFAULT_MESSAGE_TTL_SECS: u64 = 3600;
27
28pub fn encode_content(codec: u64, payload: &[u8]) -> Vec<u8> {
30 crate::multiformat::multicodec_encode(codec, payload)
31}
32
33pub fn decode_content(content: &[u8]) -> crate::error::MaResult<(u64, Vec<u8>)> {
36 crate::multiformat::multicodec_decode(content)
37}
38
39fn codec_for(content_type: &str) -> u64 {
42 match content_type {
43 "application/vnd.ipld.dag-cbor" => crate::multiformat::CODEC_DAG_CBOR,
44 "application/cbor" | "application/vnd.ma.term" => crate::multiformat::CODEC_CBOR,
46 _ => crate::multiformat::CODEC_IDENTITY,
47 }
48}
49
50#[must_use]
51pub fn default_protocol() -> String {
52 format!("{MESSAGE_PREFIX}{}", constants::VERSION)
53}
54
55#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
60pub struct Headers {
61 pub id: String,
62 #[serde(rename = "protocol")]
63 pub protocol: String,
64 #[serde(rename = "type")]
65 pub message_type: String,
66 pub from: String,
67 pub to: String,
68 #[serde(rename = "createdAt")]
69 pub created_at: u64,
70 #[serde(default)]
71 pub exp: u64,
72 #[serde(rename = "contentType")]
73 pub content_type: String,
74 #[serde(default, skip_serializing_if = "Option::is_none", rename = "replyTo")]
75 pub reply_to: Option<String>,
76 #[serde(rename = "contentHash")]
77 pub content_hash: [u8; 32],
78 pub signature: Vec<u8>,
79}
80
81impl Headers {
82 pub fn validate(&self) -> Result<()> {
83 validate_message_id(&self.id)?;
84 validate_protocol(&self.protocol)?;
85 if let Some(reply_to) = &self.reply_to {
86 validate_message_id(reply_to)?;
87 }
88
89 if self.content_type.is_empty() {
90 return Err(MaError::MissingContentType);
91 }
92
93 Did::validate(&self.from)?;
94 let recipient_is_empty = self.to.trim().is_empty();
95
96 if self.message_type == crate::service::MESSAGE_TYPE_BROADCAST {
97 if !recipient_is_empty {
98 return Err(MaError::BroadcastMustNotHaveRecipient);
99 }
100 } else {
101 if recipient_is_empty {
102 return Err(MaError::MessageRequiresRecipient);
103 }
104 Did::validate_url(&self.to).map_err(|_| MaError::InvalidRecipient)?;
105 }
106 validate_message_freshness(self.created_at, self.exp)?;
107
108 Ok(())
109 }
110}
111
112#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
151pub struct Message {
152 pub id: String,
153 #[serde(rename = "protocol")]
154 pub protocol: String,
155 #[serde(rename = "type")]
156 pub message_type: String,
157 pub from: String,
158 pub to: String,
159 #[serde(rename = "createdAt")]
160 pub created_at: u64,
161 #[serde(default)]
162 pub exp: u64,
163 #[serde(rename = "contentType")]
164 pub content_type: String,
165 #[serde(default, skip_serializing_if = "Option::is_none", rename = "replyTo")]
166 pub reply_to: Option<String>,
167 pub content: Vec<u8>,
168 pub signature: Vec<u8>,
169}
170
171struct MessageOptions {
172 exp: u64,
173 reply_to: Option<String>,
174}
175
176impl Message {
177 pub fn new(
178 from: impl Into<String>,
179 to: impl Into<String>,
180 message_type: impl Into<String>,
181 content_type: impl Into<String>,
182 content: &[u8],
183 signing_key: &SigningKey,
184 ) -> Result<Self> {
185 let exp = now_unix_secs()? + DEFAULT_MESSAGE_TTL_SECS;
186 Self::new_with_exp(
187 from,
188 to,
189 message_type,
190 content_type,
191 content,
192 exp,
193 signing_key,
194 )
195 }
196
197 pub fn new_reply(
199 from: impl Into<String>,
200 to: impl Into<String>,
201 message_type: impl Into<String>,
202 content_type: impl Into<String>,
203 content: &[u8],
204 reply_to: impl Into<String>,
205 signing_key: &SigningKey,
206 ) -> Result<Self> {
207 let exp = now_unix_secs()? + DEFAULT_MESSAGE_TTL_SECS;
208 Self::new_with_options(
209 from,
210 to,
211 message_type,
212 content_type,
213 content,
214 MessageOptions {
215 exp,
216 reply_to: Some(reply_to.into()),
217 },
218 signing_key,
219 )
220 }
221
222 pub fn new_with_exp(
223 from: impl Into<String>,
224 to: impl Into<String>,
225 message_type: impl Into<String>,
226 content_type: impl Into<String>,
227 content: &[u8],
228 exp: u64,
229 signing_key: &SigningKey,
230 ) -> Result<Self> {
231 Self::new_with_options(
232 from,
233 to,
234 message_type,
235 content_type,
236 content,
237 MessageOptions {
238 exp,
239 reply_to: None,
240 },
241 signing_key,
242 )
243 }
244
245 fn new_with_options(
246 from: impl Into<String>,
247 to: impl Into<String>,
248 message_type: impl Into<String>,
249 content_type: impl Into<String>,
250 content: &[u8],
251 options: MessageOptions,
252 signing_key: &SigningKey,
253 ) -> Result<Self> {
254 let content_type_str: String = content_type.into();
255 let encoded = encode_content(codec_for(&content_type_str), content);
256 let mut message = Self {
257 id: nanoid!(),
258 protocol: default_protocol(),
259 message_type: message_type.into(),
260 from: from.into(),
261 to: to.into(),
262 created_at: now_unix_secs()?,
263 exp: options.exp,
264 content_type: content_type_str,
265 reply_to: options.reply_to,
266 content: encoded,
267 signature: Vec::new(),
268 };
269
270 message.unsigned_headers().validate()?;
271 message.validate_content()?;
272 message.sign(signing_key)?;
273 Ok(message)
274 }
275
276 pub fn encode(&self) -> Result<Vec<u8>> {
277 let mut out = Vec::new();
278 ciborium::ser::into_writer(self, &mut out)
279 .map_err(|error| MaError::CborEncode(error.to_string()))?;
280 Ok(out)
281 }
282
283 pub fn decode(bytes: &[u8]) -> Result<Self> {
284 ciborium::de::from_reader(bytes).map_err(|error| MaError::CborDecode(error.to_string()))
285 }
286
287 #[must_use]
290 pub fn payload(&self) -> Vec<u8> {
291 decode_content(&self.content)
292 .map(|(_, p)| p)
293 .unwrap_or_else(|_| self.content.clone())
294 }
295
296 #[must_use]
297 pub fn unsigned_headers(&self) -> Headers {
298 Headers {
299 id: self.id.clone(),
300 protocol: self.protocol.clone(),
301 message_type: self.message_type.clone(),
302 from: self.from.clone(),
303 to: self.to.clone(),
304 created_at: self.created_at,
305 exp: self.exp,
306 content_type: self.content_type.clone(),
307 reply_to: self.reply_to.clone(),
308 content_hash: content_hash(&self.content),
309 signature: Vec::new(),
310 }
311 }
312
313 #[must_use]
314 pub fn headers(&self) -> Headers {
315 let mut headers = self.unsigned_headers();
316 headers.signature.clone_from(&self.signature);
317 headers
318 }
319
320 pub fn sign(&mut self, signing_key: &SigningKey) -> Result<()> {
321 let bytes = self.unsigned_headers_cbor()?;
322 self.signature = signing_key.sign(&bytes);
323 Ok(())
324 }
325
326 pub fn verify_with_document(&self, sender_document: &Document) -> Result<()> {
327 if self.from.is_empty() {
328 return Err(MaError::MissingSender);
329 }
330
331 if self.signature.is_empty() {
332 return Err(MaError::MissingSignature);
333 }
334
335 let sender_did = Did::try_from(self.from.as_str())?;
336 if sender_document.id != sender_did.base_id() {
337 return Err(MaError::InvalidRecipient);
338 }
339
340 self.headers().validate()?;
341 let bytes = self.unsigned_headers_cbor()?;
342 let signature =
343 Signature::from_slice(&self.signature).map_err(|_| MaError::InvalidMessageSignature)?;
344 sender_document
345 .assertion_method_public_key()?
346 .verify(&bytes, &signature)
347 .map_err(|_| MaError::InvalidMessageSignature)
348 }
349
350 pub fn enclose_for(&self, recipient_document: &Document) -> Result<Envelope> {
351 self.headers().validate()?;
352
353 let recipient_public_key =
354 X25519PublicKey::from(recipient_document.key_agreement_public_key_bytes()?);
355 let ephemeral_secret = StaticSecret::random_from_rng(&mut UnwrapErr(SysRng));
356 let ephemeral_public = X25519PublicKey::from(&ephemeral_secret);
357 let shared_secret = ephemeral_secret
358 .diffie_hellman(&recipient_public_key)
359 .to_bytes();
360
361 let encrypted_headers = encrypt(
362 &self.headers_cbor()?,
363 derive_symmetric_key(&shared_secret, constants::BLAKE3_HEADERS_LABEL),
364 )?;
365
366 let encrypted_content = encrypt(
367 &self.content,
368 derive_symmetric_key(&shared_secret, constants::blake3_content_label()),
369 )?;
370
371 Ok(Envelope {
372 ephemeral_key: ephemeral_public.as_bytes().to_vec(),
373 encrypted_content,
374 encrypted_headers,
375 })
376 }
377
378 fn headers_cbor(&self) -> Result<Vec<u8>> {
379 to_cbor(&self.headers())
380 }
381
382 fn unsigned_headers_cbor(&self) -> Result<Vec<u8>> {
383 to_cbor(&self.unsigned_headers())
384 }
385
386 fn validate_content(&self) -> Result<()> {
387 if self.content.is_empty() {
388 return Err(MaError::MissingContent);
389 }
390 Ok(())
391 }
392
393 fn from_headers(headers: Headers) -> Result<Self> {
394 headers.validate()?;
395 Ok(Self {
396 id: headers.id,
397 protocol: headers.protocol,
398 message_type: headers.message_type,
399 from: headers.from,
400 to: headers.to,
401 created_at: headers.created_at,
402 exp: headers.exp,
403 content_type: headers.content_type,
404 reply_to: headers.reply_to,
405 content: Vec::new(),
406 signature: headers.signature,
407 })
408 }
409}
410
411fn to_cbor<T: Serialize>(value: &T) -> Result<Vec<u8>> {
412 let mut out = Vec::new();
413 ciborium::ser::into_writer(value, &mut out)
414 .map_err(|error| MaError::CborEncode(error.to_string()))?;
415 Ok(out)
416}
417
418#[derive(Debug, Clone)]
434pub struct ReplayGuard {
435 seen: HashMap<String, u64>,
436 window_secs: u64,
437}
438
439impl Default for ReplayGuard {
440 fn default() -> Self {
441 Self::new(DEFAULT_REPLAY_WINDOW_SECS)
442 }
443}
444
445impl ReplayGuard {
446 #[must_use]
447 pub fn new(window_secs: u64) -> Self {
448 Self {
449 seen: HashMap::new(),
450 window_secs,
451 }
452 }
453
454 pub fn check_and_insert(&mut self, headers: &Headers) -> Result<()> {
455 headers.validate()?;
456 self.prune_old()?;
457 if self.seen.contains_key(&headers.id) {
458 return Err(MaError::ReplayDetected);
459 }
460 self.seen.insert(headers.id.clone(), now_unix_secs()?);
461 Ok(())
462 }
463
464 fn prune_old(&mut self) -> Result<()> {
465 let now = now_unix_secs()?;
466 self.seen
467 .retain(|_, seen_at| now.saturating_sub(*seen_at) <= self.window_secs);
468 Ok(())
469 }
470}
471
472#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
514pub struct Envelope {
515 #[serde(rename = "ephemeralKey")]
516 pub ephemeral_key: Vec<u8>,
517 #[serde(rename = "encryptedContent")]
518 pub encrypted_content: Vec<u8>,
519 #[serde(rename = "encryptedHeaders")]
520 pub encrypted_headers: Vec<u8>,
521}
522
523impl Envelope {
524 pub fn verify(&self) -> Result<()> {
525 if self.ephemeral_key.is_empty() {
526 return Err(MaError::MissingEnvelopeField("ephemeralKey"));
527 }
528 if self.ephemeral_key.len() != 32 {
529 return Err(MaError::InvalidEphemeralKeyLength);
530 }
531 if self.encrypted_content.is_empty() {
532 return Err(MaError::MissingEnvelopeField("encryptedContent"));
533 }
534 if self.encrypted_headers.is_empty() {
535 return Err(MaError::MissingEnvelopeField("encryptedHeaders"));
536 }
537 Ok(())
538 }
539
540 pub fn encode(&self) -> Result<Vec<u8>> {
541 let mut out = Vec::new();
542 ciborium::ser::into_writer(self, &mut out)
543 .map_err(|error| MaError::CborEncode(error.to_string()))?;
544 Ok(out)
545 }
546
547 pub fn decode(bytes: &[u8]) -> Result<Self> {
548 ciborium::de::from_reader(bytes).map_err(|error| MaError::CborDecode(error.to_string()))
549 }
550
551 pub fn open(
552 &self,
553 recipient_key: &EncryptionKey,
554 sender_document: &Document,
555 ) -> Result<Message> {
556 self.verify()?;
557
558 let shared_secret = compute_shared_secret(&self.ephemeral_key, recipient_key)?;
559 let headers = self.decrypt_headers(&shared_secret)?;
560 headers.validate()?;
561 let content = self.decrypt_content(&shared_secret)?;
562
563 let mut message = Message::from_headers(headers)?;
564 message.content = content;
565 message.verify_with_document(sender_document)?;
566 Ok(message)
567 }
568
569 #[cfg(feature = "iroh")]
570 pub(crate) fn decrypt(&self, recipient_key: &EncryptionKey) -> Result<Message> {
571 self.verify()?;
572
573 let shared_secret = compute_shared_secret(&self.ephemeral_key, recipient_key)?;
574 let headers = self.decrypt_headers(&shared_secret)?;
575 headers.validate()?;
576 let content = self.decrypt_content(&shared_secret)?;
577
578 let mut message = Message::from_headers(headers)?;
579 message.content = content;
580 Ok(message)
581 }
582
583 pub fn open_with_replay_guard(
584 &self,
585 recipient_key: &EncryptionKey,
586 sender_document: &Document,
587 replay_guard: &mut ReplayGuard,
588 ) -> Result<Message> {
589 self.verify()?;
590
591 let shared_secret = compute_shared_secret(&self.ephemeral_key, recipient_key)?;
592 let headers = self.decrypt_headers(&shared_secret)?;
593 let content = self.decrypt_content(&shared_secret)?;
594
595 let mut message = Message::from_headers(headers)?;
596 message.content = content;
597 message.verify_with_document(sender_document)?;
598 replay_guard.check_and_insert(&message.headers())?;
599 Ok(message)
600 }
601
602 fn decrypt_headers(&self, shared_secret: &[u8; 32]) -> Result<Headers> {
603 let decrypted = decrypt(
604 &self.encrypted_headers,
605 shared_secret,
606 constants::BLAKE3_HEADERS_LABEL,
607 )?;
608 ciborium::de::from_reader(decrypted.as_slice())
609 .map_err(|error| MaError::CborDecode(error.to_string()))
610 }
611
612 fn decrypt_content(&self, shared_secret: &[u8; 32]) -> Result<Vec<u8>> {
613 decrypt(
614 &self.encrypted_content,
615 shared_secret,
616 constants::blake3_content_label(),
617 )
618 }
619}
620
621fn validate_message_id(id: &str) -> Result<()> {
622 if id.is_empty() {
623 return Err(MaError::EmptyMessageId);
624 }
625
626 if !id
627 .chars()
628 .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-')
629 {
630 return Err(MaError::InvalidMessageId);
631 }
632
633 Ok(())
634}
635
636fn validate_protocol(kind: &str) -> Result<()> {
637 if kind == default_protocol() {
638 return Ok(());
639 }
640
641 Err(MaError::InvalidMessageType)
642}
643
644fn now_unix_secs() -> Result<u64> {
645 SystemTime::now()
646 .duration_since(UNIX_EPOCH)
647 .map(|duration| duration.as_secs())
648 .map_err(|_| MaError::InvalidMessageTimestamp)
649}
650
651fn validate_message_freshness(created_at: u64, exp: u64) -> Result<()> {
652 let now = now_unix_secs()?;
653
654 if created_at > now + DEFAULT_MAX_CLOCK_SKEW_SECS {
655 return Err(MaError::MessageFromFuture);
656 }
657
658 if exp == 0 {
659 return Ok(()); }
661
662 if now > exp + DEFAULT_MAX_CLOCK_SKEW_SECS {
663 return Err(MaError::MessageTooOld);
664 }
665
666 Ok(())
667}
668
669fn compute_shared_secret(
670 ephemeral_key_bytes: &[u8],
671 recipient_key: &EncryptionKey,
672) -> Result<[u8; 32]> {
673 let ephemeral_public = X25519PublicKey::from(
674 <[u8; 32]>::try_from(ephemeral_key_bytes)
675 .map_err(|_| MaError::InvalidEphemeralKeyLength)?,
676 );
677 Ok(recipient_key.shared_secret(&ephemeral_public))
678}
679
680fn derive_symmetric_key(shared_secret: &[u8; 32], label: &str) -> Key {
681 let derived = blake3::derive_key(label, shared_secret);
682 Key::from(derived)
683}
684
685fn encrypt(data: &[u8], key: Key) -> Result<Vec<u8>> {
686 let cipher = XChaCha20Poly1305::new(&key);
687 let nonce = XNonce::generate_from_rng(&mut UnwrapErr(SysRng));
688 let encrypted = cipher.encrypt(&nonce, data).map_err(|_| MaError::Crypto)?;
689
690 let mut out = nonce.to_vec();
691 out.extend_from_slice(&encrypted);
692 Ok(out)
693}
694
695fn decrypt(data: &[u8], shared_secret: &[u8; 32], label: &str) -> Result<Vec<u8>> {
696 if data.len() < 24 {
697 return Err(MaError::CiphertextTooShort);
698 }
699
700 let key = derive_symmetric_key(shared_secret, label);
701 let cipher = XChaCha20Poly1305::new(&key);
702 let nonce = XNonce::try_from(&data[..24]).map_err(|_| MaError::CiphertextTooShort)?;
703
704 cipher
705 .decrypt(&nonce, &data[24..])
706 .map_err(|_| MaError::Crypto)
707}
708
709fn content_hash(content: &[u8]) -> [u8; 32] {
710 blake3::hash(content).into()
711}
712
713#[cfg(test)]
714mod tests {
715 use super::*;
716 use crate::{doc::VerificationMethod, key::EncryptionKey};
717
718 fn fixture_documents() -> (
719 SigningKey,
720 EncryptionKey,
721 Document,
722 SigningKey,
723 EncryptionKey,
724 Document,
725 ) {
726 let sender_ipns = crate::ipns_from_secret([1; 32]).expect("sender ipns");
727 let sender_did = Did::new_url(&sender_ipns, None::<String>).expect("sender did");
728 let sender_sign_url = Did::new_url(&sender_ipns, None::<String>).expect("sender sign did");
729 let sender_enc_url = Did::new_url(&sender_ipns, None::<String>).expect("sender enc did");
730 let sender_signing = SigningKey::generate(sender_sign_url).expect("sender signing key");
731 let sender_encryption =
732 EncryptionKey::generate(sender_enc_url).expect("sender encryption key");
733
734 let recipient_ipns = crate::ipns_from_secret([2; 32]).expect("recipient ipns");
735 let recipient_did = Did::new_url(&recipient_ipns, None::<String>).expect("recipient did");
736 let recipient_sign_url =
737 Did::new_url(&recipient_ipns, None::<String>).expect("recipient sign did");
738 let recipient_enc_url =
739 Did::new_url(&recipient_ipns, None::<String>).expect("recipient enc did");
740 let recipient_signing =
741 SigningKey::generate(recipient_sign_url).expect("recipient signing key");
742 let recipient_encryption =
743 EncryptionKey::generate(recipient_enc_url).expect("recipient encryption key");
744
745 let mut sender_document = Document::new(&sender_did, &sender_did);
746 let sender_assertion = VerificationMethod::new(
747 sender_did.base_id(),
748 sender_did.base_id(),
749 sender_signing.key_type.clone(),
750 sender_signing.did.fragment.as_deref().unwrap_or_default(),
751 sender_signing.public_key_multibase.clone(),
752 )
753 .expect("sender assertion vm");
754 let sender_key_agreement = VerificationMethod::new(
755 sender_did.base_id(),
756 sender_did.base_id(),
757 sender_encryption.key_type.clone(),
758 sender_encryption
759 .did
760 .fragment
761 .as_deref()
762 .unwrap_or_default(),
763 sender_encryption.public_key_multibase.clone(),
764 )
765 .expect("sender key agreement vm");
766 sender_document
767 .add_verification_method(sender_assertion.clone())
768 .expect("add sender assertion");
769 sender_document
770 .add_verification_method(sender_key_agreement.clone())
771 .expect("add sender key agreement");
772 sender_document.assertion_method = vec![sender_assertion.id.clone()];
773 sender_document.key_agreement = vec![sender_key_agreement.id.clone()];
774 sender_document
775 .sign(&sender_signing, &sender_assertion)
776 .expect("sign sender doc");
777
778 let mut recipient_document = Document::new(&recipient_did, &recipient_did);
779 let recipient_assertion = VerificationMethod::new(
780 recipient_did.base_id(),
781 recipient_did.base_id(),
782 recipient_signing.key_type.clone(),
783 recipient_signing
784 .did
785 .fragment
786 .as_deref()
787 .unwrap_or_default(),
788 recipient_signing.public_key_multibase.clone(),
789 )
790 .expect("recipient assertion vm");
791 let recipient_key_agreement = VerificationMethod::new(
792 recipient_did.base_id(),
793 recipient_did.base_id(),
794 recipient_encryption.key_type.clone(),
795 recipient_encryption
796 .did
797 .fragment
798 .as_deref()
799 .unwrap_or_default(),
800 recipient_encryption.public_key_multibase.clone(),
801 )
802 .expect("recipient key agreement vm");
803 recipient_document
804 .add_verification_method(recipient_assertion.clone())
805 .expect("add recipient assertion");
806 recipient_document
807 .add_verification_method(recipient_key_agreement.clone())
808 .expect("add recipient key agreement");
809 recipient_document.assertion_method = vec![recipient_assertion.id.clone()];
810 recipient_document.key_agreement = vec![recipient_key_agreement.id.clone()];
811 recipient_document
812 .sign(&recipient_signing, &recipient_assertion)
813 .expect("sign recipient doc");
814
815 (
816 sender_signing,
817 sender_encryption,
818 sender_document,
819 recipient_signing,
820 recipient_encryption,
821 recipient_document,
822 )
823 }
824
825 fn inbox_url(document: &Document) -> String {
826 format!("{}#inbox", document.id)
827 }
828
829 #[test]
830 fn did_round_trip() {
831 let did = Did::new_url(
832 "k51qzi5uqu5dj9807pbuod1pplf0vxh8m4lfy3ewl9qbm2s8dsf9ugdf9gedhr",
833 Some("bahner"),
834 )
835 .expect("did must build");
836 let parsed = Did::try_from(did.id().as_str()).expect("did must parse");
837 assert_eq!(did, parsed);
838 }
839
840 #[test]
841 fn subject_url_round_trip() {
842 let did = Did::new_url(
843 "k51qzi5uqu5dj9807pbuod1pplf0vxh8m4lfy3ewl9qbm2s8dsf9ugdf9gedhr",
844 None::<String>,
845 )
846 .expect("subject did must build");
847 let parsed = Did::try_from(did.id().as_str()).expect("subject did must parse");
848 assert_eq!(did, parsed);
849 }
850
851 #[test]
852 fn document_signs_and_verifies() {
853 let (sender_signing, _, sender_document, _, _, _) = fixture_documents();
854 sender_signing.validate().expect("signing key validates");
855 sender_document.validate().expect("document validates");
856 }
857
858 #[test]
859 fn envelope_round_trip() {
860 let (sender_signing, _, sender_document, _, recipient_encryption, recipient_document) =
861 fixture_documents();
862 let message = Message::new(
863 sender_document.id.clone(),
864 inbox_url(&recipient_document),
865 "application/vnd.ma.message",
866 "text/plain",
867 b"look",
868 &sender_signing,
869 )
870 .expect("message creation");
871 message
872 .verify_with_document(&sender_document)
873 .expect("message signature verifies");
874
875 let envelope = message
876 .enclose_for(&recipient_document)
877 .expect("message encloses");
878 let opened = envelope
879 .open(&recipient_encryption, &sender_document)
880 .expect("envelope opens");
881
882 assert_eq!(opened.payload(), b"look");
883 assert_eq!(opened.from, sender_document.id);
884 assert_eq!(opened.to, inbox_url(&recipient_document));
885 }
886
887 #[test]
888 fn tampered_content_fails_signature_verification() {
889 let (sender_signing, _, sender_document, _, _, recipient_document) = fixture_documents();
890 let mut message = Message::new(
891 sender_document.id.clone(),
892 inbox_url(&recipient_document),
893 "application/vnd.ma.message",
894 "text/plain",
895 b"look",
896 &sender_signing,
897 )
898 .expect("message creation");
899
900 message.content = b"tampered".to_vec();
901 let result = message.verify_with_document(&sender_document);
902 assert!(matches!(result, Err(MaError::InvalidMessageSignature)));
903 }
904
905 #[test]
906 fn reply_constructor_signs_correlation_header() {
907 let (sender_signing, _, sender_document, _, _, recipient_document) = fixture_documents();
908 let mut reply = Message::new_reply(
909 sender_document.id.clone(),
910 inbox_url(&recipient_document),
911 "application/vnd.ma.rpc.reply",
912 "application/vnd.ma.term",
913 b":ok",
914 "request-id",
915 &sender_signing,
916 )
917 .expect("reply creation");
918
919 reply
920 .verify_with_document(&sender_document)
921 .expect("reply signature covers replyTo");
922 assert_eq!(reply.reply_to.as_deref(), Some("request-id"));
923
924 reply.reply_to = Some("different-request-id".to_string());
925 assert!(matches!(
926 reply.verify_with_document(&sender_document),
927 Err(MaError::InvalidMessageSignature)
928 ));
929 }
930
931 #[test]
932 fn stale_message_is_rejected() {
933 let (sender_signing, _, sender_document, _, _, recipient_document) = fixture_documents();
934 let mut message = Message::new(
935 sender_document.id.clone(),
936 inbox_url(&recipient_document),
937 "application/vnd.ma.message",
938 "text/plain",
939 b"look",
940 &sender_signing,
941 )
942 .expect("message creation");
943
944 message.created_at = 0;
945 message.exp = 1; message
947 .sign(&sender_signing)
948 .expect("re-sign with past timestamps");
949 let result = message.verify_with_document(&sender_document);
950 assert!(matches!(result, Err(MaError::MessageTooOld)));
951 }
952
953 #[test]
954 fn future_message_is_rejected() {
955 let (sender_signing, _, sender_document, _, _, recipient_document) = fixture_documents();
956 let mut message = Message::new(
957 sender_document.id.clone(),
958 inbox_url(&recipient_document),
959 "application/vnd.ma.message",
960 "text/plain",
961 b"look",
962 &sender_signing,
963 )
964 .expect("message creation");
965
966 message.created_at =
967 now_unix_secs().expect("current timestamp") + DEFAULT_MAX_CLOCK_SKEW_SECS + 60;
968 message
969 .sign(&sender_signing)
970 .expect("re-sign with updated timestamp");
971
972 let result = message.verify_with_document(&sender_document);
973 assert!(matches!(result, Err(MaError::MessageFromFuture)));
974 }
975
976 #[test]
977 fn exp_zero_disables_expiration() {
978 let (sender_signing, _, sender_document, _, _, recipient_document) = fixture_documents();
979 let mut message = Message::new(
980 sender_document.id.clone(),
981 inbox_url(&recipient_document),
982 "application/vnd.ma.message",
983 "text/plain",
984 b"look",
985 &sender_signing,
986 )
987 .expect("message creation");
988
989 message.created_at = 0;
990 message.exp = 0; message.sign(&sender_signing).expect("re-sign with exp=0");
992
993 message
994 .verify_with_document(&sender_document)
995 .expect("exp=0 should bypass expiration check");
996 }
997
998 #[test]
999 fn custom_ttl_rejects_expired_message() {
1000 let (sender_signing, _, sender_document, _, _, recipient_document) = fixture_documents();
1001 let now_secs = now_unix_secs().expect("current timestamp");
1002 let mut message = Message::new_with_exp(
1004 sender_document.id.clone(),
1005 inbox_url(&recipient_document),
1006 "application/vnd.ma.message",
1007 "text/plain",
1008 b"look",
1009 now_secs + 60,
1010 &sender_signing,
1011 )
1012 .expect("message creation with custom exp");
1013
1014 message.exp = 1;
1016 message
1017 .sign(&sender_signing)
1018 .expect("re-sign with expired exp");
1019
1020 let result = message.verify_with_document(&sender_document);
1021 assert!(matches!(result, Err(MaError::MessageTooOld)));
1022 }
1023
1024 #[test]
1025 fn replay_guard_rejects_duplicate_envelope() {
1026 let (sender_signing, _, sender_document, _, recipient_encryption, recipient_document) =
1027 fixture_documents();
1028 let message = Message::new(
1029 sender_document.id.clone(),
1030 inbox_url(&recipient_document),
1031 "application/vnd.ma.message",
1032 "text/plain",
1033 b"look",
1034 &sender_signing,
1035 )
1036 .expect("message creation");
1037
1038 let envelope = message
1039 .enclose_for(&recipient_document)
1040 .expect("message encloses");
1041 let mut replay_guard = ReplayGuard::default();
1042
1043 envelope
1044 .open_with_replay_guard(&recipient_encryption, &sender_document, &mut replay_guard)
1045 .expect("first delivery accepted");
1046
1047 let second = envelope.open_with_replay_guard(
1048 &recipient_encryption,
1049 &sender_document,
1050 &mut replay_guard,
1051 );
1052 assert!(matches!(second, Err(MaError::ReplayDetected)));
1053 }
1054
1055 #[test]
1056 fn rejected_envelope_does_not_consume_replay_id() {
1057 let (sender_signing, _, sender_document, _, recipient_encryption, recipient_document) =
1058 fixture_documents();
1059 let message = Message::new(
1060 sender_document.id.clone(),
1061 inbox_url(&recipient_document),
1062 "application/vnd.ma.message",
1063 "text/plain",
1064 b"look",
1065 &sender_signing,
1066 )
1067 .expect("message creation");
1068 let envelope = message
1069 .enclose_for(&recipient_document)
1070 .expect("message encloses");
1071 let mut tampered = envelope.clone();
1072 tampered.encrypted_content[0] ^= 0xff;
1073 let mut guard = ReplayGuard::default();
1074
1075 assert!(tampered
1076 .open_with_replay_guard(&recipient_encryption, &sender_document, &mut guard,)
1077 .is_err());
1078
1079 envelope
1080 .open_with_replay_guard(&recipient_encryption, &sender_document, &mut guard)
1081 .expect("valid envelope remains acceptable");
1082 }
1083
1084 #[test]
1085 fn broadcast_allows_empty_recipient() {
1086 let (sender_signing, _, sender_document, _, _, _) = fixture_documents();
1087 let message = Message::new(
1088 sender_document.id.clone(),
1089 String::new(),
1090 "application/vnd.ma.broadcast",
1091 "text/plain",
1092 b"hello everyone",
1093 &sender_signing,
1094 )
1095 .expect("broadcast message creation");
1096
1097 message
1098 .verify_with_document(&sender_document)
1099 .expect("broadcast with empty recipient verifies");
1100 }
1101
1102 #[test]
1103 fn broadcast_rejects_recipient() {
1104 let (sender_signing, _, sender_document, _, _, recipient_document) = fixture_documents();
1105 let result = Message::new(
1106 sender_document.id.clone(),
1107 inbox_url(&recipient_document),
1108 "application/vnd.ma.broadcast",
1109 "text/plain",
1110 b"hello everyone",
1111 &sender_signing,
1112 );
1113
1114 assert!(matches!(
1115 result,
1116 Err(MaError::BroadcastMustNotHaveRecipient)
1117 ));
1118 }
1119
1120 #[test]
1121 fn message_requires_recipient() {
1122 let (sender_signing, _, sender_document, _, _, _) = fixture_documents();
1123 let result = Message::new(
1124 sender_document.id.clone(),
1125 String::new(),
1126 "application/vnd.ma.message",
1127 "text/plain",
1128 b"secret",
1129 &sender_signing,
1130 );
1131
1132 assert!(matches!(result, Err(MaError::MessageRequiresRecipient)));
1133 }
1134
1135 #[test]
1136 fn message_accepts_bare_did_recipient() {
1137 let (sender_signing, _, sender_document, _, _, recipient_document) = fixture_documents();
1138 Message::new(
1139 sender_document.id.clone(),
1140 recipient_document.id,
1141 "application/vnd.ma.message",
1142 "text/plain",
1143 b"secret",
1144 &sender_signing,
1145 )
1146 .expect("bare DID recipient is a valid DID URL");
1147 }
1148
1149 #[test]
1150 fn custom_message_requires_recipient() {
1151 let (sender_signing, _, sender_document, _, _, _) = fixture_documents();
1152 let result = Message::new(
1153 sender_document.id.clone(),
1154 String::new(),
1155 "application/x-ma-custom",
1156 "text/plain",
1157 b"whatever",
1158 &sender_signing,
1159 );
1160
1161 assert!(matches!(result, Err(MaError::MessageRequiresRecipient)));
1162 }
1163
1164 #[test]
1165 fn unknown_content_type_allows_recipient() {
1166 let (sender_signing, _, sender_document, _, _, recipient_document) = fixture_documents();
1167 let message = Message::new(
1168 sender_document.id.clone(),
1169 inbox_url(&recipient_document),
1170 "application/x-ma-custom",
1171 "text/plain",
1172 b"whatever",
1173 &sender_signing,
1174 )
1175 .expect("custom content type with recipient");
1176
1177 message
1178 .verify_with_document(&sender_document)
1179 .expect("custom type with recipient verifies");
1180 }
1181}