Skip to content

Commit

Permalink
Add extra linting (#4977)
Browse files Browse the repository at this point in the history
* Add extra linting

Added extra linting for some code styles.
Also added the Rust Edition 2024 lints.

Closes #4974

Signed-off-by: BlackDex <[email protected]>

* Adjusted according to comments

Signed-off-by: BlackDex <[email protected]>

---------

Signed-off-by: BlackDex <[email protected]>
  • Loading branch information
BlackDex authored Sep 23, 2024
1 parent d184c8f commit 040e2a7
Show file tree
Hide file tree
Showing 21 changed files with 82 additions and 70 deletions.
20 changes: 10 additions & 10 deletions Cargo.lock

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

28 changes: 23 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -198,33 +198,46 @@ lto = "thin"
codegen-units = 16

# Linting config
# https://doc.rust-lang.org/rustc/lints/groups.html
[lints.rust]
# Forbid
unsafe_code = "forbid"
non_ascii_idents = "forbid"

# Deny
deprecated_in_future = "deny"
future_incompatible = { level = "deny", priority = -1 }
keyword_idents = { level = "deny", priority = -1 }
let_underscore = { level = "deny", priority = -1 }
noop_method_call = "deny"
refining_impl_trait = { level = "deny", priority = -1 }
rust_2018_idioms = { level = "deny", priority = -1 }
rust_2021_compatibility = { level = "deny", priority = -1 }
# rust_2024_compatibility = { level = "deny", priority = -1 } # Enable once we are at MSRV 1.81.0
single_use_lifetimes = "deny"
trivial_casts = "deny"
trivial_numeric_casts = "deny"
unused = { level = "deny", priority = -1 }
unused_import_braces = "deny"
unused_lifetimes = "deny"
deprecated_in_future = "deny"
unused_qualifications = "deny"
variant_size_differences = "deny"
# The lints below are part of the rust_2024_compatibility group
static-mut-refs = "deny"
unsafe-op-in-unsafe-fn = "deny"

# https://rust-lang.github.io/rust-clippy/stable/index.html
[lints.clippy]
# Allow
# We need this since Rust v1.76+, since it has some bugs
# https://github.com/rust-lang/rust-clippy/issues/12016
blocks_in_conditions = "allow"
# Warn
dbg_macro = "warn"
todo = "warn"

# Deny
case_sensitive_file_extension_comparisons = "deny"
cast_lossless = "deny"
clone_on_ref_ptr = "deny"
equatable_if_let = "deny"
filter_map_next = "deny"
float_cmp_const = "deny"
inefficient_to_string = "deny"
iter_on_empty_collections = "deny"
Expand All @@ -234,13 +247,18 @@ macro_use_imports = "deny"
manual_assert = "deny"
manual_instant_elapsed = "deny"
manual_string_new = "deny"
match_on_vec_items = "deny"
match_wildcard_for_single_variants = "deny"
mem_forget = "deny"
needless_continue = "deny"
needless_lifetimes = "deny"
option_option = "deny"
string_add_assign = "deny"
string_to_string = "deny"
unnecessary_join = "deny"
unnecessary_self_imports = "deny"
unnested_or_patterns = "deny"
unused_async = "deny"
unused_self = "deny"
verbose_file_reads = "deny"
zero_sized_map_values = "deny"
6 changes: 3 additions & 3 deletions src/api/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ fn post_admin_login(

let cookie = Cookie::build((COOKIE_NAME, jwt))
.path(admin_path())
.max_age(rocket::time::Duration::minutes(CONFIG.admin_session_lifetime()))
.max_age(time::Duration::minutes(CONFIG.admin_session_lifetime()))
.same_site(SameSite::Strict)
.http_only(true)
.secure(secure.https);
Expand Down Expand Up @@ -717,8 +717,8 @@ async fn diagnostics(_token: AdminToken, ip_header: IpHeader, mut conn: DbConn)
"db_version": get_sql_server_version(&mut conn).await,
"admin_url": format!("{}/diagnostics", admin_url()),
"overrides": &CONFIG.get_overrides().join(", "),
"host_arch": std::env::consts::ARCH,
"host_os": std::env::consts::OS,
"host_arch": env::consts::ARCH,
"host_os": env::consts::OS,
"server_time_local": Local::now().format("%Y-%m-%d %H:%M:%S %Z").to_string(),
"server_time": Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string(), // Run the server date/time check as late as possible to minimize the time difference
"ntp_time": get_ntp_time(has_http_access).await, // Run the ntp check as late as possible to minimize the time difference
Expand Down
6 changes: 3 additions & 3 deletions src/api/core/accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ pub async fn _register(data: Json<RegisterData>, mut conn: DbConn) -> JsonResult
}

if verified_by_invite && is_email_2fa_required(data.organization_user_id, &mut conn).await {
let _ = email::activate_email_2fa(&user, &mut conn).await;
email::activate_email_2fa(&user, &mut conn).await.ok();
}
}

