Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Documentation for all the functions in Access-control #1923

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions cnf-certification-test/accesscontrol/namespace/namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ import (
)

// TestCrsNamespaces finds the list of the input CRDs (crds parameter) instances (CRs) and verify that they are only in namespaces provided as input.
// The list of CRs not belonging to the namespaces passed as input is returned as invalid
// Returns :
// - map[string]map[string][]string : The list of CRs not belonging to the namespaces passed as input is returned as invalid.
// - error : if exist error.
func TestCrsNamespaces(crds []*apiextv1.CustomResourceDefinition, configNamespaces []string, logger *log.Logger) (invalidCrs map[string]map[string][]string, err error) {
// Initialize the top level map
invalidCrs = make(map[string]map[string][]string)
Expand All @@ -54,7 +56,9 @@ func TestCrsNamespaces(crds []*apiextv1.CustomResourceDefinition, configNamespac
}

// getCrsPerNamespaces gets the list of CRs instantiated in the cluster per namespace.
// Returns a map indexed by namespace and data is a list of CR names
// Returns :
// - map[string][]string : a map indexed by namespace and data is a list of CR names.
// - error : if exist error.
func getCrsPerNamespaces(aCrd *apiextv1.CustomResourceDefinition) (crdNamespaces map[string][]string, err error) {
oc := clientsholder.GetClientsHolder()
for _, version := range aCrd.Spec.Versions {
Expand Down Expand Up @@ -90,7 +94,9 @@ func getCrsPerNamespaces(aCrd *apiextv1.CustomResourceDefinition) (crdNamespaces
return crdNamespaces, nil
}

// GetInvalidCRDsNum returns the number of invalid CRs in the map
// GetInvalidCRDsNum returns the number of invalid CRs in the map.
// Return:
// - int : number of invalid CRs in the map.
func GetInvalidCRsNum(invalidCrs map[string]map[string][]string, logger *log.Logger) int {
var invalidCrsNum int
for crdName, namespaces := range invalidCrs {
Expand Down
4 changes: 4 additions & 0 deletions cnf-certification-test/accesscontrol/pidshelper.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ import (

const nbProcessesIndex = 2

// getNbOfProcessesInPidNamespace retrieves the number of processes in the Pid namespace.
// Returns:
// - int : the number of processes in the PID namespace associated with the specified process ID
// - error : An error, if any occurred during the execution of the command or parsing of the output.
func getNbOfProcessesInPidNamespace(ctx clientsholder.Context, targetPid int, ch clientsholder.Command) (int, error) {
cmd := "lsns -p " + strconv.Itoa(targetPid) + " -t pid -n"

Expand Down
10 changes: 10 additions & 0 deletions cnf-certification-test/accesscontrol/rbac/automount.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ import (
corev1typed "k8s.io/client-go/kubernetes/typed/core/v1"
)

// AutomountServiceAccountSetOnSA checks if the AutomountServiceAccountToken field is set on a ServiceAccount.
// Returns:
// - A boolean pointer indicating whether the AutomountServiceAccountToken field is set.
// - An error if any occurred during the operation.
func AutomountServiceAccountSetOnSA(client corev1typed.CoreV1Interface, serviceAccountName, podNamespace string) (*bool, error) {
sa, err := client.ServiceAccounts(podNamespace).Get(context.TODO(), serviceAccountName, metav1.GetOptions{})
if err != nil {
Expand All @@ -35,6 +39,12 @@ func AutomountServiceAccountSetOnSA(client corev1typed.CoreV1Interface, serviceA
return sa.AutomountServiceAccountToken, nil
}

// EvaluateAutomountTokens evaluates whether the automountServiceAccountToken is correctly configured for the given Pod.
// Checks if the token is explicitly set in the Pod's spec or if it is inherited from the associated ServiceAccount.
// Returns:
// - bool: Indicates whether the Pod passed all checks. if yes- return true, otherwise return false.
// - string: Error message if the Pod is misconfigured, otherwise an empty string.
//
//nolint:gocritic
func EvaluateAutomountTokens(client corev1typed.CoreV1Interface, put *corev1.Pod) (bool, string) {
// The token can be specified in the pod directly
Expand Down
17 changes: 16 additions & 1 deletion cnf-certification-test/accesscontrol/rbac/roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ type CrdResource struct {
ShortNames []string
}

// GetCrdResources converts a list of apiextv1.CustomResourceDefinition structs into a list of list of CrdResource structs.
// Returns:
// - []CrdResource : a slice of CrdResource objects.
func GetCrdResources(crds []*apiextv1.CustomResourceDefinition) (resourceList []CrdResource) {
for _, crd := range crds {
var aResource CrdResource
Expand All @@ -48,6 +51,9 @@ func GetCrdResources(crds []*apiextv1.CustomResourceDefinition) (resourceList []
return resourceList
}

// GetAllRules retrieves a list all of rules defined by the role passed in input.
// Returns:
// - []RoleRule : a slice of RoleRule objects.
func GetAllRules(aRole *rbacv1.Role) (ruleList []RoleRule) {
for _, aRule := range aRole.Rules {
for _, aGroup := range aRule.APIGroups {
Expand All @@ -65,14 +71,20 @@ func GetAllRules(aRole *rbacv1.Role) (ruleList []RoleRule) {
return ruleList
}

// Checks the resource name in the role against plural name
// isResourceInRoleRule Checks if a CRD resource is matched by a rule by comparing its group and plural name.
// Returns:
// - bool : if a CrdResource matches a RoleRule based on their properties return true , otherwise return false.
func isResourceInRoleRule(crd CrdResource, roleRule RoleRule) bool {
// remove subresources to keep only resource (plural) name
ruleResourcePluralName := strings.Split(roleRule.Resource.Name, "/")[0]

return crd.Group == roleRule.Resource.Group && crd.PluralName == ruleResourcePluralName
}

// FilterRulesNonMatchingResources filters RoleRules based on whether they match any CrdResource in the resourceList.
// Returns :
// - Matching: a slice of RoleRule that contains all rules where a CrdResource matches a RoleRule based on their properties.
// - NonMatching: a slice of RoleRule that contains all rules not matching the CRD resource.
func FilterRulesNonMatchingResources(ruleList []RoleRule, resourceList []CrdResource) (matching, nonMatching []RoleRule) {
for _, aRule := range ruleList {
for _, aResource := range resourceList {
Expand All @@ -85,6 +97,9 @@ func FilterRulesNonMatchingResources(ruleList []RoleRule, resourceList []CrdReso
return matching, nonMatching
}

// SliceDifference checks if there is a difference between s1 and s2 RoleRule slices.
// Returns :
// - []RoleRule : the elements that are exist in s1 but not in s2.
func SliceDifference(s1, s2 []RoleRule) (diff []RoleRule) {
var temp []RoleRule
if len(s2) > len(s1) {
Expand Down
6 changes: 6 additions & 0 deletions cnf-certification-test/accesscontrol/resources/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import (
"github.com/test-network-function/cnf-certification-test/pkg/provider"
)

// HasRequestsAndLimitsSet checks if a container has both resource limits and resource requests set.
// Returns :
// - bool : true if both resource limits and resource requests are set for the container, otherwise return false.
func HasRequestsAndLimitsSet(cut *provider.Container, logger *log.Logger) bool {
passed := true
// Parse the limits.
Expand Down Expand Up @@ -42,6 +45,9 @@ func HasRequestsAndLimitsSet(cut *provider.Container, logger *log.Logger) bool {
}

// For more info on cpu management policies see https://kubernetes.io/docs/tasks/administer-cluster/cpu-management-policies/.
// HasExclusiveCPUsAssigned checks if a container has exclusive CPU's assigned.
// Returns:
// - bool : true if a container has exclusive CPU's assigned, otherwise return false.
func HasExclusiveCPUsAssigned(cut *provider.Container, logger *log.Logger) bool {
cpuLimits := cut.Resources.Limits.Cpu()
memLimits := cut.Resources.Limits.Memory()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ const (
CategoryID4String = "CategoryID4(anything not matching lower category)"
)

// print the strings
// String converts the category to a string.
// Returns:
// - string: The string representation of the Category.
func (category CategoryID) String() string {
switch category {
case CategoryID1:
Expand All @@ -182,6 +184,10 @@ func (category CategoryID) String() string {
return CategoryID4String
}

// GetContainerSCC is update the containerSCC according capability of container(cut)
// Returns:
// - ContainerSCC: struct that updated according continer(cut)
//
//nolint:gocritic
func GetContainerSCC(cut *provider.Container, containerSCC ContainerSCC) ContainerSCC {
containerSCC.HostPorts = NOK
Expand Down Expand Up @@ -217,6 +223,7 @@ func GetContainerSCC(cut *provider.Container, containerSCC ContainerSCC) Contain
return containerSCC
}

// updateCapabilitiesFromContainer update the per container capabilities with the capabilities defined at the container level.
func updateCapabilitiesFromContainer(cut *provider.Container, containerSCC *ContainerSCC) {
containerSCC.RequiredDropCapabilitiesPresent = NOK
if cut.SecurityContext != nil && cut.SecurityContext.Capabilities != nil {
Expand Down Expand Up @@ -249,6 +256,10 @@ func updateCapabilitiesFromContainer(cut *provider.Container, containerSCC *Cont
}
}

// AllVolumeAllowed checks if all volumes in the provided slice are allowed based on certain criteria.
// Returns :
// - r1 : whether all volumes are allowed (OK/NOK)
// - r2 : whether any volume with HostPath is found (OK/NOK)
func AllVolumeAllowed(volumes []corev1.Volume) (r1, r2 OkNok) {
countVolume := 0
var value OkNok
Expand Down Expand Up @@ -282,6 +293,11 @@ func AllVolumeAllowed(volumes []corev1.Volume) (r1, r2 OkNok) {
return NOK, value
}

// checkContainerCategory categorizes each container based on Security context.
// builds a list of PodListCategory structs , each representing a container along with its category information.
// Returns:
// - []PodListCategory: a slice of PodListCategory structs representing categorized containers.
//
//nolint:gocritic
func checkContainerCategory(containers []corev1.Container, containerSCC ContainerSCC, podName, nameSpace string) []PodListCategory {
var ContainerList []PodListCategory
Expand Down Expand Up @@ -312,6 +328,9 @@ func checkContainerCategory(containers []corev1.Container, containerSCC Containe
return ContainerList
}

// checkContainCategory checks whether all elements in the addCapability exist in referenceCategoryAddCapabilities
// Returns:
// - bool: true if all elements in the addCapability exist in referenceCategoryAddCapabilities, otherwise return false
func checkContainCategory(addCapability []corev1.Capability, referenceCategoryAddCapabilities []string) bool {
for _, ncc := range addCapability {
if !stringhelper.StringInSlice(referenceCategoryAddCapabilities, string(ncc), true) {
Expand All @@ -321,6 +340,11 @@ func checkContainCategory(addCapability []corev1.Capability, referenceCategoryAd
return true
}

// CheckPod updates the containerSCC objects with security context variable defined at the Pod Level. Then it updates the containerSCC object with security context values overloaded at the container level.
// It then categorizes each container based on specific conditions and constructs a list of PodListCategory structs,
// each representing a container along with its category information.
// Returns:
// - []PodListCategory: a slice of PodListCategory structs representing categorized containers for the pod.
func CheckPod(pod *provider.Pod) []PodListCategory {
var containerSCC ContainerSCC
containerSCC.HostIPC = NOK
Expand Down Expand Up @@ -353,6 +377,10 @@ func CheckPod(pod *provider.Pod) []PodListCategory {
return checkContainerCategory(pod.Spec.Containers, containerSCC, pod.Name, pod.Namespace)
}

// compareCategory compare between the fields in refCategory and containerSCC
// Returns:
// - bool : true if containerSCC matches the reference category, otherwise return false.
//
//nolint:funlen
func compareCategory(refCategory, containerSCC *ContainerSCC, id CategoryID) bool {
result := true
Expand Down
Loading
Loading