Skip to content

Find, verify, and analyze leaked credentials

resolve race condition in result deduplication cache (#5359)

Kevin Pham5d8d4a3f51f1
diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go
index de5c412e2..408496a80 100644
--- a/pkg/engine/engine.go
+++ b/pkg/engine/engine.go
@@ -1357,14 +1357,15 @@ func (e *Engine) notifierWorker(ctx context.Context) {
// This deduplication only applies to results that are *not*
// from reverification, since we are expected to see the same
// result from reverification and want to Dispatch it below.
+
+ // Notifier workers share this cache; the check and insert must be one atomic step.
if result.SecretID == 0 {
h := md5.Sum([]byte(fmt.Sprintf("%s%s%s%s%+v", result.DetectorName, result.DetectorType.String(), result.Raw, result.RawV2, result.SourceMetadata)))
key := string(h[:])
- if _, ok := e.dedupeCache.Get(key); ok {
+ if found, _ := e.dedupeCache.ContainsOrAdd(key, struct{}{}); found {
resultsDropped.WithLabelValues("notifier", "dedupe_cache_hit", detectorNameStr).Inc()
continue
}
- e.dedupeCache.Add(key, struct{}{})
}
if result.Verified {
diff --git a/pkg/engine/engine_test.go b/pkg/engine/engine_test.go
index 236112264..c7c6419ac 100644
--- a/pkg/engine/engine_test.go
+++ b/pkg/engine/engine_test.go
@@ -9,6 +9,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -2244,12 +2245,17 @@ func TestEngine_IterativeDecoding(t *testing.T) {
}
}
-// captureDispatcher records every dispatched result for assertion in tests.
+// captureDispatcher records every dispatched result for assertion in tests. It
+// is safe for concurrent use because the engine runs many notifier workers
+// against a single dispatcher.
type captureDispatcher struct {
+ mu sync.Mutex
results []detectors.ResultWithMetadata
}
func (d *captureDispatcher) Dispatch(_ context.Context, result detectors.ResultWithMetadata) error {
+ d.mu.Lock()
+ defer d.mu.Unlock()
d.results = append(d.results, result)
return nil
}
@@ -2318,6 +2324,72 @@ func TestNotifierWorker_ReverifiedResultsBypassDedupe(t *testing.T) {
}
}
+// TestNotifierWorker_ConcurrentDuplicatesDispatchedOnce verifies that when many
+// notifier workers share the dedupe cache, identical results are dispatched
+// exactly once. The check-and-insert must be atomic; a separate lookup and add
+// lets two workers both miss and both dispatch.
+//
+// The race exists only on a key's first sighting, so the test uses many distinct
+// secrets and queues each one's copies back to back, giving every key its own
+// chance for workers to collide. It guards a logical race rather than a data
+// race, so -race does not flag the non-atomic version.
+func TestNotifierWorker_ConcurrentDuplicatesDispatchedOnce(t *testing.T) {
+ const (
+ numSecrets = 1000
+ numCopies = 16
+ numWorkers = 16
+ )
+
+ // Sized to hold every key so eviction cannot cause a re-dispatch.
+ cache, err := lru.New[string, struct{}](numSecrets)
+ require.NoError(t, err)
+
+ disp := &captureDispatcher{}
+ e := &Engine{
+ results: make(chan detectors.ResultWithMetadata, numSecrets*numCopies),
+ dedupeCache: cache,
+ dispatcher: disp,
+ notifyVerifiedResults: true,
+ notifyUnverifiedResults: true,
+ notifyUnknownResults: true,
+ }
+
+ // Fill and close the channel before starting workers so they all contend
+ // on the cache at once instead of idling on an empty channel. SecretID
+ // stays 0 so every copy goes through the dedupe cache.
+ for i := range numSecrets {
+ result := detectors.ResultWithMetadata{
+ SourceMetadata: &source_metadatapb.MetaData{
+ Data: &source_metadatapb.MetaData_Git{
+ Git: &source_metadatapb.Git{Line: 1},
+ },
+ },
+ SourceType: sourcespb.SourceType_SOURCE_TYPE_GIT,
+ Result: detectors.Result{
+ DetectorType: detector_typepb.DetectorType(-1),
+ Raw: []byte(fmt.Sprintf("secret-%d", i)),
+ Verified: true,
+ },
+ }
+ for range numCopies {
+ e.results <- result
+ }
+ }
+ close(e.results)
+
+ var wg sync.WaitGroup
+ for range numWorkers {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ e.notifierWorker(context.Background())
+ }()
+ }
+ wg.Wait()
+
+ assert.Equal(t, numSecrets, len(disp.results))
+}
+
func setupSourceMappingBench(size int, decode bool) (*sources.Chunk, *detectors.Result) {
secret := []byte("synthetic-secret-value-123456")
var original, decoded []byte