Skip to content

Commit

Permalink
fix clippy lints
Browse files Browse the repository at this point in the history
Signed-off-by: simonsan <[email protected]>
  • Loading branch information
simonsan committed Nov 14, 2024
1 parent e80cb0d commit 880550a
Show file tree
Hide file tree
Showing 23 changed files with 110 additions and 124 deletions.
8 changes: 3 additions & 5 deletions src/acl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn init_acl(acl: Acl) -> AppResult<()> {
///
// IMPORTANT: The order of the variants is important, as it is used
// to determine the access level! Don't change it!
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize, Copy)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Serialize, Deserialize, Copy)]
pub enum AccessType {
/// No access
NoAccess,
Expand Down Expand Up @@ -205,9 +205,7 @@ impl AclChecker for Acl {
access_type
};

if let Some(repo_acl) = self.repos.get(path) {
matches!(repo_acl.get(user), Some(user_access) if user_access >= &access)
} else {
self.repos.get(path).map_or_else(|| {
let is_user_path = user == path;
let is_not_private_repo = !self.private_repo;
let is_not_modify_access = access != AccessType::Modify;
Expand All @@ -220,7 +218,7 @@ impl AclChecker for Acl {
// If the user is the path, and the repo is not private, or the user has modify access
// or the repo is not append only, then allow the access
(is_user_path || is_not_private_repo) && (is_not_modify_access || is_not_append_only)
}
}, |repo_acl| matches!(repo_acl.get(user), Some(user_access) if user_access >= &access))
}
}

