Optimize cache management
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2025-12-04 18:51:46 +01:00
parent 944e7dd00d
commit 3d19a0eba2
18 changed files with 85 additions and 21 deletions

15
Cargo.lock generated
View File

@@ -583,10 +583,12 @@ dependencies = [
"base64 0.22.1",
"bcrypt",
"bincode",
"build-time",
"chrono",
"clap",
"digest 0.11.0-rc.4",
"env_logger",
"httpdate",
"include_dir",
"jwt-simple",
"lazy-regex",
@@ -722,6 +724,19 @@ dependencies = [
"alloc-stdlib",
]
[[package]]
name = "build-time"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1219c19fc29b7bfd74b7968b420aff5bc951cf517800176e795d6b2300dd382"
dependencies = [
"chrono",
"once_cell",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "bumpalo"
version = "3.19.0"

View File

@@ -39,3 +39,5 @@ bincode = "2.0.1"
chrono = "0.4.42"
lazy_static = "1.5.0"
mailchecker = "6.0.19"
httpdate = "1.0.3"
build-time = "0.1.3"

View File

@@ -5,7 +5,7 @@ use std::net::IpAddr;
use actix::{Actor, AsyncContext, Context, Handler, Message};
use crate::constants::{FAIL_LOGIN_ATTEMPT_CLEANUP_INTERVAL, KEEP_FAILED_LOGIN_ATTEMPTS_FOR};
use crate::utils::time::time;
use crate::utils::time_utils::time;
#[derive(Message)]
#[rtype(result = "()")]
@@ -87,7 +87,7 @@ mod test {
use std::net::{IpAddr, Ipv4Addr};
use crate::actors::bruteforce_actor::BruteForceActor;
use crate::utils::time::time;
use crate::utils::time_utils::time;
const IP_1: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
const IP_2: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 2));

View File

@@ -10,7 +10,7 @@ use crate::data::jwt_signer::JWTSigner;
use crate::data::user::UserID;
use crate::utils::err::Res;
use crate::utils::string_utils::rand_str;
use crate::utils::time::time;
use crate::utils::time_utils::time;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
pub struct SessionID(pub String);

View File

@@ -15,7 +15,7 @@ use std::net::IpAddr;
use crate::data::login_redirect::LoginRedirect;
use crate::data::provider::ProviderID;
use crate::utils::string_utils::rand_str;
use crate::utils::time::time;
use crate::utils::time_utils::time;
#[derive(Debug, Clone, serde::Serialize)]
pub struct ProviderLoginState {

View File

@@ -1,7 +1,11 @@
use std::path::Path;
use actix_web::{HttpResponse, web};
use crate::utils::crypt_utils::sha256;
use crate::utils::time_utils;
use actix_web::http::header;
use actix_web::{HttpRequest, HttpResponse, web};
use include_dir::{Dir, include_dir};
use std::ops::Add;
use std::path::Path;
use std::time::Duration;
/// Assets directory
static ASSETS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/assets");
@@ -12,14 +16,39 @@ pub async fn robots_txt() -> HttpResponse {
.body(include_str!("../../assets/robots.txt"))
}
pub async fn assets_route(path: web::Path<String>) -> HttpResponse {
pub async fn assets_route(req: HttpRequest, path: web::Path<String>) -> HttpResponse {
let path: &Path = path.as_ref().as_ref();
match ASSETS_DIR.get_file(path) {
None => HttpResponse::NotFound().body("404 Not found"),
Some(file) => {
let res = mime_guess::from_path(path).first_or_octet_stream();
let digest = format!("{:x?}", sha256(file.contents()));
// Check if the browser already knows the file by date
if let Some(c) = req.headers().get(header::IF_MODIFIED_SINCE) {
let date_str = c.to_str().unwrap_or("");
if let Ok(date) = httpdate::parse_http_date(date_str)
&& date.add(Duration::from_secs(1))
>= time_utils::unix_to_system_time(time_utils::build_time())
{
return HttpResponse::NotModified().finish();
}
}
// Check if the browser already knows the etag
if let Some(c) = req.headers().get(header::IF_NONE_MATCH)
&& c.to_str().unwrap_or("") == digest
{
return HttpResponse::NotModified().finish();
}
HttpResponse::Ok()
.content_type(res.to_string())
.insert_header(("etag", digest))
.insert_header((
"last-modified",
time_utils::unix_to_http_date(time_utils::build_time()),
))
.body(file.contents())
}
}

View File

@@ -26,7 +26,7 @@ use crate::data::login_redirect::{LoginRedirect, get_2fa_url};
use crate::data::session_identity::SessionIdentity;
use crate::data::user::User;
use crate::utils::string_utils::rand_str;
use crate::utils::time::time;
use crate::utils::time_utils::time;
pub async fn get_configuration(req: HttpRequest) -> impl Responder {
let is_secure_request = req

View File

@@ -14,7 +14,7 @@ use crate::data::current_user::CurrentUser;
use crate::data::totp_key::TotpKey;
use crate::data::user::User;
use crate::data::webauthn_manager::WebAuthManagerReq;
use crate::utils::time::fmt_time;
use crate::utils::time_utils::fmt_time;
#[derive(Template)]
#[template(path = "settings/two_factors_page.html")]

View File

@@ -17,7 +17,7 @@ use crate::data::provider::{Provider, ProviderID};
use crate::data::session_identity::SessionIdentity;
use crate::data::user::{FactorID, GrantedClients, TwoFactor, TwoFactorType, User, UserID};
use crate::utils::time::time;
use crate::utils::time_utils::time;
#[derive(serde::Serialize)]
pub struct LoggableUser {

View File

@@ -13,7 +13,7 @@ use crate::actors::users_actor::UsersActor;
use crate::constants::SECOND_FACTOR_EXPIRATION_FOR_CRITICAL_OPERATIONS;
use crate::data::session_identity::SessionIdentity;
use crate::data::user::User;
use crate::utils::time::time;
use crate::utils::time_utils::time;
pub struct CurrentUser {
user: User,

View File

@@ -9,7 +9,7 @@ use crate::data::app_config::AppConfig;
use crate::data::provider::Provider;
use crate::utils::err::Res;
use crate::utils::time::time;
use crate::utils::time_utils::time;
/// Provider configuration
#[derive(Debug, Clone)]

View File

@@ -3,7 +3,7 @@ use actix_web::{HttpMessage, HttpRequest};
use serde::{Deserialize, Serialize};
use crate::data::user::{User, UserID};
use crate::utils::time::time;
use crate::utils::time_utils::time;
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
pub enum SessionStatus {

View File

@@ -5,7 +5,7 @@ use totp_rfc6238::{HashAlgorithm, TotpGenerator};
use crate::data::app_config::AppConfig;
use crate::data::user::User;
use crate::utils::err::Res;
use crate::utils::time::time;
use crate::utils::time_utils::time;
const BASE32_ALPHABET: Alphabet = Alphabet::Rfc4648 { padding: true };
const NUM_DIGITS: usize = 6;

View File

@@ -9,7 +9,7 @@ use crate::data::login_redirect::LoginRedirect;
use crate::data::provider::{Provider, ProviderID};
use crate::data::totp_key::TotpKey;
use crate::data::webauthn_manager::WebauthnPubKey;
use crate::utils::time::{fmt_time, time};
use crate::utils::time_utils::{fmt_time, time};
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Encode, Decode)]
pub struct UserID(pub String);

View File

@@ -4,7 +4,7 @@ use crate::actors::users_actor::{AuthorizedAuthenticationSources, UsersSyncBacke
use crate::data::entity_manager::EntityManager;
use crate::data::user::{FactorID, GeneralSettings, GrantedClients, TwoFactor, User, UserID};
use crate::utils::err::{Res, new_error};
use crate::utils::time::time;
use crate::utils::time_utils::time;
impl EntityManager<User> {
/// Update user information

View File

@@ -16,7 +16,7 @@ use crate::constants::{
use crate::data::app_config::AppConfig;
use crate::data::user::{User, UserID};
use crate::utils::err::Res;
use crate::utils::time::time;
use crate::utils::time_utils::time;
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct WebauthnPubKey {

View File

@@ -1,4 +1,4 @@
pub mod crypt_utils;
pub mod err;
pub mod string_utils;
pub mod time;
pub mod time_utils;

View File

@@ -1,5 +1,5 @@
use chrono::DateTime;
use std::time::{SystemTime, UNIX_EPOCH};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// Get the current time since epoch
pub fn time() -> u64 {
@@ -19,9 +19,27 @@ pub fn fmt_time(timestamp: u64) -> String {
datetime.format("%Y-%m-%d %H:%M:%S").to_string()
}
/// Convert UNIX time to system time
pub fn unix_to_system_time(time: u64) -> SystemTime {
UNIX_EPOCH + Duration::from_secs(time)
}
/// Format UNIX time to HTTP date
pub fn unix_to_http_date(time: u64) -> String {
httpdate::fmt_http_date(unix_to_system_time(time))
}
/// Get build time in UNIX format
pub fn build_time() -> u64 {
let build_time = build_time::build_time_local!();
let date =
chrono::DateTime::parse_from_rfc3339(build_time).expect("Failed to parse compile date");
date.timestamp() as u64
}
#[cfg(test)]
mod test {
use crate::utils::time::{fmt_time, time};
use crate::utils::time_utils::{fmt_time, time};
#[test]
fn test_time() {