default.go 4.2 KB

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