Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 9 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,14 @@ hyper-util = { version = "0.1.3", features = ["http1", "http2", "tokio"] }
indexmap = "2"
jsonwebtoken = "9"
lazy_static = "1.4.0"
lettre = { version = "0", features = ["builder", "smtp-transport", "tokio1", "tokio1-native-tls", "tokio1-rustls-tls"] }
lettre = { version = "0", features = [
"builder",
"file-transport-envelope",
"smtp-transport",
"tokio1",
"tokio1-native-tls",
"tokio1-rustls-tls",
] }
log = "0"
pbkdf2 = { version = "0", features = ["simple"] }
pin-project-lite = "0.2"
Expand Down Expand Up @@ -85,7 +92,7 @@ tower = { version = "0.4", features = ["timeout"] }
tower-http = { version = "0", features = ["compression-full", "cors", "propagate-header", "request-id", "trace"] }
trace = "0.1.7"
tracing = "0.1.40"
url = "2.5.0"
url = { version = "2.5.0", features = ["serde"] }
urlencoding = "2"
uuid = { version = "1", features = ["v4"] }

Expand Down
2 changes: 1 addition & 1 deletion share/default/config/index.development.sqlite3.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ log_level = "info"
name = "Torrust"

[tracker]
api_url = "http://localhost:1212"
api_url = "http://localhost:1212/"
mode = "Public"
token = "MyAccessToken"
token_valid_seconds = 7257600
Expand Down
2 changes: 1 addition & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub async fn run(configuration: Configuration, api_version: &Version) -> Running
settings.validate().expect("invalid settings");

// From [database] config
let database_connect_url = settings.database.connect_url.clone();
let database_connect_url = settings.database.connect_url.clone().to_string();
// From [importer] config
let importer_torrent_info_update_interval = settings.tracker_statistics_importer.torrent_info_update_interval;
let importer_port = settings.tracker_statistics_importer.port;
Expand Down
16 changes: 12 additions & 4 deletions src/bootstrap/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
//! - `Info`
//! - `Debug`
//! - `Trace`
use std::str::FromStr;
use std::sync::Once;

use log::{info, LevelFilter};

use crate::config::v1::LogLevel;

static INIT: Once = Once::new();

