Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rename GCPAuthError to just Error #7

Merged
merged 1 commit into from
Nov 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions src/authentication_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@ use tokio::sync::Mutex;
#[async_trait]
pub trait ServiceAccount: Send {
fn get_token(&self, scopes: &[&str]) -> Option<Token>;
async fn refresh_token(
&mut self,
client: &HyperClient,
scopes: &[&str],
) -> Result<(), GCPAuthError>;
async fn refresh_token(&mut self, client: &HyperClient, scopes: &[&str]) -> Result<(), Error>;
}

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

Expand Down
22 changes: 8 additions & 14 deletions src/custom_service_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ pub struct CustomServiceAccount {
impl CustomServiceAccount {
const GOOGLE_APPLICATION_CREDENTIALS: &'static str = "GOOGLE_APPLICATION_CREDENTIALS";

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

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

let claims = Claims::new(&self.credentials, scopes, None);
let signed = signer
.sign_claims(&claims)
.map_err(GCPAuthError::TLSError)?;
let signed = signer.sign_claims(&claims).map_err(Error::TLSError)?;
let rqbody = form_urlencoded::Serializer::new(String::new())
.extend_pairs(&[("grant_type", GRANT_TYPE), ("assertion", signed.as_str())])
.finish();
Expand All @@ -57,7 +51,7 @@ impl ServiceAccount for CustomServiceAccount {
let token = client
.request(request)
.await
.map_err(GCPAuthError::OAuthConnectionError)?
.map_err(Error::OAuthConnectionError)?
.deserialize()
.await?;
let key = scopes.iter().map(|x| (*x).to_string()).collect();
Expand Down Expand Up @@ -90,10 +84,10 @@ pub struct ApplicationCredentials {
}

impl ApplicationCredentials {
async fn from_file<T: AsRef<Path>>(path: T) -> Result<ApplicationCredentials, GCPAuthError> {
async fn from_file<T: AsRef<Path>>(path: T) -> Result<ApplicationCredentials, Error> {
let content = fs::read_to_string(path)
.await
.map_err(GCPAuthError::AplicationProfilePath)?;
Ok(serde_json::from_str(&content).map_err(GCPAuthError::AplicationProfileFormat)?)
.map_err(Error::AplicationProfilePath)?;
Ok(serde_json::from_str(&content).map_err(Error::AplicationProfileFormat)?)
}
}
20 changes: 8 additions & 12 deletions src/default_authorized_user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ impl DefaultAuthorizedUser {
const USER_CREDENTIALS_PATH: &'static str =
"/.config/gcloud/application_default_credentials.json";

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

async fn get_token(client: &HyperClient) -> Result<Token, GCPAuthError> {
async fn get_token(client: &HyperClient) -> Result<Token, Error> {
log::debug!("Loading user credentials file");
let home = dirs::home_dir().ok_or(GCPAuthError::NoHomeDir)?;
let home = dirs::home_dir().ok_or(Error::NoHomeDir)?;
let cred =
UserCredentials::from_file(home.display().to_string() + Self::USER_CREDENTIALS_PATH)
.await?;
Expand All @@ -43,7 +43,7 @@ impl DefaultAuthorizedUser {
let token = client
.request(req)
.await
.map_err(GCPAuthError::OAuthConnectionError)?
.map_err(Error::OAuthConnectionError)?
.deserialize()
.await?;
Ok(token)
Expand All @@ -56,11 +56,7 @@ impl ServiceAccount for DefaultAuthorizedUser {
Some(self.token.clone())
}

async fn refresh_token(
&mut self,
client: &HyperClient,
_scopes: &[&str],
) -> Result<(), GCPAuthError> {
async fn refresh_token(&mut self, client: &HyperClient, _scopes: &[&str]) -> Result<(), Error> {
let token = Self::get_token(client).await?;
self.token = token;
Ok(())
Expand Down Expand Up @@ -88,10 +84,10 @@ struct UserCredentials {
}

impl UserCredentials {
async fn from_file<T: AsRef<Path>>(path: T) -> Result<UserCredentials, GCPAuthError> {
async fn from_file<T: AsRef<Path>>(path: T) -> Result<UserCredentials, Error> {
let content = fs::read_to_string(path)
.await
.map_err(GCPAuthError::UserProfilePath)?;
Ok(serde_json::from_str(&content).map_err(GCPAuthError::UserProfileFormat)?)
.map_err(Error::UserProfilePath)?;
Ok(serde_json::from_str(&content).map_err(Error::UserProfileFormat)?)
}
}
12 changes: 4 additions & 8 deletions src/default_service_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub struct DefaultServiceAccount {
impl DefaultServiceAccount {
const DEFAULT_TOKEN_GCP_URI: &'static str = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token";

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

async fn get_token(client: &HyperClient) -> Result<Token, GCPAuthError> {
async fn get_token(client: &HyperClient) -> Result<Token, Error> {
log::debug!("Getting token from GCP instance metadata server");
let req = Self::build_token_request();
let token = client
.request(req)
.await
.map_err(GCPAuthError::ConnectionError)?
.map_err(Error::ConnectionError)?
.deserialize()
.await?;
Ok(token)
Expand All @@ -44,11 +44,7 @@ impl ServiceAccount for DefaultServiceAccount {
Some(self.token.clone())
}

async fn refresh_token(
&mut self,
client: &HyperClient,
_scopes: &[&str],
) -> Result<(), GCPAuthError> {
async fn refresh_token(&mut self, client: &HyperClient, _scopes: &[&str]) -> Result<(), Error> {
let token = Self::get_token(client).await?;
self.token = token;
Ok(())
Expand Down
4 changes: 2 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use thiserror::Error;
/// Enumerates all possible errors returned by this library.
#[derive(Error, Debug)]
pub enum GCPAuthError {
pub enum Error {
/// No available authentication method was discovered
///
/// Application can authenticate against GCP using:
Expand All @@ -12,7 +12,7 @@ pub enum GCPAuthError {
/// All authentication methods have been tested and none succeeded.
/// Service account file can be donwloaded from GCP in json format.
#[error("No available authentication method was discovered")]
NoAuthMethod(Box<GCPAuthError>, Box<GCPAuthError>, Box<GCPAuthError>),
NoAuthMethod(Box<Error>, Box<Error>, Box<Error>),

/// Error in underlaying RustTLS library.
/// Might signal problem with establishin secure connection using trusted certificates
Expand Down
6 changes: 3 additions & 3 deletions src/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,12 @@ pub(crate) struct JWTSigner {
}

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

Expand Down
12 changes: 6 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,13 @@ mod types;
mod util;
mod prelude {
pub(crate) use {
crate::error::GCPAuthError, crate::types::HyperClient, crate::types::Token,
crate::util::HyperExt, async_trait::async_trait, hyper::Request, serde::Deserialize,
serde::Serialize, std::collections::HashMap, std::path::Path,
crate::error::Error, crate::types::HyperClient, crate::types::Token, crate::util::HyperExt,
async_trait::async_trait, hyper::Request, serde::Deserialize, serde::Serialize,
std::collections::HashMap, std::path::Path,
};
}
pub use authentication_manager::AuthenticationManager;
pub use error::GCPAuthError;
pub use error::Error;
pub use types::Token;

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

Expand All @@ -102,7 +102,7 @@ pub async fn init() -> Result<AuthenticationManager, GCPAuthError> {
service_account: Mutex::new(Box::new(user_account)),
});
}
Err(GCPAuthError::NoAuthMethod(
Err(Error::NoAuthMethod(
Box::new(custom.unwrap_err()),
Box::new(default.unwrap_err()),
Box::new(user.unwrap_err()),
Expand Down
10 changes: 5 additions & 5 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,26 @@ use serde::de;

#[async_trait]
pub trait HyperExt {
async fn deserialize<T>(self) -> Result<T, GCPAuthError>
async fn deserialize<T>(self) -> Result<T, Error>
where
T: de::DeserializeOwned;
}

#[async_trait]
impl HyperExt for hyper::Response<hyper::body::Body> {
async fn deserialize<T>(self) -> Result<T, GCPAuthError>
async fn deserialize<T>(self) -> Result<T, Error>
where
T: de::DeserializeOwned,
{
if !self.status().is_success() {
log::error!("Server responded with error");
return Err(GCPAuthError::ServerUnavailable);
return Err(Error::ServerUnavailable);
}
let (_, body) = self.into_parts();
let body = hyper::body::to_bytes(body)
.await
.map_err(GCPAuthError::ConnectionError)?;
let token = serde_json::from_slice(&body).map_err(GCPAuthError::ParsingError)?;
.map_err(Error::ConnectionError)?;
let token = serde_json::from_slice(&body).map_err(Error::ParsingError)?;

Ok(token)
}
Expand Down