Expand All @@ -232,7 +232,7 @@ pub async fn _register(data: Json<RegisterData>, mut conn: DbConn) -> JsonResult
// accept any open emergency access invitations
if !CONFIG.mail_enabled() && CONFIG.emergency_access_allowed() {
for mut emergency_invite in EmergencyAccess::find_all_invited_by_grantee_email(&user.email, &mut conn).await {
let _ = emergency_invite.accept_invite(&user.uuid, &user.email, &mut conn).await;
emergency_invite.accept_invite(&user.uuid, &user.email, &mut conn).await.ok();
}
}

Expand Down Expand Up @@ -1038,7 +1038,7 @@ async fn put_device_token(uuid: &str, data: Json<PushToken>, headers: Headers, m
return Ok(());
} else {
// Try to unregister already registered device
let _ = unregister_push_device(device.push_uuid).await;
unregister_push_device(device.push_uuid).await.ok();
}
// clear the push_uuid
device.push_uuid = None;
Expand Down
2 changes: 1 addition & 1 deletion src/api/core/organizations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1720,7 +1720,7 @@ async fn list_policies_token(org_id: &str, token: &str, mut conn: DbConn) -> Jso
return Ok(Json(json!({})));
}

let invite = crate::auth::decode_invite(token)?;
let invite = decode_invite(token)?;

