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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
// Copyright 2018-2022 Cargill Incorporated
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The `GET /oauth/callback` endpoint for receiving the authorization code from the provider and
//! exchanging it for an access token.
use actix_web::{http::header::LOCATION, web::Query, HttpResponse};
use futures::future::IntoFuture;
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use crate::biome::oauth::store::{InsertableOAuthUserSessionBuilder, OAuthUserSessionStore};
#[cfg(feature = "biome-profile")]
use crate::biome::{
profile::store::ProfileBuilder, profile::store::UserProfileStoreError, UserProfileStore,
};
#[cfg(feature = "biome-profile")]
use crate::error::InternalError;
#[cfg(feature = "biome-profile")]
use crate::oauth::Profile as OauthProfile;
use crate::oauth::{
rest_api::resources::callback::{generate_redirect_query, CallbackQuery},
OAuthClient,
};
#[cfg(feature = "authorization")]
use crate::rest_api::auth::authorization::Permission;
use crate::rest_api::{
actix_web_1::{Method, ProtocolVersionRangeGuard, Resource},
ErrorResponse, SPLINTER_PROTOCOL_VERSION,
};
const OAUTH_CALLBACK_MIN: u32 = 1;
pub fn make_callback_route(
client: OAuthClient,
oauth_user_session_store: Box<dyn OAuthUserSessionStore>,
#[cfg(feature = "biome-profile")] user_profile_store: Box<dyn UserProfileStore>,
) -> Resource {
let resource = Resource::build("/oauth/callback").add_request_guard(
ProtocolVersionRangeGuard::new(OAUTH_CALLBACK_MIN, SPLINTER_PROTOCOL_VERSION),
);
#[cfg(feature = "authorization")]
{
resource.add_method(
Method::Get,
Permission::AllowUnauthenticated,
move |req, _| {
Box::new(
match Query::<CallbackQuery>::from_query(req.query_string()) {
Ok(query) => {
match client
.exchange_authorization_code(query.code.clone(), &query.state)
{
Ok(Some((user_info, redirect_url))) => {
// Generate a Splinter access token for the new session
let splinter_access_token = new_splinter_access_token();
// Adding the token and subject to the redirect URL so the client
// may access these values after a redirect
let redirect_url = format!(
"{}?{}",
redirect_url,
generate_redirect_query(
&splinter_access_token,
user_info.subject()
)
);
// Save the new session
match InsertableOAuthUserSessionBuilder::new()
.with_splinter_access_token(splinter_access_token)
.with_subject(user_info.subject().to_string())
.with_oauth_access_token(
user_info.access_token().to_string(),
)
.with_oauth_refresh_token(
user_info.refresh_token().map(ToOwned::to_owned),
)
.build()
{
Ok(session) => {
match oauth_user_session_store.add_session(session) {
Ok(_) => {}
Err(err) => {
error!("Unable to store user session: {}", err);
return Box::new(
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
.into_future(),
);
}
}
}
Err(err) => {
error!("Unable to build user session: {}", err);
return Box::new(
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
.into_future(),
);
}
};
#[cfg(feature = "biome-profile")]
{
match save_user_profile(
user_profile_store.clone_box(),
oauth_user_session_store.clone_box(),
&user_info.profile().clone(),
user_info.subject.clone(),
) {
Ok(_) => debug!("User profile saved"),
Err(err) => {
error!(
"Failed to save profile for account: {}, {}",
user_info.subject.clone(),
err
);
return Box::new(
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
.into_future(),
);
}
}
}
HttpResponse::Found()
.header(LOCATION, redirect_url)
.finish()
}
Ok(None) => {
error!(
"Received OAuth callback request that does not correlate to an \
open authorization request"
);
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
}
Err(err) => {
error!("{}", err);
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
}
}
}
Err(err) => {
error!(
"Failed to parse query string in OAuth callback request: {}",
err
);
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
}
}
.into_future(),
)
},
)
}
#[cfg(not(feature = "authorization"))]
{
resource.add_method(Method::Get, move |req, _| {
Box::new(
match Query::<CallbackQuery>::from_query(req.query_string()) {
Ok(query) => {
match client.exchange_authorization_code(query.code.clone(), &query.state) {
Ok(Some((user_info, redirect_url))) => {
// Generate a Splinter access token for the new session
let splinter_access_token = new_splinter_access_token();
// Adding the token and subject to the redirect URL so the client
// may access these values after a redirect
let redirect_url = format!(
"{}?{}",
redirect_url,
generate_redirect_query(
&splinter_access_token,
user_info.subject()
)
);
// Save the new session
match InsertableOAuthUserSessionBuilder::new()
.with_splinter_access_token(splinter_access_token)
.with_subject(user_info.subject().to_string())
.with_oauth_access_token(user_info.access_token().to_string())
.with_oauth_refresh_token(
user_info.refresh_token().map(ToOwned::to_owned),
)
.build()
{
Ok(session) => {
match oauth_user_session_store.add_session(session) {
Ok(_) => {}
Err(err) => {
error!("Unable to store user session: {}", err);
return Box::new(
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
.into_future(),
);
}
}
}
Err(err) => {
error!("Unable to build user session: {}", err);
return Box::new(
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
.into_future(),
);
}
};
#[cfg(feature = "biome-profile")]
{
match save_user_profile(
user_profile_store.clone_box(),
oauth_user_session_store.clone_box(),
&user_info.profile().clone(),
user_info.subject.clone(),
) {
Ok(_) => debug!("User profile saved"),
Err(err) => {
error!(
"Failed to save profile for account: {}, {}",
user_info.subject.clone(),
err
);
return Box::new(
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
.into_future(),
);
}
}
}
HttpResponse::Found()
.header(LOCATION, redirect_url)
.finish()
}
Ok(None) => {
error!(
"Received OAuth callback request that does not correlate to an \
open authorization request"
);
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
}
Err(err) => {
error!("{}", err);
HttpResponse::InternalServerError()
.json(ErrorResponse::internal_error())
}
}
}
Err(err) => {
error!(
"Failed to parse query string in OAuth callback request: {}",
err
);
HttpResponse::InternalServerError().json(ErrorResponse::internal_error())
}
}
.into_future(),
)
})
}
}
/// Generates a new Splinter access token, which is a string of 32 random alphanumeric characters
fn new_splinter_access_token() -> String {
let mut rng = thread_rng();
std::iter::repeat(())
.map(|()| rng.sample(Alphanumeric))
.map(char::from)
.take(32)
.collect()
}
/// Gets the user's Biome ID from the session store and saves the user profile information to
/// the user profile store
#[cfg(feature = "biome-profile")]
fn save_user_profile(
user_profile_store: Box<dyn UserProfileStore>,
oauth_user_session_store: Box<dyn OAuthUserSessionStore>,
profile: &OauthProfile,
subject: String,
) -> Result<(), InternalError> {
if let Some(user) = oauth_user_session_store
.get_user(&subject)
.map_err(|err| InternalError::from_source(Box::new(err)))?
{
let profile = ProfileBuilder::new()
.with_user_id(user.user_id().into())
.with_subject(profile.subject.clone())
.with_name(profile.name.clone())
.with_given_name(profile.given_name.clone())
.with_family_name(profile.family_name.clone())
.with_email(profile.email.clone())
.with_picture(profile.picture.clone())
.build()
.map_err(|err| InternalError::from_source(Box::new(err)))?;
match user_profile_store.get_profile(user.user_id()) {
Ok(_) => user_profile_store
.update_profile(profile)
.map_err(|err| InternalError::from_source(Box::new(err))),
Err(UserProfileStoreError::InvalidArgument(_)) => user_profile_store
.add_profile(profile)
.map_err(|err| InternalError::from_source(Box::new(err))),
Err(err) => Err(InternalError::from_source(Box::new(err))),
}
} else {
Err(InternalError::with_message(
"Unable to retrieve user".to_string(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
use std::sync::mpsc::channel;
use std::thread::JoinHandle;
use actix::System;
use actix_web::{dev::Server, web, App, HttpResponse, HttpServer};
use futures::Future;
use reqwest::{blocking::Client, redirect, StatusCode, Url as ReqwestUrl};
use url::Url;
use crate::biome::MemoryOAuthUserSessionStore;
#[cfg(feature = "biome-profile")]
use crate::biome::MemoryUserProfileStore;
use crate::rest_api::actix_web_1::{RestApiBuilder, RestApiShutdownHandle};
use crate::oauth::{
new_basic_client,
store::{InflightOAuthRequestStore, MemoryInflightOAuthRequestStore},
tests::TestSubjectProvider,
PendingAuthorization,
};
use crate::oauth::tests::TestProfileProvider;
const TOKEN_ENDPOINT: &str = "/token";
const AUTH_CODE: &str = "auth_code";
const SUBJECT: &str = "subject";
const OAUTH_ACCESS_TOKEN: &str = "oauth_access_token";
const OAUTH_REFRESH_TOKEN: &str = "oauth_refresh_token";
/// Verifies the correct functionality of the `GET /oauth/callback` endpoint when the request
/// is correct
///
/// 1. Start the mock OAuth server
/// 2. Create a new InflightOAuthRequestStore and add a pending authorization
/// 3. Create a new OAuthClient with the pre-populated in-flight request store
/// 4. Create a new OAuthUserSessionStore
/// 5. Run the Splinter REST API on an open port with the `GET /oauth/callback` endpoint backed
/// by the OAuth client and session store
/// 6. Make the `GET /oauth/callback` request with an authorization code and the state (CSRF
/// token of pending authorization)
/// 7. Verify the response has status `302 Found` and the `Location` header is set to the
/// correct client redirect URL with the correct query parameters
/// 8. Verify the session was added to the session store
/// 9. Shutdown the Splinter REST API
/// 10. Stop the mock OAuth server
#[test]
fn get_callback_ok() {
let (oauth_shutdown_handle, address) = run_mock_oauth_server("get_callback_ok");
let request_store = Box::new(MemoryInflightOAuthRequestStore::new());
let csrf_token = "csrf_token";
let client_redirect_url =
Url::parse("http://client/redirect").expect("Failed to parse client redirect URL");
request_store
.insert_request(
csrf_token.into(),
PendingAuthorization {
pkce_verifier: "F9ZfayKQHV5exVsgM3WyzRt15UQvYxVZBm41iO-h20A".into(),
client_redirect_url: client_redirect_url.as_str().into(),
},
)
.expect("Failed to insert in-flight request");
let client = OAuthClient::new(
new_basic_client(
"client_id".into(),
"client_secret".into(),
"http://oauth/auth".into(),
"http://oauth/callback".into(),
format!("{}{}", address, TOKEN_ENDPOINT),
)
.expect("Failed to create basic client"),
vec![],
vec![],
Box::new(TestSubjectProvider),
request_store.clone(),
Box::new(TestProfileProvider),
);
let session_store = MemoryOAuthUserSessionStore::new();
#[cfg(feature = "biome-profile")]
let profile_store = MemoryUserProfileStore::new();
let (splinter_shutdown_handle, join_handle, bind_url) =
run_rest_api_on_open_port(vec![make_callback_route(
client,
session_store.clone_box(),
#[cfg(feature = "biome-profile")]
profile_store.clone_box(),
)]);
let url = ReqwestUrl::parse_with_params(
&format!("http://{}/oauth/callback", bind_url),
&[("code", AUTH_CODE), ("state", csrf_token)],
)
.expect("Failed to parse URL");
let resp = Client::builder()
// Disable redirects so the client doesn't actually go to the client redirect URL
.redirect(redirect::Policy::none())
.build()
.expect("Failed to build client")
.get(url)
.header("SplinterProtocolVersion", SPLINTER_PROTOCOL_VERSION)
.send()
.expect("Failed to perform request");
assert_eq!(resp.status(), StatusCode::FOUND);
let location = Url::parse(
resp.headers()
.get("Location")
.expect("Location header not set")
.to_str()
.expect("Location header should only contain visible ASCII characters"),
)
.expect("Failed to parse location");
assert_eq!(location.origin(), client_redirect_url.origin());
let query_map: HashMap<String, String> = location.query_pairs().into_owned().collect();
let access_token = query_map
.get("access_token")
.expect("Missing access_token")
.strip_prefix("OAuth2:")
.expect("Access token invalid");
assert_eq!(
query_map.get("display_name").expect("Missing display_name"),
SUBJECT
);
let session = session_store
.get_session(access_token)
.expect("Failed to get session")
.expect("Session missing");
assert_eq!(session.splinter_access_token(), access_token);
assert_eq!(session.user().subject(), SUBJECT);
assert_eq!(session.oauth_access_token(), OAUTH_ACCESS_TOKEN);
assert_eq!(
session
.oauth_refresh_token()
.expect("oauth_refresh_token missing"),
OAUTH_REFRESH_TOKEN
);
splinter_shutdown_handle
.shutdown()
.expect("Unable to shutdown rest api");
join_handle.join().expect("Unable to join rest api thread");
oauth_shutdown_handle.shutdown();
}
/// Verifies the correct functionality of the `GET /oauth/callback` endpoint when the request
/// has an unknown state parameter (CSRF token)
///
/// 1. Start the mock OAuth server
/// 2. Create a new OAuthClient with an empty in-flight request store
/// 3. Create a new OAuthUserSessionStore
/// 4. Run the Splinter REST API on an open port with the `GET /oauth/callback` endpoint backed
/// by the OAuth client and session store
/// 5. Make the `GET /oauth/callback` request with an authorization code and an unknown state
/// (CSRF token)
/// 6. Verify the response has status `500 Internal Server Error` (this is an internal error
/// from the authenticating client's perspective becuase this request is made by the OAuth
/// server)
/// 7. Shutdown the Splinter REST API
/// 8. Stop the mock OAuth server
#[test]
fn get_callback_unknown_state() {
let (oauth_shutdown_handle, address) = run_mock_oauth_server("get_callback_unknown_state");
let client = OAuthClient::new(
new_basic_client(
"client_id".into(),
"client_secret".into(),
"http://oauth/auth".into(),
"http://oauth/callback".into(),
format!("{}{}", address, TOKEN_ENDPOINT),
)
.expect("Failed to create basic client"),
vec![],
vec![],
Box::new(TestSubjectProvider),
Box::new(MemoryInflightOAuthRequestStore::new()),
Box::new(TestProfileProvider),
);
let session_store = MemoryOAuthUserSessionStore::new();
#[cfg(feature = "biome-profile")]
let profile_store = MemoryUserProfileStore::new();
let (splinter_shutdown_handle, join_handle, bind_url) =
run_rest_api_on_open_port(vec![make_callback_route(
client,
session_store.clone_box(),
#[cfg(feature = "biome-profile")]
profile_store.clone_box(),
)]);
let url = ReqwestUrl::parse_with_params(
&format!("http://{}/oauth/callback", bind_url),
&[("code", AUTH_CODE), ("state", "csrf_token")],
)
.expect("Failed to parse URL");
let resp = Client::new()
.get(url)
.header("SplinterProtocolVersion", SPLINTER_PROTOCOL_VERSION)
.send()
.expect("Failed to perform request");
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
splinter_shutdown_handle
.shutdown()
.expect("Unable to shutdown rest api");
join_handle.join().expect("Unable to join rest api thread");
oauth_shutdown_handle.shutdown();
}
/// Verifies the correct functionality of the `GET /oauth/callback` endpoint when the request
/// does not provide a state parameter (CSRF token)
///
/// 1. Start the mock OAuth server
/// 2. Create a new InflightOAuthRequestStore and add a pending authorization
/// 3. Create a new OAuthClient with the pre-populated in-flight request store
/// 4. Create a new OAuthUserSessionStore
/// 5. Run the Splinter REST API on an open port with the `GET /oauth/callback` endpoint backed
/// by the OAuth client and session store
/// 6. Make the `GET /oauth/callback` request with an authorization code but no state
/// 7. Verify the response has status `500 Internal Server Error` (this is an internal error
/// from the authenticating client's perspective becuase this request is made by the OAuth
/// server)
/// 8. Shutdown the Splinter REST API
/// 9. Stop the mock OAuth server
#[test]
fn get_callback_no_state() {
let (oauth_shutdown_handle, address) = run_mock_oauth_server("get_callback_no_state");
let request_store = Box::new(MemoryInflightOAuthRequestStore::new());
request_store
.insert_request(
"csrf_token".into(),
PendingAuthorization {
pkce_verifier: "F9ZfayKQHV5exVsgM3WyzRt15UQvYxVZBm41iO-h20A".into(),
client_redirect_url: "http://client/redirect".into(),
},
)
.expect("Failed to insert in-flight request");
let client = OAuthClient::new(
new_basic_client(
"client_id".into(),
"client_secret".into(),
"http://oauth/auth".into(),
"http://oauth/callback".into(),
format!("{}{}", address, TOKEN_ENDPOINT),
)
.expect("Failed to create basic client"),
vec![],
vec![],
Box::new(TestSubjectProvider),
request_store.clone(),
Box::new(TestProfileProvider),
);
let session_store = MemoryOAuthUserSessionStore::new();
#[cfg(feature = "biome-profile")]
let profile_store = MemoryUserProfileStore::new();
let (splinter_shutdown_handle, join_handle, bind_url) =
run_rest_api_on_open_port(vec![make_callback_route(
client,
session_store.clone_box(),
#[cfg(feature = "biome-profile")]
profile_store.clone_box(),
)]);
let url = ReqwestUrl::parse_with_params(
&format!("http://{}/oauth/callback", bind_url),
&[("code", AUTH_CODE)],
)
.expect("Failed to parse URL");
let resp = Client::new()
.get(url)
.header("SplinterProtocolVersion", SPLINTER_PROTOCOL_VERSION)
.send()
.expect("Failed to perform request");
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
splinter_shutdown_handle
.shutdown()
.expect("Unable to shutdown rest api");
join_handle.join().expect("Unable to join rest api thread");
oauth_shutdown_handle.shutdown();
}
/// Verifies the correct functionality of the `GET /oauth/callback` endpoint when the request
/// does not provide an authorization code parameter
///
/// 1. Start the mock OAuth server
/// 2. Create a new InflightOAuthRequestStore and add a pending authorization
/// 3. Create a new OAuthClient with the pre-populated in-flight request store
/// 4. Create a new OAuthUserSessionStore
/// 5. Run the Splinter REST API on an open port with the `GET /oauth/callback` endpoint backed
/// by the OAuth client and session store
/// 6. Make the `GET /oauth/callback` request with a state but no authorization code
/// 7. Verify the response has status `500 Internal Server Error` (this is an internal error
/// from the authenticating client's perspective becuase this request is made by the OAuth
/// server)
/// 8. Shutdown the Splinter REST API
/// 9. Stop the mock OAuth server
#[test]
fn get_callback_no_authorization_code() {
let (oauth_shutdown_handle, address) =
run_mock_oauth_server("get_callback_no_authorization_code");
let request_store = Box::new(MemoryInflightOAuthRequestStore::new());
let csrf_token = "csrf_token";
request_store
.insert_request(
csrf_token.into(),
PendingAuthorization {
pkce_verifier: "F9ZfayKQHV5exVsgM3WyzRt15UQvYxVZBm41iO-h20A".into(),
client_redirect_url: "http://client/redirect".into(),
},
)
.expect("Failed to insert in-flight request");
let client = OAuthClient::new(
new_basic_client(
"client_id".into(),
"client_secret".into(),
"http://oauth/auth".into(),
"http://oauth/callback".into(),
format!("{}{}", address, TOKEN_ENDPOINT),
)
.expect("Failed to create basic client"),
vec![],
vec![],
Box::new(TestSubjectProvider),
request_store.clone(),
Box::new(TestProfileProvider),
);
let session_store = MemoryOAuthUserSessionStore::new();
#[cfg(feature = "biome-profile")]
let profile_store = MemoryUserProfileStore::new();
let (splinter_shutdown_handle, join_handle, bind_url) =
run_rest_api_on_open_port(vec![make_callback_route(
client,
session_store.clone_box(),
#[cfg(feature = "biome-profile")]
profile_store.clone_box(),
)]);
let url = ReqwestUrl::parse_with_params(
&format!("http://{}/oauth/callback", bind_url),
&[("state", csrf_token)],
)
.expect("Failed to parse URL");
let resp = Client::new()
.get(url)
.header("SplinterProtocolVersion", SPLINTER_PROTOCOL_VERSION)
.send()
.expect("Failed to perform request");
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
splinter_shutdown_handle
.shutdown()
.expect("Unable to shutdown rest api");
join_handle.join().expect("Unable to join rest api thread");
oauth_shutdown_handle.shutdown();
}
/// Runs a mock OAuth server and returns its shutdown handle along with the address the server
/// is running on.
fn run_mock_oauth_server(test_name: &str) -> (OAuthServerShutdownHandle, String) {
let (tx, rx) = channel();
let instance_name = format!("OAuth-Server-{}", test_name);
let join_handle = std::thread::Builder::new()
.name(instance_name.clone())
.spawn(move || {
let sys = System::new(instance_name);
let server = HttpServer::new(|| {
App::new().service(web::resource(TOKEN_ENDPOINT).to(token_endpoint))
})
.bind("127.0.0.1:0")
.expect("Failed to bind OAuth server");
let address = format!("http://127.0.0.1:{}", server.addrs()[0].port());
let server = server.disable_signals().system_exit().start();
tx.send((server, address)).expect("Failed to send server");
sys.run().expect("OAuth server runtime failed");
})
.expect("Failed to spawn OAuth server thread");
let (server, address) = rx.recv().expect("Failed to receive server");
(OAuthServerShutdownHandle(server, join_handle), address)
}
/// The handler for the OAuth server's token endpoint. This endpoint receives the request
/// parameters as a form, since that's how the OAuth2 crate sends the request.
fn token_endpoint(form: web::Form<TokenRequestForm>) -> HttpResponse {
assert_eq!(&form.grant_type, "authorization_code");
assert_eq!(&form.code, AUTH_CODE);
HttpResponse::Ok()
.content_type("application/json")
.json(json!({
"token_type": "bearer",
"access_token": OAUTH_ACCESS_TOKEN,
"refresh_token": OAUTH_REFRESH_TOKEN,
"expires_in": 3600,
}))
}
#[derive(Deserialize)]
struct TokenRequestForm {
code: String,
grant_type: String,
}
struct OAuthServerShutdownHandle(Server, JoinHandle<()>);
impl OAuthServerShutdownHandle {
pub fn shutdown(self) {
self.0
.stop(false)
.wait()
.expect("Failed to stop OAuth server");
self.1.join().expect("OAuth server thread failed");
}
}
fn run_rest_api_on_open_port(
resources: Vec<Resource>,
) -> (RestApiShutdownHandle, std::thread::JoinHandle<()>, String) {
#[cfg(not(feature = "https-bind"))]
let bind = "127.0.0.1:0";
#[cfg(feature = "https-bind")]
let bind = crate::rest_api::BindConfig::Http("127.0.0.1:0".into());
let result = RestApiBuilder::new()
.with_bind(bind)
.add_resources(resources.clone())
.build_insecure()
.expect("Failed to build REST API")
.run_insecure();
match result {
Ok((shutdown_handle, join_handle)) => {
let port = shutdown_handle.port_numbers()[0];
(shutdown_handle, join_handle, format!("127.0.0.1:{}", port))
}
Err(err) => panic!("Failed to run REST API: {}", err),
}
}
}