token_manager.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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 token implements a manager of serviceaccount tokens for pods running
  14. // on the node.
  15. package token
  16. import (
  17. "context"
  18. "errors"
  19. "fmt"
  20. "sync"
  21. "time"
  22. authenticationv1 "k8s.io/api/authentication/v1"
  23. apierrors "k8s.io/apimachinery/pkg/api/errors"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/types"
  26. "k8s.io/apimachinery/pkg/util/clock"
  27. "k8s.io/apimachinery/pkg/util/wait"
  28. clientset "k8s.io/client-go/kubernetes"
  29. "k8s.io/klog"
  30. )
  31. const (
  32. maxTTL = 24 * time.Hour
  33. gcPeriod = time.Minute
  34. )
  35. // NewManager returns a new token manager.
  36. func NewManager(c clientset.Interface) *Manager {
  37. // check whether the server supports token requests so we can give a more helpful error message
  38. supported := false
  39. once := &sync.Once{}
  40. tokenRequestsSupported := func() bool {
  41. once.Do(func() {
  42. resources, err := c.Discovery().ServerResourcesForGroupVersion("v1")
  43. if err != nil {
  44. return
  45. }
  46. for _, resource := range resources.APIResources {
  47. if resource.Name == "serviceaccounts/token" {
  48. supported = true
  49. return
  50. }
  51. }
  52. })
  53. return supported
  54. }
  55. m := &Manager{
  56. getToken: func(name, namespace string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {
  57. if c == nil {
  58. return nil, errors.New("cannot use TokenManager when kubelet is in standalone mode")
  59. }
  60. tokenRequest, err := c.CoreV1().ServiceAccounts(namespace).CreateToken(context.TODO(), name, tr, metav1.CreateOptions{})
  61. if apierrors.IsNotFound(err) && !tokenRequestsSupported() {
  62. return nil, fmt.Errorf("the API server does not have TokenRequest endpoints enabled")
  63. }
  64. return tokenRequest, err
  65. },
  66. cache: make(map[string]*authenticationv1.TokenRequest),
  67. clock: clock.RealClock{},
  68. }
  69. go wait.Forever(m.cleanup, gcPeriod)
  70. return m
  71. }
  72. // Manager manages service account tokens for pods.
  73. type Manager struct {
  74. // cacheMutex guards the cache
  75. cacheMutex sync.RWMutex
  76. cache map[string]*authenticationv1.TokenRequest
  77. // mocked for testing
  78. getToken func(name, namespace string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error)
  79. clock clock.Clock
  80. }
  81. // GetServiceAccountToken gets a service account token for a pod from cache or
  82. // from the TokenRequest API. This process is as follows:
  83. // * Check the cache for the current token request.
  84. // * If the token exists and does not require a refresh, return the current token.
  85. // * Attempt to refresh the token.
  86. // * If the token is refreshed successfully, save it in the cache and return the token.
  87. // * If refresh fails and the old token is still valid, log an error and return the old token.
  88. // * If refresh fails and the old token is no longer valid, return an error
  89. func (m *Manager) GetServiceAccountToken(namespace, name string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {
  90. key := keyFunc(name, namespace, tr)
  91. ctr, ok := m.get(key)
  92. if ok && !m.requiresRefresh(ctr) {
  93. return ctr, nil
  94. }
  95. tr, err := m.getToken(name, namespace, tr)
  96. if err != nil {
  97. switch {
  98. case !ok:
  99. return nil, fmt.Errorf("failed to fetch token: %v", err)
  100. case m.expired(ctr):
  101. return nil, fmt.Errorf("token %s expired and refresh failed: %v", key, err)
  102. default:
  103. klog.Errorf("couldn't update token %s: %v", key, err)
  104. return ctr, nil
  105. }
  106. }
  107. m.set(key, tr)
  108. return tr, nil
  109. }
  110. // DeleteServiceAccountToken should be invoked when pod got deleted. It simply
  111. // clean token manager cache.
  112. func (m *Manager) DeleteServiceAccountToken(podUID types.UID) {
  113. m.cacheMutex.Lock()
  114. defer m.cacheMutex.Unlock()
  115. for k, tr := range m.cache {
  116. if tr.Spec.BoundObjectRef.UID == podUID {
  117. delete(m.cache, k)
  118. }
  119. }
  120. }
  121. func (m *Manager) cleanup() {
  122. m.cacheMutex.Lock()
  123. defer m.cacheMutex.Unlock()
  124. for k, tr := range m.cache {
  125. if m.expired(tr) {
  126. delete(m.cache, k)
  127. }
  128. }
  129. }
  130. func (m *Manager) get(key string) (*authenticationv1.TokenRequest, bool) {
  131. m.cacheMutex.RLock()
  132. defer m.cacheMutex.RUnlock()
  133. ctr, ok := m.cache[key]
  134. return ctr, ok
  135. }
  136. func (m *Manager) set(key string, tr *authenticationv1.TokenRequest) {
  137. m.cacheMutex.Lock()
  138. defer m.cacheMutex.Unlock()
  139. m.cache[key] = tr
  140. }
  141. func (m *Manager) expired(t *authenticationv1.TokenRequest) bool {
  142. return m.clock.Now().After(t.Status.ExpirationTimestamp.Time)
  143. }
  144. // requiresRefresh returns true if the token is older than 80% of its total
  145. // ttl, or if the token is older than 24 hours.
  146. func (m *Manager) requiresRefresh(tr *authenticationv1.TokenRequest) bool {
  147. if tr.Spec.ExpirationSeconds == nil {
  148. klog.Errorf("expiration seconds was nil for tr: %#v", tr)
  149. return false
  150. }
  151. now := m.clock.Now()
  152. exp := tr.Status.ExpirationTimestamp.Time
  153. iat := exp.Add(-1 * time.Duration(*tr.Spec.ExpirationSeconds) * time.Second)
  154. if now.After(iat.Add(maxTTL)) {
  155. return true
  156. }
  157. // Require a refresh if within 20% of the TTL from the expiration time.
  158. if now.After(exp.Add(-1 * time.Duration((*tr.Spec.ExpirationSeconds*20)/100) * time.Second)) {
  159. return true
  160. }
  161. return false
  162. }
  163. // keys should be nonconfidential and safe to log
  164. func keyFunc(name, namespace string, tr *authenticationv1.TokenRequest) string {
  165. var exp int64
  166. if tr.Spec.ExpirationSeconds != nil {
  167. exp = *tr.Spec.ExpirationSeconds
  168. }
  169. var ref authenticationv1.BoundObjectReference
  170. if tr.Spec.BoundObjectRef != nil {
  171. ref = *tr.Spec.BoundObjectRef
  172. }
  173. return fmt.Sprintf("%q/%q/%#v/%#v/%#v", name, namespace, tr.Spec.Audiences, exp, ref)
  174. }