google.go 10.0 KB

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