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