token_source.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. // NewCachedFileTokenSource returns a oauth2.TokenSource reads a token from a
  38. // file at a specified path and periodically reloads it.
  39. func NewCachedFileTokenSource(path string) oauth2.TokenSource {
  40. return &cachingTokenSource{
  41. now: time.Now,
  42. leeway: 10 * time.Second,
  43. base: &fileTokenSource{
  44. path: path,
  45. // This period was picked because it is half of the duration between when the kubelet
  46. // refreshes a projected service account token and when the original token expires.
  47. // Default token lifetime is 10 minutes, and the kubelet starts refreshing at 80% of lifetime.
  48. // This should induce re-reading at a frequency that works with the token volume source.
  49. period: time.Minute,
  50. },
  51. }
  52. }
  53. // NewCachedTokenSource returns a oauth2.TokenSource reads a token from a
  54. // designed TokenSource. The ts would provide the source of token.
  55. func NewCachedTokenSource(ts oauth2.TokenSource) oauth2.TokenSource {
  56. return &cachingTokenSource{
  57. now: time.Now,
  58. base: ts,
  59. }
  60. }
  61. type tokenSourceTransport struct {
  62. base http.RoundTripper
  63. ort http.RoundTripper
  64. }
  65. func (tst *tokenSourceTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  66. // This is to allow --token to override other bearer token providers.
  67. if req.Header.Get("Authorization") != "" {
  68. return tst.base.RoundTrip(req)
  69. }
  70. return tst.ort.RoundTrip(req)
  71. }
  72. func (tst *tokenSourceTransport) CancelRequest(req *http.Request) {
  73. if req.Header.Get("Authorization") != "" {
  74. tryCancelRequest(tst.base, req)
  75. return
  76. }
  77. tryCancelRequest(tst.ort, req)
  78. }
  79. type fileTokenSource struct {
  80. path string
  81. period time.Duration
  82. }
  83. var _ = oauth2.TokenSource(&fileTokenSource{})
  84. func (ts *fileTokenSource) Token() (*oauth2.Token, error) {
  85. tokb, err := ioutil.ReadFile(ts.path)
  86. if err != nil {
  87. return nil, fmt.Errorf("failed to read token file %q: %v", ts.path, err)
  88. }
  89. tok := strings.TrimSpace(string(tokb))
  90. if len(tok) == 0 {
  91. return nil, fmt.Errorf("read empty token from file %q", ts.path)
  92. }
  93. return &oauth2.Token{
  94. AccessToken: tok,
  95. Expiry: time.Now().Add(ts.period),
  96. }, nil
  97. }
  98. type cachingTokenSource struct {
  99. base oauth2.TokenSource
  100. leeway time.Duration
  101. sync.RWMutex
  102. tok *oauth2.Token
  103. // for testing
  104. now func() time.Time
  105. }
  106. var _ = oauth2.TokenSource(&cachingTokenSource{})
  107. func (ts *cachingTokenSource) Token() (*oauth2.Token, error) {
  108. now := ts.now()
  109. // fast path
  110. ts.RLock()
  111. tok := ts.tok
  112. ts.RUnlock()
  113. if tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {
  114. return tok, nil
  115. }
  116. // slow path
  117. ts.Lock()
  118. defer ts.Unlock()
  119. if tok := ts.tok; tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {
  120. return tok, nil
  121. }
  122. tok, err := ts.base.Token()
  123. if err != nil {
  124. if ts.tok == nil {
  125. return nil, err
  126. }
  127. klog.Errorf("Unable to rotate token: %v", err)
  128. return ts.tok, nil
  129. }
  130. ts.tok = tok
  131. return tok, nil
  132. }