use std::net::IpAddr;
use std::sync::Arc;
use sdforge::cli::{CliCommandRegistration, CliHandlerRegistration};
use sdforge::core::{ApiError, HandlerArgs, HandlerFuture, HandlerState};
use sdforge::inventory;
use crate::backend::embedded::BackendEmbedded;
use crate::backend::AuthBackend;
use crate::dao::{GarrisonDao, GarrisonDaoOxcache};
use crate::error::{GarrisonError, GarrisonResult};
use crate::manager::GarrisonManager;
use crate::server::is_private_proxy_addr;
use crate::server::{AuthServerConfig, GarrisonAuthServer};
use crate::stp::GarrisonInterface;
inventory::submit! {
CliCommandRegistration::new(
"serve",
env!("CARGO_PKG_VERSION"),
"Run the dual-port Garrison auth server (env-driven; external 8080 / internal 8081 by default)",
"handle_serve_cmd",
)
.with_args(&[])
}
inventory::submit! { CliHandlerRegistration { name: "serve", handler: handle_serve_cmd } }
fn handle_serve_cmd(_args: HandlerArgs, _state: HandlerState) -> HandlerFuture {
Box::pin(async move {
serve_main()
.await
.map(|()| serde_json::Value::Null)
.map_err(|e| ApiError::internal_error(e.to_string(), "garrison.serve"))
})
}
struct SimpleInterface;
#[async_trait::async_trait]
impl GarrisonInterface for SimpleInterface {
async fn get_permission_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
async fn get_role_list(&self, _login_id: &str) -> GarrisonResult<Vec<String>> {
Ok(vec![])
}
}
#[derive(Debug, Clone, serde::Deserialize, confers::Config)]
#[config(env_prefix = "GARRISON_")]
pub struct AuthServerBootstrapConfig {
#[config(default = 8080)]
external_port: u16,
#[config(default = 8081)]
internal_port: u16,
external_bind: Option<String>,
internal_bind: Option<String>,
#[config(default = 100)]
rate_limit: u32,
internal_api_key: String,
trusted_proxies: Option<String>,
#[config(default = false)]
external_login_enabled: bool,
external_login_ack: Option<String>,
#[config(default = true)]
strict_security: bool,
#[config(default = 10)]
max_login_count: u32,
#[config(default = true)]
seed_primary_amr: bool,
field_encryption_keys: Option<String>,
field_encryption_tenant: Option<String>,
}
fn resolve_bind_addr(env_name: &str, raw: Option<&str>) -> GarrisonResult<IpAddr> {
match raw {
None => Ok(IpAddr::from([127, 0, 0, 1])),
Some(s) => s
.trim()
.parse::<IpAddr>()
.map_err(|_| GarrisonError::Config(format!("auth-server-bootstrap::{env_name}::{s}"))),
}
}
fn parse_trusted_proxies(spec: &str) -> GarrisonResult<Vec<IpAddr>> {
if spec.trim().is_empty() {
return Ok(vec![]);
}
let proxies: Vec<IpAddr> = spec
.split(',')
.map(|entry| {
let raw = entry.trim();
if raw.is_empty() {
return Err(GarrisonError::Config(
"auth-server-bootstrap-proxies-empty-entry::".to_string(),
));
}
raw.parse::<IpAddr>().map_err(|_| {
GarrisonError::Config(format!(
"auth-server-bootstrap::GARRISON_TRUSTED_PROXIES::{raw}"
))
})
})
.collect::<GarrisonResult<Vec<_>>>()?;
if let Some(public) = proxies.iter().find(|ip| !is_private_proxy_addr(ip)) {
return Err(GarrisonError::Config(format!(
"auth-server-bootstrap-proxy-not-private::{public}"
)));
}
Ok(proxies)
}
fn resolve_bootstrap_security(
bootstrap: &AuthServerBootstrapConfig,
) -> GarrisonResult<AuthServerConfig> {
let external_bind =
resolve_bind_addr("GARRISON_EXTERNAL_BIND", bootstrap.external_bind.as_deref())?;
let internal_bind =
resolve_bind_addr("GARRISON_INTERNAL_BIND", bootstrap.internal_bind.as_deref())?;
let trusted_proxies =
parse_trusted_proxies(bootstrap.trusted_proxies.as_deref().unwrap_or(""))?;
let config = AuthServerConfig {
external_port: bootstrap.external_port,
internal_port: bootstrap.internal_port,
external_bind,
internal_bind,
external_rate_limit_per_ip: bootstrap.rate_limit,
rate_limit_trusted_proxies: trusted_proxies,
internal_api_key: bootstrap.internal_api_key.clone(),
external_login_enabled: bootstrap.external_login_enabled,
external_login_ack: bootstrap.external_login_ack.clone(),
strict_security: bootstrap.strict_security,
..AuthServerConfig::default()
};
config.validate().map_err(GarrisonError::Config)?;
Ok(config)
}
fn assemble_garrison_config(
max_login_count: u32,
seed_primary_amr: bool,
#[cfg(feature = "rate-limit-redis")] rate_limit_backend: Option<
crate::strategy::rate_limiter_backend::RateLimitBackend,
>,
) -> crate::config::GarrisonConfig {
let mut config = crate::config::GarrisonConfig::default_config();
config.max_login_count = max_login_count;
config.seed_primary_amr = seed_primary_amr;
#[cfg(feature = "rate-limit-redis")]
if let Some(backend) = rate_limit_backend {
config.rate_limit_backend = backend;
}
config
}
#[cfg(feature = "field-encryption")]
fn parse_field_encryption_keys(spec: &str) -> GarrisonResult<Vec<(String, String)>> {
if spec.is_empty() {
return Ok(vec![]);
}
spec.split(',')
.map(|entry| {
let (key_id, key_hex) = entry.split_once(':').ok_or_else(|| {
GarrisonError::Config(format!(
"auth-server-field-encryption::missing-colon::{entry}"
))
})?;
if key_id.is_empty() || key_hex.is_empty() {
return Err(GarrisonError::Config(format!(
"auth-server-field-encryption::empty-part::{entry}"
)));
}
Ok((key_id.to_string(), key_hex.to_string()))
})
.collect()
}
async fn setup_garrison_manager(
field_encryption_keys: &str,
#[allow(unused_variables)] field_encryption_tenant: &str,
max_login_count: u32,
seed_primary_amr: bool,
#[cfg(feature = "rate-limit-redis")] rate_limit_backend: Option<
crate::strategy::rate_limiter_backend::RateLimitBackend,
>,
) -> GarrisonResult<()> {
let dao: Arc<dyn GarrisonDao> = Arc::new(GarrisonDaoOxcache::new().await?);
#[cfg(feature = "field-encryption")]
let dao: Arc<dyn GarrisonDao> = {
let entries = parse_field_encryption_keys(field_encryption_keys)?;
if entries.is_empty() {
return Err(GarrisonError::Config(
"auth-server-field-encryption-no-keys::".to_string(),
));
}
let cipher = crate::secure::encryption::FieldCipher::from_key_entries(&entries)?;
let wrapped = crate::secure::encryption::FieldEncryptionDao::new(
dao,
Arc::new(cipher),
field_encryption_tenant,
)?;
Arc::new(wrapped)
};
#[cfg(not(feature = "field-encryption"))]
if !field_encryption_keys.is_empty() {
eprintln!(
"{}",
crate::i18n::translate_detail("cli-field-encryption-feature-disabled", &[])
);
}
let config = Arc::new(assemble_garrison_config(
max_login_count,
seed_primary_amr,
#[cfg(feature = "rate-limit-redis")]
rate_limit_backend,
));
let interface: Arc<dyn GarrisonInterface> = Arc::new(SimpleInterface);
GarrisonManager::builder()
.dao(dao)
.config(config)
.interface(interface)
.build()
.await?;
Ok(())
}
pub async fn serve_main() -> GarrisonResult<()> {
let bootstrap = match AuthServerBootstrapConfig::load_sync() {
Ok(c) => c,
Err(e) => {
return Err(GarrisonError::Config(format!(
"auth-server-bootstrap-load::{e}"
)));
},
};
if bootstrap.rate_limit == 0 {
return Err(GarrisonError::Config(
"auth-server-rate-limit-zero::GARRISON_RATE_LIMIT=0 would reject every request (all 429); set a positive value (e.g. 100), refusing to start".to_string(),
));
}
#[cfg(feature = "rate-limit-redis")]
let rate_limit_backend = match crate::config::impls::parse_rate_limit_backend_env() {
Ok(Some(crate::strategy::rate_limiter_backend::RateLimitBackend::Redis { redis_url }))
if redis_url.trim().is_empty() =>
{
return Err(GarrisonError::Config(
"auth-server-rate-limit-redis-url-empty::GARRISON_RATE_LIMIT_BACKEND=redis requires a non-empty GARRISON_REDIS_URL; refusing to start"
.to_string(),
));
},
Ok(backend) => backend,
Err(e) => {
return Err(GarrisonError::Config(format!(
"auth-server-rate-limit-backend::{e}; refusing to start"
)));
},
};
let config = match resolve_bootstrap_security(&bootstrap) {
Ok(c) => c,
Err(e) => {
let reason = e.to_string();
return Err(GarrisonError::Config(crate::i18n::translate_detail(
"auth-server-fatal",
&[("arg0", reason.as_str())],
)));
},
};
if config.external_login_enabled {
eprintln!(
"WARN: external login endpoint ENABLED (GARRISON_EXTERNAL_LOGIN_ENABLED=true); \
serve does NOT verify credentials — ensure the business layer \
validates credentials before exposing the external port"
);
}
#[cfg(feature = "audit-inklog")]
let _logger = crate::observability::init_inklog_logging_with_fallback().await;
#[cfg(all(
not(feature = "audit-inklog"),
any(feature = "metrics-prometheus", feature = "tracing-log")
))]
{
use tracing_subscriber::EnvFilter;
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
let result = tracing_subscriber::fmt()
.with_env_filter(filter)
.json()
.with_current_span(true)
.with_span_list(false)
.try_init();
if let Err(e) = result {
tracing::debug!("tracing subscriber already initialized, skip: {}", e);
}
}
#[cfg(not(any(
feature = "audit-inklog",
feature = "metrics-prometheus",
feature = "tracing-log"
)))]
{
eprintln!("WARN: no observability feature enabled, tracing logs will be dropped. Enable audit-inklog or metrics-prometheus for structured logging.");
}
if let Err(e) = setup_garrison_manager(
bootstrap.field_encryption_keys.as_deref().unwrap_or(""),
bootstrap
.field_encryption_tenant
.as_deref()
.unwrap_or("default"),
bootstrap.max_login_count,
bootstrap.seed_primary_amr,
#[cfg(feature = "rate-limit-redis")]
rate_limit_backend,
)
.await
{
tracing::error!(error = %e, "failed to initialize GarrisonManager");
return Err(e);
}
let backend: Arc<dyn AuthBackend> = Arc::new(BackendEmbedded::new());
GarrisonAuthServer::new(backend)
.with_config(config)
.listen()
.await
}
#[cfg(test)]
mod bootstrap_tests {
use super::*;
use crate::server::{EXTERNAL_LOGIN_ACK, MIN_INTERNAL_API_KEY_LEN};
const TEST_KEY: &str = "test-only-not-a-real-key-0123456789abcdef";
fn secure_defaults() -> AuthServerBootstrapConfig {
AuthServerBootstrapConfig {
internal_api_key: TEST_KEY.to_string(),
..AuthServerBootstrapConfig::default()
}
}
#[test]
fn bootstrap_defaults_are_secure_by_default() {
let b = AuthServerBootstrapConfig::default();
assert_eq!(b.max_login_count, 10, "默认并发会话上限应为 10(GAR-35)");
assert_eq!(b.external_bind, None);
assert_eq!(b.internal_bind, None);
assert_eq!(b.trusted_proxies, None);
let resolved =
resolve_bootstrap_security(&secure_defaults()).expect("默认引导配置应通过安全装配");
assert_eq!(
resolved.external_bind,
IpAddr::from([127, 0, 0, 1]),
"缺省绑定必须为回环地址(GAR-30 secure-by-default)"
);
assert_eq!(resolved.internal_bind, IpAddr::from([127, 0, 0, 1]));
assert!(
resolved.rate_limit_trusted_proxies.is_empty(),
"缺省不信任任何代理"
);
assert!(!resolved.external_login_enabled, "外网登录缺省关闭(C-1)");
assert_eq!(
resolved.external_port,
secure_defaults().external_port,
"端口经配置对象整体注入不得丢失(R-auth-server-guardrails-004)"
);
assert_eq!(
resolved.external_rate_limit_per_ip,
secure_defaults().rate_limit,
"限速经配置对象整体注入不得丢失"
);
}
#[test]
fn strict_security_defaults_on_in_serve() {
assert!(
AuthServerBootstrapConfig::default().strict_security,
"serve 缺省严格档(GARRISON_STRICT_SECURITY 缺省 true)"
);
let resolved =
resolve_bootstrap_security(&secure_defaults()).expect("默认引导配置应通过安全装配");
assert!(
resolved.strict_security,
"bootstrap 的严格档必须覆盖库层缺省 false(显式字段优先于 ..default())"
);
}
#[test]
fn bind_addr_env_overrides_and_rejects_invalid() {
assert_eq!(
resolve_bind_addr("GARRISON_EXTERNAL_BIND", Some("0.0.0.0")).unwrap(),
IpAddr::from([0, 0, 0, 0])
);
assert_eq!(
resolve_bind_addr("GARRISON_INTERNAL_BIND", Some("::1")).unwrap(),
IpAddr::from([0, 0, 0, 0, 0, 0, 0, 1])
);
for bad in ["", " ", "example.com", "999.1.1.1", "127.0.0.1:8080"] {
assert!(
resolve_bind_addr("GARRISON_EXTERNAL_BIND", Some(bad)).is_err(),
"非法绑定地址应拒绝启动: {bad}"
);
}
}
#[test]
fn trusted_proxies_parse_and_private_gate() {
assert!(parse_trusted_proxies("").unwrap().is_empty());
assert!(parse_trusted_proxies(" ").unwrap().is_empty());
assert_eq!(
parse_trusted_proxies("10.0.0.1, 127.0.0.1").unwrap(),
vec![IpAddr::from([10, 0, 0, 1]), IpAddr::from([127, 0, 0, 1]),]
);
assert!(parse_trusted_proxies("not-an-ip").is_err());
assert!(parse_trusted_proxies("10.0.0.1,").is_err());
assert!(parse_trusted_proxies("8.8.8.8").is_err());
}
#[test]
fn internal_api_key_min_length_enforced() {
let mut b = secure_defaults();
b.internal_api_key = "x".repeat(MIN_INTERNAL_API_KEY_LEN - 8);
assert_eq!(b.internal_api_key.len(), 24, "构造低于下限的密钥");
let err = resolve_bootstrap_security(&b).expect_err("严格档下 24 字节密钥应拒启动");
assert!(
matches!(err, GarrisonError::Config(ref m) if m.contains("server-internal-api-key-too-short")),
"错误应为库层下限拒绝,实际: {:?}",
err
);
b.strict_security = false;
assert!(
resolve_bootstrap_security(&b).is_ok(),
"非严格档应保持存量短密钥部署可启动(只告警)"
);
}
#[test]
fn external_login_ack_gate() {
let mut b = secure_defaults();
b.external_login_enabled = true;
b.external_bind = Some("127.0.0.1".to_string());
assert!(
resolve_bootstrap_security(&b).is_ok(),
"回环绑定开启外网登录无需 ACK(acc_srv_033 同源语义)"
);
b.external_bind = Some("0.0.0.0".to_string());
assert!(
resolve_bootstrap_security(&b).is_err(),
"非回环 + 无确认应拒启动(acc_srv_032 同源语义)"
);
b.external_login_ack = Some(String::new());
assert!(
resolve_bootstrap_security(&b).is_err(),
"空确认串不得视为已确认"
);
b.external_login_ack = Some("I-UNDERSTAND-NO-CREDENTIAL-CHECK".to_string());
assert!(
resolve_bootstrap_security(&b).is_err(),
"确认值必须精确匹配(大小写敏感)"
);
b.external_login_ack = Some(EXTERNAL_LOGIN_ACK.to_string());
assert!(
resolve_bootstrap_security(&b).is_ok(),
"精确匹配 ACK 应放行"
);
b.strict_security = false;
assert!(
resolve_bootstrap_security(&b).is_ok(),
"非严格档不应因未 ACK 拒启动(降级为告警)"
);
}
#[test]
fn max_login_count_override_and_zero_passthrough() {
assert_eq!(
assemble_garrison_config(
10,
true,
#[cfg(feature = "rate-limit-redis")]
None
)
.max_login_count,
10
);
assert_eq!(
assemble_garrison_config(
0,
true,
#[cfg(feature = "rate-limit-redis")]
None
)
.max_login_count,
0,
"显式 0 透传 = 不限制(保留运维出口)"
);
assert_eq!(
assemble_garrison_config(
3,
true,
#[cfg(feature = "rate-limit-redis")]
None
)
.max_login_count,
3,
"env 覆盖值应生效"
);
}
#[cfg(feature = "rate-limit-redis")]
#[test]
fn rate_limit_backend_applied_to_config() {
use crate::strategy::rate_limiter_backend::RateLimitBackend;
let backend = RateLimitBackend::Redis {
redis_url: "rediss://redis.example:6380/0".to_string(),
};
let config = assemble_garrison_config(10, true, Some(backend.clone()));
assert_eq!(config.rate_limit_backend, backend);
assert_eq!(
assemble_garrison_config(10, true, None).rate_limit_backend,
RateLimitBackend::Memory
);
}
#[test]
fn seed_primary_amr_assembled_into_config() {
assert!(
assemble_garrison_config(
10,
true,
#[cfg(feature = "rate-limit-redis")]
None
)
.seed_primary_amr,
"默认(true)应保持框架现状播种"
);
assert!(
!assemble_garrison_config(
10,
false,
#[cfg(feature = "rate-limit-redis")]
None
)
.seed_primary_amr,
"GARRISON_SEED_PRIMARY_AMR=false 应关闭播种"
);
}
}