cipherstash_dynamodb/crypto/
unsealed.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
use crate::{encrypted_table::TableAttribute, Decryptable};
use cipherstash_client::encryption::Plaintext;
use std::collections::HashMap;

use super::SealError;

/// Wrapper to indicate that a value is NOT encrypted
pub struct Unsealed {
    /// Optional descriptor prefix
    descriptor: Option<String>,

    /// Protected plaintexts with their descriptors
    protected: HashMap<String, (Plaintext, String)>,
    unprotected: HashMap<String, TableAttribute>,
}

impl Default for Unsealed {
    fn default() -> Self {
        Self::new()
    }
}

impl Unsealed {
    pub fn new() -> Self {
        Self {
            descriptor: None,
            protected: Default::default(),
            unprotected: Default::default(),
        }
    }

    pub fn new_with_descriptor(descriptor: impl Into<String>) -> Self {
        Self {
            descriptor: Some(descriptor.into()),
            protected: Default::default(),
            unprotected: Default::default(),
        }
    }

    pub fn protected(&self) -> &HashMap<String, (Plaintext, String)> {
        &self.protected
    }

    pub fn unprotected(&self) -> &HashMap<String, TableAttribute> {
        &self.unprotected
    }

    pub fn get_protected(&self, name: &str) -> Option<&Plaintext> {
        let (plaintext, _) = self.protected.get(name)?;

        Some(plaintext)
    }

    pub fn get_plaintext(&self, name: &str) -> TableAttribute {
        self.unprotected
            .get(name)
            .cloned()
            .unwrap_or(TableAttribute::Null)
    }

    pub fn add_protected(&mut self, name: impl Into<String>, plaintext: Plaintext) {
        let name = name.into();
        let descriptor = format!("{}/{}", self.descriptor.as_deref().unwrap_or(""), &name);
        self.protected.insert(name, (plaintext, descriptor));
    }

    pub fn add_unprotected(&mut self, name: impl Into<String>, attribute: TableAttribute) {
        self.unprotected.insert(name.into(), attribute);
    }

    /// Remove and return a protected value along with its descriptor.
    pub(crate) fn remove_protected_with_descriptor(
        &mut self,
        name: &str,
    ) -> Result<(Plaintext, String), SealError> {
        let out = self
            .protected
            .remove(name)
            .ok_or(SealError::MissingAttribute(name.to_string()))?;

        Ok(out)
    }

    pub fn into_value<T: Decryptable>(self) -> Result<T, SealError> {
        T::from_unsealed(self)
    }
}