Skip to main content

auth_framework/server/core/
client_registry.rs

1//! OAuth 2.0 Client Registry Module
2//!
3//! This module implements a client registry for managing OAuth 2.0 clients
4//! including registration, retrieval, and validation.
5
6use crate::errors::{AuthError, Result};
7use crate::storage::core::AuthStorage;
8use crate::storage::memory::InMemoryStorage;
9use std::sync::Arc;
10
11// Re-export canonical types so existing imports like
12// `server::core::client_registry::{ClientType, ClientConfig}` keep working.
13pub use crate::client::{ClientConfig, ClientType};
14
15/// Client Registry for managing OAuth 2.0 clients
16#[derive(Clone)]
17pub struct ClientRegistry {
18    storage: Arc<dyn AuthStorage>,
19}
20
21impl ClientRegistry {
22    /// Create a new client registry
23    pub async fn new(storage: Arc<dyn AuthStorage>) -> Result<Self> {
24        Ok(Self { storage })
25    }
26
27    /// Register a new OAuth 2.0 client
28    pub async fn register_client(&self, config: ClientConfig) -> Result<ClientConfig> {
29        // Validate the client configuration
30        self.validate_client_config(&config)?;
31
32        // Store the client in the storage backend
33        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    /// Retrieve a client by ID
45    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    /// Update a client configuration
60    pub async fn update_client(&self, client_id: &str, config: ClientConfig) -> Result<()> {
61        // Ensure the client ID matches
62        if config.client_id != client_id {
63            return Err(AuthError::validation("Client ID mismatch"));
64        }
65
66        // Validate the updated configuration
67        self.validate_client_config(&config)?;
68
69        // Store the updated client
70        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    /// Delete a client
82    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    /// Validate that a redirect URI is authorized for a client
89    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    /// Validate that a scope is authorized for a client
98    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    /// Validate that a grant type is authorized for a client
107    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    /// Authenticate a confidential client using client credentials
116    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                    // Use constant-time comparison to prevent timing attacks
121                    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                    // Public clients don't have secrets
128                    Ok(true)
129                }
130                _ => Ok(false),
131            }
132        } else {
133            Ok(false)
134        }
135    }
136
137    /// Validate client configuration
138    fn validate_client_config(&self, config: &ClientConfig) -> Result<()> {
139        // Client ID must not be empty
140        if config.client_id.is_empty() {
141            return Err(AuthError::validation("Client ID cannot be empty"));
142        }
143
144        // Confidential clients must have a secret
145        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        // Public clients must not have a secret
152        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        // At least one redirect URI must be provided
159        if config.redirect_uris.is_empty() {
160            return Err(AuthError::validation(
161                "At least one redirect URI must be provided",
162            ));
163        }
164
165        // Validate redirect URIs
166        for uri in &config.redirect_uris {
167            if uri.is_empty() {
168                return Err(AuthError::validation("Redirect URI cannot be empty"));
169            }
170
171            // Basic URI validation (in production, use a proper URI parser)
172            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        // At least one scope must be provided
180        if config.authorized_scopes.is_empty() {
181            return Err(AuthError::validation(
182                "At least one authorized scope must be provided",
183            ));
184        }
185
186        // At least one grant type must be provided
187        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        // At least one response type must be provided
194        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        // Create default registry with environment-based storage configuration
207        let storage =
208            if std::env::var("CLIENT_REGISTRY_STORAGE").unwrap_or_default() == "persistent" {
209                // In production, this could be database or file-based storage
210                Arc::new(InMemoryStorage::new())
211            } else {
212                // Default to in-memory storage for development/testing
213                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        // Create a test client configuration
231        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        // Register the client
240        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        // Retrieve the client
247        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        // Authenticate the client
252        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        // Validate redirect URI
265        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        // Delete the client
278        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        // Test empty client ID
289        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        // Test confidential client without secret
296        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        // Test public client with secret
304        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        // Test empty redirect URIs
312        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        // Test insecure redirect URI
319        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}