cuenv-vault 0.26.2

HashiCorp Vault integration for the cuenv ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! `HashiCorp` Vault secret resolver with auto-negotiating dual-mode (HTTP + CLI)

use async_trait::async_trait;
use cuenv_secrets::{SecretError, SecretResolver, SecretSpec};
use serde::{Deserialize, Serialize};
use tokio::process::Command;
use vaultrs::client::VaultClient;

/// Configuration for `HashiCorp` Vault resolution
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct VaultSecretConfig {
    /// Path to the secret (e.g., "secret/data/myapp/config")
    pub path: String,

    /// Key within the secret to extract
    pub key: String,

    /// Secret engine mount point (defaults to "secret")
    #[serde(default = "default_mount")]
    pub mount: String,
}

fn default_mount() -> String {
    "secret".to_string()
}

impl VaultSecretConfig {
    /// Create a new Vault secret config
    #[must_use]
    pub fn new(path: impl Into<String>, key: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            key: key.into(),
            mount: "secret".to_string(),
        }
    }

    /// Get the full path including mount point
    #[must_use]
    pub fn full_path(&self) -> String {
        // KV v2 uses /data/ in the path
        if self.path.starts_with(&self.mount) {
            self.path.clone()
        } else {
            format!("{}/data/{}", self.mount, self.path)
        }
    }
}

/// Resolves secrets from `HashiCorp` Vault
///
/// Mode is auto-negotiated based on environment:
/// - If `VAULT_TOKEN` and `VAULT_ADDR` are set → HTTP mode
/// - Otherwise → CLI mode (uses `vault` CLI)
///
/// The `source` field in [`SecretSpec`] can be:
/// - A JSON-encoded [`VaultSecretConfig`]
pub struct VaultResolver {
    client: Option<VaultClient>,
}

impl std::fmt::Debug for VaultResolver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VaultResolver")
            .field("mode", &if self.can_use_http() { "http" } else { "cli" })
            .finish()
    }
}

impl VaultResolver {
    /// Create a new Vault resolver with auto-detected mode
    ///
    /// If Vault credentials are available in environment, uses HTTP mode.
    /// Otherwise, CLI mode will be used.
    ///
    /// # Errors
    ///
    /// Returns an error if the Vault HTTP client cannot be initialized.
    pub fn new() -> Result<Self, SecretError> {
        let client = if Self::http_credentials_available() {
            let addr =
                std::env::var("VAULT_ADDR").unwrap_or_else(|_| "http://127.0.0.1:8200".to_string());
            let token =
                std::env::var("VAULT_TOKEN").map_err(|_| SecretError::ResolutionFailed {
                    name: "vault".to_string(),
                    message: "VAULT_TOKEN environment variable not set".to_string(),
                })?;

            Some(
                VaultClient::new(
                    vaultrs::client::VaultClientSettingsBuilder::default()
                        .address(addr)
                        .token(token)
                        .build()
                        .map_err(|e| SecretError::ResolutionFailed {
                            name: "vault".to_string(),
                            message: format!("Failed to build Vault client: {e}"),
                        })?,
                )
                .map_err(|e| SecretError::ResolutionFailed {
                    name: "vault".to_string(),
                    message: format!("Failed to create Vault client: {e}"),
                })?,
            )
        } else {
            None
        };

        Ok(Self { client })
    }

    /// Check if HTTP credentials are available in environment
    fn http_credentials_available() -> bool {
        std::env::var("VAULT_TOKEN").is_ok() && std::env::var("VAULT_ADDR").is_ok()
    }

    /// Check if this resolver can use HTTP mode
    const fn can_use_http(&self) -> bool {
        self.client.is_some()
    }

    /// Resolve using the Vault HTTP API
    async fn resolve_http(
        &self,
        name: &str,
        config: &VaultSecretConfig,
    ) -> Result<String, SecretError> {
        let client = self
            .client
            .as_ref()
            .ok_or_else(|| SecretError::ResolutionFailed {
                name: name.to_string(),
                message: "Vault HTTP client not initialized".to_string(),
            })?;

        // Read secret from KV v2
        let secret: std::collections::HashMap<String, String> =
            vaultrs::kv2::read(client, &config.mount, &config.path)
                .await
                .map_err(|e| SecretError::ResolutionFailed {
                    name: name.to_string(),
                    message: format!("Vault read error: {e}"),
                })?;

        secret
            .get(&config.key)
            .cloned()
            .ok_or_else(|| SecretError::ResolutionFailed {
                name: name.to_string(),
                message: format!("Key '{}' not found in secret", config.key),
            })
    }

    /// Resolve using the vault CLI
    async fn resolve_cli(
        &self,
        name: &str,
        config: &VaultSecretConfig,
    ) -> Result<String, SecretError> {
        let output = Command::new("vault")
            .args([
                "kv",
                "get",
                "-mount",
                &config.mount,
                "-field",
                &config.key,
                &config.path,
            ])
            .output()
            .await
            .map_err(|e| SecretError::ResolutionFailed {
                name: name.to_string(),
                message: format!("Failed to execute vault CLI: {e}"),
            })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(SecretError::ResolutionFailed {
                name: name.to_string(),
                message: format!("vault CLI failed: {stderr}"),
            });
        }

        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    /// Resolve a secret - tries HTTP first if available, falls back to CLI
    async fn resolve_with_config(
        &self,
        name: &str,
        config: &VaultSecretConfig,
    ) -> Result<String, SecretError> {
        // Try HTTP mode if available
        if self.client.is_some() {
            return self.resolve_http(name, config).await;
        }

        // Fallback to CLI
        self.resolve_cli(name, config).await
    }
}

