openmls 0.9.0-rc.1

A Rust implementation of the Messaging Layer Security (MLS) protocol, as defined in RFC 9420.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
//! # Targeted Messages (draft-ietf-mls-targeted-messages)
//!
//! This module implements the MLS targeted messages extension, which allows
//! a group member to send an HPKE-encrypted message to a specific member
//! of the group. The message is authenticated using the group's PSK and
//! the sender's signature key.

mod errors;

#[cfg(test)]
pub mod kat;

#[cfg(test)]
mod tests;

pub use errors::*;

use openmls_traits::{
    crypto::OpenMlsCrypto,
    signatures::Signer,
    types::{Ciphersuite, HpkeCiphertext},
};
use serde::{Deserialize, Serialize};
use tls_codec::{
    DeserializeBytes, Serialize as TlsSerializeTrait, Size, TlsDeserialize, TlsDeserializeBytes,
    TlsSerialize, TlsSize, VLByteSlice, VLBytes,
};

use crate::{
    binary_tree::array_representation::LeafNodeIndex,
    ciphersuite::{
        signable::{Signable, SignedStruct, Verifiable, VerifiedStruct},
        AeadKey, AeadNonce, OpenMlsSignaturePublicKey, Secret, Signature,
    },
    error::LibraryError,
    framing::WireFormat,
    group::{GroupEpoch, GroupId},
    treesync::node::{
        encryption_keys::{EncryptionKey, EncryptionPrivateKey},
        leaf_node::LeafNode,
    },
    versions::ProtocolVersion,
};

const TARGETED_MESSAGE_EXPORTER_LABEL: &str = "targeted message";
const PSK_SUBLABEL: &str = "psk";
const SENDER_AUTH_DATA_SECRET_SUBLABEL: &str = "sender auth data secret";
const TARGETED_MESSAGE_TBS_LABEL: &str = "TargetedMessageTBS";
const TARGETED_MESSAGE_DATA_LABEL: &str = "TargetedMessageData";
const PSK_LABEL: &str = "MLS 1.0 targeted message psk";

/// A targeted message as defined in draft-ietf-mls-targeted-messages.
///
/// ```text
/// struct {
///   opaque group_id<V>;
///   uint64 epoch;
///   uint32 recipient_leaf_index;
///   opaque authenticated_data<V>;
///   opaque encrypted_sender_auth_data<V>;
///   opaque ciphertext<V>;
/// } TargetedMessage;
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TlsSerialize, TlsSize)]
pub struct TargetedMessage {
    pub(crate) group_id: GroupId,
    pub(crate) epoch: GroupEpoch,
    pub(crate) recipient_leaf_index: u32,
    pub(crate) authenticated_data: VLBytes,
    pub(crate) encrypted_sender_auth_data: VLBytes,
    pub(crate) ciphertext: VLBytes,
}

impl TargetedMessage {
    /// Returns the group ID.
    pub fn group_id(&self) -> &GroupId {
        &self.group_id
    }

    /// Returns the epoch.
    pub fn epoch(&self) -> GroupEpoch {
        self.epoch
    }

    /// Returns the recipient leaf index.
    pub fn recipient_leaf_index(&self) -> u32 {
        self.recipient_leaf_index
    }

    /// Returns the authenticated data.
    pub fn authenticated_data(&self) -> &[u8] {
        self.authenticated_data.as_slice()
    }
}

/// A received targeted message, used as input for processing.
#[derive(Debug, Clone, PartialEq, TlsSerialize, TlsDeserialize, TlsDeserializeBytes, TlsSize)]
pub struct TargetedMessageIn {
    pub(crate) group_id: GroupId,
    pub(crate) epoch: GroupEpoch,
    pub(crate) recipient_leaf_index: u32,
    pub(crate) authenticated_data: VLBytes,
    pub(crate) encrypted_sender_auth_data: VLBytes,
    pub(crate) ciphertext: VLBytes,
}

impl TargetedMessageIn {
    /// Returns the group ID.
    pub fn group_id(&self) -> &GroupId {
        &self.group_id
    }

