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
// Copyright 2020 Karl Linderhed.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use std::collections::BTreeMap;

use ruma::{serde::Raw, DeviceKeyAlgorithm};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{value::to_raw_value, Value};
use vodozemac::Curve25519PublicKey;

use super::{deserialize_curve_key, serialize_curve_key, Signatures};

/// A key for the SignedCurve25519 algorithm
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SignedKey {
    /// The Curve25519 key that can be used to establish Olm sessions.
    #[serde(deserialize_with = "deserialize_curve_key", serialize_with = "serialize_curve_key")]
    key: Curve25519PublicKey,

    /// Signatures for the key object.
    signatures: Signatures,

    /// Is the key considered to be a fallback key.
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "double_option")]
    fallback: Option<Option<bool>>,

    #[serde(flatten)]
    other: BTreeMap<String, Value>,
}

fn double_option<'de, T, D>(de: D) -> Result<Option<Option<T>>, D::Error>
where
    T: Deserialize<'de>,
    D: Deserializer<'de>,
{
    Deserialize::deserialize(de).map(Some)
}

impl SignedKey {
    /// Creates a new `SignedKey` with the given key and signatures.
    pub fn new(key: Curve25519PublicKey) -> Self {
        Self { key, signatures: Signatures::new(), fallback: None, other: BTreeMap::new() }
    }

    /// Creates a new `SignedKey`, that represents a fallback key, with the
    /// given key and signatures.
    pub fn new_fallback(key: Curve25519PublicKey) -> Self {
        Self {
            key,
            signatures: Signatures::new(),
            fallback: Some(Some(true)),
            other: BTreeMap::new(),
        }
    }

    /// Base64-encoded 32-byte Curve25519 public key.
    pub fn key(&self) -> Curve25519PublicKey {
        self.key
    }

    /// Signatures for the key object.
    pub fn signatures(&self) -> &Signatures {
        &self.signatures
    }

    /// Signatures for the key object as a mutable borrow.
    pub fn signatures_mut(&mut self) -> &mut Signatures {
        &mut self.signatures
    }

    /// Is the key considered to be a fallback key.
    pub fn fallback(&self) -> bool {
        self.fallback.map(|f| f.unwrap_or_default()).unwrap_or_default()
    }

    /// Serialize the one-time key into a Raw version.
    pub fn into_raw<T>(self) -> Raw<T> {
        let key = OneTimeKey::SignedKey(self);
        Raw::from_json(to_raw_value(&key).expect("Couldn't serialize one-time key"))
    }
}

/// A one-time public key for "pre-key" messages.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum OneTimeKey {
    /// A signed Curve25519 one-time key.
    SignedKey(SignedKey),

    /// An unsigned Curve25519 one-time key.
    #[serde(serialize_with = "serialize_curve_key")]
    Key(Curve25519PublicKey),
}

impl OneTimeKey {
    /// Deserialize the [`OneTimeKey`] from a [`DeviceKeyAlgorithm`] and a Raw
    /// JSON value.
    pub fn deserialize(
        algorithm: DeviceKeyAlgorithm,
        key: &Raw<ruma::encryption::OneTimeKey>,
    ) -> Result<Self, serde_json::Error> {
        match algorithm {
            DeviceKeyAlgorithm::Curve25519 => {
                let key: String = key.deserialize_as()?;
                Ok(OneTimeKey::Key(
                    Curve25519PublicKey::from_base64(&key).map_err(serde::de::Error::custom)?,
                ))
            }
            DeviceKeyAlgorithm::SignedCurve25519 => {
                let key: SignedKey = key.deserialize_as()?;
                Ok(OneTimeKey::SignedKey(key))
            }
            _ => Err(serde::de::Error::custom(format!("Unsupported key algorithm {algorithm}"))),
        }
    }
}

impl OneTimeKey {
    /// Is the key considered to be a fallback key.
    pub fn fallback(&self) -> bool {
        match self {
            OneTimeKey::SignedKey(s) => s.fallback(),
            OneTimeKey::Key(_) => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use ruma::{device_id, user_id, DeviceKeyAlgorithm, DeviceKeyId};
    use serde_json::json;
    use vodozemac::{Curve25519PublicKey, Ed25519Signature};

    use crate::types::{Signature, SignedKey};

    #[test]
    fn serialization() {
        let user_id = user_id!("@user:example.com");
        let device_id = device_id!("EGURVBUNJP");

        let json = json!({
          "key":"XjhWTCjW7l59pbfx9tlCBQolfnIQWARoKOzjTOPSlWM",
          "signatures": {
            user_id: {
              "ed25519:EGURVBUNJP": "mia28GKixFzOWKJ0h7Bdrdy2fjxiHCsst1qpe467FbW85H61UlshtKBoAXfTLlVfi0FX+/noJ8B3noQPnY+9Cg",
              "other:EGURVBUNJP": "UnknownSignature"
            }
          },
          "extra_key": "extra_value"
        });

        let curve_key =
            Curve25519PublicKey::from_base64("XjhWTCjW7l59pbfx9tlCBQolfnIQWARoKOzjTOPSlWM")
                .expect("Can't construct curve key from base64");

        let signature = Ed25519Signature::from_base64(
            "mia28GKixFzOWKJ0h7Bdrdy2fjxiHCsst1qpe467FbW85H61UlshtKBoAXfTLlVfi0FX+/noJ8B3noQPnY+9Cg"
        ).expect("The signature can always be decoded");

        let custom_signature = Signature::Other("UnknownSignature".to_owned());

        let key: SignedKey =
            serde_json::from_value(json.clone()).expect("Can't deserialize a valid one-time key");

        assert_eq!(key.key(), curve_key);
        assert_eq!(
            key.signatures().get_signature(
                user_id,
                &DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, device_id)
            ),
            Some(signature)
        );
        assert_eq!(
            key.signatures()
                .get(user_id)
                .unwrap()
                .get(&DeviceKeyId::from_parts("other".into(), device_id)),
            Some(&Ok(custom_signature))
        );

        let serialized = serde_json::to_value(key).expect("Can't reserialize a signed key");

        assert_eq!(json, serialized);
    }
}