Skip to content

Commit

Permalink
chore: clippy pedantic
Browse files Browse the repository at this point in the history
  • Loading branch information
its-laika committed Jan 26, 2025
1 parent c78f14d commit 7868e2f
Show file tree
Hide file tree
Showing 10 changed files with 48 additions and 48 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use sea_orm_migration::{prelude::*, schema::*};
use sea_orm_migration::{
prelude::*,
schema::{blob, boolean, date_time, string, uuid},
};

#[derive(DeriveMigrationName)]
pub struct Migration;
Expand Down
16 changes: 8 additions & 8 deletions treasure_chest/src/api/routes/download.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::database::{get_downloadable_file, store_access_log};
use crate::file::{delete_file, load_encrypted_data, load_encrypted_metadata};
use crate::request::{build_header_map, get_request_ip};
use crate::file::{self, load_encrypted_data, load_encrypted_metadata};
use crate::request::{build_headers, get_request_ip};
use crate::return_logged;
use crate::util::get_validated_key;
use axum::extract::{Path, State};
Expand All @@ -20,10 +20,10 @@ pub struct RequestBody {
pub async fn handler(
State(database_connection): State<DatabaseConnection>,
id: Path<Uuid>,
header_map: HeaderMap,
headers: HeaderMap,
body: Json<RequestBody>,
) -> impl IntoResponse {
let request_ip = match get_request_ip(&header_map) {
let request_ip = match get_request_ip(&headers) {
Ok(ip) => ip,
Err(error) => return_logged!(error, StatusCode::BAD_GATEWAY),
};
Expand Down Expand Up @@ -51,14 +51,14 @@ pub async fn handler(
Err(error) => return_logged!(error, StatusCode::INTERNAL_SERVER_ERROR),
};

let header_hap = match load_encrypted_metadata(&file, &key) {
Ok(Some(metadata)) => build_header_map(&metadata),
let response_headers = match load_encrypted_metadata(&file, &key) {
Ok(Some(metadata)) => build_headers(&metadata),
_ => HeaderMap::new(),
};

if let Err(error) = delete_file(&id.to_string()) {
if let Err(error) = file::delete(&id.to_string()) {
error!("Could not delete used file {}: {:?}", id.to_string(), error);
}

Ok((header_hap, content))
Ok((response_headers, content))
}
8 changes: 4 additions & 4 deletions treasure_chest/src/api/routes/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ pub struct Response {

pub async fn handler(
State(database_connection): State<DatabaseConnection>,
header_map: HeaderMap,
headers: HeaderMap,
request: Request,
) -> impl IntoResponse {
let request_ip = match get_request_ip(&header_map) {
let request_ip = match get_request_ip(&headers) {
Ok(ip) => ip,
Err(error) => return_logged!(error, StatusCode::BAD_GATEWAY),
};
Expand All @@ -42,7 +42,7 @@ pub async fn handler(
Err(error) => return_logged!(error, StatusCode::INTERNAL_SERVER_ERROR),
};

let encrypted_metadata = match generate_encrypted_metadata(&get_metadata(&header_map), &key) {
let encrypted_metadata = match generate_encrypted_metadata(&get_metadata(&headers), &key) {
Ok(encrypted_metadata) => encrypted_metadata,
Err(error) => return_logged!(error, StatusCode::INTERNAL_SERVER_ERROR),
};
Expand All @@ -58,7 +58,7 @@ pub async fn handler(

let id = Uuid::new_v4();

if let Err(error) = store_data(encryption_data, &id.to_string()) {
if let Err(error) = store_data(&encryption_data, &id.to_string()) {
return_logged!(error, StatusCode::INTERNAL_SERVER_ERROR);
};

Expand Down
4 changes: 2 additions & 2 deletions treasure_chest/src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::{path::PathBuf, process::exit, sync::LazyLock};
pub const CONFIG_FILE_NAME: &str = "config.json";
pub const CONFIG_ENV_PREFIX: &str = "TREASURE_CHEST";

pub static CONFIGURATION: LazyLock<Configuration> = LazyLock::new(get_configuration);
pub static CONFIGURATION: LazyLock<Configuration> = LazyLock::new(build);

#[derive(Deserialize)]
struct RawConfiguration {
Expand Down Expand Up @@ -40,7 +40,7 @@ pub struct Configuration {
pub body_max_size: usize,
}

pub fn get_configuration() -> Configuration {
pub fn build() -> Configuration {
let Ok(raw) = config::Config::builder()
.add_source(File::new(CONFIG_FILE_NAME, FileFormat::Json).required(false))
.add_source(Environment::with_prefix(CONFIG_ENV_PREFIX))
Expand Down
2 changes: 1 addition & 1 deletion treasure_chest/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ pub async fn store_access_log(
ip: Set(ip.into()),
file_id: Set((*file_id).into()),
date_time: Set(Utc::now().naive_utc()),
successful: Set(if successful { 1 } else { 0 }),
successful: Set(i8::from(successful)),
};

entity::AccessLog::insert(log)
Expand Down
2 changes: 1 addition & 1 deletion treasure_chest/src/encryption/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ mod definitions;
mod xchacha20poly1305;

pub use definitions::*;
pub use xchacha20poly1305::XChaCha20Poly1305Data as EncryptionData;
pub use xchacha20poly1305::XChaCha20Poly1305Data as Data;
4 changes: 2 additions & 2 deletions treasure_chest/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ impl fmt::Debug for Error {
Self::LoadingFileFailed(inner) => write!(f, "Loading file failed: {inner}"),
Self::DeletingFileFailed(inner) => write!(f, "Removing file failed: {inner}"),
Self::ReadingBodyFailed(inner) => write!(f, "Reading body failed: {inner}"),
Self::EncryptionFailed(inner) => write!(f, "Encryption failed: {:?}", inner),
Self::DecrytpionFailed(inner) => write!(f, "Decryption failed: {:?}", inner),
Self::EncryptionFailed(inner) => write!(f, "Encryption failed: {inner:?}"),
Self::DecrytpionFailed(inner) => write!(f, "Decryption failed: {inner:?}"),
Self::KeyInvalid => write!(f, "Key invalid"),
Self::JsonSerializationFailed(inner) => write!(f, "JSON Serialization failed: {inner}"),
}
Expand Down
29 changes: 13 additions & 16 deletions treasure_chest/src/file.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::error::Error;
use crate::configuration::CONFIGURATION;
use crate::encryption::Error as EncryptionError;
use crate::encryption::{Encoding, Encryption, EncryptionData};
use crate::encryption::{self, Error as EncryptionError};
use crate::encryption::{Encoding, Encryption};
use entity::file;
use serde::{Deserialize, Serialize};
use std::io;
Expand All @@ -12,12 +12,12 @@ use std::{
};

#[derive(Serialize, Deserialize)]
pub struct FileMetadata {
pub struct Metadata {
pub file_name: String,
pub mime_type: String,
}

pub fn store_data<U, T: Encoding<U>>(content: T, base_name: &str) -> Result<PathBuf, Error> {
pub fn store_data<U, T: Encoding<U>>(content: &T, base_name: &str) -> Result<PathBuf, Error> {
let mut file_path = CONFIGURATION.file_path.clone();
file_path.push(base_name);

Expand All @@ -31,7 +31,7 @@ pub fn store_data<U, T: Encoding<U>>(content: T, base_name: &str) -> Result<Path
};

if let Err(error) = file.write_all(&content.encode()) {
delete_file(base_name)?;
delete(base_name)?;
return Err(Error::SavingFileFailed(error));
}

Expand All @@ -53,41 +53,38 @@ pub fn load_encrypted_data(base_name: &str, key: &[u8]) -> Result<Vec<u8>, Error
return Err(Error::LoadingFileFailed(error));
};

EncryptionData::decode(&content)
encryption::Data::decode(&content)
.map_err(Error::DecrytpionFailed)?
.decrypt(key)
.map_err(Error::DecrytpionFailed)
}

pub fn generate_encrypted_metadata(metadata: &FileMetadata, key: &[u8]) -> Result<Vec<u8>, Error> {
pub fn generate_encrypted_metadata(metadata: &Metadata, key: &[u8]) -> Result<Vec<u8>, Error> {
let metadata = serde_json::to_string(&metadata).map_err(Error::JsonSerializationFailed)?;

let encrypted_data = EncryptionData::encrypt_with_key(metadata.as_bytes(), key)
let encrypted_data = encryption::Data::encrypt_with_key(metadata.as_bytes(), key)
.map_err(Error::EncryptionFailed)?
.encode();

Ok(encrypted_data)
}

pub fn load_encrypted_metadata(
file: &file::Model,
key: &[u8],
) -> Result<Option<FileMetadata>, Error> {
pub fn load_encrypted_metadata(file: &file::Model, key: &[u8]) -> Result<Option<Metadata>, Error> {
let metadata_json = String::from_utf8(
EncryptionData::decode(&file.encrypted_metadata)
encryption::Data::decode(&file.encrypted_metadata)
.map_err(Error::EncryptionFailed)?
.decrypt(key)
.map_err(Error::EncryptionFailed)?,
)
.map_err(|inner| Error::EncryptionFailed(EncryptionError::InvalidData(inner.to_string())))?;

let metadata = serde_json::from_str::<FileMetadata>(&metadata_json)
.map_err(Error::JsonSerializationFailed)?;
let metadata =
serde_json::from_str::<Metadata>(&metadata_json).map_err(Error::JsonSerializationFailed)?;

Ok(Some(metadata))
}

pub fn delete_file(base_name: &str) -> Result<(), Error> {
pub fn delete(base_name: &str) -> Result<(), Error> {
let mut file_path = CONFIGURATION.file_path.clone();
file_path.push(base_name);

Expand Down
4 changes: 2 additions & 2 deletions treasure_chest/src/hash/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ pub enum Error {
impl Debug for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::HashingFailure(inner) => write!(f, "Hashing failed: {:?}", inner),
Self::VerifyingFailure(inner) => write!(f, "Verifiying failed: {:?}", inner),
Self::HashingFailure(inner) => write!(f, "Hashing failed: {inner:?}"),
Self::VerifyingFailure(inner) => write!(f, "Verifiying failed: {inner:?}"),
}
}
}
Expand Down
22 changes: 11 additions & 11 deletions treasure_chest/src/request.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::error::Error;
use crate::configuration::CONFIGURATION;
use crate::encryption::{Encryption, EncryptionData};
use crate::file::FileMetadata;
use crate::encryption::{self, Encryption};
use crate::file;
use axum::body::Body;
use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
use axum::http::HeaderMap;
Expand All @@ -15,10 +15,10 @@ static FILE_NAME_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new("filename=\"(.*?)\"").unwrap());

pub type DecryptionKey = Vec<u8>;
pub type EncryptionResult = Result<(EncryptionData, DecryptionKey), Error>;
pub type EncryptionResult = Result<(encryption::Data, DecryptionKey), Error>;

pub fn get_request_ip(header_map: &HeaderMap) -> Result<String, Error> {
return Ok(header_map
pub fn get_request_ip(headers: &HeaderMap) -> Result<String, Error> {
return Ok(headers
.get(CONFIGURATION.ip_header_name.clone())
.ok_or(Error::IpHeaderMissing(CONFIGURATION.ip_header_name.clone()))?
.to_str()
Expand All @@ -32,13 +32,13 @@ pub async fn encrypt_body(request_body: Body) -> EncryptionResult {
.map_err(Error::ReadingBodyFailed)?;

let (encryption_data, key) =
EncryptionData::encrypt(&content).map_err(Error::EncryptionFailed)?;
encryption::Data::encrypt(&content).map_err(Error::EncryptionFailed)?;

Ok((encryption_data, key))
}

pub fn get_metadata(header_map: &HeaderMap) -> FileMetadata {
let file_name = header_map
pub fn get_metadata(headers: &HeaderMap) -> file::Metadata {
let file_name = headers
.get(CONTENT_DISPOSITION)
.and_then(|header_value| header_value.to_str().map(String::from).ok())
.and_then(|header_value| {
Expand All @@ -48,17 +48,17 @@ pub fn get_metadata(header_map: &HeaderMap) -> FileMetadata {
.map(|capture| capture.as_str().to_string())
});

let mime_type = header_map
let mime_type = headers
.get(CONTENT_TYPE)
.and_then(|header_value| header_value.to_str().map(String::from).ok());

FileMetadata {
file::Metadata {
file_name: file_name.unwrap_or(Uuid::new_v4().to_string()),
mime_type: mime_type.unwrap_or(FALLBACK_CONTENT_TYPE.into()),
}
}

pub fn build_header_map(metadata: &FileMetadata) -> HeaderMap {
pub fn build_headers(metadata: &file::Metadata) -> HeaderMap {
let mut headers = HeaderMap::new();

if let Ok(content_disposition) =
Expand Down

0 comments on commit 7868e2f

Please sign in to comment.