secretspec 0.17.0

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
use crate::config::NativeAddress;
use crate::provider::{Address, ProviderUrl};
use crate::{Provider, SecretSpecError};
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
use std::process::Command;

/// Configuration for the gopass (gopass.pw) provider.
///
/// Gopass is a multi-user, multi-store abstraction layer on top of
/// `pass`.
/// This struct holds configuration options for the gopass provider
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct GoPassConfig {
    /// Optional folder prefix format string for organizing secrets in pass.
    ///
    /// Supports placeholders: {project}, {profile}, and {key}.
    /// Defaults to "secretspec/{project}/{profile}/{key}" if not specified.
    pub folder_prefix: Option<String>,
}

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

    /// Creates a GoPassConfig from a URL.
    ///
    /// The URL must have the scheme "gopass" (e.g., "gopass://" or
    /// "gopass://secretspec/shared/{profile}/{key}").
    fn try_from(url: &ProviderUrl) -> Result<Self, Self::Error> {
        if url.scheme() != "gopass" {
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "Invalid scheme '{}' for gopass provider",
                url.scheme(),
            )));
        }

        let mut config = Self::default();

        if let Some(host) = url.host() {
            let path = url.path();
            config.folder_prefix = Some(format!("{}{}", host, path));
        }

        Ok(config)
    }
}

pub struct GoPassProvider {
    config: GoPassConfig,
}

/// Whether a failed `gopass` invocation failed only because the entry is not in
/// the store.
///
/// The wording depends on which subcommand ran: `gopass show` reports a lookup
/// through the store layer ("... is not in the password store"), while `gopass
/// rm` checks existence itself and reports `Secret "..." does not exist`.
/// Matching only the first message made deleting an absent entry an error.
fn is_missing_entry(stderr: &str) -> bool {
    stderr.contains("is not in the password store") || stderr.contains("does not exist")
}

crate::register_provider! {
    struct: GoPassProvider,
    config: GoPassConfig,
    name: "gopass",
    description: "Multi-user and multi-store abstraction layer over pass",
    schemes: ["gopass"],
    examples: ["gopass://", "gopass://secretspec/shared/{profile}/{key}"],
    deletes: true,
}

impl GoPassProvider {
    /// Creates a new GoPassProvider with the given configuration.
    pub fn new(config: GoPassConfig) -> Self {
        Self { config }
    }

    /// Formats the entry name for a secret.
    ///
    /// Uses folder_prefix as a format string with {project}, {profile}, and {key} placeholders.
    /// Defaults to "secretspec/{project}/{profile}/{key}" if not configured.
    fn format_entry_name(&self, project: &str, profile: &str, key: &str) -> String {
        let format_string = self
            .config
            .folder_prefix
            .as_deref()
            .unwrap_or("secretspec/{project}/{profile}/{key}");

        format_string
            .replace("{project}", project)
            .replace("{profile}", profile)
            .replace("{key}", key)
    }

    /// Creates a `gopass` command
    fn command(&self) -> Command {
        Command::new("gopass")
    }
}

impl Provider for GoPassProvider {
    /// Convention entries live under the folder-prefix format string,
    /// `secretspec/{project}/{profile}/{key}` by default.
    fn convention_address(
        &self,
        project: &str,
        profile: &str,
        key: &str,
    ) -> crate::Result<NativeAddress> {
        Ok(crate::config::NativeAddress {
            item: self.format_entry_name(project, profile, key),
            ..Default::default()
        })
    }

    /// Retrieves a secret from the password store.
    ///
    /// # Arguments
    ///
    /// * `project` - The project name
    /// * `key` - The secret key to retrieve
    /// * `profile` - The profile name
    ///
    /// # Returns
    ///
    /// * `Ok(Some(SecretString))` - The secret value if found
    /// * `Ok(None)` - If the secret doesn't exist in the password store
    /// * `Err` - If there was an error executing `gopass` or reading the output
    fn get(&self, addr: Address<'_>) -> crate::Result<Option<SecretString>> {
        let entry_name = super::flat_item(self, addr)?;

        let output = self
            .command()
            .arg("show")
            // auto-confirm any yes/no prompt, in case the entry doesn't exist
            .arg("-y")
            // only show the password
            // ponytail: first line only — multiline secrets truncate; switch to -n/--noparsing if that bites
            .arg("-o")
            .arg(&*entry_name)
            .output()
            .map_err(|e| {
                SecretSpecError::ProviderOperationFailed(format!(
                    "Failed to execute 'gopass' command: {}. Is gopass installed?",
                    e
                ))
            })?;

        if output.status.success() {
            let content = String::from_utf8(output.stdout)
                .map_err(|e| {
                    SecretSpecError::ProviderOperationFailed(format!(
                        "Failed to parse gopass output as UTF-8: {}",
                        e
                    ))
                })?
                .trim()
                .to_string();

            Ok(Some(SecretString::new(content.into())))
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);

            // Entry doesn't exist. gopass exits 11 here; the message is
            // "is not in the password store" when piped.
            if output.status.code() == Some(11) && is_missing_entry(&stderr) {
                Ok(None)
            } else {
                Err(SecretSpecError::ProviderOperationFailed(format!(
                    "gopass command failed: {}",
                    stderr
                )))
            }
        }
    }

    /// Sets a secret value in the password store.
    ///
    /// # Arguments
    ///
    /// * `project` - The project name
    /// * `key` - The secret key to set
    /// * `value` - The value to store
    /// * `profile` - The profile name
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the value was successfully written
    /// * `Err(SecretSpecError)` - If writing the gopass entry fails
    fn set(&self, addr: Address<'_>, value: &SecretString) -> crate::Result<()> {
        let entry_name = super::flat_item(self, addr)?;

        let mut child = self
            .command()
            .args(["insert", "-m", "-f", &entry_name])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| {
                SecretSpecError::ProviderOperationFailed(format!(
                    "Failed to execute gopass command: {}",
                    e
                ))
            })?;

        let mut stdin = child.stdin.take().ok_or_else(|| {
            SecretSpecError::ProviderOperationFailed(
                "Failed to obtain stdin for gopass command".to_string(),
            )
        })?;

        use std::io::Write;
        stdin
            .write_all(value.expose_secret().as_bytes())
            .map_err(|e| {
                SecretSpecError::ProviderOperationFailed(format!(
                    "Failed to write to gopass stdin: {}",
                    e
                ))
            })?;

        // Drop stdin to close the pipe so gopass process receives EOF
        drop(stdin);

        let output = child.wait_with_output().map_err(|e| {
            SecretSpecError::ProviderOperationFailed(format!(
                "Failed to wait for gopass command: {}",
                e
            ))
        })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(SecretSpecError::ProviderOperationFailed(format!(
                "gopass command failed: {}",
                stderr
            )));
        }

        Ok(())
    }

    fn delete(&self, addr: Address<'_>) -> crate::Result<bool> {
        let entry_name = super::flat_item(self, addr)?;
        let output = self
            .command()
            .args(["rm", "-f", &entry_name])
            .output()
            .map_err(|error| {
                SecretSpecError::ProviderOperationFailed(format!(
                    "Failed to execute 'gopass' command: {error}. Is gopass installed?"
                ))
            })?;
        if output.status.success() {
            return Ok(true);
        }
        let stderr = String::from_utf8_lossy(&output.stderr);
        // Deleting what is already gone is a no-op, not a failure — cache
        // invalidation runs over secrets that may never have been cached. The
        // exit code is not checked here: `rm` reports a missing entry with a
        // different code than `show` does, and the codes have moved between
        // gopass releases, so the message is the reliable signal.
        if is_missing_entry(&stderr) {
            return Ok(false);
        }
        Err(SecretSpecError::ProviderOperationFailed(format!(
            "gopass command failed: {stderr}"
        )))
    }

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

    fn uri(&self) -> String {
        let prefix = self
            .config
            .folder_prefix
            .as_deref()
            .map(ProviderUrl::encode)
            .unwrap_or_default();

        if prefix.is_empty() {
            "gopass".to_string()
        } else {
            format!("gopass://{}", prefix)
        }
    }
}

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

    fn provider_url(s: &str) -> ProviderUrl {
        ProviderUrl::new(Url::parse(s).unwrap())
    }

    #[test]
    fn format_entry_name_default_pattern() {
        let provider = GoPassProvider::new(GoPassConfig::default());
        assert_eq!(
            provider.format_entry_name("myproj", "prod", "API_KEY"),
            "secretspec/myproj/prod/API_KEY"
        );
    }

    #[test]
    fn format_entry_name_custom_prefix() {
        let provider = GoPassProvider::new(GoPassConfig {
            folder_prefix: Some("team-store/{profile}/{key}".to_string()),
        });
        assert_eq!(
            provider.format_entry_name("myproj", "prod", "API_KEY"),
            "team-store/prod/API_KEY"
        );
    }

    #[test]
    fn try_from_sets_folder_prefix_from_host_and_path() {
        let config =
            GoPassConfig::try_from(&provider_url("gopass://secretspec/shared/{profile}/{key}"))
                .unwrap();
        assert_eq!(
            config.folder_prefix.as_deref(),
            Some("secretspec/shared/{profile}/{key}")
        );
    }

    #[test]
    fn try_from_bare_url_leaves_prefix_unset() {
        let config = GoPassConfig::try_from(&provider_url("gopass://")).unwrap();
        assert_eq!(config.folder_prefix, None);
    }

    #[test]
    fn missing_entry_is_recognized_from_show_and_rm() {
        // Both subcommands report an absent entry, in their own words. Deleting
        // an entry that is already gone has to be a no-op for either.
        for stderr in [
            "Error: failed to retrieve secret \"secretspec/p/default/API_KEY\": \
             entry is not in the password store\n",
            "Error: Secret \"secretspec/p/default/API_KEY\" does not exist\n",
        ] {
            assert!(is_missing_entry(stderr), "{stderr}");
        }

        for stderr in [
            "Error: failed to decrypt: gpg: decryption failed: No secret key\n",
            "Error: Store not initialized. Run gopass init.\n",
            "",
        ] {
            assert!(!is_missing_entry(stderr), "{stderr}");
        }
    }

    #[test]
    fn try_from_rejects_wrong_scheme() {
        let err = GoPassConfig::try_from(&provider_url("pass://x")).unwrap_err();
        assert!(err.to_string().contains("Invalid scheme"));
    }

    #[test]
    fn uri_round_trips_default_and_prefix() {
        assert_eq!(GoPassProvider::new(GoPassConfig::default()).uri(), "gopass");
        let provider = GoPassProvider::new(GoPassConfig {
            folder_prefix: Some("my store/{key}".to_string()),
        });
        assert_eq!(provider.uri(), "gopass://my%20store/{key}");
    }

    /// A native address names the store entry directly via `item`, bypassing
    /// the folder-prefix format string. This is what gopass logical paths
    /// (including mount-point prefixes for multi-store setups) map onto.
    #[test]
    fn native_address_names_the_entry() {
        let p = GoPassProvider::new(GoPassConfig {
            folder_prefix: Some("team-store/{profile}/{key}".to_string()),
        });
        let addr = crate::config::NativeAddress {
            item: "work-store/email/work".into(),
            ..Default::default()
        };
        assert_eq!(
            crate::provider::flat_item(&p, Address::Native(&addr)).unwrap(),
            "work-store/email/work"
        );
    }

    /// Store entries have no sub-components; a `field` coordinate is rejected.
    #[test]
    fn native_address_rejects_field() {
        let p = GoPassProvider::new(GoPassConfig::default());
        let addr = crate::config::NativeAddress {
            item: "email/work".into(),
            field: Some("password".into()),
            ..Default::default()
        };
        let err = crate::provider::flat_item(&p, Address::Native(&addr)).unwrap_err();
        assert!(err.to_string().contains("`field`"), "{err}");
    }
}