Skip to content

Commit 8b12f2e

Browse files
committed
Update documentation, introduce doctests and restructure
1 parent a3edad5 commit 8b12f2e

4 files changed

Lines changed: 93 additions & 111 deletions

File tree

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,4 @@ which = "4.2"
3535

3636
[dev-dependencies]
3737
env_logger = "0.9"
38-
tokio = { version = "1.1", features = ["macros", "rt-multi-thread"] }
38+
tokio = { version = "1.1", features = ["macros", "parking_lot", "rt-multi-thread"] }

README.md

Lines changed: 24 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# GCP Auth
2+
23
[![Crates.io][crates-badge]][crates-url]
34
[![Documentation][docs-badge]][docs-url]
45
[![MIT licensed][mit-badge]][mit-url]
@@ -10,90 +11,42 @@
1011
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
1112
[mit-url]: LICENSE
1213

13-
GCP Auth is a simple, minimal authentication library for Google Cloud Platform (GCP)
14-
providing authentication using services accounts. Once authenticated, the service
14+
GCP auth provides authentication using service accounts Google Cloud Platform (GCP)
15+
16+
GCP auth is a simple, minimal authentication library for Google Cloud Platform (GCP)
17+
providing authentication using service accounts. Once authenticated, the service
1518
account can be used to acquire bearer tokens for use in authenticating against GCP
1619
services.
1720

18-
The library looks for authentication methods in the following order:
19-
20-
1. Path to service account JSON configuration file using GOOGLE_APPLICATION_CREDENTIALS
21-
environment variable. The service account configuration file can be downloaded in the
22-
IAM service when displaying service account detail. The downloaded JSON file should
23-
be provided without any further modification.
24-
2. Invoking the library inside GCP environment fetches the default service account
25-
for the service and he application is authenticated using that particular account
26-
3. Application default credentials. Local user authetincation for development purposes
27-
created using `gcloud auth` application.
28-
4. If none of the above can be used an error occurs
29-
30-
Tokens should not be cached in the application; before every use a new token should
31-
be requested. The GCP auth library contains logic to determine if an already
32-
available token can be used, or if a new token should be requested.
33-
34-
## Default service account
21+
The library supports the following methods of retrieving tokens:
3522

36-
When running inside GCP the library can be asked without any further configuration to
37-
provide a bearer token for the current service account of the service.
23+
1. Reading custom service account credentials from the path pointed to by the
24+
`GOOGLE_APPLICATION_CREDENTIALS` environment variable. Alternatively, custom service
25+
account credentials can be read from a JSON file or string.
26+
2. Retrieving a token from the `gcloud` CLI tool, if it is available on the `PATH`.
27+
3. Use the default service account by retrieving a token from the metadata server.
28+
4. Look for credentials in `.config/gcloud/application_default_credentials.json`;
29+
if found, use these credentials to request refresh tokens.
3830

39-
```rust
40-
let scopes = &["https://www.googleapis.com/auth/bigquery/"];
41-
let authentication_manager = gcp_auth::init().await?;
42-
let token = authentication_manager.get_token(scopes).await?;
43-
```
31+
For more detailed information and examples, see the [docs][docs-url].
4432

45-
## Custom service account
33+
This crate does not currently support Windows.
4634

