1use bytes::Bytes;
2use krab_crypt::{Keyring, is_encrypted};
3use krab_store::Codec;
4
5pub struct SecretCodec(Option<Keyring>);
6
7impl SecretCodec {
8 pub fn new(keyring: Option<Keyring>) -> Self {
9 Self(keyring)
10 }
11}
12
13impl Codec for SecretCodec {
14 fn applies(&self, key: &str) -> bool {
15 key.starts_with("secrets/")
16 }
17
18 fn seal(&self, key: &str, plain: &[u8]) -> Bytes {
19 match &self.0 {
20 Some(k) => Bytes::from(k.encrypt(plain, key.as_bytes())),
21 None => Bytes::copy_from_slice(plain),
22 }
23 }
24
25 fn open(&self, key: &str, stored: &Bytes) -> Option<Bytes> {
26 if !is_encrypted(stored) {
27 return Some(stored.clone());
28 }
29 self.0
30 .as_ref()?
31 .decrypt(stored, key.as_bytes())
32 .ok()
33 .map(Bytes::from)
34 }
35
36 fn sealed(&self, stored: &[u8]) -> bool {
37 is_encrypted(stored)
38 }
39}