-
Notifications
You must be signed in to change notification settings - Fork 4
/
auth.rs
654 lines (588 loc) · 20.3 KB
/
auth.rs
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use bevy::log;
use core::slice::SlicePattern;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use url::Url;
const AUTH0_DB_CONNECTION: &str = "Username-Password-Authentication";
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct OpenIdConnectConfig {
pub issuer: Url,
pub authorization_endpoint: Url,
pub token_endpoint: Option<Url>,
pub token_introspection_endpoint: Option<Url>,
pub userinfo_endpoint: Option<Url>,
pub end_session_endpoint: Option<Url>,
pub jwks_uri: Url,
pub registration_endpoint: Option<Url>,
#[serde(default)]
pub scopes_supported: Vec<String>,
#[serde(default)]
pub grant_types_supported: Vec<String>,
}
// The code is definitely read. A clippy bug?
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct OAuthResponse {
pub state: String,
pub code: String,
}
const CODE_VERIFIER_CHARS: &[u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.~_";
#[derive(Debug, Serialize)]
pub struct AuthCodeRequest {
pub client_id: String,
pub scope: String,
}
#[derive(Debug, Serialize)]
pub struct SignUpRequestParams {
pub client_id: String,
pub email: String,
pub password: String,
pub connection: String,
}
#[derive(Debug, Deserialize)]
pub struct SignUpErrorResponse {
pub code: String,
}
#[derive(Debug, Serialize)]
pub struct SignInRequestParams {
pub client_id: String,
pub grant_type: String,
pub username: String,
pub password: String,
pub scope: String,
pub device: String,
}
#[derive(Debug, Deserialize)]
pub struct SignInErrorResponse {
pub error: String,
}
impl SignInRequestParams {
pub fn new(client_id: String, username: String, password: String) -> Self {
Self {
client_id,
grant_type: "password".to_owned(),
username,
password,
scope: "openid email offline_access".to_owned(),
device: format!("{} {}", whoami::devicename(), whoami::desktop_env()),
}
}
}
#[derive(Debug, Serialize)]
pub struct AuthRequestParams {
pub client_id: String,
pub login_hint: Option<String>,
pub redirect_uri: String,
pub response_type: String,
pub scope: String,
pub code_challenge: String,
pub code_challenge_method: String,
pub state: String,
pub access_type: String,
}
#[derive(Debug, Deserialize)]
pub struct AuthCodeResponse {
pub device_code: String,
pub expires_in: u64,
pub interval: u64,
pub user_code: String,
pub verification_url: String,
}
#[derive(Debug)]
pub struct AuthCodeErrorResponse {
pub error_code: String,
}
#[derive(Debug, Serialize)]
pub struct AuthTokenRequest {
pub client_id: String,
pub client_secret: Option<String>,
pub code: String,
pub code_verifier: String,
pub grant_type: String,
pub redirect_uri: String,
}
#[derive(Debug, Deserialize)]
pub struct AuthTokenResponse {
pub access_token: String,
pub expires_in: u64,
pub refresh_token: String,
pub scope: String,
pub token_type: String,
pub id_token: String,
}
#[derive(Debug)]
pub enum AuthRequest {
Password {
username: String,
password: String,
is_sign_up: bool,
},
RedirectUrlServerPort(u16),
CancelOpenIDRequest,
RequestGoogleAuth,
#[cfg(feature = "unstoppable_resolution")]
RequestUnstoppableDomainsAuth {
username: String,
},
HandleOAuthResponse {
state: String,
code: String,
},
}
#[derive(Debug)]
pub enum AuthMessage {
RedirectUrlServerIsReady,
Success,
WrongPasswordError,
SignUpFailedError,
#[cfg(feature = "unstoppable_resolution")]
InvalidDomainError,
UnavailableError,
}
pub struct AuthConfig {
pub google_client_id: String,
// Google OAuth requires it for desktop clients.
pub google_client_secret: Option<String>,
pub auth0_client_id: String,
#[cfg(feature = "unstoppable_resolution")]
pub ud_client_id: String,
#[cfg(feature = "unstoppable_resolution")]
pub ud_secret_id: String,
}
pub struct PendingOAuthRequest {
client_id: String,
client_secret: Option<String>,
state_token: String,
code_verifier: String,
token_uri: Url,
redirect_uri: String,
}
pub async fn serve_auth_requests(
auth_config: AuthConfig,
mut auth_request_rx: UnboundedReceiver<AuthRequest>,
auth_message_tx: UnboundedSender<AuthMessage>,
) {
let mut pending_request: Option<PendingOAuthRequest> = None;
let mut req_redirect_uri = None;
let client = reqwest::Client::new();
#[cfg(feature = "unstoppable_resolution")]
let resolution = {
let ethereum_rpc_url =
Url::parse("https://mainnet.infura.io/v3/c4bb906ed6904c42b19c95825fe55f39").unwrap();
let polygon_rpc_url =
Url::parse("https://polygon-mainnet.infura.io/v3/c4bb906ed6904c42b19c95825fe55f39")
.unwrap();
unstoppable_resolution::UnsResolutionProvider {
http_client: client.clone(),
ethereum_rpc_url: std::sync::Arc::new(ethereum_rpc_url),
polygon_rpc_url: std::sync::Arc::new(polygon_rpc_url),
}
};
loop {
match auth_request_rx.recv().await {
Some(AuthRequest::Password {
username,
password,
is_sign_up: false,
}) => {
sign_in(
&client,
&SignInRequestParams::new(
auth_config.auth0_client_id.clone(),
username,
password,
),
&auth_message_tx,
)
.await;
}
Some(AuthRequest::Password {
username,
password,
is_sign_up: true,
}) => {
let params = SignUpRequestParams {
client_id: auth_config.auth0_client_id.clone(),
email: username,
password,
connection: AUTH0_DB_CONNECTION.to_owned(),
};
sign_up(&client, ¶ms, &auth_message_tx).await;
}
Some(AuthRequest::RedirectUrlServerPort(_port)) => {
log::trace!("Initialized redirect_uri");
#[cfg(not(target_arch = "wasm32"))]
{
req_redirect_uri = Some(format!("http://localhost:{}", _port));
}
#[cfg(target_arch = "wasm32")]
{
req_redirect_uri = Some(format!(
"{}/auth",
web_sys::window().unwrap().location().origin().unwrap()
));
}
auth_message_tx
.send(AuthMessage::RedirectUrlServerIsReady)
.expect("Failed to send an auth update");
}
Some(AuthRequest::CancelOpenIDRequest) => {
pending_request = None;
}
Some(AuthRequest::RequestGoogleAuth) => {
let (code_verifier, code_challenge) = code_challenge();
let request = PendingOAuthRequest {
client_id: auth_config.google_client_id.clone(),
client_secret: auth_config.google_client_secret.clone(),
state_token: state_token(),
code_verifier,
token_uri: Url::parse("https://oauth2.googleapis.com/token").unwrap(),
redirect_uri: req_redirect_uri.clone().unwrap(),
};
let params = AuthRequestParams {
client_id: request.client_id.clone(),
login_hint: None,
redirect_uri: req_redirect_uri.clone().unwrap(),
response_type: "code".to_owned(),
scope: "openid email".to_owned(),
code_challenge,
code_challenge_method: "S256".to_owned(),
state: request.state_token.clone(),
access_type: "offline".to_owned(),
};
pending_request = Some(request);
let url = format!(
"https://accounts.google.com/o/oauth2/v2/auth?{}",
serde_urlencoded::to_string(params).unwrap()
);
webbrowser::open(&url).expect("Failed to open a URL in browser");
}
#[cfg(feature = "unstoppable_resolution")]
Some(AuthRequest::RequestUnstoppableDomainsAuth { username }) => {
let rel = "http://openid.net/specs/connect/1.0/issuer";
let (user, domain) = username.split_once('@').unwrap_or(("", username.as_str()));
let jrd = match resolution.domain_jrd(domain, user, rel, None).await {
Ok(jrd) => jrd,
Err(unstoppable_resolution::WebFingerResponseError::InvalidDomainName) => {
auth_message_tx
.send(AuthMessage::InvalidDomainError)
.expect("Failed to send an auth update");
continue;
}
Err(err) => {
log::error!("WebFinger error: {:?}", err);
continue;
}
};
log::debug!("Domain JRD: {:#?}", jrd);
let Some(openid_config) = fetch_openid_config(&client, rel, &jrd).await else {
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
continue;
};
let Some(token_uri) = openid_config.token_endpoint else {
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
continue;
};
let (code_verifier, code_challenge) = code_challenge();
let request = PendingOAuthRequest {
client_id: auth_config.ud_client_id.clone(),
client_secret: Some(auth_config.ud_secret_id.clone()),
state_token: state_token(),
code_verifier,
token_uri,
redirect_uri: req_redirect_uri.clone().unwrap(),
};
let params = AuthRequestParams {
client_id: request.client_id.clone(),
login_hint: Some(domain.to_owned()),
redirect_uri: req_redirect_uri.clone().unwrap(),
response_type: "code".to_owned(),
scope: "openid email wallet offline_access".to_owned(),
code_challenge,
code_challenge_method: "S256".to_owned(),
state: request.state_token.clone(),
access_type: "offline".to_owned(),
};
pending_request = Some(request);
let url = format!(
"{}?{}",
openid_config.authorization_endpoint,
serde_urlencoded::to_string(params).unwrap()
);
webbrowser::open(&url).expect("Failed to open a URL in browser");
}
Some(AuthRequest::HandleOAuthResponse { state, code }) => {
let Some(request) = &pending_request else {
log::warn!("Ignoring unexpected OAuth response");
continue;
};
if request.state_token != state {
log::warn!("Ignoring OAuth response: invalid state token");
continue;
}
let success = exchange_auth_code(&client, request, code, &auth_message_tx).await;
if success {
pending_request = None;
}
}
None => {
return;
}
}
}
}
#[cfg(feature = "unstoppable_resolution")]
async fn fetch_openid_config(
client: &reqwest::Client,
rel: &str,
jrd: &unstoppable_resolution::JrdDocument,
) -> Option<OpenIdConnectConfig> {
let link = jrd.links.iter().find(|link| link.rel == rel)?;
let url = link
.href
.as_ref()?
.join(".well-known/openid-configuration")
.ok()?;
client.get(url).send().await.ok()?.json().await.ok()
}
async fn sign_up(
client: &reqwest::Client,
params: &SignUpRequestParams,
auth_message_tx: &UnboundedSender<AuthMessage>,
) {
let result = client
.post("https://muddle-run.eu.auth0.com/dbconnections/signup")
.json(params)
.send()
.await;
let (data, success) = match result {
Ok(result) => {
let is_success = result.status().is_success();
(result.bytes().await, is_success)
}
Err(err) => {
log::error!("Failed to sign up: {:?}", err);
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
return;
}
};
if !success {
log::error!("Failed to sign up");
match data
.ok()
.and_then(|data| serde_json::from_slice::<SignUpErrorResponse>(data.as_slice()).ok())
{
Some(response) => {
if response.code == "invalid_signup" {
auth_message_tx
.send(AuthMessage::SignUpFailedError)
.expect("Failed to send an auth update");
return;
}
}
None => {
log::error!("Failed to parse sign up error code");
}
}
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
return;
}
sign_in(
client,
&SignInRequestParams::new(
params.client_id.clone(),
params.email.clone(),
params.password.clone(),
),
auth_message_tx,
)
.await;
}
async fn sign_in(
client: &reqwest::Client,
body: &SignInRequestParams,
auth_message_tx: &UnboundedSender<AuthMessage>,
) {
let result = client
.post("https://muddle-run.eu.auth0.com/oauth/token")
.header("Content-Type", "application/x-www-form-urlencoded")
.body(serde_urlencoded::to_string(body).unwrap())
.send()
.await;
let (data, success) = match result {
Ok(result) => {
let is_success = result.status().is_success();
(result.bytes().await, is_success)
}
Err(err) => {
log::error!("Failed to fetch token: {:?}", err);
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
return;
}
};
if success {
let response = data.map_err(anyhow::Error::msg).and_then(|data| {
serde_json::from_slice::<AuthTokenResponse>(data.as_slice()).map_err(anyhow::Error::msg)
});
match response {
Ok(_response) => {
auth_message_tx
.send(AuthMessage::Success)
.expect("Failed to send an auth update");
}
Err(err) => {
log::error!("Failed to serialize token body: {:?}", err);
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
}
}
} else {
log::error!("Failed to sign in");
match data
.ok()
.and_then(|data| serde_json::from_slice::<SignInErrorResponse>(data.as_slice()).ok())
{
Some(response) => {
if response.error == "invalid_grant" {
auth_message_tx
.send(AuthMessage::WrongPasswordError)
.expect("Failed to send an auth update");
return;
}
}
None => {
log::error!("Failed to parse sign in error");
}
}
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
}
}
async fn exchange_auth_code(
client: &reqwest::Client,
request: &PendingOAuthRequest,
code: String,
auth_message_tx: &UnboundedSender<AuthMessage>,
) -> bool {
let result = client
.post(request.token_uri.clone())
.header("Content-Type", "application/x-www-form-urlencoded")
.body(
serde_urlencoded::to_string(AuthTokenRequest {
client_id: request.client_id.clone(),
client_secret: request.client_secret.clone(),
code,
code_verifier: request.code_verifier.clone(),
grant_type: "authorization_code".to_owned(),
redirect_uri: request.redirect_uri.to_string(),
})
.unwrap(),
)
.send()
.await;
let (data, success) = match result {
Ok(result) => {
let is_success = result.status().is_success();
(result.bytes().await, is_success)
}
Err(err) => {
log::error!("Failed to fetch token: {:?}", err);
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
return false;
}
};
if success {
let response = data.map_err(anyhow::Error::msg).and_then(|data| {
serde_json::from_slice::<AuthTokenResponse>(data.as_slice()).map_err(anyhow::Error::msg)
});
match response {
Ok(_response) => {
auth_message_tx
.send(AuthMessage::Success)
.expect("Failed to send an auth update");
}
Err(err) => {
log::error!("Failed to serialize token body: {:?}", err);
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
}
}
} else {
log::debug!(
"{:?}",
serde_json::from_slice::<serde_json::Value>(data.unwrap().as_slice())
);
log::error!("Auth token exchange failed");
auth_message_tx
.send(AuthMessage::UnavailableError)
.expect("Failed to send an auth update");
}
success
}
pub fn google_client_id() -> Option<String> {
std::option_env!("MUDDLE_GOOGLE_CLIENT_ID").map(str::to_owned)
}
pub fn google_client_secret() -> Option<String> {
std::option_env!("MUDDLE_GOOGLE_CLIENT_SECRET").map(str::to_owned)
}
pub fn auth0_client_id() -> Option<String> {
std::option_env!("MUDDLE_AUTH0_CLIENT_ID").map(str::to_owned)
}
#[cfg(feature = "unstoppable_resolution")]
pub fn ud_client_id() -> Option<String> {
std::option_env!("MUDDLE_UD_CLIENT_ID").map(str::to_owned)
}
#[cfg(feature = "unstoppable_resolution")]
pub fn ud_client_secret() -> Option<String> {
std::option_env!("MUDDLE_UD_CLIENT_SECRET").map(str::to_owned)
}
fn code_challenge() -> (String, String) {
use rand::{thread_rng, Rng};
use sha2::Digest;
let mut rng = thread_rng();
let code_verifier: Vec<u8> = (0..128)
.map(|_| {
let i = rng.gen_range(0..CODE_VERIFIER_CHARS.len());
CODE_VERIFIER_CHARS[i]
})
.collect();
let mut sha = sha2::Sha256::new();
sha.update(&code_verifier);
let result = sha.finalize();
let b64 = base64::encode(result);
let challenge = b64
.chars()
.filter_map(|c| match c {
'=' => None,
'+' => Some('-'),
'/' => Some('_'),
x => Some(x),
})
.collect();
(String::from_utf8(code_verifier).unwrap(), challenge)
}
fn state_token() -> String {
use rand::{thread_rng, Rng};
use sha2::Digest;
let mut rng = thread_rng();
let random_bytes = rng.gen::<[u8; 16]>();
let mut sha = sha2::Sha256::new();
sha.update(random_bytes);
format!("{:x}", sha.finalize())
}