Skip to content

Commit

Permalink
refactor: [torrust#1191] rename mod core::auth to core::authentication
Browse files Browse the repository at this point in the history
The `auth` name is ambiguous, it could mean authorization.
  • Loading branch information
josecelano committed Jan 20, 2025
1 parent f216b05 commit 2b7373a
Show file tree
Hide file tree
Showing 18 changed files with 92 additions and 89 deletions.
30 changes: 15 additions & 15 deletions src/core/auth/key.rs → src/core/authentication/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
//! Keys are stored in this struct:
//!
//! ```rust,no_run
//! use torrust_tracker_lib::core::auth::Key;
//! use torrust_tracker_lib::core::authentication::Key;
//! use torrust_tracker_primitives::DurationSinceUnixEpoch;
//!
//! pub struct PeerKey {
Expand All @@ -28,14 +28,14 @@
//! You can generate a new key valid for `9999` seconds and `0` nanoseconds from the current time with the following:
//!
//! ```rust,no_run
//! use torrust_tracker_lib::core::auth;
//! use torrust_tracker_lib::core::authentication;
//! use std::time::Duration;
//!
//! let expiring_key = auth::key::generate_key(Some(Duration::new(9999, 0)));
//! let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0)));
//!
//! // And you can later verify it with:
//!
//! assert!(auth::key::verify_key_expiration(&expiring_key).is_ok());
//! assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok());
//! ```
use std::panic::Location;
Expand Down Expand Up @@ -199,7 +199,7 @@ impl Key {
/// Error returned when a key cannot be parsed from a string.
///
/// ```text
/// use torrust_tracker_lib::core::auth::Key;
/// use torrust_tracker_lib::core::authentication::Key;
/// use std::str::FromStr;
///
/// let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ";
Expand Down Expand Up @@ -229,7 +229,7 @@ impl FromStr for Key {
}

/// Verification error. Error returned when an [`PeerKey`] cannot be
/// verified with the (`crate::core::auth::verify_key`) function.
/// verified with the (`crate::core::authentication::verify_key`) function.
#[derive(Debug, Error)]
#[allow(dead_code)]
pub enum Error {
Expand Down Expand Up @@ -260,7 +260,7 @@ mod tests {
mod key {
use std::str::FromStr;

use crate::core::auth::Key;
use crate::core::authentication::Key;

#[test]
fn should_be_parsed_from_an_string() {
Expand Down Expand Up @@ -295,12 +295,12 @@ mod tests {
use torrust_tracker_clock::clock;
use torrust_tracker_clock::clock::stopped::Stopped as _;

use crate::core::auth;
use crate::core::authentication;

#[test]
fn should_be_parsed_from_an_string() {
let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ";
let auth_key = auth::Key::from_str(key_string);
let auth_key = authentication::Key::from_str(key_string);

assert!(auth_key.is_ok());
assert_eq!(auth_key.unwrap().to_string(), key_string);
Expand All @@ -311,7 +311,7 @@ mod tests {
// Set the time to the current time.
clock::Stopped::local_set_to_unix_epoch();

let expiring_key = auth::key::generate_key(Some(Duration::from_secs(0)));
let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(0)));

assert_eq!(
expiring_key.to_string(),
Expand All @@ -321,9 +321,9 @@ mod tests {

#[test]
fn should_be_generated_with_a_expiration_time() {
let expiring_key = auth::key::generate_key(Some(Duration::new(9999, 0)));
let expiring_key = authentication::key::generate_key(Some(Duration::new(9999, 0)));

assert!(auth::key::verify_key_expiration(&expiring_key).is_ok());
assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok());
}

#[test]
Expand All @@ -332,17 +332,17 @@ mod tests {
clock::Stopped::local_set_to_system_time_now();

// Make key that is valid for 19 seconds.
let expiring_key = auth::key::generate_key(Some(Duration::from_secs(19)));
let expiring_key = authentication::key::generate_key(Some(Duration::from_secs(19)));

// Mock the time has passed 10 sec.
clock::Stopped::local_add(&Duration::from_secs(10)).unwrap();

assert!(auth::key::verify_key_expiration(&expiring_key).is_ok());
assert!(authentication::key::verify_key_expiration(&expiring_key).is_ok());

// Mock the time has passed another 10 sec.
clock::Stopped::local_add(&Duration::from_secs(10)).unwrap();

assert!(auth::key::verify_key_expiration(&expiring_key).is_err());
assert!(authentication::key::verify_key_expiration(&expiring_key).is_err());
}
}
}
File renamed without changes.
10 changes: 5 additions & 5 deletions src/core/databases/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ use bittorrent_primitives::info_hash::InfoHash;
use torrust_tracker_primitives::PersistentTorrents;

use self::error::Error;
use crate::core::auth::{self, Key};
use crate::core::authentication::{self, Key};

struct Builder<T>
where
Expand Down Expand Up @@ -195,19 +195,19 @@ pub trait Database: Sync + Send {
/// # Errors
///
/// Will return `Err` if unable to load.
fn load_keys(&self) -> Result<Vec<auth::PeerKey>, Error>;
fn load_keys(&self) -> Result<Vec<authentication::PeerKey>, Error>;

/// It gets an expiring authentication key from the database.
///
/// It returns `Some(PeerKey)` if a [`PeerKey`](crate::core::auth::PeerKey)
/// It returns `Some(PeerKey)` if a [`PeerKey`](crate::core::authentication::PeerKey)
/// with the input [`Key`] exists, `None` otherwise.
///
/// # Context: Authentication Keys
///
/// # Errors
///
/// Will return `Err` if unable to load.
fn get_key_from_keys(&self, key: &Key) -> Result<Option<auth::PeerKey>, Error>;
fn get_key_from_keys(&self, key: &Key) -> Result<Option<authentication::PeerKey>, Error>;

/// It adds an expiring authentication key to the database.
///
Expand All @@ -216,7 +216,7 @@ pub trait Database: Sync + Send {
/// # Errors
///
/// Will return `Err` if unable to save.
fn add_key_to_keys(&self, auth_key: &auth::PeerKey) -> Result<usize, Error>;
fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result<usize, Error>;

/// It removes an expiring authentication key from the database.
///
Expand Down
18 changes: 9 additions & 9 deletions src/core/databases/mysql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use torrust_tracker_primitives::PersistentTorrents;

use super::driver::Driver;
use super::{Database, Error};
use crate::core::auth::{self, Key};
use crate::core::authentication::{self, Key};
use crate::shared::bit_torrent::common::AUTH_KEY_LENGTH;

const DRIVER: Driver = Driver::MySQL;
Expand Down Expand Up @@ -63,7 +63,7 @@ impl Database for Mysql {
PRIMARY KEY (`id`),
UNIQUE (`key`)
);",
i8::try_from(AUTH_KEY_LENGTH).expect("auth::Auth Key Length Should fit within a i8!")
i8::try_from(AUTH_KEY_LENGTH).expect("authentication key length should fit within a i8!")
);

let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?;
Expand Down Expand Up @@ -118,17 +118,17 @@ impl Database for Mysql {
}

/// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys).
fn load_keys(&self) -> Result<Vec<auth::PeerKey>, Error> {
fn load_keys(&self) -> Result<Vec<authentication::PeerKey>, Error> {
let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?;

let keys = conn.query_map(
"SELECT `key`, valid_until FROM `keys`",
|(key, valid_until): (String, Option<i64>)| match valid_until {
Some(valid_until) => auth::PeerKey {
Some(valid_until) => authentication::PeerKey {
key: key.parse::<Key>().unwrap(),
valid_until: Some(Duration::from_secs(valid_until.unsigned_abs())),
},
None => auth::PeerKey {
None => authentication::PeerKey {
key: key.parse::<Key>().unwrap(),
valid_until: None,
},
Expand Down Expand Up @@ -202,7 +202,7 @@ impl Database for Mysql {
}

/// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys).
fn get_key_from_keys(&self, key: &Key) -> Result<Option<auth::PeerKey>, Error> {
fn get_key_from_keys(&self, key: &Key) -> Result<Option<authentication::PeerKey>, Error> {
let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?;

let query = conn.exec_first::<(String, Option<i64>), _, _>(
Expand All @@ -213,19 +213,19 @@ impl Database for Mysql {
let key = query?;

Ok(key.map(|(key, opt_valid_until)| match opt_valid_until {
Some(valid_until) => auth::PeerKey {
Some(valid_until) => authentication::PeerKey {
key: key.parse::<Key>().unwrap(),
valid_until: Some(Duration::from_secs(valid_until.unsigned_abs())),
},
None => auth::PeerKey {
None => authentication::PeerKey {
key: key.parse::<Key>().unwrap(),
valid_until: None,
},
}))
}

/// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys).
fn add_key_to_keys(&self, auth_key: &auth::PeerKey) -> Result<usize, Error> {
fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result<usize, Error> {
let mut conn = self.pool.get().map_err(|e| (e, DRIVER))?;

let key = auth_key.key.to_string();
Expand Down
18 changes: 9 additions & 9 deletions src/core/databases/sqlite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use torrust_tracker_primitives::{DurationSinceUnixEpoch, PersistentTorrents};

use super::driver::Driver;
use super::{Database, Error};
use crate::core::auth::{self, Key};
use crate::core::authentication::{self, Key};

const DRIVER: Driver = Driver::Sqlite3;

Expand Down Expand Up @@ -106,7 +106,7 @@ impl Database for Sqlite {
}

/// Refer to [`databases::Database::load_keys`](crate::core::databases::Database::load_keys).
fn load_keys(&self) -> Result<Vec<auth::PeerKey>, Error> {
fn load_keys(&self) -> Result<Vec<authentication::PeerKey>, Error> {
let conn = self.pool.get().map_err(|e| (e, DRIVER))?;

let mut stmt = conn.prepare("SELECT key, valid_until FROM keys")?;
Expand All @@ -116,18 +116,18 @@ impl Database for Sqlite {
let opt_valid_until: Option<i64> = row.get(1)?;

match opt_valid_until {
Some(valid_until) => Ok(auth::PeerKey {
Some(valid_until) => Ok(authentication::PeerKey {
key: key.parse::<Key>().unwrap(),
valid_until: Some(DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs())),
}),
None => Ok(auth::PeerKey {
None => Ok(authentication::PeerKey {
key: key.parse::<Key>().unwrap(),
valid_until: None,
}),
}
})?;

let keys: Vec<auth::PeerKey> = keys_iter.filter_map(std::result::Result::ok).collect();
let keys: Vec<authentication::PeerKey> = keys_iter.filter_map(std::result::Result::ok).collect();

Ok(keys)
}
Expand Down Expand Up @@ -216,7 +216,7 @@ impl Database for Sqlite {
}

/// Refer to [`databases::Database::get_key_from_keys`](crate::core::databases::Database::get_key_from_keys).
fn get_key_from_keys(&self, key: &Key) -> Result<Option<auth::PeerKey>, Error> {
fn get_key_from_keys(&self, key: &Key) -> Result<Option<authentication::PeerKey>, Error> {
let conn = self.pool.get().map_err(|e| (e, DRIVER))?;

let mut stmt = conn.prepare("SELECT key, valid_until FROM keys WHERE key = ?")?;
Expand All @@ -230,11 +230,11 @@ impl Database for Sqlite {
let key: String = f.get(0).unwrap();

match valid_until {
Some(valid_until) => auth::PeerKey {
Some(valid_until) => authentication::PeerKey {
key: key.parse::<Key>().unwrap(),
valid_until: Some(DurationSinceUnixEpoch::from_secs(valid_until.unsigned_abs())),
},
None => auth::PeerKey {
None => authentication::PeerKey {
key: key.parse::<Key>().unwrap(),
valid_until: None,
},
Expand All @@ -243,7 +243,7 @@ impl Database for Sqlite {
}

/// Refer to [`databases::Database::add_key_to_keys`](crate::core::databases::Database::add_key_to_keys).
fn add_key_to_keys(&self, auth_key: &auth::PeerKey) -> Result<usize, Error> {
fn add_key_to_keys(&self, auth_key: &authentication::PeerKey) -> Result<usize, Error> {
let conn = self.pool.get().map_err(|e| (e, DRIVER))?;

let insert = match auth_key.valid_until {
Expand Down
4 changes: 2 additions & 2 deletions src/core/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ use bittorrent_http_protocol::v1::responses;
use bittorrent_primitives::info_hash::InfoHash;
use torrust_tracker_located_error::LocatedError;

use super::{auth::key::ParseKeyError, databases};
use super::{authentication::key::ParseKeyError, databases};

/// Authentication or authorization error returned by the core `Tracker`
#[derive(thiserror::Error, Debug, Clone)]
pub enum Error {
// Authentication errors
#[error("The supplied key: {key:?}, is not valid: {source}")]
PeerKeyNotValid {
key: super::auth::Key,
key: super::authentication::Key,
source: LocatedError<'static, dyn std::error::Error + Send + Sync>,
},

Expand Down
Loading

0 comments on commit 2b7373a

Please sign in to comment.