IDForwarding: Use single flight for SignIdentity (#76530)

* IDForwarding: Use single flight for SignIdentity

* Update cache inside single flight call
This commit is contained in:
Karl Persson
2023-10-13 14:32:53 +02:00
committed by GitHub
parent 30cb720da5
commit e2ba399e30

View File

@@ -6,6 +6,9 @@ import (
"time"
"github.com/go-jose/go-jose/v3/jwt"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/sync/singleflight"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/remotecache"
"github.com/grafana/grafana/pkg/services/auth"
@@ -13,7 +16,6 @@ import (
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/setting"
"github.com/prometheus/client_golang/prometheus"
)
const (
@@ -28,7 +30,7 @@ func ProvideService(
cfg *setting.Cfg, signer auth.IDSigner, cache remotecache.CacheStorage,
features featuremgmt.FeatureToggles, authnService authn.Service, reg prometheus.Registerer,
) *Service {
s := &Service{cfg, log.New("id-service"), signer, cache, newMetrics(reg)}
s := &Service{cfg: cfg, logger: log.New("id-service"), signer: signer, cache: cache, metrics: newMetrics(reg)}
if features.IsEnabled(featuremgmt.FlagIdForwarding) {
authnService.RegisterPostAuthHook(s.hook, 140)
@@ -42,6 +44,7 @@ type Service struct {
logger log.Logger
signer auth.IDSigner
cache remotecache.CacheStorage
si singleflight.Group
metrics *metrics
}
@@ -50,9 +53,11 @@ func (s *Service) SignIdentity(ctx context.Context, id identity.Requester) (stri
s.metrics.tokenSigningDurationHistogram.Observe(time.Since(t).Seconds())
}(time.Now())
cacheKey := prefixCacheKey(id.GetCacheKey())
result, err, _ := s.si.Do(cacheKey, func() (interface{}, error) {
namespace, identifier := id.GetNamespacedID()
cacheKey := prefixCacheKey(id.GetCacheKey())
cachedToken, err := s.cache.Get(ctx, cacheKey)
if err == nil {
s.metrics.tokenSigningFromCacheCounter.Inc()
@@ -84,6 +89,13 @@ func (s *Service) SignIdentity(ctx context.Context, id identity.Requester) (stri
}
return token, nil
})
if err != nil {
return "", err
}
return result.(string), nil
}
func (s *Service) hook(ctx context.Context, identity *authn.Identity, _ *authn.Request) error {