monosecret 0.4.4

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
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
use std::process::Command;

use serde::Deserialize;
use serde::Serialize;

use crate::MonosecretError;
use crate::Provider;
use crate::SecretBytes;
use crate::config::NativeAddress;
use crate::provider::Address;
use crate::provider::ProviderUrl;

/// 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 "monosecret/{project}/{profile}/{key}" if not specified.
	pub folder_prefix: Option<String>,
}

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

	/// Creates a `GoPassConfig` from a URL.
	///
	/// The URL must have the scheme "gopass" (e.g., "gopass://" or
	/// "<gopass://monosecret/shared/{profile}/{key>}").
	fn try_from(url: &ProviderUrl) -> Result<Self, Self::Error> {
		if url.scheme() != "gopass" {
			return Err(MonosecretError::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")
}

/// Whether `gopass insert` followed by `gopass show -o` returns `value`
/// unchanged, so it can live on the password line of a plain text entry.
///
/// `insert` terminates the entry with a newline and normalizes CRLF, `show -o`
/// prints only the first line, and text reads here remove surrounding
/// whitespace for entries other tools created. A value any of those would
/// alter is stored as a binary entry instead.
fn stores_as_password_line(value: &[u8]) -> bool {
	std::str::from_utf8(value).is_ok_and(|text| {
		!text.is_empty() && !text.contains(['\n', '\r', '\0']) && text.trim().len() == text.len()
	})
}

crate::register_provider! {
	struct: GoPassProvider,
	config: GoPassConfig,
	name: "gopass",
	description: "Multi-user and multi-store abstraction layer over pass",
	schemes: ["gopass"],
	examples: ["gopass://", "gopass://monosecret/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 "monosecret/{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("monosecret/{project}/{profile}/{key}");

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

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

	/// Whether `entry` is a binary entry written by `gopass cat`, which marks
	/// its body with `Content-Transfer-Encoding: Base64`.
	///
	/// A failed lookup means the entry has no such key, so it is not one.
	fn is_binary_entry(entry: &str) -> crate::Result<bool> {
		let output = Self::command()
			.args(["show", "-y"])
			.arg(entry)
			.arg(BINARY_ENTRY_HEADER)
			.output()
			.map_err(|e| {
				MonosecretError::ProviderOperationFailed(format!(
					"Failed to execute 'gopass' command: {e}. Is gopass installed?"
				))
			})?;
		Ok(output.status.success()
			&& String::from_utf8_lossy(&output.stdout)
				.trim()
				.eq_ignore_ascii_case("base64"))
	}
}

/// The key `gopass cat` sets on the binary entries it writes.
const BINARY_ENTRY_HEADER: &str = "Content-Transfer-Encoding";

impl Provider for GoPassProvider {
	/// Convention entries live under the folder-prefix format string,
	/// `monosecret/{project}/{profile}/{key}` by default.
	fn convention_address(
		&self,
		project: &str,
		profile: &str,
		key: &str,
	) -> crate::Result<NativeAddress> {
		Ok(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(SecretBytes))` - 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<SecretBytes>> {
		let entry_name = super::flat_item(self, addr)?;

		let mut output = Self::command()
			.args(["show", "-y", "-o"])
			.arg(&*entry_name)
			.output()
			.map_err(|e| {
				MonosecretError::ProviderOperationFailed(format!(
					"Failed to execute 'gopass' command: {e}. Is gopass installed?"
				))
			})?;

		// Keep the established password-only semantics for existing text
		// entries. Native binary entries written by `cat` have no password
		// line, so gopass directs us to their body instead. Only an entry that
		// carries the Base64 header `cat` writes is read that way: for any
		// other entry, such as one holding only YAML metadata, `cat` prints
		// the whole entry, which is not a secret value.
		let lossless = output.status.code() == Some(11)
			&& String::from_utf8_lossy(&output.stderr).contains("no password to display")
			&& Self::is_binary_entry(&entry_name)?;

		if lossless {
			output = Self::command()
				.arg("cat")
				.arg(&*entry_name)
				// `cat` writes when stdin is a pipe; select its read mode.
				.stdin(std::process::Stdio::null())
				.output()
				.map_err(|e| {
					MonosecretError::ProviderOperationFailed(format!(
						"Failed to execute 'gopass cat' command: {e}"
					))
				})?;
		}

		if output.status.success() {
			if lossless {
				// `cat` decodes the entry's body and writes the stored bytes
				// exactly, so nothing here may interpret them.
				return Ok(Some(SecretBytes::from_vec(output.stdout)));
			}

			let content = String::from_utf8(output.stdout).map_err(|e| {
				MonosecretError::ProviderOperationFailed(format!(
					"Failed to parse gopass output as UTF-8: {e}"
				))
			})?;
			Ok(Some(SecretBytes::from_utf8(content.trim())))
		} 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(MonosecretError::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(MonosecretError)` - If writing the gopass entry fails
	fn set(&self, addr: Address<'_>, value: &SecretBytes) -> crate::Result<()> {
		let entry_name = super::flat_item(self, addr)?;

		// A password-line value stays a plain text entry, which every gopass
		// reader and earlier Monosecret releases understand. Anything the text
		// path would alter is stored with `cat` instead, in gopass's native
		// binary-entry format, so it comes back byte for byte.
		let subcommand: &[&str] = if stores_as_password_line(value.expose_secret()) {
			&["insert", "-m", "-f"]
		} else {
			&["cat"]
		};

		let mut child = Self::command()
			.args(subcommand)
			.arg(&*entry_name)
			.stdin(std::process::Stdio::piped())
			.stdout(std::process::Stdio::piped())
			.stderr(std::process::Stdio::piped())
			.spawn()
			.map_err(|e| {
				MonosecretError::ProviderOperationFailed(format!(
					"Failed to execute gopass command: {e}"
				))
			})?;

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

		use std::io::Write;
		stdin.write_all(value.expose_secret()).map_err(|e| {
			MonosecretError::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| {
			MonosecretError::ProviderOperationFailed(format!(
				"Failed to wait for gopass command: {e}"
			))
		})?;

		if !output.status.success() {
			let stderr = String::from_utf8_lossy(&output.stderr);
			// Some gopass releases have `cat` report unchanged content as an
			// error. Confirm the value before treating that as a no-op.
			if output.status.code() == Some(1)
				&& stderr.trim_end().ends_with(": meaningless write")
				&& self.get(addr)?.is_some_and(|stored| stored == *value)
			{
				return Ok(());
			}
			return Err(MonosecretError::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| {
				MonosecretError::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(MonosecretError::ProviderOperationFailed(format!(
			"gopass command failed: {stderr}"
		)))
	}

	fn supports_delete(&self) -> bool {
		true
	}

	fn name(&self) -> &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}")
		}
	}

	/// The URI's folder prefix is compiled into the native entry name and does
	/// not identify a separate gopass installation.
	fn entry_container_identity(&self) -> String {
		"gopass".to_string()
	}
}

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

	use super::*;

	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"),
			"monosecret/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://monosecret/shared/{profile}/{key}"))
				.unwrap();
		assert_eq!(
			config.folder_prefix.as_deref(),
			Some("monosecret/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 password_line_values_stay_text_entries() {
		for value in ["hunter2", "with spaces inside", "🔐 émojis", "a\tb"] {
			assert!(stores_as_password_line(value.as_bytes()), "{value:?}");
		}
		for value in [
			"line1\nline2",
			"trailing\n",
			"a\r\nb",
			"cr\ronly",
			" padded ",
			"\ttab",
			"nul\0byte",
			"",
		] {
			assert!(!stores_as_password_line(value.as_bytes()), "{value:?}");
		}
		assert!(!stores_as_password_line(b"\xff\xfe"));
	}

	#[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 \"monosecret/p/default/API_KEY\": \
             entry is not in the password store\n",
			"Error: Secret \"monosecret/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 = 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 = 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}");
	}
}