cipherstash_dynamodb/encrypted_table/
table_entry.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
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
use crate::traits::ReadConversionError;
use aws_sdk_dynamodb::{primitives::Blob, types::AttributeValue};
use cipherstash_client::encryption::EncryptedRecord;
use std::{
    collections::{BTreeMap, HashMap},
    str::FromStr,
};

// FIXME: Clean this up
//#[skip_serializing_none]
#[derive(Debug, Clone)]
pub struct TableEntry {
    pub(crate) pk: String,
    pub(crate) sk: String,
    pub(crate) term: Option<Vec<u8>>,
    pub(crate) attributes: HashMap<String, TableAttribute>,
}

impl TableEntry {
    pub fn new(pk: String, sk: String) -> Self {
        Self {
            pk,
            sk,
            term: None,
            attributes: HashMap::new(),
        }
    }

    pub fn new_with_attributes(
        pk: String,
        sk: String,
        term: Option<Vec<u8>>,
        attributes: HashMap<String, TableAttribute>,
    ) -> Self {
        Self {
            pk,
            sk,
            term,
            attributes,
        }
    }

    pub fn add_attribute(&mut self, k: impl Into<String>, v: TableAttribute) {
        self.attributes.insert(k.into(), v);
    }
}

/// Trait for converting `TableAttribute` to `Self`
pub trait TryFromTableAttr: Sized {
    /// Try to convert `value` to `Self`
    fn try_from_table_attr(value: TableAttribute) -> Result<Self, ReadConversionError>;
}

#[derive(Debug, Clone)]
pub enum TableAttribute {
    String(String),
    Number(String),
    Bool(bool),
    Bytes(Vec<u8>),

    StringVec(Vec<String>),
    ByteVec(Vec<Vec<u8>>),
    NumberVec(Vec<String>),
    Map(HashMap<String, TableAttribute>),
    List(Vec<TableAttribute>),

    Null,
}

impl TableAttribute {
    pub(crate) fn as_encrypted_record(&self) -> Option<EncryptedRecord> {
        if let TableAttribute::Bytes(s) = self {
            EncryptedRecord::from_slice(&s[..]).ok()
        } else {
            None
        }
    }
}

macro_rules! impl_try_from_table_attr_helper {
    (number_parse, $ty:ty, $value:ident) => {
        $value
            .parse()
            .map_err(|_| ReadConversionError::ConversionFailed(stringify!($ty).to_string()))
    };
    (simple_parse, $_:ty, $value:ident) => {
        Ok::<_, ReadConversionError>($value)
    };
    (number_from, $_:ident, $value:ident) => {
        TableAttribute::Number($value.to_string())
    };
    (simple_from, $variant:ident, $value:ident) => {
        TableAttribute::$variant($value)
    };
    (
        body,
        $ty:ty,
        $variant:ident,
        $from_impl:ident!($from_args:tt),
        $try_from_impl:ident!($try_from_args:tt)
    ) => {
        impl From<$ty> for TableAttribute {
            fn from(value: $ty) -> Self {
                $from_impl!($from_args, $variant, value)
            }
        }

        impl TryFromTableAttr for $ty {
            fn try_from_table_attr(value: TableAttribute) -> Result<Self, ReadConversionError> {
                let TableAttribute::$variant(value) = value else {
                    return Err(ReadConversionError::ConversionFailed(
                        stringify!($ty).to_string(),
                    ));
                };

                $try_from_impl!($try_from_args, $ty, value)
            }
        }
    };
}

macro_rules! impl_try_from_table_attr {
    () => {};
    (, $($tail:tt)*) => {
        impl_try_from_table_attr!($($tail)*);
    };
    ($ty:ty => Number $($tail:tt)*) => {
        impl_try_from_table_attr_helper!(
            body,
            $ty,
            Number,
            impl_try_from_table_attr_helper!(
                number_from
            ),
            impl_try_from_table_attr_helper!(
                number_parse
            )
        );

        impl_try_from_table_attr!($($tail)*);
    };
    ($ty:ty => $variant:ident $($tail:tt)*) => {
        impl_try_from_table_attr_helper!(
            body,
            $ty,
            $variant,
            impl_try_from_table_attr_helper!(
                simple_from
            ),
            impl_try_from_table_attr_helper!(
                simple_parse
            )
        );

        impl_try_from_table_attr!($($tail)*);
    };
}

