token_manager.go 5.1 KB

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