Skip to content

Commit 040e2a7

Browse files
authored
Add extra linting (#4977)
* 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]>
1 parent d184c8f commit 040e2a7

21 files changed

+82
-70
lines changed

Cargo.lock

+10-10
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+23-5
Original file line numberDiff line numberDiff line change
@@ -198,33 +198,46 @@ lto = "thin"
198198
codegen-units = 16
199199

200200
# Linting config
201+
# https://doc.rust-lang.org/rustc/lints/groups.html
201202
[lints.rust]
202203
# Forbid
203204
unsafe_code = "forbid"
204205
non_ascii_idents = "forbid"
205206

206207
# Deny
208+
deprecated_in_future = "deny"
207209
future_incompatible = { level = "deny", priority = -1 }
210+
keyword_idents = { level = "deny", priority = -1 }
211+
let_underscore = { level = "deny", priority = -1 }
208212
noop_method_call = "deny"
213+
refining_impl_trait = { level = "deny", priority = -1 }
209214
rust_2018_idioms = { level = "deny", priority = -1 }
210215
rust_2021_compatibility = { level = "deny", priority = -1 }
216+
# rust_2024_compatibility = { level = "deny", priority = -1 } # Enable once we are at MSRV 1.81.0
217+
single_use_lifetimes = "deny"
211218
trivial_casts = "deny"
212219
trivial_numeric_casts = "deny"
213220
unused = { level = "deny", priority = -1 }
214221
unused_import_braces = "deny"
215222
unused_lifetimes = "deny"
216-
deprecated_in_future = "deny"
223+
unused_qualifications = "deny"
224+
variant_size_differences = "deny"
225+
# The lints below are part of the rust_2024_compatibility group
226+
static-mut-refs = "deny"
227+
unsafe-op-in-unsafe-fn = "deny"
217228

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

224235
# Deny
236+
case_sensitive_file_extension_comparisons = "deny"
225237
cast_lossless = "deny"
226238
clone_on_ref_ptr = "deny"
227239
equatable_if_let = "deny"
240+
filter_map_next = "deny"
228241
float_cmp_const = "deny"
229242
inefficient_to_string = "deny"
230243
iter_on_empty_collections = "deny"
@@ -234,13 +247,18 @@ macro_use_imports = "deny"
234247
manual_assert = "deny"
235248
manual_instant_elapsed = "deny"
236249
manual_string_new = "deny"
250+
match_on_vec_items = "deny"
237251
match_wildcard_for_single_variants = "deny"
238252
mem_forget = "deny"
253+
needless_continue = "deny"
239254
needless_lifetimes = "deny"
255+
option_option = "deny"
240256
string_add_assign = "deny"
241257
string_to_string = "deny"
242258
unnecessary_join = "deny"
243259
unnecessary_self_imports = "deny"
260+
unnested_or_patterns = "deny"
244261
unused_async = "deny"
262+
unused_self = "deny"
245263
verbose_file_reads = "deny"
246264
zero_sized_map_values = "deny"

src/api/admin.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ fn post_admin_login(
197197

198198
let cookie = Cookie::build((COOKIE_NAME, jwt))
199199
.path(admin_path())
200-
.max_age(rocket::time::Duration::minutes(CONFIG.admin_session_lifetime()))
200+
.max_age(time::Duration::minutes(CONFIG.admin_session_lifetime()))
201201
.same_site(SameSite::Strict)
202202
.http_only(true)
203203
.secure(secure.https);
@@ -717,8 +717,8 @@ async fn diagnostics(_token: AdminToken, ip_header: IpHeader, mut conn: DbConn)
717717
"db_version": get_sql_server_version(&mut conn).await,
718718
"admin_url": format!("{}/diagnostics", admin_url()),
719719
"overrides": &CONFIG.get_overrides().join(", "),
720-
"host_arch": std::env::consts::ARCH,
721-
"host_os": std::env::consts::OS,
720+
"host_arch": env::consts::ARCH,
721+
"host_os": env::consts::OS,
722722
"server_time_local": Local::now().format("%Y-%m-%d %H:%M:%S %Z").to_string(),
723723
"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
724724
"ntp_time": get_ntp_time(has_http_access).await, // Run the ntp check as late as possible to minimize the time difference

src/api/core/accounts.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ pub async fn _register(data: Json<RegisterData>, mut conn: DbConn) -> JsonResult
223223
}
224224