let invite_org_id = match invite.org_id {
Some(invite_org_id) => invite_org_id,
Expand Down
4 changes: 2 additions & 2 deletions src/api/core/public.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use chrono::Utc;
use rocket::{
request::{self, FromRequest, Outcome},
request::{FromRequest, Outcome},
serde::json::Json,
Request, Route,
};
Expand Down Expand Up @@ -192,7 +192,7 @@ pub struct PublicToken(String);
impl<'r> FromRequest<'r> for PublicToken {
type Error = &'static str;

async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let headers = request.headers();
// Get access_token
let access_token: &str = match headers.get_one("Authorization") {
Expand Down
2 changes: 1 addition & 1 deletion src/api/core/two_factor/email.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ impl EmailTokenData {
}

pub fn from_json(string: &str) -> Result<EmailTokenData, Error> {
let res: Result<EmailTokenData, crate::serde_json::Error> = serde_json::from_str(string);
let res: Result<EmailTokenData, serde_json::Error> = serde_json::from_str(string);
match res {
Ok(x) => Ok(x),
Err(_) => err!("Could not decode EmailTokenData from string"),
Expand Down
2 changes: 1 addition & 1 deletion src/api/core/two_factor/protected_actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl ProtectedActionData {
}

pub fn from_json(string: &str) -> Result<Self, Error> {
let res: Result<Self, crate::serde_json::Error> = serde_json::from_str(string);
let res: Result<Self, serde_json::Error> = serde_json::from_str(string);
match res {
Ok(x) => Ok(x),
Err(_) => err!("Could not decode ProtectedActionData from string"),
Expand Down
2 changes: 1 addition & 1 deletion src/api/core/two_factor/yubikey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ fn parse_yubikeys(data: &EnableYubikeyData) -> Vec<String> {
data_keys.iter().filter_map(|e| e.as_ref().cloned()).collect()
}

fn jsonify_yubikeys(yubikeys: Vec<String>) -> serde_json::Value {
fn jsonify_yubikeys(yubikeys: Vec<String>) -> Value {
let mut result = Value::Object(serde_json::Map::new());

for (i, key) in yubikeys.into_iter().enumerate() {
Expand Down
20 changes: 10 additions & 10 deletions src/api/icons.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{
collections::HashMap,
net::IpAddr,
sync::Arc,
time::{Duration, SystemTime},
Expand Down Expand Up @@ -446,6 +447,9 @@ async fn get_page_with_referer(url: &str, referer: &str) -> Result<Response, Err
/// priority2 = get_icon_priority("https://example.com/path/to/a/favicon.ico", "");
/// ```
fn get_icon_priority(href: &str, sizes: &str) -> u8 {
static PRIORITY_MAP: Lazy<HashMap<&'static str, u8>> =
Lazy::new(|| [(".png", 10), (".jpg", 20), (".jpeg", 20)].into_iter().collect());

// Check if there is a dimension set
let (width, height) = parse_sizes(sizes);

Expand All @@ -470,13 +474,9 @@ fn get_icon_priority(href: &str, sizes: &str) -> u8 {
200
}
} else {
// Change priority by file extension
if href.ends_with(".png") {
10
} else if href.ends_with(".jpg") || href.ends_with(".jpeg") {
20
} else {
30
match href.rsplit_once('.') {
Some((_, extension)) => PRIORITY_MAP.get(&*extension.to_ascii_lowercase()).copied().unwrap_or(30),
None => 30,
}
}
}
Expand Down Expand Up @@ -623,7 +623,7 @@ use cookie_store::CookieStore;
pub struct Jar(std::sync::RwLock<CookieStore>);

impl reqwest::cookie::CookieStore for Jar {
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &header::HeaderValue>, url: &url::Url) {
fn set_cookies(&self, cookie_headers: &mut dyn Iterator<Item = &HeaderValue>, url: &url::Url) {
use cookie::{Cookie as RawCookie, ParseError as RawCookieParseError};
use time::Duration;

Expand All @@ -642,7 +642,7 @@ impl reqwest::cookie::CookieStore for Jar {
cookie_store.store_response_cookies(cookies, url);
}

fn cookies(&self, url: &url::Url) -> Option<header::HeaderValue> {
fn cookies(&self, url: &url::Url) -> Option<HeaderValue> {
let cookie_store = self.0.read().unwrap();
let s = cookie_store
.get_request_values(url)
Expand All @@ -654,7 +654,7 @@ impl reqwest::cookie::CookieStore for Jar {
return None;
}

header::HeaderValue::from_maybe_shared(Bytes::from(s)).ok()
HeaderValue::from_maybe_shared(Bytes::from(s)).ok()
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/api/notifications.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ impl WebSocketUsers {
let (user_uuid, collection_uuids, revision_date) = if let Some(collection_uuids) = collection_uuids {
(
Value::Nil,
Value::Array(collection_uuids.into_iter().map(|v| v.into()).collect::<Vec<rmpv::Value>>()),
Value::Array(collection_uuids.into_iter().map(|v| v.into()).collect::<Vec<Value>>()),
serialize_date(Utc::now().naive_utc()),
)
} else {
Expand Down
6 changes: 3 additions & 3 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ static JWT_FILE_DOWNLOAD_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|file_do
static PRIVATE_RSA_KEY: OnceCell<EncodingKey> = OnceCell::new();
static PUBLIC_RSA_KEY: OnceCell<DecodingKey> = OnceCell::new();

pub fn initialize_keys() -> Result<(), crate::error::Error> {
fn read_key(create_if_missing: bool) -> Result<(Rsa<openssl::pkey::Private>, Vec<u8>), crate::error::Error> {
pub fn initialize_keys() -> Result<(), Error> {
fn read_key(create_if_missing: bool) -> Result<(Rsa<openssl::pkey::Private>, Vec<u8>), Error> {
let mut priv_key_buffer = Vec::with_capacity(2048);

let mut priv_key_file = File::options()
Expand All @@ -53,7 +53,7 @@ pub fn initialize_keys() -> Result<(), crate::error::Error> {
Rsa::private_key_from_pem(&priv_key_buffer[..bytes_read])?
} else if create_if_missing {
// Only create the key if the file doesn't exist or is empty
let rsa_key = openssl::rsa::Rsa::generate(2048)?;
let rsa_key = Rsa::generate(2048)?;
priv_key_buffer = rsa_key.private_key_to_pem()?;
priv_key_file.write_all(&priv_key_buffer)?;
info!("Private key '{}' created correctly", CONFIG.private_rsa_key());
Expand Down
10 changes: 3 additions & 7 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1225,7 +1225,7 @@ impl Config {
}

pub fn private_rsa_key(&self) -> String {
format!("{}.pem", CONFIG.rsa_key_filename())
format!("{}.pem", self.rsa_key_filename())
}
pub fn mail_enabled(&self) -> bool {
let inner = &self.inner.read().unwrap().config;
Expand Down Expand Up @@ -1256,12 +1256,8 @@ impl Config {
token.is_some() && !token.unwrap().trim().is_empty()
}

pub fn render_template<T: serde::ser::Serialize>(
&self,
name: &str,
data: &T,
) -> Result<String, crate::error::Error> {
if CONFIG.reload_templates() {
pub fn render_template<T: serde::ser::Serialize>(&self, name: &str, data: &T) -> Result<String, Error> {
if self.reload_templates() {
warn!("RELOADING TEMPLATES");
let hb = load_templates(CONFIG.templates_folder());
hb.render(name, data).map_err(Into::into)
Expand Down
6 changes: 2 additions & 4 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,19 +300,17 @@ pub trait FromDb {

impl<T: FromDb> FromDb for Vec<T> {
type Output = Vec<T::Output>;
#[allow(clippy::wrong_self_convention)]
#[inline(always)]
fn from_db(self) -> Self::Output {
self.into_iter().map(crate::db::FromDb::from_db).collect()
self.into_iter().map(FromDb::from_db).collect()
}
}

impl<T: FromDb> FromDb for Option<T> {
type Output = Option<T::Output>;
#[allow(clippy::wrong_self_convention)]
#[inline(always)]
fn from_db(self) -> Self::Output {
self.map(crate::db::FromDb::from_db)
self.map(FromDb::from_db)
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/db/models/emergency_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ impl EmergencyAccess {
Some(user) => user,
None => {
// remove outstanding invitations which should not exist
let _ = Self::delete_all_by_grantee_email(email, conn).await;
Self::delete_all_by_grantee_email(email, conn).await.ok();
return None;
}
}
Expand Down
Loading

0 comments on commit 040e2a7

Please sign in to comment.