bootstrapsigner.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /*
  2. Copyright 2016 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 bootstrap
  14. import (
  15. "context"
  16. "strings"
  17. "time"
  18. "k8s.io/klog"
  19. "fmt"
  20. v1 "k8s.io/api/core/v1"
  21. apierrors "k8s.io/apimachinery/pkg/api/errors"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/labels"
  24. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  25. "k8s.io/apimachinery/pkg/util/wait"
  26. informers "k8s.io/client-go/informers/core/v1"
  27. clientset "k8s.io/client-go/kubernetes"
  28. corelisters "k8s.io/client-go/listers/core/v1"
  29. "k8s.io/client-go/tools/cache"
  30. "k8s.io/client-go/util/workqueue"
  31. bootstrapapi "k8s.io/cluster-bootstrap/token/api"
  32. jws "k8s.io/cluster-bootstrap/token/jws"
  33. "k8s.io/component-base/metrics/prometheus/ratelimiter"
  34. api "k8s.io/kubernetes/pkg/apis/core"
  35. )
  36. // SignerOptions contains options for the Signer
  37. type SignerOptions struct {
  38. // ConfigMapNamespace is the namespace of the ConfigMap
  39. ConfigMapNamespace string
  40. // ConfigMapName is the name for the ConfigMap
  41. ConfigMapName string
  42. // TokenSecretNamespace string is the namespace for token Secrets.
  43. TokenSecretNamespace string
  44. // ConfigMapResynce is the time.Duration at which to fully re-list configmaps.
  45. // If zero, re-list will be delayed as long as possible
  46. ConfigMapResync time.Duration
  47. // SecretResync is the time.Duration at which to fully re-list secrets.
  48. // If zero, re-list will be delayed as long as possible
  49. SecretResync time.Duration
  50. }
  51. // DefaultSignerOptions returns a set of default options for creating a Signer.
  52. func DefaultSignerOptions() SignerOptions {
  53. return SignerOptions{
  54. ConfigMapNamespace: api.NamespacePublic,
  55. ConfigMapName: bootstrapapi.ConfigMapClusterInfo,
  56. TokenSecretNamespace: api.NamespaceSystem,
  57. }
  58. }
  59. // Signer is a controller that signs a ConfigMap with a set of tokens.
  60. type Signer struct {
  61. client clientset.Interface
  62. configMapKey string
  63. configMapName string
  64. configMapNamespace string
  65. secretNamespace string
  66. // syncQueue handles synchronizing updates to the ConfigMap. We'll only ever
  67. // have one item (Named <ConfigMapName>) in this queue. We are using it
  68. // serializes and collapses updates as they can come from both the ConfigMap
  69. // and Secrets controllers.
  70. syncQueue workqueue.RateLimitingInterface
  71. secretLister corelisters.SecretLister
  72. secretSynced cache.InformerSynced
  73. configMapLister corelisters.ConfigMapLister
  74. configMapSynced cache.InformerSynced
  75. }
  76. // NewSigner returns a new *Signer.
  77. func NewSigner(cl clientset.Interface, secrets informers.SecretInformer, configMaps informers.ConfigMapInformer, options SignerOptions) (*Signer, error) {
  78. e := &Signer{
  79. client: cl,
  80. configMapKey: options.ConfigMapNamespace + "/" + options.ConfigMapName,
  81. configMapName: options.ConfigMapName,
  82. configMapNamespace: options.ConfigMapNamespace,
  83. secretNamespace: options.TokenSecretNamespace,
  84. secretLister: secrets.Lister(),
  85. secretSynced: secrets.Informer().HasSynced,
  86. configMapLister: configMaps.Lister(),
  87. configMapSynced: configMaps.Informer().HasSynced,
  88. syncQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "bootstrap_signer_queue"),
  89. }
  90. if cl.CoreV1().RESTClient().GetRateLimiter() != nil {
  91. if err := ratelimiter.RegisterMetricAndTrackRateLimiterUsage("bootstrap_signer", cl.CoreV1().RESTClient().GetRateLimiter()); err != nil {
  92. return nil, err
  93. }
  94. }
  95. configMaps.Informer().AddEventHandlerWithResyncPeriod(
  96. cache.FilteringResourceEventHandler{
  97. FilterFunc: func(obj interface{}) bool {
  98. switch t := obj.(type) {
  99. case *v1.ConfigMap:
  100. return t.Name == options.ConfigMapName && t.Namespace == options.ConfigMapNamespace
  101. default:
  102. utilruntime.HandleError(fmt.Errorf("object passed to %T that is not expected: %T", e, obj))
  103. return false
  104. }
  105. },
  106. Handler: cache.ResourceEventHandlerFuncs{
  107. AddFunc: func(_ interface{}) { e.pokeConfigMapSync() },
  108. UpdateFunc: func(_, _ interface{}) { e.pokeConfigMapSync() },
  109. },
  110. },
  111. options.ConfigMapResync,
  112. )
  113. secrets.Informer().AddEventHandlerWithResyncPeriod(
  114. cache.FilteringResourceEventHandler{
  115. FilterFunc: func(obj interface{}) bool {
  116. switch t := obj.(type) {
  117. case *v1.Secret:
  118. return t.Type == bootstrapapi.SecretTypeBootstrapToken && t.Namespace == e.secretNamespace
  119. default:
  120. utilruntime.HandleError(fmt.Errorf("object passed to %T that is not expected: %T", e, obj))
  121. return false
  122. }
  123. },
  124. Handler: cache.ResourceEventHandlerFuncs{
  125. AddFunc: func(_ interface{}) { e.pokeConfigMapSync() },
  126. UpdateFunc: func(_, _ interface{}) { e.pokeConfigMapSync() },
  127. DeleteFunc: func(_ interface{}) { e.pokeConfigMapSync() },
  128. },
  129. },
  130. options.SecretResync,
  131. )
  132. return e, nil
  133. }
  134. // Run runs controller loops and returns when they are done
  135. func (e *Signer) Run(stopCh <-chan struct{}) {
  136. // Shut down queues
  137. defer utilruntime.HandleCrash()
  138. defer e.syncQueue.ShutDown()
  139. if !cache.WaitForNamedCacheSync("bootstrap_signer", stopCh, e.configMapSynced, e.secretSynced) {
  140. return
  141. }
  142. klog.V(5).Infof("Starting workers")
  143. go wait.Until(e.serviceConfigMapQueue, 0, stopCh)
  144. <-stopCh
  145. klog.V(1).Infof("Shutting down")
  146. }
  147. func (e *Signer) pokeConfigMapSync() {
  148. e.syncQueue.Add(e.configMapKey)
  149. }
  150. func (e *Signer) serviceConfigMapQueue() {
  151. key, quit := e.syncQueue.Get()
  152. if quit {
  153. return
  154. }
  155. defer e.syncQueue.Done(key)
  156. e.signConfigMap()
  157. }
  158. // signConfigMap computes the signatures on our latest cached objects and writes
  159. // back if necessary.
  160. func (e *Signer) signConfigMap() {
  161. origCM := e.getConfigMap()
  162. if origCM == nil {
  163. return
  164. }
  165. var needUpdate = false
  166. newCM := origCM.DeepCopy()
  167. // First capture the config we are signing
  168. content, ok := newCM.Data[bootstrapapi.KubeConfigKey]
  169. if !ok {
  170. klog.V(3).Infof("No %s key in %s/%s ConfigMap", bootstrapapi.KubeConfigKey, origCM.Namespace, origCM.Name)
  171. return
  172. }
  173. // Next remove and save all existing signatures
  174. sigs := map[string]string{}
  175. for key, value := range newCM.Data {
  176. if strings.HasPrefix(key, bootstrapapi.JWSSignatureKeyPrefix) {
  177. tokenID := strings.TrimPrefix(key, bootstrapapi.JWSSignatureKeyPrefix)
  178. sigs[tokenID] = value
  179. delete(newCM.Data, key)
  180. }
  181. }
  182. // Now recompute signatures and store them on the new map
  183. tokens := e.getTokens()
  184. for tokenID, tokenValue := range tokens {
  185. sig, err := jws.ComputeDetachedSignature(content, tokenID, tokenValue)
  186. if err != nil {
  187. utilruntime.HandleError(err)
  188. }
  189. // Check to see if this signature is changed or new.
  190. oldSig, _ := sigs[tokenID]
  191. if sig != oldSig {
  192. needUpdate = true
  193. }
  194. delete(sigs, tokenID)
  195. newCM.Data[bootstrapapi.JWSSignatureKeyPrefix+tokenID] = sig
  196. }
  197. // If we have signatures left over we know that some signatures were
  198. // removed. We now need to update the ConfigMap
  199. if len(sigs) != 0 {
  200. needUpdate = true
  201. }
  202. if needUpdate {
  203. e.updateConfigMap(newCM)
  204. }
  205. }
  206. func (e *Signer) updateConfigMap(cm *v1.ConfigMap) {
  207. _, err := e.client.CoreV1().ConfigMaps(cm.Namespace).Update(context.TODO(), cm, metav1.UpdateOptions{})
  208. if err != nil && !apierrors.IsConflict(err) && !apierrors.IsNotFound(err) {
  209. klog.V(3).Infof("Error updating ConfigMap: %v", err)
  210. }
  211. }
  212. // getConfigMap gets the ConfigMap we are interested in
  213. func (e *Signer) getConfigMap() *v1.ConfigMap {
  214. configMap, err := e.configMapLister.ConfigMaps(e.configMapNamespace).Get(e.configMapName)
  215. // If we can't get the configmap just return nil. The resync will eventually
  216. // sync things up.
  217. if err != nil {
  218. if !apierrors.IsNotFound(err) {
  219. utilruntime.HandleError(err)
  220. }
  221. return nil
  222. }
  223. return configMap
  224. }
  225. func (e *Signer) listSecrets() []*v1.Secret {
  226. secrets, err := e.secretLister.Secrets(e.secretNamespace).List(labels.Everything())
  227. if err != nil {
  228. utilruntime.HandleError(err)
  229. return nil
  230. }
  231. items := []*v1.Secret{}
  232. for _, secret := range secrets {
  233. if secret.Type == bootstrapapi.SecretTypeBootstrapToken {
  234. items = append(items, secret)
  235. }
  236. }
  237. return items
  238. }
  239. // getTokens returns a map of tokenID->tokenSecret. It ensures the token is
  240. // valid for signing.
  241. func (e *Signer) getTokens() map[string]string {
  242. ret := map[string]string{}
  243. secretObjs := e.listSecrets()
  244. for _, secret := range secretObjs {
  245. tokenID, tokenSecret, ok := validateSecretForSigning(secret)
  246. if !ok {
  247. continue
  248. }
  249. // Check and warn for duplicate secrets. Behavior here will be undefined.
  250. if _, ok := ret[tokenID]; ok {
  251. // This should never happen as we ensure a consistent secret name.
  252. // But leave this in here just in case.
  253. klog.V(1).Infof("Duplicate bootstrap tokens found for id %s, ignoring on in %s/%s", tokenID, secret.Namespace, secret.Name)
  254. continue
  255. }
  256. // This secret looks good, add it to the list.
  257. ret[tokenID] = tokenSecret
  258. }
  259. return ret
  260. }