node_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. /*
  2. Copyright 2017 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. "fmt"
  17. "io/ioutil"
  18. "strings"
  19. "testing"
  20. "time"
  21. coordination "k8s.io/api/coordination/v1"
  22. corev1 "k8s.io/api/core/v1"
  23. policy "k8s.io/api/policy/v1beta1"
  24. storagev1 "k8s.io/api/storage/v1"
  25. apierrors "k8s.io/apimachinery/pkg/api/errors"
  26. "k8s.io/apimachinery/pkg/api/resource"
  27. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  28. "k8s.io/apimachinery/pkg/types"
  29. "k8s.io/apimachinery/pkg/util/wait"
  30. utilfeature "k8s.io/apiserver/pkg/util/feature"
  31. clientset "k8s.io/client-go/kubernetes"
  32. featuregatetesting "k8s.io/component-base/featuregate/testing"
  33. kubeapiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
  34. "k8s.io/kubernetes/pkg/features"
  35. "k8s.io/kubernetes/test/integration/framework"
  36. "k8s.io/utils/pointer"
  37. )
  38. func TestNodeAuthorizer(t *testing.T) {
  39. const (
  40. // Define credentials
  41. // Fake values for testing.
  42. tokenMaster = "master-token"
  43. tokenNodeUnknown = "unknown-token"
  44. tokenNode1 = "node1-token"
  45. tokenNode2 = "node2-token"
  46. )
  47. // Enable DynamicKubeletConfig feature so that Node.Spec.ConfigSource can be set
  48. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.DynamicKubeletConfig, true)()
  49. // Enable CSINodeInfo feature so that nodes can create CSINode objects.
  50. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSINodeInfo, true)()
  51. tokenFile, err := ioutil.TempFile("", "kubeconfig")
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. tokenFile.WriteString(strings.Join([]string{
  56. fmt.Sprintf(`%s,admin,uid1,"system:masters"`, tokenMaster),
  57. fmt.Sprintf(`%s,unknown,uid2,"system:nodes"`, tokenNodeUnknown),
  58. fmt.Sprintf(`%s,system:node:node1,uid3,"system:nodes"`, tokenNode1),
  59. fmt.Sprintf(`%s,system:node:node2,uid4,"system:nodes"`, tokenNode2),
  60. }, "\n"))
  61. tokenFile.Close()
  62. server := kubeapiservertesting.StartTestServerOrDie(t, nil, []string{
  63. "--authorization-mode", "Node,RBAC",
  64. "--token-auth-file", tokenFile.Name(),
  65. "--enable-admission-plugins", "NodeRestriction",
  66. // The "default" SA is not installed, causing the ServiceAccount plugin to retry for ~1s per
  67. // API request.
  68. "--disable-admission-plugins", "ServiceAccount,TaintNodesByCondition",
  69. }, framework.SharedEtcd())
  70. defer server.TearDownFn()
  71. // Build client config and superuser clientset
  72. clientConfig := server.ClientConfig
  73. superuserClient, superuserClientExternal := clientsetForToken(tokenMaster, clientConfig)
  74. // Wait for a healthy server
  75. for {
  76. result := superuserClient.CoreV1().RESTClient().Get().AbsPath("/healthz").Do(context.TODO())
  77. _, err := result.Raw()
  78. if err == nil {
  79. break
  80. }
  81. t.Log(err)
  82. time.Sleep(time.Second)
  83. }
  84. // Create objects
  85. if _, err := superuserClient.CoreV1().Namespaces().Create(context.TODO(), &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "ns"}}, metav1.CreateOptions{}); err != nil {
  86. t.Fatal(err)
  87. }
  88. if _, err := superuserClient.CoreV1().Secrets("ns").Create(context.TODO(), &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "mysecret"}}, metav1.CreateOptions{}); err != nil {
  89. t.Fatal(err)
  90. }
  91. if _, err := superuserClient.CoreV1().Secrets("ns").Create(context.TODO(), &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "mypvsecret"}}, metav1.CreateOptions{}); err != nil {
  92. t.Fatal(err)
  93. }
  94. if _, err := superuserClient.CoreV1().ConfigMaps("ns").Create(context.TODO(), &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "myconfigmap"}}, metav1.CreateOptions{}); err != nil {
  95. t.Fatal(err)
  96. }
  97. if _, err := superuserClient.CoreV1().ConfigMaps("ns").Create(context.TODO(), &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "myconfigmapconfigsource"}}, metav1.CreateOptions{}); err != nil {
  98. t.Fatal(err)
  99. }
  100. pvName := "mypv"
  101. if _, err := superuserClientExternal.StorageV1().VolumeAttachments().Create(context.TODO(), &storagev1.VolumeAttachment{
  102. ObjectMeta: metav1.ObjectMeta{Name: "myattachment"},
  103. Spec: storagev1.VolumeAttachmentSpec{
  104. Attacher: "foo",
  105. Source: storagev1.VolumeAttachmentSource{PersistentVolumeName: &pvName},
  106. NodeName: "node2",
  107. },
  108. }, metav1.CreateOptions{}); err != nil {
  109. t.Fatal(err)
  110. }
  111. if _, err := superuserClient.CoreV1().PersistentVolumeClaims("ns").Create(context.TODO(), &corev1.PersistentVolumeClaim{
  112. ObjectMeta: metav1.ObjectMeta{Name: "mypvc"},
  113. Spec: corev1.PersistentVolumeClaimSpec{
  114. AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadOnlyMany},
  115. Resources: corev1.ResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("1")}},
  116. },
  117. }, metav1.CreateOptions{}); err != nil {
  118. t.Fatal(err)
  119. }
  120. if _, err := superuserClient.CoreV1().PersistentVolumes().Create(context.TODO(), &corev1.PersistentVolume{
  121. ObjectMeta: metav1.ObjectMeta{Name: "mypv"},
  122. Spec: corev1.PersistentVolumeSpec{
  123. AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadOnlyMany},
  124. Capacity: corev1.ResourceList{corev1.ResourceStorage: resource.MustParse("1")},
  125. ClaimRef: &corev1.ObjectReference{Namespace: "ns", Name: "mypvc"},
  126. PersistentVolumeSource: corev1.PersistentVolumeSource{AzureFile: &corev1.AzureFilePersistentVolumeSource{ShareName: "default", SecretName: "mypvsecret"}},
  127. },
  128. }, metav1.CreateOptions{}); err != nil {
  129. t.Fatal(err)
  130. }
  131. getSecret := func(client clientset.Interface) func() error {
  132. return func() error {
  133. _, err := client.CoreV1().Secrets("ns").Get(context.TODO(), "mysecret", metav1.GetOptions{})
  134. return err
  135. }
  136. }
  137. getPVSecret := func(client clientset.Interface) func() error {
  138. return func() error {
  139. _, err := client.CoreV1().Secrets("ns").Get(context.TODO(), "mypvsecret", metav1.GetOptions{})
  140. return err
  141. }
  142. }
  143. getConfigMap := func(client clientset.Interface) func() error {
  144. return func() error {
  145. _, err := client.CoreV1().ConfigMaps("ns").Get(context.TODO(), "myconfigmap", metav1.GetOptions{})
  146. return err
  147. }
  148. }
  149. getConfigMapConfigSource := func(client clientset.Interface) func() error {
  150. return func() error {
  151. _, err := client.CoreV1().ConfigMaps("ns").Get(context.TODO(), "myconfigmapconfigsource", metav1.GetOptions{})
  152. return err
  153. }
  154. }
  155. getPVC := func(client clientset.Interface) func() error {
  156. return func() error {
  157. _, err := client.CoreV1().PersistentVolumeClaims("ns").Get(context.TODO(), "mypvc", metav1.GetOptions{})
  158. return err
  159. }
  160. }
  161. getPV := func(client clientset.Interface) func() error {
  162. return func() error {
  163. _, err := client.CoreV1().PersistentVolumes().Get(context.TODO(), "mypv", metav1.GetOptions{})
  164. return err
  165. }
  166. }
  167. getVolumeAttachment := func(client clientset.Interface) func() error {
  168. return func() error {
  169. _, err := client.StorageV1().VolumeAttachments().Get(context.TODO(), "myattachment", metav1.GetOptions{})
  170. return err
  171. }
  172. }
  173. createNode2NormalPod := func(client clientset.Interface) func() error {
  174. return func() error {
  175. _, err := client.CoreV1().Pods("ns").Create(context.TODO(), &corev1.Pod{
  176. ObjectMeta: metav1.ObjectMeta{Name: "node2normalpod"},
  177. Spec: corev1.PodSpec{
  178. NodeName: "node2",
  179. Containers: []corev1.Container{{Name: "image", Image: "busybox"}},
  180. Volumes: []corev1.Volume{
  181. {Name: "secret", VolumeSource: corev1.VolumeSource{Secret: &corev1.SecretVolumeSource{SecretName: "mysecret"}}},
  182. {Name: "cm", VolumeSource: corev1.VolumeSource{ConfigMap: &corev1.ConfigMapVolumeSource{LocalObjectReference: corev1.LocalObjectReference{Name: "myconfigmap"}}}},
  183. {Name: "pvc", VolumeSource: corev1.VolumeSource{PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ClaimName: "mypvc"}}},
  184. },
  185. },
  186. }, metav1.CreateOptions{})
  187. return err
  188. }
  189. }
  190. updateNode2NormalPodStatus := func(client clientset.Interface) func() error {
  191. return func() error {
  192. startTime := metav1.NewTime(time.Now())
  193. _, err := client.CoreV1().Pods("ns").UpdateStatus(context.TODO(), &corev1.Pod{
  194. ObjectMeta: metav1.ObjectMeta{Name: "node2normalpod"},
  195. Status: corev1.PodStatus{StartTime: &startTime},
  196. }, metav1.UpdateOptions{})
  197. return err
  198. }
  199. }
  200. deleteNode2NormalPod := func(client clientset.Interface) func() error {
  201. return func() error {
  202. zero := int64(0)
  203. return client.CoreV1().Pods("ns").Delete(context.TODO(), "node2normalpod", &metav1.DeleteOptions{GracePeriodSeconds: &zero})
  204. }
  205. }
  206. createNode2MirrorPod := func(client clientset.Interface) func() error {
  207. return func() error {
  208. _, err := client.CoreV1().Pods("ns").Create(context.TODO(), &corev1.Pod{
  209. ObjectMeta: metav1.ObjectMeta{
  210. Name: "node2mirrorpod",
  211. Annotations: map[string]string{corev1.MirrorPodAnnotationKey: "true"},
  212. },
  213. Spec: corev1.PodSpec{
  214. NodeName: "node2",
  215. Containers: []corev1.Container{{Name: "image", Image: "busybox"}},
  216. },
  217. }, metav1.CreateOptions{})
  218. return err
  219. }
  220. }
  221. deleteNode2MirrorPod := func(client clientset.Interface) func() error {
  222. return func() error {
  223. zero := int64(0)
  224. return client.CoreV1().Pods("ns").Delete(context.TODO(), "node2mirrorpod", &metav1.DeleteOptions{GracePeriodSeconds: &zero})
  225. }
  226. }
  227. createNode2 := func(client clientset.Interface) func() error {
  228. return func() error {
  229. _, err := client.CoreV1().Nodes().Create(context.TODO(), &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: "node2"}}, metav1.CreateOptions{})
  230. return err
  231. }
  232. }
  233. setNode2ConfigSource := func(client clientset.Interface) func() error {
  234. return func() error {
  235. node2, err := client.CoreV1().Nodes().Get(context.TODO(), "node2", metav1.GetOptions{})
  236. if err != nil {
  237. return err
  238. }
  239. node2.Spec.ConfigSource = &corev1.NodeConfigSource{
  240. ConfigMap: &corev1.ConfigMapNodeConfigSource{
  241. Namespace: "ns",
  242. Name: "myconfigmapconfigsource",
  243. KubeletConfigKey: "kubelet",
  244. },
  245. }
  246. _, err = client.CoreV1().Nodes().Update(context.TODO(), node2, metav1.UpdateOptions{})
  247. return err
  248. }
  249. }
  250. unsetNode2ConfigSource := func(client clientset.Interface) func() error {
  251. return func() error {
  252. node2, err := client.CoreV1().Nodes().Get(context.TODO(), "node2", metav1.GetOptions{})
  253. if err != nil {
  254. return err
  255. }
  256. node2.Spec.ConfigSource = nil
  257. _, err = client.CoreV1().Nodes().Update(context.TODO(), node2, metav1.UpdateOptions{})
  258. return err
  259. }
  260. }
  261. updateNode2Status := func(client clientset.Interface) func() error {
  262. return func() error {
  263. _, err := client.CoreV1().Nodes().UpdateStatus(context.TODO(), &corev1.Node{
  264. ObjectMeta: metav1.ObjectMeta{Name: "node2"},
  265. Status: corev1.NodeStatus{},
  266. }, metav1.UpdateOptions{})
  267. return err
  268. }
  269. }
  270. deleteNode2 := func(client clientset.Interface) func() error {
  271. return func() error {
  272. return client.CoreV1().Nodes().Delete(context.TODO(), "node2", nil)
  273. }
  274. }
  275. createNode2NormalPodEviction := func(client clientset.Interface) func() error {
  276. return func() error {
  277. zero := int64(0)
  278. return client.PolicyV1beta1().Evictions("ns").Evict(&policy.Eviction{
  279. TypeMeta: metav1.TypeMeta{
  280. APIVersion: "policy/v1beta1",
  281. Kind: "Eviction",
  282. },
  283. ObjectMeta: metav1.ObjectMeta{
  284. Name: "node2normalpod",
  285. Namespace: "ns",
  286. },
  287. DeleteOptions: &metav1.DeleteOptions{GracePeriodSeconds: &zero},
  288. })
  289. }
  290. }
  291. createNode2MirrorPodEviction := func(client clientset.Interface) func() error {
  292. return func() error {
  293. zero := int64(0)
  294. return client.PolicyV1beta1().Evictions("ns").Evict(&policy.Eviction{
  295. TypeMeta: metav1.TypeMeta{
  296. APIVersion: "policy/v1beta1",
  297. Kind: "Eviction",
  298. },
  299. ObjectMeta: metav1.ObjectMeta{
  300. Name: "node2mirrorpod",
  301. Namespace: "ns",
  302. },
  303. DeleteOptions: &metav1.DeleteOptions{GracePeriodSeconds: &zero},
  304. })
  305. }
  306. }
  307. capacity := 50
  308. updatePVCCapacity := func(client clientset.Interface) func() error {
  309. return func() error {
  310. capacity++
  311. statusString := fmt.Sprintf("{\"status\": {\"capacity\": {\"storage\": \"%dG\"}}}", capacity)
  312. patchBytes := []byte(statusString)
  313. _, err := client.CoreV1().PersistentVolumeClaims("ns").Patch(context.TODO(), "mypvc", types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, "status")
  314. return err
  315. }
  316. }
  317. updatePVCPhase := func(client clientset.Interface) func() error {
  318. return func() error {
  319. patchBytes := []byte(`{"status":{"phase": "Bound"}}`)
  320. _, err := client.CoreV1().PersistentVolumeClaims("ns").Patch(context.TODO(), "mypvc", types.StrategicMergePatchType, patchBytes, metav1.PatchOptions{}, "status")
  321. return err
  322. }
  323. }
  324. getNode1Lease := func(client clientset.Interface) func() error {
  325. return func() error {
  326. _, err := client.CoordinationV1().Leases(corev1.NamespaceNodeLease).Get(context.TODO(), "node1", metav1.GetOptions{})
  327. return err
  328. }
  329. }
  330. node1LeaseDurationSeconds := int32(40)
  331. createNode1Lease := func(client clientset.Interface) func() error {
  332. return func() error {
  333. lease := &coordination.Lease{
  334. ObjectMeta: metav1.ObjectMeta{
  335. Name: "node1",
  336. },
  337. Spec: coordination.LeaseSpec{
  338. HolderIdentity: pointer.StringPtr("node1"),
  339. LeaseDurationSeconds: pointer.Int32Ptr(node1LeaseDurationSeconds),
  340. RenewTime: &metav1.MicroTime{Time: time.Now()},
  341. },
  342. }
  343. _, err := client.CoordinationV1().Leases(corev1.NamespaceNodeLease).Create(context.TODO(), lease, metav1.CreateOptions{})
  344. return err
  345. }
  346. }
  347. updateNode1Lease := func(client clientset.Interface) func() error {
  348. return func() error {
  349. lease, err := client.CoordinationV1().Leases(corev1.NamespaceNodeLease).Get(context.TODO(), "node1", metav1.GetOptions{})
  350. if err != nil {
  351. return err
  352. }
  353. lease.Spec.RenewTime = &metav1.MicroTime{Time: time.Now()}
  354. _, err = client.CoordinationV1().Leases(corev1.NamespaceNodeLease).Update(context.TODO(), lease, metav1.UpdateOptions{})
  355. return err
  356. }
  357. }
  358. patchNode1Lease := func(client clientset.Interface) func() error {
  359. return func() error {
  360. node1LeaseDurationSeconds++
  361. bs := []byte(fmt.Sprintf(`{"spec": {"leaseDurationSeconds": %d}}`, node1LeaseDurationSeconds))
  362. _, err := client.CoordinationV1().Leases(corev1.NamespaceNodeLease).Patch(context.TODO(), "node1", types.StrategicMergePatchType, bs, metav1.PatchOptions{})
  363. return err
  364. }
  365. }
  366. deleteNode1Lease := func(client clientset.Interface) func() error {
  367. return func() error {
  368. return client.CoordinationV1().Leases(corev1.NamespaceNodeLease).Delete(context.TODO(), "node1", &metav1.DeleteOptions{})
  369. }
  370. }
  371. getNode1CSINode := func(client clientset.Interface) func() error {
  372. return func() error {
  373. _, err := client.StorageV1().CSINodes().Get(context.TODO(), "node1", metav1.GetOptions{})
  374. return err
  375. }
  376. }
  377. createNode1CSINode := func(client clientset.Interface) func() error {
  378. return func() error {
  379. nodeInfo := &storagev1.CSINode{
  380. ObjectMeta: metav1.ObjectMeta{
  381. Name: "node1",
  382. },
  383. Spec: storagev1.CSINodeSpec{
  384. Drivers: []storagev1.CSINodeDriver{
  385. {
  386. Name: "com.example.csi.driver1",
  387. NodeID: "com.example.csi/node1",
  388. TopologyKeys: []string{"com.example.csi/zone"},
  389. },
  390. },
  391. },
  392. }
  393. _, err := client.StorageV1().CSINodes().Create(context.TODO(), nodeInfo, metav1.CreateOptions{})
  394. return err
  395. }
  396. }
  397. updateNode1CSINode := func(client clientset.Interface) func() error {
  398. return func() error {
  399. nodeInfo, err := client.StorageV1().CSINodes().Get(context.TODO(), "node1", metav1.GetOptions{})
  400. if err != nil {
  401. return err
  402. }
  403. nodeInfo.Spec.Drivers = []storagev1.CSINodeDriver{
  404. {
  405. Name: "com.example.csi.driver2",
  406. NodeID: "com.example.csi/node1",
  407. TopologyKeys: []string{"com.example.csi/rack"},
  408. },
  409. }
  410. _, err = client.StorageV1().CSINodes().Update(context.TODO(), nodeInfo, metav1.UpdateOptions{})
  411. return err
  412. }
  413. }
  414. patchNode1CSINode := func(client clientset.Interface) func() error {
  415. return func() error {
  416. bs := []byte(fmt.Sprintf(`{"csiDrivers": [ { "driver": "net.example.storage.driver2", "nodeID": "net.example.storage/node1", "topologyKeys": [ "net.example.storage/region" ] } ] }`))
  417. // StrategicMergePatch is unsupported by CRs. Falling back to MergePatch
  418. _, err := client.StorageV1().CSINodes().Patch(context.TODO(), "node1", types.MergePatchType, bs, metav1.PatchOptions{})
  419. return err
  420. }
  421. }
  422. deleteNode1CSINode := func(client clientset.Interface) func() error {
  423. return func() error {
  424. return client.StorageV1().CSINodes().Delete(context.TODO(), "node1", &metav1.DeleteOptions{})
  425. }
  426. }
  427. nodeanonClient, _ := clientsetForToken(tokenNodeUnknown, clientConfig)
  428. node1Client, node1ClientExternal := clientsetForToken(tokenNode1, clientConfig)
  429. node2Client, node2ClientExternal := clientsetForToken(tokenNode2, clientConfig)
  430. _, csiNode1Client := clientsetForToken(tokenNode1, clientConfig)
  431. _, csiNode2Client := clientsetForToken(tokenNode2, clientConfig)
  432. // all node requests from node1 and unknown node fail
  433. expectForbidden(t, getSecret(nodeanonClient))
  434. expectForbidden(t, getPVSecret(nodeanonClient))
  435. expectForbidden(t, getConfigMap(nodeanonClient))
  436. expectForbidden(t, getPVC(nodeanonClient))
  437. expectForbidden(t, getPV(nodeanonClient))
  438. expectForbidden(t, createNode2NormalPod(nodeanonClient))
  439. expectForbidden(t, createNode2MirrorPod(nodeanonClient))
  440. expectForbidden(t, deleteNode2NormalPod(nodeanonClient))
  441. expectForbidden(t, deleteNode2MirrorPod(nodeanonClient))
  442. expectForbidden(t, createNode2MirrorPodEviction(nodeanonClient))
  443. expectForbidden(t, createNode2(nodeanonClient))
  444. expectForbidden(t, updateNode2Status(nodeanonClient))
  445. expectForbidden(t, deleteNode2(nodeanonClient))
  446. expectForbidden(t, getSecret(node1Client))
  447. expectForbidden(t, getPVSecret(node1Client))
  448. expectForbidden(t, getConfigMap(node1Client))
  449. expectForbidden(t, getPVC(node1Client))
  450. expectForbidden(t, getPV(node1Client))
  451. expectForbidden(t, createNode2NormalPod(nodeanonClient))
  452. expectForbidden(t, createNode2MirrorPod(node1Client))
  453. expectNotFound(t, deleteNode2MirrorPod(node1Client))
  454. expectNotFound(t, createNode2MirrorPodEviction(node1Client))
  455. expectForbidden(t, createNode2(node1Client))
  456. expectForbidden(t, updateNode2Status(node1Client))
  457. expectForbidden(t, deleteNode2(node1Client))
  458. // related object requests from node2 fail
  459. expectForbidden(t, getSecret(node2Client))
  460. expectForbidden(t, getPVSecret(node2Client))
  461. expectForbidden(t, getConfigMap(node2Client))
  462. expectForbidden(t, getPVC(node2Client))
  463. expectForbidden(t, getPV(node2Client))
  464. expectForbidden(t, createNode2NormalPod(nodeanonClient))
  465. // mirror pod and self node lifecycle is allowed
  466. expectAllowed(t, createNode2MirrorPod(node2Client))
  467. expectAllowed(t, deleteNode2MirrorPod(node2Client))
  468. expectAllowed(t, createNode2MirrorPod(node2Client))
  469. expectAllowed(t, createNode2MirrorPodEviction(node2Client))
  470. expectAllowed(t, createNode2(node2Client))
  471. expectAllowed(t, updateNode2Status(node2Client))
  472. // self deletion is not allowed
  473. expectForbidden(t, deleteNode2(node2Client))
  474. // clean up node2
  475. expectAllowed(t, deleteNode2(superuserClient))
  476. // create a pod as an admin to add object references
  477. expectAllowed(t, createNode2NormalPod(superuserClient))
  478. // unidentifiable node and node1 are still forbidden
  479. expectForbidden(t, getSecret(nodeanonClient))
  480. expectForbidden(t, getPVSecret(nodeanonClient))
  481. expectForbidden(t, getConfigMap(nodeanonClient))
  482. expectForbidden(t, getPVC(nodeanonClient))
  483. expectForbidden(t, getPV(nodeanonClient))
  484. expectForbidden(t, createNode2NormalPod(nodeanonClient))
  485. expectForbidden(t, updateNode2NormalPodStatus(nodeanonClient))
  486. expectForbidden(t, deleteNode2NormalPod(nodeanonClient))
  487. expectForbidden(t, createNode2NormalPodEviction(nodeanonClient))
  488. expectForbidden(t, createNode2MirrorPod(nodeanonClient))
  489. expectForbidden(t, deleteNode2MirrorPod(nodeanonClient))
  490. expectForbidden(t, createNode2MirrorPodEviction(nodeanonClient))
  491. expectForbidden(t, getSecret(node1Client))
  492. expectForbidden(t, getPVSecret(node1Client))
  493. expectForbidden(t, getConfigMap(node1Client))
  494. expectForbidden(t, getPVC(node1Client))
  495. expectForbidden(t, getPV(node1Client))
  496. expectForbidden(t, createNode2NormalPod(node1Client))
  497. expectForbidden(t, updateNode2NormalPodStatus(node1Client))
  498. expectForbidden(t, deleteNode2NormalPod(node1Client))
  499. expectForbidden(t, createNode2NormalPodEviction(node1Client))
  500. expectForbidden(t, createNode2MirrorPod(node1Client))
  501. expectNotFound(t, deleteNode2MirrorPod(node1Client))
  502. expectNotFound(t, createNode2MirrorPodEviction(node1Client))
  503. // node2 can get referenced objects now
  504. expectAllowed(t, getSecret(node2Client))
  505. expectAllowed(t, getPVSecret(node2Client))
  506. expectAllowed(t, getConfigMap(node2Client))
  507. expectAllowed(t, getPVC(node2Client))
  508. expectAllowed(t, getPV(node2Client))
  509. expectForbidden(t, createNode2NormalPod(node2Client))
  510. expectAllowed(t, updateNode2NormalPodStatus(node2Client))
  511. expectAllowed(t, deleteNode2NormalPod(node2Client))
  512. expectAllowed(t, createNode2MirrorPod(node2Client))
  513. expectAllowed(t, deleteNode2MirrorPod(node2Client))
  514. // recreate as an admin to test eviction
  515. expectAllowed(t, createNode2NormalPod(superuserClient))
  516. expectAllowed(t, createNode2MirrorPod(superuserClient))
  517. expectAllowed(t, createNode2NormalPodEviction(node2Client))
  518. expectAllowed(t, createNode2MirrorPodEviction(node2Client))
  519. // re-create a pod as an admin to add object references
  520. expectAllowed(t, createNode2NormalPod(superuserClient))
  521. // ExpandPersistentVolumes feature disabled
  522. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.ExpandPersistentVolumes, false)()
  523. expectForbidden(t, updatePVCCapacity(node1Client))
  524. expectForbidden(t, updatePVCCapacity(node2Client))
  525. // ExpandPersistentVolumes feature enabled
  526. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.ExpandPersistentVolumes, true)()
  527. expectForbidden(t, updatePVCCapacity(node1Client))
  528. expectAllowed(t, updatePVCCapacity(node2Client))
  529. expectForbidden(t, updatePVCPhase(node2Client))
  530. // Enabled CSIPersistentVolume feature
  531. expectForbidden(t, getVolumeAttachment(node1ClientExternal))
  532. expectAllowed(t, getVolumeAttachment(node2ClientExternal))
  533. // create node2 again
  534. expectAllowed(t, createNode2(node2Client))
  535. // node2 can not set its own config source
  536. expectForbidden(t, setNode2ConfigSource(node2Client))
  537. // node2 can not access the configmap config source yet
  538. expectForbidden(t, getConfigMapConfigSource(node2Client))
  539. // superuser can access the configmap config source
  540. expectAllowed(t, getConfigMapConfigSource(superuserClient))
  541. // superuser can set node2's config source
  542. expectAllowed(t, setNode2ConfigSource(superuserClient))
  543. // node2 can now get the configmap assigned as its config source
  544. expectAllowed(t, getConfigMapConfigSource(node2Client))
  545. // superuser can unset node2's config source
  546. expectAllowed(t, unsetNode2ConfigSource(superuserClient))
  547. // node2 can no longer get the configmap after it is unassigned as its config source
  548. expectForbidden(t, getConfigMapConfigSource(node2Client))
  549. // clean up node2
  550. expectAllowed(t, deleteNode2(superuserClient))
  551. //TODO(mikedanese): integration test node restriction of TokenRequest
  552. // node1 allowed to operate on its own lease
  553. expectAllowed(t, createNode1Lease(node1Client))
  554. expectAllowed(t, getNode1Lease(node1Client))
  555. expectAllowed(t, updateNode1Lease(node1Client))
  556. expectAllowed(t, patchNode1Lease(node1Client))
  557. expectAllowed(t, deleteNode1Lease(node1Client))
  558. // node2 not allowed to operate on another node's lease
  559. expectForbidden(t, createNode1Lease(node2Client))
  560. expectForbidden(t, getNode1Lease(node2Client))
  561. expectForbidden(t, updateNode1Lease(node2Client))
  562. expectForbidden(t, patchNode1Lease(node2Client))
  563. expectForbidden(t, deleteNode1Lease(node2Client))
  564. // node1 allowed to operate on its own CSINode
  565. expectAllowed(t, createNode1CSINode(csiNode1Client))
  566. expectAllowed(t, getNode1CSINode(csiNode1Client))
  567. expectAllowed(t, updateNode1CSINode(csiNode1Client))
  568. expectAllowed(t, patchNode1CSINode(csiNode1Client))
  569. expectAllowed(t, deleteNode1CSINode(csiNode1Client))
  570. // node2 not allowed to operate on another node's CSINode
  571. expectForbidden(t, createNode1CSINode(csiNode2Client))
  572. expectForbidden(t, getNode1CSINode(csiNode2Client))
  573. expectForbidden(t, updateNode1CSINode(csiNode2Client))
  574. expectForbidden(t, patchNode1CSINode(csiNode2Client))
  575. expectForbidden(t, deleteNode1CSINode(csiNode2Client))
  576. }
  577. // expect executes a function a set number of times until it either returns the
  578. // expected error or executes too many times. It returns if the retries timed
  579. // out and the last error returned by the method.
  580. func expect(t *testing.T, f func() error, wantErr func(error) bool) (timeout bool, lastErr error) {
  581. t.Helper()
  582. err := wait.PollImmediate(time.Second, 30*time.Second, func() (bool, error) {
  583. t.Helper()
  584. lastErr = f()
  585. if wantErr(lastErr) {
  586. return true, nil
  587. }
  588. t.Logf("unexpected response, will retry: %v", lastErr)
  589. return false, nil
  590. })
  591. return err == nil, lastErr
  592. }
  593. func expectForbidden(t *testing.T, f func() error) {
  594. t.Helper()
  595. if ok, err := expect(t, f, apierrors.IsForbidden); !ok {
  596. t.Errorf("Expected forbidden error, got %v", err)
  597. }
  598. }
  599. func expectNotFound(t *testing.T, f func() error) {
  600. t.Helper()
  601. if ok, err := expect(t, f, apierrors.IsNotFound); !ok {
  602. t.Errorf("Expected notfound error, got %v", err)
  603. }
  604. }
  605. func expectAllowed(t *testing.T, f func() error) {
  606. t.Helper()
  607. if ok, err := expect(t, f, func(e error) bool { return e == nil }); !ok {
  608. t.Errorf("Expected no error, got %v", err)
  609. }
  610. }