    /// Returns the epoch.
    pub fn epoch(&self) -> GroupEpoch {
        self.epoch
    }

    /// Returns the recipient leaf index.
    pub fn recipient_leaf_index(&self) -> u32 {
        self.recipient_leaf_index
    }

    /// Returns the authenticated data.
    pub fn authenticated_data(&self) -> &[u8] {
        self.authenticated_data.as_slice()
    }
}

#[cfg(any(feature = "test-utils", test))]
impl From<TargetedMessageIn> for TargetedMessage {
    fn from(msg: TargetedMessageIn) -> Self {
        Self {
            group_id: msg.group_id,
            epoch: msg.epoch,
            recipient_leaf_index: msg.recipient_leaf_index,
            authenticated_data: msg.authenticated_data,
            encrypted_sender_auth_data: msg.encrypted_sender_auth_data,
            ciphertext: msg.ciphertext,
        }
    }
}

impl From<TargetedMessage> for TargetedMessageIn {
    fn from(msg: TargetedMessage) -> Self {
        Self {
            group_id: msg.group_id,
            epoch: msg.epoch,
            recipient_leaf_index: msg.recipient_leaf_index,
            authenticated_data: msg.authenticated_data,
            encrypted_sender_auth_data: msg.encrypted_sender_auth_data,
            ciphertext: msg.ciphertext,
        }
    }
}

/// The plaintext content of a targeted message.
///
/// ```text
/// struct {
///   opaque application_data<V>;
///   opaque padding[length_of_padding];
/// } TargetedMessageContent;
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct TargetedMessageContent {
    application_data: VLBytes,
    padding_length: usize,
}

impl TargetedMessageContent {
    fn new(data: &[u8], padding_length: usize) -> Self {
        Self {
            application_data: data.into(),
            padding_length,
        }
    }

    pub(crate) fn application_data(&self) -> &[u8] {
        self.application_data.as_slice()
    }

    /// Serialize to bytes: VLBytes application_data followed by raw zero
    /// padding (no length prefix on the padding).
    fn serialize_detached(&self) -> Result<Vec<u8>, tls_codec::Error> {
        use std::io::Write;
        let app_data_len = self.application_data.tls_serialized_len();
        // Guard against overflow and against exceeding Rust's allocation limit
        // of isize::MAX bytes, since padding_length is caller-controlled.
        let total_len = app_data_len
            .checked_add(self.padding_length)
            .filter(|&len| len <= isize::MAX as usize)
            .ok_or_else(|| {
                tls_codec::Error::EncodingError(
                    "Targeted message content exceeds the maximum size.".into(),
                )
            })?;
        let mut buffer = Vec::with_capacity(total_len);
        self.application_data.tls_serialize(&mut buffer)?;
        buffer
            .write_all(&vec![0u8; self.padding_length])
            .map_err(|e| {
                tls_codec::Error::EncodingError(format!("Failed to write padding: {e}"))
            })?;
        Ok(buffer)
    }

    /// Deserialize: read VLBytes application_data, treat remaining bytes as
    /// raw padding, and validate all padding bytes are zero.
    fn deserialize_detached(bytes: &[u8]) -> Result<Self, tls_codec::Error> {
        let (application_data, rest) = VLBytes::tls_deserialize_bytes(bytes)?;
        if !rest.iter().all(|&b| b == 0x00) {
            return Err(tls_codec::Error::DecodingError(
                "Non-zero padding in TargetedMessageContent".into(),
            ));
        }
        Ok(Self {
            application_data,
            padding_length: rest.len(),
        })
    }
}

/// Sender authentication data, encrypted within the targeted message.
///
/// ```text
/// struct {
///   uint32 sender_leaf_index;
///   opaque signature<V>;
///   opaque kem_output<V>;
/// } TargetedMessageSenderAuthData;
/// ```
#[derive(Debug, Clone, PartialEq, TlsSerialize, TlsDeserialize, TlsDeserializeBytes, TlsSize)]
struct TargetedMessageSenderAuthData {
    sender_leaf_index: u32,
    signature: Signature,
    kem_output: VLBytes,
}

