use crate::mime::MimeMatcher;
use crate::random::RandomURLConfig;
use crate::{AUTH_TOKENS_FILE_ENV, AUTH_TOKEN_ENV, DELETE_TOKENS_FILE_ENV, DELETE_TOKEN_ENV};
use byte_unit::Byte;
use config::{self, ConfigError};
use std::collections::HashSet;
use std::env;
use std::fs::read_to_string;
use std::path::{Path, PathBuf};
use std::time::Duration;
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct Config {
#[serde(rename = "config")]
pub settings: Option<Settings>,
pub server: ServerConfig,
pub paste: PasteConfig,
pub landing_page: Option<LandingPageConfig>,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct Settings {
#[serde(with = "humantime_serde")]
pub refresh_rate: Duration,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ServerConfig {
pub address: String,
pub url: Option<String>,
pub workers: Option<usize>,
pub max_content_length: Byte,
pub upload_path: PathBuf,
pub max_upload_dir_size: Option<Byte>,
#[serde(default, with = "humantime_serde")]
pub timeout: Option<Duration>,
#[deprecated(note = "use [server].auth_tokens instead")]
pub auth_token: Option<String>,
pub auth_tokens: Option<HashSet<String>>,
pub expose_version: Option<bool>,
#[deprecated(note = "use the [landing_page] table")]
pub landing_page: Option<String>,
#[deprecated(note = "use the [landing_page] table")]
pub landing_page_content_type: Option<String>,
pub handle_spaces: Option<SpaceHandlingConfig>,
pub expose_list: Option<bool>,
pub delete_tokens: Option<HashSet<String>>,
}
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SpaceHandlingConfig {
Encode,
Replace,
}
impl SpaceHandlingConfig {
pub fn process_filename(&self, file_name: &str) -> String {
match self {
Self::Encode => file_name.replace(' ', "%20"),
Self::Replace => file_name.replace(' ', "_"),
}
}
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct LandingPageConfig {
pub text: Option<String>,
pub file: Option<String>,
pub content_type: Option<String>,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct PasteConfig {
pub random_url: Option<RandomURLConfig>,
pub default_extension: String,
#[serde(default)]
pub mime_override: Vec<MimeMatcher>,
#[serde(default)]
pub mime_blacklist: Vec<String>,
pub duplicate_files: Option<bool>,
#[serde(default, with = "humantime_serde")]
pub default_expiry: Option<Duration>,
pub delete_expired_files: Option<CleanupConfig>,
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct CleanupConfig {
pub enabled: bool,
#[serde(default, with = "humantime_serde")]
pub interval: Duration,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum TokenType {
Auth,
Delete,
}
impl Config {
pub fn parse(path: &Path) -> Result<Config, ConfigError> {
config::Config::builder()
.add_source(config::File::from(path))
.add_source(config::Environment::default().separator("__"))
.build()?
.try_deserialize()
}
pub fn get_tokens(&self, token_type: TokenType) -> Option<HashSet<String>> {
let mut tokens = match token_type {
TokenType::Auth => {
let mut tokens: HashSet<_> = self.server.auth_tokens.clone().unwrap_or_default();
#[allow(deprecated)]
if let Some(token) = &self.server.auth_token {
tokens.insert(token.to_string());
}
if let Ok(env_token) = env::var(AUTH_TOKEN_ENV) {
tokens.insert(env_token);
}
if let Ok(env_path) = env::var(AUTH_TOKENS_FILE_ENV) {
match read_to_string(&env_path) {
Ok(s) => {
s.lines().filter(|l| !l.trim().is_empty()).for_each(|l| {
tokens.insert(l.to_string());
});
}
Err(e) => {
error!(
"failed to read tokens from authentication file ({env_path}) ({e})"
);
}
};
}
tokens
}
TokenType::Delete => {
let mut tokens: HashSet<_> = self.server.delete_tokens.clone().unwrap_or_default();
if let Ok(env_token) = env::var(DELETE_TOKEN_ENV) {
tokens.insert(env_token);
}
if let Ok(env_path) = env::var(DELETE_TOKENS_FILE_ENV) {
match read_to_string(&env_path) {
Ok(s) => {
s.lines().filter(|l| !l.trim().is_empty()).for_each(|l| {
tokens.insert(l.to_string());
});
}
Err(e) => {
error!("failed to read deletion tokens from file ({env_path}) ({e})");
}
};
}
tokens
}
};
tokens.retain(|v| !v.trim().is_empty());
Some(tokens).filter(|v| !v.is_empty())
}
#[allow(deprecated)]
pub fn warn_deprecation(&self) {
if self.server.auth_token.is_some() {
warn!("[server].auth_token is deprecated, please use [server].auth_tokens");
}
if self.server.landing_page.is_some() {
warn!("[server].landing_page is deprecated, please use [landing_page].text");
}
if self.server.landing_page_content_type.is_some() {
warn!(
"[server].landing_page_content_type is deprecated, please use [landing_page].content_type"
);
}
if let Some(random_url) = &self.paste.random_url {
if random_url.enabled.is_some() {
warn!(
"[paste].random_url.enabled is deprecated, disable it by commenting out [paste].random_url"
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
#[test]
fn test_parse_config() -> Result<(), ConfigError> {
let config_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.toml");
unsafe {
env::set_var("SERVER__ADDRESS", "0.0.1.1");
}
let config = Config::parse(&config_path)?;
assert_eq!("0.0.1.1", config.server.address);
Ok(())
}
#[test]
#[allow(deprecated)]
fn test_parse_deprecated_config() -> Result<(), ConfigError> {
let config_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.toml");
unsafe {
env::set_var("SERVER__ADDRESS", "0.0.1.1");
}
let mut config = Config::parse(&config_path)?;
config.paste.random_url = Some(RandomURLConfig {
enabled: Some(true),
..RandomURLConfig::default()
});
assert_eq!("0.0.1.1", config.server.address);
config.warn_deprecation();
Ok(())
}
#[test]
fn test_space_handling() {
let processed_filename =
SpaceHandlingConfig::Replace.process_filename("file with spaces.txt");
assert_eq!("file_with_spaces.txt", processed_filename);
let encoded_filename = SpaceHandlingConfig::Encode.process_filename("file with spaces.txt");
assert_eq!("file%20with%20spaces.txt", encoded_filename);
}
#[test]
fn test_get_tokens() -> Result<(), ConfigError> {
let config_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("config.toml");
unsafe {
env::set_var("AUTH_TOKEN", "env_auth");
env::set_var("DELETE_TOKEN", "env_delete");
}
let mut config = Config::parse(&config_path)?;
config.server.auth_tokens =
Some(["may_the_force_be_with_you".to_string(), "".to_string()].into());
config.server.delete_tokens = Some(["i_am_your_father".to_string(), "".to_string()].into());
assert_eq!(
Some(HashSet::from([
"env_auth".to_string(),
"may_the_force_be_with_you".to_string()
])),
config.get_tokens(TokenType::Auth)
);
assert_eq!(
Some(HashSet::from([
"env_delete".to_string(),
"i_am_your_father".to_string()
])),
config.get_tokens(TokenType::Delete)
);
unsafe {
env::remove_var("AUTH_TOKEN");
env::remove_var("DELETE_TOKEN");
}
config.server.auth_tokens = Some([" ".to_string()].into());
config.server.delete_tokens = Some(HashSet::new());
assert_eq!(None, config.get_tokens(TokenType::Auth));
assert_eq!(None, config.get_tokens(TokenType::Delete));
Ok(())
}
}