token_source.go 4.9 KB

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