unuseds & cargo clippy

This commit is contained in:
2026-03-01 23:59:42 +01:00
parent e60172527c
commit f6a9807794
12 changed files with 46 additions and 39 deletions

View File

@@ -55,7 +55,7 @@ pub async fn change_handle(
let mut target = if u.id == id { let mut target = if u.id == id {
u u
} else { } else {
if u.has_permission(Permission::ChangeOthersHandles)? == false { if !u.has_permission(Permission::ChangeOthersHandles)? {
return Ok((StatusCode::FORBIDDEN, CANT_CHANGE_OTHERS_HANDLE).into_response()); return Ok((StatusCode::FORBIDDEN, CANT_CHANGE_OTHERS_HANDLE).into_response());
} }
User::get_by_id(id)? User::get_by_id(id)?
@@ -77,7 +77,7 @@ pub async fn change_password(
let mut target = if u.id == id { let mut target = if u.id == id {
u u
} else { } else {
if u.has_permission(Permission::ChangeOthersPasswords)? == false { if !u.has_permission(Permission::ChangeOthersPasswords)? {
return Ok((StatusCode::FORBIDDEN, CANT_CHANGE_OTHERS_PASSW).into_response()); return Ok((StatusCode::FORBIDDEN, CANT_CHANGE_OTHERS_PASSW).into_response());
} }
User::get_by_id(id)? User::get_by_id(id)?

View File

@@ -27,7 +27,7 @@ CREATE TABLE IF NOT EXISTS migrations (
pub struct DatabaseError(#[from] rusqlite::Error); pub struct DatabaseError(#[from] rusqlite::Error);
impl IntoResponse for DatabaseError { impl IntoResponse for DatabaseError {
fn into_response(self) -> axum::response::Response { fn into_response(self) -> axum::response::Response {
println!("[DB ERROR] {}", self.to_string()); println!("[DB ERROR] {}", self);
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error.").into_response() (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error.").into_response()
} }
} }
@@ -35,7 +35,7 @@ impl IntoResponse for DatabaseError {
pub fn conn() -> Result<Connection, rusqlite::Error> { pub fn conn() -> Result<Connection, rusqlite::Error> {
let conn = Connection::open(&*DB_URL)?; let conn = Connection::open(&*DB_URL)?;
for pragma in CONNECTION_PRAGMAS { for pragma in CONNECTION_PRAGMAS {
conn.query_row(*pragma, (), |_| Ok(())).optional()?; conn.query_row(pragma, (), |_| Ok(())).optional()?;
} }
Ok(conn) Ok(conn)
} }
@@ -43,7 +43,7 @@ pub fn conn() -> Result<Connection, rusqlite::Error> {
pub fn migrations() -> Result<(), Box<dyn Error>> { pub fn migrations() -> Result<(), Box<dyn Error>> {
let conn = Connection::open(&*DB_URL)?; let conn = Connection::open(&*DB_URL)?;
for pragma in PERSISTENT_PRAGMAS { for pragma in PERSISTENT_PRAGMAS {
conn.query_row(*pragma, (), |_| Ok(()))?; conn.query_row(pragma, (), |_| Ok(()))?;
} }
conn.execute(TABLE_MIGRATIONS, ())?; conn.execute(TABLE_MIGRATIONS, ())?;
@@ -58,7 +58,7 @@ pub fn migrations() -> Result<(), Box<dyn Error>> {
println!("Applying migration {key}..."); println!("Applying migration {key}...");
conn.execute_batch(sql)?; conn.execute_batch(sql)?;
conn.execute("INSERT INTO migrations(id) VALUES (?1)", &[key])?; conn.execute("INSERT INTO migrations(id) VALUES (?1)", [key])?;
} }
if changes { if changes {

View File

@@ -17,10 +17,10 @@ const ISE_MSG: &str = "Internal server error";
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
if let Err(e) = dotenvy::dotenv() { if let Err(e) = dotenvy::dotenv()
if !e.not_found() { && !e.not_found()
return Err(e.into()); {
} return Err(e.into());
} }
database::migrations()?; database::migrations()?;

View File

@@ -2,6 +2,7 @@ use uuid::Uuid;
use crate::persons::{Person, names::Name}; use crate::persons::{Person, names::Name};
#[allow(unused)]
pub struct QuoteLine { pub struct QuoteLine {
pub id: Uuid, pub id: Uuid,
pub attribution: (Name, Person), pub attribution: (Name, Person),

View File

@@ -5,6 +5,7 @@ use crate::quotes::lines::QuoteLine;
pub mod lines; pub mod lines;
#[allow(unused)]
pub struct Quote { pub struct Quote {
pub id: Uuid, pub id: Uuid,
pub lines: Vec<QuoteLine>, pub lines: Vec<QuoteLine>,

View File

@@ -91,15 +91,15 @@ pub struct TagName(String);
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq, Serialize)] #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq, Serialize)]
pub enum TagNameError { pub enum TagNameError {
#[error("Tag is too short - must be 2 or more characters.")] #[error("Tag is too short - must be 2 or more characters.")]
TagTooShort, TooShort,
#[error("Tag is too long - must be 24 or less characters.")] #[error("Tag is too long - must be 24 or less characters.")]
TagTooLong, TooLong,
#[error("Tag must consist of ASCII alphanumerics or mid-tag dashes only.")] #[error("Tag must consist of ASCII alphanumerics or mid-tag dashes only.")]
TagNonDashAsciiAlphanumeric, NonDashAsciiAlphanumeric,
#[error("Tag must not have a leading or trailing dash.")] #[error("Tag must not have a leading or trailing dash.")]
TagLeadingTrailingDash, LeadingTrailingDash,
#[error("Tag must not have consecutive dashes.")] #[error("Tag must not have consecutive dashes.")]
TagConsecutiveDashes, ConsecutiveDashes,
} }
impl TagName { impl TagName {
@@ -110,22 +110,22 @@ impl TagName {
} }
pub fn validate_str(str: &str) -> Result<(), TagNameError> { pub fn validate_str(str: &str) -> Result<(), TagNameError> {
match str.len() { match str.len() {
..2 => return Err(TagNameError::TagTooShort), ..2 => return Err(TagNameError::TooShort),
25.. => return Err(TagNameError::TagTooLong), 25.. => return Err(TagNameError::TooLong),
_ => (), _ => (),
}; };
if str.bytes().any(|c| !c.is_ascii_alphanumeric() && c != b'-') { if str.bytes().any(|c| !c.is_ascii_alphanumeric() && c != b'-') {
return Err(TagNameError::TagNonDashAsciiAlphanumeric); return Err(TagNameError::NonDashAsciiAlphanumeric);
} }
if str.starts_with('-') || str.ends_with('-') { if str.starts_with('-') || str.ends_with('-') {
return Err(TagNameError::TagLeadingTrailingDash); return Err(TagNameError::LeadingTrailingDash);
} }
if str if str
.as_bytes() .as_bytes()
.windows(2) .windows(2)
.any(|w| w[0] == b'-' && w[1] == b'-') .any(|w| w[0] == b'-' && w[1] == b'-')
{ {
return Err(TagNameError::TagConsecutiveDashes); return Err(TagNameError::ConsecutiveDashes);
} }
Ok(()) Ok(())
} }
@@ -184,7 +184,7 @@ impl From<TagName> for String {
impl ToSql for TagName { impl ToSql for TagName {
fn to_sql(&self) -> RusqliteResult<ToSqlOutput<'_>> { fn to_sql(&self) -> RusqliteResult<ToSqlOutput<'_>> {
Ok(self.0.to_sql()?) self.0.to_sql()
} }
} }

View File

@@ -120,7 +120,7 @@ impl<'a> AuthScheme<'a> {
impl UserAuthenticate for User { impl UserAuthenticate for User {
fn authenticate(headers: &HeaderMap) -> Result<Option<User>, AuthError> { fn authenticate(headers: &HeaderMap) -> Result<Option<User>, AuthError> {
let (basic_auth, bearer_auth) = auth_common(&headers); let (basic_auth, bearer_auth) = auth_common(headers);
match (basic_auth, bearer_auth) { match (basic_auth, bearer_auth) {
(Some(creds), _) => authenticate_basic(&creds), (Some(creds), _) => authenticate_basic(&creds),
@@ -131,7 +131,7 @@ impl UserAuthenticate for User {
} }
impl SessionAuthenticate for Session { impl SessionAuthenticate for Session {
fn authenticate(headers: &HeaderMap) -> Result<Option<Session>, AuthError> { fn authenticate(headers: &HeaderMap) -> Result<Option<Session>, AuthError> {
let (_, bearer_auth) = auth_common(&headers); let (_, bearer_auth) = auth_common(headers);
if let Some(token) = bearer_auth { if let Some(token) = bearer_auth {
authenticate_bearer_with_session(&token) authenticate_bearer_with_session(&token)
} else { } else {
@@ -203,7 +203,7 @@ pub fn authenticate_via_credentials(
false => Err(AuthError::InvalidCredentials), false => Err(AuthError::InvalidCredentials),
}, },
_ => { _ => {
let _ = User::match_hash_password(DUMMY_PASSWORD, &*DUMMY_PASSWORD_PHC)?; let _ = User::match_hash_password(DUMMY_PASSWORD, &DUMMY_PASSWORD_PHC)?;
Err(AuthError::InvalidCredentials) Err(AuthError::InvalidCredentials)
} }
} }

View File

@@ -33,7 +33,7 @@ pub trait UserPasswordHashing {
fn match_hash_password(passw: &str, hash: &str) -> Result<bool, argon2::password_hash::Error>; fn match_hash_password(passw: &str, hash: &str) -> Result<bool, argon2::password_hash::Error>;
} }
pub static SHARED_ARGON: LazyLock<Argon2> = LazyLock::new(|| Argon2::default()); pub static SHARED_ARGON: LazyLock<Argon2> = LazyLock::new(Argon2::default);
pub const DUMMY_PASSWORD: &str = "PASSWORD"; pub const DUMMY_PASSWORD: &str = "PASSWORD";
pub static DUMMY_PASSWORD_PHC: LazyLock<String> = LazyLock::new(|| { pub static DUMMY_PASSWORD_PHC: LazyLock<String> = LazyLock::new(|| {
let salt = SaltString::generate(&mut OsRng); let salt = SaltString::generate(&mut OsRng);
@@ -70,15 +70,17 @@ pub enum AuthError {
} }
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
#[allow(unused)]
pub enum TokenSize { pub enum TokenSize {
/// 5 bytes = 8 chars /// 5 bytes = 8 chars
#[allow(unused)]
Char8, Char8,
/// 10 bytes = 16 chars /// 10 bytes = 16 chars
Char16, Char16,
/// 20 bytes = 32 chars /// 20 bytes = 32 chars
#[allow(unused)]
Char32, Char32,
/// 40 bytes = 64 chars /// 40 bytes = 64 chars
#[allow(unused)]
Char64, Char64,
} }

View File

@@ -14,11 +14,11 @@ pub struct UserHandle(String);
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq, Serialize)] #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq, Serialize)]
pub enum UserHandleError { pub enum UserHandleError {
#[error("Handle is too short - must be 3 or more characters.")] #[error("Handle is too short - must be 3 or more characters.")]
HandleTooShort, TooShort,
#[error("Handle is too long - must be 16 or less characters.")] #[error("Handle is too long - must be 16 or less characters.")]
HandleTooLong, TooLong,
#[error("Handle must consist of ASCII alphanumeric characters only.")] #[error("Handle must consist of ASCII alphanumeric characters only.")]
HandleNonAsciiAlphanumeric, NonAsciiAlphanumeric,
} }
impl UserHandle { impl UserHandle {
@@ -29,12 +29,12 @@ impl UserHandle {
} }
pub fn validate_str(str: &str) -> Result<(), UserHandleError> { pub fn validate_str(str: &str) -> Result<(), UserHandleError> {
match str.len() { match str.len() {
..=2 => return Err(UserHandleError::HandleTooShort), ..=2 => return Err(UserHandleError::TooShort),
17.. => return Err(UserHandleError::HandleTooLong), 17.. => return Err(UserHandleError::TooLong),
_ => (), _ => (),
}; };
if str.bytes().any(|c| !c.is_ascii_alphanumeric()) { if str.bytes().any(|c| !c.is_ascii_alphanumeric()) {
return Err(UserHandleError::HandleNonAsciiAlphanumeric); return Err(UserHandleError::NonAsciiAlphanumeric);
} }
Ok(()) Ok(())
} }
@@ -93,7 +93,7 @@ impl From<UserHandle> for String {
impl ToSql for UserHandle { impl ToSql for UserHandle {
fn to_sql(&self) -> RusqliteResult<ToSqlOutput<'_>> { fn to_sql(&self) -> RusqliteResult<ToSqlOutput<'_>> {
Ok(self.0.to_sql()?) self.0.to_sql()
} }
} }

View File

@@ -79,10 +79,10 @@ impl User {
conn.prepare("UPDATE users SET handle = ?1 WHERE id = ?2")? conn.prepare("UPDATE users SET handle = ?1 WHERE id = ?2")?
.execute((&new_handle, self.id)) .execute((&new_handle, self.id))
.map_err(|e| { .map_err(|e| {
if let Some(e) = e.sqlite_error() { if let Some(e) = e.sqlite_error()
if e.code == ErrorCode::ConstraintViolation { && e.code == ErrorCode::ConstraintViolation
return UserError::HandleAlreadyExists(new_handle.clone()); {
} return UserError::HandleAlreadyExists(new_handle.clone());
} }
UserError::from(e) UserError::from(e)
})?; })?;

View File

@@ -13,7 +13,10 @@ pub enum Permission {
} }
impl User { impl User {
pub fn has_permission(&self, permission: Permission) -> Result<bool, DatabaseError> { pub fn has_permission(
&self,
#[allow(unused)] permission: Permission,
) -> Result<bool, DatabaseError> {
// Infradmin and systemuser have all permissions // Infradmin and systemuser have all permissions
if self.is_infradmin() || self.is_systemuser() { if self.is_infradmin() || self.is_systemuser() {
return Ok(true); return Ok(true);

View File

@@ -67,7 +67,7 @@ impl Session {
let res = database::conn()? let res = database::conn()?
.prepare("SELECT user_id, expiry, revoked, revoked_at, revoked_by FROM sessions WHERE id = ?1")? .prepare("SELECT user_id, expiry, revoked, revoked_at, revoked_by FROM sessions WHERE id = ?1")?
.query_one((&id,), |r| Ok(Session { .query_one((&id,), |r| Ok(Session {
id: id, id,
user_id: r.get(0)?, user_id: r.get(0)?,
expiry: r.get(1)?, expiry: r.get(1)?,
status: match r.get::<_, bool>(2)? { status: match r.get::<_, bool>(2)? {