darkwing/server/services/
config_encryption_services.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 aes::cipher::generic_array::GenericArray;
use aes_gcm::{
  aead::{Aead, KeyInit},
  Aes256Gcm, Nonce,
};
use async_trait::async_trait;
use base64::{engine::general_purpose, Engine as _};
use mockall::automock;
use std::sync::Arc;

use crate::{
  config::DarkwingConfig,
  server::error::{AppResult, Error},
  server::services::browser_profile_services::config::BrowserProfileConfig,
};

/// A reference counter for our status service allows us to safely pass
/// instances around which depend on the database, and ultimately, our
/// connection pools.
pub type DynConfigEncryption = Arc<dyn ConfigEncryptionTrait + Send + Sync>;

#[automock]
#[async_trait]
pub trait ConfigEncryptionTrait {
  async fn encrypt_config(
    &self,
    config: BrowserProfileConfig,
  ) -> AppResult<String>;
}

#[derive(Clone)]
pub struct ConfigEncryptionService {
  config: Arc<DarkwingConfig>,
}

impl ConfigEncryptionService {
  pub fn new(config: Arc<DarkwingConfig>) -> Self {
    Self { config }
  }

  fn encrypt_string(string: String, key: String) -> AppResult<String> {
    let key = GenericArray::from_slice(key.as_bytes());

    let cipher = Aes256Gcm::new(key);
    let nonce = Nonce::from_slice(&[0u8; 12]); // 12 zero bytes for nonce

    let ciphertext = cipher
      .encrypt(nonce, string.as_bytes())
      .map_err(|_| Error::AesGcmError)?;

    let encoded = general_purpose::STANDARD.encode(ciphertext);

    Ok(encoded)
  }
}

#[async_trait]
impl ConfigEncryptionTrait for ConfigEncryptionService {
  /// Encrypts the config using AES-256-GCM.
  /// Returns a base64 encoded string.
  async fn encrypt_config(
    &self,
    config: BrowserProfileConfig,
  ) -> AppResult<String> {
    let json = config.json()?;

    Self::encrypt_string(json, self.config.config_encryption_key.clone())
  }
}

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

  #[test]
  fn test_encrypt_config() {
    let text = "happy new year 2020".into();
    let encoded =
      "a3YrXdzPOREU8Wf7ixCIdEgGm5pLTzSAAQieJFE4/UQwAAY=".to_string();
    let key = "rQFLdz7zKp4KggT7b7qmLt7MEgh598mx".into();

    assert_eq!(
      encoded,
      ConfigEncryptionService::encrypt_string(text, key).unwrap()
    );
  }
}