Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 56e22622d9 |
+2
-22
@@ -5,29 +5,9 @@ All notable changes to this project will be documented in this file.
|
|||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
## v0.2.3 (2025-10-14)
|
## [0.0.1] - 2025-09-10
|
||||||
|
|
||||||
### Refactor
|
## v0.2.0 (2025-09-29)
|
||||||
|
|
||||||
- Refactored the library for gman so that it dynamically names config and password files to be used across any application
|
|
||||||
|
|
||||||
## v0.2.2 (2025-09-30)
|
|
||||||
|
|
||||||
### Refactor
|
|
||||||
|
|
||||||
- Environment variable interpolation in config file works globally, not based on type
|
|
||||||
|
|
||||||
## v0.2.1 (2025-09-30)
|
|
||||||
|
|
||||||
### Feat
|
|
||||||
|
|
||||||
- Environment variable interpolation in the Gman configuration file
|
|
||||||
|
|
||||||
### Fix
|
|
||||||
|
|
||||||
- Corrected tab completions for the provider flag
|
|
||||||
|
|
||||||
## v0.2.0 (2025-09-30)
|
|
||||||
|
|
||||||
### Feat
|
### Feat
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -60,7 +60,7 @@ representative at an online or offline event.
|
|||||||
|
|
||||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
reported to the community leaders responsible for enforcement at
|
reported to the community leaders responsible for enforcement at
|
||||||
alex.j.tusa@gmail.com.
|
d4udts@gmail.com.
|
||||||
All complaints will be reviewed and investigated promptly and fairly.
|
All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
All community leaders are obligated to respect the privacy and security of the
|
All community leaders are obligated to respect the privacy and security of the
|
||||||
|
|||||||
Generated
+321
-385
File diff suppressed because it is too large
Load Diff
+3
-9
@@ -1,16 +1,10 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "gman"
|
name = "gman"
|
||||||
version = "0.2.3"
|
version = "0.2.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
authors = ["Alex Clarke <alex.j.tusa@gmail.com>"]
|
authors = ["Alex Clarke <alex.j.tusa@gmail.com>"]
|
||||||
description = "Universal command line secret management and injection tool"
|
description = "Universal command line secret management and injection tool"
|
||||||
keywords = [
|
keywords = ["cli", "secrets-manager", "secret-injection", "command-runner", "vault"]
|
||||||
"cli",
|
|
||||||
"secrets-manager",
|
|
||||||
"secret-injection",
|
|
||||||
"command-runner",
|
|
||||||
"vault",
|
|
||||||
]
|
|
||||||
documentation = "https://github.com/Dark-Alex-17/gman"
|
documentation = "https://github.com/Dark-Alex-17/gman"
|
||||||
repository = "https://github.com/Dark-Alex-17/gman"
|
repository = "https://github.com/Dark-Alex-17/gman"
|
||||||
homepage = "https://github.com/Dark-Alex-17/gman"
|
homepage = "https://github.com/Dark-Alex-17/gman"
|
||||||
@@ -79,7 +73,7 @@ pretty_assertions = "1.4.1"
|
|||||||
proptest = "1.5.0"
|
proptest = "1.5.0"
|
||||||
assert_cmd = "2.0.16"
|
assert_cmd = "2.0.16"
|
||||||
predicates = "3.1.2"
|
predicates = "3.1.2"
|
||||||
serial_test = "3.2.0"
|
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
bench = false
|
bench = false
|
||||||
|
|||||||
@@ -89,13 +89,11 @@ gman aws sts get-caller-identity
|
|||||||
- [Features](#features)
|
- [Features](#features)
|
||||||
- [Installation](#installation)
|
- [Installation](#installation)
|
||||||
- [Configuration](#configuration)
|
- [Configuration](#configuration)
|
||||||
- [Environment Variable Interpolation](#environment-variable-interpolation)
|
|
||||||
- [Providers](#providers)
|
- [Providers](#providers)
|
||||||
- [Local](#provider-local)
|
- [Local](#provider-local)
|
||||||
- [AWS Secrets Manager](#provider-aws_secrets_manager)
|
- [AWS Secrets Manager](#provider-aws_secrets_manager)
|
||||||
- [GCP Secret Manager](#provider-gcp_secret_manager)
|
- [GCP Secret Manager](#provider-gcp_secret_manager)
|
||||||
- [Azure Key Vault](#provider-azure_key_vault)
|
- [Azure Key Vault](#provider-azure_key_vault)
|
||||||
- [Gopass](#provider-gopass)
|
|
||||||
- [Run Configurations](#run-configurations)
|
- [Run Configurations](#run-configurations)
|
||||||
- [Specifying a Default Provider per Run Config](#specifying-a-default-provider-per-run-config)
|
- [Specifying a Default Provider per Run Config](#specifying-a-default-provider-per-run-config)
|
||||||
- [Environment Variable Secret Injection](#environment-variable-secret-injection)
|
- [Environment Variable Secret Injection](#environment-variable-secret-injection)
|
||||||
@@ -243,28 +241,6 @@ providers:
|
|||||||
run_configs: []
|
run_configs: []
|
||||||
```
|
```
|
||||||
|
|
||||||
### Environment Variable Interpolation
|
|
||||||
The config file supports environment variable interpolation using `${VAR_NAME}` syntax. For example, to use an
|
|
||||||
AWS profile from your environment:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
providers:
|
|
||||||
- name: aws
|
|
||||||
type: aws_secrets_manager
|
|
||||||
aws_profile: ${AWS_PROFILE} # Uses the AWS_PROFILE env var
|
|
||||||
aws_region: us-east-1
|
|
||||||
```
|
|
||||||
|
|
||||||
Or to set a default profile to use when `AWS_PROFILE` is unset:
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
providers:
|
|
||||||
- name: aws
|
|
||||||
type: aws_secrets_manager
|
|
||||||
aws_profile: ${AWS_PROFILE:-default} # Uses 'default' if AWS_PROFILE is unset
|
|
||||||
aws_region: us-east-1
|
|
||||||
```
|
|
||||||
|
|
||||||
## Providers
|
## Providers
|
||||||
`gman` supports multiple providers for secret storage. The default provider is `local`, which stores secrets in an
|
`gman` supports multiple providers for secret storage. The default provider is `local`, which stores secrets in an
|
||||||
encrypted file on your filesystem. The CLI and config format are designed to be extensible so new providers can be
|
encrypted file on your filesystem. The CLI and config format are designed to be extensible so new providers can be
|
||||||
|
|||||||
+2
-144
@@ -257,7 +257,7 @@ pub fn parse_args(
|
|||||||
|
|
||||||
pub fn run_config_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
pub fn run_config_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
||||||
let cur = current.to_string_lossy();
|
let cur = current.to_string_lossy();
|
||||||
match load_config(true) {
|
match load_config() {
|
||||||
Ok(config) => {
|
Ok(config) => {
|
||||||
if let Some(run_configs) = config.run_configs {
|
if let Some(run_configs) = config.run_configs {
|
||||||
run_configs
|
run_configs
|
||||||
@@ -280,27 +280,9 @@ pub fn run_config_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn provider_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
|
||||||
let cur = current.to_string_lossy();
|
|
||||||
match load_config(true) {
|
|
||||||
Ok(config) => config
|
|
||||||
.providers
|
|
||||||
.iter()
|
|
||||||
.filter(|pc| {
|
|
||||||
pc.name
|
|
||||||
.as_ref()
|
|
||||||
.expect("run config has no name")
|
|
||||||
.starts_with(&*cur)
|
|
||||||
})
|
|
||||||
.map(|pc| CompletionCandidate::new(pc.name.as_ref().expect("provider has no name")))
|
|
||||||
.collect(),
|
|
||||||
Err(_) => vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn secrets_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
pub fn secrets_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
||||||
let cur = current.to_string_lossy();
|
let cur = current.to_string_lossy();
|
||||||
match load_config(true) {
|
match load_config() {
|
||||||
Ok(config) => {
|
Ok(config) => {
|
||||||
let mut provider_config = match config.extract_provider_config(None) {
|
let mut provider_config = match config.extract_provider_config(None) {
|
||||||
Ok(pc) => pc,
|
Ok(pc) => pc,
|
||||||
@@ -323,14 +305,10 @@ pub fn secrets_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::cli::generate_files_secret_injections;
|
use crate::cli::generate_files_secret_injections;
|
||||||
use gman::config::get_config_file_path;
|
|
||||||
use gman::config::{Config, RunConfig};
|
use gman::config::{Config, RunConfig};
|
||||||
use pretty_assertions::{assert_eq, assert_str_eq};
|
use pretty_assertions::{assert_eq, assert_str_eq};
|
||||||
use serial_test::serial;
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::env as std_env;
|
|
||||||
use std::ffi::OsString;
|
use std::ffi::OsString;
|
||||||
use tempfile::tempdir;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_generate_files_secret_injections() {
|
fn test_generate_files_secret_injections() {
|
||||||
@@ -431,124 +409,4 @@ mod tests {
|
|||||||
.expect_err("expected failed secret resolution in dry_run");
|
.expect_err("expected failed secret resolution in dry_run");
|
||||||
assert!(err.to_string().contains("Failed to fetch"));
|
assert!(err.to_string().contains("Failed to fetch"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[serial]
|
|
||||||
fn test_run_config_completer_filters_by_prefix() {
|
|
||||||
let td = tempdir().unwrap();
|
|
||||||
let xdg = td.path().join("xdg");
|
|
||||||
unsafe { std_env::set_var("XDG_CONFIG_HOME", &xdg) };
|
|
||||||
let cfg_path = get_config_file_path().unwrap();
|
|
||||||
let app_dir = cfg_path.parent().unwrap().to_path_buf();
|
|
||||||
fs::create_dir_all(&app_dir).unwrap();
|
|
||||||
|
|
||||||
let yaml = indoc::indoc! {
|
|
||||||
"---
|
|
||||||
default_provider: local
|
|
||||||
providers:
|
|
||||||
- name: local
|
|
||||||
type: local
|
|
||||||
run_configs:
|
|
||||||
- name: echo
|
|
||||||
secrets: [API_KEY]
|
|
||||||
- name: docker
|
|
||||||
secrets: [DB_PASSWORD]
|
|
||||||
- name: aws
|
|
||||||
secrets: [AWS_ACCESS_KEY_ID]
|
|
||||||
"
|
|
||||||
};
|
|
||||||
fs::write(app_dir.join("config.yml"), yaml).unwrap();
|
|
||||||
|
|
||||||
let out = run_config_completer(OsStr::new("do"));
|
|
||||||
assert_eq!(out.len(), 1);
|
|
||||||
// Compare via debug string to avoid depending on crate internals
|
|
||||||
let rendered = format!("{:?}", &out[0]);
|
|
||||||
assert!(rendered.contains("docker"), "got: {}", rendered);
|
|
||||||
|
|
||||||
unsafe { std_env::remove_var("XDG_CONFIG_HOME") };
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[serial]
|
|
||||||
fn test_provider_completer_lists_matching_providers() {
|
|
||||||
let td = tempdir().unwrap();
|
|
||||||
let xdg = td.path().join("xdg");
|
|
||||||
unsafe { std_env::set_var("XDG_CONFIG_HOME", &xdg) };
|
|
||||||
let cfg_path = get_config_file_path().unwrap();
|
|
||||||
let app_dir = cfg_path.parent().unwrap().to_path_buf();
|
|
||||||
fs::create_dir_all(&app_dir).unwrap();
|
|
||||||
|
|
||||||
let yaml = indoc::indoc! {
|
|
||||||
"---
|
|
||||||
default_provider: local
|
|
||||||
providers:
|
|
||||||
- name: local
|
|
||||||
type: local
|
|
||||||
- name: prod
|
|
||||||
type: local
|
|
||||||
run_configs:
|
|
||||||
- name: echo
|
|
||||||
secrets: [API_KEY]
|
|
||||||
"
|
|
||||||
};
|
|
||||||
fs::write(app_dir.join("config.yml"), yaml).unwrap();
|
|
||||||
|
|
||||||
// Prefix 'p' should match only 'prod'
|
|
||||||
let out = provider_completer(OsStr::new("p"));
|
|
||||||
assert_eq!(out.len(), 1);
|
|
||||||
let rendered = format!("{:?}", &out[0]);
|
|
||||||
assert!(rendered.contains("prod"), "got: {}", rendered);
|
|
||||||
|
|
||||||
// Empty prefix returns at least both providers
|
|
||||||
let out_all = provider_completer(OsStr::new(""));
|
|
||||||
assert!(out_all.len() >= 2);
|
|
||||||
|
|
||||||
unsafe { std_env::remove_var("XDG_CONFIG_HOME") };
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
|
||||||
#[serial]
|
|
||||||
async fn test_secrets_completer_filters_keys_by_prefix() {
|
|
||||||
let td = tempdir().unwrap();
|
|
||||||
let xdg = td.path().join("xdg");
|
|
||||||
unsafe { std_env::set_var("XDG_CONFIG_HOME", &xdg) };
|
|
||||||
let cfg_path = get_config_file_path().unwrap();
|
|
||||||
let app_dir = cfg_path.parent().unwrap().to_path_buf();
|
|
||||||
fs::create_dir_all(&app_dir).unwrap();
|
|
||||||
|
|
||||||
let yaml = indoc::indoc! {
|
|
||||||
"---
|
|
||||||
default_provider: local
|
|
||||||
providers:
|
|
||||||
- name: local
|
|
||||||
type: local
|
|
||||||
run_configs:
|
|
||||||
- name: echo
|
|
||||||
secrets: [API_KEY]
|
|
||||||
"
|
|
||||||
};
|
|
||||||
fs::write(app_dir.join("config.yml"), yaml).unwrap();
|
|
||||||
|
|
||||||
// Seed a minimal vault with keys (values are irrelevant for listing)
|
|
||||||
let vault_yaml = indoc::indoc! {
|
|
||||||
"---
|
|
||||||
API_KEY: dummy
|
|
||||||
DB_PASSWORD: dummy
|
|
||||||
AWS_ACCESS_KEY_ID: dummy
|
|
||||||
"
|
|
||||||
};
|
|
||||||
fs::write(app_dir.join("vault.yml"), vault_yaml).unwrap();
|
|
||||||
|
|
||||||
let out = secrets_completer(OsStr::new("AWS"));
|
|
||||||
assert_eq!(out.len(), 1);
|
|
||||||
let rendered = format!("{:?}", &out[0]);
|
|
||||||
assert!(rendered.contains("AWS_ACCESS_KEY_ID"), "got: {}", rendered);
|
|
||||||
|
|
||||||
let out2 = secrets_completer(OsStr::new("DB_"));
|
|
||||||
assert_eq!(out2.len(), 1);
|
|
||||||
let rendered2 = format!("{:?}", &out2[0]);
|
|
||||||
assert!(rendered2.contains("DB_PASSWORD"), "got: {}", rendered2);
|
|
||||||
|
|
||||||
unsafe { std_env::remove_var("XDG_CONFIG_HOME") };
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-5
@@ -1,4 +1,3 @@
|
|||||||
use crate::cli::provider_completer;
|
|
||||||
use crate::cli::run_config_completer;
|
use crate::cli::run_config_completer;
|
||||||
use crate::cli::secrets_completer;
|
use crate::cli::secrets_completer;
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
@@ -52,7 +51,7 @@ struct Cli {
|
|||||||
output: Option<OutputFormat>,
|
output: Option<OutputFormat>,
|
||||||
|
|
||||||
/// Specify the secret provider to use (defaults to 'default_provider' in config (usually 'local'))
|
/// Specify the secret provider to use (defaults to 'default_provider' in config (usually 'local'))
|
||||||
#[arg(long, global = true, env = "GMAN_PROVIDER", add = ArgValueCompleter::new(provider_completer))]
|
#[arg(long, global = true, env = "GMAN_PROVIDER", value_parser = ["local", "aws_secrets_manager", "azure_key_vault", "gcp_secret_manager", "gopass"])]
|
||||||
provider: Option<String>,
|
provider: Option<String>,
|
||||||
|
|
||||||
/// Specify a run profile to use when wrapping a command
|
/// Specify a run profile to use when wrapping a command
|
||||||
@@ -123,6 +122,13 @@ enum Commands {
|
|||||||
/// configured in a corresponding run profile
|
/// configured in a corresponding run profile
|
||||||
#[command(external_subcommand)]
|
#[command(external_subcommand)]
|
||||||
External(Vec<OsString>),
|
External(Vec<OsString>),
|
||||||
|
|
||||||
|
/// Generate shell completion scripts
|
||||||
|
Completions {
|
||||||
|
/// The shell to generate the script for
|
||||||
|
#[arg(value_enum)]
|
||||||
|
shell: clap_complete::Shell,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
@@ -150,7 +156,7 @@ async fn main() -> Result<()> {
|
|||||||
exit(1);
|
exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
let config = load_config(true)?;
|
let config = load_config()?;
|
||||||
let mut provider_config = config.extract_provider_config(cli.provider.clone())?;
|
let mut provider_config = config.extract_provider_config(cli.provider.clone())?;
|
||||||
let secrets_provider = provider_config.extract_provider();
|
let secrets_provider = provider_config.extract_provider();
|
||||||
|
|
||||||
@@ -231,8 +237,7 @@ async fn main() -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Commands::Config {} => {
|
Commands::Config {} => {
|
||||||
let uninterpolated_config = load_config(false)?;
|
let config_yaml = serde_yaml::to_string(&config)
|
||||||
let config_yaml = serde_yaml::to_string(&uninterpolated_config)
|
|
||||||
.with_context(|| "failed to serialize existing configuration")?;
|
.with_context(|| "failed to serialize existing configuration")?;
|
||||||
let new_config = Editor::new()
|
let new_config = Editor::new()
|
||||||
.edit(&config_yaml)
|
.edit(&config_yaml)
|
||||||
@@ -261,6 +266,11 @@ async fn main() -> Result<()> {
|
|||||||
Commands::External(tokens) => {
|
Commands::External(tokens) => {
|
||||||
wrap_and_run_command(cli.provider, &config, tokens, cli.profile, cli.dry_run).await?;
|
wrap_and_run_command(cli.provider, &config, tokens, cli.profile, cli.dry_run).await?;
|
||||||
}
|
}
|
||||||
|
Commands::Completions { shell } => {
|
||||||
|
let mut cmd = Cli::command();
|
||||||
|
let bin_name = cmd.get_name().to_string();
|
||||||
|
clap_complete::generate(shell, &mut cmd, bin_name, &mut io::stdout());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ pub fn init_logging_config() -> log4rs::Config {
|
|||||||
|
|
||||||
pub fn get_log_path() -> PathBuf {
|
pub fn get_log_path() -> PathBuf {
|
||||||
let base_dir = dirs::cache_dir().unwrap_or_else(env::temp_dir);
|
let base_dir = dirs::cache_dir().unwrap_or_else(env::temp_dir);
|
||||||
let log_dir = base_dir.join(env!("CARGO_CRATE_NAME"));
|
let log_dir = base_dir.join("gman");
|
||||||
|
|
||||||
let dir = if let Err(e) = fs::create_dir_all(&log_dir) {
|
let dir = if let Err(e) = fs::create_dir_all(&log_dir) {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
@@ -77,7 +77,7 @@ pub fn persist_config_file(config: &Config) -> Result<()> {
|
|||||||
fs::write(&config_path, s)
|
fs::write(&config_path, s)
|
||||||
.with_context(|| format!("failed to write {}", config_path.display()))?;
|
.with_context(|| format!("failed to write {}", config_path.display()))?;
|
||||||
} else {
|
} else {
|
||||||
confy::store(env!("CARGO_CRATE_NAME"), "config", config)
|
confy::store("gman", "config", config)
|
||||||
.with_context(|| "failed to save updated config via confy")?;
|
.with_context(|| "failed to save updated config via confy")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+21
-126
@@ -21,13 +21,11 @@
|
|||||||
//! rc.validate().unwrap();
|
//! rc.validate().unwrap();
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::calling_app_name;
|
|
||||||
use crate::providers::local::LocalProvider;
|
use crate::providers::local::LocalProvider;
|
||||||
use crate::providers::{SecretProvider, SupportedProvider};
|
use crate::providers::{SecretProvider, SupportedProvider};
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use collections::HashSet;
|
use collections::HashSet;
|
||||||
use log::debug;
|
use log::debug;
|
||||||
use regex::Regex;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_with::serde_as;
|
use serde_with::serde_as;
|
||||||
use serde_with::skip_serializing_none;
|
use serde_with::skip_serializing_none;
|
||||||
@@ -269,49 +267,48 @@ impl Config {
|
|||||||
|
|
||||||
/// Discover the default password file for the local provider.
|
/// Discover the default password file for the local provider.
|
||||||
///
|
///
|
||||||
/// On most systems this resolves to `~/.<executable_name>_password`
|
/// On most systems this resolves to `~/.gman_password` when the file
|
||||||
pub fn local_provider_password_file() -> PathBuf {
|
/// exists, otherwise `None`.
|
||||||
dirs::home_dir()
|
pub fn local_provider_password_file() -> Option<PathBuf> {
|
||||||
.map(|p| p.join(format!(".{}_password", calling_app_name())))
|
let candidate = dirs::home_dir().map(|p| p.join(".gman_password"));
|
||||||
.expect("unable to determine home directory for local provider password file")
|
match candidate {
|
||||||
|
Some(p) if p.exists() => Some(p),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Load and validate the application configuration.
|
/// Load and validate the application configuration.
|
||||||
///
|
///
|
||||||
/// This uses the `confy` crate to load the configuration from a file
|
/// This uses the `confy` crate to load the configuration from a file
|
||||||
/// (e.g. `~/.config/<executable_name>/config.yaml`). If the file does
|
/// (e.g. `~/.config/gman/config.yaml`). If the file does
|
||||||
/// not exist, a default configuration is created and saved.
|
/// not exist, a default configuration is created and saved.
|
||||||
///
|
///
|
||||||
/// ```no_run
|
/// ```no_run
|
||||||
/// # use gman::config::load_config;
|
/// # use gman::config::load_config;
|
||||||
/// // Load config with environment variable interpolation enabled
|
/// let config = load_config().unwrap();
|
||||||
/// let config = load_config(true).unwrap();
|
|
||||||
/// println!("loaded config: {:?}", config);
|
/// println!("loaded config: {:?}", config);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn load_config(interpolate: bool) -> Result<Config> {
|
pub fn load_config() -> Result<Config> {
|
||||||
let xdg_path = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
|
let xdg_path = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
|
||||||
|
|
||||||
let mut config: Config = if let Some(base) = xdg_path.as_ref() {
|
let mut config: Config = if let Some(base) = xdg_path.as_ref() {
|
||||||
let app_dir = base.join(calling_app_name());
|
let app_dir = base.join("gman");
|
||||||
let yml = app_dir.join("config.yml");
|
let yml = app_dir.join("config.yml");
|
||||||
let yaml = app_dir.join("config.yaml");
|
let yaml = app_dir.join("config.yaml");
|
||||||
if yml.exists() || yaml.exists() {
|
if yml.exists() || yaml.exists() {
|
||||||
let load_path = if yml.exists() { &yml } else { &yaml };
|
let load_path = if yml.exists() { &yml } else { &yaml };
|
||||||
let mut content = fs::read_to_string(load_path)
|
let content = fs::read_to_string(load_path)
|
||||||
.with_context(|| format!("failed to read config file '{}'", load_path.display()))?;
|
.with_context(|| format!("failed to read config file '{}'", load_path.display()))?;
|
||||||
if interpolate {
|
|
||||||
content = interpolate_env_vars(&content);
|
|
||||||
}
|
|
||||||
let cfg: Config = serde_yaml::from_str(&content).with_context(|| {
|
let cfg: Config = serde_yaml::from_str(&content).with_context(|| {
|
||||||
format!("failed to parse YAML config at '{}'", load_path.display())
|
format!("failed to parse YAML config at '{}'", load_path.display())
|
||||||
})?;
|
})?;
|
||||||
cfg
|
cfg
|
||||||
} else {
|
} else {
|
||||||
load_confy_config(interpolate)?
|
confy::load("gman", "config")?
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
load_confy_config(interpolate)?
|
confy::load("gman", "config")?
|
||||||
};
|
};
|
||||||
|
|
||||||
config.validate()?;
|
config.validate()?;
|
||||||
@@ -325,128 +322,26 @@ pub fn load_config(interpolate: bool) -> Result<Config> {
|
|||||||
ref mut provider_def,
|
ref mut provider_def,
|
||||||
} = p.provider_type
|
} = p.provider_type
|
||||||
&& provider_def.password_file.is_none()
|
&& provider_def.password_file.is_none()
|
||||||
&& Config::local_provider_password_file().exists()
|
&& let Some(local_password_file) = Config::local_provider_password_file()
|
||||||
{
|
{
|
||||||
provider_def.password_file = Some(Config::local_provider_password_file());
|
provider_def.password_file = Some(local_password_file);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_confy_config(interpolate: bool) -> Result<Config> {
|
/// Returns the configuration file path that `confy` will use for this app.
|
||||||
let load_path = confy::get_configuration_file_path(&calling_app_name(), "config")?;
|
|
||||||
let mut content = fs::read_to_string(&load_path)
|
|
||||||
.with_context(|| format!("failed to read config file '{}'", load_path.display()))?;
|
|
||||||
if interpolate {
|
|
||||||
content = interpolate_env_vars(&content);
|
|
||||||
}
|
|
||||||
let cfg: Config = serde_yaml::from_str(&content)
|
|
||||||
.with_context(|| format!("failed to parse YAML config at '{}'", load_path.display()))?;
|
|
||||||
|
|
||||||
Ok(cfg)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the configuration file path that `confy` will use
|
|
||||||
pub fn get_config_file_path() -> Result<PathBuf> {
|
pub fn get_config_file_path() -> Result<PathBuf> {
|
||||||
if let Some(base) = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from) {
|
if let Some(base) = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from) {
|
||||||
let dir = base.join(calling_app_name());
|
let dir = base.join("gman");
|
||||||
let yml = dir.join("config.yml");
|
let yml = dir.join("config.yml");
|
||||||
let yaml = dir.join("config.yaml");
|
let yaml = dir.join("config.yaml");
|
||||||
if yml.exists() || yaml.exists() {
|
if yml.exists() || yaml.exists() {
|
||||||
return Ok(if yml.exists() { yml } else { yaml });
|
return Ok(if yml.exists() { yml } else { yaml });
|
||||||
}
|
}
|
||||||
|
// Prefer .yml if creating anew
|
||||||
return Ok(dir.join("config.yml"));
|
return Ok(dir.join("config.yml"));
|
||||||
}
|
}
|
||||||
Ok(confy::get_configuration_file_path(
|
Ok(confy::get_configuration_file_path("gman", "config")?)
|
||||||
&calling_app_name(),
|
|
||||||
"config",
|
|
||||||
)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn interpolate_env_vars(s: &str) -> String {
|
|
||||||
let result = s.to_string();
|
|
||||||
let scrubbing_regex = Regex::new(r#"[\s{}^()\[\]\\|`'"]+"#).unwrap();
|
|
||||||
let var_regex = Regex::new(r"\$\{(.*?)(:-.+)?}").unwrap();
|
|
||||||
|
|
||||||
var_regex
|
|
||||||
.replace_all(s, |caps: ®ex::Captures<'_>| {
|
|
||||||
if let Some(mat) = caps.get(1) {
|
|
||||||
if let Ok(value) = env::var(mat.as_str()) {
|
|
||||||
return scrubbing_regex.replace_all(&value, "").to_string();
|
|
||||||
} else if let Some(default_value) = caps.get(2) {
|
|
||||||
return scrubbing_regex
|
|
||||||
.replace_all(
|
|
||||||
default_value
|
|
||||||
.as_str()
|
|
||||||
.strip_prefix(":-")
|
|
||||||
.expect("unable to strip ':-' prefix from default value"),
|
|
||||||
"",
|
|
||||||
)
|
|
||||||
.to_string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
scrubbing_regex.replace_all(&result, "").to_string()
|
|
||||||
})
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use pretty_assertions::assert_str_eq;
|
|
||||||
use serial_test::serial;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_interpolate_env_vars_defaults_to_original_string_if_not_in_yaml_interpolation_format() {
|
|
||||||
let var = interpolate_env_vars("TEST_VAR_INTERPOLATION_NON_YAML");
|
|
||||||
|
|
||||||
assert_str_eq!(var, "TEST_VAR_INTERPOLATION_NON_YAML");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[serial]
|
|
||||||
fn test_interpolate_env_vars_scrubs_all_unnecessary_characters() {
|
|
||||||
unsafe {
|
|
||||||
env::set_var(
|
|
||||||
"TEST_VAR_INTERPOLATION_UNNECESSARY_CHARACTERS",
|
|
||||||
r#"""
|
|
||||||
`"'https://dontdo:this@testing.com/query?test=%20query#results'"` {([\|])}
|
|
||||||
"""#,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
|
|
||||||
let var = interpolate_env_vars("${TEST_VAR_INTERPOLATION_UNNECESSARY_CHARACTERS}");
|
|
||||||
|
|
||||||
assert_str_eq!(
|
|
||||||
var,
|
|
||||||
"https://dontdo:this@testing.com/query?test=%20query#results"
|
|
||||||
);
|
|
||||||
unsafe { env::remove_var("TEST_VAR_INTERPOLATION_UNNECESSARY_CHARACTERS") };
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[serial]
|
|
||||||
fn test_interpolate_env_vars_scrubs_all_unnecessary_characters_for_default_values() {
|
|
||||||
let var = interpolate_env_vars(
|
|
||||||
r#"${UNSET:-`"'https://dontdo:this@testing.com/query?test=%20query#results'"` {([\|])}}"#,
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_str_eq!(
|
|
||||||
var,
|
|
||||||
"https://dontdo:this@testing.com/query?test=%20query#results"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_interpolate_env_vars_scrubs_all_unnecessary_characters_from_non_environment_variable() {
|
|
||||||
let var =
|
|
||||||
interpolate_env_vars("https://dontdo:this@testing.com/query?test=%20query#results");
|
|
||||||
|
|
||||||
assert_str_eq!(
|
|
||||||
var,
|
|
||||||
"https://dontdo:this@testing.com/query?test=%20query#results"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
-10
@@ -20,7 +20,6 @@
|
|||||||
//! The `config` and `providers` modules power the CLI. They can be embedded
|
//! The `config` and `providers` modules power the CLI. They can be embedded
|
||||||
//! in other programs, but many functions interact with the user or the
|
//! in other programs, but many functions interact with the user or the
|
||||||
//! filesystem. Prefer `no_run` doctests for those.
|
//! filesystem. Prefer `no_run` doctests for those.
|
||||||
|
|
||||||
use anyhow::{Context, Result, anyhow, bail};
|
use anyhow::{Context, Result, anyhow, bail};
|
||||||
use argon2::{
|
use argon2::{
|
||||||
Algorithm, Argon2, Params, Version,
|
Algorithm, Argon2, Params, Version,
|
||||||
@@ -32,7 +31,6 @@ use chacha20poly1305::{
|
|||||||
aead::{Aead, KeyInit, OsRng},
|
aead::{Aead, KeyInit, OsRng},
|
||||||
};
|
};
|
||||||
use secrecy::{ExposeSecret, SecretString};
|
use secrecy::{ExposeSecret, SecretString};
|
||||||
use std::path::PathBuf;
|
|
||||||
use zeroize::Zeroize;
|
use zeroize::Zeroize;
|
||||||
/// Configuration structures and helpers used by the CLI and library.
|
/// Configuration structures and helpers used by the CLI and library.
|
||||||
pub mod config;
|
pub mod config;
|
||||||
@@ -209,14 +207,6 @@ pub fn decrypt_string(password: impl Into<SecretString>, envelope: &str) -> Resu
|
|||||||
Ok(s)
|
Ok(s)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn calling_app_name() -> String {
|
|
||||||
let exe: PathBuf = std::env::current_exe().expect("unable to get current exe path");
|
|
||||||
exe.file_stem()
|
|
||||||
.and_then(|s| s.to_str())
|
|
||||||
.map(|s| s.to_owned())
|
|
||||||
.expect("executable name not valid UTF-8")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
use crate::calling_app_name;
|
|
||||||
use anyhow::{Context, Result, anyhow};
|
use anyhow::{Context, Result, anyhow};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use dialoguer::Confirm;
|
use dialoguer::Confirm;
|
||||||
@@ -26,7 +25,7 @@ pub fn sync_and_push(opts: &SyncOpts<'_>) -> Result<()> {
|
|||||||
opts.validate()
|
opts.validate()
|
||||||
.with_context(|| "invalid git sync options")?;
|
.with_context(|| "invalid git sync options")?;
|
||||||
let commit_message = format!("chore: sync @ {}", Utc::now().to_rfc3339());
|
let commit_message = format!("chore: sync @ {}", Utc::now().to_rfc3339());
|
||||||
let config_dir = confy::get_configuration_file_path(&calling_app_name(), "vault")
|
let config_dir = confy::get_configuration_file_path("gman", "vault")
|
||||||
.with_context(|| "get config dir")?
|
.with_context(|| "get config dir")?
|
||||||
.parent()
|
.parent()
|
||||||
.map(Path::to_path_buf)
|
.map(Path::to_path_buf)
|
||||||
@@ -38,7 +37,7 @@ pub fn sync_and_push(opts: &SyncOpts<'_>) -> Result<()> {
|
|||||||
fs::create_dir_all(&repo_dir).with_context(|| format!("create {}", repo_dir.display()))?;
|
fs::create_dir_all(&repo_dir).with_context(|| format!("create {}", repo_dir.display()))?;
|
||||||
|
|
||||||
// Move the default vault into the repo dir on first sync so only vault.yml is tracked.
|
// Move the default vault into the repo dir on first sync so only vault.yml is tracked.
|
||||||
let default_vault = confy::get_configuration_file_path(&calling_app_name(), "vault")
|
let default_vault = confy::get_configuration_file_path("gman", "vault")
|
||||||
.with_context(|| "get default vault path")?;
|
.with_context(|| "get default vault path")?;
|
||||||
let repo_vault = repo_dir.join("vault.yml");
|
let repo_vault = repo_dir.join("vault.yml");
|
||||||
if default_vault.exists() && !repo_vault.exists() {
|
if default_vault.exists() && !repo_vault.exists() {
|
||||||
|
|||||||
+6
-13
@@ -13,7 +13,6 @@ use crate::providers::git_sync::{
|
|||||||
use crate::providers::{SecretProvider, SupportedProvider};
|
use crate::providers::{SecretProvider, SupportedProvider};
|
||||||
use crate::{
|
use crate::{
|
||||||
ARGON_M_COST_KIB, ARGON_P, ARGON_T_COST, HEADER, KDF, KEY_LEN, NONCE_LEN, SALT_LEN, VERSION,
|
ARGON_M_COST_KIB, ARGON_P, ARGON_T_COST, HEADER, KDF, KEY_LEN, NONCE_LEN, SALT_LEN, VERSION,
|
||||||
calling_app_name,
|
|
||||||
};
|
};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use argon2::{Algorithm, Argon2, Params, Version};
|
use argon2::{Algorithm, Argon2, Params, Version};
|
||||||
@@ -64,13 +63,8 @@ pub struct LocalProvider {
|
|||||||
|
|
||||||
impl Default for LocalProvider {
|
impl Default for LocalProvider {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
let password_file = match Config::local_provider_password_file() {
|
|
||||||
p if p.exists() => Some(p),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
password_file,
|
password_file: Config::local_provider_password_file(),
|
||||||
git_branch: Some("main".into()),
|
git_branch: Some("main".into()),
|
||||||
git_remote_url: None,
|
git_remote_url: None,
|
||||||
git_user_name: None,
|
git_user_name: None,
|
||||||
@@ -253,7 +247,7 @@ impl LocalProvider {
|
|||||||
fn persist_git_settings_to_config(&self) -> Result<()> {
|
fn persist_git_settings_to_config(&self) -> Result<()> {
|
||||||
debug!("Saving updated config (only current local provider)");
|
debug!("Saving updated config (only current local provider)");
|
||||||
|
|
||||||
let mut cfg = load_config(true).with_context(|| "failed to load existing config")?;
|
let mut cfg = load_config().with_context(|| "failed to load existing config")?;
|
||||||
|
|
||||||
let target_name = self.runtime_provider_name.clone();
|
let target_name = self.runtime_provider_name.clone();
|
||||||
let mut updated = false;
|
let mut updated = false;
|
||||||
@@ -292,7 +286,7 @@ impl LocalProvider {
|
|||||||
let s = serde_yaml::to_string(&cfg)?;
|
let s = serde_yaml::to_string(&cfg)?;
|
||||||
fs::write(&path, s).with_context(|| format!("failed to write {}", path.display()))?;
|
fs::write(&path, s).with_context(|| format!("failed to write {}", path.display()))?;
|
||||||
} else {
|
} else {
|
||||||
confy::store(&calling_app_name(), "config", &cfg)
|
confy::store("gman", "config", &cfg)
|
||||||
.with_context(|| "failed to save updated config via confy")?;
|
.with_context(|| "failed to save updated config via confy")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,11 +335,10 @@ fn default_vault_path() -> Result<PathBuf> {
|
|||||||
let xdg_path = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
|
let xdg_path = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
|
||||||
|
|
||||||
if let Some(xdg) = xdg_path {
|
if let Some(xdg) = xdg_path {
|
||||||
return Ok(xdg.join(calling_app_name()).join("vault.yml"));
|
return Ok(xdg.join("gman").join("vault.yml"));
|
||||||
}
|
}
|
||||||
|
|
||||||
confy::get_configuration_file_path(&calling_app_name(), "vault")
|
confy::get_configuration_file_path("gman", "vault").with_context(|| "get config dir")
|
||||||
.with_context(|| "get config dir")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn base_config_dir() -> Result<PathBuf> {
|
fn base_config_dir() -> Result<PathBuf> {
|
||||||
@@ -567,7 +560,7 @@ mod tests {
|
|||||||
fn persist_only_target_local_provider_git_settings() {
|
fn persist_only_target_local_provider_git_settings() {
|
||||||
let td = tempdir().unwrap();
|
let td = tempdir().unwrap();
|
||||||
let xdg = td.path().join("xdg");
|
let xdg = td.path().join("xdg");
|
||||||
let app_dir = xdg.join(calling_app_name());
|
let app_dir = xdg.join("gman");
|
||||||
fs::create_dir_all(&app_dir).unwrap();
|
fs::create_dir_all(&app_dir).unwrap();
|
||||||
unsafe {
|
unsafe {
|
||||||
std_env::set_var("XDG_CONFIG_HOME", &xdg);
|
std_env::set_var("XDG_CONFIG_HOME", &xdg);
|
||||||
|
|||||||
@@ -130,6 +130,18 @@ fn cli_shows_help() {
|
|||||||
.stdout(predicate::str::contains("Usage").or(predicate::str::contains("Add")));
|
.stdout(predicate::str::contains("Usage").or(predicate::str::contains("Add")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cli_completions_bash() {
|
||||||
|
let (_td, cfg, cache) = setup_env();
|
||||||
|
let mut cmd = Command::cargo_bin("gman").unwrap();
|
||||||
|
cmd.env("XDG_CACHE_HOME", &cache)
|
||||||
|
.env("XDG_CONFIG_HOME", &cfg)
|
||||||
|
.args(["completions", "bash"]);
|
||||||
|
cmd.assert()
|
||||||
|
.success()
|
||||||
|
.stdout(predicate::str::contains("_gman").or(predicate::str::contains("complete -F")));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn cli_add_get_list_update_delete_roundtrip() {
|
fn cli_add_get_list_update_delete_roundtrip() {
|
||||||
let (td, xdg_cfg, xdg_cache) = setup_env();
|
let (td, xdg_cfg, xdg_cache) = setup_env();
|
||||||
|
|||||||
+10
-8
@@ -252,14 +252,16 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_config_local_provider_password_file() {
|
fn test_config_local_provider_password_file() {
|
||||||
let path = Config::local_provider_password_file();
|
let path = Config::local_provider_password_file();
|
||||||
// Derive expected filename based on current test executable name
|
let expected_path = dirs::home_dir().map(|p| p.join(".gman_password"));
|
||||||
let exe = std::env::current_exe().expect("current_exe");
|
if let Some(p) = &expected_path {
|
||||||
let stem = exe
|
if !p.exists() {
|
||||||
.file_stem()
|
assert_eq!(path, None);
|
||||||
.and_then(|s| s.to_str())
|
} else {
|
||||||
.expect("utf-8 file stem");
|
assert_eq!(path, expected_path);
|
||||||
let expected = dirs::home_dir().map(|p| p.join(format!(".{}_password", stem)));
|
}
|
||||||
assert_eq!(Some(path), expected);
|
} else {
|
||||||
|
assert_eq!(path, None);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -58,11 +58,10 @@ fn test_local_provider_invalid_email() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_local_provider_default() {
|
fn test_local_provider_default() {
|
||||||
let provider = LocalProvider::default();
|
let provider = LocalProvider::default();
|
||||||
let expected_pw = {
|
assert_eq!(
|
||||||
let p = Config::local_provider_password_file();
|
provider.password_file,
|
||||||
if p.exists() { Some(p) } else { None }
|
Config::local_provider_password_file()
|
||||||
};
|
);
|
||||||
assert_eq!(provider.password_file, expected_pw);
|
|
||||||
assert_eq!(provider.git_branch, Some("main".into()));
|
assert_eq!(provider.git_branch, Some("main".into()));
|
||||||
assert_eq!(provider.git_remote_url, None);
|
assert_eq!(provider.git_remote_url, None);
|
||||||
assert_eq!(provider.git_user_name, None);
|
assert_eq!(provider.git_user_name, None);
|
||||||
|
|||||||
Reference in New Issue
Block a user