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