Skip to main content

auth_framework/server/oidc/
oidc_user_registration.rs

1//! Initiating User Registration via OpenID Connect
2//!
3//! This module implements the "Initiating User Registration via OpenID Connect 1.0"
4//! specification, which allows clients to initiate user registration through the
5//! OpenID Connect authorization flow using the `prompt=create` parameter.
6//!
7//! # Features
8//!
9//! - `prompt=create` parameter handling
10//! - User registration flow integration
11//! - Registration completion validation
12//! - Registration metadata and claims handling
13//! - Structured OIDC error responses for registration failures
14//! - Session management with timeout handling
15//! - Comprehensive error reporting using OpenID Connect error codes
16//!
17//! # Error Handling
18//!
19//! The registration manager uses `OidcErrorManager` to provide structured error
20//! responses that comply with OpenID Connect specifications:
21//!
22//! - `registration_not_supported` - When registration is disabled
23//! - `invalid_request` - For malformed registration requests
24//! - `session_selection_required` - For missing/invalid registration sessions
25//! - `registration_required` - For incomplete registration data
26//! - `login_required` - For expired registration sessions
27//!
28//! # Usage Examples
29//!
30//! ```rust,no_run
31//! use auth_framework::server::oidc::oidc_user_registration::{RegistrationManager, RegistrationConfig, RegistrationRequest};
32//!
33//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
34//! let mut manager = RegistrationManager::new(RegistrationConfig::default());
35//!
36//! let request = RegistrationRequest {
37//!     client_id: "client123".to_string(),
38//!     redirect_uri: "https://app.example.com/callback".to_string(),
39//!     scope: "openid profile email".to_string(),
40//!     response_type: "code".to_string(),
41//!     prompt: Some("create".to_string()),
42//!     state: None,
43//!     nonce: None,
44//!     login_hint: None,
45//!     ui_locales: None,
46//!     registration_metadata: None,
47//!     claims: None,
48//! };
49//!
50//! let registration_id = manager.initiate_registration(request)?;
51//! # Ok(())
52//! # }
53//! ```
54
55use crate::errors::{AuthError, Result};
56use crate::server::oidc::oidc_error_extensions::{
57    OidcErrorCode, OidcErrorManager, OidcErrorResponse,
58};
59use serde::{Deserialize, Serialize};
60use std::collections::HashMap;
61use uuid::Uuid;
62
63/// User registration request parameters
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct RegistrationRequest {
66    /// Standard OpenID Connect parameters
67    pub client_id: String,
68    pub redirect_uri: String,
69    pub scope: String,
70    pub response_type: String,
71    pub state: Option<String>,
72    pub nonce: Option<String>,
73
74    /// Registration-specific parameters
75    /// Prompt parameter should contain "create"
76    pub prompt: Option<String>,
77    /// Login hint for pre-filling registration form
78    pub login_hint: Option<String>,
79    /// UI locales for registration interface
80    pub ui_locales: Option<String>,
81    /// Registration metadata as JSON string
82    pub registration_metadata: Option<String>,
83    /// Claims to be collected during registration
84    pub claims: Option<String>,
85}
86
87/// User registration data
88#[derive(Debug, Clone, Serialize, Deserialize, Default)]
89pub struct RegistrationData {
90    /// Unique registration session ID
91    pub registration_id: String,
92    /// User's email address
93    pub email: Option<String>,
94    /// User's phone number
95    pub phone_number: Option<String>,
96    /// User's given name
97    pub given_name: Option<String>,
98    /// User's family name
99    pub family_name: Option<String>,
100    /// User's full name
101    pub name: Option<String>,
102    /// User's preferred username
103    pub preferred_username: Option<String>,
104    /// User's profile picture URL
105    pub picture: Option<String>,
106    /// User's website URL
107    pub website: Option<String>,
108    /// User's gender
109    pub gender: Option<String>,
110    /// User's birthdate
111    pub birthdate: Option<String>,
112    /// User's timezone
113    pub zoneinfo: Option<String>,
114    /// User's locale
115    pub locale: Option<String>,
116    /// Custom registration fields
117    pub custom_fields: HashMap<String, serde_json::Value>,
118    /// Registration completion status
119    pub completed: bool,
120    /// Creation timestamp
121    pub created_at: u64,
122}
123
124/// Registration completion response
125#[derive(Clone, Serialize, Deserialize)]
126pub struct RegistrationResponse {
127    /// New user's subject identifier
128    pub sub: String,
129    /// Registration completion status
130    pub completed: bool,
131    /// Authorization code for completed registration
132    pub code: Option<String>,
133    /// State parameter from original request
134    pub state: Option<String>,
135}
136
137impl std::fmt::Debug for RegistrationResponse {
138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139        let mut d = f.debug_struct("RegistrationResponse");
140        d.field("sub", &self.sub);
141        d.field("completed", &self.completed);
142        d.field("code", &crate::utils::redact::redacted(&self.code));
143        d.field("state", &self.state);
144        d.finish()
145    }
146}
147
148/// Registration configuration
149#[derive(Debug, Clone)]
150pub struct RegistrationConfig {
151    /// Enable user registration via prompt=create
152    pub enabled: bool,
153    /// Registration endpoint URL
154    pub registration_endpoint: String,
155    /// Required fields for registration
156    pub required_fields: Vec<String>,
157    /// Optional fields available during registration
158    pub optional_fields: Vec<String>,
159    /// Maximum registration session duration (seconds)
160    pub session_timeout: u64,
161    /// Enable email verification during registration
162    pub require_email_verification: bool,
163    /// Enable phone verification during registration
164    pub require_phone_verification: bool,
165    /// Custom field validation rules
166    pub field_validation_rules: HashMap<String, String>,
167}
168
169impl Default for RegistrationConfig {
170    fn default() -> Self {
171        Self {
172            enabled: true,
173            registration_endpoint: "/connect/register".to_string(),
174            required_fields: vec!["email".to_string()],
175            optional_fields: vec![
176                "given_name".to_string(),
177                "family_name".to_string(),
178                "name".to_string(),
179                "preferred_username".to_string(),
180                "phone_number".to_string(),
181            ],
182            session_timeout: 1800, // 30 minutes
183            require_email_verification: true,
184            require_phone_verification: false,
185            field_validation_rules: HashMap::new(),
186        }
187    }
188}
189
190/// User registration manager
191#[derive(Clone)]
192pub struct RegistrationManager {
193    /// Configuration
194    config: RegistrationConfig,
195    /// Error manager for creating error responses
196    error_manager: OidcErrorManager,
197    /// Active registration sessions
198    registration_sessions: HashMap<String, RegistrationData>,
199}
200
201impl std::fmt::Debug for RegistrationManager {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        let mut d = f.debug_struct("RegistrationManager");
204        d.field("config", &self.config);
205        d.field("error_manager", &self.error_manager);
206        d.field(
207            "registration_sessions",
208            &crate::utils::redact::redacted(&self.registration_sessions),
209        );
210        d.finish()
211    }
212}
213
214impl RegistrationManager {
215    /// Create new registration manager
216    pub fn new(config: RegistrationConfig) -> Self {
217        Self {
218            config,
219            error_manager: OidcErrorManager::default(),
220            registration_sessions: HashMap::new(),
221        }
222    }
223
224    /// Create new registration manager with custom error manager
225    pub fn with_error_manager(config: RegistrationConfig, error_manager: OidcErrorManager) -> Self {
226        Self {
227            config,
228            error_manager,
229            registration_sessions: HashMap::new(),
230        }
231    }
232
233    /// Create OIDC error response for registration not enabled
234    pub fn create_registration_disabled_error(&self, state: Option<String>) -> OidcErrorResponse {
235        self.error_manager.create_error_response(
236            OidcErrorCode::RegistrationNotSupported,
237            Some("User registration is not enabled on this server".to_string()),
238            state,
239            HashMap::new(),
240        )
241    }
242
243    /// Create OIDC error response for invalid registration request
244    pub fn create_invalid_registration_request_error(
245        &self,
246        description: String,
247        state: Option<String>,
248    ) -> OidcErrorResponse {
249        self.error_manager.create_error_response(
250            OidcErrorCode::InvalidRequest,
251            Some(description),
252            state,
253            HashMap::new(),
254        )
255    }
256
257    /// Create OIDC error response for registration session not found
258    pub fn create_session_not_found_error(&self, state: Option<String>) -> OidcErrorResponse {
259        self.error_manager.create_error_response(
260            OidcErrorCode::SessionSelectionRequired,
261            Some("Registration session not found or expired".to_string()),
262            state,
263            HashMap::new(),
264        )
265    }
266
267    /// Create OIDC error response for missing required registration fields
268    pub fn create_registration_incomplete_error(
269        &self,
270        missing_fields: Vec<String>,
271        state: Option<String>,
272    ) -> OidcErrorResponse {
273        let mut additional_details = HashMap::new();
274        additional_details.insert(
275            "missing_fields".to_string(),
276            serde_json::to_value(missing_fields.clone()).unwrap(),
277        );
278
279        self.error_manager.create_error_response(
280            OidcErrorCode::RegistrationRequired,
281            Some(format!(
282                "Registration incomplete. Missing required fields: {}",
283                missing_fields.join(", ")
284            )),
285            state,
286            additional_details,
287        )
288    }
289
290    /// Create OIDC error response for expired registration session
291    pub fn create_session_expired_error(&self, state: Option<String>) -> OidcErrorResponse {
292        self.error_manager.create_error_response(
293            OidcErrorCode::LoginRequired,
294            Some("Registration session has expired. Please start registration again".to_string()),
295            state,
296            HashMap::new(),
297        )
298    }
299
300    /// Get error manager reference for external usage
301    pub fn get_error_manager(&self) -> &OidcErrorManager {
302        &self.error_manager
303    }
304
305    /// Update error manager configuration
306    pub fn update_error_manager(&mut self, error_manager: OidcErrorManager) {
307        self.error_manager = error_manager;
308    }
309
310    /// Check if registration is requested via prompt=create
311    pub fn is_registration_requested(&self, prompt: Option<&str>) -> bool {
312        if !self.config.enabled {
313            return false;
314        }
315
316        if let Some(prompt_values) = prompt {
317            let prompts: Vec<&str> = prompt_values.split_whitespace().collect();
318            prompts.contains(&"create")
319        } else {
320            false
321        }
322    }
323
324    /// Initiate user registration process
325    pub fn initiate_registration(&mut self, request: RegistrationRequest) -> Result<String> {
326        if !self.config.enabled {
327            let error_response = self.create_registration_disabled_error(request.state.clone());
328            return Err(AuthError::validation(format!(
329                "Registration disabled: {}",
330                error_response.error_description.unwrap_or_default()
331            )));
332        }
333
334        // Validate prompt parameter contains "create"
335        if !self.is_registration_requested(request.prompt.as_deref()) {
336            let error_response = self.create_invalid_registration_request_error(
337                "Registration requires prompt=create parameter".to_string(),
338                request.state.clone(),
339            );
340            return Err(AuthError::validation(format!(
341                "Invalid request: {}",
342                error_response.error_description.unwrap_or_default()
343            )));
344        }
345
346        // Create new registration session
347        let registration_id = Uuid::new_v4().to_string();
348        let now = std::time::SystemTime::now()
349            .duration_since(std::time::UNIX_EPOCH)
350            .unwrap()
351            .as_secs();
352
353        let mut registration_data = RegistrationData {
354            registration_id: registration_id.clone(),
355            email: None,
356            phone_number: None,
357            given_name: None,
358            family_name: None,
359            name: None,
360            preferred_username: None,
361            picture: None,
362            website: None,
363            gender: None,
364            birthdate: None,
365            zoneinfo: None,
366            locale: None,
367            custom_fields: HashMap::new(),
368            completed: false,
369            created_at: now,
370        };
371
372        // Pre-fill with login_hint if provided
373        if let Some(login_hint) = &request.login_hint {
374            if login_hint.contains('@') {
375                registration_data.email = Some(login_hint.clone());
376            } else {
377                registration_data.preferred_username = Some(login_hint.clone());
378            }
379        }
380
381        // Parse and store registration metadata
382        if let Some(metadata_str) = &request.registration_metadata {
383            match serde_json::from_str::<HashMap<String, serde_json::Value>>(metadata_str) {
384                Ok(metadata) => {
385                    registration_data.custom_fields.extend(metadata);
386                }
387                Err(_) => {
388                    let error_response = self.create_invalid_registration_request_error(
389                        "Invalid registration metadata JSON format".to_string(),
390                        request.state.clone(),
391                    );
392                    return Err(AuthError::validation(format!(
393                        "Invalid metadata: {}",
394                        error_response.error_description.unwrap_or_default()
395                    )));
396                }
397            }
398        }
399
400        self.registration_sessions
401            .insert(registration_id.clone(), registration_data);
402
403        Ok(registration_id)
404    }
405
406    /// Update registration data
407    pub fn update_registration_data(
408        &mut self,
409        registration_id: &str,
410        updates: HashMap<String, serde_json::Value>,
411    ) -> Result<()> {
412        // Check if registration exists first
413        if !self.registration_sessions.contains_key(registration_id) {
414            let error_response = self.create_session_not_found_error(None);
415            return Err(AuthError::validation(format!(
416                "Session error: {}",
417                error_response.error_description.unwrap_or_default()
418            )));
419        }
420
421        let registration = self.registration_sessions.get_mut(registration_id).unwrap(); // Safe because we checked above
422
423        // Check session timeout
424        let now = std::time::SystemTime::now()
425            .duration_since(std::time::UNIX_EPOCH)
426            .unwrap()
427            .as_secs();
428
429        if now - registration.created_at > self.config.session_timeout {
430            let error_response = self.create_session_expired_error(None);
431            return Err(AuthError::validation(format!(
432                "Session expired: {}",
433                error_response.error_description.unwrap_or_default()
434            )));
435        }
436
437        // Update standard fields
438        for (key, value) in updates {
439            match key.as_str() {
440                "email" => registration.email = value.as_str().map(|s| s.to_string()),
441                "phone_number" => registration.phone_number = value.as_str().map(|s| s.to_string()),
442                "given_name" => registration.given_name = value.as_str().map(|s| s.to_string()),
443                "family_name" => registration.family_name = value.as_str().map(|s| s.to_string()),
444                "name" => registration.name = value.as_str().map(|s| s.to_string()),
445                "preferred_username" => {
446                    registration.preferred_username = value.as_str().map(|s| s.to_string())
447                }
448                "picture" => registration.picture = value.as_str().map(|s| s.to_string()),
449                "website" => registration.website = value.as_str().map(|s| s.to_string()),
450                "gender" => registration.gender = value.as_str().map(|s| s.to_string()),
451                "birthdate" => registration.birthdate = value.as_str().map(|s| s.to_string()),
452                "zoneinfo" => registration.zoneinfo = value.as_str().map(|s| s.to_string()),
453                "locale" => registration.locale = value.as_str().map(|s| s.to_string()),
454                _ => {
455                    // Store in custom fields
456                    registration.custom_fields.insert(key, value);
457                }
458            }
459        }
460
461        Ok(())
462    }
463
464    /// Validate registration data completeness
465    pub fn validate_registration_data(&self, registration_id: &str) -> Result<Vec<String>> {
466        // Check if registration exists first
467        if !self.registration_sessions.contains_key(registration_id) {
468            let error_response = self.create_session_not_found_error(None);
469            return Err(AuthError::validation(format!(
470                "Session error: {}",
471                error_response.error_description.unwrap_or_default()
472            )));
473        }
474
475        let registration = self.registration_sessions.get(registration_id).unwrap(); // Safe because we checked above
476
477        let mut missing_fields = Vec::new();
478
479        // Check required fields
480        for field in &self.config.required_fields {
481            let is_present = match field.as_str() {
482                "email" => registration.email.is_some(),
483                "phone_number" => registration.phone_number.is_some(),
484                "given_name" => registration.given_name.is_some(),
485                "family_name" => registration.family_name.is_some(),
486                "name" => registration.name.is_some(),
487                "preferred_username" => registration.preferred_username.is_some(),
488                _ => registration.custom_fields.contains_key(field),
489            };
490
491            if !is_present {
492                missing_fields.push(field.clone());
493            }
494        }
495
496        Ok(missing_fields)
497    }
498
499    /// Validate registration data and create error response if incomplete
500    pub fn validate_registration_completeness(
501        &self,
502        registration_id: &str,
503        state: Option<String>,
504    ) -> Result<()> {
505        let missing_fields = self.validate_registration_data(registration_id)?;
506        if !missing_fields.is_empty() {
507            let error_response = self.create_registration_incomplete_error(missing_fields, state);
508            return Err(AuthError::validation(format!(
509                "Registration incomplete: {}",
510                error_response.error_description.unwrap_or_default()
511            )));
512        }
513        Ok(())
514    }
515
516    /// Complete user registration and create user account
517    pub fn complete_registration(&mut self, registration_id: &str) -> Result<RegistrationResponse> {
518        // Validate registration data using error manager
519        self.validate_registration_completeness(registration_id, None)?;
520
521        // Check if registration exists first
522        if !self.registration_sessions.contains_key(registration_id) {
523            let error_response = self.create_session_not_found_error(None);
524            return Err(AuthError::validation(format!(
525                "Session error: {}",
526                error_response.error_description.unwrap_or_default()
527            )));
528        }
529
530        let mut registration = self.registration_sessions.remove(registration_id).unwrap(); // Safe because we checked above
531
532        // Generate new user subject identifier
533        let sub = format!("user_{}", Uuid::new_v4());
534
535        // Mark registration as completed
536        registration.completed = true;
537
538        // In a real implementation, this would:
539        // 1. Create user account in the database
540        // 2. Send verification emails/SMS if required
541        // 3. Generate authorization code for the client
542        // 4. Store user profile data
543
544        // Generate authorization code for successful registration
545        let authorization_code = format!("reg_auth_{}", Uuid::new_v4());
546
547        Ok(RegistrationResponse {
548            sub,
549            completed: true,
550            code: Some(authorization_code),
551            state: None, // This would be populated from the original request
552        })
553    }
554
555    /// Get registration session data
556    pub fn get_registration_data(&self, registration_id: &str) -> Option<&RegistrationData> {
557        self.registration_sessions.get(registration_id)
558    }
559
560    /// Generate registration form HTML
561    pub fn generate_registration_form(&self, registration_id: &str) -> Result<String> {
562        // Check if registration exists first
563        if !self.registration_sessions.contains_key(registration_id) {
564            let error_response = self.create_session_not_found_error(None);
565            return Err(AuthError::validation(format!(
566                "Session error: {}",
567                error_response.error_description.unwrap_or_default()
568            )));
569        }
570
571        let registration = self.registration_sessions.get(registration_id).unwrap(); // Safe because we checked above
572
573        let mut form = format!(
574            r#"<!DOCTYPE html>
575<html>
576<head>
577    <title>User Registration</title>
578    <style>
579        body {{ font-family: Arial, sans-serif; margin: 40px; }}
580        .form-group {{ margin-bottom: 15px; }}
581        label {{ display: block; margin-bottom: 5px; font-weight: bold; }}
582        input {{ width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }}
583        .required {{ color: red; }}
584        .submit-btn {{ background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }}
585    </style>
586</head>
587<body>
588    <h1>Create Your Account</h1>
589    <form method="post" action="/connect/register/{}/complete">
590"#,
591            registration.registration_id
592        );
593
594        // Add required fields
595        for field in &self.config.required_fields {
596            let (field_name, field_type, current_value) = match field.as_str() {
597                "email" => (
598                    "Email Address",
599                    "email",
600                    registration.email.as_deref().unwrap_or(""),
601                ),
602                "given_name" => (
603                    "First Name",
604                    "text",
605                    registration.given_name.as_deref().unwrap_or(""),
606                ),
607                "family_name" => (
608                    "Last Name",
609                    "text",
610                    registration.family_name.as_deref().unwrap_or(""),
611                ),
612                "phone_number" => (
613                    "Phone Number",
614                    "tel",
615                    registration.phone_number.as_deref().unwrap_or(""),
616                ),
617                _ => (field.as_str(), "text", ""),
618            };
619
620            form.push_str(&format!(
621                r#"        <div class="form-group">
622            <label for="{}">{} <span class="required">*</span></label>
623            <input type="{}" id="{}" name="{}" value="{}" required>
624        </div>
625"#,
626                field, field_name, field_type, field, field, current_value
627            ));
628        }
629
630        // Add optional fields
631        for field in &self.config.optional_fields {
632            if !self.config.required_fields.contains(field) {
633                let (field_name, field_type, current_value) = match field.as_str() {
634                    "preferred_username" => (
635                        "Username",
636                        "text",
637                        registration.preferred_username.as_deref().unwrap_or(""),
638                    ),
639                    "website" => (
640                        "Website",
641                        "url",
642                        registration.website.as_deref().unwrap_or(""),
643                    ),
644                    "picture" => (
645                        "Profile Picture URL",
646                        "url",
647                        registration.picture.as_deref().unwrap_or(""),
648                    ),
649                    _ => (field.as_str(), "text", ""),
650                };
651
652                form.push_str(&format!(
653                    r#"        <div class="form-group">
654            <label for="{}">{}</label>
655            <input type="{}" id="{}" name="{}" value="{}">
656        </div>
657"#,
658                    field, field_name, field_type, field, field, current_value
659                ));
660            }
661        }
662
663        form.push_str(
664            r#"        <button type="submit" class="submit-btn">Create Account</button>
665    </form>
666</body>
667</html>"#,
668        );
669
670        Ok(form)
671    }
672
673    /// Clean up expired registration sessions
674    pub fn cleanup_expired_sessions(&mut self) -> usize {
675        let now = std::time::SystemTime::now()
676            .duration_since(std::time::UNIX_EPOCH)
677            .unwrap()
678            .as_secs();
679
680        let initial_count = self.registration_sessions.len();
681
682        self.registration_sessions
683            .retain(|_, registration| now - registration.created_at < self.config.session_timeout);
684
685        initial_count - self.registration_sessions.len()
686    }
687
688    /// Get registration discovery metadata
689    pub fn get_discovery_metadata(&self) -> HashMap<String, serde_json::Value> {
690        let mut metadata = HashMap::new();
691
692        if self.config.enabled {
693            metadata.insert(
694                "registration_endpoint".to_string(),
695                serde_json::Value::String(self.config.registration_endpoint.clone()),
696            );
697            metadata.insert(
698                "prompt_values_supported".to_string(),
699                serde_json::Value::Array(vec![
700                    serde_json::Value::String("none".to_string()),
701                    serde_json::Value::String("login".to_string()),
702                    serde_json::Value::String("consent".to_string()),
703                    serde_json::Value::String("select_account".to_string()),
704                    serde_json::Value::String("create".to_string()),
705                ]),
706            );
707        }
708
709        metadata
710    }
711}
712
713#[cfg(test)]
714mod tests {
715    use super::*;
716
717    #[test]
718    fn test_error_manager_integration() {
719        let mut manager = RegistrationManager::new(RegistrationConfig::default());
720
721        // Test registration disabled error
722        let disabled_config = RegistrationConfig {
723            enabled: false,
724            ..Default::default()
725        };
726        let mut disabled_manager = RegistrationManager::new(disabled_config);
727
728        let request = RegistrationRequest {
729            client_id: "test_client".to_string(),
730            redirect_uri: "https://client.example.com/callback".to_string(),
731            scope: "openid profile email".to_string(),
732            response_type: "code".to_string(),
733            state: Some("state123".to_string()),
734            nonce: Some("nonce456".to_string()),
735            prompt: Some("create".to_string()),
736            login_hint: None,
737            ui_locales: None,
738            registration_metadata: None,
739            claims: None,
740        };
741
742        let result = disabled_manager.initiate_registration(request.clone());
743        assert!(result.is_err());
744        assert!(
745            result
746                .unwrap_err()
747                .to_string()
748                .contains("Registration disabled")
749        );
750
751        // Test invalid prompt error
752        let invalid_request = RegistrationRequest {
753            prompt: Some("login".to_string()), // Missing "create"
754            ..request.clone()
755        };
756
757        let result = manager.initiate_registration(invalid_request);
758        assert!(result.is_err());
759        assert!(result.unwrap_err().to_string().contains("Invalid request"));
760
761        // Test invalid metadata error
762        let invalid_metadata_request = RegistrationRequest {
763            registration_metadata: Some("invalid json".to_string()),
764            ..request
765        };
766
767        let result = manager.initiate_registration(invalid_metadata_request);
768        assert!(result.is_err());
769        assert!(result.unwrap_err().to_string().contains("Invalid metadata"));
770    }
771
772    #[test]
773    fn test_error_manager_session_handling() {
774        let mut manager = RegistrationManager::new(RegistrationConfig::default());
775
776        // Test session not found error
777        let result = manager.update_registration_data("nonexistent", HashMap::new());
778        assert!(result.is_err());
779        assert!(result.unwrap_err().to_string().contains("Session error"));
780
781        // Test validation completeness with missing fields
782        let config = RegistrationConfig {
783            required_fields: vec!["email".to_string(), "given_name".to_string()],
784            ..Default::default()
785        };
786        let mut manager = RegistrationManager::new(config);
787
788        let registration_data = RegistrationData {
789            registration_id: "test123".to_string(),
790            email: Some("user@example.com".to_string()),
791            given_name: None, // Missing required field
792            ..Default::default()
793        };
794
795        manager
796            .registration_sessions
797            .insert("test123".to_string(), registration_data);
798
799        let result =
800            manager.validate_registration_completeness("test123", Some("state456".to_string()));
801        assert!(result.is_err());
802        assert!(
803            result
804                .unwrap_err()
805                .to_string()
806                .contains("Registration incomplete")
807        );
808    }
809
810    #[test]
811    fn test_error_manager_custom_configuration() {
812        use crate::server::oidc::oidc_error_extensions::{OidcErrorCode, OidcErrorManager};
813
814        let mut custom_error_manager = OidcErrorManager::default();
815        custom_error_manager.add_custom_error_mapping(
816            "custom_registration_error".to_string(),
817            OidcErrorCode::RegistrationRequired,
818        );
819
820        let manager = RegistrationManager::with_error_manager(
821            RegistrationConfig::default(),
822            custom_error_manager,
823        );
824
825        // Test error manager is properly set
826        assert!(
827            manager
828                .get_error_manager()
829                .has_custom_mapping("custom_registration_error")
830        );
831
832        // Test error response creation
833        let error_response =
834            manager.create_registration_disabled_error(Some("test_state".to_string()));
835        assert_eq!(error_response.state.as_ref().unwrap(), "test_state");
836
837        let session_error = manager.create_session_not_found_error(None);
838        assert_eq!(session_error.error, OidcErrorCode::SessionSelectionRequired);
839    }
840
841    #[test]
842    fn test_registration_request_detection() {
843        let manager = RegistrationManager::new(RegistrationConfig::default());
844
845        assert!(manager.is_registration_requested(Some("create")));
846        assert!(manager.is_registration_requested(Some("login create")));
847        assert!(manager.is_registration_requested(Some("create consent")));
848        assert!(!manager.is_registration_requested(Some("login")));
849        assert!(!manager.is_registration_requested(None));
850    }
851
852    #[test]
853    fn test_registration_initiation() {
854        let mut manager = RegistrationManager::new(RegistrationConfig::default());
855
856        let request = RegistrationRequest {
857            client_id: "test_client".to_string(),
858            redirect_uri: "https://client.example.com/callback".to_string(),
859            scope: "openid profile email".to_string(),
860            response_type: "code".to_string(),
861            state: Some("state123".to_string()),
862            nonce: Some("nonce456".to_string()),
863            prompt: Some("create".to_string()),
864            login_hint: Some("user@example.com".to_string()),
865            ui_locales: None,
866            registration_metadata: None,
867            claims: None,
868        };
869
870        let registration_id = manager.initiate_registration(request).unwrap();
871        assert!(!registration_id.is_empty());
872
873        let registration_data = manager.get_registration_data(&registration_id).unwrap();
874        assert_eq!(
875            registration_data.email,
876            Some("user@example.com".to_string())
877        );
878        assert!(!registration_data.completed);
879    }
880
881    #[test]
882    fn test_registration_data_validation() {
883        let mut manager = RegistrationManager::new(RegistrationConfig {
884            required_fields: vec!["email".to_string(), "given_name".to_string()],
885            ..RegistrationConfig::default()
886        });
887
888        let registration_id = "test_reg_123";
889        let registration_data = RegistrationData {
890            registration_id: registration_id.to_string(),
891            email: Some("user@example.com".to_string()),
892            given_name: None, // Missing required field
893            ..Default::default()
894        };
895
896        manager
897            .registration_sessions
898            .insert(registration_id.to_string(), registration_data);
899
900        let missing_fields = manager.validate_registration_data(registration_id).unwrap();
901        assert_eq!(missing_fields, vec!["given_name"]);
902    }
903}