225225
if verified_by_invite && is_email_2fa_required(data.organization_user_id, &mut conn).await {
226-
let _ = email::activate_email_2fa(&user, &mut conn).await;
226+
email::activate_email_2fa(&user, &mut conn).await.ok();
227227
}
228228
}
229229

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

@@ -1038,7 +1038,7 @@ async fn put_device_token(uuid: &str, data: Json<PushToken>, headers: Headers, m
10381038
return Ok(());
10391039
} else {
10401040
// Try to unregister already registered device
1041-
let _ = unregister_push_device(device.push_uuid).await;
1041+
unregister_push_device(device.push_uuid).await.ok();
10421042
}
10431043
// clear the push_uuid
10441044
device.push_uuid = None;

src/api/core/organizations.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1720,7 +1720,7 @@ async fn list_policies_token(org_id: &str, token: &str, mut conn: DbConn) -> Jso
17201720
return Ok(Json(json!({})));
17211721
}
17221722

1723-
let invite = crate::auth::decode_invite(token)?;
1723+
let invite = decode_invite(token)?;
17241724

17251725
let invite_org_id = match invite.org_id {
17261726
Some(invite_org_id) => invite_org_id,

src/api/core/public.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use chrono::Utc;
22
use rocket::{
3-
request::{self, FromRequest, Outcome},
3+
request::{FromRequest, Outcome},
44
serde::json::Json,
55
Request, Route,
66
};
@@ -192,7 +192,7 @@ pub struct PublicToken(String);
192192
impl<'r> FromRequest<'r> for PublicToken {
193193
type Error = &'static str;
194194

195-
async fn from_request(request: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
195+
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
196196
let headers = request.headers();
197197
// Get access_token
198198
let access_token: &str = match headers.get_one("Authorization") {

src/api/core/two_factor/email.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ impl EmailTokenData {
292292
}
293293

294294
pub fn from_json(string: &str) -> Result<EmailTokenData, Error> {
295-
let res: Result<EmailTokenData, crate::serde_json::Error> = serde_json::from_str(string);
295+
let res: Result<EmailTokenData, serde_json::Error> = serde_json::from_str(string);
296296
match res {
297297
Ok(x) => Ok(x),
298298
Err(_) => err!("Could not decode EmailTokenData from string"),

src/api/core/two_factor/protected_actions.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ impl ProtectedActionData {
4242
}
4343

4444
pub fn from_json(string: &str) -> Result<Self, Error> {
45-
let res: Result<Self, crate::serde_json::Error> = serde_json::from_str(string);
45+
let res: Result<Self, serde_json::Error> = serde_json::from_str(string);
4646
match res {
4747
Ok(x) => Ok(x),
4848
Err(_) => err!("Could not decode ProtectedActionData from string"),

src/api/core/two_factor/yubikey.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ fn parse_yubikeys(data: &EnableYubikeyData) -> Vec<String> {
4949
data_keys.iter().filter_map(|e| e.as_ref().cloned()).collect()
5050
}
5151

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

5555
for (i, key) in yubikeys.into_iter().enumerate() {

src/api/icons.rs

+10-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::{
2+
collections::HashMap,
23
net::IpAddr,
34
sync::Arc,
45
time::{Duration, SystemTime},
@@ -446,6 +447,9 @@ async fn get_page_with_referer(url: &str, referer: &str) -> Result<Response, Err
446447
/// priority2 = get_icon_priority("https://example.com/path/to/a/favicon.ico", "");
447448
/// ```
448449
fn get_icon_priority(href: &str, sizes: &str) -> u8 {
450+
static PRIORITY_MAP: Lazy<HashMap<&'static str, u8>> =
451+
Lazy::new(|| [(".png", 10), (".jpg", 20), (".jpeg", 20)].into_iter().collect());
452+
449453
// Check if there is a dimension set
450454
let (width, height) = parse_sizes(sizes);
451455

@@ -470,13 +474,9 @@ fn get_icon_priority(href: &str, sizes: &str) -> u8 {
470474
200
471475
}
472476
} else {
473-
// Change priority by file extension
474-
if href.ends_with(".png") {
475-
10
476-
} else if href.ends_with(".jpg") || href.ends_with(".jpeg") {
477-
20
478-
} else {
479-
30
477+
match href.rsplit_once('.') {
478+
Some((_, extension)) => PRIORITY_MAP.get(&*extension.to_ascii_lowercase()).copied().unwrap_or(30),
479+
None => 30,
480480
}
481481
}
482482
}
@@ -623,7 +623,7 @@ use cookie_store::CookieStore;
623623
pub struct Jar(std::sync::RwLock<CookieStore>);
624624

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

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

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

657-
header::HeaderValue::from_maybe_shared(Bytes::from(s)).ok()
657+
HeaderValue::from_maybe_shared(Bytes::from(s)).ok()
658658
}
659659
}
660660

src/api/notifications.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ impl WebSocketUsers {
428428
let (user_uuid, collection_uuids, revision_date) = if let Some(collection_uuids) = collection_uuids {
429429
(
430430
Value::Nil,
431-
Value::Array(collection_uuids.into_iter().map(|v| v.into()).collect::<Vec<rmpv::Value>>()),
431+
Value::Array(collection_uuids.into_iter().map(|v| v.into()).collect::<Vec<Value>>()),
432432
serialize_date(Utc::now().naive_utc()),
433433
)
434434
} else {

src/auth.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ static JWT_FILE_DOWNLOAD_ISSUER: Lazy<String> = Lazy::new(|| format!("{}|file_do
3535
static PRIVATE_RSA_KEY: OnceCell<EncodingKey> = OnceCell::new();
3636
static PUBLIC_RSA_KEY: OnceCell<DecodingKey> = OnceCell::new();
3737

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

4242
let mut priv_key_file = File::options()
@@ -53,7 +53,7 @@ pub fn initialize_keys() -> Result<(), crate::error::Error> {
5353
Rsa::private_key_from_pem(&priv_key_buffer[..bytes_read])?
5454
} else if create_if_missing {
5555
// Only create the key if the file doesn't exist or is empty
56-
let rsa_key = openssl::rsa::Rsa::generate(2048)?;
56+
let rsa_key = Rsa::generate(2048)?;
5757
priv_key_buffer = rsa_key.private_key_to_pem()?;
5858
priv_key_file.write_all(&priv_key_buffer)?;
5959
info!("Private key '{}' created correctly", CONFIG.private_rsa_key());

src/config.rs

+3-7
Original file line numberDiff line numberDiff line change
@@ -1225,7 +1225,7 @@ impl Config {
12251225
}
12261226

12271227
pub fn private_rsa_key(&self) -> String {
1228-
format!("{}.pem", CONFIG.rsa_key_filename())
1228+
format!("{}.pem", self.rsa_key_filename())
12291229
}
12301230
pub fn mail_enabled(&self) -> bool {
12311231
let inner = &self.inner.read().unwrap().config;
@@ -1256,12 +1256,8 @@ impl Config {
12561256
token.is_some() && !token.unwrap().trim().is_empty()
12571257
}
12581258

1259-
pub fn render_template<T: serde::ser::Serialize>(
1260-
&self,
1261-
name: &str,
1262-
data: &T,
1263-
) -> Result<String, crate::error::Error> {
1264-
if CONFIG.reload_templates() {
1259+
pub fn render_template<T: serde::ser::Serialize>(&self, name: &str, data: &T) -> Result<String, Error> {
1260+
if self.reload_templates() {
12651261
warn!("RELOADING TEMPLATES");
12661262
let hb = load_templates(CONFIG.templates_folder());
12671263
hb.render(name, data).map_err(Into::into)

src/db/mod.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -300,19 +300,17 @@ pub trait FromDb {
300300

301301
impl<T: FromDb> FromDb for Vec<T> {
302302
type Output = Vec<T::Output>;
303-
#[allow(clippy::wrong_self_convention)]
304303
#[inline(always)]
305304
fn from_db(self) -> Self::Output {
306-
self.into_iter().map(crate::db::FromDb::from_db).collect()
305+
self.into_iter().map(FromDb::from_db).collect()
307306
}
308307
}
309308

310309
impl<T: FromDb> FromDb for Option<T> {
311310
type Output = Option<T::Output>;
312-
#[allow(clippy::wrong_self_convention)]
313311
#[inline(always)]
314312
fn from_db(self) -> Self::Output {
315-
self.map(crate::db::FromDb::from_db)
313+
self.map(FromDb::from_db)
316314
}
317315
}
318316

src/db/models/emergency_access.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ impl EmergencyAccess {
8989
Some(user) => user,
9090
None => {
9191
// remove outstanding invitations which should not exist
92-
let _ = Self::delete_all_by_grantee_email(email, conn).await;
92+
Self::delete_all_by_grantee_email(email, conn).await.ok();
9393
return None;
9494
}
9595
}

0 commit comments

Comments
 (0)