matrix_sdk/authentication/oauth/device_code.rs
1// Copyright 2026 Nordeck IT + Consulting GmbH <info@nordeck.net>
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
15//! Login with the OAuth 2.0 Device Authorization Grant ([RFC 8628]), as
16//! specified in the [Matrix specification].
17//!
18//! [RFC 8628]: https://datatracker.ietf.org/doc/html/rfc8628
19//! [Matrix specification]: https://spec.matrix.org/v1.19/client-server-api/#device-authorisation-flow
20
21use std::time::Duration;
22
23use oauth2::{Scope, StandardDeviceAuthorizationResponse};
24use ruma::{
25 DeviceId, OwnedDeviceId,
26 api::client::discovery::get_authorization_server_metadata::v1::{
27 AuthorizationServerMetadata, GrantType,
28 },
29};
30use tracing::{trace, warn};
31use url::Url;
32
33use super::{
34 ClientRegistrationData, OAuth, OAuthError, error::DeviceCodeLoginError,
35 registration::ensure_grant_type,
36};
37
38/// A login with the Device Authorization Grant that is waiting for the
39/// end-user to grant the authorization, returned by
40/// [`OAuth::login_with_device_code()`].
41///
42/// The verification URI and the user code must be presented to the end-user,
43/// who must open the URI in a browser on another device and enter the user
44/// code if necessary. Then [`DeviceCodeLogin::finish()`] must be called to
45/// wait for the authorization and complete the login.
46#[derive(Debug)]
47pub struct DeviceCodeLogin {
48 oauth: OAuth,
49 server_metadata: AuthorizationServerMetadata,
50 device_id: OwnedDeviceId,
51 response: StandardDeviceAuthorizationResponse,
52 verification_uri_complete: Option<Url>,
53}
54
55impl DeviceCodeLogin {
56 /// Register the client if necessary, and request the device
57 /// authorization from the OAuth 2.0 authorization server.
58 pub(super) async fn start(
59 oauth: OAuth,
60 scopes: Vec<Scope>,
61 device_id: OwnedDeviceId,
62 mut registration_data: Option<ClientRegistrationData>,
63 ) -> Result<Self, DeviceCodeLoginError> {
64 trace!("Fetching the OAuth 2.0 server metadata.");
65 let server_metadata = oauth.server_metadata().await.map_err(OAuthError::from)?;
66
67 // Fail early, before registering the client, if the server doesn't
68 // support the device authorization grant.
69 if server_metadata.device_authorization_endpoint.is_none() {
70 return Err(DeviceCodeLoginError::NoDeviceAuthorizationEndpoint);
71 }
72
73 // The client must declare the grant types that it uses during
74 // registration.
75 if let Some(data) = &mut registration_data {
76 data.metadata = ensure_grant_type(&data.metadata, GrantType::DeviceCode);
77 }
78
79 trace!("Registering the client with the OAuth 2.0 authorization server.");
80 oauth.use_registration_data(&server_metadata, registration_data.as_ref()).await?;
81
82 trace!("Requesting device authorization.");
83 let response = oauth.request_device_authorization(&server_metadata, scopes).await?;
84
85 let verification_uri_complete =
86 response.verification_uri_complete().and_then(|uri| match Url::parse(uri.secret()) {
87 Ok(uri) => Some(uri),
88 Err(error) => {
89 warn!("Ignoring invalid `verification_uri_complete`: {error}");
90 None
91 }
92 });
93
94 Ok(Self { oauth, server_metadata, device_id, response, verification_uri_complete })
95 }
96
97 /// The device ID that will be associated with the session.
98 ///
99 /// This is either the device ID that was passed to
100 /// [`OAuth::login_with_device_code()`], or the one that was generated if
101 /// none was provided.
102 pub fn device_id(&self) -> &DeviceId {
103 &self.device_id
104 }
105
106 /// The end-user verification URI on the authorization server.
107 ///
108 /// The end-user should open this URI in a browser and enter the
109 /// [`user_code()`](Self::user_code).
110 pub fn verification_uri(&self) -> &Url {
111 self.response.verification_uri().url()
112 }
113
114 /// A verification URI that includes the [`user_code()`](Self::user_code),
115 /// designed for non-textual transmission, for example in a QR code.
116 ///
117 /// This is optional, and complements the
118 /// [`verification_uri()`](Self::verification_uri) and the
119 /// [`user_code()`](Self::user_code) rather than replacing them: if it is
120 /// available, it can be presented in addition to them, so the end-user
121 /// doesn't need to enter the user code manually. The verification URI and
122 /// the user code should still be displayed, as a fallback for an end-user
123 /// that cannot use this URI, and so the user code can be compared with the
124 /// one shown by the authorization server.
125 ///
126 /// See [RFC 8628 section 3.3.1] for more details.
127 ///
128 /// [RFC 8628 section 3.3.1]: https://datatracker.ietf.org/doc/html/rfc8628#section-3.3.1
129 pub fn verification_uri_complete(&self) -> Option<&Url> {
130 self.verification_uri_complete.as_ref()
131 }
132
133 /// The end-user verification code.
134 pub fn user_code(&self) -> &str {
135 self.response.user_code().secret()
136 }
137
138 /// The lifetime of the device code and user code, from the moment received.
139 ///
140 /// If the end-user doesn't grant the authorization before this delay,
141 /// [`DeviceCodeLogin::finish()`] fails with
142 /// [`DeviceCodeLoginError::ExpiredToken`].
143 pub fn expires_in(&self) -> Duration {
144 self.response.expires_in()
145 }
146
147 /// Wait for the end-user to grant the authorization, and complete the
148 /// login.
149 ///
150 /// This polls the OAuth 2.0 authorization server until the authorization
151 /// is granted, denied, or until it expires. When the authorization is
152 /// granted, the session is loaded into the client, like with
153 /// [`OAuth::finish_login()`].
154 ///
155 /// Dropping the returned future while it is waiting for the end-user to
156 /// grant the authorization stops polling the authorization server and
157 /// leaves the client unchanged. Once the authorization is granted, the
158 /// access token is set on the client and the session is loaded: if the
159 /// future is dropped during this step, the client may be left partially
160 /// logged in and should not be used anymore.
161 pub async fn finish(self) -> Result<(), DeviceCodeLoginError> {
162 let Self { oauth, server_metadata, device_id, response, .. } = self;
163
164 trace!("Waiting for the OAuth 2.0 authorization server to give us the access token.");
165 oauth.exchange_device_code(&server_metadata, &response).await?;
166
167 trace!("Loading the session.");
168 oauth.load_session(device_id).await?;
169
170 trace!("Successfully logged in with the device authorization grant.");
171
172 Ok(())
173 }
174}