Skip to content
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 go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ require (
github.com/joncrlsn/dque v0.0.0-20241024143830-7723fd131a64
github.com/kubescape/backend v0.0.39
github.com/kubescape/go-logger v0.0.28
github.com/kubescape/k8s-interface v0.0.206
github.com/kubescape/k8s-interface v0.0.207
github.com/kubescape/storage v0.0.258
github.com/kubescape/workerpool v0.0.0-20250526074519-0e4a4e7f44cf
github.com/moby/sys/mountinfo v0.7.2
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -885,8 +885,8 @@ github.com/kubescape/backend v0.0.39 h1:B1QRfKCSFlzuE+jWOnk/l7EpH71/Q3n14KKq0QSn
github.com/kubescape/backend v0.0.39/go.mod h1:cMEGP8cXUZgY89YU4GRBGIla9HZW7grZsUtlCwvZgAE=
github.com/kubescape/go-logger v0.0.28 h1:xulKTp9kOg3rD98sopFELQ6yZCHQoQXMDzteoSHDFKI=
github.com/kubescape/go-logger v0.0.28/go.mod h1:YZHFjwGCDar1hP9OyBLE46oR7a0Y/Z/0FperDo8+9D0=
github.com/kubescape/k8s-interface v0.0.206 h1:qaYu4mlLmSBePanSGq+DBCssh4O785TAT0lQGNGWyGw=
github.com/kubescape/k8s-interface v0.0.206/go.mod h1:WNYUG93aZ5kDmuaRKFLtVhp18Yc6EfaHdD1gLYtVTN4=
github.com/kubescape/k8s-interface v0.0.207 h1:jX+EqZLjSArw4xa+XMvjnnoK0Q8IxdD2tvihwLa/WGg=
github.com/kubescape/k8s-interface v0.0.207/go.mod h1:WNYUG93aZ5kDmuaRKFLtVhp18Yc6EfaHdD1gLYtVTN4=
github.com/kubescape/storage v0.0.258 h1:0mL0z3dAmtP1qup7VgoEgwLgbBSROu5oOusBAPeMmus=
github.com/kubescape/storage v0.0.258/go.mod h1:VHs+xQzvZKE2lJDN8rR1sFmTa43N6XJAcatZ249gviU=
github.com/kubescape/workerpool v0.0.0-20250526074519-0e4a4e7f44cf h1:hI0jVwrB6fT4GJWvuUjzObfci1CUknrZdRHfnRVtKM0=
Expand Down
1 change: 1 addition & 0 deletions pkg/containerprofilemanager/v1/lifecycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ func (cpm *ContainerProfileManager) addContainer(container *containercollection.

// Setup monitoring timer
sniffingTime := cpm.calculateSniffingTime(container)
sharedData.LearningPeriod = sniffingTime
timer := time.AfterFunc(sniffingTime, func() {
cpm.handleContainerMaxTime(container)
})
Expand Down
45 changes: 24 additions & 21 deletions pkg/objectcache/shared_container_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ type WatchedContainerData struct {
CurrentReportTimestamp time.Time
UserDefinedProfile string
LabelOverrides map[string]string // optional label overrides applied after GetLabels()
LearningPeriod time.Duration
}

type ContainerInfo struct {
Expand All @@ -90,31 +91,19 @@ type ContainerInfo struct {
ImageID string
}

func formatDuration(d time.Duration) string {
s := d.String()
s = strings.Replace(s, "m0s", "m", 1)
s = strings.Replace(s, "h0m", "h", 1)
return s
}

func GetLabels(cloudMetadata *armotypes.CloudMetadata, watchedContainer *WatchedContainerData, stripContainer bool) map[string]string {
labels := watchedContainer.InstanceID.GetLabels()
for i := range labels {
if labels[i] == "" || (stripContainer && i == helpersv1.ContainerNameMetadataKey) {
delete(labels, i)
continue
}
if errs := content.IsLabelValue(labels[i]); len(errs) != 0 {
logger.L().Debug("GetLabels - label is not valid", helpers.String("label", labels[i]))
for j := range errs {
logger.L().Debug("GetLabels - label err description", helpers.String("Err: ", errs[j]))
}
delete(labels, i)
}
}
labels[helpersv1.LearningPeriodMetadataKey] = formatDuration(watchedContainer.LearningPeriod)
// Apply label overrides
for k, v := range watchedContainer.LabelOverrides {
if v == "" {
delete(labels, k)
} else if errs := content.IsLabelValue(v); len(errs) != 0 {
logger.L().Warning("GetLabels - label override value is not valid, skipping", helpers.String("key", k), helpers.String("value", v))
delete(labels, k)
} else {
labels[k] = v
}
labels[k] = v
}
Comment on lines 104 to 107
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Behavior change: invalid LabelOverrides now drop the base label too.

Previously, overrides were validated per-entry and invalid overrides were discarded so the underlying base label remained. With the single-pass sanitization at Lines 127–139, an invalid override value now first overwrites the base value at Line 106 and is then removed entirely at Line 137 — so the resulting label map is missing the key in cases where it would have kept the (valid) base value before.

If overrides are expected to be trusted/pre-validated this is fine; otherwise consider validating overrides before applying:

♻️ Suggested fix
 	// Apply label overrides
 	for k, v := range watchedContainer.LabelOverrides {
+		if v == "" || len(content.IsLabelValue(v)) != 0 {
+			continue
+		}
 		labels[k] = v
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Apply label overrides
for k, v := range watchedContainer.LabelOverrides {
if v == "" {
delete(labels, k)
} else if errs := content.IsLabelValue(v); len(errs) != 0 {
logger.L().Warning("GetLabels - label override value is not valid, skipping", helpers.String("key", k), helpers.String("value", v))
delete(labels, k)
} else {
labels[k] = v
}
labels[k] = v
}
// Apply label overrides
for k, v := range watchedContainer.LabelOverrides {
if v == "" || len(content.IsLabelValue(v)) != 0 {
continue
}
labels[k] = v
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/objectcache/shared_container_data.go` around lines 104 - 107, The current
loop applies watchedContainer.LabelOverrides directly to labels which allows an
invalid override to overwrite the base label and later be dropped by
sanitization; instead, validate each override entry before applying it: iterate
over watchedContainer.LabelOverrides, run the same per-entry
validation/sanitization logic used later (or a dedicated isValidLabelValue
check) and only set labels[k] = v when the override value is valid; this
preserves the original base label for keys whose overrides are invalid and
prevents losing keys during the later sanitization pass.

if watchedContainer.ParentResourceVersion != "" {
labels[helpersv1.ResourceVersionMetadataKey] = watchedContainer.ParentResourceVersion
Expand All @@ -134,6 +123,20 @@ func GetLabels(cloudMetadata *armotypes.CloudMetadata, watchedContainer *Watched
labels[helpersv1.RegionMetadataKey] = region
}
}
// Sanitize labels
for i := range labels {
if labels[i] == "" || (stripContainer && i == helpersv1.ContainerNameMetadataKey) {
delete(labels, i)
continue
}
if errs := content.IsLabelValue(labels[i]); len(errs) != 0 {
logger.L().Debug("GetLabels - label is not valid", helpers.String("label", labels[i]))
for j := range errs {
logger.L().Debug("GetLabels - label err description", helpers.String("Err: ", errs[j]))
}
delete(labels, i)
}
}
return labels
}

Expand Down
36 changes: 36 additions & 0 deletions pkg/objectcache/shared_container_data_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package objectcache

import (
"testing"
"time"

"github.com/kubescape/k8s-interface/instanceidhandler/v1"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -51,6 +52,7 @@ func Test_GetLabels(t *testing.T) {
"kubescape.io/workload-api-version": "v1",
"kubescape.io/workload-container-name": "redis",
"kubescape.io/workload-kind": "Deployment",
"kubescape.io/learning-period": "0s",
"kubescape.io/workload-name": "redis",
"kubescape.io/workload-namespace": "aaa",
},
Expand All @@ -67,6 +69,7 @@ func Test_GetLabels(t *testing.T) {
want: map[string]string{
"kubescape.io/workload-api-version": "v1",
"kubescape.io/workload-kind": "Deployment",
"kubescape.io/learning-period": "0s",
"kubescape.io/workload-name": "redis",
"kubescape.io/workload-namespace": "aaa",
},
Expand All @@ -79,3 +82,36 @@ func Test_GetLabels(t *testing.T) {
})
}
}

func Test_formatDuration(t *testing.T) {
tests := []struct {
d time.Duration
want string
}{
{
d: 5 * time.Minute,
want: "5m",
},
{
d: 1*time.Hour + 30*time.Minute,
want: "1h30m",
},
{
d: 45 * time.Second,
want: "45s",
},
{
d: 1*time.Hour + 30*time.Second,
want: "1h30s",
},
{
d: 1 * time.Hour,
want: "1h",
},
}
for _, tt := range tests {
t.Run(tt.d.String(), func(t *testing.T) {
assert.Equal(t, tt.want, formatDuration(tt.d))
})
}
}
Loading