Skip to content

Commit 00895df

Browse files
committed
Rename GCPAuthError to just Error
Naming the error type Error seems idiomatic. Additionally, the GCPAuthError name does not comply with the API guidelines for acronyms.
1 parent c5af83b commit 00895df

File tree

8 files changed

+38
-56
lines changed

8 files changed

+38
-56
lines changed

src/authentication_manager.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,7 @@ use tokio::sync::Mutex;
44
#[async_trait]
55
pub trait ServiceAccount: Send {
66
fn get_token(&self, scopes: &[&str]) -> Option<Token>;
7-
async fn refresh_token(
8-
&mut self,
9-
client: &HyperClient,
10-
scopes: &[&str],
11-
) -> Result<(), GCPAuthError>;
7+
async fn refresh_token(&mut self, client: &HyperClient, scopes: &[&str]) -> Result<(), Error>;
128
}
139

1410
/// Authentication manager is responsible for caching and obtaing credentials for the required scope
@@ -23,7 +19,7 @@ impl AuthenticationManager {
2319
/// Requests Bearer token for the provided scope
2420
///
2521
/// Token can be used in the request authorization header in format "Bearer {token}"
26-
pub async fn get_token(&self, scopes: &[&str]) -> Result<Token, GCPAuthError> {
22+
pub async fn get_token(&self, scopes: &[&str]) -> Result<Token, Error> {
2723
let mut sa = self.service_account.lock().await;
2824
let mut token = sa.get_token(scopes);
2925

src/custom_service_account.rs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ pub struct CustomServiceAccount {
1111
impl CustomServiceAccount {
1212
const GOOGLE_APPLICATION_CREDENTIALS: &'static str = "GOOGLE_APPLICATION_CREDENTIALS";
1313

14-
pub async fn new() -> Result<Self, GCPAuthError> {
14+
pub async fn new() -> Result<Self, Error> {
1515
let path = std::env::var(Self::GOOGLE_APPLICATION_CREDENTIALS)
16-
.map_err(|_| GCPAuthError::AplicationProfileMissing)?;
16+
.map_err(|_| Error::AplicationProfileMissing)?;
1717
let credentials = ApplicationCredentials::from_file(path).await?;
1818
Ok(Self {
1919
credentials,
@@ -29,11 +29,7 @@ impl ServiceAccount for CustomServiceAccount {
2929
self.tokens.get(&key).cloned()
3030
}
3131

32-
async fn refresh_token(
33-
&mut self,
34-
client: &HyperClient,
35-
scopes: &[&str],
36-
) -> Result<(), GCPAuthError> {
32+
async fn refresh_token(&mut self, client: &HyperClient, scopes: &[&str]) -> Result<(), Error> {
3733
use crate::jwt::Claims;
3834
use crate::jwt::JWTSigner;
3935
use crate::jwt::GRANT_TYPE;
@@ -43,9 +39,7 @@ impl ServiceAccount for CustomServiceAccount {
4339
let signer = JWTSigner::new(&self.credentials.private_key)?;
4440

4541
let claims = Claims::new(&self.credentials, scopes, None);
46-
let signed = signer
47-
.sign_claims(&claims)
48-
.map_err(GCPAuthError::TLSError)?;
42+
let signed = signer.sign_claims(&claims).map_err(Error::TLSError)?;
4943
let rqbody = form_urlencoded::Serializer::new(String::new())
5044
.extend_pairs(&[("grant_type", GRANT_TYPE), ("assertion", signed.as_str())])
5145
.finish();
@@ -57,7 +51,7 @@ impl ServiceAccount for CustomServiceAccount {
5751
let token = client
5852
.request(request)
5953
.await
60-
.map_err(GCPAuthError::OAuthConnectionError)?
54+
.map_err(Error::OAuthConnectionError)?
6155
.deserialize()
6256
.await?;
6357
let key = scopes.iter().map(|x| (*x).to_string()).collect();
@@ -90,10 +84,10 @@ pub struct ApplicationCredentials {
9084
}
9185

9286
impl ApplicationCredentials {
93-
async fn from_file<T: AsRef<Path>>(path: T) -> Result<ApplicationCredentials, GCPAuthError> {
87+
async fn from_file<T: AsRef<Path>>(path: T) -> Result<ApplicationCredentials, Error> {
9488
let content = fs::read_to_string(path)
9589
.await
96-
.map_err(GCPAuthError::AplicationProfilePath)?;
97-
Ok(serde_json::from_str(&content).map_err(GCPAuthError::AplicationProfileFormat)?)
90+
.map_err(Error::AplicationProfilePath)?;
91+
Ok(serde_json::from_str(&content).map_err(Error::AplicationProfileFormat)?)
9892
}
9993
}

src/default_authorized_user.rs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ impl DefaultAuthorizedUser {
1414
const USER_CREDENTIALS_PATH: &'static str =
1515
"/.config/gcloud/application_default_credentials.json";
1616

17-
pub async fn new(client: &HyperClient) -> Result<Self, GCPAuthError> {
17+
pub async fn new(client: &HyperClient) -> Result<Self, Error> {
1818
let token = Self::get_token(client).await?;
1919
Ok(Self { token })
2020
}
@@ -28,9 +28,9 @@ impl DefaultAuthorizedUser {
2828
.unwrap()
2929
}
3030

31-
async fn get_token(client: &HyperClient) -> Result<Token, GCPAuthError> {
31+
async fn get_token(client: &HyperClient) -> Result<Token, Error> {
3232
log::debug!("Loading user credentials file");
33-
let home = dirs::home_dir().ok_or(GCPAuthError::NoHomeDir)?;
33+
let home = dirs::home_dir().ok_or(Error::NoHomeDir)?;
3434
let cred =
3535
UserCredentials::from_file(home.display().to_string() + Self::USER_CREDENTIALS_PATH)
3636
.await?;
@@ -43,7 +43,7 @@ impl DefaultAuthorizedUser {
4343
let token = client
4444
.request(req)
4545
.await
46-
.map_err(GCPAuthError::OAuthConnectionError)?
46+
.map_err(Error::OAuthConnectionError)?
4747
.deserialize()
4848
.await?;
4949
Ok(token)
@@ -56,11 +56,7 @@ impl ServiceAccount for DefaultAuthorizedUser {
5656
Some(self.token.clone())
5757
}
5858

59-
async fn refresh_token(
60-
&mut self,
61-
client: &HyperClient,
62-
_scopes: &[&str],
63-
) -> Result<(), GCPAuthError> {
59+
async fn refresh_token(&mut self, client: &HyperClient, _scopes: &[&str]) -> Result<(), Error> {
6460
let token = Self::get_token(client).await?;
6561
self.token = token;
6662
Ok(())
@@ -88,10 +84,10 @@ struct UserCredentials {
8884
}
8985

9086
impl UserCredentials {
91-
async fn from_file<T: AsRef<Path>>(path: T) -> Result<UserCredentials, GCPAuthError> {
87+
async fn from_file<T: AsRef<Path>>(path: T) -> Result<UserCredentials, Error> {
9288
let content = fs::read_to_string(path)
9389
.await
94-
.map_err(GCPAuthError::UserProfilePath)?;
95-
Ok(serde_json::from_str(&content).map_err(GCPAuthError::UserProfileFormat)?)
90+
.map_err(Error::UserProfilePath)?;
91+
Ok(serde_json::from_str(&content).map_err(Error::UserProfileFormat)?)
9692
}
9793
}

src/default_service_account.rs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ pub struct DefaultServiceAccount {
1111
impl DefaultServiceAccount {
1212
const DEFAULT_TOKEN_GCP_URI: &'static str = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token";
1313

14-
pub async fn new(client: &HyperClient) -> Result<Self, GCPAuthError> {
14+
pub async fn new(client: &HyperClient) -> Result<Self, Error> {
1515
let token = Self::get_token(client).await?;
1616
Ok(Self { token })
1717
}
@@ -25,13 +25,13 @@ impl DefaultServiceAccount {
2525
.unwrap()
2626
}
2727

28-
async fn get_token(client: &HyperClient) -> Result<Token, GCPAuthError> {
28+
async fn get_token(client: &HyperClient) -> Result<Token, Error> {
2929
log::debug!("Getting token from GCP instance metadata server");
3030
let req = Self::build_token_request();
3131
let token = client
3232
.request(req)
3333
.await
34-
.map_err(GCPAuthError::ConnectionError)?
34+
.map_err(Error::ConnectionError)?
3535
.deserialize()
3636
.await?;
3737
Ok(token)
@@ -44,11 +44,7 @@ impl ServiceAccount for DefaultServiceAccount {
4444
Some(self.token.clone())
4545
}
4646

47-
async fn refresh_token(
48-
&mut self,
49-
client: &HyperClient,
50-
_scopes: &[&str],
51-
) -> Result<(), GCPAuthError> {
47+
async fn refresh_token(&mut self, client: &HyperClient, _scopes: &[&str]) -> Result<(), Error> {
5248
let token = Self::get_token(client).await?;
5349
self.token = token;
5450
Ok(())

src/error.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use thiserror::Error;
22
/// Enumerates all possible errors returned by this library.
33
#[derive(Error, Debug)]
4-
pub enum GCPAuthError {
4+
pub enum Error {
55
/// No available authentication method was discovered
66
///
77
/// Application can authenticate against GCP using:
@@ -12,7 +12,7 @@ pub enum GCPAuthError {
1212
/// All authentication methods have been tested and none succeeded.
1313
/// Service account file can be donwloaded from GCP in json format.
1414
#[error("No available authentication method was discovered")]
15-
NoAuthMethod(Box<GCPAuthError>, Box<GCPAuthError>, Box<GCPAuthError>),
15+
NoAuthMethod(Box<Error>, Box<Error>, Box<Error>),
1616

1717
/// Error in underlaying RustTLS library.
1818
/// Might signal problem with establishin secure connection using trusted certificates

src/jwt.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,12 +82,12 @@ pub(crate) struct JWTSigner {
8282
}
8383

8484
impl JWTSigner {
85-
pub fn new(private_key: &str) -> Result<Self, GCPAuthError> {
85+
pub fn new(private_key: &str) -> Result<Self, Error> {
8686
let key = decode_rsa_key(private_key)?;
87-
let signing_key = sign::RSASigningKey::new(&key).map_err(|_| GCPAuthError::SignerInit)?;
87+
let signing_key = sign::RSASigningKey::new(&key).map_err(|_| Error::SignerInit)?;
8888
let signer = signing_key
8989
.choose_scheme(&[rustls::SignatureScheme::RSA_PKCS1_SHA256])
90-
.ok_or_else(|| GCPAuthError::SignerSchemeError)?;
90+
.ok_or_else(|| Error::SignerSchemeError)?;
9191
Ok(JWTSigner { signer })
9292
}
9393

src/lib.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,13 +61,13 @@ mod types;
6161
mod util;
6262
mod prelude {
6363
pub(crate) use {
64-
crate::error::GCPAuthError, crate::types::HyperClient, crate::types::Token,
65-
crate::util::HyperExt, async_trait::async_trait, hyper::Request, serde::Deserialize,
66-
serde::Serialize, std::collections::HashMap, std::path::Path,
64+
crate::error::Error, crate::types::HyperClient, crate::types::Token, crate::util::HyperExt,
65+
async_trait::async_trait, hyper::Request, serde::Deserialize, serde::Serialize,
66+
std::collections::HashMap, std::path::Path,
6767
};
6868
}
6969
pub use authentication_manager::AuthenticationManager;
70-
pub use error::GCPAuthError;
70+
pub use error::Error;
7171
pub use types::Token;
7272

7373
use hyper::Client;
@@ -77,7 +77,7 @@ use tokio::sync::Mutex;
7777
/// Initialize GCP authentication
7878
///
7979
/// Returns `AuthenticationManager` which can be used to obtain tokens
80-
pub async fn init() -> Result<AuthenticationManager, GCPAuthError> {
80+
pub async fn init() -> Result<AuthenticationManager, Error> {
8181
let https = HttpsConnector::new();
8282
let client = Client::builder().build::<_, hyper::Body>(https);
8383

@@ -102,7 +102,7 @@ pub async fn init() -> Result<AuthenticationManager, GCPAuthError> {
102102
service_account: Mutex::new(Box::new(user_account)),
103103
});
104104
}
105-
Err(GCPAuthError::NoAuthMethod(
105+
Err(Error::NoAuthMethod(
106106
Box::new(custom.unwrap_err()),
107107
Box::new(default.unwrap_err()),
108108
Box::new(user.unwrap_err()),

src/util.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,26 @@ use serde::de;
33

44
#[async_trait]
55
pub trait HyperExt {
6-
async fn deserialize<T>(self) -> Result<T, GCPAuthError>
6+
async fn deserialize<T>(self) -> Result<T, Error>
77
where
88
T: de::DeserializeOwned;
99
}
1010

1111
#[async_trait]
1212
impl HyperExt for hyper::Response<hyper::body::Body> {
13-
async fn deserialize<T>(self) -> Result<T, GCPAuthError>
13+
async fn deserialize<T>(self) -> Result<T, Error>
1414
where
1515
T: de::DeserializeOwned,
1616
{
1717
if !self.status().is_success() {
1818
log::error!("Server responded with error");
19-
return Err(GCPAuthError::ServerUnavailable);
19+
return Err(Error::ServerUnavailable);
2020
}
2121
let (_, body) = self.into_parts();
2222
let body = hyper::body::to_bytes(body)
2323
.await
24-
.map_err(GCPAuthError::ConnectionError)?;
25-
let token = serde_json::from_slice(&body).map_err(GCPAuthError::ParsingError)?;
24+
.map_err(Error::ConnectionError)?;
25+
let token = serde_json::from_slice(&body).map_err(Error::ParsingError)?;
2626

2727
Ok(token)
2828
}

0 commit comments

Comments
 (0)