/// AAD for encrypting sender authentication data.
///
/// ```text
/// struct {
///   opaque group_id<V>;
///   uint64 epoch;
///   uint32 recipient_leaf_index;
/// } SenderAuthDataAAD;
/// ```
#[derive(TlsSerialize, TlsSize)]
struct SenderAuthDataAAD<'a> {
    group_id: &'a GroupId,
    epoch: GroupEpoch,
    recipient_leaf_index: u32,
}

/// The part of targeted messages that is authenticated with a signature. The
/// `ciphertext_hash` field binds the signature to the encrypted message
/// content.
///
/// ```text
/// struct {
///   ProtocolVersion version = mls10;
///   WireFormat wire_format = mls_targeted_message;
///   opaque group_id<V>;
///   uint64 epoch;
///   uint32 recipient_leaf_index;
///   opaque authenticated_data<V>;
///   uint32 sender_leaf_index;
///   opaque kem_output<V>;
///   opaque ciphertext_hash<V>;
/// } TargetedMessageTBS;
/// ```
#[derive(TlsSerialize, TlsSize)]
struct TargetedMessageTBS<'a> {
    version: ProtocolVersion,
    wire_format: WireFormat,
    group_id: &'a GroupId,
    epoch: GroupEpoch,
    recipient_leaf_index: u32,
    authenticated_data: VLByteSlice<'a>,
    sender_leaf_index: u32,
    kem_output: VLByteSlice<'a>,
    ciphertext_hash: VLByteSlice<'a>,
}

/// The part of targeted messages that is authenticated with a MAC (used as AAD
/// for the HPKE operation).
///
/// ```text
/// struct {
///   opaque group_id<V>;
///   uint64 epoch;
///   uint32 recipient_leaf_index;
///   opaque authenticated_data<V>;
///   uint32 sender_leaf_index;
///   opaque kem_output<V>;
/// } TargetedMessageTBM;
/// ```
#[derive(TlsSerialize, TlsSize)]
struct TargetedMessageTBM<'a> {
    group_id: &'a GroupId,
    epoch: GroupEpoch,
    recipient_leaf_index: u32,
    authenticated_data: VLByteSlice<'a>,
    sender_leaf_index: u32,
    kem_output: VLByteSlice<'a>,
}

/// PSK ID for the targeted message HPKE PSK mode.
///
/// ```text
/// struct {
///   opaque group_id<V>;
///   uint64 epoch;
///   opaque label<V> = "MLS 1.0 targeted message psk";
/// } PSKId;
/// ```
#[derive(TlsSerialize, TlsSize)]
struct TargetedMessagePskId<'a> {
    group_id: &'a GroupId,
    epoch: GroupEpoch,
    label: VLByteSlice<'a>,
}

impl<'a> TargetedMessagePskId<'a> {
    fn new(group_id: &'a GroupId, epoch: GroupEpoch) -> Self {
        Self {
            group_id,
            epoch,
            label: VLByteSlice(PSK_LABEL.as_bytes()),
        }
    }
}

/// Group-level context needed for targeted message operations. The group
/// state is bound through the exporter-derived PSK, so no serialized
/// GroupContext is needed.
pub(crate) struct TargetedMessageGroupContext<'a> {
    pub ciphersuite: Ciphersuite,
    pub group_id: &'a GroupId,
    pub epoch: GroupEpoch,
    pub exporter_secret: &'a crate::schedule::ExporterSecret,
}

/// Verified targeted message content, returned after successful processing.
#[derive(Debug, Clone, PartialEq)]
pub struct ProcessedTargetedMessage {
    sender_leaf_index: LeafNodeIndex,
    application_data: Vec<u8>,
    authenticated_data: Vec<u8>,
}

impl ProcessedTargetedMessage {
    /// Returns the sender's leaf index.
    pub fn sender_leaf_index(&self) -> LeafNodeIndex {
        self.sender_leaf_index
    }

    /// Returns the application data payload.
    pub fn application_data(&self) -> &[u8] {
        &self.application_data
    }

    /// Returns the authenticated data.
    pub fn authenticated_data(&self) -> &[u8] {
        &self.authenticated_data
    }

