lhotari commented on code in PR #20338:
URL: https://github.com/apache/pulsar/pull/20338#discussion_r1195959936


##########
pulsar-broker-auth-oidc/src/main/java/org/apache/pulsar/broker/authentication/oidc/JwksCache.java:
##########
@@ -87,7 +94,37 @@ CompletableFuture<Jwk> getJwk(String jwksUri, String keyId) {
             
incrementFailureMetric(AuthenticationExceptionCode.ERROR_RETRIEVING_PUBLIC_KEY);
             return CompletableFuture.failedFuture(new 
IllegalArgumentException("jwksUri must not be null."));
         }
-        return cache.get(Optional.of(jwksUri)).thenApply(jwks -> 
getJwkForKID(jwks, keyId));
+        return getJwkAndMaybeReload(Optional.of(jwksUri), keyId, false);
+    }
+
+    /**
+     * Retrieve the JWK for the given key ID from the given JWKS URI. If the 
key ID is not found, and failOnMissingKeyId
+     * is false, then the JWK will be reloaded from the JWKS URI and the key 
ID will be searched for again.
+     */
+    private CompletableFuture<Jwk> getJwkAndMaybeReload(Optional<String> 
maybeJwksUri,
+                                                        String keyId,
+                                                        boolean 
failOnMissingKeyId) {
+        return cache
+                .get(maybeJwksUri)
+                .thenCompose(jwks -> {
+                    try {
+                        return 
CompletableFuture.completedFuture(getJwkForKID(maybeJwksUri, jwks, keyId));
+                    } catch (IllegalArgumentException e) {
+                        if (failOnMissingKeyId) {
+                            throw e;
+                        } else {
+                            Long lastRefresh = 
jwksLastRefreshTime.get(maybeJwksUri);
+                            if (lastRefresh == null || System.nanoTime() - 
lastRefresh > keyIdCacheMissRefreshNanos) {
+                                // In this case, the key ID was not found, but 
we haven't refreshed the JWKS in a while,
+                                // so it is possible the key ID was added. 
Refresh the JWKS and try again.
+                                cache.synchronous().invalidate(maybeJwksUri);
+                            }
+                            // There is a small race condition where the JWKS 
could be refreshed by another thread,
+                            // so we retry getting the JWK, even though we 
might not have invalidated the cache.
+                            return getJwkAndMaybeReload(maybeJwksUri, keyId, 
true);

Review Comment:
   Would it be useful to limit deep recursion?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to