You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

156 lines
5.4 KiB

  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. )
  17. // Credentials holds Google credentials, including "Application Default Credentials".
  18. // For more details, see:
  19. // https://developers.google.com/accounts/docs/application-default-credentials
  20. type Credentials struct {
  21. ProjectID string // may be empty
  22. TokenSource oauth2.TokenSource
  23. // JSON contains the raw bytes from a JSON credentials file.
  24. // This field may be nil if authentication is provided by the
  25. // environment and not with a credentials file, e.g. when code is
  26. // running on Google Cloud Platform.
  27. JSON []byte
  28. }
  29. // DefaultCredentials is the old name of Credentials.
  30. //
  31. // Deprecated: use Credentials instead.
  32. type DefaultCredentials = Credentials
  33. // DefaultClient returns an HTTP Client that uses the
  34. // DefaultTokenSource to obtain authentication credentials.
  35. func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
  36. ts, err := DefaultTokenSource(ctx, scope...)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return oauth2.NewClient(ctx, ts), nil
  41. }
  42. // DefaultTokenSource returns the token source for
  43. // "Application Default Credentials".
  44. // It is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource.
  45. func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) {
  46. creds, err := FindDefaultCredentials(ctx, scope...)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return creds.TokenSource, nil
  51. }
  52. // FindDefaultCredentials searches for "Application Default Credentials".
  53. //
  54. // It looks for credentials in the following places,
  55. // preferring the first location found:
  56. //
  57. // 1. A JSON file whose path is specified by the
  58. // GOOGLE_APPLICATION_CREDENTIALS environment variable.
  59. // 2. A JSON file in a location known to the gcloud command-line tool.
  60. // On Windows, this is %APPDATA%/gcloud/application_default_credentials.json.
  61. // On other systems, $HOME/.config/gcloud/application_default_credentials.json.
  62. // 3. On Google App Engine standard first generation runtimes (<= Go 1.9) it uses
  63. // the appengine.AccessToken function.
  64. // 4. On Google Compute Engine, Google App Engine standard second generation runtimes
  65. // (>= Go 1.11), and Google App Engine flexible environment, it fetches
  66. // credentials from the metadata server.
  67. // (In this final case any provided scopes are ignored.)
  68. func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error) {
  69. // First, try the environment variable.
  70. const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
  71. if filename := os.Getenv(envVar); filename != "" {
  72. creds, err := readCredentialsFile(ctx, filename, scopes)
  73. if err != nil {
  74. return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err)
  75. }
  76. return creds, nil
  77. }
  78. // Second, try a well-known file.
  79. filename := wellKnownFile()
  80. if creds, err := readCredentialsFile(ctx, filename, scopes); err == nil {
  81. return creds, nil
  82. } else if !os.IsNotExist(err) {
  83. return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err)
  84. }
  85. // Third, if we're on a Google App Engine standard first generation runtime (<= Go 1.9)
  86. // use those credentials. App Engine standard second generation runtimes (>= Go 1.11)
  87. // and App Engine flexible use ComputeTokenSource and the metadata server.
  88. if appengineTokenFunc != nil {
  89. return &DefaultCredentials{
  90. ProjectID: appengineAppIDFunc(ctx),
  91. TokenSource: AppEngineTokenSource(ctx, scopes...),
  92. }, nil
  93. }
  94. // Fourth, if we're on Google Compute Engine, an App Engine standard second generation runtime,
  95. // or App Engine flexible, use the metadata server.
  96. if metadata.OnGCE() {
  97. id, _ := metadata.ProjectID()
  98. return &DefaultCredentials{
  99. ProjectID: id,
  100. TokenSource: ComputeTokenSource(""),
  101. }, nil
  102. }
  103. // None are found; return helpful error.
  104. const url = "https://developers.google.com/accounts/docs/application-default-credentials"
  105. return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url)
  106. }
  107. // CredentialsFromJSON obtains Google credentials from a JSON value. The JSON can
  108. // represent either a Google Developers Console client_credentials.json file (as in
  109. // ConfigFromJSON) or a Google Developers service account key file (as in
  110. // JWTConfigFromJSON).
  111. func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) {
  112. var f credentialsFile
  113. if err := json.Unmarshal(jsonData, &f); err != nil {
  114. return nil, err
  115. }
  116. ts, err := f.tokenSource(ctx, append([]string(nil), scopes...))
  117. if err != nil {
  118. return nil, err
  119. }
  120. return &DefaultCredentials{
  121. ProjectID: f.ProjectID,
  122. TokenSource: ts,
  123. JSON: jsonData,
  124. }, nil
  125. }
  126. func wellKnownFile() string {
  127. const f = "application_default_credentials.json"
  128. if runtime.GOOS == "windows" {
  129. return filepath.Join(os.Getenv("APPDATA"), "gcloud", f)
  130. }
  131. return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f)
  132. }
  133. func readCredentialsFile(ctx context.Context, filename string, scopes []string) (*DefaultCredentials, error) {
  134. b, err := ioutil.ReadFile(filename)
  135. if err != nil {
  136. return nil, err
  137. }
  138. return CredentialsFromJSON(ctx, b, scopes...)
  139. }