default.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. "net/http"
  10. "os"
  11. "path/filepath"
  12. "runtime"
  13. "time"
  14. "cloud.google.com/go/compute/metadata"
  15. "golang.org/x/oauth2"
  16. "golang.org/x/oauth2/authhandler"
  17. )
  18. const (
  19. adcSetupURL = "https://cloud.google.com/docs/authentication/external/set-up-adc"
  20. universeDomainDefault = "googleapis.com"
  21. )
  22. // Credentials holds Google credentials, including "Application Default Credentials".
  23. // For more details, see:
  24. // https://developers.google.com/accounts/docs/application-default-credentials
  25. // Credentials from external accounts (workload identity federation) are used to
  26. // identify a particular application from an on-prem or non-Google Cloud platform
  27. // including Amazon Web Services (AWS), Microsoft Azure or any identity provider
  28. // that supports OpenID Connect (OIDC).
  29. type Credentials struct {
  30. ProjectID string // may be empty
  31. TokenSource oauth2.TokenSource
  32. // JSON contains the raw bytes from a JSON credentials file.
  33. // This field may be nil if authentication is provided by the
  34. // environment and not with a credentials file, e.g. when code is
  35. // running on Google Cloud Platform.
  36. JSON []byte
  37. // universeDomain is the default service domain for a given Cloud universe.
  38. universeDomain string
  39. }
  40. // UniverseDomain returns the default service domain for a given Cloud universe.
  41. // The default value is "googleapis.com".
  42. func (c *Credentials) UniverseDomain() string {
  43. if c.universeDomain == "" {
  44. return universeDomainDefault
  45. }
  46. return c.universeDomain
  47. }
  48. // DefaultCredentials is the old name of Credentials.
  49. //
  50. // Deprecated: use Credentials instead.
  51. type DefaultCredentials = Credentials
  52. // CredentialsParams holds user supplied parameters that are used together
  53. // with a credentials file for building a Credentials object.
  54. type CredentialsParams struct {
  55. // Scopes is the list OAuth scopes. Required.
  56. // Example: https://www.googleapis.com/auth/cloud-platform
  57. Scopes []string
  58. // Subject is the user email used for domain wide delegation (see
  59. // https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority).
  60. // Optional.
  61. Subject string
  62. // AuthHandler is the AuthorizationHandler used for 3-legged OAuth flow. Required for 3LO flow.
  63. AuthHandler authhandler.AuthorizationHandler
  64. // State is a unique string used with AuthHandler. Required for 3LO flow.
  65. State string
  66. // PKCE is used to support PKCE flow. Optional for 3LO flow.
  67. PKCE *authhandler.PKCEParams
  68. // The OAuth2 TokenURL default override. This value overrides the default TokenURL,
  69. // unless explicitly specified by the credentials config file. Optional.
  70. TokenURL string
  71. // EarlyTokenRefresh is the amount of time before a token expires that a new
  72. // token will be preemptively fetched. If unset the default value is 10
  73. // seconds.
  74. //
  75. // Note: This option is currently only respected when using credentials
  76. // fetched from the GCE metadata server.
  77. EarlyTokenRefresh time.Duration
  78. }
  79. func (params CredentialsParams) deepCopy() CredentialsParams {
  80. paramsCopy := params
  81. paramsCopy.Scopes = make([]string, len(params.Scopes))
  82. copy(paramsCopy.Scopes, params.Scopes)
  83. return paramsCopy
  84. }
  85. // DefaultClient returns an HTTP Client that uses the
  86. // DefaultTokenSource to obtain authentication credentials.
  87. func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) {
  88. ts, err := DefaultTokenSource(ctx, scope...)
  89. if err != nil {
  90. return nil, err
  91. }
  92. return oauth2.NewClient(ctx, ts), nil
  93. }
  94. // DefaultTokenSource returns the token source for
  95. // "Application Default Credentials".
  96. // It is a shortcut for FindDefaultCredentials(ctx, scope).TokenSource.
  97. func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) {
  98. creds, err := FindDefaultCredentials(ctx, scope...)
  99. if err != nil {
  100. return nil, err
  101. }
  102. return creds.TokenSource, nil
  103. }
  104. // FindDefaultCredentialsWithParams searches for "Application Default Credentials".
  105. //
  106. // It looks for credentials in the following places,
  107. // preferring the first location found:
  108. //
  109. // 1. A JSON file whose path is specified by the
  110. // GOOGLE_APPLICATION_CREDENTIALS environment variable.
  111. // For workload identity federation, refer to
  112. // https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation on
  113. // how to generate the JSON configuration file for on-prem/non-Google cloud
  114. // platforms.
  115. // 2. A JSON file in a location known to the gcloud command-line tool.
  116. // On Windows, this is %APPDATA%/gcloud/application_default_credentials.json.
  117. // On other systems, $HOME/.config/gcloud/application_default_credentials.json.
  118. // 3. On Google App Engine standard first generation runtimes (<= Go 1.9) it uses
  119. // the appengine.AccessToken function.
  120. // 4. On Google Compute Engine, Google App Engine standard second generation runtimes
  121. // (>= Go 1.11), and Google App Engine flexible environment, it fetches
  122. // credentials from the metadata server.
  123. func FindDefaultCredentialsWithParams(ctx context.Context, params CredentialsParams) (*Credentials, error) {
  124. // Make defensive copy of the slices in params.
  125. params = params.deepCopy()
  126. // First, try the environment variable.
  127. const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
  128. if filename := os.Getenv(envVar); filename != "" {
  129. creds, err := readCredentialsFile(ctx, filename, params)
  130. if err != nil {
  131. return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err)
  132. }
  133. return creds, nil
  134. }
  135. // Second, try a well-known file.
  136. filename := wellKnownFile()
  137. if b, err := os.ReadFile(filename); err == nil {
  138. return CredentialsFromJSONWithParams(ctx, b, params)
  139. }
  140. // Third, if we're on a Google App Engine standard first generation runtime (<= Go 1.9)
  141. // use those credentials. App Engine standard second generation runtimes (>= Go 1.11)
  142. // and App Engine flexible use ComputeTokenSource and the metadata server.
  143. if appengineTokenFunc != nil {
  144. return &Credentials{
  145. ProjectID: appengineAppIDFunc(ctx),
  146. TokenSource: AppEngineTokenSource(ctx, params.Scopes...),
  147. }, nil
  148. }
  149. // Fourth, if we're on Google Compute Engine, an App Engine standard second generation runtime,
  150. // or App Engine flexible, use the metadata server.
  151. if metadata.OnGCE() {
  152. id, _ := metadata.ProjectID()
  153. return &Credentials{
  154. ProjectID: id,
  155. TokenSource: computeTokenSource("", params.EarlyTokenRefresh, params.Scopes...),
  156. }, nil
  157. }
  158. // None are found; return helpful error.
  159. return nil, fmt.Errorf("google: could not find default credentials. See %v for more information", adcSetupURL)
  160. }
  161. // FindDefaultCredentials invokes FindDefaultCredentialsWithParams with the specified scopes.
  162. func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error) {
  163. var params CredentialsParams
  164. params.Scopes = scopes
  165. return FindDefaultCredentialsWithParams(ctx, params)
  166. }
  167. // CredentialsFromJSONWithParams obtains Google credentials from a JSON value. The JSON can
  168. // represent either a Google Developers Console client_credentials.json file (as in ConfigFromJSON),
  169. // a Google Developers service account key file, a gcloud user credentials file (a.k.a. refresh
  170. // token JSON), or the JSON configuration file for workload identity federation in non-Google cloud
  171. // platforms (see https://cloud.google.com/iam/docs/how-to#using-workload-identity-federation).
  172. func CredentialsFromJSONWithParams(ctx context.Context, jsonData []byte, params CredentialsParams) (*Credentials, error) {
  173. // Make defensive copy of the slices in params.
  174. params = params.deepCopy()
  175. // First, attempt to parse jsonData as a Google Developers Console client_credentials.json.
  176. config, _ := ConfigFromJSON(jsonData, params.Scopes...)
  177. if config != nil {
  178. return &Credentials{
  179. ProjectID: "",
  180. TokenSource: authhandler.TokenSourceWithPKCE(ctx, config, params.State, params.AuthHandler, params.PKCE),
  181. JSON: jsonData,
  182. }, nil
  183. }
  184. // Otherwise, parse jsonData as one of the other supported credentials files.
  185. var f credentialsFile
  186. if err := json.Unmarshal(jsonData, &f); err != nil {
  187. return nil, err
  188. }
  189. universeDomain := f.UniverseDomain
  190. // Authorized user credentials are only supported in the googleapis.com universe.
  191. if f.Type == userCredentialsKey {
  192. universeDomain = universeDomainDefault
  193. }
  194. ts, err := f.tokenSource(ctx, params)
  195. if err != nil {
  196. return nil, err
  197. }
  198. ts = newErrWrappingTokenSource(ts)
  199. return &Credentials{
  200. ProjectID: f.ProjectID,
  201. TokenSource: ts,
  202. JSON: jsonData,
  203. universeDomain: universeDomain,
  204. }, nil
  205. }
  206. // CredentialsFromJSON invokes CredentialsFromJSONWithParams with the specified scopes.
  207. func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) {
  208. var params CredentialsParams
  209. params.Scopes = scopes
  210. return CredentialsFromJSONWithParams(ctx, jsonData, params)
  211. }
  212. func wellKnownFile() string {
  213. const f = "application_default_credentials.json"
  214. if runtime.GOOS == "windows" {
  215. return filepath.Join(os.Getenv("APPDATA"), "gcloud", f)
  216. }
  217. return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f)
  218. }
  219. func readCredentialsFile(ctx context.Context, filename string, params CredentialsParams) (*Credentials, error) {
  220. b, err := os.ReadFile(filename)
  221. if err != nil {
  222. return nil, err
  223. }
  224. return CredentialsFromJSONWithParams(ctx, b, params)
  225. }