garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
Documentation
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! sdforge 声明式路由(feature = "auth-server-sdforge")。
//!
//! 用 `#[forge]` 宏替换 `external.rs` + `internal.rs` 的手写 axum 路由。
//! sdforge `#[forge]` 宏通过 inventory 自动注册路由,
//! `sdforge::http::build()` 收集所有注册的路由。
//!
//! # 路径约定
//!
//! `#[forge]` 宏自动将 path 前缀化为 `/api/{version}{path}`。
//! 因此 path 参数只需写 `/auth/login`,version="v1" → 实际路由 `/api/v1/auth/login`。
//! 使用 `no_prefix = true` 可禁用自动前缀化(本模块未使用)。
//!
//! # State 注入
//!
//! sdforge `#[state]` 参数通过 `axum::extract::Extension<T>` 注入。
//! 调用方需在 Router 上 `.layer(Extension(backend))` 注入后端。
//!
//! # 路由列表
//!
//! - 外网 3 端点:login / logout / refresh
//! - 内网 12 端点:check-login / check-permission / check-role / check-safe /
//!   check-disable / check-api-key / get-token-info / get-session / kickout /
//!   switch-to / renew-to-equivalent / health

#![cfg(feature = "auth-server-sdforge")]
// #[forge] 宏生成的代码含 #[cfg(feature = "mcp")] / #[cfg(feature = "cli")] 等
// bulwark 不具备的 feature cfg,属于外部宏展开的正常现象,抑制 check-cfg 警告。
#![allow(unexpected_cfgs)]

use crate::backend::types::{
    ApiResponse, CheckApiKeyRequest, CheckLoginRequest, CheckPermissionRequest, CheckRoleRequest,
    KickoutRequest, LoginRequest, LogoutRequest, RenewToEquivalentRequest, SwitchToRequest,
};
use crate::backend::AuthBackend;
use crate::error::GarrisonError;
use crate::loc;
use sdforge::forge;
use sdforge::prelude::ApiError;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

// 复用 mod.rs 的 to_api_response 逻辑(避免重复实现)
use super::to_api_response;

// 内部端点请求结构体(caller_login_id 所有权校验)

/// get-session / get-token-info 请求体:在 `CheckLoginRequest` 基础上增加可选 `caller_login_id`,
/// 用于校验调用者是否有权访问目标 token 的 session。
///
/// `caller_login_id` 在 serde 层可选(`#[serde(default)]`,兼容存量反序列化),但**路由层强制必填**,
/// 缺失返回 400(fail-closed——内网 API Key 一旦泄露,缺省跳过校验即可静默枚举任意活跃 token 归属);
/// `Some(id)` 与 `session.login_id` 不符返回 `NotPermission`。
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetSessionRequest {
    /// 待查询的 token 字符串。
    pub token: String,
    /// 调用者 login_id(用于所有权校验,路由层强制必填)。
    #[serde(default)]
    pub caller_login_id: Option<String>,
}

/// caller_login_id 缺失的 fail-closed 拒绝(两所有权校验端点共用)。
fn missing_caller_login_id() -> ApiError {
    tracing::warn!(
        "{}",
        crate::i18n::translate_detail("logs-sdforge-caller-login-id-missing", &[])
    );
    ApiError::InvalidInput {
        message: crate::i18n::translate_detail("sdforge-caller-login-id-required-msg", &[]),
        field: Some("caller_login_id".to_string()),
        value: None,
    }
}

// 外网路由(3 端点)

