...
1
16
17 package pod
18
19 import (
20 "testing"
21
22 "github.com/stretchr/testify/assert"
23 v1 "k8s.io/api/core/v1"
24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
25 "k8s.io/utils/pointer"
26 )
27
28 func TestMixinRestrictedPodSecurity(t *testing.T) {
29 restrictablePods := []v1.Pod{{
30 ObjectMeta: metav1.ObjectMeta{
31 Name: "default",
32 },
33 Spec: v1.PodSpec{
34 Containers: []v1.Container{{
35 Name: "pause",
36 Image: "pause",
37 }},
38 },
39 }, {
40 ObjectMeta: metav1.ObjectMeta{
41 Name: "already_restricted",
42 },
43 Spec: v1.PodSpec{
44 SecurityContext: GetRestrictedPodSecurityContext(),
45 Containers: []v1.Container{{
46 Name: "pause",
47 Image: "pause",
48 SecurityContext: GetRestrictedContainerSecurityContext(),
49 }},
50 },
51 }, {
52 ObjectMeta: metav1.ObjectMeta{
53 Name: "empty_securityContext",
54 },
55 Spec: v1.PodSpec{
56 SecurityContext: &v1.PodSecurityContext{},
57 Containers: []v1.Container{{
58 Name: "pause",
59 Image: "pause",
60 SecurityContext: &v1.SecurityContext{},
61 }},
62 },
63 }}
64
65 for _, pod := range restrictablePods {
66 t.Run(pod.Name, func(t *testing.T) {
67 p := pod
68 assert.NoError(t, MixinRestrictedPodSecurity(&p))
69 assert.Equal(t, GetRestrictedPodSecurityContext(), p.Spec.SecurityContext,
70 "Mixed in PodSecurityContext should equal the from-scratch PodSecurityContext")
71 assert.Equal(t, GetRestrictedContainerSecurityContext(), p.Spec.Containers[0].SecurityContext,
72 "Mixed in SecurityContext should equal the from-scratch SecurityContext")
73 })
74 }
75
76 privilegedPod := v1.Pod{
77 ObjectMeta: metav1.ObjectMeta{
78 Name: "privileged",
79 },
80 Spec: v1.PodSpec{
81 Containers: []v1.Container{{
82 Name: "pause",
83 Image: "pause",
84 SecurityContext: &v1.SecurityContext{
85 Privileged: pointer.Bool(true),
86 },
87 }},
88 },
89 }
90 t.Run("privileged", func(t *testing.T) {
91 assert.Error(t, MixinRestrictedPodSecurity(&privilegedPod))
92 })
93
94 }
95
View as plain text