openmls/framing/
codec.rs

1use std::io::Read;
2use tls_codec::{Deserialize, Size};
3
4use crate::versions::ProtocolVersion;
5
6use super::{
7    mls_auth_content::FramedContentAuthData, mls_content_in::FramedContentBodyIn,
8    private_message_in::PrivateMessageContentIn, *,
9};
10
11/// This function implements deserialization manually, as it requires `content_type` as additional input.
12pub(super) fn deserialize_ciphertext_content<R: Read>(
13    bytes: &mut R,
14    content_type: ContentType,
15) -> Result<PrivateMessageContentIn, tls_codec::Error> {
16    let content = FramedContentBodyIn::deserialize_without_type(bytes, content_type)?;
17    let auth = FramedContentAuthData::deserialize(bytes, content_type)?;
18
19    let padding = {
20        let mut buffer = Vec::new();
21        bytes
22            .read_to_end(&mut buffer)
23            .map_err(|_| Error::InvalidInput)?;
24        buffer
25    };
26
27    // ValSem011: PrivateMessageContentIn padding must be all-zero.
28    // https://validation.openmls.tech/#valn1303
29    if !padding.into_iter().all(|byte| byte == 0x00) {
30        return Err(Error::InvalidInput);
31    }
32
33    Ok(PrivateMessageContentIn { content, auth })
34}
35
36impl Deserialize for MlsMessageIn {
37    fn tls_deserialize<R: Read>(bytes: &mut R) -> Result<Self, tls_codec::Error> {
38        let version = ProtocolVersion::tls_deserialize(bytes)?;
39        let body = MlsMessageBodyIn::tls_deserialize(bytes)?;
40
41        // This is required by the RFC in the struct definition of MLSMessage
42        if version != ProtocolVersion::Mls10 {
43            return Err(tls_codec::Error::DecodingError(
44                "MlsMessage protocol version is not 1.0".into(),
45            ));
46        }
47
48        // KeyPackage version must match MlsMessage version.
49        // https://validation.openmls.tech/#valn0205
50        if let MlsMessageBodyIn::KeyPackage(key_package) = &body {
51            if !key_package.version_is_supported(version) {
52                return Err(tls_codec::Error::DecodingError(
53                    "KeyPackage protocol version does not match MlsMessage version.".into(),
54                ));
55            }
56        }
57        Ok(Self { version, body })
58    }
59}
60
61impl DeserializeBytes for MlsMessageIn {
62    fn tls_deserialize_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error>
63    where
64        Self: Sized,
65    {
66        let mut bytes_ref = bytes;
67        let message = MlsMessageIn::tls_deserialize(&mut bytes_ref)?;
68        let remainder = &bytes[message.tls_serialized_len()..];
69        Ok((message, remainder))
70    }
71}