capy-core 0.10.0

Typed configuration, application context, and errors for the Capy web framework.
Documentation
use crate::{AppError, Result};
use serde::{Deserialize, Serialize};

/// Optional private object-store configuration (`config/storage.toml`, `STORAGE_*`).
#[derive(Clone, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct StorageSettings {
    /// `none`, `memory`, `local`, or `s3`.
    pub driver: String,
    /// Local filesystem root, relative to the application working directory if needed.
    pub root: String,
    /// Hard per-object size bound for uploads and buffered test reads.
    pub max_object_bytes: u64,
    /// S3 bucket.
    pub bucket: Option<String>,
    /// S3 signing region.
    pub region: Option<String>,
    /// Optional S3-compatible endpoint override.
    pub endpoint: Option<String>,
    /// Use path-style addressing, commonly required by MinIO.
    pub path_style: bool,
    /// Optional explicit S3 access key; environment credentials are also supported.
    pub access_key_id: Option<String>,
    /// Optional explicit S3 secret; never printed by Debug.
    pub secret_access_key: Option<String>,
    /// Optional temporary credential token; never printed by Debug.
    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 {
    /// Reject obviously unsafe settings without a network connection.
    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(),
            )),
        }
    }
}