#![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};
pub struct OAuth2State {
pub authorize_handler: Arc<AuthorizeHandler>,
pub token_handler: Arc<TokenHandler>,
pub revoke_handler: Arc<RevokeHandler>,
pub introspect_handler: Arc<IntrospectHandler>,
}
impl OAuth2State {
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,
}
}
}
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)
}
pub fn oauth2_internal_router(state: Arc<OAuth2State>) -> Router {
Router::new()
.route("/oauth2/introspect", post(introspect_endpoint))
.with_state(state)
}
async fn authorize_endpoint(
State(state): State<Arc<OAuth2State>>,
Query(req): Query<AuthorizeRequest>,
principal: Option<Extension<GarrisonPrincipal>>,
) -> Response {
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 {
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) => {
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();
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;
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)
}
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()
}
#[test]
fn test_oauth2_state_construction() {
let (state, _) = make_state();
assert_eq!(Arc::strong_count(&state.authorize_handler), 2);
assert_eq!(Arc::strong_count(&state.token_handler), 3);
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);
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);
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();
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}"
);
}
#[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}"
);
}
#[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();
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);
}
#[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);
let cache_control = resp
.headers()
.get("cache-control")
.expect("Cache-Control 头必须存在");
assert_eq!(
cache_control.to_str().unwrap(),
"no-store",
"Cache-Control 必须为 no-store"
);
let pragma = resp.headers().get("pragma").expect("Pragma 头必须存在");
assert_eq!(
pragma.to_str().unwrap(),
"no-cache",
"Pragma 必须为 no-cache"
);
}
#[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);
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);
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");
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);
}
#[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",
});
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);
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"
);
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"
);
}
#[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);
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();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
}