google: Add support for TokenSourceParams, Client ID json, and JWT Subject

This commit is contained in:
Andy Zhao 2021-04-19 12:13:37 -07:00
parent baf46329c2
commit 9b7db16e5e
2 changed files with 76 additions and 22 deletions

View File

@ -16,6 +16,7 @@ import (
"cloud.google.com/go/compute/metadata" "cloud.google.com/go/compute/metadata"
"golang.org/x/oauth2" "golang.org/x/oauth2"
"golang.org/x/oauth2/authhandler"
) )
// Credentials holds Google credentials, including "Application Default Credentials". // Credentials holds Google credentials, including "Application Default Credentials".
@ -41,6 +42,22 @@ type Credentials struct {
// Deprecated: use Credentials instead. // Deprecated: use Credentials instead.
type DefaultCredentials = Credentials type DefaultCredentials = Credentials
// TokenSourceParams holds user supplied parameters that are
// used for building a TokenSource.
type TokenSourceParams struct {
// List of OAuth scopes.
Scopes []string
// User email used for domain wide delegation.
Subject string
// AuthorizationHandler used for 3-legged OAuth flow.
AuthHandler authhandler.AuthorizationHandler
// State used for AuthorizationHandler.
State string
}
// DefaultClient returns an HTTP Client that uses the // DefaultClient returns an HTTP Client that uses the
// DefaultTokenSource to obtain authentication credentials. // 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) {
@ -81,11 +98,11 @@ func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSourc
// 4. On Google Compute Engine, Google App Engine standard second generation runtimes // 4. On Google Compute Engine, Google App Engine standard second generation runtimes
// (>= Go 1.11), and Google App Engine flexible environment, it fetches // (>= Go 1.11), and Google App Engine flexible environment, it fetches
// credentials from the metadata server. // credentials from the metadata server.
func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error) { func FindDefaultCredentialsWithParams(ctx context.Context, params TokenSourceParams) (*Credentials, 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 != "" {
creds, err := readCredentialsFile(ctx, filename, scopes) creds, err := readCredentialsFile(ctx, filename, params)
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)
} }
@ -94,7 +111,7 @@ func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials
// Second, try a well-known file. // Second, try a well-known file.
filename := wellKnownFile() filename := wellKnownFile()
if creds, err := readCredentialsFile(ctx, filename, scopes); err == nil { if creds, err := readCredentialsFile(ctx, filename, params); err == nil {
return creds, nil return creds, nil
} else if !os.IsNotExist(err) { } else if !os.IsNotExist(err) {
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)
@ -106,7 +123,7 @@ func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials
if appengineTokenFunc != nil { if appengineTokenFunc != nil {
return &DefaultCredentials{ return &DefaultCredentials{
ProjectID: appengineAppIDFunc(ctx), ProjectID: appengineAppIDFunc(ctx),
TokenSource: AppEngineTokenSource(ctx, scopes...), TokenSource: AppEngineTokenSource(ctx, params.Scopes...),
}, nil }, nil
} }
@ -116,7 +133,7 @@ func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials
id, _ := metadata.ProjectID() id, _ := metadata.ProjectID()
return &DefaultCredentials{ return &DefaultCredentials{
ProjectID: id, ProjectID: id,
TokenSource: ComputeTokenSource("", scopes...), TokenSource: ComputeTokenSource("", params.Scopes...),
}, nil }, nil
} }
@ -125,18 +142,36 @@ func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials
return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url) return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url)
} }
// Deprecated: use FindDefaultCredentialsWithParams instead.
func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error) {
var params TokenSourceParams
params.Scopes = scopes
return FindDefaultCredentialsWithParams(ctx, params)
}
// CredentialsFromJSON obtains Google credentials from a JSON value. The JSON can // CredentialsFromJSON obtains Google credentials from a JSON value. The JSON can
// represent either a Google Developers Console client_credentials.json file (as in // represent either a Google Developers Console client_credentials.json file (as in
// ConfigFromJSON), a Google Developers service account key file (as in // ConfigFromJSON), a Google Developers service account key file, a gCloud-style
// JWTConfigFromJSON) or the JSON configuration file for workload identity federation // user credentials file (a.k.a. refresh token JSON), or the JSON configuration file
// in non-Google cloud platforms (see // for workload identity federation in non-Google cloud platforms (see
// https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation). // https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation).
func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) { func CredentialsFromJSONWithParams(ctx context.Context, jsonData []byte, params TokenSourceParams) (*Credentials, error) {
// First, attempt to parse jsonData as a Google Developers Console client_credentials.json.
config, err := ConfigFromJSON(jsonData, params.Scopes...)
if err == nil {
return &Credentials{
ProjectID: "",
TokenSource: authhandler.TokenSource(ctx, config, params.State, params.AuthHandler),
JSON: jsonData,
}, nil
}
// Otherwise, parse jsonData as one of the other supported credential files.
var f credentialsFile var f credentialsFile
if err := json.Unmarshal(jsonData, &f); err != nil { if err = json.Unmarshal(jsonData, &f); err != nil {
return nil, err return nil, err
} }
ts, err := f.tokenSource(ctx, append([]string(nil), scopes...)) ts, err := f.tokenSource(ctx, params)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -147,6 +182,13 @@ func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string)
}, nil }, nil
} }
// Deprecated: use CredentialsFromJSONWithParams instead.
func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) {
var params TokenSourceParams
params.Scopes = scopes
return CredentialsFromJSONWithParams(ctx, jsonData, params)
}
func wellKnownFile() string { func wellKnownFile() string {
const f = "application_default_credentials.json" const f = "application_default_credentials.json"
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
@ -155,10 +197,10 @@ func wellKnownFile() string {
return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f) return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f)
} }
func readCredentialsFile(ctx context.Context, filename string, scopes []string) (*DefaultCredentials, error) { func readCredentialsFile(ctx context.Context, filename string, params TokenSourceParams) (*DefaultCredentials, error) {
b, err := ioutil.ReadFile(filename) b, err := ioutil.ReadFile(filename)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return CredentialsFromJSON(ctx, b, scopes...) return CredentialsFromJSONWithParams(ctx, b, params)
} }

