auth_framework/server/core/
client_registry.rs1use crate::errors::{AuthError, Result};
7use crate::storage::core::AuthStorage;
8use crate::storage::memory::InMemoryStorage;
9use std::sync::Arc;
10
11pub use crate::client::{ClientConfig, ClientType};
14
15#[derive(Clone)]
17pub struct ClientRegistry {
18 storage: Arc<dyn AuthStorage>,
19}
20
21impl ClientRegistry {
22 pub async fn new(storage: Arc<dyn AuthStorage>) -> Result<Self> {
24 Ok(Self { storage })
25 }
26
27 pub async fn register_client(&self, config: ClientConfig) -> Result<ClientConfig> {
29 self.validate_client_config(&config)?;
31
32 let client_key = format!("oauth_client:{}", config.client_id);
34 let client_data = serde_json::to_string(&config)
35 .map_err(|e| AuthError::internal(format!("Failed to serialize client: {}", e)))?;
36
37 self.storage
38 .store_kv(&client_key, client_data.as_bytes(), None)
39 .await?;
40
41 Ok(config)
42 }
43
44 pub async fn get_client(&self, client_id: &str) -> Result<Option<ClientConfig>> {
46 let client_key = format!("oauth_client:{}", client_id);
47
48 if let Some(client_data) = self.storage.get_kv(&client_key).await? {
49 let client_str = std::str::from_utf8(&client_data)
50 .map_err(|e| AuthError::internal(format!("Invalid UTF-8 in client data: {}", e)))?;
51 let config: ClientConfig = serde_json::from_str(client_str)
52 .map_err(|e| AuthError::internal(format!("Failed to deserialize client: {}", e)))?;
53 Ok(Some(config))
54 } else {
55 Ok(None)
56 }
57 }
58
59 pub async fn update_client(&self, client_id: &str, config: ClientConfig) -> Result<()> {
61 if config.client_id != client_id {
63 return Err(AuthError::validation("Client ID mismatch"));
64 }
65
66 self.validate_client_config(&config)?;
68
69 let client_key = format!("oauth_client:{}", client_id);
71 let client_data = serde_json::to_string(&config)
72 .map_err(|e| AuthError::internal(format!("Failed to serialize client: {}", e)))?;
73
74 self.storage
75 .store_kv(&client_key, client_data.as_bytes(), None)
76 .await?;
77
78 Ok(())
79 }
80
81 pub async fn delete_client(&self, client_id: &str) -> Result<()> {
83 let client_key = format!("oauth_client:{}", client_id);
84 self.storage.delete_kv(&client_key).await?;
85 Ok(())
86 }
87
88 pub async fn validate_redirect_uri(&self, client_id: &str, redirect_uri: &str) -> Result<bool> {
90 if let Some(client) = self.get_client(client_id).await? {
91 Ok(client.redirect_uris.contains(redirect_uri))
92 } else {
93 Ok(false)
94 }
95 }
96
97 pub async fn validate_scope(&self, client_id: &str, scope: &str) -> Result<bool> {
99 if let Some(client) = self.get_client(client_id).await? {
100 Ok(client.authorized_scopes.contains(scope))
101 } else {
102 Ok(false)
103 }
104 }
105
106 pub async fn validate_grant_type(&self, client_id: &str, grant_type: &str) -> Result<bool> {
108 if let Some(client) = self.get_client(client_id).await? {
109 Ok(client.authorized_grant_types.contains(grant_type))
110 } else {
111 Ok(false)
112 }
113 }
114
115 pub async fn authenticate_client(&self, client_id: &str, client_secret: &str) -> Result<bool> {
117 if let Some(client) = self.get_client(client_id).await? {
118 match (&client.client_type, &client.client_secret) {
119 (ClientType::Confidential, Some(stored_secret)) => {
120 Ok(crate::security::secure_utils::constant_time_compare(
122 client_secret.as_bytes(),
123 stored_secret.as_bytes(),
124 ))
125 }
126 (ClientType::Public, None) => {
127 Ok(true)
129 }
130 _ => Ok(false),
131 }
132 } else {
133 Ok(false)
134 }
135 }
136
137 fn validate_client_config(&self, config: &ClientConfig) -> Result<()> {
139 if config.client_id.is_empty() {
141 return Err(AuthError::validation("Client ID cannot be empty"));
142 }
143
144 if config.client_type == ClientType::Confidential && config.client_secret.is_none() {
146 return Err(AuthError::validation(
147 "Confidential clients must have a client secret",
148 ));
149 }
150
151 if config.client_type == ClientType::Public && config.client_secret.is_some() {
153 return Err(AuthError::validation(
154 "Public clients must not have a client secret",
155 ));
156 }
157
158 if config.redirect_uris.is_empty() {
160 return Err(AuthError::validation(
161 "At least one redirect URI must be provided",
162 ));
163 }
164
165 for uri in &config.redirect_uris {
167 if uri.is_empty() {
168 return Err(AuthError::validation("Redirect URI cannot be empty"));
169 }
170
171 if !uri.starts_with("https://") && !uri.starts_with("http://localhost") {
173 return Err(AuthError::validation(
174 "Redirect URIs must use HTTPS (except localhost)",
175 ));
176 }
177 }
178
179 if config.authorized_scopes.is_empty() {
181 return Err(AuthError::validation(
182 "At least one authorized scope must be provided",
183 ));
184 }
185
186 if config.authorized_grant_types.is_empty() {
188 return Err(AuthError::validation(
189 "At least one authorized grant type must be provided",
190 ));
191 }
192
193 if config.authorized_response_types.is_empty() {
195 return Err(AuthError::validation(
196 "At least one authorized response type must be provided",
197 ));
198 }
199
200 Ok(())
201 }
202}
203
204impl Default for ClientRegistry {
205 fn default() -> Self {
206 let storage =
208 if std::env::var("CLIENT_REGISTRY_STORAGE").unwrap_or_default() == "persistent" {
209 Arc::new(InMemoryStorage::new())
211 } else {
212 Arc::new(InMemoryStorage::new())
214 };
215
216 Self { storage }
217 }
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223 use crate::storage::memory::InMemoryStorage;
224
225 #[tokio::test]
226 async fn test_client_registry_operations() {
227 let storage = Arc::new(InMemoryStorage::new());
228 let registry = ClientRegistry::new(storage).await.unwrap();
229
230 let client_config = ClientConfig {
232 client_id: "test_client".to_string(),
233 client_type: ClientType::Confidential,
234 client_secret: Some("test_secret".to_string()),
235 redirect_uris: vec!["https://example.com/callback".to_string()].into(),
236 ..Default::default()
237 };
238
239 let registered_client = registry
241 .register_client(client_config.clone())
242 .await
243 .unwrap();
244 assert_eq!(registered_client.client_id, "test_client");
245
246 let retrieved_client = registry.get_client("test_client").await.unwrap().unwrap();
248 assert_eq!(retrieved_client.client_id, "test_client");
249 assert_eq!(retrieved_client.client_type, ClientType::Confidential);
250
251 let auth_result = registry
253 .authenticate_client("test_client", "test_secret")
254 .await
255 .unwrap();
256 assert!(auth_result);
257
258 let auth_fail = registry
259 .authenticate_client("test_client", "wrong_secret")
260 .await
261 .unwrap();
262 assert!(!auth_fail);
263
264 let valid_uri = registry
266 .validate_redirect_uri("test_client", "https://example.com/callback")
267 .await
268 .unwrap();
269 assert!(valid_uri);
270
271 let invalid_uri = registry
272 .validate_redirect_uri("test_client", "https://malicious.com/callback")
273 .await
274 .unwrap();
275 assert!(!invalid_uri);
276
277 registry.delete_client("test_client").await.unwrap();
279 let deleted_client = registry.get_client("test_client").await.unwrap();
280 assert!(deleted_client.is_none());
281 }
282
283 #[tokio::test]
284 async fn test_client_validation() {
285 let storage = Arc::new(InMemoryStorage::new());
286 let registry = ClientRegistry::new(storage).await.unwrap();
287
288 let invalid_config = ClientConfig {
290 client_id: "".to_string(),
291 ..Default::default()
292 };
293 assert!(registry.register_client(invalid_config).await.is_err());
294
295 let invalid_config = ClientConfig {
297 client_type: ClientType::Confidential,
298 client_secret: None,
299 ..Default::default()
300 };
301 assert!(registry.register_client(invalid_config).await.is_err());
302
303 let invalid_config = ClientConfig {
305 client_type: ClientType::Public,
306 client_secret: Some("secret".to_string()),
307 ..Default::default()
308 };
309 assert!(registry.register_client(invalid_config).await.is_err());
310
311 let invalid_config = ClientConfig {
313 redirect_uris: vec![].into(),
314 ..Default::default()
315 };
316 assert!(registry.register_client(invalid_config).await.is_err());
317
318 let invalid_config = ClientConfig {
320 redirect_uris: vec!["http://example.com/callback".to_string()].into(),
321 ..Default::default()
322 };
323 assert!(registry.register_client(invalid_config).await.is_err());
324 }
325}