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
81impl ClientRegistrationRequest {
82    /// Create a builder for a client registration request using a primary redirect URI.
83    pub fn builder(redirect_uri: impl Into<String>) -> ClientRegistrationRequestBuilder {
84        ClientRegistrationRequestBuilder {
85            redirect_uris: Some(vec![redirect_uri.into()]),
86            token_endpoint_auth_method: None,
87            grant_types: None,
88            response_types: None,
89            client_name: None,
90            client_uri: None,
91            logo_uri: None,
92            scope: None,
93            contacts: None,
94            tos_uri: None,
95            policy_uri: None,
96            jwks_uri: None,
97            jwks: None,
98            software_id: None,
99            software_version: None,
100            additional_metadata: HashMap::new(),
101        }
102    }
103}
104
105/// Builder for RFC 7591 client registration requests.
106pub struct ClientRegistrationRequestBuilder {
107    redirect_uris: Option<Vec<String>>,
108    token_endpoint_auth_method: Option<String>,
109    grant_types: Option<Vec<String>>,
110    response_types: Option<Vec<String>>,
111    client_name: Option<String>,
112    client_uri: Option<String>,
113    logo_uri: Option<String>,
114    scope: Option<String>,
115    contacts: Option<Vec<String>>,
116    tos_uri: Option<String>,
117    policy_uri: Option<String>,
118    jwks_uri: Option<String>,
119    jwks: Option<Value>,
120    software_id: Option<String>,
121    software_version: Option<String>,
122    additional_metadata: HashMap<String, Value>,
123}
124
125impl ClientRegistrationRequestBuilder {
126    /// Replace the redirect URI set.
127    pub fn redirect_uris<I, S>(mut self, redirect_uris: I) -> Self
128    where
129        I: IntoIterator<Item = S>,
130        S: Into<String>,
131    {
132        self.redirect_uris = Some(redirect_uris.into_iter().map(Into::into).collect());
133        self
134    }
135
136    /// Set the token endpoint authentication method.
137    pub fn auth_method(mut self, method: impl Into<String>) -> Self {
138        self.token_endpoint_auth_method = Some(method.into());
139        self
140    }
141
142    /// Configure a public client.
143    pub fn public_client(self) -> Self {
144        self.auth_method("none")
145    }
146
147    /// Set the grant types.
148    pub fn grant_types<I, S>(mut self, grant_types: I) -> Self
149    where
150        I: IntoIterator<Item = S>,
151        S: Into<String>,
152    {
153        self.grant_types = Some(grant_types.into_iter().map(Into::into).collect());
154        self
155    }
156
157    /// Set the response types.
158    pub fn response_types<I, S>(mut self, response_types: I) -> Self
159    where
160        I: IntoIterator<Item = S>,
161        S: Into<String>,
162    {
163        self.response_types = Some(response_types.into_iter().map(Into::into).collect());
164        self
165    }
166
167    /// Set a human-readable client name.
168    pub fn client_name(mut self, client_name: impl Into<String>) -> Self {
169        self.client_name = Some(client_name.into());
170        self
171    }
172
173    /// Set common client metadata URLs.
174    pub fn client_uri(mut self, client_uri: impl Into<String>) -> Self {
175        self.client_uri = Some(client_uri.into());
176        self
177    }
178
179    /// Set the logo URI.
180    pub fn logo_uri(mut self, logo_uri: impl Into<String>) -> Self {
181        self.logo_uri = Some(logo_uri.into());
182        self
183    }
184
185    /// Set the requested scope string.
186    pub fn scope(mut self, scope: impl Into<String>) -> Self {
187        self.scope = Some(scope.into());
188        self
189    }
190
191    /// Set contact email addresses.
192    pub fn contacts<I, S>(mut self, contacts: I) -> Self
193    where
194        I: IntoIterator<Item = S>,
195        S: Into<String>,
196    {
197        self.contacts = Some(contacts.into_iter().map(Into::into).collect());
198        self
199    }
200
201    /// Set the terms-of-service URI.
202    pub fn tos_uri(mut self, tos_uri: impl Into<String>) -> Self {
203        self.tos_uri = Some(tos_uri.into());
204        self
205    }
206
207    /// Set the privacy-policy URI.
208    pub fn policy_uri(mut self, policy_uri: impl Into<String>) -> Self {
209        self.policy_uri = Some(policy_uri.into());
210        self
211    }
212
213    /// Set the JWKS URI.
214    pub fn jwks_uri(mut self, jwks_uri: impl Into<String>) -> Self {
215        self.jwks_uri = Some(jwks_uri.into());
216        self
217    }
218
219    /// Set an inline JWKS value.
220    pub fn jwks(mut self, jwks: Value) -> Self {
221        self.jwks = Some(jwks);
222        self
223    }
224
225    /// Set the software metadata.
226    pub fn software(
227        mut self,
228        software_id: impl Into<String>,
229        software_version: impl Into<String>,
230    ) -> Self {
231        self.software_id = Some(software_id.into());
232        self.software_version = Some(software_version.into());
233        self
234    }
235
236    /// Add a custom metadata field.
237    pub fn metadata(mut self, key: impl Into<String>, value: Value) -> Self {
238        self.additional_metadata.insert(key.into(), value);
239        self
240    }
241
242    /// Build the client registration request.
243    pub fn build(self) -> ClientRegistrationRequest {
244        ClientRegistrationRequest {
245            redirect_uris: self.redirect_uris,
246            token_endpoint_auth_method: self.token_endpoint_auth_method,
247            grant_types: self.grant_types,
248            response_types: self.response_types,
249            client_name: self.client_name,
250            client_uri: self.client_uri,
251            logo_uri: self.logo_uri,
252            scope: self.scope,
253            contacts: self.contacts,
254            tos_uri: self.tos_uri,
255            policy_uri: self.policy_uri,
256            jwks_uri: self.jwks_uri,
257            jwks: self.jwks,
258            software_id: self.software_id,
259            software_version: self.software_version,
260            additional_metadata: self.additional_metadata,
261        }
262    }
263}
264
265/// Client registration response as defined in RFC 7591
266#[derive(Debug, Clone, Serialize, Deserialize)]
267pub struct ClientRegistrationResponse {
268    /// OAuth 2.0 client identifier
269    pub client_id: String,
270
271    /// OAuth 2.0 client secret (optional)
272    pub client_secret: Option<String>,
273
274    /// Registration access token
275    pub registration_access_token: String,
276
277    /// Registration client URI
278    pub registration_client_uri: String,
279
280    /// Time at which the client identifier was issued
281    pub client_id_issued_at: Option<i64>,
282
283    /// Time at which the client secret will expire
284    pub client_secret_expires_at: Option<i64>,
285
286    /// Registered redirect URIs
287    pub redirect_uris: Option<Vec<String>>,
288
289    /// Token endpoint authentication method
290    pub token_endpoint_auth_method: Option<String>,
291
292    /// Grant types
293    pub grant_types: Option<Vec<String>>,
294
295    /// Response types
296    pub response_types: Option<Vec<String>>,
297
298    /// Client name
299    pub client_name: Option<String>,
300
301    /// Client URI
302    pub client_uri: Option<String>,
303
304    /// Logo URI
305    pub logo_uri: Option<String>,
306
307    /// Scope
308    pub scope: Option<String>,
309
310    /// Contacts
311    pub contacts: Option<Vec<String>>,
312
313    /// Terms of service URI
314    pub tos_uri: Option<String>,
315
316    /// Policy URI
317    pub policy_uri: Option<String>,
318
319    /// JWKS URI
320    pub jwks_uri: Option<String>,
321
322    /// JWKS
323    pub jwks: Option<Value>,
324
325    /// Software ID
326    pub software_id: Option<String>,
327
328    /// Software version
329    pub software_version: Option<String>,
330
331    /// Additional metadata
332    #[serde(flatten)]
333    pub additional_metadata: HashMap<String, Value>,
334}
335
336/// Registered client information
337#[derive(Debug, Clone, Serialize, Deserialize)]
338pub struct RegisteredClient {
339    /// Client identifier
340    pub client_id: String,
341
342    /// Client secret (hashed)
343    pub client_secret_hash: Option<String>,
344
345    /// Registration access token (hashed)
346    pub registration_access_token_hash: String,
347
348    /// Client metadata
349    pub metadata: ClientRegistrationRequest,
350
351    /// Registration timestamp
352    pub registered_at: DateTime<Utc>,
353
354    /// Last updated timestamp
355    pub updated_at: DateTime<Utc>,
356
357    /// Client secret expiration
358    pub client_secret_expires_at: Option<DateTime<Utc>>,
359
360    /// Whether the client is active
361    pub is_active: bool,
362}
363
364/// Dynamic Client Registration Manager configuration
365#[derive(Debug, Clone)]
366pub struct ClientRegistrationConfig {
367    /// Base URL for registration endpoints
368    pub base_url: String,
369
370    /// Whether to require authentication for registration
371    pub require_authentication: bool,
372
373    /// Default client secret expiration (seconds)
374    pub default_secret_expiration: Option<i64>,
375
376    /// Maximum number of redirect URIs per client
377    pub max_redirect_uris: usize,
378
379    /// Allowed grant types
380    pub allowed_grant_types: Vec<String>,
381
382    /// Allowed response types
383    pub allowed_response_types: Vec<String>,
384
385    /// Allowed authentication methods
386    pub allowed_auth_methods: Vec<String>,
387
388    /// Whether to allow public clients
389    pub allow_public_clients: bool,
390
391    /// Rate limiting configuration
392    pub rate_limit_per_ip: u32,
393    pub rate_limit_window: std::time::Duration,
394}
395
396impl Default for ClientRegistrationConfig {
397    fn default() -> Self {
398        Self {
399            base_url: "https://auth.example.com".to_string(),
400            require_authentication: false,
401            default_secret_expiration: Some(86400 * 365), // 1 year
402            max_redirect_uris: 10,
403            allowed_grant_types: vec![
404                "authorization_code".to_string(),
405                "client_credentials".to_string(),
406                "refresh_token".to_string(),
407                "urn:ietf:params:oauth:grant-type:device_code".to_string(),
408            ],
409            allowed_response_types: vec![
410                "code".to_string(),
411                "token".to_string(),
412                "id_token".to_string(),
413            ],
414            allowed_auth_methods: vec![
415                "client_secret_basic".to_string(),
416                "client_secret_post".to_string(),
417                "private_key_jwt".to_string(),
418                "none".to_string(),
419            ],
420            allow_public_clients: true,
421            rate_limit_per_ip: 10,
422            rate_limit_window: std::time::Duration::from_secs(3600),
423        }
424    }
425}
426
427/// Dynamic Client Registration Manager
428pub struct ClientRegistrationManager {
429    config: ClientRegistrationConfig,
430    storage: Arc<dyn AuthStorage>,
431    rate_limiter: Arc<
432        governor::RateLimiter<
433            governor::state::direct::NotKeyed,
434            governor::state::InMemoryState,
435            governor::clock::DefaultClock,
436        >,
437    >,
438}
439
440impl ClientRegistrationManager {
441    /// Create a new client registration manager
442    pub fn new(config: ClientRegistrationConfig, storage: Arc<dyn AuthStorage>) -> Self {
443        let quota = governor::Quota::per_hour(
444            std::num::NonZeroU32::new(config.rate_limit_per_ip.max(1))
445                .expect("clamped to at least 1"),
446        );
447        let rate_limiter = Arc::new(governor::RateLimiter::direct(quota));
448
449        Self {
450            config,
451            storage,
452            rate_limiter,
453        }
454    }
455
456    /// Register a new client
457    pub async fn register_client(
458        &self,
459        request: ClientRegistrationRequest,
460        client_ip: Option<std::net::IpAddr>,
461    ) -> Result<ClientRegistrationResponse> {
462        // Rate limiting
463        if let Some(_ip) = client_ip
464            && self.rate_limiter.check().is_err()
465        {
466            return Err(AuthError::rate_limit(
467                "Client registration rate limit exceeded",
468            ));
469        }
470
471        // Validate the registration request
472        self.validate_registration_request(&request)?;
473
474        // Generate client credentials
475        let client_id = self.generate_client_id();
476        let (client_secret, client_secret_hash) = if self.requires_client_secret(&request) {
477            let secret = self.generate_client_secret();
478            let hash = self.hash_secret(&secret)?;
479            (Some(secret), Some(hash))
480        } else {
481            (None, None)
482        };
483
484        // Generate registration access token
485        let registration_access_token = self.generate_registration_access_token();
486        let registration_access_token_hash = self.hash_secret(&registration_access_token)?;
487
488        // Calculate expiration
489        let client_secret_expires_at = if client_secret.is_some() {
490            self.config
491                .default_secret_expiration
492                .map(|seconds| Utc::now() + Duration::seconds(seconds))
493        } else {
494            None
495        };
496
497        // Create registered client
498        let registered_client = RegisteredClient {
499            client_id: client_id.clone(),
500            client_secret_hash,
501            registration_access_token_hash,
502            metadata: request.clone(),
503            registered_at: Utc::now(),
504            updated_at: Utc::now(),
505            client_secret_expires_at,
506            is_active: true,
507        };
508
509        // Store the client
510        self.store_client(&registered_client).await?;
511
512        // Build response
513        let response = ClientRegistrationResponse {
514            client_id: client_id.clone(),
515            client_secret,
516            registration_access_token,
517            registration_client_uri: format!("{}/register/{}", self.config.base_url, client_id),
518            client_id_issued_at: Some(Utc::now().timestamp()),
519            client_secret_expires_at: client_secret_expires_at.map(|dt| dt.timestamp()),
520            redirect_uris: request.redirect_uris,
521            token_endpoint_auth_method: request.token_endpoint_auth_method,
522            grant_types: request.grant_types,
523            response_types: request.response_types,
524            client_name: request.client_name,
525            client_uri: request.client_uri,
526            logo_uri: request.logo_uri,
527            scope: request.scope,
528            contacts: request.contacts,
529            tos_uri: request.tos_uri,
530            policy_uri: request.policy_uri,
531            jwks_uri: request.jwks_uri,
532            jwks: request.jwks,
533            software_id: request.software_id,
534            software_version: request.software_version,
535            additional_metadata: request.additional_metadata,
536        };
537
538        Ok(response)
539    }
540
541    /// Read client configuration
542    pub async fn read_client(
543        &self,
544        client_id: &str,
545        registration_access_token: &str,
546    ) -> Result<ClientRegistrationResponse> {
547        let client = self.get_client(client_id).await?;
548
549        // Verify registration access token
550        if !self.verify_registration_token(&client, registration_access_token)? {
551            return Err(AuthError::auth_method(
552                "client_registration",
553                "Invalid registration access token",
554            ));
555        }
556
557        self.client_to_response(&client)
558    }
559
560    /// Update client configuration
561    pub async fn update_client(
562        &self,
563        client_id: &str,
564        registration_access_token: &str,
565        request: ClientRegistrationRequest,
566    ) -> Result<ClientRegistrationResponse> {
567        let mut client = self.get_client(client_id).await?;
568
569        // Verify registration access token
570        if !self.verify_registration_token(&client, registration_access_token)? {
571            return Err(AuthError::auth_method(
572                "client_registration",
573                "Invalid registration access token",
574            ));
575        }
576
577        // Validate the update request
578        self.validate_registration_request(&request)?;
579
580        // Update client metadata
581        client.metadata = request;
582        client.updated_at = Utc::now();
583
584        // Store updated client
585        self.store_client(&client).await?;
586
587        self.client_to_response(&client)
588    }
589
590    /// Delete client
591    pub async fn delete_client(
592        &self,
593        client_id: &str,
594        registration_access_token: &str,
595    ) -> Result<()> {
596        let client = self.get_client(client_id).await?;
597
598        // Verify registration access token
599        if !self.verify_registration_token(&client, registration_access_token)? {
600            return Err(AuthError::auth_method(
601                "client_registration",
602                "Invalid registration access token",
603            ));
604        }
605
606        // Mark client as inactive
607        let key = format!("client_registration:{}", client_id);
608        self.storage.delete_kv(&key).await?;
609
610        Ok(())
611    }
612
613    /// Validate registration request
614    fn validate_registration_request(&self, request: &ClientRegistrationRequest) -> Result<()> {
615        // Validate redirect URIs
616        if let Some(redirect_uris) = &request.redirect_uris {
617            if redirect_uris.len() > self.config.max_redirect_uris {
618                return Err(AuthError::auth_method(
619                    "client_registration",
620                    "Too many redirect URIs",
621                ));
622            }
623
624            for uri in redirect_uris {
625                if !self.is_valid_uri(uri) {
626                    return Err(AuthError::auth_method(
627                        "client_registration",
628                        format!("Invalid redirect URI: {}", uri),
629                    ));
630                }
631            }
632        }
633
634        // Validate grant types
635        if let Some(grant_types) = &request.grant_types {
636            for grant_type in grant_types {
637                if !self.config.allowed_grant_types.contains(grant_type) {
638                    return Err(AuthError::auth_method(
639                        "client_registration",
640                        format!("Unsupported grant type: {}", grant_type),
641                    ));
642                }
643            }
644        }
645
646        // Validate response types
647        if let Some(response_types) = &request.response_types {
648            for response_type in response_types {
649                if !self.config.allowed_response_types.contains(response_type) {
650                    return Err(AuthError::auth_method(
651                        "client_registration",
652                        format!("Unsupported response type: {}", response_type),
653                    ));
654                }
655            }
656        }
657
658        // Validate authentication method
659        if let Some(auth_method) = &request.token_endpoint_auth_method
660            && !self.config.allowed_auth_methods.contains(auth_method)
661        {
662            return Err(AuthError::auth_method(
663                "client_registration",
664                format!("Unsupported authentication method: {}", auth_method),
665            ));
666        }
667
668        Ok(())
669    }
670
671    /// Check if client requires a secret
672    fn requires_client_secret(&self, request: &ClientRegistrationRequest) -> bool {
673        if !self.config.allow_public_clients {
674            return true;
675        }
676
677        !matches!(request.token_endpoint_auth_method.as_deref(), Some("none"))
678    }
679
680    /// Generate client ID
681    fn generate_client_id(&self) -> String {
682        format!("client_{}", Uuid::new_v4().simple())
683    }
684
685    /// Generate client secret
686    fn generate_client_secret(&self) -> String {
687        use rand::Rng;
688        let mut rng = rand::rng();
689        let mut bytes = [0u8; 32];
690        rng.fill_bytes(&mut bytes);
691        general_purpose::URL_SAFE_NO_PAD.encode(bytes)
692    }
693
694    /// Generate registration access token
695    fn generate_registration_access_token(&self) -> String {
696        use rand::Rng;
697        let mut rng = rand::rng();
698        let mut bytes = [0u8; 32];
699        rng.fill_bytes(&mut bytes);
700        general_purpose::URL_SAFE_NO_PAD.encode(bytes)
701    }
702
703    /// Hash a secret
704    fn hash_secret(&self, secret: &str) -> Result<String> {
705        use sha2::{Digest, Sha256};
706        let mut hasher = Sha256::new();
707        hasher.update(secret.as_bytes());
708        Ok(format!("{:x}", hasher.finalize()))
709    }
710
711    /// Verify registration access token
712    fn verify_registration_token(&self, client: &RegisteredClient, token: &str) -> Result<bool> {
713        use subtle::ConstantTimeEq;
714        let token_hash = self.hash_secret(token)?;
715        Ok(client
716            .registration_access_token_hash
717            .as_bytes()
718            .ct_eq(token_hash.as_bytes())
719            .into())
720    }
721
722    /// Validate URI — only HTTPS is allowed, with an exception for localhost
723    /// HTTP during development. Rejects dangerous schemes like `javascript:`,
724    /// `data:`, `file:`, etc.
725    fn is_valid_uri(&self, uri: &str) -> bool {
726        let parsed = match url::Url::parse(uri) {
727            Ok(u) => u,
728            Err(_) => return false,
729        };
730        match parsed.scheme() {
731            "https" => true,
732            "http" => {
733                // Allow plain HTTP only for loopback addresses (development)
734                matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
735            }
736            _ => false,
737        }
738    }
739
740    /// Store client in storage
741    async fn store_client(&self, client: &RegisteredClient) -> Result<()> {
742        let key = format!("client_registration:{}", client.client_id);
743        let value = serde_json::to_string(client)?;
744        self.storage.store_kv(&key, value.as_bytes(), None).await?;
745        Ok(())
746    }
747
748    /// Get client from storage
749    async fn get_client(&self, client_id: &str) -> Result<RegisteredClient> {
750        let key = format!("client_registration:{}", client_id);
751        let value = match self.storage.get_kv(&key).await? {
752            Some(value) => value,
753            None => {
754                return Err(AuthError::auth_method(
755                    "client_registration",
756                    "Client not found",
757                ));
758            }
759        };
760        let value_str = String::from_utf8(value).map_err(|e| {
761            AuthError::Storage(StorageError::Serialization {
762                message: format!("Invalid UTF-8 data: {}", e),
763            })
764        })?;
765        let client: RegisteredClient = serde_json::from_str(&value_str)?;
766        Ok(client)
767    }
768
769    /// Convert registered client to response
770    fn client_to_response(&self, client: &RegisteredClient) -> Result<ClientRegistrationResponse> {
771        Ok(ClientRegistrationResponse {
772            client_id: client.client_id.clone(),
773            client_secret: None, // Never return the actual secret
774            registration_access_token: "***".to_string(), // Never return the actual token
775            registration_client_uri: format!(
776                "{}/register/{}",
777                self.config.base_url, client.client_id
778            ),
779            client_id_issued_at: Some(client.registered_at.timestamp()),
780            client_secret_expires_at: client.client_secret_expires_at.map(|dt| dt.timestamp()),
781            redirect_uris: client.metadata.redirect_uris.clone(),
782            token_endpoint_auth_method: client.metadata.token_endpoint_auth_method.clone(),
783            grant_types: client.metadata.grant_types.clone(),
784            response_types: client.metadata.response_types.clone(),
785            client_name: client.metadata.client_name.clone(),
786            client_uri: client.metadata.client_uri.clone(),
787            logo_uri: client.metadata.logo_uri.clone(),
788            scope: client.metadata.scope.clone(),
789            contacts: client.metadata.contacts.clone(),
790            tos_uri: client.metadata.tos_uri.clone(),
791            policy_uri: client.metadata.policy_uri.clone(),
792            jwks_uri: client.metadata.jwks_uri.clone(),
793            jwks: client.metadata.jwks.clone(),
794            software_id: client.metadata.software_id.clone(),
795            software_version: client.metadata.software_version.clone(),
796            additional_metadata: client.metadata.additional_metadata.clone(),
797        })
798    }
799}
800
801#[cfg(test)]
802mod tests {
803    use super::*;
804    use crate::storage::MemoryStorage;
805
806    #[tokio::test]
807    async fn test_client_registration() {
808        let storage = Arc::new(MemoryStorage::new());
809        let config = ClientRegistrationConfig::default();
810        let manager = ClientRegistrationManager::new(config, storage);
811
812        let request = ClientRegistrationRequest::builder("https://client.example.com/callback")
813            .auth_method("client_secret_basic")
814            .grant_types(["authorization_code"])
815            .response_types(["code"])
816            .client_name("Test Client")
817            .client_uri("https://client.example.com")
818            .logo_uri("https://client.example.com/logo.png")
819            .scope("read write")
820            .contacts(["admin@client.example.com"])
821            .tos_uri("https://client.example.com/tos")
822            .policy_uri("https://client.example.com/privacy")
823            .jwks_uri("https://client.example.com/jwks")
824            .software("test-client", "1.0.0")
825            .build();
826
827        let response = manager
828            .register_client(request.clone(), None)
829            .await
830            .unwrap();
831
832        assert!(!response.client_id.is_empty());
833        assert!(response.client_secret.is_some());
834        assert!(!response.registration_access_token.is_empty());
835        assert_eq!(response.client_name, Some("Test Client".to_string()));
836        assert_eq!(
837            response.redirect_uris,
838            Some(vec!["https://client.example.com/callback".to_string()])
839        );
840    }
841
842    #[tokio::test]
843    async fn test_public_client_registration() {
844        let storage = Arc::new(MemoryStorage::new());
845        let config = ClientRegistrationConfig::default();
846        let manager = ClientRegistrationManager::new(config, storage);
847
848        let request = ClientRegistrationRequest::builder("https://client.example.com/callback")
849            .public_client()
850            .grant_types(["authorization_code"])
851            .response_types(["code"])
852            .client_name("Public Client")
853            .scope("read")
854            .build();
855
856        let response = manager.register_client(request, None).await.unwrap();
857
858        assert!(!response.client_id.is_empty());
859        assert!(response.client_secret.is_none()); // Public client should not have secret
860        assert!(!response.registration_access_token.is_empty());
861        assert_eq!(response.client_name, Some("Public Client".to_string()));
862    }
863
864    #[test]
865    fn test_client_registration_request_builder() {
866        let request = ClientRegistrationRequest::builder("https://client.example.com/callback")
867            .redirect_uris([
868                "https://client.example.com/callback",
869                "https://client.example.com/alt",
870            ])
871            .auth_method("private_key_jwt")
872            .grant_types(["authorization_code", "refresh_token"])
873            .response_types(["code"])
874            .client_name("Builder Client")
875            .metadata("tenant", serde_json::json!("acme"))
876            .build();
877
878        assert_eq!(request.redirect_uris.as_ref().map(Vec::len), Some(2));
879        assert_eq!(
880            request.token_endpoint_auth_method.as_deref(),
881            Some("private_key_jwt")
882        );
883        assert_eq!(request.additional_metadata["tenant"], "acme");
884    }
885}