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
//! Tools for decrypting and loading collections from RPC responses.
use std::collections::HashMap;

use crate::{
    collection::{AnnotatedCollectionSchema, Collection},
    decoder::RecordSchema,
    indexer::{
        errors::LoadIndexerError,
        mapping::{FilterMapping, Mapping, MappingWithMeta, OreMapping},
        mapping_indexer::MappingIndexer,
        Indexer,
    },
};
use ciborium::{de::from_reader, ser::into_writer};
use cipherstash_grpc::api;
use envelopers::{DecryptionError, EncryptedRecord, EncryptionError, EnvelopeCipher, KeyProvider};
use rand_chacha::rand_core::{Error as RngError, RngCore};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use thiserror::Error;

#[derive(Error, Debug)]
pub enum DecryptIndexError {
    #[error("Failed to decrypt index settings: {0}")]
    DecryptSettings(#[from] DecryptionError),
    #[error("Failed to decode index settings from CBOR: {0}")]
    DecodeIndexSettings(#[from] ciborium::de::Error<std::io::Error>),
    #[error("{0}")]
    Other(String),
}

#[derive(Error, Debug)]
pub enum EncryptIndexError {
    #[error("Failed to encrypt index settings: {0}")]
    EncryptSettings(#[from] EncryptionError),
    #[error("Failed to encode index settings to CBOR: {0}")]
    EncodeIndexSettings(#[from] ciborium::ser::Error<std::io::Error>),
    #[error("{0}")]
    Other(String),
}

#[derive(Error, Debug)]
pub enum CreateIndexError {
    #[error("Failed to generate '{field}' key: {error}")]
    KeyGeneration {
        field: &'static str,
        error: RngError,
    },
}

#[derive(Error, Debug)]
pub enum DecryptCollectionMetadataError {
    #[error("Failed to decode metadata from CBOR: {0}")]
    Decode(#[from] ciborium::de::Error<std::io::Error>),
    #[error("Failed to decrypt metdata: {0}")]
    Decrypt(#[from] DecryptionError),
    #[error("{0}")]
    Other(String),
}

#[derive(Error, Debug)]
pub enum EncryptCollectionMetadataError {
    #[error("Failed to encode metadata to CBOR: {0}")]
    Encode(#[from] ciborium::ser::Error<std::io::Error>),
    #[error("Failed to decrypt metdata: {0}")]
    Encrypt(#[from] EncryptionError),
    #[error("{0}")]
    Other(String),
}

#[derive(Error, Debug)]
pub enum DecryptCollectionError {
    #[error("Failed to decrypt collection metadata: {0}")]
    DecryptMetadata(#[from] DecryptionError),
    #[error("Failed to decrypt index: {0}")]
    DecryptIndex(#[from] DecryptIndexError),
    #[error("Failed to decrypt metadata: {0}")]
    DecryptCollectionMetadata(#[from] DecryptCollectionMetadataError),
    #[error("{0}")]
    Other(String),
}

#[derive(Deserialize, Serialize, Debug)]
pub struct OreDecryptedIndexMeta {
    #[serde(rename = "$indexName")]
    index_name: String,
    #[serde(alias = "$prfKey", with = "hex")]
    prf_key: [u8; 16],
    #[serde(alias = "$prpKey", with = "hex")]
    prp_key: [u8; 16],
}

#[derive(Deserialize, Serialize, Debug)]
pub struct FilterDecryptedIndexMeta {
    #[serde(rename = "$indexName")]
    index_name: String,
    #[serde(alias = "$filterKey", with = "hex")]
    filter_key: [u8; 32],
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(untagged)]
pub enum DecryptedIndexSettings {
    Ore {
        mapping: OreMapping,
        meta: OreDecryptedIndexMeta,
    },
    Filter {
        mapping: FilterMapping,
        meta: FilterDecryptedIndexMeta,
    },
}

impl DecryptedIndexSettings {
    pub fn index_name(&self) -> &str {
        match self {
            Self::Ore { meta, .. } => &meta.index_name,
            Self::Filter { meta, .. } => &meta.index_name,
        }
    }

    #[cfg(test)]
    fn to_mapping(self) -> Mapping {
        match self {
            Self::Ore { mapping, .. } => mapping.into(),
            Self::Filter { mapping, .. } => mapping.into(),
        }
    }

    pub fn into_mapping_with_meta(self, index_id: Uuid) -> MappingWithMeta {
        match self {
            Self::Ore {
                mapping,
                meta:
                    OreDecryptedIndexMeta {
                        prf_key, prp_key, ..
                    },
            } => MappingWithMeta::Ore {
                mapping,
                prf_key,
                prp_key,
                index_id,
            },
            Self::Filter {
                mapping,
                meta: FilterDecryptedIndexMeta { filter_key, .. },
            } => MappingWithMeta::Filter {
                mapping,
                filter_key,
                index_id,
            },
        }
    }
}

#[derive(Debug)]
#[allow(dead_code)]
pub struct DecryptedIndex {
    pub id: Uuid,
    pub settings: DecryptedIndexSettings,
    index_type: api::indexes::index::IndexType,
    unique: bool,
    first_schema_version: u32,
    last_schema_version: u32,
}

impl DecryptedIndex {
    /// Create a new index from a [`Mapping`] and index name.
    ///
    /// This method will generate encryption keys using the provided random number generator.
    pub(crate) fn new_from_mapping(
        rng: &mut impl RngCore,
        index_name: String,
        mapping: Mapping,
    ) -> Result<Self, CreateIndexError> {
        let unique = mapping.unique();
        let index_type = mapping.api_index_type();

        let settings = match mapping {
            Mapping::Ore(mapping) => {
                let mut prf_key = [0; 16];
                let mut prp_key = [0; 16];

                rng.try_fill_bytes(&mut prf_key).map_err(|error| {
                    CreateIndexError::KeyGeneration {
                        field: "prf_key",
                        error,
                    }
                })?;

                rng.try_fill_bytes(&mut prp_key).map_err(|error| {
                    CreateIndexError::KeyGeneration {
                        field: "prp_key",
                        error,
                    }
                })?;

                DecryptedIndexSettings::Ore {
                    mapping,
                    meta: OreDecryptedIndexMeta {
                        index_name,
                        prf_key,
                        prp_key,
                    },
                }
            }
            Mapping::Filter(mapping) => {
                let mut filter_key = [0; 32];

                rng.try_fill_bytes(&mut filter_key).map_err(|error| {
                    CreateIndexError::KeyGeneration {
                        field: "filter_key",
                        error,
                    }
                })?;

                DecryptedIndexSettings::Filter {
                    mapping,
                    meta: FilterDecryptedIndexMeta {
                        index_name,
                        filter_key,
                    },
                }
            }
        };

        Ok(Self {
            settings,
            id: Uuid::new_v4(),
            last_schema_version: 0,
            first_schema_version: 0,
            unique,
            index_type,
        })
    }

    /// Decrypt a collection index from an RPC Index
    async fn decrypt(
        cipher: &EnvelopeCipher<impl KeyProvider>,
        api::indexes::Index {
            id,
            settings,
            r#type,
            last_schema_version,
            first_schema_version,
            unique,
        }: api::indexes::Index,
    ) -> Result<Self, DecryptIndexError> {
        let id = id
            .try_into()
            .map(Uuid::from_bytes)
            .map_err(|_| DecryptIndexError::Other("Returned index id was malformed".into()))?;

        let decrypted_settings = cipher
            .decrypt(&EncryptedRecord::from_vec(settings).map_err(|_| {
                DecryptIndexError::Other(
                    "Failed to load encrypted index settings from bytes".into(),
                )
            })?)
            .await?;

        let settings = from_reader(&decrypted_settings[..])?;

        Ok(Self {
            id,
            settings,
            index_type: api::indexes::index::IndexType::from_i32(r#type)
                .unwrap_or(api::indexes::index::IndexType::Ore),
            last_schema_version,
            first_schema_version,
            unique,
        })
    }

    /// Encrypt the current index and convert it to a value that can be sent to the data service
    pub(crate) async fn encrypt(
        &self,
        cipher: &EnvelopeCipher<impl KeyProvider>,
    ) -> Result<api::indexes::Index, EncryptIndexError> {
        let mut settings_buffer = vec![];
        into_writer(&self.settings, &mut settings_buffer)?;
        let settings = cipher
            .encrypt(&settings_buffer)
            .await?
            .to_vec()
            .map_err(|e| EncryptIndexError::Other(e.to_string()))?;

        Ok(api::indexes::Index {
            id: self.id.as_bytes().to_vec(),
            settings,
            first_schema_version: self.first_schema_version,
            last_schema_version: self.last_schema_version,
            r#type: self.index_type.into(),
            unique: self.unique,
        })
    }

    /// Convert the decrypted index into a tuple in the form ( index_name, indexer ).
    ///
    /// These tuples could then be stored in a hash map like on the [`Indexer`] struct.
    fn into_indexer_entry(self) -> Result<(String, MappingIndexer), LoadIndexerError> {
        Ok((
            self.settings.index_name().into(),
            MappingIndexer::from_mapping(self.settings.into_mapping_with_meta(self.id))?,
        ))
    }
}

/// The decrypted metadata that is stored on the collection.
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DecryptedCollectionMetadata {
    pub name: String,
    pub record_type: RecordSchema,
}

impl DecryptedCollectionMetadata {
    pub async fn decrypt(
        cipher: &EnvelopeCipher<impl KeyProvider>,
        encrypted_metadata: Vec<u8>,
    ) -> Result<Self, DecryptCollectionMetadataError> {
        let record = EncryptedRecord::from_vec(encrypted_metadata).map_err(|_| {
            DecryptCollectionMetadataError::Other(
                "Failed to load encrypted record from bytes".into(),
            )
        })?;

        let decrypted_bytes = cipher.decrypt(&record).await?;

        Ok(from_reader(&decrypted_bytes[..])?)
    }

    pub async fn encrypt(
        &self,
        cipher: &EnvelopeCipher<impl KeyProvider>,
    ) -> Result<Vec<u8>, EncryptCollectionMetadataError> {
        let mut bytes = vec![];

        into_writer(&self, &mut bytes)?;

        let encrypted_record = cipher.encrypt(&bytes).await?;

        encrypted_record.to_vec().map_err(|_| {
            EncryptCollectionMetadataError::Other(
                "Failed to encode encrypted record as bytes".into(),
            )
        })
    }
}

/// A collection that has been decrypted from an RPC [`InfoReply`]
#[derive(Debug)]
pub struct DecryptedCollection {
    pub id: Uuid,
    pub collection_ref: Vec<u8>,
    pub indexes: Vec<DecryptedIndex>,
    pub metadata: DecryptedCollectionMetadata,
}

impl DecryptedCollection {
    /// Load a collection from it's encrypted metadata and indexes
    pub(crate) async fn decrypt(
        cipher: &EnvelopeCipher<impl KeyProvider>,
        id: Uuid,
        collection_ref: Vec<u8>,
        encrypted_metadata: Vec<u8>,
        rpc_indexes: Vec<api::indexes::Index>,
    ) -> Result<Self, DecryptCollectionError> {
        let mut indexes = vec![];

        for index in rpc_indexes.into_iter() {
            indexes.push(DecryptedIndex::decrypt(cipher, index).await?);
        }

        let metadata = DecryptedCollectionMetadata::decrypt(cipher, encrypted_metadata).await?;

        Ok(Self {
            id,
            collection_ref,
            indexes,
            metadata,
        })
    }

    /// The plaintext name of the collection
    pub fn name(&self) -> &str {
        &self.metadata.name
    }
}

impl TryFrom<DecryptedCollection> for Collection {
    type Error = LoadIndexerError;

    fn try_from(col: DecryptedCollection) -> Result<Self, Self::Error> {
        let indexes = col
            .indexes
            .into_iter()
            .map(|x| x.into_indexer_entry())
            .collect::<Result<HashMap<_, _>, _>>()?;

        let indexer = Indexer::new(indexes, col.metadata.record_type);

        Ok(Self {
            id: col.id,
            name: col.metadata.name,
            collection_ref: col.collection_ref,
            indexer,
        })
    }
}

#[derive(Debug)]
pub enum CollectionDecryptResult {
    Decrypted(DecryptedCollection),
    DecryptionFailed {
        id: Uuid,
        r#ref: Vec<u8>,
        error: DecryptCollectionError,
    },
    Failed(DecryptCollectionError),
}

impl CollectionDecryptResult {
    /// Try and decrypt a [`CollectionDecryptResult`] from an RPC InfoReply.
    ///
    /// If the decryption fails a DecryptionFailed variant will be returned that contains the
    /// collection's ID. If the ID can't be decoded then a Failed variant will be returned.
    pub(crate) async fn decrypt(
        cipher: &EnvelopeCipher<impl KeyProvider>,
        api::collections::InfoReply {
            id,
            metadata,
            indexes,
            r#ref,
            ..
        }: api::collections::InfoReply,
    ) -> CollectionDecryptResult {
        let id_result = id.try_into().map(Uuid::from_bytes).map_err(|_| {
            DecryptCollectionError::Other("Returned collection id was malformed".into())
        });

        match id_result {
            Ok(id) => DecryptedCollection::decrypt(cipher, id, r#ref.clone(), metadata, indexes)
                .await
                .map_or_else(
                    |error| Self::DecryptionFailed { id, r#ref, error },
                    Self::Decrypted,
                ),
            Err(err) => Self::Failed(err),
        }
    }
}

impl TryFrom<CollectionDecryptResult> for Collection {
    type Error = DecryptCollectionError;

    fn try_from(value: CollectionDecryptResult) -> Result<Self, Self::Error> {
        match value {
            CollectionDecryptResult::Decrypted(collection) => collection
                .try_into()
                .map_err(|e: LoadIndexerError| DecryptCollectionError::Other(e.to_string())),
            CollectionDecryptResult::DecryptionFailed { error, .. } => Err(error),
            CollectionDecryptResult::Failed(error) => Err(error),
        }
    }
}

impl TryFrom<CollectionDecryptResult> for AnnotatedCollectionSchema {
    type Error = DecryptCollectionError;

    fn try_from(value: CollectionDecryptResult) -> Result<Self, Self::Error> {
        match value {
            CollectionDecryptResult::Decrypted(collection) => Ok(collection.into()),
            CollectionDecryptResult::DecryptionFailed { error, .. } => Err(error),
            CollectionDecryptResult::Failed(error) => Err(error),
        }
    }
}

#[cfg(test)]
mod test {
    use super::DecryptedCollection;
    use super::*;
    use crate::decoder::{DataType, RecordSchema, SchemaField};
    use crate::utils::{cbor_buffer, collection};
    use cipherstash_grpc::api::{collections::InfoReply, indexes::Index};
    use envelopers::{EnvelopeCipher, SimpleKeyProvider};
    use uuid::{uuid, Uuid};

    fn create_cipher() -> EnvelopeCipher<SimpleKeyProvider> {
        EnvelopeCipher::init(SimpleKeyProvider::init([1; 16]))
    }

    fn uuid_vec(val: &str) -> Vec<u8> {
        Uuid::parse_str(val).unwrap().as_bytes().to_vec()
    }

    async fn create_info_reply(cipher: &mut EnvelopeCipher<SimpleKeyProvider>) -> InfoReply {
        InfoReply {
            id: uuid_vec("33333c78-aaf4-488d-aef7-aeb5dc95b9e3"),
            metadata: cipher
                .encrypt(&cbor_buffer!({
                    "name" => "Great Collection",
                    "recordType" => {
                        "name" => "string",
                        "age" => "uint64"
                    }
                }))
                .await
                .unwrap()
                .to_vec()
                .unwrap(),
            indexes: vec![Index {
                id: uuid_vec("76a07734-a963-4b36-be5c-72cdfcdbf2eb"),
                settings: cipher
                    .encrypt(&cbor_buffer!({
                        "mapping" => {
                            "kind" => "exact",
                            "field" => "title"
                        },
                        "meta" => {
                            "$indexName" => "exactTitle",
                            "$prfKey" => hex::encode([0; 16]),
                            "$prpKey" => hex::encode([1; 16])
                        }
                    }))
                    .await
                    .unwrap()
                    .to_vec()
                    .unwrap(),
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn test_load_encrypted() {
        let mut cipher = create_cipher();

        let InfoReply {
            id,
            r#ref,
            metadata,
            indexes,
            ..
        } = create_info_reply(&mut cipher).await;

        let mut decrypted_collection = DecryptedCollection::decrypt(
            &mut cipher,
            Uuid::from_slice(&id).expect("Failed to load uuid"),
            r#ref,
            metadata,
            indexes,
        )
        .await
        .unwrap();

        assert_eq!(decrypted_collection.indexes.len(), 1);

        assert_eq!(decrypted_collection.name(), "Great Collection");

        assert_eq!(
            decrypted_collection.indexes.remove(0).settings.to_mapping(),
            OreMapping::Exact {
                field: "title".into(),
                unique: None
            }
            .into()
        );
    }

    #[tokio::test]
    async fn test_malformed_index_id() {
        let mut cipher = create_cipher();

        let InfoReply {
            id,
            r#ref,
            metadata,
            indexes,
            ..
        } = InfoReply {
            indexes: vec![Index {
                // invalid uuid
                id: vec![1; 10],
                ..Default::default()
            }],
            ..create_info_reply(&mut cipher).await
        };

        let error = DecryptedCollection::decrypt(
            &mut cipher,
            Uuid::from_slice(&id).expect("Failed to load uuid"),
            r#ref,
            metadata,
            indexes,
        )
        .await
        .unwrap_err();

        assert_eq!(
            format!("{}", error),
            "Failed to decrypt index: Returned index id was malformed"
        );
    }

    #[tokio::test]
    async fn test_info_reply_to_collection() {
        let mut cipher = create_cipher();

        let reply = create_info_reply(&mut cipher).await;

        let col: Collection = CollectionDecryptResult::decrypt(&mut cipher, reply)
            .await
            .try_into()
            .expect("Failed to convert result to collection");

        assert_eq!(col.name, "Great Collection");
    }

    #[tokio::test]
    async fn test_index_round_trip() {
        let cipher = create_cipher();

        let index = DecryptedIndex {
            id: uuid!("be4edac0-a692-4689-b3a2-584590ee2c2c"),
            settings: DecryptedIndexSettings::Ore {
                mapping: OreMapping::Exact {
                    field: "test".into(),
                    unique: None,
                },
                meta: OreDecryptedIndexMeta {
                    index_name: "great index".into(),
                    prf_key: [0; 16],
                    prp_key: [1; 16],
                },
            },
            unique: false,
            index_type: api::indexes::index::IndexType::Ore,
            first_schema_version: 0,
            last_schema_version: 0,
        };

        let encrypted = index.encrypt(&cipher).await.expect("Failed to encrypt");

        let decrypted = DecryptedIndex::decrypt(&cipher, encrypted)
            .await
            .expect("Failed to encrypt");

        assert_eq!(decrypted.id, index.id);
        assert_eq!(decrypted.settings.index_name(), "great index");
        assert_eq!(decrypted.unique, false);
        assert_eq!(
            decrypted.settings.to_mapping(),
            OreMapping::Exact {
                field: "test".into(),
                unique: None
            }
            .into()
        );
    }

    #[tokio::test]
    async fn test_collection_metadata_round_trip() {
        let cipher = create_cipher();

        let metadata = DecryptedCollectionMetadata {
            name: "Great Metadata".into(),
            record_type: RecordSchema {
                map: collection! {
                    "uint64" => DataType::Uint64,
                    "bool" => DataType::Boolean
                },
            },
        };

        let encrypted = metadata.encrypt(&cipher).await.expect("Failed to encrypt");

        let decrypted = DecryptedCollectionMetadata::decrypt(&cipher, encrypted)
            .await
            .expect("Failed to encrypt");

        assert_eq!(decrypted.name, "Great Metadata");
        assert_eq!(
            decrypted.record_type.map.get("uint64"),
            Some(&SchemaField::DataType(DataType::Uint64))
        );
        assert_eq!(
            decrypted.record_type.map.get("bool"),
            Some(&SchemaField::DataType(DataType::Boolean))
        );
    }
}