detect

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 11, 2024 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package detect provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs. It supports the Web server flow, client-side credentials, service accounts, Google Compute Engine service accounts, Google App Engine service accounts and workload identity federation from non-Google cloud platforms.

A brief overview of the package follows. For more information, please read https://developers.google.com/accounts/docs/OAuth2 and https://developers.google.com/accounts/docs/application-default-credentials. For more information on using workload identity federation, refer to https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation.

Workforce Identity Federation

Workforce identity federation lets you use an external identity provider (IdP) to authenticate and authorize a workforce—a group of users, such as employees, partners, and contractors—using IAM, so that the users can access Google Cloud services. Workforce identity federation extends Google Cloud's identity capabilities to support syncless, attribute-based single sign on.

With workforce identity federation, your workforce can access Google Cloud resources using an external identity provider (IdP) that supports OpenID Connect (OIDC) or SAML 2.0 such as Azure Active Directory (Azure AD), Active Directory Federation Services (AD FS), Okta, and others.

Follow the detailed instructions on how to configure Workload Identity Federation in various platforms:

For workforce identity federation, the library can retrieve tokens in three ways: from a local file location (file-sourced credentials), from a server (URL-sourced credentials), or from a local executable (executable-sourced credentials). For file-sourced credentials, a background process needs to be continuously refreshing the file location with a new OIDC/SAML token prior to expiration. For tokens with one hour lifetimes, the token needs to be updated in the file every hour. The token can be stored directly as plain text or in JSON format. For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC/SAML token. The response can be in plain text or JSON. Additional required request headers can also be specified. For executable-sourced credentials, an application needs to be available to output the OIDC/SAML token and other information in a JSON format. For more information on how these work (and how to implement executable-sourced credentials), please check out: https://cloud.google.com/iam/docs/workforce-obtaining-short-lived-credentials#generate_a_configuration_file_for_non-interactive_sign-in

Security considerations

Note that this library does not perform any validation on the token_url, token_info_url, or service_account_impersonation_url fields of the credential configuration. It is not recommended to use a credential configuration that you did not generate with the gcloud CLI unless you verify that the URL fields point to a googleapis.com domain.

Credentials

The Credentials type represents Google credentials, including Application Default Credentials.

Use DefaultCredentials to obtain Application Default Credentials.

Application Default Credentials support workload identity federation to access Google Cloud resources from non-Google Cloud platforms including Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). Workload identity federation is recommended for non-Google Cloud environments as it avoids the need to download, manage, and store service account private keys locally.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func OnGCE

func OnGCE() bool

OnGCE reports whether this process is running in Google Cloud.

Types

type Credentials

type Credentials struct {
	auth.TokenProvider
	// contains filtered or unexported fields
}

