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
use crate::api::plugin::{ConfigFilter, ConfigReq, ConfigResp};

/**
 * For example:cipher-AES-dataId.
 */
pub const DEFAULT_CIPHER_PREFIX: &str = "cipher-";

pub const DEFAULT_CIPHER_SPLIT: &str = "-";

/// EncryptionPlugin for Config.
#[async_trait::async_trait]
pub trait EncryptionPlugin: Send + Sync {
    /**
     * Whether need to do cipher.
     *
     * e.g. data_id = "cipher-AES-dataId"
     */
    fn need_cipher(&self, data_id: &str) -> bool {
        data_id.starts_with(DEFAULT_CIPHER_PREFIX)
            && self
                .parse_algorithm_name(data_id)
                .eq(&self.algorithm_name())
    }

    /**
     * Parse encryption algorithm name.
     *
     * @param data_id data_id
     * @return algorithm name
     */
    fn parse_algorithm_name(&self, data_id: &str) -> String {
        data_id
            .split(DEFAULT_CIPHER_SPLIT)
            .nth(1)
            .unwrap()
            .to_string()
    }

    /**
     * Encrypt interface.
     *
     * @param secret_key secret key
     * @param content   content unencrypted
     * @return encrypt value
     */
    async fn encrypt(&self, secret_key: &str, content: &str) -> String;

    /**
     * Decrypt interface.
     *
     * @param secret_key secret key
     * @param content   encrypted
     * @return decrypt value
     */
    async fn decrypt(&self, secret_key: &str, content: &str) -> String;

    /**
     * Generate secret key. It only be known by you.
     *
     * @return Secret key
     */
    async fn generate_secret_key(&self) -> String;

    /**
     * Algorithm name. e.g. AES,AES128,AES256,DES,3DES,...
     *
     * @return name
     */
    fn algorithm_name(&self) -> String;

    /**
     * Encrypt secret Key. It will be transmitted in the network.
     *
     * @param secretKey secretKey
     * @return encrypted secretKey
     */
    async fn encrypt_secret_key(&self, secret_key: &str) -> String;

    /**
     * Decrypt secret Key.
     *
     * @param secret_key secretKey
     * @return decrypted secretKey
     */
    async fn decrypt_secret_key(&self, secret_key: &str) -> String;
}

/// ConfigEncryptionFilter handle with [`EncryptionPlugin`]
pub struct ConfigEncryptionFilter {
    encryption_plugins: Vec<Box<dyn EncryptionPlugin>>,
}

impl ConfigEncryptionFilter {
    pub fn new(encryption_plugins: Vec<Box<dyn EncryptionPlugin>>) -> Self {
        Self { encryption_plugins }
    }
}

