token_source.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package transport
  14. import (
  15. "fmt"
  16. "net/http"
  17. "os"
  18. "strings"
  19. "sync"
  20. "time"
  21. "golang.org/x/oauth2"
  22. utilnet "k8s.io/apimachinery/pkg/util/net"
  23. "k8s.io/klog/v2"
  24. )
  25. // TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens
  26. // authentication from an oauth2.TokenSource.
  27. func TokenSourceWrapTransport(ts oauth2.TokenSource) func(http.RoundTripper) http.RoundTripper {
  28. return func(rt http.RoundTripper) http.RoundTripper {
  29. return &tokenSourceTransport{
  30. base: rt,
  31. ort: &oauth2.Transport{
  32. Source: ts,
  33. Base: rt,
  34. },
  35. }
  36. }
  37. }
  38. type ResettableTokenSource interface {
  39. oauth2.TokenSource
  40. ResetTokenOlderThan(time.Time)
  41. }
  42. // ResettableTokenSourceWrapTransport returns a WrapTransport that injects bearer tokens
  43. // authentication from an ResettableTokenSource.
  44. func ResettableTokenSourceWrapTransport(ts ResettableTokenSource) func(http.RoundTripper) http.RoundTripper {
  45. return func(rt http.RoundTripper) http.RoundTripper {
  46. return &tokenSourceTransport{
  47. base: rt,
  48. ort: &oauth2.Transport{
  49. Source: ts,
  50. Base: rt,
  51. },
  52. src: ts,
  53. }
  54. }
  55. }
  56. // NewCachedFileTokenSource returns a resettable token source which reads a
  57. // token from a file at a specified path and periodically reloads it.
  58. func NewCachedFileTokenSource(path string) *cachingTokenSource {
  59. return &cachingTokenSource{
  60. now: time.Now,
  61. leeway: 10 * time.Second,
  62. base: &fileTokenSource{
  63. path: path,
  64. // This period was picked because it is half of the duration between when the kubelet
  65. // refreshes a projected service account token and when the original token expires.
  66. // Default token lifetime is 10 minutes, and the kubelet starts refreshing at 80% of lifetime.
  67. // This should induce re-reading at a frequency that works with the token volume source.
  68. period: time.Minute,
  69. },
  70. }
  71. }
  72. // NewCachedTokenSource returns resettable token source with caching. It reads
  73. // a token from a designed TokenSource if not in cache or expired.
  74. func NewCachedTokenSource(ts oauth2.TokenSource) *cachingTokenSource {
  75. return &cachingTokenSource{
  76. now: time.Now,
  77. base: ts,
  78. }
  79. }
  80. type tokenSourceTransport struct {
  81. base http.RoundTripper
  82. ort http.RoundTripper
  83. src ResettableTokenSource
  84. }
  85. var _ utilnet.RoundTripperWrapper = &tokenSourceTransport{}
  86. func (tst *tokenSourceTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  87. // This is to allow --token to override other bearer token providers.
  88. if req.Header.Get("Authorization") != "" {
  89. return tst.base.RoundTrip(req)
  90. }
  91. // record time before RoundTrip to make sure newly acquired Unauthorized
  92. // token would not be reset. Another request from user is required to reset
  93. // and proceed.
  94. start := time.Now()
  95. resp, err := tst.ort.RoundTrip(req)
  96. if err == nil && resp != nil && resp.StatusCode == 401 && tst.src != nil {
  97. tst.src.ResetTokenOlderThan(start)
  98. }
  99. return resp, err
  100. }
  101. func (tst *tokenSourceTransport) CancelRequest(req *http.Request) {
  102. if req.Header.Get("Authorization") != "" {
  103. tryCancelRequest(tst.base, req)
  104. return
  105. }
  106. tryCancelRequest(tst.ort, req)
  107. }
  108. func (tst *tokenSourceTransport) WrappedRoundTripper() http.RoundTripper { return tst.base }
  109. type fileTokenSource struct {
  110. path string
  111. period time.Duration
  112. }
  113. var _ = oauth2.TokenSource(&fileTokenSource{})
  114. func (ts *fileTokenSource) Token() (*oauth2.Token, error) {
  115. tokb, err := os.ReadFile(ts.path)
  116. if err != nil {
  117. return nil, fmt.Errorf("failed to read token file %q: %v", ts.path, err)
  118. }
  119. tok := strings.TrimSpace(string(tokb))
  120. if len(tok) == 0 {
  121. return nil, fmt.Errorf("read empty token from file %q", ts.path)
  122. }
  123. return &oauth2.Token{
  124. AccessToken: tok,
  125. Expiry: time.Now().Add(ts.period),
  126. }, nil
  127. }
  128. type cachingTokenSource struct {
  129. base oauth2.TokenSource
  130. leeway time.Duration
  131. sync.RWMutex
  132. tok *oauth2.Token
  133. t time.Time
  134. // for testing
  135. now func() time.Time
  136. }
  137. func (ts *cachingTokenSource) Token() (*oauth2.Token, error) {
  138. now := ts.now()
  139. // fast path
  140. ts.RLock()
  141. tok := ts.tok
  142. ts.RUnlock()
  143. if tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {
  144. return tok, nil
  145. }
  146. // slow path
  147. ts.Lock()
  148. defer ts.Unlock()
  149. if tok := ts.tok; tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {
  150. return tok, nil
  151. }
  152. tok, err := ts.base.Token()
  153. if err != nil {
  154. if ts.tok == nil {
  155. return nil, err
  156. }
  157. klog.Errorf("Unable to rotate token: %v", err)
  158. return ts.tok, nil
  159. }
  160. ts.t = ts.now()
  161. ts.tok = tok
  162. return tok, nil
  163. }
  164. func (ts *cachingTokenSource) ResetTokenOlderThan(t time.Time) {
  165. ts.Lock()
  166. defer ts.Unlock()
  167. if ts.t.Before(t) {
  168. ts.tok = nil
  169. ts.t = time.Time{}
  170. }
  171. }