// The following implementations are covered by the blanket implementation on Vec<T>
// Vec<String> => StringVec,
// Vec<some number type> => NumberVec,
// Vec<Vec<u8>> => ByteVec,
impl_try_from_table_attr!(
    i16 => Number,
    i32 => Number,
    i64 => Number,
    u16 => Number,
    u32 => Number,
    u64 => Number,
    usize => Number,
    f32 => Number,
    f64  => Number,
    String => String,
    Vec<u8> => Bytes,
    bool => Bool
);

impl<T> TryFromTableAttr for Option<T>
where
    T: TryFromTableAttr,
{
    fn try_from_table_attr(value: TableAttribute) -> Result<Self, ReadConversionError> {
        if matches!(value, TableAttribute::Null) {
            Ok(None)
        } else {
            Ok(Some(T::try_from_table_attr(value)?))
        }
    }
}

impl<T> TryFromTableAttr for Vec<T>
where
    T: TryFromTableAttr,
{
    fn try_from_table_attr(value: TableAttribute) -> Result<Self, ReadConversionError> {
        match value {
            TableAttribute::StringVec(v) => v
                .into_iter()
                .map(TableAttribute::String)
                .map(T::try_from_table_attr)
                .collect(),
            TableAttribute::ByteVec(v) => v
                .into_iter()
                .map(TableAttribute::Bytes)
                .map(T::try_from_table_attr)
                .collect(),
            TableAttribute::NumberVec(v) => v
                .into_iter()
                .map(TableAttribute::Number)
                .map(T::try_from_table_attr)
                .collect(),
            TableAttribute::List(v) => v.into_iter().map(T::try_from_table_attr).collect(),
            _ => Err(ReadConversionError::ConversionFailed(
                std::any::type_name::<Vec<T>>().to_string(),
            )),
        }
    }
}

impl<T> From<Option<T>> for TableAttribute
where
    T: Into<TableAttribute>,
{
    fn from(value: Option<T>) -> Self {
        match value {
            Some(value) => value.into(),
            None => TableAttribute::Null,
        }
    }
}

impl<T> From<Vec<T>> for TableAttribute
where
    T: Into<TableAttribute>,
{
    fn from(value: Vec<T>) -> Self {
        // To determin whether we should produce a
        // Ss, Ns, Bs or a regular list, we will iterate
        // through the list and check if the all are the same
        // variant.
        #[derive(Clone, Copy, PartialEq, Eq)]
        enum IsVariant {
            // base case, we haven't looked at any elements yet.
            Empty,
            // Is String list
            IsSs,
            // Is Number list
            IsNs,
            // Is byte list
            IsBs,
            // Is mixed list
            IsList,
        }

        let len = value.len();
        let (table_attributes, is_variant) = value.into_iter().fold(
            (Vec::with_capacity(len), IsVariant::Empty),
            |(mut acc, mut is_variant), item| {
                let table_attr = item.into();

                // Don't check the variant if we already know it is a mixed list
                if is_variant != IsVariant::IsList {
                    match (&table_attr, is_variant) {
                        (TableAttribute::Bytes(_), IsVariant::Empty)
                        | (TableAttribute::Bytes(_), IsVariant::IsBs) => {
                            is_variant = IsVariant::IsBs
                        }
                        (TableAttribute::Number(_), IsVariant::Empty)
                        | (TableAttribute::Number(_), IsVariant::IsNs) => {
                            is_variant = IsVariant::IsNs
                        }
                        (TableAttribute::String(_), IsVariant::Empty)
                        | (TableAttribute::String(_), IsVariant::IsSs) => {
                            is_variant = IsVariant::IsSs
                        }
                        _ => is_variant = IsVariant::IsList,
                    }
                }

                acc.push(table_attr);
                (acc, is_variant)
            },
        );

        match is_variant {
            IsVariant::IsList | IsVariant::Empty => TableAttribute::List(table_attributes),
            IsVariant::IsSs => {
                let strings = table_attributes
                    .into_iter()
                    .map(|string| {
                        let TableAttribute::String(string) = string else {
                            // We already checked that all the items are strings
                            unreachable!()
                        };

                        string
                    })
                    .collect();

                TableAttribute::StringVec(strings)
            }
            IsVariant::IsNs => {
                let numbers = table_attributes
                    .into_iter()
                    .map(|number| {
                        let TableAttribute::Number(number) = number else {
                            // We already checked that all the items are numbers
                            unreachable!()
                        };

                        number
                    })
                    .collect();

                TableAttribute::NumberVec(numbers)
            }
            IsVariant::IsBs => {
                let bytes = table_attributes
                    .into_iter()
                    .map(|bytes| {
                        let TableAttribute::Bytes(bytes) = bytes else {
                            // We already checked that all the items are bytes
                            unreachable!()
                        };

                        bytes
                    })
                    .collect();

                TableAttribute::ByteVec(bytes)
            }
        }
    }
}