Expand Down
7 changes: 3 additions & 4 deletions src/application.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! RusticServer Abscissa Application
//! `RusticServer` Abscissa Application
use crate::{commands::EntryPoint, config::RusticServerConfig};
use abscissa_core::{
Expand All @@ -11,7 +11,7 @@ use abscissa_tokio::TokioComponent;
/// Application state
pub static RUSTIC_SERVER_APP: AppCell<RusticServerApp> = AppCell::new();

/// RusticServer Application
/// `RusticServer` Application
#[derive(Debug)]
pub struct RusticServerApp {
/// Application configuration.
Expand Down Expand Up @@ -75,8 +75,7 @@ impl Application for RusticServerApp {
/// possible.
fn after_config(&mut self, config: Self::Cfg) -> Result<(), FrameworkError> {
// Configure components
let mut components = self.state.components_mut();
components.after_config(&config)?;
self.state.components_mut().after_config(&config)?;
self.config.set_once(config);
Ok(())
}
Expand Down
13 changes: 4 additions & 9 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,7 @@ impl Auth {
let user = user.into();
let passwd = passwd.into();

match &self.users {
Some(users) => {
matches!(users.get(&user), Some(passwd_data) if htpasswd_verify::Htpasswd::from(passwd_data.to_string().borrow()).check(user, passwd))
}
None => true,
}
self.users.as_ref().map_or(true, |users| matches!(users.get(&user), Some(passwd_data) if htpasswd_verify::Htpasswd::from(passwd_data.to_string().borrow()).check(user, passwd)))
}
}

Expand All @@ -90,7 +85,7 @@ impl<S: Send + Sync> FromRequestParts<S> for AuthFromRequest {
return match auth_result {
Ok(auth) => {
let AuthBasic((user, passw)) = auth;
let password = passw.unwrap_or_else(|| "".to_string());
let password = passw.unwrap_or_else(String::new);
if checker.verify(user.as_str(), password.as_str()) {
Ok(Self {
user,
Expand All @@ -101,11 +96,11 @@ impl<S: Send + Sync> FromRequestParts<S> for AuthFromRequest {
}
}
Err(_) => {
let user = "".to_string();
let user = String::new();
if checker.verify("", "") {
return Ok(Self {
user,
_password: "".to_string().into(),
_password: String::new().into(),
});
}
Err(ApiErrorKind::AuthenticationHeaderError)
Expand Down
8 changes: 4 additions & 4 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! RusticServer Subcommands
//! `RusticServer` Subcommands
//!
//! This is where you specify the subcommands of your application.
//!
Expand All @@ -24,10 +24,10 @@ use clap::builder::{
};
use std::path::PathBuf;

/// RusticServer Configuration Filename
/// `RusticServer` Configuration Filename
pub const CONFIG_FILE: &str = "rustic_server.toml";

/// RusticServer Subcommands
/// `RusticServer` Subcommands
/// Subcommands need to be listed in an enum.
#[derive(clap::Parser, Command, Debug, Runnable)]
pub enum RusticServerCmd {
Expand Down Expand Up @@ -65,7 +65,7 @@ pub struct EntryPoint {

impl Runnable for EntryPoint {
fn run(&self) {
self.cmd.run()
self.cmd.run();
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/commands/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ fn delete(arg: &DelArg) -> Result<()> {
println!(
"Could not find a user with name {}. No changes were made.",
arg.user.as_str()
)
);
};
Ok(())
}
Expand Down
6 changes: 3 additions & 3 deletions src/commands/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,13 @@ impl ServeCmd {
if !data_dir.exists() {
debug!("Creating data directory: {:?}", data_dir);

std::fs::create_dir_all(&data_dir).map_err(|err| {
std::fs::create_dir_all(data_dir).map_err(|err| {
ErrorKind::GeneralStorageError
.context(format!("Could not create data directory: {}", err))
})?;
}

let storage = LocalStorage::try_new(&data_dir).map_err(|err| {
let storage = LocalStorage::try_new(data_dir).map_err(|err| {
ErrorKind::GeneralStorageError.context(format!("Could not create storage: {}", err))
})?;

Expand All @@ -108,7 +108,7 @@ impl ServeCmd {

info!("[serve] Starting web server ...");

let _ = tokio::spawn(async move {
_ = tokio::spawn(async move {
tokio::signal::ctrl_c().await.unwrap();
info!("[serve] Shutting down ...");
RUSTIC_SERVER_APP.shutdown(Shutdown::Graceful);
Expand Down
8 changes: 4 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! RusticServer Config
//! `RusticServer` Config
//!
//! See instructions in `commands.rs` to specify the path to your
//! application's configuration file and/or command-line options
Expand All @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};

use crate::error::{AppResult, ErrorKind};

/// RusticServer Configuration
/// `RusticServer` Configuration
#[derive(Clone, Debug, Deserialize, Serialize, Default, Merge, Parser)]
#[serde(deny_unknown_fields, rename_all = "kebab-case", default)]
pub struct RusticServerConfig {
Expand Down Expand Up @@ -78,7 +78,7 @@ pub struct LogSettings {
}

impl LogSettings {
pub fn is_disabled(&self) -> bool {
pub const fn is_disabled(&self) -> bool {
self.log_file.is_none()
}
}
Expand Down Expand Up @@ -152,7 +152,7 @@ impl HtpasswdSettings {
})
}

pub fn is_disabled(&self) -> bool {
pub const fn is_disabled(&self) -> bool {
self.disable_auth
}
}
Expand Down
62 changes: 29 additions & 33 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,104 +94,100 @@ pub enum ApiErrorKind {
impl IntoResponse for ApiErrorKind {
fn into_response(self) -> Response {
let response = match self {
ApiErrorKind::InvalidApiVersion(err) => (
Self::InvalidApiVersion(err) => (
StatusCode::BAD_REQUEST,
format!("Invalid API version: {err}"),
),
ApiErrorKind::InternalError(err) => (
Self::InternalError(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Internal server error: {}", err),
),
ApiErrorKind::BadRequest(err) => (
Self::BadRequest(err) => (
StatusCode::BAD_REQUEST,
format!("Internal server error: {}", err),
),
ApiErrorKind::FilenameNotAllowed(filename) => (
Self::FilenameNotAllowed(filename) => (
StatusCode::FORBIDDEN,
format!("filename {filename} not allowed"),
),
ApiErrorKind::AmbiguousPath(path) => (
Self::AmbiguousPath(path) => (
StatusCode::FORBIDDEN,
format!("path {path} is ambiguous with internal types and not allowed"),
),
ApiErrorKind::PathNotAllowed(path) => {
Self::PathNotAllowed(path) => {
(StatusCode::FORBIDDEN, format!("path {path} not allowed"))
}
ApiErrorKind::NonUnicodePath(path) => (
Self::NonUnicodePath(path) => (
StatusCode::BAD_REQUEST,
format!("path {path} is not valid unicode"),
),
ApiErrorKind::InvalidPath(path) => {
Self::InvalidPath(path) => {
(StatusCode::BAD_REQUEST, format!("path {path} is not valid"))
}
ApiErrorKind::CreatingDirectoryFailed(err) => (
Self::CreatingDirectoryFailed(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("error creating dir: {:?}", err),
),
ApiErrorKind::NotImplemented => (
Self::NotImplemented => (
StatusCode::NOT_IMPLEMENTED,
"not yet implemented".to_string(),
),
ApiErrorKind::FileNotFound(path) => {
(StatusCode::NOT_FOUND, format!("file not found: {path}"))
}
ApiErrorKind::GettingFileMetadataFailed(err) => (
Self::FileNotFound(path) => (StatusCode::NOT_FOUND, format!("file not found: {path}")),
Self::GettingFileMetadataFailed(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("error getting file metadata: {err}"),
),
ApiErrorKind::RangeNotValid => (StatusCode::BAD_REQUEST, "range not valid".to_string()),
ApiErrorKind::SeekingFileFailed => (
Self::RangeNotValid => (StatusCode::BAD_REQUEST, "range not valid".to_string()),
Self::SeekingFileFailed => (
StatusCode::INTERNAL_SERVER_ERROR,
"error seeking file".to_string(),
),
ApiErrorKind::MultipartRangeNotImplemented => (
Self::MultipartRangeNotImplemented => (
StatusCode::NOT_IMPLEMENTED,
"multipart range not implemented".to_string(),
),
ApiErrorKind::ConversionToU64Failed => (
Self::ConversionToU64Failed => (
StatusCode::INTERNAL_SERVER_ERROR,
"error converting length to u64".to_string(),
),
ApiErrorKind::OpeningFileFailed(err) => (
Self::OpeningFileFailed(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("error opening file: {err}"),
),
ApiErrorKind::WritingToFileFailed(err) => (
Self::WritingToFileFailed(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("error writing file: {err}"),
),
ApiErrorKind::FinalizingFileFailed(err) => (
Self::FinalizingFileFailed(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("error finalizing file: {err}"),
),
ApiErrorKind::GettingFileHandleFailed => (
Self::GettingFileHandleFailed => (
StatusCode::INTERNAL_SERVER_ERROR,
"error getting file handle".to_string(),
),
ApiErrorKind::RemovingFileFailed(err) => (
Self::RemovingFileFailed(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("error removing file: {err}"),
),
ApiErrorKind::GeneralRange => {
(StatusCode::INTERNAL_SERVER_ERROR, "range error".to_string())
}
ApiErrorKind::ReadingFromStreamFailed => (
Self::GeneralRange => (StatusCode::INTERNAL_SERVER_ERROR, "range error".to_string()),
Self::ReadingFromStreamFailed => (
StatusCode::INTERNAL_SERVER_ERROR,
"error reading from stream".to_string(),
),
ApiErrorKind::RemovingRepositoryFailed(err) => (
Self::RemovingRepositoryFailed(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("error removing repository folder: {:?}", err),
),
ApiErrorKind::AuthenticationHeaderError => (
Self::AuthenticationHeaderError => (
StatusCode::FORBIDDEN,
"Bad authentication header".to_string(),
),
ApiErrorKind::UserAuthenticationError(err) => (
Self::UserAuthenticationError(err) => (
StatusCode::FORBIDDEN,
format!("Failed to authenticate user: {:?}", err),
),
ApiErrorKind::GeneralStorageError(err) => (
Self::GeneralStorageError(err) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("Storage error: {:?}", err),
),
Expand All @@ -203,7 +199,7 @@ impl IntoResponse for ApiErrorKind {

impl ErrorKind {
/// Create an error context from this error
pub fn context(self, source: impl Into<BoxError>) -> Context<ErrorKind> {
pub fn context(self, source: impl Into<BoxError>) -> Context<Self> {
Context::new(self, Some(source.into()))
}
}
Expand Down Expand Up @@ -240,7 +236,7 @@ impl From<ErrorKind> for Error {

impl From<Context<ErrorKind>> for Error {
fn from(context: Context<ErrorKind>) -> Self {
Error(Box::new(context))
Self(Box::new(context))
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/handlers/access_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
typed_path::TpeKind,
};

pub(crate) fn check_auth_and_acl(
pub fn check_auth_and_acl(
user: String,
tpe: impl Into<Option<TpeKind>>,
path: &Path,
Expand Down
16 changes: 8 additions & 8 deletions src/handlers/file_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use crate::{
/// has_config
/// Interface: HEAD {repo}/config
#[debug_handler]
pub(crate) async fn has_config(
pub async fn has_config(
RepositoryConfigPath { repo }: RepositoryConfigPath,
AuthFromRequest { user, .. }: AuthFromRequest,
) -> ApiResult<impl IntoResponse> {
Expand Down Expand Up @@ -53,9 +53,9 @@ pub(crate) async fn has_config(
}
}

/// get_config
/// `get_config`
/// Interface: GET {repo}/config
pub(crate) async fn get_config<P: PathParts>(
pub async fn get_config<P: PathParts>(
path: P,
auth: AuthFromRequest,
range: Option<TypedHeader<Range>>,
Expand All @@ -81,9 +81,9 @@ pub(crate) async fn get_config<P: PathParts>(
Ok(Ranged::new(range, body).into_response())
}

/// add_config
/// `add_config`
/// Interface: POST {repo}/config
pub(crate) async fn add_config<P: PathParts>(
pub async fn add_config<P: PathParts>(
path: P,
auth: AuthFromRequest,
request: Request,
Expand All @@ -92,17 +92,17 @@ pub(crate) async fn add_config<P: PathParts>(
let repo = path.repo().unwrap();
tracing::debug!("[add_config] repository path: {repo}, tpe: {tpe}");
let path = PathBuf::from(&repo);
let file = get_save_file(auth.user, path, tpe, None).await?;
let file = get_save_file(auth.user, path, Some(tpe), None).await?;

let stream = request.into_body().into_data_stream();
let _ = save_body(file, stream).await?;
Ok(())
}

/// delete_config
/// `delete_config`
/// Interface: DELETE {repo}/config
#[allow(dead_code)]
pub(crate) async fn delete_config<P: PathParts>(
pub async fn delete_config<P: PathParts>(
path: P,
auth: AuthFromRequest,
) -> ApiResult<impl IntoResponse> {
Expand Down
Loading

0 comments on commit 880550a

Please sign in to comment.