garrison 0.7.3

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
//! Copyright (c) 2026 Kirky.X. All rights reserved.
//! See LICENSE for full license text.

//! OAuth2 HTTP 端点路由(feature = "oauth2-server")。
//!
//! 将 OAuth2 handler 暴露为 HTTP 端点,集成到 GarrisonAuthServer。
//! 与 sdforge_routes.rs(AuthBackend 路由)互补,使用 axum Router::merge 集成。
//!
//! # 端点
//!
//! - 外网:`GET /oauth2/authorize`、`POST /oauth2/token`、`POST /oauth2/revoke`
//! - 内网:`POST /oauth2/introspect`

#![cfg(feature = "oauth2-server")]

use std::sync::Arc;

use axum::extract::{Extension, Query, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde_json::json;

use crate::context::GarrisonPrincipal;
use crate::dao::GarrisonDao;
use crate::oauth2_server::authorize::{AuthorizeHandler, AuthorizeRequest, AuthorizeResponse};
use crate::oauth2_server::client::OAuth2ClientStore;
use crate::oauth2_server::introspect::{IntrospectHandler, IntrospectRequest};
use crate::oauth2_server::revoke::{RevokeHandler, RevokeRequest};
use crate::oauth2_server::token::{TokenHandler, TokenRequest};

/// OAuth2 路由共享状态。
///
/// 持有所有 OAuth2 handler,通过 `Arc<OAuth2State>` 注入到 axum Router。
pub struct OAuth2State {
    /// 授权码流程 handler(/oauth2/authorize)。
    pub authorize_handler: Arc<AuthorizeHandler>,
    /// Token 签发 handler(/oauth2/token,4 种 grant type)。
    pub token_handler: Arc<TokenHandler>,
    /// Token 撤销 handler(/oauth2/revoke,RFC 7009)。
    pub revoke_handler: Arc<RevokeHandler>,
    /// Token 内省 handler(/oauth2/introspect,RFC 7662)。
    pub introspect_handler: Arc<IntrospectHandler>,
}

impl OAuth2State {
    /// 创建 OAuth2State,内部构造 4 个 handler。
    pub fn new(
        store: Arc<dyn OAuth2ClientStore>,
        dao: Arc<dyn GarrisonDao>,
        login_url: String,
    ) -> Self {
        let authorize_handler =
            Arc::new(AuthorizeHandler::new(store.clone(), dao.clone(), login_url));
        let token_handler = Arc::new(TokenHandler::new(
            store.clone(),
            dao.clone(),
            authorize_handler.clone(),
        ));
        let revoke_handler = Arc::new(RevokeHandler::new(store.clone(), token_handler.clone()));
        let introspect_handler = Arc::new(IntrospectHandler::new(store, token_handler.clone()));
        Self {
            authorize_handler,
            token_handler,
            revoke_handler,
            introspect_handler,
        }
    }
}

/// 构建外网 OAuth2 路由(authorize/token/revoke)。
pub fn oauth2_external_router(state: Arc<OAuth2State>) -> Router {
    Router::new()
        .route("/oauth2/authorize", get(authorize_endpoint))
        .route("/oauth2/token", post(token_endpoint))
        .route("/oauth2/revoke", post(revoke_endpoint))
        .with_state(state)
}

/// 构建内网 OAuth2 路由(introspect)。
pub fn oauth2_internal_router(state: Arc<OAuth2State>) -> Router {
    Router::new()
        .route("/oauth2/introspect", post(introspect_endpoint))
        .with_state(state)
}

// === HTTP 端点函数(薄包装,调用 handler) ===

async fn authorize_endpoint(
    State(state): State<Arc<OAuth2State>>,
    Query(req): Query<AuthorizeRequest>,
    principal: Option<Extension<GarrisonPrincipal>>,
) -> Response {
    // 从 GarrisonPrincipal Extension 提取 user_id(无 principal 或 login_id 解析失败 → None → LoginRequired)
    let user_id: Option<i64> = principal.and_then(|ext| ext.0.login_id.parse::<i64>().ok());
    match state.authorize_handler.authorize(&req, user_id).await {
        Ok(AuthorizeResponse::Redirect { location }) => {
            (StatusCode::FOUND, [("Location", location)]).into_response()
        },
        Ok(AuthorizeResponse::LoginRequired { login_url }) => {
            (StatusCode::FOUND, [("Location", login_url)]).into_response()
        },
        Err(e) => {
            let (_, error_code, message, _) = e.response_parts_i18n();
            (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": error_code, "message": message })),
            )
                .into_response()
        },
    }
}

async fn token_endpoint(
    State(state): State<Arc<OAuth2State>>,
    headers: HeaderMap,
    Json(req): Json<TokenRequest>,
) -> Response {
    // 提取 Authorization 头(RFC 6749 §2.3.1 HTTP Basic Auth)
    let authorization = headers
        .get(axum::http::header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_string());

    match state
        .token_handler
        .handle_with_authorization(&req, authorization.as_deref())
        .await
    {
        Ok(resp) => {
            // RFC 6749 §5.1 — token 响应必须含 Cache-Control: no-store + Pragma: no-cache
            let mut response = (StatusCode::OK, Json(resp)).into_response();
            response.headers_mut().insert(
                HeaderName::from_static("cache-control"),
                HeaderValue::from_static("no-store"),
            );
            response.headers_mut().insert(
                HeaderName::from_static("pragma"),
                HeaderValue::from_static("no-cache"),
            );
            response
        },
        Err(e) => {
            let (_, error_code, message, _) = e.response_parts_i18n();
            // 速率限制错误返回 429 Too Many Requests(RFC 6585 §4)
            //
            // `GarrisonError::OAuth2(_)` 的 error_code 统一为 "OAUTH2_ERROR",
            // 需通过错误消息中的 i18n key 前缀 "oauth2-server-token-rate-limited"
            // 标识区分(与 token handler 中 `PasswordRateLimiter` / `TokenRateLimiter`
            // 的错误格式一致,迁移至 i18n key 后下划线变为连字符)。
            let is_rate_limited = e.to_string().contains("oauth2-server-token-rate-limited");
            let status = if is_rate_limited {
                StatusCode::TOO_MANY_REQUESTS
            } else {
                StatusCode::BAD_REQUEST
            };
            let body_error: &str = if is_rate_limited {
                "RATE_LIMIT_EXCEEDED"
            } else {
                error_code
            };
            (
                status,
                Json(json!({ "error": body_error, "message": message })),
            )
                .into_response()
        },
    }
}

async fn revoke_endpoint(
    State(state): State<Arc<OAuth2State>>,
    Json(req): Json<RevokeRequest>,
) -> Response {
    match state.revoke_handler.handle(&req).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => {
            let (_, error_code, message, _) = e.response_parts_i18n();
            (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": error_code, "message": message })),
            )
                .into_response()
        },
    }
}