#[forge(
    name = "auth_login",
    version = "v1",
    path = "/auth/login",
    method = "POST",
    tool_name = "auth_login",
    description = "Log in and return a token"
)]
async fn login(
    #[state] backend: Arc<dyn AuthBackend>,
    req: LoginRequest,
) -> Result<ApiResponse<String>, ApiError> {
    let result = backend.login(&req.login_id, &req.params).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_logout",
    version = "v1",
    path = "/auth/logout",
    method = "POST",
    tool_name = "auth_logout",
    description = "Log out a token"
)]
async fn logout(
    #[state] backend: Arc<dyn AuthBackend>,
    req: LogoutRequest,
) -> Result<ApiResponse<()>, ApiError> {
    let result = backend.logout(&req.token).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_refresh",
    version = "v1",
    path = "/auth/refresh",
    method = "POST",
    tool_name = "auth_refresh",
    description = "Refresh a token"
)]
async fn refresh(
    #[state] backend: Arc<dyn AuthBackend>,
    req: RenewToEquivalentRequest,
) -> Result<ApiResponse<String>, ApiError> {
    let result = backend.renew_to_equivalent(&req.token).await;
    Ok(to_api_response(result))
}

// 内网路由(12 端点)

#[forge(
    name = "auth_check_login",
    version = "v1",
    path = "/auth/check-login",
    method = "POST",
    tool_name = "auth_check_login",
    description = "Check login status"
)]
async fn check_login(
    #[state] backend: Arc<dyn AuthBackend>,
    req: CheckLoginRequest,
) -> Result<ApiResponse<bool>, ApiError> {
    let result = backend.check_login(&req.token).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_check_permission",
    version = "v1",
    path = "/auth/check-permission",
    method = "POST",
    tool_name = "auth_check_permission",
    description = "Check permission"
)]
async fn check_permission(
    #[state] backend: Arc<dyn AuthBackend>,
    req: CheckPermissionRequest,
) -> Result<ApiResponse<()>, ApiError> {
    let result = backend.check_permission(&req.token, &req.permission).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_check_role",
    version = "v1",
    path = "/auth/check-role",
    method = "POST",
    tool_name = "auth_check_role",
    description = "Check role"
)]
async fn check_role(
    #[state] backend: Arc<dyn AuthBackend>,
    req: CheckRoleRequest,
) -> Result<ApiResponse<()>, ApiError> {
    let result = backend.check_role(&req.token, &req.role).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_check_safe",
    version = "v1",
    path = "/auth/check-safe",
    method = "POST",
    tool_name = "auth_check_safe",
    description = "Check second-factor auth"
)]
async fn check_safe(
    #[state] backend: Arc<dyn AuthBackend>,
    req: CheckLoginRequest,
) -> Result<ApiResponse<bool>, ApiError> {
    let result = backend.check_safe(&req.token).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_check_disable",
    version = "v1",
    path = "/auth/check-disable",
    method = "POST",
    tool_name = "auth_check_disable",
    description = "Check ban status"
)]
async fn check_disable(
    #[state] backend: Arc<dyn AuthBackend>,
    req: CheckLoginRequest,
) -> Result<ApiResponse<bool>, ApiError> {
    let result = backend.check_disable(&req.token).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_check_api_key",
    version = "v1",
    path = "/auth/check-api-key",
    method = "POST",
    tool_name = "auth_check_api_key",
    description = "Verify API Key"
)]
async fn check_api_key(
    #[state] backend: Arc<dyn AuthBackend>,
    req: CheckApiKeyRequest,
) -> Result<ApiResponse<()>, ApiError> {
    let result = backend.check_api_key(&req.api_key, &req.namespace).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_get_token_info",
    version = "v1",
    path = "/auth/get-token-info",
    method = "POST",
    tool_name = "auth_get_token_info",
    description = "Get token info"
)]
async fn get_token_info(
    #[state] backend: Arc<dyn AuthBackend>,
    req: GetSessionRequest,
) -> Result<ApiResponse<crate::backend::types::TokenInfo>, ApiError> {
    // caller 所有权校验:caller_login_id 强制必填(fail-closed)
    let caller = match req.caller_login_id {
        Some(ref caller) => caller,
        None => return Err(missing_caller_login_id()),
    };
    // 需先获取 session 以比对 login_id
    let session_result = backend.get_session(&req.token).await;
    let session = match session_result {
        Ok(s) => s,
        Err(e) => return Ok(to_api_response(Err(e))),
    };
    if caller != &session.login_id {
        tracing::warn!(
            caller_login_id = %caller,
            session_login_id = %session.login_id,
            "{}",
            crate::i18n::translate_detail("logs-sdforge-token-info-cross-user", &[])
        );
        return Ok(to_api_response(Err(GarrisonError::NotPermission(loc!(
            "caller-login-id-mismatch",
            "caller_login_id does not match session.login_id"
        )))));
    }
    let result = backend.get_token_info(&req.token).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_get_session",
    version = "v1",
    path = "/auth/get-session",
    method = "POST",
    tool_name = "auth_get_session",
    description = "Get session"
)]
async fn get_session(
    #[state] backend: Arc<dyn AuthBackend>,
    req: GetSessionRequest,
) -> Result<ApiResponse<crate::backend::types::SessionData>, ApiError> {
    // caller 所有权校验:caller_login_id 强制必填(fail-closed)
    let caller = match req.caller_login_id {
        Some(ref caller) => caller,
        None => return Err(missing_caller_login_id()),
    };
    let mut session = match backend.get_session(&req.token).await {
        Ok(s) => s,
        Err(e) => return Ok(to_api_response(Err(e))),
    };
    if caller != &session.login_id {
        tracing::warn!(
            caller_login_id = %caller,
            session_login_id = %session.login_id,
            "{}",
            crate::i18n::translate_detail("logs-sdforge-session-cross-user", &[])
        );
        return Ok(to_api_response(Err(GarrisonError::NotPermission(loc!(
            "caller-login-id-mismatch",
            "caller_login_id does not match session.login_id"
        )))));
    }
    // A5: PII 过滤——ip / user_agent / device 不暴露给内部端点调用方
    session.ip = None;
    session.user_agent = None;
    session.device = None;
    Ok(to_api_response(Ok(session)))
}

