1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
use std::time::Duration;
use crate::callback_server::{Error, OauthCallbackServer};
use crate::oauth;
use crate::oauth::Credentials;
use crate::oauth::api::{AuthenticateWithCode, Pkce, send_async};
use super::OAUTH_CLIENT_ID;
use super::api::{
AuthenticateWithDeviceCode, AuthenticateWithDeviceCodeResponse, DeviceCodeFlowStatus,
GetDeviceAuthUrl, RefreshResponse,
};
pub enum OauthLoginFlowState {
AlreadyLoggedIn(Box<Credentials>),
LoginFlowStarted(Box<OauthLoginFlow>),
}
pub struct OauthLoginFlow {
pub server: OauthCallbackServer,
pub login_hint: Option<String>,
pkce: Pkce,
}
impl OauthLoginFlow {
/// Login to Rerun using Authorization Code flow.
///
/// This first checks if valid credentials already exist locally,
/// and doesn't perform the login flow if so, unless `force_login` is set to `true`.
pub async fn init(force_login: bool) -> Result<OauthLoginFlowState, Error> {
let mut login_hint = None;
if !force_login {
// NOTE: If the loading fails for whatever reason, we debug log the error
// and have the user login again as if nothing happened.
match oauth::load_credentials() {
Ok(Some(credentials)) => {
login_hint = Some(credentials.user().email.clone());
match oauth::refresh_credentials(credentials).await {
Ok(credentials) => {
credentials.link_analytics_id_to_user();
return Ok(OauthLoginFlowState::AlreadyLoggedIn(Box::new(credentials)));
}
Err(err) => {
// Credentials are bad, login again.
re_log::debug!("refreshing credentials failed: {err}");
}
}
}
Ok(None) => {
// No credentials yet, login as usual.
}
Err(err) => {
re_log::debug!(
"validating credentials failed, logging user in again anyway. reason: {err}"
);
}
}
}
// Start web server that listens for the authorization code received from the auth server.
let pkce = Pkce::new();
let server = OauthCallbackServer::new(&pkce)?;
Ok(OauthLoginFlowState::LoginFlowStarted(Box::new(Self {
server,
login_hint,
pkce,
})))
}
pub fn get_login_url(&self) -> &str {
self.server.get_login_url()
}
/// Polls the web server for the authorization code received from the auth server.
///
/// This will not block, and will return `None` if no authorization code has been received yet.
pub async fn poll(&self) -> Result<Option<Credentials>, Error> {
// Once the user opens the link, they are redirected to the login UI.
// If they were already logged in, it will immediately redirect them
// to the login callback with an authorization code.
// That code is then sent by our callback page back to the web server here.
let Some(code) = self.server.check_for_browser_response()? else {
return Ok(None);
};
// Exchange code for credentials.
let auth = send_async(AuthenticateWithCode::new(&code, &self.pkce))
.await
.map_err(|err| Error::Generic(err.into()))?;
// Store and return credentials
let credentials = Credentials::from_auth_response(auth.into())?.ensure_stored()?;
Ok(Some(credentials))
}
}
pub enum DeviceCodeFlowState {
AlreadyLoggedIn(Box<Credentials>),
LoginFlowStarted(Box<DeviceCodeFlow>),
}
pub struct DeviceCodeFlow {
device_code: String,
user_code: String,
verification_uri: String,
interval: Duration,
}
impl DeviceCodeFlow {
pub async fn init(force_login: bool) -> Result<DeviceCodeFlowState, Error> {
if !force_login {
// NOTE: If the loading fails for whatever reason, we debug log the error
// and have the user login again as if nothing happened.
match oauth::load_credentials() {
Ok(Some(credentials)) => {
match oauth::refresh_credentials(credentials).await {
Ok(credentials) => {
credentials.link_analytics_id_to_user();
return Ok(DeviceCodeFlowState::AlreadyLoggedIn(Box::new(credentials)));
}
Err(err) => {
// Credentials are bad, login again.
re_log::debug!("refreshing credentials failed: {err}");
}
}
}
Ok(None) => {
// No credentials yet, login as usual.
}
Err(err) => {
re_log::debug!(
"validating credentials failed, logging user in again anyway. reason: {err}"
);
}
}
}
let res = send_async(GetDeviceAuthUrl {
client_id: &OAUTH_CLIENT_ID,
})
.await
.map_err(|err| Error::Generic(err.into()))?;
let interval = Duration::from_secs(res.interval_seconds as u64);
Ok(DeviceCodeFlowState::LoginFlowStarted(Box::new(Self {
device_code: res.device_code,
user_code: res.user_code,
verification_uri: res.verification_uri_complete,
interval,
})))
}
pub fn get_login_url(&self) -> &str {
&self.verification_uri
}
pub fn get_user_code(&self) -> &str {
&self.user_code
}
pub async fn wait_for_user_confirmation(&mut self) -> Result<Credentials, Error> {
loop {
let res = send_async(AuthenticateWithDeviceCode::new(
&OAUTH_CLIENT_ID,
&self.device_code,
))
.await
.map_err(|err| Error::Generic(err.into()))?;
match res {
AuthenticateWithDeviceCodeResponse::Success {
user,
organization_id,
access_token,
refresh_token,
} => {
return Ok(Credentials::from_auth_response(RefreshResponse {
user,
organization_id,
access_token,
refresh_token,
})?
.ensure_stored()?);
}
AuthenticateWithDeviceCodeResponse::Error {
error,
error_description,
} => match error {
DeviceCodeFlowStatus::AuthorizationPending => { /*fallthrough*/ }
DeviceCodeFlowStatus::SlowDown => {
self.interval += Duration::from_secs(1);
/*fallthrough*/
}
DeviceCodeFlowStatus::AccessDenied
| DeviceCodeFlowStatus::ExpiredToken
| DeviceCodeFlowStatus::InvalidRequest
| DeviceCodeFlowStatus::InvalidClient
| DeviceCodeFlowStatus::InvalidGrant
| DeviceCodeFlowStatus::UnsupportedGrantType => {
return Err(Error::Generic(
DeviceCodeFlowError {
code: error,
reason: error_description,
}
.into(),
));
}
},
}
tokio::time::sleep(self.interval).await;
}
}
}
#[derive(Debug, thiserror::Error)]
#[error("{code:?}: {reason}")]
pub struct DeviceCodeFlowError {
code: DeviceCodeFlowStatus,
reason: String,
}