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
use std::collections::BTreeMap;
use crate::serde::Base64;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct SecretEventContent {
pub encrypted: BTreeMap<String, SecretEncryptedData>,
}
impl SecretEventContent {
pub fn new(encrypted: BTreeMap<String, SecretEncryptedData>) -> Self {
Self { encrypted }
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[serde(untagged)]
pub enum SecretEncryptedData {
AesHmacSha2EncryptedData {
iv: Base64,
ciphertext: Base64,
mac: Base64,
},
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use matches::assert_matches;
use serde_json::{from_value as from_json_value, json, to_value as to_json_value};
use crate::serde::Base64;
use super::{SecretEncryptedData, SecretEventContent};
#[test]
fn test_secret_serialization() {
let key_one_data = SecretEncryptedData::AesHmacSha2EncryptedData {
iv: Base64::parse("YWJjZGVmZ2hpamtsbW5vcA").unwrap(),
ciphertext: Base64::parse("dGhpc2lzZGVmaW5pdGVseWNpcGhlcnRleHQ").unwrap(),
mac: Base64::parse("aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U").unwrap(),
};
let mut encrypted = BTreeMap::<String, SecretEncryptedData>::new();
encrypted.insert("key_one".to_owned(), key_one_data);
let content = SecretEventContent::new(encrypted);
let json = json!({
"encrypted": {
"key_one" : {
"iv": "YWJjZGVmZ2hpamtsbW5vcA",
"ciphertext": "dGhpc2lzZGVmaW5pdGVseWNpcGhlcnRleHQ",
"mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
}
}
});
assert_eq!(to_json_value(&content).unwrap(), json);
}
#[test]
fn test_secret_deserialization() {
let json = json!({
"encrypted": {
"key_one" : {
"iv": "YWJjZGVmZ2hpamtsbW5vcA",
"ciphertext": "dGhpc2lzZGVmaW5pdGVseWNpcGhlcnRleHQ",
"mac": "aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U"
}
}
});
let deserialized: SecretEventContent = from_json_value(json).unwrap();
if let Some(secret_data) = deserialized.encrypted.get("key_one") {
assert_matches!(
secret_data,
SecretEncryptedData::AesHmacSha2EncryptedData {
iv,
ciphertext,
mac
}
if iv == &Base64::parse("YWJjZGVmZ2hpamtsbW5vcA").unwrap()
&& ciphertext == &Base64::parse("dGhpc2lzZGVmaW5pdGVseWNpcGhlcnRleHQ").unwrap()
&& mac == &Base64::parse("aWRvbnRrbm93d2hhdGFtYWNsb29rc2xpa2U").unwrap()
)
}
}
}