Package cloud.google.com/go/auth/credentials/impersonate (v0.13.0)

Package impersonate is used to impersonate Google Credentials. If you need to impersonate some credentials to use with a client library see NewCredentials. If instead you would like to create an Open Connect ID token using impersonation see NewIDTokenCredentials.

Required IAM roles

In order to impersonate a service account the base service account must have the Service Account Token Creator role, roles/iam.serviceAccountTokenCreator, on the service account being impersonated. See https://cloud.google.com/iam/docs/understanding-service-accounts.

Optionally, delegates can be used during impersonation if the base service account lacks the token creator role on the target. When using delegates, each service account must be granted roles/iam.serviceAccountTokenCreator on the next service account in the delgation chain.

For example, if a base service account of SA1 is trying to impersonate target service account SA2 while using delegate service accounts DSA1 and DSA2, the following must be true:

  1. Base service account SA1 has roles/iam.serviceAccountTokenCreator on DSA1.
  2. DSA1 has roles/iam.serviceAccountTokenCreator on DSA2.
  3. DSA2 has roles/iam.serviceAccountTokenCreator on target SA2.

If the base credential is an authorized user and not a service account, or if the option WithQuotaProject is set, the target service account must have a role that grants the serviceusage.services.use permission such as roles/serviceusage.serviceUsageConsumer.

Functions

func NewCredentials

func NewCredentials(opts *CredentialsOptions) (*auth.Credentials, error)

NewCredentials returns an impersonated [cloud.google.com/go/auth/NewCredentials] configured with the provided options and using credentials loaded from Application Default Credentials as the base credentials if not provided with the opts.

Examples

adminUser
package main

import (
	"log"

	"cloud.google.com/go/auth/credentials/impersonate"
)

func main() {
	// Base credentials sourced from ADC or provided client options
	creds, err := impersonate.NewCredentials(&impersonate.CredentialsOptions{
		TargetPrincipal: "foo@project-id.iam.gserviceaccount.com",
		Scopes:          []string{"https://www.googleapis.com/auth/cloud-platform"},
		// Optionally supply delegates
		Delegates: []string{"bar@project-id.iam.gserviceaccount.com"},
		// Specify user to impersonate
		Subject: "admin@example.com",
	})
	if err != nil {
		log.Fatal(err)
	}

	// Use this Credentials with a client library like
	// "google.golang.org/api/admin/directory/v1"
	_ = creds
}
serviceAccount
package main

import (
	"log"

	"cloud.google.com/go/auth/credentials/impersonate"
)

func main() {
	// Base credentials sourced from ADC or provided client options
	creds, err := impersonate.NewCredentials(&impersonate.CredentialsOptions{
		TargetPrincipal: "foo@project-id.iam.gserviceaccount.com",
		Scopes:          []string{"https://www.googleapis.com/auth/cloud-platform"},
		// Optionally supply delegates
		Delegates: []string{"bar@project-id.iam.gserviceaccount.com"},
	})
	if err != nil {
		log.Fatal(err)
	}

	// TODO(codyoss): link to option once it exists.

	// Use this Credentials with a client library
	_ = creds
}

func NewIDTokenCredentials

func NewIDTokenCredentials(opts *IDTokenOptions) (*auth.Credentials, error)

NewIDTokenCredentials creates an impersonated [cloud.google.com/go/auth/Credentials] that returns ID tokens configured with the provided config and using credentials loaded from Application Default Credentials as the base credentials if not provided with the opts. The tokens produced are valid for one hour and are automatically refreshed.

Example

package main

import (
	"log"

	"cloud.google.com/go/auth/credentials/impersonate"
	"cloud.google.com/go/auth/httptransport"
)

