From 28889eb338aa8f0a2d335db98445674f8caa64c2 Mon Sep 17 00:00:00 2001 From: alemi Date: Fri, 7 Jun 2024 02:22:43 +0200 Subject: [PATCH] feat: config session duration, token refreshes allow refreshing sessions before they expire --- upub/core/src/config.rs | 5 ++++- upub/routes/src/activitypub/auth.rs | 6 ++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/upub/core/src/config.rs b/upub/core/src/config.rs index f129e922..15d3355d 100644 --- a/upub/core/src/config.rs +++ b/upub/core/src/config.rs @@ -71,9 +71,12 @@ pub struct SecurityConfig { #[serde_inline_default(true)] pub show_reply_ids: bool, - #[serde(default)] + #[serde_inline_default(true)] pub allow_login_refresh: bool, + #[serde_inline_default(7 * 24)] + pub session_duration_hours: i64, + #[serde_inline_default(2)] pub max_id_redirects: u32, diff --git a/upub/routes/src/activitypub/auth.rs b/upub/routes/src/activitypub/auth.rs index d31e0cc0..02c4e07b 100644 --- a/upub/routes/src/activitypub/auth.rs +++ b/upub/routes/src/activitypub/auth.rs @@ -41,7 +41,7 @@ pub async fn login( { Some(x) => { let token = token(); - let expires = chrono::Utc::now() + std::time::Duration::from_secs(3600 * 6); + let expires = chrono::Utc::now() + chrono::Duration::hours(ctx.cfg().security.session_duration_hours); upub::model::session::Entity::insert( upub::model::session::ActiveModel { internal: sea_orm::ActiveValue::NotSet, @@ -80,7 +80,9 @@ pub async fn refresh( .await? .ok_or_else(crate::ApiError::unauthorized)?; - if prev.expires > chrono::Utc::now() { + // allow refreshing tokens a little bit before they expire, specifically 1/4 of their lifespan before + let quarter_session_lifespan = chrono::Duration::days(ctx.cfg().security.session_duration_hours) / 4; + if prev.expires - quarter_session_lifespan > chrono::Utc::now() { return Ok(Json(AuthSuccess { token: prev.secret, user: prev.actor, expires: prev.expires })); }