use std::{
env,
error::Error,
fmt, fs,
io::Read,
path::{Path, PathBuf},
};
use serde::{Deserialize, Deserializer};
use zeroize::Zeroize;
use crate::result::{ClassifyError, ErrorKind};
pub const REDACTED: &str = "[REDACTED]";
pub const MAX_SECRET_FILE_BYTES: u64 = 64 * 1024;
pub trait ExposeSecret<T: ?Sized> {
fn expose_secret(&self) -> &T;
}
#[derive(Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[non_exhaustive]
pub struct SecretString {
value: String,
}
impl SecretString {
#[must_use]
pub fn new(value: impl Into<String>) -> Self {
Self {
value: value.into(),
}
}
#[must_use]
pub fn into_secret(mut self) -> String {
std::mem::take(&mut self.value)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.value.is_empty()
}
}
impl Clone for SecretString {
fn clone(&self) -> Self {
Self::new(self.value.clone())
}
}
impl Drop for SecretString {
fn drop(&mut self) {
self.value.zeroize();
}
}
impl ExposeSecret<str> for SecretString {
fn expose_secret(&self) -> &str {
&self.value
}
}
impl From<String> for SecretString {
fn from(value: String) -> Self {
Self::new(value)
}
}
impl From<&str> for SecretString {
fn from(value: &str) -> Self {
Self::new(value)
}
}
impl fmt::Debug for SecretString {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(REDACTED)
}
}
impl fmt::Display for SecretString {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(REDACTED)
}
}
impl<'de> Deserialize<'de> for SecretString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
String::deserialize(deserializer).map(Self::new)
}
}
#[derive(Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct SecretBytes {
value: Vec<u8>,
}
impl SecretBytes {
#[must_use]
pub fn new(value: impl Into<Vec<u8>>) -> Self {
Self {
value: value.into(),
}
}
#[must_use]
pub fn into_secret(mut self) -> Vec<u8> {
std::mem::take(&mut self.value)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.value.is_empty()
}
}
impl Clone for SecretBytes {
fn clone(&self) -> Self {
Self::new(self.value.clone())
}
}
impl Drop for SecretBytes {
fn drop(&mut self) {
self.value.zeroize();
}
}
impl ExposeSecret<[u8]> for SecretBytes {
fn expose_secret(&self) -> &[u8] {
&self.value
}
}
impl fmt::Debug for SecretBytes {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(REDACTED)
}
}
impl fmt::Display for SecretBytes {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(REDACTED)
}
}
#[derive(Clone, Default, Eq, PartialEq, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(try_from = "SecretSourceWire")]
#[non_exhaustive]
pub struct SecretSource {
#[serde(default)]
inline: Option<SecretString>,
#[serde(default)]
env: Option<String>,
#[serde(default)]
file: Option<PathBuf>,
}
impl SecretSource {
pub fn inline(value: impl Into<String>) -> Result<Self, SecretSourceError> {
let source = Self {
inline: Some(SecretString::new(value)),
env: None,
file: None,
};
source.validate()?;
Ok(source)
}
pub fn env(name: impl Into<String>) -> Result<Self, SecretSourceError> {
let source = Self {
inline: None,
env: Some(name.into().trim().to_owned()),
file: None,
};
source.validate()?;
Ok(source)
}
pub fn file(path: impl Into<PathBuf>) -> Result<Self, SecretSourceError> {
let source = Self {
inline: None,
env: None,
file: Some(path.into()),
};
source.validate()?;
Ok(source)
}
#[must_use]
pub fn inline_value(&self) -> Option<&SecretString> {
self.inline.as_ref()
}
#[must_use]
pub fn env_name(&self) -> Option<&str> {
self.env.as_deref()
}
#[must_use]
pub fn file_path(&self) -> Option<&Path> {
self.file.as_deref()
}
pub fn validate(&self) -> Result<(), SecretSourceError> {
match self.source_count() {
0 => Err(SecretSourceError::MissingSource),
1 => self.validate_selected_source(),
_ => Err(SecretSourceError::AmbiguousSource),
}
}
pub fn resolve(&self) -> Result<SecretString, SecretSourceError> {
match (&self.inline, &self.env, &self.file) {
(Some(value), None, None) => Ok(value.clone()),
(None, Some(name), None) => {
validate_secret_env_name(name)?;
let name = name.trim();
env::var(name)
.map(SecretString::new)
.map_err(|source| SecretSourceError::Env {
name: name.to_owned(),
source,
})
}
(None, None, Some(path)) => {
validate_secret_file_path(path)?;
let value = read_secret_file(path)?;
Ok(SecretString::new(strip_single_trailing_newline(value)))
}
(None, None, None) => Err(SecretSourceError::MissingSource),
_ => Err(SecretSourceError::AmbiguousSource),
}
}
fn validate_selected_source(&self) -> Result<(), SecretSourceError> {
if let Some(value) = &self.inline
&& value.is_empty()
{
return Err(SecretSourceError::EmptyInlineSecret);
}
if let Some(value) = &self.inline
&& value.expose_secret() == REDACTED
{
return Err(SecretSourceError::RedactedInlineSecret);
}
if let Some(name) = &self.env {
validate_secret_env_name(name)?;
}
if let Some(path) = &self.file {
validate_secret_file_path(path)?;
}
Ok(())
}
fn source_count(&self) -> usize {
usize::from(self.inline.is_some())
+ usize::from(self.env.is_some())
+ usize::from(self.file.is_some())
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SecretSourceWire {
#[serde(default)]
inline: Option<SecretString>,
#[serde(default)]
env: Option<String>,
#[serde(default)]
file: Option<PathBuf>,
}
impl TryFrom<SecretSourceWire> for SecretSource {
type Error = SecretSourceError;
fn try_from(value: SecretSourceWire) -> Result<Self, Self::Error> {
let source = Self {
inline: value.inline,
env: value.env.map(|value| value.trim().to_owned()),
file: value.file,
};
source.validate()?;
Ok(source)
}
}
impl fmt::Debug for SecretSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SecretSource")
.field("kind", &self.kind())
.finish_non_exhaustive()
}
}
impl SecretSource {
fn kind(&self) -> &'static str {
match (
self.inline.is_some(),
self.env.is_some(),
self.file.is_some(),
) {
(true, false, false) => "inline",
(false, true, false) => "env",
(false, false, true) => "file",
(false, false, false) => "missing",
_ => "ambiguous",
}
}
}
#[non_exhaustive]
pub enum SecretSourceError {
MissingSource,
AmbiguousSource,
EmptyInlineSecret,
RedactedInlineSecret,
EmptyEnvName,
InvalidEnvName,
EmptyFilePath,
Env {
name: String,
source: env::VarError,
},
File {
path: PathBuf,
source: std::io::Error,
},
FileTooLarge {
path: PathBuf,
max_bytes: u64,
},
FileInvalidUtf8 {
path: PathBuf,
source: std::string::FromUtf8Error,
},
}
impl fmt::Debug for SecretSourceError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("SecretSourceError")
.field("code", &self.error_code())
.finish_non_exhaustive()
}
}
impl fmt::Display for SecretSourceError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingSource => formatter.write_str("secret source must be configured"),
Self::AmbiguousSource => {
formatter.write_str("secret source must set exactly one of inline, env, or file")
}
Self::EmptyInlineSecret => formatter.write_str("inline secret must not be empty"),
Self::RedactedInlineSecret => {
formatter.write_str("inline secret must not be the redaction placeholder")
}
Self::EmptyEnvName => formatter.write_str("secret env var name must not be empty"),
Self::InvalidEnvName => formatter.write_str(
"secret env var name must start with ASCII letter or '_' and contain only ASCII letters, digits, or '_'",
),
Self::EmptyFilePath => formatter.write_str("secret file path must not be empty"),
Self::Env { .. } => formatter.write_str("failed to read configured secret env var"),
Self::File { .. } => formatter.write_str("failed to read configured secret file"),
Self::FileTooLarge { max_bytes, .. } => write!(
formatter,
"configured secret file exceeds the maximum size of {max_bytes} bytes"
),
Self::FileInvalidUtf8 { .. } => {
formatter.write_str("configured secret file is not valid UTF-8")
}
}
}
}
impl Error for SecretSourceError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Env { source, .. } => Some(source),
Self::File { source, .. } => Some(source),
Self::FileInvalidUtf8 { source, .. } => Some(source),
Self::MissingSource
| Self::AmbiguousSource
| Self::EmptyInlineSecret
| Self::RedactedInlineSecret
| Self::EmptyEnvName
| Self::InvalidEnvName
| Self::EmptyFilePath
| Self::FileTooLarge { .. } => None,
}
}
}
impl ClassifyError for SecretSourceError {
fn error_kind(&self) -> ErrorKind {
match self {
Self::MissingSource
| Self::AmbiguousSource
| Self::EmptyInlineSecret
| Self::RedactedInlineSecret
| Self::EmptyEnvName
| Self::InvalidEnvName
| Self::EmptyFilePath
| Self::FileTooLarge { .. }
| Self::FileInvalidUtf8 { .. } => ErrorKind::Validation,
Self::Env { .. } | Self::File { .. } => ErrorKind::Dependency,
}
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::MissingSource => "secret_source_missing",
Self::AmbiguousSource => "secret_source_ambiguous",
Self::EmptyInlineSecret => "secret_inline_empty",
Self::RedactedInlineSecret => "secret_inline_redacted",
Self::EmptyEnvName => "secret_env_name_empty",
Self::InvalidEnvName => "secret_env_name_invalid",
Self::EmptyFilePath => "secret_file_path_empty",
Self::Env { .. } => "secret_env_unavailable",
Self::File { .. } => "secret_file_unavailable",
Self::FileTooLarge { .. } => "secret_file_too_large",
Self::FileInvalidUtf8 { .. } => "secret_file_invalid_utf8",
})
}
}
fn read_secret_file(path: &Path) -> Result<String, SecretSourceError> {
let file = fs::File::open(path).map_err(|source| SecretSourceError::File {
path: path.to_owned(),
source,
})?;
let mut bytes = Vec::with_capacity(MAX_SECRET_FILE_BYTES as usize + 1);
file.take(MAX_SECRET_FILE_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|source| SecretSourceError::File {
path: path.to_owned(),
source,
})?;
if bytes.len() as u64 > MAX_SECRET_FILE_BYTES {
return Err(SecretSourceError::FileTooLarge {
path: path.to_owned(),
max_bytes: MAX_SECRET_FILE_BYTES,
});
}
String::from_utf8(bytes).map_err(|source| SecretSourceError::FileInvalidUtf8 {
path: path.to_owned(),
source,
})
}
fn validate_secret_env_name(name: &str) -> Result<(), SecretSourceError> {
let name = name.trim();
if name.is_empty() {
return Err(SecretSourceError::EmptyEnvName);
}
let mut bytes = name.bytes();
let Some(first) = bytes.next() else {
return Err(SecretSourceError::EmptyEnvName);
};
if !(first.is_ascii_alphabetic() || first == b'_') {
return Err(SecretSourceError::InvalidEnvName);
}
if !bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') {
return Err(SecretSourceError::InvalidEnvName);
}
Ok(())
}
fn validate_secret_file_path(path: &Path) -> Result<(), SecretSourceError> {
if path.as_os_str().is_empty() {
Err(SecretSourceError::EmptyFilePath)
} else {
Ok(())
}
}
fn strip_single_trailing_newline(mut value: String) -> String {
if value.ends_with('\n') {
value.pop();
if value.ends_with('\r') {
value.pop();
}
}
value
}
#[derive(Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[non_exhaustive]
pub struct Redacted<T> {
value: T,
}
impl<T> Redacted<T> {
#[must_use]
pub fn new(value: T) -> Self {
Self { value }
}
#[must_use]
pub const fn expose(&self) -> &T {
&self.value
}
#[must_use]
pub fn into_inner(self) -> T {
self.value
}
}
impl<T> fmt::Debug for Redacted<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(REDACTED)
}
}
impl<T> fmt::Display for Redacted<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(REDACTED)
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::{
ExposeSecret, MAX_SECRET_FILE_BYTES, Redacted, SecretSource, SecretSourceError,
SecretString,
};
use crate::result::{ClassifyError, ErrorKind};
#[test]
fn secret_string_redacts_formatting_and_requires_explicit_exposure() {
let secret = SecretString::new("secret-value");
assert_eq!(secret.expose_secret(), "secret-value");
assert_eq!(format!("{secret:?}"), "[REDACTED]");
assert_eq!(format!("{secret}"), "[REDACTED]");
assert_eq!(
serde_json::to_value(secret.expose_secret()).unwrap(),
json!("secret-value")
);
let deserialized: SecretString = serde_json::from_value(json!("loaded-secret")).unwrap();
assert_eq!(deserialized.expose_secret(), "loaded-secret");
}
#[test]
fn redacted_wrapper_keeps_explicit_access() {
let value = Redacted::new("postgres://user:password@localhost/db");
assert_eq!(*value.expose(), "postgres://user:password@localhost/db");
assert_eq!(format!("{value:?}"), "[REDACTED]");
}
#[test]
fn secret_source_resolves_inline_without_exposing_debug_value() {
let source = SecretSource::inline("secret-value").unwrap();
assert_eq!(source.resolve().unwrap().expose_secret(), "secret-value");
assert!(!format!("{source:?}").contains("secret-value"));
}
#[test]
fn secret_source_reads_file_and_strips_one_trailing_newline() {
let path = std::env::temp_dir().join(format!(
"footing-secret-source-{}-{}.txt",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::write(&path, "secret-value\n").unwrap();
let source = SecretSource::file(&path).unwrap();
assert_eq!(source.resolve().unwrap().expose_secret(), "secret-value");
let _ = std::fs::remove_file(path);
}
#[test]
fn secret_source_file_resolution_rejects_oversized_and_invalid_utf8_files() {
let oversized_path = std::env::temp_dir().join(format!(
"footing-secret-source-oversized-{}-{}.txt",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::write(
&oversized_path,
vec![b'a'; MAX_SECRET_FILE_BYTES as usize + 1],
)
.unwrap();
let error = SecretSource::file(&oversized_path)
.unwrap()
.resolve()
.expect_err("oversized file should fail");
assert!(matches!(error, SecretSourceError::FileTooLarge { .. }));
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "secret_file_too_large");
let _ = std::fs::remove_file(&oversized_path);
let utf8_path = std::env::temp_dir().join(format!(
"footing-secret-source-invalid-utf8-{}-{}.txt",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::write(&utf8_path, [0xff, 0xfe]).unwrap();
let error = SecretSource::file(&utf8_path)
.unwrap()
.resolve()
.expect_err("invalid UTF-8 file should fail");
assert!(matches!(error, SecretSourceError::FileInvalidUtf8 { .. }));
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "secret_file_invalid_utf8");
let _ = std::fs::remove_file(utf8_path);
}
#[test]
fn secret_source_requires_exactly_one_source() {
assert!(matches!(
SecretSource::default().validate(),
Err(SecretSourceError::MissingSource)
));
let error = serde_json::from_value::<SecretSource>(json!({
"inline": "secret",
"env": "SECRET"
}))
.expect_err("ambiguous source should fail during deserialization");
assert!(error.to_string().contains("exactly one"));
}
#[test]
fn secret_source_validates_selected_source_shape() {
assert_eq!(
SecretSource::env(" SECRET ").unwrap().env_name(),
Some("SECRET")
);
assert!(matches!(
SecretSource::inline(""),
Err(SecretSourceError::EmptyInlineSecret)
));
assert!(matches!(
SecretSource::inline("[REDACTED]"),
Err(SecretSourceError::RedactedInlineSecret)
));
assert!(matches!(
SecretSource::env(" "),
Err(SecretSourceError::EmptyEnvName)
));
assert!(matches!(
SecretSource::env("1SECRET"),
Err(SecretSourceError::InvalidEnvName)
));
assert!(matches!(
SecretSource::file(""),
Err(SecretSourceError::EmptyFilePath)
));
assert!(serde_json::from_value::<SecretSource>(json!({ "env": "bad-name" })).is_err());
assert!(serde_json::from_value::<SecretSource>(json!({ "inline": "[REDACTED]" })).is_err());
}
#[test]
fn secret_source_errors_are_classified() {
let missing = SecretSource::default()
.validate()
.expect_err("missing source should fail");
assert_eq!(missing.error_kind(), ErrorKind::Validation);
assert_eq!(missing.error_code(), "secret_source_missing");
let file = SecretSource::file("/path/that/does/not/exist")
.unwrap()
.resolve()
.expect_err("missing file should fail");
assert_eq!(file.error_kind(), ErrorKind::Dependency);
assert_eq!(file.error_code(), "secret_file_unavailable");
}
#[test]
fn secret_source_errors_redact_locations_and_source_bytes() {
let env_name = "PRIVATE_DATABASE_PASSWORD";
let env_error = SecretSourceError::Env {
name: env_name.to_owned(),
source: std::env::VarError::NotPresent,
};
let path = std::path::PathBuf::from("/private/secrets/database-password");
let invalid_bytes = b"private-secret-bytes\xff".to_vec();
let utf8_error = SecretSourceError::FileInvalidUtf8 {
path: path.clone(),
source: String::from_utf8(invalid_bytes.clone()).unwrap_err(),
};
let output = format!("{env_error} {env_error:?} {utf8_error} {utf8_error:?}");
assert!(output.contains("secret_env_unavailable"));
assert!(output.contains("secret_file_invalid_utf8"));
assert!(!output.contains(env_name));
assert!(!output.contains(path.to_string_lossy().as_ref()));
assert!(!output.contains("private-secret-bytes"));
assert!(!output.contains(&format!("{invalid_bytes:?}")));
}
}