kubeconfig_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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 kubeconfig
  14. import (
  15. "bytes"
  16. "crypto"
  17. "crypto/x509"
  18. "fmt"
  19. "io"
  20. "os"
  21. "path/filepath"
  22. "reflect"
  23. "testing"
  24. "github.com/lithammer/dedent"
  25. "k8s.io/client-go/tools/clientcmd"
  26. clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
  27. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  28. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  29. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  30. certstestutil "k8s.io/kubernetes/cmd/kubeadm/app/util/certs"
  31. pkiutil "k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil"
  32. testutil "k8s.io/kubernetes/cmd/kubeadm/test"
  33. kubeconfigtestutil "k8s.io/kubernetes/cmd/kubeadm/test/kubeconfig"
  34. )
  35. func TestGetKubeConfigSpecsFailsIfCADoesntExists(t *testing.T) {
  36. // Create temp folder for the test case (without a CA)
  37. tmpdir := testutil.SetupTempDir(t)
  38. defer os.RemoveAll(tmpdir)
  39. // Creates an InitConfiguration pointing to the pkidir folder
  40. cfg := &kubeadmapi.InitConfiguration{
  41. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  42. CertificatesDir: tmpdir,
  43. },
  44. }
  45. // Executes getKubeConfigSpecs
  46. if _, err := getKubeConfigSpecs(cfg); err == nil {
  47. t.Error("getKubeConfigSpecs didnt failed when expected")
  48. }
  49. }
  50. func TestGetKubeConfigSpecs(t *testing.T) {
  51. // Create temp folder for the test case
  52. tmpdir := testutil.SetupTempDir(t)
  53. defer os.RemoveAll(tmpdir)
  54. // Adds a pki folder with a ca certs to the temp folder
  55. pkidir := testutil.SetupPkiDirWithCertificateAuthorithy(t, tmpdir)
  56. // Creates InitConfigurations pointing to the pkidir folder
  57. cfgs := []*kubeadmapi.InitConfiguration{
  58. {
  59. LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
  60. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  61. CertificatesDir: pkidir,
  62. },
  63. NodeRegistration: kubeadmapi.NodeRegistrationOptions{Name: "valid-node-name"},
  64. },
  65. {
  66. LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
  67. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  68. ControlPlaneEndpoint: "api.k8s.io",
  69. CertificatesDir: pkidir,
  70. },
  71. NodeRegistration: kubeadmapi.NodeRegistrationOptions{Name: "valid-node-name"},
  72. },
  73. {
  74. LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
  75. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  76. ControlPlaneEndpoint: "api.k8s.io:4321",
  77. CertificatesDir: pkidir,
  78. },
  79. NodeRegistration: kubeadmapi.NodeRegistrationOptions{Name: "valid-node-name"},
  80. },
  81. {
  82. LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
  83. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  84. ControlPlaneEndpoint: "api.k8s.io",
  85. CertificatesDir: pkidir,
  86. },
  87. NodeRegistration: kubeadmapi.NodeRegistrationOptions{Name: "valid-node-name"},
  88. },
  89. {
  90. LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
  91. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  92. ControlPlaneEndpoint: "api.k8s.io:4321",
  93. CertificatesDir: pkidir,
  94. },
  95. NodeRegistration: kubeadmapi.NodeRegistrationOptions{Name: "valid-node-name"},
  96. },
  97. }
  98. for i, cfg := range cfgs {
  99. var assertions = []struct {
  100. kubeConfigFile string
  101. clientName string
  102. organizations []string
  103. }{
  104. {
  105. kubeConfigFile: kubeadmconstants.AdminKubeConfigFileName,
  106. clientName: "kubernetes-admin",
  107. organizations: []string{kubeadmconstants.SystemPrivilegedGroup},
  108. },
  109. {
  110. kubeConfigFile: kubeadmconstants.KubeletKubeConfigFileName,
  111. clientName: fmt.Sprintf("%s%s", kubeadmconstants.NodesUserPrefix, cfg.NodeRegistration.Name),
  112. organizations: []string{kubeadmconstants.NodesGroup},
  113. },
  114. {
  115. kubeConfigFile: kubeadmconstants.ControllerManagerKubeConfigFileName,
  116. clientName: kubeadmconstants.ControllerManagerUser,
  117. },
  118. {
  119. kubeConfigFile: kubeadmconstants.SchedulerKubeConfigFileName,
  120. clientName: kubeadmconstants.SchedulerUser,
  121. },
  122. }
  123. for _, assertion := range assertions {
  124. t.Run(fmt.Sprintf("%d-%s", i, assertion.clientName), func(t *testing.T) {
  125. // Executes getKubeConfigSpecs
  126. specs, err := getKubeConfigSpecs(cfg)
  127. if err != nil {
  128. t.Fatal("getKubeConfigSpecs failed!")
  129. }
  130. var spec *kubeConfigSpec
  131. var ok bool
  132. // assert the spec for the kubeConfigFile exists
  133. if spec, ok = specs[assertion.kubeConfigFile]; !ok {
  134. t.Errorf("getKubeConfigSpecs didn't create spec for %s ", assertion.kubeConfigFile)
  135. return
  136. }
  137. // Assert clientName
  138. if spec.ClientName != assertion.clientName {
  139. t.Errorf("getKubeConfigSpecs for %s clientName is %s, expected %s", assertion.kubeConfigFile, spec.ClientName, assertion.clientName)
  140. }
  141. // Assert Organizations
  142. if spec.ClientCertAuth == nil || !reflect.DeepEqual(spec.ClientCertAuth.Organizations, assertion.organizations) {
  143. t.Errorf("getKubeConfigSpecs for %s Organizations is %v, expected %v", assertion.kubeConfigFile, spec.ClientCertAuth.Organizations, assertion.organizations)
  144. }
  145. // Asserts InitConfiguration values injected into spec
  146. controlPlaneEndpoint, err := kubeadmutil.GetControlPlaneEndpoint(cfg.ControlPlaneEndpoint, &cfg.LocalAPIEndpoint)
  147. if err != nil {
  148. t.Error(err)
  149. }
  150. if spec.APIServer != controlPlaneEndpoint {
  151. t.Errorf("getKubeConfigSpecs didn't injected cfg.APIServer endpoint into spec for %s", assertion.kubeConfigFile)
  152. }
  153. // Asserts CA certs and CA keys loaded into specs
  154. if spec.CACert == nil {
  155. t.Errorf("getKubeConfigSpecs didn't loaded CACert into spec for %s!", assertion.kubeConfigFile)
  156. }
  157. if spec.ClientCertAuth == nil || spec.ClientCertAuth.CAKey == nil {
  158. t.Errorf("getKubeConfigSpecs didn't loaded CAKey into spec for %s!", assertion.kubeConfigFile)
  159. }
  160. })
  161. }
  162. }
  163. }
  164. func TestBuildKubeConfigFromSpecWithClientAuth(t *testing.T) {
  165. // Creates a CA
  166. caCert, caKey := certstestutil.SetupCertificateAuthorithy(t)
  167. // Executes buildKubeConfigFromSpec passing a KubeConfigSpec with a ClientAuth
  168. config := setupdKubeConfigWithClientAuth(t, caCert, caKey, "https://1.2.3.4:1234", "myClientName", "test-cluster", "myOrg1", "myOrg2")
  169. // Asserts spec data are propagated to the kubeconfig
  170. kubeconfigtestutil.AssertKubeConfigCurrentCluster(t, config, "https://1.2.3.4:1234", caCert)
  171. kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithClientCert(t, config, caCert, "myClientName", "myOrg1", "myOrg2")
  172. }
  173. func TestBuildKubeConfigFromSpecWithTokenAuth(t *testing.T) {
  174. // Creates a CA
  175. caCert, _ := certstestutil.SetupCertificateAuthorithy(t)
  176. // Executes buildKubeConfigFromSpec passing a KubeConfigSpec with a Token
  177. config := setupdKubeConfigWithTokenAuth(t, caCert, "https://1.2.3.4:1234", "myClientName", "123456", "test-cluster")
  178. // Asserts spec data are propagated to the kubeconfig
  179. kubeconfigtestutil.AssertKubeConfigCurrentCluster(t, config, "https://1.2.3.4:1234", caCert)
  180. kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithToken(t, config, "myClientName", "123456")
  181. }
  182. func TestCreateKubeConfigFileIfNotExists(t *testing.T) {
  183. // Creates a CAs
  184. caCert, caKey := certstestutil.SetupCertificateAuthorithy(t)
  185. anotherCaCert, anotherCaKey := certstestutil.SetupCertificateAuthorithy(t)
  186. // build kubeconfigs (to be used to test kubeconfigs equality/not equality)
  187. config := setupdKubeConfigWithClientAuth(t, caCert, caKey, "https://1.2.3.4:1234", "test-cluster", "myOrg1", "myOrg2")
  188. configWithAnotherClusterCa := setupdKubeConfigWithClientAuth(t, anotherCaCert, anotherCaKey, "https://1.2.3.4:1234", "test-cluster", "myOrg1", "myOrg2")
  189. configWithAnotherClusterAddress := setupdKubeConfigWithClientAuth(t, caCert, caKey, "https://3.4.5.6:3456", "myOrg1", "test-cluster", "myOrg2")
  190. var tests = []struct {
  191. name string
  192. existingKubeConfig *clientcmdapi.Config
  193. kubeConfig *clientcmdapi.Config
  194. expectedError bool
  195. }{
  196. { // if there is no existing KubeConfig, creates the kubeconfig
  197. name: "KubeConfig doesn't exist",
  198. kubeConfig: config,
  199. },
  200. { // if KubeConfig is equal to the existingKubeConfig - refers to the same cluster -, use the existing (Test idempotency)
  201. name: "KubeConfig refers to the same cluster",
  202. existingKubeConfig: config,
  203. kubeConfig: config,
  204. },
  205. { // if KubeConfig is not equal to the existingKubeConfig - refers to the another cluster (a cluster with another Ca) -, raise error
  206. name: "KubeConfig refers to the cluster with another CA",
  207. existingKubeConfig: config,
  208. kubeConfig: configWithAnotherClusterCa,
  209. expectedError: true,
  210. },
  211. { // if KubeConfig is not equal to the existingKubeConfig - refers to the another cluster (a cluster with another address) -, raise error
  212. name: "KubeConfig referst to the cluster with another address",
  213. existingKubeConfig: config,
  214. kubeConfig: configWithAnotherClusterAddress,
  215. expectedError: true,
  216. },
  217. }
  218. for _, test := range tests {
  219. t.Run(test.name, func(t *testing.T) {
  220. // Create temp folder for the test case
  221. tmpdir := testutil.SetupTempDir(t)
  222. defer os.RemoveAll(tmpdir)
  223. // Writes the existing kubeconfig file to disk
  224. if test.existingKubeConfig != nil {
  225. if err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.existingKubeConfig); err != nil {
  226. t.Errorf("createKubeConfigFileIfNotExists failed")
  227. }
  228. }
  229. // Writes the kubeconfig file to disk
  230. err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.kubeConfig)
  231. if test.expectedError && err == nil {
  232. t.Errorf("createKubeConfigFileIfNotExists didn't failed when expected to fail")
  233. }
  234. if !test.expectedError && err != nil {
  235. t.Errorf("createKubeConfigFileIfNotExists failed")
  236. }
  237. // Assert that the created file is there
  238. testutil.AssertFileExists(t, tmpdir, "test.conf")
  239. })
  240. }
  241. }
  242. func TestCreateKubeconfigFilesAndWrappers(t *testing.T) {
  243. var tests = []struct {
  244. name string
  245. createKubeConfigFunction func(outDir string, cfg *kubeadmapi.InitConfiguration) error
  246. expectedFiles []string
  247. expectedError bool
  248. }{
  249. { // Test createKubeConfigFiles fails for unknown kubeconfig is requested
  250. name: "createKubeConfigFiles",
  251. createKubeConfigFunction: func(outDir string, cfg *kubeadmapi.InitConfiguration) error {
  252. return createKubeConfigFiles(outDir, cfg, "unknown.conf")
  253. },
  254. expectedError: true,
  255. },
  256. { // Test CreateJoinControlPlaneKubeConfigFiles (wrapper to createKubeConfigFile)
  257. name: "CreateJoinControlPlaneKubeConfigFiles",
  258. createKubeConfigFunction: CreateJoinControlPlaneKubeConfigFiles,
  259. expectedFiles: []string{
  260. kubeadmconstants.AdminKubeConfigFileName,
  261. kubeadmconstants.ControllerManagerKubeConfigFileName,
  262. kubeadmconstants.SchedulerKubeConfigFileName,
  263. },
  264. },
  265. }
  266. for _, test := range tests {
  267. t.Run(test.name, func(t *testing.T) {
  268. // Create temp folder for the test case
  269. tmpdir := testutil.SetupTempDir(t)
  270. defer os.RemoveAll(tmpdir)
  271. // Adds a pki folder with a ca certs to the temp folder
  272. pkidir := testutil.SetupPkiDirWithCertificateAuthorithy(t, tmpdir)
  273. // Creates an InitConfiguration pointing to the pkidir folder
  274. cfg := &kubeadmapi.InitConfiguration{
  275. LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
  276. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  277. CertificatesDir: pkidir,
  278. },
  279. }
  280. // Execs the createKubeConfigFunction
  281. err := test.createKubeConfigFunction(tmpdir, cfg)
  282. if test.expectedError && err == nil {
  283. t.Errorf("createKubeConfigFunction didn't failed when expected to fail")
  284. return
  285. }
  286. if !test.expectedError && err != nil {
  287. t.Errorf("createKubeConfigFunction failed")
  288. return
  289. }
  290. // Assert expected files are there
  291. testutil.AssertFileExists(t, tmpdir, test.expectedFiles...)
  292. })
  293. }
  294. }
  295. func TestWriteKubeConfigFailsIfCADoesntExists(t *testing.T) {
  296. // Temporary folders for the test case (without a CA)
  297. tmpdir := testutil.SetupTempDir(t)
  298. defer os.RemoveAll(tmpdir)
  299. // Creates an InitConfiguration pointing to the tmpdir folder
  300. cfg := &kubeadmapi.InitConfiguration{
  301. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  302. CertificatesDir: tmpdir,
  303. },
  304. }
  305. var tests = []struct {
  306. name string
  307. writeKubeConfigFunction func(out io.Writer) error
  308. }{
  309. {
  310. name: "WriteKubeConfigWithClientCert",
  311. writeKubeConfigFunction: func(out io.Writer) error {
  312. return WriteKubeConfigWithClientCert(out, cfg, "myUser", []string{"myOrg"})
  313. },
  314. },
  315. {
  316. name: "WriteKubeConfigWithToken",
  317. writeKubeConfigFunction: func(out io.Writer) error {
  318. return WriteKubeConfigWithToken(out, cfg, "myUser", "12345")
  319. },
  320. },
  321. }
  322. for _, test := range tests {
  323. t.Run(test.name, func(t *testing.T) {
  324. buf := new(bytes.Buffer)
  325. // executes writeKubeConfigFunction
  326. if err := test.writeKubeConfigFunction(buf); err == nil {
  327. t.Error("writeKubeConfigFunction didnt failed when expected")
  328. }
  329. })
  330. }
  331. }
  332. func TestWriteKubeConfig(t *testing.T) {
  333. // Temporary folders for the test case
  334. tmpdir := testutil.SetupTempDir(t)
  335. defer os.RemoveAll(tmpdir)
  336. // Adds a pki folder with a ca cert to the temp folder
  337. pkidir := testutil.SetupPkiDirWithCertificateAuthorithy(t, tmpdir)
  338. // Retrieves ca cert for assertions
  339. caCert, _, err := pkiutil.TryLoadCertAndKeyFromDisk(pkidir, kubeadmconstants.CACertAndKeyBaseName)
  340. if err != nil {
  341. t.Fatalf("couldn't retrieve ca cert: %v", err)
  342. }
  343. // Creates an InitConfiguration pointing to the pkidir folder
  344. cfg := &kubeadmapi.InitConfiguration{
  345. LocalAPIEndpoint: kubeadmapi.APIEndpoint{AdvertiseAddress: "1.2.3.4", BindPort: 1234},
  346. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  347. CertificatesDir: pkidir,
  348. },
  349. }
  350. var tests = []struct {
  351. name string
  352. writeKubeConfigFunction func(out io.Writer) error
  353. withClientCert bool
  354. withToken bool
  355. }{
  356. {
  357. name: "WriteKubeConfigWithClientCert",
  358. writeKubeConfigFunction: func(out io.Writer) error {
  359. return WriteKubeConfigWithClientCert(out, cfg, "myUser", []string{"myOrg"})
  360. },
  361. withClientCert: true,
  362. },
  363. {
  364. name: "WriteKubeConfigWithToken",
  365. writeKubeConfigFunction: func(out io.Writer) error {
  366. return WriteKubeConfigWithToken(out, cfg, "myUser", "12345")
  367. },
  368. withToken: true,
  369. },
  370. }
  371. for _, test := range tests {
  372. t.Run(test.name, func(t *testing.T) {
  373. buf := new(bytes.Buffer)
  374. // executes writeKubeConfigFunction
  375. if err := test.writeKubeConfigFunction(buf); err != nil {
  376. t.Error("writeKubeConfigFunction failed")
  377. return
  378. }
  379. // reads kubeconfig written to stdout
  380. config, err := clientcmd.Load(buf.Bytes())
  381. if err != nil {
  382. t.Errorf("Couldn't read kubeconfig file from buffer: %v", err)
  383. return
  384. }
  385. // checks that CLI flags are properly propagated
  386. kubeconfigtestutil.AssertKubeConfigCurrentCluster(t, config, "https://1.2.3.4:1234", caCert)
  387. if test.withClientCert {
  388. // checks that kubeconfig files have expected client cert
  389. kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithClientCert(t, config, caCert, "myUser")
  390. }
  391. if test.withToken {
  392. // checks that kubeconfig files have expected token
  393. kubeconfigtestutil.AssertKubeConfigCurrentAuthInfoWithToken(t, config, "myUser", "12345")
  394. }
  395. })
  396. }
  397. }
  398. func TestValidateKubeConfig(t *testing.T) {
  399. caCert, caKey := certstestutil.SetupCertificateAuthorithy(t)
  400. anotherCaCert, anotherCaKey := certstestutil.SetupCertificateAuthorithy(t)
  401. config := setupdKubeConfigWithClientAuth(t, caCert, caKey, "https://1.2.3.4:1234", "test-cluster", "myOrg1")
  402. configWithAnotherClusterCa := setupdKubeConfigWithClientAuth(t, anotherCaCert, anotherCaKey, "https://1.2.3.4:1234", "test-cluster", "myOrg1")
  403. configWithAnotherServerURL := setupdKubeConfigWithClientAuth(t, caCert, caKey, "https://4.3.2.1:4321", "test-cluster", "myOrg1")
  404. tests := map[string]struct {
  405. existingKubeConfig *clientcmdapi.Config
  406. kubeConfig *clientcmdapi.Config
  407. expectedError bool
  408. }{
  409. "kubeconfig don't exist": {
  410. kubeConfig: config,
  411. expectedError: true,
  412. },
  413. "kubeconfig exist and has invalid ca": {
  414. existingKubeConfig: configWithAnotherClusterCa,
  415. kubeConfig: config,
  416. expectedError: true,
  417. },
  418. "kubeconfig exist and has invalid server url": {
  419. existingKubeConfig: configWithAnotherServerURL,
  420. kubeConfig: config,
  421. expectedError: true,
  422. },
  423. "kubeconfig exist and is valid": {
  424. existingKubeConfig: config,
  425. kubeConfig: config,
  426. expectedError: false,
  427. },
  428. }
  429. for name, test := range tests {
  430. t.Run(name, func(t *testing.T) {
  431. tmpdir := testutil.SetupTempDir(t)
  432. defer os.RemoveAll(tmpdir)
  433. if test.existingKubeConfig != nil {
  434. if err := createKubeConfigFileIfNotExists(tmpdir, "test.conf", test.existingKubeConfig); err != nil {
  435. t.Errorf("createKubeConfigFileIfNotExists failed")
  436. }
  437. }
  438. err := validateKubeConfig(tmpdir, "test.conf", test.kubeConfig)
  439. if (err != nil) != test.expectedError {
  440. t.Fatalf(dedent.Dedent(
  441. "validateKubeConfig failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"),
  442. name,
  443. test.expectedError,
  444. (err != nil),
  445. err,
  446. )
  447. }
  448. })
  449. }
  450. }
  451. func TestValidateKubeconfigsForExternalCA(t *testing.T) {
  452. tmpDir := testutil.SetupTempDir(t)
  453. defer os.RemoveAll(tmpDir)
  454. pkiDir := filepath.Join(tmpDir, "pki")
  455. initConfig := &kubeadmapi.InitConfiguration{
  456. ClusterConfiguration: kubeadmapi.ClusterConfiguration{
  457. CertificatesDir: pkiDir,
  458. },
  459. LocalAPIEndpoint: kubeadmapi.APIEndpoint{
  460. BindPort: 1234,
  461. AdvertiseAddress: "1.2.3.4",
  462. },
  463. }
  464. // creates CA, write to pkiDir and remove ca.key to get into external CA condition
  465. caCert, caKey := certstestutil.SetupCertificateAuthorithy(t)
  466. if err := pkiutil.WriteCertAndKey(pkiDir, kubeadmconstants.CACertAndKeyBaseName, caCert, caKey); err != nil {
  467. t.Fatalf("failure while saving CA certificate and key: %v", err)
  468. }
  469. if err := os.Remove(filepath.Join(pkiDir, kubeadmconstants.CAKeyName)); err != nil {
  470. t.Fatalf("failure while deleting ca.key: %v", err)
  471. }
  472. // create a valid config
  473. config := setupdKubeConfigWithClientAuth(t, caCert, caKey, "https://1.2.3.4:1234", "test-cluster", "myOrg1")
  474. // create a config with another CA
  475. anotherCaCert, anotherCaKey := certstestutil.SetupCertificateAuthorithy(t)
  476. configWithAnotherClusterCa := setupdKubeConfigWithClientAuth(t, anotherCaCert, anotherCaKey, "https://1.2.3.4:1234", "test-cluster", "myOrg1")
  477. // create a config with another server URL
  478. configWithAnotherServerURL := setupdKubeConfigWithClientAuth(t, caCert, caKey, "https://4.3.2.1:4321", "test-cluster", "myOrg1")
  479. tests := map[string]struct {
  480. filesToWrite map[string]*clientcmdapi.Config
  481. initConfig *kubeadmapi.InitConfiguration
  482. expectedError bool
  483. }{
  484. "files don't exist": {
  485. initConfig: initConfig,
  486. expectedError: true,
  487. },
  488. "some files don't exist": {
  489. filesToWrite: map[string]*clientcmdapi.Config{
  490. kubeadmconstants.AdminKubeConfigFileName: config,
  491. kubeadmconstants.KubeletKubeConfigFileName: config,
  492. },
  493. initConfig: initConfig,
  494. expectedError: true,
  495. },
  496. "some files have invalid CA": {
  497. filesToWrite: map[string]*clientcmdapi.Config{
  498. kubeadmconstants.AdminKubeConfigFileName: config,
  499. kubeadmconstants.KubeletKubeConfigFileName: config,
  500. kubeadmconstants.ControllerManagerKubeConfigFileName: configWithAnotherClusterCa,
  501. kubeadmconstants.SchedulerKubeConfigFileName: config,
  502. },
  503. initConfig: initConfig,
  504. expectedError: true,
  505. },
  506. "some files have invalid Server Url": {
  507. filesToWrite: map[string]*clientcmdapi.Config{
  508. kubeadmconstants.AdminKubeConfigFileName: config,
  509. kubeadmconstants.KubeletKubeConfigFileName: config,
  510. kubeadmconstants.ControllerManagerKubeConfigFileName: config,
  511. kubeadmconstants.SchedulerKubeConfigFileName: configWithAnotherServerURL,
  512. },
  513. initConfig: initConfig,
  514. expectedError: true,
  515. },
  516. "all files are valid": {
  517. filesToWrite: map[string]*clientcmdapi.Config{
  518. kubeadmconstants.AdminKubeConfigFileName: config,
  519. kubeadmconstants.KubeletKubeConfigFileName: config,
  520. kubeadmconstants.ControllerManagerKubeConfigFileName: config,
  521. kubeadmconstants.SchedulerKubeConfigFileName: config,
  522. },
  523. initConfig: initConfig,
  524. expectedError: false,
  525. },
  526. }
  527. for name, test := range tests {
  528. t.Run(name, func(t *testing.T) {
  529. tmpdir := testutil.SetupTempDir(t)
  530. defer os.RemoveAll(tmpdir)
  531. for name, config := range test.filesToWrite {
  532. if err := createKubeConfigFileIfNotExists(tmpdir, name, config); err != nil {
  533. t.Errorf("createKubeConfigFileIfNotExists failed: %v", err)
  534. }
  535. }
  536. err := ValidateKubeconfigsForExternalCA(tmpdir, test.initConfig)
  537. if (err != nil) != test.expectedError {
  538. t.Fatalf(dedent.Dedent(
  539. "ValidateKubeconfigsForExternalCA failed\n%s\nexpected error: %t\n\tgot: %t\nerror: %v"),
  540. name,
  541. test.expectedError,
  542. (err != nil),
  543. err,
  544. )
  545. }
  546. })
  547. }
  548. }
  549. // setupdKubeConfigWithClientAuth is a test utility function that wraps buildKubeConfigFromSpec for building a KubeConfig object With ClientAuth
  550. func setupdKubeConfigWithClientAuth(t *testing.T, caCert *x509.Certificate, caKey crypto.Signer, APIServer, clientName, clustername string, organizations ...string) *clientcmdapi.Config {
  551. spec := &kubeConfigSpec{
  552. CACert: caCert,
  553. APIServer: APIServer,
  554. ClientName: clientName,
  555. ClientCertAuth: &clientCertAuth{
  556. CAKey: caKey,
  557. Organizations: organizations,
  558. },
  559. }
  560. config, err := buildKubeConfigFromSpec(spec, clustername)
  561. if err != nil {
  562. t.Fatal("buildKubeConfigFromSpec failed!")
  563. }
  564. return config
  565. }
  566. // setupdKubeConfigWithClientAuth is a test utility function that wraps buildKubeConfigFromSpec for building a KubeConfig object With Token
  567. func setupdKubeConfigWithTokenAuth(t *testing.T, caCert *x509.Certificate, APIServer, clientName, token, clustername string) *clientcmdapi.Config {
  568. spec := &kubeConfigSpec{
  569. CACert: caCert,
  570. APIServer: APIServer,
  571. ClientName: clientName,
  572. TokenAuth: &tokenAuth{
  573. Token: token,
  574. },
  575. }
  576. config, err := buildKubeConfigFromSpec(spec, clustername)
  577. if err != nil {
  578. t.Fatal("buildKubeConfigFromSpec failed!")
  579. }
  580. return config
  581. }