Credentials holds Google credentials, including [Application Default Credentials](https://developers.google.com/accounts/docs/application-default-credentials).

func DefaultCredentials

func DefaultCredentials(opts *Options) (*Credentials, error)

DefaultCredentials searches for "Application Default Credentials" and returns a credential based on the Options provided.

It looks for credentials in the following places, preferring the first location found:

  • A JSON file whose path is specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable. For workload identity federation, refer to https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation on how to generate the JSON configuration file for on-prem/non-Google cloud platforms.
  • A JSON file in a location known to the gcloud command-line tool. On Windows, this is %APPDATA%/gcloud/application_default_credentials.json. On other systems, $HOME/.config/gcloud/application_default_credentials.json.
  • On Google Compute Engine, Google App Engine standard second generation runtimes, and Google App Engine flexible environment, it fetches credentials from the metadata server.
Example
package main

import (
	"log"

	"cloud.google.com/go/auth/detect"
	"cloud.google.com/go/auth/httptransport"
)

func main() {
	creds, err := detect.DefaultCredentials(&detect.Options{
		Scopes: []string{"https://www.googleapis.com/auth/devstorage.full_control"},
	})
	if err != nil {
		log.Fatal(err)
	}
	client, err := httptransport.NewClient(&httptransport.Options{
		TokenProvider: creds,
	})
	if err != nil {
		log.Fatal(err)
	}
	client.Get("...")
}
Output:

Example (WithFilepath)
package main

import (
	"log"

	"cloud.google.com/go/auth/detect"
	"cloud.google.com/go/auth/httptransport"
)

func main() {
	// Your credentials should be obtained from the Google
	// Developer Console (https://console.developers.google.com).
	// Navigate to your project, then see the "Credentials" page
	// under "APIs & Auth".
	// To create a service account client, click "Create new Client ID",
	// select "Service Account", and click "Create Client ID". A JSON
	// key file will then be downloaded to your computer.
	filepath := "/path/to/your-project-key.json"
	creds, err := detect.DefaultCredentials(&detect.Options{
		Scopes:          []string{"https://www.googleapis.com/auth/bigquery"},
		CredentialsFile: filepath,
	})
	if err != nil {
		log.Fatal(err)
	}
	client, err := httptransport.NewClient(&httptransport.Options{
		TokenProvider: creds,
	})
	if err != nil {
		log.Fatal(err)
	}
	client.Get("...")
}
Output:

Example (WithJSON)
package main

import (
	"log"
	"os"

	"cloud.google.com/go/auth/detect"
	"cloud.google.com/go/auth/httptransport"
)

func main() {
	data, err := os.ReadFile("/path/to/key-file.json")
	if err != nil {
		log.Fatal(err)
	}
	creds, err := detect.DefaultCredentials(&detect.Options{
		Scopes:          []string{"https://www.googleapis.com/auth/bigquery"},
		CredentialsJSON: data,
	})
	if err != nil {
		log.Fatal(err)
	}
	client, err := httptransport.NewClient(&httptransport.Options{
		TokenProvider: creds,
	})
	if err != nil {
		log.Fatal(err)
	}
	client.Get("...")
}
Output:

func (*Credentials) JSON

func (c *Credentials) JSON() []byte

JSON returns the bytes associated with the the file used to source credentials if one was used.

func (*Credentials) ProjectID

func (c *Credentials) ProjectID() string

ProjectID returns the associated project ID from the underlying file or environment.

func (*Credentials) QuotaProjectID

func (c *Credentials) QuotaProjectID() string

QuotaProjectID returns the associated quota project ID from the underlying file or environment.

func (*Credentials) UniverseDomain

func (c *Credentials) UniverseDomain() string

UniverseDomain returns the default service domain for a given Cloud universe. The default value is "googleapis.com".

type Options

type Options struct {
	// Scopes that credentials tokens should have. Example:
	// https://www.googleapis.com/auth/cloud-platform. Required if Audience is
	// not provided.
	Scopes []string
	// Audience that credentials tokens should have. Only applicable for 2LO
	// flows with service accounts. If specified, scopes should not be provided.
	Audience string
	// Subject is the user email used for [domain wide delegation](https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority).
	// Optional.
	Subject string
	// EarlyTokenRefresh configures how early before a token expires that it
	// should be refreshed.
	EarlyTokenRefresh time.Duration
	// AuthHandlerOptions configures an authorization handler and other options
	// for 3LO flows. It is required, and only used, for client credential
	// flows.
	AuthHandlerOptions *auth.AuthorizationHandlerOptions
	// TokenURL allows to set the token endpoint for user credential flows. If
	// unset the default value is: https://oauth2.googleapis.com/token.
	// Optional.
	TokenURL string
	// STSAudience is the audience sent to when retrieving an STS token.
	// Currently this only used for GDCH auth flow, for which it is required.
	STSAudience string
	// CredentialsFile overrides detection logic and sources a credential file
	// from the provided filepath. If provided, CredentialsJSON must not be.
	// Optional.
	CredentialsFile string
	// CredentialsJSON overrides detection logic and uses the JSON bytes as the
	// source for the credential. If provided, CredentialsFile must not be.
	// Optional.
	CredentialsJSON []byte
	// UseSelfSignedJWT directs service account based credentials to create a
	// self-signed JWT with the private key found in the file, skipping any
	// network requests that would normally be made. Optional.
	UseSelfSignedJWT bool
	// Client configures the underlying client used to make network requests
	// when fetching tokens. Optional.
	Client *http.Client
}

Options provides configuration for DefaultCredentials.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL