rustcrypt_jasypt/config_loader.rs
1//! [`ConfigLoader`]: load `.env`, flat YAML and JSON configuration files with
2//! automatic `ENC(...)` decryption (feature `config`).
3
4use std::collections::HashMap;
5use std::fs;
6use std::io::{BufRead, BufReader};
7use std::path::Path;
8
9use serde::de::DeserializeOwned;
10use serde_json::Value;
11
12use crate::prefix::is_encrypted;
13use crate::{Encryptor, Error, Result, StringEncryptor};
14
15/// Loads configuration files and transparently decrypts every `ENC(...)`
16/// value with the configured encryptor.
17///
18/// The loader is generic over the encryptor. [`ConfigLoader::new`] uses
19/// [`Encryptor`] (AES-256-GCM) like GoCrypt's `NewConfigLoader`; use
20/// [`ConfigLoader::with_encryptor`] to read files shared with Java Jasypt:
21///
22/// ```
23/// use rustcrypt_jasypt::{ConfigLoader, JasyptEncryptor};
24///
25/// # fn main() -> rustcrypt_jasypt::Result<()> {
26/// // AES-256-GCM (family-internal format)
27/// let loader = ConfigLoader::new("password")?;
28///
29/// // PBEWithMD5AndDES, readable by Java Jasypt (e.g. a JasperReport service)
30/// let loader = ConfigLoader::with_encryptor(JasyptEncryptor::new("password")?);
31/// # let _ = loader;
32/// # Ok(())
33/// # }
34/// ```
35///
36/// # File formats
37///
38/// * [`load_env_file`](Self::load_env_file): `KEY=VALUE` lines. Blank lines
39/// and lines starting with `#` are skipped, keys and values are trimmed and
40/// surrounding single or double quotes are removed from the value.
41/// * [`load_yaml`](Self::load_yaml): the same line-based parser splitting on
42/// the first `:`. This intentionally mirrors GoCrypt's simplified loader: it
43/// flattens nesting (a `database:` line yields an empty `database` entry and
44/// ` password: ENC(...)` yields `password`). Use a real YAML crate plus
45/// [`decrypt_map`](StringEncryptor::decrypt_map) for complex documents.
46/// * [`load_json`](Self::load_json): full JSON via serde. Every string inside
47/// objects and arrays, at any depth, that looks like `ENC(...)` is decrypted;
48/// strings that fail to decrypt are kept as-is.
49#[derive(Debug, Clone)]
50pub struct ConfigLoader<E: StringEncryptor = Encryptor> {
51 encryptor: E,
52}
53
54impl ConfigLoader<Encryptor> {
55 /// Creates a loader backed by an [`Encryptor`] (AES-256-GCM) with default
56 /// parameters. Returns [`Error::EmptyPassword`] for an empty password.
57 pub fn new(password: &str) -> Result<Self> {
58 Ok(Self {
59 encryptor: Encryptor::new(password)?,
60 })
61 }
62}
63
64impl<E: StringEncryptor> ConfigLoader<E> {
65 /// Creates a loader backed by any [`StringEncryptor`], for example a
66 /// [`JasyptEncryptor`](crate::JasyptEncryptor) or an [`Encryptor`] with
67 /// custom iterations.
68 pub fn with_encryptor(encryptor: E) -> Self {
69 Self { encryptor }
70 }
71
72 /// The underlying encryptor.
73 pub fn encryptor(&self) -> &E {
74 &self.encryptor
75 }
76
77 /// Loads a `.env`-style file and returns its key/value pairs with every
78 /// `ENC(...)` value decrypted.
79 ///
80 /// A value that fails to decrypt aborts with [`Error::KeyDecrypt`] naming
81 /// the key. I/O problems are reported as [`Error::Io`].
82 ///
83 /// ```no_run
84 /// use rustcrypt_jasypt::ConfigLoader;
85 ///
86 /// # fn main() -> rustcrypt_jasypt::Result<()> {
87 /// let loader = ConfigLoader::new(&std::env::var("RUSTCRYPT_PASSWORD").unwrap())?;
88 /// let config = loader.load_env_file(".env")?;
89 /// println!("{}", config["DATABASE_PASSWORD"]);
90 /// # Ok(())
91 /// # }
92 /// ```
93 pub fn load_env_file(&self, path: impl AsRef<Path>) -> Result<HashMap<String, String>> {
94 self.load_key_values(path.as_ref(), '=')
95 }
96
97 /// Loads a simple flat YAML file (`key: value` lines) and returns its
98 /// pairs with every `ENC(...)` value decrypted. See the type-level docs
99 /// for the (GoCrypt-compatible) limitations of this parser.
100 pub fn load_yaml(&self, path: impl AsRef<Path>) -> Result<HashMap<String, String>> {
101 self.load_key_values(path.as_ref(), ':')
102 }
103
104 fn load_key_values(&self, path: &Path, separator: char) -> Result<HashMap<String, String>> {
105 let file = fs::File::open(path)?;
106 let mut config = HashMap::new();
107
108 for line in BufReader::new(file).lines() {
109 let line = line?;
110 let line = line.trim();
111 if line.is_empty() || line.starts_with('#') {
112 continue;
113 }
114 let Some((key, value)) = line.split_once(separator) else {
115 continue;
116 };
117 let key = key.trim();
118 let value = value.trim().trim_matches(|c| c == '"' || c == '\'');
119
120 let value = if is_encrypted(value) {
121 self.encryptor
122 .decrypt_prefixed(value)
123 .map_err(|err| Error::key_decrypt(key, err))?
124 } else {
125 value.to_owned()
126 };
127 config.insert(key.to_owned(), value);
128 }
129
130 Ok(config)
131 }
132
133 /// Loads a JSON file into `T`, decrypting every `ENC(...)` string at any
134 /// depth first. Strings that fail to decrypt are left unchanged so the
135 /// caller can surface them.
136 ///
137 /// ```no_run
138 /// use rustcrypt_jasypt::ConfigLoader;
139 /// use serde::Deserialize;
140 ///
141 /// #[derive(Deserialize)]
142 /// struct Database { host: String, password: String }
143 ///
144 /// #[derive(Deserialize)]
145 /// struct Config { database: Database }
146 ///
147 /// # fn main() -> rustcrypt_jasypt::Result<()> {
148 /// let loader = ConfigLoader::new("password")?;
149 /// let config: Config = loader.load_json("config.json")?;
150 /// println!("{}", config.database.password);
151 /// # Ok(())
152 /// # }
153 /// ```
154 pub fn load_json<T: DeserializeOwned>(&self, path: impl AsRef<Path>) -> Result<T> {
155 let data = fs::read_to_string(path)?;
156 let mut value: Value = serde_json::from_str(&data)?;
157 self.decrypt_json_value(&mut value);
158 Ok(serde_json::from_value(value)?)
159 }
160
161 /// Recursively decrypts every `ENC(...)` string inside `value` (objects,
162 /// arrays and nested combinations). Strings that fail to decrypt are left
163 /// unchanged; non-string values are untouched.
164 pub fn decrypt_json_value(&self, value: &mut Value) {
165 match value {
166 Value::String(s) => {
167 if is_encrypted(s) {
168 if let Ok(decrypted) = self.encryptor.decrypt_prefixed(s) {
169 *s = decrypted;
170 }
171 }
172 }
173 Value::Array(items) => items.iter_mut().for_each(|v| self.decrypt_json_value(v)),
174 Value::Object(map) => map.values_mut().for_each(|v| self.decrypt_json_value(v)),
175 Value::Null | Value::Bool(_) | Value::Number(_) => {}
176 }
177 }
178
179 /// Loads a `.env`-style file with [`load_env_file`](Self::load_env_file)
180 /// and exports every pair as a process environment variable.
181 ///
182 /// Call this during single-threaded start-up: the standard library's
183 /// `set_var` is not safe to run while other threads read the environment.
184 /// Returns [`Error::InvalidParameter`] for a key that cannot be an
185 /// environment variable name (empty, or containing `=` / NUL).
186 pub fn set_to_env(&self, path: impl AsRef<Path>) -> Result<()> {
187 let config = self.load_env_file(path)?;
188 for (key, value) in config {
189 set_env_var(&key, &value)?;
190 }
191 Ok(())
192 }
193}
194
195/// Sets a process environment variable after validating the name.
196///
197/// `std::env::set_var` is safe to call in edition 2021 but is `unsafe` from
198/// edition 2024 onwards (mutating the environment can race with concurrent
199/// reads on some platforms). The `unsafe` block documents that contract now so
200/// the crate is ready for the edition bump.
201#[allow(unsafe_code, unused_unsafe)]
202fn set_env_var(key: &str, value: &str) -> Result<()> {
203 if key.is_empty() || key.contains('=') || key.contains('\0') || value.contains('\0') {
204 return Err(Error::InvalidParameter(format!(
205 "cannot set environment variable {key:?}"
206 )));
207 }
208 // SAFETY: `set_to_env` is documented to be called during single-threaded
209 // start-up before other threads read the environment (the same contract
210 // as GoCrypt's SetToEnv / os.Setenv). The key was validated above so the
211 // call cannot panic.
212 unsafe { std::env::set_var(key, value) };
213 Ok(())
214}