Skip to content

Commit

Permalink
refactor: rename structs, attributes and variables with sufix KeyId o…
Browse files Browse the repository at this point in the history
…r key_id

to `Key` and `key`. removing the `Id` and `id`, since the `KeyId` struct
was renamed to `Key`.
  • Loading branch information
josecelano committed Mar 5, 2023
1 parent 7b690a4 commit 0ee5a51
Show file tree
Hide file tree
Showing 16 changed files with 83 additions and 83 deletions.
6 changes: 3 additions & 3 deletions src/apis/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,15 @@ pub async fn generate_auth_key_handler(State(tracker): State<Arc<Tracker>>, Path
}

#[derive(Deserialize)]
pub struct KeyIdParam(String);
pub struct KeyParam(String);

pub async fn delete_auth_key_handler(
State(tracker): State<Arc<Tracker>>,
Path(seconds_valid_or_key): Path<KeyIdParam>,
Path(seconds_valid_or_key): Path<KeyParam>,
) -> Response {
match Key::from_str(&seconds_valid_or_key.0) {
Err(_) => invalid_auth_key_param_response(&seconds_valid_or_key.0),
Ok(key_id) => match tracker.remove_auth_key(&key_id.to_string()).await {
Ok(key) => match tracker.remove_auth_key(&key.to_string()).await {
Ok(_) => ok_response(),
Err(e) => failed_to_delete_key_response(e),
},
Expand Down
4 changes: 2 additions & 2 deletions src/databases/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@ pub trait Database: Sync + Send {

async fn remove_info_hash_from_whitelist(&self, info_hash: InfoHash) -> Result<usize, Error>;

// todo: replace type `&str` with `&KeyId`
// todo: replace type `&str` with `&Key`
async fn get_key_from_keys(&self, key: &str) -> Result<Option<auth::ExpiringKey>, Error>;

async fn add_key_to_keys(&self, auth_key: &auth::ExpiringKey) -> Result<usize, Error>;

// todo: replace type `&str` with `&KeyId`
// todo: replace type `&str` with `&Key`
async fn remove_key_from_keys(&self, key: &str) -> Result<usize, Error>;

async fn is_info_hash_whitelisted(&self, info_hash: &InfoHash) -> Result<bool, Error> {
Expand Down
14 changes: 7 additions & 7 deletions src/http/axum_implementation/extractors/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,30 @@ use axum::extract::{FromRequestParts, Path};
use axum::http::request::Parts;
use axum::response::{IntoResponse, Response};

use crate::http::axum_implementation::handlers::auth::{self, KeyIdParam};
use crate::http::axum_implementation::handlers::auth::{self, KeyParam};
use crate::http::axum_implementation::responses;
use crate::tracker::auth::Key;

pub struct ExtractKeyId(pub Key);
pub struct Extract(pub Key);

#[async_trait]
impl<S> FromRequestParts<S> for ExtractKeyId
impl<S> FromRequestParts<S> for Extract
where
S: Send + Sync,
{
type Rejection = Response;

async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
match Path::<KeyIdParam>::from_request_parts(parts, state).await {
Ok(key_id_param) => {
let Ok(key_id) = key_id_param.0.value().parse::<Key>() else {
match Path::<KeyParam>::from_request_parts(parts, state).await {
Ok(key_param) => {
let Ok(key) = key_param.0.value().parse::<Key>() else {
return Err(responses::error::Error::from(
auth::Error::InvalidKeyFormat {
location: Location::caller()
})
.into_response())
};
Ok(ExtractKeyId(key_id))
Ok(Extract(key))
}
Err(rejection) => match rejection {
axum::extract::rejection::PathRejection::FailedToDeserializePathParams(_) => {
Expand Down
6 changes: 3 additions & 3 deletions src/http/axum_implementation/handlers/announce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use axum::response::{IntoResponse, Response};
use log::debug;

use crate::http::axum_implementation::extractors::announce_request::ExtractRequest;
use crate::http::axum_implementation::extractors::key::ExtractKeyId;
use crate::http::axum_implementation::extractors::key::Extract;
use crate::http::axum_implementation::extractors::peer_ip;
use crate::http::axum_implementation::extractors::remote_client_ip::RemoteClientIp;
use crate::http::axum_implementation::handlers::auth;
Expand Down Expand Up @@ -41,12 +41,12 @@ pub async fn handle_without_key(
pub async fn handle_with_key(
State(tracker): State<Arc<Tracker>>,
ExtractRequest(announce_request): ExtractRequest,
ExtractKeyId(key_id): ExtractKeyId,
Extract(key): Extract,
remote_client_ip: RemoteClientIp,
) -> Response {
debug!("http announce request: {:#?}", announce_request);

match tracker.authenticate(&key_id).await {
match tracker.authenticate(&key).await {
Ok(_) => (),
Err(error) => return responses::error::Error::from(error).into_response(),
}
Expand Down
4 changes: 2 additions & 2 deletions src/http/axum_implementation/handlers/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ use crate::http::axum_implementation::responses;
use crate::tracker::auth;

#[derive(Deserialize)]
pub struct KeyIdParam(String);
pub struct KeyParam(String);

impl KeyIdParam {
impl KeyParam {
#[must_use]
pub fn value(&self) -> String {
self.0.clone()
Expand Down
6 changes: 3 additions & 3 deletions src/http/axum_implementation/handlers/scrape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use axum::extract::State;
use axum::response::{IntoResponse, Response};
use log::debug;

use crate::http::axum_implementation::extractors::key::ExtractKeyId;
use crate::http::axum_implementation::extractors::key::Extract;
use crate::http::axum_implementation::extractors::peer_ip;
use crate::http::axum_implementation::extractors::remote_client_ip::RemoteClientIp;
use crate::http::axum_implementation::extractors::scrape_request::ExtractRequest;
Expand All @@ -31,12 +31,12 @@ pub async fn handle_without_key(
pub async fn handle_with_key(
State(tracker): State<Arc<Tracker>>,
ExtractRequest(scrape_request): ExtractRequest,
ExtractKeyId(key_id): ExtractKeyId,
Extract(key): Extract,
remote_client_ip: RemoteClientIp,
) -> Response {
debug!("http scrape request: {:#?}", &scrape_request);

match tracker.authenticate(&key_id).await {
match tracker.authenticate(&key).await {
Ok(_) => (),
Err(_) => return handle_fake_scrape(&tracker, &scrape_request, &remote_client_ip).await,
}
Expand Down
6 changes: 3 additions & 3 deletions src/http/warp_implementation/filters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ pub fn with_peer_id() -> impl Filter<Extract = (peer::Id,), Error = Rejection> +

/// Pass Arc<tracker::TorrentTracker> along
#[must_use]
pub fn with_auth_key_id() -> impl Filter<Extract = (Option<Key>,), Error = Infallible> + Clone {
pub fn with_auth_key() -> impl Filter<Extract = (Option<Key>,), Error = Infallible> + Clone {
warp::path::param::<String>()
.map(|key: String| {
let key_id = Key::from_str(&key);
match key_id {
let key = Key::from_str(&key);
match key {
Ok(id) => Some(id),
Err(_) => None,
}
Expand Down
12 changes: 6 additions & 6 deletions src/http/warp_implementation/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ use crate::tracker::{self, auth, peer, statistics, torrent};
/// Will return `ServerError` that wraps the `tracker::error::Error` if unable to `authenticate_request`.
pub async fn authenticate(
info_hash: &InfoHash,
auth_key_id: &Option<auth::Key>,
auth_key: &Option<auth::Key>,
tracker: Arc<tracker::Tracker>,
) -> Result<(), Error> {
tracker
.authenticate_request(info_hash, auth_key_id)
.authenticate_request(info_hash, auth_key)
.await
.map_err(|e| Error::TrackerError {
source: (Arc::new(e) as Arc<dyn std::error::Error + Send + Sync>).into(),
Expand All @@ -38,15 +38,15 @@ pub async fn authenticate(
/// Will return `warp::Rejection` that wraps the `ServerError` if unable to `send_announce_response`.
pub async fn handle_announce(
announce_request: request::Announce,
auth_key_id: Option<Key>,
auth_key: Option<Key>,
tracker: Arc<tracker::Tracker>,
) -> WebResult<impl Reply> {
debug!("http announce request: {:#?}", announce_request);

let info_hash = announce_request.info_hash;
let remote_client_ip = announce_request.peer_addr;

authenticate(&info_hash, &auth_key_id, tracker.clone()).await?;
authenticate(&info_hash, &auth_key, tracker.clone()).await?;

let mut peer = peer_builder::from_request(&announce_request, &remote_client_ip);

Expand Down Expand Up @@ -78,7 +78,7 @@ pub async fn handle_announce(
/// Will return `warp::Rejection` that wraps the `ServerError` if unable to `send_scrape_response`.
pub async fn handle_scrape(
scrape_request: request::Scrape,
auth_key_id: Option<Key>,
auth_key: Option<Key>,
tracker: Arc<tracker::Tracker>,
) -> WebResult<impl Reply> {
let mut files: HashMap<InfoHash, response::ScrapeEntry> = HashMap::new();
Expand All @@ -87,7 +87,7 @@ pub async fn handle_scrape(
for info_hash in &scrape_request.info_hashes {
let scrape_entry = match db.get(info_hash) {
Some(torrent_info) => {
if authenticate(info_hash, &auth_key_id, tracker.clone()).await.is_ok() {
if authenticate(info_hash, &auth_key, tracker.clone()).await.is_ok() {
let (seeders, completed, leechers) = torrent_info.get_stats();
response::ScrapeEntry {
complete: seeders,
Expand Down
6 changes: 3 additions & 3 deletions src/http/warp_implementation/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::sync::Arc;

use warp::{Filter, Rejection};

use super::filters::{with_announce_request, with_auth_key_id, with_scrape_request, with_tracker};
use super::filters::{with_announce_request, with_auth_key, with_scrape_request, with_tracker};
use super::handlers::{handle_announce, handle_scrape, send_error};
use crate::tracker;

Expand All @@ -20,7 +20,7 @@ fn announce(tracker: Arc<tracker::Tracker>) -> impl Filter<Extract = impl warp::
warp::path::path("announce")
.and(warp::filters::method::get())
.and(with_announce_request(tracker.config.on_reverse_proxy))
.and(with_auth_key_id())
.and(with_auth_key())
.and(with_tracker(tracker))
.and_then(handle_announce)
}
Expand All @@ -30,7 +30,7 @@ fn scrape(tracker: Arc<tracker::Tracker>) -> impl Filter<Extract = impl warp::Re
warp::path::path("scrape")
.and(warp::filters::method::get())
.and(with_scrape_request(tracker.config.on_reverse_proxy))
.and(with_auth_key_id())
.and(with_auth_key())
.and(with_tracker(tracker))
.and_then(handle_scrape)
}
18 changes: 9 additions & 9 deletions src/tracker/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,14 @@ impl ExpiringKey {
pub struct Key(String);

#[derive(Debug, PartialEq, Eq)]
pub struct ParseKeyIdError;
pub struct ParseKeyError;

impl FromStr for Key {
type Err = ParseKeyIdError;
type Err = ParseKeyError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() != AUTH_KEY_LENGTH {
return Err(ParseKeyIdError);
return Err(ParseKeyError);
}

Ok(Self(s.to_string()))
Expand All @@ -106,10 +106,10 @@ pub enum Error {
KeyVerificationError {
source: LocatedError<'static, dyn std::error::Error + Send + Sync>,
},
#[error("Failed to read key: {key_id}, {location}")]
#[error("Failed to read key: {key}, {location}")]
UnableToReadKey {
location: &'static Location<'static>,
key_id: Box<Key>,
key: Box<Key>,
},
#[error("Key has expired, {location}")]
KeyExpired { location: &'static Location<'static> },
Expand All @@ -132,12 +132,12 @@ mod tests {
use crate::tracker::auth;

#[test]
fn auth_key_id_from_string() {
fn auth_key_from_string() {
let key_string = "YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ";
let auth_key_id = auth::Key::from_str(key_string);
let auth_key = auth::Key::from_str(key_string);

assert!(auth_key_id.is_ok());
assert_eq!(auth_key_id.unwrap().to_string(), key_string);
assert!(auth_key.is_ok());
assert_eq!(auth_key.unwrap().to_string(), key_string);
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions src/tracker/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ use crate::located_error::LocatedError;

#[derive(thiserror::Error, Debug, Clone)]
pub enum Error {
#[error("The supplied key: {key_id:?}, is not valid: {source}")]
#[error("The supplied key: {key:?}, is not valid: {source}")]
PeerKeyNotValid {
key_id: super::auth::Key,
key: super::auth::Key,
source: LocatedError<'static, dyn std::error::Error + Send + Sync>,
},
#[error("The peer is not authenticated, {location}")]
Expand Down
24 changes: 12 additions & 12 deletions src/tracker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,9 @@ impl Tracker {
///
/// # Panics
///
/// Will panic if key cannot be converted into a valid `KeyId`.
/// Will panic if key cannot be converted into a valid `Key`.
pub async fn remove_auth_key(&self, key: &str) -> Result<(), databases::error::Error> {
// todo: change argument `key: &str` to `key_id: &KeyId`
// todo: change argument `key: &str` to `key: &Key`
self.database.remove_key_from_keys(key).await?;
self.keys.write().await.remove(&key.parse::<Key>().unwrap());
Ok(())
Expand All @@ -211,13 +211,13 @@ impl Tracker {
/// # Errors
///
/// Will return a `key::Error` if unable to get any `auth_key`.
pub async fn verify_auth_key(&self, key_id: &Key) -> Result<(), auth::Error> {
pub async fn verify_auth_key(&self, key: &Key) -> Result<(), auth::Error> {
// code-review: this function is public only because it's used in a test.
// We should change the test and make it private.
match self.keys.read().await.get(key_id) {
match self.keys.read().await.get(key) {
None => Err(auth::Error::UnableToReadKey {
location: Location::caller(),
key_id: Box::new(key_id.clone()),
key: Box::new(key.clone()),
}),
Some(key) => auth::verify(key),
}
Expand Down Expand Up @@ -342,7 +342,7 @@ impl Tracker {
Some(key) => {
if let Err(e) = self.verify_auth_key(key).await {
return Err(Error::PeerKeyNotValid {
key_id: key.clone(),
key: key.clone(),
source: (Arc::new(e) as Arc<dyn std::error::Error + Send + Sync>).into(),
});
}
Expand Down Expand Up @@ -371,9 +371,9 @@ impl Tracker {
/// # Errors
///
/// Will return an error if the the authentication key cannot be verified.
pub async fn authenticate(&self, key_id: &Key) -> Result<(), auth::Error> {
pub async fn authenticate(&self, key: &Key) -> Result<(), auth::Error> {
if self.is_private() {
self.verify_auth_key(key_id).await
self.verify_auth_key(key).await
} else {
Ok(())
}
Expand Down Expand Up @@ -1165,9 +1165,9 @@ mod tests {
async fn it_should_fail_authenticating_a_peer_when_it_uses_an_unregistered_key() {
let tracker = private_tracker();

let unregistered_key_id = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap();
let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap();

let result = tracker.authenticate(&unregistered_key_id).await;
let result = tracker.authenticate(&unregistered_key).await;

assert!(result.is_err());
}
Expand All @@ -1187,9 +1187,9 @@ mod tests {
async fn it_should_fail_verifying_an_unregistered_authentication_key() {
let tracker = private_tracker();

let unregistered_key_id = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap();
let unregistered_key = auth::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap();

assert!(tracker.verify_auth_key(&unregistered_key_id).await.is_err());
assert!(tracker.verify_auth_key(&unregistered_key).await.is_err());
}

#[tokio::test]
Expand Down
Loading

0 comments on commit 0ee5a51

Please sign in to comment.