default.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "runtime"
  13. "cloud.google.com/go/compute/metadata"
  14. "golang.org/x/net/context"
  15. "golang.org/x/oauth2"
  16. )
  17. // DefaultCredentials holds "Application Default Credentials".
  18. // For more details, see:
  19. // https://developers.google.com/accounts/docs/application-default-credentials
  20. type DefaultCredentials 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. // DefaultClient returns an HTTP Client that uses the
  30. // DefaultTokenSource to obtain authentication credentials.
  31. func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
  32. ts, err := DefaultTokenSource(ctx, scope...)
  33. if err != nil {
  34. return nil, err
  35. }
  36. return oauth2.NewClient(ctx, ts), nil
  37. }
  38. // DefaultTokenSource returns the token source for
  39. // "Application Default Credentials".
  40. // It is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource.
  41. func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) {
  42. creds, err := FindDefaultCredentials(ctx, scope...)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return creds.TokenSource, nil
  47. }
  48. // FindDefaultCredentials searches for "Application Default Credentials".
  49. //
  50. // It looks for credentials in the following places,
  51. // preferring the first location found:
  52. //
  53. // 1. A JSON file whose path is specified by the
  54. // GOOGLE_APPLICATION_CREDENTIALS environment variable.
  55. // 2. A JSON file in a location known to the gcloud command-line tool.
  56. // On Windows, this is %APPDATA%/gcloud/application_default_credentials.json.
  57. // On other systems, $HOME/.config/gcloud/application_default_credentials.json.
  58. // 3. On Google App Engine it uses the appengine.AccessToken function.
  59. // 4. On Google Compute Engine and Google App Engine Managed VMs, it fetches
  60. // credentials from the metadata server.
  61. // (In this final case any provided scopes are ignored.)
  62. func FindDefaultCredentials(ctx context.Context, scope ...string) (*DefaultCredentials, error) {
  63. // First, try the environment variable.
  64. const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
  65. if filename := os.Getenv(envVar); filename != "" {
  66. creds, err := readCredentialsFile(ctx, filename, scope)
  67. if err != nil {
  68. return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err)
  69. }
  70. return creds, nil
  71. }
  72. // Second, try a well-known file.
  73. filename := wellKnownFile()
  74. if creds, err := readCredentialsFile(ctx, filename, scope); err == nil {
  75. return creds, nil
  76. } else if !os.IsNotExist(err) {
  77. return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err)
  78. }
  79. // Third, if we're on Google App Engine use those credentials.
  80. if appengineTokenFunc != nil && !appengineFlex {
  81. return &DefaultCredentials{
  82. ProjectID: appengineAppIDFunc(ctx),
  83. TokenSource: AppEngineTokenSource(ctx, scope...),
  84. }, nil
  85. }
  86. // Fourth, if we're on Google Compute Engine use the metadata server.
  87. if metadata.OnGCE() {
  88. id, _ := metadata.ProjectID()
  89. return &DefaultCredentials{
  90. ProjectID: id,
  91. TokenSource: ComputeTokenSource(""),
  92. }, nil
  93. }
  94. // None are found; return helpful error.
  95. const url = "https://developers.google.com/accounts/docs/application-default-credentials"
  96. return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url)
  97. }
  98. func wellKnownFile() string {
  99. const f = "application_default_credentials.json"
  100. if runtime.GOOS == "windows" {
  101. return filepath.Join(os.Getenv("APPDATA"), "gcloud", f)
  102. }
  103. return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f)
  104. }
  105. func readCredentialsFile(ctx context.Context, filename string, scopes []string) (*DefaultCredentials, error) {
  106. b, err := ioutil.ReadFile(filename)
  107. if err != nil {
  108. return nil, err
  109. }
  110. var f credentialsFile
  111. if err := json.Unmarshal(b, &f); err != nil {
  112. return nil, err
  113. }
  114. ts, err := f.tokenSource(ctx, append([]string(nil), scopes...))
  115. if err != nil {
  116. return nil, err
  117. }
  118. return &DefaultCredentials{
  119. ProjectID: f.ProjectID,
  120. TokenSource: ts,
  121. JSON: b,
  122. }, nil
  123. }