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

fix: Validation for Resource Limits #3

Merged
merged 2 commits into from
Sep 19, 2024
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
2 changes: 1 addition & 1 deletion deploy/helm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ Keeps security report resources updated
| trivy.podLabels | object | `{}` | podLabels is the extra pod labels to be used for trivy server |
| trivy.priorityClassName | string | `""` | priorityClassName is the name of the priority class used for trivy server |
| trivy.registry | object | `{"mirror":{}}` | Mirrored registries. There can be multiple registries with different keys. Make sure to quote registries containing dots |
| trivy.resources | object | `{"limits":{"cpu":"500m","memory":"500M"},"requests":{"cpu":"100m","memory":"100M"}}` | resources resource requests and limits for scan job containers |
| trivy.resources | object | `{"limits":{"cpu":"500m","memory":"500Mi"},"requests":{"cpu":"100m","memory":"100Mi"}}` | resources resource requests and limits for scan job containers |
| trivy.sbomSources | string | `""` | sbomSources trivy will try to retrieve SBOM from the specified sources (oci,rekor) |
| trivy.server.podSecurityContext | object | `{"fsGroup":65534,"runAsNonRoot":true,"runAsUser":65534}` | podSecurityContext set trivy-server podSecurityContext |
| trivy.server.replicas | int | `1` | the number of replicas of the trivy-server |
Expand Down
4 changes: 2 additions & 2 deletions deploy/helm/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -472,11 +472,11 @@ trivy:
resources:
requests:
cpu: 100m
memory: 100M
memory: 100Mi
# ephemeralStorage: "2Gi"
limits:
cpu: 500m
memory: 500M
memory: 500Mi
# ephemeralStorage: "2Gi"

# -- githubToken is the GitHub access token used by Trivy to download the vulnerabilities
Expand Down
4 changes: 2 additions & 2 deletions deploy/static/trivy-operator.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3053,9 +3053,9 @@ data:
trivy.timeout: "5m0s"
trivy.mode: "Standalone"
trivy.resources.requests.cpu: "100m"
trivy.resources.requests.memory: "100M"
trivy.resources.requests.memory: "100Mi"
trivy.resources.limits.cpu: "500m"
trivy.resources.limits.memory: "500M"
trivy.resources.limits.memory: "500Mi"
---
# Source: trivy-operator/templates/secrets/operator.yaml
apiVersion: v1
Expand Down
4 changes: 2 additions & 2 deletions docs/docs/vulnerability-scanning/trivy.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,10 @@ EOF
| `trivy.httpsProxy` | N/A | The HTTPS proxy used by Trivy to download the vulnerabilities database from GitHub. |
| `trivy.noProxy` | N/A | A comma separated list of IPs and domain names that are not subject to proxy settings. |
| `trivy.resources.requests.cpu` | `100m` | The minimum amount of CPU required to run Trivy scanner pod. |
| `trivy.resources.requests.memory` | `100M` | The minimum amount of memory required to run Trivy scanner pod. |
| `trivy.resources.requests.memory` | `100Mi` | The minimum amount of memory required to run Trivy scanner pod. |
| `trivy.resources.requests.ephemeral-storage` |`` | The minimum amount of ephemeral-storage required to run Trivy scanner pod. |
| `trivy.resources.limits.cpu` | `500m` | The maximum amount of CPU allowed to run Trivy scanner pod. |
| `trivy.resources.limits.memory` | `500M` | The maximum amount of memory allowed to run Trivy scanner pod. |
| `trivy.resources.limits.memory` | `500Mi` | The maximum amount of memory allowed to run Trivy scanner pod. |
| `trivy.resources.limits.ephemeral-storage` | ``| The maximum amount of ephemeral-storage allowed to run Trivy scanner pod. |
| `trivy.storageClassName` | `` | The name of the storage class to be used for Trivy server PVC. |
| `trivy.podLabels` | ``| The extra pod labels to be used for Trivy server. |
Expand Down
41 changes: 41 additions & 0 deletions pkg/plugins/trivy/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,47 @@ func (c Config) setResourceLimit(configKey string, k8sResourceList *corev1.Resou
return fmt.Errorf("parsing resource definition %s: %s %w", configKey, value, err)
}

