use crate::error::{GarrisonError, GarrisonResult};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
use sha2::{Digest, Sha256};
use std::time::Duration;
use super::{TokenIntrospectionResponse, TokenResponse};
pub(crate) const HTTP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
pub(crate) const HTTP_READ_TIMEOUT: Duration = Duration::from_secs(30);
pub(crate) fn build_safe_http_client() -> GarrisonResult<reqwest::Client> {
reqwest::Client::builder()
.connect_timeout(HTTP_CONNECT_TIMEOUT)
.read_timeout(HTTP_READ_TIMEOUT)
.build()
.map_err(|e| GarrisonError::Network(format!("oauth2-http-client-build::{}", e)))
}
pub(crate) const MAX_BODY_BYTES: usize = 4 * 1024 * 1024;
pub(crate) async fn read_limited_bytes(resp: reqwest::Response) -> GarrisonResult<Vec<u8>> {
let mut buf: Vec<u8> = Vec::new();
let mut resp = resp;
while let Some(chunk) = resp
.chunk()
.await
.map_err(|e| GarrisonError::Network(format!("oauth2-body-read::{}", e)))?
{
let new_len = buf
.len()
.checked_add(chunk.len())
.ok_or_else(|| GarrisonError::Network("oauth2-body-overflow".to_string()))?;
if new_len > MAX_BODY_BYTES {
return Err(GarrisonError::Network("oauth2-body-overflow::".to_string()));
}
buf.extend_from_slice(&chunk);
}
Ok(buf)
}
const URLENCODE_SET: &AsciiSet = &NON_ALPHANUMERIC
.remove(b'-')
.remove(b'_')
.remove(b'.')
.remove(b'~');
fn url_encode(s: &str) -> String {
utf8_percent_encode(s, URLENCODE_SET).to_string()
}
pub struct OAuth2Client {
client_id: String,
client_secret: String,
redirect_uri: String,
auth_url: String,
token_url: String,
user_info_url: Option<String>,
introspect_url: Option<String>,
http: reqwest::Client,
#[cfg(feature = "oauth2-scope-handler")]
scope_registry: Option<std::sync::Arc<super::scope::ScopeRegistry>>,
}
impl OAuth2Client {
pub fn new(
client_id: impl Into<String>,
client_secret: impl Into<String>,
redirect_uri: impl Into<String>,
auth_url: impl Into<String>,
token_url: impl Into<String>,
) -> GarrisonResult<Self> {
let client_id = client_id.into();
if client_id.is_empty() {
return Err(GarrisonError::Config("oauth2-client-id-empty".to_string()));
}
let redirect_uri = redirect_uri.into();
Self::validate_redirect_uri(&redirect_uri)?;
let auth_url = auth_url.into();
Self::validate_endpoint_url(&auth_url, "auth_url")?;
let token_url = token_url.into();
Self::validate_endpoint_url(&token_url, "token_url")?;
let http = build_safe_http_client()?;
Ok(Self {
client_id,
client_secret: client_secret.into(),
redirect_uri,
auth_url,
token_url,
user_info_url: None,
introspect_url: None,
http,
#[cfg(feature = "oauth2-scope-handler")]
scope_registry: None,
})
}
fn validate_redirect_uri(redirect_uri: &str) -> GarrisonResult<()> {
let Some(scheme_end) = redirect_uri.find("://") else {
return Err(GarrisonError::InvalidParam(format!(
"url-scheme-https-required::redirect_uri::{}",
redirect_uri
)));
};
let scheme = &redirect_uri[..scheme_end];
let rest = &redirect_uri[scheme_end + 3..];
if scheme == "https" {
return Ok(());
}
if scheme == "http" {
let host_end = rest.find(['/', ':', '?']).unwrap_or(rest.len());
let host = &rest[..host_end];
if host == "localhost" || host == "127.0.0.1" {
return Ok(());
}
}
Err(GarrisonError::InvalidParam(format!(
"url-scheme-https-required::redirect_uri::{}",
redirect_uri
)))
}
fn validate_endpoint_url(url: &str, field: &str) -> GarrisonResult<()> {
Self::validate_redirect_uri(url).map_err(|_| {
GarrisonError::InvalidParam(format!("url-scheme-https-required::{}::{}", field, url))
})
}
pub fn with_user_info_url(mut self, url: impl Into<String>) -> Self {
self.user_info_url = Some(url.into());
self
}
pub fn with_introspect_url(mut self, url: impl Into<String>) -> Self {
self.introspect_url = Some(url.into());
self
}
#[cfg(feature = "oauth2-scope-handler")]
pub fn with_scope_registry(
mut self,
registry: std::sync::Arc<super::scope::ScopeRegistry>,
) -> Self {
self.scope_registry = Some(registry);
self
}
#[cfg(feature = "oauth2-scope-handler")]
async fn validate_scope(&self, scope: Option<&str>) -> GarrisonResult<()> {
if let (Some(registry), Some(s)) = (&self.scope_registry, scope) {
let allowed = registry.validate(s, 0)?;
if !allowed {
return Err(GarrisonError::OAuth2(format!(
"scope validation failed: {}",
s
)));
}
}
Ok(())
}
pub fn auth_url(&self) -> &str {
&self.auth_url
}
pub fn token_url(&self) -> &str {
&self.token_url
}
pub fn user_info_url(&self) -> Option<&str> {
self.user_info_url.as_deref()
}
pub fn generate_pkce_challenge(code_verifier: &str) -> GarrisonResult<String> {
if code_verifier.len() < 43 || code_verifier.len() > 128 {
return Err(GarrisonError::InvalidParam(format!(
"oauth2-pkce-length-invalid::{}",
code_verifier.len()
)));
}
if !code_verifier
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.' || c == '_' || c == '~')
{
return Err(GarrisonError::InvalidParam(
"oauth2-pkce-chars-invalid".to_string(),
));
}
let mut hasher = Sha256::new();
hasher.update(code_verifier.as_bytes());
let digest = hasher.finalize();
Ok(URL_SAFE_NO_PAD.encode(digest))
}
pub fn get_auth_url_with_pkce(
&self,
state: &str,
code_verifier: &str,
) -> GarrisonResult<(String, String)> {
let code_challenge = Self::generate_pkce_challenge(code_verifier)?;
let url = format!(
"{}?response_type=code&client_id={}&redirect_uri={}&state={}&code_challenge={}&code_challenge_method=S256",
self.auth_url,
url_encode(&self.client_id),
url_encode(&self.redirect_uri),
url_encode(state),
url_encode(&code_challenge),
);
Ok((url, code_challenge))
}
pub async fn exchange_code_with_pkce(
&self,
code: &str,
expected_state: &str,
actual_state: &str,
code_verifier: &str,
) -> GarrisonResult<TokenResponse> {
if expected_state.is_empty() || actual_state.is_empty() {
return Err(GarrisonError::OAuth2("oauth2-state-missing".to_string()));
}
if expected_state != actual_state {
return Err(GarrisonError::OAuth2("oauth2-state-mismatch".to_string()));
}
Self::generate_pkce_challenge(code_verifier)?;
let params = [
("grant_type", "authorization_code"),
("code", code),
("redirect_uri", &self.redirect_uri),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
("code_verifier", code_verifier),
];
self.post_token_request(¶ms).await
}
pub async fn get_client_credentials_token(
&self,
scope: Option<&str>,
) -> GarrisonResult<TokenResponse> {
#[cfg(feature = "oauth2-scope-handler")]
self.validate_scope(scope).await?;
let mut params: Vec<(&str, &str)> = vec![
("grant_type", "client_credentials"),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
];
if let Some(s) = scope {
params.push(("scope", s));
}
self.post_token_request(¶ms).await
}
pub async fn get_password_token(
&self,
username: &str,
password: &str,
scope: Option<&str>,
) -> GarrisonResult<TokenResponse> {
if username.is_empty() {
return Err(GarrisonError::InvalidParam(
"oauth2-username-empty".to_string(),
));
}
#[cfg(feature = "oauth2-scope-handler")]
self.validate_scope(scope).await?;
let mut params: Vec<(&str, &str)> = vec![
("grant_type", "password"),
("username", username),
("password", password),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
];
if let Some(s) = scope {
params.push(("scope", s));
}
self.post_token_request(¶ms).await
}
pub async fn refresh_access_token(
&self,
refresh_token: &str,
scope: Option<&str>,
) -> GarrisonResult<TokenResponse> {
if refresh_token.is_empty() {
return Err(GarrisonError::InvalidParam(
"oauth2-refresh-token-empty".to_string(),
));
}
#[cfg(feature = "oauth2-scope-handler")]
self.validate_scope(scope).await?;
let mut params: Vec<(&str, &str)> = vec![
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
];
if let Some(s) = scope {
params.push(("scope", s));
}
self.post_token_request(¶ms).await
}
async fn post_token_request(&self, params: &[(&str, &str)]) -> GarrisonResult<TokenResponse> {
let resp = self
.http
.post(&self.token_url)
.form(params)
.send()
.await
.map_err(|e| GarrisonError::Network(format!("oauth2-token-endpoint::{}", e)))?;
let status = resp.status();
if !status.is_success() {
return Err(GarrisonError::OAuth2(format!(
"token endpoint returned {} for {}",
status.as_u16(),
self.token_url
)));
}
let token_bytes = read_limited_bytes(resp)
.await
.map_err(|e| GarrisonError::OAuth2(format!("oauth2-token-body-read::{}", e)))?;
let token: TokenResponse = serde_json::from_slice(&token_bytes)
.map_err(|e| GarrisonError::OAuth2(format!("oauth2-token-body-parse::{}", e)))?;
Ok(token)
}
pub async fn introspect_token(
&self,
token: &str,
) -> GarrisonResult<TokenIntrospectionResponse> {
let url = self.introspect_url();
Self::validate_endpoint_url(&url, "introspect_url")?;
let params = [
("token", token),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
];
let resp = self
.http
.post(&url)
.form(¶ms)
.send()
.await
.map_err(|e| GarrisonError::Network(format!("oauth2-introspect-endpoint::{}", e)))?;
let status = resp.status();
if !status.is_success() {
return Err(GarrisonError::OAuth2(format!(
"introspect endpoint returned {} for {}",
status.as_u16(),
url
)));
}
let introspect_bytes = read_limited_bytes(resp)
.await
.map_err(|e| GarrisonError::OAuth2(format!("oauth2-introspect-body-read::{}", e)))?;
let response: TokenIntrospectionResponse = serde_json::from_slice(&introspect_bytes)
.map_err(|e| GarrisonError::OAuth2(format!("oauth2-introspect-body-parse::{}", e)))?;
Ok(response)
}
fn introspect_url(&self) -> String {
if let Some(url) = &self.introspect_url {
url.clone()
} else if let Some(base) = self.token_url.strip_suffix("/token") {
format!("{base}/introspect")
} else {
format!("{}/introspect", self.token_url)
}
}
}
#[cfg(feature = "protocol-zeroize")]
impl Drop for OAuth2Client {
fn drop(&mut self) {
use zeroize::Zeroize;
self.client_secret.zeroize();
}
}
#[cfg(test)]
mod tests {
use super::{url_encode, *};
#[test]
fn url_encode_preserves_safe_chars() {
assert_eq!(url_encode("abc-_.~"), "abc-_.~");
}
#[test]
fn url_encode_encodes_special_chars() {
assert_eq!(url_encode("a b/c:d"), "a%20b%2Fc%3Ad");
}
#[test]
fn urlencode_set_preserves_unreserved_chars() {
for ch in ['-', '_', '.', '~'] {
let s = ch.to_string();
assert_eq!(url_encode(&s), s, "字符 {} 应被保留", ch);
}
}
#[tokio::test]
async fn exchange_code_rejects_missing_state_before_http() {
let client = OAuth2Client::new(
"cid",
"secret",
"https://localhost/callback",
"https://auth.example.com/authorize",
"https://auth.example.com/token",
)
.expect("client 构建成功");
let verifier = "a".repeat(43);
let err = client
.exchange_code_with_pkce("code-x", "", "", &verifier)
.await
.unwrap_err();
match err {
GarrisonError::OAuth2(msg) => {
assert!(msg.contains("oauth2-state-missing"), "实际: {}", msg)
},
other => panic!("期望 OAuth2(state-missing),实际: {:?}", other),
}
for (expected, actual) in [("", "s"), ("s", "")] {
let err = client
.exchange_code_with_pkce("code-x", expected, actual, &verifier)
.await
.unwrap_err();
match err {
GarrisonError::OAuth2(msg) => {
assert!(msg.contains("oauth2-state-missing"), "实际: {}", msg)
},
other => panic!("期望 OAuth2(state-missing),实际: {:?}", other),
}
}
}
#[test]
fn introspect_url_replaces_only_trailing_token_segment() {
let client = OAuth2Client::new(
"cid",
"secret",
"https://localhost/callback",
"https://auth.example.com/authorize",
"https://auth.example.com/token/rotate/token",
)
.expect("client 构建成功");
assert_eq!(
client.introspect_url(),
"https://auth.example.com/token/rotate/introspect",
);
}
#[test]
fn introspect_url_replaces_trailing_token() {
let client = OAuth2Client::new(
"cid",
"secret",
"https://localhost/callback",
"https://auth.example.com/authorize",
"https://auth.example.com/token",
)
.expect("client 构建成功");
assert_eq!(
client.introspect_url(),
"https://auth.example.com/introspect"
);
}
#[test]
fn introspect_url_appends_when_not_ending_with_token() {
let client = OAuth2Client::new(
"cid",
"secret",
"https://localhost/callback",
"https://auth.example.com/authorize",
"https://auth.example.com/oauth2/v2/tokenize",
)
.expect("client 构建成功");
assert_eq!(
client.introspect_url(),
"https://auth.example.com/oauth2/v2/tokenize/introspect",
);
}
#[test]
fn introspect_url_explicit_overrides_derived() {
let client = OAuth2Client::new(
"cid",
"secret",
"https://localhost/callback",
"https://auth.example.com/authorize",
"https://auth.example.com/token",
)
.expect("client 构建成功")
.with_introspect_url("https://introspect.example.com/check");
assert_eq!(
client.introspect_url(),
"https://introspect.example.com/check"
);
}
#[test]
fn e1_build_safe_http_client_returns_valid_client() {
let client = build_safe_http_client();
assert!(client.is_ok(), "build_safe_http_client 必须返回 Ok");
}
#[test]
fn e1_timeout_constants_match_spec() {
assert_eq!(HTTP_CONNECT_TIMEOUT, Duration::from_secs(10));
assert_eq!(HTTP_READ_TIMEOUT, Duration::from_secs(30));
}
#[tokio::test]
#[ignore = "慢测试(~30s),按需运行:cargo test e1_read_timeout_triggers -- --ignored"]
async fn e1_read_timeout_triggers_on_slow_server() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
let delay = std::time::Duration::from_secs(35);
Mock::given(method("POST"))
.and(path("/token"))
.respond_with(ResponseTemplate::new(200).set_delay(delay))
.mount(&server)
.await;
let client = build_safe_http_client().expect("client 构建成功");
let start = std::time::Instant::now();
let result = client
.post(format!("{}/token", server.uri()))
.form(&[("grant_type", "test")])
.send()
.await;
let elapsed = start.elapsed();
assert!(result.is_err(), "慢服务器必须触发超时错误");
assert!(
elapsed >= Duration::from_secs(28) && elapsed <= Duration::from_secs(33),
"超时应约 30s 触发,实际 {:?}",
elapsed
);
}
#[test]
fn e2_max_body_bytes_is_4_mib() {
assert_eq!(MAX_BODY_BYTES, 4 * 1024 * 1024);
}
#[tokio::test]
async fn e2_read_limited_bytes_rejects_oversized_response() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
let oversized_body = "x".repeat(5 * 1024 * 1024);
Mock::given(method("GET"))
.and(path("/oversized"))
.respond_with(ResponseTemplate::new(200).set_body_string(oversized_body))
.mount(&server)
.await;
let client = build_safe_http_client().expect("client 构建成功");
let resp = client
.get(format!("{}/oversized", server.uri()))
.send()
.await
.expect("请求必须成功(错误在读取阶段)");
let result = read_limited_bytes(resp).await;
assert!(result.is_err(), "5 MiB 响应必须被拒绝");
let err_msg = result.unwrap_err().to_string();
assert!(
err_msg.contains(&crate::i18n::translate_detail("oauth2-body-overflow", &[],)),
"错误消息应含'oauth2-body-overflow',实际: {}",
err_msg
);
}
#[tokio::test]
async fn e2_read_limited_bytes_accepts_exact_limit() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
let exact_body = "x".repeat(MAX_BODY_BYTES);
Mock::given(method("GET"))
.and(path("/exact"))
.respond_with(ResponseTemplate::new(200).set_body_string(exact_body))
.mount(&server)
.await;
let client = build_safe_http_client().expect("client 构建成功");
let resp = client
.get(format!("{}/exact", server.uri()))
.send()
.await
.expect("请求必须成功");
let result = read_limited_bytes(resp).await;
assert!(result.is_ok(), "恰好 {} 字节应被接受", MAX_BODY_BYTES);
assert_eq!(result.unwrap().len(), MAX_BODY_BYTES);
}
#[tokio::test]
async fn e2_read_limited_bytes_accepts_small_response() {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/small"))
.respond_with(ResponseTemplate::new(200).set_body_string("hello world"))
.mount(&server)
.await;
let client = build_safe_http_client().expect("client 构建成功");
let resp = client
.get(format!("{}/small", server.uri()))
.send()
.await
.expect("请求必须成功");
let bytes = read_limited_bytes(resp).await.expect("小响应必须通过");
assert_eq!(bytes, b"hello world");
}
#[tokio::test]
async fn e2_oauth2_client_rejects_oversized_token_response() {
use wiremock::matchers::{body_string_contains, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
let server = MockServer::start().await;
let huge_value = "x".repeat(5 * 1024 * 1024);
let huge_json = format!(r#"{{"access_token":"{}"}}"#, huge_value);
Mock::given(method("POST"))
.and(path("/token"))
.and(body_string_contains("grant_type=authorization_code"))
.respond_with(ResponseTemplate::new(200).set_body_string(huge_json))
.mount(&server)
.await;
let client = OAuth2Client::new(
"cid",
"secret",
"https://localhost/callback",
"https://auth.example.com/auth",
format!("{}/token", server.uri()),
)
.expect("client 构建成功");
let verifier = "a".repeat(43);
let result = client
.exchange_code_with_pkce("code123", "state", "state", &verifier)
.await;
assert!(result.is_err(), "超大 token 响应必须被拒绝");
}
#[test]
fn new_rejects_plaintext_http_token_endpoint() {
let result = OAuth2Client::new(
"cid",
"secret",
"https://app.example.com/callback",
"https://auth.example.com/authorize",
"http://auth.example.com/token",
);
match result {
Err(GarrisonError::InvalidParam(msg)) => {
assert!(
msg.contains("token_url"),
"错误应指明 token_url,实际: {}",
msg
);
},
Err(other) => panic!("期望 InvalidParam,实际: {:?}", other),
Ok(_) => panic!("公网明文 http token 端点应被构造期拒绝"),
}
}
#[test]
fn new_rejects_plaintext_http_auth_endpoint() {
let result = OAuth2Client::new(
"cid",
"secret",
"https://app.example.com/callback",
"http://auth.example.com/authorize",
"https://auth.example.com/token",
);
match result {
Err(GarrisonError::InvalidParam(msg)) => {
assert!(
msg.contains("auth_url"),
"错误应指明 auth_url,实际: {}",
msg
);
},
Err(other) => panic!("期望 InvalidParam,实际: {:?}", other),
Ok(_) => panic!("公网明文 http auth 端点应被构造期拒绝"),
}
}
#[test]
fn new_allows_localhost_http_endpoints() {
let result = OAuth2Client::new(
"cid",
"secret",
"http://localhost:8080/cb",
"http://localhost:9000/authorize",
"http://127.0.0.1:9000/token",
);
assert!(
result.is_ok(),
"localhost http 端点应放行,实际: {:?}",
result.err()
);
}
#[tokio::test]
async fn introspect_token_rejects_plaintext_introspect_url() {
let client = OAuth2Client::new(
"cid",
"secret",
"https://app.example.com/callback",
"https://auth.example.com/authorize",
"https://auth.example.com/token",
)
.expect("client 构建成功")
.with_introspect_url("http://evil.example.com/introspect");
let result = client.introspect_token("token-value").await;
match result {
Err(GarrisonError::InvalidParam(msg)) => {
assert!(
msg.contains("introspect_url"),
"错误应指明 introspect_url,实际: {}",
msg
);
},
Err(other) => panic!("期望 InvalidParam,实际: {:?}", other),
Ok(_) => panic!("明文 introspection 端点应在请求前被拒绝"),
}
}
#[test]
fn validate_redirect_uri_no_scheme() {
let result = OAuth2Client::new(
"cid",
"secret",
"no-scheme-here",
"https://auth.example.com/authorize",
"https://auth.example.com/token",
);
assert!(result.is_err(), "无 scheme 应报错");
}
#[test]
fn validate_redirect_uri_http_public_host() {
let result = OAuth2Client::new(
"cid",
"secret",
"http://evil.com/callback",
"https://auth.example.com/authorize",
"https://auth.example.com/token",
);
assert!(result.is_err(), "http + 公网域名应报错");
}
#[test]
fn validate_redirect_uri_http_localhost_ok() {
let result = OAuth2Client::new(
"cid",
"secret",
"http://localhost:3000/callback",
"https://auth.example.com/authorize",
"https://auth.example.com/token",
);
assert!(
result.is_ok(),
"http://localhost 应放行,实际: {:?}",
result.err()
);
}
#[test]
fn validate_redirect_uri_http_127_ok() {
let result = OAuth2Client::new(
"cid",
"secret",
"http://127.0.0.1:8080/cb",
"https://auth.example.com/authorize",
"https://auth.example.com/token",
);
assert!(
result.is_ok(),
"http://127.0.0.1 应放行,实际: {:?}",
result.err()
);
}
#[test]
fn pkce_challenge_too_short() {
let short = "a".repeat(42);
let result = OAuth2Client::generate_pkce_challenge(&short);
assert!(result.is_err(), "长度 < 43 应报错");
}
#[test]
fn pkce_challenge_too_long() {
let long = "a".repeat(129);
let result = OAuth2Client::generate_pkce_challenge(&long);
assert!(result.is_err(), "长度 > 128 应报错");
}
#[test]
fn pkce_challenge_invalid字符() {
let invalid = "a b".to_string() + &"c".repeat(40);
let result = OAuth2Client::generate_pkce_challenge(&invalid);
assert!(result.is_err(), "含非法字符应报错");
}
#[test]
fn pkce_challenge_valid_input() {
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let challenge = OAuth2Client::generate_pkce_challenge(verifier).unwrap();
assert_eq!(challenge, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
}
#[test]
fn new_empty_client_id_returns_config_error() {
let result = OAuth2Client::new(
"",
"secret",
"https://localhost/cb",
"https://auth.example.com/authorize",
"https://auth.example.com/token",
);
assert!(result.is_err(), "空 client_id 应报错");
}
}