|
| 1 | +//! Shared callback parsing and form building logic for OAuth/OIDC operations. |
| 2 | +//! |
| 3 | +//! This module provides pure functions that can be called from different layers |
| 4 | +//! (core, FFI, Windows) to consolidate duplicate code while preserving error |
| 5 | +//! variants and messages specific to each layer. |
| 6 | +
|
| 7 | +use std::collections::{BTreeMap, HashSet}; |
| 8 | + |
| 9 | +use url::{form_urlencoded, HasQueryData, Url}; |
| 10 | + |
| 11 | +use crate::validation::{has_valid_query_encoding, validate_redirect_uri_match}; |
| 12 | + |
| 13 | +/// Validates and parses a callback URI query into a map of parameters. |
| 14 | +/// |
| 15 | +/// Performs the following checks: |
| 16 | +/// - URL has valid percent encoding and UTF-8 |
| 17 | +/// - No duplicate parameter names |
| 18 | +/// - Redirect URI query matches (except for state, code, error) |
| 19 | +/// |
| 20 | +/// Returns a map of remaining parameters after removing recognized ones. |
| 21 | +fn parse_callback_query_base(redirect_uri: &Url, expected_state: impl AsRef<str>) -> Result<BTreeMap<String, String>, ParseError> { |
| 22 | + validate_redirect_uri_match(redirect_uri)?; |
| 23 | + |
| 24 | + if !has_valid_query_encoding(redirect_uri) { |
| 25 | + return Err(ParseError::InvalidEncoding); |
| 26 | + } |
| 27 | + |
| 28 | + let mut parameters = BTreeMap::new(); |
| 29 | + let mut names = HashSet::new(); |
| 30 | + for (name, value) in redirect_uri.query_pairs() { |
| 31 | + if !names.insert(name.to_string()) { |
| 32 | + return Err(ParseError::DuplicateParameter); |
| 33 | + } |
| 34 | + parameters.insert(name.into_owned(), value.into_owned()); |
| 35 | + } |
| 36 | + |
| 37 | + // Validate redirect URI query matches (except state, code, error) |
| 38 | + for (name, expected_value) in redirect_uri.query_pairs() { |
| 39 | + if name == "state" || name == "code" || name == "error" { |
| 40 | + continue; |
| 41 | + } |
| 42 | + if parameters.get(name.as_ref()) != Some(&expected_value.into_owned()) { |
| 43 | + return Err(ParseError::RedirectUriMismatch); |
| 44 | + } |
| 45 | + parameters.remove(name.as_ref()); |
| 46 | + } |
| 47 | + |
| 48 | + // Check state |
| 49 | + let returned_state = parameters.remove("state").ok_or(ParseError::MissingState)?; |
| 50 | + if expected_state.as_ref() != returned_state.as_str() { |
| 51 | + return Err(ParseError::StateMismatch); |
| 52 | + } |
| 53 | + parameters.remove("state"); |
| 54 | + |
| 55 | + // Extract code or error |
| 56 | + let code = parameters.remove("code"); |
| 57 | + let error = parameters.remove("error"); |
| 58 | + if code.is_some() && error.is_some() { |
| 59 | + return Err(ParseError::BothCodeAndError); |
| 60 | + } |
| 61 | + |
| 62 | + Ok(parameters) |
| 63 | +} |
| 64 | + |
| 65 | +/// Parses an authorization callback. |
| 66 | +pub fn parse_authorization_callback(redirect_uri: &Url, state: impl AsRef<str>) -> Result<(String, BTreeMap<String, String>), ParseError> { |
| 67 | + let mut parameters = parse_callback_query_base(redirect_uri, state)?; |
| 68 | + |
| 69 | + let code = parameters.remove("code").ok_or(ParseError::MissingCode)?; |
| 70 | + if code.is_empty() { |
| 71 | + return Err(ParseError::EmptyCode); |
| 72 | + } |
| 73 | + |
| 74 | + Ok((code, parameters)) |
| 75 | +} |
| 76 | + |
| 77 | +/// Parses an end-session callback. |
| 78 | +pub fn parse_end_session_callback(redirect_uri: &Url, state: impl AsRef<str>) -> Result<(String, BTreeMap<String, String>), ParseError> { |
| 79 | + // EndSessionResponse doesn't expect a code or error |
| 80 | + let mut parameters = BTreeMap::new(); |
| 81 | + |
| 82 | + if !has_valid_query_encoding(redirect_uri) { |
| 83 | + return Err(ParseError::InvalidEncoding); |
| 84 | + } |
| 85 | + |
| 86 | + let mut names = HashSet::new(); |
| 87 | + for (name, value) in redirect_uri.query_pairs() { |
| 88 | + if !names.insert(name.to_string()) { |
| 89 | + return Err(ParseError::DuplicateParameter); |
| 90 | + } |
| 91 | + parameters.insert(name.into_owned(), value.into_owned()); |
| 92 | + } |
| 93 | + |
| 94 | + // Validate redirect URI query matches |
| 95 | + let expected_redirect_uri = redirect_uri; |
| 96 | + for (name, expected_value) in expected_redirect_uri.query_pairs() { |
| 97 | + if parameters.get(name.as_ref()) != Some(&expected_value.into_owned()) { |
| 98 | + return Err(ParseError::RedirectUriMismatch); |
| 99 | + } |
| 100 | + parameters.remove(name.as_ref()); |
| 101 | + } |
| 102 | + |
| 103 | + let returned_state = parameters.remove("state").ok_or(ParseError::MissingState)?; |
| 104 | + |
| 105 | + Ok((returned_state, parameters)) |
| 106 | +} |
| 107 | + |
| 108 | +/// Validates and parses an authorization error from the callback. |
| 109 | +pub fn parse_authorization_error(redirect_uri: &Url) -> Result<Option<(String, Option<String>)>, ParseError> { |
| 110 | + let mut parameters = BTreeMap::new(); |
| 111 | + |
| 112 | + if !has_valid_query_encoding(redirect_uri) { |
| 113 | + return Err(ParseError::InvalidEncoding); |
| 114 | + } |
| 115 | + |
| 116 | + let mut names = HashSet::new(); |
| 117 | + for (name, value) in redirect_uri.query_pairs() { |
| 118 | + if !names.insert(name.to_string()) { |
| 119 | + return Err(ParseError::DuplicateParameter); |
| 120 | + } |
| 121 | + parameters.insert(name.into_owned(), value.into_owned()); |
| 122 | + } |
| 123 | + |
| 124 | + // EndSessionResponse doesn't expect a code or error |
| 125 | + let error = parameters.remove("error").ok_or(ParseError::MissingError)?; |
| 126 | + |
| 127 | + if error.is_empty() { |
| 128 | + return Err(ParseError::EmptyError); |
| 129 | + } |
| 130 | + |
| 131 | + Ok(Some((error, parameters.remove("error_description")))) |
| 132 | +} |
| 133 | + |
| 134 | +/// Error types returned by callback parsing functions. |
| 135 | +#[derive(Debug)] |
| 136 | +pub enum ParseError { |
| 137 | + /// The redirect URI has invalid percent encoding or UTF-8 |
| 138 | + InvalidEncoding, |
| 139 | + |
| 140 | + /// The response contains a duplicate parameter |
| 141 | + DuplicateParameter, |
| 142 | + |
| 143 | + /// The response query does not match the registered redirect URI |
| 144 | + RedirectUriMismatch, |
| 145 | + |
| 146 | + /// Response is missing state |
| 147 | + MissingState, |
| 148 | + |
| 149 | + /// State mismatch between session and response |
| 150 | + StateMismatch, |
| 151 | + |
| 152 | + /// Both code and error are present in the response |
| 153 | + BothCodeAndError, |
| 154 | + |
| 155 | + /// Missing code in authorization response |
| 156 | + MissingCode, |
| 157 | + |
| 158 | + /// Authorization code must not be empty |
| 159 | + EmptyCode, |
| 160 | + |
| 161 | + /// Missing error in authorization error response |
| 162 | + MissingError, |
| 163 | + |
| 164 | + /// Authorization error must not be empty |
| 165 | + EmptyError, |
| 166 | +} |
| 167 | + |
| 168 | +impl std::fmt::Display for ParseError { |
| 169 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 170 | + match self { |
| 171 | + Self::InvalidEncoding => write!(f, "response query has invalid percent encoding or UTF-8"), |
| 172 | + Self::DuplicateParameter => write!(f, "response contains a duplicate parameter"), |
| 173 | + Self::RedirectUriMismatch => write!(f, "redirect URI query does not match"), |
| 174 | + Self::MissingState => write!(f, "response is missing state"), |
| 175 | + Self::StateMismatch => write!(f, "state mismatch"), |
| 176 | + Self::BothCodeAndError => write!(f, "response contains both code and error"), |
| 177 | + Self::MissingCode => write!(f, "missing authorization code"), |
| 178 | + Self::EmptyCode => write!(f, "authorization code must not be empty"), |
| 179 | + Self::MissingError => write!(f, "missing authorization error"), |
| 180 | + Self::EmptyError => write!(f, "authorization error must not be empty"), |
| 181 | + } |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +impl std::error::Error for ParseError {} |
| 186 | + |
| 187 | +/// Helper to map ParseError to AuthError (core authorization layer). |
| 188 | +pub fn parse_error_to_auth_error(err: ParseError) -> crate::AuthError { |
| 189 | + match err { |
| 190 | + ParseError::InvalidEncoding => crate::AuthError::InvalidAuthorizationResponse( |
| 191 | + "response query has invalid percent encoding or UTF-8", |
| 192 | + ), |
| 193 | + ParseError::DuplicateParameter => crate::AuthError::InvalidAuthorizationResponse( |
| 194 | + "response contains a duplicate parameter", |
| 195 | + ), |
| 196 | + ParseError::RedirectUriMismatch => crate::AuthError::InvalidAuthorizationResponse( |
| 197 | + "redirect URI query does not match", |
| 198 | + ), |
| 199 | + ParseError::MissingState | ParseError::StateMismatch => crate::AuthError::InvalidAuthorizationResponse("state mismatch"), |
| 200 | + ParseError::BothCodeAndError => crate::AuthError::InvalidAuthorizationResponse( |
| 201 | + "response contains both code and error", |
| 202 | + ), |
| 203 | + ParseError::MissingCode => crate::AuthError::InvalidAuthorizationResponse( |
| 204 | + "missing authorization code", |
| 205 | + ), |
| 206 | + ParseError::EmptyCode => crate::AuthError::InvalidAuthorizationResponse( |
| 207 | + "authorization code must not be empty", |
| 208 | + ), |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +/// Helper to map ParseError to AuthError (end-session layer). |
| 213 | +pub fn parse_error_to_auth_end_session_error(err: ParseError) -> crate::AuthError { |
| 214 | + match err { |
| 215 | + ParseError::InvalidEncoding => crate::AuthError::InvalidEndSessionResponse( |
| 216 | + "response query has invalid percent encoding or UTF-8", |
| 217 | + ), |
| 218 | + ParseError::DuplicateParameter => crate::AuthError::InvalidEndSessionResponse( |
| 219 | + "response contains a duplicate parameter", |
| 220 | + ), |
| 221 | + ParseError::RedirectUriMismatch => crate::AuthError::InvalidEndSessionResponse( |
| 222 | + "post-logout redirect URI query does not match", |
| 223 | + ), |
| 224 | + ParseError::MissingState | ParseError::StateMismatch => crate::AuthError::InvalidEndSessionResponse("state mismatch"), |
| 225 | + _ => crate::AuthError::InvalidEndSessionResponse("invalid end-session response"), |
| 226 | + } |
| 227 | +} |
| 228 | + |
| 229 | +/// Builds a token exchange request body with fixed parameters plus additional ones. |
| 230 | +pub fn build_token_request_body( |
| 231 | + grant_type: &str, |
| 232 | + code_or_refresh_token: &str, |
| 233 | + redirect_uri: &Url, |
| 234 | + client_id: &str, |
| 235 | + code_verifier: Option<&str>, |
| 236 | + additional_parameters: &BTreeMap<String, String>, |
| 237 | +) -> Vec<u8> { |
| 238 | + let mut form = form_urlencoded::Serializer::new(String::new()); |
| 239 | + |
| 240 | + // Grant type and required parameters |
| 241 | + form.append_pair("grant_type", grant_type); |
| 242 | + |
| 243 | + match grant_type { |
| 244 | + "authorization_code" => { |
| 245 | + form.append_pair("code", code_or_refresh_token); |
| 246 | + form.append_pair("redirect_uri", redirect_uri.as_str()); |
| 247 | + form.append_pair("client_id", client_id); |
| 248 | + if let Some(verifier) = code_verifier { |
| 249 | + form.append_pair("code_verifier", verifier); |
| 250 | + } |
| 251 | + }, |
| 252 | + "refresh_token" => { |
| 253 | + form.append_pair("refresh_token", code_or_refresh_token); |
| 254 | + form.append_pair("client_id", client_id); |
| 255 | + }, |
| 256 | + _ => {} |
| 257 | + }; |
| 258 | + |
| 259 | + // Additional parameters |
| 260 | + for (name, value) in additional_parameters { |
| 261 | + form.append_pair(name, value); |
| 262 | + } |
| 263 | + |
| 264 | + form.finish().into_bytes() |
| 265 | +} |
| 266 | + |
| 267 | +/// Checks that all parameter names are unique. |
| 268 | +pub fn ensure_unique_parameter_names<T>(parameters: &[T]) -> std::result::Result<(), String> |
| 269 | +where |
| 270 | + T: AsRef<str>, |
| 271 | +{ |
| 272 | + let mut names = BTreeSet::new(); |
| 273 | + if parameters.iter().any(|parameter| !names.insert(parameter.as_ref())) { |
| 274 | + return Err("parameter names must be unique".to_owned()); |
| 275 | + } |
| 276 | + Ok(()) |
| 277 | +} |
| 278 | + |
0 commit comments