func credentialsOpt()

in internal/proxy/proxy.go [262:329]


func credentialsOpt(c Config, l alloydb.Logger) (alloydbconn.Option, error) {
	// If service account impersonation is configured, set up an impersonated
	// credentials token source.
	if c.ImpersonationChain != "" {
		var iopts []option.ClientOption
		switch {
		case c.Token != "":
			l.Infof("Impersonating service account with OAuth2 token")
			iopts = append(iopts, option.WithTokenSource(
				oauth2.StaticTokenSource(&oauth2.Token{AccessToken: c.Token}),
			))
		case c.CredentialsFile != "":
			l.Infof("Impersonating service account with the credentials file at %q", c.CredentialsFile)
			iopts = append(iopts, option.WithCredentialsFile(c.CredentialsFile))
		case c.CredentialsJSON != "":
			l.Infof("Impersonating service account with JSON credentials environment variable")
			iopts = append(iopts, option.WithCredentialsJSON([]byte(c.CredentialsJSON)))
		case c.GcloudAuth:
			l.Infof("Impersonating service account with gcloud user credentials")
			ts, err := gcloud.TokenSource()
			if err != nil {
				return nil, err
			}
			iopts = append(iopts, option.WithTokenSource(ts))
		default:
			l.Infof("Impersonating service account with Application Default Credentials")
		}
		target, delegates := parseImpersonationChain(c.ImpersonationChain)
		ts, err := impersonate.CredentialsTokenSource(
			context.Background(),
			impersonate.CredentialsConfig{
				TargetPrincipal: target,
				Delegates:       delegates,
				Scopes:          []string{"https://www.googleapis.com/auth/cloud-platform"},
			},
			iopts...,
		)
		if err != nil {
			return nil, err
		}
		return alloydbconn.WithTokenSource(ts), nil
	}
	// Otherwise, configure credentials as usual.
	switch {
	case c.Token != "":
		l.Infof("Authorizing with OAuth2 token")
		return alloydbconn.WithTokenSource(
			oauth2.StaticTokenSource(&oauth2.Token{AccessToken: c.Token}),
		), nil
	case c.CredentialsFile != "":
		l.Infof("Authorizing with the credentials file at %q", c.CredentialsFile)
		return alloydbconn.WithCredentialsFile(c.CredentialsFile), nil
	case c.CredentialsJSON != "":
		l.Infof("Authorizing with JSON credentials environment variable")
		return alloydbconn.WithCredentialsJSON([]byte(c.CredentialsJSON)), nil
	case c.GcloudAuth:
		l.Infof("Authorizing with gcloud user credentials")
		ts, err := gcloud.TokenSource()
		if err != nil {
			return nil, err
		}
		return alloydbconn.WithTokenSource(ts), nil
	default:
		l.Infof("Authorizing with Application Default Credentials")
		// Return no-op options to avoid having to handle nil in caller code
		return alloydbconn.WithOptions(), nil
	}
}