Skip to content

Commit

Permalink
Fix data race in store.Items() (kiali#8214)
Browse files Browse the repository at this point in the history
`store.Items()` was returning the underlying data rather than a copy.
  • Loading branch information
nrfox authored Mar 6, 2025
1 parent 91118b4 commit 0288ebd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
12 changes: 12 additions & 0 deletions store/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,18 @@ func TestItemsReturnsWholeMap(t *testing.T) {
require.Equal(99, contents["key2"])
}

func TestItemsReturnsCopy(t *testing.T) {
require := require.New(t)

testStore := store.New[string, int]()
testStore.Replace(map[string]int{"key1": 42, "key2": 99})

contents := testStore.Items()
contents["key1"] = 52

require.Equal(42, testStore.Items()["key1"])
}

func TestDeleteKey(t *testing.T) {
require := require.New(t)

Expand Down
9 changes: 5 additions & 4 deletions store/threadsafe_store.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package store

import (
"maps"
"slices"
"sync"

"golang.org/x/exp/maps"
)

// threadSafeStore implements the Store interface and is safe for concurrent use.
Expand All @@ -25,10 +25,11 @@ func (s *threadSafeStore[K, V]) Get(key K) (V, bool) {
return v, found
}

// Items returns a copy of all items in the store.
func (s *threadSafeStore[K, V]) Items() map[K]V {
s.lock.RLock()
defer s.lock.RUnlock()
return s.data
return maps.Clone(s.data)
}

// Replace replaces the contents of the store with the given map.
Expand Down Expand Up @@ -63,7 +64,7 @@ func (s *threadSafeStore[K, V]) Remove(key K) {
func (s *threadSafeStore[K, V]) Keys() []K {
s.lock.RLock()
defer s.lock.RUnlock()
return maps.Keys(s.data)
return slices.Collect(maps.Keys(s.data))
}

func (s *threadSafeStore[K, V]) Version() uint {
Expand Down

0 comments on commit 0288ebd

Please sign in to comment.