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(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
336impl std::fmt::Debug for ClientRegistrationResponse {
337    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
338        let mut d = f.debug_struct("ClientRegistrationResponse");
339        d.field("client_id", &self.client_id);
340        d.field(
341            "client_secret",
342            &crate::utils::redact::redacted(&self.client_secret),
343        );
344        d.field("registration_access_token", &self.registration_access_token);
345        d.field("registration_client_uri", &self.registration_client_uri);
346        d.field("client_id_issued_at", &self.client_id_issued_at);
347        d.field("client_secret_expires_at", &self.client_secret_expires_at);
348        d.field("redirect_uris", &self.redirect_uris);
349        d.field(
350            "token_endpoint_auth_method",
351            &self.token_endpoint_auth_method,
352        );
353        d.field("grant_types", &self.grant_types);
354        d.field("response_types", &self.response_types);
355        d.field("client_name", &self.client_name);
356        d.field("client_uri", &self.client_uri);
357        d.field("logo_uri", &self.logo_uri);
358        d.field("scope", &self.scope);
359        d.field("contacts", &self.contacts);
360        d.field("tos_uri", &self.tos_uri);
361        d.field("policy_uri", &self.policy_uri);
362        d.field("jwks_uri", &self.jwks_uri);
363        d.field("jwks", &self.jwks);
364        d.field("software_id", &self.software_id);
365        d.field("software_version", &self.software_version);
366        d.field("additional_metadata", &self.additional_metadata);
367        d.finish()
368    }
369}
370
371/// Registered client information
372#[derive(Debug, Clone, Serialize, Deserialize)]
373pub struct RegisteredClient {
374    /// Client identifier
375    pub client_id: String,
376
377    /// Client secret (hashed)
378    pub client_secret_hash: Option<String>,
379
380    /// Registration access token (hashed)
381    pub registration_access_token_hash: String,
382
383    /// Client metadata
384    pub metadata: ClientRegistrationRequest,
385
386    /// Registration timestamp
387    pub registered_at: DateTime<Utc>,
388
389    /// Last updated timestamp
390    pub updated_at: DateTime<Utc>,
391
392    /// Client secret expiration
393    pub client_secret_expires_at: Option<DateTime<Utc>>,
394
395    /// Whether the client is active
396    pub is_active: bool,
397}
398
399/// Dynamic Client Registration Manager configuration
400#[derive(Debug, Clone)]
401pub struct ClientRegistrationConfig {
402    /// Base URL for registration endpoints
403    pub base_url: String,
404
405    /// Whether to require authentication for registration
406    pub require_authentication: bool,
407
408    /// Default client secret expiration (seconds)
409    pub default_secret_expiration: Option<i64>,
410
411    /// Maximum number of redirect URIs per client
412    pub max_redirect_uris: usize,
413
414    /// Allowed grant types
415    pub allowed_grant_types: Vec<String>,
416
417    /// Allowed response types
418    pub allowed_response_types: Vec<String>,
419
420    /// Allowed authentication methods
421    pub allowed_auth_methods: Vec<String>,
422
423    /// Whether to allow public clients
424    pub allow_public_clients: bool,
425
426    /// Rate limiting configuration
427    pub rate_limit_per_ip: u32,
428    pub rate_limit_window: std::time::Duration,
429}
430
431impl Default for ClientRegistrationConfig {
432    fn default() -> Self {
433        Self {
434            base_url: "https://auth.example.com".to_string(),
435            require_authentication: false,
436            default_secret_expiration: Some(86400 * 365), // 1 year
437            max_redirect_uris: 10,
438            allowed_grant_types: vec![
439                "authorization_code".to_string(),
440                "client_credentials".to_string(),
441                "refresh_token".to_string(),
442                "urn:ietf:params:oauth:grant-type:device_code".to_string(),
443            ],
444            allowed_response_types: vec![
445                "code".to_string(),
446                "token".to_string(),
447                "id_token".to_string(),
448            ],
449            allowed_auth_methods: vec![
450                "client_secret_basic".to_string(),
451                "client_secret_post".to_string(),
452                "private_key_jwt".to_string(),
453                "none".to_string(),
454            ],
455            allow_public_clients: true,
456            rate_limit_per_ip: 10,
457            rate_limit_window: std::time::Duration::from_secs(3600),
458        }
459    }
460}
461
462/// Dynamic Client Registration Manager
463pub struct ClientRegistrationManager {
464    config: ClientRegistrationConfig,
465    storage: Arc<dyn AuthStorage>,
466    rate_limiter: Arc<
467        governor::RateLimiter<
468            governor::state::direct::NotKeyed,
469            governor::state::InMemoryState,
470            governor::clock::DefaultClock,
471        >,
472    >,
473}
474
475impl ClientRegistrationManager {
476    /// Create a new client registration manager
477    pub fn new(config: ClientRegistrationConfig, storage: Arc<dyn AuthStorage>) -> Self {
478        let quota = governor::Quota::per_hour(
479            std::num::NonZeroU32::new(config.rate_limit_per_ip.max(1))
480                .expect("clamped to at least 1"),
481        );
482        let rate_limiter = Arc::new(governor::RateLimiter::direct(quota));
483
484        Self {
485            config,
486            storage,
487            rate_limiter,
488        }
489    }
490
491    /// Register a new client
492    pub async fn register_client(
493        &self,
494        request: ClientRegistrationRequest,
495        client_ip: Option<std::net::IpAddr>,
496    ) -> Result<ClientRegistrationResponse> {
497        // Rate limiting
498        if let Some(_ip) = client_ip
499            && self.rate_limiter.check().is_err()
500        {
501            return Err(AuthError::rate_limit(
502                "Client registration rate limit exceeded",
503            ));
504        }
505
506        // Validate the registration request
507        self.validate_registration_request(&request)?;
508
509        // Generate client credentials
510        let client_id = self.generate_client_id();
511        let (client_secret, client_secret_hash) = if self.requires_client_secret(&request) {
512            let secret = self.generate_client_secret();
513            let hash = self.hash_secret(&secret)?;
514            (Some(secret), Some(hash))
515        } else {
516            (None, None)
517        };
518
519        // Generate registration access token
520        let registration_access_token = self.generate_registration_access_token();
521        let registration_access_token_hash = self.hash_secret(&registration_access_token)?;
522
523        // Calculate expiration
524        let client_secret_expires_at = if client_secret.is_some() {
525            self.config
526                .default_secret_expiration
527                .map(|seconds| Utc::now() + Duration::seconds(seconds))
528        } else {
529            None
530        };
531
532        // Create registered client
533        let registered_client = RegisteredClient {
534            client_id: client_id.clone(),
535            client_secret_hash,
536            registration_access_token_hash,
537            metadata: request.clone(),
538            registered_at: Utc::now(),
539            updated_at: Utc::now(),
540            client_secret_expires_at,
541            is_active: true,
542        };
543
544        // Store the client
545        self.store_client(&registered_client).await?;
546
547        // Build response
548        let response = ClientRegistrationResponse {
549            client_id: client_id.clone(),
550            client_secret,
551            registration_access_token,
552            registration_client_uri: format!("{}/register/{}", self.config.base_url, client_id),
553            client_id_issued_at: Some(Utc::now().timestamp()),
554            client_secret_expires_at: client_secret_expires_at.map(|dt| dt.timestamp()),
555            redirect_uris: request.redirect_uris,
556            token_endpoint_auth_method: request.token_endpoint_auth_method,
557            grant_types: request.grant_types,
558            response_types: request.response_types,
559            client_name: request.client_name,
560            client_uri: request.client_uri,
561            logo_uri: request.logo_uri,
562            scope: request.scope,
563            contacts: request.contacts,
564            tos_uri: request.tos_uri,
565            policy_uri: request.policy_uri,
566            jwks_uri: request.jwks_uri,
567            jwks: request.jwks,
568            software_id: request.software_id,
569            software_version: request.software_version,
570            additional_metadata: request.additional_metadata,
571        };
572
573        Ok(response)
574    }
575
576    /// Read client configuration
577    pub async fn read_client(
578        &self,
579        client_id: &str,
580        registration_access_token: &str,
581    ) -> Result<ClientRegistrationResponse> {
582        let client = self.get_client(client_id).await?;
583
584        // Verify registration access token
585        if !self.verify_registration_token(&client, registration_access_token)? {
586            return Err(AuthError::auth_method(
587                "client_registration",
588                "Invalid registration access token",
589            ));
590        }
591
592        self.client_to_response(&client)
593    }
594
595    /// Update client configuration
596    pub async fn update_client(
597        &self,
598        client_id: &str,
599        registration_access_token: &str,
600        request: ClientRegistrationRequest,
601    ) -> Result<ClientRegistrationResponse> {
602        let mut client = self.get_client(client_id).await?;
603
604        // Verify registration access token
605        if !self.verify_registration_token(&client, registration_access_token)? {
606            return Err(AuthError::auth_method(
607                "client_registration",
608                "Invalid registration access token",
609            ));
610        }
611
612        // Validate the update request
613        self.validate_registration_request(&request)?;
614
615        // Update client metadata
616        client.metadata = request;
617        client.updated_at = Utc::now();
618
619        // Store updated client
620        self.store_client(&client).await?;
621
622        self.client_to_response(&client)
623    }
624
625    /// Delete client
626    pub async fn delete_client(
627        &self,
628        client_id: &str,
629        registration_access_token: &str,
630    ) -> Result<()> {
631        let client = self.get_client(client_id).await?;
632
633        // Verify registration access token
634        if !self.verify_registration_token(&client, registration_access_token)? {
635            return Err(AuthError::auth_method(
636                "client_registration",
637                "Invalid registration access token",
638            ));
639        }
640
641        // Mark client as inactive
642        let key = format!("client_registration:{}", client_id);
643        self.storage.delete_kv(&key).await?;
644
645        Ok(())
646    }
647
648    /// Validate registration request
649    fn validate_registration_request(&self, request: &ClientRegistrationRequest) -> Result<()> {
650        // Validate redirect URIs
651        if let Some(redirect_uris) = &request.redirect_uris {
652            if redirect_uris.len() > self.config.max_redirect_uris {
653                return Err(AuthError::auth_method(
654                    "client_registration",
655                    "Too many redirect URIs",
656                ));
657            }
658
659            for uri in redirect_uris {
660                if !self.is_valid_uri(uri) {
661                    return Err(AuthError::auth_method(
662                        "client_registration",
663                        format!("Invalid redirect URI: {}", uri),
664                    ));
665                }
666            }
667        }
668
669        // Validate grant types
670        if let Some(grant_types) = &request.grant_types {
671            for grant_type in grant_types {
672                if !self.config.allowed_grant_types.contains(grant_type) {
673                    return Err(AuthError::auth_method(
674                        "client_registration",
675                        format!("Unsupported grant type: {}", grant_type),
676                    ));
677                }
678            }
679        }
680
681        // Validate response types
682        if let Some(response_types) = &request.response_types {
683            for response_type in response_types {
684                if !self.config.allowed_response_types.contains(response_type) {
685                    return Err(AuthError::auth_method(
686                        "client_registration",
687                        format!("Unsupported response type: {}", response_type),
688                    ));
689                }
690            }
691        }
692
693        // Validate authentication method
694        if let Some(auth_method) = &request.token_endpoint_auth_method
695            && !self.config.allowed_auth_methods.contains(auth_method)
696        {
697            return Err(AuthError::auth_method(
698                "client_registration",
699                format!("Unsupported authentication method: {}", auth_method),
700            ));
701        }
702
703        Ok(())
704    }
705
706    /// Check if client requires a secret
707    fn requires_client_secret(&self, request: &ClientRegistrationRequest) -> bool {
708        if !self.config.allow_public_clients {
709            return true;
710        }
711
712        !matches!(request.token_endpoint_auth_method.as_deref(), Some("none"))
713    }
714
715    /// Generate client ID
716    fn generate_client_id(&self) -> String {
717        format!("client_{}", Uuid::new_v4().simple())
718    }
719
720    /// Generate client secret
721    fn generate_client_secret(&self) -> String {
722        use rand::Rng;
723        let mut rng = rand::rng();
724        let mut bytes = [0u8; 32];
725        rng.fill_bytes(&mut bytes);
726        general_purpose::URL_SAFE_NO_PAD.encode(bytes)
727    }
728
729    /// Generate registration access token
730    fn generate_registration_access_token(&self) -> String {
731        use rand::Rng;
732        let mut rng = rand::rng();
733        let mut bytes = [0u8; 32];
734        rng.fill_bytes(&mut bytes);
735        general_purpose::URL_SAFE_NO_PAD.encode(bytes)
736    }
737
738    /// Hash a secret
739    fn hash_secret(&self, secret: &str) -> Result<String> {
740        use sha2::{Digest, Sha256};
741        let mut hasher = Sha256::new();
742        hasher.update(secret.as_bytes());
743        Ok(format!("{:x}", hasher.finalize()))
744    }
745
746    /// Verify registration access token
747    fn verify_registration_token(&self, client: &RegisteredClient, token: &str) -> Result<bool> {
748        use subtle::ConstantTimeEq;
749        let token_hash = self.hash_secret(token)?;
750        Ok(client
751            .registration_access_token_hash
752            .as_bytes()
753            .ct_eq(token_hash.as_bytes())
754            .into())
755    }
756
757    /// Validate URI — only HTTPS is allowed, with an exception for localhost
758    /// HTTP during development. Rejects dangerous schemes like `javascript:`,
759    /// `data:`, `file:`, etc.
760    fn is_valid_uri(&self, uri: &str) -> bool {
761        let parsed = match url::Url::parse(uri) {
762            Ok(u) => u,
763            Err(_) => return false,
764        };
765        match parsed.scheme() {
766            "https" => true,
767            "http" => {
768                // Allow plain HTTP only for loopback addresses (development)
769                matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
770            }
771            _ => false,
772        }
773    }
774
775    /// Store client in storage
776    async fn store_client(&self, client: &RegisteredClient) -> Result<()> {
777        let key = format!("client_registration:{}", client.client_id);
778        let value = serde_json::to_string(client)?;
779        self.storage.store_kv(&key, value.as_bytes(), None).await?;
780        Ok(())
781    }
782
783    /// Get client from storage
784    async fn get_client(&self, client_id: &str) -> Result<RegisteredClient> {
785        let key = format!("client_registration:{}", client_id);
786        let value = match self.storage.get_kv(&key).await? {
787            Some(value) => value,
788            None => {
789                return Err(AuthError::auth_method(
790                    "client_registration",
791                    "Client not found",
792                ));
793            }
794        };
795        let value_str = String::from_utf8(value).map_err(|e| {
796            AuthError::Storage(StorageError::Serialization {
797                message: format!("Invalid UTF-8 data: {}", e),
798            })
799        })?;
800        let client: RegisteredClient = serde_json::from_str(&value_str)?;
801        Ok(client)
802    }
803
804    /// Convert registered client to response
805    fn client_to_response(&self, client: &RegisteredClient) -> Result<ClientRegistrationResponse> {
806        Ok(ClientRegistrationResponse {
807            client_id: client.client_id.clone(),
808            client_secret: None, // Never return the actual secret
809            registration_access_token: "***".to_string(), // Never return the actual token
810            registration_client_uri: format!(
811                "{}/register/{}",
812                self.config.base_url, client.client_id
813            ),
814            client_id_issued_at: Some(client.registered_at.timestamp()),
815            client_secret_expires_at: client.client_secret_expires_at.map(|dt| dt.timestamp()),
816            redirect_uris: client.metadata.redirect_uris.clone(),
817            token_endpoint_auth_method: client.metadata.token_endpoint_auth_method.clone(),
818            grant_types: client.metadata.grant_types.clone(),
819            response_types: client.metadata.response_types.clone(),
820            client_name: client.metadata.client_name.clone(),
821            client_uri: client.metadata.client_uri.clone(),
822            logo_uri: client.metadata.logo_uri.clone(),
823            scope: client.metadata.scope.clone(),
824            contacts: client.metadata.contacts.clone(),
825            tos_uri: client.metadata.tos_uri.clone(),
826            policy_uri: client.metadata.policy_uri.clone(),
827            jwks_uri: client.metadata.jwks_uri.clone(),
828            jwks: client.metadata.jwks.clone(),
829            software_id: client.metadata.software_id.clone(),
830            software_version: client.metadata.software_version.clone(),
831            additional_metadata: client.metadata.additional_metadata.clone(),
832        })
833    }
834}
835
836#[cfg(test)]
837mod tests {
838    use super::*;
839    use crate::storage::MemoryStorage;
840
841    #[tokio::test]
842    async fn test_client_registration() {
843        let storage = Arc::new(MemoryStorage::new());
844        let config = ClientRegistrationConfig::default();
845        let manager = ClientRegistrationManager::new(config, storage);
846
847        let request = ClientRegistrationRequest::builder("https://client.example.com/callback")
848            .auth_method("client_secret_basic")
849            .grant_types(["authorization_code"])
850            .response_types(["code"])
851            .client_name("Test Client")
852            .client_uri("https://client.example.com")
853            .logo_uri("https://client.example.com/logo.png")
854            .scope("read write")
855            .contacts(["admin@client.example.com"])
856            .tos_uri("https://client.example.com/tos")
857            .policy_uri("https://client.example.com/privacy")
858            .jwks_uri("https://client.example.com/jwks")
859            .software("test-client", "1.0.0")
860            .build();
861
862        let response = manager
863            .register_client(request.clone(), None)
864            .await
865            .unwrap();
866
867        assert!(!response.client_id.is_empty());
868        assert!(response.client_secret.is_some());
869        assert!(!response.registration_access_token.is_empty());
870        assert_eq!(response.client_name, Some("Test Client".to_string()));
871        assert_eq!(
872            response.redirect_uris,
873            Some(vec!["https://client.example.com/callback".to_string()])
874        );
875    }
876
877    #[tokio::test]
878    async fn test_public_client_registration() {
879        let storage = Arc::new(MemoryStorage::new());
880        let config = ClientRegistrationConfig::default();
881        let manager = ClientRegistrationManager::new(config, storage);
882
883        let request = ClientRegistrationRequest::builder("https://client.example.com/callback")
884            .public_client()
885            .grant_types(["authorization_code"])
886            .response_types(["code"])
887            .client_name("Public Client")
888            .scope("read")
889            .build();
890
891        let response = manager.register_client(request, None).await.unwrap();
892
893        assert!(!response.client_id.is_empty());
894        assert!(response.client_secret.is_none()); // Public client should not have secret
895        assert!(!response.registration_access_token.is_empty());
896        assert_eq!(response.client_name, Some("Public Client".to_string()));
897    }
898
899    #[test]
900    fn test_client_registration_request_builder() {
901        let request = ClientRegistrationRequest::builder("https://client.example.com/callback")
902            .redirect_uris([
903                "https://client.example.com/callback",
904                "https://client.example.com/alt",
905            ])
906            .auth_method("private_key_jwt")
907            .grant_types(["authorization_code", "refresh_token"])
908            .response_types(["code"])
909            .client_name("Builder Client")
910            .metadata("tenant", serde_json::json!("acme"))
911            .build();
912
913        assert_eq!(request.redirect_uris.as_ref().map(Vec::len), Some(2));
914        assert_eq!(
915            request.token_endpoint_auth_method.as_deref(),
916            Some("private_key_jwt")
917        );
918        assert_eq!(request.additional_metadata["tenant"], "acme");
919    }
920}