Skip to content

Commit 85d9133

Browse files
committed
Merge pull request #201 from ProjectFlora/issue-156-split-authorization-module
Split src/authorization.rs into responsibility modules
2 parents 5a03f09 + b0d458e commit 85d9133

14 files changed

Lines changed: 4523 additions & 4059 deletions

‎src/authorization.rs‎

Lines changed: 0 additions & 4059 deletions
This file was deleted.

‎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/config.rs‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
use url::Url;
2+
3+
use super::validation::{
4+
validate_endpoint, validate_issuer, validate_logout_endpoint, validate_oidc_endpoint,
5+
validate_registration_endpoint, validate_revocation_endpoint,
6+
};
7+
use crate::{id_token::JwksCache, Result};
8+
9+
#[derive(Clone)]
10+
/// Authorization, token, OIDC, registration, and end-session endpoint configuration.
11+
pub struct ServiceConfiguration {
12+
pub(super) authorization_endpoint: Url,
13+
pub(super) token_endpoint: Url,
14+
pub(super) revocation_endpoint: Option<Url>,
15+
pub(super) end_session_endpoint: Option<Url>,
16+
pub(super) registration_endpoint: Option<Url>,
17+
pub(super) issuer: Option<Url>,
18+
pub(super) jwks_uri: Option<Url>,
19+
pub(super) jwks_cache: JwksCache,
20+
}
21+
22+
impl ServiceConfiguration {
23+
/// Creates a configuration from explicit authorization and token endpoints.
24+
pub fn new(authorization_endpoint: Url, token_endpoint: Url) -> Result<Self> {
25+
validate_endpoint(&authorization_endpoint)?;
26+
validate_endpoint(&token_endpoint)?;
27+
28+
Ok(Self {
29+
authorization_endpoint,
30+
token_endpoint,
31+
revocation_endpoint: None,
32+
end_session_endpoint: None,
33+
registration_endpoint: None,
34+
issuer: None,
35+
jwks_uri: None,
36+
jwks_cache: JwksCache::default(),
37+
})
38+
}
39+
40+
/// Adds an OAuth 2.0 token revocation endpoint. It must use HTTPS, or HTTP
41+
/// on a loopback host (`127.0.0.0/8`, `::1`, or `localhost`).
42+
pub fn with_revocation_endpoint(mut self, endpoint: Url) -> Result<Self> {
43+
validate_revocation_endpoint(&endpoint)?;
44+
self.revocation_endpoint = Some(endpoint);
45+
Ok(self)
46+
}
47+
48+
/// Adds an HTTPS end-session endpoint.
49+
pub fn with_end_session_endpoint(mut self, endpoint: Url) -> Result<Self> {
50+
validate_logout_endpoint(&endpoint)?;
51+
self.end_session_endpoint = Some(endpoint);
52+
Ok(self)
53+
}
54+
55+
/// Adds an HTTPS dynamic client registration endpoint.
56+
pub fn with_registration_endpoint(mut self, endpoint: Url) -> Result<Self> {
57+
validate_registration_endpoint(&endpoint)?;
58+
self.registration_endpoint = Some(endpoint);
59+
Ok(self)
60+
}
61+
62+
/// Configures the issuer and JWKS endpoint used to validate ID Tokens.
63+
pub fn with_oidc_validation_endpoints(mut self, issuer: Url, jwks_uri: Url) -> Result<Self> {
64+
validate_issuer(&issuer)?;
65+
validate_oidc_endpoint(&jwks_uri)?;
66+
self.issuer = Some(issuer);
67+
self.jwks_uri = Some(jwks_uri);
68+
self.jwks_cache = JwksCache::default();
69+
Ok(self)
70+
}
71+
72+
/// Returns the configured authorization endpoint.
73+
pub fn authorization_endpoint(&self) -> &Url {
74+
&self.authorization_endpoint
75+
}
76+
77+
/// Returns the configured token endpoint.
78+
pub fn token_endpoint(&self) -> &Url {
79+
&self.token_endpoint
80+
}
81+
82+
/// Returns the configured token revocation endpoint, if any.
83+
pub fn revocation_endpoint(&self) -> Option<&Url> {
84+
self.revocation_endpoint.as_ref()
85+
}
86+
87+
/// Returns the configured end-session endpoint, if any.
88+
pub fn end_session_endpoint(&self) -> Option<&Url> {
89+
self.end_session_endpoint.as_ref()
90+
}
91+
92+
/// Returns the configured client registration endpoint, if any.
93+
pub fn registration_endpoint(&self) -> Option<&Url> {
94+
self.registration_endpoint.as_ref()
95+
}
96+
97+
/// Returns the configured OIDC issuer, if any.
98+
pub fn issuer(&self) -> Option<&Url> {
99+
self.issuer.as_ref()
100+
}
101+
102+
/// Returns the configured JWKS endpoint, if any.
103+
pub fn jwks_uri(&self) -> Option<&Url> {
104+
self.jwks_uri.as_ref()
105+
}
106+
}

0 commit comments

Comments
 (0)