file.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 file
  14. import (
  15. "context"
  16. "time"
  17. "github.com/pkg/errors"
  18. v1 "k8s.io/api/core/v1"
  19. apierrors "k8s.io/apimachinery/pkg/api/errors"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/util/wait"
  22. "k8s.io/client-go/tools/clientcmd"
  23. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  24. bootstrapapi "k8s.io/cluster-bootstrap/token/api"
  25. "k8s.io/klog"
  26. "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  27. kubeconfigutil "k8s.io/kubernetes/cmd/kubeadm/app/util/kubeconfig"
  28. )
  29. // RetrieveValidatedConfigInfo connects to the API Server and makes sure it can talk
  30. // securely to the API Server using the provided CA cert and
  31. // optionally refreshes the cluster-info information from the cluster-info ConfigMap
  32. func RetrieveValidatedConfigInfo(filepath, clustername string, discoveryTimeout time.Duration) (*clientcmdapi.Config, error) {
  33. config, err := clientcmd.LoadFromFile(filepath)
  34. if err != nil {
  35. return nil, err
  36. }
  37. return ValidateConfigInfo(config, clustername, discoveryTimeout)
  38. }
  39. // ValidateConfigInfo connects to the API Server and makes sure it can talk
  40. // securely to the API Server using the provided CA cert/client certificates and
  41. // optionally refreshes the cluster-info information from the cluster-info ConfigMap
  42. func ValidateConfigInfo(config *clientcmdapi.Config, clustername string, discoveryTimeout time.Duration) (*clientcmdapi.Config, error) {
  43. if len(config.Clusters) < 1 {
  44. return nil, errors.New("the provided kubeconfig file must have at least one Cluster defined")
  45. }
  46. currentCluster := kubeconfigutil.GetClusterFromKubeConfig(config)
  47. if currentCluster == nil {
  48. return nil, errors.New("the provided kubeconfig file must have a unnamed Cluster or a CurrentContext that specifies a non-nil Cluster")
  49. }
  50. if err := clientcmd.Validate(*config); err != nil {
  51. return nil, err
  52. }
  53. // If the kubeconfig points to a file for the CA, make sure the CA file contents are embedded
  54. if err := kubeconfigutil.EnsureCertificateAuthorityIsEmbedded(currentCluster); err != nil {
  55. return nil, err
  56. }
  57. // If the discovery file config contains authentication credentials
  58. if kubeconfigutil.HasAuthenticationCredentials(config) {
  59. klog.V(1).Info("[discovery] Using authentication credentials from the discovery file for validating TLS connection")
  60. // We should ensure that all the authentication info is embedded in config file, so everything will work also when
  61. // the kubeconfig file will be stored in /etc/kubernetes/boostrap-kubelet.conf
  62. if err := kubeconfigutil.EnsureAuthenticationInfoAreEmbedded(config); err != nil {
  63. return nil, err
  64. }
  65. } else {
  66. // If the discovery file config does not contains authentication credentials
  67. klog.V(1).Info("[discovery] Discovery file does not contains authentication credentials, using unauthenticated request for validating TLS connection")
  68. // Create a new kubeconfig object from the discovery file config, with only the server and the CA cert.
  69. // NB. We do this in order to not pick up other possible misconfigurations in the clusterinfo file
  70. config = kubeconfigutil.CreateBasic(
  71. currentCluster.Server,
  72. clustername,
  73. "", // no user provided
  74. currentCluster.CertificateAuthorityData,
  75. )
  76. }
  77. // Try to read the cluster-info config map; this step was required by the original design in order
  78. // to validate the TLS connection to the server early in the process
  79. client, err := kubeconfigutil.ToClientSet(config)
  80. if err != nil {
  81. return nil, err
  82. }
  83. klog.V(1).Infof("[discovery] Created cluster-info discovery client, requesting info from %q\n", currentCluster.Server)
  84. var clusterinfoCM *v1.ConfigMap
  85. err = wait.Poll(constants.DiscoveryRetryInterval, discoveryTimeout, func() (bool, error) {
  86. var err error
  87. clusterinfoCM, err = client.CoreV1().ConfigMaps(metav1.NamespacePublic).Get(context.TODO(), bootstrapapi.ConfigMapClusterInfo, metav1.GetOptions{})
  88. if err != nil {
  89. if apierrors.IsForbidden(err) {
  90. // If the request is unauthorized, the cluster admin has not granted access to the cluster info configmap for unauthenticated users
  91. // In that case, trust the cluster admin and do not refresh the cluster-info data
  92. klog.Warningf("[discovery] Could not access the %s ConfigMap for refreshing the cluster-info information, but the TLS cert is valid so proceeding...\n", bootstrapapi.ConfigMapClusterInfo)
  93. return true, nil
  94. }
  95. klog.V(1).Infof("[discovery] Error reading the %s ConfigMap, will try again: %v\n", bootstrapapi.ConfigMapClusterInfo, err)
  96. return false, nil
  97. }
  98. return true, nil
  99. })
  100. if err == wait.ErrWaitTimeout {
  101. return nil, errors.Errorf("Abort reading the %s ConfigMap after timeout of %v", bootstrapapi.ConfigMapClusterInfo, discoveryTimeout)
  102. }
  103. // If we couldn't fetch the cluster-info ConfigMap, just return the cluster-info object the user provided
  104. if clusterinfoCM == nil {
  105. return config, nil
  106. }
  107. // We somehow got hold of the ConfigMap, try to read some data from it. If we can't, fallback on the user-provided file
  108. refreshedBaseKubeConfig, err := tryParseClusterInfoFromConfigMap(clusterinfoCM)
  109. if err != nil {
  110. klog.V(1).Infof("[discovery] The %s ConfigMap isn't set up properly (%v), but the TLS cert is valid so proceeding...\n", bootstrapapi.ConfigMapClusterInfo, err)
  111. return config, nil
  112. }
  113. refreshedCluster := kubeconfigutil.GetClusterFromKubeConfig(refreshedBaseKubeConfig)
  114. currentCluster.Server = refreshedCluster.Server
  115. currentCluster.CertificateAuthorityData = refreshedCluster.CertificateAuthorityData
  116. klog.V(1).Infof("[discovery] Synced Server and CertificateAuthorityData from the %s ConfigMap", bootstrapapi.ConfigMapClusterInfo)
  117. return config, nil
  118. }
  119. // tryParseClusterInfoFromConfigMap tries to parse a kubeconfig file from a ConfigMap key
  120. func tryParseClusterInfoFromConfigMap(cm *v1.ConfigMap) (*clientcmdapi.Config, error) {
  121. kubeConfigString, ok := cm.Data[bootstrapapi.KubeConfigKey]
  122. if !ok || len(kubeConfigString) == 0 {
  123. return nil, errors.Errorf("no %s key in ConfigMap", bootstrapapi.KubeConfigKey)
  124. }
  125. parsedKubeConfig, err := clientcmd.Load([]byte(kubeConfigString))
  126. if err != nil {
  127. return nil, errors.Wrapf(err, "couldn't parse the kubeconfig file in the %s ConfigMap", bootstrapapi.ConfigMapClusterInfo)
  128. }
  129. return parsedKubeConfig, nil
  130. }