[java-oidc-common] branch main updated: JCOMOIDC-199 - Add negative cache to DynamicMetadataCache

Codeberg noreply at shibboleth.net
Fri Nov 27 11:11:16 UTC 2026


This is an automated email from the git hooks/post-receive script.

codeberg pushed a commit to branch main
in repository java-oidc-common.

View the commit online:
https://codeberg.org/Shibboleth/java-oidc-common/commit/d820a469c1b3ba335d089019daac02226d70dc34

The following commit(s) were added to refs/heads/main by this push:
     new d820a469 JCOMOIDC-199 - Add negative cache to DynamicMetadataCache
d820a469 is described below

commit d820a469c1b3ba335d089019daac02226d70dc34
Author: Phil Smart <philip.smart at jisc.ac.uk>
AuthorDate: Fri Nov 27 11:11:03 2026 +0000

    JCOMOIDC-199 - Add negative cache to DynamicMetadataCache
    
     - Added a negative cache to the management object
     - Integrated the negative cache into the DynamicMetadataCache for
    failed lookups
    - The property is exposed in the cache builder spec, so it can be set
    when the cache is initialised. The default is 1 minute.
     - extra tests to exploit the negative lookup path.
    
    https://shibboleth.atlassian.net/browse/JCOMOIDC-199
---
 .../oidc/metadata/MetadataManagementData.java      |  40 ++++-
 .../metadata/cache/impl/AbstractMetadataCache.java |  36 ++++
 .../metadata/cache/impl/DynamicMetadataCache.java  |  59 +++++--
 .../impl/DynamicMetadataCacheBuilderSpec.java      |  33 ++++
 .../metadata/cache/impl/MetadataCacheBuilder.java  |   1 +
 .../cache/impl/DynamicMetadataCacheTest.java       | 196 +++++++++++++++++++++
 6 files changed, 343 insertions(+), 22 deletions(-)

diff --git a/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/MetadataManagementData.java b/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/MetadataManagementData.java
index 9631de8b..fe11d193 100644
--- a/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/MetadataManagementData.java
+++ b/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/MetadataManagementData.java
@@ -14,6 +14,7 @@
 
 package net.shibboleth.oidc.metadata;
 
+import java.time.Duration;
 import java.time.Instant;
 import java.util.concurrent.locks.StampedLock;
 
@@ -28,9 +29,6 @@ import net.shibboleth.shared.logic.Constraint;
  * @param <MetadataIdentifier> the key to the stored object. 
  * 
  */
