mas_handlers/upstream_oauth2/
authorize.rs

1// Copyright 2024 New Vector Ltd.
2// Copyright 2022-2024 The Matrix.org Foundation C.I.C.
3//
4// SPDX-License-Identifier: AGPL-3.0-only
5// Please see LICENSE in the repository root for full details.
6
7use axum::{
8    extract::{Path, Query, State},
9    response::{IntoResponse, Redirect},
10};
11use hyper::StatusCode;
12use mas_axum_utils::{cookies::CookieJar, sentry::SentryEventID};
13use mas_data_model::UpstreamOAuthProvider;
14use mas_oidc_client::requests::authorization_code::AuthorizationRequestData;
15use mas_router::UrlBuilder;
16use mas_storage::{
17    BoxClock, BoxRepository, BoxRng,
18    upstream_oauth2::{UpstreamOAuthProviderRepository, UpstreamOAuthSessionRepository},
19};
20use thiserror::Error;
21use ulid::Ulid;
22
23use super::{UpstreamSessionsCookie, cache::LazyProviderInfos};
24use crate::{
25    impl_from_error_for_route, upstream_oauth2::cache::MetadataCache,
26    views::shared::OptionalPostAuthAction,
27};
28
29#[derive(Debug, Error)]
30pub(crate) enum RouteError {
31    #[error("Provider not found")]
32    ProviderNotFound,
33
34    #[error(transparent)]
35    Internal(Box<dyn std::error::Error>),
36}
37
38impl_from_error_for_route!(mas_oidc_client::error::DiscoveryError);
39impl_from_error_for_route!(mas_oidc_client::error::AuthorizationError);
40impl_from_error_for_route!(mas_storage::RepositoryError);
41
42impl IntoResponse for RouteError {
43    fn into_response(self) -> axum::response::Response {
44        let event_id = sentry::capture_error(&self);
45        let response = match self {
46            Self::ProviderNotFound => (StatusCode::NOT_FOUND, "Provider not found").into_response(),
47            Self::Internal(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
48        };
49
50        (SentryEventID::from(event_id), response).into_response()
51    }
52}
53
54#[tracing::instrument(
55    name = "handlers.upstream_oauth2.authorize.get",
56    fields(upstream_oauth_provider.id = %provider_id),
57    skip_all,
58    err,
59)]
60pub(crate) async fn get(
61    mut rng: BoxRng,
62    clock: BoxClock,
63    State(metadata_cache): State<MetadataCache>,
64    mut repo: BoxRepository,
65    State(url_builder): State<UrlBuilder>,
66    State(http_client): State<reqwest::Client>,
67    cookie_jar: CookieJar,
68    Path(provider_id): Path<Ulid>,
69    Query(query): Query<OptionalPostAuthAction>,
70) -> Result<impl IntoResponse, RouteError> {
71    let provider = repo
72        .upstream_oauth_provider()
73        .lookup(provider_id)
74        .await?
75        .filter(UpstreamOAuthProvider::enabled)
76        .ok_or(RouteError::ProviderNotFound)?;
77
78    // First, discover the provider
79    // This is done lazyly according to provider.discovery_mode and the various
80    // endpoint overrides
81    let mut lazy_metadata = LazyProviderInfos::new(&metadata_cache, &provider, &http_client);
82    lazy_metadata.maybe_discover().await?;
83
84    let redirect_uri = url_builder.upstream_oauth_callback(provider.id);
85
86    let mut data = AuthorizationRequestData::new(
87        provider.client_id.clone(),
88        provider.scope.clone(),
89        redirect_uri,
90    );
91
92    if let Some(response_mode) = provider.response_mode {
93        data = data.with_response_mode(response_mode.into());
94    }
95
96    let data = if let Some(methods) = lazy_metadata.pkce_methods().await? {
97        data.with_code_challenge_methods_supported(methods)
98    } else {
99        data
100    };
101
102    // Build an authorization request for it
103    let (mut url, data) = mas_oidc_client::requests::authorization_code::build_authorization_url(
104        lazy_metadata.authorization_endpoint().await?.clone(),
105        data,
106        &mut rng,
107    )?;
108
109    // We do that in a block because params borrows url mutably
110    {
111        // Add any additional parameters to the query
112        let mut params = url.query_pairs_mut();
113        for (key, value) in &provider.additional_authorization_parameters {
114            params.append_pair(key, value);
115        }
116    }
117
118    let session = repo
119        .upstream_oauth_session()
120        .add(
121            &mut rng,
122            &clock,
123            &provider,
124            data.state.clone(),
125            data.code_challenge_verifier,
126            data.nonce,
127        )
128        .await?;
129
130    let cookie_jar = UpstreamSessionsCookie::load(&cookie_jar)
131        .add(session.id, provider.id, data.state, query.post_auth_action)
132        .save(cookie_jar, &clock);
133
134    repo.save().await?;
135
136    Ok((cookie_jar, Redirect::temporary(url.as_str())))
137}