// Ensure memory and ephemeral storage is set in valid units and the value is positive
if k8sResourceName == corev1.ResourceMemory || k8sResourceName == corev1.ResourceEphemeralStorage {
allowedUnits := []string{"Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "K", "M", "G", "T", "P", "E"}
valid := false
for _, unit := range allowedUnits {
if strings.HasSuffix(value, unit) {
valid = true
break
}
}
if !valid {
return fmt.Errorf("invalid value %s for key %s, should be specified in units like Ki, Mi, Gi, etc", value, configKey)
}
if quantity.Value() < 0 {
return fmt.Errorf("%s value %s must be a positive number", configKey, value)
}
}

// Ensure CPU values are correctly parsed, and that the value is positive
if k8sResourceName == corev1.ResourceCPU {
cpuValue := quantity.MilliValue()
if cpuValue < 0 {
return fmt.Errorf("CPU value %s must be a positive number", value)
}
// Ensure CPU value is either in millicores or cores
valueStr := quantity.String()
if !(strings.HasSuffix(valueStr, "m") || !strings.Contains(valueStr, "m")) {
return fmt.Errorf("CPU value %s is not in a valid format", valueStr)
}
}

// Ensure the parsed quantity matches the original value
originalQuantity, err := resource.ParseQuantity(value)
if err != nil {
return fmt.Errorf("parsing original resource definition %s: %s %w", configKey, value, err)
}

if quantity.Cmp(originalQuantity) != 0 {
return fmt.Errorf("parsed value %s does not match the original value %s for key %s", quantity.String(), value, configKey)
}

(*k8sResourceList)[k8sResourceName] = quantity
}
return nil
Expand Down
95 changes: 82 additions & 13 deletions pkg/plugins/trivy/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,24 +360,28 @@ func TestConfig_GetResourceRequirements(t *testing.T) {
config: Config{
PluginConfig: trivyoperator.PluginConfig{
Data: map[string]string{
"trivy.dbRepository": DefaultDBRepository,
"trivy.javaDbRepository": DefaultJavaDBRepository,
"trivy.resources.requests.cpu": "800m",
"trivy.resources.requests.memory": "200M",
"trivy.resources.limits.cpu": "600m",
"trivy.resources.limits.memory": "700M",
"trivy.dbRepository": DefaultDBRepository,
"trivy.javaDbRepository": DefaultJavaDBRepository,
"trivy.resources.requests.cpu": "800m",
"trivy.resources.requests.memory": "200Mi",
"trivy.resources.requests.ephemeral-storage": "500Mi",
"trivy.resources.limits.cpu": "600m",
"trivy.resources.limits.memory": "700Mi",
"trivy.resources.limits.ephemeral-storage": "1Gi",
},
},
},
expectedError: "",
expectedRequirements: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("800m"),
corev1.ResourceMemory: resource.MustParse("200M"),
corev1.ResourceCPU: resource.MustParse("800m"),
corev1.ResourceMemory: resource.MustParse("200Mi"),
corev1.ResourceEphemeralStorage: resource.MustParse("500Mi"),
},
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("600m"),
corev1.ResourceMemory: resource.MustParse("700M"),
corev1.ResourceCPU: resource.MustParse("600m"),
corev1.ResourceMemory: resource.MustParse("700Mi"),
corev1.ResourceEphemeralStorage: resource.MustParse("1Gi"),
},
},
},
Expand All @@ -392,6 +396,72 @@ func TestConfig_GetResourceRequirements(t *testing.T) {
},
expectedError: "parsing resource definition trivy.resources.requests.cpu: roughly 100 quantities must match the regular expression '^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$'",
},
{
name: "Should return error if memory value is invalid",
config: Config{
PluginConfig: trivyoperator.PluginConfig{
Data: map[string]string{
"trivy.resources.requests.memory": "100InvalidUnit",
},
},
},
expectedError: "parsing resource definition trivy.resources.requests.memory: 100InvalidUnit quantities must match the regular expression '^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$'",
},
{
name: "Should return error if parsed memory value does not match original value",
config: Config{
PluginConfig: trivyoperator.PluginConfig{
Data: map[string]string{
"trivy.resources.requests.memory": "1288490188800m",
},
},
},
expectedError: "invalid value 1288490188800m for key trivy.resources.requests.memory, should be specified in units like Ki, Mi, Gi, etc",
},
{
name: "Should return error if CPU value is negative",
config: Config{
PluginConfig: trivyoperator.PluginConfig{
Data: map[string]string{
"trivy.resources.requests.cpu": "-500m",
},
},
},
expectedError: "CPU value -500m must be a positive number",
},
{
name: "Should return error if memory value is negative",
config: Config{
PluginConfig: trivyoperator.PluginConfig{
Data: map[string]string{
"trivy.resources.requests.memory": "-200Mi",
},
},
},
expectedError: "trivy.resources.requests.memory value -200Mi must be a positive number",
},
{
name: "Should return error if ephemeral storage value is negative",
config: Config{
PluginConfig: trivyoperator.PluginConfig{
Data: map[string]string{
"trivy.resources.requests.ephemeral-storage": "-1Gi",
},
},
},
expectedError: "trivy.resources.requests.ephemeral-storage value -1Gi must be a positive number",
},
{
name: "Should return error if ephemeral storage value is invalid",
config: Config{
PluginConfig: trivyoperator.PluginConfig{
Data: map[string]string{
"trivy.resources.requests.ephemeral-storage": "500InvalidUnit",
},
},
},
expectedError: "parsing resource definition trivy.resources.requests.ephemeral-storage: 500InvalidUnit quantities must match the regular expression '^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$'",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
Expand Down Expand Up @@ -735,9 +805,9 @@ func TestPlugin_Init(t *testing.T) {
"trivy.useBuiltinRegoPolicies": "true",
"trivy.supportedConfigAuditKinds": SupportedConfigAuditKinds,
"trivy.resources.requests.cpu": "100m",
"trivy.resources.requests.memory": "100M",
"trivy.resources.requests.memory": "100Mi",
"trivy.resources.limits.cpu": "500m",
"trivy.resources.limits.memory": "500M",
"trivy.resources.limits.memory": "500Mi",
},
}, cm)
})
Expand Down Expand Up @@ -880,7 +950,6 @@ func TestPlugin_FindIgnorePolicyKey(t *testing.T) {
}

func TestPlugin_GetIncludeDevDeps(t *testing.T) {

testCases := []struct {
name string
configData map[string]string
Expand Down
4 changes: 2 additions & 2 deletions pkg/plugins/trivy/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ func (p *plugin) Init(ctx trivyoperator.PluginContext) error {
keyTrivyUseBuiltinRegoPolicies: "true",
keyTrivySupportedConfigAuditKinds: SupportedConfigAuditKinds,
keyResourcesRequestsCPU: "100m",
keyResourcesRequestsMemory: "100M",
keyResourcesRequestsMemory: "100Mi",
keyResourcesLimitsCPU: "500m",
keyResourcesLimitsMemory: "500M",
keyResourcesLimitsMemory: "500Mi",
},
})
}
Expand Down
Loading
Loading