use crate::constants::DaoKeyPrefix;
use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use argon2::{
password_hash::{phc::PasswordHash, PasswordHasher, PasswordVerifier},
Algorithm, Argon2, Version,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GrantType {
AuthorizationCode,
RefreshToken,
ClientCredentials,
Password,
}
impl GrantType {
pub fn as_str(&self) -> &'static str {
match self {
Self::AuthorizationCode => "authorization_code",
Self::RefreshToken => "refresh_token",
Self::ClientCredentials => "client_credentials",
Self::Password => "password",
}
}
}
impl std::str::FromStr for GrantType {
type Err = GarrisonError;
fn from_str(s: &str) -> GarrisonResult<Self> {
match s {
"authorization_code" => Ok(Self::AuthorizationCode),
"refresh_token" => Ok(Self::RefreshToken),
"client_credentials" => Ok(Self::ClientCredentials),
"password" => Ok(Self::Password),
other => Err(GarrisonError::OAuth2(format!(
"unsupported_grant_type: {other}"
))),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuth2Client {
pub client_id: String,
pub client_secret_hash: String,
pub redirect_uris: Vec<String>,
pub grant_types: Vec<GrantType>,
pub scopes: Vec<String>,
pub pkce_required: bool,
}
impl OAuth2Client {
pub fn new(
client_id: &str,
client_secret: &str,
redirect_uris: Vec<String>,
grant_types: Vec<GrantType>,
scopes: Vec<String>,
) -> GarrisonResult<Self> {
if client_id.is_empty() {
return Err(GarrisonError::InvalidParam("oauth2-client-id-empty".into()));
}
if client_secret.is_empty() {
return Err(GarrisonError::InvalidParam(
"oauth2-client-secret-empty".into(),
));
}
const REDIRECT_URI_MAX_LEN: usize = 2048;
for uri in &redirect_uris {
if uri.is_empty()
|| uri.len() > REDIRECT_URI_MAX_LEN
|| !uri.contains(':')
|| uri.chars().any(|c| c.is_whitespace() || c.is_control())
{
return Err(GarrisonError::InvalidParam(
"oauth2-client-redirect-uri-invalid".to_string(),
));
}
}
let client_secret_hash = hash_secret(client_secret)?;
Ok(Self {
client_id: client_id.to_string(),
client_secret_hash,
redirect_uris,
grant_types,
scopes,
pkce_required: true,
})
}
pub fn verify_secret(&self, client_secret: &str) -> GarrisonResult<bool> {
verify_secret(client_secret, &self.client_secret_hash)
}
pub fn is_redirect_uri_allowed(&self, redirect_uri: &str) -> bool {
self.redirect_uris.iter().any(|uri| uri == redirect_uri)
}
pub fn allows_grant_type(&self, grant_type: &GrantType) -> bool {
self.grant_types.iter().any(|gt| gt == grant_type)
}
pub fn allows_scope(&self, scope: &str) -> bool {
self.scopes.iter().any(|s| s == "*" || s == scope)
}
pub fn validate_scopes(&self, scopes: &[String]) -> GarrisonResult<()> {
if scopes.is_empty() {
return Ok(());
}
if self.scopes.iter().any(|s| s == "*") {
return Ok(());
}
for s in scopes {
if !self.allows_scope(s) {
return Err(GarrisonError::OAuth2(format!(
"oauth2-server-client-invalid-scope::{}",
s
)));
}
}
Ok(())
}
}
#[async_trait]
pub trait OAuth2ClientStore: Send + Sync {
async fn create(&self, client: OAuth2Client) -> GarrisonResult<()>;
async fn get(&self, client_id: &str) -> GarrisonResult<Option<OAuth2Client>>;
async fn update(&self, client: OAuth2Client) -> GarrisonResult<()>;
async fn delete(&self, client_id: &str) -> GarrisonResult<()>;
async fn list(&self) -> GarrisonResult<Vec<OAuth2Client>>;
}
pub struct DaoOAuth2ClientStore {
dao: Arc<dyn GarrisonDao>,
}
impl DaoOAuth2ClientStore {
pub fn new(dao: Arc<dyn GarrisonDao>) -> Self {
Self { dao }
}
fn build_key(client_id: &str) -> String {
DaoKeyPrefix::OAuth2Client.build_key(client_id)
}
}
#[async_trait]
impl OAuth2ClientStore for DaoOAuth2ClientStore {
async fn create(&self, client: OAuth2Client) -> GarrisonResult<()> {
let key = Self::build_key(&client.client_id);
let json = serde_json::to_string(&client).map_err(|e| {
GarrisonError::Internal(format!("oauth2-server-client-serialize::{}", e))
})?;
if !self.dao.set_if_absent(&key, &json, 0).await? {
return Err(GarrisonError::OAuth2(format!(
"oauth2-server-client-exists::{}",
client.client_id
)));
}
Ok(())
}
async fn get(&self, client_id: &str) -> GarrisonResult<Option<OAuth2Client>> {
let key = Self::build_key(client_id);
match self.dao.get(&key).await? {
Some(json) => {
let client: OAuth2Client = serde_json::from_str(&json).map_err(|e| {
GarrisonError::Internal(format!("oauth2-server-client-deserialize::{}", e))
})?;
Ok(Some(client))
},
None => Ok(None),
}
}
async fn update(&self, client: OAuth2Client) -> GarrisonResult<()> {
let key = Self::build_key(&client.client_id);
let current = self.dao.get(&key).await?.ok_or_else(|| {
GarrisonError::OAuth2(format!(
"oauth2-server-client-not-found::{}",
client.client_id
))
})?;
let json = serde_json::to_string(&client).map_err(|e| {
GarrisonError::Internal(format!("oauth2-server-client-serialize::{}", e))
})?;
if !self
.dao
.compare_and_swap(&key, Some(current.as_str()), &json, 0)
.await?
{
return Err(GarrisonError::OAuth2(format!(
"oauth2-server-client-update-conflict::{}",
client.client_id
)));
}
Ok(())
}
async fn delete(&self, client_id: &str) -> GarrisonResult<()> {
let key = Self::build_key(client_id);
self.dao.delete(&key).await
}
async fn list(&self) -> GarrisonResult<Vec<OAuth2Client>> {
let pattern = format!("{}*", DaoKeyPrefix::OAuth2Client.as_str());
let keys = self.dao.keys(&pattern).await?;
let mut clients = Vec::with_capacity(keys.len());
for key in keys {
match self.dao.get(&key).await? {
Some(json) => {
let client: OAuth2Client = serde_json::from_str(&json).map_err(|e| {
GarrisonError::Internal(format!("oauth2-server-client-deserialize::{}", e))
})?;
clients.push(client);
},
None => continue,
}
}
clients.sort_by(|a, b| a.client_id.cmp(&b.client_id));
Ok(clients)
}
}
fn argon2_instance() -> Argon2<'static> {
Argon2::new(
Algorithm::Argon2id,
Version::V0x13,
argon2::Params::default(),
)
}
fn hash_secret(secret: &str) -> GarrisonResult<String> {
let hash = argon2_instance()
.hash_password(secret.as_bytes())
.map_err(|e| GarrisonError::Internal(format!("oauth2-server-client-hash::{}", e)))?;
Ok(hash.to_string())
}
fn verify_secret(secret: &str, hash_str: &str) -> GarrisonResult<bool> {
let parsed = PasswordHash::new(hash_str).map_err(|e| {
GarrisonError::InvalidParam(format!("oauth2-server-client-hash-format::{}", e))
})?;
Ok(argon2_instance()
.verify_password(secret.as_bytes(), &parsed)
.is_ok())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn grant_type_as_str() {
assert_eq!(GrantType::AuthorizationCode.as_str(), "authorization_code");
assert_eq!(GrantType::RefreshToken.as_str(), "refresh_token");
assert_eq!(GrantType::ClientCredentials.as_str(), "client_credentials");
assert_eq!(GrantType::Password.as_str(), "password");
}
#[test]
fn grant_type_serde_roundtrip() {
let gt = GrantType::AuthorizationCode;
let json = serde_json::to_string(>).unwrap();
assert_eq!(json, "\"authorization_code\"");
let de: GrantType = serde_json::from_str(&json).unwrap();
assert_eq!(de, gt);
}
#[test]
fn grant_type_from_str_parses_all_known_types() {
assert_eq!(
"authorization_code".parse::<GrantType>().unwrap(),
GrantType::AuthorizationCode
);
assert_eq!(
"refresh_token".parse::<GrantType>().unwrap(),
GrantType::RefreshToken
);
assert_eq!(
"client_credentials".parse::<GrantType>().unwrap(),
GrantType::ClientCredentials
);
assert_eq!(
"password".parse::<GrantType>().unwrap(),
GrantType::Password
);
}
#[test]
fn grant_type_from_str_rejects_unknown() {
let err = "unknown_grant".parse::<GrantType>().unwrap_err();
assert!(
matches!(err, GarrisonError::OAuth2(_)),
"未知 grant_type 应返回 OAuth2 错误"
);
assert!(
err.to_string().contains("unsupported_grant_type"),
"错误信息应包含 unsupported_grant_type"
);
}
#[test]
fn grant_type_from_str_roundtrips_with_as_str() {
for original in [
GrantType::AuthorizationCode,
GrantType::RefreshToken,
GrantType::ClientCredentials,
GrantType::Password,
] {
let s = original.as_str();
let parsed: GrantType = s.parse().unwrap();
assert_eq!(parsed, original, "as_str -> FromStr 往返失败");
}
}
#[test]
fn new_client_hashes_secret_and_enforces_pkce() {
let client = OAuth2Client::new(
"client-001",
"super-secret",
vec!["https://app.example.com/callback".into()],
vec![GrantType::AuthorizationCode],
vec!["read".into()],
)
.expect("创建客户端");
assert_eq!(client.client_id, "client-001");
assert_ne!(client.client_secret_hash, "super-secret");
assert!(client.client_secret_hash.starts_with("$argon2id$"));
assert!(client.pkce_required, "pkce_required 必须始终为 true");
assert_eq!(client.redirect_uris.len(), 1);
assert_eq!(client.grant_types.len(), 1);
}
#[test]
fn new_client_rejects_empty_id() {
let err = OAuth2Client::new("", "secret", vec![], vec![], vec![]).unwrap_err();
assert!(matches!(err, GarrisonError::InvalidParam(_)));
}
#[test]
fn new_client_rejects_empty_secret() {
let err = OAuth2Client::new("cid", "", vec![], vec![], vec![]).unwrap_err();
assert!(matches!(err, GarrisonError::InvalidParam(_)));
}
#[test]
fn new_client_rejects_invalid_redirect_uris() {
let err = OAuth2Client::new("cid", "s", vec!["".into()], vec![], vec![]).unwrap_err();
assert!(matches!(err, GarrisonError::InvalidParam(_)));
let err = OAuth2Client::new(
"cid",
"s",
vec!["app.example.com/cb".into()],
vec![],
vec![],
)
.unwrap_err();
assert!(matches!(err, GarrisonError::InvalidParam(_)));
let err = OAuth2Client::new(
"cid",
"s",
vec!["https://app.example.com/ cb".into()],
vec![],
vec![],
)
.unwrap_err();
assert!(matches!(err, GarrisonError::InvalidParam(_)));
let long_uri = format!("https://app.example.com/{}", "a".repeat(2048));
let err = OAuth2Client::new("cid", "s", vec![long_uri], vec![], vec![]).unwrap_err();
assert!(matches!(err, GarrisonError::InvalidParam(_)));
assert!(
OAuth2Client::new("cid", "s", vec!["myapp://callback".into()], vec![], vec![]).is_ok()
);
}
#[test]
fn verify_secret_matches_correct() {
let client = OAuth2Client::new("client-001", "super-secret", vec![], vec![], vec![])
.expect("创建客户端");
assert!(client.verify_secret("super-secret").expect("验证"));
}
#[test]
fn verify_secret_rejects_wrong() {
let client = OAuth2Client::new("client-001", "super-secret", vec![], vec![], vec![])
.expect("创建客户端");
assert!(!client.verify_secret("wrong-secret").expect("验证"));
}
#[test]
fn verify_secret_rejects_invalid_hash() {
let err = verify_secret("secret", "not-a-valid-hash").unwrap_err();
assert!(matches!(err, GarrisonError::InvalidParam(_)));
}
#[test]
fn is_redirect_uri_allowed_exact_match() {
let client = OAuth2Client::new(
"c1",
"s",
vec![
"https://app1.example.com/callback".into(),
"https://app2.example.com/callback".into(),
],
vec![],
vec![],
)
.unwrap();
assert!(client.is_redirect_uri_allowed("https://app1.example.com/callback"));
assert!(client.is_redirect_uri_allowed("https://app2.example.com/callback"));
}
#[test]
fn is_redirect_uri_allowed_rejects_not_in_whitelist() {
let client = OAuth2Client::new(
"c1",
"s",
vec!["https://app.example.com/callback".into()],
vec![],
vec![],
)
.unwrap();
assert!(!client.is_redirect_uri_allowed("https://evil.example.com/callback"));
}
#[test]
fn is_redirect_uri_allowed_rejects_partial_match() {
let client = OAuth2Client::new(
"c1",
"s",
vec!["https://app.example.com/callback".into()],
vec![],
vec![],
)
.unwrap();
assert!(!client.is_redirect_uri_allowed("https://app.example.com/callback/extra"));
assert!(!client.is_redirect_uri_allowed("http://app.example.com/callback"));
}
#[test]
fn allows_grant_type() {
let client = OAuth2Client::new(
"c1",
"s",
vec![],
vec![GrantType::AuthorizationCode, GrantType::RefreshToken],
vec![],
)
.unwrap();
assert!(client.allows_grant_type(&GrantType::AuthorizationCode));
assert!(client.allows_grant_type(&GrantType::RefreshToken));
assert!(!client.allows_grant_type(&GrantType::ClientCredentials));
}
#[test]
fn allows_scope_empty_means_none_fail_closed() {
let client = OAuth2Client::new("c1", "s", vec![], vec![], vec![]).unwrap();
assert!(
!client.allows_scope("anything"),
"空 allowed_scopes 必须拒绝一切 scope(fail-closed)"
);
}
#[test]
fn validate_scopes_empty_request_ok_in_all_client_states() {
for scopes in [Vec::new(), vec!["*".to_string()], vec!["read".to_string()]] {
let client = OAuth2Client::new("c1", "s", vec![], vec![], scopes).unwrap();
let empty: Vec<String> = Vec::new();
assert!(
client.validate_scopes(&empty).is_ok(),
"空 scope 请求应对任意 client 配置放行"
);
}
}
#[test]
fn allows_scope_wildcard_means_any() {
let client = OAuth2Client::new("c1", "s", vec![], vec![], vec!["*".into()]).unwrap();
assert!(
client.allows_scope("anything"),
"\"*\" 通配应允许任意 scope"
);
}
#[test]
fn allows_scope_explicit_list() {
let client = OAuth2Client::new(
"c1",
"s",
vec![],
vec![],
vec!["read".into(), "write".into()],
)
.unwrap();
assert!(client.allows_scope("read"));
assert!(client.allows_scope("write"));
assert!(!client.allows_scope("admin"));
}
use crate::dao::InMemoryDao;
fn make_test_client(id: &str) -> OAuth2Client {
OAuth2Client::new(
id,
"secret-123",
vec!["https://app.example.com/cb".into()],
vec![GrantType::AuthorizationCode, GrantType::RefreshToken],
vec!["read".into(), "write".into()],
)
.unwrap()
}
#[tokio::test]
async fn store_create_and_get() {
let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
let client = make_test_client("store-001");
store.create(client.clone()).await.expect("创建");
let got = store.get("store-001").await.expect("查询").expect("应存在");
assert_eq!(got.client_id, "store-001");
assert_eq!(got.redirect_uris, client.redirect_uris);
assert_eq!(got.grant_types, client.grant_types);
assert!(got.pkce_required);
}
#[tokio::test]
async fn store_create_duplicate_fails() {
let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
let client = make_test_client("dup-001");
store.create(client.clone()).await.expect("首次创建");
let err = store.create(client).await.unwrap_err();
assert!(matches!(err, GarrisonError::OAuth2(_)));
}
#[tokio::test(flavor = "multi_thread")]
async fn store_create_concurrent_only_one_wins() {
let store = Arc::new(DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new())));
let mut handles = Vec::new();
for _ in 0..16 {
let s = store.clone();
let client = make_test_client("conc-001");
handles.push(tokio::spawn(async move { s.create(client).await }));
}
let mut wins = 0usize;
for h in handles {
if h.await.unwrap().is_ok() {
wins += 1;
}
}
assert_eq!(
wins, 1,
"并发创建同一 client_id 仅一个应成功,实际 {}",
wins
);
assert_eq!(store.list().await.unwrap().len(), 1);
}
#[tokio::test]
async fn store_get_nonexistent_returns_none() {
let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
let got = store.get("no-such").await.expect("查询");
assert!(got.is_none());
}
#[tokio::test]
async fn store_update_existing() {
let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
let mut client = make_test_client("upd-001");
store.create(client.clone()).await.expect("创建");
client.scopes = vec!["admin".into()];
store.update(client).await.expect("更新");
let got = store.get("upd-001").await.unwrap().unwrap();
assert_eq!(got.scopes, vec!["admin"]);
}
#[tokio::test]
async fn store_update_nonexistent_fails() {
let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
let client = make_test_client("no-exist");
let err = store.update(client).await.unwrap_err();
assert!(matches!(err, GarrisonError::OAuth2(_)));
}
#[tokio::test]
async fn store_delete() {
let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
store
.create(make_test_client("del-001"))
.await
.expect("创建");
store.delete("del-001").await.expect("删除");
assert!(store.get("del-001").await.unwrap().is_none());
}
#[tokio::test]
async fn store_list_sorted_by_client_id() {
let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
store.create(make_test_client("charlie")).await.unwrap();
store.create(make_test_client("alpha")).await.unwrap();
store.create(make_test_client("bravo")).await.unwrap();
let list = store.list().await.expect("列表");
assert_eq!(list.len(), 3);
assert_eq!(list[0].client_id, "alpha");
assert_eq!(list[1].client_id, "bravo");
assert_eq!(list[2].client_id, "charlie");
}
#[tokio::test]
async fn store_list_empty() {
let store = DaoOAuth2ClientStore::new(Arc::new(InMemoryDao::new()));
let list = store.list().await.expect("列表");
assert!(list.is_empty());
}
#[test]
fn build_key_format() {
let key = DaoOAuth2ClientStore::build_key("my-client");
assert_eq!(key, "oauth2:client:my-client");
}
}