1use 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#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct ClientRegistrationRequest {
31 pub redirect_uris: Option<Vec<String>>,
33
34 pub token_endpoint_auth_method: Option<String>,
36
37 pub grant_types: Option<Vec<String>>,
39
40 pub response_types: Option<Vec<String>>,
42
43 pub client_name: Option<String>,
45
46 pub client_uri: Option<String>,
48
49 pub logo_uri: Option<String>,
51
52 pub scope: Option<String>,
54
55 pub contacts: Option<Vec<String>>,
57
58 pub tos_uri: Option<String>,
60
61 pub policy_uri: Option<String>,
63
64 pub jwks_uri: Option<String>,
66
67 pub jwks: Option<Value>,
69
70 pub software_id: Option<String>,
72
73 pub software_version: Option<String>,
75
76 #[serde(flatten)]
78 pub additional_metadata: HashMap<String, Value>,
79}
80
81impl ClientRegistrationRequest {
82 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
105pub 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 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 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 pub fn public_client(self) -> Self {
144 self.auth_method("none")
145 }
146
147 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 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 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 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 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 pub fn scope(mut self, scope: impl Into<String>) -> Self {
187 self.scope = Some(scope.into());
188 self
189 }
190
191 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 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 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 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 pub fn jwks(mut self, jwks: Value) -> Self {
221 self.jwks = Some(jwks);
222 self
223 }
224
225 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 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
267pub struct ClientRegistrationResponse {
268 pub client_id: String,
270
271 pub client_secret: Option<String>,
273
274 pub registration_access_token: String,
276
277 pub registration_client_uri: String,
279
280 pub client_id_issued_at: Option<i64>,
282
283 pub client_secret_expires_at: Option<i64>,
285
286 pub redirect_uris: Option<Vec<String>>,
288
289 pub token_endpoint_auth_method: Option<String>,
291
292 pub grant_types: Option<Vec<String>>,
294
295 pub response_types: Option<Vec<String>>,
297
298 pub client_name: Option<String>,
300
301 pub client_uri: Option<String>,
303
304 pub logo_uri: Option<String>,
306
307 pub scope: Option<String>,
309
310 pub contacts: Option<Vec<String>>,
312
313 pub tos_uri: Option<String>,
315
316 pub policy_uri: Option<String>,
318
319 pub jwks_uri: Option<String>,
321
322 pub jwks: Option<Value>,
324
325 pub software_id: Option<String>,
327
328 pub software_version: Option<String>,
330
331 #[serde(flatten)]
333 pub additional_metadata: HashMap<String, Value>,
334}
335
336#[derive(Debug, Clone, Serialize, Deserialize)]
338pub struct RegisteredClient {
339 pub client_id: String,
341
342 pub client_secret_hash: Option<String>,
344
345 pub registration_access_token_hash: String,
347
348 pub metadata: ClientRegistrationRequest,
350
351 pub registered_at: DateTime<Utc>,
353
354 pub updated_at: DateTime<Utc>,
356
357 pub client_secret_expires_at: Option<DateTime<Utc>>,
359
360 pub is_active: bool,
362}
363
364#[derive(Debug, Clone)]
366pub struct ClientRegistrationConfig {
367 pub base_url: String,
369
370 pub require_authentication: bool,
372
373 pub default_secret_expiration: Option<i64>,
375
376 pub max_redirect_uris: usize,
378
379 pub allowed_grant_types: Vec<String>,
381
382 pub allowed_response_types: Vec<String>,
384
385 pub allowed_auth_methods: Vec<String>,
387
388 pub allow_public_clients: bool,
390
391 pub rate_limit_per_ip: u32,
393 pub rate_limit_window: std::time::Duration,
394}
395
396impl Default for ClientRegistrationConfig {
397 fn default() -> Self {
398 Self {
399 base_url: "https://auth.example.com".to_string(),
400 require_authentication: false,
401 default_secret_expiration: Some(86400 * 365), max_redirect_uris: 10,
403 allowed_grant_types: vec![
404 "authorization_code".to_string(),
405 "client_credentials".to_string(),
406 "refresh_token".to_string(),
407 "urn:ietf:params:oauth:grant-type:device_code".to_string(),
408 ],
409 allowed_response_types: vec![
410 "code".to_string(),
411 "token".to_string(),
412 "id_token".to_string(),
413 ],
414 allowed_auth_methods: vec![
415 "client_secret_basic".to_string(),
416 "client_secret_post".to_string(),
417 "private_key_jwt".to_string(),
418 "none".to_string(),
419 ],
420 allow_public_clients: true,
421 rate_limit_per_ip: 10,
422 rate_limit_window: std::time::Duration::from_secs(3600),
423 }
424 }
425}
426
427pub struct ClientRegistrationManager {
429 config: ClientRegistrationConfig,
430 storage: Arc<dyn AuthStorage>,
431 rate_limiter: Arc<
432 governor::RateLimiter<
433 governor::state::direct::NotKeyed,
434 governor::state::InMemoryState,
435 governor::clock::DefaultClock,
436 >,
437 >,
438}
439
440impl ClientRegistrationManager {
441 pub fn new(config: ClientRegistrationConfig, storage: Arc<dyn AuthStorage>) -> Self {
443 let quota = governor::Quota::per_hour(
444 std::num::NonZeroU32::new(config.rate_limit_per_ip.max(1))
445 .expect("clamped to at least 1"),
446 );
447 let rate_limiter = Arc::new(governor::RateLimiter::direct(quota));
448
449 Self {
450 config,
451 storage,
452 rate_limiter,
453 }
454 }
455
456 pub async fn register_client(
458 &self,
459 request: ClientRegistrationRequest,
460 client_ip: Option<std::net::IpAddr>,
461 ) -> Result<ClientRegistrationResponse> {
462 if let Some(_ip) = client_ip
464 && self.rate_limiter.check().is_err()
465 {
466 return Err(AuthError::rate_limit(
467 "Client registration rate limit exceeded",
468 ));
469 }
470
471 self.validate_registration_request(&request)?;
473
474 let client_id = self.generate_client_id();
476 let (client_secret, client_secret_hash) = if self.requires_client_secret(&request) {
477 let secret = self.generate_client_secret();
478 let hash = self.hash_secret(&secret)?;
479 (Some(secret), Some(hash))
480 } else {
481 (None, None)
482 };
483
484 let registration_access_token = self.generate_registration_access_token();
486 let registration_access_token_hash = self.hash_secret(®istration_access_token)?;
487
488 let client_secret_expires_at = if client_secret.is_some() {
490 self.config
491 .default_secret_expiration
492 .map(|seconds| Utc::now() + Duration::seconds(seconds))
493 } else {
494 None
495 };
496
497 let registered_client = RegisteredClient {
499 client_id: client_id.clone(),
500 client_secret_hash,
501 registration_access_token_hash,
502 metadata: request.clone(),
503 registered_at: Utc::now(),
504 updated_at: Utc::now(),
505 client_secret_expires_at,
506 is_active: true,
507 };
508
509 self.store_client(®istered_client).await?;
511
512 let response = ClientRegistrationResponse {
514 client_id: client_id.clone(),
515 client_secret,
516 registration_access_token,
517 registration_client_uri: format!("{}/register/{}", self.config.base_url, client_id),
518 client_id_issued_at: Some(Utc::now().timestamp()),
519 client_secret_expires_at: client_secret_expires_at.map(|dt| dt.timestamp()),
520 redirect_uris: request.redirect_uris,
521 token_endpoint_auth_method: request.token_endpoint_auth_method,
522 grant_types: request.grant_types,
523 response_types: request.response_types,
524 client_name: request.client_name,
525 client_uri: request.client_uri,
526 logo_uri: request.logo_uri,
527 scope: request.scope,
528 contacts: request.contacts,
529 tos_uri: request.tos_uri,
530 policy_uri: request.policy_uri,
531 jwks_uri: request.jwks_uri,
532 jwks: request.jwks,
533 software_id: request.software_id,
534 software_version: request.software_version,
535 additional_metadata: request.additional_metadata,
536 };
537
538 Ok(response)
539 }
540
541 pub async fn read_client(
543 &self,
544 client_id: &str,
545 registration_access_token: &str,
546 ) -> Result<ClientRegistrationResponse> {
547 let client = self.get_client(client_id).await?;
548
549 if !self.verify_registration_token(&client, registration_access_token)? {
551 return Err(AuthError::auth_method(
552 "client_registration",
553 "Invalid registration access token",
554 ));
555 }
556
557 self.client_to_response(&client)
558 }
559
560 pub async fn update_client(
562 &self,
563 client_id: &str,
564 registration_access_token: &str,
565 request: ClientRegistrationRequest,
566 ) -> Result<ClientRegistrationResponse> {
567 let mut client = self.get_client(client_id).await?;
568
569 if !self.verify_registration_token(&client, registration_access_token)? {
571 return Err(AuthError::auth_method(
572 "client_registration",
573 "Invalid registration access token",
574 ));
575 }
576
577 self.validate_registration_request(&request)?;
579
580 client.metadata = request;
582 client.updated_at = Utc::now();
583
584 self.store_client(&client).await?;
586
587 self.client_to_response(&client)
588 }
589
590 pub async fn delete_client(
592 &self,
593 client_id: &str,
594 registration_access_token: &str,
595 ) -> Result<()> {
596 let client = self.get_client(client_id).await?;
597
598 if !self.verify_registration_token(&client, registration_access_token)? {
600 return Err(AuthError::auth_method(
601 "client_registration",
602 "Invalid registration access token",
603 ));
604 }
605
606 let key = format!("client_registration:{}", client_id);
608 self.storage.delete_kv(&key).await?;
609
610 Ok(())
611 }
612
613 fn validate_registration_request(&self, request: &ClientRegistrationRequest) -> Result<()> {
615 if let Some(redirect_uris) = &request.redirect_uris {
617 if redirect_uris.len() > self.config.max_redirect_uris {
618 return Err(AuthError::auth_method(
619 "client_registration",
620 "Too many redirect URIs",
621 ));
622 }
623
624 for uri in redirect_uris {
625 if !self.is_valid_uri(uri) {
626 return Err(AuthError::auth_method(
627 "client_registration",
628 format!("Invalid redirect URI: {}", uri),
629 ));
630 }
631 }
632 }
633
634 if let Some(grant_types) = &request.grant_types {
636 for grant_type in grant_types {
637 if !self.config.allowed_grant_types.contains(grant_type) {
638 return Err(AuthError::auth_method(
639 "client_registration",
640 format!("Unsupported grant type: {}", grant_type),
641 ));
642 }
643 }
644 }
645
646 if let Some(response_types) = &request.response_types {
648 for response_type in response_types {
649 if !self.config.allowed_response_types.contains(response_type) {
650 return Err(AuthError::auth_method(
651 "client_registration",
652 format!("Unsupported response type: {}", response_type),
653 ));
654 }
655 }
656 }
657
658 if let Some(auth_method) = &request.token_endpoint_auth_method
660 && !self.config.allowed_auth_methods.contains(auth_method)
661 {
662 return Err(AuthError::auth_method(
663 "client_registration",
664 format!("Unsupported authentication method: {}", auth_method),
665 ));
666 }
667
668 Ok(())
669 }
670
671 fn requires_client_secret(&self, request: &ClientRegistrationRequest) -> bool {
673 if !self.config.allow_public_clients {
674 return true;
675 }
676
677 !matches!(request.token_endpoint_auth_method.as_deref(), Some("none"))
678 }
679
680 fn generate_client_id(&self) -> String {
682 format!("client_{}", Uuid::new_v4().simple())
683 }
684
685 fn generate_client_secret(&self) -> String {
687 use rand::Rng;
688 let mut rng = rand::rng();
689 let mut bytes = [0u8; 32];
690 rng.fill_bytes(&mut bytes);
691 general_purpose::URL_SAFE_NO_PAD.encode(bytes)
692 }
693
694 fn generate_registration_access_token(&self) -> String {
696 use rand::Rng;
697 let mut rng = rand::rng();
698 let mut bytes = [0u8; 32];
699 rng.fill_bytes(&mut bytes);
700 general_purpose::URL_SAFE_NO_PAD.encode(bytes)
701 }
702
703 fn hash_secret(&self, secret: &str) -> Result<String> {
705 use sha2::{Digest, Sha256};
706 let mut hasher = Sha256::new();
707 hasher.update(secret.as_bytes());
708 Ok(format!("{:x}", hasher.finalize()))
709 }
710
711 fn verify_registration_token(&self, client: &RegisteredClient, token: &str) -> Result<bool> {
713 use subtle::ConstantTimeEq;
714 let token_hash = self.hash_secret(token)?;
715 Ok(client
716 .registration_access_token_hash
717 .as_bytes()
718 .ct_eq(token_hash.as_bytes())
719 .into())
720 }
721
722 fn is_valid_uri(&self, uri: &str) -> bool {
726 let parsed = match url::Url::parse(uri) {
727 Ok(u) => u,
728 Err(_) => return false,
729 };
730 match parsed.scheme() {
731 "https" => true,
732 "http" => {
733 matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
735 }
736 _ => false,
737 }
738 }
739
740 async fn store_client(&self, client: &RegisteredClient) -> Result<()> {
742 let key = format!("client_registration:{}", client.client_id);
743 let value = serde_json::to_string(client)?;
744 self.storage.store_kv(&key, value.as_bytes(), None).await?;
745 Ok(())
746 }
747
748 async fn get_client(&self, client_id: &str) -> Result<RegisteredClient> {
750 let key = format!("client_registration:{}", client_id);
751 let value = match self.storage.get_kv(&key).await? {
752 Some(value) => value,
753 None => {
754 return Err(AuthError::auth_method(
755 "client_registration",
756 "Client not found",
757 ));
758 }
759 };
760 let value_str = String::from_utf8(value).map_err(|e| {
761 AuthError::Storage(StorageError::Serialization {
762 message: format!("Invalid UTF-8 data: {}", e),
763 })
764 })?;
765 let client: RegisteredClient = serde_json::from_str(&value_str)?;
766 Ok(client)
767 }
768
769 fn client_to_response(&self, client: &RegisteredClient) -> Result<ClientRegistrationResponse> {
771 Ok(ClientRegistrationResponse {
772 client_id: client.client_id.clone(),
773 client_secret: None, registration_access_token: "***".to_string(), registration_client_uri: format!(
776 "{}/register/{}",
777 self.config.base_url, client.client_id
778 ),
779 client_id_issued_at: Some(client.registered_at.timestamp()),
780 client_secret_expires_at: client.client_secret_expires_at.map(|dt| dt.timestamp()),
781 redirect_uris: client.metadata.redirect_uris.clone(),
782 token_endpoint_auth_method: client.metadata.token_endpoint_auth_method.clone(),
783 grant_types: client.metadata.grant_types.clone(),
784 response_types: client.metadata.response_types.clone(),
785 client_name: client.metadata.client_name.clone(),
786 client_uri: client.metadata.client_uri.clone(),
787 logo_uri: client.metadata.logo_uri.clone(),
788 scope: client.metadata.scope.clone(),
789 contacts: client.metadata.contacts.clone(),
790 tos_uri: client.metadata.tos_uri.clone(),
791 policy_uri: client.metadata.policy_uri.clone(),
792 jwks_uri: client.metadata.jwks_uri.clone(),
793 jwks: client.metadata.jwks.clone(),
794 software_id: client.metadata.software_id.clone(),
795 software_version: client.metadata.software_version.clone(),
796 additional_metadata: client.metadata.additional_metadata.clone(),
797 })
798 }
799}
800
801#[cfg(test)]
802mod tests {
803 use super::*;
804 use crate::storage::MemoryStorage;
805
806 #[tokio::test]
807 async fn test_client_registration() {
808 let storage = Arc::new(MemoryStorage::new());
809 let config = ClientRegistrationConfig::default();
810 let manager = ClientRegistrationManager::new(config, storage);
811
812 let request = ClientRegistrationRequest::builder("https://client.example.com/callback")
813 .auth_method("client_secret_basic")
814 .grant_types(["authorization_code"])
815 .response_types(["code"])
816 .client_name("Test Client")
817 .client_uri("https://client.example.com")
818 .logo_uri("https://client.example.com/logo.png")
819 .scope("read write")
820 .contacts(["admin@client.example.com"])
821 .tos_uri("https://client.example.com/tos")
822 .policy_uri("https://client.example.com/privacy")
823 .jwks_uri("https://client.example.com/jwks")
824 .software("test-client", "1.0.0")
825 .build();
826
827 let response = manager
828 .register_client(request.clone(), None)
829 .await
830 .unwrap();
831
832 assert!(!response.client_id.is_empty());
833 assert!(response.client_secret.is_some());
834 assert!(!response.registration_access_token.is_empty());
835 assert_eq!(response.client_name, Some("Test Client".to_string()));
836 assert_eq!(
837 response.redirect_uris,
838 Some(vec!["https://client.example.com/callback".to_string()])
839 );
840 }
841
842 #[tokio::test]
843 async fn test_public_client_registration() {
844 let storage = Arc::new(MemoryStorage::new());
845 let config = ClientRegistrationConfig::default();
846 let manager = ClientRegistrationManager::new(config, storage);
847
848 let request = ClientRegistrationRequest::builder("https://client.example.com/callback")
849 .public_client()
850 .grant_types(["authorization_code"])
851 .response_types(["code"])
852 .client_name("Public Client")
853 .scope("read")
854 .build();
855
856 let response = manager.register_client(request, None).await.unwrap();
857
858 assert!(!response.client_id.is_empty());
859 assert!(response.client_secret.is_none()); assert!(!response.registration_access_token.is_empty());
861 assert_eq!(response.client_name, Some("Public Client".to_string()));
862 }
863
864 #[test]
865 fn test_client_registration_request_builder() {
866 let request = ClientRegistrationRequest::builder("https://client.example.com/callback")
867 .redirect_uris([
868 "https://client.example.com/callback",
869 "https://client.example.com/alt",
870 ])
871 .auth_method("private_key_jwt")
872 .grant_types(["authorization_code", "refresh_token"])
873 .response_types(["code"])
874 .client_name("Builder Client")
875 .metadata("tenant", serde_json::json!("acme"))
876 .build();
877
878 assert_eq!(request.redirect_uris.as_ref().map(Vec::len), Some(2));
879 assert_eq!(
880 request.token_endpoint_auth_method.as_deref(),
881 Some("private_key_jwt")
882 );
883 assert_eq!(request.additional_metadata["tenant"], "acme");
884 }
885}