本站源代码
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.

155 lines
5.3KB

  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. func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error) {
  68. // First, try the environment variable.
  69. const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
  70. if filename := os.Getenv(envVar); filename != "" {
  71. creds, err := readCredentialsFile(ctx, filename, scopes)
  72. if err != nil {
  73. return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err)
  74. }
  75. return creds, nil
  76. }
  77. // Second, try a well-known file.
  78. filename := wellKnownFile()
  79. if creds, err := readCredentialsFile(ctx, filename, scopes); err == nil {
  80. return creds, nil
  81. } else if !os.IsNotExist(err) {
  82. return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err)
  83. }
  84. // Third, if we're on a Google App Engine standard first generation runtime (<= Go 1.9)
  85. // use those credentials. App Engine standard second generation runtimes (>= Go 1.11)
  86. // and App Engine flexible use ComputeTokenSource and the metadata server.
  87. if appengineTokenFunc != nil {
  88. return &DefaultCredentials{
  89. ProjectID: appengineAppIDFunc(ctx),
  90. TokenSource: AppEngineTokenSource(ctx, scopes...),
  91. }, nil
  92. }
  93. // Fourth, if we're on Google Compute Engine, an App Engine standard second generation runtime,
  94. // or App Engine flexible, use the metadata server.
  95. if metadata.OnGCE() {
  96. id, _ := metadata.ProjectID()
  97. return &DefaultCredentials{
  98. ProjectID: id,
  99. TokenSource: ComputeTokenSource("", scopes...),
  100. }, nil
  101. }
  102. // None are found; return helpful error.
  103. const url = "https://developers.google.com/accounts/docs/application-default-credentials"
  104. return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url)
  105. }
  106. // CredentialsFromJSON obtains Google credentials from a JSON value. The JSON can
  107. // represent either a Google Developers Console client_credentials.json file (as in
  108. // ConfigFromJSON) or a Google Developers service account key file (as in
  109. // JWTConfigFromJSON).
  110. func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) {
  111. var f credentialsFile
  112. if err := json.Unmarshal(jsonData, &f); err != nil {
  113. return nil, err
  114. }
  115. ts, err := f.tokenSource(ctx, append([]string(nil), scopes...))
  116. if err != nil {
  117. return nil, err
  118. }
  119. return &DefaultCredentials{
  120. ProjectID: f.ProjectID,
  121. TokenSource: ts,
  122. JSON: jsonData,
  123. }, nil
  124. }
  125. func wellKnownFile() string {
  126. const f = "application_default_credentials.json"
  127. if runtime.GOOS == "windows" {
  128. return filepath.Join(os.Getenv("APPDATA"), "gcloud", f)
  129. }
  130. return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f)
  131. }
  132. func readCredentialsFile(ctx context.Context, filename string, scopes []string) (*DefaultCredentials, error) {
  133. b, err := ioutil.ReadFile(filename)
  134. if err != nil {
  135. return nil, err
  136. }
  137. return CredentialsFromJSON(ctx, b, scopes...)
  138. }
上海开阖软件有限公司 沪ICP备12045867号-1