cuenv-secrets 0.40.6

Secret resolution and management 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
//! Resolved secrets with fingerprinting support

use crate::{
    BatchSecrets, SaltConfig, SecretError, SecretResolver, SecretSpec, compute_secret_fingerprint,
};
use std::collections::HashMap;

/// Resolved secrets ready for injection
#[derive(Debug, Clone, Default)]
pub struct ResolvedSecrets {
    /// Secret name -> resolved value
    pub values: HashMap<String, String>,
    /// Secret name -> HMAC fingerprint (for cache keys)
    pub fingerprints: HashMap<String, String>,
}

impl ResolvedSecrets {
    /// Create empty resolved secrets
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Resolve secrets using a resolver with salt configuration
    ///
    /// # Arguments
    /// * `resolver` - The secret resolver to use
    /// * `secrets` - Map of secret names to their configuration
    /// * `salt_config` - Salt configuration for fingerprinting
    ///
    /// # Errors
    /// Returns error if a secret cannot be resolved or if salt is missing
    /// when secrets have `cache_key: true`
    pub async fn resolve<R: SecretResolver>(
        resolver: &R,
        secrets: &HashMap<String, SecretSpec>,
        salt_config: &SaltConfig,
    ) -> Result<Self, SecretError> {
        let mut values = HashMap::new();
        let mut fingerprints = HashMap::new();

        // Check if any secret requires cache key and salt is missing
        let needs_salt = secrets.values().any(|c| c.cache_key);
        if needs_salt && !salt_config.has_salt() {
            return Err(SecretError::MissingSalt);
        }

        for (name, spec) in secrets {
            let value = resolver.resolve(name, spec).await?;

            // Compute fingerprint if secret affects cache
            if spec.cache_key {
                // Warn if secret is too short (but don't fail)
                if value.len() < 4 {
                    tracing::warn!(
                        secret = %name,
                        len = value.len(),
                        "Secret is too short for safe cache key inclusion"
                    );
                }

                // Use write_salt for computing fingerprints (current salt preferred)
                let fingerprint = compute_secret_fingerprint(
                    name,
                    &value,
                    salt_config.write_salt().unwrap_or(""),
                );
                fingerprints.insert(name.clone(), fingerprint);
            }

            values.insert(name.clone(), value);
        }

        Ok(Self {
            values,
            fingerprints,
        })
    }

    /// Create from a `BatchSecrets` instance.
    ///
    /// This consumes the batch and converts it to the legacy format.
    /// Note that this exposes the secret values from the secure storage.
    #[must_use]
    pub fn from_batch(batch: BatchSecrets) -> Self {
        batch.into_resolved_secrets()
    }

    /// Resolve secrets using batch resolution with a resolver.
    ///
    /// This is the preferred method for resolving multiple secrets efficiently.
    /// It uses the resolver's batch resolution method which may use native
    /// batch APIs (e.g., AWS `BatchGetSecretValue`, 1Password `Secrets.ResolveAll`).
    ///
    /// # Arguments
    /// * `resolver` - The secret resolver to use
    /// * `secrets` - Map of secret names to their configuration
    /// * `salt_config` - Salt configuration for fingerprinting
    ///
    /// # Errors
    /// Returns error if a secret cannot be resolved or if salt is missing
    /// when secrets have `cache_key: true`
    pub async fn resolve_batch<R: SecretResolver>(
        resolver: &R,
        secrets: &HashMap<String, SecretSpec>,
        salt_config: &SaltConfig,
    ) -> Result<Self, SecretError> {
        let batch = crate::batch::resolve_batch(resolver, secrets, salt_config).await?;
        Ok(Self::from_batch(batch))
    }

    /// Check if any secrets were resolved
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Get a resolved secret value by name
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&str> {
        self.values.get(name).map(String::as_str)
    }

