Skip to main content

mas_handlers/oauth2/authorization/
mod.rs

1// Copyright 2025, 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2021-2024 The Matrix.org Foundation C.I.C.
4//
5// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
6// Please see LICENSE files in the repository root for full details.
7
8use 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
87/// Given a list of response types and an optional user-defined response mode,
88/// figure out what response mode must be used, and emit an error if the
89/// suggested response mode isn't allowed for the given response types.
90fn 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 the response type includes either "token" or "id_token", the default
97    // response mode is "fragment" and the response mode "query" must not be
98    // used
99    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        // In other cases, all response modes are allowed, defaulting to "query"
107        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    // Extract the query parameters twice: once to get the raw query string,
126    // and once to parse it into a structured `Params` object.
127    Query(raw_parameters): Query<BTreeMap<String, String>>,
128    Query(params): Query<Params>,
129) -> Result<Response, RouteError> {
130    // First, figure out what client it is
131    let client = repo
132        .oauth2_client()
133        .find_by_client_id(&params.auth.client_id)
134        .await?
135        .ok_or(RouteError::ClientNotFound)?;
136
137    // And resolve the redirect_uri and response_mode
138    let redirect_uri = client
139        .resolve_redirect_uri(&params.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    // Now we have a proper callback destination to go to on error
145    let callback_destination = CallbackDestination::try_new(
146        &response_mode,
147        redirect_uri.clone(),
148        params.auth.state.clone(),
149    )?;
150
151    // Get the session info from the cookie
152    let (session_info, cookie_jar) = cookie_jar.session_info();
153
154    // One day, we will have try blocks
155    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            // Check if the request/request_uri/registration params are used. If so, reply
163            // with the right error since we don't support them.
164            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            // Check if the client asked for a `token` response type, and bail out if it's
181            // the case, since we don't support them
182            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 the client asked for a `id_token` response type, we must check if it can
191            // use the `implicit` grant type
192            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            // Fail early if prompt=none; we never let it go through
209            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                // Check if it is allowed to use this grant type
219                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                // 32 random alphanumeric characters, about 190bit of entropy
228                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 the request had PKCE params but no code asked, it should get back with an
242                // error
243                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                    // Client asked for a registration, show the registration prompt
277                    repo.save().await?;
278
279                    url_builder
280                        .redirect(&mas_router::Register::and_then(continue_grant))
281                        .into_response()
282                }
283
284                None => {
285                    // Other cases where we don't have a session, ask for a login
286                    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                    // TODO: better support for prompt=create when we have a session
301                    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}