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(Debug, 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
77/// JARM (JWT Response Mode) implementation
78#[derive(Clone)]
79pub struct JarmResponseMode {
80    /// JWT response token
81    pub response_token: String,
82    /// Response mode for JWT delivery
83    pub delivery_mode: ResponseMode,
84}
85
86impl std::fmt::Debug for JarmResponseMode {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        let mut d = f.debug_struct("JarmResponseMode");
89        d.field(
90            "response_token",
91            &crate::utils::redact::redacted(&self.response_token),
92        );
93        d.field("delivery_mode", &self.delivery_mode);
94        d.finish()
95    }
96}
97
98impl MultipleResponseTypesManager {
99    /// Create new manager
100    pub fn new(config: MultipleResponseTypesConfig) -> Self {
101        Self { config }
102    }
103
104    /// Parse and validate response type parameter
105    pub fn parse_response_type(&self, response_type: &str) -> Result<Vec<String>> {
106        let types: Vec<String> = response_type
107            .split_whitespace()
108            .map(|s| s.to_string())
109            .collect();
110
111        // Validate each type
112        for response_type in &types {
113            if !self.is_supported_response_type(response_type) {
114                return Err(AuthError::validation(format!(
115                    "Unsupported response_type: {}",
116                    response_type
117                )));
118            }
119        }
120
121        // Validate combinations
122        self.validate_response_type_combination(&types)?;
123
124        Ok(types)
125    }
126
127    /// Check if response type is supported
128    pub fn is_supported_response_type(&self, response_type: &str) -> bool {
129        let full_type = match response_type {
130            "code" | "token" | "id_token" => response_type.to_string(),
131            _ => return false,
132        };
133
134        self.config.supported_response_types.contains(&full_type)
135            || self
136                .config
137                .supported_response_types
138                .iter()
139                .any(|t| t.contains(response_type))
140    }
141
142    /// Validate response type combinations
143    fn validate_response_type_combination(&self, types: &[String]) -> Result<()> {
144        if types.is_empty() {
145            return Err(AuthError::validation("Empty response_type"));
146        }
147
148        // Specific validation rules for combinations
149        if types.contains(&"token".to_string()) || types.contains(&"id_token".to_string()) {
150            // Implicit flow requirements - should have nonce for id_token
151            // This will be validated at the authorization level
152        }
153
154        if types.len() > 3 {
155            return Err(AuthError::validation("Too many response types"));
156        }
157
158        Ok(())
159    }
160
161    /// Generate response based on types
162    pub async fn generate_response(
163        &self,
164        response_types: &[String],
165        authorization_code: Option<String>,
166        access_token: Option<String>,
167        id_token: Option<String>,
168    ) -> Result<HashMap<String, String>> {
169        let mut response = HashMap::new();
170
171        for response_type in response_types {
172            match response_type.as_str() {
173                "code" => {
174                    if let Some(code) = &authorization_code {
175                        response.insert("code".to_string(), code.clone());
176                    }
177                }
178                "token" => {
179                    if let Some(token) = &access_token {
180                        response.insert("access_token".to_string(), token.clone());
181                        response.insert("token_type".to_string(), "Bearer".to_string());
182                        // Add expires_in, scope, etc.
183                        response.insert("expires_in".to_string(), "3600".to_string());
184                    }
185                }
186                "id_token" => {
187                    if let Some(token) = &id_token {
188                        response.insert("id_token".to_string(), token.clone());
189                    }
190                }
191                _ => {
192                    return Err(AuthError::validation(format!(
193                        "Unsupported response type: {}",
194                        response_type
195                    )));
196                }
197            }
198        }
199
200        Ok(response)
201    }
202}
203
204impl FormPostResponseMode {
205    /// Create new form post response
206    pub fn new(redirect_uri: String, parameters: HashMap<String, String>) -> Self {
207        Self {
208            redirect_uri,
209            parameters,
210        }
211    }
212
213    /// Generate HTML form for auto-submission
214    pub fn generate_html_form(&self) -> String {
215        let mut form = format!(
216            r#"<!DOCTYPE html>
217<html>
218<head>
219    <title>Authorization Response</title>
220</head>
221<body>
222    <form method="post" action="{}" id="response_form">
223"#,
224            self.redirect_uri
225        );
226
227        for (name, value) in &self.parameters {
228            form.push_str(&format!(
229                r#"        <input type="hidden" name="{}" value="{}" />
230"#,
231                html_escape::encode_text(name),
232                html_escape::encode_text(value)
233            ));
234        }
235
236        form.push_str(
237            r#"    </form>
238    <script>
239        window.onload = function() {
240            document.getElementById('response_form').submit();
241        };
242    </script>
243</body>
244</html>"#,
245        );
246
247        form
248    }
249}
250
251impl JarmResponseMode {
252    /// Create new JARM response
253    pub fn new(response_token: String, delivery_mode: ResponseMode) -> Self {
254        Self {
255            response_token,
256            delivery_mode,
257        }
258    }
259
260    /// Generate JARM response parameters
261    pub fn generate_response_parameters(&self) -> HashMap<String, String> {
262        let mut params = HashMap::new();
263        params.insert("response".to_string(), self.response_token.clone());
264        params
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    #[test]
273    fn test_multiple_response_types_parsing() {
274        let manager = MultipleResponseTypesManager::new(MultipleResponseTypesConfig::default());
275
276        // Test single response type
277        let result = manager.parse_response_type("code").unwrap();
278        assert_eq!(result, vec!["code"]);
279
280        // Test multiple response types
281        let result = manager.parse_response_type("code token").unwrap();
282        assert_eq!(result, vec!["code", "token"]);
283
284        // Test invalid response type
285        assert!(manager.parse_response_type("invalid").is_err());
286    }
287
288    #[test]
289    fn test_form_post_html_generation() {
290        let mut params = HashMap::new();
291        params.insert("code".to_string(), "auth_code_123".to_string());
292        params.insert("state".to_string(), "client_state".to_string());
293
294        let form_post =
295            FormPostResponseMode::new("https://client.example.com/callback".to_string(), params);
296
297        let html = form_post.generate_html_form();
298        assert!(html.contains("auth_code_123"));
299        assert!(html.contains("client_state"));
300        assert!(html.contains("https://client.example.com/callback"));
301    }
302
303    #[test]
304    fn test_jarm_response_generation() {
305        let jarm = JarmResponseMode::new(
306            "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9...".to_string(),
307            ResponseMode::JwtQuery,
308        );
309
310        let params = jarm.generate_response_parameters();
311        assert!(params.contains_key("response"));
312        assert!(params["response"].starts_with("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9"));
313    }
314}