Skip to content

Commit

Permalink
chore: update deps & use moka sync & remove auth feature
Browse files Browse the repository at this point in the history
Signed-off-by: Martichou <[email protected]>
  • Loading branch information
Martichou committed Sep 22, 2024
1 parent 77954f4 commit ebe8c1a
Show file tree
Hide file tree
Showing 13 changed files with 27 additions and 117 deletions.
15 changes: 7 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,30 @@ edition = "2021"
[dependencies]
sproot = { git = "https://github.com/speculare-cloud/sproot" }
ahash = "0.8"
actix-cors = { version = "0.6" }
actix-session = { version = "0.7", features = ["cookie-session"], optional = true }
actix-cors = { version = "0.7" }
actix-session = { version = "0.10", features = ["cookie-session"] }
actix-web = { version = "4.3", features = ["rustls"] }
actix-http = { version = "3.3.1", optional = true }
actix-http = { version = "3.3.1" }
clap = { version = "4.2", features = ["derive"] }
clap-verbosity-flag = "2.0"
chrono = { version = "0.4", features = ["serde"] }
config = "0.13"
config = "0.14"
diesel = { version = "2.0", features = ["postgres", "r2d2", "chrono"] }
diesel_migrations = "2.0"
evalexpr = "9.0"
evalexpr = "11.3"
futures-util = "0.3"
log = "0.4"
moka = { version = "0.11", features = ["future"] }
moka = { version = "0.12", features = ["sync"] }
once_cell = "1.14"
r2d2 = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = {version = "1.0", optional = true}
serde_json = {version = "1.0"}
sys_metrics = { git = "https://github.com/Martichou/sys_metrics" }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
uuid = { version = "1.1", features = ["v4"] }

[features]
default = []
auth = ["actix-session", "actix-http", "serde_json"]