#[async_trait]
impl SecretResolver for VaultResolver {
    fn provider_name(&self) -> &'static str {
        "vault"
    }

    async fn resolve(&self, name: &str, spec: &SecretSpec) -> Result<String, SecretError> {
        // Parse source as JSON VaultSecretConfig
        let config: VaultSecretConfig =
            serde_json::from_str(&spec.source).map_err(|e| SecretError::ResolutionFailed {
                name: name.to_string(),
                message: format!("Invalid Vault secret config: {e}"),
            })?;

        self.resolve_with_config(name, &config).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_vault_config_serialization() {
        let config = VaultSecretConfig {
            path: "myapp/config".to_string(),
            key: "password".to_string(),
            mount: "secret".to_string(),
        };

        let json = serde_json::to_string(&config).unwrap();
        let parsed: VaultSecretConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(config, parsed);
    }

    #[test]
    fn test_full_path() {
        let config = VaultSecretConfig::new("myapp/config", "password");
        assert_eq!(config.full_path(), "secret/data/myapp/config");
    }

    #[test]
    fn test_full_path_with_mount() {
        let config = VaultSecretConfig {
            path: "myapp/config".to_string(),
            key: "password".to_string(),
            mount: "kv".to_string(),
        };
        assert_eq!(config.full_path(), "kv/data/myapp/config");
    }

    #[test]
    fn test_http_credentials_check() {
        // This test just ensures the function exists and doesn't panic
        let _ = VaultResolver::http_credentials_available();
    }

    #[test]
    fn test_vault_config_new() {
        let config = VaultSecretConfig::new("path/to/secret", "api_key");
        assert_eq!(config.path, "path/to/secret");
        assert_eq!(config.key, "api_key");
        assert_eq!(config.mount, "secret"); // Default mount
    }

    #[test]
    fn test_vault_config_new_with_string_types() {
        let config = VaultSecretConfig::new(String::from("my/path"), String::from("mykey"));
        assert_eq!(config.path, "my/path");
        assert_eq!(config.key, "mykey");
    }

    #[test]
    fn test_full_path_already_includes_mount() {
        // When path already starts with mount, don't add data prefix
        let config = VaultSecretConfig {
            path: "secret/myapp/config".to_string(),
            key: "password".to_string(),
            mount: "secret".to_string(),
        };
        assert_eq!(config.full_path(), "secret/myapp/config");
    }

    #[test]
    fn test_full_path_custom_mount_already_included() {
        let config = VaultSecretConfig {
            path: "kv/production/db".to_string(),
            key: "password".to_string(),
            mount: "kv".to_string(),
        };
        assert_eq!(config.full_path(), "kv/production/db");
    }

    #[test]
    fn test_default_mount_function() {
        assert_eq!(default_mount(), "secret");
    }

    #[test]
    fn test_vault_config_clone() {
        let config = VaultSecretConfig {
            path: "myapp/config".to_string(),
            key: "password".to_string(),
            mount: "kv".to_string(),
        };
        let cloned = config.clone();
        assert_eq!(config, cloned);
    }

    #[test]
    fn test_vault_config_debug() {
        let config = VaultSecretConfig::new("test/path", "test_key");
        let debug_str = format!("{config:?}");
        assert!(debug_str.contains("VaultSecretConfig"));
        assert!(debug_str.contains("test/path"));
        assert!(debug_str.contains("test_key"));
    }

    #[test]
    fn test_vault_config_deserialization_with_defaults() {
        // When mount is missing in JSON, it should use the default
        let json = r#"{"path": "myapp", "key": "secret"}"#;
        let config: VaultSecretConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.path, "myapp");
        assert_eq!(config.key, "secret");
        assert_eq!(config.mount, "secret"); // Default value
    }

    #[test]
    fn test_vault_config_full_deserialization() {
        let json = r#"{"path": "prod/db", "key": "password", "mount": "kv"}"#;
        let config: VaultSecretConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.path, "prod/db");
        assert_eq!(config.key, "password");
        assert_eq!(config.mount, "kv");
    }

    #[test]
    fn test_vault_config_camel_case_serialization() {
        let config = VaultSecretConfig::new("mypath", "mykey");
        let json = serde_json::to_string(&config).unwrap();
        // Verify camelCase is used (not snake_case)
        assert!(json.contains("\"path\""));
        assert!(json.contains("\"key\""));
        assert!(json.contains("\"mount\""));
    }

    #[test]
    fn test_full_path_deep_nesting() {
        let config = VaultSecretConfig {
            path: "environments/production/services/api/database".to_string(),
            key: "connection_string".to_string(),
            mount: "secret".to_string(),
        };
        assert_eq!(
            config.full_path(),
            "secret/data/environments/production/services/api/database"
        );
    }

    #[test]
    fn test_vault_config_equality() {
        let config1 = VaultSecretConfig::new("path", "key");
        let config2 = VaultSecretConfig::new("path", "key");
        let config3 = VaultSecretConfig::new("path", "different_key");

        assert_eq!(config1, config2);
        assert_ne!(config1, config3);
    }

    #[test]
    fn test_vault_config_with_different_mounts() {
        let mut config1 = VaultSecretConfig::new("path", "key");
        config1.mount = "kv".to_string();
        let mut config2 = VaultSecretConfig::new("path", "key");
        config2.mount = "secrets".to_string();

        assert_ne!(config1, config2);
    }

    #[test]
    fn test_vault_config_roundtrip() {
        let original = VaultSecretConfig {
            path: "deep/nested/path".to_string(),
            key: "complex_key".to_string(),
            mount: "custom_mount".to_string(),
        };
        let json = serde_json::to_string(&original).unwrap();
        let parsed: VaultSecretConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(original, parsed);
    }

    #[test]
    fn test_full_path_with_special_characters() {
        let config = VaultSecretConfig {
            path: "my-app/config_v1".to_string(),
            key: "api-key".to_string(),
            mount: "secret".to_string(),
        };
        assert_eq!(config.full_path(), "secret/data/my-app/config_v1");
    }

    #[test]
    fn test_full_path_empty_path() {
        let config = VaultSecretConfig {
            path: String::new(),
            key: "key".to_string(),
            mount: "secret".to_string(),
        };
        assert_eq!(config.full_path(), "secret/data/");
    }

    #[test]
    fn test_vault_config_deserialization_missing_path() {
        let json = r#"{"key": "mykey"}"#;
        let result = serde_json::from_str::<VaultSecretConfig>(json);
        assert!(result.is_err());
    }

    #[test]
    fn test_vault_config_deserialization_missing_key() {
        let json = r#"{"path": "mypath"}"#;
        let result = serde_json::from_str::<VaultSecretConfig>(json);
        assert!(result.is_err());
    }

    #[test]
    fn test_resolver_new_without_credentials() {
        // Without VAULT_TOKEN and VAULT_ADDR, should use CLI mode
        if std::env::var("VAULT_TOKEN").is_err() || std::env::var("VAULT_ADDR").is_err() {
            let resolver = VaultResolver::new();
            assert!(resolver.is_ok());
            let resolver = resolver.unwrap();
            assert!(!resolver.can_use_http());
        }
    }

    #[test]
    fn test_resolver_provider_name() {
        if std::env::var("VAULT_TOKEN").is_err() || std::env::var("VAULT_ADDR").is_err() {
            let resolver = VaultResolver::new().unwrap();
            assert_eq!(resolver.provider_name(), "vault");
        }
    }

    #[test]
    fn test_resolver_debug_output() {
        if std::env::var("VAULT_TOKEN").is_err() || std::env::var("VAULT_ADDR").is_err() {
            let resolver = VaultResolver::new().unwrap();
            let debug = format!("{resolver:?}");
            assert!(debug.contains("VaultResolver"));
            assert!(debug.contains("cli") || debug.contains("http"));
        }
    }

    #[test]
    fn test_http_credentials_available_logic() {
        let token = std::env::var("VAULT_TOKEN").is_ok();
        let addr = std::env::var("VAULT_ADDR").is_ok();
        let expected = token && addr;
        assert_eq!(VaultResolver::http_credentials_available(), expected);
    }

    #[test]
    fn test_vault_config_unicode_path() {
        let config = VaultSecretConfig::new("路径/配置", "密钥");
        assert_eq!(config.path, "路径/配置");
        assert_eq!(config.key, "密钥");
        assert_eq!(config.full_path(), "secret/data/路径/配置");
    }

    #[test]
    fn test_vault_config_with_slashes_in_key() {
        let config = VaultSecretConfig {
            path: "myapp/config".to_string(),
            key: "nested/key/path".to_string(),
            mount: "secret".to_string(),
        };
        assert_eq!(config.key, "nested/key/path");
    }

    #[test]
    fn test_vault_config_empty_key() {
        let config = VaultSecretConfig {
            path: "myapp/config".to_string(),
            key: String::new(),
            mount: "secret".to_string(),
        };
        assert_eq!(config.key, "");
    }

    #[test]
    fn test_full_path_mount_partial_match() {
        // Path starts with "secret" but not as mount
        let config = VaultSecretConfig {
            path: "secretive/path".to_string(),
            key: "key".to_string(),
            mount: "secret".to_string(),
        };
        // "secretive" starts with "secret", so it matches the starts_with check
        assert_eq!(config.full_path(), "secretive/path");
    }

    #[test]
    fn test_full_path_different_mount_prefix() {
        // Path doesn't start with mount
        let config = VaultSecretConfig {
            path: "other/path".to_string(),
            key: "key".to_string(),
            mount: "kv".to_string(),
        };
        assert_eq!(config.full_path(), "kv/data/other/path");
    }
}