use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::Path;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum Environment {
#[default]
Development,
Production,
}
pub const ENVIRONMENT_VARIABLE: &str = "RUSTF_ENV";
impl Environment {
pub fn parse(env: &str) -> Result<Self> {
Self::parse_named(env).map_err(Error::internal)
}
fn parse_named(env: &str) -> std::result::Result<Self, String> {
match env.trim().to_ascii_lowercase().as_str() {
"production" | "prod" => Ok(Environment::Production),
"development" | "dev" => Ok(Environment::Development),
other => Err(format!(
"unknown environment '{}': use development (dev) or production (prod)",
other
)),
}
}
pub fn from_process_env() -> Result<Option<Self>> {
match env::var(ENVIRONMENT_VARIABLE) {
Ok(value) => Self::parse_named(&value)
.map(Some)
.map_err(|reason| Error::internal(format!("{}: {}", ENVIRONMENT_VARIABLE, reason))),
Err(env::VarError::NotPresent) => Ok(None),
Err(env::VarError::NotUnicode(_)) => Err(Error::internal(format!(
"{}: not valid UTF-8; use development (dev) or production (prod)",
ENVIRONMENT_VARIABLE
))),
}
}
pub fn from_process_env_or_production_on_error() -> Self {
match Self::from_process_env() {
Ok(Some(env)) => env,
Ok(None) => Environment::Development,
Err(e) => {
log::error!("{}; running as production", e);
Environment::Production
}
}
}
#[deprecated(note = "use Environment::parse, which rejects unknown names")]
pub fn from_str(env: &str) -> Self {
Self::parse(env).unwrap_or(Environment::Development)
}
pub fn name(&self) -> &'static str {
match self {
Environment::Development => "development",
Environment::Production => "production",
}
}
pub fn as_str(&self) -> &'static str {
match self {
Environment::Development => "dev",
Environment::Production => "prod",
}
}
pub fn is_production(&self) -> bool {
matches!(self, Environment::Production)
}
pub fn is_development(&self) -> bool {
matches!(self, Environment::Development)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AppConfig {
#[serde(default)]
pub environment: Environment,
#[serde(default)]
pub server: ServerConfig,
#[serde(default)]
pub views: ViewConfig,
#[serde(default)]
pub session: SessionConfig,
#[serde(default)]
pub static_files: StaticConfig,
#[serde(default)]
pub database: DatabaseConfig,
#[serde(default)]
pub cors: CorsConfig,
#[serde(default)]
pub logging: LoggingConfig,
#[serde(default)]
pub uploads: UploadConfig,
#[serde(default, rename = "private")]
pub r#private: PrivateConfig,
#[serde(default)]
pub websocket: WebSocketSettings,
#[serde(flatten)]
pub sections: HashMap<String, toml::Value>,
#[doc(hidden)]
#[serde(skip)]
pub resolved_values: ResolvedValues,
}
#[doc(hidden)]
#[derive(Clone, Default)]
pub struct ResolvedValues(Vec<String>);
impl std::fmt::Debug for ResolvedValues {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ResolvedValues({} masked)", self.0.len())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
#[serde(default = "default_host")]
pub host: String,
#[serde(default = "default_port")]
pub port: u16,
#[serde(default = "default_timeout")]
pub timeout: u64,
#[serde(default)]
pub ssl_enabled: bool,
#[serde(default)]
pub ssl_cert: Option<String>,
#[serde(default)]
pub ssl_key: Option<String>,
#[serde(default)]
pub public_url: Option<String>,
#[serde(default = "default_max_connections")]
pub max_connections: usize,
#[serde(default = "default_shutdown_timeout")]
pub shutdown_timeout: u64,
#[serde(default)]
pub trusted_proxies: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ViewConfig {
#[serde(default = "default_views_dir")]
pub directory: String,
#[serde(default = "default_layout")]
pub default_layout: String,
#[serde(default)]
pub cache_enabled: bool,
#[serde(default = "default_extension")]
pub extension: String,
#[serde(default)]
pub engine: TemplateEngine,
#[serde(default)]
pub storage: TemplateStorage,
#[serde(default = "default_root")]
pub default_root: String,
#[serde(default)]
pub minify: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum TemplateEngine {
#[default]
TotalJs,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum TemplateStorage {
Filesystem,
#[default]
Embedded,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionConfig {
#[serde(default = "default_session_enabled")]
pub enabled: bool,
#[serde(default = "default_cookie_name")]
pub cookie_name: String,
#[serde(default = "default_idle_timeout")]
pub idle_timeout: u64,
#[serde(default = "default_absolute_timeout")]
pub absolute_timeout: u64,
#[serde(default = "default_same_site")]
pub same_site: String,
#[serde(default = "default_fingerprint_mode")]
pub fingerprint_mode: String,
#[serde(default)]
pub storage: SessionStorageConfig,
#[serde(default)]
pub exempt_routes: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum SessionStorageConfig {
Memory {
#[serde(default = "default_cleanup_interval")]
cleanup_interval: u64,
},
Redis {
url: String,
#[serde(default = "default_redis_prefix")]
prefix: String,
#[serde(default = "default_redis_pool_size")]
pool_size: usize,
#[serde(default = "default_redis_connection_timeout")]
connection_timeout: u64,
#[serde(default = "default_redis_command_timeout")]
command_timeout: u64,
},
Database {
#[serde(default = "default_sessions_table")]
table: String,
connection_url: Option<String>,
#[serde(default = "default_cleanup_interval")]
cleanup_interval: u64,
},
}
impl Default for SessionStorageConfig {
fn default() -> Self {
Self::Memory {
cleanup_interval: default_cleanup_interval(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StaticConfig {
#[serde(default = "default_static_dir")]
pub directory: String,
#[serde(default = "default_static_prefix")]
pub url_prefix: String,
#[serde(default)]
pub cache_enabled: bool,
#[serde(default = "default_cache_max_age")]
pub cache_max_age: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DatabaseConfig {
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub max_connections: Option<u32>,
#[serde(default)]
pub timeout: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CorsConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub allowed_origins: Vec<String>,
#[serde(default)]
pub allowed_methods: Vec<String>,
#[serde(default)]
pub allowed_headers: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebSocketSettings {
#[serde(default = "default_ws_max_message_size")]
pub max_message_size: usize,
#[serde(default = "default_ws_max_frame_size")]
pub max_frame_size: usize,
#[serde(default = "default_ws_ping_interval")]
pub ping_interval: u64,
#[serde(default)]
pub allowed_origins: Vec<String>,
#[serde(default)]
pub accept_subprotocols: Vec<String>,
#[serde(default)]
pub require_origin: bool,
#[serde(default)]
pub max_connections: usize,
}
impl Default for WebSocketSettings {
fn default() -> Self {
Self {
max_message_size: default_ws_max_message_size(),
max_frame_size: default_ws_max_frame_size(),
ping_interval: default_ws_ping_interval(),
allowed_origins: Vec::new(),
accept_subprotocols: Vec::new(),
require_origin: false,
max_connections: 0,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
#[serde(default = "default_log_level")]
pub level: String,
#[serde(default)]
pub file: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UploadConfig {
#[serde(default = "default_upload_dir")]
pub directory: String,
#[serde(default = "default_max_file_size")]
pub max_file_size: u64,
#[serde(default = "default_max_files")]
pub max_files: usize,
#[serde(default)]
pub allowed_extensions: Vec<String>,
#[serde(default)]
pub blocked_extensions: Vec<String>,
#[serde(default)]
pub create_directories: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrivateConfig {
#[serde(default = "default_private_dir")]
pub directory: String,
}
fn default_host() -> String {
"127.0.0.1".to_string()
}
fn default_port() -> u16 {
8000
}
fn default_timeout() -> u64 {
30
}
fn default_shutdown_timeout() -> u64 {
30
}
fn default_ws_max_message_size() -> usize {
1024 * 1024
}
fn default_ws_max_frame_size() -> usize {
256 * 1024
}
fn default_ws_ping_interval() -> u64 {
30
}
fn default_max_connections() -> usize {
1000
}
fn default_views_dir() -> String {
"views".to_string()
}
fn default_layout() -> String {
"layouts/default".to_string()
}
fn default_extension() -> String {
"html".to_string()
}
fn default_root() -> String {
"".to_string()
}
fn default_session_enabled() -> bool {
true
}
fn default_idle_timeout() -> u64 {
900
} fn default_absolute_timeout() -> u64 {
28800
} fn default_same_site() -> String {
"Lax".to_string()
}
fn default_fingerprint_mode() -> String {
"soft".to_string()
}
fn default_cookie_name() -> String {
"rustf_session".to_string()
}
fn default_static_dir() -> String {
"public".to_string()
}
fn default_static_prefix() -> String {
"/static".to_string()
}
fn default_cache_max_age() -> u64 {
86400
}
fn default_log_level() -> String {
"info".to_string()
}
fn default_upload_dir() -> String {
"uploads".to_string()
}
fn default_private_dir() -> String {
"private".to_string()
}
fn default_max_file_size() -> u64 {
10 * 1024 * 1024
} fn default_max_files() -> usize {
5
}
fn default_cleanup_interval() -> u64 {
300
} fn default_redis_prefix() -> String {
"rustf:session:".to_string()
}
fn default_redis_pool_size() -> usize {
10
}
fn default_redis_connection_timeout() -> u64 {
5000
} fn default_redis_command_timeout() -> u64 {
3000
} fn default_sessions_table() -> String {
"sessions".to_string()
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
host: default_host(),
port: default_port(),
timeout: default_timeout(),
ssl_enabled: false,
ssl_cert: None,
ssl_key: None,
public_url: None,
max_connections: default_max_connections(),
shutdown_timeout: default_shutdown_timeout(),
trusted_proxies: Vec::new(),
}
}
}
impl Default for ViewConfig {
fn default() -> Self {
Self {
directory: default_views_dir(),
default_layout: default_layout(),
cache_enabled: false,
extension: default_extension(),
engine: TemplateEngine::default(),
storage: TemplateStorage::default(),
default_root: default_root(),
minify: false,
}
}
}
impl Default for SessionConfig {
fn default() -> Self {
Self {
enabled: default_session_enabled(),
cookie_name: default_cookie_name(),
idle_timeout: default_idle_timeout(),
absolute_timeout: default_absolute_timeout(),
same_site: default_same_site(),
fingerprint_mode: default_fingerprint_mode(),
storage: SessionStorageConfig::default(),
exempt_routes: Vec::new(),
}
}
}
impl Default for StaticConfig {
fn default() -> Self {
Self {
directory: default_static_dir(),
url_prefix: default_static_prefix(),
cache_enabled: true,
cache_max_age: default_cache_max_age(),
}
}
}
impl Default for CorsConfig {
fn default() -> Self {
Self {
enabled: false,
allowed_origins: vec!["*".to_string()],
allowed_methods: vec!["GET".to_string(), "POST".to_string()],
allowed_headers: vec!["Content-Type".to_string()],
}
}
}
impl Default for LoggingConfig {
fn default() -> Self {
Self {
level: default_log_level(),
file: None,
}
}
}
impl Default for UploadConfig {
fn default() -> Self {
Self {
directory: default_upload_dir(),
max_file_size: default_max_file_size(),
max_files: default_max_files(),
allowed_extensions: vec![],
blocked_extensions: vec![
"exe".to_string(),
"bat".to_string(),
"sh".to_string(),
"cmd".to_string(),
],
create_directories: true,
}
}
}
impl Default for PrivateConfig {
fn default() -> Self {
Self {
directory: default_private_dir(),
}
}
}
impl AppConfig {
pub fn load() -> Result<Self> {
Self::load_with_base_dir(".")
}
pub fn load_with_dev_detection() -> Result<Self> {
let base_dir: std::path::PathBuf = if cfg!(debug_assertions) {
if Path::new("target/debug").exists() && Path::new("../../config.toml").exists() {
std::path::PathBuf::from("../..")
} else {
std::path::PathBuf::from(".")
}
} else {
std::env::current_exe()
.ok()
.and_then(|p| p.canonicalize().ok())
.and_then(|p| p.parent().map(|p| p.to_path_buf()))
.unwrap_or_else(|| std::path::PathBuf::from("."))
};
Self::load_with_base_dir(base_dir)
}
pub fn load_with_base_dir<P: AsRef<Path>>(base_dir: P) -> Result<Self> {
let base_dir = base_dir.as_ref();
let base_config_path = base_dir.join("config.toml");
let mut secrets = Vec::new();
let mut merged_value = if base_config_path.exists() {
Self::load_resolved_toml_value(&base_config_path, base_dir, None, &mut secrets)?
} else if !cfg!(debug_assertions) {
return Err(Error::internal(format!(
"Configuration file not found: '{}'. \
Launch the binary from the directory containing config.toml, \
or use --config <path> to specify its location.",
base_config_path.display()
)));
} else {
let default_config = AppConfig::default();
toml::to_string(&default_config)
.ok()
.and_then(|s| toml::from_str(&s).ok())
.unwrap_or(toml::Value::Table(toml::map::Map::new()))
};
let env = Self::resolve_environment(&merged_value)?;
let env_config_path = base_dir.join(format!("config.{}.toml", env.as_str()));
if env_config_path.exists() {
let env_value = Self::load_resolved_toml_value(
&env_config_path,
base_dir,
Some(&merged_value),
&mut secrets,
)?;
merged_value = Self::merge_overlay(merged_value, env_value, &secrets)?;
}
let config = Self::finish_loading(merged_value, env, base_dir, &secrets)?;
log::info!(
"Configuration loaded and merged successfully (environment: {})",
config.environment.as_str()
);
Ok(config)
}
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let path_ref = path.as_ref();
let base_dir = path_ref
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| std::path::PathBuf::from("."));
let mut secrets = Vec::new();
let mut merged_value =
Self::load_resolved_toml_value(path_ref, &base_dir, None, &mut secrets)?;
let env = Self::resolve_environment(&merged_value)?;
let env_config_path = base_dir.join(format!("config.{}.toml", env.as_str()));
if env_config_path.exists() {
let env_value = Self::load_resolved_toml_value(
&env_config_path,
&base_dir,
Some(&merged_value),
&mut secrets,
)?;
merged_value = Self::merge_overlay(merged_value, env_value, &secrets)?;
}
let config = Self::finish_loading(merged_value, env, &base_dir, &secrets)?;
log::info!(
"Configuration loaded from '{}' (environment: {})",
path_ref.display(),
config.environment.as_str()
);
Ok(config)
}
fn load_resolved_toml_value(
path: &Path,
base_dir: &Path,
base: Option<&toml::Value>,
secrets: &mut Vec<String>,
) -> Result<toml::Value> {
let mut value = Self::load_toml_value(path)?;
let framework = Self::reference_template()?;
let template = match base {
Some(base) => {
serde_toml_merge::merge(framework.clone(), base.clone()).unwrap_or(framework)
}
None => framework,
};
let resolved = crate::config_refs::resolve(&mut value, &template, base_dir)
.map_err(|reason| Error::internal(format!("{}: {}", path.display(), reason)))?;
secrets.extend(resolved);
Ok(value)
}
fn reference_template() -> Result<toml::Value> {
let mut template = toml::Value::try_from(AppConfig::default()).map_err(|e| {
Error::internal(format!("Failed to build the configuration template: {}", e))
})?;
let hints: toml::Value = toml::from_str(
r#"
[database]
max_connections = 0
timeout = 0
[session.storage]
pool_size = 0
connection_timeout = 0
command_timeout = 0
cleanup_interval = 0
"#,
)
.map_err(|e| Error::internal(format!("Invalid configuration type hints: {}", e)))?;
template = serde_toml_merge::merge(template, hints)
.map_err(|e| Error::internal(format!("Invalid configuration type hints: {}", e)))?;
Ok(template)
}
fn merge_overlay(
base: toml::Value,
overlay: toml::Value,
secrets: &[String],
) -> Result<toml::Value> {
serde_toml_merge::merge(base, overlay).map_err(|e| {
Error::internal(crate::config_refs::mask(
&format!("Failed to merge configuration files: {}", e),
secrets,
))
})
}
fn finish_loading(
merged_value: toml::Value,
env: Environment,
base_dir: &Path,
secrets: &[String],
) -> Result<Self> {
let load = || -> Result<Self> {
let json_value = serde_json::to_value(&merged_value).map_err(|e| {
Error::internal(format!("Failed to convert merged configuration: {}", e))
})?;
let mut config: AppConfig = serde_json::from_value(json_value).map_err(|e| {
Error::internal(format!("Failed to deserialize merged configuration: {}", e))
})?;
config.environment = env;
config.apply_env_overrides()?;
config.resolve_relative_paths(base_dir)?;
if config.environment.is_production() {
config.apply_security_defaults();
config.apply_performance_defaults();
}
config.validate()?;
config.resolved_values = ResolvedValues(secrets.to_vec());
Ok(config)
};
load().map_err(|e| {
if secrets.is_empty() {
e
} else {
let message = match &e {
Error::Internal(message) => message.clone(),
other => other.to_string(),
};
Error::internal(crate::config_refs::mask(&message, secrets))
}
})
}
pub fn check_references<P: AsRef<Path>>(path: P) -> Result<()> {
let path = path.as_ref();
let value = Self::load_toml_value(path)?;
crate::config_refs::check(&value)
.map_err(|reason| Error::internal(format!("{}: {}", path.display(), reason)))
}
fn load_toml_value<P: AsRef<Path>>(path: P) -> Result<toml::Value> {
let path_ref = path.as_ref();
let content = fs::read_to_string(path_ref).map_err(|e| {
Error::internal(format!(
"Failed to read config file '{}': {}. Make sure the file exists and is readable.",
path_ref.display(),
e
))
})?;
let value: toml::Value = toml::from_str(&content).map_err(|e| {
Error::internal(format!(
"Failed to parse config file '{}': {}. Check TOML syntax.",
path_ref.display(),
e
))
})?;
log::debug!(
"Successfully loaded TOML value from: {}",
path_ref.display()
);
Ok(value)
}
pub fn from_env() -> Result<Self> {
let mut config = AppConfig::default();
config.apply_env_overrides()?;
Ok(config)
}
pub fn detect_environment() -> Result<Environment> {
Ok(Environment::from_process_env()?.unwrap_or_default())
}
fn resolve_environment(base_toml: &toml::Value) -> Result<Environment> {
if let Some(env) = Environment::from_process_env()? {
return Ok(env);
}
if let Some(declared) = base_toml.get("app").and_then(|app| app.get("environment")) {
return match declared {
toml::Value::String(name) => Environment::parse_named(name)
.map_err(|reason| Error::internal(format!("[app] environment: {}", reason))),
_ => Err(Error::internal(
"[app] environment must be a string: \"development\" or \"production\"",
)),
};
}
Ok(Environment::Development)
}
pub fn apply_security_defaults(&mut self) {
if !self.cors.enabled {
self.cors.allowed_origins = vec![];
}
if self.environment.is_production() && !self.server.ssl_enabled {
eprintln!("WARNING: SSL is not enabled in production environment");
}
}
pub fn apply_performance_defaults(&mut self) {
self.views.cache_enabled = true;
self.views.minify = true;
self.static_files.cache_enabled = true;
if self.server.max_connections == default_max_connections() {
self.server.max_connections = 2000; }
if self.server.timeout == default_timeout() {
self.server.timeout = 60; }
}
pub fn validate(&self) -> Result<()> {
self.validate_template_engine()?;
if self.server.port == 0 {
return Err(Error::internal("Server port cannot be 0"));
}
if self.server.ssl_enabled {
if self.server.ssl_cert.is_none() {
return Err(Error::internal(
"SSL certificate path required when SSL is enabled",
));
}
if self.server.ssl_key.is_none() {
return Err(Error::internal(
"SSL private key path required when SSL is enabled",
));
}
}
if self.environment.is_production() && self.database.url.is_none() {
eprintln!("WARNING: No database configured in production environment");
}
if matches!(self.views.storage, TemplateStorage::Filesystem)
&& !Path::new(&self.views.directory).exists()
{
log::warn!(
"Views directory does not exist: {} (can be overridden with --views flag)",
self.views.directory
);
}
if !Path::new(&self.static_files.directory).exists() {
return Err(Error::internal(format!(
"Static files directory does not exist: {}",
self.static_files.directory
)));
}
Ok(())
}
fn apply_env_overrides(&mut self) -> Result<()> {
if let Some(env) = Environment::from_process_env()? {
self.environment = env;
}
if let Ok(host) = env::var("RUSTF_HOST") {
self.server.host = host;
}
if let Ok(port) = env::var("RUSTF_PORT") {
self.server.port = port
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_PORT value"))?;
}
if let Ok(timeout) = env::var("RUSTF_TIMEOUT") {
self.server.timeout = timeout
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_TIMEOUT value"))?;
}
if let Ok(ssl) = env::var("RUSTF_SSL_ENABLED") {
self.server.ssl_enabled = ssl
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_SSL_ENABLED value"))?;
}
if let Ok(ssl_cert) = env::var("RUSTF_SSL_CERT") {
self.server.ssl_cert = Some(ssl_cert);
}
if let Ok(ssl_key) = env::var("RUSTF_SSL_KEY") {
self.server.ssl_key = Some(ssl_key);
}
if let Ok(max_conn) = env::var("RUSTF_MAX_CONNECTIONS") {
self.server.max_connections = max_conn
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_MAX_CONNECTIONS value"))?;
}
if let Ok(views_dir) = env::var("RUSTF_VIEWS_DIR") {
self.views.directory = views_dir;
}
if let Ok(layout) = env::var("RUSTF_DEFAULT_LAYOUT") {
self.views.default_layout = layout;
}
if let Ok(cache) = env::var("RUSTF_VIEW_CACHE") {
self.views.cache_enabled = cache
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_VIEW_CACHE value"))?;
}
if let Ok(minify) = env::var("RUSTF_VIEW_MINIFY") {
self.views.minify = minify
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_VIEW_MINIFY value"))?;
}
if let Ok(storage) = env::var("RUSTF_TEMPLATE_STORAGE") {
self.views.storage = match storage.to_lowercase().as_str() {
"filesystem" => TemplateStorage::Filesystem,
"embedded" => TemplateStorage::Embedded,
_ => {
return Err(Error::internal(
"Invalid RUSTF_TEMPLATE_STORAGE value. Use 'filesystem' or 'embedded'.",
))
}
};
}
if let Ok(engine) = env::var("RUSTF_VIEW_ENGINE") {
self.views.storage =
match engine.to_lowercase().as_str() {
"filesystem" | "totaljs" | "tera" | "auto" => TemplateStorage::Filesystem,
"embedded" => TemplateStorage::Embedded,
_ => return Err(Error::internal(
"Invalid RUSTF_VIEW_ENGINE value (DEPRECATED - use RUSTF_TEMPLATE_STORAGE)",
)),
};
log::warn!("RUSTF_VIEW_ENGINE is deprecated. Use RUSTF_TEMPLATE_STORAGE instead.");
}
if let Ok(db_url) = env::var("DATABASE_URL") {
self.database.url = Some(db_url);
}
if let Ok(db_url) = env::var("RUSTF_DATABASE_URL") {
self.database.url = Some(db_url);
}
if let Ok(max_conn) = env::var("RUSTF_DB_MAX_CONNECTIONS") {
self.database.max_connections = Some(
max_conn
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_DB_MAX_CONNECTIONS value"))?,
);
}
if let Ok(timeout) = env::var("RUSTF_DB_TIMEOUT") {
self.database.timeout = Some(
timeout
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_DB_TIMEOUT value"))?,
);
}
if let Ok(static_dir) = env::var("RUSTF_STATIC_DIR") {
self.static_files.directory = static_dir;
}
if let Ok(url_prefix) = env::var("RUSTF_STATIC_PREFIX") {
self.static_files.url_prefix = url_prefix;
}
if let Ok(cache) = env::var("RUSTF_STATIC_CACHE") {
self.static_files.cache_enabled = cache
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_STATIC_CACHE value"))?;
}
if let Ok(max_age) = env::var("RUSTF_STATIC_MAX_AGE") {
self.static_files.cache_max_age = max_age
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_STATIC_MAX_AGE value"))?;
}
if let Ok(cors) = env::var("RUSTF_CORS_ENABLED") {
self.cors.enabled = cors
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_CORS_ENABLED value"))?;
}
if let Ok(origins) = env::var("RUSTF_CORS_ORIGINS") {
self.cors.allowed_origins = origins.split(',').map(|s| s.trim().to_string()).collect();
}
if let Ok(methods) = env::var("RUSTF_CORS_METHODS") {
self.cors.allowed_methods = methods
.split(',')
.map(|s| s.trim().to_uppercase())
.collect();
}
if let Ok(headers) = env::var("RUSTF_CORS_HEADERS") {
self.cors.allowed_headers = headers.split(',').map(|s| s.trim().to_string()).collect();
}
if let Ok(level) = env::var("RUSTF_LOG_LEVEL") {
self.logging.level = level;
}
if let Ok(log_file) = env::var("RUSTF_LOG_FILE") {
self.logging.file = Some(log_file);
}
if let Ok(trusted_proxies) = env::var("RUSTF_TRUSTED_PROXIES") {
self.server.trusted_proxies = trusted_proxies
.split(',')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.collect();
}
if let Ok(public_url) = env::var("RUSTF_PUBLIC_URL") {
self.server.public_url = Some(public_url);
}
if let Ok(upload_dir) = env::var("RUSTF_UPLOAD_DIR") {
self.uploads.directory = upload_dir;
}
if let Ok(private_dir) = env::var("RUSTF_PRIVATE_DIR") {
self.r#private.directory = private_dir;
}
if let Ok(max_size) = env::var("RUSTF_MAX_FILE_SIZE") {
self.uploads.max_file_size = max_size
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_MAX_FILE_SIZE value"))?;
}
if let Ok(max_files) = env::var("RUSTF_MAX_FILES") {
self.uploads.max_files = max_files
.parse()
.map_err(|_| Error::internal("Invalid RUSTF_MAX_FILES value"))?;
}
Ok(())
}
fn validate_template_engine(&self) -> Result<()> {
match self.views.storage {
TemplateStorage::Embedded => {
#[cfg(not(feature = "embedded-views"))]
{
return Err(Error::internal(
"Embedded template storage selected but 'embedded-views' feature not enabled. Enable the feature or change storage to 'filesystem'."
));
}
}
TemplateStorage::Filesystem => {
}
}
Ok(())
}
fn resolve_relative_paths<P: AsRef<Path>>(&mut self, base_dir: P) -> Result<()> {
let base = base_dir.as_ref();
if matches!(self.views.storage, TemplateStorage::Filesystem) {
self.views.directory = Self::resolve_dir(&self.views.directory, base);
}
self.static_files.directory = Self::resolve_dir(&self.static_files.directory, base);
self.r#private.directory = Self::resolve_dir(&self.r#private.directory, base);
let private_root = Path::new(&self.r#private.directory);
self.uploads.directory = Self::resolve_dir(&self.uploads.directory, private_root);
Ok(())
}
fn resolve_dir(dir: &str, base: &Path) -> String {
let p = Path::new(dir);
if p.is_absolute() {
return dir.to_string();
}
let joined = base.join(p);
if joined.exists() {
joined
.canonicalize()
.unwrap_or(joined)
.to_string_lossy()
.into_owned()
} else {
joined.to_string_lossy().into_owned()
}
}
pub fn server_address(&self) -> String {
format!("{}:{}", self.server.host, self.server.port)
}
pub fn is_debug(&self) -> bool {
cfg!(debug_assertions) || env::var("RUSTF_DEBUG").is_ok()
}
pub fn section<T: serde::de::DeserializeOwned>(&self, name: &str) -> Result<T> {
self.sections
.get(name)
.ok_or_else(|| {
Error::internal(format!(
"Configuration section '{}' not found. Check your config.toml.",
name
))
})
.and_then(|value| {
let json = serde_json::to_value(value).map_err(|e| {
Error::internal(format!(
"Failed to serialize section '{}' to JSON: {}",
name, e
))
})?;
crate::config_lenient::from_value(&json).map_err(|e| {
Error::internal(crate::config_refs::mask(
&format!("Failed to deserialize section '{}': {}", name, e),
&self.resolved_values.0,
))
})
})
}
pub fn get_value(&self, section_name: &str) -> Option<&toml::Value> {
self.sections.get(section_name)
}
pub fn has_section(&self, name: &str) -> bool {
self.sections.contains_key(name)
}
}
use toml;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_toml_level_merging_simple() {
use serde_toml_merge::merge;
let base_toml = r#"
[server]
port = 8000
host = "127.0.0.1"
"#;
let dev_toml = r#"
[server]
port = 3000
"#;
let base_value: toml::Value = toml::from_str(base_toml).unwrap();
let dev_value: toml::Value = toml::from_str(dev_toml).unwrap();
let merged = merge(base_value, dev_value).unwrap();
assert_eq!(merged["server"]["port"].as_integer().unwrap(), 3000);
assert_eq!(merged["server"]["host"].as_str().unwrap(), "127.0.0.1");
}
#[test]
fn test_toml_level_merging_nested_tables() {
use serde_toml_merge::merge;
let base_toml = r#"
[session.storage]
type = "memory"
cleanup_interval = 300
[session]
enabled = true
cookie_name = "base_session"
"#;
let dev_toml = r#"
[session.storage]
type = "redis"
url = "redis://localhost:6379"
"#;
let base_value: toml::Value = toml::from_str(base_toml).unwrap();
let dev_value: toml::Value = toml::from_str(dev_toml).unwrap();
let merged = merge(base_value, dev_value).unwrap();
assert_eq!(
merged["session"]["storage"]["type"].as_str().unwrap(),
"redis"
);
assert_eq!(
merged["session"]["storage"]["url"].as_str().unwrap(),
"redis://localhost:6379"
);
assert_eq!(merged["session"]["enabled"].as_bool().unwrap(), true);
}
#[test]
fn test_toml_level_merging_custom_sections() {
use serde_toml_merge::merge;
let base_toml = r#"
[custom.email]
smtp_host = "smtp.example.com"
smtp_port = 587
[custom.app]
name = "MyApp"
"#;
let dev_toml = r#"
[custom.email]
smtp_port = 2525
[custom.logging]
debug = true
"#;
let base_value: toml::Value = toml::from_str(base_toml).unwrap();
let dev_value: toml::Value = toml::from_str(dev_toml).unwrap();
let merged = merge(base_value, dev_value).unwrap();
assert_eq!(
merged["custom"]["email"]["smtp_port"].as_integer().unwrap(),
2525
);
assert_eq!(
merged["custom"]["email"]["smtp_host"].as_str().unwrap(),
"smtp.example.com"
);
assert_eq!(merged["custom"]["app"]["name"].as_str().unwrap(), "MyApp");
assert_eq!(
merged["custom"]["logging"]["debug"].as_bool().unwrap(),
true
);
}
#[test]
fn test_custom_section_access() {
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct AppSettings {
name: String,
version: String,
debug: bool,
}
let mut config = AppConfig::default();
let app_value = toml::Value::Table(toml::map::Map::from_iter(vec![
(
"name".to_string(),
toml::Value::String("TestApp".to_string()),
),
(
"version".to_string(),
toml::Value::String("1.0.0".to_string()),
),
("debug".to_string(), toml::Value::Boolean(true)),
]));
config.sections.insert("app".to_string(), app_value);
assert!(config.has_section("app"));
assert!(!config.has_section("nonexistent"));
assert!(config.get_value("app").is_some());
assert!(config.get_value("nonexistent").is_none());
let app_settings: AppSettings = config.section("app").unwrap();
assert_eq!(app_settings.name, "TestApp");
assert_eq!(app_settings.version, "1.0.0");
assert_eq!(app_settings.debug, true);
}
#[test]
fn test_custom_section_error_handling() {
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct PaymentConfig {
#[allow(dead_code)]
stripe_key: String,
}
let config = AppConfig::default();
let result: Result<PaymentConfig> = config.section("payment");
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("not found"));
}
#[test]
fn test_custom_sections_with_toml_loading() {
let config_toml = r#"
[server]
port = 8000
[app]
name = "TestApp"
version = "2.0.0"
[payment]
stripe_key = "sk_test_123"
enabled = true
"#;
let config: AppConfig = toml::from_str(config_toml).unwrap();
assert_eq!(config.server.port, 8000);
assert!(config.has_section("app"));
assert!(config.has_section("payment"));
assert!(!config.has_section("nonexistent"));
assert!(config.get_value("app").is_some());
assert!(config.get_value("payment").is_some());
let app_name = config
.get_value("app")
.and_then(|v| v.get("name"))
.and_then(|v| v.as_str());
assert_eq!(app_name, Some("TestApp"));
let stripe_key = config
.get_value("payment")
.and_then(|v| v.get("stripe_key"))
.and_then(|v| v.as_str());
assert_eq!(stripe_key, Some("sk_test_123"));
}
#[test]
fn test_resolve_environment_from_config_toml() {
let toml_str = r#"[app]
environment = "production"
"#;
let toml_value: toml::Value = toml::from_str(toml_str).unwrap();
let env = AppConfig::resolve_environment(&toml_value).unwrap();
assert_eq!(env, Environment::Production);
}
#[test]
fn test_resolve_environment_rejects_unknown_names() {
let staging: toml::Value = toml::from_str("[app]\nenvironment = \"staging\"\n").unwrap();
let error = AppConfig::resolve_environment(&staging)
.unwrap_err()
.to_string();
assert!(error.contains("[app] environment"), "{error}");
assert!(error.contains("staging"), "{error}");
let not_a_string: toml::Value = toml::from_str("[app]\nenvironment = 1\n").unwrap();
assert!(AppConfig::resolve_environment(¬_a_string).is_err());
}
#[test]
fn test_environment_parse_is_strict() {
assert_eq!(Environment::parse("prod").unwrap(), Environment::Production);
assert_eq!(
Environment::parse(" Production ").unwrap(),
Environment::Production
);
assert_eq!(Environment::parse("DEV").unwrap(), Environment::Development);
assert!(Environment::parse("staging").is_err());
assert!(Environment::parse("prodution").is_err());
assert!(Environment::parse("").is_err());
}
#[test]
fn test_resolve_environment_default() {
let toml_value = toml::Value::Table(toml::map::Map::new());
let env = AppConfig::resolve_environment(&toml_value).unwrap();
assert_eq!(env, Environment::Development);
}
#[test]
fn test_private_and_upload_defaults() {
let config = AppConfig::default();
assert_eq!(config.r#private.directory, "private");
assert_eq!(config.uploads.directory, "uploads");
assert!(config.server.trusted_proxies.is_empty());
}
#[test]
fn test_trusted_proxies_toml_loading() {
let config_toml = r#"
[server]
trusted_proxies = ["127.0.0.1/32", "10.0.0.0/8"]
"#;
let config: AppConfig = toml::from_str(config_toml).unwrap();
assert_eq!(
config.server.trusted_proxies,
vec!["127.0.0.1/32".to_string(), "10.0.0.0/8".to_string()]
);
}
#[test]
fn test_upload_directory_resolves_under_private_root() {
let base_dir = std::env::temp_dir().join(format!(
"rustf-config-private-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&base_dir).unwrap();
let mut config = AppConfig::default();
config.resolve_relative_paths(&base_dir).unwrap();
let expected_private = base_dir.join("private");
let expected_uploads = expected_private.join("uploads");
assert_eq!(
std::path::Path::new(&config.r#private.directory),
expected_private
);
assert_eq!(
std::path::Path::new(&config.uploads.directory),
expected_uploads
);
std::fs::remove_dir_all(&base_dir).unwrap();
}
#[test]
fn test_absolute_upload_directory_stays_absolute() {
let base_dir = std::env::temp_dir().join(format!(
"rustf-config-absolute-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let absolute_uploads = std::env::temp_dir().join(format!(
"rustf-absolute-uploads-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&base_dir).unwrap();
let mut config = AppConfig::default();
config.uploads.directory = absolute_uploads.to_string_lossy().into_owned();
config.resolve_relative_paths(&base_dir).unwrap();
assert_eq!(
std::path::Path::new(&config.uploads.directory),
absolute_uploads
);
std::fs::remove_dir_all(&base_dir).unwrap();
}
}