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 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
//! Module containing the core functionality for OAuth2 Authentication.
use crate::application_default_credentials::{
ApplicationDefaultCredentialsFlow, ApplicationDefaultCredentialsFlowOpts,
};
use crate::authenticator_delegate::{DeviceFlowDelegate, InstalledFlowDelegate};
use crate::authorized_user::{AuthorizedUserFlow, AuthorizedUserSecret};
use crate::device::DeviceFlow;
use crate::error::Error;
use crate::external_account::{ExternalAccountFlow, ExternalAccountSecret};
use crate::installed::{InstalledFlow, InstalledFlowReturnMethod};
use crate::refresh::RefreshFlow;
use crate::service_account_impersonator::ServiceAccountImpersonationFlow;
#[cfg(feature = "service-account")]
use crate::service_account::{self, ServiceAccountFlow, ServiceAccountFlowOpts, ServiceAccountKey};
use crate::storage::{self, Storage, TokenStorage};
use crate::types::{AccessToken, ApplicationSecret, TokenInfo};
use private::AuthFlow;
#[cfg(all(feature = "aws-lc-rs", feature = "hyper-rustls", not(feature = "ring")))]
use rustls::crypto::aws_lc_rs::default_provider as default_crypto_provider;
#[cfg(all(feature = "ring", feature = "hyper-rustls"))]
use rustls::crypto::ring::default_provider as default_crypto_provider;
use crate::access_token::AccessTokenFlow;
use futures::lock::Mutex;
use hyper_util::client::legacy::connect::Connect;
use std::borrow::Cow;
use std::fmt;
use std::io;
use std::path::PathBuf;
use std::sync::Arc;
struct InnerAuthenticator<C> {
hyper_client: hyper_util::client::legacy::Client<C, String>,
storage: Storage,
auth_flow: AuthFlow,
}
/// Authenticator is responsible for fetching tokens, handling refreshing tokens,
/// and optionally persisting tokens to disk.
#[derive(Clone)]
pub struct Authenticator<C> {
inner: Arc<InnerAuthenticator<C>>,
}
struct DisplayScopes<'a, T>(&'a [T]);
impl<'a, T> fmt::Display for DisplayScopes<'a, T>
where
T: AsRef<str>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("[")?;
let mut iter = self.0.iter();
if let Some(first) = iter.next() {
f.write_str(first.as_ref())?;
for scope in iter {
f.write_str(", ")?;
f.write_str(scope.as_ref())?;
}
}
f.write_str("]")
}
}
impl<C> Authenticator<C>
where
C: Connect + Clone + Send + Sync + 'static,
{
/// Return the current token for the provided scopes.
pub async fn token<'a, T>(&'a self, scopes: &'a [T]) -> Result<AccessToken, Error>
where
T: AsRef<str>,
{
self.find_token_info(scopes, /* force_refresh = */ false)
.await
.map(|info| info.into())
}
/// Return a token for the provided scopes, but don't reuse cached tokens. Instead,
/// always fetch a new token from the OAuth server.
pub async fn force_refreshed_token<'a, T>(
&'a self,
scopes: &'a [T],
) -> Result<AccessToken, Error>
where
T: AsRef<str>,
{
self.find_token_info(scopes, /* force_refresh = */ true)
.await
.map(|info| info.into())
}
/// Return the current ID token for the provided scopes, if any
pub async fn id_token<'a, T>(&'a self, scopes: &'a [T]) -> Result<Option<String>, Error>
where
T: AsRef<str>,
{
self.find_token_info(scopes, /* force_refresh = */ false)
.await
.map(|info| info.id_token)
}
/// Return a cached token or fetch a new one from the server.
async fn find_token_info<'a, T>(
&'a self,
scopes: &'a [T],
force_refresh: bool,
) -> Result<TokenInfo, Error>
where
T: AsRef<str>,
{
log::debug!(
"access token requested for scopes: {}",
DisplayScopes(scopes)
);
let hashed_scopes = storage::ScopeSet::from(scopes);
match (
self.inner.storage.get(hashed_scopes).await,
self.inner.auth_flow.app_secret(),
) {
(Some(t), _) if !t.is_expired() && !force_refresh => {
// unexpired token found
log::debug!("found valid token in cache: {:?}", t);
Ok(t)
}
(
Some(TokenInfo {
refresh_token: Some(refresh_token),
..
}),
Some(app_secret),
) => {
// token is expired but has a refresh token.
let token_info_result = RefreshFlow::refresh_token(
&self.inner.hyper_client,
app_secret,
&refresh_token,
)
.await;
let token_info = if let Ok(token_info) = token_info_result {
token_info
} else {
// token refresh failed.
self.inner
.auth_flow
.token(&self.inner.hyper_client, scopes)
.await?
};
self.inner
.storage
.set(hashed_scopes, token_info.clone())
.await?;
Ok(token_info)
}
_ => {
// no token in the cache or the token returned can't be refreshed.
let token_info = self
.inner
.auth_flow
.token(&self.inner.hyper_client, scopes)
.await?;
self.inner
.storage
.set(hashed_scopes, token_info.clone())
.await?;
Ok(token_info)
}
}
}
}
/// Configure an Authenticator using the builder pattern.
pub struct AuthenticatorBuilder<C, F> {
hyper_client_builder: C,
storage_type: StorageType,
auth_flow: F,
}
/// Create an authenticator that uses the installed flow.
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # use yup_oauth2::InstalledFlowReturnMethod;
/// # let custom_flow_delegate = yup_oauth2::authenticator_delegate::DefaultInstalledFlowDelegate;
/// # let app_secret = yup_oauth2::read_application_secret("/tmp/foo").await.unwrap();
/// let authenticator = yup_oauth2::InstalledFlowAuthenticator::builder(
/// app_secret,
/// InstalledFlowReturnMethod::HTTPRedirect,
/// )
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
pub struct InstalledFlowAuthenticator;
impl InstalledFlowAuthenticator {
/// Use the builder pattern to create an Authenticator that uses the installed flow.
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
pub fn builder(
app_secret: ApplicationSecret,
method: InstalledFlowReturnMethod,
) -> AuthenticatorBuilder<DefaultHyperClient, InstalledFlow> {
Self::with_client(app_secret, method, DefaultHyperClient)
}
/// Construct a new Authenticator that uses the installed flow and the provided http client.
pub fn with_client<C>(
app_secret: ApplicationSecret,
method: InstalledFlowReturnMethod,
client: C,
) -> AuthenticatorBuilder<C, InstalledFlow> {
AuthenticatorBuilder::new(InstalledFlow::new(app_secret, method), client)
}
}
/// Create an authenticator that uses the device flow.
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # let app_secret = yup_oauth2::read_application_secret("/tmp/foo").await.unwrap();
/// let authenticator = yup_oauth2::DeviceFlowAuthenticator::builder(app_secret)
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
pub struct DeviceFlowAuthenticator;
impl DeviceFlowAuthenticator {
/// Use the builder pattern to create an Authenticator that uses the device flow.
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
pub fn builder(
app_secret: ApplicationSecret,
) -> AuthenticatorBuilder<DefaultHyperClient, DeviceFlow> {
Self::with_client(app_secret, DefaultHyperClient)
}
/// Construct a new Authenticator that uses the installed flow and the provided http client.
pub fn with_client<C>(
app_secret: ApplicationSecret,
client: C,
) -> AuthenticatorBuilder<C, DeviceFlow> {
AuthenticatorBuilder::new(DeviceFlow::new(app_secret), client)
}
}
/// Create an authenticator that uses a service account.
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # let service_account_key = yup_oauth2::read_service_account_key("/tmp/foo").await.unwrap();
/// let authenticator = yup_oauth2::ServiceAccountAuthenticator::builder(service_account_key)
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
#[cfg(feature = "service-account")]
pub struct ServiceAccountAuthenticator;
#[cfg(feature = "service-account")]
impl ServiceAccountAuthenticator {
/// Use the builder pattern to create an Authenticator that uses a service account.
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
pub fn builder(
service_account_key: ServiceAccountKey,
) -> AuthenticatorBuilder<DefaultHyperClient, ServiceAccountFlowOpts> {
Self::with_client(service_account_key, DefaultHyperClient)
}
/// Construct a new Authenticator that uses the installed flow and the provided http client.
pub fn with_client<C>(
service_account_key: ServiceAccountKey,
client: C,
) -> AuthenticatorBuilder<C, ServiceAccountFlowOpts> {
AuthenticatorBuilder::new(
ServiceAccountFlowOpts {
key: service_account::FlowOptsKey::Key(Box::new(service_account_key)),
subject: None,
},
client,
)
}
}
/// Create an authenticator that uses a application default credentials.
/// ```
/// # #[cfg(all(any(feature = "hyper-rustls", feature = "hyper-tls"), feature = "service-account"))]
/// # async fn foo() {
/// # use yup_oauth2::ApplicationDefaultCredentialsAuthenticator;
/// # use yup_oauth2::ApplicationDefaultCredentialsFlowOpts;
/// # use yup_oauth2::authenticator::ApplicationDefaultCredentialsTypes;
///
/// let opts = ApplicationDefaultCredentialsFlowOpts::default();
/// let authenticator = match ApplicationDefaultCredentialsAuthenticator::builder(opts).await {
/// ApplicationDefaultCredentialsTypes::InstanceMetadata(auth) => auth
/// .build()
/// .await
/// .expect("Unable to create instance metadata authenticator"),
/// ApplicationDefaultCredentialsTypes::ServiceAccount(auth) => auth
/// .build()
/// .await
/// .expect("Unable to create service account authenticator"),
/// };
/// # }
/// ```
pub struct ApplicationDefaultCredentialsAuthenticator;
impl ApplicationDefaultCredentialsAuthenticator {
/// Try to build ServiceAccountFlowOpts from the environment
#[cfg(feature = "service-account")]
pub async fn from_environment() -> Result<ServiceAccountFlowOpts, std::env::VarError> {
let key_path = std::env::var("GOOGLE_APPLICATION_CREDENTIALS")?;
Ok(ServiceAccountFlowOpts {
key: service_account::FlowOptsKey::Path(key_path.into()),
subject: None,
})
}
/// Use the builder pattern to deduce which model of authenticator should be used:
/// Service account one or GCE instance metadata kind
#[cfg(feature = "service-account")]
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
pub async fn builder(
opts: ApplicationDefaultCredentialsFlowOpts,
) -> ApplicationDefaultCredentialsTypes<DefaultHyperClient> {
Self::with_client(opts, DefaultHyperClient).await
}
/// Use the builder pattern to deduce which model of authenticator should be used and allow providing a hyper client
#[cfg(feature = "service-account")]
pub async fn with_client<C>(
opts: ApplicationDefaultCredentialsFlowOpts,
client: C,
) -> ApplicationDefaultCredentialsTypes<C>
where
C: HyperClientBuilder,
{
match ApplicationDefaultCredentialsAuthenticator::from_environment().await {
Ok(flow_opts) => {
let builder = AuthenticatorBuilder::new(flow_opts, client);
ApplicationDefaultCredentialsTypes::ServiceAccount(builder)
}
Err(_) => ApplicationDefaultCredentialsTypes::InstanceMetadata(
AuthenticatorBuilder::new(opts, client),
),
}
}
}
/// Types of authenticators provided by ApplicationDefaultCredentialsAuthenticator
pub enum ApplicationDefaultCredentialsTypes<C>
where
C: HyperClientBuilder,
{
/// Service account based authenticator signature
#[cfg(feature = "service-account")]
ServiceAccount(AuthenticatorBuilder<C, ServiceAccountFlowOpts>),
/// GCE Instance Metadata based authenticator signature
InstanceMetadata(AuthenticatorBuilder<C, ApplicationDefaultCredentialsFlowOpts>),
}
/// Create an authenticator that uses an authorized user credentials.
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # use yup_oauth2::authenticator::AuthorizedUserAuthenticator;
/// # let secret = yup_oauth2::read_authorized_user_secret("/tmp/foo").await.unwrap();
/// let authenticator = yup_oauth2::AuthorizedUserAuthenticator::builder(secret)
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
pub struct AuthorizedUserAuthenticator;
impl AuthorizedUserAuthenticator {
/// Use the builder pattern to create an Authenticator that uses an authorized user.
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
pub fn builder(
authorized_user_secret: AuthorizedUserSecret,
) -> AuthenticatorBuilder<DefaultHyperClient, AuthorizedUserFlow> {
Self::with_client(authorized_user_secret, DefaultHyperClient)
}
/// Construct a new Authenticator that uses the installed flow and the provided http client.
pub fn with_client<C>(
authorized_user_secret: AuthorizedUserSecret,
client: C,
) -> AuthenticatorBuilder<C, AuthorizedUserFlow> {
AuthenticatorBuilder::new(
AuthorizedUserFlow {
secret: authorized_user_secret,
},
client,
)
}
}
/// Create an authenticator that uses an external account credentials.
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # use yup_oauth2::authenticator::ExternalAccountAuthenticator;
/// # let secret = yup_oauth2::read_external_account_secret("/tmp/foo").await.unwrap();
/// let authenticator = yup_oauth2::ExternalAccountAuthenticator::builder(secret)
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
pub struct ExternalAccountAuthenticator;
impl ExternalAccountAuthenticator {
/// Use the builder pattern to create an Authenticator that uses an external account.
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
pub fn builder(
external_account_secret: ExternalAccountSecret,
) -> AuthenticatorBuilder<DefaultHyperClient, ExternalAccountFlow> {
Self::with_client(external_account_secret, DefaultHyperClient)
}
/// Construct a new Authenticator that uses the installed flow and the provided http client.
pub fn with_client<C>(
external_account_secret: ExternalAccountSecret,
client: C,
) -> AuthenticatorBuilder<C, ExternalAccountFlow> {
AuthenticatorBuilder::new(
ExternalAccountFlow {
secret: external_account_secret,
},
client,
)
}
}
/// Create a access token authenticator for use with pre-generated
/// access tokens
/// ```
/// # async fn foo() {
/// # use yup_oauth2::authenticator::AccessTokenAuthenticator;
/// # let authenticator = yup_oauth2::AccessTokenAuthenticator::builder("TOKEN".to_string())
/// # .build()
/// # .await
/// # .expect("failed to create authenticator");
/// # }
/// ```
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
pub struct AccessTokenAuthenticator;
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
impl AccessTokenAuthenticator {
/// the builder pattern for the authenticator
pub fn builder(
access_token: String,
) -> AuthenticatorBuilder<DefaultHyperClient, AccessTokenFlow> {
Self::with_client(access_token, DefaultHyperClient)
}
/// Construct a new Authenticator that uses the installed flow and the provided http client.
/// the client itself is not used
pub fn with_client<C>(
access_token: String,
client: C,
) -> AuthenticatorBuilder<C, AccessTokenFlow> {
AuthenticatorBuilder::new(AccessTokenFlow { access_token }, client)
}
}
/// Create a access token authenticator that uses user secrets to impersonate
/// a service account.
///
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # use yup_oauth2::authenticator::AuthorizedUserAuthenticator;
/// # let secret = yup_oauth2::read_authorized_user_secret("/tmp/foo").await.unwrap();
/// # let email = "my-test-account@my-test-project.iam.gserviceaccount.com";
/// let authenticator = yup_oauth2::ServiceAccountImpersonationAuthenticator::builder(secret, email)
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
pub struct ServiceAccountImpersonationAuthenticator;
impl ServiceAccountImpersonationAuthenticator {
/// Use the builder pattern to create an Authenticator that uses the device flow.
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
pub fn builder(
authorized_user_secret: AuthorizedUserSecret,
service_account_email: &str,
) -> AuthenticatorBuilder<DefaultHyperClient, ServiceAccountImpersonationFlow> {
Self::with_client(
authorized_user_secret,
service_account_email,
DefaultHyperClient,
)
}
/// Construct a new Authenticator that uses the installed flow and the provided http client.
pub fn with_client<C>(
authorized_user_secret: AuthorizedUserSecret,
service_account_email: &str,
client: C,
) -> AuthenticatorBuilder<C, ServiceAccountImpersonationFlow> {
AuthenticatorBuilder::new(
ServiceAccountImpersonationFlow::new(authorized_user_secret, service_account_email),
client,
)
}
}
/// ## Methods available when building any Authenticator.
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # let custom_hyper_client = hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new()).build_http::<String>();
/// # let app_secret = yup_oauth2::read_application_secret("/tmp/foo").await.unwrap();
/// let authenticator = yup_oauth2::DeviceFlowAuthenticator::builder(app_secret)
/// .hyper_client(custom_hyper_client)
/// .persist_tokens_to_disk("/tmp/tokenfile.json")
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
impl<C, F> AuthenticatorBuilder<C, F> {
async fn common_build(
hyper_client_builder: C,
storage_type: StorageType,
auth_flow: AuthFlow,
) -> io::Result<Authenticator<C::Connector>>
where
C: HyperClientBuilder,
{
let hyper_client = hyper_client_builder.build_hyper_client().map_err(|err| {
io::Error::new(
io::ErrorKind::Other,
format!("failed to build hyper client: {}", err),
)
})?;
let storage = match storage_type {
StorageType::Memory => Storage::Memory {
tokens: Mutex::new(storage::JSONTokens::new()),
},
StorageType::Disk(path) => Storage::Disk(storage::DiskStorage::new(path).await?),
StorageType::Custom(custom_store) => Storage::Custom(custom_store),
};
Ok(Authenticator {
inner: Arc::new(InnerAuthenticator {
hyper_client,
storage,
auth_flow,
}),
})
}
fn new(auth_flow: F, hyper_client_builder: C) -> AuthenticatorBuilder<C, F> {
AuthenticatorBuilder {
hyper_client_builder,
storage_type: StorageType::Memory,
auth_flow,
}
}
/// Use the provided token storage mechanism
pub fn with_storage(self, storage: Box<dyn TokenStorage>) -> Self {
AuthenticatorBuilder {
storage_type: StorageType::Custom(storage),
..self
}
}
/// Use the provided hyper client.
pub fn hyper_client<NewC>(
self,
hyper_client: hyper_util::client::legacy::Client<NewC, String>,
) -> AuthenticatorBuilder<hyper_util::client::legacy::Client<NewC, String>, F> {
AuthenticatorBuilder {
hyper_client_builder: hyper_client,
storage_type: self.storage_type,
auth_flow: self.auth_flow,
}
}
/// Persist tokens to disk in the provided filename.
pub fn persist_tokens_to_disk<P: Into<PathBuf>>(self, path: P) -> AuthenticatorBuilder<C, F> {
AuthenticatorBuilder {
storage_type: StorageType::Disk(path.into()),
..self
}
}
}
/// ## Methods available when building a device flow Authenticator.
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # let custom_flow_delegate = yup_oauth2::authenticator_delegate::DefaultDeviceFlowDelegate;
/// # let app_secret = yup_oauth2::read_application_secret("/tmp/foo").await.unwrap();
/// let authenticator = yup_oauth2::DeviceFlowAuthenticator::builder(app_secret)
/// .device_code_url("foo")
/// .flow_delegate(Box::new(custom_flow_delegate))
/// .grant_type("foo")
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
impl<C> AuthenticatorBuilder<C, DeviceFlow> {
/// Use the provided device code url.
pub fn device_code_url(self, url: impl Into<Cow<'static, str>>) -> Self {
AuthenticatorBuilder {
auth_flow: DeviceFlow {
device_code_url: url.into(),
..self.auth_flow
},
..self
}
}
/// Use the provided DeviceFlowDelegate.
pub fn flow_delegate(self, flow_delegate: Box<dyn DeviceFlowDelegate>) -> Self {
AuthenticatorBuilder {
auth_flow: DeviceFlow {
flow_delegate,
..self.auth_flow
},
..self
}
}
/// Use the provided grant type.
pub fn grant_type(self, grant_type: impl Into<Cow<'static, str>>) -> Self {
AuthenticatorBuilder {
auth_flow: DeviceFlow {
grant_type: grant_type.into(),
..self.auth_flow
},
..self
}
}
/// Create the authenticator.
pub async fn build(self) -> io::Result<Authenticator<C::Connector>>
where
C: HyperClientBuilder,
{
Self::common_build(
self.hyper_client_builder,
self.storage_type,
AuthFlow::DeviceFlow(self.auth_flow),
)
.await
}
}
/// ## Methods available when building an installed flow Authenticator.
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # use yup_oauth2::InstalledFlowReturnMethod;
/// # let custom_flow_delegate = yup_oauth2::authenticator_delegate::DefaultInstalledFlowDelegate;
/// # let app_secret = yup_oauth2::read_application_secret("/tmp/foo").await.unwrap();
/// let authenticator = yup_oauth2::InstalledFlowAuthenticator::builder(
/// app_secret,
/// InstalledFlowReturnMethod::HTTPRedirect,
/// )
/// .flow_delegate(Box::new(custom_flow_delegate))
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
impl<C> AuthenticatorBuilder<C, InstalledFlow> {
/// Use the provided InstalledFlowDelegate.
pub fn flow_delegate(self, flow_delegate: Box<dyn InstalledFlowDelegate>) -> Self {
AuthenticatorBuilder {
auth_flow: InstalledFlow {
flow_delegate,
..self.auth_flow
},
..self
}
}
/// Force the user to select an account on the initial request
pub fn force_account_selection(self, force: bool) -> Self {
AuthenticatorBuilder {
auth_flow: InstalledFlow {
force_account_selection: force,
..self.auth_flow
},
..self
}
}
/// Create the authenticator.
pub async fn build(self) -> io::Result<Authenticator<C::Connector>>
where
C: HyperClientBuilder,
{
Self::common_build(
self.hyper_client_builder,
self.storage_type,
AuthFlow::InstalledFlow(self.auth_flow),
)
.await
}
}
/// ## Methods available when building a service account authenticator.
/// ```
/// # #[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
/// # async fn foo() {
/// # let service_account_key = yup_oauth2::read_service_account_key("/tmp/foo").await.unwrap();
/// let authenticator = yup_oauth2::ServiceAccountAuthenticator::builder(
/// service_account_key,
/// )
/// .subject("mysubject")
/// .build()
/// .await
/// .expect("failed to create authenticator");
/// # }
/// ```
#[cfg(feature = "service-account")]
impl<C> AuthenticatorBuilder<C, ServiceAccountFlowOpts> {
/// Use the provided subject.
pub fn subject(self, subject: impl Into<String>) -> Self {
AuthenticatorBuilder {
auth_flow: ServiceAccountFlowOpts {
subject: Some(subject.into()),
..self.auth_flow
},
..self
}
}
/// Create the authenticator.
pub async fn build(self) -> io::Result<Authenticator<C::Connector>>
where
C: HyperClientBuilder,
{
let service_account_auth_flow = ServiceAccountFlow::new(self.auth_flow).await?;
Self::common_build(
self.hyper_client_builder,
self.storage_type,
AuthFlow::ServiceAccountFlow(service_account_auth_flow),
)
.await
}
}
impl<C> AuthenticatorBuilder<C, ApplicationDefaultCredentialsFlowOpts> {
/// Create the authenticator.
pub async fn build(self) -> io::Result<Authenticator<C::Connector>>
where
C: HyperClientBuilder,
{
let application_default_credential_flow =
ApplicationDefaultCredentialsFlow::new(self.auth_flow);
Self::common_build(
self.hyper_client_builder,
self.storage_type,
AuthFlow::ApplicationDefaultCredentialsFlow(application_default_credential_flow),
)
.await
}
}
/// ## Methods available when building an authorized user flow Authenticator.
impl<C> AuthenticatorBuilder<C, AuthorizedUserFlow> {
/// Create the authenticator.
pub async fn build(self) -> io::Result<Authenticator<C::Connector>>
where
C: HyperClientBuilder,
{
Self::common_build(
self.hyper_client_builder,
self.storage_type,
AuthFlow::AuthorizedUserFlow(self.auth_flow),
)
.await
}
}
/// ## Methods available when building an external account flow Authenticator.
impl<C> AuthenticatorBuilder<C, ExternalAccountFlow> {
/// Create the authenticator.
pub async fn build(self) -> io::Result<Authenticator<C::Connector>>
where
C: HyperClientBuilder,
{
Self::common_build(
self.hyper_client_builder,
self.storage_type,
AuthFlow::ExternalAccountFlow(self.auth_flow),
)
.await
}
}
/// ## Methods available when building a service account impersonation Authenticator.
impl<C> AuthenticatorBuilder<C, ServiceAccountImpersonationFlow> {
/// Create the authenticator.
pub async fn build(self) -> io::Result<Authenticator<C::Connector>>
where
C: HyperClientBuilder,
{
Self::common_build(
self.hyper_client_builder,
self.storage_type,
AuthFlow::ServiceAccountImpersonationFlow(self.auth_flow),
)
.await
}
/// Configure this authenticator to impersonate an ID token (rather an an access token,
/// as is the default).
///
/// For more on impersonating ID tokens, see [google's docs](https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc).
pub fn request_id_token(mut self) -> Self {
self.auth_flow.access_token = false;
self
}
}
/// ## Methods available when building an access token flow Authenticator.
impl<C> AuthenticatorBuilder<C, AccessTokenFlow> {
/// Create the authenticator.
pub async fn build(self) -> io::Result<Authenticator<C::Connector>>
where
C: HyperClientBuilder,
{
Self::common_build(
self.hyper_client_builder,
self.storage_type,
AuthFlow::AccessTokenFlow(self.auth_flow),
)
.await
}
}
mod private {
use crate::access_token::AccessTokenFlow;
use crate::application_default_credentials::ApplicationDefaultCredentialsFlow;
use crate::authenticator::Connect;
use crate::authorized_user::AuthorizedUserFlow;
use crate::device::DeviceFlow;
use crate::error::Error;
use crate::external_account::ExternalAccountFlow;
use crate::installed::InstalledFlow;
#[cfg(feature = "service-account")]
use crate::service_account::ServiceAccountFlow;
use crate::service_account_impersonator::ServiceAccountImpersonationFlow;
use crate::types::{ApplicationSecret, TokenInfo};
#[allow(clippy::enum_variant_names)]
pub enum AuthFlow {
DeviceFlow(DeviceFlow),
InstalledFlow(InstalledFlow),
#[cfg(feature = "service-account")]
ServiceAccountFlow(ServiceAccountFlow),
ServiceAccountImpersonationFlow(ServiceAccountImpersonationFlow),
ApplicationDefaultCredentialsFlow(ApplicationDefaultCredentialsFlow),
AuthorizedUserFlow(AuthorizedUserFlow),
ExternalAccountFlow(ExternalAccountFlow),
AccessTokenFlow(AccessTokenFlow),
}
impl AuthFlow {
pub(crate) fn app_secret(&self) -> Option<&ApplicationSecret> {
match self {
AuthFlow::DeviceFlow(device_flow) => Some(&device_flow.app_secret),
AuthFlow::InstalledFlow(installed_flow) => Some(&installed_flow.app_secret),
#[cfg(feature = "service-account")]
AuthFlow::ServiceAccountFlow(_) => None,
AuthFlow::ServiceAccountImpersonationFlow(_) => None,
AuthFlow::ApplicationDefaultCredentialsFlow(_) => None,
AuthFlow::AuthorizedUserFlow(_) => None,
AuthFlow::ExternalAccountFlow(_) => None,
AuthFlow::AccessTokenFlow(_) => None,
}
}
pub(crate) async fn token<'a, C, T>(
&'a self,
hyper_client: &'a hyper_util::client::legacy::Client<C, String>,
scopes: &'a [T],
) -> Result<TokenInfo, Error>
where
T: AsRef<str>,
C: Connect + Clone + Send + Sync + 'static,
{
match self {
AuthFlow::DeviceFlow(device_flow) => device_flow.token(hyper_client, scopes).await,
AuthFlow::InstalledFlow(installed_flow) => {
installed_flow.token(hyper_client, scopes).await
}
#[cfg(feature = "service-account")]
AuthFlow::ServiceAccountFlow(service_account_flow) => {
service_account_flow.token(hyper_client, scopes).await
}
AuthFlow::ServiceAccountImpersonationFlow(service_account_impersonation_flow) => {
service_account_impersonation_flow
.token(hyper_client, scopes)
.await
}
AuthFlow::ApplicationDefaultCredentialsFlow(adc_flow) => {
adc_flow.token(hyper_client, scopes).await
}
AuthFlow::AuthorizedUserFlow(authorized_user_flow) => {
authorized_user_flow.token(hyper_client, scopes).await
}
AuthFlow::ExternalAccountFlow(external_account_flow) => {
external_account_flow.token(hyper_client, scopes).await
}
AuthFlow::AccessTokenFlow(access_token_flow) => {
access_token_flow.token(hyper_client, scopes).await
}
}
}
}
}
/// A trait implemented for any hyper_util::client::legacy::Client as well as the DefaultHyperClient.
pub trait HyperClientBuilder {
/// The hyper connector that the resulting hyper client will use.
type Connector: Connect + Clone + Send + Sync + 'static;
/// Create a hyper::Client
fn build_hyper_client(
self,
) -> Result<hyper_util::client::legacy::Client<Self::Connector, String>, Error>;
/// Create a `hyper_util::client::legacy::Client` for tests (HTTPS not required)
#[doc(hidden)]
fn build_test_hyper_client(self)
-> hyper_util::client::legacy::Client<Self::Connector, String>;
}
#[cfg(feature = "hyper-rustls")]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
/// Default authenticator type
pub type DefaultAuthenticator =
Authenticator<hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>>;
#[cfg(all(not(feature = "hyper-rustls"), feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
/// Default authenticator type
pub type DefaultAuthenticator =
Authenticator<hyper_tls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>>;
/// The builder value used when the default hyper client should be used.
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
pub struct DefaultHyperClient;
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
#[cfg_attr(
yup_oauth2_docsrs,
doc(cfg(any(feature = "hyper-rustls", feature = "hyper-tls")))
)]
impl HyperClientBuilder for DefaultHyperClient {
#[cfg(feature = "hyper-rustls")]
type Connector =
hyper_rustls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>;
#[cfg(all(not(feature = "hyper-rustls"), feature = "hyper-tls"))]
type Connector = hyper_tls::HttpsConnector<hyper_util::client::legacy::connect::HttpConnector>;
fn build_hyper_client(
self,
) -> Result<hyper_util::client::legacy::Client<Self::Connector, String>, Error> {
#[cfg(feature = "hyper-rustls")]
let connector = hyper_rustls::HttpsConnectorBuilder::new()
.with_provider_and_native_roots(default_crypto_provider())?
.https_or_http()
.enable_http1()
.enable_http2()
.build();
#[cfg(all(not(feature = "hyper-rustls"), feature = "hyper-tls"))]
let connector = hyper_tls::HttpsConnector::new();
Ok(
hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
.pool_max_idle_per_host(0)
.build::<_, String>(connector),
)
}
fn build_test_hyper_client(
self,
) -> hyper_util::client::legacy::Client<Self::Connector, String> {
#[cfg(feature = "hyper-rustls")]
let connector = hyper_rustls::HttpsConnectorBuilder::new()
.with_provider_and_native_roots(default_crypto_provider())
.unwrap()
.https_or_http()
.enable_http1()
.enable_http2()
.build();
#[cfg(all(not(feature = "hyper-rustls"), feature = "hyper-tls"))]
let connector = hyper_tls::HttpsConnector::new();
hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
.pool_max_idle_per_host(0)
.build::<_, String>(connector)
}
}
impl<C> HyperClientBuilder for hyper_util::client::legacy::Client<C, String>
where
C: Connect + Clone + Send + Sync + 'static,
{
type Connector = C;
fn build_hyper_client(self) -> Result<hyper_util::client::legacy::Client<C, String>, Error> {
Ok(self)
}
fn build_test_hyper_client(
self,
) -> hyper_util::client::legacy::Client<Self::Connector, String> {
self
}
}
/// How should the acquired tokens be stored?
enum StorageType {
/// Store tokens in memory (and always log in again to acquire a new token on startup)
Memory,
/// Store tokens to disk in the given file. Warning, this may be insecure unless you configure your operating system to restrict read access to the file.
Disk(PathBuf),
/// Implement your own storage provider
Custom(Box<dyn TokenStorage>),
}
#[cfg(test)]
mod tests {
#[test]
#[cfg(any(feature = "hyper-rustls", feature = "hyper-tls"))]
fn ensure_send_sync() {
use super::*;
fn is_send_sync<T: Send + Sync>() {}
is_send_sync::<Authenticator<<DefaultHyperClient as HyperClientBuilder>::Connector>>()
}
}