pub fn setup(log_level: &Option<String>) {
pub fn setup(log_level: &Option<LogLevel>) {
let level = config_level_or_default(log_level);

if level == log::LevelFilter::Off {
Expand All @@ -25,10 +26,17 @@ pub fn setup(log_level: &Option<String>) {
});
}

fn config_level_or_default(log_level: &Option<String>) -> LevelFilter {
fn config_level_or_default(log_level: &Option<LogLevel>) -> LevelFilter {
match log_level {
None => log::LevelFilter::Info,
Some(level) => LevelFilter::from_str(level).unwrap(),
Some(level) => match level {
LogLevel::Off => LevelFilter::Off,
LogLevel::Error => LevelFilter::Error,
LogLevel::Warn => LevelFilter::Warn,
LogLevel::Info => LevelFilter::Info,
LogLevel::Debug => LevelFilter::Debug,
LogLevel::Trace => LevelFilter::Trace,
},
}
}

Expand Down
58 changes: 23 additions & 35 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use tokio::sync::RwLock;
use torrust_index_located_error::LocatedError;
use url::Url;

use self::v1::tracker::ApiToken;
use crate::web::api::server::DynError;

pub type Settings = v1::Settings;
Expand Down Expand Up @@ -55,7 +56,7 @@ pub const ENV_VAR_AUTH_SECRET_KEY: &str = "TORRUST_INDEX_AUTH_SECRET_KEY";
pub struct Info {
config_toml: Option<String>,
config_toml_path: String,
tracker_api_token: Option<String>,
tracker_api_token: Option<ApiToken>,
auth_secret_key: Option<String>,
}

Expand Down Expand Up @@ -88,7 +89,10 @@ impl Info {
default_config_toml_path
};

let tracker_api_token = env::var(env_var_tracker_api_admin_token).ok();
let tracker_api_token = env::var(env_var_tracker_api_admin_token)
.ok()
.map(|token| ApiToken::new(&token));

let auth_secret_key = env::var(env_var_auth_secret_key).ok();

Ok(Self {
Expand Down Expand Up @@ -316,8 +320,7 @@ impl Configuration {

pub async fn get_api_base_url(&self) -> Option<String> {
let settings_lock = self.settings.read().await;

settings_lock.net.base_url.clone()
settings_lock.net.base_url.as_ref().map(std::string::ToString::to_string)
}
}

Expand All @@ -326,18 +329,18 @@ impl Configuration {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ConfigurationPublic {
website_name: String,
tracker_url: String,
tracker_url: Url,
tracker_mode: TrackerMode,
email_on_signup: EmailOnSignup,
}

fn parse_url(url_str: &str) -> Result<Url, url::ParseError> {
Url::parse(url_str)
}

#[cfg(test)]
mod tests {

use url::Url;

use crate::config::v1::auth::SecretKey;
use crate::config::v1::tracker::ApiToken;
use crate::config::{Configuration, ConfigurationPublic, Info, Settings};

#[cfg(test)]
Expand All @@ -348,7 +351,7 @@ mod tests {
[tracker]
url = "udp://localhost:6969"
mode = "Public"
api_url = "http://localhost:1212"
api_url = "http://localhost:1212/"
token = "MyAccessToken"
token_valid_seconds = 7257600

Expand Down Expand Up @@ -441,10 +444,10 @@ mod tests {
assert_eq!(configuration.get_api_base_url().await, None);

let mut settings_lock = configuration.settings.write().await;
settings_lock.net.base_url = Some("http://localhost".to_string());
settings_lock.net.base_url = Some(Url::parse("http://localhost").unwrap());
drop(settings_lock);

assert_eq!(configuration.get_api_base_url().await, Some("http://localhost".to_string()));
assert_eq!(configuration.get_api_base_url().await, Some("http://localhost/".to_string()));
}

#[tokio::test]
Expand Down Expand Up @@ -473,15 +476,15 @@ mod tests {
let info = Info {
config_toml: Some(default_config_toml()),
config_toml_path: String::new(),
tracker_api_token: Some("OVERRIDDEN API TOKEN".to_string()),
tracker_api_token: Some(ApiToken::new("OVERRIDDEN API TOKEN")),
auth_secret_key: None,
};

let configuration = Configuration::load(&info).expect("Failed to load configuration from info");

assert_eq!(
configuration.get_all().await.tracker.token,
"OVERRIDDEN API TOKEN".to_string()
ApiToken::new("OVERRIDDEN API TOKEN")
);
}

Expand All @@ -502,7 +505,7 @@ mod tests {

let settings = Configuration::load_settings(&info).expect("Could not load configuration from file");

assert_eq!(settings.tracker.token, "OVERRIDDEN API TOKEN".to_string());
assert_eq!(settings.tracker.token, ApiToken::new("OVERRIDDEN API TOKEN"));

Ok(())
});
Expand All @@ -521,7 +524,7 @@ mod tests {

assert_eq!(
configuration.get_all().await.auth.secret_key,
"OVERRIDDEN AUTH SECRET KEY".to_string()
SecretKey::new("OVERRIDDEN AUTH SECRET KEY")
);
}

Expand All @@ -542,30 +545,15 @@ mod tests {

let settings = Configuration::load_settings(&info).expect("Could not load configuration from file");

assert_eq!(settings.auth.secret_key, "OVERRIDDEN AUTH SECRET KEY".to_string());
assert_eq!(settings.auth.secret_key, SecretKey::new("OVERRIDDEN AUTH SECRET KEY"));

Ok(())
});
}

mod syntax_checks {
// todo: use rich types in configuration structs for basic syntax checks.

use crate::config::validator::Validator;
use crate::config::Configuration;

#[tokio::test]
async fn tracker_url_should_be_a_valid_url() {
let configuration = Configuration::default();

let mut settings_lock = configuration.settings.write().await;
settings_lock.tracker.url = "INVALID URL".to_string();

assert!(settings_lock.validate().is_err());
}
}

mod semantic_validation {
use url::Url;

use crate::config::validator::Validator;
use crate::config::{Configuration, TrackerMode};

Expand All @@ -575,7 +563,7 @@ mod tests {

let mut settings_lock = configuration.settings.write().await;
settings_lock.tracker.mode = TrackerMode::Private;
settings_lock.tracker.url = "udp://localhost:6969".to_string();
settings_lock.tracker.url = Url::parse("udp://localhost:6969").unwrap();

assert!(settings_lock.validate().is_err());
}
Expand Down
45 changes: 42 additions & 3 deletions src/config/v1/auth.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt;

use serde::{Deserialize, Serialize};

/// Authentication options.
Expand All @@ -10,7 +12,7 @@ pub struct Auth {
/// The maximum password length.
pub max_password_length: usize,
/// The secret key used to sign JWT tokens.
pub secret_key: String,
pub secret_key: SecretKey,
}

impl Default for Auth {
Expand All @@ -19,14 +21,14 @@ impl Default for Auth {
email_on_signup: EmailOnSignup::default(),
min_password_length: 6,
max_password_length: 64,
secret_key: "MaxVerstappenWC2021".to_string(),
secret_key: SecretKey::new("MaxVerstappenWC2021"),
}
}
}

impl Auth {
pub fn override_secret_key(&mut self, secret_key: &str) {
self.secret_key = secret_key.to_string();
self.secret_key = SecretKey::new(secret_key);
}
}

Expand All @@ -46,3 +48,40 @@ impl Default for EmailOnSignup {
Self::Optional
}
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SecretKey(String);

impl SecretKey {
/// # Panics
///
/// Will panic if the key if empty.
#[must_use]
pub fn new(key: &str) -> Self {
assert!(!key.is_empty(), "secret key cannot be empty");

Self(key.to_owned())
}

#[must_use]
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
}

impl fmt::Display for SecretKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}

#[cfg(test)]
mod tests {
use super::SecretKey;

#[test]
#[should_panic(expected = "secret key cannot be empty")]
fn secret_key_can_not_be_empty() {
drop(SecretKey::new(""));
}
}
10 changes: 7 additions & 3 deletions src/config/v1/database.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
use serde::{Deserialize, Serialize};
use url::Url;

/// Database configuration.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Database {
/// The connection string for the database. For example: `sqlite://data.db?mode=rwc`.
pub connect_url: String,
/// The connection URL for the database. For example:
///
/// Sqlite: `sqlite://data.db?mode=rwc`.
/// Mysql: `mysql://root:root_secret_password@mysql:3306/torrust_index_e2e_testing`.
pub connect_url: Url,
}

impl Default for Database {
fn default() -> Self {
Self {
connect_url: "sqlite://data.db?mode=rwc".to_string(),
connect_url: Url::parse("sqlite://data.db?mode=rwc").unwrap(),
}
}
}
9 changes: 5 additions & 4 deletions src/config/v1/mail.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use lettre::message::Mailbox;
use serde::{Deserialize, Serialize};

/// SMTP configuration.
Expand All @@ -6,9 +7,9 @@ pub struct Mail {
/// Whether or not to enable email verification on signup.
pub email_verification_enabled: bool,
/// The email address to send emails from.
pub from: String,
pub from: Mailbox,
/// The email address to reply to.
pub reply_to: String,
pub reply_to: Mailbox,
/// The username to use for SMTP authentication.
pub username: String,
/// The password to use for SMTP authentication.
Expand All @@ -23,8 +24,8 @@ impl Default for Mail {
fn default() -> Self {
Self {
email_verification_enabled: false,
from: "[email protected]".to_string(),
reply_to: "[email protected]".to_string(),
from: "[email protected]".parse().expect("valid mailbox"),
reply_to: "[email protected]".parse().expect("valid mailbox"),
username: String::default(),
password: String::default(),
server: String::default(),
Expand Down
Loading