Add login token expiration to the license server's duties

This commit is contained in:
Herbert Wolverson
2023-08-12 15:50:49 +00:00
parent 71135aa0b2
commit df3bc69282
5 changed files with 41 additions and 2 deletions

View File

@@ -1,6 +1,7 @@
use tracing_subscriber::fmt::format::FmtSpan;
mod pki;
mod server;
mod token_expiration;
fn set_console_logging() -> anyhow::Result<()> {
// install global collector configured based on RUST_LOG env var.
@@ -39,6 +40,10 @@ async fn main() -> anyhow::Result<()> {
// Start the logger
set_console_logging().unwrap();
// Start the token expiration
tokio::spawn(token_expiration::token_expiration_loop(pool.clone()));
// Start the main server
let _ = server::listen_accept(pool.clone()).await;
Ok(())
}

View File

@@ -0,0 +1,20 @@
use std::time::Duration;
use pgdb::sqlx::{Postgres, Pool};
pub async fn token_expiration_loop(pool: Pool<Postgres>) {
loop {
tracing::info!("Checking token expiration");
let mut interval = tokio::time::interval(Duration::from_secs(300));
interval.tick().await;
let result = check_token_expiration(&pool).await;
if let Err(e) = result {
tracing::error!("Error checking token expiration: {:?}", e);
}
}
}
#[tracing::instrument(skip(pool))]
async fn check_token_expiration(pool: &Pool<Postgres>) -> anyhow::Result<()> {
pgdb::expire_tokens(pool).await?;
Ok(())
}

View File

@@ -19,7 +19,7 @@ pub use license::{get_stats_host_for_key, insert_or_update_node_public_key, fetc
pub use organization::{OrganizationDetails, get_organization};
pub use hosts::add_stats_host;
pub use orchestrator::create_free_trial;
pub use logins::{try_login, delete_user, add_user, refresh_token, token_to_credentials};
pub use logins::{try_login, delete_user, add_user, refresh_token, token_to_credentials, expire_tokens};
pub use nodes::{new_stats_arrived, node_status, NodeStatus};
pub use search::*;
pub use tree::*;

View File

@@ -5,4 +5,4 @@ mod token_cache;
pub use login::{LoginDetails, try_login};
pub use add_del::{add_user, delete_user};
pub use token_cache::{refresh_token, token_to_credentials};
pub use token_cache::{refresh_token, token_to_credentials, expire_tokens};

View File

@@ -94,3 +94,17 @@ pub async fn token_to_credentials(
Ok(details)
}
pub async fn expire_tokens(cnn: &Pool<Postgres>) -> Result<(), StatsHostError> {
sqlx::query("SELECT * FROM active_tokens WHERE expires < NOW()")
.execute(cnn)
.await
.map_err(|e| StatsHostError::DatabaseError(e.to_string()))?;
let ten_mins_ago = unix_now().unwrap_or(0) - 600;
TOKEN_CACHE.retain(|k, v| {
v.last_seen < ten_mins_ago
});
Ok(())
}