[java-oidc-common] branch main updated: Add a fetch-through metadata cache. Where no backing store is used
Phil Smart
philip.smart at jisc.ac.uk
Tue Mar 8 10:56:46 UTC 2022
This is an automated email from the git hooks/post-receive script.
philsmart pushed a commit to branch main
in repository java-oidc-common.
View the commit online:
http://git.shibboleth.net/view/?p=java-oidc-common.git;a=commit;h=9e4da5bca933d031443019e5d3d125dd702d3463
The following commit(s) were added to refs/heads/main by this push:
new 9e4da5b Add a fetch-through metadata cache. Where no backing store is used
9e4da5b is described below
commit 9e4da5bca933d031443019e5d3d125dd702d3463
Author: Phil Smart <philip.smart at jisc.ac.uk>
AuthorDate: Tue Mar 8 10:56:40 2022 +0000
Add a fetch-through metadata cache. Where no backing store is used
---
.../cache/impl/BaseMetadataCacheBuilderSpec.java | 2 +-
.../cache/impl/FetchThroughMetadataCache.java | 130 ++++++++++++++++++++
.../impl/FetchThroughMetadataCacheBuilder.java | 77 ++++++++++++
.../impl/FetchThroughMetadataCacheBuilderSpec.java | 67 +++++++++++
.../cache/impl/FetchThroughMetadataCacheTest.java | 134 +++++++++++++++++++++
5 files changed, 409 insertions(+), 1 deletion(-)
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/BaseMetadataCacheBuilderSpec.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/BaseMetadataCacheBuilderSpec.java
index d24a10b..e50ddaf 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/BaseMetadataCacheBuilderSpec.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/BaseMetadataCacheBuilderSpec.java
@@ -73,7 +73,7 @@ public abstract class BaseMetadataCacheBuilderSpec<IdentifierType, MetadataType>
protected BaseMetadataCacheBuilderSpec() {
// defaults
refreshDelayFactor = 0.75f;
- cacheId = "Uknown";
+ cacheId = "Unknown";
// create a default direct in/out filter
metadataFilterStrategy = (metadata, context) -> metadata;
// create default TRUE is metadata valid predicate
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCache.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCache.java
new file mode 100644
index 0000000..3980f87
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCache.java
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the University Corporation for Advanced Internet Development,
+ * Inc. (UCAID) under one or more contributor license agreements. See the
+ * NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The UCAID licenses this file to You under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package net.shibboleth.oidc.metadata.cache.impl;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Function;
+
+import javax.annotation.Nonnull;
+import javax.annotation.concurrent.ThreadSafe;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import net.shibboleth.oidc.metadata.cache.MetadataCache;
+import net.shibboleth.oidc.metadata.cache.MetadataCacheException;
+import net.shibboleth.utilities.java.support.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.utilities.java.support.annotation.constraint.NonnullElements;
+import net.shibboleth.utilities.java.support.annotation.constraint.NotEmpty;
+import net.shibboleth.utilities.java.support.component.ComponentSupport;
+import net.shibboleth.utilities.java.support.logic.Constraint;
+import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
+
+/**
+ * A {@link MetadataCache metadata cache} implementation that does not support reading and writing to
+ * a backing store. Entries are fetched, validated, and filtered before being returned to the caller.
+ * Each request always requires fetching and processing. This is not,
+ * therefore, a true cache, and is only useful for special cases which just want to exercise the
+ * fetch, validate, filter, cycle.
+ *
+ * @param <IdentifierType> the metadata identifier type.
+ * @param <MetadataType> the metadata type.
+ */
+ at ThreadSafe
+public class FetchThroughMetadataCache <IdentifierType, MetadataType>
+ extends AbstractMetadataCache<IdentifierType, MetadataType> {
+
+ /** Class logger. */
+ private final Logger log = LoggerFactory.getLogger(FetchThroughMetadataCache.class);
+
+ /** The function to use to fetch/load metadata entries.*/
+ @NonnullAfterInit private Function<CriteriaSet, MetadataType> fetchStrategy;
+
+ /** Constructor. */
+ protected FetchThroughMetadataCache() {
+ // Does not require a backingstore.
+ super(null);
+ }
+
+ /**
+ * Set the metadata fetching strategy.
+ *
+ * @param strategy the strategy used to fetch metadata using a 'read-through' semantic.
+ */
+ public void setFetchStrategy(@Nonnull final Function<CriteriaSet, MetadataType> strategy) {
+ ComponentSupport.ifInitializedThrowUnmodifiabledComponentException(this);
+ ComponentSupport.ifDestroyedThrowDestroyedComponentException(this);
+
+ fetchStrategy = Constraint.isNotNull(strategy, "Dynamic Metadata fetch strategy can not be null");
+ }
+
+ @Override
+ @Nonnull @NonnullElements public List<MetadataType> get(
+ @Nonnull @NotEmpty final CriteriaSet criteria) throws MetadataCacheException {
+
+ if (!isInitialized()) {
+ throw new MetadataCacheException("Metadata cache has not been initialized");
+ }
+
+ final IdentifierType identifier = getCriteriaToIdentifierStrategy().apply(criteria);
+ log.debug("{} Resolved criteria to identifier: {}", getLogPrefix(), identifier);
+
+ if (identifier != null) {
+ final MetadataType resolvedMetadata = fetchStrategy.apply(criteria);
+
+ if (resolvedMetadata != null && getMetadataValidPredicate().test(resolvedMetadata)) {
+
+ final MetadataType filteredMetadata =
+ getMetadataFilterStrategy().apply(resolvedMetadata, newFilterContext());
+
+ if (filteredMetadata == null) {
+ log.warn("{} Filtered metadata is null, no further processing performed", getLogPrefix());
+ return Collections.emptyList();
+ }
+
+ final IdentifierType extractedIdentifier = getIdentifierExtractionStrategy().apply(filteredMetadata);
+
+ if (extractedIdentifier == null) {
+ log.warn("{} Metadata identifier could not be extracted, no further processing performed", getLogPrefix());
+ return Collections.emptyList();
+ }
+
+ // equality method of the identifier is required to be implemented correctly.
+ if (!Objects.equals(identifier, extractedIdentifier)) {
+ log.warn("{} New metadata's identifer '{}' does not match expected identifier '{}', will not process",
+ getLogPrefix(), extractedIdentifier, identifier);
+ return Collections.emptyList();
+ }
+
+ log.debug("{} Resolved metadata with identifier '{}'",getLogPrefix(), extractedIdentifier);
+
+ return List.of(filteredMetadata);
+ } else {
+ log.trace("{} Metadata for '{}' could not be resolved or is not valid",getLogPrefix(), identifier);
+ }
+ } else {
+ log.debug("Identifier not resolvable from criteria, can not fetch metadata");
+ }
+ return Collections.emptyList();
+
+ }
+
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCacheBuilder.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCacheBuilder.java
new file mode 100644
index 0000000..db9847b
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCacheBuilder.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the University Corporation for Advanced Internet Development,
+ * Inc. (UCAID) under one or more contributor license agreements. See the
+ * NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The UCAID licenses this file to You under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package net.shibboleth.oidc.metadata.cache.impl;
+
+import javax.annotation.Nonnull;
+
+import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
+
+/**
+ * Build a fully initialized and safely published fetch-through metadata cache for use. Each cache is built from its own
+ * specification.
+ *
+ * <p>Spring's XML injection can not enforce type safety here, so an incorrect specification will
+ * not be picked up until it is used.</p>
+ */
+public final class FetchThroughMetadataCacheBuilder {
+
+ /** Private constructor.*/
+ private FetchThroughMetadataCacheBuilder() {
+
+ }
+
+ /**
+ * A static builder for generating a dynamic metadata cache from a given specification.
+ *
+ * @param <IdentifierType> The identifier type
+ * @param <MetadataType> The metadata type
+ */
+ public static class Builder<IdentifierType, MetadataType> {
+
+ /**
+ * Build a metadata cache from the given metadata specification.
+ *
+ * @param spec the specification used to build the cache.
+ *
+ * @return the metadata cache.
+ *
+ * @throws ComponentInitializationException on error.
+ */
+ public FetchThroughMetadataCache<IdentifierType, MetadataType>
+ build(@Nonnull final DynamicMetadataCacheBuilderSpec<IdentifierType, MetadataType> spec)
+ throws ComponentInitializationException {
+
+ final FetchThroughMetadataCache<IdentifierType, MetadataType> cache = new FetchThroughMetadataCache<>();
+ cache.setFetchStrategy(spec.getFetchStrategy());
+ //TODO refresh delay is not really needed here.
+ cache.setRefreshDelayFactor(spec.getRefreshDelayFactor());
+ cache.setIdentifierExtractionStrategy(spec.getIdentifierExtractionStrategy());
+ cache.setCriteriaToIdentifierStrategy(spec.getCriteriaToIdentifierStrategy());
+ cache.setMetadataFilterStrategy(spec.getMetadataFilterStrategy());
+ cache.setMetadataBeforeRemovalHook(spec.getMetadataBeforeRemovalHook());
+ cache.setMetadataValidPredicate(spec.getMetadataValidPredicate());
+ cache.setId(spec.getCacheId());
+ cache.initialize();
+ return cache;
+ }
+
+ }
+
+
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCacheBuilderSpec.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCacheBuilderSpec.java
new file mode 100644
index 0000000..b420bda
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCacheBuilderSpec.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the University Corporation for Advanced Internet Development,
+ * Inc. (UCAID) under one or more contributor license agreements. See the
+ * NOTICE file distributed with this work for additional information regarding
+ * copyright ownership. The UCAID licenses this file to You under the Apache
+ * License, Version 2.0 (the "License"); you may not use this file except in
+ * compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package net.shibboleth.oidc.metadata.cache.impl;
+
+import java.util.function.Function;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import net.shibboleth.utilities.java.support.logic.Constraint;
+import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
+
+/**
+ * A specification for building a fetch-through metadata cache.
+ *
+ * @param <IdentifierType> The metadata identifier type.
+ * @param <MetadataType> the metadata type.
+ */
+public class FetchThroughMetadataCacheBuilderSpec <IdentifierType, MetadataType>
+ extends BaseMetadataCacheBuilderSpec<IdentifierType, MetadataType> {
+
+
+ /** The function to use to fetch metadata if either none exists, or the existing is stale.*/
+ @Nullable private Function<CriteriaSet, MetadataType> fetchStrategy;
+
+
+ /** Constructor. */
+ protected FetchThroughMetadataCacheBuilderSpec() {
+ super();
+ }
+
+ /**
+ * Set the metadata fetching strategy.
+ *
+ * @param strategy the strategy to use.
+ */
+ public void setFetchStrategy(@Nonnull final Function<CriteriaSet, MetadataType> strategy) {
+ fetchStrategy = Constraint.isNotNull(strategy, "Metadata fetch strategy can not be null");
+ }
+
+ /**
+ * Get the metadata fetching strategy.
+ *
+ * @return the fetching strategy.
+ */
+ @Nullable protected Function<CriteriaSet, MetadataType> getFetchStrategy() {
+ return fetchStrategy;
+ }
+
+
+}
diff --git a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCacheTest.java b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCacheTest.java
new file mode 100644
index 0000000..fda2dfb
--- /dev/null
+++ b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/cache/impl/FetchThroughMetadataCacheTest.java
@@ -0,0 +1,134 @@
+package net.shibboleth.oidc.metadata.cache.impl;
+
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+import java.util.function.Function;
+
+import javax.annotation.Nonnull;
+
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Predicates;
+import com.nimbusds.oauth2.sdk.id.Issuer;
+import com.nimbusds.openid.connect.sdk.SubjectType;
+import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
+
+import net.shibboleth.oidc.metadata.cache.MetadataCacheException;
+import net.shibboleth.oidc.metadata.criterion.IssuerIDCriterion;
+import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
+
+public class FetchThroughMetadataCacheTest {
+
+ /** The cache.*/
+ private FetchThroughMetadataCache<Issuer, OIDCProviderMetadata> cache;
+
+ /** A default fetching strategy.*/
+ @Nonnull private Function<CriteriaSet, OIDCProviderMetadata> defaultFetchStrategy;
+
+ @BeforeMethod
+ void setup() throws Exception {
+
+ defaultFetchStrategy = crit -> {
+ try {
+ return new OIDCProviderMetadata(new Issuer("https://op.example.com"), List.of(SubjectType.PUBLIC),
+ new URI("https://op.example.com/metadata"));
+ } catch (final URISyntaxException e) {
+ return null;
+ }
+ };
+
+ cache = new FetchThroughMetadataCache<Issuer, OIDCProviderMetadata>();
+ cache.setFetchStrategy(defaultFetchStrategy);
+ cache.setIdentifierExtractionStrategy(OIDCProviderMetadata::getIssuer);
+
+ cache.setCriteriaToIdentifierStrategy(crit -> {
+ final IssuerIDCriterion issuerId = crit.get(IssuerIDCriterion.class);
+ if (issuerId != null) {
+ return issuerId.getIssuerID();
+ }
+ return null;});
+
+ //TODO what to do about this refresh factor when not needed?
+ cache.setRefreshDelayFactor(0.75f);
+ cache.setMetadataValidPredicate(Predicates.alwaysTrue());
+ cache.setMetadataFilterStrategy((metadata, context) -> metadata);
+ cache.setId("MockCache");
+ // Initialise when you need to use it, if creating a local version, do not init this one.
+ //cache.initialize();
+
+ }
+
+ @Test
+ public void testSuccessfullFetch() throws Exception {
+
+ cache.initialize();
+ final Issuer iss = new Issuer("https://op.example.com");
+ final var metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+ assertEquals(metadata.size(), 1);
+ assertTrue(metadata.get(0).getIssuer().equals(iss));
+
+ }
+
+ @Test(expectedExceptions = MetadataCacheException.class)
+ public void testNotInitialized() throws Exception {
+ final Issuer iss = new Issuer("https://not-op.example.com");
+ cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+ }
+
+ @Test
+ public void testUnSuccessfullFetch() throws Exception {
+
+ cache.initialize();
+ final Issuer iss = new Issuer("https://not-op.example.com");
+ final var metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+ assertEquals(metadata.size(), 0);
+
+ }
+
+ @Test
+ public void testFilteredMetadata() throws Exception {
+ cache.setMetadataFilterStrategy((metadata, context) -> null);
+ cache.initialize();
+ final Issuer iss = new Issuer("https://op.example.com");
+ final var metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+ assertEquals(metadata.size(), 0);
+
+ }
+
+ @Test
+ public void testIdentifierExtractionFailed() throws Exception {
+ cache.setIdentifierExtractionStrategy(metadata -> null);
+ cache.initialize();
+ final Issuer iss = new Issuer("https://op.example.com");
+ final var metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+ assertEquals(metadata.size(), 0);
+
+ }
+
+ @Test
+ public void testCriteriaToIdentifierNull() throws Exception {
+ cache.setCriteriaToIdentifierStrategy(c -> null);
+ cache.initialize();
+ final Issuer iss = new Issuer("https://op.example.com");
+ final var metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+ assertEquals(metadata.size(), 0);
+
+ }
+
+ @Test
+ public void testMetadataNotValid() throws Exception {
+ cache.setMetadataValidPredicate(m -> false);
+ cache.initialize();
+ final Issuer iss = new Issuer("https://op.example.com");
+ final var metadata = cache.get(new CriteriaSet(new IssuerIDCriterion(iss)));
+ assertEquals(metadata.size(), 0);
+
+ }
+
+}
--
To stop receiving notification emails like this one, please contact
the administrator of this repository.
More information about the commits
mailing list