openzeppelin_relayer/models/
plain_or_env_value.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
//! PlainOrEnvValue module for secure configuration value handling
//!
//! This module provides functionality to securely handle configuration values
//! that can either be provided directly in the configuration file ("plain")
//! or retrieved from environment variables ("env").
//!
//! The `PlainOrEnvValue` enum supports two variants:
//! - `Plain`: For values stored directly in the configuration
//! - `Env`: For values that should be retrieved from environment variables
//!
//! When a value is requested, if it's an "env" variant, the module will
//! attempt to retrieve the value from the specified environment variable.
//! All values are wrapped in `SecretString` to ensure secure memory handling.
use serde::{Deserialize, Serialize};
use thiserror::Error;
use validator::ValidationError;
use zeroize::Zeroizing;

use super::SecretString;

#[derive(Error, Debug)]
pub enum PlainOrEnvValueError {
    #[error("Missing env var: {0}")]
    MissingEnvVar(String),
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum PlainOrEnvValue {
    Env { value: String },
    Plain { value: SecretString },
}

impl PlainOrEnvValue {
    pub fn get_value(&self) -> Result<SecretString, PlainOrEnvValueError> {
        match self {
            PlainOrEnvValue::Env { value } => {
                let value = Zeroizing::new(std::env::var(value).map_err(|_| {
                    PlainOrEnvValueError::MissingEnvVar(format!(
                        "Environment variable {} not found",
                        value
                    ))
                })?);
                Ok(SecretString::new(&value))
            }
            PlainOrEnvValue::Plain { value } => Ok(value.clone()),
        }
    }
    pub fn is_empty(&self) -> bool {
        let value = self.get_value();

        match value {
            Ok(v) => v.is_empty(),
            Err(_) => true,
        }
    }
}

pub fn validate_plain_or_env_value(plain_or_env: &PlainOrEnvValue) -> Result<(), ValidationError> {
    let value = plain_or_env.get_value().map_err(|e| {
        let mut err = ValidationError::new("plain_or_env_value_error");
        err.message = Some(format!("plain_or_env_value_error: {}", e).into());
        err
    })?;

    match value.is_empty() {
        true => Err(ValidationError::new(
            "plain_or_env_value_error: value cannot be empty",
        )),
        false => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    use validator::Validate;

    #[derive(Validate)]
    struct TestStruct {
        #[validate(custom(function = "validate_plain_or_env_value"))]
        value: PlainOrEnvValue,
    }

    #[test]
    fn test_plain_value_get_value() {
        let plain = PlainOrEnvValue::Plain {
            value: SecretString::new("test-secret"),
        };

        let result = plain.get_value().unwrap();
        result.as_str(|s| {
            assert_eq!(s, "test-secret");
        });
    }

    #[test]
    fn test_env_value_get_value_when_env_exists() {
        env::set_var("TEST_ENV_VAR", "env-secret-value");

        let env_value = PlainOrEnvValue::Env {
            value: "TEST_ENV_VAR".to_string(),
        };

        let result = env_value.get_value().unwrap();
        result.as_str(|s| {
            assert_eq!(s, "env-secret-value");
        });

        env::remove_var("TEST_ENV_VAR");
    }

    #[test]
    fn test_env_value_get_value_when_env_missing() {
        env::remove_var("NONEXISTENT_VAR");

        let env_value = PlainOrEnvValue::Env {
            value: "NONEXISTENT_VAR".to_string(),
        };

        let result = env_value.get_value();
        assert!(result.is_err());

        match result {
            Err(PlainOrEnvValueError::MissingEnvVar(msg)) => {
                assert!(msg.contains("NONEXISTENT_VAR"));
            }
            _ => panic!("Expected MissingEnvVar error"),
        }
    }

    #[test]
    fn test_is_empty_with_plain_empty_value() {
        let plain = PlainOrEnvValue::Plain {
            value: SecretString::new(""),
        };

        assert!(plain.is_empty());
    }

    #[test]
    fn test_is_empty_with_plain_non_empty_value() {
        let plain = PlainOrEnvValue::Plain {
            value: SecretString::new("non-empty"),
        };

        assert!(!plain.is_empty());
    }

    #[test]
    fn test_is_empty_with_env_missing_var() {
        env::remove_var("NONEXISTENT_VAR");

        let env_value = PlainOrEnvValue::Env {
            value: "NONEXISTENT_VAR".to_string(),
        };

        assert!(env_value.is_empty());
    }

    #[test]
    fn test_is_empty_with_env_empty_var() {
        env::set_var("EMPTY_ENV_VAR", "");

        let env_value = PlainOrEnvValue::Env {
            value: "EMPTY_ENV_VAR".to_string(),
        };

        assert!(env_value.is_empty());

        env::remove_var("EMPTY_ENV_VAR");
    }

    #[test]
    fn test_is_empty_with_env_non_empty_var() {
        env::set_var("TEST_ENV_VAR", "some-value");

        let env_value = PlainOrEnvValue::Env {
            value: "TEST_ENV_VAR".to_string(),
        };

        assert!(!env_value.is_empty());

        env::remove_var("TEST_ENV_VAR");
    }

    #[test]
    fn test_validator_with_plain_empty_value() {
        let test_struct = TestStruct {
            value: PlainOrEnvValue::Plain {
                value: SecretString::new(""),
            },
        };

        let result = test_struct.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_validator_with_plain_non_empty_value() {
        let test_struct = TestStruct {
            value: PlainOrEnvValue::Plain {
                value: SecretString::new("non-empty"),
            },
        };

        let result = test_struct.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_validator_with_env_missing_var() {
        env::remove_var("NONEXISTENT_VAR");

        let test_struct = TestStruct {
            value: PlainOrEnvValue::Env {
                value: "NONEXISTENT_VAR".to_string(),
            },
        };

        let result = test_struct.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_validator_with_env_empty_var() {
        env::set_var("EMPTY_ENV_VAR", "");

        let test_struct = TestStruct {
            value: PlainOrEnvValue::Env {
                value: "EMPTY_ENV_VAR".to_string(),
            },
        };

        let result = test_struct.validate();
        assert!(result.is_err());

        env::remove_var("EMPTY_ENV_VAR");
    }

    #[test]
    fn test_validator_with_env_non_empty_var() {
        env::set_var("TEST_ENV_VAR", "some-value");

        let test_struct = TestStruct {
            value: PlainOrEnvValue::Env {
                value: "TEST_ENV_VAR".to_string(),
            },
        };

        let result = test_struct.validate();
        assert!(result.is_ok());

        env::remove_var("TEST_ENV_VAR");
    }

    #[test]
    fn test_serialize_plain_value() {
        let plain = PlainOrEnvValue::Plain {
            value: SecretString::new("test-secret"),
        };

        let serialized = serde_json::to_string(&plain).unwrap();

        assert!(serialized.contains(r#""type":"plain"#));
        assert!(serialized.contains(r#""value":"REDACTED"#));
    }

    #[test]
    fn test_serialize_env_value() {
        let env_value = PlainOrEnvValue::Env {
            value: "TEST_ENV_VAR".to_string(),
        };

        let serialized = serde_json::to_string(&env_value).unwrap();

        assert!(serialized.contains(r#""type":"env"#));
        assert!(serialized.contains(r#""value":"TEST_ENV_VAR"#));
    }

    #[test]
    fn test_deserialize_plain_value() {
        let json = r#"{"type":"plain","value":"test-secret"}"#;

        let deserialized: PlainOrEnvValue = serde_json::from_str(json).unwrap();

        match &deserialized {
            PlainOrEnvValue::Plain { value } => {
                value.as_str(|s| {
                    assert_eq!(s, "test-secret");
                });
            }
            _ => panic!("Expected Plain variant"),
        }
    }

    #[test]
    fn test_deserialize_env_value() {
        let json = r#"{"type":"env","value":"TEST_ENV_VAR"}"#;

        let deserialized: PlainOrEnvValue = serde_json::from_str(json).unwrap();

        match &deserialized {
            PlainOrEnvValue::Env { value } => {
                assert_eq!(value, "TEST_ENV_VAR");
            }
            _ => panic!("Expected Env variant"),
        }
    }

    #[test]
    fn test_error_messages() {
        let error = PlainOrEnvValueError::MissingEnvVar("TEST_VAR".to_string());
        let message = format!("{}", error);
        assert_eq!(message, "Missing env var: TEST_VAR");
    }

    #[test]
    fn test_validation_error_messages() {
        let test_struct = TestStruct {
            value: PlainOrEnvValue::Plain {
                value: SecretString::new(""),
            },
        };

        let result = test_struct.validate();
        assert!(result.is_err());

        if let Err(errors) = result {
            let field_errors = errors.field_errors();
            assert!(field_errors.contains_key("value"));

            let error_msgs = &field_errors["value"];
            assert!(!error_msgs.is_empty());

            let has_empty_message = error_msgs
                .iter()
                .any(|e| e.code == "plain_or_env_value_error: value cannot be empty");

            assert!(
                has_empty_message,
                "Validation error should mention empty value"
            );
        }
    }
}