async fn introspect_endpoint(
    State(state): State<Arc<OAuth2State>>,
    Json(req): Json<IntrospectRequest>,
) -> Response {
    match state.introspect_handler.handle(&req).await {
        Ok(resp) => (StatusCode::OK, Json(resp)).into_response(),
        Err(e) => {
            let (_, error_code, message, _) = e.response_parts_i18n();
            (
                StatusCode::BAD_REQUEST,
                Json(json!({ "error": error_code, "message": message })),
            )
                .into_response()
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dao::{GarrisonDao, MockDao};
    use crate::oauth2_server::client::{
        DaoOAuth2ClientStore, GrantType, OAuth2Client, OAuth2ClientStore,
    };
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    /// 创建测试用 OAuth2State + store(用于注册客户端)。
    fn make_state() -> (Arc<OAuth2State>, Arc<dyn OAuth2ClientStore>) {
        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let store: Arc<dyn OAuth2ClientStore> = Arc::new(DaoOAuth2ClientStore::new(dao.clone()));
        let state = Arc::new(OAuth2State::new(
            store.clone(),
            dao,
            "https://auth.example.com/login".to_string(),
        ));
        (state, store)
    }

    /// 创建测试用 OAuth2Client(支持 AuthorizationCode + ClientCredentials)。
    fn make_test_client(id: &str) -> OAuth2Client {
        OAuth2Client::new(
            id,
            "secret-123",
            vec!["https://app.example.com/cb".into()],
            vec![GrantType::AuthorizationCode, GrantType::ClientCredentials],
            vec!["read".into()],
        )
        .unwrap()
    }

    // === OAuth2State 构造测试 ===

    #[test]
    fn test_oauth2_state_construction() {
        let (state, _) = make_state();
        // authorize_handler 被 state + token_handler 共享 → strong_count = 2
        assert_eq!(Arc::strong_count(&state.authorize_handler), 2);
        // token_handler 被 state + revoke_handler + introspect_handler 共享 → strong_count = 3
        assert_eq!(Arc::strong_count(&state.token_handler), 3);
        // revoke_handler / introspect_handler 仅被 state 持有 → strong_count = 1
        assert_eq!(Arc::strong_count(&state.revoke_handler), 1);
        assert_eq!(Arc::strong_count(&state.introspect_handler), 1);
    }

    // === 路由存在性测试 ===

    #[tokio::test]
    async fn test_oauth2_external_router_has_authorize_route() {
        let (state, store) = make_state();
        store.create(make_test_client("route-auth")).await.unwrap();
        let app = oauth2_external_router(state);
        // 无 query string → Query 提取失败 → 400(非 404 证明路由存在)
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/oauth2/authorize")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_ne!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_oauth2_external_router_has_token_route() {
        let (state, _) = make_state();
        let app = oauth2_external_router(state);
        // 空 JSON body → Json 提取失败 → 400(非 404 证明路由存在)
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/token")
                    .header("content-type", "application/json")
                    .body(Body::from("{}"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_ne!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_oauth2_external_router_has_revoke_route() {
        let (state, _) = make_state();
        let app = oauth2_external_router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/revoke")
                    .header("content-type", "application/json")
                    .body(Body::from("{}"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_ne!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_oauth2_internal_router_has_introspect_route() {
        let (state, store) = make_state();
        store.create(make_test_client("route-int")).await.unwrap();
        let app = oauth2_internal_router(state);
        let body = serde_json::json!({
            "token": "nonexistent",
            "client_id": "route-int",
            "client_secret": "secret-123",
        });
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/introspect")
                    .header("content-type", "application/json")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        // token 不存在 → active=false,但返回 200 OK
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // === 端点行为测试 ===

    #[tokio::test]
    async fn test_authorize_endpoint_redirects_when_not_logged_in() {
        let (state, store) = make_state();
        store.create(make_test_client("auth-redir")).await.unwrap();
        let app = oauth2_external_router(state);
        let uri = "/oauth2/authorize?response_type=code&client_id=auth-redir&redirect_uri=https://app.example.com/cb&code_challenge=test-challenge&code_challenge_method=S256";
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri(uri)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FOUND);
        let location = resp
            .headers()
            .get("Location")
            .expect("Location header 必须存在")
            .to_str()
            .unwrap();
        assert!(
            location.starts_with("https://auth.example.com/login"),
            "应重定向到登录页,实际: {location}"
        );
    }

    /// T003: 有 GarrisonPrincipal(Extension)时 authorize 端点返回 Redirect 含 code。
    /// principal.login_id = "1001" → user_id = Some(1001) → 授权成功 → Redirect。
    #[tokio::test]
    async fn test_authorize_endpoint_returns_redirect_with_code_when_principal_present() {
        let (state, store) = make_state();
        store
            .create(make_test_client("auth-principal"))
            .await
            .unwrap();
        let app = oauth2_external_router(state).layer(Extension(GarrisonPrincipal {
            login_id: "1001".to_string(),
        }));
        let uri = "/oauth2/authorize?response_type=code&client_id=auth-principal&redirect_uri=https://app.example.com/cb&code_challenge=test-challenge&code_challenge_method=S256";
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri(uri)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FOUND);
        let location = resp
            .headers()
            .get("Location")
            .expect("Location header 必须存在")
            .to_str()
            .unwrap();
        assert!(
            location.starts_with("https://app.example.com/cb?code="),
            "有 principal 时应重定向到 redirect_uri 含 code,实际: {location}"
        );
    }

    /// T003: 无 GarrisonPrincipal(Extension 缺失)时 authorize 端点返回 LoginRequired。
    #[tokio::test]
    async fn test_authorize_endpoint_returns_login_required_when_no_principal() {
        let (state, store) = make_state();
        store
            .create(make_test_client("auth-no-principal"))
            .await
            .unwrap();
        // 无 .layer(Extension(...)) → principal 提取为 None
        let app = oauth2_external_router(state);
        let uri = "/oauth2/authorize?response_type=code&client_id=auth-no-principal&redirect_uri=https://app.example.com/cb&code_challenge=test-challenge&code_challenge_method=S256";
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri(uri)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FOUND);
        let location = resp
            .headers()
            .get("Location")
            .expect("Location header 必须存在")
            .to_str()
            .unwrap();
        assert!(
            location.starts_with("https://auth.example.com/login"),
            "无 principal 应重定向到登录页,实际: {location}"
        );
    }

    #[tokio::test]
    async fn test_token_endpoint_returns_bad_request_on_invalid_client() {
        let (state, _) = make_state();
        let app = oauth2_external_router(state);
        let body = serde_json::json!({
            "grant_type": "client_credentials",
            "client_id": "no-such-client",
            "client_secret": "secret",
        });
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/token")
                    .header("content-type", "application/json")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    /// token 端点成功响应必须含 Cache-Control: no-store + Pragma: no-cache(RFC 6749 §5.1)。
    #[tokio::test]
    async fn test_token_endpoint_returns_cache_control_no_store_header() {
        let (state, store) = make_state();
        store.create(make_test_client("cc-cid")).await.unwrap();
        let app = oauth2_external_router(state);
        let body = serde_json::json!({
            "grant_type": "client_credentials",
            "client_id": "cc-cid",
            "client_secret": "secret-123",
        });
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/token")
                    .header("content-type", "application/json")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        // RFC 6749 §5.1 — 必须含 Cache-Control: no-store
        let cache_control = resp
            .headers()
            .get("cache-control")
            .expect("Cache-Control 头必须存在");
        assert_eq!(
            cache_control.to_str().unwrap(),
            "no-store",
            "Cache-Control 必须为 no-store"
        );
        // RFC 6749 §5.1 — 必须含 Pragma: no-cache
        let pragma = resp.headers().get("pragma").expect("Pragma 头必须存在");
        assert_eq!(
            pragma.to_str().unwrap(),
            "no-cache",
            "Pragma 必须为 no-cache"
        );
    }

    /// token 端点接受 HTTP Basic Auth 头认证客户端(RFC 6749 §2.3.1)。
    #[tokio::test]
    async fn test_token_endpoint_accepts_basic_auth_header() {
        use base64::engine::general_purpose::STANDARD;
        use base64::Engine;
        let (state, store) = make_state();
        store.create(make_test_client("basic-cid")).await.unwrap();
        let app = oauth2_external_router(state);
        // "basic-cid:secret-123" → base64
        let credentials = STANDARD.encode("basic-cid:secret-123");
        let auth_header = format!("Basic {}", credentials);
        let body = serde_json::json!({
            "grant_type": "client_credentials",
            "client_id": "",
            "client_secret": "",
        });
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/token")
                    .header("content-type", "application/json")
                    .header("authorization", &auth_header)
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "Basic Auth 认证应成功,body 留空"
        );
    }

    #[tokio::test]
    async fn test_revoke_endpoint_returns_no_content_on_success() {
        let (state, store) = make_state();
        store.create(make_test_client("rev-ok")).await.unwrap();
        let app = oauth2_external_router(state);

        // 1. 先通过 client_credentials 签发 token
        let issue_body = serde_json::json!({
            "grant_type": "client_credentials",
            "client_id": "rev-ok",
            "client_secret": "secret-123",
        });
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/token")
                    .header("content-type", "application/json")
                    .body(Body::from(issue_body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let token_resp: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        let token = token_resp["access_token"].as_str().expect("access_token");

        // 2. 撤销 token
        let revoke_body = serde_json::json!({
            "token": token,
            "client_id": "rev-ok",
            "client_secret": "secret-123",
        });
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/revoke")
                    .header("content-type", "application/json")
                    .body(Body::from(revoke_body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
    }

    // === /token 端点速率限制测试(B5)===

    /// /token 端点超速率限制时返回 429 Too Many Requests(RFC 6585 §4)。
    ///
    /// 注入 `TokenRateLimiter`(client_max=1),第 2 次请求应返回 429 + `RATE_LIMIT_EXCEEDED`。
    #[tokio::test]
    async fn test_token_endpoint_returns_429_on_rate_limit_exceeded() {
        use crate::oauth2_server::token::TokenRateLimiter;

        let dao: Arc<dyn GarrisonDao> = Arc::new(MockDao::new());
        let store: Arc<dyn OAuth2ClientStore> = Arc::new(DaoOAuth2ClientStore::new(dao.clone()));
        let authorize_handler = Arc::new(AuthorizeHandler::new(
            store.clone(),
            dao.clone(),
            "https://auth.example.com/login".to_string(),
        ));
        let token_handler = Arc::new(
            TokenHandler::new(store.clone(), dao.clone(), authorize_handler.clone())
                .with_token_rate_limiter(Arc::new(TokenRateLimiter::with_limits(1, 60, 100, 60))),
        );
        let revoke_handler = Arc::new(RevokeHandler::new(store.clone(), token_handler.clone()));
        let introspect_handler =
            Arc::new(IntrospectHandler::new(store.clone(), token_handler.clone()));
        let state = Arc::new(OAuth2State {
            authorize_handler,
            token_handler,
            revoke_handler,
            introspect_handler,
        });

        store.create(make_test_client("rl-429")).await.unwrap();
        let app = oauth2_external_router(state);

        let body = serde_json::json!({
            "grant_type": "client_credentials",
            "client_id": "rl-429",
            "client_secret": "secret-123",
        });

        // 第 1 次成功(200 OK)
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/token")
                    .header("content-type", "application/json")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        // 第 2 次被限速(429 Too Many Requests)
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/token")
                    .header("content-type", "application/json")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::TOO_MANY_REQUESTS,
            "超速率限制应返回 429"
        );

        // 验证响应体含 RATE_LIMIT_EXCEEDED error code
        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["error"].as_str().unwrap(),
            "RATE_LIMIT_EXCEEDED",
            "error code 应为 RATE_LIMIT_EXCEEDED"
        );
    }

    /// /token 端点未注入 `TokenRateLimiter` 时,非 rate_limited 错误仍返回 400(向后兼容)。
    #[tokio::test]
    async fn test_token_endpoint_returns_400_on_non_rate_limited_error() {
        let (state, store) = make_state();
        store.create(make_test_client("nrl-400")).await.unwrap();
        let app = oauth2_external_router(state);

        // 用错误 client_secret 触发 OAuth2 错误(非 rate_limited)
        let body = serde_json::json!({
            "grant_type": "client_credentials",
            "client_id": "nrl-400",
            "client_secret": "wrong-secret",
        });

        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/oauth2/token")
                    .header("content-type", "application/json")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        // 非 rate_limited 错误应返回 400(非 429)
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }
}