Skip to content

Commit 2da57fd

Browse files
committed
using sync maps for limiters in middlewares - resolves panic
1 parent c905cac commit 2da57fd

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

cmd/devguard/api/api.go

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"os"
2121
"sort"
2222
"strings"
23+
"sync"
2324
"time"
2425

2526
"github.com/prometheus/client_golang/prometheus/promhttp"
@@ -254,14 +255,16 @@ func neededScope(neededScopes []string) core.MiddlewareFunc {
254255
}
255256

256257
func externalEntityProviderOrgSyncMiddleware(externalEntityProviderService core.ExternalEntityProviderService) core.MiddlewareFunc {
257-
limiter := map[string]time.Time{}
258+
limiter := &sync.Map{}
258259
return func(next echo.HandlerFunc) echo.HandlerFunc {
259260
return func(ctx core.Context) error {
260261

261262
key := core.GetSession(ctx).GetUserID()
262-
if _, ok := limiter[key]; !ok || time.Now().After(limiter[key]) {
263+
now := time.Now()
264+
265+
if value, ok := limiter.Load(key); !ok || now.After(value.(time.Time)) {
263266
slog.Info("syncing external entity provider orgs", "userID", key)
264-
limiter[key] = time.Now().Add(15 * time.Minute)
267+
limiter.Store(key, now.Add(15*time.Minute))
265268
// Create a goroutine-safe context to avoid using the request context
266269
safeCtx := core.GoroutineSafeContext(ctx)
267270
go func() {
@@ -276,17 +279,20 @@ func externalEntityProviderOrgSyncMiddleware(externalEntityProviderService core.
276279
}
277280

278281
func externalEntityProviderRefreshMiddleware(externalEntityProviderService core.ExternalEntityProviderService) core.MiddlewareFunc {
279-
limiter := map[string]time.Time{}
282+
limiter := &sync.Map{}
280283

281284
return func(next echo.HandlerFunc) echo.HandlerFunc {
282285
// get the current org
283286
return func(ctx core.Context) error {
284287
org := core.GetOrg(ctx)
285288

286289
if org.IsExternalEntity() {
287-
// check if we are allowed to refresh the external entity provider projects
288-
if time.Now().After(limiter[org.GetID().String()+"/"+core.GetSession(ctx).GetUserID()]) {
289-
limiter[org.GetID().String()+"/"+core.GetSession(ctx).GetUserID()] = time.Now().Add(15 * time.Minute)
290+
key := org.GetID().String() + "/" + core.GetSession(ctx).GetUserID()
291+
now := time.Now()
292+
293+
// Check if we are allowed to refresh the external entity provider projects
294+
if value, ok := limiter.Load(key); !ok || now.After(value.(time.Time)) {
295+
limiter.Store(key, now.Add(15*time.Minute))
290296

291297
// Create a goroutine-safe context and capture the values we need
292298
safeCtx := core.GoroutineSafeContext(ctx)

0 commit comments

Comments
 (0)