mas_handlers/oauth2/authorization/
mod.rs1use std::collections::BTreeMap;
9
10use axum::{
11 extract::State,
12 response::{IntoResponse, Response},
13};
14use axum_extra::extract::Query;
15use hyper::StatusCode;
16use mas_axum_utils::{GenericError, InternalError, SessionInfoExt, cookies::CookieJar};
17use mas_data_model::{AuthorizationCode, BoxClock, BoxRng, Pkce};
18use mas_router::{PostAuthAction, UrlBuilder};
19use mas_storage::{
20 BoxRepository,
21 oauth2::{OAuth2AuthorizationGrantRepository, OAuth2ClientRepository},
22};
23use mas_templates::Templates;
24use oauth2_types::{
25 errors::{ClientError, ClientErrorCode},
26 pkce,
27 requests::{AuthorizationRequest, GrantType, Prompt, ResponseMode},
28 response_type::ResponseType,
29};
30use rand::{RngExt, distr::Alphanumeric};
31use serde::Deserialize;
32use thiserror::Error;
33
34use self::callback::CallbackDestination;
35use crate::{BoundActivityTracker, PreferredLanguage, impl_from_error_for_route};
36
37mod callback;
38pub(crate) mod consent;
39
40#[derive(Debug, Error)]
41pub enum RouteError {
42 #[error(transparent)]
43 Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
44
45 #[error("could not find client")]
46 ClientNotFound,
47
48 #[error("invalid response mode")]
49 InvalidResponseMode,
50
51 #[error("invalid parameters")]
52 IntoCallbackDestination(#[from] self::callback::IntoCallbackDestinationError),
53
54 #[error("invalid redirect uri")]
55 UnknownRedirectUri(#[from] mas_data_model::InvalidRedirectUriError),
56}
57
58impl IntoResponse for RouteError {
59 fn into_response(self) -> axum::response::Response {
60 match self {
61 Self::Internal(e) => InternalError::new(e).into_response(),
62 e @ (Self::ClientNotFound
63 | Self::InvalidResponseMode
64 | Self::IntoCallbackDestination(_)
65 | Self::UnknownRedirectUri(_)) => {
66 GenericError::new(StatusCode::BAD_REQUEST, e).into_response()
67 }
68 }
69 }
70}
71
72impl_from_error_for_route!(mas_storage::RepositoryError);
73impl_from_error_for_route!(mas_templates::TemplateError);
74impl_from_error_for_route!(self::callback::CallbackDestinationError);
75impl_from_error_for_route!(mas_policy::LoadError);
76impl_from_error_for_route!(mas_policy::EvaluationError);
77
78#[derive(Deserialize)]
79pub(crate) struct Params {
80 #[serde(flatten)]
81 auth: AuthorizationRequest,
82
83 #[serde(flatten)]
84 pkce: Option<pkce::AuthorizationRequest>,
85}
86
87fn resolve_response_mode(
91 response_type: &ResponseType,
92 suggested_response_mode: Option<ResponseMode>,
93) -> Result<ResponseMode, RouteError> {
94 use ResponseMode as M;
95
96 if response_type.has_token() || response_type.has_id_token() {
100 match suggested_response_mode {
101 None => Ok(M::Fragment),
102 Some(M::Query) => Err(RouteError::InvalidResponseMode),
103 Some(mode) => Ok(mode),
104 }
105 } else {
106 Ok(suggested_response_mode.unwrap_or(M::Query))
108 }
109}
110
111#[tracing::instrument(
112 name = "handlers.oauth2.authorization.get",
113 fields(client.id = %params.auth.client_id),
114 skip_all,
115)]
116pub(crate) async fn get(
117 mut rng: BoxRng,
118 clock: BoxClock,
119 PreferredLanguage(locale): PreferredLanguage,
120 State(templates): State<Templates>,
121 State(url_builder): State<UrlBuilder>,
122 activity_tracker: BoundActivityTracker,
123 mut repo: BoxRepository,
124 cookie_jar: CookieJar,
125 Query(raw_parameters): Query<BTreeMap<String, String>>,
128 Query(params): Query<Params>,
129) -> Result<Response, RouteError> {
130 let client = repo
132 .oauth2_client()
133 .find_by_client_id(¶ms.auth.client_id)
134 .await?
135 .ok_or(RouteError::ClientNotFound)?;
136
137 let redirect_uri = client
139 .resolve_redirect_uri(¶ms.auth.redirect_uri)?
140 .clone();
141 let response_type = params.auth.response_type;
142 let response_mode = resolve_response_mode(&response_type, params.auth.response_mode)?;
143
144 let callback_destination = CallbackDestination::try_new(
146 &response_mode,
147 redirect_uri.clone(),
148 params.auth.state.clone(),
149 )?;
150
151 let (session_info, cookie_jar) = cookie_jar.session_info();
153
154 let res: Result<Response, RouteError> = ({
156 let templates = templates.clone();
157 let callback_destination = callback_destination.clone();
158 async move {
159 let maybe_session = session_info.load_active_session(&mut repo).await?;
160 let prompt = params.auth.prompt.as_deref().unwrap_or_default();
161
162 if params.auth.request.is_some() {
165 return Ok(callback_destination.go(
166 &templates,
167 &locale,
168 ClientError::from(ClientErrorCode::RequestNotSupported),
169 )?);
170 }
171
172 if params.auth.request_uri.is_some() {
173 return Ok(callback_destination.go(
174 &templates,
175 &locale,
176 ClientError::from(ClientErrorCode::RequestUriNotSupported),
177 )?);
178 }
179
180 if response_type.has_token() {
183 return Ok(callback_destination.go(
184 &templates,
185 &locale,
186 ClientError::from(ClientErrorCode::UnsupportedResponseType),
187 )?);
188 }
189
190 if response_type.has_id_token() && !client.grant_types.contains(&GrantType::Implicit) {
193 return Ok(callback_destination.go(
194 &templates,
195 &locale,
196 ClientError::from(ClientErrorCode::UnauthorizedClient),
197 )?);
198 }
199
200 if params.auth.registration.is_some() {
201 return Ok(callback_destination.go(
202 &templates,
203 &locale,
204 ClientError::from(ClientErrorCode::RegistrationNotSupported),
205 )?);
206 }
207
208 if prompt.contains(&Prompt::None) {
210 return Ok(callback_destination.go(
211 &templates,
212 &locale,
213 ClientError::from(ClientErrorCode::LoginRequired),
214 )?);
215 }
216
217 let code: Option<AuthorizationCode> = if response_type.has_code() {
218 if !client.grant_types.contains(&GrantType::AuthorizationCode) {
220 return Ok(callback_destination.go(
221 &templates,
222 &locale,
223 ClientError::from(ClientErrorCode::UnauthorizedClient),
224 )?);
225 }
226
227 let code: String = (&mut rng)
229 .sample_iter(&Alphanumeric)
230 .take(32)
231 .map(char::from)
232 .collect();
233
234 let pkce = params.pkce.map(|p| Pkce {
235 challenge: p.code_challenge,
236 challenge_method: p.code_challenge_method,
237 });
238
239 Some(AuthorizationCode { code, pkce })
240 } else {
241 if params.pkce.is_some() {
244 return Ok(callback_destination.go(
245 &templates,
246 &locale,
247 ClientError::from(ClientErrorCode::InvalidRequest),
248 )?);
249 }
250
251 None
252 };
253
254 let grant = repo
255 .oauth2_authorization_grant()
256 .add(
257 &mut rng,
258 &clock,
259 &client,
260 redirect_uri.clone(),
261 params.auth.scope,
262 code,
263 params.auth.state.clone(),
264 params.auth.nonce,
265 response_mode,
266 response_type.has_id_token(),
267 params.auth.login_hint,
268 Some(locale.to_string()),
269 raw_parameters,
270 )
271 .await?;
272 let continue_grant = PostAuthAction::continue_grant(grant.id);
273
274 let res = match maybe_session {
275 None if prompt.contains(&Prompt::Create) => {
276 repo.save().await?;
278
279 url_builder
280 .redirect(&mas_router::Register::and_then(continue_grant))
281 .into_response()
282 }
283
284 None => {
285 repo.save().await?;
287
288 let mut url = mas_router::Login::and_then(continue_grant);
289
290 url = if let Some(login_hint) = grant.login_hint {
291 url.with_login_hint(login_hint)
292 } else {
293 url
294 };
295
296 url_builder.redirect(&url).into_response()
297 }
298
299 Some(user_session) => {
300 repo.save().await?;
302
303 activity_tracker
304 .record_browser_session(&clock, &user_session)
305 .await;
306 url_builder
307 .redirect(&mas_router::Consent(grant.id))
308 .into_response()
309 }
310 };
311
312 Ok(res)
313 }
314 })
315 .await;
316
317 let response = match res {
318 Ok(r) => r,
319 Err(err) => {
320 tracing::error!(message = &err as &dyn std::error::Error);
321 callback_destination.go(
322 &templates,
323 &locale,
324 ClientError::from(ClientErrorCode::ServerError),
325 )?
326 }
327 };
328
329 Ok((cookie_jar, response).into_response())
330}