Skip to main content

auth_framework/server/core/
client_registration.rs

1//! RFC 7591 - OAuth 2.0 Dynamic Client Registration Protocol
2//!
3//! This module implements the OAuth 2.0 Dynamic Client Registration Protocol
4//! as defined in RFC 7591, allowing clients to dynamically register with
5//! an authorization server.
6//!
7//! # Features
8//!
9//! - **Dynamic Client Registration**: Allow clients to register programmatically
10//! - **Client Metadata Management**: Comprehensive client configuration support
11//! - **Registration Validation**: Security controls for client registration
12//! - **Client Credentials Management**: Automatic client secret generation
13//! - **Update and Delete Operations**: Full client lifecycle management
14//! - **Security Controls**: Rate limiting and validation for registration requests
15
16use crate::errors::{AuthError, Result, StorageError};
17use crate::storage::AuthStorage;
18use base64::{Engine as _, engine::general_purpose};
19use chrono::{DateTime, Duration, Utc};
20use governor;
21use serde::{Deserialize, Serialize};
22use serde_json::Value;
23use std::collections::HashMap;
24use std::sync::Arc;
25use url;
26use uuid::Uuid;
27
28/// Client registration request as defined in RFC 7591
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct ClientRegistrationRequest {
31    /// Array of redirect URIs
32    pub redirect_uris: Option<Vec<String>>,
33
34    /// Token endpoint authentication method
35    pub token_endpoint_auth_method: Option<String>,
36
37    /// Grant types that the client will use
38    pub grant_types: Option<Vec<String>>,
39
40    /// Response types that the client will use
41    pub response_types: Option<Vec<String>>,
42
43    /// Human-readable name of the client
44    pub client_name: Option<String>,
45
46    /// URL of the home page of the client
47    pub client_uri: Option<String>,
48
49    /// URL of the logo for the client
50    pub logo_uri: Option<String>,
51
52    /// Array of scope values that the client will use
53    pub scope: Option<String>,
54
55    /// Array of contact information
56    pub contacts: Option<Vec<String>>,
57
58    /// URL of the terms of service
59    pub tos_uri: Option<String>,
60
61    /// URL of the privacy policy
62    pub policy_uri: Option<String>,
63
64    /// URL for the client's JSON Web Key Set
65    pub jwks_uri: Option<String>,
66
67    /// Client's JSON Web Key Set
68    pub jwks: Option<Value>,
69
70    /// Software identifier of the client
71    pub software_id: Option<String>,
72
73    /// Software version of the client
74    pub software_version: Option<String>,
75
76    /// Additional client metadata
77    #[serde(flatten)]
78    pub additional_metadata: HashMap<String, Value>,
79}
80
81/// Client registration response as defined in RFC 7591
82#[derive(Clone, Serialize, Deserialize)]
83pub struct ClientRegistrationResponse {
84    /// OAuth 2.0 client identifier
85    pub client_id: String,
86
87    /// OAuth 2.0 client secret (optional)
88    pub client_secret: Option<String>,
89
90    /// Registration access token
91    pub registration_access_token: String,
92
93    /// Registration client URI
94    pub registration_client_uri: String,
95
96    /// Time at which the client identifier was issued
97    pub client_id_issued_at: Option<i64>,
98
99    /// Time at which the client secret will expire
100    pub client_secret_expires_at: Option<i64>,
101
102    /// Registered redirect URIs
103    pub redirect_uris: Option<Vec<String>>,
104
105    /// Token endpoint authentication method
106    pub token_endpoint_auth_method: Option<String>,
107
108    /// Grant types
109    pub grant_types: Option<Vec<String>>,
110
111    /// Response types
112    pub response_types: Option<Vec<String>>,
113
114    /// Client name
115    pub client_name: Option<String>,
116
117    /// Client URI
118    pub client_uri: Option<String>,
119
120    /// Logo URI
121    pub logo_uri: Option<String>,
122
123    /// Scope
124    pub scope: Option<String>,
125
126    /// Contacts
127    pub contacts: Option<Vec<String>>,
128
129    /// Terms of service URI
130    pub tos_uri: Option<String>,
131
132    /// Policy URI
133    pub policy_uri: Option<String>,
134
135    /// JWKS URI
136    pub jwks_uri: Option<String>,
137
138    /// JWKS
139    pub jwks: Option<Value>,
140
141    /// Software ID
142    pub software_id: Option<String>,
143
144    /// Software version
145    pub software_version: Option<String>,
146
147    /// Additional metadata
148    #[serde(flatten)]
149    pub additional_metadata: HashMap<String, Value>,
150}
151
152impl std::fmt::Debug for ClientRegistrationResponse {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        let mut d = f.debug_struct("ClientRegistrationResponse");
155        d.field("client_id", &self.client_id);
156        d.field(
157            "client_secret",
158            &crate::utils::redact::redacted(&self.client_secret),
159        );
160        d.field(
161            "registration_access_token",
162            &crate::utils::redact::redacted(&self.registration_access_token),
163        );
164        d.field("registration_client_uri", &self.registration_client_uri);
165        d.field("client_id_issued_at", &self.client_id_issued_at);
166        d.field("client_secret_expires_at", &self.client_secret_expires_at);
167        d.field("redirect_uris", &self.redirect_uris);
168        d.field(
169            "token_endpoint_auth_method",
170            &self.token_endpoint_auth_method,
171        );
172        d.field("grant_types", &self.grant_types);
173        d.field("response_types", &self.response_types);
174        d.field("client_name", &self.client_name);
175        d.field("client_uri", &self.client_uri);
176        d.field("logo_uri", &self.logo_uri);
177        d.field("scope", &self.scope);
178        d.field("contacts", &self.contacts);
179        d.field("tos_uri", &self.tos_uri);
180        d.field("policy_uri", &self.policy_uri);
181        d.field("jwks_uri", &self.jwks_uri);
182        d.field("jwks", &self.jwks);
183        d.field("software_id", &self.software_id);
184        d.field("software_version", &self.software_version);
185        d.field("additional_metadata", &self.additional_metadata);
186        d.finish()
187    }
188}
189
190/// Registered client information
191#[derive(Clone, Serialize, Deserialize)]
192pub struct RegisteredClient {
193    /// Client identifier
194    pub client_id: String,
195
196    /// Client secret (hashed)
197    pub client_secret_hash: Option<String>,
198
199    /// Registration access token (hashed)
200    pub registration_access_token_hash: String,
201
202    /// Client metadata
203    pub metadata: ClientRegistrationRequest,
204
205    /// Registration timestamp
206    pub registered_at: DateTime<Utc>,
207
208    /// Last updated timestamp
209    pub updated_at: DateTime<Utc>,
210
211    /// Client secret expiration
212    pub client_secret_expires_at: Option<DateTime<Utc>>,
213
214    /// Whether the client is active
215    pub is_active: bool,
216}
217
218impl std::fmt::Debug for RegisteredClient {
219    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220        let mut d = f.debug_struct("RegisteredClient");
221        d.field("client_id", &self.client_id);
222        d.field(
223            "client_secret_hash",
224            &crate::utils::redact::redacted(&self.client_secret_hash),
225        );
226        d.field(
227            "registration_access_token_hash",
228            &crate::utils::redact::redacted(&self.registration_access_token_hash),
229        );
230        d.field("metadata", &self.metadata);
231        d.field("registered_at", &self.registered_at);
232        d.field("updated_at", &self.updated_at);
233        d.field("client_secret_expires_at", &self.client_secret_expires_at);
234        d.field("is_active", &self.is_active);
235        d.finish()
236    }
237}
238
239/// Dynamic Client Registration Manager configuration
240#[derive(Debug, Clone)]
241pub struct ClientRegistrationConfig {
242    /// Base URL for registration endpoints
243    pub base_url: String,
244
245    /// Whether to require authentication for registration
246    pub require_authentication: bool,
247
248    /// Default client secret expiration (seconds)
249    pub default_secret_expiration: Option<i64>,
250
251    /// Maximum number of redirect URIs per client
252    pub max_redirect_uris: usize,
253
254    /// Allowed grant types
255    pub allowed_grant_types: Vec<String>,
256
257    /// Allowed response types
258    pub allowed_response_types: Vec<String>,
259
260    /// Allowed authentication methods
261    pub allowed_auth_methods: Vec<String>,
262
263    /// Whether to allow public clients
264    pub allow_public_clients: bool,
265
266    /// Rate limiting configuration
267    pub rate_limit_per_ip: u32,
268    pub rate_limit_window: std::time::Duration,
269}
270
271impl Default for ClientRegistrationConfig {
272    fn default() -> Self {
273        Self {
274            base_url: "https://auth.example.com".to_string(),
275            require_authentication: false,
276            default_secret_expiration: Some(86400 * 365), // 1 year
277            max_redirect_uris: 10,
278            allowed_grant_types: vec![
279                "authorization_code".to_string(),
280                "client_credentials".to_string(),
281                "refresh_token".to_string(),
282                "urn:ietf:params:oauth:grant-type:device_code".to_string(),
283            ],
284            allowed_response_types: vec![
285                "code".to_string(),
286                "token".to_string(),
287                "id_token".to_string(),
288            ],
289            allowed_auth_methods: vec![
290                "client_secret_basic".to_string(),
291                "client_secret_post".to_string(),
292                "private_key_jwt".to_string(),
293                "none".to_string(),
294            ],
295            allow_public_clients: true,
296            rate_limit_per_ip: 10,
297            rate_limit_window: std::time::Duration::from_secs(3600),
298        }
299    }
300}
301
302/// Dynamic Client Registration Manager
303pub struct ClientRegistrationManager {
304    config: ClientRegistrationConfig,
305    storage: Arc<dyn AuthStorage>,
306    rate_limiter: Arc<
307        governor::RateLimiter<
308            governor::state::direct::NotKeyed,
309            governor::state::InMemoryState,
310            governor::clock::DefaultClock,
311        >,
312    >,
313}
314
315impl ClientRegistrationManager {
316    /// Create a new client registration manager
317    pub fn new(config: ClientRegistrationConfig, storage: Arc<dyn AuthStorage>) -> Self {
318        let quota =
319            governor::Quota::per_hour(std::num::NonZeroU32::new(config.rate_limit_per_ip).unwrap());
320        let rate_limiter = Arc::new(governor::RateLimiter::direct(quota));
321
322        Self {
323            config,
324            storage,
325            rate_limiter,
326        }
327    }
328
329    /// Register a new client
330    pub async fn register_client(
331        &self,
332        request: ClientRegistrationRequest,
333        client_ip: Option<std::net::IpAddr>,
334    ) -> Result<ClientRegistrationResponse> {
335        // Rate limiting
336        if let Some(_ip) = client_ip
337            && self.rate_limiter.check().is_err()
338        {
339            return Err(AuthError::rate_limit(
340                "Client registration rate limit exceeded",
341            ));
342        }
343
344        // Validate the registration request
345        self.validate_registration_request(&request)?;
346
347        // Generate client credentials
348        let client_id = self.generate_client_id();
349        let (client_secret, client_secret_hash) = if self.requires_client_secret(&request) {
350            let secret = self.generate_client_secret();
351            let hash = self.hash_secret(&secret)?;
352            (Some(secret), Some(hash))
353        } else {
354            (None, None)
355        };
356
357        // Generate registration access token
358        let registration_access_token = self.generate_registration_access_token();
359        let registration_access_token_hash = self.hash_secret(&registration_access_token)?;
360
361        // Calculate expiration
362        let client_secret_expires_at = if client_secret.is_some() {
363            self.config
364                .default_secret_expiration
365                .map(|seconds| Utc::now() + Duration::seconds(seconds))
366        } else {
367            None
368        };
369
370        // Create registered client
371        let registered_client = RegisteredClient {
372            client_id: client_id.clone(),
373            client_secret_hash,
374            registration_access_token_hash,
375            metadata: request.clone(),
376            registered_at: Utc::now(),
377            updated_at: Utc::now(),
378            client_secret_expires_at,
379            is_active: true,
380        };
381
382        // Store the client
383        self.store_client(&registered_client).await?;
384
385        // Build response
386        let response = ClientRegistrationResponse {
387            client_id: client_id.clone(),
388            client_secret,
389            registration_access_token,
390            registration_client_uri: format!("{}/register/{}", self.config.base_url, client_id),
391            client_id_issued_at: Some(Utc::now().timestamp()),
392            client_secret_expires_at: client_secret_expires_at.map(|dt| dt.timestamp()),
393            redirect_uris: request.redirect_uris,
394            token_endpoint_auth_method: request.token_endpoint_auth_method,
395            grant_types: request.grant_types,
396            response_types: request.response_types,
397            client_name: request.client_name,
398            client_uri: request.client_uri,
399            logo_uri: request.logo_uri,
400            scope: request.scope,
401            contacts: request.contacts,
402            tos_uri: request.tos_uri,
403            policy_uri: request.policy_uri,
404            jwks_uri: request.jwks_uri,
405            jwks: request.jwks,
406            software_id: request.software_id,
407            software_version: request.software_version,
408            additional_metadata: request.additional_metadata,
409        };
410
411        Ok(response)
412    }
413
414    /// Read client configuration
415    pub async fn read_client(
416        &self,
417        client_id: &str,
418        registration_access_token: &str,
419    ) -> Result<ClientRegistrationResponse> {
420        let client = self.get_client(client_id).await?;
421
422        // Verify registration access token
423        if !self.verify_registration_token(&client, registration_access_token)? {
424            return Err(AuthError::auth_method(
425                "client_registration",
426                "Invalid registration access token",
427            ));
428        }
429
430        self.client_to_response(&client)
431    }
432
433    /// Update client configuration
434    pub async fn update_client(
435        &self,
436        client_id: &str,
437        registration_access_token: &str,
438        request: ClientRegistrationRequest,
439    ) -> Result<ClientRegistrationResponse> {
440        let mut client = self.get_client(client_id).await?;
441
442        // Verify registration access token
443        if !self.verify_registration_token(&client, registration_access_token)? {
444            return Err(AuthError::auth_method(
445                "client_registration",
446                "Invalid registration access token",
447            ));
448        }
449
450        // Validate the update request
451        self.validate_registration_request(&request)?;
452
453        // Update client metadata
454        client.metadata = request;
455        client.updated_at = Utc::now();
456
457        // Store updated client
458        self.store_client(&client).await?;
459
460        self.client_to_response(&client)
461    }
462
463    /// Delete client
464    pub async fn delete_client(
465        &self,
466        client_id: &str,
467        registration_access_token: &str,
468    ) -> Result<()> {
469        let client = self.get_client(client_id).await?;
470
471        // Verify registration access token
472        if !self.verify_registration_token(&client, registration_access_token)? {
473            return Err(AuthError::auth_method(
474                "client_registration",
475                "Invalid registration access token",
476            ));
477        }
478
479        // Mark client as inactive
480        let key = format!("client_registration:{}", client_id);
481        self.storage.delete_kv(&key).await?;
482
483        Ok(())
484    }
485
486    /// Validate registration request
487    fn validate_registration_request(&self, request: &ClientRegistrationRequest) -> Result<()> {
488        // Validate redirect URIs
489        if let Some(redirect_uris) = &request.redirect_uris {
490            if redirect_uris.len() > self.config.max_redirect_uris {
491                return Err(AuthError::auth_method(
492                    "client_registration",
493                    "Too many redirect URIs",
494                ));
495            }
496
497            for uri in redirect_uris {
498                if !self.is_valid_uri(uri) {
499                    return Err(AuthError::auth_method(
500                        "client_registration",
501                        format!("Invalid redirect URI: {}", uri),
502                    ));
503                }
504            }
505        }
506
507        // Validate grant types
508        if let Some(grant_types) = &request.grant_types {
509            for grant_type in grant_types {
510                if !self.config.allowed_grant_types.contains(grant_type) {
511                    return Err(AuthError::auth_method(
512                        "client_registration",
513                        format!("Unsupported grant type: {}", grant_type),
514                    ));
515                }
516            }
517        }
518
519        // Validate response types
520        if let Some(response_types) = &request.response_types {
521            for response_type in response_types {
522                if !self.config.allowed_response_types.contains(response_type) {
523                    return Err(AuthError::auth_method(
524                        "client_registration",
525                        format!("Unsupported response type: {}", response_type),
526                    ));
527                }
528            }
529        }
530
531        // Validate authentication method
532        if let Some(auth_method) = &request.token_endpoint_auth_method
533            && !self.config.allowed_auth_methods.contains(auth_method)
534        {
535            return Err(AuthError::auth_method(
536                "client_registration",
537                format!("Unsupported authentication method: {}", auth_method),
538            ));
539        }
540
541        Ok(())
542    }
543
544    /// Check if client requires a secret
545    fn requires_client_secret(&self, request: &ClientRegistrationRequest) -> bool {
546        if !self.config.allow_public_clients {
547            return true;
548        }
549
550        !matches!(request.token_endpoint_auth_method.as_deref(), Some("none"))
551    }
552
553    /// Generate client ID
554    fn generate_client_id(&self) -> String {
555        format!("client_{}", Uuid::new_v4().simple())
556    }
557
558    /// Generate client secret
559    fn generate_client_secret(&self) -> String {
560        use rand::RngCore;
561        let mut rng = rand::rng();
562        let mut bytes = [0u8; 32];
563        rng.fill_bytes(&mut bytes);
564        general_purpose::URL_SAFE_NO_PAD.encode(bytes)
565    }
566
567    /// Generate registration access token
568    fn generate_registration_access_token(&self) -> String {
569        use rand::RngCore;
570        let mut rng = rand::rng();
571        let mut bytes = [0u8; 32];
572        rng.fill_bytes(&mut bytes);
573        general_purpose::URL_SAFE_NO_PAD.encode(bytes)
574    }
575
576    /// Hash a secret
577    fn hash_secret(&self, secret: &str) -> Result<String> {
578        use sha2::{Digest, Sha256};
579        let mut hasher = Sha256::new();
580        hasher.update(secret.as_bytes());
581        Ok(format!("{:x}", hasher.finalize()))
582    }
583
584    /// Verify registration access token
585    fn verify_registration_token(&self, client: &RegisteredClient, token: &str) -> Result<bool> {
586        let token_hash = self.hash_secret(token)?;
587        Ok(client.registration_access_token_hash == token_hash)
588    }
589
590    /// Validate URI
591    fn is_valid_uri(&self, uri: &str) -> bool {
592        url::Url::parse(uri).is_ok()
593    }
594
595    /// Store client in storage
596    async fn store_client(&self, client: &RegisteredClient) -> Result<()> {
597        let key = format!("client_registration:{}", client.client_id);
598        let value = serde_json::to_string(client)?;
599        self.storage.store_kv(&key, value.as_bytes(), None).await?;
600        Ok(())
601    }
602
603    /// Get client from storage
604    async fn get_client(&self, client_id: &str) -> Result<RegisteredClient> {
605        let key = format!("client_registration:{}", client_id);
606        let value = match self.storage.get_kv(&key).await? {
607            Some(value) => value,
608            None => {
609                return Err(AuthError::auth_method(
610                    "client_registration",
611                    "Client not found",
612                ));
613            }
614        };
615        let value_str = String::from_utf8(value).map_err(|e| {
616            AuthError::Storage(StorageError::Serialization {
617                message: format!("Invalid UTF-8 data: {}", e),
618            })
619        })?;
620        let client: RegisteredClient = serde_json::from_str(&value_str)?;
621        Ok(client)
622    }
623
624    /// Convert registered client to response
625    fn client_to_response(&self, client: &RegisteredClient) -> Result<ClientRegistrationResponse> {
626        Ok(ClientRegistrationResponse {
627            client_id: client.client_id.clone(),
628            client_secret: None, // Never return the actual secret
629            registration_access_token: "***".to_string(), // Never return the actual token
630            registration_client_uri: format!(
631                "{}/register/{}",
632                self.config.base_url, client.client_id
633            ),
634            client_id_issued_at: Some(client.registered_at.timestamp()),
635            client_secret_expires_at: client.client_secret_expires_at.map(|dt| dt.timestamp()),
636            redirect_uris: client.metadata.redirect_uris.clone(),
637            token_endpoint_auth_method: client.metadata.token_endpoint_auth_method.clone(),
638            grant_types: client.metadata.grant_types.clone(),
639            response_types: client.metadata.response_types.clone(),
640            client_name: client.metadata.client_name.clone(),
641            client_uri: client.metadata.client_uri.clone(),
642            logo_uri: client.metadata.logo_uri.clone(),
643            scope: client.metadata.scope.clone(),
644            contacts: client.metadata.contacts.clone(),
645            tos_uri: client.metadata.tos_uri.clone(),
646            policy_uri: client.metadata.policy_uri.clone(),
647            jwks_uri: client.metadata.jwks_uri.clone(),
648            jwks: client.metadata.jwks.clone(),
649            software_id: client.metadata.software_id.clone(),
650            software_version: client.metadata.software_version.clone(),
651            additional_metadata: client.metadata.additional_metadata.clone(),
652        })
653    }
654}
655
656#[cfg(test)]
657mod tests {
658    use super::*;
659    use crate::storage::MemoryStorage;
660
661    #[tokio::test]
662    async fn test_client_registration() {
663        let storage = Arc::new(MemoryStorage::new());
664        let config = ClientRegistrationConfig::default();
665        let manager = ClientRegistrationManager::new(config, storage);
666
667        let request = ClientRegistrationRequest {
668            redirect_uris: Some(vec!["https://client.example.com/callback".to_string()]),
669            token_endpoint_auth_method: Some("client_secret_basic".to_string()),
670            grant_types: Some(vec!["authorization_code".to_string()]),
671            response_types: Some(vec!["code".to_string()]),
672            client_name: Some("Test Client".to_string()),
673            client_uri: Some("https://client.example.com".to_string()),
674            logo_uri: Some("https://client.example.com/logo.png".to_string()),
675            scope: Some("read write".to_string()),
676            contacts: Some(vec!["admin@client.example.com".to_string()]),
677            tos_uri: Some("https://client.example.com/tos".to_string()),
678            policy_uri: Some("https://client.example.com/privacy".to_string()),
679            jwks_uri: Some("https://client.example.com/jwks".to_string()),
680            jwks: None,
681            software_id: Some("test-client".to_string()),
682            software_version: Some("1.0.0".to_string()),
683            additional_metadata: HashMap::new(),
684        };
685
686        let response = manager
687            .register_client(request.clone(), None)
688            .await
689            .unwrap();
690
691        assert!(!response.client_id.is_empty());
692        assert!(response.client_secret.is_some());
693        assert!(!response.registration_access_token.is_empty());
694        assert_eq!(response.client_name, Some("Test Client".to_string()));
695        assert_eq!(
696            response.redirect_uris,
697            Some(vec!["https://client.example.com/callback".to_string()])
698        );
699    }
700
701    #[tokio::test]
702    async fn test_public_client_registration() {
703        let storage = Arc::new(MemoryStorage::new());
704        let config = ClientRegistrationConfig::default();
705        let manager = ClientRegistrationManager::new(config, storage);
706
707        let request = ClientRegistrationRequest {
708            redirect_uris: Some(vec!["https://client.example.com/callback".to_string()]),
709            token_endpoint_auth_method: Some("none".to_string()),
710            grant_types: Some(vec!["authorization_code".to_string()]),
711            response_types: Some(vec!["code".to_string()]),
712            client_name: Some("Public Client".to_string()),
713            client_uri: None,
714            logo_uri: None,
715            scope: Some("read".to_string()),
716            contacts: None,
717            tos_uri: None,
718            policy_uri: None,
719            jwks_uri: None,
720            jwks: None,
721            software_id: None,
722            software_version: None,
723            additional_metadata: HashMap::new(),
724        };
725
726        let response = manager.register_client(request, None).await.unwrap();
727
728        assert!(!response.client_id.is_empty());
729        assert!(response.client_secret.is_none()); // Public client should not have secret
730        assert!(!response.registration_access_token.is_empty());
731        assert_eq!(response.client_name, Some("Public Client".to_string()));
732    }
733}