Skip to main content

esh_providers_vault/
lib.rs

1//! HashiCorp Vault KV v2 provider with injectable client.
2
3use async_trait::async_trait;
4use esh_core::{
5    ConfigMap, ConfigValue, Error, Provider, ProviderCapability, ProviderId, ProviderMeta, Result,
6};
7use serde_json::Value as JsonValue;
8use std::collections::HashMap;
9use std::sync::Arc;
10
11/// Vault KV read client.
12#[async_trait]
13pub trait VaultClient: Send + Sync {
14    /// Read a KV v2 secret path; returns the `data` object as JSON.
15    async fn read_kv2(&self, mount: &str, path: &str) -> Result<JsonValue>;
16}
17
18/// In-memory fake Vault.
19#[derive(Default, Clone)]
20pub struct MapVaultClient {
21    /// map key: `{mount}/{path}` → data object
22    data: HashMap<String, JsonValue>,
23    fault: Option<VaultFault>,
24}
25
26/// Injected failure mode for [`MapVaultClient`].
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum VaultFault {
29    /// Permission denied.
30    Auth,
31    /// Upstream timeout.
32    Timeout,
33}
34
35impl MapVaultClient {
36    /// Empty client.
37    #[must_use]
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    /// Insert KV data.
43    #[must_use]
44    pub fn with_secret(mut self, mount: &str, path: &str, data: JsonValue) -> Self {
45        self.data.insert(format!("{mount}/{path}"), data);
46        self
47    }
48
49    /// Force failures.
50    #[must_use]
51    pub fn with_fault(mut self, fault: VaultFault) -> Self {
52        self.fault = Some(fault);
53        self
54    }
55}
56
57#[async_trait]
58impl VaultClient for MapVaultClient {
59    async fn read_kv2(&self, mount: &str, path: &str) -> Result<JsonValue> {
60        match self.fault {
61            Some(VaultFault::Auth) => return Err(Error::provider("vault", "permission denied")),
62            Some(VaultFault::Timeout) => return Err(Error::provider("vault", "timeout")),
63            None => {}
64        }
65        self.data
66            .get(&format!("{mount}/{path}"))
67            .cloned()
68            .ok_or_else(|| Error::not_found(path))
69    }
70}
71
72/// Vault KV v2 provider.
73///
74/// Modes:
75/// - **path mode** (default): logical key maps to `path_prefix/key` and returns a chosen field
76///   or the whole JSON as string.
77/// - **field mode**: fixed `path` secret; logical key selects a field inside `data`.
78pub struct VaultKvProvider {
79    meta: ProviderMeta,
80    client: Arc<dyn VaultClient>,
81    mount: String,
82    path_prefix: String,
83    /// When set, treat this path as the secret and keys as fields.
84    fixed_path: Option<String>,
85    field: Option<String>,
86}
87
88impl VaultKvProvider {
89    /// Create provider for a KV mount (default `secret`).
90    #[must_use]
91    pub fn new(client: Arc<dyn VaultClient>) -> Self {
92        Self {
93            meta: ProviderMeta {
94                id: ProviderId::new("vault"),
95                name: "HashiCorp Vault".into(),
96                capabilities: ProviderCapability {
97                    bulk: true,
98                    versioned: true,
99                    local: false,
100                },
101            },
102            client,
103            mount: "secret".into(),
104            path_prefix: String::new(),
105            fixed_path: None,
106            field: None,
107        }
108    }
109
110    /// KV mount name.
111    #[must_use]
112    pub fn mount(mut self, mount: impl Into<String>) -> Self {
113        self.mount = mount.into();
114        self
115    }
116
117    /// Path prefix for per-key secrets.
118    #[must_use]
119    pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
120        self.path_prefix = prefix.into();
121        self
122    }
123
124    /// Use a single secret path; logical keys are JSON fields.
125    #[must_use]
126    pub fn secret_path(mut self, path: impl Into<String>) -> Self {
127        self.fixed_path = Some(path.into());
128        self
129    }
130
131    /// When not in field mode, extract this field from each secret object.
132    #[must_use]
133    pub fn value_field(mut self, field: impl Into<String>) -> Self {
134        self.field = Some(field.into());
135        self
136    }
137}
138
139#[async_trait]
140impl Provider for VaultKvProvider {
141    fn meta(&self) -> &ProviderMeta {
142        &self.meta
143    }
144
145    async fn get(&self, key: &str) -> Result<ConfigValue> {
146        if let Some(path) = &self.fixed_path {
147            let data = self.client.read_kv2(&self.mount, path).await?;
148            let val = data
149                .get(key)
150                .ok_or_else(|| Error::not_found(key))?;
151            return Ok(json_to_secret(val));
152        }
153
154        let path = if self.path_prefix.is_empty() {
155            key.to_string()
156        } else {
157            format!("{}/{key}", self.path_prefix.trim_end_matches('/'))
158        };
159        let data = self.client.read_kv2(&self.mount, &path).await.map_err(|e| {
160            match e {
161                Error::NotFound { .. } => Error::not_found(key),
162                other => other,
163            }
164        })?;
165
166        if let Some(field) = &self.field {
167            let val = data.get(field).ok_or_else(|| Error::not_found(key))?;
168            Ok(json_to_secret(val))
169        } else if let Some(val) = data.get("value") {
170            Ok(json_to_secret(val))
171        } else if data.is_object() {
172            Ok(ConfigValue::secret(data.to_string()))
173        } else {
174            Ok(json_to_secret(&data))
175        }
176    }
177
178    async fn get_many(&self, keys: &[String]) -> Result<ConfigMap> {
179        if let Some(path) = &self.fixed_path {
180            let data = self.client.read_kv2(&self.mount, path).await?;
181            let mut out = ConfigMap::new();
182            if keys.is_empty() {
183                if let Some(obj) = data.as_object() {
184                    for (k, v) in obj {
185                        out.insert(k.clone(), json_to_secret(v));
186                    }
187                }
188            } else {
189                for key in keys {
190                    if let Some(v) = data.get(key) {
191                        out.insert(key.clone(), json_to_secret(v));
192                    }
193                }
194            }
195            return Ok(out);
196        }
197        // Fall back to default trait impl behavior via sequential get
198        let mut out = ConfigMap::new();
199        for key in keys {
200            match self.get(key).await {
201                Ok(v) => {
202                    out.insert(key.clone(), v);
203                }
204                Err(Error::NotFound { .. }) => {}
205                Err(e) => return Err(e),
206            }
207        }
208        Ok(out)
209    }
210}
211
212fn json_to_secret(v: &JsonValue) -> ConfigValue {
213    match v {
214        JsonValue::String(s) => ConfigValue::secret(s.clone()),
215        other => ConfigValue::secret(other.to_string()),
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use esh_test_support::{
223        run_provider_conformance, ProviderConformanceCfg, SAMPLE_SECRET,
224    };
225    use serde_json::json;
226
227    #[tokio::test]
228    async fn field_mode() {
229        let client = Arc::new(MapVaultClient::new().with_secret(
230            "secret",
231            "app/prod",
232            json!({"database_url": "postgres://vault"}),
233        ));
234        let p = VaultKvProvider::new(client).secret_path("app/prod");
235        assert_eq!(
236            p.get("database_url").await.unwrap().as_str(),
237            Some("postgres://vault")
238        );
239    }
240
241    #[tokio::test]
242    async fn vault_conformance() {
243        let client = Arc::new(MapVaultClient::new().with_secret(
244            "secret",
245            "app",
246            json!({ "database_url": SAMPLE_SECRET }),
247        ));
248        let p = VaultKvProvider::new(client).secret_path("app");
249        run_provider_conformance(
250            &p,
251            &ProviderConformanceCfg {
252                expected_id: "vault".into(),
253                expected_capabilities: ProviderCapability {
254                    bulk: true,
255                    versioned: true,
256                    local: false,
257                },
258                present_key: "database_url".into(),
259                present_value: SAMPLE_SECRET.into(),
260                missing_key: "missing".into(),
261                fault_key: None,
262                health_ok: true,
263                test_get_many: true,
264            },
265        )
266        .await;
267    }
268
269    #[tokio::test]
270    async fn vault_auth_fault() {
271        let client = Arc::new(
272            MapVaultClient::new()
273                .with_secret("secret", "app", json!({ "database_url": SAMPLE_SECRET }))
274                .with_fault(VaultFault::Auth),
275        );
276        let p = VaultKvProvider::new(client).secret_path("app");
277        let err = p.get("database_url").await.unwrap_err();
278        assert!(!err.to_string().contains(SAMPLE_SECRET));
279    }
280}