Files
rezervovator/src/config.rs
T

373 lines
11 KiB
Rust
Raw Normal View History

2023-11-16 21:13:33 +01:00
#[cfg(feature = "ssr")]
use std::fs::read_to_string;
#[cfg(feature = "ssr")]
use std::net::SocketAddr;
#[cfg(feature = "ssr")]
use std::path::{Path, PathBuf};
#[cfg(feature = "ssr")]
2023-11-16 21:13:33 +01:00
use std::str::FromStr;
#[cfg(feature = "ssr")]
use serde::Deserialize;
#[cfg(feature = "ssr")]
#[derive(Deserialize)]
pub struct Network {
bind_ip: String,
port: u16
}
2023-12-26 19:50:29 +01:00
#[cfg(feature = "ssr")]
#[derive(Deserialize)]
pub struct Session {
key: String
}
#[cfg(feature = "ssr")]
impl Session {
pub fn key(&self) -> &[u8] {
self.key.as_bytes()
}
}
2023-11-16 21:13:33 +01:00
#[cfg(feature = "ssr")]
impl Network {
pub fn bind_address(&self) -> SocketAddr {
SocketAddr::from_str(format!("{}:{}", &self.bind_ip, self.port).as_str()).expect("Can't parse bind IP address")
}
}
#[cfg(feature = "ssr")]
#[derive(Deserialize)]
pub struct Database {
user: String,
password: String,
db_name: String,
host: String,
port: Option<u16>
}
#[cfg(feature = "ssr")]
impl Database {
pub fn con_string(&self) -> String {
format!("postgres://{}:{}@{}:{}/{}", self.user, self.password, self.host, self.port.unwrap_or(5432), self.db_name)
}
}
2024-02-12 17:17:26 +01:00
#[cfg(feature = "ssr")]
#[derive(Deserialize, Clone)]
pub enum MailTransport {
Smtp,
File
}
#[cfg(feature = "ssr")]
#[derive(Deserialize, Clone)]
pub struct Mailing {
transport: MailTransport,
from: String,
path: Option<String>,
server: Option<String>,
2024-02-16 13:04:27 +01:00
hello_name: Option<String>,
2024-02-16 11:22:34 +01:00
port: Option<u16>,
2024-02-12 17:17:26 +01:00
user: Option<String>,
password: Option<String>,
tls: Option<bool>,
accept_all_certs: Option<bool>
2024-02-12 17:17:26 +01:00
}
#[cfg(feature = "ssr")]
impl Mailing {
pub fn transport(&self) -> &MailTransport {
&self.transport
}
pub fn from(&self) -> &str {
&self.from
}
pub fn path(&self) -> &Option<String> {
&self.path
}
pub fn server(&self) -> &Option<String> {
&self.server
}
2024-02-16 13:04:27 +01:00
pub fn hello_name(&self) -> &Option<String> {
&self.hello_name
}
2024-02-16 11:22:34 +01:00
pub fn port(&self) -> Option<u16> {
self.port
}
2024-02-12 17:17:26 +01:00
pub fn user(&self) -> &Option<String> {
&self.user
}
pub fn password(&self) -> &Option<String> {
&self.password
}
pub fn tls(&self) -> Option<bool> {
self.tls
}
pub fn accept_all_certs(&self) -> Option<bool> {
self.accept_all_certs
}
2024-02-12 17:17:26 +01:00
}
2024-02-23 14:00:31 +01:00
#[cfg(feature = "ssr")]
#[derive(Deserialize)]
pub struct Logging {
severity: String
}
#[cfg(feature = "ssr")]
impl Logging {
pub fn severity(&self) -> &str {
&self.severity
}
}
2024-02-12 17:17:26 +01:00
/// Where files created at runtime (uploaded banner, generated CSS) are kept
#[cfg(feature = "ssr")]
#[derive(Deserialize, Default)]
pub struct Storage {
data_dir: Option<String>
}
#[cfg(feature = "ssr")]
impl Storage {
/// Directory served under `/data`. Defaults to `data` in the working directory.
pub fn data_dir(&self) -> PathBuf {
PathBuf::from(self.data_dir.as_deref().unwrap_or("data"))
}
}
/// Environment variable with the password of the first admin account. Takes precedence over the config file.
#[cfg(feature = "ssr")]
pub const ADMIN_PASSWORD_ENV: &str = "REZERVATOR_ADMIN_PASSWORD";
#[cfg(feature = "ssr")]
pub const ADMIN_PASSWORD_MIN_LEN: usize = 8;
/// Setup of the first admin account
#[cfg(feature = "ssr")]
#[derive(Deserialize, Default)]
pub struct Admin {
initial_password: Option<String>
}
#[cfg(feature = "ssr")]
impl Admin {
/// Password for the admin account created on first start: the environment variable, or the
/// `initial_password` config key. There is no default, a known password must never be used.
pub fn initial_password(&self) -> Result<String, String> {
resolve_initial_password(std::env::var(ADMIN_PASSWORD_ENV).ok(), self.initial_password.clone())
}
}
#[cfg(feature = "ssr")]
fn resolve_initial_password(env: Option<String>, config: Option<String>) -> Result<String, String> {
let password = env.filter(|p| !p.is_empty()).or(config.filter(|p| !p.is_empty()))
.ok_or(format!(
"No admin account exists and no initial password is set. Set the {} environment variable or initial_password in the [admin] section of the config.",
ADMIN_PASSWORD_ENV))?;
if password.chars().count() < ADMIN_PASSWORD_MIN_LEN {
return Err(format!("Initial admin password must have at least {} characters.", ADMIN_PASSWORD_MIN_LEN))
}
Ok(password)
}
2023-11-16 21:13:33 +01:00
#[cfg(feature = "ssr")]
#[derive(Deserialize)]
pub struct Configuration {
2023-12-26 19:50:29 +01:00
session: Session,
2023-11-16 21:13:33 +01:00
network: Network,
2024-02-12 17:17:26 +01:00
database: Database,
2024-02-23 14:00:31 +01:00
mailing: Mailing,
logging: Logging,
#[serde(default)]
storage: Storage,
#[serde(default)]
admin: Admin
2023-11-16 21:13:33 +01:00
}
#[cfg(feature = "ssr")]
impl Configuration {
2023-12-26 19:50:29 +01:00
pub fn session(&self) -> &Session {
&self.session
}
2023-11-16 21:13:33 +01:00
pub fn network(&self) -> &Network {
&self.network
}
pub fn database(&self) -> &Database {
&self.database
}
2024-02-12 17:17:26 +01:00
pub fn mailing(&self) -> &Mailing {
&self.mailing
}
2024-02-23 14:00:31 +01:00
pub fn logging(&self) -> &Logging {
&self.logging
}
pub fn storage(&self) -> &Storage {
&self.storage
}
pub fn admin(&self) -> &Admin {
&self.admin
}
2023-11-16 21:13:33 +01:00
}
/// The config file holds passwords and the session key, so it must never lie in a directory
/// that is served as static files. Returns true when `config_path` is inside `public_dir`.
#[cfg(feature = "ssr")]
pub fn is_publicly_served(config_path: &Path, public_dir: &Path) -> bool {
match (config_path.canonicalize(), public_dir.canonicalize()) {
(Ok(config), Ok(root)) => config.starts_with(root),
_ => false
}
}
2023-11-16 21:13:33 +01:00
#[cfg(feature = "ssr")]
pub fn load_config(path: &str) -> Configuration {
toml::from_str(read_to_string(path).expect("Can not open config file").as_str()).expect("Can not parse config file")
}
2026-10-10 17:01:51 +02:00
#[cfg(all(test, feature = "ssr"))]
mod tests {
use super::*;
fn sample() -> Configuration {
load_config(concat!(env!("CARGO_MANIFEST_DIR"), "/config_sample.toml"))
}
#[test]
fn sample_config_is_valid() {
let config = sample();
assert_eq!(config.network().bind_address(), SocketAddr::from_str("127.0.0.1:3000").unwrap());
assert_eq!(config.database().con_string(), "postgres://user:password@localhost:5432/rezervator");
assert_eq!(config.logging().severity(), "debug");
assert!(matches!(config.mailing().transport(), MailTransport::File));
assert_eq!(config.mailing().from(), "[email protected]");
assert_eq!(config.mailing().path(), &Some("Maildir".to_string()));
assert_eq!(config.mailing().server(), &None);
}
/// Creates `<temp>/<name>/site/data` and returns the `<temp>/<name>` directory
fn site_dir(name: &str) -> std::path::PathBuf {
let base = std::env::temp_dir().join(format!("rezervator-test-{}-{}", name, std::process::id()));
std::fs::create_dir_all(base.join("site/data")).unwrap();
base
}
#[test]
fn config_inside_site_root_is_publicly_served() {
let base = site_dir("inside");
let config = base.join("site/data/config.toml");
std::fs::write(&config, "").unwrap();
assert!(is_publicly_served(&config, &base.join("site")));
// Relative segments must not hide it
assert!(is_publicly_served(&base.join("site/data/../data/config.toml"), &base.join("site")));
std::fs::remove_dir_all(base).unwrap();
}
#[test]
fn config_outside_site_root_is_not_publicly_served() {
let base = site_dir("outside");
let config = base.join("config.toml");
std::fs::write(&config, "").unwrap();
assert!(!is_publicly_served(&config, &base.join("site")));
// A sibling directory with the same prefix is not inside the site root
std::fs::create_dir_all(base.join("site-config")).unwrap();
std::fs::write(base.join("site-config/config.toml"), "").unwrap();
assert!(!is_publicly_served(&base.join("site-config/config.toml"), &base.join("site")));
std::fs::remove_dir_all(base).unwrap();
}
#[test]
fn initial_password_is_required() {
assert!(resolve_initial_password(None, None).is_err());
assert!(resolve_initial_password(Some("".to_string()), Some("".to_string())).is_err());
// The sample config must not ship a usable password
assert!(resolve_initial_password(None, sample().admin.initial_password).is_err());
}
#[test]
fn initial_password_from_config() {
let admin: Admin = toml::from_str("initial_password = 'correct horse'").unwrap();
assert_eq!(resolve_initial_password(None, admin.initial_password), Ok("correct horse".to_string()));
}
#[test]
fn initial_password_env_takes_precedence() {
assert_eq!(
resolve_initial_password(Some("from-environment".to_string()), Some("from-config".to_string())),
Ok("from-environment".to_string()));
// An empty variable does not hide the config value
assert_eq!(
resolve_initial_password(Some("".to_string()), Some("from-config".to_string())),
Ok("from-config".to_string()));
}
#[test]
fn initial_password_must_not_be_short() {
assert!(resolve_initial_password(Some("admin".to_string()), None).is_err());
assert!(resolve_initial_password(None, Some("1234567".to_string())).is_err());
assert!(resolve_initial_password(None, Some("12345678".to_string())).is_ok());
// Length is counted in characters, not bytes
assert!(resolve_initial_password(None, Some("čšřžýáí".to_string())).is_err());
}
#[test]
fn data_dir_defaults_to_data() {
// The sample config has the storage section commented out
assert_eq!(sample().storage().data_dir(), PathBuf::from("data"));
let storage: Storage = toml::from_str("").unwrap();
assert_eq!(storage.data_dir(), PathBuf::from("data"));
}
#[test]
fn data_dir_can_be_configured() {
let storage: Storage = toml::from_str("data_dir = '/var/lib/rezervator'").unwrap();
assert_eq!(storage.data_dir(), PathBuf::from("/var/lib/rezervator"));
}
2026-10-10 17:01:51 +02:00
#[test]
fn sample_session_key_is_long_enough() {
// actix_web::cookie::Key::from panics on keys shorter than 64 bytes
assert!(sample().session().key().len() >= 64);
}
#[test]
fn database_port_defaults_to_5432() {
let database: Database = toml::from_str(
"user = 'u'\npassword = 'p'\ndb_name = 'db'\nhost = 'db.example.com'").unwrap();
assert_eq!(database.con_string(), "postgres://u:[email protected]:5432/db");
}
#[test]
fn database_custom_port() {
let database: Database = toml::from_str(
"user = 'u'\npassword = 'p'\ndb_name = 'db'\nhost = 'db.example.com'\nport = 6543").unwrap();
assert_eq!(database.con_string(), "postgres://u:[email protected]:6543/db");
}
#[test]
fn smtp_mailing_config() {
let mailing: Mailing = toml::from_str(
"transport = 'Smtp'\nfrom = '[email protected]'\nserver = 'smtp.b.cz'\nport = 587\ntls = true").unwrap();
assert!(matches!(mailing.transport(), MailTransport::Smtp));
assert_eq!(mailing.server(), &Some("smtp.b.cz".to_string()));
assert_eq!(mailing.port(), Some(587));
assert_eq!(mailing.tls(), Some(true));
assert_eq!(mailing.accept_all_certs(), None);
}
}