knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/test/security/security.go (about)

     1  /*
     2  Copyright 2022 The Knative Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package security
    18  
    19  import (
    20  	"context"
    21  
    22  	corev1 "k8s.io/api/core/v1"
    23  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    24  	"k8s.io/client-go/kubernetes"
    25  	"knative.dev/pkg/ptr"
    26  )
    27  
    28  var DefaultPodSecurityContext = corev1.PodSecurityContext{
    29  	RunAsNonRoot: ptr.Bool(true),
    30  	SeccompProfile: &corev1.SeccompProfile{
    31  		Type: corev1.SeccompProfileTypeRuntimeDefault,
    32  	},
    33  }
    34  
    35  var DefaultContainerSecurityContext = corev1.SecurityContext{
    36  	AllowPrivilegeEscalation: ptr.Bool(false),
    37  	Capabilities: &corev1.Capabilities{
    38  		Drop: []corev1.Capability{"ALL"},
    39  	},
    40  }
    41  
    42  // AllowRestrictedPodSecurityStandard adds SecurityContext to Pod and its containers so that it can run
    43  // in a namespace with enforced "restricted" security standard.
    44  func AllowRestrictedPodSecurityStandard(ctx context.Context, kubeClient kubernetes.Interface, pod *corev1.Pod) error {
    45  	enforced, err := IsRestrictedPodSecurityEnforced(ctx, kubeClient, pod.Namespace)
    46  	if err != nil {
    47  		return err
    48  	}
    49  	if enforced {
    50  		pod.Spec.SecurityContext = &DefaultPodSecurityContext
    51  		for _, c := range pod.Spec.Containers {
    52  			c.SecurityContext = &DefaultContainerSecurityContext
    53  		}
    54  	}
    55  	return nil
    56  }
    57  
    58  // IsRestrictedPodSecurityEnforced checks if the given namespace has enforced restricted security standard.
    59  func IsRestrictedPodSecurityEnforced(ctx context.Context, kubeClient kubernetes.Interface, namespace string) (bool, error) {
    60  	ns, err := kubeClient.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
    61  	if err != nil {
    62  		return false, err
    63  	}
    64  	for k, v := range ns.Labels {
    65  		if k == "pod-security.kubernetes.io/enforce" && v == "restricted" {
    66  			return true, nil
    67  		}
    68  	}
    69  	return false, nil
    70  }