use super::*;
impl GarrisonLogicDefault {
#[cfg(any(feature = "protocol-jwt", feature = "firewall-bruteforce"))]
pub(crate) fn dao(&self) -> std::sync::Arc<dyn crate::dao::GarrisonDao> {
self.session.dao().clone()
}
#[cfg(all(test, feature = "firewall-bruteforce"))]
pub(crate) fn firewall_hook_injected(&self) -> bool {
self.firewall.firewall_hook_injected()
}
pub fn new(
session: Arc<GarrisonSession>,
config: Arc<GarrisonConfig>,
firewall: Arc<dyn GarrisonPermissionStrategy>,
disable_repository: Arc<dyn crate::account::disable::DisableRepository>,
) -> Self {
Self {
session,
config,
firewall,
plugin_manager: None,
#[cfg(feature = "listener")]
listener_manager: None,
auth_logic: None,
permission_checker: None,
#[cfg(feature = "metrics-prometheus")]
metrics: None,
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
password_hasher: None,
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
user_repository: None,
login_type: "default".to_string(),
jwt_mode: JwtMode::default(),
#[cfg(all(feature = "protocol-jwt", feature = "db-sqlite"))]
refresh_token_rotation: None,
renewal_locks: DashMap::new(),
clock: Arc::new(SystemClock::new()),
#[cfg(feature = "security-extra")]
anomaly_detectors: None,
#[cfg(feature = "security-extra")]
alert_listener_manager: None,
#[cfg(feature = "device-binding")]
device_binding_policy: None,
disable_repository,
#[cfg(feature = "three-tier-cache")]
user_cache_service: None,
marker: None,
#[cfg(all(feature = "protocol-apikey", feature = "firewall-bruteforce"))]
brute_force_strategy: std::sync::OnceLock::new(),
}
}
pub fn with_plugin_manager(mut self, pm: Arc<GarrisonPluginManager>) -> Self {
self.plugin_manager = Some(pm);
self
}
#[cfg(feature = "listener")]
pub fn with_listener_manager(mut self, lm: Arc<GarrisonListenerManager>) -> Self {
self.listener_manager = Some(lm);
self
}
pub fn with_auth_logic(mut self, auth: Arc<dyn AuthLogic>) -> Self {
self.auth_logic = Some(auth);
self
}
pub fn with_permission_checker(mut self, pc: Arc<dyn PermissionChecker>) -> Self {
self.permission_checker = Some(pc);
self
}
#[cfg(feature = "metrics-prometheus")]
pub fn with_metrics(mut self, metrics: Arc<crate::observability::GarrisonMetrics>) -> Self {
self.metrics = Some(metrics);
self
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
pub fn with_password_hasher(
mut self,
hasher: Arc<dyn crate::account::credential::password::PasswordHasher>,
) -> Self {
self.password_hasher = Some(hasher);
self
}
#[cfg(all(feature = "account-credential", feature = "db-sqlite"))]
pub fn with_user_repository(
mut self,
repo: Arc<dyn crate::dao::repository::UserRepository>,
) -> Self {
self.user_repository = Some(repo);
self
}
pub fn with_login_type(mut self, login_type: &str) -> Self {
self.login_type = login_type.to_string();
self
}
pub fn with_jwt_mode(mut self, mode: JwtMode) -> Self {
self.jwt_mode = mode;
self
}
pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
#[cfg(all(feature = "protocol-jwt", feature = "db-sqlite"))]
pub fn with_refresh_token_rotation(
mut self,
rtr: crate::protocol::jwt::refresh::RefreshTokenRotation,
) -> Self {
self.refresh_token_rotation = Some(rtr);
self
}
#[cfg(feature = "security-extra")]
pub fn with_anomaly_detector(
mut self,
detector: Arc<dyn crate::strategy::alert::AnomalyDetector>,
) -> Self {
self.anomaly_detectors
.get_or_insert_with(Vec::new)
.push(detector);
self
}
#[cfg(feature = "security-extra")]
pub fn with_alert_listener_manager(
mut self,
manager: Arc<crate::strategy::alert::AlertListenerManager>,
) -> Self {
self.alert_listener_manager = Some(manager);
self
}
#[cfg(feature = "device-binding")]
pub fn with_device_binding_policy(
mut self,
policy: Arc<dyn crate::strategy::device_binding::DeviceBindingPolicy>,
) -> Self {
self.device_binding_policy = Some(policy);
self
}
#[cfg(feature = "three-tier-cache")]
pub fn with_user_cache_service(mut self, service: Arc<crate::cache::UserCacheService>) -> Self {
self.user_cache_service = Some(service);
self
}
pub fn with_marker(mut self, marker: &'static str) -> Self {
self.marker = Some(marker);
self
}
#[cfg(feature = "protocol-apikey")]
pub async fn check_api_key(&self, namespace: &str) -> GarrisonResult<()> {
let key = match current_token() {
Ok(t) => t,
Err(_) => {
return Err(GarrisonError::NotLogin("stp-no-api-key::".to_string()));
},
};
let handler = crate::protocol::apikey::ApiKeyHandler::new(self.session.dao().clone());
#[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 = self.brute_force_strategy.get_or_init(|| {
Arc::new(BruteForceStrategy::new(
BruteForceConfig::default(),
self.session.dao().clone(),
))
});
let fw_ctx = FirewallContext::new(&ip);
if strategy.is_blocked(&fw_ctx).await? {
return Err(GarrisonError::FirewallBlocked(format!(
"stp-apikey-ip-blocked::{}",
ip
)));
}
return match handler.verify_with_namespace(&key, namespace).await {
Ok(_) => Ok(()),
Err(e) => {
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 auth result, original auth error is still returned)"
);
}
Err(e)
},
};
}
handler.verify_with_namespace(&key, namespace).await?;
Ok(())
}
#[cfg(not(feature = "protocol-apikey"))]
pub async fn check_api_key(&self, _namespace: &str) -> GarrisonResult<()> {
Err(GarrisonError::Config(
"stp-apikey-feature-required::".to_string(),
))
}
}
#[cfg(all(test, not(feature = "protocol-apikey")))]
mod no_feature_tests {
use super::*;
use crate::config::GarrisonConfig;
use crate::dao::InMemoryDao;
use crate::manager::GarrisonManager;
use crate::stp::mock::MockInterface;
use serial_test::serial;
#[serial]
#[tokio::test]
async fn check_api_key_without_feature_returns_config_error() {
GarrisonManager::reset_for_test();
let dao: std::sync::Arc<dyn crate::dao::GarrisonDao> =
std::sync::Arc::new(InMemoryDao::new());
let config = std::sync::Arc::new(GarrisonConfig::default());
let interface: std::sync::Arc<dyn crate::stp::GarrisonInterface> =
std::sync::Arc::new(MockInterface);
GarrisonManager::builder()
.dao(dao)
.config(config)
.interface(interface)
.build()
.await
.unwrap();
let result = GarrisonUtil::check_api_key("any-namespace").await;
assert!(
matches!(result, Err(GarrisonError::Config(ref m)) if m.contains("stp-apikey-feature-required")),
"feature 关闭时应返回 Err(Config),实际: {:?}",
result
);
}
}