diff --git a/core/pkg/sync/blob/blob_sync.go b/core/pkg/sync/blob/blob_sync.go index c5806d484..8c0c98177 100644 --- a/core/pkg/sync/blob/blob_sync.go +++ b/core/pkg/sync/blob/blob_sync.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "path/filepath" + stdsync "sync" "time" "github.com/open-feature/flagd/core/pkg/logger" @@ -26,8 +27,11 @@ type Sync struct { Poller polling.Poller Logger *logger.Logger Interval uint32 + mu stdsync.Mutex ready bool lastUpdated time.Time + lastETag string + lastBodySHA string } func (hs *Sync) Init(_ context.Context) error { @@ -41,6 +45,8 @@ func (hs *Sync) Init(_ context.Context) error { } func (hs *Sync) IsReady() bool { + hs.mu.Lock() + defer hs.mu.Unlock() return hs.ready } @@ -54,7 +60,9 @@ func (hs *Sync) Sync(ctx context.Context, dataSync chan<- sync.DataSync) error { return err } + hs.mu.Lock() hs.ready = true + hs.mu.Unlock() hs.Logger.Debug(fmt.Sprintf("polling %s/%s every %ds (offset: %ds)", hs.Bucket, hs.Object, hs.Interval, hs.Poller.Offset())) @@ -73,38 +81,81 @@ func (hs *Sync) ReSync(ctx context.Context, dataSync chan<- sync.DataSync) error return hs.sync(ctx, dataSync, true) } -func (hs *Sync) sync(ctx context.Context, dataSync chan<- sync.DataSync, skipCheckingModTime bool) error { +func (hs *Sync) sync(ctx context.Context, dataSync chan<- sync.DataSync, forcePublish bool) error { bucket, err := hs.getBucket(ctx) if err != nil { return fmt.Errorf("couldn't get bucket: %v", err) } defer bucket.Close() - var updated time.Time - if !skipCheckingModTime { - updated, err = hs.fetchObjectModificationTime(ctx, bucket) + + var attrs *blob.Attributes + if !forcePublish { + attrs, err = hs.fetchObjectAttributes(ctx, bucket) if err != nil { return fmt.Errorf("couldn't get object attributes: %v", err) } - if hs.lastUpdated.Equal(updated) { + if hs.attributesUnchanged(attrs) { hs.Logger.Debug("configuration hasn't changed, skipping fetching full object") return nil } - if hs.lastUpdated.After(updated) { - hs.Logger.Warn("configuration changed but the modification time decreased instead of increasing") - } } - msg, err := hs.fetchObject(ctx, bucket) + + msg, bodySHA, err := hs.fetchObject(ctx, bucket) if err != nil { return fmt.Errorf("couldn't get object: %v", err) } - hs.Logger.Debug(fmt.Sprintf("configuration updated: %s", msg)) - if !skipCheckingModTime { - hs.lastUpdated = updated + + // only publish if the content actually differs + if !forcePublish && hs.bodyUnchanged(bodySHA) { + hs.Logger.Debug("configuration hasn't changed, skipping publishing") + hs.updateState(attrs, bodySHA) + return nil } + + hs.Logger.Debug(fmt.Sprintf("configuration updated: %s", msg)) + hs.updateState(attrs, bodySHA) dataSync <- sync.DataSync{FlagData: msg, Source: bloburi.Join(hs.Bucket, hs.Object)} return nil } +// attributesUnchanged reports whether the object can be considered unchanged +// based on its attributes alone, allowing us to skip fetching the full object. +// prefers the ETag and falls back to the mod time for stores that don't expose one. +func (hs *Sync) attributesUnchanged(attrs *blob.Attributes) bool { + hs.mu.Lock() + defer hs.mu.Unlock() + if attrs.ETag != "" { + return hs.lastETag == attrs.ETag + } + if hs.lastUpdated.Equal(attrs.ModTime) { + return true + } + if hs.lastUpdated.After(attrs.ModTime) { + hs.Logger.Warn("configuration changed but the modification time decreased instead of increasing") + } + return false +} + +// bodyUnchanged reports whether bodySHA matches the body hash recorded by the +// last updateState call. +func (hs *Sync) bodyUnchanged(bodySHA string) bool { + hs.mu.Lock() + defer hs.mu.Unlock() + return bodySHA == hs.lastBodySHA +} + +// updateState records the attributes and body hash of the object we just +// observed so subsequent syncs can detect whether anything actually changed. +func (hs *Sync) updateState(attrs *blob.Attributes, bodySHA string) { + hs.mu.Lock() + defer hs.mu.Unlock() + if attrs != nil { + hs.lastETag = attrs.ETag + hs.lastUpdated = attrs.ModTime + } + hs.lastBodySHA = bodySHA +} + func (hs *Sync) getBucket(ctx context.Context) (*blob.Bucket, error) { b, err := hs.BlobURLMux.OpenBucket(ctx, hs.Bucket) if err != nil { @@ -113,32 +164,33 @@ func (hs *Sync) getBucket(ctx context.Context) (*blob.Bucket, error) { return b, nil } -func (hs *Sync) fetchObjectModificationTime(ctx context.Context, bucket *blob.Bucket) (time.Time, error) { +func (hs *Sync) fetchObjectAttributes(ctx context.Context, bucket *blob.Bucket) (*blob.Attributes, error) { if hs.Object == "" { - return time.Time{}, errors.New("no object string set") + return nil, errors.New("no object string set") } attrs, err := bucket.Attributes(ctx, hs.Object) if err != nil { - return time.Time{}, fmt.Errorf("error fetching attributes for object %s/%s: %w", hs.Bucket, hs.Object, err) + return nil, fmt.Errorf("error fetching attributes for object %s/%s: %w", hs.Bucket, hs.Object, err) } - return attrs.ModTime, nil + return attrs, nil } -func (hs *Sync) fetchObject(ctx context.Context, bucket *blob.Bucket) (string, error) { +func (hs *Sync) fetchObject(ctx context.Context, bucket *blob.Bucket) (string, string, error) { r, err := bucket.NewReader(ctx, hs.Object, nil) if err != nil { - return "", fmt.Errorf("error opening reader for object %s/%s: %w", hs.Bucket, hs.Object, err) + return "", "", fmt.Errorf("error opening reader for object %s/%s: %w", hs.Bucket, hs.Object, err) } defer r.Close() data, err := io.ReadAll(r) if err != nil { - return "", fmt.Errorf("error downloading object %s/%s: %w", hs.Bucket, hs.Object, err) + return "", "", fmt.Errorf("error downloading object %s/%s: %w", hs.Bucket, hs.Object, err) } - json, err := utils.ConvertToJSON(data, filepath.Ext(hs.Object), r.ContentType()) + flagJSON, err := utils.ConvertToJSON(data, filepath.Ext(hs.Object), r.ContentType()) if err != nil { - return "", fmt.Errorf("error converting blob data to json: %w", err) + return "", "", fmt.Errorf("error converting blob data to json: %w", err) } - return json, nil + + return flagJSON, utils.GenerateSha([]byte(flagJSON)), nil } diff --git a/core/pkg/sync/blob/blob_sync_test.go b/core/pkg/sync/blob/blob_sync_test.go index 66cc4de2d..5b709cd0b 100644 --- a/core/pkg/sync/blob/blob_sync_test.go +++ b/core/pkg/sync/blob/blob_sync_test.go @@ -3,6 +3,7 @@ package blob import ( "context" "log" + stdsync "sync" "testing" "time" @@ -13,25 +14,33 @@ import ( func TestBlobSync(t *testing.T) { tests := map[string]struct { - scheme string - bucket string - object string - content string - convertedContent string + scheme string + bucket string + object string + // initial and changed content in the object's native format, along + // with the JSON we expect flagd to publish for each. + initialContent string + initialConverted string + changedContent string + changedConverted string }{ "json file type": { scheme: "xyz", bucket: "b", object: "flags.json", - content: "{\"flags\":{}}", - convertedContent: "{\"flags\":{}}", + initialContent: "{\"flags\":{}}", + initialConverted: "{\"flags\":{}}", + changedContent: "{\"flags\":{\"a\":{}}}", + changedConverted: "{\"flags\":{\"a\":{}}}", }, "yaml file type": { scheme: "xyz", bucket: "b", object: "flags.yaml", - content: "flags: []", - convertedContent: "{\"flags\":[]}", + initialContent: "flags: []", + initialConverted: "{\"flags\":[]}", + changedContent: "flags: {a: {}}", + changedConverted: "{\"flags\":{\"a\":{}}}", }, } @@ -39,21 +48,19 @@ func TestBlobSync(t *testing.T) { t.Run(name, func(t *testing.T) { mockPoller := synctesting.NewMockPoller() + blobMock := NewMockBlob(tt.scheme) blobSync := &Sync{ - Bucket: tt.scheme + "://" + tt.bucket, - Object: tt.object, - Poller: mockPoller, - Logger: logger.NewLogger(nil, false), + Bucket: tt.scheme + "://" + tt.bucket, + Object: tt.object, + BlobURLMux: blobMock.URLMux(), + Poller: mockPoller, + Logger: logger.NewLogger(nil, false), } - blobMock := NewMockBlob(tt.scheme, func() *Sync { - return blobSync - }) - blobSync.BlobURLMux = blobMock.URLMux() ctx := context.Background() dataSyncChan := make(chan sync.DataSync, 1) - blobMock.AddObject(tt.object, tt.content) + blobMock.AddObject(tt.initialContent) go func() { err := blobSync.Sync(ctx, dataSyncChan) @@ -64,27 +71,31 @@ func TestBlobSync(t *testing.T) { }() data := <-dataSyncChan // initial sync - if data.FlagData != tt.convertedContent { - t.Errorf("expected content: %s, but received content: %s", tt.convertedContent, data.FlagData) + if data.FlagData != tt.initialConverted { + t.Errorf("expected content: %s, but received content: %s", tt.initialConverted, data.FlagData) } - tickWithConfigChange(t, mockPoller, dataSyncChan, blobMock, tt.object, tt.convertedContent) - tickWithoutConfigChange(t, mockPoller, dataSyncChan) - tickWithConfigChange(t, mockPoller, dataSyncChan, blobMock, tt.object, tt.convertedContent) + // A genuine content change is published. + tickWithConfigChange(t, mockPoller, dataSyncChan, blobMock, tt.changedContent, tt.changedConverted) + // An unchanged object (matching ETag) is skipped. tickWithoutConfigChange(t, mockPoller, dataSyncChan) + // A new ETag/ModTime but identical bytes is skipped by the body hash backstop. + tickWithMetadataOnlyChange(t, mockPoller, dataSyncChan, blobMock, tt.changedContent) + // Back to the original content is a genuine change again. + tickWithConfigChange(t, mockPoller, dataSyncChan, blobMock, tt.initialContent, tt.initialConverted) tickWithoutConfigChange(t, mockPoller, dataSyncChan) }) } } -func tickWithConfigChange(t *testing.T, mockPoller *synctesting.MockPoller, dataSyncChan chan sync.DataSync, blobMock *MockBlob, object string, newConfig string) { - time.Sleep(1 * time.Millisecond) // sleep so the new file has different modification date - blobMock.AddObject(object, newConfig) +// tickWithConfigChange writes new content (bumping ETag/ModTime) and expects the change to be published. +func tickWithConfigChange(t *testing.T, mockPoller *synctesting.MockPoller, dataSyncChan chan sync.DataSync, blobMock *MockBlob, newContent, expectedConverted string) { + blobMock.AddObject(newContent) mockPoller.Tick() select { case data, ok := <-dataSyncChan: if ok { - if data.FlagData != newConfig { - t.Errorf("expected content: %s, but received content: %s", newConfig, data.FlagData) + if data.FlagData != expectedConverted { + t.Errorf("expected content: %s, but received content: %s", expectedConverted, data.FlagData) } } else { t.Errorf("data channel unexpectedly closed") @@ -94,8 +105,21 @@ func tickWithConfigChange(t *testing.T, mockPoller *synctesting.MockPoller, data } } +// tickWithoutConfigChange ticks without touching the object; the matching ETag means nothing is fetched or published. func tickWithoutConfigChange(t *testing.T, mockPoller *synctesting.MockPoller, dataSyncChan chan sync.DataSync) { mockPoller.Tick() + expectNoUpdate(t, dataSyncChan) +} + +// tickWithMetadataOnlyChange rewrites the object with identical bytes, bumping ETag/ModTime; +// the body hash backstop must recognize the content is unchanged and skip publishing. +func tickWithMetadataOnlyChange(t *testing.T, mockPoller *synctesting.MockPoller, dataSyncChan chan sync.DataSync, blobMock *MockBlob, sameContent string) { + blobMock.AddObject(sameContent) + mockPoller.Tick() + expectNoUpdate(t, dataSyncChan) +} + +func expectNoUpdate(t *testing.T, dataSyncChan chan sync.DataSync) { select { case data, ok := <-dataSyncChan: if ok { @@ -115,22 +139,20 @@ func TestReSync(t *testing.T) { ) mockPoller := synctesting.NewMockPoller() + blobMock := NewMockBlob(scheme) blobSync := &Sync{ - Bucket: scheme + "://" + bucket, - Object: object, - Poller: mockPoller, - Logger: logger.NewLogger(nil, false), + Bucket: scheme + "://" + bucket, + Object: object, + BlobURLMux: blobMock.URLMux(), + Poller: mockPoller, + Logger: logger.NewLogger(nil, false), } - blobMock := NewMockBlob(scheme, func() *Sync { - return blobSync - }) - blobSync.BlobURLMux = blobMock.URLMux() ctx := context.Background() dataSyncChan := make(chan sync.DataSync, 1) config := "my-config" - blobMock.AddObject(object, config) + blobMock.AddObject(config) err := blobSync.ReSync(ctx, dataSyncChan) if err != nil { @@ -143,3 +165,251 @@ func TestReSync(t *testing.T) { t.Errorf("expected content: %s, but received content: %s", config, data.FlagData) } } + +// runSync performs a single change-detecting sync and reports whether the full +// object was fetched and whether anything was published. +func runSync(t *testing.T, s *Sync, blobMock *MockBlob, ch chan sync.DataSync) (fetched, published bool, data string) { + t.Helper() + before := blobMock.Reads() + if err := s.sync(context.Background(), ch, false); err != nil { + t.Fatalf("sync failed: %v", err) + } + fetched = blobMock.Reads() > before + select { + case d := <-ch: + published = true + data = d.FlagData + default: + } + return fetched, published, data +} + +func TestBlobSync_ReSync_DoesNotCauseFakeChange(t *testing.T) { + t1 := time.Now() + t2 := t1.Add(time.Second) + + body1 := "{\"flags\":{\"a\":{}}}" + body2 := "{\"flags\":{\"b\":{}}}" + + blobMock := NewMockBlob("fake") + blobMock.SetObject("v1", t1, body1) + s := &Sync{ + Bucket: "fake://bucket", + Object: "flags.json", + BlobURLMux: blobMock.URLMux(), + Logger: logger.NewLogger(nil, false), + } + ch := make(chan sync.DataSync, 1) + + // Baseline regular sync establishes the ETag/ModTime/body hash. + fetched, published, data := runSync(t, s, blobMock, ch) + if !fetched || !published || data != body1 { + t.Fatalf("baseline sync: expected fetch+publish of %q, got fetched=%v published=%v data=%q", + body1, fetched, published, data) + } + + blobMock.SetObject("v2", t2, body2) + + // ReSync publishes the current content unconditionally. + if err := s.ReSync(context.Background(), ch); err != nil { + t.Fatalf("ReSync failed: %v", err) + } + select { + case d := <-ch: + if d.FlagData != body2 { + t.Fatalf("ReSync: expected published content %q, got %q", body2, d.FlagData) + } + default: + t.Fatalf("ReSync: expected a publish") + } + + // The next regular poll observes the same, still-unchanged content. + // It must fetch (ETag differs from last regular sync) but must + // NOT republish, since the body matches what ReSync sent. + fetched, published, data = runSync(t, s, blobMock, ch) + if !fetched { + t.Errorf("expected the next regular poll to fetch due to the stale recorded ETag") + } + if published { + t.Errorf("expected no publish (fake change), got data=%q", data) + } +} + +func TestBlobSync_SyncAndResync(t *testing.T) { + t0 := time.Now() + t1 := t0.Add(time.Second) + + body1 := "{\"flags\":{\"a\":{}}}" + body2 := "{\"flags\":{\"b\":{}}}" + + blobMock := NewMockBlob("fake") + blobMock.SetObject("v1", t0, body1) + s := &Sync{ + Bucket: "fake://bucket", + Object: "flags.json", + BlobURLMux: blobMock.URLMux(), + Logger: logger.NewLogger(nil, false), + } + ch := make(chan sync.DataSync, 1) + + // Initial sync fetches and publishes + fetched, published, data := runSync(t, s, blobMock, ch) + if !fetched || !published || data != body1 { + t.Fatalf("initial sync: expected fetch+publish of %q, got fetched=%v published=%v data=%q", + body1, fetched, published, data) + } + + // A change is fetched and published + blobMock.SetObject("v2", t1, body2) + fetched, published, data = runSync(t, s, blobMock, ch) + if !fetched || !published || data != body2 { + t.Fatalf("change sync: expected fetch+publish of %q, got fetched=%v published=%v data=%q", + body2, fetched, published, data) + } + + // An identical tick is not fetched and published + fetched, published, data = runSync(t, s, blobMock, ch) + if fetched || published { + t.Errorf("identical tick: expected no fetch and no publish, got fetched=%v published=%v (data=%q)", + fetched, published, data) + } +} + +func TestBlobSync_ChangeDetection(t *testing.T) { + t0 := time.Now() + t1 := t0.Add(time.Second) + + body1 := "{\"flags\":{\"a\":{}}}" + body2 := "{\"flags\":{\"b\":{}}}" + + type state struct { + etag string + modTime time.Time + content string + } + + tests := map[string]struct { + base state + next state + wantFetch bool + wantPublish bool + wantData string + }{ + "ETag unchanged -> no fetch, no publish": { + base: state{etag: "v1", modTime: t0, content: body1}, + next: state{etag: "v1", modTime: t0, content: body1}, + wantFetch: false, + wantPublish: false, + }, + "ETag changed, ModTime bumped, body identical -> fetch but no publish": { + base: state{etag: "v1", modTime: t0, content: body1}, + next: state{etag: "v2", modTime: t1, content: body1}, + wantFetch: true, + wantPublish: false, + }, + "ETag absent, ModTime unchanged -> no fetch, no publish": { + base: state{etag: "", modTime: t0, content: body1}, + next: state{etag: "", modTime: t0, content: body1}, + wantFetch: false, + wantPublish: false, + }, + "ETag absent, ModTime bumped, body identical -> fetch but no publish": { + base: state{etag: "", modTime: t0, content: body1}, + next: state{etag: "", modTime: t1, content: body1}, + wantFetch: true, + wantPublish: false, + }, + "ETag absent, ModTime bumped, body changed -> fetch and publish": { + base: state{etag: "", modTime: t0, content: body1}, + next: state{etag: "", modTime: t1, content: body2}, + wantFetch: true, + wantPublish: true, + wantData: body2, + }, + "ETag changed, body changed -> fetch and publish": { + base: state{etag: "v1", modTime: t0, content: body1}, + next: state{etag: "v2", modTime: t1, content: body2}, + wantFetch: true, + wantPublish: true, + wantData: body2, + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + blobMock := NewMockBlob("fake") + blobMock.SetObject(tt.base.etag, tt.base.modTime, tt.base.content) + s := &Sync{ + Bucket: "fake://bucket", + Object: "flags.json", + BlobURLMux: blobMock.URLMux(), + Logger: logger.NewLogger(nil, false), + } + ch := make(chan sync.DataSync, 1) + + // Baseline sync establishes the cached ETag/ModTime/body hash. + fetched, published, data := runSync(t, s, blobMock, ch) + if !fetched || !published || data != tt.base.content { + t.Fatalf("baseline sync: expected fetch+publish of %q, got fetched=%v published=%v data=%q", + tt.base.content, fetched, published, data) + } + + // Apply the scenario's next observed state. + blobMock.SetObject(tt.next.etag, tt.next.modTime, tt.next.content) + + fetched, published, data = runSync(t, s, blobMock, ch) + if fetched != tt.wantFetch { + t.Errorf("fetch: expected %v, got %v", tt.wantFetch, fetched) + } + if published != tt.wantPublish { + t.Errorf("publish: expected %v, got %v (data=%q)", tt.wantPublish, published, data) + } + if tt.wantPublish && data != tt.wantData { + t.Errorf("published data: expected %q, got %q", tt.wantData, data) + } + }) + } +} + +// runs sync and ReSync concurrently on a single blob to detect races due to missing locks +func TestBlobSync_ConcurrentChanges(t *testing.T) { + blobMock := NewMockBlob("fake") + blobMock.SetObject("v1", time.Now(), "{\"flags\":{\"a\":{}}}") + s := &Sync{ + Bucket: "fake://bucket", + Object: "flags.json", + BlobURLMux: blobMock.URLMux(), + Logger: logger.NewLogger(nil, false), + } + + // Drain published data so publishing syncs never block on the channel. + ch := make(chan sync.DataSync) + go func() { + for range ch { + } + }() + + // run a bunch of sync/ReSyncs on the same blob + // will break under --race if we remove locks + ctx := context.Background() + var wg stdsync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 50; j++ { + if err := s.sync(ctx, ch, false); err != nil { + t.Errorf("sync failed: %v", err) + return + } + if err := s.ReSync(ctx, ch); err != nil { + t.Errorf("ReSync failed: %v", err) + return + } + } + }() + } + + wg.Wait() + close(ch) // all sends are done; stop the drainer +} diff --git a/core/pkg/sync/blob/mock_blob.go b/core/pkg/sync/blob/mock_blob.go deleted file mode 100644 index 59d003f8d..000000000 --- a/core/pkg/sync/blob/mock_blob.go +++ /dev/null @@ -1,72 +0,0 @@ -package blob - -import ( - "context" - "log" - "net/url" - - "gocloud.dev/blob" - "gocloud.dev/blob/memblob" -) - -type MockBlob struct { - mux *blob.URLMux - scheme string - opener *fakeOpener -} - -type fakeOpener struct { - object string - content string - keepModTime bool - getSync func() *Sync -} - -func (f *fakeOpener) OpenBucketURL(ctx context.Context, _ *url.URL) (*blob.Bucket, error) { - bucketURL, err := url.Parse("mem://") - if err != nil { - log.Fatalf("couldn't parse url: %s: %v", "mem://", err) - } - opener := &memblob.URLOpener{} - bucket, err := opener.OpenBucketURL(ctx, bucketURL) - if err != nil { - log.Fatalf("couldn't open in memory bucket: %v", err) - } - if f.object != "" { - err = bucket.WriteAll(ctx, f.object, []byte(f.content), nil) - if err != nil { - log.Fatalf("couldn't write in memory file: %v", err) - } - } - if f.keepModTime && f.object != "" { - attrs, err := bucket.Attributes(ctx, f.object) - if err != nil { - log.Fatalf("couldn't get memory file attributes: %v", err) - } - f.getSync().lastUpdated = attrs.ModTime - } else { - f.keepModTime = true - } - return bucket, nil -} - -func NewMockBlob(scheme string, getSync func() *Sync) *MockBlob { - mux := new(blob.URLMux) - opener := &fakeOpener{getSync: getSync} - mux.RegisterBucket(scheme, opener) - return &MockBlob{ - mux: mux, - scheme: scheme, - opener: opener, - } -} - -func (mb *MockBlob) URLMux() *blob.URLMux { - return mb.mux -} - -func (mb *MockBlob) AddObject(object, content string) { - mb.opener.object = object - mb.opener.content = content - mb.opener.keepModTime = false -} diff --git a/core/pkg/sync/blob/mock_blob_test.go b/core/pkg/sync/blob/mock_blob_test.go new file mode 100644 index 000000000..b7308291e --- /dev/null +++ b/core/pkg/sync/blob/mock_blob_test.go @@ -0,0 +1,147 @@ +package blob + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/url" + "sync/atomic" + "time" + + "gocloud.dev/blob" + "gocloud.dev/blob/driver" + "gocloud.dev/gcerrors" +) + +// MockBlob is a controllable blob source for tests. It is backed by a fake +// driver.Bucket so tests can set the object's ETag, ModTime and body +// independently, and can inspect how many full-object fetches occurred. +type MockBlob struct { + mux *blob.URLMux + scheme string + drv *fakeBlobDriver +} + +// NewMockBlob registers a fake bucket under scheme and returns a handle for +// controlling the object it serves. +func NewMockBlob(scheme string) *MockBlob { + drv := &fakeBlobDriver{} + mux := new(blob.URLMux) + mux.RegisterBucket(scheme, &fakeDriverOpener{drv: drv}) + return &MockBlob{ + mux: mux, + scheme: scheme, + drv: drv, + } +} + +func (mb *MockBlob) URLMux() *blob.URLMux { + return mb.mux +} + +// AddObject sets the object's content and assigns a fresh ETag and ModTime +func (mb *MockBlob) AddObject(content string) { + mb.drv.revision++ + mb.drv.etag = fmt.Sprintf("etag-%d", mb.drv.revision) + mb.drv.modTime = time.Now() + mb.drv.content = []byte(content) +} + +// SetObject sets the object's ETag, ModTime and content explicitly +func (mb *MockBlob) SetObject(etag string, modTime time.Time, content string) { + mb.drv.etag = etag + mb.drv.modTime = modTime + mb.drv.content = []byte(content) +} + +// Reads reports how many full-object fetches (NewRangeReader calls) have happened +func (mb *MockBlob) Reads() int { + return int(mb.drv.reads.Load()) +} + +// fakeBlobDriver is a controllable driver.Bucket. It keeps its state +// across OpenBucket calls and never regenerates ETags or ModTimes on +// its own, so tests decide exactly what a sync observes. Object state is +// only mutated between syncs, but reads is bumped from within concurrent +// syncs, so it is atomic to stay clean under `go test -race`. +type fakeBlobDriver struct { + etag string + modTime time.Time + content []byte + reads atomic.Int64 // number of NewRangeReader calls, i.e. full-object fetches + revision int // monotonically bumped by AddObject to mint fresh ETags +} + +func (d *fakeBlobDriver) Attributes(_ context.Context, _ string) (*driver.Attributes, error) { + return &driver.Attributes{ + ContentType: "application/json", + ModTime: d.modTime, + Size: int64(len(d.content)), + ETag: d.etag, + }, nil +} + +func (d *fakeBlobDriver) NewRangeReader( + _ context.Context, _ string, offset, length int64, _ *driver.ReaderOptions, +) (driver.Reader, error) { + d.reads.Add(1) + data := d.content + if offset > int64(len(data)) { + offset = int64(len(data)) + } + data = data[offset:] + if length >= 0 && length < int64(len(data)) { + data = data[:length] + } + return &fakeBlobReader{ + Reader: bytes.NewReader(data), + attrs: driver.ReaderAttributes{ + ContentType: "application/json", + ModTime: d.modTime, + Size: int64(len(d.content)), + }, + }, nil +} + +var errNotImplemented = errors.New("not implemented") + +func (d *fakeBlobDriver) ErrorCode(error) gcerrors.ErrorCode { return gcerrors.OK } +func (d *fakeBlobDriver) As(any) bool { return false } +func (d *fakeBlobDriver) ErrorAs(error, any) bool { return false } +func (d *fakeBlobDriver) Close() error { return nil } + +func (d *fakeBlobDriver) ListPaged(context.Context, *driver.ListOptions) (*driver.ListPage, error) { + return nil, errNotImplemented +} + +func (d *fakeBlobDriver) NewTypedWriter( + context.Context, string, string, *driver.WriterOptions, +) (driver.Writer, error) { + return nil, errNotImplemented +} + +func (d *fakeBlobDriver) Copy(context.Context, string, string, *driver.CopyOptions) error { + return errNotImplemented +} +func (d *fakeBlobDriver) Delete(context.Context, string) error { return errNotImplemented } + +func (d *fakeBlobDriver) SignedURL(context.Context, string, *driver.SignedURLOptions) (string, error) { + return "", errNotImplemented +} + +// fakeBlobReader adapts a bytes.Reader to the driver.Reader interface. +type fakeBlobReader struct { + *bytes.Reader + attrs driver.ReaderAttributes +} + +func (r *fakeBlobReader) Close() error { return nil } +func (r *fakeBlobReader) Attributes() *driver.ReaderAttributes { return &r.attrs } +func (r *fakeBlobReader) As(any) bool { return false } + +type fakeDriverOpener struct{ drv *fakeBlobDriver } + +func (o *fakeDriverOpener) OpenBucketURL(_ context.Context, _ *url.URL) (*blob.Bucket, error) { + return blob.NewBucket(o.drv), nil +} diff --git a/core/pkg/sync/http/http_sync.go b/core/pkg/sync/http/http_sync.go index e68f1f6d8..cc679d5cf 100644 --- a/core/pkg/sync/http/http_sync.go +++ b/core/pkg/sync/http/http_sync.go @@ -3,7 +3,6 @@ package http import ( "bytes" "context" - "encoding/base64" "errors" "fmt" "io" @@ -18,7 +17,6 @@ import ( "github.com/open-feature/flagd/core/pkg/sync/internal/polling" "github.com/open-feature/flagd/core/pkg/utils" "go.uber.org/zap" - "golang.org/x/crypto/sha3" //nolint:gosec "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" ) @@ -220,7 +218,7 @@ func (hs *Sync) fetchBody(ctx context.Context, fetchAll bool) (string, bool, err } if json != "" { - hs.lastBodySHA = hs.generateSha([]byte(body)) + hs.lastBodySHA = utils.GenerateSha([]byte(json)) } return json, false, nil @@ -236,12 +234,6 @@ func getFileExtensions(url string) string { return filepath.Ext(u.Path) } -func (hs *Sync) generateSha(body []byte) string { - hasher := sha3.New256() - hasher.Write(body) - return base64.URLEncoding.EncodeToString(hasher.Sum(nil)) -} - func (hs *Sync) Fetch(ctx context.Context) (string, error) { body, _, err := hs.fetchBody(ctx, false) return body, err diff --git a/core/pkg/utils/hash.go b/core/pkg/utils/hash.go new file mode 100644 index 000000000..e5f0c29e9 --- /dev/null +++ b/core/pkg/utils/hash.go @@ -0,0 +1,37 @@ +package utils + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "io" + + "golang.org/x/crypto/sha3" //nolint:gosec +) + +func GenerateSha(body []byte) string { + hasher := sha3.New256() + hasher.Write(canonicalize(body)) + return base64.URLEncoding.EncodeToString(hasher.Sum(nil)) +} + +func canonicalize(body []byte) []byte { + dec := json.NewDecoder(bytes.NewReader(body)) + dec.UseNumber() + + var parsed interface{} + if err := dec.Decode(&parsed); err != nil { + return body + } + // check for leftover garbage after valid json + var extra json.RawMessage + if dec.Decode(&extra) != io.EOF { + return body + } + + canonical, err := json.Marshal(parsed) + if err != nil { + return body + } + return canonical +} diff --git a/core/pkg/utils/hash_test.go b/core/pkg/utils/hash_test.go new file mode 100644 index 000000000..080611bb6 --- /dev/null +++ b/core/pkg/utils/hash_test.go @@ -0,0 +1,51 @@ +package utils + +import "testing" + +func TestGenerateSha(t *testing.T) { + t.Run("ignores object key ordering", func(t *testing.T) { + a := []byte(`{"flags":{"a":{},"b":{}},"metadata":{"x":1}}`) + b := []byte(`{"metadata":{"x":1},"flags":{"b":{},"a":{}}}`) + if GenerateSha(a) != GenerateSha(b) { + t.Errorf("expected key-reordered JSON to hash equally:\n a=%s\n b=%s", GenerateSha(a), GenerateSha(b)) + } + }) + + t.Run("ignores insignificant whitespace", func(t *testing.T) { + compact := []byte(`{"flags":{"a":{}}}`) + spaced := []byte("{\n \"flags\": {\n \"a\": {}\n }\n}") + if GenerateSha(compact) != GenerateSha(spaced) { + t.Error("expected formatting-only differences to hash equally") + } + }) + + t.Run("detects genuine content changes", func(t *testing.T) { + a := []byte(`{"flags":{"a":{}}}`) + b := []byte(`{"flags":{"b":{}}}`) + if GenerateSha(a) == GenerateSha(b) { + t.Error("expected different content to hash differently") + } + }) + + t.Run("falls back to raw bytes for non-json", func(t *testing.T) { + if GenerateSha([]byte("not json")) == GenerateSha([]byte("also not json")) { + t.Error("expected distinct non-json payloads to hash differently") + } + }) + + t.Run("preserves precision of large integers", func(t *testing.T) { + a := []byte(`{"flags":{"a":{"value":9007199254740993}}}`) + b := []byte(`{"flags":{"a":{"value":9007199254740992}}}`) + if GenerateSha(a) == GenerateSha(b) { + t.Error("expected distinct large integers to hash differently") + } + }) + + t.Run("rejects trailing garbage (}) after a valid json value", func(t *testing.T) { + valid := []byte(`{"flags":{}}`) + trailing := []byte(`{"flags":{}}}`) + if GenerateSha(valid) == GenerateSha(trailing) { + t.Error("expected trailing garbage to fall back to raw-byte hashing, not be silently ignored") + } + }) +}