secretspec 0.9.1

Declarative secrets, every environment, any provider
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
use super::{Provider, ProviderUrl};
use crate::{Result, SecretSpecError};
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::path::PathBuf;

/// Serializes a map of env vars into `.env` file content.
///
/// Each entry is emitted as `KEY="value"` with the escapes that
/// [`dotenvy`] understands inside double-quoted values: `\\`, `\"`,
/// `\$` (suppresses variable substitution), and `\n` (literal
/// newlines folded onto a single line). Keys are sorted for stable
/// output.
fn serialize_dotenv(vars: &HashMap<String, String>) -> String {
    let sorted: BTreeMap<&str, &str> = vars.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
    let mut out = String::new();
    for (key, value) in sorted {
        out.push_str(key);
        out.push_str("=\"");
        for ch in value.chars() {
            match ch {
                '\\' => out.push_str("\\\\"),
                '"' => out.push_str("\\\""),
                '$' => out.push_str("\\$"),
                '\n' => out.push_str("\\n"),
                c => out.push(c),
            }
        }
        out.push_str("\"\n");
    }
    out
}

/// Configuration for the dotenv provider.
///
/// This struct holds the configuration for accessing .env files,
/// primarily the path to the .env file to read from and write to.
///
/// # Examples
///
/// ```ignore
/// use std::path::PathBuf;
/// use secretspec::provider::dotenv::DotEnvConfig;
///
/// let config = DotEnvConfig {
///     path: PathBuf::from(".env.production"),
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DotEnvConfig {
    /// Path to the .env file.
    ///
    /// Can be either an absolute path (e.g., `/etc/secrets/.env`)
    /// or a relative path (e.g., `.env`, `config/.env.local`).
    pub path: PathBuf,
}

impl Default for DotEnvConfig {
    /// Creates a default configuration with path set to `.env`.
    ///
    /// This is the conventional default location for dotenv files
    /// in the current working directory.
    fn default() -> Self {
        Self {
            path: PathBuf::from(".env"),
        }
    }
}

impl TryFrom<&ProviderUrl> for DotEnvConfig {
    type Error = SecretSpecError;

    /// Creates a DotEnvConfig from a URL.
    ///
    /// Parses a URL in the format `dotenv://[path]` to extract
    /// the path to the .env file. The URL parsing handles several cases:
    ///
    /// # URL Formats
    ///
    /// - `dotenv:///absolute/path` - Absolute path
    /// - `dotenv://.env` - Relative path (authority as filename)
    /// - `dotenv://` - Uses default `.env` in current directory
    fn try_from(url: &ProviderUrl) -> std::result::Result<Self, Self::Error> {
        if url.scheme() != "dotenv" {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "Invalid scheme '{}' for dotenv provider",
                url.scheme()
            )));
        }

        let path_str = url.path();
        let path = if path_str != "" && path_str != "/" {
            if let Some(host) = url.host() {
                format!("{}{}", host, path_str)
            } else {
                path_str
            }
        } else if let Some(host) = url.host() {
            host
        } else {
            ".env".to_string()
        };

        Ok(Self {
            path: PathBuf::from(path),
        })
    }
}

/// Provider for managing secrets in .env files.
///
/// The DotEnvProvider implements the Provider trait to enable reading
/// and writing secrets from/to .env files. It uses the dotenvy crate
/// for parsing and a small local serializer for writing, with proper
/// handling of special characters and escaping.
///
/// # Features
///
/// - Reads environment variables from .env files
/// - Writes new or updated variables back to .env files
/// - Preserves existing variables when updating
/// - Handles proper escaping of values with special characters
/// - Supports both relative and absolute file paths
///
/// # Note
///
/// This provider ignores the project and profile parameters as .env files
/// typically don't have built-in namespacing. All secrets are stored
/// flat in the file.
pub struct DotEnvProvider {
    /// Configuration containing the path to the .env file
    config: DotEnvConfig,
}

