google.go 11 KB

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