    /// Returns both the application data and authenticated data.
    pub fn into_data(self) -> (Vec<u8>, Vec<u8>) {
        (self.application_data, self.authenticated_data)
    }
}

/// Derive the targeted message PSK from the MLS exporter.
fn derive_targeted_message_psk(
    crypto: &impl OpenMlsCrypto,
    ciphersuite: Ciphersuite,
    exporter_secret: &crate::schedule::ExporterSecret,
) -> Result<Vec<u8>, LibraryError> {
    exporter_secret
        .derive_exported_secret(
            ciphersuite,
            crypto,
            TARGETED_MESSAGE_EXPORTER_LABEL,
            PSK_SUBLABEL.as_bytes(),
            ciphersuite.hash_length(),
        )
        .map_err(LibraryError::unexpected_crypto_error)
}

/// Derive the sender auth data secret from the MLS exporter.
fn derive_sender_auth_data_secret(
    crypto: &impl OpenMlsCrypto,
    ciphersuite: Ciphersuite,
    exporter_secret: &crate::schedule::ExporterSecret,
) -> Result<Secret, LibraryError> {
    let secret_bytes = exporter_secret
        .derive_exported_secret(
            ciphersuite,
            crypto,
            TARGETED_MESSAGE_EXPORTER_LABEL,
            SENDER_AUTH_DATA_SECRET_SUBLABEL.as_bytes(),
            ciphersuite.hash_length(),
        )
        .map_err(LibraryError::unexpected_crypto_error)?;
    Ok(Secret::from_slice(&secret_bytes))
}

/// Derive sender auth data key and nonce from the ciphertext sample.
fn derive_sender_auth_data_key_nonce(
    crypto: &impl OpenMlsCrypto,
    ciphersuite: Ciphersuite,
    sender_auth_data_secret: &Secret,
    ciphertext: &[u8],
) -> Result<(AeadKey, AeadNonce), LibraryError> {
    let sample_len = ciphersuite.hash_length().min(ciphertext.len());
    let ciphertext_sample = &ciphertext[..sample_len];

    let key_secret = sender_auth_data_secret
        .kdf_expand_label(
            crypto,
            ciphersuite,
            "key",
            ciphertext_sample,
            ciphersuite.aead_key_length(),
        )
        .map_err(LibraryError::unexpected_crypto_error)?;

    let nonce_secret = sender_auth_data_secret
        .kdf_expand_label(
            crypto,
            ciphersuite,
            "nonce",
            ciphertext_sample,
            ciphersuite.aead_nonce_length(),
        )
        .map_err(LibraryError::unexpected_crypto_error)?;

    Ok((
        AeadKey::from_secret(key_secret, ciphersuite),
        AeadNonce::from_secret(nonce_secret),
    ))
}

/// Wraps a TBS struct for use with the Signable/Verifiable traits.
struct TargetedMessageTBSPayload {
    serialized: Vec<u8>,
}

impl Signable for TargetedMessageTBSPayload {
    type SignedOutput = TargetedMessageSignature;

    fn unsigned_payload(&self) -> Result<Vec<u8>, tls_codec::Error> {
        Ok(self.serialized.clone())
    }

    fn label(&self) -> &str {
        TARGETED_MESSAGE_TBS_LABEL
    }
}

struct TargetedMessageSignature(pub(crate) Signature);

impl SignedStruct<TargetedMessageTBSPayload> for TargetedMessageSignature {
    fn from_payload(
        _payload: TargetedMessageTBSPayload,
        signature: Signature,
        _serialized_payload: Vec<u8>,
    ) -> Self {
        Self(signature)
    }
}

/// Wraps a TBS struct for verification.
struct VerifiableTargetedMessageTBS {
    serialized: Vec<u8>,
    signature: Signature,
}

impl Verifiable for VerifiableTargetedMessageTBS {
    type VerifiedStruct = VerifiedTargetedMessage;

