auth_framework/server/core/
client_registry.rs1use crate::errors::{AuthError, Result};
7use crate::storage::core::AuthStorage;
8use crate::storage::memory::InMemoryStorage;
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11use std::sync::Arc;
12use uuid::Uuid;
13
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
16pub enum ClientType {
17 Confidential,
19 Public,
21}
22
23#[derive(Clone, Serialize, Deserialize)]
25pub struct ClientConfig {
26 pub client_id: String,
28 pub client_secret: Option<String>,
30 pub client_type: ClientType,
32 pub redirect_uris: Vec<String>,
34 pub authorized_scopes: Vec<String>,
36 pub authorized_grant_types: Vec<String>,
38 pub authorized_response_types: Vec<String>,
40 pub client_name: Option<String>,
42 pub client_description: Option<String>,
44 pub metadata: HashMap<String, serde_json::Value>,
46}
47
48impl std::fmt::Debug for ClientConfig {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 let mut d = f.debug_struct("ClientConfig");
51 d.field("client_id", &self.client_id);
52 d.field(
53 "client_secret",
54 &crate::utils::redact::redacted(&self.client_secret),
55 );
56 d.field("client_type", &self.client_type);
57 d.field("redirect_uris", &self.redirect_uris);
58 d.field("authorized_scopes", &self.authorized_scopes);
59 d.field("authorized_grant_types", &self.authorized_grant_types);
60 d.field("authorized_response_types", &self.authorized_response_types);
61 d.field("client_name", &self.client_name);
62 d.field("client_description", &self.client_description);
63 d.field("metadata", &self.metadata);
64 d.finish()
65 }
66}
67
68impl Default for ClientConfig {
69 fn default() -> Self {
70 Self {
71 client_id: Uuid::new_v4().to_string(),
72 client_secret: None,
73 client_type: ClientType::Public,
74 redirect_uris: Vec::new(),
75 authorized_scopes: vec!["read".to_string()],
76 authorized_grant_types: vec!["authorization_code".to_string()],
77 authorized_response_types: vec!["code".to_string()],
78 client_name: None,
79 client_description: None,
80 metadata: HashMap::new(),
81 }
82 }
83}
84
85#[derive(Clone)]
87pub struct ClientRegistry {
88 storage: Arc<dyn AuthStorage>,
89}
90
91impl ClientRegistry {
92 pub async fn new(storage: Arc<dyn AuthStorage>) -> Result<Self> {
94 Ok(Self { storage })
95 }
96
97 pub async fn register_client(&self, config: ClientConfig) -> Result<ClientConfig> {
99 self.validate_client_config(&config)?;
101
102 let client_key = format!("oauth_client:{}", config.client_id);
104 let client_data = serde_json::to_string(&config)
105 .map_err(|e| AuthError::internal(format!("Failed to serialize client: {}", e)))?;
106
107 self.storage
108 .store_kv(&client_key, client_data.as_bytes(), None)
109 .await?;
110
111 Ok(config)
112 }
113
114 pub async fn get_client(&self, client_id: &str) -> Result<Option<ClientConfig>> {
116 let client_key = format!("oauth_client:{}", client_id);
117
118 if let Some(client_data) = self.storage.get_kv(&client_key).await? {
119 let client_str = std::str::from_utf8(&client_data)
120 .map_err(|e| AuthError::internal(format!("Invalid UTF-8 in client data: {}", e)))?;
121 let config: ClientConfig = serde_json::from_str(client_str)
122 .map_err(|e| AuthError::internal(format!("Failed to deserialize client: {}", e)))?;
123 Ok(Some(config))
124 } else {
125 Ok(None)
126 }
127 }
128
129 pub async fn update_client(&self, client_id: &str, config: ClientConfig) -> Result<()> {
131 if config.client_id != client_id {
133 return Err(AuthError::validation("Client ID mismatch"));
134 }
135
136 self.validate_client_config(&config)?;
138
139 let client_key = format!("oauth_client:{}", client_id);
141 let client_data = serde_json::to_string(&config)
142 .map_err(|e| AuthError::internal(format!("Failed to serialize client: {}", e)))?;
143
144 self.storage
145 .store_kv(&client_key, client_data.as_bytes(), None)
146 .await?;
147
148 Ok(())
149 }
150
151 pub async fn delete_client(&self, client_id: &str) -> Result<()> {
153 let client_key = format!("oauth_client:{}", client_id);
154 self.storage.delete_kv(&client_key).await?;
155 Ok(())
156 }
157
158 pub async fn validate_redirect_uri(&self, client_id: &str, redirect_uri: &str) -> Result<bool> {
160 if let Some(client) = self.get_client(client_id).await? {
161 Ok(client.redirect_uris.contains(&redirect_uri.to_string()))
162 } else {
163 Ok(false)
164 }
165 }
166
167 pub async fn validate_scope(&self, client_id: &str, scope: &str) -> Result<bool> {
169 if let Some(client) = self.get_client(client_id).await? {
170 Ok(client.authorized_scopes.contains(&scope.to_string()))
171 } else {
172 Ok(false)
173 }
174 }
175
176 pub async fn validate_grant_type(&self, client_id: &str, grant_type: &str) -> Result<bool> {
178 if let Some(client) = self.get_client(client_id).await? {
179 Ok(client
180 .authorized_grant_types
181 .contains(&grant_type.to_string()))
182 } else {
183 Ok(false)
184 }
185 }
186
187 pub async fn authenticate_client(&self, client_id: &str, client_secret: &str) -> Result<bool> {
189 if let Some(client) = self.get_client(client_id).await? {
190 match (&client.client_type, &client.client_secret) {
191 (ClientType::Confidential, Some(stored_secret)) => {
192 Ok(crate::security::secure_utils::constant_time_compare(
194 client_secret.as_bytes(),
195 stored_secret.as_bytes(),
196 ))
197 }
198 (ClientType::Public, None) => {
199 Ok(true)
201 }
202 _ => Ok(false),
203 }
204 } else {
205 Ok(false)
206 }
207 }
208
209 fn validate_client_config(&self, config: &ClientConfig) -> Result<()> {
211 if config.client_id.is_empty() {
213 return Err(AuthError::validation("Client ID cannot be empty"));
214 }
215
216 if config.client_type == ClientType::Confidential && config.client_secret.is_none() {
218 return Err(AuthError::validation(
219 "Confidential clients must have a client secret",
220 ));
221 }
222
223 if config.client_type == ClientType::Public && config.client_secret.is_some() {
225 return Err(AuthError::validation(
226 "Public clients must not have a client secret",
227 ));
228 }
229
230 if config.redirect_uris.is_empty() {
232 return Err(AuthError::validation(
233 "At least one redirect URI must be provided",
234 ));
235 }
236
237 for uri in &config.redirect_uris {
239 if uri.is_empty() {
240 return Err(AuthError::validation("Redirect URI cannot be empty"));
241 }
242
243 if !uri.starts_with("https://") && !uri.starts_with("http://localhost") {
245 return Err(AuthError::validation(
246 "Redirect URIs must use HTTPS (except localhost)",
247 ));
248 }
249 }
250
251 if config.authorized_scopes.is_empty() {
253 return Err(AuthError::validation(
254 "At least one authorized scope must be provided",
255 ));
256 }
257
258 if config.authorized_grant_types.is_empty() {
260 return Err(AuthError::validation(
261 "At least one authorized grant type must be provided",
262 ));
263 }
264
265 if config.authorized_response_types.is_empty() {
267 return Err(AuthError::validation(
268 "At least one authorized response type must be provided",
269 ));
270 }
271
272 Ok(())
273 }
274}
275
276impl Default for ClientRegistry {
277 fn default() -> Self {
278 let storage =
280 if std::env::var("CLIENT_REGISTRY_STORAGE").unwrap_or_default() == "persistent" {
281 Arc::new(InMemoryStorage::new())
283 } else {
284 Arc::new(InMemoryStorage::new())
286 };
287
288 Self { storage }
289 }
290}
291
292#[cfg(test)]
293mod tests {
294 use super::*;
295 use crate::storage::memory::InMemoryStorage;
296
297 #[tokio::test]
298 async fn test_client_registry_operations() {
299 let storage = Arc::new(InMemoryStorage::new());
300 let registry = ClientRegistry::new(storage).await.unwrap();
301
302 let client_config = ClientConfig {
304 client_id: "test_client".to_string(),
305 client_type: ClientType::Confidential,
306 client_secret: Some("test_secret".to_string()),
307 redirect_uris: vec!["https://example.com/callback".to_string()],
308 ..Default::default()
309 };
310
311 let registered_client = registry
313 .register_client(client_config.clone())
314 .await
315 .unwrap();
316 assert_eq!(registered_client.client_id, "test_client");
317
318 let retrieved_client = registry.get_client("test_client").await.unwrap().unwrap();
320 assert_eq!(retrieved_client.client_id, "test_client");
321 assert_eq!(retrieved_client.client_type, ClientType::Confidential);
322
323 let auth_result = registry
325 .authenticate_client("test_client", "test_secret")
326 .await
327 .unwrap();
328 assert!(auth_result);
329
330 let auth_fail = registry
331 .authenticate_client("test_client", "wrong_secret")
332 .await
333 .unwrap();
334 assert!(!auth_fail);
335
336 let valid_uri = registry
338 .validate_redirect_uri("test_client", "https://example.com/callback")
339 .await
340 .unwrap();
341 assert!(valid_uri);
342
343 let invalid_uri = registry
344 .validate_redirect_uri("test_client", "https://malicious.com/callback")
345 .await
346 .unwrap();
347 assert!(!invalid_uri);
348
349 registry.delete_client("test_client").await.unwrap();
351 let deleted_client = registry.get_client("test_client").await.unwrap();
352 assert!(deleted_client.is_none());
353 }
354
355 #[tokio::test]
356 async fn test_client_validation() {
357 let storage = Arc::new(InMemoryStorage::new());
358 let registry = ClientRegistry::new(storage).await.unwrap();
359
360 let invalid_config = ClientConfig {
362 client_id: "".to_string(),
363 ..Default::default()
364 };
365 assert!(registry.register_client(invalid_config).await.is_err());
366
367 let invalid_config = ClientConfig {
369 client_type: ClientType::Confidential,
370 client_secret: None,
371 ..Default::default()
372 };
373 assert!(registry.register_client(invalid_config).await.is_err());
374
375 let invalid_config = ClientConfig {
377 client_type: ClientType::Public,
378 client_secret: Some("secret".to_string()),
379 ..Default::default()
380 };
381 assert!(registry.register_client(invalid_config).await.is_err());
382
383 let invalid_config = ClientConfig {
385 redirect_uris: vec![],
386 ..Default::default()
387 };
388 assert!(registry.register_client(invalid_config).await.is_err());
389
390 let invalid_config = ClientConfig {
392 redirect_uris: vec!["http://example.com/callback".to_string()],
393 ..Default::default()
394 };
395 assert!(registry.register_client(invalid_config).await.is_err());
396 }
397}