@@ -20,6 +20,7 @@ import (
2020
2121 "github.com/kinbiko/jsonassert"
2222 "github.com/stretchr/testify/assert"
23+ v1 "k8s.io/api/core/v1"
2324
2425 "go.woodpecker-ci.org/woodpecker/v2/pipeline/backend/types"
2526)
@@ -348,3 +349,66 @@ func TestFullPod(t *testing.T) {
348349 ja := jsonassert .New (t )
349350 ja .Assertf (string (podJSON ), expected )
350351}
352+
353+ func TestPodPrivilege (t * testing.T ) {
354+ createTestPod := func (stepPrivileged , globalRunAsRoot bool , secCtx SecurityContext ) (* v1.Pod , error ) {
355+ return mkPod (& types.Step {
356+ Name : "go-test" ,
357+ Image : "golang:1.16" ,
358+ Privileged : stepPrivileged ,
359+ }, & config {
360+ Namespace : "woodpecker" ,
361+ SecurityContext : SecurityContextConfig {RunAsNonRoot : globalRunAsRoot },
362+ }, "wp-01he8bebctabr3kgk0qj36d2me-0" , "linux/amd64" , BackendOptions {
363+ SecurityContext : & secCtx ,
364+ })
365+ }
366+
367+ // securty context is requesting user and group 101 (non-root)
368+ secCtx := SecurityContext {
369+ RunAsUser : newInt64 (101 ),
370+ RunAsGroup : newInt64 (101 ),
371+ FSGroup : newInt64 (101 ),
372+ }
373+ pod , err := createTestPod (false , false , secCtx )
374+ assert .NoError (t , err )
375+ assert .Equal (t , int64 (101 ), * pod .Spec .SecurityContext .RunAsUser )
376+ assert .Equal (t , int64 (101 ), * pod .Spec .SecurityContext .RunAsGroup )
377+ assert .Equal (t , int64 (101 ), * pod .Spec .SecurityContext .FSGroup )
378+
379+ // securty context is requesting root, but step is not privileged
380+ secCtx = SecurityContext {
381+ RunAsUser : newInt64 (0 ),
382+ RunAsGroup : newInt64 (0 ),
383+ FSGroup : newInt64 (0 ),
384+ }
385+ pod , err = createTestPod (false , false , secCtx )
386+ assert .NoError (t , err )
387+ assert .Nil (t , pod .Spec .SecurityContext )
388+ assert .Nil (t , pod .Spec .Containers [0 ].SecurityContext )
389+
390+ // step is not privileged, but security context is requesting privileged
391+ secCtx = SecurityContext {
392+ Privileged : newBool (true ),
393+ }
394+ pod , err = createTestPod (false , false , secCtx )
395+ assert .NoError (t , err )
396+ assert .Nil (t , pod .Spec .SecurityContext )
397+ assert .Nil (t , pod .Spec .Containers [0 ].SecurityContext )
398+
399+ // step is privileged and security context is requesting privileged
400+ secCtx = SecurityContext {
401+ Privileged : newBool (true ),
402+ }
403+ pod , err = createTestPod (true , false , secCtx )
404+ assert .NoError (t , err )
405+ assert .Equal (t , true , * pod .Spec .Containers [0 ].SecurityContext .Privileged )
406+
407+ // global runAsNonRoot is true and override is requested value by security context
408+ secCtx = SecurityContext {
409+ RunAsNonRoot : newBool (false ),
410+ }
411+ pod , err = createTestPod (false , true , secCtx )
412+ assert .NoError (t , err )
413+ assert .Equal (t , true , * pod .Spec .SecurityContext .RunAsNonRoot )
414+ }
0 commit comments