    fn unsigned_payload(&self) -> Result<Vec<u8>, tls_codec::Error> {
        Ok(self.serialized.clone())
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn label(&self) -> &str {
        TARGETED_MESSAGE_TBS_LABEL
    }

    fn verify(
        self,
        crypto: &impl OpenMlsCrypto,
        pk: &crate::ciphersuite::OpenMlsSignaturePublicKey,
    ) -> Result<Self::VerifiedStruct, crate::ciphersuite::signable::SignatureError> {
        self.verify_no_out(crypto, pk)?;
        Ok(VerifiedTargetedMessage)
    }
}

struct VerifiedTargetedMessage;
impl VerifiedStruct for VerifiedTargetedMessage {}

/// Create a targeted message.
#[allow(clippy::too_many_arguments)]
pub(crate) fn create_targeted_message(
    crypto: &impl OpenMlsCrypto,
    signer: &impl Signer,
    ctx: &TargetedMessageGroupContext<'_>,
    sender_leaf_index: LeafNodeIndex,
    recipient_leaf_index: LeafNodeIndex,
    recipient_encryption_key: &EncryptionKey,
    authenticated_data: &[u8],
    application_data: &[u8],
    padding_length: usize,
) -> Result<TargetedMessage, CreateTargetedMessageError> {
    let psk = derive_targeted_message_psk(crypto, ctx.ciphersuite, ctx.exporter_secret)?;
    let sender_auth_data_secret =
        derive_sender_auth_data_secret(crypto, ctx.ciphersuite, ctx.exporter_secret)?;

    let psk_id = TargetedMessagePskId::new(ctx.group_id, ctx.epoch);
    let psk_id_bytes = psk_id
        .tls_serialize_detached()
        .map_err(LibraryError::missing_bound_check)?;

    let content = TargetedMessageContent::new(application_data, padding_length);
    let content_bytes = content
        .serialize_detached()
        .map_err(LibraryError::missing_bound_check)?;

    let hpke_ct = recipient_encryption_key.encrypt_with_label_psk_resolved_aad(
        crate::ciphersuite::hpke::PskEncryptParams {
            label: TARGETED_MESSAGE_DATA_LABEL,
            // The group state is bound through the PSK, so the context stays
            // empty.
            context: &[],
            psk: &psk,
            psk_id: &psk_id_bytes,
            ciphersuite: ctx.ciphersuite,
        },
        &content_bytes,
        crypto,
        |kem_output| {
            let tbm = TargetedMessageTBM {
                group_id: ctx.group_id,
                epoch: ctx.epoch,
                recipient_leaf_index: recipient_leaf_index.u32(),
                authenticated_data: VLByteSlice(authenticated_data),
                sender_leaf_index: sender_leaf_index.u32(),
                kem_output: VLByteSlice(kem_output),
            };
            tbm.tls_serialize_detached()
                .map_err(LibraryError::missing_bound_check)
        },
    )?;

    // The signature covers the ciphertext through its hash, so it can only be
    // computed after the HPKE encryption.
    let ciphertext_hash = crypto
        .hash(
            ctx.ciphersuite.hash_algorithm(),
            hpke_ct.ciphertext.as_slice(),
        )
        .map_err(LibraryError::unexpected_crypto_error)?;

    let tbs = TargetedMessageTBS {
        version: ProtocolVersion::default(),
        wire_format: WireFormat::TargetedMessage,
        group_id: ctx.group_id,
        epoch: ctx.epoch,
        recipient_leaf_index: recipient_leaf_index.u32(),
        authenticated_data: VLByteSlice(authenticated_data),
        sender_leaf_index: sender_leaf_index.u32(),
        kem_output: VLByteSlice(hpke_ct.kem_output.as_slice()),
        ciphertext_hash: VLByteSlice(&ciphertext_hash),
    };
    let tbs_bytes = tbs
        .tls_serialize_detached()
        .map_err(LibraryError::missing_bound_check)?;

    let tbs_payload = TargetedMessageTBSPayload {
        serialized: tbs_bytes,
    };
    let signature = tbs_payload.sign(signer).map_err(|e| {
        log::error!("Signing targeted message failed: {e:?}");
        LibraryError::custom("Signing targeted message failed")
    })?;

    let sender_auth_data = TargetedMessageSenderAuthData {
        sender_leaf_index: sender_leaf_index.u32(),
        signature: signature.0,
        kem_output: hpke_ct.kem_output.as_slice().to_vec().into(),
    };
    let sender_auth_data_bytes = sender_auth_data
        .tls_serialize_detached()
        .map_err(LibraryError::missing_bound_check)?;

    // Encrypt sender auth data
    let (key, nonce) = derive_sender_auth_data_key_nonce(
        crypto,
        ctx.ciphersuite,
        &sender_auth_data_secret,
        hpke_ct.ciphertext.as_slice(),
    )?;

    let sender_auth_aad = SenderAuthDataAAD {
        group_id: ctx.group_id,
        epoch: ctx.epoch,
        recipient_leaf_index: recipient_leaf_index.u32(),
    };
    let sender_auth_aad_bytes = sender_auth_aad
        .tls_serialize_detached()
        .map_err(LibraryError::missing_bound_check)?;

    let encrypted_sender_auth_data = key
        .aead_seal(
            crypto,
            &sender_auth_data_bytes,
            &sender_auth_aad_bytes,
            &nonce,
        )
        .map_err(LibraryError::unexpected_crypto_error)?;

    Ok(TargetedMessage {
        group_id: ctx.group_id.clone(),
        epoch: ctx.epoch,
        recipient_leaf_index: recipient_leaf_index.u32(),
        authenticated_data: authenticated_data.to_vec().into(),
        encrypted_sender_auth_data: encrypted_sender_auth_data.into(),
        ciphertext: hpke_ct.ciphertext,
    })
}

/// Process (decrypt and verify) a targeted message.
pub(crate) fn process_targeted_message<StorageError>(
    crypto: &impl OpenMlsCrypto,
    ctx: &TargetedMessageGroupContext<'_>,
    own_leaf_index: LeafNodeIndex,
    own_encryption_private_key: &EncryptionPrivateKey,
    message: &TargetedMessageIn,
    leaves: &[Option<&LeafNode>],
) -> Result<ProcessedTargetedMessage, ProcessTargetedMessageError<StorageError>> {
    // Validate group_id
    if &message.group_id != ctx.group_id {
        return Err(ProcessTargetedMessageError::GroupIdMismatch);
    }

    // Validate epoch
    if message.epoch != ctx.epoch {
        return Err(ProcessTargetedMessageError::EpochMismatch);
    }

    // Validate recipient
    if message.recipient_leaf_index != own_leaf_index.u32() {
        return Err(ProcessTargetedMessageError::NotIntendedRecipient);
    }

    let sender_auth_data_secret =
        derive_sender_auth_data_secret(crypto, ctx.ciphersuite, ctx.exporter_secret)?;

    // Derive key/nonce for sender auth data decryption
    let (key, nonce) = derive_sender_auth_data_key_nonce(
        crypto,
        ctx.ciphersuite,
        &sender_auth_data_secret,
        message.ciphertext.as_slice(),
    )?;

    let sender_auth_aad = SenderAuthDataAAD {
        group_id: ctx.group_id,
        epoch: ctx.epoch,
        recipient_leaf_index: own_leaf_index.u32(),
    };
    let sender_auth_aad_bytes = sender_auth_aad
        .tls_serialize_detached()
        .map_err(LibraryError::missing_bound_check)?;

    // Decrypt sender auth data
    let sender_auth_data_bytes = key
        .aead_open(
            crypto,
            message.encrypted_sender_auth_data.as_slice(),
            &sender_auth_aad_bytes,
            &nonce,
        )
        .map_err(|e| {
            log::error!("Targeted message sender auth data decryption failed: {e:?}");
            ProcessTargetedMessageError::SenderAuthDataDecryptionFailed
        })?;

    let sender_auth_data =
        TargetedMessageSenderAuthData::tls_deserialize_exact_bytes(&sender_auth_data_bytes)
            .map_err(|e| {
                log::error!("Targeted message sender auth data is malformed: {e:?}");
                ProcessTargetedMessageError::MalformedSenderAuthData
            })?;

    let sender_leaf_index = LeafNodeIndex::new(sender_auth_data.sender_leaf_index);

    let sender_leaf = leaves
        .get(sender_leaf_index.usize())
        .and_then(|opt| opt.as_ref())
        .ok_or(ProcessTargetedMessageError::SenderNotFound)?;
    let sender_signature_key = OpenMlsSignaturePublicKey::from_signature_key(
        sender_leaf.signature_key().clone(),
        ctx.ciphersuite.signature_algorithm(),
    );

    // Verify signature over TBS. The ciphertext hash is computed from the
    // wire-format ciphertext, so verification does not require decryption.
    let ciphertext_hash = crypto
        .hash(
            ctx.ciphersuite.hash_algorithm(),
            message.ciphertext.as_slice(),
        )
        .map_err(LibraryError::unexpected_crypto_error)?;

    let tbs = TargetedMessageTBS {
        version: ProtocolVersion::default(),
        wire_format: WireFormat::TargetedMessage,
        group_id: ctx.group_id,
        epoch: ctx.epoch,
        recipient_leaf_index: own_leaf_index.u32(),
        authenticated_data: VLByteSlice(message.authenticated_data.as_slice()),
        sender_leaf_index: sender_auth_data.sender_leaf_index,
        kem_output: VLByteSlice(sender_auth_data.kem_output.as_slice()),
        ciphertext_hash: VLByteSlice(&ciphertext_hash),
    };
    let tbs_bytes = tbs
        .tls_serialize_detached()
        .map_err(LibraryError::missing_bound_check)?;

    let verifiable = VerifiableTargetedMessageTBS {
        serialized: tbs_bytes,
        signature: sender_auth_data.signature.clone(),
    };

    verifiable
        .verify(crypto, &sender_signature_key)
        .map_err(|e| {
            log::error!("Targeted message signature verification failed: {e:?}");
            ProcessTargetedMessageError::SignatureVerificationFailed
        })?;

    // Decrypt the content via HPKE PSK open
    let psk = derive_targeted_message_psk(crypto, ctx.ciphersuite, ctx.exporter_secret)?;

    let psk_id = TargetedMessagePskId::new(ctx.group_id, ctx.epoch);
    let psk_id_bytes = psk_id
        .tls_serialize_detached()
        .map_err(LibraryError::missing_bound_check)?;

    let tbm = TargetedMessageTBM {
        group_id: ctx.group_id,
        epoch: ctx.epoch,
        recipient_leaf_index: own_leaf_index.u32(),
        authenticated_data: VLByteSlice(message.authenticated_data.as_slice()),
        sender_leaf_index: sender_auth_data.sender_leaf_index,
        kem_output: VLByteSlice(sender_auth_data.kem_output.as_slice()),
    };
    let tbm_bytes = tbm
        .tls_serialize_detached()
        .map_err(LibraryError::missing_bound_check)?;

    let hpke_ciphertext = HpkeCiphertext {
        kem_output: sender_auth_data.kem_output.as_slice().to_vec().into(),
        ciphertext: message.ciphertext.as_slice().to_vec().into(),
    };

    let content_bytes = own_encryption_private_key
        .decrypt_with_label_psk_aad(
            crate::ciphersuite::hpke::PskEncryptParams {
                label: TARGETED_MESSAGE_DATA_LABEL,
                // The group state is bound through the PSK, so the context
                // stays empty.
                context: &[],
                psk: &psk,
                psk_id: &psk_id_bytes,
                ciphersuite: ctx.ciphersuite,
            },
            &tbm_bytes,
            &hpke_ciphertext,
            crypto,
        )
        .map_err(|e| {
            log::error!("Targeted message content decryption failed: {e:?}");
            ProcessTargetedMessageError::ContentDecryptionFailed
        })?;

    let content = TargetedMessageContent::deserialize_detached(&content_bytes).map_err(|e| {
        log::error!("Targeted message content is malformed: {e:?}");
        ProcessTargetedMessageError::MalformedContent
    })?;

    Ok(ProcessedTargetedMessage {
        sender_leaf_index,
        application_data: content.application_data().to_vec(),
        authenticated_data: message.authenticated_data.as_slice().to_vec(),
    })
}