use super::profile::Profile;
use crate::error::{Failure, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
const STORE_FILE: &str = "profiles.toml";
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct StoreDocument {
#[serde(default, rename = "profile")]
profiles: Vec<Profile>,
}
#[derive(Debug, Clone)]
pub struct ProfileStore {
path: PathBuf,
document: StoreDocument,
}
impl ProfileStore {
pub fn open(directory: &Path) -> Result<Self> {
let path = directory.join(STORE_FILE);
if !path.exists() {
return Ok(Self {
path,
document: StoreDocument::default(),
});
}
let text = std::fs::read_to_string(&path).map_err(|cause| {
Failure::config(
"profile.store_unreadable",
"the profile store cannot be read",
)
.with_hint("check the permissions of the configuration directory")
.with_cause(cause.to_string())
})?;
let document = toml::from_str(&text).map_err(|cause| {
Failure::config(
"profile.store_malformed",
"the profile store is not in the expected form",
)
.with_hint("repair the file by hand, or remove it to start from an empty store")
.with_cause(cause.to_string())
})?;
Ok(Self { path, document })
}
#[must_use]
pub fn empty_at(path: PathBuf) -> Self {
Self {
path,
document: StoreDocument::default(),
}
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
#[must_use]
pub fn list(&self) -> &[Profile] {
&self.document.profiles
}
pub fn get(&self, name: &str) -> Result<&Profile> {
self.document
.profiles
.iter()
.find(|profile| profile.name == name)
.ok_or_else(|| Self::unknown(name))
}
pub fn get_mut(&mut self, name: &str) -> Result<&mut Profile> {
self.document
.profiles
.iter_mut()
.find(|profile| profile.name == name)
.ok_or_else(|| Self::unknown(name))
}
#[must_use]
pub fn contains(&self, name: &str) -> bool {
self.document
.profiles
.iter()
.any(|profile| profile.name == name)
}
pub fn add(&mut self, profile: Profile) -> Result<()> {
if profile.name.trim().is_empty() {
return Err(Failure::config(
"profile.empty_name",
"a profile name may not be empty",
));
}
if self.contains(&profile.name) {
return Err(
Failure::config("profile.already_exists", format!("`{}`", profile.name))
.with_detail("detail", profile.name.clone())
.with_hint("change it with `conn edit`, or remove it first"),
);
}
self.document.profiles.push(profile);
Ok(())
}
pub fn remove(&mut self, name: &str) -> Result<Profile> {
let position = self
.document
.profiles
.iter()
.position(|profile| profile.name == name)
.ok_or_else(|| Self::unknown(name))?;
Ok(self.document.profiles.remove(position))
}
pub fn ensure_exists(&self, name: &str) -> Result<()> {
if self.contains(name) {
return Ok(());
}
Err(Self::unknown(name))
}
pub fn resolve(
&self,
requested: Option<&str>,
stored_default: Option<&str>,
) -> Result<&Profile> {
if let Some(name) = requested {
return self.get(name).map_err(|_| {
Failure::config("profile.unknown", format!("`{name}`"))
.with_detail("detail", format!("`{name}`"))
.with_hint("list the ones that exist with `conn list`")
});
}
let name = stored_default.ok_or_else(|| {
Failure::config(
"profile.no_default",
"no profile was named and none is marked as the default",
)
.with_hint("name one with --profile, or mark one with `conn default`")
})?;
self.get(name).map_err(|_| {
Failure::config("profile.unknown", format!("`{name}`"))
.with_detail("detail", format!("`{name}`"))
.with_detail("named", "default")
.with_hint("list the ones that exist with `conn list`")
})
}
pub fn save(&self) -> Result<()> {
let directory = self.path.parent().ok_or_else(|| {
Failure::config(
"profile.store_path_invalid",
"the profile store path has no directory",
)
})?;
std::fs::create_dir_all(directory).map_err(|cause| {
Failure::config(
"profile.store_directory_unwritable",
"the configuration directory cannot be created",
)
.with_cause(cause.to_string())
})?;
let text = toml::to_string_pretty(&self.document).map_err(|cause| {
Failure::config(
"profile.store_unserialisable",
"the profile store cannot be written in the expected form",
)
.with_cause(cause.to_string())
})?;
write_private_atomically(&self.path, directory, text.as_bytes())
}
fn unknown(name: &str) -> Failure {
Failure::absence("profile.unknown", format!("`{name}`"))
.with_detail("detail", format!("`{name}`"))
.with_hint("run `conn list` to see the stored profiles")
}
}
#[cfg(unix)]
fn restrict(file: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(
file,
std::fs::Permissions::from_mode(crate::config::store::OWNER_ONLY),
)
.map_err(|cause| {
Failure::config(
"profile.store_permissions",
"the profile store could not be restricted to its owner",
)
.with_cause(cause.to_string())
})
}
#[cfg(not(unix))]
fn restrict(file: &Path) -> Result<()> {
crate::i18n::report::permissions_unavailable_profiles(&file.display().to_string());
Ok(())
}
fn write_private_atomically(path: &Path, directory: &Path, bytes: &[u8]) -> Result<()> {
use std::io::Write;
let mut temporary = tempfile::NamedTempFile::new_in(directory).map_err(|cause| {
Failure::config(
"profile.store_unwritable",
"no temporary file could be created next to the profile store",
)
.with_cause(cause.to_string())
})?;
temporary.write_all(bytes).map_err(|cause| {
Failure::config(
"profile.store_unwritable",
"the profile store cannot be written",
)
.with_cause(cause.to_string())
})?;
restrict(temporary.path())?;
temporary.persist(path).map_err(|cause| {
Failure::config(
"profile.store_not_replaced",
"the profile store could not be replaced",
)
.with_cause(cause.to_string())
})?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::conn::profile::SecretRef;
fn store() -> ProfileStore {
ProfileStore::empty_at(PathBuf::from("/nonexistent/profiles.toml"))
}
fn sample(name: &str) -> Profile {
Profile {
host: Some("db.example".to_owned()),
user: Some("reader".to_owned()),
secret: Some(SecretRef::for_profile(name)),
..Profile::named(name)
}
}
#[test]
fn the_store_owns_the_names_and_never_the_default() {
let mut store = store();
store.add(sample("first")).expect("added");
assert!(store.ensure_exists("first").is_ok());
assert!(store.ensure_exists("second").is_err());
}
#[test]
fn a_repeated_name_is_refused() {
let mut store = store();
store.add(sample("main")).expect("added");
let failure = store.add(sample("main")).expect_err("must refuse");
assert_eq!(failure.code(), "profile.already_exists");
}
#[test]
fn an_empty_name_is_refused() {
let failure = store().add(Profile::named(" ")).expect_err("must refuse");
assert_eq!(failure.code(), "profile.empty_name");
}
#[test]
fn a_default_naming_a_lost_profile_is_reported() {
let mut store = store();
store.add(sample("first")).expect("added");
store.remove("first").expect("removed");
let failure = store.resolve(None, Some("first")).expect_err("must refuse");
assert_eq!(failure.code(), "profile.unknown");
assert_eq!(failure.category(), crate::error::Category::Config);
}
#[test]
fn an_unknown_name_is_an_absence() {
let failure = store().get("ghost").expect_err("must refuse");
assert_eq!(failure.category(), crate::error::Category::Absence);
assert!(failure.hint().is_some());
assert!(store().ensure_exists("ghost").is_err());
assert!(store().resolve(Some("ghost"), None).is_err());
}
#[test]
fn resolving_without_a_default_is_a_configuration_failure() {
let failure = store().resolve(None, None).expect_err("must refuse");
assert_eq!(failure.code(), "profile.no_default");
}
#[test]
fn resolving_without_a_name_takes_the_marked_default() {
let mut store = store();
store.add(sample("first")).expect("added");
store.add(sample("second")).expect("added");
assert_eq!(
store.resolve(None, Some("second")).expect("resolved").name,
"second"
);
}
#[test]
fn the_store_round_trips_through_its_file() {
let directory = tempfile::tempdir().expect("temporary directory");
assert!(ProfileStore::open(directory.path())
.expect("opened")
.list()
.is_empty());
let mut written = ProfileStore::empty_at(directory.path().join(STORE_FILE));
written.add(sample("main")).expect("added");
written.save().expect("saved");
let read = ProfileStore::open(directory.path()).expect("opened");
assert_eq!(read.list().len(), 1);
assert_eq!(
read.get("main").expect("present").host.as_deref(),
Some("db.example")
);
}
#[test]
fn a_malformed_store_is_reported_and_not_treated_as_empty() {
let directory = tempfile::tempdir().expect("temporary directory");
std::fs::write(directory.path().join(STORE_FILE), "this is not = [valid").expect("written");
let failure = ProfileStore::open(directory.path()).expect_err("must refuse");
assert_eq!(failure.code(), "profile.store_malformed");
assert!(failure.hint().is_some());
}
#[cfg(unix)]
#[test]
fn the_written_store_is_private_to_its_owner() {
use std::os::unix::fs::PermissionsExt;
let directory = tempfile::tempdir().expect("temporary directory");
let mut store = ProfileStore::empty_at(directory.path().join(STORE_FILE));
store.add(sample("main")).expect("added");
store.save().expect("saved");
let mode = std::fs::metadata(store.path())
.expect("metadata")
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600);
}
}