View File

@ -19,7 +19,7 @@ import (
"golang.org/x/oauth2/jwt" "golang.org/x/oauth2/jwt"
) )
// Endpoint is Google's OAuth 2.0 endpoint. // Endpoint is Google's OAuth 2.0 default endpoint.
var Endpoint = oauth2.Endpoint{ var Endpoint = oauth2.Endpoint{
AuthURL: "https://accounts.google.com/o/oauth2/auth", AuthURL: "https://accounts.google.com/o/oauth2/auth",
TokenURL: "https://oauth2.googleapis.com/token", TokenURL: "https://oauth2.googleapis.com/token",
@ -87,7 +87,7 @@ func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error) {
return nil, fmt.Errorf("google: read JWT from JSON credentials: 'type' field is %q (expected %q)", f.Type, serviceAccountKey) return nil, fmt.Errorf("google: read JWT from JSON credentials: 'type' field is %q (expected %q)", f.Type, serviceAccountKey)
} }
scope = append([]string(nil), scope...) // copy scope = append([]string(nil), scope...) // copy
return f.jwtConfig(scope), nil return f.jwtConfig(scope, ""), nil
} }
// JSON key file types. // JSON key file types.
@ -99,12 +99,13 @@ const (
// credentialsFile is the unmarshalled representation of a credentials file. // credentialsFile is the unmarshalled representation of a credentials file.
type credentialsFile struct { type credentialsFile struct {
Type string `json:"type"` // serviceAccountKey or userCredentialsKey Type string `json:"type"`
// Service Account fields // Service Account fields
ClientEmail string `json:"client_email"` ClientEmail string `json:"client_email"`
PrivateKeyID string `json:"private_key_id"` PrivateKeyID string `json:"private_key_id"`
PrivateKey string `json:"private_key"` PrivateKey string `json:"private_key"`
AuthURL string `json:"auth_uri"`
TokenURL string `json:"token_uri"` TokenURL string `json:"token_uri"`
ProjectID string `json:"project_id"` ProjectID string `json:"project_id"`
@ -124,13 +125,14 @@ type credentialsFile struct {
QuotaProjectID string `json:"quota_project_id"` QuotaProjectID string `json:"quota_project_id"`
} }
func (f *credentialsFile) jwtConfig(scopes []string) *jwt.Config { func (f *credentialsFile) jwtConfig(scopes []string, subject string) *jwt.Config {
cfg := &jwt.Config{ cfg := &jwt.Config{
Email: f.ClientEmail, Email: f.ClientEmail,
PrivateKey: []byte(f.PrivateKey), PrivateKey: []byte(f.PrivateKey),
PrivateKeyID: f.PrivateKeyID, PrivateKeyID: f.PrivateKeyID,
Scopes: scopes, Scopes: scopes,
TokenURL: f.TokenURL, TokenURL: f.TokenURL,
Subject: subject, // This is the user email to impersonate
} }
if cfg.TokenURL == "" { if cfg.TokenURL == "" {
cfg.TokenURL = JWTTokenURL cfg.TokenURL = JWTTokenURL
@ -138,17 +140,27 @@ func (f *credentialsFile) jwtConfig(scopes []string) *jwt.Config {
return cfg return cfg
} }
func (f *credentialsFile) tokenSource(ctx context.Context, scopes []string) (oauth2.TokenSource, error) { func (f *credentialsFile) tokenSource(ctx context.Context, params TokenSourceParams) (oauth2.TokenSource, error) {
switch f.Type { switch f.Type {
case serviceAccountKey: case serviceAccountKey:
cfg := f.jwtConfig(scopes) cfg := f.jwtConfig(params.Scopes, params.Subject)
return cfg.TokenSource(ctx), nil return cfg.TokenSource(ctx), nil
case userCredentialsKey: case userCredentialsKey:
cfg := &oauth2.Config{ cfg := &oauth2.Config{
ClientID: f.ClientID, ClientID: f.ClientID,
ClientSecret: f.ClientSecret, ClientSecret: f.ClientSecret,
Scopes: scopes, Scopes: params.Scopes,
Endpoint: Endpoint, Endpoint: oauth2.Endpoint{
AuthURL: f.AuthURL,
TokenURL: f.TokenURL,
AuthStyle: oauth2.AuthStyleInParams,
},
}
if cfg.Endpoint.AuthURL == "" {
cfg.Endpoint.AuthURL = Endpoint.AuthURL
}
if cfg.Endpoint.TokenURL == "" {
cfg.Endpoint.TokenURL = Endpoint.TokenURL
} }
tok := &oauth2.Token{RefreshToken: f.RefreshToken} tok := &oauth2.Token{RefreshToken: f.RefreshToken}
return cfg.TokenSource(ctx, tok), nil return cfg.TokenSource(ctx, tok), nil
@ -163,7 +175,7 @@ func (f *credentialsFile) tokenSource(ctx context.Context, scopes []string) (oau
ClientID: f.ClientID, ClientID: f.ClientID,
CredentialSource: f.CredentialSource, CredentialSource: f.CredentialSource,
QuotaProjectID: f.QuotaProjectID, QuotaProjectID: f.QuotaProjectID,
Scopes: scopes, Scopes: params.Scopes,
} }
return cfg.TokenSource(ctx), nil return cfg.TokenSource(ctx), nil
case "": case "":