bootstrapsigner.go 9.0 KB

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