impersonate.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package impersonate
  15. import (
  16. "bytes"
  17. "context"
  18. "encoding/json"
  19. "errors"
  20. "fmt"
  21. "net/http"
  22. "time"
  23. "cloud.google.com/go/auth"
  24. "cloud.google.com/go/auth/internal"
  25. )
  26. const (
  27. defaultTokenLifetime = "3600s"
  28. authHeaderKey = "Authorization"
  29. )
  30. // generateAccesstokenReq is used for service account impersonation
  31. type generateAccessTokenReq struct {
  32. Delegates []string `json:"delegates,omitempty"`
  33. Lifetime string `json:"lifetime,omitempty"`
  34. Scope []string `json:"scope,omitempty"`
  35. }
  36. type impersonateTokenResponse struct {
  37. AccessToken string `json:"accessToken"`
  38. ExpireTime string `json:"expireTime"`
  39. }
  40. // NewTokenProvider uses a source credential, stored in Ts, to request an access token to the provided URL.
  41. // Scopes can be defined when the access token is requested.
  42. func NewTokenProvider(opts *Options) (auth.TokenProvider, error) {
  43. if err := opts.validate(); err != nil {
  44. return nil, err
  45. }
  46. return opts, nil
  47. }
  48. // Options for [NewTokenProvider].
  49. type Options struct {
  50. // Tp is the source credential used to generate a token on the
  51. // impersonated service account. Required.
  52. Tp auth.TokenProvider
  53. // URL is the endpoint to call to generate a token
  54. // on behalf of the service account. Required.
  55. URL string
  56. // Scopes that the impersonated credential should have. Required.
  57. Scopes []string
  58. // Delegates are the service account email addresses in a delegation chain.
  59. // Each service account must be granted roles/iam.serviceAccountTokenCreator
  60. // on the next service account in the chain. Optional.
  61. Delegates []string
  62. // TokenLifetimeSeconds is the number of seconds the impersonation token will
  63. // be valid for. Defaults to 1 hour if unset. Optional.
  64. TokenLifetimeSeconds int
  65. // Client configures the underlying client used to make network requests
  66. // when fetching tokens. Required.
  67. Client *http.Client
  68. }
  69. func (o *Options) validate() error {
  70. if o.Tp == nil {
  71. return errors.New("credentials: missing required 'source_credentials' field in impersonated credentials")
  72. }
  73. if o.URL == "" {
  74. return errors.New("credentials: missing required 'service_account_impersonation_url' field in impersonated credentials")
  75. }
  76. return nil
  77. }
  78. // Token performs the exchange to get a temporary service account token to allow access to GCP.
  79. func (o *Options) Token(ctx context.Context) (*auth.Token, error) {
  80. lifetime := defaultTokenLifetime
  81. if o.TokenLifetimeSeconds != 0 {
  82. lifetime = fmt.Sprintf("%ds", o.TokenLifetimeSeconds)
  83. }
  84. reqBody := generateAccessTokenReq{
  85. Lifetime: lifetime,
  86. Scope: o.Scopes,
  87. Delegates: o.Delegates,
  88. }
  89. b, err := json.Marshal(reqBody)
  90. if err != nil {
  91. return nil, fmt.Errorf("credentials: unable to marshal request: %w", err)
  92. }
  93. req, err := http.NewRequestWithContext(ctx, "POST", o.URL, bytes.NewReader(b))
  94. if err != nil {
  95. return nil, fmt.Errorf("credentials: unable to create impersonation request: %w", err)
  96. }
  97. req.Header.Set("Content-Type", "application/json")
  98. if err := setAuthHeader(ctx, o.Tp, req); err != nil {
  99. return nil, err
  100. }
  101. resp, body, err := internal.DoRequest(o.Client, req)
  102. if err != nil {
  103. return nil, fmt.Errorf("credentials: unable to generate access token: %w", err)
  104. }
  105. if c := resp.StatusCode; c < http.StatusOK || c >= http.StatusMultipleChoices {
  106. return nil, fmt.Errorf("credentials: status code %d: %s", c, body)
  107. }
  108. var accessTokenResp impersonateTokenResponse
  109. if err := json.Unmarshal(body, &accessTokenResp); err != nil {
  110. return nil, fmt.Errorf("credentials: unable to parse response: %w", err)
  111. }
  112. expiry, err := time.Parse(time.RFC3339, accessTokenResp.ExpireTime)
  113. if err != nil {
  114. return nil, fmt.Errorf("credentials: unable to parse expiry: %w", err)
  115. }
  116. return &auth.Token{
  117. Value: accessTokenResp.AccessToken,
  118. Expiry: expiry,
  119. Type: internal.TokenTypeBearer,
  120. }, nil
  121. }
  122. func setAuthHeader(ctx context.Context, tp auth.TokenProvider, r *http.Request) error {
  123. t, err := tp.Token(ctx)
  124. if err != nil {
  125. return err
  126. }
  127. typ := t.Type
  128. if typ == "" {
  129. typ = internal.TokenTypeBearer
  130. }
  131. r.Header.Set(authHeaderKey, typ+" "+t.Value)
  132. return nil
  133. }