default.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. Required for 3LO flow.
  49. AuthHandler authhandler.AuthorizationHandler
  50. // State is a unique string used with AuthHandler. Required for 3LO flow.
  51. State string
  52. // PKCE is used to support PKCE flow. Optional for 3LO flow.
  53. PKCE *authhandler.PKCEParams
  54. }
  55. func (params CredentialsParams) deepCopy() CredentialsParams {
  56. paramsCopy := params
  57. paramsCopy.Scopes = make([]string, len(params.Scopes))
  58. copy(paramsCopy.Scopes, params.Scopes)
  59. return paramsCopy
  60. }
  61. // DefaultClient returns an HTTP Client that uses the
  62. // DefaultTokenSource to obtain authentication credentials.
  63. func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
  64. ts, err := DefaultTokenSource(ctx, scope...)
  65. if err != nil {
  66. return nil, err
  67. }
  68. return oauth2.NewClient(ctx, ts), nil
  69. }
  70. // DefaultTokenSource returns the token source for
  71. // "Application Default Credentials".
  72. // It is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource.
  73. func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) {
  74. creds, err := FindDefaultCredentials(ctx, scope...)
  75. if err != nil {
  76. return nil, err
  77. }
  78. return creds.TokenSource, nil
  79. }
  80. // FindDefaultCredentialsWithParams searches for "Application Default Credentials".
  81. //
  82. // It looks for credentials in the following places,
  83. // preferring the first location found:
  84. //
  85. // 1. A JSON file whose path is specified by the
  86. // GOOGLE_APPLICATION_CREDENTIALS environment variable.
  87. // For workload identity federation, refer to
  88. // https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation on
  89. // how to generate the JSON configuration file for on-prem/non-Google cloud
  90. // platforms.
  91. // 2. A JSON file in a location known to the gcloud command-line tool.
  92. // On Windows, this is %APPDATA%/gcloud/application_default_credentials.json.
  93. // On other systems, $HOME/.config/gcloud/application_default_credentials.json.
  94. // 3. On Google App Engine standard first generation runtimes (<= Go 1.9) it uses
  95. // the appengine.AccessToken function.
  96. // 4. On Google Compute Engine, Google App Engine standard second generation runtimes
  97. // (>= Go 1.11), and Google App Engine flexible environment, it fetches
  98. // credentials from the metadata server.
  99. func FindDefaultCredentialsWithParams(ctx context.Context, params CredentialsParams) (*Credentials, error) {
  100. // Make defensive copy of the slices in params.
  101. params = params.deepCopy()
  102. // First, try the environment variable.
  103. const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
  104. if filename := os.Getenv(envVar); filename != "" {
  105. creds, err := readCredentialsFile(ctx, filename, params)
  106. if err != nil {
  107. return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err)
  108. }
  109. return creds, nil
  110. }
  111. // Second, try a well-known file.
  112. filename := wellKnownFile()
  113. if creds, err := readCredentialsFile(ctx, filename, params); err == nil {
  114. return creds, nil
  115. } else if !os.IsNotExist(err) {
  116. return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err)
  117. }
  118. // Third, if we're on a Google App Engine standard first generation runtime (<= Go 1.9)
  119. // use those credentials. App Engine standard second generation runtimes (>= Go 1.11)
  120. // and App Engine flexible use ComputeTokenSource and the metadata server.
  121. if appengineTokenFunc != nil {
  122. return &DefaultCredentials{
  123. ProjectID: appengineAppIDFunc(ctx),
  124. TokenSource: AppEngineTokenSource(ctx, params.Scopes...),
  125. }, nil
  126. }
  127. // Fourth, if we're on Google Compute Engine, an App Engine standard second generation runtime,
  128. // or App Engine flexible, use the metadata server.
  129. if metadata.OnGCE() {
  130. id, _ := metadata.ProjectID()
  131. return &DefaultCredentials{
  132. ProjectID: id,
  133. TokenSource: ComputeTokenSource("", params.Scopes...),
  134. }, nil
  135. }
  136. // None are found; return helpful error.
  137. const url = "https://developers.google.com/accounts/docs/application-default-credentials"
  138. return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url)
  139. }
  140. // FindDefaultCredentials invokes FindDefaultCredentialsWithParams with the specified scopes.
  141. func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error) {
  142. var params CredentialsParams
  143. params.Scopes = scopes
  144. return FindDefaultCredentialsWithParams(ctx, params)
  145. }
  146. // CredentialsFromJSONWithParams obtains Google credentials from a JSON value. The JSON can
  147. // represent either a Google Developers Console client_credentials.json file (as in ConfigFromJSON),
  148. // a Google Developers service account key file, a gcloud user credentials file (a.k.a. refresh
  149. // token JSON), or the JSON configuration file for workload identity federation in non-Google cloud
  150. // platforms (see https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation).
  151. func CredentialsFromJSONWithParams(ctx context.Context, jsonData []byte, params CredentialsParams) (*Credentials, error) {
  152. // Make defensive copy of the slices in params.
  153. params = params.deepCopy()
  154. // First, attempt to parse jsonData as a Google Developers Console client_credentials.json.
  155. config, _ := ConfigFromJSON(jsonData, params.Scopes...)
  156. if config != nil {
  157. return &Credentials{
  158. ProjectID: "",
  159. TokenSource: authhandler.TokenSourceWithPKCE(ctx, config, params.State, params.AuthHandler, params.PKCE),
  160. JSON: jsonData,
  161. }, nil
  162. }
  163. // Otherwise, parse jsonData as one of the other supported credentials files.
  164. var f credentialsFile
  165. if err := json.Unmarshal(jsonData, &f); err != nil {
  166. return nil, err
  167. }
  168. ts, err := f.tokenSource(ctx, params)
  169. if err != nil {
  170. return nil, err
  171. }
  172. ts = newErrWrappingTokenSource(ts)
  173. return &DefaultCredentials{
  174. ProjectID: f.ProjectID,
  175. TokenSource: ts,
  176. JSON: jsonData,
  177. }, nil
  178. }
  179. // CredentialsFromJSON invokes CredentialsFromJSONWithParams with the specified scopes.
  180. func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) {
  181. var params CredentialsParams
  182. params.Scopes = scopes
  183. return CredentialsFromJSONWithParams(ctx, jsonData, params)
  184. }
  185. func wellKnownFile() string {
  186. const f = "application_default_credentials.json"
  187. if runtime.GOOS == "windows" {
  188. return filepath.Join(os.Getenv("APPDATA"), "gcloud", f)
  189. }
  190. return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f)
  191. }
  192. func readCredentialsFile(ctx context.Context, filename string, params CredentialsParams) (*DefaultCredentials, error) {
  193. b, err := ioutil.ReadFile(filename)
  194. if err != nil {
  195. return nil, err
  196. }
  197. return CredentialsFromJSONWithParams(ctx, b, params)
  198. }