crbench//

← all cases

Anonymous: Add configurable device limit

Tier 2 easy go · local · real merged PR from grafana/grafana #79265

Ground-truth defects

d1 · security · medium
Race condition: Multiple concurrent requests could pass the device count check simultaneously and create devices beyond the limit. Consider using a database transaction or lock.
d2 · security · medium
When the anonymous device limit is reached, a new device's first request is denied (401) but a retry authenticates: tagDeviceUI populates localCache (SetDefault) before the CreateOrUpdateDevice write that returns ErrDeviceLimitReached, so the cached key short-circuits the next request — the limit is bypassable on reload and the denial is intermittent.

The change under review

diff
diff --git a/packages/grafana-data/src/types/config.ts b/packages/grafana-data/src/types/config.ts
index 5703028f2c..e1c8c8eaa4 100644
--- a/packages/grafana-data/src/types/config.ts
+++ b/packages/grafana-data/src/types/config.ts
@@ -197,6 +197,7 @@ export interface GrafanaConfig {
   theme: GrafanaTheme;
   theme2: GrafanaTheme2;
   anonymousEnabled: boolean;
+  anonymousDeviceLimit: number | undefined;
   featureToggles: FeatureToggles;
   licenseInfo: LicenseInfo;
   http2Enabled: boolean;
diff --git a/packages/grafana-runtime/src/config.ts b/packages/grafana-runtime/src/config.ts
index 2709d5cf9a..deedcfeee5 100644
--- a/packages/grafana-runtime/src/config.ts
+++ b/packages/grafana-runtime/src/config.ts
@@ -94,6 +94,7 @@ export class GrafanaBootConfig implements GrafanaConfig {
   theme2: GrafanaTheme2;
   featureToggles: FeatureToggles = {};
   anonymousEnabled = false;
+  anonymousDeviceLimit = undefined;
   licenseInfo: LicenseInfo = {} as LicenseInfo;
   rendererAvailable = false;
   rendererVersion = '';
diff --git a/pkg/api/dtos/frontend_settings.go b/pkg/api/dtos/frontend_settings.go
index 166dae6216..84dd91c622 100644
--- a/pkg/api/dtos/frontend_settings.go
+++ b/pkg/api/dtos/frontend_settings.go
@@ -192,6 +192,7 @@ type FrontendSettingsDTO struct {
 
 	FeatureToggles                   map[string]bool                `json:"featureToggles"`
 	AnonymousEnabled                 bool                           `json:"anonymousEnabled"`
+	AnonymousDeviceLimit             int64                          `json:"anonymousDeviceLimit"`
 	RendererAvailable                bool                           `json:"rendererAvailable"`
 	RendererVersion                  string                         `json:"rendererVersion"`
 	SecretsManagerPluginEnabled      bool                           `json:"secretsManagerPluginEnabled"`
diff --git a/pkg/api/frontendsettings.go b/pkg/api/frontendsettings.go
index 215714b6f8..1092efe028 100644
--- a/pkg/api/frontendsettings.go
+++ b/pkg/api/frontendsettings.go
@@ -195,6 +195,7 @@ func (hs *HTTPServer) getFrontendSettings(c *contextmodel.ReqContext) (*dtos.Fro
 
 		FeatureToggles:                   hs.Features.GetEnabled(c.Req.Context()),
 		AnonymousEnabled:                 hs.Cfg.AnonymousEnabled,
+		AnonymousDeviceLimit:             hs.Cfg.AnonymousDeviceLimit,
 		RendererAvailable:                hs.RenderService.IsAvailable(c.Req.Context()),
 		RendererVersion:                  hs.RenderService.Version(),
 		SecretsManagerPluginEnabled:      secretsManagerPluginEnabled,
diff --git a/pkg/services/anonymous/anonimpl/anonstore/database.go b/pkg/services/anonymous/anonimpl/anonstore/database.go
index 6531348662..8c5ed04db2 100644
--- a/pkg/services/anonymous/anonimpl/anonstore/database.go
+++ b/pkg/services/anonymous/anonimpl/anonstore/database.go
@@ -13,10 +13,14 @@ import (
 )
 
 const cacheKeyPrefix = "anon-device"
+const anonymousDeviceExpiration = 30 * 24 * time.Hour
+
+var ErrDeviceLimitReached = fmt.Errorf("device limit reached")
 
 type AnonDBStore struct {
-	sqlStore db.DB
-	log      log.Logger
+	sqlStore    db.DB
+	log         log.Logger
+	deviceLimit int64
 }
 
 type Device struct {
@@ -45,8 +49,8 @@ type AnonStore interface {
 	DeleteDevicesOlderThan(ctx context.Context, olderThan time.Time) error
 }
 
-func ProvideAnonDBStore(sqlStore db.DB) *AnonDBStore {
-	return &AnonDBStore{sqlStore: sqlStore, log: log.New("anonstore")}
+func ProvideAnonDBStore(sqlStore db.DB, deviceLimit int64) *AnonDBStore {
+	return &AnonDBStore{sqlStore: sqlStore, log: log.New("anonstore"), deviceLimit: deviceLimit}
 }
 
 func (s *AnonDBStore) ListDevices(ctx context.Context, from *time.Time, to *time.Time) ([]*Device, error) {
@@ -65,9 +69,54 @@ func (s *AnonDBStore) ListDevices(ctx context.Context, from *time.Time, to *time
 	return devices, err
 }
 
+// updateDevice updates a device if it exists and has been updated between the given times.
+func (s *AnonDBStore) updateDevice(ctx context.Context, device *Device) error {
+	const query = `UPDATE anon_device SET
+client_ip = ?,
+user_agent = ?,
+updated_at = ?
+WHERE device_id = ? AND updated_at BETWEEN ? AND ?`
+
+	args := []interface{}{device.ClientIP, device.UserAgent, device.UpdatedAt.UTC(), device.DeviceID,
+		device.UpdatedAt.UTC().Add(-anonymousDeviceExpiration), device.UpdatedAt.UTC().Add(time.Minute),
+	}
+	err := s.sqlStore.WithDbSession(ctx, func(dbSession *sqlstore.DBSession) error {
+		args = append([]interface{}{query}, args...)
+		result, err := dbSession.Exec(args...)
+		if err != nil {
+			return err
+		}
+
+		rowsAffected, err := result.RowsAffected()
+		if err != nil {
+			return err
+		}
+
+		if rowsAffected == 0 {
+			return ErrDeviceLimitReached
+		}
+
+		return nil
+	})
+
+	return err
+}
+
 func (s *AnonDBStore) CreateOrUpdateDevice(ctx context.Context, device *Device) error {
 	var query string
 
+	// if device limit is reached, only update devices
+	if s.deviceLimit > 0 {
+		count, err := s.CountDevices(ctx, time.Now().UTC().Add(-anonymousDeviceExpiration), time.Now().UTC().Add(time.Minute))
+		if err != nil {
+			return err
+		}
+
+		if count >= s.deviceLimit {
+			return s.updateDevice(ctx, device)
+		}
+	}
+
 	args := []any{device.DeviceID, device.ClientIP, device.UserAgent,
 		device.CreatedAt.UTC(), device.UpdatedAt.UTC()}
 	switch s.sqlStore.GetDBType() {
diff --git a/pkg/services/anonymous/anonimpl/anonstore/database_test.go b/pkg/services/anonymous/anonimpl/anonstore/database_test.go
index b94dd82d28..0da29d5f6b 100644
--- a/pkg/services/anonymous/anonimpl/anonstore/database_test.go
+++ b/pkg/services/anonymous/anonimpl/anonstore/database_test.go
@@ -13,7 +13,7 @@ import (
 
 func TestIntegrationAnonStore_DeleteDevicesOlderThan(t *testing.T) {
 	store := db.InitTestDB(t)
-	anonDBStore := ProvideAnonDBStore(store)
+	anonDBStore := ProvideAnonDBStore(store, 0)
 	const keepFor = time.Hour * 24 * 61
 
 	anonDevice := &Device{
@@ -48,9 +48,30 @@ func TestIntegrationAnonStore_DeleteDevicesOlderThan(t *testing.T) {
 	assert.Equal(t, "keep", devices[0].DeviceID)
 }
 
+func TestIntegrationBeyondDeviceLimit(t *testing.T) {
+	store := db.InitTestDB(t)
+	anonDBStore := ProvideAnonDBStore(store, 1)
+
+	anonDevice := &Device{
+		DeviceID:  "32mdo31deeqwes",
+		ClientIP:  "10.30.30.2",
+		UserAgent: "test",
+		UpdatedAt: time.Now().Add(-time.Hour),
+	}
+
+	err := anonDBStore.CreateOrUpdateDevice(context.Background(), anonDevice)
+	require.NoError(t, err)
+
+	anonDevice.DeviceID = "keep"
+	anonDevice.UpdatedAt = time.Now().Add(-time.Hour)
+
+	err = anonDBStore.CreateOrUpdateDevice(context.Background(), anonDevice)
+	require.ErrorIs(t, err, ErrDeviceLimitReached)
+}
+
 func TestIntegrationAnonStore_DeleteDevice(t *testing.T) {
 	store := db.InitTestDB(t)
-	anonDBStore := ProvideAnonDBStore(store)
+	anonDBStore := ProvideAnonDBStore(store, 0)
 	const keepFor = time.Hour * 24 * 61
 
 	anonDevice := &Device{
diff --git a/pkg/services/anonymous/anonimpl/api/api.go b/pkg/services/anonymous/anonimpl/api/api.go
index 85d9c7318e..defdf28d17 100644
--- a/pkg/services/anonymous/anonimpl/api/api.go
+++ b/pkg/services/anonymous/anonimpl/api/api.go
@@ -15,9 +15,7 @@ import (
 	"github.com/grafana/grafana/pkg/util"
 )
 
-const (
-	thirtyDays = 30 * 24 * time.Hour
-)
+const anonymousDeviceExpiration = 30 * 24 * time.Hour
 
 type deviceDTO struct {
 	anonstore.Device
@@ -70,7 +68,7 @@ func (api *AnonDeviceServiceAPI) RegisterAPIEndpoints() {
 //	404: notFoundError
 //	500: internalServerError
 func (api *AnonDeviceServiceAPI) ListDevices(c *contextmodel.ReqContext) response.Response {
-	fromTime := time.Now().Add(-thirtyDays)
+	fromTime := time.Now().Add(-anonymousDeviceExpiration)
 	toTime := time.Now()
 
 	devices, err := api.store.ListDevices(c.Req.Context(), &fromTime, &toTime)
diff --git a/pkg/services/anonymous/anonimpl/client.go b/pkg/services/anonymous/anonimpl/client.go
index 363345e6cb..a74c9367cd 100644
--- a/pkg/services/anonymous/anonimpl/client.go
+++ b/pkg/services/anonymous/anonimpl/client.go
@@ -2,12 +2,13 @@ package anonimpl
 
 import (
 	"context"
+	"errors"
 	"net/http"
 	"strings"
-	"time"
 
 	"github.com/grafana/grafana/pkg/infra/log"
 	"github.com/grafana/grafana/pkg/services/anonymous"
+	"github.com/grafana/grafana/pkg/services/anonymous/anonimpl/anonstore"
 	"github.com/grafana/grafana/pkg/services/authn"
 	"github.com/grafana/grafana/pkg/services/org"
 	"github.com/grafana/grafana/pkg/setting"
@@ -15,8 +16,6 @@ import (
 
 var _ authn.ContextAwareClient = new(Anonymous)
 
-const timeoutTag = 2 * time.Minute
-
 type Anonymous struct {
 	cfg               *setting.Cfg
 	log               log.Logger
@@ -42,19 +41,13 @@ func (a *Anonymous) Authenticate(ctx context.Context, r *authn.Request) (*authn.
 		httpReqCopy.RemoteAddr = r.HTTPRequest.RemoteAddr
 	}
 
-	go func() {
-		defer func() {
-			if err := recover(); err != nil {
-				a.log.Warn("Tag anon session panic", "err", err)
-			}
-		}()
-
-		newCtx, cancel := context.WithTimeout(context.Background(), timeoutTag)
-		defer cancel()
-		if err := a.anonDeviceService.TagDevice(newCtx, httpReqCopy, anonymous.AnonDeviceUI); err != nil {
-			a.log.Warn("Failed to tag anonymous session", "error", err)
+	if err := a.anonDeviceService.TagDevice(ctx, httpReqCopy, anonymous.AnonDeviceUI); err != nil {
+		if errors.Is(err, anonstore.ErrDeviceLimitReached) {
+			return nil, err
 		}
-	}()
+
+		a.log.Warn("Failed to tag anonymous session", "error", err)
+	}
 
 	return &authn.Identity{
 		ID:           authn.AnonymousNamespaceID,
diff --git a/pkg/services/anonymous/anonimpl/impl.go b/pkg/services/anonymous/anonimpl/impl.go
index 4a98805412..c85463708f 100644
--- a/pkg/services/anonymous/anonimpl/impl.go
+++ b/pkg/services/anonymous/anonimpl/impl.go
@@ -6,6 +6,7 @@ import (
 	"time"
 
 	"github.com/grafana/grafana/pkg/api/routing"
+	"github.com/grafana/grafana/pkg/infra/db"
 	"github.com/grafana/grafana/pkg/infra/localcache"
 	"github.com/grafana/grafana/pkg/infra/log"
 	"github.com/grafana/grafana/pkg/infra/network"
@@ -33,13 +34,13 @@ type AnonDeviceService struct {
 }
 
 func ProvideAnonymousDeviceService(usageStats usagestats.Service, authBroker authn.Service,
-	anonStore anonstore.AnonStore, cfg *setting.Cfg, orgService org.Service,
+	sqlStore db.DB, cfg *setting.Cfg, orgService org.Service,
 	serverLockService *serverlock.ServerLockService, accesscontrol accesscontrol.AccessControl, routeRegister routing.RouteRegister,
 ) *AnonDeviceService {
 	a := &AnonDeviceService{
 		log:        log.New("anonymous-session-service"),
 		localCache: localcache.New(29*time.Minute, 15*time.Minute),
-		anonStore:  anonStore,
+		anonStore:  anonstore.ProvideAnonDBStore(sqlStore, cfg.AnonymousDeviceLimit),
 		serverLock: serverLockService,
 	}
 
@@ -57,7 +58,7 @@ func ProvideAnonymousDeviceService(usageStats usagestats.Service, authBroker aut
 		authBroker.RegisterPostLoginHook(a.untagDevice, 100)
 	}
 
-	anonAPI := api.NewAnonDeviceServiceAPI(cfg, anonStore, accesscontrol, routeRegister)
+	anonAPI := api.NewAnonDeviceServiceAPI(cfg, a.anonStore, accesscontrol, routeRegister)
 	anonAPI.RegisterAPIEndpoints()
 
 	return a
@@ -143,6 +144,7 @@ func (a *AnonDeviceService) TagDevice(ctx context.Context, httpReq *http.Request
 	err = a.tagDeviceUI(ctx, httpReq, taggedDevice)
 	if err != nil {
 		a.log.Debug("Failed to tag device for UI", "error", err)
+		return err
 	}
 
 	return nil
diff --git a/pkg/services/anonymous/anonimpl/impl_test.go b/pkg/services/anonymous/anonimpl/impl_test.go
index 1a1ca2a89e..295654f93b 100644
--- a/pkg/services/anonymous/anonimpl/impl_test.go
+++ b/pkg/services/anonymous/anonimpl/impl_test.go
@@ -113,16 +113,15 @@ func TestIntegrationDeviceService_tag(t *testing.T) {
 	for _, tc := range testCases {
 		t.Run(tc.name, func(t *testing.T) {
 			store := db.InitTestDB(t)
-			anonDBStore := anonstore.ProvideAnonDBStore(store)
 			anonService := ProvideAnonymousDeviceService(&usagestats.UsageStatsMock{},
-				&authntest.FakeService{}, anonDBStore, setting.NewCfg(), orgtest.NewOrgServiceFake(), nil, actest.FakeAccessControl{}, &routing.RouteRegisterImpl{})
+				&authntest.FakeService{}, store, setting.NewCfg(), orgtest.NewOrgServiceFake(), nil, actest.FakeAccessControl{}, &routing.RouteRegisterImpl{})
 
 			for _, req := range tc.req {
 				err := anonService.TagDevice(context.Background(), req.httpReq, req.kind)
 				require.NoError(t, err)
 			}
 
-			devices, err := anonDBStore.ListDevices(context.Background(), nil, nil)
+			devices, err := anonService.anonStore.ListDevices(context.Background(), nil, nil)
 			require.NoError(t, err)
 			require.Len(t, devices, int(tc.expectedAnonUICount))
 			if tc.expectedDevice != nil {
@@ -149,9 +148,8 @@ func TestIntegrationDeviceService_tag(t *testing.T) {
 // Ensure that the local cache prevents request from being tagged
 func TestIntegrationAnonDeviceService_localCacheSafety(t *testing.T) {
 	store := db.InitTestDB(t)
-	anonDBStore := anonstore.ProvideAnonDBStore(store)
 	anonService := ProvideAnonymousDeviceService(&usagestats.UsageStatsMock{},
-		&authntest.FakeService{}, anonDBStore, setting.NewCfg(), orgtest.NewOrgServiceFake(), nil, actest.FakeAccessControl{}, &routing.RouteRegisterImpl{})
+		&authntest.FakeService{}, store, setting.NewCfg(), orgtest.NewOrgServiceFake(), nil, actest.FakeAccessControl{}, &routing.RouteRegisterImpl{})
 
 	req := &http.Request{
 		Header: http.Header{
diff --git a/pkg/setting/setting.go b/pkg/setting/setting.go
index 45d9e2ae60..d34049fed5 100644
--- a/pkg/setting/setting.go
+++ b/pkg/setting/setting.go
@@ -371,6 +371,7 @@ type Cfg struct {
 	AnonymousOrgName     string
 	AnonymousOrgRole     string
 	AnonymousHideVersion bool
+	AnonymousDeviceLimit int64
 
 	DateFormats DateFormats
 
@@ -1645,10 +1646,12 @@ func readAuthSettings(iniFile *ini.File, cfg *Cfg) (err error) {
 	readAuthGithubSettings(cfg)
 
 	// anonymous access
-	cfg.AnonymousEnabled = iniFile.Section("auth.anonymous").Key("enabled").MustBool(false)
-	cfg.AnonymousOrgName = valueAsString(iniFile.Section("auth.anonymous"), "org_name", "")
-	cfg.AnonymousOrgRole = valueAsString(iniFile.Section("auth.anonymous"), "org_role", "")
-	cfg.AnonymousHideVersion = iniFile.Section("auth.anonymous").Key("hide_version").MustBool(false)
+	anonSection := iniFile.Section("auth.anonymous")
+	cfg.AnonymousEnabled = anonSection.Key("enabled").MustBool(false)
+	cfg.AnonymousOrgName = valueAsString(anonSection, "org_name", "")
+	cfg.AnonymousOrgRole = valueAsString(anonSection, "org_role", "")
+	cfg.AnonymousHideVersion = anonSection.Key("hide_version").MustBool(false)
+	cfg.AnonymousDeviceLimit = anonSection.Key("device_limit").MustInt64(0)
 
 	// basic auth
 	authBasic := iniFile.Section("auth.basic")

Leaderboard for this case

easy · 8 of 9 bots fully caught it (89% solve rate) · 94% avg coverage.

#BotResultCaughtCoverageFindingsFalse alarms
1 Cubic solved 2/2 100.0% 2 0
2 cursor solved 2/2 100.0% 2 0
3 Drape (Deep Review) solved 2/2 100.0% 5 0
4 Drape (Review) solved 2/2 100.0% 5 0
5 greptile solved 2/2 100.0% 3 0
6 Mjolnir (Sonnet 5.5) solved 2/2 100.0% 3 0
7 qodo solved 2/2 100.0% 3 0
8 Claude Code (Opus 5.5) solved 2/2 100.0% 5 1
9 Mjolnir (Opus 5.5) partial 1/2 50.0% 3 1

Bot results

Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ exact
d2 medium ✓ off by one
uncertain
wire.go still lists anonstore.ProvideAnonDBStore, whose signature now takes an int64. In OSS nothing consumes AnonStore through wire any more, though. Wire only checks unused providers at the wire.Build argument level and only resolves the inputs of providers it actually needs, so whether generation really fails can't be shown from this code. [uncertain: no evidence quoted] [consensus 2/4: uncertain=2, valid=1, invalid=1]
valid · matches d2 · impact medium
invalid
Grafana's MySQL connection string sets clientFoundRows=true, so RowsAffected counts matched rows rather than changed rows. An unchanged UPDATE on an existing device therefore still returns 1, and the claimed false rejection doesn't happen. [invalid: contradiction] [consensus 3/3: invalid=3]
valid · matches d1 · impact medium
valid · impact low
The diff removes the goroutine, its recover() and the background context with a timeout. Tagging now runs inline on the request context, so it adds DB latency to anonymous auth and has no panic recovery, as the finding says. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
pkg/server/wire.go:374
`anonstore.ProvideAnonDBStore` is still registered in the wire set, but its signature is now `(db.DB, int64)`. Nothing provides an `int64`, so wire code generation fails. Also, `ProvideAnonymousDeviceService` no longer takes `anonstore.AnonStore`, so this provider and binding are unused, which wire reports as an error too. The DI graph needs updating (remove the provider and binding, or have them inject cfg).
pkg/services/anonymous/anonimpl/impl.go:86
The device limit can be bypassed. `tagDeviceUI` writes the device key to `localCache` before `CreateOrUpdateDevice` runs. When the store returns `ErrDeviceLimitReached`, the first request is rejected, but the key stays cached for 29 minutes. Every later request from that over-limit device returns nil early and authenticates. The cache entry should only be set after a successful create/update, or removed when an error occurs.
pkg/services/anonymous/anonimpl/anonstore/database.go:95
`updateDevice` treats `RowsAffected()==0` as 'device limit reached'. On MySQL (without CLIENT_FOUND_ROWS), RowsAffected counts changed rows, not matched rows. An existing device whose UPDATE sets the same values (same IP and UA, with `updated_at` equal at second precision, e.g. two instances or a cache miss in the same second) reports 0 rows. A legitimate, already-registered device is then rejected as over the limit.
pkg/services/anonymous/anonimpl/anonstore/database.go:109
The limit check is not atomic. It counts devices, then inserts in a separate statement. Concurrent new devices, or multiple Grafana instances, can all see `count < limit` and insert, so the configured `device_limit` can be exceeded. It also adds an extra COUNT(*) query over `anon_device` for every tag attempt when a limit is set.
pkg/services/anonymous/anonimpl/client.go:44
Device tagging moved from a background goroutine onto the synchronous authentication path, using the request context. Every anonymous request that misses the local cache now waits on DB writes (plus a COUNT query when a limit is set). A slow or failing DB adds latency to anonymous auth. It also removes the old panic recovery, and a cancelled request context now aborts the tagging write.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ exact
d2 medium ✓ exact
valid · matches d1 · impact medium
valid · matches d2 · impact medium
raw comments (3)
pkg/services/anonymous/anonimpl/anonstore/database.go:115
<!-- cubic:v=4301ee5e-3bbf-4258-b75c-045b33b0a661 --> <!-- cubic:review-run=a7f45378-7e9c-5c3c-ad3f-5b25ac67e901 --> <!-- metadata:{"confidence":9} --> P2: When multiple new devices arrive concurrently, each request can observe the same count below `deviceLimit` before inserting, so the configured limit is exceeded. Make admission atomic with the insert/update using a transaction, lock, or database-enforced conditional operation. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At pkg/services/anonymous/anonimpl/anonstore/database.go, line 115: <comment>When multiple new devices arrive concurrently, each request can observe the same count below `deviceLimit` before inserting, so the configured limit is exceeded. Make admission atomic with the insert/update using a transaction, lock, or database-enforced conditional operation.</comment> <file context> @@ -65,9 +69,54 @@ func (s *AnonDBStore) ListDevices(ctx context.Context, from *time.Time, to *time + return err + } + + if count >= s.deviceLimit { + return s.updateDevice(ctx, device) + } </file context> ``` </details>
pkg/services/anonymous/anonimpl/client.go:45
<!-- cubic:v=0ae715b3-332a-4484-808f-430633748ed8 --> <!-- cubic:review-run=a7f45378-7e9c-5c3c-ad3f-5b25ac67e901 --> <!-- metadata:{"confidence":10} --> P2: When a new device hits the limit, `tagDeviceUI` has already cached its key before persistence fails, so this branch rejects only the first request. Move `SetDefault` after a successful write or evict the key on errors so subsequent requests cannot bypass the limit. <details> <summary>Prompt for AI agents</summary> ```text Check if this issue is valid — if so, understand the root cause and fix it. At pkg/services/anonymous/anonimpl/client.go, line 45: <comment>When a new device hits the limit, `tagDeviceUI` has already cached its key before persistence fails, so this branch rejects only the first request. Move `SetDefault` after a successful write or evict the key on errors so subsequent requests cannot bypass the limit.</comment> <file context> @@ -42,19 +41,13 @@ func (a *Anonymous) Authenticate(ctx context.Context, r *authn.Request) (*authn. - if err := a.anonDeviceService.TagDevice(newCtx, httpReqCopy, anonymous.AnonDeviceUI); err != nil { - a.log.Warn("Failed to tag anonymous session", "error", err) + if err := a.anonDeviceService.TagDevice(ctx, httpReqCopy, anonymous.AnonDeviceUI); err != nil { + if errors.Is(err, anonstore.ErrDeviceLimitReached) { + return nil, err } </file context> ``` </details>
PR-level
<!-- cubic:review-summary:start --> **2 issues found** across 11 files <!-- cubic:review-summary:end --> <details> <summary>Prompt for AI agents (unresolved issues)</summary> ```text Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately. <file name="pkg/services/anonymous/anonimpl/anonstore/database.go"> <violation number="1" location="pkg/services/anonymous/anonimpl/anonstore/database.go:115"> P2: When multiple new devices arrive concurrently, each request can observe the same count below `deviceLimit` before inserting, so the configured limit is exceeded. Make admission atomic with the insert/update using a transaction, lock, or database-enforced conditional operation.</violation> </file> <file name="pkg/services/anonymous/anonimpl/client.go"> <violation number="1" location="pkg/services/anonymous/anonimpl/client.go:45"> P2: When a new device hits the limit, `tagDeviceUI` has already cached its key before persistence fails, so this branch rejects only the first request. Move `SetDefault` after a successful write or evict the key on errors so subsequent requests cannot bypass the limit.</violation> </file> ``` </details> <sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/90/ai_pr_review_github_delivery_c4a5b46595449b99103c82d7add185d8af8725dcbf446fac02ec265ea547cd79?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F90)</sub> <!-- cubic:review-post:ai_pr_review_github_delivery_c4a5b46595449b99103c82d7add185d8af8725dcbf446fac02ec265ea547cd79:86afe20a0d83b78efc78e527f4f387d5b650777c:a7f45378-7e9c-5c3c-ad3f-5b25ac67e901 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ exact
d2 medium ✓ off by one
valid · matches d2 · impact medium
valid · matches d1 · impact medium
raw comments (3)
pkg/services/anonymous/anonimpl/impl.go:61
### Cache bypasses device limit after failure **High Severity** <!-- DESCRIPTION START --> `tagDeviceUI` writes the device into `localCache` before `CreateOrUpdateDevice` succeeds. After a limit rejection, later requests from the same device hit the cache, skip the store, and `Authenticate` treats tagging as successful, so anonymous access is granted for the rest of the 29-minute TTL. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: 3ee47b60-8bd1-4911-831f-d3302934a50b --> <!-- LOCATIONS START pkg/services/anonymous/anonimpl/impl.go#L79-L97 pkg/services/anonymous/anonimpl/client.go#L43-L47 LOCATIONS END --> <details> <summary>Additional Locations (1)</summary> - [`pkg/services/anonymous/anonimpl/client.go#L43-L47`](https://github.com/drape-io/crbench-cursor-2026-09/blob/d7ddde65a5d68737bff4c730dbd299aea54ff916/pkg/services/anonymous/anonimpl/client.go#L43-L47) </details> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjNlZDJkOWVhLTNlNDktNGVkNC04ZmE1LTM1ZjhmMzA3MDA3YiIsImVuY3J5cHRpb25LZXkiOiIxRTlkN09salM3dDFXMmRLb2NsNEpSZ2hWNzNadWFYdFFNejE2UktOYTRNIiwiYnJhbmNoIjoidDItZ3JhZmFuYS03OTI2NSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjNlZDJkOWVhLTNlNDktNGVkNC04ZmE1LTM1ZjhmMzA3MDA3YiIsImVuY3J5cHRpb25LZXkiOiIxRTlkN09salM3dDFXMmRLb2NsNEpSZ2hWNzNadWFYdFFNejE2UktOYTRNIiwiYnJhbmNoIjoidDItZ3JhZmFuYS03OTI2NSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjQyLCJjb21taXRTaGEiOiJkN2RkZGU2NWE1ZDY4NzM3YmZmNGM3MzBkYmQyOTlhZWE1NGZmOTE2IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d7ddde65a5d68737bff4c730dbd299aea54ff916. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
pkg/services/anonymous/anonimpl/anonstore/database.go:118
### Device limit check is not atomic **Medium Severity** <!-- DESCRIPTION START --> `CreateOrUpdateDevice` counts active devices and, when under the cap, inserts in a separate step with no transaction or lock. Concurrent first-time devices can all observe `count &lt; deviceLimit` and all insert, so the configured limit can be exceeded. <!-- DESCRIPTION END --> <!-- BUGBOT_BUG_ID: d68670a4-1ba6-4c86-883a-eae39ba9fb5c --> <!-- LOCATIONS START pkg/services/anonymous/anonimpl/anonstore/database.go#L107-L118 LOCATIONS END --> <div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjE5MmM5ZGMyLWVlMmQtNDg1YS05NzhmLTM0ZDVmMGQ5MGJiNiIsImVuY3J5cHRpb25LZXkiOiJxWTBMUE5icWc3T2UzcHZCVFVsNGFYb1A1RzZxSXJfdUVHV3h5bk5CSEZzIiwiYnJhbmNoIjoidDItZ3JhZmFuYS03OTI2NSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>&nbsp;<a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjE5MmM5ZGMyLWVlMmQtNDg1YS05NzhmLTM0ZDVmMGQ5MGJiNiIsImVuY3J5cHRpb25LZXkiOiJxWTBMUE5icWc3T2UzcHZCVFVsNGFYb1A1RzZxSXJfdUVHV3h5bk5CSEZzIiwiYnJhbmNoIjoidDItZ3JhZmFuYS03OTI2NSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjQyLCJjb21taXRTaGEiOiJkN2RkZGU2NWE1ZDY4NzM3YmZmNGM3MzBkYmQyOTlhZWE1NGZmOTE2IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d7ddde65a5d68737bff4c730dbd299aea54ff916. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
PR-level
<!-- BUGBOT_REVIEW --> Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues. <!-- BUGBOT_FIX_ALL --> <a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTo0ZDgxODI3MC04MDExLTQ4MGQtYjcxNy1kNGNlZjUwOWRlOGQiLCJlbmNyeXB0aW9uS2V5Ijoid1dPTFB1MEZaRlN0YUl6bWp6ZDQwSnlrUzBQVmkzdGRJUngtVjZfT3BURSIsImJyYW5jaCI6InQyLWdyYWZhbmEtNzkyNjUiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <!-- /BUGBOT_FIX_ALL --> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN --> <sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup> <!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END --> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d7ddde65a5d68737bff4c730dbd299aea54ff916. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ off by one
d2 medium ✓ off by one
valid · matches d1 · impact medium
valid · matches d2 · impact medium
valid · impact medium
The new device_limit is only enforced inside TagDevice, which returns nil before any limit check when the device header is missing. Authenticate then returns an identity, so a request without the header gets past the limit the change adds. [grounded: tree pkg/services/anonymous/anonimpl/impl.go] [consensus 3/3: valid=3]
valid · impact low
The diff removes the background goroutine, so the DB upsert now runs inline on the auth path even when deviceLimit is 0. Only the local cache softens this; uncached requests still wait on the write. [grounded: diff] [consensus 3/3: valid=3]
valid · impact low
retryOnLocks calls the callback again on SQLite lock/busy errors. Because args is reassigned inside the callback, each retry adds the query string to the front again, which breaks the bound parameters. The new updateDevice brings in this bug. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
pkg/services/anonymous/anonimpl/anonstore/database.go:108
**Concurrent new devices can go over the limit** `CreateOrUpdateDevice` counts devices and then inserts in a separate step with no lock. New devices that arrive at the same time all see a count under the limit, and all get inserted. Do the count and insert atomically. ``` pkg/services/anonymous/anonimpl/anonstore/database.go:108 // if device limit is reached, only update devices pkg/services/anonymous/anonimpl/anonstore/database.go:109 if s.deviceLimit > 0 { pkg/services/anonymous/anonimpl/anonstore/database.go:110 count, err := s.CountDevices(ctx, time.Now().UTC().Add(-anonymousDeviceExpiration), time.Now().UTC().Add(time.Minute)) pkg/services/anonymous/anonimpl/anonstore/database.go:111 if err != nil { pkg/services/anonymous/anonimpl/anonstore/database.go:112 return err pkg/services/anonymous/anonimpl/anonstore/database.go:113 } pkg/services/anonymous/anonimpl/anonstore/database.go:115 if count >= s.deviceLimit { pkg/services/anonymous/anonimpl/anonstore/database.go:116 return s.updateDevice(ctx, device) pkg/services/anonymous/anonimpl/anonstore/database.go:117 } pkg/services/anonymous/anonimpl/anonstore/database.go:118 } ```
pkg/services/anonymous/anonimpl/impl.go:87
**Device limit bypassed on the second request** `tagDeviceUI` caches the device ID before the store write. If the write returns `ErrDeviceLimitReached`, the cache entry stays, so that device's later requests return nil and get in for 29 minutes. Set the cache entry only after `CreateOrUpdateDevice` succeeds. ``` pkg/services/anonymous/anonimpl/impl.go:144 err = a.tagDeviceUI(ctx, httpReq, taggedDevice) pkg/services/anonymous/anonimpl/impl.go:145 if err != nil { pkg/services/anonymous/anonimpl/impl.go:146 a.log.Debug("Failed to tag device for UI", "error", err) pkg/services/anonymous/anonimpl/impl.go:147 return err pkg/services/anonymous/anonimpl/impl.go:83 if _, ok := a.localCache.Get(key); ok { pkg/services/anonymous/anonimpl/impl.go:84 return nil pkg/services/anonymous/anonimpl/impl.go:85 } pkg/services/anonymous/anonimpl/impl.go:87 a.localCache.SetDefault(key, struct{}{}) pkg/services/anonymous/anonimpl/impl.go:93 if err := a.anonStore.CreateOrUpdateDevice(ctx, device); err != nil { pkg/services/anonymous/anonimpl/impl.go:94 return err ```
pkg/services/anonymous/anonimpl/impl.go:120
**Device limit skipped without the device header** `TagDevice` returns nil when there is no `X-Grafana-Device-Id` header, so `Authenticate` lets the request through unchecked. Any client that leaves out the header gets around `device_limit`. When a limit is set, decide what header-less requests should do: reject them, or fall back to an IP/UA key. ``` pkg/services/anonymous/anonimpl/client.go:44 if err := a.anonDeviceService.TagDevice(ctx, httpReqCopy, anonymous.AnonDeviceUI); err != nil { pkg/services/anonymous/anonimpl/client.go:45 if errors.Is(err, anonstore.ErrDeviceLimitReached) { pkg/services/anonymous/anonimpl/client.go:46 return nil, err pkg/services/anonymous/anonimpl/client.go:47 } pkg/services/anonymous/anonimpl/impl.go:119 deviceID := httpReq.Header.Get(deviceIDHeader) pkg/services/anonymous/anonimpl/impl.go:120 if deviceID == "" { pkg/services/anonymous/anonimpl/impl.go:121 return nil pkg/services/anonymous/anonimpl/impl.go:122 } ```
pkg/services/anonymous/anonimpl/client.go:44
**Anonymous requests now wait on device DB writes** `TagDevice` used to run in a background goroutine and now runs inline in `Authenticate`. Every uncached anonymous request waits on an upsert, plus a COUNT query when a limit is set, even with `device_limit` at 0. Keep the async tagging when no limit is set. ``` pkg/services/anonymous/anonimpl/client.go:44 if err := a.anonDeviceService.TagDevice(ctx, httpReqCopy, anonymous.AnonDeviceUI); err != nil { pkg/services/anonymous/anonimpl/client.go:45 if errors.Is(err, anonstore.ErrDeviceLimitReached) { pkg/services/anonymous/anonimpl/client.go:46 return nil, err pkg/services/anonymous/anonimpl/client.go:47 } pkg/services/anonymous/anonimpl/client.go:45 (base) go func() { pkg/services/anonymous/anonimpl/client.go:46 (base) defer func() { pkg/services/anonymous/anonimpl/client.go:47 (base) if err := recover(); err != nil { pkg/services/anonymous/anonimpl/client.go:48 (base) a.log.Warn("Tag anon session panic", "err", err) pkg/services/anonymous/anonimpl/client.go:49 (base) } pkg/services/anonymous/anonimpl/client.go:50 (base) }() ```
pkg/services/anonymous/anonimpl/anonstore/database.go:85
**Device update fails when a DB lock retries** `args` is reassigned inside the `WithDbSession` callback, and that callback reruns on database-locked retries. Each rerun puts the query at the front again, so the SQL string gets bound as a parameter. Build the full argument slice once, outside the callback. ``` pkg/services/anonymous/anonimpl/anonstore/database.go:84 args = append([]interface{}{query}, args...) pkg/services/anonymous/anonimpl/anonstore/database.go:85 result, err := dbSession.Exec(args...) pkg/services/anonymous/anonimpl/anonstore/database.go:86 if err != nil { pkg/services/sqlstore/session.go:86 func (ss *SQLStore) retryOnLocks(ctx context.Context, callback DBTransactionFunc, sess *DBSession, retry int) func() (retryer.RetrySignal, error) { pkg/services/sqlstore/session.go:87 return func() (retryer.RetrySignal, error) { pkg/services/sqlstore/session.go:88 retry++ pkg/services/sqlstore/session.go:90 err := callback(sess) pkg/services/sqlstore/session.go:92 ctxLogger := tsclogger.FromContext(ctx) pkg/services/sqlstore/session.go:94 var sqlError sqlite3.Error pkg/services/sqlstore/session.go:95 if errors.As(err, &sqlError) && (sqlError.Code == sqlite3.ErrLocked || sqlError.Code == sqlite3.ErrBusy) { ```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ off by one
d2 medium ✓ off by one
valid · matches d1 · impact medium
valid · matches d2 · impact medium
valid · impact low
The diff removed the background goroutine (which used context.Background with a timeout), so tagging now runs synchronously on the request context. That holds even when deviceLimit is 0, which adds DB latency to the request and lets cancellation abort the tagging. [grounded: diff] [consensus 3/3: valid=3]
valid · impact medium
The new device-limit check is only reached through TagDevice, and TagDevice returns nil when the client-supplied header is missing. A client can omit the header, still get an anonymous identity, and get past the limit this change adds. [grounded: tree pkg/services/anonymous/anonimpl/impl.go] [consensus 3/3: valid=3]
uncertain
wire.go still lists ProvideAnonDBStore, which now needs an int64. However, nothing resolved by wire consumes AnonStore any more (a grep shows no injected consumer). Wire normally only checks the dependencies it actually needs to resolve, so it is unclear whether generation really fails. Dead entries alone are not a behaviour defect. [uncertain: no evidence quoted] [consensus 2/4: uncertain=2, valid=1, invalid=1]
raw comments (5)
pkg/services/anonymous/anonimpl/anonstore/database.go:109
**Device limit check is racy** `CreateOrUpdateDevice` counts devices, then inserts in a separate statement with no lock or transaction. Concurrent requests from different new devices can all see count < limit and all insert, going over the limit. Do the count and insert atomically, e.g. in one transaction or a conditional INSERT ... SELECT. ``` pkg/services/anonymous/anonimpl/anonstore/database.go:108 // if device limit is reached, only update devices pkg/services/anonymous/anonimpl/anonstore/database.go:109 if s.deviceLimit > 0 { pkg/services/anonymous/anonimpl/anonstore/database.go:110 count, err := s.CountDevices(ctx, time.Now().UTC().Add(-anonymousDeviceExpiration), time.Now().UTC().Add(time.Minute)) pkg/services/anonymous/anonimpl/anonstore/database.go:111 if err != nil { ```
pkg/services/anonymous/anonimpl/impl.go:147
**Device limit bypassed after first rejection** `tagDeviceUI` caches the device before `CreateOrUpdateDevice` runs. When the limit rejects it, the cache entry stays, so the device's next requests return early with no error and get anonymous access. Set the cache entry only after `CreateOrUpdateDevice` succeeds, or delete it on error. ``` pkg/services/anonymous/anonimpl/impl.go:144 err = a.tagDeviceUI(ctx, httpReq, taggedDevice) pkg/services/anonymous/anonimpl/impl.go:145 if err != nil { pkg/services/anonymous/anonimpl/impl.go:146 a.log.Debug("Failed to tag device for UI", "error", err) pkg/services/anonymous/anonimpl/impl.go:147 return err ```
pkg/services/anonymous/anonimpl/client.go:44
**Anonymous requests now wait on device DB writes** Authenticate now calls TagDevice inline with the request context, even when device_limit is 0. So each device's first request in every 29-minute cache window waits on the DB upsert. If the request is cancelled, tagging fails. Keep tagging in the background when no limit is configured. ``` pkg/services/anonymous/anonimpl/client.go:44 if err := a.anonDeviceService.TagDevice(ctx, httpReqCopy, anonymous.AnonDeviceUI); err != nil { pkg/services/anonymous/anonimpl/client.go:45 if errors.Is(err, anonstore.ErrDeviceLimitReached) { pkg/services/anonymous/anonimpl/client.go:46 return nil, err pkg/services/anonymous/anonimpl/client.go:47 } ```
pkg/services/anonymous/anonimpl/impl.go:147
**Limit skipped when device id header is missing** `TagDevice` returns nil early when the `X-Grafana-Device-Id` header is empty or the IP can't be parsed. The client controls that header, so omitting it gets anonymous access past the limit. When a limit is set, reject requests that carry no usable device id. ``` pkg/services/anonymous/anonimpl/impl.go:144 err = a.tagDeviceUI(ctx, httpReq, taggedDevice) pkg/services/anonymous/anonimpl/impl.go:145 if err != nil { pkg/services/anonymous/anonimpl/impl.go:146 a.log.Debug("Failed to tag device for UI", "error", err) pkg/services/anonymous/anonimpl/impl.go:147 return err ```
pkg/server/wire.go:374
**Wire still provides AnonDBStore with changed signature** `ProvideAnonDBStore` now takes an `int64` deviceLimit, but wire.go still lists it as a provider. wire can't supply a bare int64, so wire generation fails. `ProvideAnonymousDeviceService` no longer takes an `AnonStore` either, so both wire.go entries are unused. Remove the two anonstore entries from wire.go. ``` pkg/services/anonymous/anonimpl/anonstore/database.go:52 func ProvideAnonDBStore(sqlStore db.DB, deviceLimit int64) *AnonDBStore { pkg/services/anonymous/anonimpl/anonstore/database.go:53 return &AnonDBStore{sqlStore: sqlStore, log: log.New("anonstore"), deviceLimit: deviceLimit} pkg/services/anonymous/anonimpl/anonstore/database.go:54 } pkg/services/anonymous/anonimpl/impl.go:36 func ProvideAnonymousDeviceService(usageStats usagestats.Service, authBroker authn.Service, ```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ off by one
d2 medium ✓ off by one
valid · matches d2 · impact medium
valid · matches d1 · impact medium
valid · impact low
With strictNullChecks, a class property initialized to `undefined` without an annotation is typed as `undefined`. Code that uses `config` (a GrafanaBootConfig) therefore can't treat the value as a number without a cast, even though the interface declares `number | undefined` and `merge` sets a number at runtime. This is a real type-contract gap with low impact. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
pkg/services/anonymous/anonimpl/impl.go:147
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Cached rejection bypasses limit** When a new device is rejected at the configured limit, `tagDeviceUI` has already cached its device ID. The error path does not remove that entry, so a later request with the same `X-Grafana-Device-Id` skips the database limit check and authenticates successfully for up to 29 minutes, bypassing the limit.
pkg/services/anonymous/anonimpl/anonstore/database.go:115
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Concurrent registrations exceed cap** The active-device count and the later upsert run in separate database sessions without a shared transaction or lock. Concurrent requests for distinct device IDs can both observe a count below the limit and then both insert, causing the configured cap to be exceeded.
packages/grafana-runtime/src/config.ts:97
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Property type excludes numbers** Initializing `anonymousDeviceLimit` without an explicit annotation makes the concrete `GrafanaBootConfig` property infer as `undefined`, even though constructor merging can assign a number at runtime. Consumers typed against this class cannot use the configured numeric value without a cast, so the property should match the `number | undefined` interface contract. ```suggestion anonymousDeviceLimit: number | undefined = undefined; ``` Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
PR-level
<h3>Greptile Summary</h3> The PR introduces a configurable active anonymous-device limit, exposes it through frontend settings, and makes anonymous authentication reject devices when that limit is reached. - Adds `auth.anonymous.device_limit` parsing and frontend configuration fields. - Counts devices active during the last 30 days and conditionally updates or inserts registrations. - Changes anonymous-device tagging from asynchronous best-effort work to synchronous authentication-path enforcement. - The current cache and count/write ordering leave two paths that can exceed or bypass the configured limit. <h3>Confidence Score: 3/5</h3> The PR is not safe to merge until retry caching and concurrent registration can no longer bypass the configured anonymous-device cap. A rejected device is cached before persistence and consequently succeeds on retry, while concurrent count-then-insert operations can independently pass the limit check and exceed the cap. **Files Needing Attention:** pkg/services/anonymous/anonimpl/impl.go, pkg/services/anonymous/anonimpl/anonstore/database.go, packages/grafana-runtime/src/config.ts <details><summary><h3>Important Files Changed</h3></summary> | Filename | Overview | |----------|----------| | pkg/services/anonymous/anonimpl/anonstore/database.go | Adds the device-limit count and conditional-update logic, but its non-atomic count/write sequence permits concurrent cap overruns. | | pkg/services/anonymous/anonimpl/impl.go | Constructs the limited store and propagates tagging failures, exposing a cache-on-failure path that bypasses enforcement on retry. | | pkg/services/anonymous/anonimpl/client.go | Makes device-limit errors reject anonymous authentication while continuing to log other tagging failures. | | pkg/setting/setting.go | Adds and parses the anonymous-device limit with zero representing no configured limit. | | pkg/api/dtos/frontend_settings.go | Adds the anonymous-device limit to the frontend settings DTO. | | pkg/api/frontendsettings.go | Populates the frontend device-limit setting from server configuration. | | packages/grafana-runtime/src/config.ts | Adds the boot-config property, but its inferred concrete type is narrower than the intended numeric-or-undefined contract. | </details> <details open><summary><h3>Flowchart</h3></summary> ```mermaid %%{init: {'theme': 'neutral'}}%% flowchart TD A[Anonymous request] --> B[Authenticate] B --> C[TagDevice] C --> D{Device ID cached?} D -->|Yes| E[Allow authentication] D -->|No| F[Cache device ID] F --> G[Count active devices] G -->|Below limit| H[Upsert device] G -->|At limit| I[Update existing active device] I -->|No matching row| J[Return device-limit error] J --> K[Reject first request] K -. cached retry .-> D ``` </details> <!-- greptile_other_comments_section --> <sub>Reviews (1): Last reviewed commit: ["Update packages/grafana-data/src/types/c..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/e994788aa2185051e9e2e000c067693c89ae9526) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284476)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✗ —
d2 medium ✓ off by one
valid · matches d2 · impact medium
invalid
Grafana's MySQL connection string sets clientFoundRows=true. With that flag, RowsAffected counts matched rows rather than changed rows. An unchanged update of an existing device therefore returns 1, not 0, so the claimed false rejection does not happen. [invalid: contradiction] [consensus 3/3: invalid=3]
valid · impact high
tagDeviceUI caches the device key before calling CreateOrUpdateDevice and never removes it when the write fails. Because the change now uses ErrDeviceLimitReached to reject authentication, later requests from the same device hit the cache, return nil and are allowed in. This is a real defect introduced by the change, and it largely defeats the new limit. [grounded: tree pkg/services/anonymous/anonimpl/impl.go] [consensus 3/3: valid=3]
raw comments (3)
pkg/services/anonymous/anonimpl/impl.go:147
[P1] Device limit is bypassed on the next request after a rejection The new limit enforcement relies on `TagDevice` returning `ErrDeviceLimitReached`, but `tagDeviceUI` calls `a.localCache.SetDefault(key, ...)` before it calls `CreateOrUpdateDevice`, and the cache entry stays even when the store rejects the device. So once the limit is reached, a new device is rejected on its first request, but every request it makes in the next ~29 minutes hits the cache, `tagDeviceUI` returns nil, and `Authenticate` treats it as a valid anonymous identity. A device over the limit only has to retry to get in. On error, the cache entry needs to be skipped or removed, at least for `ErrDeviceLimitReached`.
pkg/services/anonymous/anonimpl/anonstore/database.go:95
[P2] On MySQL, an unchanged update counts as "limit reached" `updateDevice` treats `rowsAffected == 0` as "this device doesn't exist yet". By default the MySQL driver reports changed rows, not matched rows, and `updated_at` is stored at one-second precision. If an existing device is re-tagged within the same second with the same IP and user agent, MySQL reports 0 rows affected. That can happen when Grafana runs on several instances, since each has its own local cache. In that case an already-registered device gets `ErrDeviceLimitReached` and its anonymous auth fails, even though it is within the limit. Checking whether the row exists, or counting matched rows instead of changed rows, would avoid rejecting known devices.
pkg/services/anonymous/anonimpl/impl.go:145
[P1] Rejected devices get cached, so the device limit only blocks their first request `TagDevice` now passes on the `ErrDeviceLimitReached` error from `tagDeviceUI`, and `Anonymous.Authenticate` uses that error to reject the request. But `tagDeviceUI` calls `a.localCache.SetDefault(key, ...)` before `CreateOrUpdateDevice` runs, and it never clears that entry when the write fails. So when a new device goes over `device_limit`, only its first request is rejected. For the next ~29 minutes (the local cache TTL), its requests hit the cache, `tagDeviceUI` returns nil, and anonymous access is allowed. Each time the cache entry expires, the same thing repeats: one request is rejected, then the device gets in again. This happens whenever `auth.anonymous.device_limit` › 0 and the limit has been reached, which makes the new limit mostly ineffective. Possible fixes: set the cache entry only after the write succeeds, or delete it when the error is `ErrDeviceLimitReached`.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ off by one
d2 medium ✓ off by one
valid · matches d2 · impact medium
valid · matches d1 · impact medium
valid · impact medium
tagDeviceUI caches the key before CreateOrUpdateDevice. Because of this change, ErrDeviceLimitReached now goes back to Authenticate and blocks the request. A later request from the same device within the cache TTL hits the cache, returns nil and gets authenticated, so the new limit is bypassed. The caching line itself is unchanged, but the new enforcement is what turns it into a bypass. [grounded: tree pkg/services/anonymous/anonimpl/impl.go] [consensus 3/3: valid=3]
raw comments (3)
pkg/services/anonymous/anonimpl/impl.go:78
[P1] Rejected device is cached before the store call, so the limit is bypassed on retry tagDeviceUI calls `a.localCache.SetDefault(key, ...)` before `CreateOrUpdateDevice`. When the store now returns `ErrDeviceLimitReached`, the key stays in the cache (29-minute TTL). The next request from the same device ID hits the cache, `tagDeviceUI` returns nil, and `Authenticate` lets the device through as anonymous. A rejected device is therefore blocked only once per cache window, which defeats the new limit whenever the limit is reached and the client retries or reloads. The cache entry should only be set after a successful store write, or removed on error.
pkg/services/anonymous/anonimpl/anonstore/database.go:105
[P3] Limit check and insert are not atomic, so concurrent new devices can exceed the limit `CountDevices` and the upsert run as separate statements with no transaction or lock. When many new devices arrive at once while the count is just under the limit, each request sees `count ‹ limit` and inserts, so the limit can be overshot. The overshoot is bounded by concurrency and is probably acceptable as a soft limit, but it makes the cap approximate.
pkg/services/anonymous/anonimpl/impl.go:92
[P2] Device limit is bypassed after the first rejection `tagDeviceUI` calls `a.localCache.SetDefault(key, ...)` before `CreateOrUpdateDevice`. When the device limit is reached and an unknown device is rejected with `ErrDeviceLimitReached`, the key stays in the cache. The cache TTL is 29 minutes. On the next request from that device, `localCache.Get` hits and `tagDeviceUI` returns nil. `Authenticate` then lets the request through as anonymous without the device being stored. This only matters when `device_limit` › 0 and the limit has been reached. An over-limit device is blocked once per cache window and then admitted (an untracked, uncounted device), which defeats the limit. The cache entry should only be set after a successful write, or removed when the write fails.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
DefectSeverityFoundGrade
d1 medium ✓ off by one
d2 medium ✓ off by one
valid · matches d1 · impact medium
valid · matches d2 · impact medium
valid · impact medium
The `[auth.anonymous]` section of conf/defaults.ini (lines 581-593) has no device_limit key. applyEnvVariableOverrides only goes through keys that already exist in the loaded INI. readAuthSettings reads the value with iniFile.Section, not SectionWithEnvOverrides. So GF_AUTH_ANONYMOUS_DEVICE_LIMIT is ignored and the limit stays 0 unless it is set in a config file. The new setting added by this change causes the problem. [grounded: tree pkg/setting/setting.go] [consensus 3/3: valid=3]
raw comments (5)
pkg/services/anonymous/anonimpl/anonstore/database.go:117
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 1\. Concurrent devices exceed the limit <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>CreateOrUpdateDevice</i></b> checks <b><i>CountDevices</i></b> separately from the later insert, without a transaction or lock spanning both operations. Concurrent requests with distinct device identifiers can all observe available capacity and then insert successfully, allowing the active-device count to exceed the configured limit. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description `CreateOrUpdateDevice` performs a separate count and insert, so concurrent requests can each observe spare capacity and collectively exceed the configured anonymous-device limit. ## Fix Focus Areas - pkg/services/anonymous/anonimpl/anonstore/database.go[105-155] ## Recommended Fix Serialize capacity checks and inserts across Grafana instances using a database transaction and a lockable shared row or equivalent atomic reservation mechanism. Recheck the active-device count while holding that lock, update known devices normally, and return `ErrDeviceLimitReached` before inserting a new device when no capacity remains. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
pkg/services/anonymous/anonimpl/impl.go:147
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 2\. Denied devices pass on retry <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>tagDeviceUI</i></b> caches a device before writing it, while <b><i>TagDevice</i></b> now propagates the write failure that denies authentication without removing that cache entry. After a new device receives <b><i>ErrDeviceLimitReached</i></b>, its next request hits the cache and skips the store entirely, allowing anonymous authentication until the cache entry expires. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description A device is cached before persistence, and the entry remains after a limit error, so the next authentication attempt bypasses limit enforcement. ## Fix Focus Areas - pkg/services/anonymous/anonimpl/impl.go[80-95] - pkg/services/anonymous/anonimpl/client.go[44-50] ## Recommended Fix Only populate the local cache after `CreateOrUpdateDevice` succeeds, or delete the device key on every persistence failure before returning the error. Add a test that retries the same over-limit device and verifies that every attempt still returns `ErrDeviceLimitReached`. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
pkg/setting/setting.go:1654
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> 3\. Environment limits stay disabled <code>🐞 Bug</code> <code>≡ Correctness</code> <pre> <b><i>readAuthSettings</i></b> parses <b><i>auth.anonymous.device_limit</i></b>, but the key is absent from the default anonymous-authentication section. Because environment overrides are generated only for keys already loaded from the INI files, setting <b><i>GF_AUTH_ANONYMOUS_DEVICE_LIMIT</i></b> against the standard configuration leaves the value at zero and enforcement disabled. </pre> <details> <summary><strong>Agent Prompt</strong></summary> ``` ## Issue description The new anonymous device-limit key is not declared in the default configuration, preventing the standard environment-variable override from being discovered and applied. ## Fix Focus Areas - conf/defaults.ini[580-593] - pkg/setting/setting.go[1648-1654] ## Recommended Fix Add `device_limit = 0` with an explanatory comment to the `[auth.anonymous]` section of `conf/defaults.ini`. Add a settings test proving that `GF_AUTH_ANONYMOUS_DEVICE_LIMIT` overrides the default and populates `Cfg.AnonymousDeviceLimit`. ``` <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> </details>
PR-level
<h3>PR Summary by Qodo</h3> Enforce configurable limits on anonymous devices <code>✨ Enhancement</code> <code>⚙️ Configuration changes</code> <code>🕐 20-40 Minutes</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <details> <summary>AI Description</summary> <dl> <dd> <br/> ><pre> >• Add a configurable 30-day active-device limit for anonymous access. >• Allow known devices while rejecting new anonymous devices after reaching the limit. >• Expose the limit in frontend settings and add database integration coverage. ></pre> </dd> </dl> </details> <details> <summary>Diagram</summary> <dl> <dd> <br/> ```mermaid sequenceDiagram actor Browser participant Settings as Frontend Settings participant Auth as Anonymous Auth participant Service as Device Service participant Store as Limited Store participant DB as Device Database Browser->>Settings: Load boot config Settings-->>Browser: Device limit Browser->>Auth: Anonymous request Auth->>Service: Tag device Service->>Store: Create or update Store->>DB: Count active devices DB-->>Store: Active count alt Below limit Store->>DB: Upsert device DB-->>Store: Saved Store-->>Service: Saved Service-->>Auth: Tagged Auth-->>Browser: Anonymous identity else At limit Store->>DB: Update known device alt Device found DB-->>Store: Updated Store-->>Service: Saved Service-->>Auth: Tagged Auth-->>Browser: Anonymous identity else Device missing DB-->>Store: No rows Store-->>Service: Limit error Service-->>Auth: Limit error Auth-->>Browser: Reject access end end ``` </dd> </dl> </details> <details> <summary>High-Level Assessment</summary> <dl> <dd> <br/> >The following are alternative approaches to this PR: <details> <summary><b>1. Atomic database admission</b></summary> <dl> <dd> - ➕ Enforces the configured limit under concurrent requests and multiple Grafana instances. - ➕ Avoids a race between counting active devices and inserting a new device. - ➖ Requires transaction or locking behavior tailored to supported database engines. - ➖ May increase contention on anonymous authentication during traffic spikes. </dd> </dl> </details> >**Recommendation:** Keep the configuration, frontend exposure, and synchronous error propagation, but enforce new-device admission atomically if the limit must be strict. The current count-then-write strategy is simpler but concurrent requests can observe the same count and exceed the configured limit; successful persistence should also precede local caching so rejected devices are not temporarily treated as tagged. </dd> </dl> </details> <details> <summary> Files changed (11) <code> +105 / -37 </code> </summary> <dl> <dd> <br/> <details> <summary>Enhancement (7) <code> +70 / -22 </code></summary> <dl> <dd> <details> <summary>config.ts<code>Add anonymous device limit to shared configuration</code> <code>+1/-0</code></summary> <br/> >Add anonymous device limit to shared configuration > ><pre> >• Extends GrafanaConfig with an optional numeric anonymous device limit for frontend consumers. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-50b1613fd37394879ad3a23adc33d4a538df9b752cd856a1d8e7cd2bb8b77b87'>packages/grafana-data/src/types/config.ts</a> </details> <details> <summary>config.ts<code>Initialize the runtime anonymous device limit</code> <code>+1/-0</code></summary> <br/> >Initialize the runtime anonymous device limit > ><pre> >• Adds the anonymous device limit field to GrafanaBootConfig with an undefined default before boot settings are applied. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-8e6d1dc8bffebb9fc6d982a51a284e963b36aefdd18a58451fff8abb47068db5'>packages/grafana-runtime/src/config.ts</a> </details> <details> <summary>frontend_settings.go<code>Expose device limit in the frontend settings DTO</code> <code>+1/-0</code></summary> <br/> >Expose device limit in the frontend settings DTO > ><pre> >• Adds anonymousDeviceLimit to the serialized frontend settings contract. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-73b194a7c8d0d6d20098f8c622bacfc3b99641eef999a23d36d92cf61f3af58b'>pkg/api/dtos/frontend_settings.go</a> </details> <details> <summary>frontendsettings.go<code>Populate the frontend anonymous device limit</code> <code>+1/-0</code></summary> <br/> >Populate the frontend anonymous device limit > ><pre> >• Copies the configured anonymous device limit into the frontend settings response. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-cea61b688b82f66d0b664d7a06957747172c3554730a80da1a8f7a13ed9b0f1a'>pkg/api/frontendsettings.go</a> </details> <details> <summary>database.go<code>Enforce the active anonymous device limit</code> <code>+53/-4</code></summary> <br/> >Enforce the active anonymous device limit > ><pre> >• Stores the configured limit, counts devices active within 30 days, and only updates known devices after capacity is reached. Returns a sentinel error when an unknown device cannot be admitted. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-7fbf7975d048a464d9e283b32a103eaf1d7e0c6f6cd37c1926c7d10553dacc0c'>pkg/services/anonymous/anonimpl/anonstore/database.go</a> </details> <details> <summary>client.go<code>Reject authentication when the device limit is reached</code> <code>+8/-15</code></summary> <br/> >Reject authentication when the device limit is reached > ><pre> >• Makes device tagging synchronous and propagates the device-limit sentinel error to authentication. Other tagging failures remain non-blocking and are logged. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-8b7b738288661f230305c7b8bb118ac2fdf04c5a4c804b89bdaf22b7b2e4ce7e'>pkg/services/anonymous/anonimpl/client.go</a> </details> <details> <summary>impl.go<code>Construct the limited store from service configuration</code> <code>+5/-3</code></summary> <br/> >Construct the limited store from service configuration > ><pre> >• Builds the anonymous database store with the configured limit and shares it with the device API. Device tagging now returns persistence errors to its caller. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-70030faa245250908d55db47258ce505d474db1559995683f8df1a951504236f'>pkg/services/anonymous/anonimpl/impl.go</a> </details> </dd> </dl> </details> <details> <summary>Refactor (1) <code> +2 / -4 </code></summary> <dl> <dd> <details> <summary>api.go<code>Clarify the anonymous device expiration constant</code> <code>+2/-4</code></summary> <br/> >Clarify the anonymous device expiration constant > ><pre> >• Renames the 30-day lookback constant to describe anonymous device expiration and uses it when listing active devices. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-69bcb0d0ef19ae43c01e5e6d1b7eabe2f2b5a3d504cac8fdb5db9718d774a995'>pkg/services/anonymous/anonimpl/api/api.go</a> </details> </dd> </dl> </details> <details> <summary>Tests (2) <code> +26 / -7 </code></summary> <dl> <dd> <details> <summary>database_test.go<code>Cover anonymous device limit enforcement</code> <code>+23/-2</code></summary> <br/> >Cover anonymous device limit enforcement > ><pre> >• Updates store construction for the new limit parameter and adds an integration test verifying that a second unknown device is rejected at capacity. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-5ab43aa733ff0010e3e3aa7e6764c4f0a8c46d11c298749f354f6ef43fc7ba00'>pkg/services/anonymous/anonimpl/anonstore/database_test.go</a> </details> <details> <summary>impl_test.go<code>Adapt device service integration tests to store wiring</code> <code>+3/-5</code></summary> <br/> >Adapt device service integration tests to store wiring > ><pre> >• Passes the database dependency directly into the service provider and inspects the service-owned anonymous store in assertions. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-90c452efdafa803f1ef288ba309bc1e192e54c1d184feb04de7ec16b9a3a8667'>pkg/services/anonymous/anonimpl/impl_test.go</a> </details> </dd> </dl> </details> <details> <summary>Other (1) <code> +7 / -4 </code></summary> <dl> <dd> <details> <summary>setting.go<code>Read the anonymous device limit setting</code> <code>+7/-4</code></summary> <br/> >Read the anonymous device limit setting > ><pre> >• Adds AnonymousDeviceLimit to server configuration and reads auth.anonymous.device_limit as an int64. A value of zero keeps the limit disabled. ></pre> > ><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-dc899ea32f268c53e94f76ae5ff45a239dde212d815e715fc3804ea4dfe87a75'>pkg/setting/setting.go</a> </details> </dd> </dl> </details> </dd> </dl> </details>
PR-level
<h3>Code Review by Qodo</h3> <code>🐞 Bugs (3)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <br/> <img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required"> <details> <summary> 1. Concurrent devices exceed the limit <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>CreateOrUpdateDevice</i></b> checks <b><i>CountDevices</i></b> separately from the later insert, without a transaction >or lock spanning both operations. Concurrent requests with distinct device identifiers can all >observe available capacity and then insert successfully, allowing the active-device count to exceed >the configured limit. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[pkg/services/anonymous/anonimpl/anonstore/database.go[R115-117]](https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-7fbf7975d048a464d9e283b32a103eaf1d7e0c6f6cd37c1926c7d10553dacc0cR115-R117)</code> > >```diff >+ if count >= s.deviceLimit { >+ return s.updateDevice(ctx, device) >+ } >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The active-device count and decision occur before the insert, while the insert runs through a later >independent database session. The schema only makes each device identifier unique and has no >constraint enforcing the aggregate count, so distinct concurrent inserts are not prevented. ></pre> > > <code>[pkg/services/anonymous/anonimpl/anonstore/database.go[105-117]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/anonymous/anonimpl/anonstore/database.go/#L105-L117)</code> > <code>[pkg/services/anonymous/anonimpl/anonstore/database.go[120-155]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/anonymous/anonimpl/anonstore/database.go/#L120-L155)</code> > <code>[pkg/services/anonymous/anonimpl/anonstore/database.go[158-165]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/anonymous/anonimpl/anonstore/database.go/#L158-L165)</code> > <code>[pkg/services/sqlstore/migrations/anonservice/migrations.go[16-19]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/sqlstore/migrations/anonservice/migrations.go/#L16-L19)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >`CreateOrUpdateDevice` performs a separate count and insert, so concurrent requests can each observe spare capacity and collectively exceed the configured anonymous-device limit. > >## Fix Focus Areas >- pkg/services/anonymous/anonimpl/anonstore/database.go[105-155] > >## Recommended Fix >Serialize capacity checks and inserts across Grafana instances using a database transaction and a lockable shared row or equivalent atomic reservation mechanism. Recheck the active-device count while holding that lock, update known devices normally, and return `ErrDeviceLimitReached` before inserting a new device when no capacity remains. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 2. Denied devices pass on retry <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>tagDeviceUI</i></b> caches a device before writing it, while <b><i>TagDevice</i></b> now propagates the write failure >that denies authentication without removing that cache entry. After a new device receives ><b><i>ErrDeviceLimitReached</i></b>, its next request hits the cache and skips the store entirely, allowing >anonymous authentication until the cache entry expires. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[pkg/services/anonymous/anonimpl/impl.go[R144-147]](https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-70030faa245250908d55db47258ce505d474db1559995683f8df1a951504236fR144-R147)</code> > >```diff > err = a.tagDeviceUI(ctx, httpReq, taggedDevice) > if err != nil { > a.log.Debug("Failed to tag device for UI", "error", err) >+ return err >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The cache entry is set before <b><i>CreateOrUpdateDevice</i></b>, and the error path returns without deleting >it. At capacity, an unknown device produces <b><i>ErrDeviceLimitReached</i></b>, but later calls return >successfully from the cache check before reaching the database or propagating the error. ></pre> > > <code>[pkg/services/anonymous/anonimpl/impl.go[80-95]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/anonymous/anonimpl/impl.go/#L80-L95)</code> > <code>[pkg/services/anonymous/anonimpl/impl.go[136-150]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/anonymous/anonimpl/impl.go/#L136-L150)</code> > <code>[pkg/services/anonymous/anonimpl/anonstore/database.go[72-102]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/anonymous/anonimpl/anonstore/database.go/#L72-L102)</code> > <code>[pkg/services/anonymous/anonimpl/anonstore/database.go[105-117]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/anonymous/anonimpl/anonstore/database.go/#L105-L117)</code> > <code>[pkg/services/anonymous/anonimpl/client.go[44-50]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/anonymous/anonimpl/client.go/#L44-L50)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >A device is cached before persistence, and the entry remains after a limit error, so the next authentication attempt bypasses limit enforcement. > >## Fix Focus Areas >- pkg/services/anonymous/anonimpl/impl.go[80-95] >- pkg/services/anonymous/anonimpl/client.go[44-50] > >## Recommended Fix >Only populate the local cache after `CreateOrUpdateDevice` succeeds, or delete the device key on every persistence failure before returning the error. Add a test that retries the same over-limit device and verifies that every attempt still returns `ErrDeviceLimitReached`. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <details> <summary> 3. Environment limits stay disabled <code>🐞 Bug</code> <code>≡ Correctness</code></summary> <br/> > <details open> ><summary>Description</summary> ><br/> > ><pre> ><b><i>readAuthSettings</i></b> parses <b><i>auth.anonymous.device_limit</i></b>, but the key is absent from the default >anonymous-authentication section. Because environment overrides are generated only for keys already >loaded from the INI files, setting <b><i>GF_AUTH_ANONYMOUS_DEVICE_LIMIT</i></b> against the standard >configuration leaves the value at zero and enforcement disabled. ></pre> ></details> > <details> ><summary>Code</summary> ><br/> > ><code>[pkg/setting/setting.go[1654]](https://github.com/drape-io/crbench-qodo-2026-09/pull/41/files#diff-dc899ea32f268c53e94f76ae5ff45a239dde212d815e715fc3804ea4dfe87a75R1654-R1654)</code> > >```diff >+ cfg.AnonymousDeviceLimit = anonSection.Key("device_limit").MustInt64(0) >``` ></details> > <details> ><summary>Evidence</summary> ><br/> > ><pre> >The parser defaults the new key to zero, while <b><i>conf/defaults.ini</i></b> does not define it. ><b><i>applyEnvVariableOverrides</i></b> iterates existing sections and keys rather than arbitrary environment >variables, so the absent key prevents the normal environment override from reaching the store. ></pre> > > <code>[pkg/setting/setting.go[1648-1654]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/setting/setting.go/#L1648-L1654)</code> > <code>[conf/defaults.ini[580-593]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/conf/defaults.ini/#L580-L593)</code> > <code>[pkg/setting/setting.go[686-700]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/setting/setting.go/#L686-L700)</code> > <code>[pkg/services/anonymous/anonimpl/impl.go[36-44]](https://github.com/drape-io/crbench-qodo-2026-09/blob/fc520ab7242f5fe1a6304107f13f08fd2e1d0874/pkg/services/anonymous/anonimpl/impl.go/#L36-L44)</code> ></details> > <details> ><summary>Agent prompt</summary> ><br/> > >``` >The issue below was found during a code review. Follow the provided context and guidance below and implement a solution > >## Issue description >The new anonymous device-limit key is not declared in the default configuration, preventing the standard environment-variable override from being discovered and applied. > >## Fix Focus Areas >- conf/defaults.ini[580-593] >- pkg/setting/setting.go[1648-1654] > >## Recommended Fix >Add `device_limit = 0` with an explanatory comment to the `[auth.anonymous]` section of `conf/defaults.ini`. Add a settings test proving that `GF_AUTH_ANONYMOUS_DEVICE_LIMIT` overrides the default and populates `Cfg.AnonymousDeviceLimit`. >``` > <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code> ></details> <hr/> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-context:start --> <details><summary><strong>Context sources</strong></summary> <div>Review mode: <code>⚖️ Balanced</code>: This changes anonymous-device enforcement across configuration, frontend contracts, persistence, authentication, and service wiring, creating meaningful behavioral and concurrency/limit-handling risk, but not enough independent logic for extended review.</div> <!-- qodo-context:end --> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:start --> <details> <summary><strong>Tip of the day</strong></summary> <br/> <pre>💡 Did you know, you can reply &#x27;qodo&#x27; on any finding to push back, ask questions, or dig deeper</pre> <a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a> </details> <img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider"> <!-- qodo-daily-tip:end --> <!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/fc520ab7242f5fe1a6304107f13f08fd2e1d0874 --> <a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>