From 7f6a942768e27b6098d22e401c72aca2cdc7d940 Mon Sep 17 00:00:00 2001 From: Oded Viner Date: Mon, 2 Dec 2024 14:34:50 +0200 Subject: [PATCH] core: prevent side effects in Annotations.Merge This commit updates the Annotations.Merge function to fix an issue where the original Annotations map was unintentionally modified. The new implementation creates a separate map to ensure the original map remains unchanged during the merge process. Signed-off-by: Oded Viner (cherry picked from commit f1d3e0d4c0903a5b178d9724fca75558ecef6f23) --- pkg/apis/ceph.rook.io/v1/annotations.go | 14 ++++++++++---- pkg/apis/ceph.rook.io/v1/annotations_test.go | 5 +++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/pkg/apis/ceph.rook.io/v1/annotations.go b/pkg/apis/ceph.rook.io/v1/annotations.go index efd40793f..4eaa64878 100644 --- a/pkg/apis/ceph.rook.io/v1/annotations.go +++ b/pkg/apis/ceph.rook.io/v1/annotations.go @@ -110,14 +110,20 @@ func (a Annotations) ApplyToObjectMeta(t *metav1.ObjectMeta) { // original Annotations with the attributes of the supplied one. The supplied // Annotation attributes will override the original ones if defined. func (a Annotations) Merge(with map[string]string) Annotations { - ret := a - if ret == nil { - ret = map[string]string{} + // Create a new map of type Annotations to hold the merged results + ret := Annotations{} + + // Copy the contents of the original map (a) into ret + for k, v := range a { + ret[k] = v } + + // Add entries from the 'with' map only if the key does not already exist for k, v := range with { - if _, ok := ret[k]; !ok { + if _, exists := ret[k]; !exists { ret[k] = v } } + return ret } diff --git a/pkg/apis/ceph.rook.io/v1/annotations_test.go b/pkg/apis/ceph.rook.io/v1/annotations_test.go index c3137d8ed..465ccbd23 100644 --- a/pkg/apis/ceph.rook.io/v1/annotations_test.go +++ b/pkg/apis/ceph.rook.io/v1/annotations_test.go @@ -62,6 +62,7 @@ func TestCephAnnotationsMerge(t *testing.T) { "mgr": {"mgrkey": "mgrval"}, "cmdreporter": {"myversions": "detect"}, "crashcollector": {"crash": "crashval"}, + "osd": {"osdkey": "osdval"}, } a = GetMonAnnotations(testAnnotations) assert.Equal(t, "allval1", a["allkey1"]) @@ -80,6 +81,10 @@ func TestCephAnnotationsMerge(t *testing.T) { assert.Equal(t, "crashval", c["crash"]) assert.Equal(t, "allval1", c["allkey1"]) assert.Equal(t, "allval2", c["allkey2"]) + d := GetOSDAnnotations(testAnnotations) + assert.Equal(t, "allval1", d["allkey1"]) + assert.Equal(t, "allval2", d["allkey2"]) + assert.Equal(t, "osdval", d["osdkey"]) } func TestAnnotationsSpec(t *testing.T) {