Skip to content

Commit

Permalink
Add basic seccon config flag
Browse files Browse the repository at this point in the history
  • Loading branch information
dsimansk committed Jun 27, 2023
1 parent 686b083 commit 009b2e7
Show file tree
Hide file tree
Showing 13 changed files with 116 additions and 25 deletions.
1 change: 1 addition & 0 deletions docs/cmd/kn_container_add.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ kn container add NAME
--pull-policy string Image pull policy. Valid values (case insensitive): Always | Never | IfNotPresent
--pull-secret string Image pull secret to set. An empty argument ("") clears the pull secret. The referenced secret must exist in the service's namespace.
--request strings The resource requirement requests for this Service. For example, 'cpu=100m,memory=256Mi'. You can use this flag multiple times. To unset a resource request, append "-" to the resource name, e.g. '--request cpu-'.
--security-context string Security Context definition to be added the service. Accepted values: strict | none. (default "strict")
--service-account string Service account name to set. An empty argument ("") clears the service account. The referenced service account must exist in the service's namespace.
--user int The user ID to run the container (e.g., 1001).
```
Expand Down
1 change: 1 addition & 0 deletions docs/cmd/kn_service_apply.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ kn service apply s0 --filename my-svc.yml
--scale-target int Recommendation for what metric value the PodAutoscaler should attempt to maintain. Use with --scale-metric flag to configure the metric name for which the target value should be maintained. Default metric name is concurrency. The flag defaults to --concurrency-limit when given.
--scale-utilization int Percentage of concurrent requests utilization before scaling up. (default 70)
--scale-window string Duration to look back for making auto-scaling decisions. The service is scaled to zero if no request was received in during that time. (eg: 10s)
--security-context string Security Context definition to be added the service. Accepted values: strict | none. (default "strict")
--service-account string Service account name to set. An empty argument ("") clears the service account. The referenced service account must exist in the service's namespace.
--timeout int Duration in seconds that the request routing layer will wait for a request delivered to a container to begin replying (default 300)
--user int The user ID to run the container (e.g., 1001).
Expand Down
1 change: 1 addition & 0 deletions docs/cmd/kn_service_create.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ kn service create NAME --image IMAGE
--scale-target int Recommendation for what metric value the PodAutoscaler should attempt to maintain. Use with --scale-metric flag to configure the metric name for which the target value should be maintained. Default metric name is concurrency. The flag defaults to --concurrency-limit when given.
--scale-utilization int Percentage of concurrent requests utilization before scaling up. (default 70)
--scale-window string Duration to look back for making auto-scaling decisions. The service is scaled to zero if no request was received in during that time. (eg: 10s)
--security-context string Security Context definition to be added the service. Accepted values: strict | none. (default "strict")
--service-account string Service account name to set. An empty argument ("") clears the service account. The referenced service account must exist in the service's namespace.
--tag strings Set tag (format: --tag revisionRef=tagName) where revisionRef can be a revision or '@latest' string representing latest ready revision. This flag can be specified multiple times.
--target string Work on local directory instead of a remote cluster (experimental)
Expand Down
1 change: 1 addition & 0 deletions docs/cmd/kn_service_update.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ kn service update NAME
--scale-target int Recommendation for what metric value the PodAutoscaler should attempt to maintain. Use with --scale-metric flag to configure the metric name for which the target value should be maintained. Default metric name is concurrency. The flag defaults to --concurrency-limit when given.
--scale-utilization int Percentage of concurrent requests utilization before scaling up. (default 70)
--scale-window string Duration to look back for making auto-scaling decisions. The service is scaled to zero if no request was received in during that time. (eg: 10s)
--security-context string Security Context definition to be added the service. Accepted values: strict | none. (default "strict")
--service-account string Service account name to set. An empty argument ("") clears the service account. The referenced service account must exist in the service's namespace.
--tag strings Set tag (format: --tag revisionRef=tagName) where revisionRef can be a revision or '@latest' string representing latest ready revision. This flag can be specified multiple times.
--target string Work on local directory instead of a remote cluster (experimental)
Expand Down
1 change: 1 addition & 0 deletions docs/cmd/kn_source_container_create.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ kn source container create NAME --image IMAGE --sink SINK
--pull-policy string Image pull policy. Valid values (case insensitive): Always | Never | IfNotPresent
--pull-secret string Image pull secret to set. An empty argument ("") clears the pull secret. The referenced secret must exist in the service's namespace.
--request strings The resource requirement requests for this Service. For example, 'cpu=100m,memory=256Mi'. You can use this flag multiple times. To unset a resource request, append "-" to the resource name, e.g. '--request cpu-'.
--security-context string Security Context definition to be added the service. Accepted values: strict | none. (default "strict")
--service-account string Service account name to set. An empty argument ("") clears the service account. The referenced service account must exist in the service's namespace.
-s, --sink string Addressable sink for events. You can specify a broker, channel, Knative service or URI. Examples: '--sink broker:nest' for a broker 'nest', '--sink channel:pipe' for a channel 'pipe', '--sink ksvc:mysvc:mynamespace' for a Knative service 'mysvc' in another namespace 'mynamespace', '--sink https://event.receiver.uri' for an URI with an 'http://' or 'https://' schema, '--sink ksvc:receiver' or simply '--sink receiver' for a Knative service 'receiver' in the current namespace. If a prefix is not provided, it is considered as a Knative service in the current namespace. If referring to a Knative service in another namespace, 'ksvc:name:namespace' combination must be provided explicitly.
--user int The user ID to run the container (e.g., 1001).
Expand Down
1 change: 1 addition & 0 deletions docs/cmd/kn_source_container_update.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ kn source container update NAME --image IMAGE
--pull-policy string Image pull policy. Valid values (case insensitive): Always | Never | IfNotPresent
--pull-secret string Image pull secret to set. An empty argument ("") clears the pull secret. The referenced secret must exist in the service's namespace.
--request strings The resource requirement requests for this Service. For example, 'cpu=100m,memory=256Mi'. You can use this flag multiple times. To unset a resource request, append "-" to the resource name, e.g. '--request cpu-'.
--security-context string Security Context definition to be added the service. Accepted values: strict | none. (default "strict")
--service-account string Service account name to set. An empty argument ("") clears the service account. The referenced service account must exist in the service's namespace.
-s, --sink string Addressable sink for events. You can specify a broker, channel, Knative service or URI. Examples: '--sink broker:nest' for a broker 'nest', '--sink channel:pipe' for a channel 'pipe', '--sink ksvc:mysvc:mynamespace' for a Knative service 'mysvc' in another namespace 'mynamespace', '--sink https://event.receiver.uri' for an URI with an 'http://' or 'https://' schema, '--sink ksvc:receiver' or simply '--sink receiver' for a Knative service 'receiver' in the current namespace. If a prefix is not provided, it is considered as a Knative service in the current namespace. If referring to a Knative service in another namespace, 'ksvc:name:namespace' combination must be provided explicitly.
--user int The user ID to run the container (e.g., 1001).
Expand Down
2 changes: 1 addition & 1 deletion pkg/kn/commands/service/create_mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ func getService(name string) *servingv1.Service {
Limits: corev1.ResourceList{},
Requests: corev1.ResourceList{},
},
SecurityContext: flags.DefaultSecCon(),
SecurityContext: flags.DefaultStrictSecCon(),
}}

return service
Expand Down
2 changes: 1 addition & 1 deletion pkg/kn/commands/source/container/container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func createContainerSource(name, image string, sink duckv1.Destination, ceo map[
Limits: corev1.ResourceList{},
Requests: corev1.ResourceList{},
},
SecurityContext: flags.DefaultSecCon(),
SecurityContext: flags.DefaultStrictSecCon(),
}}}).
Sink(sink).
Build()
Expand Down
17 changes: 16 additions & 1 deletion pkg/kn/flags/podspec.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ type PodSpecFlags struct {
ServiceAccountName string
ImagePullSecrets string
User int64

SecurityContext string
}

type ResourceFlags struct {
Expand Down Expand Up @@ -234,6 +236,10 @@ func (p *PodSpecFlags) AddFlags(flagset *pflag.FlagSet) []string {
flagNames = append(flagNames, "pull-secret")
flagset.Int64VarP(&p.User, "user", "", 0, "The user ID to run the container (e.g., 1001).")
flagNames = append(flagNames, "user")

flagset.StringVar(&p.SecurityContext, "security-context", "strict", "Security Context definition to be added the service. Accepted values: strict | none.")
flagNames = append(flagNames, "security-context")

return flagNames
}

Expand Down Expand Up @@ -405,7 +411,16 @@ func (p *PodSpecFlags) ResolvePodSpec(podSpec *corev1.PodSpec, flags *pflag.Flag
}
}

UpdateDefaultSecurityContext(podSpec)
if flags.Changed("security-context") && p.SecurityContext != "" {
if err := UpdateSecurityContext(podSpec, p.SecurityContext); err != nil {
return err
}
} else {
// Set default Security Context
if err := UpdateSecurityContext(podSpec, ""); err != nil {
return err
}
}

return nil
}
24 changes: 20 additions & 4 deletions pkg/kn/flags/podspec_helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,14 +380,30 @@ func UpdateImagePullPolicy(spec *corev1.PodSpec, imagePullPolicy string) error {
return nil
}

func UpdateDefaultSecurityContext(spec *corev1.PodSpec) {
// UpdateSecurityContext update the Security Context
func UpdateSecurityContext(spec *corev1.PodSpec, securityContext string) error {
container := containerOfPodSpec(spec)
if container.SecurityContext == nil {
container.SecurityContext = DefaultSecCon()
switch strings.ToLower(securityContext) {
case "none":
// Remove any Security Context defined
container.SecurityContext = nil
case "strict":
// Add or update Security Context to default strict
container.SecurityContext = DefaultStrictSecCon()
case "":
// Add default strict SC flag is not used, hence empty value
if container.SecurityContext == nil {
container.SecurityContext = DefaultStrictSecCon()
}
//TODO(dsimansk): add parsing of SC options from the flag value
default:
return fmt.Errorf("invalid --security-context %s. Valid arguments: strict | none", securityContext)
}
return nil
}

func DefaultSecCon() *corev1.SecurityContext {
// DefaultStrictSecCon helper function to get default strict Security Context
func DefaultStrictSecCon() *corev1.SecurityContext {
return &corev1.SecurityContext{
AllowPrivilegeEscalation: pointer.Bool(false),
RunAsNonRoot: pointer.Bool(true),
Expand Down
54 changes: 54 additions & 0 deletions pkg/kn/flags/podspec_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1487,3 +1487,57 @@ func TestResolveProbeOptions(t *testing.T) {
})
}
}

func TestUpdateSecurityContext(t *testing.T) {
testCases := []struct {
name string

expected *corev1.PodSpec
expectedError error
}{
{
name: "strict",
expected: &corev1.PodSpec{
Containers: []corev1.Container{
{SecurityContext: DefaultStrictSecCon()}},
},
expectedError: nil,
},
{
name: "none",
expected: &corev1.PodSpec{
Containers: []corev1.Container{{}},
},
expectedError: nil,
},
{
name: "",
expected: &corev1.PodSpec{
Containers: []corev1.Container{
{SecurityContext: DefaultStrictSecCon()}},
},
expectedError: nil,
},
{
name: "unknown",
expected: &corev1.PodSpec{
Containers: []corev1.Container{
{SecurityContext: DefaultStrictSecCon()}},
},
expectedError: errors.New("invalid --security-context unknown. Valid arguments: strict | none"),
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
actual := &corev1.PodSpec{}
err := UpdateSecurityContext(actual, tc.name)
if tc.expectedError != nil {
assert.Error(t, err, tc.expectedError.Error())
} else {
assert.NilError(t, err)
assert.DeepEqual(t, actual, tc.expected)
}
})
}
}
32 changes: 16 additions & 16 deletions pkg/kn/flags/podspec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,22 @@ import (
"github.com/spf13/cobra"
"gotest.tools/v3/assert"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
"knative.dev/client/pkg/util"
"knative.dev/pkg/ptr"
)

func TestPodSpecFlags(t *testing.T) {
args := []string{"--image", "repo/user/imageID:tag", "--env", "b=c"}
wantedPod := &PodSpecFlags{
Image: "repo/user/imageID:tag",
Env: []string{"b=c"},
EnvFrom: []string{},
EnvValueFrom: []string{},
Mount: []string{},
Volume: []string{},
Arg: []string{},
Command: []string{},
Image: "repo/user/imageID:tag",
Env: []string{"b=c"},
EnvFrom: []string{},
EnvValueFrom: []string{},
Mount: []string{},
Volume: []string{},
Arg: []string{},
Command: []string{},
SecurityContext: "strict",
}
flags := &PodSpecFlags{}
testCmd := &cobra.Command{
Expand Down Expand Up @@ -86,12 +86,12 @@ func TestPodSpecResolve(t *testing.T) {
},
},
ReadinessProbe: &corev1.Probe{
ProbeHandler: v1.ProbeHandler{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{Port: intstr.Parse("8080"), Path: "/path"},
},
},
LivenessProbe: &corev1.Probe{
ProbeHandler: v1.ProbeHandler{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{Port: intstr.Parse("8080"), Path: "/path"},
},
},
Expand Down Expand Up @@ -223,7 +223,7 @@ containers:
Limits: corev1.ResourceList{},
Requests: corev1.ResourceList{},
},
SecurityContext: DefaultSecCon(),
SecurityContext: DefaultStrictSecCon(),
},
{
Name: "foo",
Expand Down Expand Up @@ -394,11 +394,11 @@ func TestPodSpecResolveWithEnvFile(t *testing.T) {
},
},
Env: []corev1.EnvVar{{Name: "svcOwner", Value: "James"}, {Name: "svcAuthor", Value: "James"}},
Resources: v1.ResourceRequirements{
Limits: v1.ResourceList{},
Requests: v1.ResourceList{},
Resources: corev1.ResourceRequirements{
Limits: corev1.ResourceList{},
Requests: corev1.ResourceList{},
},
SecurityContext: DefaultSecCon(),
SecurityContext: DefaultStrictSecCon(),
},
},
}
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/service_export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func TestServiceExport(t *testing.T) {
defer r.DumpIfFailed()

t.Log("create service with byo revision")
serviceCreateWithOptions(r, "hello", "--revision-name", "rev1")
serviceCreateWithOptions(r, "hello", "--revision-name", "rev1", "--security-context=none")

userImage := pkgtest.ImagePath("helloworld")
if strings.Contains(userImage, "@") {
Expand Down Expand Up @@ -233,7 +233,7 @@ func TestServiceExport(t *testing.T) {
), "--with-revisions", "--mode", "export", "-o", "yaml")

t.Log("create and export service 'foo' and verify that serviceUID and configurationUID labels are absent")
serviceCreateWithOptions(r, "foo")
serviceCreateWithOptions(r, "foo", "--security-context=none")
output := serviceExportOutput(r, "foo", "-o", "json")
actSvc := servingv1.Service{}
err = json.Unmarshal([]byte(output), &actSvc)
Expand Down

0 comments on commit 009b2e7

Please sign in to comment.