Skip to main content

configbuilder_pattern_substitution/
pattern_whitelist_policy.rs

1use crate::{SubstitutionError, SubstitutionPolicy};
2
3/// Allows only environment variables whose names fully match a regular expression.
4#[derive(Debug)]
5pub struct PatternWhitelistPolicy {
6    pattern: regex::Regex,
7    pattern_str: String,
8}
9
10impl PatternWhitelistPolicy {
11    /// Create a regex-backed whitelist policy.
12    pub fn new(pattern: String) -> Result<Self, String> {
13        regex::Regex::new(&pattern)
14            .map(|regex| Self {
15                pattern: regex,
16                pattern_str: pattern,
17            })
18            .map_err(|e| format!("Invalid regex pattern: {}", e))
19    }
20
21    /// Return the original regex pattern string.
22    pub fn pattern(&self) -> &str {
23        &self.pattern_str
24    }
25}
26
27impl SubstitutionPolicy for PatternWhitelistPolicy {
28    fn validate(&self, var_name: &str) -> Result<(), SubstitutionError> {
29        if self.pattern.is_match(var_name) {
30            Ok(())
31        } else {
32            Err(SubstitutionError::VariableRejected {
33                var_name: var_name.to_string(),
34                reason: format!("does not match pattern: {}", self.pattern()),
35                policy: self.description(),
36            })
37        }
38    }
39
40    fn description(&self) -> String {
41        format!("PatternWhitelist({})", self.pattern())
42    }
43}