google: add DefaultCredentials function

This new function allows reading the project ID from a service account
JSON file without an additional disk read.

Change-Id: I1f03ca3ca39a2ae3bd6524367c17761b0f08de45
Reviewed-on: https://go-review.googlesource.com/32876
Reviewed-by: Jaana Burcu Dogan <jbd@google.com>
This commit is contained in:
Ross Light 2016-11-07 13:06:47 -08:00
parent d5040cddfc
commit f6093e37b6
5 changed files with 49 additions and 31 deletions

View File

@ -20,6 +20,9 @@ var appengineVM bool
// Set at init time by appengine_hook.go. If nil, we're not on App Engine. // Set at init time by appengine_hook.go. If nil, we're not on App Engine.
var appengineTokenFunc func(c context.Context, scopes ...string) (token string, expiry time.Time, err error) var appengineTokenFunc func(c context.Context, scopes ...string) (token string, expiry time.Time, err error)
// Set at init time by appengine_hook.go. If nil, we're not on App Engine.
var appengineAppIDFunc func(c context.Context) string
// AppEngineTokenSource returns a token source that fetches tokens // AppEngineTokenSource returns a token source that fetches tokens
// issued to the current App Engine application's service account. // issued to the current App Engine application's service account.
// If you are implementing a 3-legged OAuth 2.0 flow on App Engine // If you are implementing a 3-legged OAuth 2.0 flow on App Engine

View File

@ -10,4 +10,5 @@ import "google.golang.org/appengine"
func init() { func init() {
appengineTokenFunc = appengine.AccessToken appengineTokenFunc = appengine.AccessToken
appengineAppIDFunc = appengine.AppID
} }

View File

@ -11,4 +11,5 @@ import "google.golang.org/appengine"
func init() { func init() {
appengineVM = true appengineVM = true
appengineTokenFunc = appengine.AccessToken appengineTokenFunc = appengine.AccessToken
appengineAppIDFunc = appengine.AppID
} }

View File

@ -18,16 +18,16 @@ import (
"golang.org/x/oauth2" "golang.org/x/oauth2"
) )
// DefaultClient returns an HTTP Client that uses the // DefaultCredentials holds "Application Default Credentials".
// DefaultTokenSource to obtain authentication credentials.
//
// This client should be used when developing services
// that run on Google App Engine or Google Compute Engine
// and use "Application Default Credentials."
//
// For more details, see: // For more details, see:
// https://developers.google.com/accounts/docs/application-default-credentials // https://developers.google.com/accounts/docs/application-default-credentials
// type DefaultCredentials struct {
ProjectID string // may be empty
TokenSource oauth2.TokenSource
}
// DefaultClient returns an HTTP Client that uses the
// DefaultTokenSource to obtain authentication credentials.
func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) { func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
ts, err := DefaultTokenSource(ctx, scope...) ts, err := DefaultTokenSource(ctx, scope...)
if err != nil { if err != nil {
@ -36,8 +36,18 @@ func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
return oauth2.NewClient(ctx, ts), nil return oauth2.NewClient(ctx, ts), nil
} }
// DefaultTokenSource is a token source that uses // DefaultTokenSource returns the token source for
// "Application Default Credentials". // "Application Default Credentials".
// It is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource.
func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) {
creds, err := FindDefaultCredentials(ctx, scope...)
if err != nil {
return nil, err
}
return creds.TokenSource, nil
}
// FindDefaultCredentials searches for "Application Default Credentials".
// //
// It looks for credentials in the following places, // It looks for credentials in the following places,
// preferring the first location found: // preferring the first location found:
@ -51,45 +61,40 @@ func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
// 4. On Google Compute Engine and Google App Engine Managed VMs, it fetches // 4. On Google Compute Engine and Google App Engine Managed VMs, it fetches
// credentials from the metadata server. // credentials from the metadata server.
// (In this final case any provided scopes are ignored.) // (In this final case any provided scopes are ignored.)
// func FindDefaultCredentials(ctx context.Context, scope ...string) (*DefaultCredentials, error) {
// For more details, see:
// https://developers.google.com/accounts/docs/application-default-credentials
//
func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) {
// First, try the environment variable. // First, try the environment variable.
const envVar = "GOOGLE_APPLICATION_CREDENTIALS" const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
if filename := os.Getenv(envVar); filename != "" { if filename := os.Getenv(envVar); filename != "" {
ts, err := tokenSourceFromFile(ctx, filename, scope) creds, err := readCredentialsFile(ctx, filename, scope)
if err != nil { if err != nil {
return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err) return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err)
} }
return ts, nil return creds, nil
} }
// Second, try a well-known file. // Second, try a well-known file.
filename := wellKnownFile() filename := wellKnownFile()
_, err := os.Stat(filename) if creds, err := readCredentialsFile(ctx, filename, scope); err == nil {
if err == nil { return creds, nil
ts, err2 := tokenSourceFromFile(ctx, filename, scope) } else if !os.IsNotExist(err) {
if err2 == nil {
return ts, nil
}
err = err2
} else if os.IsNotExist(err) {
err = nil // ignore this error
}
if err != nil {
return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err) return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err)
} }
// Third, if we're on Google App Engine use those credentials. // Third, if we're on Google App Engine use those credentials.
if appengineTokenFunc != nil && !appengineVM { if appengineTokenFunc != nil && !appengineVM {
return AppEngineTokenSource(ctx, scope...), nil return &DefaultCredentials{
ProjectID: appengineAppIDFunc(ctx),
TokenSource: AppEngineTokenSource(ctx, scope...),
}, nil
} }
// Fourth, if we're on Google Compute Engine use the metadata server. // Fourth, if we're on Google Compute Engine use the metadata server.
if metadata.OnGCE() { if metadata.OnGCE() {
return ComputeTokenSource(""), nil id, _ := metadata.ProjectID()
return &DefaultCredentials{
ProjectID: id,
TokenSource: ComputeTokenSource(""),
}, nil
} }
// None are found; return helpful error. // None are found; return helpful error.
@ -105,7 +110,7 @@ func wellKnownFile() string {
return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f) return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f)
} }
func tokenSourceFromFile(ctx context.Context, filename string, scopes []string) (oauth2.TokenSource, error) { func readCredentialsFile(ctx context.Context, filename string, scopes []string) (*DefaultCredentials, error) {
b, err := ioutil.ReadFile(filename) b, err := ioutil.ReadFile(filename)
if err != nil { if err != nil {
return nil, err return nil, err
@ -114,5 +119,12 @@ func tokenSourceFromFile(ctx context.Context, filename string, scopes []string)
if err := json.Unmarshal(b, &f); err != nil { if err := json.Unmarshal(b, &f); err != nil {
return nil, err return nil, err
} }
return f.tokenSource(ctx, scopes) ts, err := f.tokenSource(ctx, append([]string(nil), scopes...))
if err != nil {
return nil, err
}
return &DefaultCredentials{
ProjectID: f.ProjectID,
TokenSource: ts,
}, nil
} }

View File

@ -112,6 +112,7 @@ type credentialsFile struct {
PrivateKeyID string `json:"private_key_id"` PrivateKeyID string `json:"private_key_id"`
PrivateKey string `json:"private_key"` PrivateKey string `json:"private_key"`
TokenURL string `json:"token_uri"` TokenURL string `json:"token_uri"`
ProjectID string `json:"project_id"`
// User Credential fields // User Credential fields
// (These typically come from gcloud auth.) // (These typically come from gcloud auth.)