google.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. // Copyright 2014 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. "errors"
  9. "fmt"
  10. "net/url"
  11. "strings"
  12. "time"
  13. "cloud.google.com/go/compute/metadata"
  14. "golang.org/x/oauth2"
  15. "golang.org/x/oauth2/google/internal/externalaccount"
  16. "golang.org/x/oauth2/jwt"
  17. )
  18. // Endpoint is Google's OAuth 2.0 default endpoint.
  19. var Endpoint = oauth2.Endpoint{
  20. AuthURL: "https://accounts.google.com/o/oauth2/auth",
  21. TokenURL: "https://oauth2.googleapis.com/token",
  22. AuthStyle: oauth2.AuthStyleInParams,
  23. }
  24. // JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow.
  25. const JWTTokenURL = "https://oauth2.googleapis.com/token"
  26. // ConfigFromJSON uses a Google Developers Console client_credentials.json
  27. // file to construct a config.
  28. // client_credentials.json can be downloaded from
  29. // https://console.developers.google.com, under "Credentials". Download the Web
  30. // application credentials in the JSON format and provide the contents of the
  31. // file as jsonKey.
  32. func ConfigFromJSON(jsonKey []byte, scope ...string) (*oauth2.Config, error) {
  33. type cred struct {
  34. ClientID string `json:"client_id"`
  35. ClientSecret string `json:"client_secret"`
  36. RedirectURIs []string `json:"redirect_uris"`
  37. AuthURI string `json:"auth_uri"`
  38. TokenURI string `json:"token_uri"`
  39. }
  40. var j struct {
  41. Web *cred `json:"web"`
  42. Installed *cred `json:"installed"`
  43. }
  44. if err := json.Unmarshal(jsonKey, &j); err != nil {
  45. return nil, err
  46. }
  47. var c *cred
  48. switch {
  49. case j.Web != nil:
  50. c = j.Web
  51. case j.Installed != nil:
  52. c = j.Installed
  53. default:
  54. return nil, fmt.Errorf("oauth2/google: no credentials found")
  55. }
  56. if len(c.RedirectURIs) < 1 {
  57. return nil, errors.New("oauth2/google: missing redirect URL in the client_credentials.json")
  58. }
  59. return &oauth2.Config{
  60. ClientID: c.ClientID,
  61. ClientSecret: c.ClientSecret,
  62. RedirectURL: c.RedirectURIs[0],
  63. Scopes: scope,
  64. Endpoint: oauth2.Endpoint{
  65. AuthURL: c.AuthURI,
  66. TokenURL: c.TokenURI,
  67. },
  68. }, nil
  69. }
  70. // JWTConfigFromJSON uses a Google Developers service account JSON key file to read
  71. // the credentials that authorize and authenticate the requests.
  72. // Create a service account on "Credentials" for your project at
  73. // https://console.developers.google.com to download a JSON key file.
  74. func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error) {
  75. var f credentialsFile
  76. if err := json.Unmarshal(jsonKey, &f); err != nil {
  77. return nil, err
  78. }
  79. if f.Type != serviceAccountKey {
  80. return nil, fmt.Errorf("google: read JWT from JSON credentials: 'type' field is %q (expected %q)", f.Type, serviceAccountKey)
  81. }
  82. scope = append([]string(nil), scope...) // copy
  83. return f.jwtConfig(scope, ""), nil
  84. }
  85. // JSON key file types.
  86. const (
  87. serviceAccountKey = "service_account"
  88. userCredentialsKey = "authorized_user"
  89. externalAccountKey = "external_account"
  90. impersonatedServiceAccount = "impersonated_service_account"
  91. )
  92. // credentialsFile is the unmarshalled representation of a credentials file.
  93. type credentialsFile struct {
  94. Type string `json:"type"`
  95. // Service Account fields
  96. ClientEmail string `json:"client_email"`
  97. PrivateKeyID string `json:"private_key_id"`
  98. PrivateKey string `json:"private_key"`
  99. AuthURL string `json:"auth_uri"`
  100. TokenURL string `json:"token_uri"`
  101. ProjectID string `json:"project_id"`
  102. // User Credential fields
  103. // (These typically come from gcloud auth.)
  104. ClientSecret string `json:"client_secret"`
  105. ClientID string `json:"client_id"`
  106. RefreshToken string `json:"refresh_token"`
  107. // External Account fields
  108. Audience string `json:"audience"`
  109. SubjectTokenType string `json:"subject_token_type"`
  110. TokenURLExternal string `json:"token_url"`
  111. TokenInfoURL string `json:"token_info_url"`
  112. ServiceAccountImpersonationURL string `json:"service_account_impersonation_url"`
  113. ServiceAccountImpersonation serviceAccountImpersonationInfo `json:"service_account_impersonation"`
  114. Delegates []string `json:"delegates"`
  115. CredentialSource externalaccount.CredentialSource `json:"credential_source"`
  116. QuotaProjectID string `json:"quota_project_id"`
  117. WorkforcePoolUserProject string `json:"workforce_pool_user_project"`
  118. // Service account impersonation
  119. SourceCredentials *credentialsFile `json:"source_credentials"`
  120. }
  121. type serviceAccountImpersonationInfo struct {
  122. TokenLifetimeSeconds int `json:"token_lifetime_seconds"`
  123. }
  124. func (f *credentialsFile) jwtConfig(scopes []string, subject string) *jwt.Config {
  125. cfg := &jwt.Config{
  126. Email: f.ClientEmail,
  127. PrivateKey: []byte(f.PrivateKey),
  128. PrivateKeyID: f.PrivateKeyID,
  129. Scopes: scopes,
  130. TokenURL: f.TokenURL,
  131. Subject: subject, // This is the user email to impersonate
  132. Audience: f.Audience,
  133. }
  134. if cfg.TokenURL == "" {
  135. cfg.TokenURL = JWTTokenURL
  136. }
  137. return cfg
  138. }
  139. func (f *credentialsFile) tokenSource(ctx context.Context, params CredentialsParams) (oauth2.TokenSource, error) {
  140. switch f.Type {
  141. case serviceAccountKey:
  142. cfg := f.jwtConfig(params.Scopes, params.Subject)
  143. return cfg.TokenSource(ctx), nil
  144. case userCredentialsKey:
  145. cfg := &oauth2.Config{
  146. ClientID: f.ClientID,
  147. ClientSecret: f.ClientSecret,
  148. Scopes: params.Scopes,
  149. Endpoint: oauth2.Endpoint{
  150. AuthURL: f.AuthURL,
  151. TokenURL: f.TokenURL,
  152. AuthStyle: oauth2.AuthStyleInParams,
  153. },
  154. }
  155. if cfg.Endpoint.AuthURL == "" {
  156. cfg.Endpoint.AuthURL = Endpoint.AuthURL
  157. }
  158. if cfg.Endpoint.TokenURL == "" {
  159. cfg.Endpoint.TokenURL = Endpoint.TokenURL
  160. }
  161. tok := &oauth2.Token{RefreshToken: f.RefreshToken}
  162. return cfg.TokenSource(ctx, tok), nil
  163. case externalAccountKey:
  164. cfg := &externalaccount.Config{
  165. Audience: f.Audience,
  166. SubjectTokenType: f.SubjectTokenType,
  167. TokenURL: f.TokenURLExternal,
  168. TokenInfoURL: f.TokenInfoURL,
  169. ServiceAccountImpersonationURL: f.ServiceAccountImpersonationURL,
  170. ServiceAccountImpersonationLifetimeSeconds: f.ServiceAccountImpersonation.TokenLifetimeSeconds,
  171. ClientSecret: f.ClientSecret,
  172. ClientID: f.ClientID,
  173. CredentialSource: f.CredentialSource,
  174. QuotaProjectID: f.QuotaProjectID,
  175. Scopes: params.Scopes,
  176. WorkforcePoolUserProject: f.WorkforcePoolUserProject,
  177. }
  178. return cfg.TokenSource(ctx)
  179. case impersonatedServiceAccount:
  180. if f.ServiceAccountImpersonationURL == "" || f.SourceCredentials == nil {
  181. return nil, errors.New("missing 'source_credentials' field or 'service_account_impersonation_url' in credentials")
  182. }
  183. ts, err := f.SourceCredentials.tokenSource(ctx, params)
  184. if err != nil {
  185. return nil, err
  186. }
  187. imp := externalaccount.ImpersonateTokenSource{
  188. Ctx: ctx,
  189. URL: f.ServiceAccountImpersonationURL,
  190. Scopes: params.Scopes,
  191. Ts: ts,
  192. Delegates: f.Delegates,
  193. }
  194. return oauth2.ReuseTokenSource(nil, imp), nil
  195. case "":
  196. return nil, errors.New("missing 'type' field in credentials")
  197. default:
  198. return nil, fmt.Errorf("unknown credential type: %q", f.Type)
  199. }
  200. }
  201. // ComputeTokenSource returns a token source that fetches access tokens
  202. // from Google Compute Engine (GCE)'s metadata server. It's only valid to use
  203. // this token source if your program is running on a GCE instance.
  204. // If no account is specified, "default" is used.
  205. // If no scopes are specified, a set of default scopes are automatically granted.
  206. // Further information about retrieving access tokens from the GCE metadata
  207. // server can be found at https://cloud.google.com/compute/docs/authentication.
  208. func ComputeTokenSource(account string, scope ...string) oauth2.TokenSource {
  209. return oauth2.ReuseTokenSource(nil, computeSource{account: account, scopes: scope})
  210. }
  211. type computeSource struct {
  212. account string
  213. scopes []string
  214. }
  215. func (cs computeSource) Token() (*oauth2.Token, error) {
  216. if !metadata.OnGCE() {
  217. return nil, errors.New("oauth2/google: can't get a token from the metadata service; not running on GCE")
  218. }
  219. acct := cs.account
  220. if acct == "" {
  221. acct = "default"
  222. }
  223. tokenURI := "instance/service-accounts/" + acct + "/token"
  224. if len(cs.scopes) > 0 {
  225. v := url.Values{}
  226. v.Set("scopes", strings.Join(cs.scopes, ","))
  227. tokenURI = tokenURI + "?" + v.Encode()
  228. }
  229. tokenJSON, err := metadata.Get(tokenURI)
  230. if err != nil {
  231. return nil, err
  232. }
  233. var res struct {
  234. AccessToken string `json:"access_token"`
  235. ExpiresInSec int `json:"expires_in"`
  236. TokenType string `json:"token_type"`
  237. }
  238. err = json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res)
  239. if err != nil {
  240. return nil, fmt.Errorf("oauth2/google: invalid token JSON from metadata: %v", err)
  241. }
  242. if res.ExpiresInSec == 0 || res.AccessToken == "" {
  243. return nil, fmt.Errorf("oauth2/google: incomplete token received from metadata")
  244. }
  245. tok := &oauth2.Token{
  246. AccessToken: res.AccessToken,
  247. TokenType: res.TokenType,
  248. Expiry: time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second),
  249. }
  250. // NOTE(cbro): add hidden metadata about where the token is from.
  251. // This is needed for detection by client libraries to know that credentials come from the metadata server.
  252. // This may be removed in a future version of this library.
  253. return tok.WithExtra(map[string]interface{}{
  254. "oauth2.google.tokenSource": "compute-metadata",
  255. "oauth2.google.serviceAccount": acct,
  256. }), nil
  257. }