47-
When running outside of GCP (for example, on a developer's laptop), a custom service
48-
account may be used to grant some permissions. To use a custom service account a
49-
configuration file containing a private key can be downloaded in IAM service for the
50-
service account you intend to use. The configuration file has to be available to the
51-
application at run time. The path to the configuration file is specified by the
52-
`GOOGLE_APPLICATION_CREDENTIALS` environment variable.
35+
## Simple usage
5336

54-
```rust
55-
// With the GOOGLE_APPLICATION_CREDENTIALS environment variable set
56-
let scopes = &["https://www.googleapis.com/auth/bigquery/"];
57-
let authentication_manager = gcp_auth::init().await?;
58-
let token = authentication_manager.get_token(&scopes).await?;
59-
```
37+
The default way to use this library is to get instantiate an `AuthenticationManager`. It will
38+
find the appropriate authentication method and use it to retrieve tokens.
6039

61-
You may instantiate `authentication_manager` from a credentials file path using the method `from_credentials_file`:
62-
63-
```async
64-
// `credentials_path` variable is the path for the credentials `.json` file.
65-
let authentication_manager = gcp_auth::from_credentials_file(credentials_path).await?;
66-
let token = authentication_manager.get_token().await?;
67-
```
40+
```rust,no_run
41+
use gcp_auth::AuthenticationManager;
6842
69-
## Local user authentication
70-
71-
This authentication method allows developers to authenticate again GCP when
72-
developing locally. Its use should be limited to development. Credentials can be
73-
set up using the `gcloud auth` utility. Credentials are read from file `~/.config/gcloud/application_default_credentials.json`.
74-
75-
## FAQ
76-
77-
### Does the library support windows?
78-
79-
No.
80-
81-
## Getting tokens in multithreaded async programs
82-
83-
There is a simple pattern that can be used in async/await programs,
84-
to avoid creating multiple instances of `AuthenticationManager`:
85-
86-
```rust
87-
use once_cell::sync::Lazy;
88-
89-
static AUTHENTICATOR: Lazy<gcp_auth::AuthenticationManager> =
90-
Lazy::new(|| {
91-
futures::executor::block_on(gcp_auth::init()).expect("Should set-up auth")
92-
});
43+
let authentication_manager = AuthenticationManager::new().await?;
44+
let scopes = &["https://www.googleapis.com/auth/cloud-platform"];
45+
let token = authentication_manager.get_token(scopes).await?;
9346
```
9447

9548
# License
9649

97-
Parts of the implementatino have been sourced from [yup-oauth2](https://github.com/dermesser/yup-oauth2).
50+
Parts of the implementation have been sourced from [yup-oauth2](https://github.com/dermesser/yup-oauth2).
9851

9952
Licensed under [MIT license](http://opensource.org/licenses/MIT).

src/custom_service_account.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ use crate::util::HyperExt;
1414
///
1515
/// Once initialized, a [`CustomServiceAccount`] can be converted into an [`AuthenticationManager`]
1616
/// using the applicable `From` implementation.
17+
///
18+
/// [`AuthenticationManager`]: crate::AuthenticationManager
1719
#[derive(Debug)]
1820
pub struct CustomServiceAccount {
1921
credentials: ApplicationCredentials,

src/lib.rs

Lines changed: 66 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,87 @@
11
//! GCP auth provides authentication using service accounts Google Cloud Platform (GCP)
22
//!
3-
//! The library looks for authentication methods in the following order:
3+
//! GCP auth is a simple, minimal authentication library for Google Cloud Platform (GCP)
4+
//! providing authentication using service accounts. Once authenticated, the service
5+
//! account can be used to acquire bearer tokens for use in authenticating against GCP
6+
//! services.
47
//!
5-
//! 1. Path to service account JSON configuration file using GOOGLE_APPLICATION_CREDENTIALS environment
6-
//! variable. The service account configuration file can be downloaded in the IAM service when displaying service account detail.
7-
//! The downloaded JSON file should be provided without any further modification.
8-
//! 2. Invoking the library inside GCP environment fetches the default service account for the service and
9-
//! the application is authenticated using that particular account
10-
//! 3. Application default credentials. Local user authentication for development purposes created using `gcloud auth` application.
11-
//! 4. If none of the above can be used an error occurs
8+
//! The library supports the following methods of retrieving tokens:
129
//!
13-
//! The tokens are single-use and as such they shouldn't be cached and for each use a new token should be requested.
14-
//! Library handles token caching for their lifetime and so it won't make a request if a token with appropriate scope
15-
//! is available.
10+
//! 1. Reading custom service account credentials from the path pointed to by the
11+
//! `GOOGLE_APPLICATION_CREDENTIALS` environment variable. Alternatively, custom service
12+
//! account credentials can be read from a JSON file or string.
13+
//! 2. Retrieving a token from the `gcloud` CLI tool, if it is available on the `PATH`.
14+
//! 3. Use the default service account by retrieving a token from the metadata server.
15+
//! 4. Look for credentials in `.config/gcloud/application_default_credentials.json`;
16+
//! if found, use these credentials to request refresh tokens.
1617
//!
17-
//! # Default service account
18+
//! For more details, see [`AuthenticationManager::new()`].
1819
//!
19-
//! When running inside GCP the library can be asked directly without any further configuration to provide a Bearer token
20-
//! for the current service account of the service.
20+
//! The `AuthenticationManager` handles caching tokens for their lifetime; it will not make a request if
21+
//! an appropriate token is already cached. Therefore, the caller should not cache tokens.
2122
//!
22-
//! ```async
23-
//! let authentication_manager = gcp_auth::init().await?;
24-
//! let token = authentication_manager.get_token().await?;
25-
//! ```
23+
//! ## Simple usage
2624
//!
27-
//! # Custom service account
25+
//! The default way to use this library is to get instantiate an [`AuthenticationManager`]. It will
26+
//! find the appropriate authentication method and use it to retrieve tokens.
2827
//!
29-
//! When running outside of GCP e.g on development laptop to allow finer granularity for permission a
30-
//! custom service account can be used. To use a custom service account a configuration file containing key
31-
//! has to be downloaded in IAM service for the service account you intend to use. The configuration file has to
32-
//! be available to the application at run time. The path to the configuration file is specified by
33-
//! `GOOGLE_APPLICATION_CREDENTIALS` environment variable.
28+
//! ```rust,no_run
29+
//! # async fn get_token() -> Result<(), gcp_auth::Error> {
30+
//! use gcp_auth::AuthenticationManager;
3431
//!
35-
//! ```async
36-
//! // GOOGLE_APPLICATION_CREDENTIALS environment variable is set-up
37-
//! let authentication_manager = gcp_auth::init().await?;
38-
//! let token = authentication_manager.get_token().await?;
32+
//! let authentication_manager = AuthenticationManager::new().await?;
33+
//! let scopes = &["https://www.googleapis.com/auth/cloud-platform"];
34+
//! let token = authentication_manager.get_token(scopes).await?;
35+
//! # Ok(())
36+
//! # }
3937
//! ```
40-
//! You may instantiate `authentication_manager` from a credentials file path using the method `from_credentials_file`:
4138
//!
42-
//! ```async
39+
//! ## Supplying service account credentials
40+
//!
41+
//! When running outside of GCP (for example, on a development machine), it can be useful to supply
42+
//! service account credentials. The first method checked by [`AuthenticationManager::new()`] is to
43+
//! read a path to a file containing JSON credentials in the `GOOGLE_APPLICATION_CREDENTIALS`
44+
//! environment variable. However, you may also supply a custom path to read credentials from, or
45+
//! a `&str` containing the credentials. In both of these cases, you should create a
46+
//! [`CustomServiceAccount`] directly using one of its associated functions:
47+
//!
48+
//! ```rust,no_run
49+
//! # use std::path::PathBuf;
50+
//! #
51+
//! # async fn get_token() -> Result<(), gcp_auth::Error> {
52+
//! use gcp_auth::{AuthenticationManager, CustomServiceAccount};
53+
//!
4354
//! // `credentials_path` variable is the path for the credentials `.json` file.
44-
//! let authentication_manager = gcp_auth::from_credentials_file(credentials_path).await?;
45-
//! let token = authentication_manager.get_token().await?;
55+
//! let credentials_path = PathBuf::from("service-account.json");
56+
//! let service_account = CustomServiceAccount::from_file(credentials_path)?;
57+
//! let authentication_manager = AuthenticationManager::from(service_account);
58+
//! let scopes = &["https://www.googleapis.com/auth/cloud-platform"];
59+
//! let token = authentication_manager.get_token(scopes).await?;
60+
//! # Ok(())
61+
//! # }
4662
//! ```
4763
//!
48-
//! # Local user authentication
49-
//! This authentication method allows developers to authenticate again GCP services when developing locally.
50-
//! The method is intended only for development. Credentials can be set-up using `gcloud auth` utility.
51-
//! Credentials are read from file `~/.config/gcloud/application_default_credentials.json`.
64+
//! ## Getting tokens in multi-thread or async environments
65+
//!
66+
//! Using a `OnceCell` makes it easy to reuse the [`AuthenticationManager`] across different
67+
//! threads or async tasks.
5268
//!
53-
//! # FAQ
69+
//! ```rust,no_run
70+
//! use gcp_auth::AuthenticationManager;
71+
//! use tokio::sync::OnceCell;
5472
//!
55-
//! ## Does library support windows?
73+
//! static AUTH_MANAGER: OnceCell<AuthenticationManager> = OnceCell::const_new();
5674
//!
57-
//! No
75+
//! async fn authentication_manager() -> &'static AuthenticationManager {
76+
//! AUTH_MANAGER
77+
//! .get_or_init(|| async {
78+
//! AuthenticationManager::new()
79+
//! .await
80+
//! .expect("unable to initialize authentication manager")
81+
//! })
82+
//! .await
83+
//! }
84+
//! ```
5885
5986
#![deny(missing_docs)]
6087
#![deny(warnings)]

0 commit comments

Comments
 (0)