#[async_trait::async_trait]
impl ConfigFilter for ConfigEncryptionFilter {
    async fn filter(
        &self,
        config_req: Option<&mut ConfigReq>,
        config_resp: Option<&mut ConfigResp>,
    ) {
        // Publish configuration, encrypt
        if let Some(config_req) = config_req {
            for plugin in &self.encryption_plugins {
                if !plugin.need_cipher(&config_req.data_id) {
                    continue;
                }

                let secret_key = plugin.generate_secret_key().await;
                let encrypted_content = plugin.encrypt(&secret_key, &config_req.content).await;
                let encrypted_secret_key = plugin.encrypt_secret_key(&secret_key).await;

                // set encrypted data.
                config_req.encrypted_data_key = encrypted_secret_key;
                config_req.content = encrypted_content;
                break;
            }
        }

        // Get configuration, decrypt
        if let Some(config_resp) = config_resp {
            if !config_resp.encrypted_data_key.is_empty() {
                for plugin in &self.encryption_plugins {
                    if !plugin.need_cipher(&config_resp.data_id) {
                        continue;
                    }

                    // get encrypted data.
                    let encrypted_secret_key = &config_resp.encrypted_data_key;
                    let encrypted_content = &config_resp.content;

                    let decrypted_secret_key =
                        plugin.decrypt_secret_key(encrypted_secret_key).await;
                    let decrypted_content = plugin
                        .decrypt(&decrypted_secret_key, encrypted_content)
                        .await;

                    // set decrypted data.
                    config_resp.content = decrypted_content;
                    break;
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::api::plugin::config_filter::{ConfigReq, ConfigResp};
    use crate::api::plugin::encryption::DEFAULT_CIPHER_PREFIX;
    use crate::api::plugin::{ConfigEncryptionFilter, ConfigFilter, EncryptionPlugin};

    struct TestEncryptionPlugin;

    #[async_trait::async_trait]
    impl EncryptionPlugin for TestEncryptionPlugin {
        async fn encrypt(&self, secret_key: &str, content: &str) -> String {
            secret_key.to_owned() + content
        }

        async fn decrypt(&self, secret_key: &str, content: &str) -> String {
            content.replace(secret_key, "")
        }

        async fn generate_secret_key(&self) -> String {
            "secret-key".to_string()
        }

        fn algorithm_name(&self) -> String {
            "TEST".to_string()
        }

        async fn encrypt_secret_key(&self, secret_key: &str) -> String {
            "crypt_".to_owned() + secret_key
        }

        async fn decrypt_secret_key(&self, secret_key: &str) -> String {
            secret_key.replace("crypt_", "")
        }
    }

    #[tokio::test]
    async fn test_config_encryption_filters_empty() {
        let config_encryption_filter = ConfigEncryptionFilter::new(vec![]);

        let (data_id, group, namespace, content, encrypted_data_key) = (
            "D".to_string(),
            "G".to_string(),
            "N".to_string(),
            "C".to_string(),
            "".to_string(),
        );

        let mut config_req = ConfigReq::new(
            data_id.clone(),
            group.clone(),
            namespace.clone(),
            content.clone(),
            encrypted_data_key.clone(),
        );
        config_encryption_filter
            .filter(Some(&mut config_req), None)
            .await;

        assert_eq!(config_req.content, encrypted_data_key + content.as_str());

        let mut config_resp = ConfigResp::new(
            config_req.data_id.clone(),
            config_req.group.clone(),
            config_req.namespace.clone(),
            config_req.content.clone(),
            config_req.encrypted_data_key.clone(),
        );
        config_encryption_filter
            .filter(None, Some(&mut config_resp))
            .await;

        assert_eq!(config_resp.content, content);
    }

    #[tokio::test]
    async fn test_config_encryption_filters() {
        let config_encryption_filter =
            ConfigEncryptionFilter::new(vec![Box::new(TestEncryptionPlugin {})]);

        let (data_id, group, namespace, content, encrypted_data_key) = (
            DEFAULT_CIPHER_PREFIX.to_owned() + "-TEST-D",
            "G".to_string(),
            "N".to_string(),
            "C".to_string(),
            "E".to_string(),
        );

        let mut config_req = ConfigReq::new(
            data_id.clone(),
            group.clone(),
            namespace.clone(),
            content.clone(),
            encrypted_data_key.clone(),
        );
        config_encryption_filter
            .filter(Some(&mut config_req), None)
            .await;

        let mut config_resp = ConfigResp::new(
            config_req.data_id.clone(),
            config_req.group.clone(),
            config_req.namespace.clone(),
            config_req.content.clone(),
            config_req.encrypted_data_key.clone(),
        );
        config_encryption_filter
            .filter(None, Some(&mut config_resp))
            .await;

        assert_eq!(config_resp.content, content);
    }

    #[tokio::test]
    async fn test_config_encryption_filters_not_need_cipher() {
        let config_encryption_filter =
            ConfigEncryptionFilter::new(vec![Box::new(TestEncryptionPlugin {})]);

        let (data_id, group, namespace, content, encrypted_data_key) = (
            "D".to_string(),
            "G".to_string(),
            "N".to_string(),
            "C".to_string(),
            "E".to_string(),
        );

        let mut config_req = ConfigReq::new(
            data_id.clone(),
            group.clone(),
            namespace.clone(),
            content.clone(),
            encrypted_data_key.clone(),
        );
        config_encryption_filter
            .filter(Some(&mut config_req), None)
            .await;

        let mut config_resp = ConfigResp::new(
            config_req.data_id.clone(),
            config_req.group.clone(),
            config_req.namespace.clone(),
            config_req.content.clone(),
            config_req.encrypted_data_key.clone(),
        );
        config_encryption_filter
            .filter(None, Some(&mut config_resp))
            .await;

        assert_eq!(config_resp.content, content);
    }
}