use super::context::set_renewed_token;
use super::current_token;
use super::GarrisonLogicDefault;
use super::JwtMode;
use super::LoginParams;
#[cfg(feature = "listener")]
use crate::config::OverflowLogoutMode;
use crate::config::ReplacedLoginExitMode;
#[cfg(feature = "secure-simple-token")]
use crate::core::token::Token;
use crate::error::{GarrisonError, GarrisonResult};
#[cfg(feature = "listener")]
use crate::listener::GarrisonEvent;
#[cfg(feature = "listener")]
use crate::loc;
use crate::stp::core::GarrisonCore;
use crate::stp::token::TokenLogic;
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
use crate::strategy::FirewallLoginContext;
use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::Mutex as TokioMutex;
#[async_trait]
pub trait SessionLogic: GarrisonCore {
async fn login(&self, login_id: &str, params: &LoginParams) -> GarrisonResult<String>;
async fn login_with_token(&self, login_id: &str, token: &str) -> GarrisonResult<()>;
async fn logout(&self) -> GarrisonResult<()>;
async fn logout_by_login_id(&self, login_id: &str) -> GarrisonResult<()>;
async fn kickout(&self, login_id: &str) -> GarrisonResult<()>;
async fn kickout_by_token(&self, token: &str) -> GarrisonResult<()>;
async fn revoke_token(&self, token: &str) -> GarrisonResult<()>;
async fn revoke_all_sessions(&self, login_id: &str) -> GarrisonResult<usize> {
let _ = login_id;
Err(GarrisonError::NotImplemented(
"stp-revoke-all-sessions-not-implemented::".to_string(),
))
}
async fn get_active_sessions(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
let _ = login_id;
Err(GarrisonError::NotImplemented(
"stp-get-active-sessions-not-implemented::".to_string(),
))
}
async fn check_login(&self) -> GarrisonResult<bool>;
async fn get_login_id(&self) -> GarrisonResult<Option<String>>;
async fn login_by_token(&self, _token: &str) -> GarrisonResult<()> {
Err(GarrisonError::NotImplemented(
"stp-login-by-token-feature-required::".to_string(),
))
}
async fn refresh_access_token(&self, _refresh_token: &str) -> GarrisonResult<(String, String)> {
Err(GarrisonError::NotImplemented(
"stp-refresh-access-token-not-implemented-db::".to_string(),
))
}
}
fn validate_login_with_token_inputs(token: &str) -> GarrisonResult<()> {
if token.is_empty() {
return Err(GarrisonError::InvalidParam("stp-token-empty::".to_string()));
}
let len = token.len();
if len < 8 {
return Err(GarrisonError::InvalidParam(format!(
"stp-token-length-too-short::{}",
len
)));
}
if len > 256 {
return Err(GarrisonError::InvalidParam(format!(
"stp-token-length-too-long::{}",
len
)));
}
if token.chars().any(|c| c.is_control()) {
return Err(GarrisonError::InvalidParam(
"stp-token-control-char::".to_string(),
));
}
Ok(())
}
#[async_trait]
impl SessionLogic for GarrisonLogicDefault {
#[tracing::instrument(skip_all, fields(login_id = %login_id))]
async fn login(&self, login_id: &str, params: &LoginParams) -> GarrisonResult<String> {
#[cfg(feature = "metrics-prometheus")]
let start = std::time::Instant::now();
#[cfg(feature = "firewall-bruteforce")]
if let Some(ip) = crate::stp::current_ip() {
use crate::strategy::firewall::brute_force::{BruteForceConfig, BruteForceStrategy};
use crate::strategy::firewall::FirewallContext;
let strategy = BruteForceStrategy::new(BruteForceConfig::default(), self.dao().clone());
let fw_ctx = FirewallContext::new(&ip);
if strategy.is_blocked(&fw_ctx).await? {
return Err(GarrisonError::FirewallBlocked(format!(
"stp-login-ip-blocked::{}",
ip
)));
}
}
let result = self.login_inner(login_id, params).await;
#[cfg(feature = "firewall-bruteforce")]
if let Some(ip) = crate::stp::current_ip() {
use crate::strategy::firewall::brute_force::{BruteForceConfig, BruteForceStrategy};
use crate::strategy::firewall::FirewallContext;
let strategy = BruteForceStrategy::new(BruteForceConfig::default(), self.dao().clone());
let fw_ctx = FirewallContext::new(&ip);
match &result {
Ok(_) => {
let count_key =
format!("{}{}:count", crate::constants::DaoKeyPrefix::BruteForce, ip);
if let Err(e) = self.dao().delete(&count_key).await {
tracing::warn!(
ip = %ip,
error = %e,
"brute force reset-on-success failed (does not affect the login result)"
);
}
},
Err(_) => {
if let Err(record_err) = strategy.record_failure(&fw_ctx).await {
tracing::warn!(
ip = %ip,
error = %record_err,
"brute force record_failure failed (does not affect the login result)"
);
}
},
}
}
#[cfg(feature = "metrics-prometheus")]
if let Some(m) = &self.metrics {
m.record_login(result.is_ok());
m.observe_token_validation(start.elapsed());
}
result
}
async fn login_with_token(&self, login_id: &str, token: &str) -> GarrisonResult<()> {
self.validate_login_id(login_id)?;
validate_login_with_token_inputs(token)?;
let session = &self.session;
session
.with_token_session_lock(token, async {
if let Some(existing_ts) = session.get_token_session(token).await? {
if existing_ts.login_id != login_id {
return Err(GarrisonError::InvalidToken(format!(
"stp-token-login-id-bound::{}",
existing_ts.login_id
)));
}
}
self.create_session_with_quota(login_id, token, None, None, None, false)
.await
})
.await
}
#[tracing::instrument(skip_all)]
async fn logout(&self) -> GarrisonResult<()> {
match current_token() {
Ok(token) => {
let login_id = self
.session
.get_token_session(&token)
.await?
.map(|ts| ts.login_id);
#[cfg(feature = "protocol-jwt")]
self.blacklist_jwt_jti(&token).await;
self.session.logout(&token).await?;
crate::stp::context::invalidate_login_identity_by_token(&token);
if let (Some(pm), Some(id)) = (&self.plugin_manager, login_id.as_ref()) {
pm.on_logout(id, &token);
}
#[cfg(feature = "listener")]
if let (Some(lm), Some(id)) = (&self.listener_manager, login_id.as_ref()) {
lm.broadcast(&GarrisonEvent::Logout {
login_id: id.clone(),
token: crate::listener::mask_token_for_event(&token),
request_context: None,
})
.await;
}
#[cfg(feature = "three-tier-cache")]
if let (Some(ucs), Some(id)) = (&self.user_cache_service, login_id.as_ref()) {
if let Err(e) = ucs.invalidate(id).await {
tracing::warn!(error = %e, login_id = id, "logout invalidate user cache failed");
}
}
Ok(())
},
Err(_) => Ok(()),
}
}
async fn logout_by_login_id(&self, login_id: &str) -> GarrisonResult<()> {
if let Err(e) = self.firewall.invalidate_login_cache(login_id).await {
tracing::warn!(error = %e, login_id, "{}", crate::i18n::translate_detail("logs-stp-invalidate-login-cache-logout-failed", &[]));
}
self.session
.with_login_lock(login_id, async {
#[cfg(feature = "protocol-jwt")]
self.blacklist_all_jwt_jti_locked(login_id).await;
self.session.logout_by_login_id_inner(login_id).await
})
.await?;
crate::stp::context::invalidate_login_identity_by_login_id(login_id);
#[cfg(feature = "three-tier-cache")]
if let Some(ucs) = &self.user_cache_service {
if let Err(e) = ucs.invalidate(login_id).await {
tracing::warn!(error = %e, login_id, "logout_by_login_id invalidate user cache failed");
}
}
Ok(())
}
async fn kickout(&self, login_id: &str) -> GarrisonResult<()> {
if let Err(e) = self.firewall.invalidate_login_cache(login_id).await {
tracing::warn!(error = %e, login_id, "{}", crate::i18n::translate_detail("logs-stp-invalidate-login-cache-kickout-failed", &[]));
}
self.session
.with_login_lock(login_id, async {
#[cfg(feature = "protocol-jwt")]
self.blacklist_all_jwt_jti_locked(login_id).await;
self.session.logout_by_login_id_inner(login_id).await
})
.await?;
crate::stp::context::invalidate_login_identity_by_login_id(login_id);
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&GarrisonEvent::Kickout {
login_id: login_id.to_string(),
token: String::new(),
reason: loc!("session-kickout-admin", ""),
request_context: None,
})
.await;
}
Ok(())
}
async fn kickout_by_token(&self, token: &str) -> GarrisonResult<()> {
#[cfg(feature = "protocol-jwt")]
self.blacklist_jwt_jti(token).await;
let result = self.session.logout(token).await;
if result.is_ok() {
crate::stp::context::invalidate_login_identity_by_token(token);
}
result
}
async fn revoke_token(&self, token: &str) -> GarrisonResult<()> {
#[cfg(feature = "protocol-jwt")]
self.blacklist_jwt_jti(token).await;
self.session.logout(token).await?;
crate::stp::context::invalidate_login_identity_by_token(token);
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&GarrisonEvent::RevokeToken {
token: token.to_string(),
request_context: None,
})
.await;
}
Ok(())
}
async fn revoke_all_sessions(&self, login_id: &str) -> GarrisonResult<usize> {
let tokens = self.session.get_tokens_by_login_id(login_id);
let mut count = 0usize;
for token in tokens {
match self.revoke_token(&token).await {
Ok(()) => count += 1,
Err(e) => {
let token_preview = if token.len() > 8 { &token[..8] } else { &token };
tracing::warn!(
error = %e,
login_id,
token = %token_preview,
"revoke_all_sessions: single token revoke failed, continuing"
);
},
}
}
if let Err(e) = self.logout_by_login_id(login_id).await {
tracing::warn!(
error = %e,
login_id,
"revoke_all_sessions: Account-Session cleanup failed"
);
}
Ok(count)
}
async fn get_active_sessions(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
let tokens = self.session.get_tokens_by_login_id(login_id);
let mut active = Vec::with_capacity(tokens.len());
for token in tokens {
if self.session.get_token_session(&token).await?.is_some() {
active.push(token);
}
}
Ok(active)
}
#[tracing::instrument(skip_all)]
async fn check_login(&self) -> GarrisonResult<bool> {
#[cfg(feature = "firewall-bruteforce")]
if let Some(ip) = crate::stp::current_ip() {
use crate::strategy::firewall::brute_force::{BruteForceConfig, BruteForceStrategy};
use crate::strategy::firewall::FirewallContext;
let strategy = BruteForceStrategy::new(BruteForceConfig::default(), self.dao().clone());
let fw_ctx = FirewallContext::new(&ip);
if strategy.is_blocked(&fw_ctx).await? {
return Err(GarrisonError::FirewallBlocked(format!(
"stp-check-login-ip-blocked::{}",
ip
)));
}
}
let token = match current_token() {
Ok(t) => t,
Err(_) => {
if self.config.throw_on_not_login {
return Err(GarrisonError::Session("stp-not-login::".to_string()));
}
return Ok(false);
},
};
let (result, snapshot) = match self.jwt_mode {
JwtMode::Stateless => (self.check_login_stateless(&token).await, None),
JwtMode::Mixin => self.check_login_mixin(&token).await,
JwtMode::Simple => self.check_login_simple(&token).await,
};
let result = self
.validate_session_tenant_binding(&token, result, snapshot.as_ref())
.await;
#[cfg(feature = "security-extra")]
if let Ok((true, Some(ref login_id))) = result {
self.run_anomaly_check_on_check_login(login_id, &token)
.await;
}
#[cfg(feature = "firewall-bruteforce")]
if let Some(ip) = crate::stp::current_ip() {
use crate::strategy::firewall::brute_force::{BruteForceConfig, BruteForceStrategy};
use crate::strategy::firewall::FirewallContext;
let strategy = BruteForceStrategy::new(BruteForceConfig::default(), self.dao().clone());
let fw_ctx = FirewallContext::new(&ip);
match &result {
Ok((true, _)) => {
let count_key =
format!("{}{}:count", crate::constants::DaoKeyPrefix::BruteForce, ip);
if let Err(e) = self.dao().delete(&count_key).await {
tracing::warn!(
ip = %ip,
error = %e,
"brute force reset-on-success failed (does not affect the verification result)"
);
}
},
Ok((false, _)) => {
if let Err(record_err) = strategy.record_failure(&fw_ctx).await {
tracing::warn!(
ip = %ip,
error = %record_err,
"brute force record_failure failed (does not affect the verification result)"
);
}
},
Err(_) => {
},
}
}
if let Ok((true, Some(ref login_id))) = result {
crate::stp::context::cache_login_identity(&token, login_id);
}
result.map(|(valid, _)| valid)
}
async fn get_login_id(&self) -> GarrisonResult<Option<String>> {
match current_token() {
Ok(token) => {
if let Some(login_id) = crate::stp::context::cached_login_id_for(&token) {
return Ok(Some(login_id));
}
match self.session.get_token_session(&token).await? {
Some(ts) => Ok(Some(ts.login_id)),
None => Ok(None),
}
},
Err(_) => Ok(None),
}
}
async fn login_by_token(&self, token: &str) -> GarrisonResult<()> {
let login_id = if let Some(auth) = &self.auth_logic {
auth.verify_token(token).await?
} else {
self.verify_token(token).await?
};
self.validate_login_id(&login_id)?;
self.session.create(&login_id, token).await?;
if let Some(pm) = &self.plugin_manager {
pm.on_login(&login_id, token);
}
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&GarrisonEvent::Login {
login_id,
token: token.to_string(),
device: None,
request_context: None,
})
.await;
}
Ok(())
}
#[tracing::instrument(level = "info", skip(self, refresh_token))]
async fn refresh_access_token(&self, refresh_token: &str) -> GarrisonResult<(String, String)> {
#[cfg(all(feature = "protocol-jwt", feature = "db-sqlite"))]
{
if let Some(rtr) = &self.refresh_token_rotation {
return rtr.rotate(refresh_token).await;
}
return Err(GarrisonError::NotImplemented(
"stp-refresh-access-token-no-rotation::".to_string(),
));
}
#[cfg(not(all(feature = "protocol-jwt", feature = "db-sqlite")))]
{
let _ = refresh_token;
Err(GarrisonError::NotImplemented(
"stp-refresh-access-token-feature-required::".to_string(),
))
}
}
}
impl GarrisonLogicDefault {
async fn validate_session_tenant_binding(
&self,
token: &str,
result: GarrisonResult<(bool, Option<String>)>,
snapshot: Option<&crate::session::TokenSession>,
) -> GarrisonResult<(bool, Option<String>)> {
if !matches!(result, Ok((true, _))) {
return result;
}
let ctx = match crate::context::tenant::TENANT.try_get() {
Ok(ctx) => ctx,
Err(_) => return result, };
let bound = match snapshot {
Some(ts) => ts
.attrs
.get(crate::context::tenant::SESSION_TENANT_ATTR_KEY)
.cloned(),
None => {
self.session
.get(token, crate::context::tenant::SESSION_TENANT_ATTR_KEY)
.await?
},
};
match bound {
Some(bound) if bound == ctx.tenant_id.to_string() => result,
Some(_) => Err(GarrisonError::Session(
"stp-check-login-tenant-mismatch::".to_string(),
)),
None if self.config.require_session_tenant_binding
&& self.jwt_mode != JwtMode::Stateless =>
{
Err(GarrisonError::Session(
"stp-check-login-session-tenant-unbound::".to_string(),
))
},
None => result,
}
}
}
mod helpers;
#[cfg(test)]
mod tests;
#[cfg(all(test, feature = "db-sqlite"))]
mod role_union_tests;