use crate::conn::profile::{SecretRef, SecretVault};
use crate::error::{Failure, Result};
use secrecy::{ExposeSecret, SecretString};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecretStorage {
File,
Nowhere,
}
impl SecretStorage {
pub fn parse(word: &str) -> Result<Self> {
match word {
"file" => Ok(Self::File),
"none" => Ok(Self::Nowhere),
other => Err(
Failure::config("config.unknown_secret_storage", other.to_owned())
.with_detail("detail", other.to_owned())
.with_hint("the ways are `file` and `none`"),
),
}
}
#[must_use]
pub const fn keeps_anything(self) -> bool {
matches!(self, Self::File)
}
}
#[derive(Debug)]
pub struct FileVault {
file: PathBuf,
storage: SecretStorage,
}
const VAULT_FILE: &str = "secrets.toml";
impl FileVault {
pub fn open(directory: &Path) -> Result<Self> {
Self::open_keeping(directory, SecretStorage::File)
}
pub fn open_keeping(directory: &Path, storage: SecretStorage) -> Result<Self> {
Ok(Self {
file: directory.join(VAULT_FILE),
storage,
})
}
#[must_use]
pub fn path(&self) -> &Path {
&self.file
}
#[must_use]
pub const fn storage(&self) -> SecretStorage {
self.storage
}
}
impl SecretVault for FileVault {
fn store(&mut self, reference: &SecretRef, secret: &SecretString) -> Result<()> {
if !self.storage.keeps_anything() {
return Err(kept_nowhere());
}
crate::config::store::store(&self.file, reference.key(), secret.expose_secret())
}
fn load(&self, reference: &SecretRef) -> Result<Option<SecretString>> {
if !self.storage.keeps_anything() {
return Ok(None);
}
let stored = crate::config::store::load(&self.file)?;
Ok(stored
.get(reference.key())
.map(|raw| SecretString::from(raw.to_owned())))
}
fn forget(&mut self, reference: &SecretRef) -> Result<()> {
crate::config::store::remove(&self.file, reference.key())?;
Ok(())
}
}
#[must_use]
pub fn kept_nowhere() -> Failure {
Failure::config(
"vault.keeps_nothing",
"this host keeps no secret, so the one offered was not written down",
)
.with_hint(
"supply it on every invocation, or allow storage with \
`config set secret.storage_mode file`",
)
}
#[must_use]
pub fn missing(profile: &str) -> Failure {
Failure::config(
"vault.secret_missing",
format!("profile `{profile}` has no recorded secret"),
)
.with_detail("detail", profile)
.with_hint("record one with `conn edit <name> --password-stdin`")
}
#[cfg(test)]
mod tests {
use super::*;
fn scratch() -> tempfile::TempDir {
tempfile::tempdir().expect("scratch directory")
}
#[test]
fn a_recorded_secret_comes_back_intact() {
let dir = scratch();
let mut vault = FileVault::open(dir.path()).expect("opens");
let reference = SecretRef::for_profile("staging");
vault
.store(&reference, &SecretString::from("s3cr3t".to_owned()))
.expect("records");
let found = vault.load(&reference).expect("reads").expect("present");
assert_eq!(found.expose_secret(), "s3cr3t");
}
#[test]
fn an_unrecorded_secret_is_absent_rather_than_a_failure() {
let dir = scratch();
let vault = FileVault::open(dir.path()).expect("opens");
let found = vault
.load(&SecretRef::for_profile("never-set"))
.expect("reads");
assert!(found.is_none());
}
#[test]
fn forgetting_leaves_nothing_behind() {
let dir = scratch();
let mut vault = FileVault::open(dir.path()).expect("opens");
let reference = SecretRef::for_profile("gone");
vault
.store(&reference, &SecretString::from("value".to_owned()))
.expect("records");
vault.forget(&reference).expect("forgets");
assert!(vault.load(&reference).expect("reads").is_none());
}
#[test]
fn secrets_live_apart_from_settings() {
let dir = scratch();
let vault = FileVault::open(dir.path()).expect("opens");
let settings = crate::config::paths::config_file(Some(dir.path())).expect("location");
assert_ne!(
vault.path(),
settings,
"a shared configuration file must never carry a credential"
);
}
#[cfg(unix)]
#[test]
fn the_vault_file_is_readable_only_by_its_owner() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch();
let mut vault = FileVault::open(dir.path()).expect("opens");
vault
.store(
&SecretRef::for_profile("guarded"),
&SecretString::from("value".to_owned()),
)
.expect("records");
let mode = std::fs::metadata(vault.path())
.expect("the file exists")
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600, "unexpected mode {:o}", mode & 0o777);
}
}