impl From<TableAttribute> for AttributeValue {
    fn from(attribute: TableAttribute) -> Self {
        match attribute {
            TableAttribute::String(s) => AttributeValue::S(s),
            TableAttribute::StringVec(s) => AttributeValue::Ss(s),

            TableAttribute::Number(i) => AttributeValue::N(i),
            TableAttribute::NumberVec(x) => AttributeValue::Ns(x),

            TableAttribute::Bytes(x) => AttributeValue::B(Blob::new(x)),
            TableAttribute::ByteVec(x) => {
                AttributeValue::Bs(x.into_iter().map(Blob::new).collect())
            }

            TableAttribute::Bool(x) => AttributeValue::Bool(x),
            TableAttribute::List(x) => AttributeValue::L(x.into_iter().map(|x| x.into()).collect()),
            TableAttribute::Map(x) => {
                AttributeValue::M(x.into_iter().map(|(k, v)| (k, v.into())).collect())
            }
            TableAttribute::Null => AttributeValue::Null(true),
        }
    }
}

impl From<AttributeValue> for TableAttribute {
    fn from(attribute: AttributeValue) -> Self {
        match attribute {
            AttributeValue::S(s) => TableAttribute::String(s),
            AttributeValue::N(n) => TableAttribute::Number(n),
            AttributeValue::Bool(n) => TableAttribute::Bool(n),
            AttributeValue::B(n) => TableAttribute::Bytes(n.into_inner()),
            AttributeValue::L(l) => {
                TableAttribute::List(l.into_iter().map(TableAttribute::from).collect())
            }
            AttributeValue::M(l) => TableAttribute::Map(
                l.into_iter()
                    .map(|(k, v)| (k, TableAttribute::from(v)))
                    .collect(),
            ),
            AttributeValue::Bs(x) => {
                TableAttribute::ByteVec(x.into_iter().map(|x| x.into_inner()).collect())
            }
            AttributeValue::Ss(x) => TableAttribute::StringVec(x),
            AttributeValue::Ns(x) => TableAttribute::NumberVec(x),
            AttributeValue::Null(_) => TableAttribute::Null,

            x => panic!("Unsupported Dynamo attribute value: {x:?}"),
        }
    }
}

impl<K, V> From<HashMap<K, V>> for TableAttribute
where
    K: ToString,
    V: Into<TableAttribute>,
{
    fn from(map: HashMap<K, V>) -> Self {
        TableAttribute::Map(
            map.into_iter()
                .map(|(k, v)| (k.to_string(), v.into()))
                .collect(),
        )
    }
}

impl<K, V> TryFromTableAttr for HashMap<K, V>
where
    K: FromStr + std::hash::Hash + std::cmp::Eq,
    V: TryFromTableAttr,
{
    fn try_from_table_attr(value: TableAttribute) -> Result<Self, ReadConversionError> {
        let TableAttribute::Map(map) = value else {
            return Err(ReadConversionError::ConversionFailed(
                std::any::type_name::<Self>().to_string(),
            ));
        };

        map.into_iter()
            .map(|(k, v)| {
                let k = k.parse().map_err(|_| {
                    ReadConversionError::ConversionFailed(std::any::type_name::<Self>().to_string())
                })?;
                let v = V::try_from_table_attr(v)?;

                Ok((k, v))
            })
            .collect()
    }
}

impl<K, V> From<BTreeMap<K, V>> for TableAttribute
where
    K: ToString,
    V: Into<TableAttribute>,
{
    fn from(map: BTreeMap<K, V>) -> Self {
        TableAttribute::Map(
            map.into_iter()
                .map(|(k, v)| (k.to_string(), v.into()))
                .collect(),
        )
    }
}

