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
use std::{collections::HashMap, hash::Hash};

use uuid::Uuid;

use crate::{
    client::encryption_settings::EncryptionSettings,
    error::{Error, Result},
};

use super::{KeyDecryptable, KeyEncryptable, SymmetricCryptoKey};

pub trait LocateKey {
    fn locate_key<'a>(
        &self,
        enc: &'a EncryptionSettings,
        org_id: &Option<Uuid>,
    ) -> Option<&'a SymmetricCryptoKey> {
        enc.get_key(org_id)
    }
}

/// Deprecated: please use LocateKey and KeyDecryptable instead
pub trait Encryptable<Output> {
    fn encrypt(self, enc: &EncryptionSettings, org_id: &Option<Uuid>) -> Result<Output>;
}

/// Deprecated: please use LocateKey and KeyDecryptable instead
pub trait Decryptable<Output> {
    fn decrypt(&self, enc: &EncryptionSettings, org_id: &Option<Uuid>) -> Result<Output>;
}

impl<T: KeyEncryptable<Output> + LocateKey, Output> Encryptable<Output> for T {
    fn encrypt(self, enc: &EncryptionSettings, org_id: &Option<Uuid>) -> Result<Output> {
        let key = self.locate_key(enc, org_id).ok_or(Error::VaultLocked)?;
        self.encrypt_with_key(key)
    }
}

impl<T: KeyDecryptable<Output> + LocateKey, Output> Decryptable<Output> for T {
    fn decrypt(&self, enc: &EncryptionSettings, org_id: &Option<Uuid>) -> Result<Output> {
        let key = self.locate_key(enc, org_id).ok_or(Error::VaultLocked)?;
        self.decrypt_with_key(key)
    }
}

impl<T: Encryptable<Output>, Output> Encryptable<Vec<Output>> for Vec<T> {
    fn encrypt(self, enc: &EncryptionSettings, org_id: &Option<Uuid>) -> Result<Vec<Output>> {
        self.into_iter().map(|e| e.encrypt(enc, org_id)).collect()
    }
}

impl<T: Decryptable<Output>, Output> Decryptable<Vec<Output>> for Vec<T> {
    fn decrypt(&self, enc: &EncryptionSettings, org_id: &Option<Uuid>) -> Result<Vec<Output>> {
        self.iter().map(|e| e.decrypt(enc, org_id)).collect()
    }
}

impl<T: Encryptable<Output>, Output, Id: Hash + Eq> Encryptable<HashMap<Id, Output>>
    for HashMap<Id, T>
{
    fn encrypt(
        self,
        enc: &EncryptionSettings,
        org_id: &Option<Uuid>,
    ) -> Result<HashMap<Id, Output>> {
        self.into_iter()
            .map(|(id, e)| Ok((id, e.encrypt(enc, org_id)?)))
            .collect()
    }
}

impl<T: Decryptable<Output>, Output, Id: Hash + Eq + Copy> Decryptable<HashMap<Id, Output>>
    for HashMap<Id, T>
{
    fn decrypt(
        &self,
        enc: &EncryptionSettings,
        org_id: &Option<Uuid>,
    ) -> Result<HashMap<Id, Output>> {
        self.iter()
            .map(|(id, e)| Ok((*id, e.decrypt(enc, org_id)?)))
            .collect()
    }
}