use super::*;
use crate::error::{GarrisonError, GarrisonResult};
use crate::loc;
use confers::config::ConfigBuilder;
impl Default for TenantIsolationConfig {
fn default() -> Self {
Self {
enabled: false,
resolver: TenantResolverKind::Header,
}
}
}
impl Default for PasswordHasherConfig {
fn default() -> Self {
Self {
algorithm: "argon2id".to_string(),
argon2_m_cost: ARGON2_MIN_M_COST,
argon2_t_cost: 2,
argon2_p_cost: 1,
bcrypt_cost: 12,
allow_weak_argon2_params: false,
argon2_pool_size: DEFAULT_ARGON2_POOL_SIZE,
}
}
}
impl PasswordHasherConfig {
#[cfg(feature = "account-credential")]
pub fn build_hasher(
&self,
) -> GarrisonResult<std::sync::Arc<dyn crate::account::credential::PasswordHasher>> {
match self.algorithm.as_str() {
"argon2id" => {
use crate::account::credential::password::Argon2Hasher;
self.validate_argon2_params()?;
let (m, t, p) = (self.argon2_m_cost, self.argon2_t_cost, self.argon2_p_cost);
let hasher =
Argon2Hasher::with_params(m, t, p).with_pool(self.argon2_pool_size as usize);
Ok(std::sync::Arc::new(hasher))
},
"bcrypt" => {
use crate::account::credential::password::BcryptHasher;
self.validate_bcrypt_cost()?;
let hasher = BcryptHasher::with_cost(self.bcrypt_cost);
Ok(std::sync::Arc::new(hasher))
},
other => Err(GarrisonError::Config(format!(
"config-password-hash-algorithm-unsupported::{}",
other
))),
}
}
fn validate_argon2_params(&self) -> GarrisonResult<()> {
if self.argon2_t_cost == 0 || self.argon2_p_cost == 0 {
let which = if self.argon2_t_cost == 0 {
"t_cost"
} else {
"p_cost"
};
return Err(GarrisonError::Config(format!(
"config-password-hash-argon2-param-invalid::{which}"
)));
}
if !(ARGON2_POOL_SIZE_MIN..=ARGON2_POOL_SIZE_MAX).contains(&self.argon2_pool_size) {
return Err(GarrisonError::Config(format!(
"config-password-hash-argon2-pool-size-out-of-range::{} (allowed {}-{})",
self.argon2_pool_size, ARGON2_POOL_SIZE_MIN, ARGON2_POOL_SIZE_MAX
)));
}
if self.argon2_m_cost >= ARGON2_MIN_M_COST {
return Ok(());
}
if !self.allow_weak_argon2_params {
return Err(GarrisonError::Config(format!(
"config-password-hash-argon2-m-below-floor::{} (min {})::{}",
self.argon2_m_cost, ARGON2_MIN_M_COST, self.algorithm
)));
}
let cost = self.argon2_m_cost.to_string();
let floor = ARGON2_MIN_M_COST.to_string();
tracing::warn!(
"{}",
crate::i18n::translate_detail(
"logs-config-argon2-weak-params-accepted",
&[("cost", cost.as_str()), ("floor", floor.as_str())]
)
);
Ok(())
}
fn validate_bcrypt_cost(&self) -> GarrisonResult<()> {
if (BCRYPT_MIN_COST..=BCRYPT_MAX_COST).contains(&self.bcrypt_cost) {
return Ok(());
}
Err(GarrisonError::Config(format!(
"config-password-hash-bcrypt-cost-out-of-range::{} (allowed {}-{})",
self.bcrypt_cost, BCRYPT_MIN_COST, BCRYPT_MAX_COST
)))
}
}
impl std::fmt::Debug for GarrisonConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut value = match serde_json::to_value(self) {
Ok(v) => v,
Err(_) => serde_json::json!({
"token_name": self.token_name,
"token_style": self.token_style,
"timeout": self.timeout,
}),
};
if let serde_json::Value::Object(ref mut map) = value {
redact_fields(map, DEBUG_REDACTED_FIELDS.iter().copied());
}
f.write_str("GarrisonConfig ")?;
std::fmt::Debug::fmt(&value, f)
}
}
const DEBUG_REDACTED_FIELDS: &[&str] = &[
"jwt_secret",
"jwt_rsa_private_key_pem",
"jwt_ec_private_key_pem",
"jwt_ed_private_key_pem",
];
fn redact_fields<I>(map: &mut serde_json::Map<String, serde_json::Value>, keys: I)
where
I: IntoIterator,
I::Item: std::ops::Deref<Target = str>,
{
for key in keys {
map.insert(
key.to_string(),
serde_json::Value::String("<redacted>".to_string()),
);
}
}
impl GarrisonConfig {
pub fn default_config() -> Self {
let config = Self {
token_name: DEFAULT_TOKEN_NAME.to_string(),
timeout: DEFAULT_TIMEOUT,
active_timeout: DEFAULT_ACTIVE_TIMEOUT,
is_read_cookie: true,
is_read_header: true,
is_read_body: DEFAULT_IS_READ_BODY,
is_write_header: true,
is_write_cookie: false,
token_style: "uuid".to_string(),
throw_on_not_login: true,
cookie_secure: DEFAULT_COOKIE_SECURE,
cookie_same_site: DEFAULT_COOKIE_SAME_SITE.to_string(),
jwt_algorithm: DEFAULT_JWT_ALGORITHM.to_string(),
jwt_secret: default_jwt_secret(),
jwt_rsa_private_key_pem: None,
jwt_ec_private_key_pem: None,
jwt_ed_private_key_pem: None,
sign_window_seconds: DEFAULT_SIGN_WINDOW_SECONDS,
sso_ticket_ttl_seconds: DEFAULT_SSO_TICKET_TTL_SECONDS,
jwks_retention_secs: DEFAULT_JWKS_RETENTION_SECS,
remember_me_enabled: false,
remember_me_timeout: REMEMBER_ME_DEFAULT_TIMEOUT,
seed_primary_amr: true,
login_id_max_len: DEFAULT_LOGIN_ID_MAX_LEN,
session_hover_timeout: DEFAULT_SESSION_HOVER_TIMEOUT,
frontend_separation: DEFAULT_FRONTEND_SEPARATION,
auto_renewal_threshold: DEFAULT_AUTO_RENEWAL_THRESHOLD,
token_map_cleanup_interval_secs: DEFAULT_TOKEN_MAP_CLEANUP_INTERVAL,
#[cfg(feature = "three-tier-cache")]
l1_cache_ttl_secs: DEFAULT_L1_CACHE_TTL_SECS,
#[cfg(feature = "three-tier-cache")]
l2_cache_ttl_secs: DEFAULT_L2_CACHE_TTL_SECS,
#[cfg(feature = "three-tier-cache")]
l1_cache_capacity: DEFAULT_L1_CACHE_CAPACITY,
#[cfg(feature = "session-extra")]
login_token_map_persist_interval_secs: DEFAULT_LOGIN_TOKEN_MAP_PERSIST_INTERVAL_SECS,
#[cfg(feature = "session-extra")]
anon_session_timeout: DEFAULT_ANON_SESSION_TIMEOUT_SECS,
is_concurrent: DEFAULT_IS_CONCURRENT,
is_share: DEFAULT_IS_SHARE,
max_login_count: DEFAULT_MAX_LOGIN_COUNT,
device_binding_mode: DEFAULT_DEVICE_BINDING_MODE.to_string(),
replaced_login_exit_mode: ReplacedLoginExitMode::default(),
overflow_logout_mode: OverflowLogoutMode::default(),
#[cfg(feature = "session-hijack-detection")]
session_hijack_mode: SessionHijackMode::default(),
enable_jwt_revocation: false,
allow_stateless_jwt_no_revocation: false,
require_tenant_bound_jwt: false,
require_session_tenant_binding: false,
recent_reuse_behaviour: RecentReuseBehaviour::default(),
refresh_grace_period_secs: DEFAULT_REFRESH_GRACE_PERIOD_SECS,
refresh_grace_max_uses: DEFAULT_REFRESH_GRACE_MAX_USES,
audit_mask_mode: AuditMaskMode::default(),
tenant_isolation: TenantIsolationConfig::default(),
password_hasher: PasswordHasherConfig::default(),
mfa: MfaConfig::default(),
#[cfg(feature = "web-cors")]
cors_config: CorsConfig::default(),
#[cfg(feature = "web-csrf")]
csrf_config: CsrfConfig::default(),
#[cfg(feature = "rate-limit-redis")]
rate_limit_backend: RateLimitBackend::default(),
#[cfg(feature = "firewall-waf")]
waf_enabled_hooks: Vec::new(),
#[cfg(feature = "firewall-waf")]
waf_white_paths: Vec::new(),
#[cfg(feature = "firewall-waf")]
waf_black_paths: Vec::new(),
#[cfg(feature = "firewall-waf")]
waf_allowed_hosts: Vec::new(),
#[cfg(feature = "firewall-waf")]
waf_allowed_methods: Vec::new(),
#[cfg(feature = "firewall-waf")]
waf_banned_headers: Vec::new(),
#[cfg(feature = "firewall-waf")]
waf_banned_params: Vec::new(),
#[cfg(feature = "sms-rate-limit")]
sms_hourly_limit: 5,
#[cfg(feature = "sms-rate-limit")]
sms_daily_limit: 10,
#[cfg(feature = "sms-rate-limit")]
sms_verify_max_attempts: 3,
#[cfg(feature = "sms-rate-limit")]
sms_unverified_threshold: 3,
#[cfg(feature = "email-verification")]
email_hourly_limit: 5,
#[cfg(feature = "email-verification")]
email_daily_limit: 10,
#[cfg(feature = "email-verification")]
email_verify_max_attempts: 3,
#[cfg(feature = "email-verification")]
email_unverified_threshold: 3,
#[cfg(feature = "email-verification")]
email_code_ttl: 600,
#[cfg(feature = "anomalous-detector-dual")]
anomalous_analyzer_interval_secs: DEFAULT_ANOMALOUS_ANALYZER_INTERVAL_SECS,
#[cfg(feature = "anomalous-detector-dual")]
anomalous_analyzer_burst_threshold: DEFAULT_ANOMALOUS_BURST_THRESHOLD,
#[cfg(feature = "credit-metering")]
credit: None,
watcher: None,
};
config.with_watcher()
}
pub fn load(toml_path: Option<&str>) -> GarrisonResult<Self> {
Self::load_with_deprecations(
toml_path,
deprecation::deprecations(),
env!("CARGO_PKG_VERSION"),
)
}
pub(super) fn load_with_deprecations(
toml_path: Option<&str>,
registry: &[deprecation::Deprecation],
current_version: &'static str,
) -> GarrisonResult<Self> {
let env_source = {
let s = confers::config::EnvSource::with_prefix(ENV_PREFIX).separator("__");
#[cfg(feature = "rate-limit-redis")]
let s = s.exclude_keys(["rate_limit_backend"]);
#[cfg(feature = "web-cors")]
let s = s.exclude_keys(["cors_allowed_origins"]);
s
};
let mut builder = ConfigBuilder::<Self>::new()
.default("token_name", ConfigValue::string(DEFAULT_TOKEN_NAME))
.default("timeout", ConfigValue::integer(DEFAULT_TIMEOUT))
.default(
"active_timeout",
ConfigValue::integer(DEFAULT_ACTIVE_TIMEOUT),
)
.default("is_read_cookie", ConfigValue::bool(true))
.default("is_read_header", ConfigValue::bool(true))
.default("is_read_body", ConfigValue::bool(DEFAULT_IS_READ_BODY))
.default("is_write_header", ConfigValue::bool(true))
.default("is_write_cookie", ConfigValue::bool(false))
.default("token_style", ConfigValue::string("uuid"))
.default("throw_on_not_login", ConfigValue::bool(true))
.default("cookie_secure", ConfigValue::bool(DEFAULT_COOKIE_SECURE))
.default(
"cookie_same_site",
ConfigValue::string(DEFAULT_COOKIE_SAME_SITE),
)
.default("jwt_algorithm", ConfigValue::string(DEFAULT_JWT_ALGORITHM))
.default("jwt_secret", ConfigValue::string(""))
.default(
"sign_window_seconds",
ConfigValue::integer(DEFAULT_SIGN_WINDOW_SECONDS),
)
.default(
"sso_ticket_ttl_seconds",
ConfigValue::uint(DEFAULT_SSO_TICKET_TTL_SECONDS),
)
.default(
"jwks_retention_secs",
ConfigValue::uint(DEFAULT_JWKS_RETENTION_SECS),
)
.default("remember_me_enabled", ConfigValue::bool(false))
.default(
"remember_me_timeout",
ConfigValue::integer(REMEMBER_ME_DEFAULT_TIMEOUT),
)
.default("seed_primary_amr", ConfigValue::bool(true))
.default(
"login_id_max_len",
ConfigValue::uint(DEFAULT_LOGIN_ID_MAX_LEN as u64),
)
.default(
"session_hover_timeout",
ConfigValue::integer(DEFAULT_SESSION_HOVER_TIMEOUT),
)
.default(
"frontend_separation",
ConfigValue::bool(DEFAULT_FRONTEND_SEPARATION),
)
.default(
"auto_renewal_threshold",
ConfigValue::integer(DEFAULT_AUTO_RENEWAL_THRESHOLD),
)
.default(
"token_map_cleanup_interval_secs",
ConfigValue::integer(DEFAULT_TOKEN_MAP_CLEANUP_INTERVAL),
)
.default("is_concurrent", ConfigValue::bool(DEFAULT_IS_CONCURRENT))
.default("is_share", ConfigValue::bool(DEFAULT_IS_SHARE))
.default(
"max_login_count",
ConfigValue::uint(DEFAULT_MAX_LOGIN_COUNT as u64),
)
.default(
"device_binding_mode",
ConfigValue::string(DEFAULT_DEVICE_BINDING_MODE),
)
.default(
"replaced_login_exit_mode",
ConfigValue::string(DEFAULT_REPLACED_LOGIN_EXIT_MODE),
)
.default(
"overflow_logout_mode",
ConfigValue::string(DEFAULT_OVERFLOW_LOGOUT_MODE),
)
.default("audit_mask_mode", ConfigValue::string("partial"))
.default(
"recent_reuse_behaviour",
ConfigValue::string(DEFAULT_RECENT_REUSE_BEHAVIOUR),
)
.default(
"refresh_grace_period_secs",
ConfigValue::integer(DEFAULT_REFRESH_GRACE_PERIOD_SECS),
)
.default(
"refresh_grace_max_uses",
ConfigValue::uint(DEFAULT_REFRESH_GRACE_MAX_USES as u64),
)
.default("require_tenant_bound_jwt", ConfigValue::bool(false))
.default("require_session_tenant_binding", ConfigValue::bool(false));
#[cfg(feature = "session-extra")]
{
builder = Self::apply_session_extra_defaults(builder);
}
#[cfg(feature = "three-tier-cache")]
{
builder = Self::apply_three_tier_cache_defaults(builder);
}
#[cfg(feature = "sms-rate-limit")]
{
builder = Self::apply_sms_rate_limit_defaults(builder);
}
#[cfg(feature = "email-verification")]
{
builder = Self::apply_email_verification_defaults(builder);
}
#[cfg(feature = "anomalous-detector-dual")]
{
builder = Self::apply_anomalous_defaults(builder);
}
if let Some(path) = toml_path {
const MAX_CONFIG_FILE_SIZE: usize = 10 * 1024 * 1024; if path.is_empty() {
return Err(GarrisonError::Config(loc!("config-path-empty", "")));
}
let file_source = confers_file_source(path, MAX_CONFIG_FILE_SIZE);
builder = builder.source(Box::new(file_source));
}
builder = builder.source(Box::new(env_source));
let deprecation_failures: std::sync::Arc<std::sync::Mutex<Vec<String>>> =
std::sync::Arc::default();
let failure_slot = std::sync::Arc::clone(&deprecation_failures);
let registry: Vec<deprecation::Deprecation> = registry.to_vec();
let new_key_defaults =
serde_json::to_value(Self::default_config()).unwrap_or(serde_json::Value::Null);
builder = builder.map_json(move |tree| {
if let Err(msgs) =
deprecation::apply_deprecations(tree, ®istry, current_version, &new_key_defaults)
{
*failure_slot.lock().unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail("config-deprecation-slot-lock-poisoned", &[],)
)
}) = msgs;
}
});
let config = builder.build().map_err(map_confers_build_error)?;
let failures = deprecation_failures
.lock()
.unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail("config-deprecation-slot-lock-poisoned", &[],)
)
})
.clone();
if !failures.is_empty() {
return Err(GarrisonError::Config(failures.join("; ")));
}
#[cfg_attr(
not(any(
feature = "web-cors",
feature = "web-csrf",
feature = "rate-limit-redis"
)),
allow(unused_mut)
)]
let mut config = config;
#[cfg(feature = "web-cors")]
apply_web_cors_env_override(&mut config);
#[cfg(feature = "web-csrf")]
apply_web_csrf_env_override(&mut config)?;
#[cfg(feature = "rate-limit-redis")]
apply_rate_limit_env_override(&mut config)?;
let config = config.with_watcher();
config.validate()?;
Ok(config)
}
pub fn with_watcher(mut self) -> Self {
if self.watcher.is_none() {
let (tx, _rx) = watch::channel(self.clone_for_watcher());
self.watcher = Some(tx);
}
self
}
fn clone_for_watcher(&self) -> Self {
let mut c = self.clone();
c.watcher = None;
c
}
pub fn validate(&self) -> GarrisonResult<()> {
self.validate_core()?;
self.validate_mfa()?;
self.validate_jwt_secret()?;
self.validate_session_config()?;
self.validate_device_binding()?;
self.validate_refresh_grace()?;
self.validate_feature_gated()?;
self.warn_memory_rate_limit_backend();
#[cfg(feature = "config-security-rules")]
self.validate_security_rules()?;
Ok(())
}
#[cfg(not(feature = "rate-limit-redis"))]
fn warn_memory_rate_limit_backend(&self) {
tracing::warn!(
backend = "memory",
"{}",
crate::i18n::translate_detail("logs-config-rate-limit-redis-feature-disabled", &[])
);
}
#[cfg(feature = "rate-limit-redis")]
fn warn_memory_rate_limit_backend(&self) {
if self.rate_limit_backend
== crate::strategy::rate_limiter_backend::RateLimitBackend::Memory
{
tracing::warn!(
backend = "memory",
"{}",
crate::i18n::translate_detail("logs-config-rate-limit-memory-backend", &[])
);
}
}
fn validate_refresh_grace(&self) -> GarrisonResult<()> {
if self.refresh_grace_period_secs < 0 {
return Err(GarrisonError::Config(format!(
"config-refresh-grace-period-negative::{}",
self.refresh_grace_period_secs
)));
}
if self.refresh_grace_max_uses < 1 {
return Err(GarrisonError::Config(format!(
"config-refresh-grace-max-uses-zero::{}",
self.refresh_grace_max_uses
)));
}
Ok(())
}
fn validate_core(&self) -> GarrisonResult<()> {
if !TOKEN_STYLES.contains(&self.token_style.as_str()) {
return Err(GarrisonError::Config(format!(
"config-unknown-token-style::{}",
self.token_style
)));
}
if self.timeout <= 0 {
return Err(GarrisonError::Config(
"config-timeout-must-positive::".to_string(),
));
}
if !COOKIE_SAME_SITE_VALUES.contains(&self.cookie_same_site.as_str()) {
return Err(GarrisonError::Config(format!(
"config-unknown-cookie-same-site::{}",
self.cookie_same_site
)));
}
if !JWT_ALGORITHMS.contains(&self.jwt_algorithm.as_str()) {
return Err(GarrisonError::Config(format!(
"config-jwt-algorithm-unsupported::{}",
self.jwt_algorithm
)));
}
let rsa_set = self.jwt_rsa_private_key_pem.is_some();
let ec_set = self.jwt_ec_private_key_pem.is_some();
let ed_set = self.jwt_ed_private_key_pem.is_some();
let configured_keys = rsa_set as u8 + ec_set as u8 + ed_set as u8;
if configured_keys > 1 {
return Err(GarrisonError::Config(
"config-jwt-key-multiple-types::".to_string(),
));
}
let is_asymmetric = matches!(self.jwt_algorithm.as_str(), "RS256" | "ES256" | "EdDSA");
let required_key_present = match self.jwt_algorithm.as_str() {
"RS256" => rsa_set,
"ES256" => ec_set,
"EdDSA" => ed_set,
_ => true,
};
if !required_key_present {
return Err(GarrisonError::Config(format!(
"config-jwt-key-missing::{}",
self.jwt_algorithm
)));
}
if !is_asymmetric && configured_keys > 0 {
return Err(GarrisonError::Config(format!(
"config-jwt-key-unexpected-for-hs::{}",
self.jwt_algorithm
)));
}
self.validate_password_hasher()?;
if self.jwks_retention_secs == 0 {
return Err(GarrisonError::Config(
"config-jwks-retention-must-positive::".to_string(),
));
}
Ok(())
}
fn validate_mfa(&self) -> GarrisonResult<()> {
crate::stp::mfa::validate_mfa_chains(&self.mfa.global_chain, &self.mfa.per_client_chains)
}
fn validate_password_hasher(&self) -> GarrisonResult<()> {
let ph = &self.password_hasher;
if !PASSWORD_HASH_ALGORITHMS.contains(&ph.algorithm.as_str()) {
return Err(GarrisonError::Config(format!(
"config-password-hash-algorithm-unsupported::{}",
ph.algorithm
)));
}
if ph.algorithm == "argon2id" {
ph.validate_argon2_params()
} else {
ph.validate_bcrypt_cost()
}
}
pub(super) fn validate_jwt_secret(&self) -> GarrisonResult<()> {
if self.token_style == "jwt" {
if matches!(self.jwt_algorithm.as_str(), "RS256" | "ES256" | "EdDSA") {
return Ok(());
}
self.validate_hs_secret_min_len()?;
return self.reject_weak_jwt_secret();
}
if self.token_style == "simple" {
let secret_len = self.jwt_secret.as_str().len();
if secret_len < 32 {
return Err(GarrisonError::Config(format!(
"config-jwt-secret-too-short::simple (min 32 bytes)::{}",
secret_len
)));
}
return self.reject_weak_jwt_secret();
}
Ok(())
}
const WEAK_JWT_SECRETS: &[&str] = &[
"secret",
"changeme",
"change_me",
"password",
"test",
"test123",
"key",
"default",
"admin",
"letmein",
"welcome",
"qwerty",
"abc123",
"123456",
"12345678",
"1234567890",
];
fn reject_weak_jwt_secret(&self) -> GarrisonResult<()> {
const PADDING_CHARS: &[char] = &[' ', '\t', '_', '-', '.', '=', '*', '~'];
let normalized = self
.jwt_secret
.as_str()
.trim_matches(PADDING_CHARS)
.to_lowercase();
if Self::WEAK_JWT_SECRETS.contains(&normalized.as_str()) {
return Err(GarrisonError::Config(
"config-jwt-secret-weak::blacklist hit (padded/case variants included)".to_string(),
));
}
Ok(())
}
fn validate_hs_secret_min_len(&self) -> GarrisonResult<()> {
let secret_len = self.jwt_secret.as_str().len();
if secret_len == 0 {
return Err(GarrisonError::Config(
"config-jwt-secret-empty::".to_string(),
));
}
let min_len = match self.jwt_algorithm.as_str() {
"HS256" => 32,
"HS384" => 48,
"HS512" => 64,
"RS256" | "ES256" | "EdDSA" => 0,
other => return Err(unsupported_jwt_algorithm(other)),
};
if secret_len < min_len {
return Err(GarrisonError::Config(format!(
"config-jwt-secret-too-short::{} (min {} bytes)::{}",
self.jwt_algorithm, min_len, secret_len
)));
}
Ok(())
}
fn validate_session_config(&self) -> GarrisonResult<()> {
if self.remember_me_enabled && self.remember_me_timeout <= self.timeout {
return Err(GarrisonError::Config(format!(
"config-remember-me-timeout-mismatch::{}::{}",
self.remember_me_timeout, self.timeout
)));
}
if !self.remember_me_enabled && self.remember_me_timeout <= 0 {
return Err(GarrisonError::Config(format!(
"config-remember-me-timeout-positive::{}",
self.remember_me_timeout
)));
}
if self.frontend_separation {
tracing::info!(
"frontend separation mode enabled: token read from Authorization header, no cookie set"
);
}
if self.auto_renewal_threshold != -1 && !(0..=100).contains(&self.auto_renewal_threshold) {
return Err(GarrisonError::Config(format!(
"config-auto-renewal-threshold-invalid::{}",
self.auto_renewal_threshold
)));
}
if self.is_share && !self.is_concurrent {
return Err(GarrisonError::Config(
"config-is-share-requires-concurrent::".to_string(),
));
}
const MAX_SESSION_HOVER_TIMEOUT_SECS: i64 = 315_360_000;
if self.session_hover_timeout > MAX_SESSION_HOVER_TIMEOUT_SECS {
return Err(GarrisonError::Config(format!(
"config-session-hover-timeout-exceeds::{}::{}",
self.session_hover_timeout, MAX_SESSION_HOVER_TIMEOUT_SECS
)));
}
Ok(())
}
fn validate_device_binding(&self) -> GarrisonResult<()> {
if !DEVICE_BINDING_MODES.contains(&self.device_binding_mode.as_str()) {
return Err(GarrisonError::Config(format!(
"config-unknown-device-binding-mode::{}",
self.device_binding_mode
)));
}
Ok(())
}
fn validate_feature_gated(&self) -> GarrisonResult<()> {
#[cfg(feature = "session-extra")]
self.validate_anon_session()?;
#[cfg(feature = "three-tier-cache")]
self.validate_three_tier_cache()?;
#[cfg(feature = "rate-limit-redis")]
self.validate_rate_limit_redis()?;
#[cfg(feature = "firewall-waf")]
self.validate_firewall_waf()?;
#[cfg(feature = "sms-rate-limit")]
self.validate_sms_rate_limit()?;
#[cfg(feature = "email-verification")]
self.validate_email_verification()?;
#[cfg(feature = "anomalous-detector-dual")]
self.validate_anomalous_detector()?;
#[cfg(feature = "web-cors")]
crate::web::cors::CorsConfig::validate(&self.cors_config)?;
Ok(())
}
#[cfg(feature = "session-extra")]
fn apply_session_extra_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
builder
.default(
"login_token_map_persist_interval_secs",
ConfigValue::uint(DEFAULT_LOGIN_TOKEN_MAP_PERSIST_INTERVAL_SECS),
)
.default(
"anon_session_timeout",
ConfigValue::uint(DEFAULT_ANON_SESSION_TIMEOUT_SECS),
)
}
#[cfg(feature = "three-tier-cache")]
fn apply_three_tier_cache_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
builder
.default(
"l1_cache_ttl_secs",
ConfigValue::uint(DEFAULT_L1_CACHE_TTL_SECS),
)
.default(
"l2_cache_ttl_secs",
ConfigValue::uint(DEFAULT_L2_CACHE_TTL_SECS),
)
.default(
"l1_cache_capacity",
ConfigValue::uint(DEFAULT_L1_CACHE_CAPACITY),
)
}
#[cfg(feature = "sms-rate-limit")]
fn apply_sms_rate_limit_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
builder
.default("sms_hourly_limit", ConfigValue::uint(5))
.default("sms_daily_limit", ConfigValue::uint(10))
.default("sms_verify_max_attempts", ConfigValue::uint(3))
.default("sms_unverified_threshold", ConfigValue::uint(3))
}
#[cfg(feature = "email-verification")]
fn apply_email_verification_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
builder
.default("email_hourly_limit", ConfigValue::uint(5))
.default("email_daily_limit", ConfigValue::uint(10))
.default("email_verify_max_attempts", ConfigValue::uint(3))
.default("email_unverified_threshold", ConfigValue::uint(3))
.default("email_code_ttl", ConfigValue::uint(600))
}
#[cfg(feature = "anomalous-detector-dual")]
fn apply_anomalous_defaults(builder: ConfigBuilder<Self>) -> ConfigBuilder<Self> {
builder
.default(
"anomalous_analyzer_interval_secs",
ConfigValue::uint(DEFAULT_ANOMALOUS_ANALYZER_INTERVAL_SECS),
)
.default(
"anomalous_analyzer_burst_threshold",
ConfigValue::uint(DEFAULT_ANOMALOUS_BURST_THRESHOLD.into()),
)
}
#[cfg(feature = "session-extra")]
fn validate_anon_session(&self) -> GarrisonResult<()> {
if self.anon_session_timeout == 0 {
return Err(GarrisonError::Config(
"config-anon-timeout-invalid::".to_string(),
));
}
Ok(())
}
#[cfg(feature = "three-tier-cache")]
fn validate_three_tier_cache(&self) -> GarrisonResult<()> {
if self.l1_cache_ttl_secs == 0 {
return Err(GarrisonError::Config("config-l1-ttl-invalid".to_string()));
}
if self.l2_cache_ttl_secs == 0 {
return Err(GarrisonError::Config("config-l2-ttl-invalid".to_string()));
}
if self.l1_cache_capacity == 0 {
return Err(GarrisonError::Config(
"config-l1-capacity-invalid".to_string(),
));
}
Ok(())
}
#[cfg(feature = "rate-limit-redis")]
fn validate_rate_limit_redis(&self) -> GarrisonResult<()> {
let redis_url = match &self.rate_limit_backend {
RateLimitBackend::Redis { redis_url } => redis_url,
_ => return Ok(()),
};
if !redis_url.is_empty() {
return Ok(());
}
Err(GarrisonError::Config(
"config-redis-url-empty::".to_string(),
))
}
#[cfg(feature = "firewall-waf")]
fn validate_firewall_waf(&self) -> GarrisonResult<()> {
for method in &self.waf_allowed_methods {
if method == &method.to_uppercase() {
continue;
}
return Err(GarrisonError::Config(format!(
"config-waf-method-case::{}",
method
)));
}
Ok(())
}
#[cfg(feature = "sms-rate-limit")]
fn validate_sms_rate_limit(&self) -> GarrisonResult<()> {
if self.sms_hourly_limit == 0 {
return Err(GarrisonError::Config(
"config-sms-hourly-invalid::".to_string(),
));
}
if self.sms_daily_limit < self.sms_hourly_limit {
return Err(GarrisonError::Config(
"config-sms-daily-invalid::".to_string(),
));
}
if self.sms_verify_max_attempts == 0 {
return Err(GarrisonError::Config(
"config-sms-max-attempts-invalid::".to_string(),
));
}
if self.sms_unverified_threshold == 0 {
return Err(GarrisonError::Config(
"config-sms-threshold-invalid::".to_string(),
));
}
Ok(())
}
#[cfg(feature = "email-verification")]
fn validate_email_verification(&self) -> GarrisonResult<()> {
if self.email_hourly_limit == 0 {
return Err(GarrisonError::Config(
"config-email-hourly-invalid::".to_string(),
));
}
if self.email_daily_limit < self.email_hourly_limit {
return Err(GarrisonError::Config(
"config-email-daily-invalid::".to_string(),
));
}
if self.email_verify_max_attempts == 0 {
return Err(GarrisonError::Config(
"config-email-max-attempts-invalid::".to_string(),
));
}
if self.email_unverified_threshold == 0 {
return Err(GarrisonError::Config(
"config-email-threshold-invalid::".to_string(),
));
}
if self.email_code_ttl == 0 {
return Err(GarrisonError::Config(
"config-email-ttl-invalid::".to_string(),
));
}
Ok(())
}
#[cfg(feature = "anomalous-detector-dual")]
fn validate_anomalous_detector(&self) -> GarrisonResult<()> {
if self.anomalous_analyzer_interval_secs < 60 {
return Err(GarrisonError::Config(
"config-anomalous-interval-invalid::".to_string(),
));
}
if self.anomalous_analyzer_burst_threshold == 0 {
return Err(GarrisonError::Config(
"config-anomalous-burst-invalid::".to_string(),
));
}
Ok(())
}
pub fn watch(&self) -> Option<watch::Receiver<GarrisonConfig>> {
self.watcher.as_ref().map(|tx| tx.subscribe())
}
pub fn update<F: FnOnce(&mut GarrisonConfig)>(&self, f: F) -> GarrisonResult<()> {
let Some(sender) = &self.watcher else {
return Ok(());
};
let mut new_config = sender.borrow().clone();
f(&mut new_config);
new_config.validate()?;
sender
.send(new_config)
.map_err(|_| GarrisonError::Config("config watcher closed".to_string()))?;
Ok(())
}
}
impl Default for GarrisonConfig {
fn default() -> Self {
Self::default_config()
}
}
#[cfg(feature = "web-cors")]
fn apply_web_cors_env_override(config: &mut GarrisonConfig) {
let Ok(val) = std::env::var("GARRISON_CORS_ALLOWED_ORIGINS") else {
return;
};
config.cors_config.allowed_origins = val
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
}
#[cfg(feature = "web-csrf")]
fn apply_web_csrf_env_override(config: &mut GarrisonConfig) -> GarrisonResult<()> {
let Ok(val) = std::env::var("GARRISON_CSRF_ENABLED") else {
return Ok(());
};
match val.to_lowercase().as_str() {
"true" => config.csrf_config.enabled = true,
"false" => config.csrf_config.enabled = false,
_ => {
return Err(GarrisonError::Config(format!(
"config-csrf-enabled-unsupported::{} (allowed: true/false, case-insensitive)",
val
)));
},
}
Ok(())
}
#[cfg(feature = "rate-limit-redis")]
pub fn parse_rate_limit_backend_env() -> GarrisonResult<Option<RateLimitBackend>> {
let Ok(val) = std::env::var("GARRISON_RATE_LIMIT_BACKEND") else {
return Ok(None);
};
match val.to_lowercase().as_str() {
"memory" => Ok(Some(RateLimitBackend::Memory)),
"redis" => {
let redis_url = std::env::var("GARRISON_REDIS_URL").unwrap_or_default();
Ok(Some(RateLimitBackend::Redis { redis_url }))
},
_ => Err(GarrisonError::Config(format!(
"config-rate-limit-backend-unsupported::{}",
val
))),
}
}
#[cfg(feature = "rate-limit-redis")]
fn apply_rate_limit_env_override(config: &mut GarrisonConfig) -> GarrisonResult<()> {
if let Some(backend) = parse_rate_limit_backend_env()? {
config.rate_limit_backend = backend;
}
Ok(())
}
fn confers_file_source(path: &str, max_size: usize) -> confers::config::FileSource {
confers::config::FileSource::new(path)
.with_priority(10)
.with_loader_config(
confers::loader::LoaderConfig::new()
.allow_absolute()
.max_size(max_size)
.redact_error_paths()
.with_format(confers::loader::Format::Toml),
)
}
fn map_confers_build_error(e: confers::ConfigError) -> GarrisonError {
use confers::ConfigError as CE;
match e {
CE::FileNotFound { filename, .. } => {
let name = filename.display().to_string();
GarrisonError::Config(loc!("config-open-failed", "", ("arg0", name.as_str())))
},
CE::SizeLimitExceeded { actual, limit } => {
let actual_str = actual.to_string();
let limit_str = limit.to_string();
GarrisonError::Config(loc!(
"config-too-large",
"",
("arg0", "config"),
("arg1", actual_str.as_str()),
("arg2", limit_str.as_str())
))
},
other => GarrisonError::Config(format!("config-confers-build-failed::{}", other)),
}
}
fn unsupported_jwt_algorithm(alg: &str) -> GarrisonError {
GarrisonError::Config(format!("config-jwt-algorithm-unsupported::{alg}"))
}