use crate::{AppError, Result};
use serde::{Deserialize, Serialize};
#[derive(Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct StorageSettings {
pub driver: String,
pub root: String,
pub max_object_bytes: u64,
pub bucket: Option<String>,
pub region: Option<String>,
pub endpoint: Option<String>,
pub path_style: bool,
pub access_key_id: Option<String>,
pub secret_access_key: Option<String>,
pub session_token: Option<String>,
}
impl Default for StorageSettings {
fn default() -> Self {
Self {
driver: "none".into(),
root: ".capy/storage".into(),
max_object_bytes: 32 * 1024 * 1024,
bucket: None,
region: None,
endpoint: None,
path_style: true,
access_key_id: None,
secret_access_key: None,
session_token: None,
}
}
}
impl std::fmt::Debug for StorageSettings {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StorageSettings")
.field("driver", &self.driver)
.field("root", &self.root)
.field("max_object_bytes", &self.max_object_bytes)
.field("bucket", &self.bucket)
.field("region", &self.region)
.field("endpoint", &self.endpoint)
.field("path_style", &self.path_style)
.field(
"access_key_id",
&self.access_key_id.as_ref().map(|_| "[redacted]"),
)
.field(
"secret_access_key",
&self.secret_access_key.as_ref().map(|_| "[redacted]"),
)
.field(
"session_token",
&self.session_token.as_ref().map(|_| "[redacted]"),
)
.finish()
}
}
impl StorageSettings {
pub fn validate(&self, production: bool) -> Result<()> {
if !(1..=1_073_741_824).contains(&self.max_object_bytes) {
return Err(AppError::Configuration(
"Storage max_object_bytes must be 1..=1073741824.".into(),
));
}
match self.driver.as_str() {
"none" => Ok(()),
"memory" if production => Err(AppError::Configuration(
"In-memory storage is unavailable in production.".into(),
)),
"memory" => Ok(()),
"local" => {
let root = std::path::Path::new(&self.root);
if self.root.trim().is_empty()
|| self.root == "/"
|| root
.components()
.any(|component| matches!(component, std::path::Component::ParentDir))
{
return Err(AppError::Configuration("Storage local root must be a dedicated directory without parent traversal.".into()));
}
if let Ok(metadata) = std::fs::symlink_metadata(root) {
if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(AppError::Configuration(
"Storage local root must be a real directory.".into(),
));
}
}
Ok(())
}
"s3" => {
if self.bucket.as_deref().is_none_or(str::is_empty)
|| self.region.as_deref().is_none_or(str::is_empty)
{
return Err(AppError::Configuration(
"S3 storage requires bucket and region.".into(),
));
}
if self.access_key_id.is_some() != self.secret_access_key.is_some() {
return Err(AppError::Configuration(
"S3 access key and secret must be configured together.".into(),
));
}
if let Some(endpoint) = &self.endpoint {
let parsed = url::Url::parse(endpoint)
.map_err(|_| AppError::Configuration("Invalid S3 endpoint URL.".into()))?;
let secure = parsed.scheme() == "https";
let local = parsed.scheme() == "http"
&& matches!(parsed.host_str(), Some("127.0.0.1" | "localhost"));
if parsed.host_str().is_none()
|| !parsed.username().is_empty()
|| parsed.password().is_some()
|| parsed.query().is_some()
|| parsed.fragment().is_some()
{
return Err(AppError::Configuration("Invalid S3 endpoint URL.".into()));
}
if !(secure || local && !production) {
return Err(AppError::Configuration(
"S3 endpoint must use HTTPS, except localhost in development/test."
.into(),
));
}
}
Ok(())
}
_ => Err(AppError::Configuration(
"Storage driver must be none, memory, local, or s3.".into(),
)),
}
}
}