Skip to main content

matrix_sdk/authentication/oauth/
error.rs

1// Copyright 2025 Kévin Commaille
2// Copyright 2026 Nordeck IT + Consulting GmbH <info@nordeck.net>
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Error types used in the [`OAuth`](super::OAuth) API.
17
18use as_variant::as_variant;
19use matrix_sdk_base::deserialized_responses::PrivOwnedStr;
20use oauth2::ErrorResponseType;
21pub use oauth2::{
22    ConfigurationError, DeviceCodeErrorResponse, DeviceCodeErrorResponseType, HttpClientError,
23    RequestTokenError, RevocationErrorResponseType, StandardErrorResponse,
24    basic::{
25        BasicErrorResponse, BasicErrorResponseType, BasicRequestTokenError,
26        BasicRevocationErrorResponse,
27    },
28};
29use ruma::{
30    api::client::discovery::get_authorization_server_metadata::v1::AuthorizationServerMetadataUrlError,
31    serde::StringEnum,
32};
33
34#[cfg(feature = "e2e-encryption")]
35pub use super::cross_process::CrossProcessRefreshLockError;
36
37/// An error when interacting with the OAuth 2.0 authorization server.
38pub type OAuthRequestError<T> =
39    RequestTokenError<HttpClientError<reqwest::Error>, StandardErrorResponse<T>>;
40
41/// An error when trying to parse the query of a redirect URI.
42#[derive(Debug, Clone, thiserror::Error)]
43#[non_exhaustive]
44pub enum RedirectUriQueryParseError {
45    /// There is no query part in the URI.
46    #[error("No query in URI")]
47    MissingQuery,
48
49    /// Deserialization failed.
50    #[error("Query is not using one of the defined formats")]
51    UnknownFormat,
52}
53
54/// All errors that can occur when using the OAuth 2.0 API.
55#[derive(Debug, thiserror::Error)]
56#[non_exhaustive]
57pub enum OAuthError {
58    /// An error occurred when discovering the authorization server's issuer.
59    #[error("authorization server discovery failed: {0}")]
60    Discovery(#[from] OAuthDiscoveryError),
61
62    /// An error occurred when registering the client with the authorization
63    /// server.
64    #[error("client registration failed: {0}")]
65    ClientRegistration(#[from] OAuthClientRegistrationError),
66
67    /// The client has not registered while the operation requires it.
68    #[error("client not registered")]
69    NotRegistered,
70
71    /// The client is not authenticated while the request requires it.
72    #[error("client not authenticated")]
73    NotAuthenticated,
74
75    /// An error occurred using the OAuth 2.0 authorization code grant.
76    #[error("authorization code grant failed: {0}")]
77    AuthorizationCode(#[from] OAuthAuthorizationCodeError),
78
79    /// An error occurred interacting with the OAuth 2.0 authorization server
80    /// while refreshing the access token.
81    #[error("failed to refresh token: {0}")]
82    RefreshToken(OAuthRequestError<BasicErrorResponseType>),
83
84    /// An error occurred revoking an OAuth 2.0 access token.
85    #[error("failed to log out: {0}")]
86    Logout(#[from] OAuthTokenRevocationError),
87
88    /// An error occurred caused by the cross-process locks.
89    #[cfg(feature = "e2e-encryption")]
90    #[error(transparent)]
91    LockError(#[from] CrossProcessRefreshLockError),
92
93    /// The user logged into a session that is different than the one the client
94    /// is already using.
95    ///
96    /// This only happens if the session was already restored, and the user logs
97    /// into a new session that is different than the old one.
98    #[error("new logged-in session is different than current client session")]
99    SessionMismatch,
100}
101
102/// All errors that can occur when discovering the OAuth 2.0 server metadata.
103#[derive(Debug, thiserror::Error)]
104#[non_exhaustive]
105pub enum OAuthDiscoveryError {
106    /// OAuth 2.0 is not supported by the homeserver.
107    #[error("OAuth 2.0 is not supported by the homeserver")]
108    NotSupported,
109
110    /// An error occurred when making a request to the homeserver.
111    #[error(transparent)]
112    Http(#[from] crate::HttpError),
113
114    /// The server metadata is invalid.
115    #[error(transparent)]
116    Json(#[from] serde_json::Error),
117
118    /// The server metadata URLs are insecure.
119    #[error(transparent)]
120    Validation(#[from] AuthorizationServerMetadataUrlError),
121
122    /// An error occurred when building the OpenID Connect provider
123    /// configuration URL.
124    #[error(transparent)]
125    Url(#[from] url::ParseError),
126
127    /// An error occurred when making a request to the OpenID Connect provider.
128    #[error(transparent)]
129    Oidc(#[from] OAuthRequestError<BasicErrorResponseType>),
130}
131
132impl OAuthDiscoveryError {
133    /// Whether this error occurred because OAuth 2.0 is not supported by the
134    /// homeserver.
135    pub fn is_not_supported(&self) -> bool {
136        matches!(self, Self::NotSupported)
137    }
138}
139
140/// All errors that can occur when using the Authorization Code grant with the
141/// OAuth 2.0 API.
142#[derive(Debug, thiserror::Error)]
143#[non_exhaustive]
144pub enum OAuthAuthorizationCodeError {
145    /// The query of the redirect URI doesn't have the expected format.
146    #[error(transparent)]
147    RedirectUri(#[from] RedirectUriQueryParseError),
148
149    /// The user cancelled the authorization in the web UI.
150    #[error("authorization cancelled by the user")]
151    Cancelled,
152
153    /// An error occurred when getting the authorization from the user in the
154    /// web UI.
155    #[error("authorization failed: {0}")]
156    Authorization(StandardErrorResponse<AuthorizationCodeErrorResponseType>),
157
158    /// The state used to complete authorization doesn't match any of the
159    /// ongoing authorizations.
160    #[error("authorization state value is unexpected")]
161    InvalidState,
162
163    /// An error occurred interacting with the OAuth 2.0 authorization server
164    /// while exchanging the authorization code for an access token.
165    #[error("failed to request token: {0}")]
166    RequestToken(OAuthRequestError<BasicErrorResponseType>),
167}
168
169impl From<StandardErrorResponse<AuthorizationCodeErrorResponseType>>
170    for OAuthAuthorizationCodeError
171{
172    fn from(value: StandardErrorResponse<AuthorizationCodeErrorResponseType>) -> Self {
173        if *value.error() == AuthorizationCodeErrorResponseType::AccessDenied {
174            // The user cancelled the login in the web view.
175            Self::Cancelled
176        } else {
177            Self::Authorization(value)
178        }
179    }
180}
181
182/// Error response returned by server after requesting an authorization code.
183///
184/// The fields in this structure are defined in [Section 4.1.2.1 of RFC 6749].
185///
186/// [Section 4.1.2.1 of RFC 6749]: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1
187#[derive(Clone, StringEnum)]
188#[ruma_enum(rename_all = "snake_case")]
189#[non_exhaustive]
190pub enum AuthorizationCodeErrorResponseType {
191    /// The request is invalid.
192    ///
193    /// It is missing a required parameter, includes an invalid parameter value,
194    /// includes a parameter more than once, or is otherwise malformed.
195    InvalidRequest,
196
197    /// The client is not authorized to request an authorization code using this
198    /// method.
199    UnauthorizedClient,
200
201    /// The resource owner or authorization server denied the request.
202    AccessDenied,
203
204    /// The authorization server does not support obtaining an authorization
205    /// code using this method.
206    UnsupportedResponseType,
207
208    /// The requested scope is invalid, unknown, or malformed.
209    InvalidScope,
210
211    /// The authorization server encountered an unexpected error.
212    ServerError,
213
214    /// The authorization server is currently unable to handle the request due
215    /// to a temporary overloading or maintenance of the server.
216    TemporarilyUnavailable,
217
218    #[doc(hidden)]
219    _Custom(PrivOwnedStr),
220}
221
222impl ErrorResponseType for AuthorizationCodeErrorResponseType {}
223
224/// All errors that can occur when revoking an OAuth 2.0 token.
225#[derive(Debug, thiserror::Error)]
226#[non_exhaustive]
227pub enum OAuthTokenRevocationError {
228    /// The revocation endpoint URL is insecure.
229    #[error(transparent)]
230    Url(ConfigurationError),
231
232    /// An error occurred interacting with the OAuth 2.0 authorization server
233    /// while revoking the token.
234    #[error("failed to revoke token: {0}")]
235    Revoke(OAuthRequestError<RevocationErrorResponseType>),
236}
237
238/// All errors that can occur when registering a client with an OAuth 2.0
239/// authorization server.
240#[derive(Debug, thiserror::Error)]
241#[non_exhaustive]
242pub enum OAuthClientRegistrationError {
243    /// The authorization server doesn't support dynamic client registration.
244    ///
245    /// The server probably offers another way to register clients.
246    #[error("dynamic client registration is not supported")]
247    NotSupported,
248
249    /// Serialization of the client metadata failed.
250    #[error("failed to serialize client metadata: {0}")]
251    IntoJson(serde_json::Error),
252
253    /// An error occurred when making a request to the OAuth 2.0 authorization
254    /// server.
255    #[error(transparent)]
256    OAuth(#[from] OAuthRequestError<ClientRegistrationErrorResponseType>),
257
258    /// Deserialization of the registration response failed.
259    #[error("failed to deserialize registration response: {0}")]
260    FromJson(serde_json::Error),
261}
262
263/// Error response returned by server after requesting an authorization code.
264///
265/// The variant of this enum are defined in [Section 3.2.2 of RFC 7591].
266///
267/// [Section 3.2.2 of RFC 7591]: https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.2
268#[derive(Clone, StringEnum)]
269#[ruma_enum(rename_all = "snake_case")]
270#[non_exhaustive]
271pub enum ClientRegistrationErrorResponseType {
272    /// The value of one or more redirection URIs is invalid.
273    InvalidRedirectUri,
274
275    /// The value of one of the client metadata fields is invalid and the server
276    /// has rejected this request.
277    InvalidClientMetadata,
278
279    /// The software statement presented is invalid.
280    InvalidSoftwareStatement,
281
282    /// The software statement presented is not approved for use by this
283    /// authorization server.
284    UnapprovedSoftwareStatement,
285
286    #[doc(hidden)]
287    _Custom(PrivOwnedStr),
288}
289
290impl ErrorResponseType for ClientRegistrationErrorResponseType {}
291
292/// Error type describing failures in the interaction between the device
293/// attempting to log in and the OAuth 2.0 authorization server, when using the
294/// device authorization grant defined in [RFC 8628] and specified in the
295/// [Matrix specification].
296///
297/// [RFC 8628]: https://datatracker.ietf.org/doc/html/rfc8628
298/// [Matrix specification]: https://spec.matrix.org/v1.19/client-server-api/#device-authorisation-flow
299#[derive(Debug, thiserror::Error)]
300pub enum DeviceAuthorizationOAuthError {
301    /// A generic OAuth 2.0 error happened while we were attempting to register
302    /// the device with the OAuth 2.0 authorization server.
303    #[error(transparent)]
304    OAuth(#[from] OAuthError),
305
306    /// The OAuth 2.0 server doesn't support the device authorization grant.
307    #[error("OAuth 2.0 server doesn't support the device authorization grant")]
308    NoDeviceAuthorizationEndpoint,
309
310    /// An error happened while we attempted to request a device authorization
311    /// from the OAuth 2.0 authorization server.
312    #[error(transparent)]
313    DeviceAuthorization(#[from] BasicRequestTokenError<HttpClientError<reqwest::Error>>),
314
315    /// An error happened while waiting for the access token to be issued and
316    /// sent to us by the OAuth 2.0 authorization server.
317    #[error(transparent)]
318    RequestToken(
319        #[from] RequestTokenError<HttpClientError<reqwest::Error>, DeviceCodeErrorResponse>,
320    ),
321}
322
323impl DeviceAuthorizationOAuthError {
324    /// If the [`DeviceAuthorizationOAuthError`] is of the
325    /// [`DeviceCodeErrorResponseType`] error variant, return it.
326    pub fn as_request_token_error(&self) -> Option<&DeviceCodeErrorResponseType> {
327        let error = as_variant!(self, DeviceAuthorizationOAuthError::RequestToken)?;
328        let request_token_error = as_variant!(error, RequestTokenError::ServerResponse)?;
329
330        Some(request_token_error.error())
331    }
332}
333
334/// All errors that can occur when logging in with the device authorization
335/// grant, using [`OAuth::login_with_device_code()`].
336///
337/// [`OAuth::login_with_device_code()`]: super::OAuth::login_with_device_code
338#[derive(Debug, thiserror::Error)]
339#[non_exhaustive]
340pub enum DeviceCodeLoginError {
341    /// The client is not registered with the OAuth 2.0 authorization server,
342    /// and no [`ClientRegistrationData`] was provided to register it.
343    ///
344    /// [`ClientRegistrationData`]: super::ClientRegistrationData
345    #[error("client not registered")]
346    NotRegistered,
347
348    /// The OAuth 2.0 authorization server doesn't support the device
349    /// authorization grant, i.e. it doesn't advertise a
350    /// `device_authorization_endpoint` in its metadata.
351    #[error("OAuth 2.0 server doesn't support the device authorization grant")]
352    NoDeviceAuthorizationEndpoint,
353
354    /// The user denied the authorization request.
355    #[error("the authorization request was denied")]
356    AccessDenied,
357
358    /// The device code expired before the user approved the authorization
359    /// request.
360    #[error("the device code has expired")]
361    ExpiredToken,
362
363    /// A generic OAuth 2.0 error happened, for example while discovering the
364    /// server metadata or registering the client.
365    #[error(transparent)]
366    OAuth(OAuthError),
367
368    /// An error happened while requesting a device authorization from the
369    /// OAuth 2.0 authorization server.
370    #[error("failed to request device authorization: {0}")]
371    DeviceAuthorization(BasicRequestTokenError<HttpClientError<reqwest::Error>>),
372
373    /// An error happened while waiting for the access token to be issued by the
374    /// OAuth 2.0 authorization server.
375    #[error("failed to request token: {0}")]
376    RequestToken(RequestTokenError<HttpClientError<reqwest::Error>, DeviceCodeErrorResponse>),
377
378    /// An error happened while loading the session after we obtained the
379    /// access token, for example when discovering our user ID or setting up
380    /// the stores.
381    #[error("failed to load the session: {0}")]
382    SessionLoad(Box<crate::Error>),
383}
384
385impl From<OAuthError> for DeviceCodeLoginError {
386    fn from(error: OAuthError) -> Self {
387        match error {
388            OAuthError::NotRegistered => Self::NotRegistered,
389            error => Self::OAuth(error),
390        }
391    }
392}
393
394impl From<DeviceAuthorizationOAuthError> for DeviceCodeLoginError {
395    fn from(error: DeviceAuthorizationOAuthError) -> Self {
396        match error {
397            DeviceAuthorizationOAuthError::OAuth(error) => error.into(),
398            DeviceAuthorizationOAuthError::NoDeviceAuthorizationEndpoint => {
399                Self::NoDeviceAuthorizationEndpoint
400            }
401            DeviceAuthorizationOAuthError::DeviceAuthorization(error) => {
402                Self::DeviceAuthorization(error)
403            }
404            DeviceAuthorizationOAuthError::RequestToken(error) => {
405                if let RequestTokenError::ServerResponse(response) = &error {
406                    match response.error() {
407                        DeviceCodeErrorResponseType::AccessDenied => return Self::AccessDenied,
408                        DeviceCodeErrorResponseType::ExpiredToken => return Self::ExpiredToken,
409                        _ => {}
410                    }
411                }
412
413                Self::RequestToken(error)
414            }
415        }
416    }
417}
418
419impl From<crate::Error> for DeviceCodeLoginError {
420    fn from(error: crate::Error) -> Self {
421        match error {
422            crate::Error::OAuth(error) => (*error).into(),
423            error => Self::SessionLoad(Box::new(error)),
424        }
425    }
426}