Skip to content

Commit 703009d

Browse files
committed
feat: consolidate duplicate OIDC callback handling logic (#157)
- Add shared callback.rs with parsing, form building, and validation helpers - Refactor session::parse_redirect() to use parse_authorization_callback() - Refactor end_session::parse_redirect() to use parse_end_session_callback() - Refactor session::exchange_code() to use build_token_request_body() - Extract OIDC endpoint extraction to extract_oidc_endpoints() - Refactor state::refresh_with_additional_parameters() with shared helpers - Replace local ensure_unique_parameter_names with callback module in ffi.rs - Replace local ensure_unique_parameter_names with callback module in windows/data.rs Fixes #157
1 parent f854c37 commit 703009d

7 files changed

Lines changed: 411 additions & 186 deletions

File tree

‎src/authorization/callback.rs‎

Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
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+

‎src/authorization/end_session.rs‎

Lines changed: 9 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
use std::collections::{BTreeMap, HashSet};
1+
use std::collections::BTreeMap;
22

33
use url::Url;
44

55
use super::{
6+
callback::{parse_end_session_callback, parse_error_to_auth_end_session_error},
67
validation::{
78
has_valid_query_encoding, reject_reserved_end_session_parameters,
89
validate_end_session_redirect_uri_match, validate_redirect_uri,
@@ -110,52 +111,14 @@ impl EndSessionSession {
110111

111112
/// Validates the post-logout redirect and returns its state and extra parameters.
112113
pub fn parse_redirect(&self, redirect: &Url) -> Result<EndSessionResponse> {
113-
let expected_redirect_uri =
114-
self.post_logout_redirect_uri
115-
.as_ref()
116-
.ok_or(AuthError::InvalidEndSessionResponse(
117-
"no post-logout redirect URI was requested",
118-
))?;
119-
validate_end_session_redirect_uri_match(expected_redirect_uri, redirect)?;
120-
if !has_valid_query_encoding(redirect) {
121-
return Err(AuthError::InvalidEndSessionResponse(
122-
"response query has invalid percent encoding or UTF-8",
123-
));
124-
}
125-
126-
let mut parameters = BTreeMap::new();
127-
let mut names = HashSet::new();
128-
for (name, value) in redirect.query_pairs() {
129-
if !names.insert(name.to_string()) {
130-
return Err(AuthError::InvalidEndSessionResponse(
131-
"response contains a duplicate parameter",
132-
));
133-
}
134-
parameters.insert(name.into_owned(), value.into_owned());
135-
}
136-
137-
for (name, expected_value) in expected_redirect_uri.query_pairs() {
138-
if parameters.get(name.as_ref()) != Some(&expected_value.into_owned()) {
139-
return Err(AuthError::InvalidEndSessionResponse(
140-
"post-logout redirect URI query does not match",
141-
));
142-
}
143-
parameters.remove(name.as_ref());
144-
}
145-
146-
let returned_state =
147-
parameters
148-
.remove("state")
149-
.ok_or(AuthError::InvalidEndSessionResponse(
150-
"response is missing state",
151-
))?;
152-
if self.state.as_deref() != Some(returned_state.as_str()) {
153-
return Err(AuthError::InvalidEndSessionResponse("state mismatch"));
154-
}
155-
114+
let (state, additional_parameters) = match callback::parse_end_session_callback(redirect, &self.state) {
115+
Ok(pair) => pair,
116+
Err(err) => return Err(parse_error_to_auth_end_session_error(err)),
117+
};
118+
156119
Ok(EndSessionResponse {
157-
state: returned_state,
158-
additional_parameters: parameters,
120+
state,
121+
additional_parameters,
159122
})
160123
}
161124
}

‎src/authorization/mod.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
mod callback;
12
mod config;
23
mod discovery;
34
mod end_session;
@@ -11,9 +12,12 @@ mod state;
1112
mod test_support;
1213
mod validation;
1314

15+
pub use callback::{ParseError, parse_authorization_callback, parse_error_to_auth_error, parse_error_to_auth_end_session_error};
1416
pub use config::ServiceConfiguration;
1517
pub use end_session::{EndSessionRequest, EndSessionResponse, EndSessionSession};
1618
pub use registration::{ClientRegistrationRequest, ClientRegistrationResponse};
1719
pub use revocation::{revoke_token, RevocationTokenType};
1820
pub use session::{AuthorizationRequest, AuthorizationResponse, AuthorizationSession};
1921
pub use state::{AuthenticationState, TokenResponse};
22+
23+
pub use callback as Callback;

0 commit comments

Comments
 (0)