    /// Check if a cached fingerprint matches with salt rotation support
    ///
    /// During salt rotation, this checks if the cached fingerprint matches
    /// using either the current or previous salt. This allows cache hits
    /// during the rotation window.
    ///
    /// # Arguments
    /// * `name` - Secret name
    /// * `cached_fingerprint` - Fingerprint from cache
    /// * `salt_config` - Salt configuration with current and optional previous salt
    ///
    /// # Returns
    /// `true` if the fingerprint matches with either salt, `false` otherwise
    #[must_use]
    pub fn fingerprint_matches(
        &self,
        name: &str,
        cached_fingerprint: &str,
        salt_config: &SaltConfig,
    ) -> bool {
        let Some(value) = self.values.get(name) else {
            return false;
        };

        // Check against current salt
        if let Some(current) = &salt_config.current {
            let current_fp = compute_secret_fingerprint(name, value, current);
            if current_fp == cached_fingerprint {
                return true;
            }
        }

        // Check against previous salt (for rotation window)
        if let Some(previous) = &salt_config.previous {
            let previous_fp = compute_secret_fingerprint(name, value, previous);
            if previous_fp == cached_fingerprint {
                tracing::debug!(
                    secret = %name,
                    "Cache hit using previous salt - rotation in progress"
                );
                return true;
            }
        }

        false
    }

