1use std::collections::HashMap;
5use std::sync::OnceLock;
6
7use regex::Regex;
8
9use crate::{Error, Result};
10
11pub const ENC_PREFIX: &str = "ENC(";
13
14pub const ENC_SUFFIX: &str = ")";
16
17pub fn is_encrypted(value: &str) -> bool {
30 let v = value.trim();
31 v.starts_with(ENC_PREFIX) && v.ends_with(ENC_SUFFIX)
32}
33
34pub(crate) fn wrap(encoded: &str) -> String {
36 let mut out = String::with_capacity(ENC_PREFIX.len() + encoded.len() + ENC_SUFFIX.len());
37 out.push_str(ENC_PREFIX);
38 out.push_str(encoded);
39 out.push_str(ENC_SUFFIX);
40 out
41}
42
43pub(crate) fn unwrap_enc(value: &str) -> Result<&str> {
46 let v = value.trim();
47 if !(v.starts_with(ENC_PREFIX) && v.ends_with(ENC_SUFFIX)) {
48 return Err(Error::InvalidEncFormat);
49 }
50 v.get(ENC_PREFIX.len()..v.len() - ENC_SUFFIX.len())
51 .ok_or(Error::InvalidEncFormat)
52}
53
54pub(crate) fn enc_pattern() -> &'static Regex {
56 static PATTERN: OnceLock<Regex> = OnceLock::new();
57 PATTERN.get_or_init(|| Regex::new(r"ENC\(([^)]+)\)").expect("ENC pattern is a valid regex"))
58}
59
60pub(crate) fn replace_all_enc<F>(input: &str, mut f: F) -> (String, Option<Error>)
66where
67 F: FnMut(&str) -> Result<String>,
68{
69 let mut last_err = None;
70 let out = enc_pattern().replace_all(input, |caps: ®ex::Captures<'_>| {
71 let matched = caps.get(0).map(|m| m.as_str()).unwrap_or_default();
72 match f(matched) {
73 Ok(replacement) => replacement,
74 Err(err) => {
75 last_err = Some(err);
76 matched.to_owned()
77 }
78 }
79 });
80 (out.into_owned(), last_err)
81}
82
83pub(crate) fn decrypt_map_with<F>(
87 map: &HashMap<String, String>,
88 mut f: F,
89) -> Result<HashMap<String, String>>
90where
91 F: FnMut(&str) -> Result<String>,
92{
93 let mut out = HashMap::with_capacity(map.len());
94 for (key, value) in map {
95 let decrypted = if is_encrypted(value) {
96 f(value).map_err(|err| Error::key_decrypt(key.clone(), err))?
97 } else {
98 value.clone()
99 };
100 out.insert(key.clone(), decrypted);
101 }
102 Ok(out)
103}
104
105pub trait StringEncryptor {
114 fn encrypt(&self, plaintext: &str) -> Result<String>;
116
117 fn decrypt(&self, encoded: &str) -> Result<String>;
119
120 fn encrypt_with_prefix(&self, plaintext: &str) -> Result<String> {
122 Ok(wrap(&self.encrypt(plaintext)?))
123 }
124
125 fn decrypt_prefixed(&self, value: &str) -> Result<String> {
129 self.decrypt(unwrap_enc(value)?)
130 }
131
132 fn decrypt_all_in_string(&self, input: &str) -> Result<String> {
139 let (out, err) = replace_all_enc(input, |m| self.decrypt_prefixed(m));
140 match err {
141 Some(err) => Err(err),
142 None => Ok(out),
143 }
144 }
145
146 fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
151 replace_all_enc(input, |m| self.decrypt_prefixed(m)).0
152 }
153
154 fn decrypt_map(&self, map: &HashMap<String, String>) -> Result<HashMap<String, String>> {
158 decrypt_map_with(map, |v| self.decrypt_prefixed(v))
159 }
160}
161
162impl<T: StringEncryptor + ?Sized> StringEncryptor for &T {
163 fn encrypt(&self, plaintext: &str) -> Result<String> {
164 (**self).encrypt(plaintext)
165 }
166 fn decrypt(&self, encoded: &str) -> Result<String> {
167 (**self).decrypt(encoded)
168 }
169 fn encrypt_with_prefix(&self, plaintext: &str) -> Result<String> {
170 (**self).encrypt_with_prefix(plaintext)
171 }
172 fn decrypt_prefixed(&self, value: &str) -> Result<String> {
173 (**self).decrypt_prefixed(value)
174 }
175 fn decrypt_all_in_string(&self, input: &str) -> Result<String> {
176 (**self).decrypt_all_in_string(input)
177 }
178 fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
179 (**self).decrypt_all_in_string_lossy(input)
180 }
181 fn decrypt_map(&self, map: &HashMap<String, String>) -> Result<HashMap<String, String>> {
182 (**self).decrypt_map(map)
183 }
184}
185
186impl<T: StringEncryptor + ?Sized> StringEncryptor for Box<T> {
187 fn encrypt(&self, plaintext: &str) -> Result<String> {
188 (**self).encrypt(plaintext)
189 }
190 fn decrypt(&self, encoded: &str) -> Result<String> {
191 (**self).decrypt(encoded)
192 }
193 fn encrypt_with_prefix(&self, plaintext: &str) -> Result<String> {
194 (**self).encrypt_with_prefix(plaintext)
195 }
196 fn decrypt_prefixed(&self, value: &str) -> Result<String> {
197 (**self).decrypt_prefixed(value)
198 }
199 fn decrypt_all_in_string(&self, input: &str) -> Result<String> {
200 (**self).decrypt_all_in_string(input)
201 }
202 fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
203 (**self).decrypt_all_in_string_lossy(input)
204 }
205 fn decrypt_map(&self, map: &HashMap<String, String>) -> Result<HashMap<String, String>> {
206 (**self).decrypt_map(map)
207 }
208}
209
210macro_rules! impl_string_encryptor {
214 ($t:ty) => {
215 impl $t {
216 pub fn encrypt_with_prefix(&self, plaintext: &str) -> $crate::Result<String> {
221 Ok($crate::prefix::wrap(&self.encrypt(plaintext)?))
222 }
223
224 pub fn decrypt_prefixed(&self, value: &str) -> $crate::Result<String> {
230 self.decrypt($crate::prefix::unwrap_enc(value)?)
231 }
232
233 pub fn decrypt_all_in_string(&self, input: &str) -> $crate::Result<String> {
242 let (out, err) =
243 $crate::prefix::replace_all_enc(input, |m| self.decrypt_prefixed(m));
244 match err {
245 Some(err) => Err(err),
246 None => Ok(out),
247 }
248 }
249
250 pub fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
253 $crate::prefix::replace_all_enc(input, |m| self.decrypt_prefixed(m)).0
254 }
255
256 pub fn decrypt_map(
260 &self,
261 map: &::std::collections::HashMap<String, String>,
262 ) -> $crate::Result<::std::collections::HashMap<String, String>> {
263 $crate::prefix::decrypt_map_with(map, |v| self.decrypt_prefixed(v))
264 }
265 }
266
267 impl $crate::StringEncryptor for $t {
268 fn encrypt(&self, plaintext: &str) -> $crate::Result<String> {
269 <$t>::encrypt(self, plaintext)
270 }
271 fn decrypt(&self, encoded: &str) -> $crate::Result<String> {
272 <$t>::decrypt(self, encoded)
273 }
274 fn encrypt_with_prefix(&self, plaintext: &str) -> $crate::Result<String> {
275 <$t>::encrypt_with_prefix(self, plaintext)
276 }
277 fn decrypt_prefixed(&self, value: &str) -> $crate::Result<String> {
278 <$t>::decrypt_prefixed(self, value)
279 }
280 fn decrypt_all_in_string(&self, input: &str) -> $crate::Result<String> {
281 <$t>::decrypt_all_in_string(self, input)
282 }
283 fn decrypt_all_in_string_lossy(&self, input: &str) -> String {
284 <$t>::decrypt_all_in_string_lossy(self, input)
285 }
286 fn decrypt_map(
287 &self,
288 map: &::std::collections::HashMap<String, String>,
289 ) -> $crate::Result<::std::collections::HashMap<String, String>> {
290 <$t>::decrypt_map(self, map)
291 }
292 }
293 };
294}
295
296pub(crate) use impl_string_encryptor;
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 struct Reverse;
304
305 impl StringEncryptor for Reverse {
306 fn encrypt(&self, plaintext: &str) -> Result<String> {
307 if plaintext.is_empty() {
308 return Err(Error::EmptyValue);
309 }
310 Ok(plaintext.chars().rev().collect())
311 }
312 fn decrypt(&self, encoded: &str) -> Result<String> {
313 if encoded == "bad" {
314 return Err(Error::DecryptionFailed);
315 }
316 Ok(encoded.chars().rev().collect())
317 }
318 }
319
320 #[test]
321 fn is_encrypted_matches_gocrypt() {
322 for ok in ["ENC(abc)", " ENC(abc) ", "ENC()", "\tENC(a b)\n"] {
323 assert!(is_encrypted(ok), "{ok:?}");
324 }
325 for bad in [
326 "enc(abc)",
327 "ENC(abc",
328 "abc",
329 "",
330 "ENC(",
331 "ENC",
332 ")",
333 "xENC(abc)",
334 ] {
335 assert!(!is_encrypted(bad), "{bad:?}");
336 }
337 }
338
339 #[test]
340 fn unwrap_enc_extracts_payload() {
341 assert_eq!(unwrap_enc("ENC(x)").unwrap(), "x");
342 assert_eq!(unwrap_enc(" ENC(abc==)\n").unwrap(), "abc==");
343 assert_eq!(unwrap_enc("ENC()").unwrap(), "");
344 assert!(matches!(unwrap_enc("x"), Err(Error::InvalidEncFormat)));
345 assert!(matches!(unwrap_enc("ENC(x"), Err(Error::InvalidEncFormat)));
346 assert!(matches!(unwrap_enc(""), Err(Error::InvalidEncFormat)));
347 }
348
349 #[test]
350 fn wrap_adds_prefix_and_suffix() {
351 assert_eq!(wrap("abc"), "ENC(abc)");
352 assert_eq!(wrap(""), "ENC()");
353 }
354
355 #[test]
356 fn replace_all_enc_zero_one_many() {
357 let upper = |m: &str| Ok(unwrap_enc(m)?.to_uppercase());
358
359 let (out, err) = replace_all_enc("nothing here", upper);
360 assert_eq!(out, "nothing here");
361 assert!(err.is_none());
362
363 let (out, err) = replace_all_enc("k=ENC(abc)", upper);
364 assert_eq!(out, "k=ABC");
365 assert!(err.is_none());
366
367 let (out, err) = replace_all_enc("a=ENC(x) b=ENC(y)\nc=ENC(z)", upper);
368 assert_eq!(out, "a=X b=Y\nc=Z");
369 assert!(err.is_none());
370 }
371
372 #[test]
373 fn replace_all_enc_keeps_failed_match_and_returns_last_error() {
374 let f = |m: &str| {
375 let inner = unwrap_enc(m)?;
376 if inner == "bad" {
377 Err(Error::DecryptionFailed)
378 } else {
379 Ok(inner.to_uppercase())
380 }
381 };
382 let (out, err) = replace_all_enc("a=ENC(x) b=ENC(bad) c=ENC(y)", f);
383 assert_eq!(out, "a=X b=ENC(bad) c=Y");
384 assert!(matches!(err, Some(Error::DecryptionFailed)));
385 }
386
387 #[test]
388 fn replace_all_enc_regex_edge_cases() {
389 let mut seen = Vec::new();
390 let mut spy = |m: &str| {
391 seen.push(m.to_owned());
392 Ok(String::from("_"))
393 };
394 let (out, _) = replace_all_enc("ENC() ENC(ENC(x)) ENC(a(b)", &mut spy);
397 assert_eq!(out, "ENC() _) _");
398 assert_eq!(seen, vec!["ENC(ENC(x)", "ENC(a(b)"]);
399 }
400
401 #[test]
402 fn decrypt_map_with_mixed_values() {
403 let mut map = HashMap::new();
404 map.insert("host".to_owned(), "localhost".to_owned());
405 map.insert("secret".to_owned(), "ENC(abc)".to_owned());
406 let out = decrypt_map_with(&map, |v| Ok(unwrap_enc(v)?.to_uppercase())).unwrap();
407 assert_eq!(out["host"], "localhost");
408 assert_eq!(out["secret"], "ABC");
409 assert_eq!(out.len(), 2);
410 }
411
412 #[test]
413 fn decrypt_map_with_reports_failing_key() {
414 let mut map = HashMap::new();
415 map.insert("ok".to_owned(), "ENC(abc)".to_owned());
416 map.insert("api_key".to_owned(), "ENC(bad)".to_owned());
417 let err = decrypt_map_with(&map, |v| {
418 let inner = unwrap_enc(v)?;
419 if inner == "bad" {
420 Err(Error::DecryptionFailed)
421 } else {
422 Ok(inner.to_owned())
423 }
424 })
425 .unwrap_err();
426 match err {
427 Error::KeyDecrypt { key, source } => {
428 assert_eq!(key, "api_key");
429 assert!(matches!(*source, Error::DecryptionFailed));
430 }
431 other => panic!("unexpected error: {other:?}"),
432 }
433 }
434
435 #[test]
436 fn trait_default_methods() {
437 let enc = Reverse;
438 assert_eq!(enc.encrypt_with_prefix("abc").unwrap(), "ENC(cba)");
439 assert_eq!(enc.decrypt_prefixed(" ENC(cba) ").unwrap(), "abc");
440 assert!(matches!(
441 enc.decrypt_prefixed("cba"),
442 Err(Error::InvalidEncFormat)
443 ));
444 assert_eq!(
445 enc.decrypt_all_in_string("x=ENC(cba) y=ENC(fed)").unwrap(),
446 "x=abc y=def"
447 );
448 assert!(matches!(
449 enc.decrypt_all_in_string("x=ENC(cba) y=ENC(bad)"),
450 Err(Error::DecryptionFailed)
451 ));
452 assert_eq!(
453 enc.decrypt_all_in_string_lossy("x=ENC(cba) y=ENC(bad)"),
454 "x=abc y=ENC(bad)"
455 );
456
457 let mut map = HashMap::new();
458 map.insert("a".to_owned(), "ENC(cba)".to_owned());
459 map.insert("b".to_owned(), "plain".to_owned());
460 let out = enc.decrypt_map(&map).unwrap();
461 assert_eq!(out["a"], "abc");
462 assert_eq!(out["b"], "plain");
463 }
464
465 #[test]
466 fn trait_is_object_safe_and_forwards_through_box_and_ref() {
467 let boxed: Box<dyn StringEncryptor> = Box::new(Reverse);
468 assert_eq!(boxed.encrypt_with_prefix("abc").unwrap(), "ENC(cba)");
469 let by_ref: &dyn StringEncryptor = &Reverse;
470 assert_eq!(by_ref.decrypt_prefixed("ENC(cba)").unwrap(), "abc");
471
472 fn generic<E: StringEncryptor>(e: E) -> String {
473 e.decrypt("cba").unwrap()
474 }
475 assert_eq!(generic(&Reverse), "abc");
476 assert_eq!(generic(boxed), "abc");
477 }
478}