1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0
//! `GarrisonAuthServer` 的实现下沉(builder 方法、路由构建、listen),与 [`crate::server`]
//! 的类型定义分离(mod 接口隔离原则)。
#[cfg(feature = "tls")]
use std::path::PathBuf;
use std::sync::Arc;
use axum::Router;
#[cfg(feature = "oauth2-server")]
use super::oauth2_routes;
#[cfg(feature = "protocol-qrlogin")]
use super::qrlogin_routes;
#[cfg(feature = "tls-cert-watch")]
use super::tls_watch;
#[cfg(feature = "tls")]
use super::TlsConfig;
use super::{api_key_auth_middleware, audit_log_middleware, rate_limit_middleware};
use super::{middleware, AuthServerConfig, GarrisonAuthServer};
use crate::backend::types::ApiResponse;
use crate::backend::AuthBackend;
use crate::error::{GarrisonError, GarrisonResult};
/// 优雅停机 drain 上限(秒):信号后等待在途请求完成的最长时间,超时强制中止;
/// 与 TLS 路径 `axum_server::Handle::graceful_shutdown` 上限对齐,非 TLS 路径消费本常量实现同等语义。
const SHUTDOWN_DRAIN_TIMEOUT_SECS: u64 = 30;
/// 生产 drain 上限(两站点经此取参;取值由 graceful_shutdown_tests 锁定)。
#[cfg(feature = "server-graceful-shutdown")]
fn drain_timeout() -> std::time::Duration {
std::time::Duration::from_secs(SHUTDOWN_DRAIN_TIMEOUT_SECS)
}
/// 在 drain 上限内驱动 serve future:serve 先完成返回 `Some(输出)`,停机信号后超过 `timeout`
/// 仍未完成返回 `None`。外/内网两条非 TLS 路径共用(timeout 注入使回归测试无需真实等待 30s)。
#[cfg(feature = "server-graceful-shutdown")]
async fn drive_with_drain_deadline<S, D>(
serve: S,
drain_signal: D,
timeout: std::time::Duration,
) -> Option<S::Output>
where
S: std::future::Future,
D: std::future::Future<Output = ()>,
{
tokio::pin!(serve);
tokio::select! {
result = &mut serve => Some(result),
_ = async move {
drain_signal.await;
tokio::time::sleep(timeout).await;
} => None,
}
}
/// 将 `GarrisonResult<T>` 转换为 `ApiResponse<T>`:Ok → `ok(data)`,Err → `err(error_code, message)`,
/// error_code 来自 `response_parts_i18n()`,message 经 i18n 翻译为当前 locale 文本(避免硬编码中文泄露)。
pub fn to_api_response<T>(result: Result<T, GarrisonError>) -> ApiResponse<T> {
match result {
Ok(data) => ApiResponse::ok(data),
Err(e) => {
let (_, error_code, message, _) = e.response_parts_i18n();
ApiResponse::err(error_code, message)
},
}
}
/// OAuth2 启动期维护:reconcile 引用已删 client 的孤儿 consent 行。
///
/// `listen()` 在监听端口前调用(R-consent-004),内联 await 保证清理在首个 authorize 请求前完成
/// (确定性语义;代价是启动耗时受 consent 键数量约束,低频启动路径可接受)。维护性操作 fail-open:
/// 失败仅告警不阻断启动——孤儿行只是垃圾数据(已删 client 的 authorize 过不了 client 存活校验),
/// 下次启动或显式调用 `AuthorizeHandler::reconcile_consents` 可重试。
#[cfg(feature = "oauth2-server")]
async fn oauth2_consent_startup_reconcile(state: &oauth2_routes::OAuth2State) {
match state.authorize_handler.reconcile_consents().await {
Ok((removed, kept)) if removed > 0 => {
tracing::info!(
removed,
kept,
"{}",
crate::i18n::translate_detail("logs-server-consent-reconcile-removed-orphans", &[])
);
},
Ok((_, kept)) => {
tracing::debug!(
kept,
"{}",
crate::i18n::translate_detail("logs-server-consent-reconcile-no-orphans", &[])
);
},
Err(e) => {
tracing::warn!(
error = %e,
"{}", crate::i18n::translate_detail("logs-server-consent-reconcile-failed", &[])
);
},
}
}
impl GarrisonAuthServer {
/// 创建 Auth Server 实例;`backend` 为认证后端(`BackendEmbedded` 或 `BackendRemote`)。
pub fn new(backend: Arc<dyn AuthBackend>) -> Self {
Self {
backend,
config: AuthServerConfig::default(),
#[cfg(feature = "tenant-isolation")]
tenant_resolver: None,
#[cfg(feature = "oauth2-server")]
oauth2_state: None,
#[cfg(feature = "protocol-qrlogin")]
qrlogin_state: None,
#[cfg(feature = "tls")]
tls_config: None,
}
}
/// 用 trait-kit AsyncKit 构建后端(feature = "backend-kit")。
///
/// 从已构建的 `AsyncKit<Ready>` require `BackendModule` 的 `Arc<dyn AuthBackend>` 并委托
/// [`Self::new`];kit 中未注册/未构建时返回 `GarrisonError::Internal`。
///
/// # 示例
///
/// ```ignore
/// use trait_kit::kit::AsyncKit;
/// use garrison::backend::BackendModule;
///
/// let mut kit = AsyncKit::new();
/// kit.register::<BackendModule>().unwrap();
/// let kit = kit.build().await.unwrap();
/// let server = GarrisonAuthServer::new_with_kit(kit).await.unwrap();
/// ```
#[cfg(feature = "backend-kit")]
pub async fn new_with_kit(
kit: trait_kit::kit::AsyncKit<trait_kit::kit::AsyncReady>,
) -> GarrisonResult<Self> {
use crate::backend::BackendModule;
let backend = kit.require::<BackendModule>().map_err(|e| {
GarrisonError::Internal(format!("kit require BackendModule failed: {}", e))
})?;
Ok(Self::new(backend))
}
/// 设置外网端口(默认 8080)。
pub fn with_external_port(mut self, port: u16) -> Self {
self.config.external_port = port;
self
}
/// 设置外网端口绑定地址(默认 **0.0.0.0**,保持既有下游行为)。
///
/// TCP 与 TLS 两条路径均使用该地址;安全敏感部署应显式收口(如 127.0.0.1 仅本机可达)。
pub fn with_external_bind(mut self, addr: std::net::IpAddr) -> Self {
self.config.external_bind = addr;
self
}
/// 设置内网端口(默认 8081)。
pub fn with_internal_port(mut self, port: u16) -> Self {
self.config.internal_port = port;
self
}
/// 设置内网端口绑定地址(默认 **0.0.0.0**,向后兼容,语义同 `with_external_bind`)。
pub fn with_internal_bind(mut self, addr: std::net::IpAddr) -> Self {
self.config.internal_bind = addr;
self
}
/// 设置外网每 IP 限速(默认 100 req/s)。
pub fn with_rate_limit(mut self, limit: u32) -> Self {
self.config.external_rate_limit_per_ip = limit;
self
}
/// 是否启用外网登录端点(默认 `false`,secure-by-default)。
///
/// 框架 login 端点不校验任何凭证(职责边界:凭证校验属业务层,框架只签发会话),禁用时
/// 外网端口对 `POST /api/v1/auth/login` 一律 404。开启前须确保业务侧已注入凭证校验,否则
/// 任何主体都能获取任意用户的有效会话;开启后 `listen()` 启动时输出 warn。
pub fn with_external_login_enabled(mut self, enabled: bool) -> Self {
self.config.external_login_enabled = enabled;
self
}
/// 设置限速 HashMap 最大条目数(默认 100_000):超限 LRU 淘汰最久未访问的 bucket,防 DoS 内存耗尽。
pub fn with_rate_limit_max_entries(mut self, max_entries: usize) -> Self {
self.config.rate_limit_max_entries = max_entries;
self
}
/// 设置可信代理 IP 列表:仅这些 IP 的请求其 X-Forwarded-For 被信任,其余使用连接 IP。
pub fn with_trusted_proxies(mut self, proxies: Vec<std::net::IpAddr>) -> Self {
self.config.rate_limit_trusted_proxies = proxies;
self
}
/// 设置内网 API Key(用于 X-API-Key 头校验)。
pub fn with_internal_api_key(mut self, api_key: impl Into<String>) -> Self {
self.config.internal_api_key = api_key.into();
self
}
/// 设置内网 API Key 认证失败锁定:`threshold` 为同源 IP 连续失败阈值(达到后窗口期内一律
/// 429,`0` 禁用),`window_secs` 为锁定窗口秒数。
pub fn with_api_key_lockout(mut self, threshold: u32, window_secs: u64) -> Self {
self.config.api_key_lockout_threshold = threshold;
self.config.api_key_lockout_window_secs = window_secs;
self
}
/// 是否透传内网 `/readyz` 的 `checks[].details`(默认 **false**)。
///
/// details 可能包含内部依赖拓扑(host、延迟等),默认剥离仅保留 name/healthy;显式开启后方可输出。
pub fn with_health_details(mut self, enabled: bool) -> Self {
self.config.health_details_enabled = enabled;
self
}
/// 是否启用严格安全档(默认 **false**,只告警不拒绝)。
///
/// `true` 时短内网 API Key 与未确认的外网登录暴露在 `validate()` 直接返回错误;参考部署 bin 缺省 `true`。
pub fn with_strict_security(mut self, enabled: bool) -> Self {
self.config.strict_security = enabled;
self
}
/// 设置外网登录暴露确认串(默认 `None`):启用外网登录且绑定非回环时,须传入与
/// [`crate::server::EXTERNAL_LOGIN_ACK`] 完全相等的确认串。
pub fn with_external_login_ack(mut self, ack: Option<String>) -> Self {
self.config.external_login_ack = ack;
self
}
/// 整体注入 `AuthServerConfig`(与逐项 builder 等价,混用时后调用者生效)。
pub fn with_config(mut self, config: crate::server::AuthServerConfig) -> Self {
self.config = config;
self
}
/// 设置外网请求体大小上限(字节,默认 256KB),超限返回 `413 Payload Too Large`。
pub fn with_external_body_limit(mut self, limit: usize) -> Self {
self.config.external_body_limit = limit;
self
}
/// 设置内网请求体大小上限(字节,默认 1MB),超限返回 `413 Payload Too Large`。
pub fn with_internal_body_limits(mut self, limit: usize) -> Self {
self.config.internal_body_limit = limit;
self
}
/// 注入租户解析器(feature = "tenant-isolation")。
///
/// `Some` 时 `external_router` / `internal_router` 自动注入 `tenant_resolution_middleware`,
/// 使 `check_permission` / `check_role` / 审计日志可经 `current_tenant_id_or_error()` 读取租户
/// 上下文;`None` 表示未启用租户隔离(单租户部署)。`resolver` 可为 `HeaderTenantResolver` /
/// `SubdomainTenantResolver` / `ClaimTenantResolver`。
///
/// # 示例
///
/// ```ignore
/// use garrison::context::tenant::HeaderTenantResolver;
/// use std::sync::Arc;
///
/// let server = GarrisonAuthServer::new(backend)
/// .with_tenant_resolver(Some(Arc::new(HeaderTenantResolver)));
/// ```
#[cfg(feature = "tenant-isolation")]
pub fn with_tenant_resolver(
mut self,
resolver: Option<Arc<dyn crate::context::tenant::TenantResolver>>,
) -> Self {
self.tenant_resolver = resolver;
self
}
/// 注入 OAuth2 状态,启用 4 个 OAuth2 端点(外网 authorize/token/revoke,内网 introspect)。
#[cfg(feature = "oauth2-server")]
pub fn with_oauth2(mut self, state: Arc<oauth2_routes::OAuth2State>) -> Self {
self.oauth2_state = Some(state);
self
}
/// 注入扫码登录状态,外网端口启用 create/poll/scan/confirm 4 个端点。
#[cfg(feature = "protocol-qrlogin")]
pub fn with_qrlogin(mut self, state: Arc<qrlogin_routes::QrLoginHttpState>) -> Self {
self.qrlogin_state = Some(state);
self
}
/// 启用 HTTPS/TLS 终止(feature = "tls")。
///
/// `listen()` 使用 `axum_server::bind_rustls` 替代 `axum::serve`,对外网和内网端口均启用 TLS。
///
/// # 示例
///
/// ```ignore
/// let server = GarrisonAuthServer::new(backend)
/// .with_tls("/etc/garrison/cert.pem", "/etc/garrison/key.pem");
/// server.listen().await?;
/// ```
#[cfg(feature = "tls")]
pub fn with_tls(mut self, cert_path: impl Into<PathBuf>, key_path: impl Into<PathBuf>) -> Self {
self.tls_config = Some(TlsConfig {
cert_path: cert_path.into(),
key_path: key_path.into(),
});
self
}
/// 构建外网路由(sdforge + path-filter + rate_limit + audit_log + tenant_resolution)。
///
/// `sdforge::http::build()` 收集所有 `#[forge]` 路由(15 基础 + metrics-prometheus 时 +1),
/// `external_path_filter` 仅放行 3 个外网路径(login/logout/refresh),其余 404。
///
/// 中间件栈(从外到内):`audit_log → rate_limit → external_path_filter → tenant_resolution? → handler`;
/// tenant_resolution 仅在 `tenant-isolation` 启用且 `with_tenant_resolver(Some(..))` 时注入。
///
/// 用于测试时通过 `tower::ServiceExt::oneshot` 发送请求,避免实际 listen。
pub fn external_router(&self) -> Router {
use axum::Extension;
let rate_limit_state = Arc::new(middleware::RateLimitState::with_options(
self.config.external_rate_limit_per_ip,
self.config.rate_limit_max_entries,
self.config.rate_limit_trusted_proxies.clone(),
));
// 可信代理列表注入 Extension,供 inject_client_ip middleware 读取
let trusted_proxies =
middleware::TrustedProxies(self.config.rate_limit_trusted_proxies.clone());
let router = sdforge::http::build()
.layer(Extension(self.backend.clone()))
// 外网 login 端点默认关闭(secure-by-default):框架 login 不校验凭证,
// 业务方注入凭证校验后经 with_external_login_enabled(true) 显式开启。
.layer(axum::middleware::from_fn_with_state(
middleware::ExternalLoginGate(self.config.external_login_enabled),
middleware::external_login_gate,
))
.layer(axum::middleware::from_fn(middleware::external_path_filter))
// IP 自动注入(path_filter 之后、rate_limit 之前)
.layer(axum::middleware::from_fn(
middleware::inject_login_client_ip,
))
// Json extractor rejection(400/413/415/422)统一清洗,
// 不向调用方回显内部类型名/字段名/字节偏移
.layer(axum::middleware::from_fn(
middleware::sanitize_json_rejection_middleware,
))
.layer(axum::middleware::from_fn(middleware::inject_client_ip))
// User-Agent 注入(在 inject_client_ip 之后)
.layer(axum::middleware::from_fn(middleware::inject_user_agent))
.layer(Extension(trusted_proxies))
.layer(axum::middleware::from_fn_with_state(
rate_limit_state.clone(),
rate_limit_middleware,
));
// 安全头中间件位于 rate_limit 之后、audit_log 之前
// (axum layer 反序执行:audit_log → security_headers → rate_limit → path_filter)
#[cfg(feature = "web-security-headers")]
let router = router.layer(axum::middleware::from_fn(
crate::web::security_headers::security_headers_middleware,
));
let router = router.layer(axum::middleware::from_fn(audit_log_middleware));
// 租户中间件:tenant-isolation feature 启用且注入 resolver 时才挂载
#[cfg(feature = "tenant-isolation")]
let router = {
if let Some(resolver) = &self.tenant_resolver {
router.layer(axum::middleware::from_fn_with_state(
resolver.clone(),
crate::router::tenant_resolution_middleware,
))
} else {
router
}
};
#[cfg(feature = "oauth2-server")]
let router = {
if let Some(state) = &self.oauth2_state {
let oauth2_router = oauth2_routes::oauth2_external_router(state.clone())
.layer(axum::middleware::from_fn(
middleware::principal_inject_middleware,
))
.layer(Extension(self.backend.clone()));
// axum merge 不合并 layer,OAuth2 router 必须单独注入租户中间件;否则 login 写入的 key
// 带 tenant 前缀(`tenant:0:session:xxx`),而 OAuth2 端点(principal_inject → get_session)
// 读时无 TENANT scope 导致 key 不带前缀(`session:xxx`),命中失败。
#[cfg(feature = "tenant-isolation")]
let oauth2_router = {
if let Some(resolver) = &self.tenant_resolver {
oauth2_router.layer(axum::middleware::from_fn_with_state(
resolver.clone(),
crate::router::tenant_resolution_middleware,
))
} else {
oauth2_router
}
};
router.merge(oauth2_router)
} else {
router
}
};
#[cfg(feature = "protocol-qrlogin")]
let router = {
if let Some(state) = &self.qrlogin_state {
// qrlogin 存储键为全局命名空间(garrison:qrlogin:*,租户记在会话 JSON 内),刻意不注入
// tenant_resolution_middleware——匿名 create/poll 与带租户头的 scan/confirm 必须命中同一批 key。
//
// axum merge 不继承 layer:必须在 merge 前自带与主栈同构的中间件(rate_limit / client_ip /
// user_agent / audit_log),否则 4 个端点将绕过外网限流与审计。
let qrlogin_router = qrlogin_routes::qrlogin_external_router(state.clone())
.layer(axum::middleware::from_fn(middleware::inject_client_ip))
.layer(axum::middleware::from_fn(middleware::inject_user_agent))
.layer(Extension(middleware::TrustedProxies(
self.config.rate_limit_trusted_proxies.clone(),
)))
.layer(axum::middleware::from_fn_with_state(
rate_limit_state.clone(),
middleware::rate_limit_middleware,
))
.layer(axum::middleware::from_fn(audit_log_middleware));
router.merge(qrlogin_router)
} else {
router
}
};
// 请求体大小限制(最外层,确保所有 body extractor 受控)
let router = router.layer(axum::extract::DefaultBodyLimit::max(
self.config.external_body_limit,
));
// server-health-check:K8s 探针 merge 在最外层——axum merge 不继承 layer,探针绕过
// path_filter/rate_limit/audit 全部中间件(K8s 探针惯例)。外网端口仅暴露最小化
// /healthz(无版本号),/readyz 仅挂内网。
#[cfg(feature = "server-health-check")]
let router = router.merge(Self::external_health_probe_router());
router
}
/// 外网健康探针路由(server-health-check feature)。
///
/// 最小语义:外网仅 `/healthz`,响应只含 `{"status":"healthy"}`——不暴露 sdforge 版本号,
/// 不暴露 `/readyz`(readiness 拓扑仅限内网)。
#[cfg(feature = "server-health-check")]
fn external_health_probe_router() -> Router {
use axum::routing::get;
Router::new().route("/healthz", get(super::health::liveness_handler))
}
/// 内网健康探针路由(server-health-check feature)。
///
/// `/healthz` 同外网最小语义;`/readyz` 按已注册 readiness check
/// (`sdforge::health::register_readiness_check_fn`)返回 200/503,
/// `checks[].details` 仅在 `health_details_enabled=true` 时透传(默认剥离)。
#[cfg(feature = "server-health-check")]
fn internal_health_probe_router(&self) -> Router {
use axum::routing::get;
Router::new()
.route("/healthz", get(super::health::liveness_handler))
.route("/readyz", get(super::health::readiness_handler))
.with_state(super::health::HealthDetailsEnabled(
self.config.health_details_enabled,
))
}
/// 构建内网路由(sdforge + path-filter + api_key_auth + rate_limit + audit_log + tenant_resolution)。
///
/// `sdforge::http::build()` 收集所有 `#[forge]` 路由(15 基础 + metrics-prometheus 时 +1),
/// `internal_path_filter` 拒绝 3 个外网路径(login/logout/refresh),其余由 api_key_auth 保护。
///
/// # 内网路由保护
///
/// - 同样挂载 `rate_limit_middleware`(参数复用外网配置:`external_rate_limit_per_ip` /
/// `rate_limit_max_entries` / `rate_limit_trusted_proxies`),防止持有合法 API Key 的调用方
/// 无限速打满后端资源。
/// - OAuth2 内网路由(introspect)**先 merge 再统一挂中间件**:axum `merge` 不继承 layer,
/// 若 introspect 在挂 layer 后 merge 会绕过 `api_key_auth`。
///
/// 中间件栈(从外到内):`tenant_resolution? → audit_log → rate_limit → api_key_auth → internal_path_filter → handler`。
/// 用于测试时通过 `tower::ServiceExt::oneshot` 发送请求,避免实际 listen。
pub fn internal_router(&self) -> Router {
use axum::Extension;
// 认证失败锁定由配置驱动(threshold=0 禁用)
let api_key_state = Arc::new(middleware::ApiKeyState {
api_key: self.config.internal_api_key.clone(),
lockout: Arc::new(super::api_key_lockout::ApiKeyLockout::new(
self.config.api_key_lockout_threshold,
self.config.api_key_lockout_window_secs,
)),
});
// 内网路由限速状态(参数与外网一致,独立 bucket 实例)
let rate_limit_state = Arc::new(middleware::RateLimitState::with_options(
self.config.external_rate_limit_per_ip,
self.config.rate_limit_max_entries,
self.config.rate_limit_trusted_proxies.clone(),
));
let router = sdforge::http::build().layer(Extension(self.backend.clone()));
// OAuth2 introspect 先 merge 再统一挂中间件:axum merge 不继承 layer,
// 先挂 layer 再 merge 会绕过 api_key_auth。
#[cfg(feature = "oauth2-server")]
let router = {
if let Some(state) = &self.oauth2_state {
router.merge(oauth2_routes::oauth2_internal_router(state.clone()))
} else {
router
}
};
let router = router
.layer(axum::middleware::from_fn(middleware::internal_path_filter))
.layer(axum::middleware::from_fn_with_state(
api_key_state,
api_key_auth_middleware,
))
// 内网端点同样统一清洗 Json rejection(类型名不因内网信任边界而豁免——
// 单 key 泄露即可触达)
.layer(axum::middleware::from_fn(
middleware::sanitize_json_rejection_middleware,
))
.layer(axum::middleware::from_fn_with_state(
rate_limit_state,
rate_limit_middleware,
))
.layer(axum::middleware::from_fn(audit_log_middleware));
// 租户中间件:tenant-isolation feature 启用且注入 resolver 时才挂载
// (覆盖全部内网路由,含 merge 进来的 introspect,读取 tenant 前缀 key)
#[cfg(feature = "tenant-isolation")]
let router = {
if let Some(resolver) = &self.tenant_resolver {
router.layer(axum::middleware::from_fn_with_state(
resolver.clone(),
crate::router::tenant_resolution_middleware,
))
} else {
router
}
};
// 请求体大小限制(最外层,确保所有 body extractor 受控)
let router = router.layer(axum::extract::DefaultBodyLimit::max(
self.config.internal_body_limit,
));
// server-health-check:内网探针同样 merge 在最外层(绕过 api_key_auth,
// K8s 探针不持有 API Key);/readyz 的 details 经配置门控
#[cfg(feature = "server-health-check")]
let router = router.merge(self.internal_health_probe_router());
router
}
/// 同时启动外网和内网两个 axum 服务器,任一服务器异常退出时整体返回错误。
///
/// # 绑定地址
///
/// 由配置驱动:默认 **0.0.0.0**,经 `with_external_bind` / `with_internal_bind` 显式收口;
/// TCP 与 TLS 两条路径使用同一地址。
///
/// # TLS 终止
///
/// 启用 `tls` feature 且调用 `with_tls()` 后,两个端口均用 `axum_server::bind_rustls` 替代
/// `axum::serve`,实现 HTTPS/TLS 终止。
///
/// # 优雅停机(feature = "server-graceful-shutdown")
///
/// SIGTERM / SIGINT 触发后停止接收新连接并 drain 在途请求;TLS 路径经
/// `axum_server::Handle::graceful_shutdown`(30s 上限)等效实现。
pub async fn listen(self) -> GarrisonResult<()> {
self.config.validate().map_err(GarrisonError::Config)?;
// 启动期维护:清理引用已删 client 的孤儿 consent 行(fail-open,失败仅告警,见函数文档)
#[cfg(feature = "oauth2-server")]
if let Some(state) = &self.oauth2_state {
oauth2_consent_startup_reconcile(state).await;
}
// 信号监听 → Notify 广播给两个端口 serve future
#[cfg(feature = "server-graceful-shutdown")]
let shutdown_notify = {
let notify = Arc::new(tokio::sync::Notify::new());
let n2 = Arc::clone(¬ify);
tokio::spawn(async move {
shutdown_signal().await;
n2.notify_waiters();
});
notify
};
// 绑定地址由配置驱动(默认 0.0.0.0;with_external_bind/with_internal_bind 可收口),
// TCP 与 TLS 路径共用同一 SocketAddr
let external_addr =
std::net::SocketAddr::new(self.config.external_bind, self.config.external_port);
let internal_addr =
std::net::SocketAddr::new(self.config.internal_bind, self.config.internal_port);
// rustls 拒绝在「aws-lc-rs 与 ring 双开」的构建图上自动判定进程级 provider,此时
// ServerConfig::builder() 直接 panic(rustls crypto/mod.rs);而 db 系 feature
// (sqlx tls-rustls → rustls/ring)与 tls(axum-server tls-rustls → rustls/aws-lc-rs)
// 恰好构成该图。显式安装 tls 面选定的 aws-lc-rs;安装幂等,重复调用返回 Err 即已装。
#[cfg(feature = "tls")]
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
// TLS 终止配置在两条 serve 任务启动前一次性构建:两端口共享同一 RustlsConfig
// (内部 ArcSwap,clone 共享同一快照),tls-cert-watch 换入新证书后两端口新握手同时生效;
// 加载失败即两端口都不启动(fail-fast),错误码沿用既有外网 TLS 加载键(其 FTL 条目已备,
// 失败发生在任一端口绑定前,不指向具体端口)。
#[cfg(feature = "tls")]
let rustls_config = match self.tls_config.as_ref() {
Some(tc) => Some(
axum_server::tls_rustls::RustlsConfig::from_pem_file(&tc.cert_path, &tc.key_path)
.await
.map_err(|e| {
GarrisonError::Internal(format!("server-external-tls-load::{}", e))
})?,
),
None => None,
};
#[cfg(feature = "tls")]
let rustls_config_ext = rustls_config.clone();
#[cfg(feature = "tls")]
let rustls_config_int = rustls_config.clone();
#[cfg(feature = "tls-cert-watch")]
let tls_paths = self.tls_config.clone();
let external_router = self.external_router();
let internal_router = self.internal_router();
tracing::info!(
external_bind = %external_addr,
internal_bind = %internal_addr,
external_port = self.config.external_port,
internal_port = self.config.internal_port,
"GarrisonAuthServer starting"
);
// 显式开启外网 login 时提醒业务方凭证校验责任
if self.config.external_login_enabled {
tracing::warn!(
external_port = self.config.external_port,
"external login endpoint ENABLED (external_login_enabled=true): \
GarrisonAuthServer does NOT verify credentials; ensure the \
business layer validates credentials before exposing this port"
);
}
// 每 task 专属克隆(async move 捕获整块环境,须在闭包外克隆)
#[cfg(feature = "server-graceful-shutdown")]
let shutdown_notify_ext = Arc::clone(&shutdown_notify);
#[cfg(feature = "server-graceful-shutdown")]
let shutdown_notify_int = Arc::clone(&shutdown_notify);
let mut external_handle = tokio::spawn(async move {
#[cfg(feature = "server-graceful-shutdown")]
let shutdown_notify = shutdown_notify_ext;
#[cfg(feature = "tls")]
if let Some(rustls_config) = rustls_config_ext {
// TLS 路径经 axum_server::Handle 等效实现优雅停机(30s drain 上限)
#[cfg(feature = "server-graceful-shutdown")]
let handle = {
let handle = axum_server::Handle::new();
let h2 = handle.clone();
let notify = Arc::clone(&shutdown_notify);
tokio::spawn(async move {
notify.notified().await;
h2.graceful_shutdown(Some(std::time::Duration::from_secs(
SHUTDOWN_DRAIN_TIMEOUT_SECS,
)));
});
handle
};
let bind = axum_server::bind_rustls(external_addr, rustls_config);
#[cfg(feature = "server-graceful-shutdown")]
let bind = bind.handle(handle);
return bind
.serve(
external_router
.into_make_service_with_connect_info::<std::net::SocketAddr>(),
)
.await
.map_err(|e| {
GarrisonError::Internal(format!("server-external-server-error::{}", e))
});
}
let external_listener = tokio::net::TcpListener::bind(&external_addr)
.await
.map_err(|e| GarrisonError::Internal(format!("server-external-bind::{}", e)))?;
let serve = axum::serve(
external_listener,
external_router.into_make_service_with_connect_info::<std::net::SocketAddr>(),
);
// 信号触发后停止接收新连接并 drain 在途请求,drain 最长 30s(与 TLS 路径同一常量);
// 超时后停止等待并返回,避免被卡死连接无限拖延(随附 bin 场景下进程退出收尾在途连接任务)
#[cfg(feature = "server-graceful-shutdown")]
{
let drain_notify = std::sync::Arc::clone(&shutdown_notify);
// axum Serve 实现 IntoFuture 而非 Future:驱动前显式转换
let serve = std::future::IntoFuture::into_future(serve.with_graceful_shutdown(
async move {
shutdown_notify.notified().await;
},
));
match drive_with_drain_deadline(
serve,
async move { drain_notify.notified().await },
drain_timeout(),
)
.await
{
Some(Err(e)) => {
tracing::error!(error = %e, "external server error");
Err(GarrisonError::Internal(format!(
"server-external-server-error::{}",
e
)))
},
None => {
tracing::warn!(
timeout_secs = SHUTDOWN_DRAIN_TIMEOUT_SECS,
"{}",
crate::i18n::translate_detail(
"logs-server-external-drain-timeout",
&[]
)
);
Ok(())
},
Some(Ok(())) => Ok(()),
}
}
#[cfg(not(feature = "server-graceful-shutdown"))]
{
if let Err(e) = serve.await {
tracing::error!(error = %e, "external server error");
return Err(GarrisonError::Internal(format!(
"server-external-server-error::{}",
e
)));
}
Ok(())
}
});
let mut internal_handle = tokio::spawn(async move {
#[cfg(feature = "server-graceful-shutdown")]
let shutdown_notify = shutdown_notify_int;
#[cfg(feature = "tls")]
if let Some(rustls_config) = rustls_config_int {
// TLS 路径经 axum_server::Handle 等效实现优雅停机(30s drain 上限)
#[cfg(feature = "server-graceful-shutdown")]
let handle = {
let handle = axum_server::Handle::new();
let h2 = handle.clone();
let notify = Arc::clone(&shutdown_notify);
tokio::spawn(async move {
notify.notified().await;
h2.graceful_shutdown(Some(std::time::Duration::from_secs(
SHUTDOWN_DRAIN_TIMEOUT_SECS,
)));
});
handle
};
let bind = axum_server::bind_rustls(internal_addr, rustls_config);
#[cfg(feature = "server-graceful-shutdown")]
let bind = bind.handle(handle);
return bind
.serve(
// 内网 TLS 路径同样注入 ConnectInfo,与外网对齐
// (限速/IP 提取中间件依赖 ConnectInfo<SocketAddr>)
internal_router
.into_make_service_with_connect_info::<std::net::SocketAddr>(),
)
.await
.map_err(|e| {
GarrisonError::Internal(format!("server-internal-server-error::{}", e))
});
}
let internal_listener = tokio::net::TcpListener::bind(&internal_addr)
.await
.map_err(|e| GarrisonError::Internal(format!("server-internal-bind::{}", e)))?;
let serve = axum::serve(
internal_listener,
// 内网非 TLS 路径同样注入 ConnectInfo(与外网对齐)
internal_router.into_make_service_with_connect_info::<std::net::SocketAddr>(),
);
// 信号触发后停止接收新连接并 drain 在途请求,drain 最长 30s(与 TLS 路径同一常量);
// 超时后停止等待并返回,避免被卡死连接无限拖延(随附 bin 场景下进程退出收尾在途连接任务)
#[cfg(feature = "server-graceful-shutdown")]
{
let drain_notify = std::sync::Arc::clone(&shutdown_notify);
// axum Serve 实现 IntoFuture 而非 Future:驱动前显式转换
let serve = std::future::IntoFuture::into_future(serve.with_graceful_shutdown(
async move {
shutdown_notify.notified().await;
},
));
match drive_with_drain_deadline(
serve,
async move { drain_notify.notified().await },
drain_timeout(),
)
.await
{
Some(Err(e)) => {
tracing::error!(error = %e, "internal server error");
Err(GarrisonError::Internal(format!(
"server-internal-server-error::{}",
e
)))
},
None => {
tracing::warn!(
timeout_secs = SHUTDOWN_DRAIN_TIMEOUT_SECS,
"{}",
crate::i18n::translate_detail(
"logs-server-internal-drain-timeout",
&[]
)
);
Ok(())
},
Some(Ok(())) => Ok(()),
}
}
#[cfg(not(feature = "server-graceful-shutdown"))]
{
if let Err(e) = serve.await {
tracing::error!(error = %e, "internal server error");
return Err(GarrisonError::Internal(format!(
"server-internal-server-error::{}",
e
)));
}
Ok(())
}
});
// 证书热重载(feature = "tls-cert-watch"):监视证书/私钥文件,去抖后的变更事件换入
// 上面的共享 RustlsConfig(两端口同时生效);未配置 TLS 时不启动。
#[cfg(feature = "tls-cert-watch")]
let cert_watcher = rustls_config.clone().zip(tls_paths).map(|(config, tc)| {
#[cfg(feature = "server-graceful-shutdown")]
let watcher_shutdown = {
let notify = Arc::clone(&shutdown_notify);
async move { notify.notified().await }
};
#[cfg(not(feature = "server-graceful-shutdown"))]
let watcher_shutdown = std::future::pending::<()>();
tls_watch::spawn_cert_watcher(config, tc.cert_path, tc.key_path, watcher_shutdown)
});
// 任一服务器异常即返回错误, 显式 abort 另一个 task 避免资源泄漏
let result = tokio::select! {
res = &mut external_handle => {
internal_handle.abort();
res.map_err(|e| GarrisonError::Internal(format!("server-external-task-panic::{}", e)))?
},
res = &mut internal_handle => {
external_handle.abort();
res.map_err(|e| GarrisonError::Internal(format!("server-internal-task-panic::{}", e)))?
},
};
// 服务退出后停止证书 watcher(fs 监听线程随之释放)
#[cfg(feature = "tls-cert-watch")]
if let Some(handle) = cert_watcher {
handle.abort();
}
result
}
}
// 优雅停机(feature = "server-graceful-shutdown")
#[cfg(feature = "server-graceful-shutdown")]
async fn shutdown_signal() {
let ctrl_c = async {
let _ = tokio::signal::ctrl_c().await;
};
#[cfg(unix)]
let terminate = async {
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(mut sig) => {
sig.recv().await;
},
Err(e) => {
// 信号处理器安装失败(罕见):不 panic,退化为仅监听 Ctrl-C
tracing::warn!(error = %e, "failed to install SIGTERM handler");
std::future::pending::<()>().await;
},
}
};
#[cfg(not(unix))]
let terminate = std::future::pending::<()>();
tokio::select! {
_ = ctrl_c => {},
_ = terminate => {},
}
tracing::info!(
"shutdown signal received; stopping new connections and draining in-flight requests"
);
}
#[cfg(all(test, feature = "server-graceful-shutdown"))]
mod graceful_shutdown_tests {
use super::*;
use axum::routing::get;
/// 触发 shutdown 通知后 serve future 完成(监听停止);
/// 触发前到达的在途请求完整收到响应(drain 语义)。
#[tokio::test]
async fn graceful_shutdown_drains_and_stops() {
let notify = Arc::new(tokio::sync::Notify::new());
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind 应成功");
let addr = listener.local_addr().unwrap();
// serve 侧持有专属克隆,外层 notify 留作触发端
let serve_notify = Arc::clone(¬ify);
let app = Router::new().route(
"/ping",
get(|| async {
// 模拟在途处理耗时
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
"pong"
}),
);
let serve = tokio::spawn(async move {
let serve = axum::serve(
listener,
app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
);
serve
.with_graceful_shutdown(async move { serve_notify.notified().await })
.await
});
// 在途请求先于关闭信号到达并应完整完成
let client = reqwest::get(format!("http://{addr}/ping"))
.await
.expect("请求应成功");
assert_eq!(client.status(), 200);
assert_eq!(client.text().await.unwrap(), "pong");
// 触发关闭:serve future 应在超时内完成(监听停止 + drain 完成)
notify.notify_waiters();
let result = tokio::time::timeout(std::time::Duration::from_secs(5), serve).await;
assert!(
result.is_ok(),
"shutdown 通知后 serve 应在超时内完成(graceful drain)"
);
assert!(result.unwrap().is_ok(), "serve 任务不应 panic");
// 关闭后新连接被拒绝/超时(监听已停止)
let new_conn = tokio::time::timeout(
std::time::Duration::from_millis(300),
reqwest::get(format!("http://{addr}/ping")),
)
.await;
assert!(
new_conn.is_err() || new_conn.unwrap().is_err(),
"shutdown 后新请求应失败(监听已停止)"
);
}
/// 接线锁定:生产 drain 上限为 30s(两站点经 `drain_timeout()` 取参,
/// 常量被改动时本测试显性失败)。
#[test]
fn drain_timeout_wires_thirty_seconds() {
assert_eq!(drain_timeout(), std::time::Duration::from_secs(30));
}
/// serve 先完成且无停机信号:即使 timeout=0 也返回 Some——timeout 仅从信号起算。
#[tokio::test]
async fn drain_deadline_serve_completes_without_signal() {
let out = drive_with_drain_deadline(
async { Ok::<u32, &'static str>(42) },
std::future::pending::<()>(),
std::time::Duration::from_secs(0),
)
.await;
assert_eq!(out, Some(Ok(42)));
}
/// 停机信号到达且 serve 在限时内完成:正常路径返回 Some(drain 未被 select 破坏)。
#[tokio::test]
async fn drain_deadline_completes_before_timeout() {
let out = drive_with_drain_deadline(
async {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
Ok::<u32, &'static str>(7)
},
async {},
std::time::Duration::from_secs(5),
)
.await;
assert_eq!(out, Some(Ok(7)));
}
/// 停机信号后 serve 卡死:超过注入的短 timeout 返回 None(不再无限等待在途连接)。
#[tokio::test]
async fn drain_deadline_times_out_on_hung_serve() {
let started = std::time::Instant::now();
let out = drive_with_drain_deadline(
std::future::pending::<Result<(), std::io::Error>>(),
async {},
std::time::Duration::from_millis(30),
)
.await;
assert!(out.is_none(), "卡死 serve 应返回 None(停止等待)");
assert!(
started.elapsed() < std::time::Duration::from_secs(2),
"应在注入的短 timeout 附近返回,实际 {:?}",
started.elapsed()
);
}
}
#[cfg(all(test, feature = "oauth2-server"))]
mod oauth2_startup_reconcile_tests {
use super::*;
use crate::dao::{GarrisonDao, InMemoryDao};
use crate::oauth2_server::client::{
DaoOAuth2ClientStore, GrantType, OAuth2Client, OAuth2ClientStore,
};
fn make_client(id: &str) -> OAuth2Client {
OAuth2Client::new(
id,
"secret-123",
vec!["https://app.example.com/cb".into()],
vec![GrantType::AuthorizationCode],
vec!["read".into()],
)
.unwrap()
}
/// listen() 启动接线的实测:删除 client 后启动清理对应 consent 行,存活 client 的记录原样保留
/// (R-consent-004 的启动路径用例;reconcile 本体分支语义见 authorize.rs 的
/// `reconcile_removes_orphan_consent_and_keeps_live`)。
#[tokio::test]
async fn startup_reconcile_removes_orphan_and_keeps_live() {
let dao = Arc::new(InMemoryDao::new());
let store: Arc<DaoOAuth2ClientStore> = Arc::new(DaoOAuth2ClientStore::new(dao.clone()));
let state = oauth2_routes::OAuth2State::new(
store.clone(),
dao.clone(),
"https://auth.example.com/login".into(),
);
store.create(make_client("reconcile-live")).await.unwrap();
store.create(make_client("reconcile-dead")).await.unwrap();
let handler = &state.authorize_handler;
handler
.grant_consent(0, 9101, "reconcile-live", &["read".into()], &[])
.await
.unwrap();
handler
.grant_consent(0, 9102, "reconcile-dead", &["read".into()], &[])
.await
.unwrap();
store.delete("reconcile-dead").await.unwrap();
// listen() 启动路径调用的正是本函数(见 listen() 的 oauth2-server 分支)
oauth2_consent_startup_reconcile(&state).await;
assert!(
dao.get("oauth2:consent:0:9102:reconcile-dead")
.await
.unwrap()
.is_none(),
"启动 reconcile 应清理已删 client 的孤儿 consent 行"
);
assert!(
dao.get("oauth2:consent:0:9101:reconcile-live")
.await
.unwrap()
.is_some(),
"存活 client 的 consent 行应保留"
);
}
/// keys() 直接报错的 DAO:不实现 `keys()` 即命中默认 NotImplemented
/// Err,恰好充当 reconcile 首步(client list 扫描)的故障注入。
struct ReconcileFailingDao;
#[async_trait::async_trait]
impl crate::dao::GarrisonDao for ReconcileFailingDao {
async fn get(&self, _key: &str) -> GarrisonResult<Option<String>> {
Ok(None)
}
async fn set(&self, _key: &str, _value: &str, _ttl_seconds: u64) -> GarrisonResult<()> {
Ok(())
}
async fn update(&self, _key: &str, _value: &str) -> GarrisonResult<()> {
Ok(())
}
async fn expire(&self, _key: &str, _seconds: u64) -> GarrisonResult<()> {
Ok(())
}
async fn delete(&self, _key: &str) -> GarrisonResult<()> {
Ok(())
}
crate::atomic_test_fallback!();
}
/// reconcile 失败 fail-open:DAO 故障(keys() Err)不向启动路径传播错误、不 panic——
/// listen() 不因维护性清理失败而拒绝启动。
#[tokio::test]
async fn startup_reconcile_failure_is_fail_open() {
let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(ReconcileFailingDao);
let store = Arc::new(DaoOAuth2ClientStore::new(dao.clone()));
let state =
oauth2_routes::OAuth2State::new(store, dao, "https://auth.example.com/login".into());
// 不 panic、不 Err——错误仅记录告警(fail-open 语义,见函数文档)
oauth2_consent_startup_reconcile(&state).await;
}
}