[profile.release]
lto = true
Expand Down
File renamed without changes.
16 changes: 7 additions & 9 deletions src/api/balerts/alerts.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#[cfg(feature = "auth")]
use actix_session::Session;
use actix_web::{web, HttpResponse};
use ahash::AHasher;
Expand Down Expand Up @@ -138,13 +137,12 @@ pub async fn alerts_count(
/// GET /api/alerts/test
/// Return the result of a Alert's query if successful
pub async fn alerts_test(
#[cfg(feature = "auth")] session: Session,
session: Session,
metrics: web::Data<MetricsPool>,
item: web::Json<AlertsDTO>,
) -> Result<HttpResponse, ApiError> {
info!("Route POST /api/alerts/test");

#[cfg(feature = "auth")]
// Restrict access to auth users
match session.get::<String>("user_id") {
Ok(None) | Err(_) => {
Expand All @@ -159,12 +157,12 @@ pub async fn alerts_test(
item.hash(&mut hasher);
let hash = hasher.finish();

let data = web::block(move || {
// Check if the Hash already exists in the Cache
if ALERTSHASH_CACHE.get(&hash) == Some(()) {
return Ok(String::from("alert is valid and already cached"));
}
// Check if the Hash already exists in the Cache
if ALERTSHASH_CACHE.get(&hash) == Some(()) {
return Ok(HttpResponse::Ok().body(String::from("alert is valid and already cached")));
}

let data = web::block(move || {
let (query, qtype) = match item.construct_query() {
Ok((q, t)) => (q, t),
Err(err) => return Err(err),
Expand Down Expand Up @@ -219,7 +217,7 @@ pub async fn alerts_test(
.await??;

// Insert inside the Cache
ALERTSHASH_CACHE.insert(hash, ()).await;
ALERTSHASH_CACHE.insert(hash, ());

Ok(HttpResponse::Ok().body(data))
}
17 changes: 2 additions & 15 deletions src/api/balerts/incidents.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,25 @@
#[cfg(feature = "auth")]
use actix_session::Session;
use actix_web::{web, HttpResponse};
use sproot::apierrors::ApiError;
#[cfg(not(feature = "auth"))]
use sproot::models::BaseCrud;
use sproot::models::ExtCrud;
use sproot::models::Incidents;
use sproot::models::MetricsPool;
#[cfg(feature = "auth")]
use uuid::Uuid;

#[cfg(feature = "auth")]
use crate::api::OptSpecificPaged;
use crate::api::SpecificPaged;

/// GET /api/incidents
/// Return all incidents
pub async fn incidents_list(
#[cfg(feature = "auth")] session: Session,
session: Session,
metrics: web::Data<MetricsPool>,
#[cfg(not(feature = "auth"))] info: web::Query<SpecificPaged>,
#[cfg(feature = "auth")] info: web::Query<OptSpecificPaged>,
info: web::Query<OptSpecificPaged>,
) -> Result<HttpResponse, ApiError> {
info!("Route GET /api/incidents");

let (size, page) = info.get_size_page()?;

#[cfg(not(feature = "auth"))]
let data = web::block(move || Incidents::get(&mut metrics.pool.get()?, &info.uuid, size, page))
.await??;

#[cfg(feature = "auth")]
let inner_user = match session.get::<String>("user_id") {
Ok(Some(inner)) => inner,
Ok(None) | Err(_) => {
Expand All @@ -39,7 +28,6 @@ pub async fn incidents_list(
}
};

#[cfg(feature = "auth")]
let uuid = match Uuid::parse_str(&inner_user) {
Ok(uuid) => uuid,
Err(err) => {
Expand All @@ -48,7 +36,6 @@ pub async fn incidents_list(
}
};

#[cfg(feature = "auth")]
let data = match info.uuid.clone() {
Some(huuid) => {
info!("Getting own specific for {}", huuid);
Expand Down
22 changes: 6 additions & 16 deletions src/api/metrics/hosts.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use actix_web::{web, HttpResponse};
use sproot::models::{BaseCrud, Host, HttpHost, MetricsPool};
use sproot::{apierrors::ApiError, models::Specific};
#[cfg(feature = "auth")]
use {
crate::{api::get_user_session, AUTHPOOL},
actix_session::Session,
Expand All @@ -15,34 +14,25 @@ use super::{Paged, SpecificPaged};
pub async fn host_all(
metrics: web::Data<MetricsPool>,
info: web::Query<Paged>,
#[cfg(feature = "auth")] session: Session,
session: Session,
) -> Result<HttpResponse, ApiError> {
trace!("Route GET /api/hosts");

let (size, page) = info.get_size_page()?;

#[cfg(feature = "auth")]
let user_uuid = get_user_session(&session)?;

// If we're in the auth feature, we need to get a list of
// hosts belonging to the currently logged user. To do so
// we'll fetch the ApiKey entries owned by the inner_user.uuid
// (returning only the host_uuids).
// Then we'll simply lookup all Host which have the host_uuid
// from the call to the ApiKey entries.
// This is a bit hacky, but for now it'll do the job just fine.
#[cfg(feature = "auth")]
// We need to get a list of hosts belonging to the currently logged user.
// To do so we'll fetch the ApiKey entries owned by the inner_user.uuid
// (returning only the host_uuids). Then we'll simply lookup all Host which
// have the host_uuid from the call to the ApiKey entries. This is a bit
// hacky, but for now it'll do the job just fine.
let data = web::block(move || {
let hosts_uuid = ApiKey::get_hosts_by_owner(&mut AUTHPOOL.get()?, &user_uuid, size, page)?;
Host::get_from_uuids(&mut metrics.pool.get()?, hosts_uuid.as_slice())
})
.await??;

// If we're not using the auth feature, just get the hosts using
// the legacy method (just fetch them all, no difference for 'owner').
#[cfg(not(feature = "auth"))]
let data = web::block(move || Host::list_hosts(&mut metrics.pool.get()?, size, page)).await??;

Ok(HttpResponse::Ok().json(data))
}

Expand Down
3 changes: 0 additions & 3 deletions src/api/metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//! being performed.
use serde::{Deserialize, Serialize};
use sproot::apierrors::ApiError;
#[cfg(feature = "auth")]
use {actix_session::Session, uuid::Uuid};

pub mod cpustats;
Expand Down Expand Up @@ -76,7 +75,6 @@ impl SpecificPaged {
}

impl OptSpecificPaged {
#[cfg(feature = "auth")]
pub fn get_size_page(&self) -> Result<(i64, i64), ApiError> {
let size = self.size.unwrap_or(100);
let page = self.page.unwrap_or(0);
Expand All @@ -91,7 +89,6 @@ impl OptSpecificPaged {

/// Get the Uuid of the user from his Session or
/// return an InvalidToken error if not found
#[cfg(feature = "auth")]
pub fn get_user_session(session: &Session) -> Result<Uuid, ApiError> {
match session.get::<String>("user_id") {
Ok(Some(id)) => Ok(Uuid::parse_str(&id).unwrap()),
Expand Down
3 changes: 1 addition & 2 deletions src/auth/alerthostowned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,7 @@ where
match exists {
true => {
CHECKSESSIONS_CACHE
.insert(alert.host_uuid.to_owned(), uuid)
.await;
.insert(alert.host_uuid.to_owned(), uuid);

let encoded_alert = serde_json::to_vec(&alert.0).unwrap();
sres.set_payload(super::bytes_to_payload(Bytes::from(encoded_alert)));
Expand Down
2 changes: 1 addition & 1 deletion src/auth/checksessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ where
// If the entry does not exists, return Unauthorized.
match exists {
true => {
CHECKSESSIONS_CACHE.insert(host_uuid, uuid).await;
CHECKSESSIONS_CACHE.insert(host_uuid, uuid);
let res = svc.call(ServiceRequest::from_parts(request, pl));
res.await.map(ServiceResponse::map_into_left_body)
}
Expand Down
2 changes: 1 addition & 1 deletion src/auth/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use actix_web::{dev, web};
use moka::future::Cache;
use moka::sync::Cache;
use once_cell::sync::Lazy;
use std::time::Duration;
use uuid::Uuid;
Expand Down
2 changes: 1 addition & 1 deletion src/auth/sptkvalidator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ where
// depending on the state of APIKEY.host_uuid.
if let Some(khost_uuid) = api_key.host_uuid {
if khost_uuid == info.uuid {
CHECKSPTK_CACHE.insert(host_uuid, sptk_owned).await;
CHECKSPTK_CACHE.insert(host_uuid, sptk_owned);
let res = svc.call(ServiceRequest::from_parts(request, pl));
res.await.map(ServiceResponse::map_into_left_body)
} else {
Expand Down
4 changes: 1 addition & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ extern crate sproot;

use clap::Parser;
use diesel_migrations::EmbeddedMigrations;
use moka::future::Cache;
use moka::sync::Cache;
use once_cell::sync::Lazy;
use sproot::{prog, Pool};
use std::time::Duration;
Expand All @@ -16,7 +16,6 @@ use utils::database::{apply_migration, build_pool};
use crate::utils::config::Config;

mod api;
#[cfg(feature = "auth")]
mod auth;
mod routes;
mod server;
Expand All @@ -41,7 +40,6 @@ static CONFIG: Lazy<Config> = Lazy::new(|| match Config::new() {
}
});

#[cfg(feature = "auth")]
// Auth Pool is used when the Authentication feature is enabled.
// This "Pool" is a direct connection to the Auth database.
pub static AUTHPOOL: Lazy<Pool> = Lazy::new(|| {
Expand Down
50 changes: 0 additions & 50 deletions src/routes.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use actix_web::{guard, web};
#[cfg(feature = "auth")]
use {
crate::auth::{
alerthostowned::AlertHostOwned, alertowned::AlertOwned, checksessions::CheckSessions,
Expand All @@ -15,55 +14,6 @@ use crate::{
CONFIG,
};

#[cfg(not(feature = "auth"))]
pub fn routes(cfg: &mut web::ServiceConfig) {
cfg.route("/ping", web::get().to(|| async { "zpour" }))
.route("/ping", web::head().to(|| async { "zpour" }))
.service(
web::scope("/api")
.guard(guard::All(guard::Post()).and(guard::Header("SPTK", &CONFIG.api_token)))
.route("/hosts", web::post().to(hosts::host_ingest)),
)
.service(
web::resource("/api/alerts")
.guard(
guard::Any(guard::Post())
.or(guard::Patch())
.or(guard::Delete()),
)
.guard(guard::Header("SPTK", &CONFIG.api_token))
.route(web::post().to(alerts::alerts_create))
.route(web::patch().to(alerts::alerts_update))
.route(web::delete().to(alerts::alerts_delete)),
)
.service(
web::resource("/api/alerts/test")
.guard(guard::All(guard::Post()).and(guard::Header("SPTK", &CONFIG.api_token)))
.route(web::post().to(alerts::alerts_test)),
)
.service(
web::scope("/api")
.route("/hosts", web::get().to(hosts::host_all))
.route("/host", web::get().to(hosts::host_specific))
.route("/cpustats", web::get().to(cpustats::cpustats))
.route("/cputimes", web::get().to(cputimes::cputimes))
.route("/loadavg", web::get().to(loadavg::loadavg))
.route("/disks", web::get().to(disks::disks))
.route("/ioblocks", web::get().to(ioblock::ioblocks))
.route("/ionets", web::get().to(ionet::ionets))
.route("/memory", web::get().to(memory::memory))
.route("/swap", web::get().to(swap::swap))
.route("/incidents", web::get().to(incidents::incidents_list))
.route(
"/incidents/count",
web::get().to(incidents::incidents_count),
)
.route("/alerts", web::get().to(alerts::alerts_list))
.route("/alerts/count", web::get().to(alerts::alerts_count)),
);
}

#[cfg(feature = "auth")]
pub fn routes(cfg: &mut web::ServiceConfig) {
cfg.route("/ping", web::get().to(|| async { "zpour" }))
.route("/ping", web::head().to(|| async { "zpour" }))
Expand Down
8 changes: 0 additions & 8 deletions src/utils/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ pub struct Config {
pub database_max_connection: u32,

// AUTH POSTGRESQL CONNECTION
#[cfg(feature = "auth")]
pub auth_database_url: String,
#[cfg(feature = "auth")]
#[serde(default = "default_maxconn")]
pub auth_database_max_connection: u32,

Expand All @@ -30,14 +28,8 @@ pub struct Config {
pub key_priv: Option<String>,
pub key_cert: Option<String>,

#[cfg(not(feature = "auth"))]
pub api_token: String,

#[cfg(feature = "auth")]
pub berta_name: String,
#[cfg(feature = "auth")]
pub cookie_secret: String,
#[cfg(feature = "auth")]
pub cookie_domain: Option<String>,
}

Expand Down

0 comments on commit ebe8c1a

Please sign in to comment.