-
Notifications
You must be signed in to change notification settings - Fork 4
/
objects_db.rs
209 lines (190 loc) · 6.41 KB
/
objects_db.rs
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
use std::collections::{HashMap, HashSet};
use async_trait::async_trait;
use cloudproof::reexport::{
crypto_core::{kdf256, Aes256Gcm, Dem, Instantiable, Nonce, SymmetricKey},
findex::{
implementations::redis::{FindexRedisError, RemovedLocationsFinder},
Keyword, Location,
},
};
use cosmian_kmip::kmip::{
kmip_objects::{Object, ObjectType},
kmip_types::{Attributes, StateEnumeration},
};
use redis::{aio::ConnectionManager, pipe, AsyncCommands};
use serde::{Deserialize, Serialize};
use crate::result::KResult;
/// Extract the keywords from the attributes
pub(crate) fn keywords_from_attributes(attributes: &Attributes) -> HashSet<Keyword> {
let mut keywords = HashSet::new();
if let Some(algo) = attributes.cryptographic_algorithm {
keywords.insert(Keyword::from(algo.to_string().as_bytes()));
}
if let Some(key_format_type) = attributes.key_format_type {
keywords.insert(Keyword::from(key_format_type.to_string().as_bytes()));
}
if let Some(cryptographic_length) = attributes.cryptographic_length {
keywords.insert(Keyword::from(cryptographic_length.to_be_bytes().as_slice()));
}
if let Some(links) = &attributes.link {
for link in links {
match serde_json::to_vec(link) {
Ok(bytes) => keywords.insert(Keyword::from(bytes.as_slice())),
// ignore malformed links (this should never be possible)
Err(_) => continue,
};
}
}
keywords
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub(crate) struct RedisDbObject {
#[serde(rename = "o")]
pub(crate) object: Object,
#[serde(rename = "t")]
pub(crate) object_type: ObjectType,
#[serde(rename = "w")]
pub(crate) owner: String,
#[serde(rename = "s")]
pub(crate) state: StateEnumeration,
#[serde(rename = "l")]
pub(crate) tags: HashSet<String>,
}
impl RedisDbObject {
pub fn new(
object: Object,
owner: String,
state: StateEnumeration,
tags: HashSet<String>,
) -> Self {
let object_type = object.object_type();
Self {
object,
object_type,
owner,
state,
tags,
}
}
pub fn keywords(&self) -> HashSet<Keyword> {
let mut keywords = self
.tags
.iter()
.map(|tag| Keyword::from(tag.as_bytes()))
.collect::<HashSet<Keyword>>();
// index some of the attributes
if let Ok(attributes) = self.object.attributes() {
keywords.extend(keywords_from_attributes(attributes));
}
// index the owner
keywords.insert(Keyword::from(self.owner.as_bytes()));
keywords
}
}
pub const DB_KEY_LENGTH: usize = 32;
pub(crate) struct ObjectsDB {
mgr: ConnectionManager,
dem: Aes256Gcm,
}
impl ObjectsDB {
pub async fn new(mgr: ConnectionManager, db_key: SymmetricKey<DB_KEY_LENGTH>) -> KResult<Self> {
Ok(Self {
mgr,
dem: Aes256Gcm::new(&db_key),
})
}
fn object_key(uid: &str) -> String {
format!("do::{uid}")
}
fn encrypt_object(&self, uid: &str, redis_db_object: &RedisDbObject) -> KResult<Vec<u8>> {
let mut nonce_bytes = [0; Aes256Gcm::NONCE_LENGTH];
kdf256!(&mut nonce_bytes, uid.as_bytes());
let ciphertext = self.dem.encrypt(
&Nonce::from(nonce_bytes),
&serde_json::to_vec(redis_db_object)?,
None,
)?;
Ok(ciphertext)
}
fn decrypt_object(&self, uid: &str, ciphertext: &[u8]) -> KResult<RedisDbObject> {
let mut nonce_bytes = [0; Aes256Gcm::NONCE_LENGTH];
kdf256!(&mut nonce_bytes, uid.as_bytes());
let plaintext = self
.dem
.decrypt(&Nonce::from(nonce_bytes), ciphertext, None)?;
let redis_db_object: RedisDbObject = serde_json::from_slice(&plaintext)?;
Ok(redis_db_object)
}
pub async fn object_upsert(&self, uid: &str, redis_db_object: &RedisDbObject) -> KResult<()> {
self.mgr
.clone()
.set(
ObjectsDB::object_key(uid),
self.encrypt_object(uid, redis_db_object)?,
)
.await?;
Ok(())
}
pub async fn object_get(&self, uid: &str) -> KResult<RedisDbObject> {
let ciphertext: Vec<u8> = self.mgr.clone().get(ObjectsDB::object_key(uid)).await?;
let mut dbo: RedisDbObject = self.decrypt_object(uid, &ciphertext)?;
dbo.object = Object::post_fix(dbo.object_type, dbo.object);
Ok(dbo)
}
pub async fn object_delete(&self, uid: &str) -> KResult<()> {
self.mgr.clone().del(ObjectsDB::object_key(uid)).await?;
Ok(())
}
pub async fn objects_upsert(&self, objects: &HashMap<String, RedisDbObject>) -> KResult<()> {
let mut pipeline = pipe();
for (uid, redis_db_object) in objects {
pipeline.set(
ObjectsDB::object_key(uid),
self.encrypt_object(uid, redis_db_object)?,
);
}
pipeline.query_async(&mut self.mgr.clone()).await?;
Ok(())
}
pub async fn objects_get(
&self,
uids: &HashSet<String>,
) -> KResult<HashMap<String, RedisDbObject>> {
let mut pipeline = pipe();
for uid in uids {
pipeline.get(ObjectsDB::object_key(uid));
}
let bytes: Vec<Vec<u8>> = pipeline.query_async(&mut self.mgr.clone()).await?;
let mut results = HashMap::new();
for (uid, ciphertext) in uids.iter().zip(bytes) {
if ciphertext.is_empty() {
continue
}
let mut dbo: RedisDbObject = self.decrypt_object(uid, &ciphertext)?;
dbo.object = Object::post_fix(dbo.object_type, dbo.object);
results.insert(uid.to_string(), dbo);
}
Ok(results)
}
/// Clear all data
///
/// # Warning
/// This is definitive
#[cfg(test)]
pub async fn clear_all(&self) -> KResult<()> {
redis::cmd("FLUSHDB")
.query_async(&mut self.mgr.clone())
.await?;
Ok(())
}
}
#[async_trait]
impl RemovedLocationsFinder for ObjectsDB {
async fn find_removed_locations(
&self,
_locations: HashSet<Location>,
) -> Result<HashSet<Location>, FindexRedisError> {
// Objects and permissions are never removed from the DB
Ok(HashSet::new())
}
}