func main() {
	// Base credentials sourced from ADC or provided client options.
	creds, err := impersonate.NewIDTokenCredentials(&impersonate.IDTokenOptions{
		Audience:        "http://example.com/",
		TargetPrincipal: "foo@project-id.iam.gserviceaccount.com",
		IncludeEmail:    true,
		// Optionally supply delegates.
		Delegates: []string{"bar@project-id.iam.gserviceaccount.com"},
	})
	if err != nil {
		log.Fatal(err)
	}

	// Create an authenticated client
	client, err := httptransport.NewClient(&httptransport.Options{
		Credentials: creds,
	})
	if err != nil {
		log.Fatal(err)
	}

	// Use your client that is authenticated with impersonated credentials to
	// make requests.
	client.Get("http://example.com/")
}

CredentialsOptions

type CredentialsOptions struct {
	// TargetPrincipal is the email address of the service account to
	// impersonate. Required.
	TargetPrincipal string
	// Scopes that the impersonated credential should have. Required.
	Scopes []string
	// Delegates are the service account email addresses in a delegation chain.
	// Each service account must be granted roles/iam.serviceAccountTokenCreator
	// on the next service account in the chain. Optional.
	Delegates []string
	// Lifetime is the amount of time until the impersonated token expires. If
	// unset the token's lifetime will be one hour and be automatically
	// refreshed. If set the token may have a max lifetime of one hour and will
	// not be refreshed. Service accounts that have been added to an org policy
	// with constraints/iam.allowServiceAccountCredentialLifetimeExtension may
	// request a token lifetime of up to 12 hours. Optional.
	Lifetime time.Duration
	// Subject is the sub field of a JWT. This field should only be set if you
	// wish to impersonate as a user. This feature is useful when using domain
	// wide delegation. Optional.
	Subject string

	// Credentials used in generating the impersonated token. If empty, an
	// attempt will be made to detect credentials from the environment (see
	// [cloud.google.com/go/auth/credentials.DetectDefault]). Optional.
	Credentials *auth.Credentials
	// Client configures the underlying client used to make network requests
	// when fetching tokens. If provided this should be a fully-authenticated
	// client. Optional.
	Client *http.Client
	// UniverseDomain is the default service domain for a given Cloud universe.
	// This field has no default value, and only if provided will it be used to
	// verify the universe domain from the credentials. Optional.
	UniverseDomain string
	// Logger is used for debug logging. If provided, logging will be enabled
	// at the loggers configured level. By default logging is disabled unless
	// enabled by setting GOOGLE_SDK_GO_LOGGING_LEVEL in which case a default
	// logger will be used. Optional.
	Logger *slog.Logger
}

CredentialsOptions for generating an impersonated credential token.

IDTokenOptions

type IDTokenOptions struct {
	// Audience is the `aud` field for the token, such as an API endpoint the
	// token will grant access to. Required.
	Audience string
	// TargetPrincipal is the email address of the service account to
	// impersonate. Required.
	TargetPrincipal string
	// IncludeEmail includes the target service account's email in the token.
	// The resulting token will include both an `email` and `email_verified`
	// claim. Optional.
	IncludeEmail bool
	// Delegates are the ordered service account email addresses in a delegation
	// chain. Each service account must be granted
	// roles/iam.serviceAccountTokenCreator on the next service account in the
	// chain. Optional.
	Delegates []string

	// Credentials used in generating the impersonated ID token. If empty, an
	// attempt will be made to detect credentials from the environment (see
	// [cloud.google.com/go/auth/credentials.DetectDefault]). Optional.
	Credentials *auth.Credentials
	// Client configures the underlying client used to make network requests
	// when fetching tokens. If provided this should be a fully-authenticated
	// client. Optional.
	Client *http.Client
	// Logger is used for debug logging. If provided, logging will be enabled
	// at the loggers configured level. By default logging is disabled unless
	// enabled by setting GOOGLE_SDK_GO_LOGGING_LEVEL in which case a default
	// logger will be used. Optional.
	Logger *slog.Logger
}

IDTokenOptions for generating an impersonated ID token.