dynamic_client_test.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. /*
  2. Copyright 2019 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 auth
  14. import (
  15. "context"
  16. "io/ioutil"
  17. "os"
  18. "testing"
  19. "time"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apiserver/pkg/authentication/authenticator"
  22. "k8s.io/apiserver/pkg/authorization/authorizerfactory"
  23. utilfeature "k8s.io/apiserver/pkg/util/feature"
  24. clientset "k8s.io/client-go/kubernetes"
  25. restclient "k8s.io/client-go/rest"
  26. featuregatetesting "k8s.io/component-base/featuregate/testing"
  27. "k8s.io/kubernetes/cmd/kube-apiserver/app/options"
  28. "k8s.io/kubernetes/pkg/controller"
  29. "k8s.io/kubernetes/pkg/features"
  30. kubeoptions "k8s.io/kubernetes/pkg/kubeapiserver/options"
  31. "k8s.io/kubernetes/pkg/master"
  32. "k8s.io/kubernetes/test/integration/framework"
  33. )
  34. func TestDynamicClientBuilder(t *testing.T) {
  35. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.TokenRequest, true)()
  36. tmpfile, err := ioutil.TempFile("/tmp", "key")
  37. if err != nil {
  38. t.Fatalf("create temp file failed: %v", err)
  39. }
  40. defer os.RemoveAll(tmpfile.Name())
  41. if err = ioutil.WriteFile(tmpfile.Name(), []byte(ecdsaPrivateKey), 0666); err != nil {
  42. t.Fatalf("write file %s failed: %v", tmpfile.Name(), err)
  43. }
  44. const iss = "https://foo.bar.example.com"
  45. aud := authenticator.Audiences{"api"}
  46. maxExpirationDuration := time.Second * 60 * 60
  47. if err != nil {
  48. t.Fatalf("parse duration failed: %v", err)
  49. }
  50. stopCh := make(chan struct{})
  51. defer close(stopCh)
  52. baseClient, baseConfig := framework.StartTestServer(t, stopCh, framework.TestServerSetup{
  53. ModifyServerRunOptions: func(opts *options.ServerRunOptions) {
  54. opts.ServiceAccountSigningKeyFile = tmpfile.Name()
  55. opts.ServiceAccountTokenMaxExpiration = maxExpirationDuration
  56. if opts.Authentication == nil {
  57. opts.Authentication = &kubeoptions.BuiltInAuthenticationOptions{}
  58. }
  59. opts.Authentication.APIAudiences = aud
  60. if opts.Authentication.ServiceAccounts == nil {
  61. opts.Authentication.ServiceAccounts = &kubeoptions.ServiceAccountAuthenticationOptions{}
  62. }
  63. opts.Authentication.ServiceAccounts.Issuer = iss
  64. opts.Authentication.ServiceAccounts.KeyFiles = []string{tmpfile.Name()}
  65. },
  66. ModifyServerConfig: func(config *master.Config) {
  67. config.GenericConfig.Authorization.Authorizer = authorizerfactory.NewAlwaysAllowAuthorizer()
  68. },
  69. })
  70. // We want to test if the token rotation works fine here.
  71. // To minimize the time this test would consume, we use the minimial token expiration.
  72. // The minimial token expiration is defined in:
  73. // pkg/apis/authentication/validation/validation.go
  74. exp := int64(600)
  75. leeway := 99
  76. ns := "default"
  77. clientBuilder := controller.NewTestDynamicClientBuilder(
  78. restclient.AnonymousClientConfig(baseConfig),
  79. baseClient.CoreV1(),
  80. ns, exp, leeway)
  81. saName := "dt"
  82. dymClient, err := clientBuilder.Client(saName)
  83. if err != nil {
  84. t.Fatalf("build client via dynamic client builder failed: %v", err)
  85. }
  86. if err = testClientBuilder(dymClient, ns, saName); err != nil {
  87. t.Fatalf("dynamic client get resources failed befroe deleting sa: %v", err)
  88. }
  89. // We want to trigger token rotation here by deleting service account
  90. // the dynamic client was using.
  91. if err = dymClient.CoreV1().ServiceAccounts(ns).Delete(context.TODO(), saName, nil); err != nil {
  92. t.Fatalf("delete service account %s failed: %v", saName, err)
  93. }
  94. time.Sleep(time.Second * 10)
  95. if err = testClientBuilder(dymClient, ns, saName); err != nil {
  96. t.Fatalf("dynamic client get resources failed after deleting sa: %v", err)
  97. }
  98. }
  99. func testClientBuilder(dymClient clientset.Interface, ns, saName string) error {
  100. _, err := dymClient.CoreV1().Namespaces().Get(context.TODO(), ns, metav1.GetOptions{})
  101. if err != nil {
  102. return err
  103. }
  104. _, err = dymClient.CoreV1().ServiceAccounts(ns).Get(context.TODO(), saName, metav1.GetOptions{})
  105. if err != nil {
  106. return err
  107. }
  108. return nil
  109. }