bitwarden_crypto/safe/
data_envelope_namespace.rs

1use crate::safe::DataEnvelopeError;
2
3/// Data envelopes are domain-separated within bitwarden, to prevent cross protocol attacks.
4///
5/// A new struct shall use a new data envelope namespace. Generally, this means
6/// that a data envelope namespace has exactly one associated valid message struct. Internal
7/// versioning within a namespace is permitted and up to the domain owner to ensure is done
8/// correctly.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum DataEnvelopeNamespace {
11    /// The namespace for vault items ("ciphers")
12    VaultItem = 1,
13    /// This namespace is only used in tests
14    #[cfg(test)]
15    ExampleNamespace = -1,
16    /// This namespace is only used in tests
17    #[cfg(test)]
18    ExampleNamespace2 = -2,
19}
20
21impl DataEnvelopeNamespace {
22    /// Returns the numeric value of the namespace.
23    pub fn as_i64(&self) -> i64 {
24        *self as i64
25    }
26}
27
28impl TryFrom<i64> for DataEnvelopeNamespace {
29    type Error = DataEnvelopeError;
30
31    fn try_from(value: i64) -> Result<Self, Self::Error> {
32        match value {
33            1 => Ok(DataEnvelopeNamespace::VaultItem),
34            #[cfg(test)]
35            -1 => Ok(DataEnvelopeNamespace::ExampleNamespace),
36            #[cfg(test)]
37            -2 => Ok(DataEnvelopeNamespace::ExampleNamespace2),
38            _ => Err(DataEnvelopeError::InvalidNamespace),
39        }
40    }
41}
42
43impl TryFrom<i128> for DataEnvelopeNamespace {
44    type Error = DataEnvelopeError;
45
46    fn try_from(value: i128) -> Result<Self, Self::Error> {
47        let Ok(value) = i64::try_from(value) else {
48            return Err(DataEnvelopeError::InvalidNamespace);
49        };
50        Self::try_from(value)
51    }
52}