crate::register_provider! {
    struct: DotEnvProvider,
    config: DotEnvConfig,
    name: "dotenv",
    description: "Traditional .env files",
    schemes: ["dotenv"],
    examples: ["dotenv://.env", "dotenv://.env.production"],
}

impl DotEnvProvider {
    /// Creates a new DotEnvProvider with the given configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - The configuration specifying the .env file path
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use secretspec::provider::dotenv::{DotEnvProvider, DotEnvConfig};
    ///
    /// let config = DotEnvConfig::default();
    /// let provider = DotEnvProvider::new(config);
    /// ```
    pub fn new(config: DotEnvConfig) -> Self {
        Self { config }
    }
}

impl Provider for DotEnvProvider {
    fn name(&self) -> &'static str {
        Self::PROVIDER_NAME
    }

    fn uri(&self) -> String {
        // Dotenv uses single colon format: dotenv:path
        // The path can be relative or absolute
        let path_str = self.config.path.display().to_string();

        if path_str == ".env" {
            "dotenv".to_string()
        } else {
            format!("dotenv:{}", path_str)
        }
    }

    /// Retrieves a secret value from the .env file.
    ///
    /// Reads the .env file and returns the value for the specified key.
    /// The project and profile parameters are ignored as .env files
    /// don't support namespacing.
    ///
    /// # Arguments
    ///
    /// * `_project` - Ignored, .env files don't support project namespacing
    /// * `key` - The environment variable name to look up
    /// * `_profile` - Ignored, .env files don't support profile namespacing
    ///
    /// # Returns
    ///
    /// * `Ok(Some(String))` - The value if the key exists
    /// * `Ok(None)` - If the key doesn't exist or the file doesn't exist
    /// * `Err(SecretSpecError)` - If reading the file fails
    ///
    /// # Implementation Details
    ///
    /// Uses the dotenvy crate for parsing to ensure compatibility with
    /// standard .env file formats and proper handling of quoted values,
    /// multiline strings, and escape sequences.
    fn get(&self, _project: &str, key: &str, _profile: &str) -> Result<Option<SecretString>> {
        if !self.config.path.exists() {
            return Ok(None);
        }

        // Use dotenvy for reading to ensure compatibility
        let mut vars = HashMap::new();
        let env_vars = dotenvy::from_path_iter(&self.config.path)?;
        for item in env_vars {
            let (k, v) = item?;
            vars.insert(k, v);
        }

        Ok(vars.get(key).map(|v| SecretString::new(v.clone().into())))
    }

    /// Sets a secret value in the .env file.
    ///
    /// Updates or adds a key-value pair in the .env file. If the file
    /// doesn't exist, it will be created. Existing variables are preserved.
    ///
    /// # Arguments
    ///
    /// * `_project` - Ignored, .env files don't support project namespacing
    /// * `key` - The environment variable name to set
    /// * `value` - The value to store
    /// * `_profile` - Ignored, .env files don't support profile namespacing
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the value was successfully written
    /// * `Err(SecretSpecError)` - If reading or writing the file fails
    ///
    /// # Implementation Details
    ///
    /// 1. Loads existing variables using dotenvy to preserve them
    /// 2. Updates or adds the new key-value pair
    /// 3. Serializes back with `serialize_dotenv` for proper escaping
    fn set(&self, _project: &str, key: &str, value: &SecretString, _profile: &str) -> Result<()> {
        // Load existing vars using dotenvy
        let mut vars = HashMap::new();
        if self.config.path.exists() {
            let env_vars = dotenvy::from_path_iter(&self.config.path)?;
            for item in env_vars {
                let (k, v) = item?;
                vars.insert(k, v);
            }
        }

        // Update the value
        vars.insert(key.to_string(), value.expose_secret().to_string());

        let content = serialize_dotenv(&vars);
        fs::write(&self.config.path, content)?;
        Ok(())
    }

    fn reflect(&self) -> Result<HashMap<String, crate::config::Secret>> {
        use crate::config::Secret;

        if !self.config.path.exists() {
            return Ok(HashMap::new());
        }

        // Check if path is a directory
        if self.config.path.is_dir() {
            return Err(SecretSpecError::Io(std::io::Error::new(
                std::io::ErrorKind::IsADirectory,
                format!(
                    "Expected file but found directory: {}",
                    self.config.path.display()
                ),
            )));
        }

        let mut secrets = HashMap::new();
        let env_vars = dotenvy::from_path_iter(&self.config.path)?;
        for item in env_vars {
            let (key, _value) = item?;
            secrets.insert(
                key.clone(),
                Secret {
                    description: Some(format!("{} secret", key)),
                    required: Some(true),
                    ..Default::default()
                },
            );
        }

        Ok(secrets)
    }
}

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

    #[test]
    fn test_dotenv_url_parsing() {
        use url::Url;

        // Test with absolute path using three slashes - this is the main syntax we want to support
        let url = ProviderUrl::new(Url::parse("dotenv:///tmp/test/.env").unwrap());
        let config: DotEnvConfig = (&url).try_into().unwrap();
        assert_eq!(config.path.to_str().unwrap(), "/tmp/test/.env");

        // Test with relative path using two slashes - authority as filename
        let url = ProviderUrl::new(Url::parse("dotenv://.env").unwrap());
        let config: DotEnvConfig = (&url).try_into().unwrap();
        assert_eq!(config.path.to_str().unwrap(), ".env");

        // Test with relative path in subdirectory
        let url = ProviderUrl::new(Url::parse("dotenv://config/.env.local").unwrap());
        let config: DotEnvConfig = (&url).try_into().unwrap();
        assert_eq!(config.path.to_str().unwrap(), "config/.env.local");

        // Test with default (empty after //)
        let url = ProviderUrl::new(Url::parse("dotenv://").unwrap());
        let config: DotEnvConfig = (&url).try_into().unwrap();
        assert_eq!(config.path.to_str().unwrap(), ".env");

        // Test with relative path - host part becomes first part of path
        let url = ProviderUrl::new(Url::parse("dotenv://foobar/custom/path/.env").unwrap());
        let config: DotEnvConfig = (&url).try_into().unwrap();
        assert_eq!(config.path.to_str().unwrap(), "foobar/custom/path/.env");
    }

    #[test]
    fn test_default_config() {
        let config = DotEnvConfig::default();
        assert_eq!(config.path.to_str().unwrap(), ".env");
    }

    #[test]
    fn test_reflect() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();
        let env_file = dir.path().join(".env");

        let mut file = std::fs::File::create(&env_file).unwrap();
        writeln!(file, "API_KEY=test123").unwrap();
        writeln!(file, "DATABASE_URL=postgres://localhost").unwrap();

        let provider = DotEnvProvider::new(DotEnvConfig {
            path: env_file.clone(),
        });

        let secrets = provider.reflect().unwrap();
        assert_eq!(secrets.len(), 2);
        assert!(secrets.contains_key("API_KEY"));
        assert!(secrets.contains_key("DATABASE_URL"));

        let api_key_config = &secrets["API_KEY"];
        assert_eq!(
            api_key_config.description,
            Some("API_KEY secret".to_string())
        );
        assert_eq!(api_key_config.required, Some(true));
        assert!(api_key_config.default.is_none());
    }

    #[test]
    fn test_reflect_nonexistent_file() {
        let provider = DotEnvProvider::new(DotEnvConfig {
            path: PathBuf::from("/tmp/nonexistent/.env"),
        });

        let secrets = provider.reflect().unwrap();
        assert!(secrets.is_empty());
    }

    #[test]
    fn test_serialize_dotenv_escapes() {
        let mut vars = HashMap::new();
        vars.insert("PLAIN".to_string(), "hello".to_string());
        vars.insert("QUOTES".to_string(), r#"{"a":"b"}"#.to_string());
        vars.insert("BACKSLASH".to_string(), r"C:\path\to".to_string());
        vars.insert("DOLLAR".to_string(), "$VAR".to_string());
        vars.insert("NEWLINE".to_string(), "line1\nline2".to_string());

        let out = serialize_dotenv(&vars);
        // Sorted by key, double-quoted, with escapes applied.
        assert_eq!(
            out,
            concat!(
                "BACKSLASH=\"C:\\\\path\\\\to\"\n",
                "DOLLAR=\"\\$VAR\"\n",
                "NEWLINE=\"line1\\nline2\"\n",
                "PLAIN=\"hello\"\n",
                "QUOTES=\"{\\\"a\\\":\\\"b\\\"}\"\n",
            )
        );
    }

    #[test]
    fn test_set_roundtrips_special_characters() {
        let dir = tempfile::tempdir().unwrap();
        let env_file = dir.path().join(".env");
        let provider = DotEnvProvider::new(DotEnvConfig {
            path: env_file.clone(),
        });

        // Each entry exercises a different class of input the previous
        // serde-envfile bug or dotenvy's parser cared about.
        let cases = [
            ("PLAIN", "hello world"),
            ("QUOTES", r#"{"a":"b"}"#),
            ("LEADING_QUOTE", r#""leading"#),
            ("TRAILING_QUOTE", r#"trailing""#),
            ("BACKSLASH", r"C:\path\to"),
            ("BACKSLASH_BEFORE_QUOTE", r#"a\"b"#),
            ("BACKSLASH_BEFORE_DOLLAR", r"a\$b"),
            ("DOLLAR_VAR", "literal $VAR not expanded"),
            ("DOLLAR_BRACED", "literal ${VAR} not expanded"),
            ("DOLLAR_ONLY", "$"),
            ("HASH", "value with # not a comment"),
            ("SINGLE_QUOTE", "it's literal"),
            ("EQUALS", "k=v=more"),
            ("NEWLINE", "line1\nline2"),
            ("MIXED", "a\\b\"c$d\ne"),
            ("UNICODE", "café — 🚀"),
            ("WHITESPACE_EDGES", "  spaced  "),
            ("EMPTY", ""),
        ];

        for (k, v) in cases {
            provider
                .set("proj", k, &SecretString::new(v.into()), "default")
                .unwrap();
        }

        for (k, v) in cases {
            let got = provider.get("proj", k, "default").unwrap();
            assert_eq!(
                got.map(|s| s.expose_secret().to_string()),
                Some(v.to_string()),
                "round-trip failed for {k}",
            );
        }
    }

    // Regression test for https://github.com/cachix/secretspec/issues/74:
    // setting a secret on a file that already holds a JSON-shaped value used to
    // corrupt the existing value because the serializer did not escape quotes.
    #[test]
    fn test_set_preserves_existing_quoted_json_value() {
        let dir = tempfile::tempdir().unwrap();
        let env_file = dir.path().join(".env");
        fs::write(&env_file, "FOO=\"{\\\"bar\\\":\\\"baz\\\"}\"\n").unwrap();

        let provider = DotEnvProvider::new(DotEnvConfig {
            path: env_file.clone(),
        });

        provider
            .set(
                "proj",
                "BAR",
                &SecretString::new("foobar".into()),
                "default",
            )
            .unwrap();

        let foo = provider.get("proj", "FOO", "default").unwrap();
        assert_eq!(
            foo.map(|s| s.expose_secret().to_string()),
            Some(r#"{"bar":"baz"}"#.to_string()),
        );
        let bar = provider.get("proj", "BAR", "default").unwrap();
        assert_eq!(
            bar.map(|s| s.expose_secret().to_string()),
            Some("foobar".to_string()),
        );
    }
}