IDToken: cache invalidation (#100592)

* Make org role part of id token cache key. This way we will always sign a new token when it changes

* Remove calls to remove id token
This commit is contained in:
Karl Persson
2025-02-13 14:10:58 +01:00
committed by GitHub
parent a69fac6e16
commit be60ef0500
6 changed files with 60 additions and 72 deletions
+4 -4
View File
@@ -63,7 +63,7 @@ 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())
cacheKey := getCacheKey(id)
type resultType struct {
token string
@@ -140,7 +140,7 @@ func (s *Service) SignIdentity(ctx context.Context, id identity.Requester) (stri
}
func (s *Service) RemoveIDToken(ctx context.Context, id identity.Requester) error {
return s.cache.Delete(ctx, prefixCacheKey(id.GetCacheKey()))
return s.cache.Delete(ctx, getCacheKey(id))
}
func (s *Service) hook(ctx context.Context, identity *authn.Identity, _ *authn.Request) error {
@@ -181,8 +181,8 @@ func getAudience(orgID int64) jwt.Audience {
return jwt.Audience{fmt.Sprintf("org:%d", orgID)}
}
func prefixCacheKey(key string) string {
return fmt.Sprintf("%s-%s", cachePrefix, key)
func getCacheKey(ident identity.Requester) string {
return cachePrefix + ident.GetCacheKey() + string(ident.GetOrgRole())
}
func shouldLogErr(err error) bool {
+31
View File
@@ -16,6 +16,7 @@ import (
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/authn/authntest"
"github.com/grafana/grafana/pkg/services/login"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/setting"
)
@@ -101,4 +102,34 @@ func TestService_SignIdentity(t *testing.T) {
assert.Equal(t, claims.TypeUser, gotClaims.Rest.Type)
assert.Equal(t, "edpu3nnt61se8e", gotClaims.Rest.Identifier)
})
t.Run("should sign new token if org role has changed", func(t *testing.T) {
s := ProvideService(
setting.NewCfg(), signer, remotecache.NewFakeCacheStorage(),
&authntest.FakeService{}, nil,
)
ident := &authn.Identity{
ID: "1",
Type: claims.TypeUser,
AuthenticatedBy: login.AzureADAuthModule,
Login: "U1",
UID: "edpu3nnt61se8e",
OrgID: 1,
OrgRoles: map[int64]org.RoleType{1: org.RoleAdmin},
}
first, _, err := s.SignIdentity(context.Background(), ident)
require.NoError(t, err)
second, _, err := s.SignIdentity(context.Background(), ident)
require.NoError(t, err)
assert.Equal(t, first, second)
ident.OrgRoles[1] = org.RoleEditor
third, _, err := s.SignIdentity(context.Background(), ident)
require.NoError(t, err)
assert.NotEqual(t, first, third)
})
}