impl<K, V> TryFromTableAttr for BTreeMap<K, V>
where
    K: FromStr + std::cmp::Ord,
    V: TryFromTableAttr,
{
    fn try_from_table_attr(value: TableAttribute) -> Result<Self, ReadConversionError> {
        let TableAttribute::Map(map) = value else {
            return Err(ReadConversionError::ConversionFailed(
                std::any::type_name::<Self>().to_string(),
            ));
        };

        map.into_iter()
            .map(|(k, v)| {
                let k = k.parse().map_err(|_| {
                    ReadConversionError::ConversionFailed(std::any::type_name::<Self>().to_string())
                })?;
                let v = V::try_from_table_attr(v)?;

                Ok((k, v))
            })
            .collect()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum TestType {
        Number,
        String,
        Bytes,
    }

    impl From<TestType> for TableAttribute {
        fn from(value: TestType) -> Self {
            match value {
                TestType::Number => TableAttribute::Number(42.to_string()),
                TestType::String => TableAttribute::String("fourty two".to_string()),
                TestType::Bytes => TableAttribute::Bytes(b"101010".to_vec()),
            }
        }
    }

    impl TryFromTableAttr for TestType {
        fn try_from_table_attr(value: TableAttribute) -> Result<Self, ReadConversionError> {
            match value {
                TableAttribute::Number(n) if n == "42" => Ok(Self::Number),
                TableAttribute::String(s) if s == "fourty two" => Ok(Self::String),
                TableAttribute::Bytes(b) if b == b"101010" => Ok(Self::Bytes),
                _ => Err(ReadConversionError::ConversionFailed("".to_string())),
            }
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
    enum MapKeys {
        A,
        B,
        C,
    }

    impl std::fmt::Display for MapKeys {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let c = match self {
                MapKeys::A => "A",
                MapKeys::B => "B",
                MapKeys::C => "C",
            };

            write!(f, "{c}")
        }
    }

    impl FromStr for MapKeys {
        type Err = ();

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            match s {
                "A" => Ok(MapKeys::A),
                "B" => Ok(MapKeys::B),
                "C" => Ok(MapKeys::C),
                _ => Err(()),
            }
        }
    }

    #[test]
    fn test_to_and_from_list() {
        let test_vec = vec![
            TestType::Number,
            TestType::Number,
            TestType::String,
            TestType::Bytes,
        ];

        let table_attribute = TableAttribute::from(test_vec.clone());

        // Assert that we convert to the correct variant.
        assert!(matches!(&table_attribute, TableAttribute::List(x) if x.len() == test_vec.len()));

        let original = Vec::<TestType>::try_from_table_attr(table_attribute).unwrap();

        assert_eq!(original, test_vec);
    }

    #[test]
    fn test_string_vec() {
        let test_vec = vec![
            "String0".to_string(),
            "String1".to_string(),
            "String2".to_string(),
        ];

        let table_attribute = TableAttribute::from(test_vec.clone());

        assert!(matches!(
            &table_attribute,
            TableAttribute::StringVec(x)
            if x.len() == test_vec.len()
        ));

        let original = Vec::<String>::try_from_table_attr(table_attribute).unwrap();

        assert_eq!(original, test_vec);
    }

    #[test]
    fn test_number_vec() {
        let test_vec = vec![2, 3, 5, 7, 13];

        let table_attribute = TableAttribute::from(test_vec.clone());

        assert!(matches!(
            &table_attribute,
            TableAttribute::NumberVec(x)
            if x.len() == test_vec.len()
        ));

        let original = Vec::<i32>::try_from_table_attr(table_attribute).unwrap();

        assert_eq!(original, test_vec);
    }

    #[test]
    fn test_bytes_vec() {
        let test_vec: Vec<Vec<u8>> = (0u8..5).map(|i| (i * 10..i * 10 + 10).collect()).collect();

        let table_attribute = TableAttribute::from(test_vec.clone());

        assert!(matches!(
            &table_attribute,
            TableAttribute::ByteVec(x)
            if x.len() == test_vec.len()
        ));

        let original = Vec::<Vec<u8>>::try_from_table_attr(table_attribute).unwrap();

        assert_eq!(original, test_vec);
    }

    #[test]
    fn test_hashmap() {
        let map = [
            (MapKeys::A, "Something in A".to_string()),
            (MapKeys::A, "Something in B".to_string()),
            (MapKeys::A, "Something in C".to_string()),
        ]
        .into_iter()
        .collect::<HashMap<_, _>>();

        let table_attribute = TableAttribute::from(map.clone());

        assert!(matches!(
            &table_attribute,
            TableAttribute::Map(x)
            if x.len() == map.len()
        ));

        let original = HashMap::<MapKeys, String>::try_from_table_attr(table_attribute).unwrap();

        assert_eq!(original, map);
    }

    #[test]
    fn test_btreemap() {
        let map = [
            (MapKeys::A, "Something in A".to_string()),
            (MapKeys::A, "Something in B".to_string()),
            (MapKeys::A, "Something in C".to_string()),
        ]
        .into_iter()
        .collect::<BTreeMap<_, _>>();

        let table_attribute = TableAttribute::from(map.clone());

        assert!(matches!(
            &table_attribute,
            TableAttribute::Map(x)
            if x.len() == map.len()
        ));

        let original = BTreeMap::<MapKeys, String>::try_from_table_attr(table_attribute).unwrap();

        assert_eq!(original, map);
    }
}