From c0f89011973ee980d33184806bc2688d6f815934 Mon Sep 17 00:00:00 2001 From: "Adam T. Williams" Date: Mon, 28 Oct 2024 14:48:13 -0600 Subject: [PATCH] refactor(jwk): aquire read lock unless generating --- jwk/helper.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/jwk/helper.go b/jwk/helper.go index 50f3a28b2d2..600edebd4f0 100644 --- a/jwk/helper.go +++ b/jwk/helper.go @@ -44,12 +44,16 @@ func EnsureAsymmetricKeypairExists(ctx context.Context, r InternalRegistry, alg, } func GetOrGenerateKeys(ctx context.Context, r InternalRegistry, m Manager, set, kid, alg string) (private *jose.JSONWebKey, err error) { - getLock(set).Lock() - defer getLock(set).Unlock() - + getLock(set).RLock() keys, err := m.GetKeySet(ctx, set) + getLock(set).RUnlock() + if errors.Is(err, x.ErrNotFound) || keys != nil && len(keys.Keys) == 0 { r.Logger().Warnf("JSON Web Key Set \"%s\" does not exist yet, generating new key pair...", set) + + getLock(set).Lock() + defer getLock(set).Unlock() + keys, err = m.GenerateAndPersistKeySet(ctx, set, kid, alg, "sig") if err != nil { return nil, err @@ -64,6 +68,9 @@ func GetOrGenerateKeys(ctx context.Context, r InternalRegistry, m Manager, set, } else { r.Logger().WithField("jwks", set).Warnf("JSON Web Key not found in JSON Web Key Set %s, generating new key pair...", set) + getLock(set).Lock() + defer getLock(set).Unlock() + keys, err = m.GenerateAndPersistKeySet(ctx, set, kid, alg, "sig") if err != nil { return nil, err