Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Base64;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
Expand Down Expand Up @@ -130,13 +131,23 @@ private PublicKey getCachedPublicKey(List<String> certificateChain) {
return null;
}

private void putVerifiedPublicKey(List<String> certificateChain, PublicKey publicKey) {
Instant cacheExpiration = clock.instant().plus(CACHE_TIME_LIMIT, ChronoUnit.MINUTES);
verifiedPublicKeyCache.put(certificateChain, new CachedEntry(cacheExpiration, publicKey));
if (verifiedPublicKeyCache.size() > MAXIMUM_CACHE_SIZE) {
// In the very unlikely event that the map has become too large, clear out old entries
verifiedPublicKeyCache.entrySet().removeIf(e -> e.getValue().cachedExpirationDate.isBefore(clock.instant()));
private synchronized void putVerifiedPublicKey(List<String> certificateChain, PublicKey publicKey) {
Instant now = clock.instant();
verifiedPublicKeyCache.entrySet().removeIf(e -> e.getValue().cachedExpirationDate.isBefore(now));

while (verifiedPublicKeyCache.size() >= MAXIMUM_CACHE_SIZE) {
List<String> certificateChainToEvict = verifiedPublicKeyCache.entrySet().stream()
.min(Comparator.comparing(e -> e.getValue().cachedExpirationDate))
.map(e -> e.getKey())
.orElse(null);
if (certificateChainToEvict == null) {
break;
}
verifiedPublicKeyCache.remove(certificateChainToEvict);
}

Instant cacheExpiration = now.plus(CACHE_TIME_LIMIT, ChronoUnit.MINUTES);
verifiedPublicKeyCache.put(certificateChain, new CachedEntry(cacheExpiration, publicKey));
}

private static class CachedEntry {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,23 @@ public void testOcspResponseCachingWithSlightlyDifferentChains() throws Verifica
Mockito.verify(mockedChainVerifier, Mockito.times(2)).verifyChainWithoutCaching(Mockito.any(), Mockito.anyBoolean(), Mockito.any());
}

@Test
public void testOcspResponseCacheDoesNotExceedMaximumSizeWhenEntriesAreFresh() throws Exception {
for (int index = 0; index <= 32; index++) {
mockedChainVerifier.verifyChain(new String[] {
LEAF_CERT_BASE64_ENCODED,
INTERMEDIATE_CA_BASE64_ENCODED,
ROOT_CA_BASE64_ENCODED + index
}, true, EFFECTIVE_DATE);
}

Field cacheField = ChainVerifier.class.getDeclaredField("verifiedPublicKeyCache");
cacheField.setAccessible(true);
Map<?, ?> cache = (Map<?, ?>) cacheField.get(mockedChainVerifier);

Assertions.assertEquals(32, cache.size());
}

@Test
public void testOcspResponseCachingWhenEntryIsRemovedDuringLookup() throws Exception {
String[] chain = new String[] {
Expand Down