    /// Compute fingerprints using both current and previous salts
    ///
    /// Returns a tuple of (`current_fingerprint`, `previous_fingerprint`) for cache validation.
    /// Either may be None if the corresponding salt is not configured.
    #[must_use]
    pub fn compute_fingerprints_for_validation(
        &self,
        name: &str,
        salt_config: &SaltConfig,
    ) -> (Option<String>, Option<String>) {
        let Some(value) = self.values.get(name) else {
            return (None, None);
        };

        let current_fp = salt_config
            .current
            .as_ref()
            .map(|salt| compute_secret_fingerprint(name, value, salt));

        let previous_fp = salt_config
            .previous
            .as_ref()
            .map(|salt| compute_secret_fingerprint(name, value, salt));

        (current_fp, previous_fp)
    }
}

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

    #[test]
    fn test_resolved_secrets_new_is_empty() {
        let secrets = ResolvedSecrets::new();
        assert!(secrets.is_empty());
        assert!(secrets.values.is_empty());
        assert!(secrets.fingerprints.is_empty());
    }

    #[test]
    fn test_resolved_secrets_default_is_empty() {
        let secrets = ResolvedSecrets::default();
        assert!(secrets.is_empty());
    }

    #[test]
    fn test_resolved_secrets_get_existing() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("API_KEY".to_string(), "secret123".to_string());

        assert_eq!(secrets.get("API_KEY"), Some("secret123"));
        assert!(!secrets.is_empty());
    }

    #[test]
    fn test_resolved_secrets_get_missing() {
        let secrets = ResolvedSecrets::new();
        assert_eq!(secrets.get("NONEXISTENT"), None);
    }

    #[test]
    fn test_fingerprint_matches_with_current_salt() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("API_KEY".to_string(), "secret123".to_string());

        let salt_config = SaltConfig::new(Some("my-salt".to_string()));
        let fingerprint = compute_secret_fingerprint("API_KEY", "secret123", "my-salt");

        assert!(secrets.fingerprint_matches("API_KEY", &fingerprint, &salt_config));
    }

    #[test]
    fn test_fingerprint_matches_with_previous_salt() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("API_KEY".to_string(), "secret123".to_string());

        // Salt config with new salt but old fingerprint should still match
        let salt_config =
            SaltConfig::with_rotation(Some("new-salt".to_string()), Some("old-salt".to_string()));
        let old_fingerprint = compute_secret_fingerprint("API_KEY", "secret123", "old-salt");

        assert!(secrets.fingerprint_matches("API_KEY", &old_fingerprint, &salt_config));
    }

    #[test]
    fn test_fingerprint_matches_no_match() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("API_KEY".to_string(), "secret123".to_string());

        let salt_config = SaltConfig::new(Some("my-salt".to_string()));
        let wrong_fingerprint = compute_secret_fingerprint("API_KEY", "wrong-secret", "my-salt");

        assert!(!secrets.fingerprint_matches("API_KEY", &wrong_fingerprint, &salt_config));
    }

    #[test]
    fn test_fingerprint_matches_missing_secret() {
        let secrets = ResolvedSecrets::new();
        let salt_config = SaltConfig::new(Some("my-salt".to_string()));

        assert!(!secrets.fingerprint_matches("NONEXISTENT", "any-fingerprint", &salt_config));
    }

    #[test]
    fn test_fingerprint_matches_no_salt_configured() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("API_KEY".to_string(), "secret123".to_string());

        let salt_config = SaltConfig::default();

        // With no salt configured, no fingerprint should match
        assert!(!secrets.fingerprint_matches("API_KEY", "any-fingerprint", &salt_config));
    }

    #[test]
    fn test_compute_fingerprints_for_validation_both_salts() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("DB_PASS".to_string(), "password".to_string());

        let salt_config = SaltConfig::with_rotation(
            Some("current-salt".to_string()),
            Some("previous-salt".to_string()),
        );

        let (current_fp, previous_fp) =
            secrets.compute_fingerprints_for_validation("DB_PASS", &salt_config);

        assert!(current_fp.is_some());
        assert!(previous_fp.is_some());
        assert_ne!(current_fp, previous_fp);

        // Verify fingerprints are correct
        let expected_current = compute_secret_fingerprint("DB_PASS", "password", "current-salt");
        let expected_previous = compute_secret_fingerprint("DB_PASS", "password", "previous-salt");
        assert_eq!(current_fp.unwrap(), expected_current);
        assert_eq!(previous_fp.unwrap(), expected_previous);
    }

    #[test]
    fn test_compute_fingerprints_for_validation_only_current() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("TOKEN".to_string(), "abc123".to_string());

        let salt_config = SaltConfig::new(Some("only-current".to_string()));

        let (current_fp, previous_fp) =
            secrets.compute_fingerprints_for_validation("TOKEN", &salt_config);

        assert!(current_fp.is_some());
        assert!(previous_fp.is_none());
    }

    #[test]
    fn test_compute_fingerprints_for_validation_only_previous() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("TOKEN".to_string(), "abc123".to_string());

        let salt_config = SaltConfig::with_rotation(None, Some("only-previous".to_string()));

        let (current_fp, previous_fp) =
            secrets.compute_fingerprints_for_validation("TOKEN", &salt_config);

        assert!(current_fp.is_none());
        assert!(previous_fp.is_some());
    }

    #[test]
    fn test_compute_fingerprints_for_validation_missing_secret() {
        let secrets = ResolvedSecrets::new();
        let salt_config = SaltConfig::new(Some("salt".to_string()));

        let (current_fp, previous_fp) =
            secrets.compute_fingerprints_for_validation("MISSING", &salt_config);

        assert!(current_fp.is_none());
        assert!(previous_fp.is_none());
    }

    #[test]
    fn test_compute_fingerprints_for_validation_no_salt() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("KEY".to_string(), "value".to_string());

        let salt_config = SaltConfig::default();

        let (current_fp, previous_fp) =
            secrets.compute_fingerprints_for_validation("KEY", &salt_config);

        assert!(current_fp.is_none());
        assert!(previous_fp.is_none());
    }

    #[test]
    fn test_resolved_secrets_clone() {
        let mut secrets = ResolvedSecrets::new();
        secrets.values.insert("K1".to_string(), "V1".to_string());
        secrets
            .fingerprints
            .insert("K1".to_string(), "FP1".to_string());

        let cloned = secrets.clone();
        assert_eq!(cloned.values.get("K1"), Some(&"V1".to_string()));
        assert_eq!(cloned.fingerprints.get("K1"), Some(&"FP1".to_string()));
    }

    #[test]
    fn test_resolved_secrets_debug() {
        let secrets = ResolvedSecrets::new();
        let debug = format!("{secrets:?}");
        assert!(debug.contains("ResolvedSecrets"));
    }

    #[test]
    fn test_multiple_secrets() {
        let mut secrets = ResolvedSecrets::new();
        secrets
            .values
            .insert("KEY1".to_string(), "value1".to_string());
        secrets
            .values
            .insert("KEY2".to_string(), "value2".to_string());
        secrets
            .values
            .insert("KEY3".to_string(), "value3".to_string());

        assert_eq!(secrets.values.len(), 3);
        assert!(!secrets.is_empty());
        assert_eq!(secrets.get("KEY1"), Some("value1"));
        assert_eq!(secrets.get("KEY2"), Some("value2"));
        assert_eq!(secrets.get("KEY3"), Some("value3"));
    }
}