default.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package google
  5. import (
  6. "context"
  7. "encoding/json"
  8. "fmt"
  9. "io/ioutil"
  10. "net/http"
  11. "os"
  12. "path/filepath"
  13. "runtime"
  14. "cloud.google.com/go/compute/metadata"
  15. "golang.org/x/oauth2"
  16. "golang.org/x/oauth2/authhandler"
  17. )
  18. // Credentials holds Google credentials, including "Application Default Credentials".
  19. // For more details, see:
  20. // https://developers.google.com/accounts/docs/application-default-credentials
  21. // Credentials from external accounts (workload identity federation) are used to
  22. // identify a particular application from an on-prem or non-Google Cloud platform
  23. // including Amazon Web Services (AWS), Microsoft Azure or any identity provider
  24. // that supports OpenID Connect (OIDC).
  25. type Credentials struct {
  26. ProjectID string // may be empty
  27. TokenSource oauth2.TokenSource
  28. // JSON contains the raw bytes from a JSON credentials file.
  29. // This field may be nil if authentication is provided by the
  30. // environment and not with a credentials file, e.g. when code is
  31. // running on Google Cloud Platform.
  32. JSON []byte
  33. }
  34. // DefaultCredentials is the old name of Credentials.
  35. //
  36. // Deprecated: use Credentials instead.
  37. type DefaultCredentials = Credentials
  38. // CredentialsParams holds user supplied parameters that are used together
  39. // with a credentials file for building a Credentials object.
  40. type CredentialsParams struct {
  41. // Scopes is the list OAuth scopes. Required.
  42. // Example: https://www.googleapis.com/auth/cloud-platform
  43. Scopes []string
  44. // Subject is the user email used for domain wide delegation (see
  45. // https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority).
  46. // Optional.
  47. Subject string
  48. // AuthHandler is the AuthorizationHandler used for 3-legged OAuth flow. Optional.
  49. AuthHandler authhandler.AuthorizationHandler
  50. // State is a unique string used with AuthHandler. Optional.
  51. State string
  52. }
  53. func (params CredentialsParams) deepCopy() CredentialsParams {
  54. paramsCopy := params
  55. paramsCopy.Scopes = make([]string, len(params.Scopes))
  56. copy(paramsCopy.Scopes, params.Scopes)
  57. return paramsCopy
  58. }
  59. // DefaultClient returns an HTTP Client that uses the
  60. // DefaultTokenSource to obtain authentication credentials.
  61. func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
  62. ts, err := DefaultTokenSource(ctx, scope...)
  63. if err != nil {
  64. return nil, err
  65. }
  66. return oauth2.NewClient(ctx, ts), nil
  67. }
  68. // DefaultTokenSource returns the token source for
  69. // "Application Default Credentials".
  70. // It is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource.
  71. func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) {
  72. creds, err := FindDefaultCredentials(ctx, scope...)
  73. if err != nil {
  74. return nil, err
  75. }
  76. return creds.TokenSource, nil
  77. }
  78. // FindDefaultCredentialsWithParams searches for "Application Default Credentials".
  79. //
  80. // It looks for credentials in the following places,
  81. // preferring the first location found:
  82. //
  83. // 1. A JSON file whose path is specified by the
  84. // GOOGLE_APPLICATION_CREDENTIALS environment variable.
  85. // For workload identity federation, refer to
  86. // https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation on
  87. // how to generate the JSON configuration file for on-prem/non-Google cloud
  88. // platforms.
  89. // 2. A JSON file in a location known to the gcloud command-line tool.
  90. // On Windows, this is %APPDATA%/gcloud/application_default_credentials.json.
  91. // On other systems, $HOME/.config/gcloud/application_default_credentials.json.
  92. // 3. On Google App Engine standard first generation runtimes (<= Go 1.9) it uses
  93. // the appengine.AccessToken function.
  94. // 4. On Google Compute Engine, Google App Engine standard second generation runtimes
  95. // (>= Go 1.11), and Google App Engine flexible environment, it fetches
  96. // credentials from the metadata server.
  97. func FindDefaultCredentialsWithParams(ctx context.Context, params CredentialsParams) (*Credentials, error) {
  98. // Make defensive copy of the slices in params.
  99. params = params.deepCopy()
  100. // First, try the environment variable.
  101. const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
  102. if filename := os.Getenv(envVar); filename != "" {
  103. creds, err := readCredentialsFile(ctx, filename, params)
  104. if err != nil {
  105. return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err)
  106. }
  107. return creds, nil
  108. }
  109. // Second, try a well-known file.
  110. filename := wellKnownFile()
  111. if creds, err := readCredentialsFile(ctx, filename, params); err == nil {
  112. return creds, nil
  113. } else if !os.IsNotExist(err) {
  114. return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err)
  115. }
  116. // Third, if we're on a Google App Engine standard first generation runtime (<= Go 1.9)
  117. // use those credentials. App Engine standard second generation runtimes (>= Go 1.11)
  118. // and App Engine flexible use ComputeTokenSource and the metadata server.
  119. if appengineTokenFunc != nil {
  120. return &DefaultCredentials{
  121. ProjectID: appengineAppIDFunc(ctx),
  122. TokenSource: AppEngineTokenSource(ctx, params.Scopes...),
  123. }, nil
  124. }
  125. // Fourth, if we're on Google Compute Engine, an App Engine standard second generation runtime,
  126. // or App Engine flexible, use the metadata server.
  127. if metadata.OnGCE() {
  128. id, _ := metadata.ProjectID()
  129. return &DefaultCredentials{
  130. ProjectID: id,
  131. TokenSource: ComputeTokenSource("", params.Scopes...),
  132. }, nil
  133. }
  134. // None are found; return helpful error.
  135. const url = "https://developers.google.com/accounts/docs/application-default-credentials"
  136. return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url)
  137. }
  138. // FindDefaultCredentials invokes FindDefaultCredentialsWithParams with the specified scopes.
  139. func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error) {
  140. var params CredentialsParams
  141. params.Scopes = scopes
  142. return FindDefaultCredentialsWithParams(ctx, params)
  143. }
  144. // CredentialsFromJSONWithParams obtains Google credentials from a JSON value. The JSON can
  145. // represent either a Google Developers Console client_credentials.json file (as in ConfigFromJSON),
  146. // a Google Developers service account key file, a gcloud user credentials file (a.k.a. refresh
  147. // token JSON), or the JSON configuration file for workload identity federation in non-Google cloud
  148. // platforms (see https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation).
  149. func CredentialsFromJSONWithParams(ctx context.Context, jsonData []byte, params CredentialsParams) (*Credentials, error) {
  150. // Make defensive copy of the slices in params.
  151. params = params.deepCopy()
  152. // First, attempt to parse jsonData as a Google Developers Console client_credentials.json.
  153. config, _ := ConfigFromJSON(jsonData, params.Scopes...)
  154. if config != nil {
  155. return &Credentials{
  156. ProjectID: "",
  157. TokenSource: authhandler.TokenSource(ctx, config, params.State, params.AuthHandler),
  158. JSON: jsonData,
  159. }, nil
  160. }
  161. // Otherwise, parse jsonData as one of the other supported credentials files.
  162. var f credentialsFile
  163. if err := json.Unmarshal(jsonData, &f); err != nil {
  164. return nil, err
  165. }
  166. ts, err := f.tokenSource(ctx, params)
  167. if err != nil {
  168. return nil, err
  169. }
  170. return &DefaultCredentials{
  171. ProjectID: f.ProjectID,
  172. TokenSource: ts,
  173. JSON: jsonData,
  174. }, nil
  175. }
  176. // CredentialsFromJSON invokes CredentialsFromJSONWithParams with the specified scopes.
  177. func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) {
  178. var params CredentialsParams
  179. params.Scopes = scopes
  180. return CredentialsFromJSONWithParams(ctx, jsonData, params)
  181. }
  182. func wellKnownFile() string {
  183. const f = "application_default_credentials.json"
  184. if runtime.GOOS == "windows" {
  185. return filepath.Join(os.Getenv("APPDATA"), "gcloud", f)
  186. }
  187. return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f)
  188. }
  189. func readCredentialsFile(ctx context.Context, filename string, params CredentialsParams) (*DefaultCredentials, error) {
  190. b, err := ioutil.ReadFile(filename)
  191. if err != nil {
  192. return nil, err
  193. }
  194. return CredentialsFromJSONWithParams(ctx, b, params)
  195. }