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
81#[derive(Clone, Serialize, Deserialize)]
83pub struct ClientRegistrationResponse {
84 pub client_id: String,
86
87 pub client_secret: Option<String>,
89
90 pub registration_access_token: String,
92
93 pub registration_client_uri: String,
95
96 pub client_id_issued_at: Option<i64>,
98
99 pub client_secret_expires_at: Option<i64>,
101
102 pub redirect_uris: Option<Vec<String>>,
104
105 pub token_endpoint_auth_method: Option<String>,
107
108 pub grant_types: Option<Vec<String>>,
110
111 pub response_types: Option<Vec<String>>,
113
114 pub client_name: Option<String>,
116
117 pub client_uri: Option<String>,
119
120 pub logo_uri: Option<String>,
122
123 pub scope: Option<String>,
125
126 pub contacts: Option<Vec<String>>,
128
129 pub tos_uri: Option<String>,
131
132 pub policy_uri: Option<String>,
134
135 pub jwks_uri: Option<String>,
137
138 pub jwks: Option<Value>,
140
141 pub software_id: Option<String>,
143
144 pub software_version: Option<String>,
146
147 #[serde(flatten)]
149 pub additional_metadata: HashMap<String, Value>,
150}
151
152impl std::fmt::Debug for ClientRegistrationResponse {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 let mut d = f.debug_struct("ClientRegistrationResponse");
155 d.field("client_id", &self.client_id);
156 d.field(
157 "client_secret",
158 &crate::utils::redact::redacted(&self.client_secret),
159 );
160 d.field(
161 "registration_access_token",
162 &crate::utils::redact::redacted(&self.registration_access_token),
163 );
164 d.field("registration_client_uri", &self.registration_client_uri);
165 d.field("client_id_issued_at", &self.client_id_issued_at);
166 d.field("client_secret_expires_at", &self.client_secret_expires_at);
167 d.field("redirect_uris", &self.redirect_uris);
168 d.field(
169 "token_endpoint_auth_method",
170 &self.token_endpoint_auth_method,
171 );
172 d.field("grant_types", &self.grant_types);
173 d.field("response_types", &self.response_types);
174 d.field("client_name", &self.client_name);
175 d.field("client_uri", &self.client_uri);
176 d.field("logo_uri", &self.logo_uri);
177 d.field("scope", &self.scope);
178 d.field("contacts", &self.contacts);
179 d.field("tos_uri", &self.tos_uri);
180 d.field("policy_uri", &self.policy_uri);
181 d.field("jwks_uri", &self.jwks_uri);
182 d.field("jwks", &self.jwks);
183 d.field("software_id", &self.software_id);
184 d.field("software_version", &self.software_version);
185 d.field("additional_metadata", &self.additional_metadata);
186 d.finish()
187 }
188}
189
190#[derive(Clone, Serialize, Deserialize)]
192pub struct RegisteredClient {
193 pub client_id: String,
195
196 pub client_secret_hash: Option<String>,
198
199 pub registration_access_token_hash: String,
201
202 pub metadata: ClientRegistrationRequest,
204
205 pub registered_at: DateTime<Utc>,
207
208 pub updated_at: DateTime<Utc>,
210
211 pub client_secret_expires_at: Option<DateTime<Utc>>,
213
214 pub is_active: bool,
216}
217
218impl std::fmt::Debug for RegisteredClient {
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 let mut d = f.debug_struct("RegisteredClient");
221 d.field("client_id", &self.client_id);
222 d.field(
223 "client_secret_hash",
224 &crate::utils::redact::redacted(&self.client_secret_hash),
225 );
226 d.field(
227 "registration_access_token_hash",
228 &crate::utils::redact::redacted(&self.registration_access_token_hash),
229 );
230 d.field("metadata", &self.metadata);
231 d.field("registered_at", &self.registered_at);
232 d.field("updated_at", &self.updated_at);
233 d.field("client_secret_expires_at", &self.client_secret_expires_at);
234 d.field("is_active", &self.is_active);
235 d.finish()
236 }
237}
238
239#[derive(Debug, Clone)]
241pub struct ClientRegistrationConfig {
242 pub base_url: String,
244
245 pub require_authentication: bool,
247
248 pub default_secret_expiration: Option<i64>,
250
251 pub max_redirect_uris: usize,
253
254 pub allowed_grant_types: Vec<String>,
256
257 pub allowed_response_types: Vec<String>,
259
260 pub allowed_auth_methods: Vec<String>,
262
263 pub allow_public_clients: bool,
265
266 pub rate_limit_per_ip: u32,
268 pub rate_limit_window: std::time::Duration,
269}
270
271impl Default for ClientRegistrationConfig {
272 fn default() -> Self {
273 Self {
274 base_url: "https://auth.example.com".to_string(),
275 require_authentication: false,
276 default_secret_expiration: Some(86400 * 365), max_redirect_uris: 10,
278 allowed_grant_types: vec![
279 "authorization_code".to_string(),
280 "client_credentials".to_string(),
281 "refresh_token".to_string(),
282 "urn:ietf:params:oauth:grant-type:device_code".to_string(),
283 ],
284 allowed_response_types: vec![
285 "code".to_string(),
286 "token".to_string(),
287 "id_token".to_string(),
288 ],
289 allowed_auth_methods: vec![
290 "client_secret_basic".to_string(),
291 "client_secret_post".to_string(),
292 "private_key_jwt".to_string(),
293 "none".to_string(),
294 ],
295 allow_public_clients: true,
296 rate_limit_per_ip: 10,
297 rate_limit_window: std::time::Duration::from_secs(3600),
298 }
299 }
300}
301
302pub struct ClientRegistrationManager {
304 config: ClientRegistrationConfig,
305 storage: Arc<dyn AuthStorage>,
306 rate_limiter: Arc<
307 governor::RateLimiter<
308 governor::state::direct::NotKeyed,
309 governor::state::InMemoryState,
310 governor::clock::DefaultClock,
311 >,
312 >,
313}
314
315impl ClientRegistrationManager {
316 pub fn new(config: ClientRegistrationConfig, storage: Arc<dyn AuthStorage>) -> Self {
318 let quota =
319 governor::Quota::per_hour(std::num::NonZeroU32::new(config.rate_limit_per_ip).unwrap());
320 let rate_limiter = Arc::new(governor::RateLimiter::direct(quota));
321
322 Self {
323 config,
324 storage,
325 rate_limiter,
326 }
327 }
328
329 pub async fn register_client(
331 &self,
332 request: ClientRegistrationRequest,
333 client_ip: Option<std::net::IpAddr>,
334 ) -> Result<ClientRegistrationResponse> {
335 if let Some(_ip) = client_ip
337 && self.rate_limiter.check().is_err()
338 {
339 return Err(AuthError::rate_limit(
340 "Client registration rate limit exceeded",
341 ));
342 }
343
344 self.validate_registration_request(&request)?;
346
347 let client_id = self.generate_client_id();
349 let (client_secret, client_secret_hash) = if self.requires_client_secret(&request) {
350 let secret = self.generate_client_secret();
351 let hash = self.hash_secret(&secret)?;
352 (Some(secret), Some(hash))
353 } else {
354 (None, None)
355 };
356
357 let registration_access_token = self.generate_registration_access_token();
359 let registration_access_token_hash = self.hash_secret(®istration_access_token)?;
360
361 let client_secret_expires_at = if client_secret.is_some() {
363 self.config
364 .default_secret_expiration
365 .map(|seconds| Utc::now() + Duration::seconds(seconds))
366 } else {
367 None
368 };
369
370 let registered_client = RegisteredClient {
372 client_id: client_id.clone(),
373 client_secret_hash,
374 registration_access_token_hash,
375 metadata: request.clone(),
376 registered_at: Utc::now(),
377 updated_at: Utc::now(),
378 client_secret_expires_at,
379 is_active: true,
380 };
381
382 self.store_client(®istered_client).await?;
384
385 let response = ClientRegistrationResponse {
387 client_id: client_id.clone(),
388 client_secret,
389 registration_access_token,
390 registration_client_uri: format!("{}/register/{}", self.config.base_url, client_id),
391 client_id_issued_at: Some(Utc::now().timestamp()),
392 client_secret_expires_at: client_secret_expires_at.map(|dt| dt.timestamp()),
393 redirect_uris: request.redirect_uris,
394 token_endpoint_auth_method: request.token_endpoint_auth_method,
395 grant_types: request.grant_types,
396 response_types: request.response_types,
397 client_name: request.client_name,
398 client_uri: request.client_uri,
399 logo_uri: request.logo_uri,
400 scope: request.scope,
401 contacts: request.contacts,
402 tos_uri: request.tos_uri,
403 policy_uri: request.policy_uri,
404 jwks_uri: request.jwks_uri,
405 jwks: request.jwks,
406 software_id: request.software_id,
407 software_version: request.software_version,
408 additional_metadata: request.additional_metadata,
409 };
410
411 Ok(response)
412 }
413
414 pub async fn read_client(
416 &self,
417 client_id: &str,
418 registration_access_token: &str,
419 ) -> Result<ClientRegistrationResponse> {
420 let client = self.get_client(client_id).await?;
421
422 if !self.verify_registration_token(&client, registration_access_token)? {
424 return Err(AuthError::auth_method(
425 "client_registration",
426 "Invalid registration access token",
427 ));
428 }
429
430 self.client_to_response(&client)
431 }
432
433 pub async fn update_client(
435 &self,
436 client_id: &str,
437 registration_access_token: &str,
438 request: ClientRegistrationRequest,
439 ) -> Result<ClientRegistrationResponse> {
440 let mut client = self.get_client(client_id).await?;
441
442 if !self.verify_registration_token(&client, registration_access_token)? {
444 return Err(AuthError::auth_method(
445 "client_registration",
446 "Invalid registration access token",
447 ));
448 }
449
450 self.validate_registration_request(&request)?;
452
453 client.metadata = request;
455 client.updated_at = Utc::now();
456
457 self.store_client(&client).await?;
459
460 self.client_to_response(&client)
461 }
462
463 pub async fn delete_client(
465 &self,
466 client_id: &str,
467 registration_access_token: &str,
468 ) -> Result<()> {
469 let client = self.get_client(client_id).await?;
470
471 if !self.verify_registration_token(&client, registration_access_token)? {
473 return Err(AuthError::auth_method(
474 "client_registration",
475 "Invalid registration access token",
476 ));
477 }
478
479 let key = format!("client_registration:{}", client_id);
481 self.storage.delete_kv(&key).await?;
482
483 Ok(())
484 }
485
486 fn validate_registration_request(&self, request: &ClientRegistrationRequest) -> Result<()> {
488 if let Some(redirect_uris) = &request.redirect_uris {
490 if redirect_uris.len() > self.config.max_redirect_uris {
491 return Err(AuthError::auth_method(
492 "client_registration",
493 "Too many redirect URIs",
494 ));
495 }
496
497 for uri in redirect_uris {
498 if !self.is_valid_uri(uri) {
499 return Err(AuthError::auth_method(
500 "client_registration",
501 format!("Invalid redirect URI: {}", uri),
502 ));
503 }
504 }
505 }
506
507 if let Some(grant_types) = &request.grant_types {
509 for grant_type in grant_types {
510 if !self.config.allowed_grant_types.contains(grant_type) {
511 return Err(AuthError::auth_method(
512 "client_registration",
513 format!("Unsupported grant type: {}", grant_type),
514 ));
515 }
516 }
517 }
518
519 if let Some(response_types) = &request.response_types {
521 for response_type in response_types {
522 if !self.config.allowed_response_types.contains(response_type) {
523 return Err(AuthError::auth_method(
524 "client_registration",
525 format!("Unsupported response type: {}", response_type),
526 ));
527 }
528 }
529 }
530
531 if let Some(auth_method) = &request.token_endpoint_auth_method
533 && !self.config.allowed_auth_methods.contains(auth_method)
534 {
535 return Err(AuthError::auth_method(
536 "client_registration",
537 format!("Unsupported authentication method: {}", auth_method),
538 ));
539 }
540
541 Ok(())
542 }
543
544 fn requires_client_secret(&self, request: &ClientRegistrationRequest) -> bool {
546 if !self.config.allow_public_clients {
547 return true;
548 }
549
550 !matches!(request.token_endpoint_auth_method.as_deref(), Some("none"))
551 }
552
553 fn generate_client_id(&self) -> String {
555 format!("client_{}", Uuid::new_v4().simple())
556 }
557
558 fn generate_client_secret(&self) -> String {
560 use rand::RngCore;
561 let mut rng = rand::rng();
562 let mut bytes = [0u8; 32];
563 rng.fill_bytes(&mut bytes);
564 general_purpose::URL_SAFE_NO_PAD.encode(bytes)
565 }
566
567 fn generate_registration_access_token(&self) -> String {
569 use rand::RngCore;
570 let mut rng = rand::rng();
571 let mut bytes = [0u8; 32];
572 rng.fill_bytes(&mut bytes);
573 general_purpose::URL_SAFE_NO_PAD.encode(bytes)
574 }
575
576 fn hash_secret(&self, secret: &str) -> Result<String> {
578 use sha2::{Digest, Sha256};
579 let mut hasher = Sha256::new();
580 hasher.update(secret.as_bytes());
581 Ok(format!("{:x}", hasher.finalize()))
582 }
583
584 fn verify_registration_token(&self, client: &RegisteredClient, token: &str) -> Result<bool> {
586 let token_hash = self.hash_secret(token)?;
587 Ok(client.registration_access_token_hash == token_hash)
588 }
589
590 fn is_valid_uri(&self, uri: &str) -> bool {
592 url::Url::parse(uri).is_ok()
593 }
594
595 async fn store_client(&self, client: &RegisteredClient) -> Result<()> {
597 let key = format!("client_registration:{}", client.client_id);
598 let value = serde_json::to_string(client)?;
599 self.storage.store_kv(&key, value.as_bytes(), None).await?;
600 Ok(())
601 }
602
603 async fn get_client(&self, client_id: &str) -> Result<RegisteredClient> {
605 let key = format!("client_registration:{}", client_id);
606 let value = match self.storage.get_kv(&key).await? {
607 Some(value) => value,
608 None => {
609 return Err(AuthError::auth_method(
610 "client_registration",
611 "Client not found",
612 ));
613 }
614 };
615 let value_str = String::from_utf8(value).map_err(|e| {
616 AuthError::Storage(StorageError::Serialization {
617 message: format!("Invalid UTF-8 data: {}", e),
618 })
619 })?;
620 let client: RegisteredClient = serde_json::from_str(&value_str)?;
621 Ok(client)
622 }
623
624 fn client_to_response(&self, client: &RegisteredClient) -> Result<ClientRegistrationResponse> {
626 Ok(ClientRegistrationResponse {
627 client_id: client.client_id.clone(),
628 client_secret: None, registration_access_token: "***".to_string(), registration_client_uri: format!(
631 "{}/register/{}",
632 self.config.base_url, client.client_id
633 ),
634 client_id_issued_at: Some(client.registered_at.timestamp()),
635 client_secret_expires_at: client.client_secret_expires_at.map(|dt| dt.timestamp()),
636 redirect_uris: client.metadata.redirect_uris.clone(),
637 token_endpoint_auth_method: client.metadata.token_endpoint_auth_method.clone(),
638 grant_types: client.metadata.grant_types.clone(),
639 response_types: client.metadata.response_types.clone(),
640 client_name: client.metadata.client_name.clone(),
641 client_uri: client.metadata.client_uri.clone(),
642 logo_uri: client.metadata.logo_uri.clone(),
643 scope: client.metadata.scope.clone(),
644 contacts: client.metadata.contacts.clone(),
645 tos_uri: client.metadata.tos_uri.clone(),
646 policy_uri: client.metadata.policy_uri.clone(),
647 jwks_uri: client.metadata.jwks_uri.clone(),
648 jwks: client.metadata.jwks.clone(),
649 software_id: client.metadata.software_id.clone(),
650 software_version: client.metadata.software_version.clone(),
651 additional_metadata: client.metadata.additional_metadata.clone(),
652 })
653 }
654}
655
656#[cfg(test)]
657mod tests {
658 use super::*;
659 use crate::storage::MemoryStorage;
660
661 #[tokio::test]
662 async fn test_client_registration() {
663 let storage = Arc::new(MemoryStorage::new());
664 let config = ClientRegistrationConfig::default();
665 let manager = ClientRegistrationManager::new(config, storage);
666
667 let request = ClientRegistrationRequest {
668 redirect_uris: Some(vec!["https://client.example.com/callback".to_string()]),
669 token_endpoint_auth_method: Some("client_secret_basic".to_string()),
670 grant_types: Some(vec!["authorization_code".to_string()]),
671 response_types: Some(vec!["code".to_string()]),
672 client_name: Some("Test Client".to_string()),
673 client_uri: Some("https://client.example.com".to_string()),
674 logo_uri: Some("https://client.example.com/logo.png".to_string()),
675 scope: Some("read write".to_string()),
676 contacts: Some(vec!["admin@client.example.com".to_string()]),
677 tos_uri: Some("https://client.example.com/tos".to_string()),
678 policy_uri: Some("https://client.example.com/privacy".to_string()),
679 jwks_uri: Some("https://client.example.com/jwks".to_string()),
680 jwks: None,
681 software_id: Some("test-client".to_string()),
682 software_version: Some("1.0.0".to_string()),
683 additional_metadata: HashMap::new(),
684 };
685
686 let response = manager
687 .register_client(request.clone(), None)
688 .await
689 .unwrap();
690
691 assert!(!response.client_id.is_empty());
692 assert!(response.client_secret.is_some());
693 assert!(!response.registration_access_token.is_empty());
694 assert_eq!(response.client_name, Some("Test Client".to_string()));
695 assert_eq!(
696 response.redirect_uris,
697 Some(vec!["https://client.example.com/callback".to_string()])
698 );
699 }
700
701 #[tokio::test]
702 async fn test_public_client_registration() {
703 let storage = Arc::new(MemoryStorage::new());
704 let config = ClientRegistrationConfig::default();
705 let manager = ClientRegistrationManager::new(config, storage);
706
707 let request = ClientRegistrationRequest {
708 redirect_uris: Some(vec!["https://client.example.com/callback".to_string()]),
709 token_endpoint_auth_method: Some("none".to_string()),
710 grant_types: Some(vec!["authorization_code".to_string()]),
711 response_types: Some(vec!["code".to_string()]),
712 client_name: Some("Public Client".to_string()),
713 client_uri: None,
714 logo_uri: None,
715 scope: Some("read".to_string()),
716 contacts: None,
717 tos_uri: None,
718 policy_uri: None,
719 jwks_uri: None,
720 jwks: None,
721 software_id: None,
722 software_version: None,
723 additional_metadata: HashMap::new(),
724 };
725
726 let response = manager.register_client(request, None).await.unwrap();
727
728 assert!(!response.client_id.is_empty());
729 assert!(response.client_secret.is_none()); assert!(!response.registration_access_token.is_empty());
731 assert_eq!(response.client_name, Some("Public Client".to_string()));
732 }
733}