Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unwraps removed #224

Merged
merged 5 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions database/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub struct Db {
}

impl Db {
// CHECK THIS
pub async fn connect_to_the_pool() -> Db {
dotenvy::from_filename("infra/.env").unwrap();

Expand Down
3 changes: 2 additions & 1 deletion database/src/tables/requests/table_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ impl FromRow<'_, PgRow> for Request {
Ok(Request {
request_id: row.get("request_id"),
app_id: row.get("app_id"),
request_type: RequestType::from_str(row.get("request_type")).unwrap(),
request_type: RequestType::from_str(row.get("request_type"))
.map_err(|_| sqlx::Error::Decode(format!("Invalid request_type")))?,
session_id: row.get("session_id"),
request_status: row.get("request_status"),
dzlk17 marked this conversation as resolved.
Show resolved Hide resolved
network: row.get("network"),
Expand Down
10 changes: 8 additions & 2 deletions database/src/tables/sessions/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ impl Db {
ip_address: &String,
current_time: &DateTime<Utc>,
) -> Result<(), DbError> {
let mut tx = self.connection_pool.begin().await.unwrap();
let mut tx = match self.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => return Err(err.into()),
};

// 1. Save the new session
if let Err(err) = self.save_new_session(&mut tx, &session).await {
Expand Down Expand Up @@ -116,7 +119,10 @@ impl Db {
session_id: &String,
) -> Result<(), DbError> {
// Start a new transaction
let mut tx = self.connection_pool.begin().await.unwrap();
let mut tx = match self.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => return Err(err.into()),
};

// User can't connect to the session without any connected keys
if connected_keys.is_empty() {
Expand Down
17 changes: 15 additions & 2 deletions database/src/tables/utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
use log::error;
use sqlx::types::chrono::{DateTime, TimeZone, Utc};
use std::time::{SystemTime, UNIX_EPOCH};

pub fn get_timestamp_in_milliseconds() -> u64 {
let now = SystemTime::now();
let since_the_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
let since_the_epoch = match now.duration_since(UNIX_EPOCH) {
dzlk17 marked this conversation as resolved.
Show resolved Hide resolved
Ok(duration) => duration,
Err(err) => {
error!(
"Error getting timestamp in milliseconds: {}. Time went backwards",
err
);
return 0;
}
};
since_the_epoch.as_millis() as u64
}

Expand All @@ -17,7 +27,10 @@ pub fn get_current_datetime() -> DateTime<Utc> {

pub fn to_microsecond_precision(datetime: &DateTime<Utc>) -> DateTime<Utc> {
dzlk17 marked this conversation as resolved.
Show resolved Hide resolved
// Should never fail as we are converting from a valid DateTime<Utc>
Utc.timestamp_micros(datetime.timestamp_micros()).unwrap()
match Utc.timestamp_micros(datetime.timestamp_micros()) {
chrono::LocalResult::Single(dt) => dt,
_ => get_current_datetime(),
}
}

// This function is used to format the keys of a table to be used in a view query
Expand Down
1 change: 1 addition & 0 deletions server/src/cloud_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ pub struct CloudState {
pub grafana_client_conf: Arc<Configuration>,
}

// CHECK THIS
impl CloudState {
pub async fn new() -> Self {
let sessions_cache = get_new_session();
Expand Down
1 change: 1 addition & 0 deletions server/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub struct ENV {
pub GF_SECURITY_ADMIN_PASSWORD: String,
pub MAILER_ACTIVE: bool,
}
// CHECK THIS
pub fn get_env() -> &'static ENV {
static INSTANCE: OnceCell<ENV> = OnceCell::new();

Expand Down
18 changes: 13 additions & 5 deletions server/src/http/cloud/change_user_privileges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,17 @@ pub async fn change_user_privileges(
// Update users privileges
for requested_change in request.privileges_changes {
// Determine action
let new_privilege_level = requested_change.new_privilege_level.to_privilege_level();
let new_privilege_level =
match requested_change.new_privilege_level.to_privilege_level() {
Some(privilege) => privilege,
None => {
error!("Failed to convert new privilege level");
return Err((
StatusCode::BAD_REQUEST,
CloudApiErrors::InternalServerError.to_string(),
));
}
};
let user_id = user_ids.get(&requested_change.user_email).ok_or((
StatusCode::BAD_REQUEST,
CloudApiErrors::UserDoesNotExist.to_string(),
Expand All @@ -158,8 +168,7 @@ pub async fn change_user_privileges(
&mut tx,
user_id,
&requested_change.app_id,
// Safe unwrap
new_privilege_level.unwrap(),
new_privilege_level,
)
.await
.map_err(|err| {
Expand Down Expand Up @@ -212,8 +221,7 @@ pub async fn change_user_privileges(
&mut tx,
user_id,
&requested_change.app_id,
// Safe unwrap
new_privilege_level.unwrap(),
new_privilege_level,
)
.await
.map_err(|err| {
Expand Down
11 changes: 10 additions & 1 deletion server/src/http/cloud/delete_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,16 @@ pub async fn delete_app(
}
// Delete the app
// Start a transaction
let mut tx = db.connection_pool.begin().await.unwrap();
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};

if let Err(err) = db
.remove_privileges_for_inactive_app_within_tx(&mut tx, &request.app_id)
Expand Down
11 changes: 10 additions & 1 deletion server/src/http/cloud/delete_team.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,16 @@ pub async fn delete_team(
validate_request(&request, &())?;
warn!("Delete team request: {:?}", request);
// Start a transaction
let mut tx = db.connection_pool.begin().await.unwrap();
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};

// First check if team exists
let team = match db.get_team_by_team_id(None, &request.team_id).await {
Expand Down
11 changes: 10 additions & 1 deletion server/src/http/cloud/domains/remove_whitelisted_domain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,16 @@ pub async fn remove_whitelisted_domain(
));
}

let mut tx = db.connection_pool.begin().await.unwrap();
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};

// Remove domain from whitelisted domains
if let Err(err) = db
Expand Down
16 changes: 14 additions & 2 deletions server/src/http/cloud/domains/verify_domain_finish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,16 @@ pub async fn verify_domain_finish(
}

// Add domain to whitelist
let mut tx = db.connection_pool.begin().await.unwrap();
let mut tx = match db.connection_pool.begin().await {
dzlk17 marked this conversation as resolved.
Show resolved Hide resolved
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};

if let Err(err) = db
.add_new_whitelisted_domain(&mut tx, &request.app_id, &domain_name)
Expand Down Expand Up @@ -249,7 +258,10 @@ async fn check_verification_code(
let txt_data = txt.txt_data();
// Each TXT record can contain multiple strings, so we iterate through them all
for txt_str in txt_data {
let txt_str = std::str::from_utf8(txt_str).unwrap();
let txt_str = match std::str::from_utf8(txt_str) {
Ok(txt_str) => txt_str,
Err(err) => bail!("Failed to parse TXT record: {:?}", err),
};
// Check if the verification code is present
if txt_str.contains(&code) {
return Ok(());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,16 @@ pub async fn process_event_app_connect(
}
} else {
// Reconnection to an existing session
let mut tx = db.connection_pool.begin().await.unwrap();
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!(
"Failed to create new transaction to save app connection event, app_id: [{}], event: [{:?}], err: [{}]",
app_id, event, err
);
return;
}
};

// Get the geolocation data
let geo_location_data = get_geolocation_data(&db, &geo_loc_requester, &ip).await;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,16 @@ pub async fn process_event_client_connect_init(
save_event_client_connect(db, app_id, network, event, &current_time).await;

// Save connection attempt by client
let mut tx = db.connection_pool.begin().await.unwrap();
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!(
"Failed to create new transaction to save client connect event, app_id: [{}], event: [{:?}], err: [{}]",
app_id, event, err
);
return;
}
};

// Get the geolocation data
let geo_location_data = get_geolocation_data(&db, &geo_loc_requester, &ip).await;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,16 @@ pub async fn process_event_client_disconnect(
save_event_client_disconnect(db, app_id, network, event, &current_timestamp).await;

// Update connection status for user
let mut tx = db.connection_pool.begin().await.unwrap();
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!(
"Failed to create new transaction to update client disconnect status, app_id: [{}], event: [{:?}], err: [{}]",
app_id, event, err
);
return;
}
};

match db
.close_client_connection(&mut tx, &app_id, &event.disconnected_session_id)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use openapi::{
use serde_json::Value;
use std::{env, sync::Arc};
use tokio::fs;

// CHECK THIS - used only at the begginning - better to have error
pub async fn setup_templates_dashboard(
grafana_conf: &Arc<Configuration>,
) -> Result<(), (StatusCode, String)> {
Expand Down
11 changes: 10 additions & 1 deletion server/src/http/cloud/register_new_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,16 @@ pub async fn register_new_app(

// Register a new app under this team
// Start a transaction
let mut tx = db.connection_pool.begin().await.unwrap();
let mut tx = match db.connection_pool.begin().await {
Ok(tx) => tx,
Err(err) => {
error!("Failed to start transaction: {:?}", err);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
CloudApiErrors::DatabaseError.to_string(),
));
}
};

// Register a new app
let db_registered_app =
Expand Down
1 change: 1 addition & 0 deletions server/src/infra_env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pub struct INFRA_ENV {
pub OFELIA_EMAIL_TO: String,
}

// CHECK THIS
pub fn get_env() -> &'static INFRA_ENV {
static INSTANCE: OnceCell<INFRA_ENV> = OnceCell::new();

Expand Down
2 changes: 1 addition & 1 deletion server/src/mailer/mailer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub struct Mailer {
pub templates: Arc<HashMap<Templates, String>>,
pub mailbox: Mailbox,
}

// CHECK THIS
impl Mailer {
pub async fn init(username: String, password: String) -> Self {
let creds = Credentials::new(username.clone(), password);
Expand Down
22 changes: 18 additions & 4 deletions server/src/sesssion_cleaner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
utils::get_timestamp_in_milliseconds,
};
use futures::SinkExt;
use log::info;
use log::{error, info};
use std::{collections::HashMap, time::Duration, vec};

pub fn start_cleaning_sessions(
Expand Down Expand Up @@ -78,12 +78,26 @@ pub fn start_cleaning_sessions(

// Remove all sessions that expired
for (app_id, session_id) in sessions_to_remove {
// safe unwrap because we just checked if the session exists
let app_sessions = sessions_write.get_mut(&app_id).unwrap();
let app_sessions = match sessions_write.get_mut(&app_id) {
Some(app_sessions) => app_sessions,
None => {
error!("App: [{}] does not have any sessions", app_id);
return;
}
};
let mut app_sessions_write = app_sessions.write().await;

for session_id in session_id {
let session = app_sessions_write.get_mut(&session_id).unwrap();
let session = match app_sessions_write.get_mut(&session_id) {
Some(session) => session,
None => {
error!(
"App: [{}] does not have session with id: [{}]",
app_id, session_id
);
return;
}
};
let mut session_write = session.write().await;

// Remove session from client_to_sessions
Expand Down
15 changes: 11 additions & 4 deletions server/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use axum::extract::{
};
use database::db::Db;
use futures::{stream::SplitSink, SinkExt};
use log::info;
use log::{error, info};
use openapi::apis::configuration::Configuration;
use std::{
collections::{HashMap, HashSet},
Expand All @@ -41,6 +41,7 @@ pub struct ServerState {
pub cloud_state: Option<Arc<CloudState>>,
}

// CHECK THIS
impl FromRef<ServerState> for Arc<Db> {
fn from_ref(state: &ServerState) -> Self {
// Safe as middleware will prevent this from being None
Expand Down Expand Up @@ -125,12 +126,18 @@ impl SendToClient for ClientSockets {
match self.read().await.get(&client_id) {
Some(client_socket) => {
info!("Send to client {}, msg: {:?}", client_id, msg);
let serialized_msg = match serde_json::to_string(&msg) {
Ok(serialized_msg) => serialized_msg,
Err(err) => {
error!("Failed to serialize message: {:?}", err);
return Err(anyhow::anyhow!("Failed to serialize message: {:?}", err));
}
};

return Ok(client_socket
.write()
.await
.send(Message::Text(
serde_json::to_string(&msg).expect("Serialization should work"),
))
.send(Message::Text(serialized_msg))
.await?);
}
None => Err(anyhow::anyhow!("No client socket found for session")),
Expand Down
1 change: 1 addition & 0 deletions server/src/statics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub const TEMPLATES_FOLDER_UID: &str = "TEMPLATE_FOLDER_UID";
pub const POSTGRES_DATASOURCE_UID: &str = "POSTGRES_DATASOURCE_UID";

// Name must be 3-30 characters long and include only alphanumeric characters, underscores, or slashes.
// CHECK THIS - all regex creation
pub static NAME_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^[a-zA-Z0-9_-]{3,30}$").expect("Regex creation failed"));

Expand Down
Loading