From f3c7dead973e949edbcd22a397ce67fa7bf4c8d5 Mon Sep 17 00:00:00 2001 From: mateuszpiorowski Date: Sun, 23 Apr 2023 19:46:55 +0200 Subject: [PATCH] fix-warnings --- .github/workflows/lint-server.yml | 7 +++ service-notes/src/main.rs | 2 +- service-users/src/main.rs | 2 +- service-users/src/users_service.rs | 10 ++-- service-users/src/utils.rs | 40 ------------- service-utils/src/main.rs | 9 +-- service-utils/src/utils_service.rs | 91 +++++++++++++++++------------- 7 files changed, 70 insertions(+), 91 deletions(-) diff --git a/.github/workflows/lint-server.yml b/.github/workflows/lint-server.yml index 0ea4b746..6eae969e 100644 --- a/.github/workflows/lint-server.yml +++ b/.github/workflows/lint-server.yml @@ -7,6 +7,13 @@ env: RUSTFLAGS: "-Dwarnings" jobs: + utils: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Run Clippy + run: cargo clippy --all-targets --all-features + working-directory: service-utils users: runs-on: ubuntu-latest steps: diff --git a/service-notes/src/main.rs b/service-notes/src/main.rs index 9216f7d7..ea275ec3 100644 --- a/service-notes/src/main.rs +++ b/service-notes/src/main.rs @@ -70,7 +70,7 @@ fn check_auth(mut req: Request<()>) -> Result, Status> { .parse() .map_err(|_| Status::unauthenticated("Invalid user id"))?, ); - return Ok(req); + Ok(req) } _ => Err(Status::unauthenticated("No valid auth token")), } diff --git a/service-users/src/main.rs b/service-users/src/main.rs index 68b16729..4647c6cc 100644 --- a/service-users/src/main.rs +++ b/service-users/src/main.rs @@ -77,7 +77,7 @@ fn check_auth(mut req: Request<()>) -> Result, Status> { .parse() .map_err(|_| Status::unauthenticated("Invalid user id"))?, ); - return Ok(req); + Ok(req) } _ => Err(Status::unauthenticated("No valid auth token")), } diff --git a/service-users/src/users_service.rs b/service-users/src/users_service.rs index ee8d2a3e..96ef81bc 100644 --- a/service-users/src/users_service.rs +++ b/service-users/src/users_service.rs @@ -188,7 +188,7 @@ impl UsersService for MyService { let user_id = Uuid::parse_str(&user_id).map_err(|e| Status::internal(e.to_string()))?; let row = query("select * from users where id = $1") - .bind(&user_id) + .bind(user_id) .fetch_optional(&pool) .await .map_err(sqlx::Error::into_status)?; @@ -212,21 +212,21 @@ impl UsersService for MyService { .ok_or_else(|| Status::unauthenticated("Missing user_id metadata"))? .to_str() .map_err(|e| Status::internal(e.to_string()))?; - let user_uuid = Uuid::parse_str(&user_id).map_err(|e| Status::internal(e.to_string()))?; + let user_uuid = Uuid::parse_str(user_id).map_err(|e| Status::internal(e.to_string()))?; let request = request.into_inner(); let avatar_id = request.avatar; let avatar_uuid = match avatar_id { Some(avatar_id) => Some(Uuid::try_parse(&avatar_id).map_err(|e| { - Status::invalid_argument(format!("Invalid avatar_id: {}", e.to_string())) + Status::invalid_argument(format!("Invalid avatar_id: {}", e)) })?), None => None, }; let row = query("update users set name = $1, avatar = $2 where id = $3 returning *") .bind(&request.name) - .bind(&avatar_uuid) - .bind(&user_uuid) + .bind(avatar_uuid) + .bind(user_uuid) .fetch_one(&mut tx) .await .map_err(sqlx::Error::into_status)?; diff --git a/service-users/src/utils.rs b/service-users/src/utils.rs index bb51cd94..87e06597 100644 --- a/service-users/src/utils.rs +++ b/service-users/src/utils.rs @@ -1,7 +1,4 @@ use anyhow::Result; -use jsonwebtoken::{Validation, DecodingKey, Header, encode, EncodingKey}; -use serde::{Deserialize, Serialize}; -use tonic::metadata::{MetadataMap, MetadataValue}; pub fn check_env(env_str: &str) -> Result { let env = std::env::var(env_str); @@ -13,40 +10,3 @@ pub fn check_env(env_str: &str) -> Result { )), } } - -pub fn create_auth_metadata(user_id: &String) -> Result { - let secret = check_env("SECRET")?; - let token = encode_token(user_id, secret.as_ref())?; - let metadata_value = MetadataValue::try_from("Bearer ".to_owned() + &token)?; - let mut metadata = MetadataMap::new(); - metadata.insert("authorization", metadata_value); - Ok(metadata) -} - - -#[derive(Debug, Deserialize, Serialize)] -struct Claims { - user_id: String, - exp: usize, -} - -pub fn decode_token(token: &str, secret: &[u8]) -> Result { - let validation = Validation::new(jsonwebtoken::Algorithm::HS256); - let decoding_key = DecodingKey::from_secret(secret); - let token_data = jsonwebtoken::decode::(token, &decoding_key, &validation)?; - Ok(token_data.claims.user_id) -} - -pub fn encode_token(user_id: &String, secret: &[u8]) -> Result { - let current_time = time::OffsetDateTime::now_utc(); - let claims = Claims { - user_id: user_id.to_string(), - exp: (current_time + time::Duration::hours(1)).unix_timestamp() as usize, - }; - let token = encode( - &Header::new(jsonwebtoken::Algorithm::HS256), - &claims, - &EncodingKey::from_secret(secret), - )?; - Ok(token) -} diff --git a/service-utils/src/main.rs b/service-utils/src/main.rs index 04adf453..37af6f64 100644 --- a/service-utils/src/main.rs +++ b/service-utils/src/main.rs @@ -1,6 +1,6 @@ -mod utils_service; mod proto; mod utils; +mod utils_service; use anyhow::{Context, Result}; use sqlx::{postgres::PgPoolOptions, PgPool}; @@ -40,10 +40,7 @@ async fn main() -> Result<()> { let server = MyService { pool }; let svc = UtilsServiceServer::with_interceptor(server, check_auth); - Server::builder() - .add_service(svc) - .serve(addr) - .await?; + Server::builder().add_service(svc).serve(addr).await?; Ok(()) } @@ -65,7 +62,7 @@ fn check_auth(mut req: Request<()>) -> Result, Status> { .parse() .map_err(|_| Status::unauthenticated("Invalid user id"))?, ); - return Ok(req); + Ok(req) } _ => Err(Status::unauthenticated("No valid auth token")), } diff --git a/service-utils/src/utils_service.rs b/service-utils/src/utils_service.rs index 884ac8f6..171c09b1 100644 --- a/service-utils/src/utils_service.rs +++ b/service-utils/src/utils_service.rs @@ -10,32 +10,36 @@ use tokio::sync::mpsc; use tokio_stream::wrappers::ReceiverStream; use tonic::{Request, Response, Status}; -fn map_file(row: Option) -> Result { - match row { - Some(row) => { - let id: Uuid = row.try_get("id")?; - let created: OffsetDateTime = row.try_get("created")?; - let updated: OffsetDateTime = row.try_get("updated")?; - let deleted: Option = row.try_get("deleted")?; - let target_id: Uuid = row.try_get("targetId")?; - let name: String = row.try_get("name")?; - let r#type: String = row.try_get("type")?; - let file_type = - FileType::from_str_name(&r#type).ok_or(anyhow::anyhow!("Invalid file type"))?; - - let file = File { - id: id.to_string(), - created: created.to_string(), - updated: updated.to_string(), - deleted: deleted.map(|d| d.to_string()), - target_id: target_id.to_string(), - name: name.to_string(), - r#type: file_type.into(), - buffer: Vec::new(), - }; - return Ok(file); +impl TryFrom> for File { + type Error = anyhow::Error; + + fn try_from(row: Option) -> Result { + match row { + Some(row) => { + let id: Uuid = row.try_get("id")?; + let created: OffsetDateTime = row.try_get("created")?; + let updated: OffsetDateTime = row.try_get("updated")?; + let deleted: Option = row.try_get("deleted")?; + let target_id: Uuid = row.try_get("targetId")?; + let name: String = row.try_get("name")?; + let r#type: String = row.try_get("type")?; + let file_type = + FileType::from_str_name(&r#type).ok_or(anyhow::anyhow!("Invalid file type"))?; + + let file = File { + id: id.to_string(), + created: created.to_string(), + updated: updated.to_string(), + deleted: deleted.map(|d| d.to_string()), + target_id: target_id.to_string(), + name, + r#type: file_type.into(), + buffer: Vec::new(), + }; + Ok(file) + } + None => Err(anyhow::anyhow!("File not found")), } - None => Err(anyhow::anyhow!("File not found")), } } @@ -62,8 +66,8 @@ impl UtilsService for MyService { tokio::spawn(async move { let mut files_stream = query("SELECT * FROM files WHERE \"targetId\" = $1 and type = $2 and deleted is null order by created desc") - .bind(&target_uuid) - .bind(&r#type) + .bind(target_uuid) + .bind(r#type) .fetch(&pool); loop { @@ -74,7 +78,7 @@ impl UtilsService for MyService { break; } Ok(file) => { - let mut file = match map_file(file) { + let mut file: File = match file.try_into() { Ok(file) => file, Err(e) => { tx.send(Err(Status::internal(e.to_string()))).await.unwrap(); @@ -115,12 +119,17 @@ impl UtilsService for MyService { Uuid::parse_str(&request.target_id).map_err(|e| Status::internal(e.to_string()))?; let row = query("SELECT * FROM files WHERE id = $1 and \"targetId\" = $2 and deleted is null") - .bind(&uuid) - .bind(&target_uuid) + .bind(uuid) + .bind(target_uuid) .fetch_one(&pool) .await .map_err(|e| Status::internal(e.to_string()))?; - let mut file = map_file(Some(row)).map_err(|e| Status::internal(e.to_string()))?; + + let mut file: File = match Some(row).try_into() { + Ok(file) => file, + Err(e) => return Err(Status::internal(e.to_string())), + }; + let file_path = format!("/app/files/{}/{}", &file.id, &file.name); let buffer = std::fs::read(file_path).unwrap(); file.buffer = buffer; @@ -154,13 +163,16 @@ impl UtilsService for MyService { // save file to db let row = query("INSERT INTO files (\"targetId\", name, type) VALUES ($1, $2, $3) RETURNING *") - .bind(&uuid) - .bind(&file.name) - .bind(&r#type) + .bind(uuid) + .bind(file.name) + .bind(r#type) .fetch_one(&mut tx) .await .map_err(|e| Status::internal(e.to_string()))?; - let file = map_file(Some(row)).map_err(|e| Status::internal(e.to_string()))?; + let file: File = match Some(row).try_into() { + Ok(file) => file, + Err(e) => return Err(Status::internal(e.to_string())), + }; // save file to disk let file_path = format!("/app/files/{}/{}", file.id, file.name); @@ -196,8 +208,8 @@ impl UtilsService for MyService { let row = query( "UPDATE files SET deleted = now() WHERE id = $1 and \"targetId\" = $2 RETURNING *", ) - .bind(&file_id) - .bind(&target_id) + .bind(file_id) + .bind(target_id) .fetch_one(&mut tx) .await .map_err(|e| Status::not_found(e.to_string()))?; @@ -205,7 +217,10 @@ impl UtilsService for MyService { // delete file from disk tokio::fs::remove_dir_all(format!("/app/files/{}", file_id)).await?; - let file = map_file(Some(row)).map_err(|e| Status::internal(e.to_string()))?; + let file: File = match Some(row).try_into() { + Ok(file) => file, + Err(e) => return Err(Status::internal(e.to_string())), + }; // commit transaction tx.commit()