use crate::core::permission::PermissionChecker;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
#[cfg(all(
feature = "listener",
any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
)
))]
use crate::listener::GarrisonEvent;
#[cfg(feature = "listener")]
use crate::listener::GarrisonListenerManager;
use crate::plugin::GarrisonPluginManager;
use crate::stp::GarrisonInterface;
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
use crate::strategy::hooks::{GarrisonFirewallCheckHook, LoginContext};
use async_trait::async_trait;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use super::{GarrisonPermissionStrategy, GarrisonPermissionStrategyDefault};
const DECISION_CACHE_TTL_SECS: u64 = 300;
const DECISION_VERSION_KEY_TTL_SECS: u64 = 2 * DECISION_CACHE_TTL_SECS;
const PERM_CACHE_KEY_PREFIX: &str = "garrison:perm:cache:";
const ROLE_CACHE_KEY_PREFIX: &str = "garrison:role:cache:";
const DECISION_VERSION_KEY_PREFIX: &str = "garrison:decision:ver:";
const SENTINEL_DECISION_EPOCH: &str = "0";
fn encode_key_component(component: &str) -> String {
component.replace('%', "%25").replace(':', "%3A")
}
impl GarrisonPermissionStrategyDefault {
pub fn new(interface: Arc<dyn GarrisonInterface>) -> Self {
Self {
interface,
permission_checker: None,
dao: None,
tenant_id: None,
login_type: "default".to_string(),
role_hierarchy: HashMap::new(),
plugin_manager: None,
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
firewall_hook: None,
#[cfg(feature = "listener")]
listener_manager: None,
}
}
pub fn with_permission_checker(mut self, pc: Arc<dyn PermissionChecker>) -> Self {
self.permission_checker = Some(pc);
self
}
pub fn with_dao(mut self, dao: Arc<dyn GarrisonDao>) -> Self {
self.dao = Some(dao);
self
}
pub fn with_tenant_id(mut self, tenant_id: i64) -> Self {
self.tenant_id = Some(tenant_id);
self
}
pub fn with_login_type(mut self, login_type: &str) -> Self {
self.login_type = login_type.to_string();
self
}
fn decision_cache_key(
&self,
prefix: &str,
tenant_override: Option<i64>,
epoch: &str,
login_id: &str,
component: &str,
) -> String {
let tenant = tenant_override
.or(self.tenant_id)
.map(|t| t.to_string())
.unwrap_or_else(|| "_".to_string());
format!(
"{}v{}:{}:{}:{}",
prefix,
epoch,
tenant,
encode_key_component(login_id),
encode_key_component(component)
)
}
fn decision_version_key(&self, login_id: &str) -> String {
format!(
"{}{}",
DECISION_VERSION_KEY_PREFIX,
encode_key_component(login_id)
)
}
async fn current_decision_epoch(&self, login_id: &str) -> GarrisonResult<String> {
match self.dao.as_ref() {
Some(dao) => {
let key = self.decision_version_key(login_id);
match dao.get(&key).await? {
Some(v) if !v.is_empty() => Ok(v),
_ => Ok(SENTINEL_DECISION_EPOCH.to_string()),
}
},
None => Ok(SENTINEL_DECISION_EPOCH.to_string()),
}
}
pub fn with_role_hierarchy(mut self, hierarchy: HashMap<String, Vec<String>>) -> Self {
self.role_hierarchy = hierarchy;
self
}
pub fn with_plugin_manager(mut self, pm: Arc<GarrisonPluginManager>) -> Self {
self.plugin_manager = Some(pm);
self
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
pub fn with_firewall_hook(mut self, hook: Arc<dyn GarrisonFirewallCheckHook>) -> Self {
self.firewall_hook = Some(hook);
self
}
#[cfg(feature = "listener")]
pub fn with_listener_manager(mut self, lm: Arc<GarrisonListenerManager>) -> Self {
self.listener_manager = Some(lm);
self
}
fn expand_roles(&self, roles: &[String]) -> HashSet<String> {
let mut result = HashSet::new();
let mut stack: Vec<String> = roles.to_vec();
while let Some(r) = stack.pop() {
if result.insert(r.clone()) {
if let Some(implied) = self.role_hierarchy.get(&r) {
stack.extend(implied.iter().cloned());
}
}
}
result
}
pub async fn cache_permission(
&self,
login_id: &str,
permission: &str,
result: bool,
ttl_seconds: u64,
) -> GarrisonResult<()> {
self.cache_permission_with(None, login_id, permission, result, ttl_seconds)
.await
}
pub async fn cache_permission_with(
&self,
tenant_override: Option<i64>,
login_id: &str,
permission: &str,
result: bool,
ttl_seconds: u64,
) -> GarrisonResult<()> {
if let Some(dao) = &self.dao {
let epoch = self.current_decision_epoch(login_id).await?;
let key = self.decision_cache_key(
PERM_CACHE_KEY_PREFIX,
tenant_override,
&epoch,
login_id,
permission,
);
dao.set(&key, if result { "true" } else { "false" }, ttl_seconds)
.await?;
}
Ok(())
}
pub async fn get_cached_permission(
&self,
login_id: &str,
permission: &str,
) -> GarrisonResult<Option<bool>> {
self.get_cached_permission_with(None, login_id, permission)
.await
}
pub async fn get_cached_permission_with(
&self,
tenant_override: Option<i64>,
login_id: &str,
permission: &str,
) -> GarrisonResult<Option<bool>> {
if let Some(dao) = &self.dao {
let epoch = self.current_decision_epoch(login_id).await?;
let key = self.decision_cache_key(
PERM_CACHE_KEY_PREFIX,
tenant_override,
&epoch,
login_id,
permission,
);
match dao.get(&key).await? {
Some(v) => Ok(Some(v == "true")),
None => Ok(None),
}
} else {
Ok(None)
}
}
pub async fn invalidate_permission_cache(&self, login_id: &str) -> GarrisonResult<()> {
if let Some(dao) = &self.dao {
let key = self.decision_version_key(login_id);
let epoch = uuid::Uuid::new_v4().simple().to_string();
dao.set(&key, &epoch, DECISION_VERSION_KEY_TTL_SECS).await?;
}
Ok(())
}
}
#[async_trait]
impl GarrisonPermissionStrategy for GarrisonPermissionStrategyDefault {
async fn invalidate_login_cache(&self, login_id: &str) -> GarrisonResult<()> {
if let Err(e) = self.invalidate_permission_cache(login_id).await {
tracing::warn!(
login_id = login_id,
error = %e,
"{}", crate::i18n::translate_detail("logs-strategy-permission-cache-invalidate-failed", &[])
);
}
Ok(())
}
fn firewall_hook_injected(&self) -> bool {
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
{
self.firewall_hook.is_some()
}
#[cfg(not(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
)))]
{
false
}
}
async fn get_permission_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
self.interface
.get_permission_list_with_type(login_id, &self.login_type)
.await
}
async fn get_role_list(&self, login_id: &str) -> GarrisonResult<Vec<String>> {
self.interface
.get_role_list_with_type(login_id, &self.login_type)
.await
}
async fn check_permission(&self, login_id: &str, permission: &str) -> GarrisonResult<bool> {
self.check_permission_scoped(self.tenant_id, None, login_id, permission)
.await
}
async fn check_permission_in_tenant(
&self,
tenant_id: i64,
login_id: &str,
permission: &str,
) -> GarrisonResult<bool> {
self.check_permission_scoped(Some(tenant_id), Some(tenant_id), login_id, permission)
.await
}
async fn check_role_in_tenant(
&self,
tenant_id: i64,
login_id: &str,
role: &str,
) -> GarrisonResult<bool> {
self.check_role_scoped(tenant_id, login_id, role).await
}
async fn check_role(&self, login_id: &str, role: &str) -> GarrisonResult<bool> {
if role.is_empty() {
return Err(GarrisonError::InvalidParam(
"strategy-role-empty::".to_string(),
));
}
let roles = self.get_role_list(login_id).await?;
if !self.role_hierarchy.is_empty() {
let expanded = self.expand_roles(&roles);
Ok(expanded.contains(role))
} else {
Ok(roles.iter().any(|r| r == role))
}
}
async fn check_role_any(&self, login_id: &str, roles: &[&str]) -> GarrisonResult<bool> {
let user_roles = self.get_role_list(login_id).await?;
if !self.role_hierarchy.is_empty() {
let expanded = self.expand_roles(&user_roles);
Ok(roles.iter().any(|r| expanded.contains(*r)))
} else {
Ok(roles.iter().any(|r| user_roles.iter().any(|ur| ur == r)))
}
}
async fn check_role_all(&self, login_id: &str, roles: &[&str]) -> GarrisonResult<bool> {
let user_roles = self.get_role_list(login_id).await?;
if !self.role_hierarchy.is_empty() {
let expanded = self.expand_roles(&user_roles);
Ok(roles.iter().all(|r| expanded.contains(*r)))
} else {
Ok(roles.iter().all(|r| user_roles.iter().any(|ur| ur == r)))
}
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
async fn check_login_hooks(&self, login_id: &str, ctx: &LoginContext) -> GarrisonResult<()> {
let Some(hook) = &self.firewall_hook else {
#[cfg(feature = "firewall")]
tracing::error!(
"firewall feature enabled but GarrisonFirewallCheckHook not injected \
(builder auto-wire may be broken)"
);
return Ok(());
};
if let Err(e) = hook.check_login_frequency(ctx).await {
self.broadcast_firewall_block(login_id, &e).await;
return Err(e);
}
if let Err(e) = hook.check_brute_force(ctx).await {
self.broadcast_firewall_block(login_id, &e).await;
return Err(e);
}
if let Err(e) = hook.check_geo_anomaly(ctx).await {
self.broadcast_firewall_block(login_id, &e).await;
return Err(e);
}
if let Err(e) = hook.check_token_reuse(ctx).await {
self.broadcast_firewall_block(login_id, &e).await;
return Err(e);
}
if let Err(e) = hook.check_device_anomaly(ctx).await {
self.broadcast_firewall_block(login_id, &e).await;
return Err(e);
}
Ok(())
}
}
impl GarrisonPermissionStrategyDefault {
async fn check_permission_scoped(
&self,
cache_tenant: Option<i64>,
data_tenant: Option<i64>,
login_id: &str,
permission: &str,
) -> GarrisonResult<bool> {
if permission.is_empty() {
return Err(GarrisonError::InvalidParam(
"strategy-perm-empty::".to_string(),
));
}
if let Some(pm) = &self.plugin_manager {
pm.on_permission_check(login_id, permission);
}
if self.dao.is_some() {
if let Ok(Some(cached)) = self
.get_cached_permission_with(cache_tenant, login_id, permission)
.await
{
return Ok(cached);
}
}
let result = if let Some(pc) = &self.permission_checker {
match data_tenant {
Some(t) => pc.has_permission_in_tenant(t, login_id, permission).await?,
None => pc.has_permission(login_id, permission).await?,
}
} else {
let permissions = match data_tenant {
Some(t) => {
self.interface
.get_permission_list_in_tenant(t, login_id)
.await?
},
None => self.get_permission_list(login_id).await?,
};
permissions.iter().any(|p| p == permission)
};
if let Some(_dao) = &self.dao {
if let Err(e) = self
.cache_permission_with(
cache_tenant,
login_id,
permission,
result,
DECISION_CACHE_TTL_SECS,
)
.await
{
tracing::warn!(
"permission cache write failed (login_id={}, perm={}): {}",
login_id,
permission,
e
);
}
}
Ok(result)
}
async fn check_role_scoped(
&self,
tenant_id: i64,
login_id: &str,
role: &str,
) -> GarrisonResult<bool> {
if role.is_empty() {
return Err(GarrisonError::InvalidParam(
"strategy-role-empty::".to_string(),
));
}
let cached_epoch = match self.dao.as_ref() {
Some(_) => self.current_decision_epoch(login_id).await.ok(),
None => None,
};
if let (Some(dao), Some(epoch)) = (&self.dao, cached_epoch.clone()) {
let key = self.decision_cache_key(
ROLE_CACHE_KEY_PREFIX,
Some(tenant_id),
&epoch,
login_id,
role,
);
if let Ok(Some(cached)) = dao.get(&key).await {
return Ok(cached == "true");
}
}
let roles = self
.interface
.get_role_list_in_tenant(tenant_id, login_id)
.await?;
let result = if !self.role_hierarchy.is_empty() {
let expanded = self.expand_roles(&roles);
expanded.contains(role)
} else {
roles.iter().any(|r| r == role)
};
if let (Some(dao), Some(epoch)) = (&self.dao, cached_epoch) {
let key = self.decision_cache_key(
ROLE_CACHE_KEY_PREFIX,
Some(tenant_id),
&epoch,
login_id,
role,
);
if let Err(e) = dao
.set(
&key,
if result { "true" } else { "false" },
DECISION_CACHE_TTL_SECS,
)
.await
{
tracing::warn!(
"{}",
crate::i18n::translate_detail(
"logs-strategy-role-cache-write-failed",
&[
("login_id", login_id),
("role", role),
("error", e.to_string().as_str()),
]
)
);
}
}
Ok(result)
}
#[cfg(any(
feature = "sms-rate-limit",
feature = "firewall-ratelimit",
feature = "firewall-bruteforce",
feature = "firewall-ddos",
feature = "firewall",
feature = "oauth2-server"
))]
#[cfg_attr(not(feature = "listener"), allow(unused_variables))]
async fn broadcast_firewall_block(&self, login_id: &str, e: &GarrisonError) {
#[cfg(feature = "listener")]
if let Some(lm) = &self.listener_manager {
lm.broadcast(&GarrisonEvent::FirewallBlock {
login_id: login_id.to_string(),
reason: e.to_string(),
request_context: None,
})
.await;
}
}
}