### Example: Provider Customization and Fallback Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to explicitly configure providers and handle fallback scenarios. ```rust use gcp_auth::{Credentials, Provider}; // Assuming Provider enum exists async fn custom_provider_config() -> Credentials { let mut builder = gcp_auth::Credentials::builder(); // Explicitly add a provider, e.g., a service account key file. builder.add_provider(Provider::ServiceAccountJsonPath("path/to/key.json".to_string())); // The builder will still attempt other providers if the explicit one fails or is not suitable. builder.build().await.expect("Failed to build credentials") } ``` -------------------------------- ### Example: Local Development with Gcloud Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates setting up authentication for local development using gcloud. ```rust // Ensure you have run `gcloud auth application-default login` // The library will automatically pick up these credentials. let credentials = gcp_auth::find_credentials().await.expect("Failed to find credentials"); ``` -------------------------------- ### CI/CD Pipeline Authentication Setup (GitHub Actions) Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/authentication-discovery.md Example YAML configuration for authenticating to Google Cloud in a GitHub Actions workflow using a service account key. ```yaml - name: Authenticate to Google Cloud uses: google-github-actions/auth@v1 with: credentials_json: ${{ secrets.GCP_SA_KEY }} ``` -------------------------------- ### Instantiate and Get Token with MetadataServiceAccount Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-metadata-service-account.md Example of creating a MetadataServiceAccount and fetching a token. This code must run on a GCP compute instance. The token obtained is for the 'cloud-platform' scope. ```rust use gcp_auth::{MetadataServiceAccount, TokenProvider}; #[tokio::main] async fn main() -> Result<(), Box> { // This will only work when running on a GCP compute instance let metadata = MetadataServiceAccount::new().await?; let token = metadata.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; println!("Token from metadata server acquired"); Ok(()) } ``` -------------------------------- ### Example: User Impersonation / Domain-Wide Delegation Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates how to use domain-wide delegation to impersonate a user. ```rust use gcp_auth::Credentials; async fn get_delegated_token() -> String { let mut credentials = gcp_auth::find_credentials().await.expect("Failed to find credentials"); // Impersonate a user for domain-wide delegation. let delegated_credentials = credentials.with_subject("user:impersonated-user@example.com"); let token = delegated_credentials.token().await.expect("Failed to get token"); token.access_token } ``` -------------------------------- ### Token Caching Example Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates how the library handles token caching automatically. ```rust use gcp_auth::Credentials; async fn use_cached_token() { let credentials = gcp_auth::find_credentials().await.expect("Failed to find credentials"); // The library manages token caching internally. // When you request a token, it will check the cache first. let token = credentials.token().await.expect("Failed to get token"); println!("Obtained token: {}", token.access_token); // The token will be automatically refreshed if expired. } ``` -------------------------------- ### Quick Start: Discover Credentials and Get Token Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/index.md This snippet demonstrates the most common usage pattern for the gcp_auth library. It automatically discovers credentials, retrieves an access token for specified scopes, and optionally fetches the project ID. Ensure you have the tokio runtime available for async operations. ```rust use gcp_auth::TokenProvider; #[tokio::main] async fn main() -> Result<(), Box> { // Automatically discovers credentials let provider = gcp_auth::provider().await?; // Get a token for specific scopes let scopes = &["https://www.googleapis.com/auth/cloud-platform"]; let token = provider.token(scopes).await?; // Use as bearer token println!("Bearer: {}", token.as_str()); // Optional: get project ID let project_id = provider.project_id().await?; println!("Project: {}", project_id); Ok(()) } ``` -------------------------------- ### Production on GCP Instance Setup Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/authentication-discovery.md Command to create a GCP compute instance with a specified service account. This is recommended for production environments on GCP. ```bash gcloud compute instances create my-instance \ --service-account=my-sa@my-project.iam.gserviceaccount.com ``` -------------------------------- ### Example: Production on GCP Compute Instances Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates authentication when running on GCP Compute Instances, leveraging the metadata server. ```rust // When running on a GCP Compute Instance, the library automatically uses the metadata server. let credentials = gcp_auth::find_credentials().await.expect("Failed to find credentials"); ``` -------------------------------- ### Example: Development with Explicit Service Account Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to authenticate using an explicitly provided service account JSON key file. ```rust use gcp_auth::service_account::CustomServiceAccount; let credentials = CustomServiceAccount::builder() .json_key_path("path/to/your/service-account-key.json") .build(); let token = credentials.token().await.expect("Failed to get token"); ``` -------------------------------- ### Local Development: Authenticate with gcloud Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/00_START_HERE.md This scenario outlines the setup and code for authenticating in a local development environment using `gcloud auth application-default login`. It shows how to obtain a provider after the initial setup. ```bash # Setup gcloud auth application-default login # Code let provider = gcp_auth::provider().await?; ``` -------------------------------- ### Example: CI/CD Pipeline Authentication Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates a common pattern for authenticating in CI/CD environments using service account keys. ```rust use gcp_auth::service_account::CustomServiceAccount; // Load service account key from an environment variable or secret management system. let key_json = std::env::var("GOOGLE_APPLICATION_CREDENTIALS_JSON") .expect("GOOGLE_APPLICATION_CREDENTIALS_JSON must be set"); let credentials = CustomServiceAccount::builder() .json_key_string(&key_json) .build(); let token = credentials.token().await.expect("Failed to get token"); ``` -------------------------------- ### Development Environment Authentication Setup Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/configuration.md Sets up authentication for a development environment using gcloud CLI or a service account JSON file. ```bash # Set up gcloud gcloud auth application-default login # Or set an explicit service account export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json ``` -------------------------------- ### Example: Custom JWT Generation Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to configure and generate custom JWTs for specific authentication needs. ```rust use gcp_auth::service_account::CustomServiceAccount; let credentials = CustomServiceAccount::builder() .json_key_path("path/to/your/key.json") .with_audience("https://my.custom.audience") .build(); // The token obtained will be a JWT signed by the service account, with the specified audience. let token = credentials.token().await.expect("Failed to get token"); ``` -------------------------------- ### Authenticating with GCP Instance Metadata Server Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Example of how the library fetches credentials from the GCP metadata server. ```rust use gcp_auth::Credentials; async fn authenticate_from_metadata_server() -> Credentials { // If running on a GCP Compute Instance, this will be the default provider. gcp_auth::find_credentials().await.expect("Failed to find credentials") } ``` -------------------------------- ### Example: Container-Based Deployments Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Shows authentication for applications running in containers, often using service account keys. ```rust use gcp_auth::service_account::CustomServiceAccount; // Assuming the service account key is mounted as a file inside the container. let credentials = CustomServiceAccount::builder() .json_key_path("/etc/secrets/gcp-key.json") .build(); let token = credentials.token().await.expect("Failed to get token"); ``` -------------------------------- ### Example Usage of ConfigDefaultCredentials Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-config-default-credentials.md Demonstrates how to create a ConfigDefaultCredentials instance and obtain an access token for a specific scope. This is typically used during local development. ```rust use gcp_auth::{ConfigDefaultCredentials, TokenProvider}; #[tokio::main] async fn main() -> Result<(), Box> { let credentials = ConfigDefaultCredentials::new().await?; let token = credentials.token(&["https://www.googleapis.com/auth/drive"]).await?; println!("Using gcloud default credentials"); Ok(()) } ``` -------------------------------- ### provider() Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md Automatically discovers and initializes an authentication provider. This is the main function to get a `TokenProvider` instance. ```APIDOC ## provider() ### Description Automatically discovers and initializes an authentication provider. ### Function Signature `pub async fn provider() -> Result, Error>` ### Import `use gcp_auth::provider;` ### Returns `Result, Error>` - An `Arc` containing a dynamic `TokenProvider` implementation or an `Error`. ### Details See [api-reference-provider.md](api-reference-provider.md) ### Example ```rust let provider = gcp_auth::provider().await?; ``` ``` -------------------------------- ### Token Debug Implementation Example Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/types.md Illustrates the masked output of the `Debug` implementation for `Token`, which hides the sensitive access token string. ```text Token { access_token: "****", expires_at: 2024-06-16T15:30:45.123456Z, } ``` -------------------------------- ### CI/CD Pipeline: Authenticate with Service Account Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/00_START_HERE.md This scenario details the setup for authenticating in a CI/CD pipeline by exporting the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. It then shows how to obtain a provider. ```bash # Setup export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json # Code let provider = gcp_auth::provider().await?; ``` -------------------------------- ### Example: Token Sharing Across Async Tasks Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates how to share a token obtained from the library across multiple asynchronous tasks using Arc. ```rust use gcp_auth::Credentials; use std::sync::Arc; use tokio::task; async fn fetch_data(credentials: Arc) { let token = credentials.token().await.expect("Failed to get token"); println!("Task using token: {}", token.access_token); // Use the token to make an authenticated request } #[tokio::main] async fn main() { let credentials = Arc::new(gcp_auth::find_credentials().await.expect("Failed to find credentials")); let mut tasks = vec![]; for _ in 0..5 { let creds_clone = Arc::clone(&credentials); tasks.push(task::spawn(fetch_data(creds_clone))); } for task in tasks { task.await.expect("Task failed"); } } ``` -------------------------------- ### Basic Error Handling with anyhow::Result Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/errors.md This example shows how to use `anyhow::Result` and the `?` operator for simplified error propagation in an async main function. ```rust #[tokio::main] async fn main() -> Result<(), Box> { let provider = gcp_auth::provider().await?; let token = provider.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; Ok(()) } ``` -------------------------------- ### GCloudAuthorizedUser Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md Initializes credentials by interacting with the gcloud CLI tool. This is useful when gcloud is installed and authenticated. ```rust use gcp_auth::{GCloudAuthorizedUser, TokenProvider}; let gcloud = GCloudAuthorizedUser::new().await?; let token = gcloud.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; ``` -------------------------------- ### GCP Default Credentials File Format Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-config-default-credentials.md This is an example of the JSON structure for the `application_default_credentials.json` file. It includes fields necessary for authentication and quota management. ```json { "client_id": "...", "client_secret": "...", "quota_project_id": "my-project", "refresh_token": "..." } ``` -------------------------------- ### Enabling Crate Feature Flags Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Example of how to enable specific feature flags for the gcp-auth crate in Cargo.toml. ```toml [dependencies.gcp-auth] version = "0.1.0" features = ["mock-requests", "google-cloud-storage"] ``` -------------------------------- ### Authenticate and Get Tokens Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-custom-service-account.md Demonstrates how to create a CustomServiceAccount from a file and retrieve authentication tokens. It shows token caching for identical scope requests and how different scopes result in separate token fetches. ```rust let account = CustomServiceAccount::from_file("service-account.json")?; // First call fetches a new token let token1 = account.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; // Immediate second call returns cached token let token2 = account.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; // Different scopes create a separate cache entry let token3 = account.token(&["https://www.googleapis.com/auth/compute"]).await?; ``` -------------------------------- ### Production on GCP: Automatic Metadata Server Detection Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/00_START_HERE.md This scenario illustrates the code for authenticating in a production environment on GCP. No explicit setup is needed as the library automatically detects and uses the metadata service. ```rust // No setup needed — automatic metadata server detection let provider = gcp_auth::provider().await?; ``` -------------------------------- ### Configure CustomServiceAccount with Builder Pattern Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/configuration.md Example of configuring a CustomServiceAccount using the builder pattern, including setting subject and audience. Used for domain-wide delegation. ```rust use gcp_auth::{CustomServiceAccount, TokenProvider}; let account = CustomServiceAccount::from_file("service-account.json")? .with_subject("user@example.com".to_string()) .with_audience("https://example.com".to_string()); let token = account.token(&["https://www.googleapis.com/auth/drive"]).await?; ``` -------------------------------- ### Quick Start: Obtain GCP Token Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/00_START_HERE.md This snippet demonstrates the basic usage of the gcp_auth library to obtain an authentication token for a specified scope. It requires the `TokenProvider` trait and uses `tokio` for asynchronous operations. ```rust use gcp_auth::TokenProvider; #[tokio::main] async fn main() -> Result<(), Box> { let provider = gcp_auth::provider().await?; let token = provider.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; println!("Token: {}", token.as_str()); Ok(()) } ``` -------------------------------- ### Service Account Credentials JSON Format Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/configuration.md Example JSON structure for service account credentials. Required fields include client_email, private_key, and token_uri. ```json { "type": "service_account", "project_id": "my-project-123", "private_key_id": "key-id", "private_key": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----", "client_email": "my-service-account@my-project-123.iam.gserviceaccount.com", "client_id": "123456789", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs" } ``` -------------------------------- ### Set GOOGLE_APPLICATION_CREDENTIALS Environment Variable Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/authentication-discovery.md Example of setting the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to a service account JSON file. This is typically used in development or CI/CD environments. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json # Then the provider() function will use CustomServiceAccount ``` -------------------------------- ### Attempt to Load GCloudAuthorizedUser Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/authentication-discovery.md Attempts to obtain an access token by executing the `gcloud auth print-access-token` command. This method requires the gcloud CLI to be installed and authenticated. ```rust let gcloud_error = match GCloudAuthorizedUser::new().await { Ok(provider) => return Ok(Arc::new(provider)), Err(e) => e, }; Err(Error::NoAuthMethod( Box::new(gcloud_error), Box::new(default_service_error), Box::new(default_user_error), )) ``` -------------------------------- ### Fetch Access Token using GCloudAuthorizedUser Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-gcloud-authorized-user.md Fetches a valid access token using the GCloudAuthorizedUser provider. The scopes parameter is accepted but ignored, as the gcloud CLI determines the token's scopes. This example demonstrates fetching a token and printing it. ```rust use gcp_auth::{GCloudAuthorizedUser, TokenProvider}; #[tokio::main] async fn main() -> Result<(), Box> { let gcloud = GCloudAuthorizedUser::new().await?; let token = gcloud.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; println!("Token from gcloud acquired"); Ok(()) } ``` -------------------------------- ### Get Default Authentication Provider Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md Automatically discovers and initializes an authentication provider. Use this function when you need a default provider without specifying particular credentials. ```Rust pub async fn provider() -> Result, Error> ``` ```Rust let provider = gcp_auth::provider().await?; ``` -------------------------------- ### Error Handling: Other Error Type Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Example of handling a generic 'Other' error type from the library. ```rust use gcp_auth::error::Error; match gcp_auth::find_credentials().await { Ok(_) => println!("Credentials found"), Err(Error::Other(ref msg)) => println!("An other error occurred: {}", msg), Err(e) => println!("An unexpected error occurred: {}", e), } ``` -------------------------------- ### Authenticating with Gcloud CLI Tool Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates using the gcloud CLI tool as an authentication provider. ```rust use gcp_auth::Credentials; async fn authenticate_with_gcloud_cli() -> Credentials { // This provider requires the 'gcloud' command to be available in the system's PATH. gcp_auth::find_credentials().await.expect("Failed to find credentials") } ``` -------------------------------- ### Retry with Backoff Pattern Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/errors.md Implement a retry mechanism with exponential backoff for transient errors when fetching tokens. This example retries up to 3 times. ```rust use std::time::Duration; use tokio::time::sleep; let mut retries = 0; loop { match provider.token(scopes).await { Ok(token) => break token, Err(e) if retries < 3 => { eprintln!("Token fetch failed: {}; retrying...", e); retries += 1; sleep(Duration::from_millis(100 * 2u64.pow(retries))).await; } Err(e) => return Err(e), } } ``` -------------------------------- ### Initialize GCP Authentication Provider Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-provider.md Finds and initializes a token provider using the first available authentication method. Attempts methods in a specific priority order, returning the first successful one or an error if all fail. ```rust pub async fn provider() -> Result, Error> ``` ```rust use gcp_auth::TokenProvider; #[tokio::main] async fn main() -> Result<(), Box> { let provider = gcp_auth::provider().await?; let scopes = &["https://www.googleapis.com/auth/cloud-platform"]; let token = provider.token(scopes).await?; println!("Token: {}", token.as_str()); Ok(()) } ``` -------------------------------- ### Using Gcloud Application Default Credentials Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Shows how to authenticate using gcloud's application default credentials. ```rust use gcp_auth::Credentials; async fn authenticate_with_gcloud_adc() -> Credentials { // This will automatically look for the ADC file at standard locations. gcp_auth::find_credentials().await.expect("Failed to find credentials") } ``` -------------------------------- ### ServiceAccountKey::from_file() Constructor Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/types.md Reads service account credentials from a JSON file. ```rust pub(crate) fn from_file(path: impl AsRef) -> Result ``` -------------------------------- ### CustomServiceAccount from File Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md Loads service account credentials from a JSON file and configures an audience. Use this when you have explicit service account key files. ```rust use gcp_auth::{CustomServiceAccount, TokenProvider}; let account = CustomServiceAccount::from_file("service-account.json")? .with_subject("user@example.com".to_string()); let token = account.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; ``` -------------------------------- ### Get Signer from Custom Service Account Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-custom-service-account.md Retrieve the RSA PKCS1 SHA256 signer from a `CustomServiceAccount` instance. This signer can then be used to sign arbitrary data. ```rust let account = CustomServiceAccount::from_file("service-account.json")?; let signer = account.signer(); // Use signer to sign arbitrary data let signature = signer.sign(b"data to sign")?; println!("Signature created: {} bytes", signature.len()); ``` -------------------------------- ### Token Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/types.md Represents an OAuth 2.0 access token with expiration information. It provides methods to get the token string, expiration time, and check its validity. ```APIDOC ## Type: Token Represents an OAuth 2.0 access token with expiration information. ### Fields - **access_token** (`String`) - Yes - The actual token string to use as a bearer token in HTTP requests. Not displayed in Debug output for security. - **expires_at** (`DateTime`) - Yes - The UTC time when the token expires. Tokens are considered expired 20 seconds before this time to provide safety margin. ### Constructor: Token::from_string() Creates a Token from a token string and duration. #### Parameters - **access_token** (`String`) - The token string to use. - **expires_in** (`Duration`) - How long until the token expires (e.g., `Duration::from_secs(3600)`). #### Example ```rust use std::time::Duration; use gcp_auth::Token; let token = Token::from_string( "ya29.a0AfH6SMBx...".to_string(), Duration::from_secs(3600), ); ``` ### Method: Token::as_str() Returns the token as a string suitable for use in an HTTP Authorization header. #### Return Type - `&str` - The access token string. #### Example ```rust let token = provider.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; let auth_header = format!("Bearer {}", token.as_str()); ``` ### Method: Token::expires_at() Returns the expiration time of the token. #### Return Type - `DateTime` - The UTC time when the token expires. #### Example ```rust let token = provider.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; let expires = token.expires_at(); println!("Token expires at: {}", expires); ``` ### Method: Token::has_expired() Checks if the token has expired, with a 20-second safety margin. #### Return Type - `bool` - `true` if the token has expired (or will expire within 20 seconds); `false` otherwise. #### Expiration Margin A 20-second safety margin is applied to ensure tokens are not used right before expiration. #### Example ```rust let token = provider.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; if !token.has_expired() { println!("Token is still valid"); } ``` ``` -------------------------------- ### Correct Crate Import Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md Demonstrates the correct way to import types from the gcp-auth crate at the crate root. ```rust // Correct use gcp_auth::CustomServiceAccount; // Not necessary (but equivalent) use gcp_auth::custom_service_account::CustomServiceAccount; ``` -------------------------------- ### Retrieve Token and Project ID with GCloudAuthorizedUser Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-gcloud-authorized-user.md Demonstrates fetching an access token and retrieving the project ID using GCloudAuthorizedUser. It shows how to obtain a token, use it, and how subsequent calls to token() may return a cached value. ```rust let gcloud = GCloudAuthorizedUser::new().await?; // First call invokes gcloud to fetch a token let token1 = gcloud.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; // Immediate second call returns cached token let token2 = gcloud.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; // Scope parameter is accepted but does not affect the returned token let token3 = gcloud.token(&["https://www.googleapis.com/auth/compute"]).await?; println!("Bearer: {}", token1.as_str()); ``` -------------------------------- ### Authenticate with Gcloud CLI Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/authentication-discovery.md Commands to authenticate the gcloud CLI, which can then be used by the gcloud CLI tool provider. This is useful for local or containerized development where gcloud is installed. ```bash gcloud auth login # or gcloud auth application-default login ``` -------------------------------- ### ServiceAccountKey::from_env() Constructor Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/types.md Reads service account credentials from the path specified in the GOOGLE_APPLICATION_CREDENTIALS environment variable. ```rust pub(crate) fn from_env() -> Result, Error> ``` -------------------------------- ### Obtain and Use Default Credentials in Rust Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-config-default-credentials.md This snippet shows how to instantiate `ConfigDefaultCredentials`, retrieve the project ID, and print it. It requires an asynchronous context. ```rust let credentials = ConfigDefaultCredentials::new().await?; let project_id = credentials.project_id().await?; println!("Project: {}", project_id); ``` -------------------------------- ### Gcloud Application Default Credentials JSON Format Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/configuration.md Example JSON structure for gcloud application default credentials. Required fields include client_id, client_secret, and refresh_token. ```json { "client_id": "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com", "client_secret": "d-FL95Q19q7MQmFpd7hHD0Ty", "quota_project_id": "my-project", "refresh_token": "1/Tl6awhpFjkMkSJoj754ERF2xQTDCiUmpz8...", "type": "authorized_user" } ``` -------------------------------- ### Check GOOGLE_APPLICATION_CREDENTIALS Environment Variable Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/authentication-discovery.md Attempts to load credentials from the file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable. Requires the file to be readable and contain valid JSON with client email, private key, and token URI. ```rust if let Some(provider) = CustomServiceAccount::from_env()? { return Ok(Arc::new(provider)); } ``` -------------------------------- ### Get GCP Authentication Provider Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/authentication-discovery.md This Rust code snippet demonstrates how to obtain the GCP authentication provider. It's used across different development and deployment contexts. ```rust let provider = gcp_auth::provider().await?; ``` -------------------------------- ### Builder Pattern for Custom Service Account Configuration Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates using the builder pattern to configure a service account credential. ```rust use gcp_auth::service_account::CustomServiceAccount; let credential = CustomServiceAccount::builder() .json_key_path("path/to/your/key.json") .build(); // Use the credential for authentication ``` -------------------------------- ### User Impersonation with with_subject() Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Demonstrates how to perform domain-wide delegation by impersonating a user with `with_subject()`. ```rust use gcp_auth::Credentials; async fn impersonate_user() -> Credentials { let mut credentials = gcp_auth::find_credentials().await.expect("Failed to find credentials"); // Impersonate a specific user account for domain-wide delegation. credentials.with_subject("user:test-user@example.com") } ``` -------------------------------- ### Get Project ID from MetadataServiceAccount Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-metadata-service-account.md Retrieves the GCP project ID of the compute instance using the MetadataServiceAccount provider. This requires the code to be running on a GCP compute instance. ```rust let metadata = MetadataServiceAccount::new().await?; let project_id = metadata.project_id().await?; println!("Instance project: {}", project_id); ``` -------------------------------- ### Get Project ID using gcloud CLI Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-gcloud-authorized-user.md Retrieves the default project ID configured in gcloud using `gcloud config get-value project`. If the command fails, it is silently ignored. ```bash gcloud config get-value project ``` -------------------------------- ### Get Project ID with GCloudAuthorizedUser Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-gcloud-authorized-user.md Retrieves the default project ID configured in gcloud. The project ID is cached after the first call to `new()` and remains constant for the instance's lifetime. ```rust let gcloud = GCloudAuthorizedUser::new().await?; match gcloud.project_id().await { Ok(project_id) => println!("Project: {}", project_id), Err(_) => println!("No default project configured in gcloud"), } ``` -------------------------------- ### All-Inclusive Import Pattern Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md This pattern imports all commonly used types from the `gcp_auth` crate for comprehensive access. It includes various provider types, traits, and utility types. ```rust use gcp_auth::{ CustomServiceAccount, ConfigDefaultCredentials, MetadataServiceAccount, GCloudAuthorizedUser, TokenProvider, Token, Signer, Error, provider, }; ``` -------------------------------- ### Load Credentials from File Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-custom-service-account.md Use `from_file` to load service account credentials from a specified JSON file path. This method returns a `CustomServiceAccount` instance or an `Error` if the file cannot be read, is not valid JSON, or contains an invalid private key. The path must point to a valid service account JSON key file. ```rust use std::path::PathBuf; use gcp_auth::{CustomServiceAccount, TokenProvider}; let credentials_path = PathBuf::from("./service-account.json"); let account = CustomServiceAccount::from_file(credentials_path)?; let token = account.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; println!("Authenticated with service account from file"); ``` -------------------------------- ### CustomServiceAccount::from_file() Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-custom-service-account.md Creates a `CustomServiceAccount` instance from a JSON key file. This is the primary way to load service account credentials. ```APIDOC ## Method: CustomServiceAccount::from_file() ### Description Loads service account credentials from a JSON key file. ### Parameters #### Path Parameters - **file_path** (string) - Required - The path to the service account JSON key file. ### Example ```rust use gcp_auth::CustomServiceAccount; let account = CustomServiceAccount::from_file("service-account.json")?; ``` ``` -------------------------------- ### Set GOOGLE_APPLICATION_CREDENTIALS Environment Variable Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/configuration.md Specifies the path to a JSON file containing service account credentials. This is checked first in the authentication provider discovery sequence. ```bash export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json ``` -------------------------------- ### Get Private Key PEM from Custom Service Account Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-custom-service-account.md Retrieve the PEM-encoded RSA private key from the service account credentials using the `private_key_pem` method. The key is returned as a string slice. ```rust let account = CustomServiceAccount::from_file("service-account.json")?; let key = account.private_key_pem(); println!("Key length: {} characters", key.len()); ``` -------------------------------- ### Get Project ID from Custom Service Account Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-custom-service-account.md Access the project ID stored within the service account credentials using the `project_id` method. Returns `None` if the project ID is not specified in the credentials. ```rust let account = CustomServiceAccount::from_file("service-account.json")?; match account.project_id() { Some(pid) => println!("Project: {}", pid), None => println!("No project ID in credentials"), } ``` -------------------------------- ### User Impersonation with Custom Service Account Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/00_START_HERE.md This scenario demonstrates how to use a custom service account file to impersonate a specific user. It shows creating a `CustomServiceAccount` instance, setting the subject, and obtaining a token for a specific scope. ```rust let account = CustomServiceAccount::from_file("service-account.json")? .with_subject("user@example.com".to_string()); let token = account.token(&["https://www.googleapis.com/auth/drive"]).await?; ``` -------------------------------- ### Load Credentials from Environment Variable Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-custom-service-account.md Use `from_env` to load service account credentials from the GOOGLE_APPLICATION_CREDENTIALS environment variable. This method returns `Some(CustomServiceAccount)` if the variable is set and credentials are valid, `None` if the variable is not set, or an `Err` if credentials are invalid. Ensure the environment variable points to a valid JSON file. ```rust use gcp_auth::{CustomServiceAccount, TokenProvider}; match CustomServiceAccount::from_env()? { Some(account) => { let token = account.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; println!("Token acquired from env credentials"); } None => println!("GOOGLE_APPLICATION_CREDENTIALS not set"), } ``` -------------------------------- ### Provider Discovery Mechanism Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates the prioritized sequence for discovering GCP authentication providers. ```rust use gcp_auth::Credentials; async fn get_gcp_credentials() -> Credentials { // The library automatically tries providers in a prioritized order: // 1. Explicit service account JSON file // 2. Gcloud application default credentials file // 3. GCP instance metadata server // 4. Gcloud CLI tool gcp_auth::find_credentials().await.expect("Failed to find credentials") } ``` -------------------------------- ### Retrieve Service Account Token Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-metadata-service-account.md Use this endpoint to get an access token for the default service account. Ensure the 'Metadata-Flavor: Google' header is included. The response contains the access token, its expiration time, and type. ```http GET http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token Header: Metadata-Flavor: Google ``` ```json { "access_token": "...", "expires_in": 3599, "token_type": "Bearer" } ``` -------------------------------- ### Get GCP Auth Provider and Token Source: https://github.com/djc/gcp_auth/blob/main/README.md Selects the appropriate token provider based on available credentials and retrieves a bearer token for specified scopes. Ensure the necessary environment variables or configuration files are set up. ```rust let provider = gcp_auth::provider().await?; let scopes = &["https://www.googleapis.com/auth/cloud-platform"]; let token = provider.token(scopes).await?; ``` -------------------------------- ### gcp_auth::provider() Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-provider.md Finds and initializes a token provider using the first available authentication method. It attempts several methods in a specific order and returns the first one that succeeds. ```APIDOC ## Function: provider() Finds and initializes a token provider using the first available authentication method. ### Description Attempts authentication methods in the following priority order: 1. Check `GOOGLE_APPLICATION_CREDENTIALS` environment variable for a path to a JSON service account file 2. Look for credentials in `.config/gcloud/application_default_credentials.json` (Unix/macOS) or `%APPDATA%/gcloud/application_default_credentials.json` (Windows) 3. Query the GCP instance metadata server for a token (available when running on GCP compute instances) 4. Execute `gcloud auth print-access-token` command if the gcloud CLI tool is available on the PATH Returns the first authentication method that succeeds. If all methods fail, returns a `NoAuthMethod` error containing the failures from all attempted providers. ### Return Type | Field | Type | Description | |-------|------|-------------| | — | `Arc` | An authentication provider implementing the `TokenProvider` trait. Can be one of: `CustomServiceAccount`, `ConfigDefaultCredentials`, `MetadataServiceAccount`, or `GCloudAuthorizedUser`. | ### Errors | Error Type | Condition | |-----------|-----------| | `Error::NoAuthMethod(Box, Box, Box)` | No authentication method was available. Contains nested errors from gcloud, metadata server, and default user attempts respectively. | ### Example ```rust use gcp_auth::TokenProvider; #[tokio::main] async fn main() -> Result<(), Box> { let provider = gcp_auth::provider().await?; let scopes = &["https://www.googleapis.com/auth/cloud-platform"]; let token = provider.token(scopes).await?; println!("Token: {}", token.as_str()); Ok(()) } ``` ``` -------------------------------- ### Configure gcp_auth with webpki root certificates Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md Use this configuration to enable webpki root certificates for TLS operations. ```rust gcp_auth = { version = "0.12", features = ["webpki-roots"], default-features = false } ``` -------------------------------- ### Explicit Provider Import Pattern Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md This pattern shows how to instantiate a specific provider, `CustomServiceAccount`, directly from a file. It imports `CustomServiceAccount` and `TokenProvider`. ```rust use gcp_auth::{CustomServiceAccount, TokenProvider}; let account = CustomServiceAccount::from_file("service-account.json")?; ``` -------------------------------- ### Attempt to Load MetadataServiceAccount Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/authentication-discovery.md Attempts to retrieve credentials from the GCP instance metadata server. This is only applicable when running on GCP compute instances. ```rust let default_service_error = match MetadataServiceAccount::with_client(&client).await { Ok(provider) => return Ok(Arc::new(provider)), Err(e) => e, }; ``` -------------------------------- ### Gcloud CLI Command Reference (Windows) Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Reference to the gcloud CLI command on Windows systems. ```text gcloud.cmd ``` -------------------------------- ### MetadataServiceAccount::new() Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-metadata-service-account.md Creates a new MetadataServiceAccount instance by contacting the GCP instance metadata server. This method is used to initialize the provider and fetch an initial token and project ID. ```APIDOC ## Function: MetadataServiceAccount::new() ### Description Creates a new instance by contacting the GCP instance metadata server. ### Signature ```rust pub async fn new() -> Result ``` ### Return Type - `Result`: A configured `MetadataServiceAccount` instance with an initial token already fetched and project ID retrieved. ### Errors - `Error::Http("HTTP request failed", ...)`: Connection attempt to the metadata server failed or timed out. - `Error::Str("empty project ID from GCP instance metadata server")`: The metadata server returned an empty string for the project ID. - `Error::Str("received invalid UTF-8 project ID from GCP instance metadata server")`: The project ID from the metadata server is not valid UTF-8. - `Error::Json("failed to deserialize token from response", ...)`: The token response from the metadata server is not valid JSON. ### Example ```rust use gcp_auth::{MetadataServiceAccount, TokenProvider}; #[tokio::main] async fn main() -> Result<(), Box> { // This will only work when running on a GCP compute instance let metadata = MetadataServiceAccount::new().await?; let token = metadata.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; println!("Token from metadata server acquired"); Ok(()) } ``` ``` -------------------------------- ### MetadataServiceAccount Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md Creates a provider that queries the GCP instance metadata server for credentials. Use this when running on GCP compute instances. ```rust use gcp_auth::{MetadataServiceAccount, TokenProvider}; let metadata = MetadataServiceAccount::new().await?; let token = metadata.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; ``` -------------------------------- ### Login with Gcloud CLI Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/configuration.md Authenticates the gcloud CLI for local development. This command initiates a browser-based login flow. ```bash gcloud auth login ``` -------------------------------- ### Fetch Access Token using gcloud CLI Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-gcloud-authorized-user.md Fetches an access token using the `gcloud auth print-access-token` command. This command requires the user to be authenticated with gcloud. ```bash gcloud auth print-access-token --quiet ``` -------------------------------- ### Explicit Service Account Token Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/index.md Load credentials from a service account JSON file and obtain a token. Ensure the file path is correct. ```rust use gcp_auth::{CustomServiceAccount, TokenProvider}; let account = CustomServiceAccount::from_file("service-account.json")?; let token = account.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; ``` -------------------------------- ### Obtain Token in Development Environment Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/configuration.md Obtains an access token using the gcp_auth crate in a development environment. It automatically discovers credentials from the environment. ```rust use gcp_auth::TokenProvider; #[tokio::main] async fn main() -> Result<(), Box> { // Automatically discovers credentials from environment let provider = gcp_auth::provider().await?; let token = provider.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; println!("Token: {}", token.as_str()); Ok(()) } ``` -------------------------------- ### ConfigDefaultCredentials::new() Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/api-reference-config-default-credentials.md Creates a new instance of ConfigDefaultCredentials by reading user credentials from the default configuration location. This is the standard method for authenticating during local development. ```APIDOC ## Function: ConfigDefaultCredentials::new() ### Description Creates a new instance by reading user credentials from the default configuration location. This is the standard method for authenticating during local development when using `gcloud auth application-default login`. ### Return Type - `Result`: A configured `ConfigDefaultCredentials` instance with an initial token already fetched. ### Configuration Locations - Unix/macOS: `~/.config/gcloud/application_default_credentials.json` - Windows: `%APPDATA%/gcloud/application_default_credentials.json` ### Errors - `Error::Str("home directory not found")`: Unable to locate the user's home directory (Unix/macOS only). - `Error::Str("APPDATA environment variable not found")`: The APPDATA environment variable is not set (Windows only). - `Error::Str("APPDATA directory not found")`: The APPDATA directory does not exist (Windows only). - `Error::Io("failed to open application credentials file", ...)`: The credentials file does not exist or cannot be read. - `Error::Json("failed to deserialize ApplicationCredentials", ...)`: The credentials file is not valid JSON or lacks required fields. - `Error::Http(...)`: Network error while fetching the initial token from Google's token endpoint. ### Example ```rust use gcp_auth::{ConfigDefaultCredentials, TokenProvider}; #[tokio::main] async fn main() -> Result<(), Box> { let credentials = ConfigDefaultCredentials::new().await?; let token = credentials.token(&["https://www.googleapis.com/auth/drive"]).await?; println!("Using gcloud default credentials"); Ok(()) } ``` ``` -------------------------------- ### Gcloud CLI Command Reference Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Reference to the gcloud CLI command, used for authentication and other GCP operations. ```text gcloud ``` -------------------------------- ### Discovery Only Import Pattern Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md This pattern is used when you only need to discover credentials and obtain a provider. It imports the `provider` function. ```rust use gcp_auth::provider; let provider = provider().await?; ``` -------------------------------- ### Error Handling: NoAuthMethod Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Illustrates the NoAuthMethod error, which occurs when no authentication method can be determined. ```rust use gcp_auth::error::Error; match gcp_auth::find_credentials().await { Ok(_) => println!("Credentials found"), Err(Error::NoAuthMethod) => println!("No authentication method could be determined."), Err(e) => println!("An unexpected error occurred: {}", e), } ``` -------------------------------- ### GCP Authentication Provider Discovery Order Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/00_START_HERE.md Lists the order in which the `provider()` function discovers authentication methods. These methods implement the `TokenProvider` trait. ```text provider() discovers: 1. CustomServiceAccount (explicit credentials) 2. ConfigDefaultCredentials (gcloud config) 3. MetadataServiceAccount (GCP metadata server) 4. GCloudAuthorizedUser (gcloud CLI) ``` -------------------------------- ### Login for Gcloud Application Default Credentials Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/authentication-discovery.md Command to authenticate the gcloud CLI and set up Application Default Credentials. This is commonly used for local development. ```bash gcloud auth application-default login ``` -------------------------------- ### ConfigDefaultCredentials Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/module-exports.md Initializes credentials using gcloud application default credentials. This is suitable for local development or environments where gcloud is configured. ```rust use gcp_auth::{ConfigDefaultCredentials, TokenProvider}; let creds = ConfigDefaultCredentials::new().await?; let token = creds.token(&["https://www.googleapis.com/auth/cloud-platform"]).await?; ``` -------------------------------- ### ConfigDefaultCredentials Source: https://github.com/djc/gcp_auth/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Loads credentials using the default configuration, typically from gcloud or environment variables. ```APIDOC ## ConfigDefaultCredentials ### Description Represents credentials loaded from the default configuration, such as gcloud application default credentials. ### Constructor #### new() Creates a new `ConfigDefaultCredentials` instance. - **Signature**: `fn new() -> Result` ```