#[forge(
    name = "auth_kickout",
    version = "v1",
    path = "/auth/kickout",
    method = "POST",
    tool_name = "auth_kickout",
    description = "Kick out a login subject"
)]
async fn kickout(
    #[state] backend: Arc<dyn AuthBackend>,
    req: KickoutRequest,
) -> Result<ApiResponse<()>, ApiError> {
    let result = backend.kickout(&req.login_id).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_switch_to",
    version = "v1",
    path = "/auth/switch-to",
    method = "POST",
    tool_name = "auth_switch_to",
    description = "Switch login subject"
)]
async fn switch_to(
    #[state] backend: Arc<dyn AuthBackend>,
    req: SwitchToRequest,
) -> Result<ApiResponse<()>, ApiError> {
    let result = backend.switch_to(&req.token, &req.target_login_id).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_renew_to_equivalent",
    version = "v1",
    path = "/auth/renew-to-equivalent",
    method = "POST",
    tool_name = "auth_renew_to_equivalent",
    description = "Renew a token"
)]
async fn renew_to_equivalent(
    #[state] backend: Arc<dyn AuthBackend>,
    req: CheckLoginRequest,
) -> Result<ApiResponse<String>, ApiError> {
    let result = backend.renew_to_equivalent(&req.token).await;
    Ok(to_api_response(result))
}

#[forge(
    name = "auth_health",
    version = "v1",
    path = "/auth/health",
    method = "GET",
    tool_name = "auth_health",
    description = "Health check"
)]
async fn health() -> Result<ApiResponse<&'static str>, ApiError> {
    Ok(ApiResponse::ok("ok"))
}

// Metrics 端点(feature = "metrics-prometheus")

