Skip to content

Commit d6b0c35

Browse files
authored
CMP-2870, CMP-2869, CMP-2870, CMP-2872, CMP-2868: Compliance SDK Compliance Operator Implementation (#811)
* feat: Add CustomRule CRD for custom compliance rules Adds a new CustomRule CRD to support user-defined compliance rules with CEL expressions * Enhance TailoredProfile to support CustomRules Add CustomRule handling logic Validate rule types consistency Update ownership management logic Ensure correct product type annotation for CustomRUle Ensure correct scannerType annotation is set * feat: Add initial CEL expression scanner pod implmentation * Fix CustomRule api verify-bundle error Fix an issues that fails verify-bundle make target, we need to move rulepayload under Spec * Skip not used component for CEL scan We are going to disable the raw stroage related resources as well as runtime kubeletconfig for CEL as those are not going to be used * Skip aggregator for cel scanner based Scan * Handle CustomRule in ScanSettingBinding Controller We are modifying the ScanSettingBinding controller so that if tailoredProfile is referencing CustomRule will be handled accordingly, we are also removing the not used scannerImage field in ComplianceScan CRD * Update ScanHandler to support CEL We are updating the Platform ScanHandler to be able to process CEL based CustomRule. * Add CCR generation in CEL-Scanner We are adding the ability to generate ComplianceCheckResult directly in CEL scanner * Update TailoredProfile status for CustomRule * Fix tailoredProfile controller annotation generation for Custom CEL Rule * Add custom rule annotation for ComplianceSuite Controller * Add CEL-scanner cmd * Fix UUID generation for CustomRule * Add CEL demo files * Fix issues in cel scanner cmd * Fill correct tp information for CustomRule in the Scan * Add rbac for CEL Scanner * Fix cmd flag and client creation for CEL scanner * Adjust demo, add rbac for kubevirt rule * Fix issue with CEl scanner Use correct resouce as input for cel scanner * Add necessary permission so scanner can set ownership to CCR * Make KubeResource Input as inline config This will align with enhancement, make input KubeResource as inline config under input instead of having it under input.KubeResource * Add more demo files for CEL * Update tailoredProfile controller to watch for CustomRule changes * Fix the CEL aggregation phase Updating platformScanTypeHandler to handle compliance result for CEL correctly during aggregator phase so that we can move to Done state. * Change check status to Fail for not fetched resource We are switching the ComplianceCheckStatus to Fail Instead of error for resource that we are not able to fetch. We will only set it to error when we were having other issues evaluating the rule. This matches the openscap default behavior. * Fix duplicated scanner pod for OpenScap scan This is to revert changes made to scanner pod config, so that OpenScap can run without issues. * Add support for custom variables in CEL scanner and tailored profile * Add README for writing and running CEL rules in Compliance Operator * remove unwanted changes * Make OpenSCAP as default value for scannerType This makes changes backward compatible and will also address some e2e failures with rerunner * Updating scanner field description * Add CEL scanner module with comprehensive architecture and input handling This commit introduces a new CEL scanner module designed for compliance checking using Google's Common Expression Language (CEL). Key features include: - A flexible architecture supporting multiple input types (Kubernetes, filesystem, system commands). - Comprehensive test coverage with unit, integration, and benchmark tests. - Detailed documentation including usage guides and architecture principles. - New input fetchers for Kubernetes and filesystem resources, along with system command execution capabilities. This implementation enhances the compliance operator's ability to evaluate rules against various data sources, ensuring a robust compliance scanning solution. * Update go.sum to remove unused dependencies and update existing ones from mergy conflict with master * Install compliance-sdk go1.23 dependency * Remove deprecated cel-scanner-refactored.go and eliminate unused components. * Refactor KubeResource structure in customrule_types.go to integrate KubernetesInputSpec from compliance-sdk This update modifies the KubeResource type to include a KubernetesInputSpec field, enhancing the input handling for compliance rules. The InputPayload structure has also been adjusted to reflect this change, improving the overall architecture for compliance scanning. * Add custom rule controller and unit tests for validation This commit introduces a new controller for managing custom rules within the compliance operator. It includes the implementation of the `add_customrule.go` file, which registers the custom rule controller with the manager. Additionally, comprehensive unit tests have been added in `customrule_controller_test.go` to validate the reconciliation logic and structure of custom rules, ensuring proper handling of various scenarios including valid and invalid rules. * Update compliance-sdk dependency and enhance CustomRule CRD with validation features This commit updates the compliance-sdk dependency to a newer version, improving compatibility and functionality. Additionally, it enhances the CustomRule Custom Resource Definition (CRD) by adding additional printer columns for better visibility of rule status and severity. The validation structure for CustomRule inputs has been refined, ensuring more robust error handling and validation during rule processing. Unit tests have been updated to reflect these changes, ensuring comprehensive coverage of the new features. * Add support for deprecated tailored profile notifications in ComplianceScan for CustomRule This commit enhances the ComplianceScan controller to notify users when a deprecated tailored profile is in use for CEL scanner types. * Refactor CEL scanner to integrate compliance-sdk and enhance logging This commit refactors the CEL scanner implementation to utilize the compliance-sdk for improved resource fetching and scanning capabilities. * Remove deprecated CEL demo rules and associated resources; add new custom rule for pod security context as for the demo. * Add e2e tests for customRule This commit adds tests for CustomRule functionality, including tests for tailored profiles, validation of CEL expressions, and handling of multiple inputs. * Revert image registry cleanup in Makefile * Remove unused DeriveResourcePath function and clean up imports in common.go * Move end-to-end tests for CustomRule functionality to Parallel * Refactor CustomRule validation tests to improve error handling This commit updates the error handling in the CustomRule validation tests, it was asserting the wrong result * Update CustomRule and TailoredProfile descriptions for clarity This commit refines the descriptions in the CustomRule and TailoredProfile CRDs to enhance clarity, specifically changing references from "XCCDF ID" to "ID of the Rule" and improving the wording of scanner type descriptions. Additionally, it updates the CustomRule validation logic to use the new CustomRulePayload structure, ensuring consistency across the codebase. Unit tests have been adjusted accordingly to reflect these changes. * Clean Up not used CRD and RBAC config * Add checkType to CustomRule examples. * Refactor CustomRule to replace ErrorMessage with FailureReason * Enhance ScanSettingBinding status handling in controller This commit introduces logic to transition the ScanSettingBinding status from Invalid to Ready when the associated TailoredProfile is fixed. It updates the status check function to account for this transition and adds corresponding unit tests to verify the behavior. * Remove unused label from custom security checks profile in pod security configuration * Update CustomRule descriptions for improved clarity * Revert the id field of Rule and TailoredProfile to be XCCDF ID * Enhance descriptions for rule reference in TailoredProfiles and CRDs to improve clarity. Specify the type of rule reference as "Rule" or "CustomRule" and clarify default behavior. * Update ComplianceScanSpec and CustomRule definitions for improved clarity and validation. Enhance ScannerType description and add validation enum for ScannerType. Remove unused Severity column from CustomRule resource definition. * Rename getCelScannerClient to getRuntimeClient for improved clarity in client creation function. * Refactor CelScanner configuration to use ApiResourceCacheDir instead of ApiResourcePath for API resources are cached ApiResourceCacheDir unambiguously refers to a local filesystem directory where API resources are cached * Update failure reason in CustomRule for pod security context validation * Enhance error logging and refactor variable handling in CelScanner. Improved log messages to include additional context for profile and tailored profile errors. * Change scan result output format from XML to JSON in CelScanner and update serialization error messages for clarity. * Add error handling for ComplianceCheckResult operations in CelScanner Implement os.Exit with CelExitCodeError for error scenarios when listing, creating/updating, and deleting ComplianceCheckResults to ensure proper termination on failure. * Refactor object retrieval logic in CelScanner and introduce utility function for improved error handling Replace the existing getObjectIfFoundCEL function with a new utility function GetObjectIfFound in the utils package, which implements retry logic with exponential backoff for retrieving Kubernetes objects. Additionally, correct spelling errors in method names related to scanner type validation in ComplianceScan. * Update CustomRuleProfileAnnotation to clarify its purpose as tailored profile containing custom rules * Refactor CustomRule validation logic to remove redudent checks performed by kubebuilder * Update CustomRule ID in TestCustomRuleTailoredProfile to just use customRuleName * Fix TestCustomRuleTailoredProfile e2e test * Add readiness check for ScanSettingBinding in TestCustomRuleWithMultipleInputs * Fix spelling error in scanner type validation method in ComplianceScan * Add TestCustomRuleCascadingStatusUpdate to validate cascading status changes This test checks the behavior of CustomRule, TailoredProfile, and ScanSettingBinding when a CustomRule is updated with an invalid expression. It verifies that the resources transition to error states and subsequently recover when the expression is fixed. Additionally, it updates the ID fields in existing tests to use consistent naming conventions. * Refactor TestCustomRuleTailoredProfile to improve pod creation logic and update compliance expectations. The test now verifies that a pod without the test label is ignored, while a pod with the label is expected to be non-compliant due to the absence of a security context. * Add validation to prevent mixing CustomRules and regular Rules in TailoredProfile * Add FailureReason to warnings in ComplianceCheckResult for failed scans * Adjusted the rule in TestTailoredProfileRejectsMixedRuleTypes to fix error in tailoredProfile states caused by node rule platform mixing. * Refactor TailoredProfile controller logic and enhance test validations. Updated condition for custom rules check and improved error messaging for unsupported rule types. Enhanced tests to validate CustomRule results, ensuring accurate compliance status reporting. * Update scan name assignment in CustomRule tests to use TailoredProfile name. This change clarifies the expected behavior for TailoredProfiles in the tests, ensuring accurate compliance check results. * Added validation to ensure CustomRules only use 'Platform' as the check type and 'CEL' as the scanner type. Updated descriptions in CRDs for clarity on rule ID and check type restrictions. * Update error logging in CelScanner to use TailoredProfile name for improved clarity in scan failure messages. * Refactor error handling in TestCustomRuleCheckTypeAndScannerTypeValidation to improve clarity on invalid scannerType creation. Removed unnecessary status checks and streamlined test logic for better readability.
1 parent 8277b8d commit d6b0c35

File tree

420 files changed

+99376
-18958
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

420 files changed

+99376
-18958
lines changed

PROJECT

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# Code generated by tool. DO NOT EDIT.
2+
# This file is used to track the info used to scaffold your project
3+
# and allow the plugins properly work.
4+
# More info: https://book.kubebuilder.io/reference/project-config.html
15
domain: openshift.io
26
layout:
37
- go.kubebuilder.io/v3
@@ -61,4 +65,12 @@ resources:
6165
kind: TailoredProfile
6266
path: github.com/ComplianceAsCode/compliance-operator/api/v1alpha1
6367
version: v1alpha1
68+
- api:
69+
crdVersion: v1
70+
namespaced: true
71+
domain: openshift.io
72+
group: compliance
73+
kind: CustomRule
74+
path: github.com/ComplianceAsCode/compliance-operator/api/v1alpha1
75+
version: v1alpha1
6476
version: "3"

bundle/manifests/compliance-operator.clusterserviceversion.yaml

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,12 @@ spec:
206206
kind: ComplianceSuite
207207
name: compliancesuites.compliance.openshift.io
208208
version: v1alpha1
209+
- description: CustomRule represents a rule that can be used with TailoredProfiles
210+
to execute arbitrary checks against the cluster.
211+
displayName: Custom Rule
212+
kind: CustomRule
213+
name: customrules.compliance.openshift.io
214+
version: v1alpha1
209215
- description: ProfileBundle is the Schema for the profilebundles API
210216
displayName: Profile Bundle
211217
kind: ProfileBundle
@@ -1034,16 +1040,47 @@ spec:
10341040
- get
10351041
- list
10361042
- watch
1043+
- apiGroups:
1044+
- compliance.openshift.io
1045+
resources:
1046+
- compliancescans/finalizers
1047+
- compliancecheckresults/finalizers
1048+
verbs:
1049+
- update
10371050
- apiGroups:
10381051
- compliance.openshift.io
10391052
resources:
10401053
- compliancesuites
1054+
- compliancescans
10411055
- scansettings
10421056
- scansettingbindings
1057+
- tailoredprofiles
1058+
- customrules
1059+
- variables
1060+
verbs:
1061+
- get
1062+
- list
1063+
- watch
1064+
- apiGroups:
1065+
- hco.kubevirt.io
1066+
resources:
1067+
- '*'
10431068
verbs:
10441069
- get
10451070
- list
10461071
- watch
1072+
- apiGroups:
1073+
- compliance.openshift.io
1074+
resources:
1075+
- compliancecheckresults
1076+
verbs:
1077+
- get
1078+
- list
1079+
- watch
1080+
- update
1081+
- patch
1082+
- create
1083+
- delete
10471084
- apiGroups:
10481085
- machineconfiguration.openshift.io
10491086
resources:

bundle/manifests/compliance.openshift.io_compliancescans.yaml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,14 @@ spec:
273273
default: Node
274274
description: The type of Compliance scan.
275275
type: string
276+
scannerType:
277+
default: OpenSCAP
278+
description: The scanner used to evaluate the rules in a Profile or
279+
TailoredProfile.
280+
enum:
281+
- OpenSCAP
282+
- CEL
283+
type: string
276284
showNotApplicable:
277285
default: false
278286
description: Determines whether to hide or show results that are not

bundle/manifests/compliance.openshift.io_compliancesuites.yaml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,14 @@ spec:
292292
default: Node
293293
description: The type of Compliance scan.
294294
type: string
295+
scannerType:
296+
default: OpenSCAP
297+
description: The scanner used to evaluate the rules in a Profile
298+
or TailoredProfile.
299+
enum:
300+
- OpenSCAP
301+
- CEL
302+
type: string
295303
showNotApplicable:
296304
default: false
297305
description: Determines whether to hide or show results that
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
apiVersion: apiextensions.k8s.io/v1
2+
kind: CustomResourceDefinition
3+
metadata:
4+
annotations:
5+
controller-gen.kubebuilder.io/version: v0.17.1
6+
creationTimestamp: null
7+
name: customrules.compliance.openshift.io
8+
spec:
9+
group: compliance.openshift.io
10+
names:
11+
kind: CustomRule
12+
listKind: CustomRuleList
13+
plural: customrules
14+
singular: customrule
15+
scope: Namespaced
16+
versions:
17+
- additionalPrinterColumns:
18+
- jsonPath: .status.phase
19+
name: Status
20+
type: string
21+
- jsonPath: .metadata.creationTimestamp
22+
name: Age
23+
type: date
24+
name: v1alpha1
25+
schema:
26+
openAPIV3Schema:
27+
description: CustomRule represents a rule that can be used with TailoredProfiles
28+
to execute arbitrary checks against the cluster.
29+
properties:
30+
apiVersion:
31+
description: |-
32+
APIVersion defines the versioned schema of this representation of an object.
33+
Servers should convert recognized schemas to the latest internal value, and
34+
may reject unrecognized values.
35+
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
36+
type: string
37+
kind:
38+
description: |-
39+
Kind is a string value representing the REST resource this object represents.
40+
Servers may infer this from the endpoint the client submits requests to.
41+
Cannot be updated.
42+
In CamelCase.
43+
More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
44+
type: string
45+
metadata:
46+
type: object
47+
spec:
48+
properties:
49+
availableFixes:
50+
description: The Available fixes
51+
items:
52+
description: |-
53+
FixDefinition Specifies a fix or remediation
54+
that applies to a rule
55+
properties:
56+
disruption:
57+
description: |-
58+
An estimate of the potential disruption or operational
59+
degradation that this fix will impose in the target system
60+
type: string
61+
fixObject:
62+
description: an object that should bring the rule into compliance
63+
type: object
64+
x-kubernetes-embedded-resource: true
65+
x-kubernetes-preserve-unknown-fields: true
66+
platform:
67+
description: The platform that the fix applies to
68+
type: string
69+
type: object
70+
nullable: true
71+
type: array
72+
x-kubernetes-list-type: atomic
73+
checkType:
74+
description: |-
75+
What type of check will this rule execute:
76+
Platform, Node or none (represented by an empty string)
77+
For CustomRules, only Platform is supported.
78+
type: string
79+
description:
80+
description: The description of the Rule
81+
type: string
82+
expression:
83+
description: Expression is the CEL expression to evaluate
84+
minLength: 1
85+
type: string
86+
failureReason:
87+
description: FailureReason is displayed when the rule evaluation fails
88+
minLength: 1
89+
type: string
90+
id:
91+
description: The ID of the Rule
92+
type: string
93+
inputs:
94+
description: Inputs defines the Kubernetes resources that need to
95+
be fetched before evaluating the expression
96+
items:
97+
properties:
98+
kubernetesInputSpec:
99+
description: KubernetesInputSpec is the specification of the
100+
Kubernetes resource to fetch
101+
properties:
102+
apiVersion:
103+
description: APIVersion is the API version (e.g., "v1",
104+
"v1beta1")
105+
minLength: 1
106+
type: string
107+
group:
108+
description: Group is the API group (e.g., "apps", "" for
109+
core resources)
110+
type: string
111+
resource:
112+
description: |-
113+
Resource is the resource type (e.g., "pods", "configmaps")
114+
Use the plural form of the resource
115+
minLength: 1
116+
type: string
117+
resourceName:
118+
description: |-
119+
ResourceName is the specific resource name
120+
Leave empty to fetch all resources of this type
121+
type: string
122+
resourceNamespace:
123+
description: |-
124+
ResourceNamespace is the namespace to search in
125+
Leave empty for cluster-scoped resources or to search all namespaces
126+
type: string
127+
required:
128+
- apiVersion
129+
- resource
130+
type: object
131+
name:
132+
description: Name is the variable name used to reference this
133+
resource in the CEL expression
134+
minLength: 1
135+
type: string
136+
required:
137+
- kubernetesInputSpec
138+
- name
139+
type: object
140+
minItems: 1
141+
type: array
142+
instructions:
143+
description: Instructions for auditing this specific rule
144+
type: string
145+
rationale:
146+
description: The rationale of the Rule
147+
type: string
148+
scannerType:
149+
description: ScannerType denotes the scanning implementation to use
150+
when evaluating rules
151+
enum:
152+
- CEL
153+
type: string
154+
severity:
155+
description: The severity level
156+
type: string
157+
title:
158+
description: The title of the Rule
159+
type: string
160+
warning:
161+
description: A discretionary warning about the of the Rule
162+
type: string
163+
required:
164+
- expression
165+
- failureReason
166+
- id
167+
- inputs
168+
- scannerType
169+
- title
170+
type: object
171+
status:
172+
description: Status contains the validation status and other runtime information
173+
properties:
174+
errorMessage:
175+
description: ErrorMessage contains any validation error message
176+
type: string
177+
lastValidationTime:
178+
description: LastValidationTime is the timestamp of the last validation
179+
format: date-time
180+
type: string
181+
observedGeneration:
182+
description: ObservedGeneration represents the .metadata.generation
183+
that the status was set based upon
184+
format: int64
185+
type: integer
186+
phase:
187+
description: Phase describes the current phase of the CustomRule (Ready
188+
or Error)
189+
enum:
190+
- Ready
191+
- Error
192+
type: string
193+
type: object
194+
type: object
195+
served: true
196+
storage: true
197+
subresources:
198+
status: {}
199+
status:
200+
acceptedNames:
201+
kind: ""
202+
plural: ""
203+
conditions: null
204+
storedVersions: null

bundle/manifests/compliance.openshift.io_rules.yaml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,13 @@ spec:
5454
description: |-
5555
What type of check will this rule execute:
5656
Platform, Node or none (represented by an empty string)
57+
For CustomRules, only Platform is supported.
5758
type: string
5859
description:
5960
description: The description of the Rule
6061
type: string
6162
id:
62-
description: The XCCDF ID
63+
description: The ID of the Rule
6364
type: string
6465
instructions:
6566
description: Instructions for auditing this specific rule

bundle/manifests/compliance.openshift.io_tailoredprofiles.yaml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ spec:
5757
description: RuleReferenceSpec specifies a rule to be selected/deselected,
5858
as well as the reason why
5959
properties:
60+
kind:
61+
description: |-
62+
Specifies the type of rule reference: either "Rule" or "CustomRule".
63+
If not set, "Rule" is used by default. The "CustomRule" type is only applicable
64+
when referencing CustomRule resources in TailoredProfiles via enableRules.
65+
type: string
6066
name:
6167
description: Name of the rule that's being referenced
6268
type: string
@@ -75,6 +81,12 @@ spec:
7581
description: RuleReferenceSpec specifies a rule to be selected/deselected,
7682
as well as the reason why
7783
properties:
84+
kind:
85+
description: |-
86+
Specifies the type of rule reference: either "Rule" or "CustomRule".
87+
If not set, "Rule" is used by default. The "CustomRule" type is only applicable
88+
when referencing CustomRule resources in TailoredProfiles via enableRules.
89+
type: string
7890
name:
7991
description: Name of the rule that's being referenced
8092
type: string
@@ -97,6 +109,12 @@ spec:
97109
description: RuleReferenceSpec specifies a rule to be selected/deselected,
98110
as well as the reason why
99111
properties:
112+
kind:
113+
description: |-
114+
Specifies the type of rule reference: either "Rule" or "CustomRule".
115+
If not set, "Rule" is used by default. The "CustomRule" type is only applicable
116+
when referencing CustomRule resources in TailoredProfiles via enableRules.
117+
type: string
100118
name:
101119
description: Name of the rule that's being referenced
102120
type: string

0 commit comments

Comments
 (0)