-//TODO removed negative lookup cache.
-//TODO guard this class?
-//TODO change to a generic ObjectManagmentData type - if we want to broaden beyond metadata.
 public class MetadataManagementData<MetadataIdentifier> {
     
     /** The identifier of the entity managed by this instance. */
@@ -51,6 +49,9 @@ public class MetadataManagementData<MetadataIdentifier> {
     /** Read-write stamped lock which governs access to the metadata's backing store data. */
     @Nonnull private final StampedLock stmpLock;
     
+    /** The time at which the negative lookup cache flag expires, if set. */
+    @Nullable private Instant negativeLookupCacheExpiration;
+    
     /** Constructor. 
      * 
      * @param identifier the entity ID managed by this instance
@@ -149,5 +150,38 @@ public class MetadataManagementData<MetadataIdentifier> {
     @Nonnull public StampedLock getStampLock() {
         return stmpLock;
     }
+    
+    /**
+     * Determine whether the negative lookup cache for the entity is in effect.
+     * 
+     * @return true if active, false otherwise
+     * 
+     * @since 3.4.0
+     */
+    public synchronized boolean isNegativeLookupCacheActive() {
+        return negativeLookupCacheExpiration != null && Instant.now().isBefore(negativeLookupCacheExpiration);
+    }
+    
+    /**
+     * Initialize the negative lookup cache for the entity.
+     * 
+     * @return the time before which no further lookups for the entity will be performed
+     * 
+     * @since 3.4.0
+     */
+    @Nonnull public synchronized Instant initNegativeLookupCache(final Duration negativeCacheLookupDuration) {
+        negativeLookupCacheExpiration = Instant.now().plus(negativeCacheLookupDuration);
+        assert negativeLookupCacheExpiration != null;
+        return negativeLookupCacheExpiration;
+    }
+    
+    /**
+     * Clear out the negative lookup cache.
+     * 
+     * @since 3.4.0
+     */
+    public synchronized void clearNegativeLookupCache() {
+        negativeLookupCacheExpiration = null;
+    }
 
 }
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/AbstractMetadataCache.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/AbstractMetadataCache.java
index cbb82dbe..97995ab0 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/AbstractMetadataCache.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/AbstractMetadataCache.java
@@ -14,6 +14,7 @@
 
 package net.shibboleth.oidc.metadata.cache.impl;
 
+import java.time.Duration;
 import java.time.Instant;
 import java.util.ArrayList;
 import java.util.Iterator;
@@ -103,6 +104,9 @@ public abstract class AbstractMetadataCache<IdentifierType, MetadataType>
     /** Whether we created our own schedular during object construction. */
     private boolean createOwnSchedular;
     
+    /** Negative lookup cache duration. */
+    @Nonnull private Duration negativeLookupCacheDuration;
+    
     /** 
      * Package private constructor. For safe-construction through the factory only.
      * 
@@ -131,6 +135,7 @@ public abstract class AbstractMetadataCache<IdentifierType, MetadataType>
         } else {
             createOwnSchedular = true;
         }
+        negativeLookupCacheDuration = Duration.ofMinutes(1);
         
     }
     
@@ -316,6 +321,37 @@ public abstract class AbstractMetadataCache<IdentifierType, MetadataType>
         return refreshDelayFactor;
     }
     
+    /**
+     *  Get the negative lookup cache duration for metadata.
+     *  
+     *  <p>Defaults to: 10 minutes.</p>
+     *  
+     * @return the negative lookup cache duration
+     * 
+     * @since 3.4.0
+     */
+    @Nonnull public Duration getNegativeLookupCacheDuration() {
+        return negativeLookupCacheDuration;
+    }
+
+    /**
+     *  Set the negative lookup cache duration for metadata.
+     *  
+     *  <p>Defaults to: 1 minute.</p>
+     *  
+     * @param duration the negative lookup cache duration
+     * 
+     * @since 3.4.0
+     */
+    public void setNegativeLookupCacheDuration(@Nonnull final Duration duration) {
+        checkSetterPreconditions();
+
+        Constraint.isNotNull(duration, "Duration cannot be null");
+        Constraint.isFalse(duration.isNegative(), "Duration cannot be negative");
+        
+        negativeLookupCacheDuration = duration;
+    }
+    
     /**
      * Get list of descriptors matching the identifier.
      * 
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCache.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCache.java
index 104e71d5..944aec4c 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCache.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCache.java
@@ -157,7 +157,7 @@ public class DynamicMetadataCache<IdentifierType, MetadataType>
             final MetadataManagementData<IdentifierType> mgmt = new MetadataManagementData<>(id);
             mgmt.setRefreshTriggerTime(Constraint.isNotNull(now.plus(maxCacheDuration),
                     "Refresh Trigger cannot be null"));
-            mgmt.setExpirationTime(Constraint.isNotNull(now.plus(maxCacheDuration),"Refresh Trigger cannot be null"));
+            mgmt.setExpirationTime(Constraint.isNotNull(now.plus(maxCacheDuration),"Expiration time cannot be null"));
             return mgmt;
         };
         
@@ -421,9 +421,15 @@ public class DynamicMetadataCache<IdentifierType, MetadataType>
                     allMetadata = read(mgmtData, identifier);
                 }
                 if (allMetadata.isEmpty()) {
-                    log.debug("Metadata for '{}' does not exist, is no longer valid, or is stale, "
-                            + "attempting to fetch it", identifier);
-                    fetch(mgmtData, identifier, criteria);
+                    // This is a fail-fast check of the negative cache, the one inside fetch is under a lock
+                    if (!mgmtData.isNegativeLookupCacheActive()) {
+                        log.debug("{} Metadata for '{}' does not exist, is no longer valid, or is stale, "
+                                + "attempting to fetch it",getLogPrefix(), identifier);
+                        fetch(mgmtData, identifier, criteria);                        
+                    } else {
+                        log.debug("{} Negative lookup cache is active for '{}', skipping fetch",
+                                getLogPrefix(), identifier);
+                    }
                     return read(mgmtData, identifier);
                 } else {
                     log.debug("Metadata for '{}' found in cache", identifier);
@@ -496,7 +502,11 @@ public class DynamicMetadataCache<IdentifierType, MetadataType>
         final StampedLock sl = mgmtData.getStampLock();
         final long stamp = sl.writeLock();
         
-        try {            
+        try {
+            // Recheck negative cache under the write lock
+            if (mgmtData.isNegativeLookupCacheActive()) {
+                return;
+            }
             if (!shouldAttemptRefresh(mgmtData)){
                 // re-check another thread has not acquired this lock before hand - and therefore obtained
                 // the metadata.
@@ -518,10 +528,19 @@ public class DynamicMetadataCache<IdentifierType, MetadataType>
                 MetricsSupport.stopTimer(contextFetchFromSource);
             }
             
-            if (resolvedMetadata != null) {
-                storeNewMetadata(mgmtData, resolvedMetadata, identifier);
+            if (resolvedMetadata != null) {                
+                final boolean stored = storeNewMetadata(mgmtData, resolvedMetadata, identifier);
+                if (stored) {
+                    mgmtData.clearNegativeLookupCache();
+                } else {
+                    mgmtData.initNegativeLookupCache(getNegativeLookupCacheDuration());
+                    log.debug("{} Metadata for '{}' could not be stored",
+                            getLogPrefix(), identifier);
+                }
             } else {
-                log.warn("{} Metadata for '{}' could not be resolved from source", getLogPrefix(), identifier);
+                // Update the negative cache to back off subsequent fetch attempts.
+                mgmtData.initNegativeLookupCache(getNegativeLookupCacheDuration());
+                log.debug("{} Metadata for '{}' could not be resolved from source", getLogPrefix(), identifier);
             }
             
         } finally {
@@ -541,7 +560,7 @@ public class DynamicMetadataCache<IdentifierType, MetadataType>
      * @param metadata the new metadata to process.
      * @param expectedIdentifier the identifier expected on the new metadata.
      */
-    private void storeNewMetadata(@Nonnull final MetadataManagementData<IdentifierType> mgmtData,
+    private boolean storeNewMetadata(@Nonnull final MetadataManagementData<IdentifierType> mgmtData,
             @Nonnull final MetadataType metadata,
             @Nonnull final IdentifierType expectedIdentifier) {
         checkComponentActive();
@@ -550,21 +569,21 @@ public class DynamicMetadataCache<IdentifierType, MetadataType>
         
         if (filteredMetadata == null) {
             log.warn("{} Filtered metadata is null, no further processing performed", getLogPrefix());
-            return;
+            return false;
         }
         
         final IdentifierType extractedIdentifier = getIdentifierExtractionStrategy().apply(filteredMetadata);
         
         if (extractedIdentifier == null) {
             log.warn("{} Metadata identifier could not be extracted, no further processing performed", getLogPrefix());
-            return;
+            return false;
         }
         
         // equality method of the identifier is required to be implemented correctly.
         if (!Objects.equals(expectedIdentifier, extractedIdentifier)) {
-            log.warn("{} New metadata's identifer '{}' does not match expected identifier '{}', will not process", 
+            log.warn("{} New metadata's identifier '{}' does not match expected identifier '{}', will not process", 
                     getLogPrefix(), extractedIdentifier, expectedIdentifier); 
-            return;
+            return false;
         }                   
         
         log.debug("{} Resolved metadata with identifier '{}'",getLogPrefix(), extractedIdentifier);
@@ -585,11 +604,13 @@ public class DynamicMetadataCache<IdentifierType, MetadataType>
         log.debug("{} Computed metadata '{}' expiration time: {}", getLogPrefix(), 
                 extractedIdentifier, mgmtData.getExpirationTime());
         
-        mgmtData.setRefreshTriggerTime(computeRefreshTriggerTime(mgmtData.getExpirationTime(), now));
+        mgmtData.setRefreshTriggerTime(computeRefreshTriggerTime(mgmtData.getExpirationTime(), now));        
+        
         log.debug("{} Computed metadata '{}' refresh trigger time: {}", getLogPrefix(), 
                 extractedIdentifier, mgmtData.getRefreshTriggerTime());
         
-        log.debug("{} Successfully loaded new Metadata with identifer '{}'", getLogPrefix(), extractedIdentifier);   
+        log.debug("{} Successfully loaded new Metadata with identifier '{}'", getLogPrefix(), extractedIdentifier);
+        return true;
     }
     
     /**
@@ -636,9 +657,9 @@ public class DynamicMetadataCache<IdentifierType, MetadataType>
             refreshDelay = minCacheDuration.toMillis();
         }
 
-        final Instant refreshTiggerTime = nowDateTime.plusMillis(refreshDelay);
-        assert refreshTiggerTime != null;
-        return refreshTiggerTime;
+        final Instant refreshTriggerTime = nowDateTime.plusMillis(refreshDelay);
+        assert refreshTriggerTime != null;
+        return refreshTriggerTime;
     }
     
     /**
@@ -763,7 +784,7 @@ public class DynamicMetadataCache<IdentifierType, MetadataType>
                     lastAccessedTime.isBefore(earliestValidLastAccessed)) {
                 log.debug("{} Metadata exceeds maximum idle time, removing: {}", getLogPrefix(), mgmtData.getID());
                 return true;
-            } else if (now.isAfter(mgmtData.getExpirationTime())) {
+            } else if (mgmtData.getExpirationTime() != null && now.isAfter(mgmtData.getExpirationTime())) {
                 log.debug("{} Metadata has expired, removing: {}", getLogPrefix(), mgmtData.getID());
                 return true;
             } else {
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCacheBuilderSpec.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCacheBuilderSpec.java
index e1f9ac0f..f2551738 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCacheBuilderSpec.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCacheBuilderSpec.java
@@ -61,6 +61,9 @@ public class DynamicMetadataCacheBuilderSpec <IdentifierType, MetadataType>
     /** Strategy used to compute an expiration time. */
     @Nullable private Function<ExpirationTimeContext<MetadataType>, Instant> metadataExpirationTimeStrategy;
     
+    /** Negative lookup cache duration. */
+    @Nonnull private Duration negativeLookupCacheDuration;
+    
     /** Constructor. */
     protected DynamicMetadataCacheBuilderSpec() {
         maxCacheDuration = Constraint.isNotNull(Duration.ofHours(8), "Duration can not be null");
@@ -68,6 +71,7 @@ public class DynamicMetadataCacheBuilderSpec <IdentifierType, MetadataType>
         maxIdleEntityData = Constraint.isNotNull(Duration.ofHours(8), "Duration can not be null");
         cleanupTaskInterval = Constraint.isNotNull(Duration.ofMinutes(30), "Duration can not be null");
         initialCleanupTaskDelay = Constraint.isNotNull(Duration.ofMinutes(1), "Duration can not be null");
+        negativeLookupCacheDuration = Constraint.isNotNull(Duration.ofMinutes(1), "Duration can not be null");
         removeIdleEntityData = true;
     }
     
@@ -249,5 +253,34 @@ public class DynamicMetadataCacheBuilderSpec <IdentifierType, MetadataType>
         initialCleanupTaskDelay = delay;
         
     }
+    
+    /**
+     *  Get the negative lookup cache duration for metadata.
+     *  
+     *  <p>Defaults to: 1 minute.</p>
+     *  
+     * @return the negative lookup cache duration
+     * 
+     * @since 3.4.0
+     */
+    @Nonnull public Duration getNegativeLookupCacheDuration() {
+        return negativeLookupCacheDuration;
+    }
+
+    /**
+     *  Set the negative lookup cache duration for metadata.
+     *  
+     *  <p>Defaults to: 1 minute.</p>
+     *  
+     * @param duration the negative lookup cache duration
+     * 
+     * @since 3.4.0
+     */
+    public void setNegativeLookupCacheDuration(@Nonnull final Duration duration) {
+        Constraint.isNotNull(duration, "Duration cannot be null");
+        Constraint.isFalse(duration.isNegative(), "Duration cannot be negative");
+        
+        negativeLookupCacheDuration = duration;
+    }
 
 }
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/MetadataCacheBuilder.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/MetadataCacheBuilder.java
index 5a5532fb..405168ce 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/MetadataCacheBuilder.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/MetadataCacheBuilder.java
@@ -110,6 +110,7 @@ public final class MetadataCacheBuilder {
                 cache.setMetadataFilterStrategy(spec.getMetadataFilterStrategy());
                 cache.setMetadataBeforeRemovalHook(spec.getMetadataBeforeRemovalHook());
                 cache.setMetadataValidPredicate(spec.getMetadataValidPredicate());
+                cache.setNegativeLookupCacheDuration(spec.getNegativeLookupCacheDuration());
                 cache.setId(spec.getCacheId());
                 cache.initialize();
                 return cache;
diff --git a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCacheTest.java b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCacheTest.java
index 61d11955..e8e7f510 100644
--- a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCacheTest.java
+++ b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/cache/impl/DynamicMetadataCacheTest.java
@@ -28,6 +28,7 @@ import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Function;
 
 import javax.annotation.Nonnull;
@@ -220,6 +221,199 @@ public class DynamicMetadataCacheTest {
         assertEquals(metadata.size(), 0);
 
     }
+    
+    /**
+     * Tests:
+     * <ul>
+     *  <li>Cached metadata exists</li>
+     *  <li>Refresh needed</li>
+     *  <li>Refresh attempt fails</li>
+     *  <li>Stale metadata still returned</li>
+     *  <li>Refresh trigger moved forward</li>
+     *  <li>Next request uses cache and does not refresh</li>
+     *  <li>Later request refreshes again</li>
+     * </ul>
+     * @throws Exception
+     */
+    @Test
+    public void testFetchSuccesThenFetchFailsFinalRequestFromCache() throws Exception {
+        // Add expired record to the cache
+        final Issuer iss = new Issuer("https://example.oidc.op.org");   
+                
+        final MetadataManagementData<Issuer> mgmtData = cache.getBackingStore()
+                .computeManagementDataIfAbsent(iss, MetadataManagementData::new);
+        
+        mgmtData.setExpirationTime(Instant.now().plus(Duration.ofMinutes(1)));
+        // Set refresh is in the past, so refresh required.
+        mgmtData.setRefreshTriggerTime(Instant.now().minus(Duration.ofSeconds(60)));
+            
+        cache.getBackingStore().getIndexedValues().put(iss, 
+                List.of(new OIDCProviderMetadata(iss, List.of(SubjectType.PUBLIC), new URI("http://example.oidc.op.org/metadata"))));
+
+        cache.setMetadataExpirationTimeStrategy(ctx -> ctx.getNow().plus(Duration.ofMinutes(60)));
+        cache.setNegativeLookupCacheDuration(Duration.ofSeconds(2));
+        
+        	
+        final AtomicInteger fetchCount = new AtomicInteger();
+        cache.setFetchStrategy(crit -> {
+            try {
+                if (fetchCount.incrementAndGet() == 1) {
+                    final IssuerIDCriterion issuerCrit = crit.get(IssuerIDCriterion.class);
+                    final Issuer issuer = issuerCrit != null ? issuerCrit.getIssuerID() : null;                       
+                    return new OIDCProviderMetadata(issuer, List.of(SubjectType.PUBLIC),
+                            new URI("http://example.oidc.op.org"));
+                }
+                return null;
+            } catch (final URISyntaxException e) {
+                return null;
+            }
+        });
+        cache.initialize();
+
+        // first request should fetch it
+        var metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        assertEquals(metadata.size(), 1);
+        assertEquals(fetchCount.get(),1);
+        
+        // Expire the metadata, to force update
+        mgmtData.setRefreshTriggerTime(Instant.now().minus(Duration.ofSeconds(10)));
+
+        // Second, wait for refresh needed, fetch fails.
+        metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        assertEquals(metadata.size(), 1);
+        assertEquals(fetchCount.get(), 2);
+        
+        // Third, negative lookup is active, so skip refresh and use cached
+        metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        // should not attempt a fetch
+        assertEquals(metadata.size(), 1);
+        assertEquals(fetchCount.get(),2);
+        
+        Thread.sleep(3000);
+        // Fourth, negative lookup and refresh past, not expired, fetch again
+        metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        assertEquals(fetchCount.get(),3);
+       
+    }
+    
+    @Test
+    public void testRejectedMetadataActivatesBackoff() throws Exception {
+        final AtomicInteger fetchCount = new AtomicInteger();
+
+        cache.setNegativeLookupCacheDuration(Duration.ofMinutes(1));
+        cache.setFetchStrategy(criteria -> {
+            fetchCount.incrementAndGet();
+            try {
+                return new OIDCProviderMetadata(
+                        new Issuer("wrong-id"),
+                        List.of(SubjectType.PUBLIC),
+                        new URI("http://example.oidc.op.org"));
+            } catch (final URISyntaxException e) {
+                return null;
+            }
+        });
+        cache.initialize();
+
+        // The resolved metadata has the wrong issuer, so it cannot be stored.
+        final CriteriaSet criteria =
+                new CriteriaSet(new IssuerIDCriterion(new Issuer("the-issuer")));
+
+        assertTrue(cache.get(criteria).isEmpty());
+        assertEquals(fetchCount.get(), 1);
+
+        assertTrue(cache.get(criteria).isEmpty());
+        assertEquals(fetchCount.get(), 1);
+    }
+    
+    @Test
+    public void testFetchFails_NextRequestWaitsForBackoff() throws Exception {
+        // Add expired record to the cache
+        final Issuer iss = new Issuer("https://example.oidc.op.org");
+        
+        cache.setMetadataExpirationTimeStrategy(ctx -> ctx.getNow().plus(Duration.ofMinutes(60)));
+        // Back off failed origin lookups for two seconds.
+        cache.setNegativeLookupCacheDuration(Duration.ofSeconds(2));
+        
+            
+        final AtomicInteger fetchCount = new AtomicInteger();
+        cache.setFetchStrategy(crit -> {
+            try {
+                final int count = fetchCount.incrementAndGet();
+                if (count == 2 || count == 3) {
+                    final IssuerIDCriterion issuerCrit = crit.get(IssuerIDCriterion.class);
+                    final Issuer issuer = issuerCrit != null ? issuerCrit.getIssuerID() : null;                       
+                    return new OIDCProviderMetadata(issuer, List.of(SubjectType.PUBLIC),
+                            new URI("http://example.oidc.op.org"));
+                }
+                return null;
+            } catch (final URISyntaxException e) {
+                return null;
+            }
+        });
+        cache.initialize();
+        // first request should fail to fetch it
+        var metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        assertEquals(metadata.size(), 0);
+        assertEquals(fetchCount.get(),1);
+
+        // Second, should not attempt a new refresh in backoff window
+        metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        assertEquals(metadata.size(), 0);
+        assertEquals(fetchCount.get(), 1);
+        
+        Thread.sleep(2500);
+        
+        // The negative-cache interval has expired, so retry and store the result.
+        metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        // A second fetch should have been attempted
+        assertEquals(metadata.size(), 1);
+        assertEquals(fetchCount.get(),2);
+
+        // Fourth, should not attempt a new refresh as not in refresh window or backoff
+        metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        // should not attempt a fetch
+        assertEquals(metadata.size(), 1);
+        assertEquals(fetchCount.get(),2);
+
+        // Fifth, refresh is needed, refetch
+        // Expire the metadata, to force update
+        final MetadataManagementData<Issuer> mgmtData = cache.getBackingStore().getManagementData(iss);
+        mgmtData.setRefreshTriggerTime(Instant.now().minus(Duration.ofSeconds(10)));
+        metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        assertEquals(metadata.size(), 1);
+        assertEquals(fetchCount.get(),3);
+        
+
+       
+    }
+    
+    @Test
+    public void testFetchFails_BackoffDisabled() throws Exception {
+        // Add expired record to the cache
+        final Issuer iss = new Issuer("https://example.oidc.op.org");
+        
+        cache.setMetadataExpirationTimeStrategy(ctx -> ctx.getNow().plus(Duration.ofMinutes(60)));
+        // Set the minimum cache duration, how long the entry should stay in the cache
+        cache.setNegativeLookupCacheDuration(Duration.ZERO);
+        
+            
+        final AtomicInteger fetchCount = new AtomicInteger();
+        cache.setFetchStrategy(crit -> {
+            final int count = fetchCount.incrementAndGet();
+            return null;
+        });
+        cache.initialize();
+        // first request should fail to fetch it
+        var metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        assertEquals(metadata.size(), 0);
+        assertEquals(fetchCount.get(),1);
+
+        // No backoff (negative cache), so attempt another fetch
+        metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+        assertEquals(metadata.size(), 0);
+        assertEquals(fetchCount.get(), 2);
+
+    }
 
     /* FIXME disabled as not working on Jenkins, will fix.*/
     @Test(enabled = false)
@@ -421,6 +615,8 @@ public class DynamicMetadataCacheTest {
         assertSame(firstMetadata.get(0), secondMetadata.get(0));
         assertSame(firstMetadata.get(0), thirdMetadata.get(0));
         assertSame(firstMetadata.get(0), provider.get(0));
+        
+        service.shutdownNow();
 
     }
 

-- 
To stop receiving notification emails like this one, please contact
the administrator of this repository.


More information about the commits mailing list