diff --git a/jwk/helper.go b/jwk/helper.go index 50f3a28b2d..78ce906cd8 100644 --- a/jwk/helper.go +++ b/jwk/helper.go @@ -44,13 +44,17 @@ 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() - keys, err := m.GetKeySet(ctx, set) + if err == nil && keys != nil && len(keys.Keys) > 0 { + return FindPrivateKey(keys) + } + 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() keys, err = m.GenerateAndPersistKeySet(ctx, set, kid, alg, "sig") + getLock(set).Unlock() + if err != nil { return nil, err } @@ -64,7 +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() keys, err = m.GenerateAndPersistKeySet(ctx, set, kid, alg, "sig") + getLock(set).Unlock() if err != nil { return nil, err }