Skip to main content

auth_framework/server/oidc/
oidc_response_modes.rs

1//! OpenID Connect Response Modes Extension
2//!
3//! This module implements additional OAuth 2.0 and OpenID Connect response modes
4//! beyond the standard 'query' and 'fragment' modes defined in the core specifications.
5//!
6//! # Implemented Response Modes
7//!
8//! - **Form Post Response Mode** (OAuth 2.0 Form Post Response Mode)
9//! - **JWT Response Mode** (JARM - JWT Secured Authorization Response Mode)
10//! - **Multiple Response Types** (OAuth 2.0 Multiple Response Types)
11//!
12//! These form the foundation for many other OpenID specifications.
13
14use crate::errors::{AuthError, Result};
15use html_escape;
16use serde::{Deserialize, Serialize};
17use std::collections::HashMap;
18
19/// Response Mode types supported
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
21pub enum ResponseMode {
22    /// Standard query parameter response
23    Query,
24    /// Fragment-based response
25    Fragment,
26    /// Form POST response
27    FormPost,
28    /// JWT-secured response (JARM)
29    JwtQuery,
30    /// JWT-secured fragment response
31    JwtFragment,
32    /// JWT-secured form POST response
33    JwtFormPost,
34}
35
36/// Multiple Response Types handler
37#[derive(Debug, Clone)]
38pub struct MultipleResponseTypesManager {
39    /// Configuration for response types
40    config: MultipleResponseTypesConfig,
41}
42
43#[derive(Debug, Clone)]
44pub struct MultipleResponseTypesConfig {
45    /// Supported response types
46    pub supported_response_types: Vec<String>,
47    /// Enable multiple response types in single request
48    pub enable_multiple_types: bool,
49}
50
51impl Default for MultipleResponseTypesConfig {
52    fn default() -> Self {
53        Self {
54            supported_response_types: vec![
55                "code".to_string(),
56                "token".to_string(),
57                "id_token".to_string(),
58                "code token".to_string(),
59                "code id_token".to_string(),
60                "token id_token".to_string(),
61                "code token id_token".to_string(),
62            ],
63            enable_multiple_types: true,
64        }
65    }
66}
67
68/// Form Post Response Mode implementation
69#[derive(Clone)]
70pub struct FormPostResponseMode {
71    /// Target redirect URI
72    pub redirect_uri: String,
73    /// Form parameters to post
74    pub parameters: HashMap<String, String>,
75}
76
77impl std::fmt::Debug for FormPostResponseMode {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        let mut d = f.debug_struct("FormPostResponseMode");
80        d.field("redirect_uri", &self.redirect_uri);
81        d.field(
82            "parameters",
83            &crate::utils::redact::redacted(&self.parameters),
84        );
85        d.finish()
86    }
87}
88
89/// JARM (JWT Response Mode) implementation
90#[derive(Clone)]
91pub struct JarmResponseMode {
92    /// JWT response token
93    pub response_token: String,
94    /// Response mode for JWT delivery
95    pub delivery_mode: ResponseMode,
96}
97
98impl std::fmt::Debug for JarmResponseMode {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        let mut d = f.debug_struct("JarmResponseMode");
101        d.field(
102            "response_token",
103            &crate::utils::redact::redacted(&self.response_token),
104        );
105        d.field("delivery_mode", &self.delivery_mode);
106        d.finish()
107    }
108}
109
110impl MultipleResponseTypesManager {
111    /// Create new manager
112    pub fn new(config: MultipleResponseTypesConfig) -> Self {
113        Self { config }
114    }
115
116    /// Parse and validate response type parameter
117    pub fn parse_response_type(&self, response_type: &str) -> Result<Vec<String>> {
118        let types: Vec<String> = response_type
119            .split_whitespace()
120            .map(|s| s.to_string())
121            .collect();
122
123        // Validate each type
124        for response_type in &types {
125            if !self.is_supported_response_type(response_type) {
126                return Err(AuthError::validation(format!(
127                    "Unsupported response_type: {}",
128                    response_type
129                )));
130            }
131        }
132
133        // Validate combinations
134        self.validate_response_type_combination(&types)?;
135
136        Ok(types)
137    }
138
139    /// Check if response type is supported
140    pub fn is_supported_response_type(&self, response_type: &str) -> bool {
141        let full_type = match response_type {
142            "code" | "token" | "id_token" => response_type.to_string(),
143            _ => return false,
144        };
145
146        self.config.supported_response_types.contains(&full_type)
147            || self
148                .config
149                .supported_response_types
150                .iter()
151                .any(|t| t.contains(response_type))
152    }
153
154    /// Validate response type combinations
155    fn validate_response_type_combination(&self, types: &[String]) -> Result<()> {
156        if types.is_empty() {
157            return Err(AuthError::validation("Empty response_type"));
158        }
159
160        // Specific validation rules for combinations
161        if types.contains(&"token".to_string()) || types.contains(&"id_token".to_string()) {
162            // Implicit flow requirements - should have nonce for id_token
163            // This will be validated at the authorization level
164        }
165
166        if types.len() > 3 {
167            return Err(AuthError::validation("Too many response types"));
168        }
169
170        Ok(())
171    }
172
173    /// Generate response based on types
174    pub async fn generate_response(
175        &self,
176        response_types: &[String],
177        authorization_code: Option<String>,
178        access_token: Option<String>,
179        id_token: Option<String>,
180    ) -> Result<HashMap<String, String>> {
181        let mut response = HashMap::new();
182
183        for response_type in response_types {
184            match response_type.as_str() {
185                "code" => {
186                    if let Some(code) = &authorization_code {
187                        response.insert("code".to_string(), code.clone());
188                    }
189                }
190                "token" => {
191                    if let Some(token) = &access_token {
192                        response.insert("access_token".to_string(), token.clone());
193                        response.insert("token_type".to_string(), "Bearer".to_string());
194                        // Add expires_in, scope, etc.
195                        response.insert("expires_in".to_string(), "3600".to_string());
196                    }
197                }
198                "id_token" => {
199                    if let Some(token) = &id_token {
200                        response.insert("id_token".to_string(), token.clone());
201                    }
202                }
203                _ => {
204                    return Err(AuthError::validation(format!(
205                        "Unsupported response type: {}",
206                        response_type
207                    )));
208                }
209            }
210        }
211
212        Ok(response)
213    }
214}
215
216impl FormPostResponseMode {
217    /// Create new form post response
218    pub fn new(redirect_uri: String, parameters: HashMap<String, String>) -> Self {
219        Self {
220            redirect_uri,
221            parameters,
222        }
223    }
224
225    /// Generate HTML form for auto-submission
226    pub fn generate_html_form(&self) -> String {
227        let mut form = format!(
228            r#"<!DOCTYPE html>
229<html>
230<head>
231    <title>Authorization Response</title>
232</head>
233<body>
234    <form method="post" action="{}" id="response_form">
235"#,
236            self.redirect_uri
237        );
238
239        for (name, value) in &self.parameters {
240            form.push_str(&format!(
241                r#"        <input type="hidden" name="{}" value="{}" />
242"#,
243                html_escape::encode_text(name),
244                html_escape::encode_text(value)
245            ));
246        }
247
248        form.push_str(
249            r#"    </form>
250    <script>
251        window.onload = function() {
252            document.getElementById('response_form').submit();
253        };
254    </script>
255</body>
256</html>"#,
257        );
258
259        form
260    }
261}
262
263impl JarmResponseMode {
264    /// Create new JARM response
265    pub fn new(response_token: String, delivery_mode: ResponseMode) -> Self {
266        Self {
267            response_token,
268            delivery_mode,
269        }
270    }
271
272    /// Generate JARM response parameters
273    pub fn generate_response_parameters(&self) -> HashMap<String, String> {
274        let mut params = HashMap::new();
275        params.insert("response".to_string(), self.response_token.clone());
276        params
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    #[test]
285    fn test_multiple_response_types_parsing() {
286        let manager = MultipleResponseTypesManager::new(MultipleResponseTypesConfig::default());
287
288        // Test single response type
289        let result = manager.parse_response_type("code").unwrap();
290        assert_eq!(result, vec!["code"]);
291
292        // Test multiple response types
293        let result = manager.parse_response_type("code token").unwrap();
294        assert_eq!(result, vec!["code", "token"]);
295
296        // Test invalid response type
297        assert!(manager.parse_response_type("invalid").is_err());
298    }
299
300    #[test]
301    fn test_form_post_html_generation() {
302        let mut params = HashMap::new();
303        params.insert("code".to_string(), "auth_code_123".to_string());
304        params.insert("state".to_string(), "client_state".to_string());
305
306        let form_post =
307            FormPostResponseMode::new("https://client.example.com/callback".to_string(), params);
308
309        let html = form_post.generate_html_form();
310        assert!(html.contains("auth_code_123"));
311        assert!(html.contains("client_state"));
312        assert!(html.contains("https://client.example.com/callback"));
313    }
314
315    #[test]
316    fn test_jarm_response_generation() {
317        let jarm = JarmResponseMode::new(
318            "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...".to_string(),
319            ResponseMode::JwtQuery,
320        );
321
322        let params = jarm.generate_response_parameters();
323        assert!(params.contains_key("response"));
324        assert!(params["response"].starts_with("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9"));
325    }
326}