/// /metrics 端点,暴露 Prometheus 格式指标。
///
/// 调用 `prometheus::gather()` 收集 default registry 的所有指标
/// (`GarrisonMetrics::new()` 注册的 `garrison_*` 指标),
/// 用 `TextEncoder` 编码为 Prometheus 文本格式。
///
/// # 设计权衡(已知限制)
///
/// `#[forge]` 宏非 streaming 模式下用 `Json(value)` 包装返回值,故本端点 Content-Type 为 `application/json`、body 为 JSON 序列化字符串,非标准 Prometheus `text/plain` 抓取格式;标准 scraper 无法直接解析,须在 `GarrisonAuthServer::external_router()`/`internal_router()` 用 axum 原生路由注册 text/plain 版(绕过 `#[forge]` 宏)或在抓取侧解包。本端点保留 `#[forge]` 声明式注册以维持路由定义一致性(集成测试固化该 JSON 契约)。
///
/// # 错误
///
/// `TextEncoder::encode` 仅在 buffer 写入失败时返回 `ApiError::Internal`(error_id = "metrics-encode-failure",实际不会发生)。
#[cfg(feature = "metrics-prometheus")]
#[forge(
    name = "auth_metrics",
    version = "v1",
    path = "/metrics",
    method = "GET",
    tool_name = "auth_metrics",
    description = "Prometheus metrics endpoint"
)]
async fn metrics() -> Result<String, ApiError> {
    let output = prometheus::TextEncoder::new()
        .encode_to_string(&prometheus::gather())
        .map_err(|e| {
            ApiError::internal_with_source(
                loc!(
                    "metrics-encode-failed",
                    "Prometheus metrics encoding failed"
                ),
                "metrics-encode-failure",
                e,
            )
        })?;
    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::types::LoginParams;
    use crate::error::GarrisonError;
    use async_trait::async_trait;
    use axum::body::Body;
    use axum::extract::Extension;
    use axum::http::{Request, StatusCode};
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    /// 测试用 Mock AuthBackend(返回可预测的固定数据)。
    struct MockAuthBackend;

    #[async_trait]
    impl AuthBackend for MockAuthBackend {
        async fn login(
            &self,
            login_id: &str,
            _params: &LoginParams,
        ) -> Result<String, GarrisonError> {
            Ok(format!("token-{}", login_id))
        }
        async fn logout(&self, _token: &str) -> Result<(), GarrisonError> {
            Ok(())
        }
        async fn check_login(&self, token: &str) -> Result<bool, GarrisonError> {
            Ok(token.starts_with("valid-"))
        }
        async fn check_permission(
            &self,
            token: &str,
            permission: &str,
        ) -> Result<(), GarrisonError> {
            if token.is_empty() {
                return Err(GarrisonError::InvalidToken("token 为空".to_string()));
            }
            if permission == "denied" {
                return Err(GarrisonError::NotPermission("无权限".to_string()));
            }
            Ok(())
        }
        async fn check_role(&self, _token: &str, _role: &str) -> Result<(), GarrisonError> {
            Ok(())
        }
        async fn check_safe(&self, _token: &str) -> Result<bool, GarrisonError> {
            Ok(true)
        }
        async fn check_disable(&self, _token: &str) -> Result<bool, GarrisonError> {
            Ok(false)
        }
        async fn check_api_key(
            &self,
            api_key: &str,
            _namespace: &str,
        ) -> Result<(), GarrisonError> {
            if api_key == "invalid" {
                return Err(GarrisonError::InvalidToken("API Key 无效".to_string()));
            }
            Ok(())
        }
        async fn get_token_info(
            &self,
            token: &str,
        ) -> Result<crate::backend::types::TokenInfo, GarrisonError> {
            Ok(crate::backend::types::TokenInfo {
                token: token.to_string(),
                created_at: 1000,
                last_active_at: 2000,
            })
        }
        async fn get_session(
            &self,
            token: &str,
        ) -> Result<crate::backend::types::SessionData, GarrisonError> {
            Ok(crate::backend::types::SessionData {
                token: token.to_string(),
                login_id: "mock-user".to_string(),
                created_at: 1000,
                last_active_at: 2000,
                attrs: std::collections::HashMap::new(),
                device: Some("web-chrome".to_string()),
                ip: Some("127.0.0.1".to_string()),
                user_agent: Some("Mozilla/5.0".to_string()),
                safe_services: std::collections::HashMap::new(),
                #[cfg(feature = "session-extra")]
                dynamic_active_timeout: None,
                #[cfg(feature = "session-extra")]
                is_anon: false,
                effective_timeout: None,
                amr_ledger: Vec::new(),
                auth_time: None,
            })
        }
        async fn kickout(&self, _login_id: &str) -> Result<(), GarrisonError> {
            Ok(())
        }
        async fn switch_to(
            &self,
            _token: &str,
            _target_login_id: &str,
        ) -> Result<(), GarrisonError> {
            Ok(())
        }
        async fn renew_to_equivalent(&self, token: &str) -> Result<String, GarrisonError> {
            Ok(format!("renewed-{}", token))
        }
    }

    fn make_backend() -> Arc<dyn AuthBackend> {
        Arc::new(MockAuthBackend)
    }

    /// 构建 sdforge 路由(注入 mock backend via Extension layer)。
    fn make_router() -> axum::Router {
        sdforge::http::build().layer(Extension(make_backend()))
    }

    /// 发送 POST 请求并返回 (状态码, 响应 JSON)。
    async fn post_json_with_status(
        router: axum::Router,
        uri: &str,
        body: serde_json::Value,
    ) -> (StatusCode, serde_json::Value) {
        let resp = router
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri(uri)
                    .header("content-type", "application/json")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = resp.status();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        (status, serde_json::from_slice(&bytes).unwrap())
    }

    /// 发送 POST 请求并断言 200 后返回响应 JSON。
    async fn post_json(
        router: axum::Router,
        uri: &str,
        body: serde_json::Value,
    ) -> serde_json::Value {
        let (status, json) = post_json_with_status(router, uri, body).await;
        assert_eq!(status, StatusCode::OK);
        json
    }

    // 外网路由测试(3 端点)

    #[tokio::test]
    async fn test_sdforge_login_returns_token() {
        let app = make_router();
        let body = serde_json::json!({
            "login_id": "user1",
            "params": LoginParams::default()
        });
        let resp_json = post_json(app, "/api/v1/auth/login", body).await;
        assert_eq!(resp_json["data"], "token-user1");
    }

    #[tokio::test]
    async fn test_sdforge_logout_succeeds() {
        let app = make_router();
        let body = serde_json::json!({ "token": "some-token" });
        let resp_json = post_json(app, "/api/v1/auth/logout", body).await;
        assert!(resp_json.get("error_code").is_none() || resp_json["error_code"].is_null());
    }

    #[tokio::test]
    async fn test_sdforge_refresh_returns_new_token() {
        let app = make_router();
        let body = serde_json::json!({ "token": "old-token" });
        let resp_json = post_json(app, "/api/v1/auth/refresh", body).await;
        assert_eq!(resp_json["data"], "renewed-old-token");
    }

    // 内网路由测试(12 端点)

    #[tokio::test]
    async fn test_sdforge_check_login_returns_true() {
        let app = make_router();
        let body = serde_json::json!({ "token": "valid-token" });
        let resp_json = post_json(app, "/api/v1/auth/check-login", body).await;
        assert_eq!(resp_json["data"], true);
    }

    #[tokio::test]
    async fn test_sdforge_check_login_returns_false() {
        let app = make_router();
        let body = serde_json::json!({ "token": "invalid-token" });
        let resp_json = post_json(app, "/api/v1/auth/check-login", body).await;
        assert_eq!(resp_json["data"], false);
    }

    #[tokio::test]
    async fn test_sdforge_check_permission_succeeds() {
        let app = make_router();
        let body = serde_json::json!({ "token": "valid", "permission": "user:read" });
        let resp_json = post_json(app, "/api/v1/auth/check-permission", body).await;
        assert!(resp_json.get("error_code").is_none() || resp_json["error_code"].is_null());
    }

    #[tokio::test]
    async fn test_sdforge_check_permission_denied() {
        let app = make_router();
        let body = serde_json::json!({ "token": "valid", "permission": "denied" });
        let resp_json = post_json(app, "/api/v1/auth/check-permission", body).await;
        assert_eq!(resp_json["error_code"], "NOT_PERMISSION");
    }

    #[tokio::test]
    async fn test_sdforge_check_role_succeeds() {
        let app = make_router();
        let body = serde_json::json!({ "token": "valid", "role": "admin" });
        let resp_json = post_json(app, "/api/v1/auth/check-role", body).await;
        assert!(resp_json.get("error_code").is_none() || resp_json["error_code"].is_null());
    }

    #[tokio::test]
    async fn test_sdforge_check_safe_returns_true() {
        let app = make_router();
        let body = serde_json::json!({ "token": "valid" });
        let resp_json = post_json(app, "/api/v1/auth/check-safe", body).await;
        assert_eq!(resp_json["data"], true);
    }

    #[tokio::test]
    async fn test_sdforge_check_disable_returns_false() {
        let app = make_router();
        let body = serde_json::json!({ "token": "valid" });
        let resp_json = post_json(app, "/api/v1/auth/check-disable", body).await;
        assert_eq!(resp_json["data"], false);
    }

    #[tokio::test]
    async fn test_sdforge_check_api_key_valid() {
        let app = make_router();
        let body = serde_json::json!({ "api_key": "valid-key", "namespace": "default" });
        let resp_json = post_json(app, "/api/v1/auth/check-api-key", body).await;
        assert!(resp_json.get("error_code").is_none() || resp_json["error_code"].is_null());
    }

    #[tokio::test]
    async fn test_sdforge_check_api_key_invalid() {
        let app = make_router();
        let body = serde_json::json!({ "api_key": "invalid", "namespace": "default" });
        let resp_json = post_json(app, "/api/v1/auth/check-api-key", body).await;
        assert_eq!(resp_json["error_code"], "INVALID_TOKEN");
    }

    #[tokio::test]
    async fn test_sdforge_get_token_info() {
        let app = make_router();
        let body = serde_json::json!({ "token": "my-token", "caller_login_id": "mock-user" });
        let resp_json = post_json(app, "/api/v1/auth/get-token-info", body).await;
        assert_eq!(resp_json["data"]["token"], "my-token");
        assert_eq!(resp_json["data"]["created_at"], 1000);
    }

    #[tokio::test]
    async fn test_sdforge_get_session() {
        let app = make_router();
        let body = serde_json::json!({ "token": "my-token", "caller_login_id": "mock-user" });
        let resp_json = post_json(app, "/api/v1/auth/get-session", body).await;
        assert_eq!(resp_json["data"]["token"], "my-token");
        assert_eq!(resp_json["data"]["login_id"], "mock-user");
    }

    // get-session 所有权校验 + PII 过滤

    /// A5: get-session 返回数据应过滤 PII 字段(ip/user_agent/device)。
    #[tokio::test]
    async fn test_sdforge_get_session_filters_pii_fields() {
        let app = make_router();
        let body = serde_json::json!({ "token": "my-token", "caller_login_id": "mock-user" });
        let resp_json = post_json(app, "/api/v1/auth/get-session", body).await;
        // PII 字段应为 null(被过滤)
        assert!(
            resp_json["data"]["ip"].is_null(),
            "ip 应被过滤为 null,实际: {:?}",
            resp_json["data"]["ip"]
        );
        assert!(
            resp_json["data"]["user_agent"].is_null(),
            "user_agent 应被过滤为 null,实际: {:?}",
            resp_json["data"]["user_agent"]
        );
        assert!(
            resp_json["data"]["device"].is_null(),
            "device 应被过滤为 null,实际: {:?}",
            resp_json["data"]["device"]
        );
    }

    /// A5: caller_login_id 匹配 session.login_id 时应返回 OK。
    #[tokio::test]
    async fn test_sdforge_get_session_with_matching_caller() {
        let app = make_router();
        let body = serde_json::json!({ "token": "my-token", "caller_login_id": "mock-user" });
        let resp_json = post_json(app, "/api/v1/auth/get-session", body).await;
        assert_eq!(resp_json["data"]["login_id"], "mock-user");
        assert!(
            resp_json.get("error_code").is_none() || resp_json["error_code"].is_null(),
            "匹配的 caller_login_id 应返回 OK,实际: {:?}",
            resp_json
        );
    }

    /// A5: caller_login_id 不匹配 session.login_id 时应返回 NotPermission 错误。
    #[tokio::test]
    async fn test_sdforge_get_session_with_mismatched_caller() {
        let app = make_router();
        let body = serde_json::json!({ "token": "my-token", "caller_login_id": "attacker-user" });
        let resp_json = post_json(app, "/api/v1/auth/get-session", body).await;
        assert_eq!(
            resp_json["error_code"], "NOT_PERMISSION",
            "跨用户访问应返回 NOT_PERMISSION,实际: {:?}",
            resp_json
        );
    }

    /// 未提供 caller_login_id 时 fail-closed 拒绝(HTTP 400,不再 warn+放行——内网 key 泄露不再可静默枚举任意 token 归属)。
    #[tokio::test]
    async fn test_sdforge_get_session_missing_caller_login_id_rejected() {
        let app = make_router();
        let (status, resp_json) = post_json_with_status(
            app,
            "/api/v1/auth/get-session",
            serde_json::json!({ "token": "my-token" }),
        )
        .await;
        assert_eq!(
            status,
            StatusCode::BAD_REQUEST,
            "caller_login_id 缺失应返回 4xx,实际: {status}"
        );
        assert!(resp_json.get("data").is_none(), "拒绝响应不得携带会话数据");
    }

    /// get-token-info 缺失 caller_login_id 同样 fail-closed 拒绝。
    #[tokio::test]
    async fn test_sdforge_get_token_info_missing_caller_login_id_rejected() {
        let app = make_router();
        let (status, resp_json) = post_json_with_status(
            app,
            "/api/v1/auth/get-token-info",
            serde_json::json!({ "token": "my-token" }),
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(resp_json.get("data").is_none());
    }

    /// A5: get-token-info 同样应用 caller 所有权校验。
    #[tokio::test]
    async fn test_sdforge_get_token_info_with_mismatched_caller() {
        let app = make_router();
        let body = serde_json::json!({ "token": "my-token", "caller_login_id": "attacker-user" });
        let resp_json = post_json(app, "/api/v1/auth/get-token-info", body).await;
        assert_eq!(
            resp_json["error_code"], "NOT_PERMISSION",
            "get-token-info 跨用户访问应返回 NOT_PERMISSION,实际: {:?}",
            resp_json
        );
    }

    /// A5: get-token-info 匹配的 caller_login_id 应正常返回。
    #[tokio::test]
    async fn test_sdforge_get_token_info_with_matching_caller() {
        let app = make_router();
        let body = serde_json::json!({ "token": "my-token", "caller_login_id": "mock-user" });
        let resp_json = post_json(app, "/api/v1/auth/get-token-info", body).await;
        assert_eq!(resp_json["data"]["token"], "my-token");
    }

    #[tokio::test]
    async fn test_sdforge_kickout_succeeds() {
        let app = make_router();
        let body = serde_json::json!({ "login_id": "user1" });
        let resp_json = post_json(app, "/api/v1/auth/kickout", body).await;
        assert!(resp_json.get("error_code").is_none() || resp_json["error_code"].is_null());
    }

    #[tokio::test]
    async fn test_sdforge_switch_to_succeeds() {
        let app = make_router();
        let body = serde_json::json!({ "token": "tok", "target_login_id": "user2" });
        let resp_json = post_json(app, "/api/v1/auth/switch-to", body).await;
        assert!(resp_json.get("error_code").is_none() || resp_json["error_code"].is_null());
    }

    #[tokio::test]
    async fn test_sdforge_renew_to_equivalent() {
        let app = make_router();
        let body = serde_json::json!({ "token": "old-token" });
        let resp_json = post_json(app, "/api/v1/auth/renew-to-equivalent", body).await;
        assert_eq!(resp_json["data"], "renewed-old-token");
    }

    #[tokio::test]
    async fn test_sdforge_health() {
        let app = make_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/api/v1/auth/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let resp_json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(resp_json["data"], "ok");
    }

    // 路由计数验证

    #[test]
    fn test_sdforge_route_count() {
        // sdforge::http::build() 收集所有 #[forge] 注册的路由
        // metrics-prometheus 启用时 16 个(3 外网 + 12 内网 + 1 metrics)
        // 未启用时 15 个(3 外网 + 12 内网)
        let router = sdforge::http::build();
        let route_count = count_routes(&router);
        #[cfg(feature = "metrics-prometheus")]
        let expected = 16;
        #[cfg(not(feature = "metrics-prometheus"))]
        let expected = 15;
        assert_eq!(
            route_count, expected,
            "sdforge 应注册 {} 个路由,实际 {}",
            expected, route_count
        );
    }

    /// 递归计数 Router 中的路由数(通过 axum 内部结构)。
    /// axum Router 没有公开的 route 计数 API,
    /// 这里用 inventory 直接计数注册项。
    fn count_routes(_router: &axum::Router) -> usize {
        // inventory::iter 收集所有编译期注册的 RouteRegistration + HttpRoute
        let reg_count = inventory::iter::<sdforge::http::RouteRegistration>
            .into_iter()
            .count();
        let direct_count = inventory::iter::<sdforge::http::HttpRoute>
            .into_iter()
            .count();
        // 去重后的数量由 build() 内部处理,这里取注册总数作为近似值
        reg_count + direct_count
    }

    // Metrics 端点测试(feature = "metrics-prometheus")

    /// /metrics 端点返回 200 + JSON 包装的 Prometheus 文本格式。
    ///
    /// `#[forge]` 宏用 `Json(value).into_response()` 包装返回值,
    /// 响应 body 为 JSON 序列化的字符串(含转义换行符)。
    /// 测试解析 JSON 字符串后验证包含 `bulwark_` 前缀指标。
    ///
    /// 注:该测试固化了「metrics 经 #[forge] 输出 JSON 包装」的设计取舍
    /// ——标准 Prometheus `text/plain` 抓取需绕过
    /// `#[forge]` 用 axum 原生路由注册,见 metrics handler 的文档说明。
    #[cfg(feature = "metrics-prometheus")]
    #[tokio::test]
    #[serial_test::serial]
    async fn test_sdforge_metrics_returns_prometheus_format() {
        use crate::observability::GarrisonMetrics;

        // 注册 GarrisonMetrics 到 default registry(若已注册则跳过 AlreadyReg)
        if let Ok(metrics) = GarrisonMetrics::register_to(prometheus::default_registry()) {
            metrics.record_login(true);
            metrics.record_permission_query(true);
        }

        let app = make_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/api/v1/metrics")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        // #[forge] 宏用 Json(value) 包装返回值,响应是 JSON 字符串
        let body: String = serde_json::from_slice(&bytes).expect("响应应为 JSON 序列化的字符串");
        assert!(
            body.contains("garrison_login_total"),
            "/metrics 应包含 garrison_login_total 指标,实际: {}",
            body
        );
    }

    /// /metrics 端点在未注册 GarrisonMetrics 时返回 200 + 空字符串。
    ///
    /// 验证 default registry 为空时端点不 panic,返回空 Prometheus 文本。
    #[cfg(feature = "metrics-prometheus")]
    #[tokio::test]
    #[serial_test::serial]
    async fn test_sdforge_metrics_returns_empty_when_no_metrics() {
        // 不注册任何指标,验证端点不 panic
        // 注意:default registry 是全局共享的,其他测试可能已注册指标,
        // 此测试仅验证端点不 panic 且返回 200(不验证 body 内容)
        let app = make_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/api/v1/metrics")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        // 响应应为有效 JSON 字符串(可能为空字符串 "")
        let _body: String = serde_json::from_slice(&bytes).expect("响应应为 JSON 序列化的字符串");
    }
}