matrix_sdk/authentication/oauth/
auth_code_builder.rs

1// Copyright 2022 Kévin Commaille
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::borrow::Cow;
16
17use oauth2::{
18    basic::BasicClient as OAuthClient, AuthUrl, CsrfToken, PkceCodeChallenge, RedirectUrl, Scope,
19};
20use ruma::{
21    api::client::discovery::get_authorization_server_metadata::msc2965::Prompt, OwnedDeviceId,
22    UserId,
23};
24use tracing::{info, instrument};
25use url::Url;
26
27use super::{ClientRegistrationData, OAuth, OAuthError};
28use crate::{authentication::oauth::AuthorizationValidationData, Result};
29
30/// Builder type used to configure optional settings for authorization with an
31/// OAuth 2.0 authorization server via the Authorization Code flow.
32///
33/// Created with [`OAuth::login()`]. Finalized with [`Self::build()`].
34#[allow(missing_debug_implementations)]
35pub struct OAuthAuthCodeUrlBuilder {
36    oauth: OAuth,
37    registration_data: Option<ClientRegistrationData>,
38    scopes: Vec<Scope>,
39    device_id: OwnedDeviceId,
40    redirect_uri: Url,
41    prompt: Option<Vec<Prompt>>,
42    login_hint: Option<String>,
43}
44
45impl OAuthAuthCodeUrlBuilder {
46    pub(super) fn new(
47        oauth: OAuth,
48        scopes: Vec<Scope>,
49        device_id: OwnedDeviceId,
50        redirect_uri: Url,
51        registration_data: Option<ClientRegistrationData>,
52    ) -> Self {
53        Self {
54            oauth,
55            registration_data,
56            scopes,
57            device_id,
58            redirect_uri,
59            prompt: None,
60            login_hint: None,
61        }
62    }
63
64    /// Set the [`Prompt`] of the authorization URL.
65    ///
66    /// If this is not set, it is assumed that the user wants to log into an
67    /// existing account.
68    ///
69    /// [`Prompt::Create`] can be used to signify that the user wants to
70    /// register a new account.
71    pub fn prompt(mut self, prompt: Vec<Prompt>) -> Self {
72        self.prompt = Some(prompt);
73        self
74    }
75
76    /// Set a generic login hint to help an identity provider pre-fill the login
77    /// form.
78    ///
79    /// Note: This is not the same as the [`Self::user_id_hint()`] method, which
80    /// is specifically designed to a) take a `UserId` and no other type of
81    /// hint and b) be used directly by MAS and not the identity provider.
82    ///
83    /// The most likely use case for this method is to pre-fill the login page
84    /// using a provisioning link provided by an external party such as
85    /// `https://app.example.com/?server_name=example.org&login_hint=alice`
86    /// In this instance it is up to the external party to make ensure that the
87    /// hint is known to work with their identity provider. For more information
88    /// see `login_hint` in <https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest>
89    ///
90    /// The following methods are mutually exclusive: [`Self::login_hint()`] and
91    /// [`Self::user_id_hint()`].
92    pub fn login_hint(mut self, login_hint: String) -> Self {
93        self.login_hint = Some(login_hint);
94        self
95    }
96
97    /// Set the hint to the Authorization Server about the Matrix user ID the
98    /// End-User might use to log in, as defined in [MSC4198].
99    ///
100    /// [MSC4198]: https://github.com/matrix-org/matrix-spec-proposals/pull/4198
101    ///
102    /// The following methods are mutually exclusive: [`Self::login_hint()`] and
103    /// [`Self::user_id_hint()`].
104    pub fn user_id_hint(mut self, user_id: &UserId) -> Self {
105        self.login_hint = Some(format!("mxid:{user_id}"));
106        self
107    }
108
109    /// Get the URL that should be presented to login via the Authorization Code
110    /// flow.
111    ///
112    /// This URL should be presented to the user and once they are redirected to
113    /// the `redirect_uri`, the login can be completed by calling
114    /// [`OAuth::finish_login()`].
115    ///
116    /// Returns an error if the client registration was not restored, or if a
117    /// request fails.
118    #[instrument(target = "matrix_sdk::client", skip_all)]
119    pub async fn build(self) -> Result<OAuthAuthorizationData, OAuthError> {
120        let Self { oauth, registration_data, scopes, device_id, redirect_uri, prompt, login_hint } =
121            self;
122
123        let server_metadata = oauth.server_metadata().await?;
124
125        oauth.use_registration_data(&server_metadata, registration_data.as_ref()).await?;
126
127        let data = oauth.data().expect("OAuth 2.0 data should be set after registration");
128        info!(
129            issuer = server_metadata.issuer.as_str(),
130            ?scopes,
131            "Authorizing scope via the OAuth 2.0 Authorization Code flow"
132        );
133
134        let auth_url = AuthUrl::from_url(server_metadata.authorization_endpoint.clone());
135
136        let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
137        let redirect_uri = RedirectUrl::from_url(redirect_uri);
138
139        let client = OAuthClient::new(data.client_id.clone()).set_auth_uri(auth_url);
140        let mut request = client
141            .authorize_url(CsrfToken::new_random)
142            .add_scopes(scopes)
143            .set_pkce_challenge(pkce_challenge)
144            .set_redirect_uri(Cow::Borrowed(&redirect_uri));
145
146        if let Some(prompt) = prompt {
147            // This should be a list of space separated values.
148            let prompt_str = prompt.iter().map(Prompt::as_str).collect::<Vec<_>>().join(" ");
149            request = request.add_extra_param("prompt", prompt_str);
150        }
151
152        if let Some(login_hint) = login_hint {
153            request = request.add_extra_param("login_hint", login_hint);
154        }
155
156        let (url, state) = request.url();
157
158        data.authorization_data.lock().await.insert(
159            state.clone(),
160            AuthorizationValidationData { server_metadata, device_id, redirect_uri, pkce_verifier },
161        );
162
163        Ok(OAuthAuthorizationData { url, state })
164    }
165}
166
167/// The data needed to perform authorization using OAuth 2.0.
168#[derive(Debug, Clone)]
169#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
170pub struct OAuthAuthorizationData {
171    /// The URL that should be presented.
172    pub url: Url,
173    /// A unique identifier for the request, used to ensure the response
174    /// originated from the authentication issuer.
175    pub state: CsrfToken,
176}
177
178#[cfg(feature = "uniffi")]
179#[matrix_sdk_ffi_macros::export]
180impl OAuthAuthorizationData {
181    /// The login URL to use for authorization.
182    pub fn login_url(&self) -> String {
183        self.url.to_string()
184    }
185}