use crate::error::{Failure, Result};
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::path::PathBuf;
const REDACTED: &str = "***";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SecretRef(String);
impl SecretRef {
#[must_use]
pub fn for_profile(name: &str) -> Self {
Self(format!("profile.{name}.secret"))
}
#[must_use]
pub fn key(&self) -> &str {
&self.0
}
}
pub trait SecretVault {
fn store(&mut self, reference: &SecretRef, secret: &SecretString) -> Result<()>;
fn load(&self, reference: &SecretRef) -> Result<Option<SecretString>>;
fn forget(&mut self, reference: &SecretRef) -> Result<()>;
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Profile {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub host: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub port: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub socket: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub user: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub database: Option<String>,
#[serde(default)]
pub pin_database: bool,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub auth_method: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub secret: Option<SecretRef>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub client_cert: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub client_key: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub ca: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub require_tls: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub session_setup: Vec<String>,
#[serde(default)]
pub read_only: bool,
}
impl Profile {
#[must_use]
pub fn named(name: impl Into<String>) -> Self {
Self {
name: name.into(),
..Self::default()
}
}
#[must_use]
pub fn redacted(&self) -> Value {
json!({
"name": self.name,
"host": self.host,
"port": self.port,
"socket": self.socket,
"user": self.user,
"database": self.database,
"pin_database": self.pin_database,
"auth_method": self.auth_method,
"secret": self.secret.as_ref().map(|_| REDACTED),
"client_cert": self.client_cert,
"client_key": self.client_key,
"ca": self.ca,
"require_tls": self.require_tls,
"session_setup": self.session_setup,
"read_only": self.read_only,
})
}
pub fn ensure_reachable(&self) -> Result<()> {
if self.host.is_none() && self.socket.is_none() {
return Err(Failure::config(
"profile.no_destination",
format!("profile `{}` names neither a host nor a socket", self.name),
)
.with_detail("profile", self.name.clone())
.with_hint("set a host with --host, or a local socket with --socket"));
}
Ok(())
}
pub fn ensure_pin_names_a_database(&self) -> Result<()> {
if self.pin_database && self.database.is_none() {
return Err(Failure::usage(
"profile.pinned_database_missing",
format!(
"profile `{}` fixes its database without naming one",
self.name
),
)
.with_detail("profile", self.name.clone())
.with_hint("name it in the same call, as in `--database loja --pin-database`"));
}
Ok(())
}
pub fn ensure_accepts_a_named_database(&self, named: Option<&str>) -> Result<()> {
let (true, Some(named)) = (self.pin_database, named) else {
return Ok(());
};
let pinned = self.database.as_deref().unwrap_or("<none>");
Err(Failure::usage(
"profile.database_is_pinned",
format!(
"profile `{}` is fixed on database `{pinned}` and takes no database parameter, \
so `{named}` cannot be honoured",
self.name
),
)
.with_detail("profile", self.name.clone())
.with_detail("pinned", pinned.to_owned())
.with_detail("named", named.to_owned())
.with_hint(format!(
"drop --database, or point at a destination whose database is not fixed; \
`conn edit {} --pin-database false` releases this one",
self.name
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
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 a_shown_profile_never_reveals_the_secret() {
let shown = sample("main").redacted();
assert_eq!(shown["secret"], REDACTED);
let text = serde_json::to_string(&shown).expect("serialises");
assert!(
!text.contains("profile.main.secret"),
"no handle leaks: {text}"
);
}
#[test]
fn a_profile_without_a_secret_shows_none() {
assert!(Profile::named("socketonly").redacted()["secret"].is_null());
}
#[test]
fn a_stored_profile_carries_a_handle_and_never_a_value() {
let written = toml::to_string(&sample("main")).expect("serialises");
assert!(
written.contains("profile.main.secret"),
"the handle is stored"
);
assert!(!written.contains("hunter2"));
}
#[test]
fn a_profile_with_no_destination_is_refused() {
let failure = Profile::named("empty")
.ensure_reachable()
.expect_err("must refuse");
assert_eq!(failure.code(), "profile.no_destination");
assert_eq!(failure.category(), crate::error::Category::Config);
}
#[test]
fn a_socket_alone_is_a_destination() {
let profile = Profile {
socket: Some(PathBuf::from("/run/mysqld/mysqld.sock")),
..Profile::named("local")
};
assert!(profile.ensure_reachable().is_ok());
}
}