[java-oidc-common] branch main updated: JCOMOIDC-179 - Update support for metadata policies
Codeberg
noreply at shibboleth.net
Thu Nov 12 12:36:24 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/9d8b15b83cf6aa2661b9e1d5e48348c2a9405a92
The following commit(s) were added to refs/heads/main by this push:
new 9d8b15b8 JCOMOIDC-179 - Update support for metadata policies
9d8b15b8 is described below
commit 9d8b15b83cf6aa2661b9e1d5e48348c2a9405a92
Author: Henri Mikkonen <henri.mikkonen at iki.fi>
AuthorDate: Thu Nov 12 14:31:53 2026 +0200
JCOMOIDC-179 - Update support for metadata policies
https://shibboleth.atlassian.net/browse/JCOMOIDC-179
- MetadataPolicy
- deprecated regexp and instruct to use it via custom operators
- annotations
- MetadataPolicyOperator
- new interface to cover both standard and custom metadata operators
- Refactored CustomMetadataPolicyOperator
- now extends the MetadataPolicyOperator
- requires getOperatorName() (breaking change)
- Updated BeanMetadataPolicyOperator and DefaultMetadataPolicyOperator accordingly
- New RegexpMetadataPolicyOperator to implement 'regexp'
- Implement standard operators with respective MetadataPolicyOperator implementation
- DefaultMetadataPolicy(Add/Default/Essential/OneOf/SubsetOf/SupersetOf/Value)Operator
- MetadataPolicyEnforcer
- Now exploits configurable list of MetaadataPolicyOperators
- Deprecated the existing
- By default implements the enforcing as defined in OpenID Federation 1.0 section 6.1
- Most notable changes to the previous draft-based implementation
- value does not anymore deny other operators to be applied
- add, subset_of and superset_of requires array values for metadata and operator
- one_of solely works with non-array values
- subset_of returns empty array instead of a failure
- MetadataPolicyValidator
- Now exploits configurable list of MetaadataPolicyOperators
- Deprecated the existing
- By default implements the validation as defined in OpenID Federation 1.0 section 6.1
- Updated tests accordingly
---
.../oidc/metadata/policy/MetadataPolicy.java | 144 +++---
.../metadata/policy/MetadataPolicyOperator.java | 19 +-
.../AbstractFederationMetadataPolicyOperator.java | 58 +++
.../policy/impl/BeanMetadataPolicyOperator.java | 50 +-
.../policy/impl/CustomMetadataPolicyOperator.java | 26 +-
.../impl/DefaultMetadataPolicyAddOperator.java | 94 ++++
.../impl/DefaultMetadataPolicyDefaultOperator.java | 46 ++
.../impl/DefaultMetadataPolicyDeserializer.java | 173 +++++++
.../policy/impl/DefaultMetadataPolicyEnforcer.java | 266 +++--------
.../DefaultMetadataPolicyEssentialOperator.java | 48 ++
.../impl/DefaultMetadataPolicyMergingStrategy.java | 155 +++++++
.../impl/DefaultMetadataPolicyOneOfOperator.java | 83 ++++
.../policy/impl/DefaultMetadataPolicyOperator.java | 31 +-
.../DefaultMetadataPolicySubsetOfOperator.java | 67 +++
.../DefaultMetadataPolicySupersetOfOperator.java | 70 +++
.../impl/DefaultMetadataPolicyValidator.java | 196 ++++----
.../impl/DefaultMetadataPolicyValueOperator.java | 46 ++
.../metadata/policy/impl/MetadataPolicyHelper.java | 229 ++++++++-
.../policy/impl/RegexpMetadataPolicyOperator.java | 117 +++++
.../impl/BeanMetadataPolicyOperatorTest.java | 28 +-
.../impl/DefaultMetadataPolicyEnforcerTest.java | 204 ++++----
.../impl/DefaultMetadataPolicyValidatorTest.java | 514 +++++++++++++--------
.../policy/impl/MetadataPolicyHelperTest.java | 38 +-
.../impl/OIDCMetadataPolicyResolverTest.java | 42 +-
.../impl/RegexpMetadataPolicyOperatorTest.java | 171 +++++++
25 files changed, 2142 insertions(+), 773 deletions(-)
diff --git a/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/policy/MetadataPolicy.java b/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/policy/MetadataPolicy.java
index 6e2e1cda..d0cdcac1 100644
--- a/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/policy/MetadataPolicy.java
+++ b/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/policy/MetadataPolicy.java
@@ -17,51 +17,58 @@ package net.shibboleth.oidc.metadata.policy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.primitive.DeprecationSupport;
+import net.shibboleth.shared.primitive.DeprecationSupport.ObjectType;
+
/**
- * The metadata policy for a single claim. It exploits the operators defined in the 5.1 of OIDC federation spec
- * (draft 17 for time being): https://openid.net/specs/openid-connect-federation-1_0.html#rfc.section.5.1
+ * The metadata policy for a single claim. It contains the operators defined in the 6.1 of OpenID Federation 1.0. Any
+ * non-standard operators are wired to the map of custom operators.
*/
public class MetadataPolicy {
/** The (forced) value for the claim. */
- @JsonProperty("value") private Object forcedValue;
+ @JsonProperty("value") @Nullable private Object forcedValue;
/** The value(s) to be added for the claim. */
- @JsonProperty("add") private Object add;
+ @JsonProperty("add") @Nullable private Object add;
/** The default value for the claim to be used in case none is specified. */
- @JsonProperty("default") private Object defaultValue;
+ @JsonProperty("default") @Nullable private Object defaultValue;
/** The list of values from which the claim must be one of. */
- @JsonProperty("one_of") private List<Object> oneOfValues;
+ @JsonProperty("one_of") @Nullable private List<Object> oneOfValues;
/** The list of value(s) from which the claim must be subset of. */
- @JsonProperty("subset_of") private List<Object> subsetOfValues;
+ @JsonProperty("subset_of") @Nullable private List<Object> subsetOfValues;
/** The list of value(s) from which the claim must be superset of. */
- @JsonProperty("superset_of") private List<Object> supersetOfValues;
+ @JsonProperty("superset_of") @Nullable private List<Object> supersetOfValues;
/** The flag indicating that the claim must have a value. */
- @JsonProperty("essential") private Boolean essential;
+ @JsonProperty("essential") @Nullable private Boolean essential;
- /** The regular expression that the claim value must meet. */
- @JsonProperty("regexp") private String regexp;
-
/** The map of any other operators not directly mapped. */
- private final Map<String, Object> customOperators = new HashMap<>();
+ @Nonnull private final Map<String, Object> customOperators = new HashMap<>();
/**
* Get the (forced) value for the claim.
*
* @return The (forced) value for the claim.
*/
- public Object getValue() {
+ @Nullable public Object getValue() {
return forcedValue;
}
@@ -70,7 +77,7 @@ public class MetadataPolicy {
*
* @param value What to set.
*/
- public void setValue(final Object value) {
+ public void setValue(@Nullable final Object value) {
this.forcedValue = value;
}
@@ -79,7 +86,7 @@ public class MetadataPolicy {
*
* @return The value(s) to be added for the claim.
*/
- public Object getAdd() {
+ @Nullable public Object getAdd() {
return add;
}
@@ -88,7 +95,7 @@ public class MetadataPolicy {
*
* @param value What to set.
*/
- public void setAdd(final Object value) {
+ public void setAdd(@Nullable final Object value) {
this.add = value;
}
@@ -97,7 +104,7 @@ public class MetadataPolicy {
*
* @return The default value for the claim to be used in case none is specified.
*/
- public Object getDefaultValue() {
+ @Nullable public Object getDefaultValue() {
return defaultValue;
}
@@ -106,7 +113,7 @@ public class MetadataPolicy {
*
* @param value What to set.
*/
- public void setDefaultValue(final Object value) {
+ public void setDefaultValue(@Nullable final Object value) {
this.defaultValue = value;
}
@@ -115,7 +122,7 @@ public class MetadataPolicy {
*
* @return The list of values from which the claim must be one of.
*/
- public List<Object> getOneOfValues() {
+ @Nullable public List<Object> getOneOfValues() {
return oneOfValues;
}
@@ -124,7 +131,7 @@ public class MetadataPolicy {
*
* @param values What to set.
*/
- public void setOneOfValues(final List<Object> values) {
+ public void setOneOfValues(@Nullable final List<Object> values) {
this.oneOfValues = values;
}
@@ -133,7 +140,7 @@ public class MetadataPolicy {
*
* @return The list of value(s) from which the claim must be subset of.
*/
- public List<Object> getSubsetOfValues() {
+ @Nullable public List<Object> getSubsetOfValues() {
return subsetOfValues;
}
@@ -142,7 +149,7 @@ public class MetadataPolicy {
*
* @param values What to set.
*/
- public void setSubsetOfValues(final List<Object> values) {
+ public void setSubsetOfValues(@Nullable final List<Object> values) {
this.subsetOfValues = values;
}
@@ -151,7 +158,7 @@ public class MetadataPolicy {
*
* @return The list of value(s) from which the claim must be superset of.
*/
- public List<Object> getSupersetOfValues() {
+ @Nullable public List<Object> getSupersetOfValues() {
return supersetOfValues;
}
@@ -160,7 +167,7 @@ public class MetadataPolicy {
*
* @param values What to set.
*/
- public void setSupersetOfValues(final List<Object> values) {
+ public void setSupersetOfValues(@Nullable final List<Object> values) {
this.supersetOfValues = values;
}
@@ -169,7 +176,7 @@ public class MetadataPolicy {
*
* @return The flag indicating that the claim must have a value.
*/
- public Boolean getEssential() {
+ @Nullable public Boolean getEssential() {
return essential;
}
@@ -187,7 +194,7 @@ public class MetadataPolicy {
*
* @param isEssential What to set.
*/
- public void setEssential(final Boolean isEssential) {
+ public void setEssential(@Nullable final Boolean isEssential) {
this.essential = isEssential;
}
@@ -195,18 +202,35 @@ public class MetadataPolicy {
* Get the regular expression that the claim value must meet.
*
* @return The regular expression that the claim value must meet.
+ * @deprecated use {@link #getCustomOperators()}
*/
+ @Deprecated(since="4.0.0", forRemoval=true)
+ @JsonIgnore @Nullable
public String getRegexp() {
- return regexp;
+ DeprecationSupport.warn(ObjectType.METHOD, "MetadataPolicy.getRegexp", null,
+ "MetadataPolicy.getCustomOperators");
+ return Optional.ofNullable(customOperators.get("regexp"))
+ .filter(String.class::isInstance)
+ .map(String.class::cast)
+ .orElse(null);
}
/**
* Set the regular expression that the claim value must meet.
*
* @param value What to set.
+ * @deprecated use {@link #getCustomOperators()}
*/
- public void setRegexp(final String value) {
- regexp = value;
+ @Deprecated(since="4.0.0", forRemoval=true)
+ @JsonIgnore
+ public void setRegexp(@Nullable final String value) {
+ DeprecationSupport.warn(ObjectType.METHOD, "MetadataPolicy.setRegexp", null,
+ "MetadataPolicy.setCustomOperator");
+ if (value == null) {
+ customOperators.remove("regexp");
+ } else {
+ customOperators.put("regexp", value);
+ }
}
/**
@@ -216,7 +240,7 @@ public class MetadataPolicy {
*
* @since 3.1.0
*/
- @JsonAnyGetter
+ @JsonAnyGetter @Nonnull
public Map<String, Object> getCustomOperators() {
return customOperators;
}
@@ -230,8 +254,8 @@ public class MetadataPolicy {
* @since 3.1.0
*/
@JsonAnySetter
- public void setCustomOperator(final String name, final Object value) {
- customOperators.put(name, value);
+ public void setCustomOperator(@Nonnull @NotEmpty final String name, @Nullable final Object value) {
+ customOperators.put(Constraint.isNotEmpty(name, "Custom operator name cannot be empty"), value);
}
/**
@@ -246,7 +270,6 @@ public class MetadataPolicy {
.add("subset_of", subsetOfValues)
.add("superset_of", supersetOfValues)
.add("essential", essential)
- .add("regexp", regexp)
.add("customOperators", customOperators).toString();
}
@@ -256,31 +279,28 @@ public class MetadataPolicy {
public static class Builder {
/** The (forced) value for the claim. */
- private Object forcedValue;
+ @Nullable private Object forcedValue;
/** The value(s) to be added for the claim. */
- private Object add;
+ @Nullable private Object add;
/** The default value for the claim to be used in case none is specified. */
- private Object defaultValue;
+ @Nullable private Object defaultValue;
/** The list of values from which the claim must be one of. */
- private List<Object> oneOfValues;
+ @Nullable private List<Object> oneOfValues;
/** The list of value(s) from which the claim must be subset of. */
- private List<Object> subsetOfValues;
+ @Nullable private List<Object> subsetOfValues;
/** The list of value(s) from which the claim must be superset of. */
- private List<Object> supersetOfValues;
+ @Nullable private List<Object> supersetOfValues;
/** The flag indicating that the claim must have a value. */
- private Boolean essential;
+ @Nullable private Boolean essential;
- /** The regular expression that the claim value must meet. */
- private String regexp;
-
/** The map of any other operators not directly mapped. */
- private final Map<String, Object> customOperators;
+ @Nonnull private final Map<String, Object> customOperators;
/**
* Constructor.
@@ -295,7 +315,7 @@ public class MetadataPolicy {
* @param value What to set.
* @return The builder object with the new value set.
*/
- public Builder withValue(final Object value) {
+ @Nonnull public Builder withValue(@Nullable final Object value) {
this.forcedValue = value;
return this;
}
@@ -306,7 +326,7 @@ public class MetadataPolicy {
* @param value What to set.
* @return The builder object with the new value set.
*/
- public Builder withAdd(final Object value) {
+ @Nonnull public Builder withAdd(@Nullable final Object value) {
this.add = value;
return this;
}
@@ -317,7 +337,7 @@ public class MetadataPolicy {
* @param value What to set.
* @return The builder object with the new value set.
*/
- public Builder withDefaultValue(final Object value) {
+ @Nonnull public Builder withDefaultValue(@Nullable final Object value) {
this.defaultValue = value;
return this;
}
@@ -328,7 +348,7 @@ public class MetadataPolicy {
* @param values What to set.
* @return The builder object with the new value set.
*/
- public Builder withOneOfValues(final List<Object> values) {
+ @Nonnull public Builder withOneOfValues(@Nullable final List<Object> values) {
this.oneOfValues = values;
return this;
}
@@ -339,7 +359,7 @@ public class MetadataPolicy {
* @param values What to set.
* @return The builder object with the new value set.
*/
- public Builder withSubsetOfValues(final List<Object> values) {
+ @Nonnull public Builder withSubsetOfValues(@Nullable final List<Object> values) {
this.subsetOfValues = values;
return this;
}
@@ -350,7 +370,7 @@ public class MetadataPolicy {
* @param values What to set.
* @return The builder object with the new value set.
*/
- public Builder withSupersetOfValues(final List<Object> values) {
+ @Nonnull public Builder withSupersetOfValues(@Nullable final List<Object> values) {
this.supersetOfValues = values;
return this;
}
@@ -361,7 +381,7 @@ public class MetadataPolicy {
* @param isEssential What to set.
* @return The builder object with the new value set.
*/
- public Builder withEssential(final Boolean isEssential) {
+ @Nonnull public Builder withEssential(@Nullable final Boolean isEssential) {
this.essential = isEssential;
return this;
}
@@ -371,9 +391,17 @@ public class MetadataPolicy {
*
* @param value What to set.
* @return The builder object with the new value set.
+ * @deprecated use {@link #withCustomOperator(String, Object)}
*/
- public Builder withRegexp(final String value) {
- this.regexp = value;
+ @Deprecated(since="4.0.0", forRemoval=true)
+ @Nonnull public Builder withRegexp(@Nullable final String value) {
+ DeprecationSupport.warn(ObjectType.METHOD, "MetadataPolicy.Builder.withRegexp", null,
+ "MetadataPolicy.Builder.withCustomOperator");
+ if (value == null) {
+ this.customOperators.remove("regexp");
+ } else {
+ this.customOperators.put("regexp", value);
+ }
return this;
}
@@ -386,8 +414,8 @@ public class MetadataPolicy {
*
* @since 3.1.0
*/
- public Builder withCustomOperator(final String name, final Object value) {
- this.customOperators.put(name, value);
+ @Nonnull public Builder withCustomOperator(@Nonnull @NotEmpty final String name, @Nullable final Object value) {
+ this.customOperators.put(Constraint.isNotEmpty(name, "Custom operator name cannot be empty"), value);
return this;
}
@@ -396,7 +424,7 @@ public class MetadataPolicy {
*
* @return The metadata policy corresponding to the current builder state.
*/
- public MetadataPolicy build() {
+ @Nonnull public MetadataPolicy build() {
final MetadataPolicy policy = new MetadataPolicy();
policy.setValue(this.forcedValue);
policy.setAdd(this.add);
@@ -405,8 +433,8 @@ public class MetadataPolicy {
policy.setSubsetOfValues(this.subsetOfValues);
policy.setSupersetOfValues(this.supersetOfValues);
policy.setEssential(this.essential);
- policy.setRegexp(this.regexp);
for (final String key : this.customOperators.keySet()) {
+ assert key != null;
policy.setCustomOperator(key, this.customOperators.get(key));
}
return policy;
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/CustomMetadataPolicyOperator.java b/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/policy/MetadataPolicyOperator.java
similarity index 76%
copy from oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/CustomMetadataPolicyOperator.java
copy to oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/policy/MetadataPolicyOperator.java
index d2c78cb7..4c797a15 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/CustomMetadataPolicyOperator.java
+++ b/oidc-common-metadata-api/src/main/java/net/shibboleth/oidc/metadata/policy/MetadataPolicyOperator.java
@@ -12,26 +12,33 @@
* limitations under the License.
*/
-package net.shibboleth.oidc.metadata.policy.impl;
+package net.shibboleth.oidc.metadata.policy;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
-import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
import net.shibboleth.shared.logic.ConstraintViolationException;
/**
- * Interface describing a custom policy operator to be used with {@link MetadataPolicy} objects.
+ * Interface to be implemented by the metadata policy operators.
*
- * @since 3.1.0
+ * @since 4.0.0
*/
-public interface CustomMetadataPolicyOperator {
+public interface MetadataPolicyOperator {
+
+ /**
+ * The unique case-sensitive name of this operator.
+ *
+ * @return the operator name.
+ */
+ @Nonnull @NotEmpty public String getOperatorName();
/**
* Validate whether the operator is compatible with the other operators in the policy.
*
* @param policy The metadata policy to be used by the custom policy operator.
- * @return true if
+ * @return true if the policy is valid for this operator, false otherwise.
*/
public boolean validate(@Nonnull final MetadataPolicy policy);
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/AbstractFederationMetadataPolicyOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/AbstractFederationMetadataPolicyOperator.java
new file mode 100644
index 00000000..94cb114e
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/AbstractFederationMetadataPolicyOperator.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.util.List;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicyOperator;
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.component.AbstractIdentifiableInitializableComponent;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+
+/**
+ * Base implementation for the classes implementing {@link MetadataPolicyOperator}.
+ *
+ * @since 4.0.0
+ */
+public abstract class AbstractFederationMetadataPolicyOperator extends AbstractIdentifiableInitializableComponent
+ implements MetadataPolicyOperator {
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean validate(@Nonnull final MetadataPolicy policy) {
+ return true;
+ }
+
+ /**
+ * Parses a list from the given object.
+ *
+ * @param object the object to be parsed
+ * @return a list of it couöd be parsed from the object, or null if input was null
+ * @throws ConstraintViolationException thrown if non-null input value was not a list
+ */
+ @Nullable protected static List<Object> parseList(@Nullable final Object object)
+ throws ConstraintViolationException {
+ if (object instanceof List<?> list) {
+ return list.stream().filter(Object.class::isInstance).map(Object.class::cast).toList();
+ } else if (object != null) {
+ throw new ConstraintViolationException("Could not parse list from the given object");
+ }
+ return null;
+ }
+
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/BeanMetadataPolicyOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/BeanMetadataPolicyOperator.java
index 9990d979..bf6b9e95 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/BeanMetadataPolicyOperator.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/BeanMetadataPolicyOperator.java
@@ -17,13 +17,16 @@ package net.shibboleth.oidc.metadata.policy.impl;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import org.slf4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
import net.shibboleth.shared.logic.Constraint;
import net.shibboleth.shared.logic.ConstraintViolationException;
+import net.shibboleth.shared.primitive.LoggerFactory;
/**
* A custom metadata policy operator that fetches a bean from {@link ApplicationContext} and uses it for as
@@ -34,26 +37,36 @@ import net.shibboleth.shared.logic.ConstraintViolationException;
public class BeanMetadataPolicyOperator implements CustomMetadataPolicyOperator, ApplicationContextAware {
/** The operator name to be used within {@link MetadataPolicy} custom operators. */
- public static final String BEAN_OPERATOR_NAME = "bean";
+ @Nonnull @NotEmpty public static final String BEAN_OPERATOR_NAME = "bean";
+
+ /** Class logger. */
+ @Nonnull private final Logger log = LoggerFactory.getLogger(BeanMetadataPolicyOperator.class);
/** The application context from where to fetch the custom policy operators. */
private ApplicationContext applicationContext;
@Override
public boolean validate(@Nonnull final MetadataPolicy policy) {
- try {
- final CustomMetadataPolicyOperator operator = fetchPolicyOperatorBean(policy);
- return operator.validate(policy);
- } catch (final ConstraintViolationException e) {
- return false;
+ if (policy.getCustomOperators().containsKey(BEAN_OPERATOR_NAME)) {
+ try {
+ final CustomMetadataPolicyOperator operator = fetchPolicyOperatorBean(policy);
+ return operator.validate(policy);
+ } catch (final ConstraintViolationException e) {
+ log.warn("Could not call the bean metadata operator's validate-method", e);
+ return false;
+ }
}
+ return true;
}
@Override
- public Object apply(final @Nullable Object inputValue, final @Nonnull MetadataPolicy policy)
+ public Object apply(@Nullable final Object inputValue, @Nonnull final MetadataPolicy policy)
throws ConstraintViolationException {
- final CustomMetadataPolicyOperator operator = fetchPolicyOperatorBean(policy);
- return operator.apply(inputValue, policy);
+ if (policy.getCustomOperators().containsKey(BEAN_OPERATOR_NAME)) {
+ final CustomMetadataPolicyOperator operator = fetchPolicyOperatorBean(policy);
+ return operator.apply(inputValue, policy);
+ }
+ return inputValue;
}
/**
@@ -63,18 +76,23 @@ public class BeanMetadataPolicyOperator implements CustomMetadataPolicyOperator,
* @return The bean whose identifier matches the one given in the policy.
* @throws ConstraintViolationException If the matching bean could not be wired or its id could not be parsed.
*/
- @Nonnull protected CustomMetadataPolicyOperator fetchPolicyOperatorBean(final @Nonnull MetadataPolicy policy)
+ @Nonnull protected CustomMetadataPolicyOperator fetchPolicyOperatorBean(@Nonnull final MetadataPolicy policy)
throws ConstraintViolationException {
Constraint.isNotNull(policy, "metadata policy cannot be null");
final Object rawBeanId = policy.getCustomOperators().get(BEAN_OPERATOR_NAME);
if (rawBeanId instanceof String beanId) {
try {
- return applicationContext.getBean(beanId, CustomMetadataPolicyOperator.class);
+ final CustomMetadataPolicyOperator bean =
+ applicationContext.getBean(beanId, CustomMetadataPolicyOperator.class);
+ if (bean != null) {
+ return bean;
+ }
} catch (final BeansException e) {
- throw new ConstraintViolationException("Could not wire a compatible bean " + beanId);
+ // covered below
}
+ throw new ConstraintViolationException("Could not wire a compatible bean " + beanId);
} else {
- throw new ConstraintViolationException("Could not parse the bean name from policy");
+ throw new ConstraintViolationException("Could not parse the bean name from policy " + rawBeanId);
}
}
@@ -83,4 +101,10 @@ public class BeanMetadataPolicyOperator implements CustomMetadataPolicyOperator,
applicationContext = context;
}
+ /** {@inheritDoc} */
+ @Override @Nonnull @NotEmpty
+ public String getOperatorName() {
+ return BEAN_OPERATOR_NAME;
+ }
+
}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/CustomMetadataPolicyOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/CustomMetadataPolicyOperator.java
index d2c78cb7..d6c2a838 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/CustomMetadataPolicyOperator.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/CustomMetadataPolicyOperator.java
@@ -14,36 +14,14 @@
package net.shibboleth.oidc.metadata.policy.impl;
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-
+import net.shibboleth.oidc.metadata.policy.MetadataPolicyOperator;
import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
-import net.shibboleth.shared.logic.ConstraintViolationException;
/**
* Interface describing a custom policy operator to be used with {@link MetadataPolicy} objects.
*
* @since 3.1.0
*/
-public interface CustomMetadataPolicyOperator {
-
- /**
- * Validate whether the operator is compatible with the other operators in the policy.
- *
- * @param policy The metadata policy to be used by the custom policy operator.
- * @return true if
- */
- public boolean validate(@Nonnull final MetadataPolicy policy);
-
- /**
- * Apply the operator for the given input that has the given metadata policy attached.
- *
- * @param inputValue The value to be used by the custom policy operator.
- * @param policy The metadata policy to be used by the custom policy operator.
- * @return The value returned by the custom policy operator.
- * @throws ConstraintViolationException If the value-check of the custom operator fails.
- */
- @Nullable public Object apply(@Nullable final Object inputValue, @Nonnull final MetadataPolicy policy)
- throws ConstraintViolationException;
+public interface CustomMetadataPolicyOperator extends MetadataPolicyOperator {
}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyAddOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyAddOperator.java
new file mode 100644
index 00000000..1b753b8c
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyAddOperator.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.util.List;
+import java.util.stream.Stream;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+import net.shibboleth.shared.primitive.LoggerFactory;
+
+/**
+ * Default implementation for the 'add'-operator.
+ *
+ * @since 4.0.0
+ */
+public class DefaultMetadataPolicyAddOperator extends AbstractFederationMetadataPolicyOperator {
+
+ /** Class logger. */
+ @Nonnull private final Logger log = LoggerFactory.getLogger(DefaultMetadataPolicyAddOperator.class);
+
+ /** {@inheritDoc} */
+ @Nonnull @NotEmpty public String getOperatorName() {
+ return "add";
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Nullable public Object apply(@Nullable final Object candidate, @Nonnull final MetadataPolicy policy)
+ throws ConstraintViolationException {
+ final List<Object> add = parseList(policy.getAdd());
+ if (add != null) {
+ if (candidate instanceof List<?> list) {
+ log.debug("Combining candidate {} and add {}", list, add);
+ return buildResult(Stream.concat(list.stream(), add.stream()));
+ } else if (candidate == null) {
+ log.debug("Returning the contents of the add operator: {}", add);
+ return buildResult(add.stream());
+ } else {
+ log.debug("Candidate value {} is not a list/array", candidate);
+ throw new ConstraintViolationException("Candidate " + candidate + " is not a list/array");
+ }
+ }
+ return candidate;
+ }
+
+ /**
+ * Builds a list from the given stream.
+ *
+ * @param stream the stream
+ * @return the list
+ */
+ @Nonnull protected List<Object> buildResult(final Stream<?> stream) {
+ final List<Object> result = stream
+ .filter(Object.class::isInstance)
+ .map(Object.class::cast)
+ .distinct()
+ .toList();
+ assert result != null;
+ return CollectionSupport.copyToList(result);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean validate(@Nonnull final MetadataPolicy policy) {
+ try {
+ parseList(policy.getAdd());
+ } catch (final ConstraintViolationException e) {
+ log.warn("The value for add operator {} is not a list/array", policy.getAdd());
+ return false;
+ }
+ return true;
+ }
+
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyDefaultOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyDefaultOperator.java
new file mode 100644
index 00000000..95e2ae0f
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyDefaultOperator.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed 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.policy.impl;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+
+/**
+ * Default implementation for the 'default' -operator.
+ *
+ * @since 4.0.0
+ */
+public class DefaultMetadataPolicyDefaultOperator extends AbstractFederationMetadataPolicyOperator {
+
+ /** {@inheritDoc} */
+ @Nonnull @NotEmpty public String getOperatorName() {
+ return "default";
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Nullable public Object apply(@Nullable final Object candidate, @Nonnull final MetadataPolicy policy)
+ throws ConstraintViolationException {
+ if (candidate != null) {
+ return candidate;
+ }
+ final Object defaultValue = policy.getDefaultValue();
+ return defaultValue != null ? defaultValue : candidate;
+ }
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyDeserializer.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyDeserializer.java
new file mode 100644
index 00000000..5666f9a3
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyDeserializer.java
@@ -0,0 +1,173 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.type.MapType;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.ParameterName;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.primitive.LoggerFactory;
+
+/**
+ * Default deserializer for the {@link MetadataPolicy} used within OpenID Federation. If the value for the "value"
+ * -operator is explicitly set to null in JSON, this deserializer sets {@link MetadataPolicy#setValue(Object)} into
+ * {@link Optional#empty()}.
+ *
+ * @since 4.0.0
+ */
+public class DefaultMetadataPolicyDeserializer extends JsonDeserializer<MetadataPolicy> {
+
+ /** Class logger. */
+ @Nonnull private final Logger log = LoggerFactory.getLogger(DefaultMetadataPolicyDeserializer.class);
+
+ /** List of claim names who are transformed from a space-separated String into a List. */
+ @Nonnull private final List<String> arraysAsSpaceSeparatedList;
+
+ /**
+ * Constructor.
+ */
+ public DefaultMetadataPolicyDeserializer() {
+ this("scope");
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param string comma-separated list of claim names who are transformed from a space-separated String into a List.
+ */
+ public DefaultMetadataPolicyDeserializer(
+ @Nonnull @ParameterName(name = "arraysAsSpaceSeparatedList") final String string) {
+ final List<String> list = Arrays.asList(Constraint.isNotEmpty(string, "The string cannot be empty").split(","));
+ assert list != null;
+ arraysAsSpaceSeparatedList = list;
+ }
+
+ /** {@inheritDoc} */
+ @Override @Nonnull
+ public MetadataPolicy deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext)
+ throws IOException, JsonProcessingException {
+ final MetadataPolicy policy = new MetadataPolicy();
+ log.debug("Starting deseralize");
+ final JavaType objectType = TypeFactory.defaultInstance().constructType(Object.class);
+ final JavaType stringType = TypeFactory.defaultInstance().constructType(String.class);
+ final MapType objectMapType =
+ TypeFactory.defaultInstance().constructMapType(Map.class, stringType, objectType);
+
+ final Map<String,Object> map = deserializationContext.readValue(jsonParser, objectMapType);
+ final String claim = jsonParser.getParsingContext().getCurrentName();
+ if (claim == null) {
+ throw new IOException("Could not find the parent claim name for the metadata policy");
+ }
+ log.debug("Processing claim {}, value {}", claim, map);
+
+ if (map != null) {
+ log.debug("Processing map object {}", map);
+ for (final String key : map.keySet().stream().filter(Objects::nonNull).toList()) {
+ switch (key) {
+ case "value":
+ final Object value;
+ if (map.get("value") instanceof String string) {
+ value = MetadataPolicyHelper.transformSpaceSeparatedStringIntoList(
+ arraysAsSpaceSeparatedList, claim, string);
+ } else {
+ value = map.get("value");
+ }
+ policy.setValue(value != null ? value : Optional.empty());
+ break;
+ case "add":
+ policy.setAdd(transformObjectIntoList("add", map.get("add")));
+ break;
+ case "default":
+ final Object defaultValue = map.get("default");
+ if (defaultValue instanceof String) {
+ policy.setDefaultValue(
+ MetadataPolicyHelper.transformSpaceSeparatedStringIntoList(
+ arraysAsSpaceSeparatedList, claim, defaultValue));
+ } else if (defaultValue == null) {
+ throw new IOException("The default value is not allowed to be null");
+ } else {
+ policy.setDefaultValue(defaultValue);
+ }
+ break;
+ case "essential":
+ final Object essentialFlag = map.get("essential");
+ if (essentialFlag instanceof Boolean flag) {
+ policy.setEssential(flag);
+ } else {
+ throw new IOException("The essential value is not boolean: " + essentialFlag);
+ }
+ break;
+ case "one_of":
+ policy.setOneOfValues(transformObjectIntoList("one_of", map.get("one_of")));
+ break;
+ case "subset_of":
+ policy.setSubsetOfValues(transformObjectIntoList("subset_of", map.get("subset_of")));
+ break;
+ case "superset_of":
+ policy.setSupersetOfValues(transformObjectIntoList("superset_of", map.get("superset_of")));
+ break;
+ default:
+ policy.setCustomOperator(key, map.get(key));
+ break;
+ }
+ }
+ } else {
+ log.debug("No map object could be parsed from the input, leaving the policy empty");
+ }
+ return policy;
+ }
+
+ /**
+ * Transforms the given value into a list of objects.
+ *
+ * @param id the key for the map of objects
+ * @param object the object value
+ * @return the value for the key as list or null
+ * @throws IOException if a non-null value could not be transformed into a list or the list contained null elements
+ */
+ @Nullable private List<Object> transformObjectIntoList(@Nonnull final String id,
+ @Nullable final Object object) throws IOException {
+ if (object instanceof List<?> list) {
+ final List<Object> result = list.stream().map(Object.class::cast).toList();
+ if (result.contains(null)) {
+ throw new IOException("The list value '" + object + "' for '" + id + "' contains null elements");
+ }
+ return result;
+ } else if (object != null) {
+ throw new IOException("The value '" + object + "' for '" + id + "' is not a list");
+ }
+ return null;
+ }
+
+}
\ No newline at end of file
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEnforcer.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEnforcer.java
index 5d96c1fa..b94af0c7 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEnforcer.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEnforcer.java
@@ -15,11 +15,11 @@
package net.shibboleth.oidc.metadata.policy.impl;
import java.util.ArrayList;
-import java.util.Collection;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.function.BiFunction;
-import java.util.regex.Pattern;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
@@ -27,34 +27,28 @@ import javax.annotation.Nullable;
import org.slf4j.Logger;
import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.oidc.metadata.policy.MetadataPolicyOperator;
+import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
import net.shibboleth.shared.collection.CollectionSupport;
import net.shibboleth.shared.collection.Pair;
import net.shibboleth.shared.component.AbstractInitializableComponent;
+import net.shibboleth.shared.component.ComponentInitializationException;
import net.shibboleth.shared.logic.Constraint;
import net.shibboleth.shared.logic.ConstraintViolationException;
+import net.shibboleth.shared.primitive.DeprecationSupport;
import net.shibboleth.shared.primitive.LoggerFactory;
+import net.shibboleth.shared.primitive.DeprecationSupport.ObjectType;
/**
* <p>A function that applies the given {@link MetadataPolicy} to the given object. The input is given as a {@link
- * Pair} of the object and the policy. The policy is applied to the incoming object in the following way, as specified
- * in the OIDC federation federation specification 1.0 (draft 17 / September 2021):</p>
- *
- * <ul>
- * <li>If there is a value operator in the policy, apply that and you are done.</li>
- * <li>Add whatever value is specified in an add operator.</li>
- * <li>If the parameter still has no value apply the default if there is one.</li>
- * <li>Do the essential check. If essential is missing as an operator essential is to be treated as if set to false.
- * If essential is defined to be true, then the claim MUST have a value by now. Otherwise applying the operator MUST
- * fail.</li>
- * <li>Do the other checks. Verified that the value is one_of or that the values are subset_of/superset_of. If the
- * parameter values do not fall within the allowed boundaries, applying the operator MUST fail.</li>
- * </ul>
- *
- * <p>In addition to the checks above, we also support regular expression validation.</p>
+ * Pair} of the object and the policy. The policy is applied to the incoming object by the configurable list of
+ * {@link MetadataPolicyOperator}s, in the provided order.</p>
*
* <p>The function returns a {@link Pair} of the object for which the value modifiers of the metadata policy have
* been applied to, and a flag indicating if the object was compatible with the value checks of the metadata policy.
- * </p>
+ * By default, the function indicates a failure if a policy operator that was not recognized by the configurable list
+ * of operators was included in the incoming policy. It can be modified via
+ * {@link #setFailureOnUnknownOperators(boolean)}</p>
*/
public class DefaultMetadataPolicyEnforcer extends AbstractInitializableComponent
implements BiFunction<Object,MetadataPolicy,Pair<Object,Boolean>> {
@@ -62,201 +56,91 @@ public class DefaultMetadataPolicyEnforcer extends AbstractInitializableComponen
/** Class logger. */
@Nonnull private final Logger log = LoggerFactory.getLogger(DefaultMetadataPolicyEnforcer.class);
- /** Map of custom metadata policy operators that are applied after the standard operators. */
- @Nonnull private Map<String, CustomMetadataPolicyOperator> customOperators;
+ /** The list of metadata policy operators used for enforcing the metadata policy. */
+ @NonnullAfterInit private List<MetadataPolicyOperator> operators;
+
+ /** The flag to indicate whether to consider unrecognized custom operator as a failure. */
+ private boolean failureOnUnknownOperators = true;
+
+ /**
+ * Set the map of custom metadata policy operators that are applied after the standard operators. They are
+ * applied after the standard operators excluding the essential operator. It is applied after the custom operators.
+ *
+ * @param map What to set
+ * @deprecated use {@link #setMetadataPolicyOperators(List)}
+ */
+ @Deprecated(since = "4.0.0", forRemoval = true)
+ public void setCustomMetadataPolicyOperators(@Nonnull final Map<String, CustomMetadataPolicyOperator> map) {
+ checkSetterPreconditions();
+ DeprecationSupport.warn(ObjectType.METHOD, "DefaultMetadataPolicyEnforcer.setCustomMetadataPolicyOperators",
+ null, "DefaultMetadataPolicyEnforcer.setMetadataPolicyOperators");
+ final List<MetadataPolicyOperator> list =
+ new ArrayList<>(MetadataPolicyHelper.standardMetadataPolicyOperatorsWithoutEssential());
+ Constraint.isNotNull(map, "Map of custom operators cannot be null").entrySet().stream()
+ .forEach(entry -> list.add(entry.getValue()));
+ list.add(new DefaultMetadataPolicyEssentialOperator());
+ operators = CollectionSupport.copyToList(list);
+ }
/**
- * Constructor.
+ * Set the list of metadata policy operators used for enforcing the metadata policy.
+ *
+ * @param policyOperators What to set
*/
- public DefaultMetadataPolicyEnforcer() {
- customOperators = CollectionSupport.emptyMap();
+ public void setMetadataPolicyOperators(@Nonnull final List<MetadataPolicyOperator> policyOperators) {
+ checkSetterPreconditions();
+ Constraint.isNotEmpty(policyOperators, "List of metadata policy operators cannot be empty");
+ assert policyOperators != null;
+ operators = policyOperators;
}
/**
- * Set the map of custom metadata policy operators that are applied after the standard operators.
- * @param operators What to set
+ * Set the flag to indicate whether to consider unrecognized custom operators as a failure.
+ *
+ * @param flag What to set
*/
- public void setCustomMetadataPolicyOperators(@Nonnull final Map<String, CustomMetadataPolicyOperator> operators) {
+ public void setFailureOnUnknownOperators(final boolean flag) {
checkSetterPreconditions();
- customOperators = Constraint.isNotNull(operators, "Map of custom operators cannot be null");
+ failureOnUnknownOperators = flag;
}
/** {@inheritDoc} */
- @Override
- @Nonnull public Pair<Object, Boolean> apply(@Nullable final Object candidate,
+ protected void doInitialize() throws ComponentInitializationException {
+ super.doInitialize();
+
+ if (operators == null) {
+ throw new ComponentInitializationException("List of metadata policy operators cannot be null");
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Override @Nonnull public Pair<Object, Boolean> apply(@Nullable final Object candidate,
@Nullable final MetadataPolicy policy) {
+ checkComponentActive();
if (policy == null) {
return new Pair<>(candidate, Boolean.TRUE);
}
- final Object value = policy.getValue();
- if (value != null) {
- return new Pair<>(value, Boolean.TRUE);
- }
- final Object result;
- final Object add = policy.getAdd();
-
- if (add != null) {
+ Object operatorResult = candidate;
+ final Set<String> appliedOperators = new HashSet<>();
+ for (final MetadataPolicyOperator operator : operators) {
try {
- result = applyAddOperator(candidate, add);
+ operatorResult = operator.apply(operatorResult, policy);
} catch (final ConstraintViolationException e) {
- log.warn("Could not add values to candidate: {}", e.getMessage());
- return new Pair<>(candidate, Boolean.FALSE);
+ log.debug("Operator {} returned a non-success result", operator.getClass(), e);
+ return new Pair<>(operatorResult, Boolean.FALSE);
}
- } else {
- result = candidate == null ? policy.getDefaultValue() : candidate;
+ appliedOperators.add(operator.getOperatorName());
}
-
- final boolean validation = doValueChecks(result, policy);
- return customOperators.isEmpty() || !validation
- ? new Pair<>(result, Boolean.valueOf(validation))
- : applyCustomOperators(result, policy);
- }
-
- /**
- * Applies the custom operators attached to this enforcer.
- *
- * @param initialResult The result after standard operators have been applied
- * @param policy The metadata policy to be applied to the initial result
- * @return a {@link Pair} as required to return by this enforcer function
- */
- @Nonnull protected Pair<Object, Boolean> applyCustomOperators(@Nullable final Object initialResult,
- @Nonnull final MetadataPolicy policy) {
- Object result = initialResult;
for (final String customOperator : policy.getCustomOperators().keySet()) {
- if (customOperators.containsKey(customOperator)) {
- try {
- result = customOperators.get(customOperator).apply(result, policy);
- } catch (final ConstraintViolationException e) {
- log.debug("The custom operator {} did not accept the value {}", customOperator, result, e);
- return new Pair<>(result, Boolean.FALSE);
- }
- } else {
- log.warn("The custom operator {} is not configured for this enforcer", customOperator);
- return new Pair<>(result, Boolean.FALSE);
- }
- }
- return new Pair<>(result, Boolean.TRUE);
- }
-
- /**
- * Applies the given add value modifier for the given candidate and returns the result of the operation.
- *
- * @param candidate The candidate for which the add operation is applied.
- * @param add The value(s) to be added to the claim.
- * @return An object containing the candidate for which the add operation has been applied.
- * @throws ConstraintViolationException If the add operator is not compliant with the given candidate.
- */
- @Nonnull protected Object applyAddOperator(@Nullable final Object candidate, @Nonnull final Object add)
- throws ConstraintViolationException {
- if (candidate != null) {
- if (candidate instanceof List) {
- final List<Object> list = new ArrayList<>((List<?>)candidate);
- if (add instanceof Collection) {
- list.addAll((Collection<?>) add);
- } else {
- list.add(add);
- }
- return list;
- } else {
- if (add instanceof Collection) {
- final Collection<?> collection = (Collection<?>) add;
- if (collection.size() > 1 || !collection.contains(candidate)) {
- throw new ConstraintViolationException("The array-values in add (" + add +
- ") not compliant with the single existing value " + candidate);
- }
- }
- if (!add.equals(candidate)) {
- throw new ConstraintViolationException("The single-value in add (" + add +
- ") does not match with the single existing value " + candidate);
- }
- return candidate;
- }
- }
- if (add instanceof Collection) {
- return CollectionSupport.copyToList((Collection<?>) add);
- }
- return add;
- }
-
- // Checkstyle: MethodLength|CyclomaticComplexity OFF
- /**
- * Runs the value check operators for the candidate.
- *
- * @param candidate The candidate to be verified.
- * @param policy The metadata policy whose value check operators are used.
- * @return true if the candidate is compliant with the metadata policy, false otherwise.
- */
- protected boolean doValueChecks(@Nullable final Object candidate, @Nonnull final MetadataPolicy policy) {
- boolean validation = true;
-
- if (candidate != null) {
- final List<Object> oneOfValues = policy.getOneOfValues();
- if (oneOfValues != null) {
- if (candidate instanceof List) {
- final List<?> list = (List<?>) candidate;
- if (list.size() > 1) {
- log.warn("The candidate {} contains multiple values, not compatible with one_of", candidate);
- validation = false;
- } else {
- if (!MetadataPolicyHelper.isSubsetOfValues(candidate, oneOfValues)) {
- log.warn("The candidate {} is not compatible with one_of {}", candidate, oneOfValues);
- validation = false;
- }
- }
- } else {
- if (!oneOfValues.contains(candidate)) {
- log.warn("The candidate {} does not contain a value required by one_of {}", candidate,
- oneOfValues);
- validation = false;
- }
- }
- }
- final List<Object> subsetOfValues = policy.getSubsetOfValues();
- if (subsetOfValues != null && !MetadataPolicyHelper.isSubsetOfValues(candidate, subsetOfValues)) {
- log.warn("The candidate {} is not a subset as required by subset_of {}", candidate, subsetOfValues);
- validation = false;
- }
- final List<Object> supersetOfValues = policy.getSupersetOfValues();
- if (supersetOfValues != null && !MetadataPolicyHelper.isSupersetOfValues(candidate, supersetOfValues)) {
- log.warn("The candidate {} is not a superset as required by superset_of {}", candidate,
- supersetOfValues);
- validation = false;
- }
- if (!verifyRegexp(candidate, policy.getRegexp())) {
- validation = false;
- }
- } else {
- if (policy.isEssential()) {
- log.warn("No value even though essential is set to true");
- validation = false;
- }
- }
- return validation;
- }
- // Checkstyle: MethodLength|CyclomaticComplexity ON
- /**
- * Verifies that the given candidate meets the regular expression.
- *
- * @param candidate The candidate to be verified.
- * @param regexp The regular expression.
- * @return true if the candidate is compliant with regex, false otherwise.
- */
- protected boolean verifyRegexp(@Nonnull final Object candidate, @Nullable final String regexp) {
- if (regexp != null) {
- if (candidate instanceof List) {
- for (final Object item : (List<?>) candidate) {
- if (!Pattern.matches(regexp, item.toString())) {
- log.warn("One of candidate values {} does not match the regex {}", item, regexp);
- return false;
- }
- }
- } else {
- if (!Pattern.matches(regexp, candidate.toString())) {
- log.warn("The candidate value {} does not match the regex {}", candidate, regexp);
- return false;
+ if (!appliedOperators.contains(customOperator)) {
+ if (failureOnUnknownOperators) {
+ log.warn("Custom operator {} was not processed by the policy operators, rejecting the result",
+ customOperator);
+ return new Pair<>(operatorResult, Boolean.FALSE);
}
+ log.warn("Custom operator {} was not processed by the policy operators", customOperator);
}
}
- return true;
+ return new Pair<>(operatorResult, Boolean.TRUE);
}
}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEssentialOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEssentialOperator.java
new file mode 100644
index 00000000..3c9d720a
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEssentialOperator.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed 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.policy.impl;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+
+/**
+ * Default implementation for the 'essential' -operator.
+ *
+ * @since 4.0.0
+ */
+public class DefaultMetadataPolicyEssentialOperator extends AbstractFederationMetadataPolicyOperator {
+
+ /** {@inheritDoc} */
+ @Nonnull @NotEmpty public String getOperatorName() {
+ return "essential";
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Nullable public Object apply(@Nullable final Object candidate, @Nonnull final MetadataPolicy policy)
+ throws ConstraintViolationException {
+ if (candidate != null) {
+ return candidate;
+ }
+ if (policy.isEssential()) {
+ throw new ConstraintViolationException("Essential value is missing");
+ }
+ return candidate;
+ }
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyMergingStrategy.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyMergingStrategy.java
new file mode 100644
index 00000000..54a7d8a7
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyMergingStrategy.java
@@ -0,0 +1,155 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.BiFunction;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicyOperator;
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.shared.collection.Pair;
+import net.shibboleth.shared.component.AbstractIdentifiableInitializableComponent;
+import net.shibboleth.shared.component.ComponentInitializationException;
+import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+import net.shibboleth.shared.primitive.LoggerFactory;
+import net.shibboleth.shared.primitive.StringSupport;
+
+/**
+ * A function that merges two maps of metadata policies according to the rules specified in the OID federation 1.0 spec
+ * section 6.1. The function returns a pair of map of merged metadata policies and a boolean indicating if the merging
+ * operators in the policies were compliant.
+ *
+ * @since 4.0.0
+ */
+public class DefaultMetadataPolicyMergingStrategy extends AbstractIdentifiableInitializableComponent
+ implements BiFunction<Map<String, MetadataPolicy>, Map<String, MetadataPolicy>,
+ Pair<Map<String, MetadataPolicy>, Boolean>> {
+
+ /** Class logger. */
+ @Nonnull private final Logger log = LoggerFactory.getLogger(DefaultMetadataPolicyMergingStrategy.class);
+
+ /** The list of metadata policy operators used for enforcing the metadata policy. */
+ @NonnullAfterInit private List<MetadataPolicyOperator> operators;
+
+ /**
+ * Set the list of metadata policy operators used for merging the metadata policy.
+ *
+ * @param policyOperators What to set
+ */
+ public void setMetadataPolicyOperators(@Nonnull final List<MetadataPolicyOperator> policyOperators) {
+ checkSetterPreconditions();
+ Constraint.isNotEmpty(policyOperators, "List of metadata policy operators cannot be empty");
+ assert policyOperators != null;
+ operators = policyOperators;
+ }
+
+ /** {@inheritDoc} */
+ protected void doInitialize() throws ComponentInitializationException {
+ super.doInitialize();
+
+ if (operators == null) {
+ throw new ComponentInitializationException("List of metadata policy operators cannot be null");
+ }
+ }
+
+ /** {@inheritDoc} */
+ @Nonnull
+ public Pair<Map<String, MetadataPolicy>, Boolean> apply(@Nullable final Map<String,MetadataPolicy> firstMap,
+ @Nullable final Map<String,MetadataPolicy> secondMap) {
+ checkComponentActive();
+ if (firstMap == null && secondMap == null) {
+ return new Pair<>(null, Boolean.TRUE);
+ }
+ final Map<String,MetadataPolicy> first = firstMap != null ? firstMap : CollectionSupport.emptyMap();
+ final Map<String,MetadataPolicy> second = secondMap != null ? secondMap : CollectionSupport.emptyMap();
+ final Set<String> combinedKeys = Stream.concat(first.keySet().stream(),
+ second.keySet().stream()).collect(Collectors.toSet());
+ final Map<String, MetadataPolicy> result = new HashMap<>();
+ boolean valid = true;
+ for (final String key : combinedKeys) {
+ try {
+ if (StringSupport.trimOrNull(key) == null) {
+ log.warn("Null key in the metadata map of metadata policies");
+ valid = false;
+ continue;
+ }
+ assert key != null;
+ final MetadataPolicy firstPolicy = first.get(key);
+ final MetadataPolicy secondPolicy = second.get(key);
+ if (firstPolicy != null && !validatePolicy(firstPolicy, key, "first", true)) {
+ valid = false;
+ }
+ if (secondPolicy != null && !validatePolicy(secondPolicy, key, "second", true)) {
+ valid = false;
+ }
+ log.debug("Claim {}: Attempting to merge {} with {}", key, firstPolicy, secondPolicy);
+ final MetadataPolicy merged =
+ MetadataPolicyHelper.mergeMetadataPolicies(firstPolicy, secondPolicy);
+ log.debug("Claim {}: Merging result of {} with {}: {}", key, firstPolicy, secondPolicy, merged);
+ if (merged != null) {
+ result.put(key, merged);
+ if (!validatePolicy(merged, key, "merged", false)) {
+ valid = false;
+ }
+ }
+ } catch (final ConstraintViolationException e) {
+ log.warn("Claim {}: Incompatible metadata policies that cannot be merged: {}", key, e.getMessage());
+ valid = false;
+ }
+ }
+ return new Pair<>(CollectionSupport.copyToMap(result), Boolean.valueOf(valid));
+ }
+
+ /**
+ * Validates the given policy against the metadata policy operators and their standard combinations.
+ *
+ * @param policy metadata policy to be validated
+ * @param key the claim related to policy, exploited in logging
+ * @param indicator the indicator of policy, exploited in logging
+ * @param beforeMerging whether policy is before merging, exploited in logging
+ * @return true if valid, false otherwise with cause logged
+ */
+ protected boolean validatePolicy(@Nonnull final MetadataPolicy policy, @Nonnull final String key,
+ @Nonnull @NotEmpty final String indicator, final boolean beforeMerging) {
+ for (final MetadataPolicyOperator operator : operators) {
+ if (!operator.validate(policy)) {
+ log.warn("Claim {}: Operator {} is not valid for the {} policy {}{}", key, operator.getOperatorName(),
+ indicator, policy, beforeMerging ? " before merging" : "");
+ return false;
+ }
+ }
+ try {
+ MetadataPolicyHelper.verifyStandardCombinations(policy);
+ } catch (final ConstraintViolationException e) {
+ log.warn("Claim {}: Metadata policy combinations are not valid: {}", key, e.getMessage());
+ return false;
+ }
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyOneOfOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyOneOfOperator.java
new file mode 100644
index 00000000..805b080b
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyOneOfOperator.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.util.List;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+import net.shibboleth.shared.primitive.LoggerFactory;
+
+/**
+ * Default implementation for the 'one_of' -operator.
+ *
+ * @since 4.0.0
+ */
+public class DefaultMetadataPolicyOneOfOperator extends AbstractFederationMetadataPolicyOperator {
+
+ /** Class logger. */
+ @Nonnull private final Logger log = LoggerFactory.getLogger(DefaultMetadataPolicyOneOfOperator.class);
+
+ /** {@inheritDoc} */
+ @Nonnull @NotEmpty public String getOperatorName() {
+ return "one_of";
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Nullable public Object apply(@Nullable final Object candidate, @Nonnull final MetadataPolicy policy)
+ throws ConstraintViolationException {
+ final List<Object> oneOf = policy.getOneOfValues();
+ if (candidate == null || oneOf == null) {
+ log.debug("No candidate or one_of value present. nothing to do");
+ return candidate;
+ }
+ if (candidate instanceof List<?>) {
+ throw new ConstraintViolationException(
+ "The candidate " + candidate + " is an array that cannot be used with one_of");
+ }
+ if (!oneOf.contains(candidate)) {
+ throw new ConstraintViolationException(
+ "The candidate " + candidate + " is not included in the values for one_of: " + oneOf);
+ }
+ return candidate;
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean validate(@Nonnull final MetadataPolicy policy) {
+ final List<Object> oneOf = policy.getOneOfValues();
+ if (oneOf == null) {
+ return true;
+ }
+ if (oneOf.isEmpty()) {
+ log.warn("One_of value cannot be an empty array");
+ return false;
+ }
+ for (final Object item : oneOf) {
+ if (item instanceof List<?>) {
+ log.warn("One_of array cannot contain an array item: {}", item);
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyOperator.java
index e5c0b711..406d0247 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyOperator.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyOperator.java
@@ -22,6 +22,7 @@ import javax.annotation.Nullable;
import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
import net.shibboleth.shared.component.AbstractInitializableComponent;
import net.shibboleth.shared.component.ComponentInitializationException;
import net.shibboleth.shared.logic.Constraint;
@@ -33,7 +34,8 @@ import net.shibboleth.shared.logic.ConstraintViolationException;
*
* @since 3.1.0
*/
-public class DefaultMetadataPolicyOperator extends AbstractInitializableComponent implements CustomMetadataPolicyOperator {
+public class DefaultMetadataPolicyOperator extends AbstractInitializableComponent
+ implements CustomMetadataPolicyOperator {
/** The metadata policy validator. */
@NonnullAfterInit private Predicate<MetadataPolicy> validator;
@@ -41,6 +43,9 @@ public class DefaultMetadataPolicyOperator extends AbstractInitializableComponen
/** The metadata policy operator. */
@NonnullAfterInit private BiFunction<Object, MetadataPolicy, Object> valueOperator;
+ /** The operator name. */
+ @NonnullAfterInit private String operatorName;
+
/**
* Set the metadata policy validator.
*
@@ -61,6 +66,17 @@ public class DefaultMetadataPolicyOperator extends AbstractInitializableComponen
valueOperator = Constraint.isNotNull(function, "The value operator cannot be null");
}
+ /**
+ * Set the operator name.
+ *
+ * @param name What to set.
+ */
+ public void setOperatorName(@Nonnull @NotEmpty final String name) {
+ checkSetterPreconditions();
+ operatorName = Constraint.isNotEmpty(name, "The operator name cannot be empty");
+ }
+
+ /** {@inheritDoc} */
@Override
public void doInitialize() throws ComponentInitializationException {
if (validator == null) {
@@ -69,17 +85,30 @@ public class DefaultMetadataPolicyOperator extends AbstractInitializableComponen
if (valueOperator == null) {
throw new ComponentInitializationException("The value operator cannot be null");
}
+ if (operatorName == null) {
+ throw new ComponentInitializationException("The operator name cannot be null");
+ }
}
+ /** {@inheritDoc} */
@Override
public boolean validate(@Nullable final MetadataPolicy policy) {
return validator.test(policy);
}
+ /** {@inheritDoc} */
@Override
public Object apply(@Nullable final Object inputValue, @Nullable final MetadataPolicy policy)
throws ConstraintViolationException {
return valueOperator.apply(inputValue, policy);
}
+ /** {@inheritDoc} */
+ @Override @Nonnull @NotEmpty
+ public String getOperatorName() {
+ checkComponentActive();
+ assert operatorName != null;
+ return operatorName;
+ }
+
}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicySubsetOfOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicySubsetOfOperator.java
new file mode 100644
index 00000000..3ef3c324
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicySubsetOfOperator.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.util.List;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+import net.shibboleth.shared.primitive.LoggerFactory;
+
+/**
+ * Default implementation for the 'subset_of' -operator.
+ *
+ * @since 4.0.0
+ */
+public class DefaultMetadataPolicySubsetOfOperator extends AbstractFederationMetadataPolicyOperator {
+
+ /** Class logger. */
+ @Nonnull private final Logger log = LoggerFactory.getLogger(DefaultMetadataPolicySubsetOfOperator.class);
+
+ /** {@inheritDoc} */
+ @Nonnull @NotEmpty public String getOperatorName() {
+ return "subset_of";
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Nullable public Object apply(@Nullable final Object candidate, @Nonnull final MetadataPolicy policy)
+ throws ConstraintViolationException {
+ final List<Object> subsetOf = policy.getSubsetOfValues();
+ if (candidate == null || subsetOf == null) {
+ log.debug("No candidate or subset_of value present. nothing to do");
+ return candidate;
+ }
+ if (candidate instanceof List<?> list) {
+ final List<Object> candidateList = list.stream()
+ .filter(Object.class::isInstance)
+ .map(Object.class::cast)
+ .filter(item -> subsetOf.contains(item))
+ .toList();
+ assert candidateList != null;
+ return CollectionSupport.copyToList(candidateList);
+ }
+ log.debug("Candidate value {} is not a list/array", candidate);
+ throw new ConstraintViolationException("Candidate value " + candidate + " is not a list/array");
+ }
+
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicySupersetOfOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicySupersetOfOperator.java
new file mode 100644
index 00000000..9547f7a8
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicySupersetOfOperator.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.util.List;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+import net.shibboleth.shared.primitive.LoggerFactory;
+
+/**
+ * Default implementation for the 'superset_of' -operator.
+ *
+ * @since 4.0.0
+ */
+public class DefaultMetadataPolicySupersetOfOperator extends AbstractFederationMetadataPolicyOperator {
+
+ /** Class logger. */
+ @Nonnull private final Logger log = LoggerFactory.getLogger(DefaultMetadataPolicySupersetOfOperator.class);
+
+ /** {@inheritDoc} */
+ @Nonnull @NotEmpty public String getOperatorName() {
+ return "superset_of";
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Nullable public Object apply(@Nullable final Object candidate, @Nonnull final MetadataPolicy policy)
+ throws ConstraintViolationException {
+ final List<Object> supersetOf = policy.getSupersetOfValues();
+ if (candidate == null || supersetOf == null) {
+ return candidate;
+ }
+ final List<Object> candidateList;
+ if (candidate instanceof List<?> list) {
+ candidateList = list.stream().filter(Object.class::isInstance).map(Object.class::cast).toList();
+ } else {
+ log.warn("The value for superset_of is not a list/array {}", candidate);
+ throw new ConstraintViolationException("Candidate value " + candidate + " is not a list/array");
+ }
+ assert candidateList != null;
+
+ if (!candidateList.containsAll(supersetOf)) {
+ log.debug("The candidate {} did not contain all the values of superset_of: {}", candidate, supersetOf);
+ throw new ConstraintViolationException(
+ "Candidate value " + candidate + " did not contain all values of superset_of: " + supersetOf);
+ }
+
+ return CollectionSupport.copyToList(candidateList);
+ }
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValidator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValidator.java
index 1d4a345c..1fe14246 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValidator.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValidator.java
@@ -14,8 +14,11 @@
package net.shibboleth.oidc.metadata.policy.impl;
+import java.util.ArrayList;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
@@ -24,43 +27,27 @@ import javax.annotation.Nullable;
import org.slf4j.Logger;
import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.oidc.metadata.policy.MetadataPolicyOperator;
+import net.shibboleth.shared.annotation.constraint.NonnullAfterInit;
import net.shibboleth.shared.collection.CollectionSupport;
-import net.shibboleth.shared.collection.Pair;
import net.shibboleth.shared.component.AbstractInitializableComponent;
+import net.shibboleth.shared.component.ComponentInitializationException;
import net.shibboleth.shared.logic.Constraint;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+import net.shibboleth.shared.primitive.DeprecationSupport;
import net.shibboleth.shared.primitive.LoggerFactory;
+import net.shibboleth.shared.primitive.DeprecationSupport.ObjectType;
/**
* <p>
* A function that verifies that the map of {@link MetadataPolicy} entries meets the restrictions defined in the
- * OIDC federation specification 1.0 (draft 17 / September 2021):
+ * configurable list of metadata policy operators.
* </p>
*
* <p>
* A policy entry can contain one or more operators. Not all operators are allowed to appear together in a policy
* entry.
* </p>
- *
- * <ul>
- * <li>subset_of and superset_of applies to parameters that can have more than one value (for instance, contacts)
- * while one_of applies to parameters that can only have one value (for instance, id_token_signed_response_alg). This
- * means that one_of cannot appear beside subset_of/ superset_of in a policy entry.</li>
- * <li>value overrides everything else. So having value together with any other operator (except for essential) does
- * not make sense.</li>
- * <li>If subset_of and superset_of both appear as operators, then the list of values in subset_of MUST be a superset
- * of the values in superset_of.<li>
- * <li>If add appears in a policy entry together with subset_of then the value/values of add MUST be a subset of
- * subset_of.<li>
- * <li>If add appears in a policy entry together with superset_of then the values of add MUST be a superset of
- * superset_of.<li>
- * <li>If default appears in a policy entry together with subset_of then the values of default MUST be a subset of
- * subset_of.<li>
- * <li>If default appears in a policy entry together with superset_of then the values of default MUST be a superset of
- * superset_of.<li>
- * <li>If add appears in a policy entry together with one_of then the value of add MUST be a member of one_of.<li>
- * <li>If default appears in a policy entry together with one_of then the value default MUST be a member of one_of.
- * </li>
- * </ul>
*/
public class DefaultMetadataPolicyValidator extends AbstractInitializableComponent
implements Predicate<Map<String, MetadataPolicy>> {
@@ -68,131 +55,106 @@ public class DefaultMetadataPolicyValidator extends AbstractInitializableCompone
/** Class logger. */
@Nonnull private final Logger log = LoggerFactory.getLogger(DefaultMetadataPolicyValidator.class);
- /** Map of custom metadata policy operators that are applied after the standard operators. */
- @Nonnull private Map<String, CustomMetadataPolicyOperator> customOperators;
+ /** The list of metadata policy operators used for validating the metadata policy. */
+ @NonnullAfterInit private List<MetadataPolicyOperator> operators;
+
+ /** The flag to indicate whether to consider unrecognized custom operator as a failure. */
+ private boolean failureOnUnknownOperators = true;
/**
- * Constructor.
+ * Set the map of custom metadata policy operators that are applied after the standard operators. They are
+ * applied after the standard operators excluding the essential operator. It is applied after the custom operators.
+ *
+ * @param map What to set
+ * @deprecated use {@link #setMetadataPolicyOperators(List)}
*/
- public DefaultMetadataPolicyValidator() {
- customOperators = CollectionSupport.emptyMap();
+ @Deprecated(since = "4.0.0", forRemoval = true)
+ public void setCustomMetadataPolicyOperators(@Nonnull final Map<String, CustomMetadataPolicyOperator> map) {
+ checkSetterPreconditions();
+ DeprecationSupport.warn(ObjectType.METHOD, "DefaultMetadataPolicyValidator.setCustomMetadataPolicyOperators",
+ null, "DefaultMetadataPolicyValidator.setMetadataPolicyOperators");
+ final List<MetadataPolicyOperator> list =
+ new ArrayList<>(MetadataPolicyHelper.standardMetadataPolicyOperatorsWithoutEssential());
+ Constraint.isNotNull(map, "Map of custom operators cannot be null").entrySet().stream()
+ .forEach(entry -> list.add(entry.getValue()));
+ list.add(new DefaultMetadataPolicyEssentialOperator());
+ operators = CollectionSupport.copyToList(list);
}
/**
- * Set the map of custom metadata policy operators that are applied after the standard operators.
- * @param operators What to set
+ * Set the list of metadata policy operators used for validating the metadata policy.
+ *
+ * @param policyOperators What to set
+ */
+ public void setMetadataPolicyOperators(@Nonnull final List<MetadataPolicyOperator> policyOperators) {
+ checkSetterPreconditions();
+ Constraint.isNotEmpty(policyOperators, "List of metadata policy operators cannot be empty");
+ assert policyOperators != null;
+ operators = policyOperators;
+ }
+
+ /**
+ * Set the flag to indicate whether to consider unrecognized custom operators as a failure.
+ *
+ * @param flag What to set
*/
- public void setCustomMetadataPolicyOperators(@Nonnull final Map<String, CustomMetadataPolicyOperator> operators) {
+ public void setFailureOnUnknownOperators(final boolean flag) {
checkSetterPreconditions();
- customOperators = Constraint.isNotNull(operators, "Map of custom operators cannot be null");
+ failureOnUnknownOperators = flag;
+ }
+
+ /** {@inheritDoc} */
+ protected void doInitialize() throws ComponentInitializationException {
+ super.doInitialize();
+
+ if (operators == null) {
+ throw new ComponentInitializationException("List of metadata policy operators cannot be null");
+ }
}
/** {@inheritDoc} */
- // Checkstyle: CyclomaticComplexity OFF
@Override
public boolean test(@Nullable final Map<String, MetadataPolicy> map) {
+ checkComponentActive();
boolean result = true;
if (map == null || map.isEmpty()) {
return true;
}
for (final String claim : map.keySet()) {
final MetadataPolicy policy = map.get(claim);
- final List<Object> oneOfValues = policy.getOneOfValues();
- final List<Object> subsetOfValues = policy.getSubsetOfValues();
- final List<Object> supersetOfValues = policy.getSupersetOfValues();
- if ((subsetOfValues != null || supersetOfValues != null) && oneOfValues != null) {
- log.warn("Claim {}: one_of cannot be set when superset_of and/or subset_of is set", claim);
- result = false;
+ if (policy == null) {
+ log.warn("Null metadata policy found for claim {}, map is not valid", claim);
+ return false;
}
-
- final Object value = policy.getValue();
- final Object add = policy.getAdd();
- final Object defaultValue = policy.getDefaultValue();
- final String regexp = policy.getRegexp();
-
- if (value != null) {
- if (add != null || defaultValue != null || oneOfValues != null || regexp != null
- || subsetOfValues != null || supersetOfValues != null) {
- log.warn("Claim {}: value is set together with modifiers or value checks (other than essential)",
- claim);
+ final Set<String> appliedOperators = new HashSet<>();
+ for (final MetadataPolicyOperator operator : operators) {
+ if (!operator.validate(policy)) {
+ log.warn("Metadata policy operator {} validation failed for policy {}", operator.getOperatorName(),
+ policy);
result = false;
}
- }
- if (supersetOfValues != null && subsetOfValues != null) {
- if (!subsetOfValues.containsAll(supersetOfValues)) {
- log.warn("Claim {}: subset_of and superset_of set, but subset_of is not a superset of superset_of",
- claim);
- result = false;
- }
- }
-
- if (!verifyValue(claim, new Pair<>("add", add), subsetOfValues, supersetOfValues, oneOfValues)) {
- result = false;
+ appliedOperators.add(operator.getOperatorName());
}
- if (!verifyValue(claim, new Pair<>("default", defaultValue), subsetOfValues, supersetOfValues,
- oneOfValues)) {
+ try {
+ MetadataPolicyHelper.verifyStandardCombinations(policy);
+ } catch (final ConstraintViolationException e) {
+ log.warn("Metadata policy for claim {} did not pass the standard combination verification: {}", claim,
+ e.getMessage());
result = false;
}
-
- if (!policy.getCustomOperators().isEmpty()) {
- for (final String operatorName : policy.getCustomOperators().keySet()) {
- final CustomMetadataPolicyOperator customOperator = customOperators.get(operatorName);
- if (customOperator == null) {
- log.warn("Claim {}: could not find a custom operator {}", claim, operatorName);
- result = false;
- } else if (!customOperator.validate(policy)) {
- log.warn("Claimn {}: policy is not compatible with the custom operator {}", claim, operatorName);
+ for (final String customOperator : policy.getCustomOperators().keySet()) {
+ if (!appliedOperators.contains(customOperator)) {
+ if (failureOnUnknownOperators) {
+ log.warn("Custom operator {} was not processed by the policy operators, returning false",
+ customOperator);
result = false;
+ } else {
+ log.warn("Custom operator {} was not processed by the policy operators", customOperator);
}
}
}
}
return result;
}
- // Checkstyle: CyclomaticComplexity ON
-
- /**
- * <p>
- * Verifies the value against the following rules:
- * </p>
- *
- * <ul>
- * <li>If it appears in a policy entry together with subset_of then the value/values of add MUST be a subset of
- * subset_of.</li>
- * <li>If it appears in a policy entry together with superset_of then the values of add MUST be a superset of
- * superset_of.</li>
- * <li>If it appears in a policy entry together with one_of then the value of add MUST be a member of one_of.</li>
- * </ul>
- *
- * @param claim The claim whose metadata policy is being verified, used in logging.
- * @param value The value to be verified against the rules.
- * @param subsetOfValues The contents of subset_of.
- * @param supersetOfValues The contents of superset_of.
- * @param oneOfValues The contents of one_of.
- * @return true if the value meets the rules, false otherwise.
- */
- protected boolean verifyValue(final String claim, final Pair<String, Object> value,
- final List<Object> subsetOfValues, final List<Object> supersetOfValues, final List<Object> oneOfValues) {
- boolean result = true;
- final String valueId = value.getFirst();
- final Object valueObject = value.getSecond();
- if (valueObject != null) {
- if (subsetOfValues != null && !MetadataPolicyHelper.isSubsetOfValues(valueObject, subsetOfValues)) {
- log.warn("Claim {}: {} contains values that are not subset of values in subset_of", claim, valueId);
- result = false;
- }
- if (supersetOfValues != null && !MetadataPolicyHelper.isSupersetOfValues(valueObject, supersetOfValues)) {
- log.warn("Claim {}: {} contains values that are not superset of values in superset_of", claim,
- valueId);
- result = false;
- }
- if (oneOfValues != null && !oneOfValues.contains(valueObject)) {
- log.warn("Claim {}: {} contains value that is not included in one_of", claim, valueId);
- result = false;
- }
- }
- return result;
- }
-
}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValueOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValueOperator.java
new file mode 100644
index 00000000..5ac76ad3
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValueOperator.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.util.Optional;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+
+/**
+ * Default implementation for the 'value' -operator.
+ *
+ * @since 4.0.0
+ */
+public class DefaultMetadataPolicyValueOperator extends AbstractFederationMetadataPolicyOperator {
+
+ /** {@inheritDoc} */
+ @Nonnull @NotEmpty public String getOperatorName() {
+ return "value";
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @Nullable public Object apply(@Nullable final Object candidate, @Nonnull final MetadataPolicy policy)
+ throws ConstraintViolationException {
+ final Object value = policy.getValue();
+ return value != null ? value instanceof Optional optional && optional.isEmpty() ? null : value : candidate;
+ }
+
+}
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/MetadataPolicyHelper.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/MetadataPolicyHelper.java
index 72718fc6..ae058da0 100644
--- a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/MetadataPolicyHelper.java
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/MetadataPolicyHelper.java
@@ -20,12 +20,17 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
+import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.oidc.metadata.policy.MetadataPolicyOperator;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.collection.CollectionSupport;
import net.shibboleth.shared.logic.ConstraintViolationException;
/**
@@ -43,32 +48,32 @@ public final class MetadataPolicyHelper {
/**
* Checks if the given candidate is a superset of the given values.
*
- * @param candidate The candidate to be checked. May not be null.
+ * @param candidate The candidate to be checked, expected to be a collection.
* @param values The values to be checked. May not be null.
- * @return true if the candidate is a superset of the values or they are equal, false otherwise.
+ * @return true if the candidate is a superset of the values or the values match, false otherwise.
*/
public static boolean isSupersetOfValues(@Nonnull final Object candidate, @Nonnull final Collection<?> values) {
return candidate instanceof Collection
? ((Collection<?>) candidate).containsAll(values)
- : values.size() == 1 && values.contains(candidate);
+ : false;
}
/**
* Checks if the given candiate is a subset of the given values.
*
- * @param candidate The candidate to be checked. May not be null.
+ * @param candidate The candidate to be checked, expected to be a collection.
* @param values The values to be checked. May not be null.
- * @return true if the candidate is a subset of the values or they are equal, false otherwise.
+ * @return true if the candidate is a subset of the values or the values match, false otherwise.
*/
public static boolean isSubsetOfValues(@Nonnull final Object candidate, @Nonnull final Collection<?> values) {
return candidate instanceof Collection
? values.containsAll((Collection<?>) candidate)
- : values.contains(candidate);
+ : false;
}
// Checkstyle: CyclomaticComplexity OFF
/**
- * <p>Merges two metadata policies with the rules defined in the OIDC federation spec 5.1.3.1:</p>
+ * <p>Merges two metadata policies with the rules defined in the OID Federation 1.0 spec 6.1.3.1:</p>
* <ul>
* <li>
* subset_of: The result of merging the values of two subset_of operators is the intersection of the operator
@@ -96,14 +101,14 @@ public final class MetadataPolicyHelper {
* </li>
* </ul>
*
- * <p>In addition to the list above, 'regex' operator and all custom operators are treated in the same way as
- * 'value' and 'default'.</p>
+ * <p>In addition to the list above, all custom operators are treated in the same way as value' and 'default'.</p>
*
* @param superior The superior metadata policy.
* @param subordinate The subordinate metadata policy.
* @return The merged metadata policy.
* @throws ConstraintViolationException If two 'value' or 'default' operators with different values are attempted
- * to be merged.
+ * to be merged, merging of 'one_of' produces an empty intersection or non-equal custom operators are attempted to
+ * be merged.
*/
@Nullable public static MetadataPolicy mergeMetadataPolicies(@Nullable final MetadataPolicy superior,
@Nullable final MetadataPolicy subordinate) throws ConstraintViolationException {
@@ -130,14 +135,11 @@ public final class MetadataPolicyHelper {
}
}
- final String regexp;
- try {
- regexp = (String) doMergeForTwoObjects(superior.getRegexp(), subordinate.getRegexp(), false);
- } catch (final ConstraintViolationException e) {
+ final List<Object> oneOf = doMergeForTwoLists(superior.getOneOfValues(), subordinate.getOneOfValues(), false);
+ if (oneOf != null && oneOf.isEmpty()) {
throw new ConstraintViolationException(
- "Merging two regexp operators is NOT allowed unless the two operator values are equal.");
+ "Merging of two one_of operators cannot produce an empty intersection");
}
-
for (final String customOperator : superior.getCustomOperators().keySet()) {
if (subordinate.getCustomOperators().containsKey(customOperator)) {
final Object superiorValue = superior.getCustomOperators().get(customOperator);
@@ -161,10 +163,10 @@ public final class MetadataPolicyHelper {
.withAdd(doMergeForTwoObjects(superior.getAdd(), subordinate.getAdd(), true))
.withValue(value != null ? value : subordinate.getValue())
.withDefaultValue(defaultValue != null ? defaultValue : subordinate.getDefaultValue())
- .withEssential(superior.isEssential() ? Boolean.TRUE : subordinate.getEssential())
- .withRegexp(regexp);
+ .withEssential(superior.isEssential() ? Boolean.TRUE : subordinate.getEssential());
for (final String customOperator : customOperators.keySet()) {
+ assert customOperator != null;
builder.withCustomOperator(customOperator, customOperators.get(customOperator));
}
return builder.build();
@@ -220,11 +222,10 @@ public final class MetadataPolicyHelper {
* @param union Flag to indicate the use of union. Intersection is used if false.
* @return The merged value.
*/
- @SuppressWarnings("unchecked")
@Nullable private static List<Object> doMergeForTwoLists(@Nullable final List<?> superior,
@Nullable final List<?> subordinate, final boolean union) {
if (superior == null) {
- return (List<Object>) subordinate;
+ return subordinate == null ? null : subordinate.stream().map(Object.class::cast).toList();
}
if (subordinate == null) {
return List.copyOf(superior);
@@ -238,4 +239,192 @@ public final class MetadataPolicyHelper {
result.retainAll(subordinate);
return result;
}
+
+ /**
+ * Transforms a list into a space-separated string. Operation is done for non-null values if the given claim is
+ * included in the given list of claims that are to be transformed.
+ *
+ * @param arraysAsSpaceSeparatedList the list of claim names to be transformed
+ * @param claim the candidate claim
+ * @param value the candidate claim value
+ * @return the claim value transformed into a space-separated string if it met the requirements, or initial value
+ * if not
+ * @throws ConstraintViolationException if the non-null value to be transformed was not a list
+ *
+ * @since 4.0.0
+ */
+ @Nullable
+ public static Object transformListIntoSpaceSeparatedString(@Nonnull final List<String> arraysAsSpaceSeparatedList,
+ @Nonnull final String claim, @Nullable final Object value) throws ConstraintViolationException {
+ if (arraysAsSpaceSeparatedList.contains(claim)) {
+ if (value instanceof List<?> list) {
+ return list.stream()
+ .map(item -> String.valueOf(item))
+ .collect(Collectors.joining(" "));
+ } else if (value != null) {
+ throw new ConstraintViolationException(
+ "Unexpected value for claim " + claim + ": the value is not a List");
+ }
+ }
+ return value;
+ }
+
+ /**
+ * Transforms a space-separated string into a list. Operation is done for non-null values if the given claim is
+ * included in the given list of claims that are to be transformed.
+ *
+ * @param arraysAsSpaceSeparatedList the list of claim names to be transformed
+ * @param claim the candidate claim
+ * @param value the candidate claim value
+ * @return the claim value transformed into a list if it met the requirements, or initial value
+ * @throws ConstraintViolationException if the non-null value to be transformed was not a string
+ *
+ * @since 4.0.0
+ */
+ @Nullable
+ public static Object transformSpaceSeparatedStringIntoList(@Nonnull final List<String> arraysAsSpaceSeparatedList,
+ @Nonnull final String claim, @Nullable final Object value) throws ConstraintViolationException {
+ if (arraysAsSpaceSeparatedList.contains(claim)) {
+ if (value instanceof String string) {
+ return List.of(string.split(" ")).stream().filter(item -> !item.isEmpty()).toList();
+ } else if (value != null) {
+ throw new ConstraintViolationException(
+ "Unexpected value for claim " + claim + ": the value is not a String");
+ }
+ }
+ return value;
+ }
+
+ /**
+ * Returns the list of standard metadata policy operators specified in the OpenID Federation 1.0 specification.
+ *
+ * @return list of standard metadata policy operators
+ *
+ * @since 4.0.0
+ */
+ @Nonnull @NotEmpty public static List<MetadataPolicyOperator> standardMetadataPolicyOperators() {
+ final List<MetadataPolicyOperator> result = new ArrayList<>(standardMetadataPolicyOperatorsWithoutEssential());
+ result.add(new DefaultMetadataPolicyEssentialOperator());
+ return CollectionSupport.copyToList(result);
+ }
+
+ /**
+ * Returns the list of standard metadata policy operators specified in the OpenID Federation 1.0 specification,
+ * without the essential-operator. This is useful to be used the base list of operators before adding the custom
+ * operators and finally essential operator.
+ *
+ * @return list of standard metadata policy operators
+ *
+ * @since 4.0.0
+ */
+ @Nonnull @NotEmpty public static List<MetadataPolicyOperator> standardMetadataPolicyOperatorsWithoutEssential() {
+ return CollectionSupport.listOf(
+ new DefaultMetadataPolicyValueOperator(),
+ new DefaultMetadataPolicyAddOperator(),
+ new DefaultMetadataPolicyDefaultOperator(),
+ new DefaultMetadataPolicyOneOfOperator(),
+ new DefaultMetadataPolicySubsetOfOperator(),
+ new DefaultMetadataPolicySupersetOfOperator());
+ }
+
+ /**
+ * Verifies the given metadata policy against rules related to standard combinations specified in the OpenID
+ * Federation 1.0 section 6.1.3.1. An empty {@link Optional} is considered as explicitly set null value with the
+ * value operator.
+ *
+ * @param policy metadata policy to be verified
+ * @throws ConstraintViolationException if any standard rule is violated with the message describing the issue
+ */
+ public static void verifyStandardCombinations(@Nonnull final MetadataPolicy policy)
+ throws ConstraintViolationException {
+ final List<Object> add;
+
+ if (policy.getAdd() instanceof List<?> addList) {
+ add = addList.stream().map(Object.class::cast).toList();
+ } else if (policy.getAdd() != null){
+ throw new ConstraintViolationException("Add operator " + policy.getAdd() + " is not an array");
+ } else {
+ add = null;
+ }
+
+ final Object value = policy.getValue();
+ final Boolean essential = policy.isEssential();
+ final Object defaultValue = policy.getDefaultValue();
+ final List<Object> oneOf = policy.getOneOfValues();
+ final List<Object> supersetOf = policy.getSupersetOfValues();
+
+ if (value instanceof Optional optional && optional.isEmpty()) {
+ if (essential) {
+ throw new ConstraintViolationException("Value for the value operator is null and essential is true");
+ }
+ if (defaultValue != null) {
+ throw new ConstraintViolationException("Null value cannot be combined with non-empty default: "
+ + defaultValue);
+ }
+ if (add != null) {
+ throw new ConstraintViolationException("Null value cannot be combined with add: " + add);
+ }
+ if (oneOf != null) {
+ throw new ConstraintViolationException("Null value cannot be combined with one_of: " + oneOf);
+ }
+ if (supersetOf != null) {
+ throw new ConstraintViolationException("Null value cannot be combined with superset_of: " + supersetOf);
+ }
+ }
+
+ final List<Object> subsetOf = policy.getSubsetOfValues();
+
+ if (value != null && !(value instanceof Optional)) {
+ if (add != null) {
+ if (value instanceof List<?> valueList) {
+ if (!MetadataPolicyHelper.isSubsetOfValues(add, valueList)) {
+ throw new ConstraintViolationException("Add " + add + " is not a subset of value "
+ + valueList);
+ }
+ } else {
+ throw new ConstraintViolationException("Value " + value
+ + " is not an array and cannot be compared to add " + add);
+ }
+ }
+ if (oneOf != null && !oneOf.contains(value)) {
+ throw new ConstraintViolationException("Value " + value + " is not included in the one_of values "
+ + oneOf);
+ }
+ if (subsetOf != null && !MetadataPolicyHelper.isSubsetOfValues(value, subsetOf)) {
+ throw new ConstraintViolationException("Value " + value
+ + " is not included in the of subset_of values " + subsetOf);
+ }
+ if (supersetOf != null && !MetadataPolicyHelper.isSupersetOfValues(value, supersetOf)) {
+ throw new ConstraintViolationException("Value " + value
+ + " is not included in the of superset_of values " + supersetOf);
+ }
+ }
+
+ if (add != null && oneOf != null) {
+ throw new ConstraintViolationException("Add " + add + " one_of " + oneOf + " cannot be combined");
+ }
+
+ if (add != null && subsetOf != null) {
+ if (!MetadataPolicyHelper.isSubsetOfValues(add, subsetOf)) {
+ throw new ConstraintViolationException("Add " + add + " is not a subset of subset_of "
+ + subsetOf);
+ }
+ }
+
+ if (oneOf != null && subsetOf != null) {
+ throw new ConstraintViolationException("One_of " + oneOf + " cannot be combined with subset_of "
+ + subsetOf);
+ }
+ if (oneOf != null && supersetOf != null) {
+ throw new ConstraintViolationException("One_of " + oneOf + " cannot be combined with superset_of "
+ + supersetOf);
+ }
+
+ if (subsetOf != null && supersetOf != null) {
+ if (!MetadataPolicyHelper.isSupersetOfValues(subsetOf, supersetOf)) {
+ throw new ConstraintViolationException("Subset_of " + subsetOf + " is not a superset of superset_of "
+ + supersetOf);
+ }
+ }
+ }
}
\ No newline at end of file
diff --git a/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/RegexpMetadataPolicyOperator.java b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/RegexpMetadataPolicyOperator.java
new file mode 100644
index 00000000..1fafce24
--- /dev/null
+++ b/oidc-common-metadata-impl/src/main/java/net/shibboleth/oidc/metadata/policy/impl/RegexpMetadataPolicyOperator.java
@@ -0,0 +1,117 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.util.List;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.slf4j.Logger;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+import net.shibboleth.shared.component.AbstractIdentifiableInitializableComponent;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+import net.shibboleth.shared.primitive.LoggerFactory;
+import net.shibboleth.shared.primitive.StringSupport;
+
+/**
+ * Default implementation for the custom 'regexp'-operator.
+ *
+ * @since 4.0.0
+ */
+public class RegexpMetadataPolicyOperator extends AbstractIdentifiableInitializableComponent
+ implements CustomMetadataPolicyOperator {
+
+ /** The operator name to be used within {@link MetadataPolicy} custom operators. */
+ @Nonnull @NotEmpty public static final String REGEXP_OPERATOR_NAME = "regexp";
+
+ /** Class logger. */
+ @Nonnull private final Logger log = LoggerFactory.getLogger(RegexpMetadataPolicyOperator.class);
+
+ /** {@inheritDoc} */
+ @Override
+ public boolean validate(@Nonnull final MetadataPolicy policy) {
+ if (policy.getCustomOperators().containsKey(REGEXP_OPERATOR_NAME)) {
+ final Object rawValue = policy.getCustomOperators().get(REGEXP_OPERATOR_NAME);
+ if (rawValue instanceof String regexp) {
+ if (StringSupport.trimOrNull(regexp) == null) {
+ log.warn("No value found for the regexp: {}", regexp);
+ return false;
+ }
+ try {
+ Pattern.compile(regexp);
+ } catch (final PatternSyntaxException e) {
+ log.warn("The regexp {} syntax is not valid", regexp, e);
+ return false;
+ }
+ return true;
+ }
+ log.warn("The regexp {} is in unexpected format", rawValue);
+ return false;
+ }
+ return true;
+ }
+
+ /** {@inheritDoc} */
+ @Override @Nullable
+ public Object apply(@Nullable final Object candidate, @Nonnull final MetadataPolicy policy)
+ throws ConstraintViolationException {
+ if (policy.getCustomOperators().containsKey(REGEXP_OPERATOR_NAME)) {
+ final Object rawValue = policy.getCustomOperators().get(REGEXP_OPERATOR_NAME);
+ if (rawValue instanceof String regexp) {
+ if (StringSupport.trimOrNull(regexp) == null) {
+ throw new ConstraintViolationException("No value found for the regexp: " + regexp);
+ }
+ try {
+ final Pattern pattern = Pattern.compile(regexp);
+ if (candidate instanceof List<?> list) {
+ for (final Object item : list) {
+ if (item != null) {
+ if (!pattern.matcher(item.toString()).matches()) {
+ throw new ConstraintViolationException(
+ "The item " + item + " did not match the regexp " + regexp);
+ }
+ } else {
+ throw new ConstraintViolationException("Unexpected candidate list item value: " + item);
+ }
+ }
+ } else if (candidate != null){
+ if (!pattern.matcher(candidate.toString()).matches()) {
+ throw new ConstraintViolationException(
+ "The item " + candidate + " did not match the regexp " + regexp);
+ }
+ }
+ } catch (final PatternSyntaxException e) {
+ log.warn("The regexp {} syntax is not valid", regexp, e);
+ throw new ConstraintViolationException("Invalid regexp syntax " + regexp);
+ }
+ } else {
+ throw new ConstraintViolationException("Unexpected regexp value " + rawValue);
+ }
+ }
+ return candidate;
+ }
+
+ /** {@inheritDoc} */
+ @Override @Nonnull @NotEmpty
+ public String getOperatorName() {
+ return REGEXP_OPERATOR_NAME;
+ }
+
+}
diff --git a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/BeanMetadataPolicyOperatorTest.java b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/BeanMetadataPolicyOperatorTest.java
index 68844edb..eb1da35b 100644
--- a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/BeanMetadataPolicyOperatorTest.java
+++ b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/BeanMetadataPolicyOperatorTest.java
@@ -151,7 +151,12 @@ public class BeanMetadataPolicyOperatorTest {
public boolean validate(@Nonnull final MetadataPolicy policy) {
return true;
}
- };
+
+ @Override
+ public String getOperatorName() {
+ return "mock";
+ }
+};
}
protected CustomMetadataPolicyOperator alwaysInvalidOperator() {
@@ -167,7 +172,12 @@ public class BeanMetadataPolicyOperatorTest {
public boolean validate(@Nonnull final MetadataPolicy policy) {
return false;
}
- };
+
+ @Override
+ public String getOperatorName() {
+ return "mock";
+ }
+};
}
protected CustomMetadataPolicyOperator alwaysChangedOperator() {
@@ -183,7 +193,12 @@ public class BeanMetadataPolicyOperatorTest {
public boolean validate(@Nonnull final MetadataPolicy policy) {
return true;
}
- };
+
+ @Override
+ public String getOperatorName() {
+ return "mock";
+ }
+};
}
protected CustomMetadataPolicyOperator alwaysFailingOperator() {
@@ -199,7 +214,12 @@ public class BeanMetadataPolicyOperatorTest {
public boolean validate(@Nonnull final MetadataPolicy policy) {
return true;
}
- };
+
+ @Override
+ public String getOperatorName() {
+ return "mock";
+ }
+};
}
@SuppressWarnings("serial")
diff --git a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEnforcerTest.java b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEnforcerTest.java
index dc2cb248..d7e7c7de 100644
--- a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEnforcerTest.java
+++ b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyEnforcerTest.java
@@ -14,6 +14,7 @@
package net.shibboleth.oidc.metadata.policy.impl;
+import java.util.ArrayList;
import java.util.List;
import org.mockito.Mockito;
@@ -22,8 +23,10 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.oidc.metadata.policy.MetadataPolicyOperator;
import net.shibboleth.shared.collection.CollectionSupport;
import net.shibboleth.shared.collection.Pair;
+import net.shibboleth.shared.component.ComponentInitializationException;
import net.shibboleth.shared.logic.ConstraintViolationException;
/**
@@ -35,8 +38,10 @@ public class DefaultMetadataPolicyEnforcerTest {
DefaultMetadataPolicyEnforcer applier;
@BeforeMethod
- public void init() {
+ public void init() throws ComponentInitializationException {
applier = new DefaultMetadataPolicyEnforcer();
+ applier.setMetadataPolicyOperators(MetadataPolicyHelper.standardMetadataPolicyOperators());
+ applier.initialize();
}
@Test
@@ -82,37 +87,35 @@ public class DefaultMetadataPolicyEnforcerTest {
@Test
public void apply_whenAddToNullCandidate_resultIsSameAsWithValue() {
final String stringValue = "mockValue";
- System.out.println("" + applier.apply(null, new MetadataPolicy.Builder()
- .withAdd(stringValue).build()));
Assert.assertEquals(
- applier.apply(null, new MetadataPolicy.Builder().withAdd(stringValue).build()),
- applier.apply(null, new MetadataPolicy.Builder().withValue(stringValue).build()));
+ applier.apply(null, new MetadataPolicy.Builder().withAdd(List.of(stringValue)).build()),
+ applier.apply(null, new MetadataPolicy.Builder().withValue(List.of(stringValue)).build()));
final List<String> listValue = List.of("value1", "value2");
Assert.assertEquals(
applier.apply(null, new MetadataPolicy.Builder().withAdd(listValue).build()),
applier.apply(null, new MetadataPolicy.Builder().withValue(listValue).build()));
final int intValue = 123;
Assert.assertEquals(
- applier.apply(null, new MetadataPolicy.Builder().withAdd(intValue).build()),
- applier.apply(null, new MetadataPolicy.Builder().withValue(intValue).build()));
+ applier.apply(null, new MetadataPolicy.Builder().withAdd(List.of(intValue)).build()),
+ applier.apply(null, new MetadataPolicy.Builder().withValue(List.of(intValue)).build()));
final boolean booleanValue = true;
Assert.assertEquals(
- applier.apply(null, new MetadataPolicy.Builder().withAdd(booleanValue).build()),
- applier.apply(null, new MetadataPolicy.Builder().withValue(booleanValue).build()));
+ applier.apply(null, new MetadataPolicy.Builder().withAdd(List.of(booleanValue)).build()),
+ applier.apply(null, new MetadataPolicy.Builder().withValue(List.of(booleanValue)).build()));
}
@Test
public void apply_whenAddToSameExistingCandidate_resultIsSameWithTrue() {
assertResultEquals(
- applier.apply("existing", new MetadataPolicy.Builder().withAdd("existing").build()),
- "existing");
+ applier.apply(List.of("existing"), new MetadataPolicy.Builder().withAdd(List.of("existing")).build()),
+ List.of("existing"));
assertResultEquals(
- applier.apply(123, new MetadataPolicy.Builder().withAdd(123).build()),
- 123);
+ applier.apply(List.of(123), new MetadataPolicy.Builder().withAdd(List.of(123)).build()),
+ List.of(123));
assertResultEquals(
- applier.apply(true, new MetadataPolicy.Builder().withAdd(true).build()),
- true);
+ applier.apply(List.of(true), new MetadataPolicy.Builder().withAdd(List.of(true)).build()),
+ List.of(true));
}
@Test
@@ -204,14 +207,6 @@ public class DefaultMetadataPolicyEnforcerTest {
applier.apply("existing", new MetadataPolicy.Builder().withOneOfValues(List.of("existing",
"another")).build()),
"existing");
- assertResultEquals(
- applier.apply(List.of("existing"), new MetadataPolicy.Builder().withOneOfValues(
- List.of("existing")).build()),
- List.of("existing"));
- assertResultEquals(
- applier.apply(List.of("existing"), new MetadataPolicy.Builder().withOneOfValues(
- List.of("existing", "another")).build()),
- List.of("existing"));
assertResultEquals(
applier.apply(123, new MetadataPolicy.Builder().withOneOfValues(List.of(123))
.build()),
@@ -220,14 +215,6 @@ public class DefaultMetadataPolicyEnforcerTest {
applier.apply(123, new MetadataPolicy.Builder().withOneOfValues(List.of(123, 321))
.build()),
123);
- assertResultEquals(
- applier.apply(List.of(123), new MetadataPolicy.Builder().withOneOfValues(List.of(123))
- .build()),
- List.of(123));
- assertResultEquals(
- applier.apply(List.of(123), new MetadataPolicy.Builder().withOneOfValues(List.of(123, 321))
- .build()),
- List.of(123));
assertResultEquals(
applier.apply(true, new MetadataPolicy.Builder().withOneOfValues(List.of(true))
.build()),
@@ -236,14 +223,6 @@ public class DefaultMetadataPolicyEnforcerTest {
applier.apply(true, new MetadataPolicy.Builder().withOneOfValues(List.of(true, false))
.build()),
true);
- assertResultEquals(
- applier.apply(List.of(true), new MetadataPolicy.Builder().withOneOfValues(List.of(true))
- .build()),
- List.of(true));
- assertResultEquals(
- applier.apply(List.of(true), new MetadataPolicy.Builder().withOneOfValues(List.of(true,
- false)).build()),
- List.of(true));
}
@Test
@@ -288,33 +267,6 @@ public class DefaultMetadataPolicyEnforcerTest {
@Test
public void apply_whenSubsetOfMeetsValue_resultIsCandidateWithTrue() {
- // single values
- assertResultEquals(
- applier.apply("existing", new MetadataPolicy.Builder().withSubsetOfValues(List.of(
- "existing")).build()),
- "existing");
- assertResultEquals(
- applier.apply("existing", new MetadataPolicy.Builder().withSubsetOfValues(List.of(
- "existing", "another")).build()),
- "existing");
- assertResultEquals(
- applier.apply(123, new MetadataPolicy.Builder().withSubsetOfValues(List.of(123))
- .build()),
- 123);
- assertResultEquals(
- applier.apply(123, new MetadataPolicy.Builder().withSubsetOfValues(List.of(123, 321))
- .build()),
- 123);
- assertResultEquals(
- applier.apply(true, new MetadataPolicy.Builder().withSubsetOfValues(List.of(true))
- .build()),
- true);
- assertResultEquals(
- applier.apply(true, new MetadataPolicy.Builder().withSubsetOfValues(List.of(true, false))
- .build()),
- true);
-
- // list of values
assertResultEquals(
applier.apply(List.of("existing", "another"),
new MetadataPolicy.Builder().withSubsetOfValues(List.of("existing", "another")).build()),
@@ -365,48 +317,35 @@ public class DefaultMetadataPolicyEnforcerTest {
.build()));
// list of values
- assertResultFalse(
+ assertResultEquals(
applier.apply(List.of("not"),
- new MetadataPolicy.Builder().withSubsetOfValues(List.of("existing", "another")).build()));
- assertResultFalse(
+ new MetadataPolicy.Builder().withSubsetOfValues(List.of("existing", "another")).build()),
+ CollectionSupport.emptyList());
+ assertResultEquals(
applier.apply(List.of("not", "neither"),
new MetadataPolicy.Builder().withSubsetOfValues(List.of(
- "existing", "another", "yet_another")).build()));
- assertResultFalse(
+ "existing", "another", "yet_another")).build()),
+ CollectionSupport.emptyList());
+ assertResultEquals(
applier.apply(List.of(123), new MetadataPolicy.Builder()
- .withSubsetOfValues(List.of(321, 432)).build()));
- assertResultFalse(
+ .withSubsetOfValues(List.of(321, 432)).build()),
+ CollectionSupport.emptyList());
+ assertResultEquals(
applier.apply(List.of(123, 321), new MetadataPolicy.Builder()
- .withSubsetOfValues(List.of(123, 213)).build()));
- assertResultFalse(
+ .withSubsetOfValues(List.of(123, 213)).build()),
+ CollectionSupport.listOf(123));
+ assertResultEquals(
applier.apply(List.of(true), new MetadataPolicy.Builder()
- .withSubsetOfValues(List.of(false)).build()));
- assertResultFalse(
+ .withSubsetOfValues(List.of(false)).build()),
+ CollectionSupport.emptyList());
+ assertResultEquals(
applier.apply(List.of(false), new MetadataPolicy.Builder()
- .withSubsetOfValues(List.of(true)).build()));
+ .withSubsetOfValues(List.of(true)).build()),
+ CollectionSupport.emptyList());
}
@Test
public void apply_whenSupersetOfMeetsValue_resultIsCandidateWithTrue() {
- // single values
- assertResultEquals(
- applier.apply("existing", new MetadataPolicy.Builder().withSupersetOfValues(List.of(
- "existing")).build()),
- "existing");
- assertResultEquals(
- applier.apply(123, new MetadataPolicy.Builder().withSupersetOfValues(List.of(123))
- .build()),
- 123);
- assertResultEquals(
- applier.apply(true, new MetadataPolicy.Builder().withSupersetOfValues(List.of(true))
- .build()),
- true);
- assertResultEquals(
- applier.apply(false, new MetadataPolicy.Builder().withSupersetOfValues(List.of(false))
- .build()),
- false);
-
- // list of values
assertResultEquals(
applier.apply(List.of("existing", "another"),
new MetadataPolicy.Builder().withSupersetOfValues(List.of("existing", "another")).build()),
@@ -479,60 +418,101 @@ public class DefaultMetadataPolicyEnforcerTest {
}
@Test
- public void apply_whenRegexMeetsValue_resultIsCandidateWithTrue() {
+ public void apply_whenRegexMeetsValue_resultIsCandidateWithTrue() throws ComponentInitializationException {
+ applier = new DefaultMetadataPolicyEnforcer();
+ applier.setMetadataPolicyOperators(standardOperatorsWithCustom(new RegexpMetadataPolicyOperator()));
+ applier.initialize();
final String candidate = "https://sub.example.org/cb";
assertResultEquals(applier.apply(candidate,
- new MetadataPolicy.Builder().withRegexp(".*").build()), candidate);
+ new MetadataPolicy.Builder().withCustomOperator("regexp", ".*").build()), candidate);
assertResultEquals(applier.apply(candidate,
- new MetadataPolicy.Builder().withRegexp("^https:\\/\\/(?:([^.]+)\\.)?example\\.org\\/(.*)").build()),
+ new MetadataPolicy.Builder()
+ .withCustomOperator("regexp", "^https:\\/\\/(?:([^.]+)\\.)?example\\.org\\/(.*)").build()),
candidate);
final List<String> candidates = List.of(candidate + "1", candidate + "2");
assertResultEquals(applier.apply(candidates,
- new MetadataPolicy.Builder().withRegexp("^https:\\/\\/(?:([^.]+)\\.)?example\\.org\\/(.*)").build()),
+ new MetadataPolicy.Builder()
+ .withCustomOperator("regexp","^https:\\/\\/(?:([^.]+)\\.)?example\\.org\\/(.*)").build()),
candidates);
}
@Test
- public void apply_whenRegexNotMeetingValue_resultIsFalse() {
+ public void apply_whenRegexNotMeetingValue_resultIsFalse() throws ComponentInitializationException {
+ applier = new DefaultMetadataPolicyEnforcer();
+ applier.setMetadataPolicyOperators(standardOperatorsWithCustom(new RegexpMetadataPolicyOperator()));
+ applier.initialize();
final String regex = "^https:\\/\\/(?:([^.]+)\\.)?example\\.org\\/(.*)";
assertResultFalse(applier.apply("http://example.org/cb",
- new MetadataPolicy.Builder().withRegexp(regex).build()));
+ new MetadataPolicy.Builder().withCustomOperator("regexp", regex).build()));
assertResultFalse(applier.apply("https://example.com/cb",
- new MetadataPolicy.Builder().withRegexp(regex).build()));
+ new MetadataPolicy.Builder().withCustomOperator("regexp", regex).build()));
assertResultFalse(applier.apply(List.of("https://sub.example.org/cb", "https://sub.example.com/cb"),
- new MetadataPolicy.Builder().withRegexp(regex).build()));
+ new MetadataPolicy.Builder().withCustomOperator("regexp", regex).build()));
}
@Test
- public void apply_whenCustomOperatorAcceptsValue_resultIsCandidateWithTrue() {
+ public void apply_whenCustomOperatorAcceptsValue_resultIsCandidateWithTrue() throws ComponentInitializationException {
final String candidate = "expectdValue";
final CustomMetadataPolicyOperator customOperator = Mockito.mock(CustomMetadataPolicyOperator.class);
Mockito.when(customOperator.apply(Mockito.any(), Mockito.any())).thenReturn(candidate);
- applier.setCustomMetadataPolicyOperators(CollectionSupport.singletonMap("customOperator", customOperator));
+ Mockito.when(customOperator.getOperatorName()).thenReturn("customOperator");
+ applier = new DefaultMetadataPolicyEnforcer();
+ applier.setMetadataPolicyOperators(standardOperatorsWithCustom(customOperator));
+ applier.initialize();
assertResultEquals(applier.apply(candidate,
new MetadataPolicy.Builder().withCustomOperator("customOperator", "mockId").build()), candidate);
}
@Test
- public void apply_whenCustomOperatorDoesNotAcceptValue_resultIsFalse() {
+ public void apply_whenCustomOperatorDoesNotAcceptValue_resultIsFalse() throws ComponentInitializationException {
final String candidate = "expectdValue";
final CustomMetadataPolicyOperator customOperator = Mockito.mock(CustomMetadataPolicyOperator.class);
Mockito.doThrow(ConstraintViolationException.class).when(customOperator).apply(Mockito.any(), Mockito.any());
- applier.setCustomMetadataPolicyOperators(CollectionSupport.singletonMap("customOperator", customOperator));
+ Mockito.when(customOperator.getOperatorName()).thenReturn("customOperator");
+ applier = new DefaultMetadataPolicyEnforcer();
+ applier.setMetadataPolicyOperators(standardOperatorsWithCustom(customOperator));
+ applier.initialize();
assertResultFalse(applier.apply(candidate,
new MetadataPolicy.Builder().withCustomOperator("customOperator", "mockId").build()));
}
@Test
- public void apply_whenCustomOperatorNotFound_resultIsFalse() {
+ public void apply_whenCustomOperatorNotFound_resultIsFalse() throws ComponentInitializationException {
final String candidate = "expectdValue";
final CustomMetadataPolicyOperator customOperator = Mockito.mock(CustomMetadataPolicyOperator.class);
- Mockito.doThrow(ConstraintViolationException.class).when(customOperator).apply(Mockito.any(), Mockito.any());
- applier.setCustomMetadataPolicyOperators(CollectionSupport.singletonMap("customOperator", customOperator));
+ Mockito.when(customOperator.apply(Mockito.any(), Mockito.any())).thenReturn(candidate);
+ Mockito.when(customOperator.getOperatorName()).thenReturn("customOperator");
+ applier = new DefaultMetadataPolicyEnforcer();
+ applier.setMetadataPolicyOperators(standardOperatorsWithCustom(customOperator));
+ applier.initialize();
assertResultFalse(applier.apply(candidate,
new MetadataPolicy.Builder().withCustomOperator("nonExistingOperator", "mockId").build()));
}
+ @Test
+ public void apply_whenCustomOperatorNotFoundButAllowed_resultIsCandidateWithTrue()
+ throws ComponentInitializationException {
+ final String candidate = "expectdValue";
+ final CustomMetadataPolicyOperator customOperator = Mockito.mock(CustomMetadataPolicyOperator.class);
+ Mockito.when(customOperator.apply(Mockito.any(), Mockito.any())).thenReturn(candidate);
+ Mockito.when(customOperator.getOperatorName()).thenReturn("customOperator");
+ applier = new DefaultMetadataPolicyEnforcer();
+ applier.setMetadataPolicyOperators(standardOperatorsWithCustom(customOperator));
+ applier.setFailureOnUnknownOperators(false);
+ applier.initialize();
+ assertResultEquals(applier.apply(candidate,
+ new MetadataPolicy.Builder().withCustomOperator("nonExistingOperator", "mockId").build()), candidate);
+ }
+
+ protected List<MetadataPolicyOperator> standardOperatorsWithCustom(final CustomMetadataPolicyOperator... custom) {
+ final List<MetadataPolicyOperator> operators =
+ new ArrayList<>(MetadataPolicyHelper.standardMetadataPolicyOperators());
+ for (final CustomMetadataPolicyOperator operator : custom) {
+ operators.add(operator);
+ }
+ return operators;
+ }
+
public static void assertResultEquals(final Pair<Object, Boolean> pair, final Object expected) {
final Boolean flag = pair.getSecond();
Assert.assertTrue(flag != null && flag);
diff --git a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValidatorTest.java b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValidatorTest.java
index 1abf00a9..baec729d 100644
--- a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValidatorTest.java
+++ b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/DefaultMetadataPolicyValidatorTest.java
@@ -14,8 +14,11 @@
package net.shibboleth.oidc.metadata.policy.impl;
+import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
import org.mockito.Mockito;
import org.testng.Assert;
@@ -23,7 +26,9 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.oidc.metadata.policy.MetadataPolicyOperator;
import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.shared.component.ComponentInitializationException;
/**
* Unit tests for {@link DefaultMetadataPolicyValidator}.
@@ -34,249 +39,358 @@ public class DefaultMetadataPolicyValidatorTest {
DefaultMetadataPolicyValidator validator;
@BeforeMethod
- public void init() {
+ public void init() throws ComponentInitializationException {
validator = new DefaultMetadataPolicyValidator();
- }
-
- @Test
- public void test_whenOneOfAndSupersetOfHaveBeenSet_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withOneOfValues(List.of("must"))
- .withSupersetOfValues(List.of("must"))
- .build());
- Assert.assertFalse(validator.test(map));
- }
-
- @Test
- public void test_whenOneOfAndSubsetOfHaveBeenSet_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withOneOfValues(List.of("must"))
- .withSubsetOfValues(List.of("must"))
- .build());
- Assert.assertFalse(validator.test(map));
- }
-
- @Test
- public void test_whenValueAndAddIsSet_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withValue("mockValue")
- .withAdd("another")
- .build());
- Assert.assertFalse(validator.test(map));
- }
-
- @Test
- public void test_whenValueAndDefaultSet_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withValue("mockValue")
- .withDefaultValue("mockValue")
- .build());
- Assert.assertFalse(validator.test(map));
+ validator.setMetadataPolicyOperators(MetadataPolicyHelper.standardMetadataPolicyOperators());
+ validator.initialize();
}
@Test
- public void test_whenValueAndOneOfSet_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withValue("mockValue")
- .withOneOfValues(List.of("mockValue"))
- .build());
- Assert.assertFalse(validator.test(map));
+ public void test_whenNullMap_shouldReturnTrue() {
+ Assert.assertTrue(validator.test(null));
}
@Test
- public void test_whenValueAndSubsetOfSet_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withValue("mockValue")
- .withSubsetOfValues(List.of("mockValue"))
- .build());
- Assert.assertFalse(validator.test(map));
+ public void test_whenEmptyMap_shouldReturnTrue() {
+ Assert.assertTrue(validator.test(CollectionSupport.emptyMap()));
}
@Test
- public void test_whenValueAndSupersetOfSet_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withValue("mockValue")
- .withSupersetOfValues(List.of("mockValue"))
- .build());
+ public void test_whenNullPolicy_shouldReturnFalse() {
+ final Map<String, MetadataPolicy> map = new HashMap<>();
+ map.put("mockClaim", null);
Assert.assertFalse(validator.test(map));
}
@Test
- public void test_whenValueAndRegexpSet_shouldReturnFalse() {
+ public void test_whenAddNotArray_shouldReturnFalse() {
final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withValue("mockValue")
- .withRegexp(".*")
+ .withAdd("notArray")
.build());
Assert.assertFalse(validator.test(map));
}
@Test
- public void test_whenValueAndEssentialSet_shouldReturnTrue() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withValue("mockValue")
+ public void test_whenEmptyOptionalValue_unallowedCombination_shouldReturnFalse() {
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(Optional.empty())
+ .withAdd(List.of("add"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(Optional.empty())
.withEssential(true)
- .build());
- Assert.assertTrue(validator.test(map));
- }
-
- @Test
- public void test_whenValueAndNonEssentialSet_shouldReturnTrue() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withValue("mockValue")
- .withEssential(false)
- .build());
- Assert.assertTrue(validator.test(map));
- }
-
-
- @Test
- public void test_whenSubsetAndSupersetOfSet_subsetOfNotBeingSuperset_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withSupersetOfValues(List.of("mockValue", "mockValue2"))
- .withSubsetOfValues(List.of("mockValue"))
- .build());
- Assert.assertFalse(validator.test(map));
- }
-
- @Test
- public void test_whenSubsetAndSupersetOfSet_subsetOfMatchingSupersetOf_shouldReturnTrue() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withSupersetOfValues(List.of("mockValue", "mockValue2"))
- .withSubsetOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertTrue(validator.test(map));
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(Optional.empty())
+ .withSupersetOfValues(List.of("value"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(Optional.empty())
+ .withDefaultValue("default")
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(Optional.empty())
+ .withOneOfValues(List.of("one_of"))
+ .build())));
}
@Test
- public void test_whenSubsetOfAndAdd_singleAddNotBeingInSubset_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withAdd("mockValue")
- .withSubsetOfValues(List.of("mockValue2", "mockValue3"))
- .build());
- Assert.assertFalse(validator.test(map));
+ public void test_whenEmptyOptionalValue_allowedCombination_shouldReturnTrue() {
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(Optional.empty())
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(Optional.empty())
+ .withSubsetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(Optional.empty())
+ .withDefaultValue(null)
+ .build())));
}
@Test
- public void test_whenSubsetOfAndAdd_listAddNotBeingInSubset_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withAdd(List.of("mockValue"))
- .withSubsetOfValues(List.of("mockValue2", "mockValue3"))
- .build());
- Assert.assertFalse(validator.test(map));
+ public void test_whenValue_allowedCombination_shouldReturnTrue() {
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withAdd(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "another"))
+ .withAdd(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withDefaultValue(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue("value")
+ .withDefaultValue("value")
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue("value")
+ .withOneOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue("value")
+ .withOneOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withSubsetOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withSubsetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "another"))
+ .withSupersetOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "another"))
+ .withSupersetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "another"))
+ .withEssential(true)
+ .build())));
}
@Test
- public void test_whenSupersetOfAndAdd_singleAddNotBeingInSuperset_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withAdd("mockValue")
- .withSupersetOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertFalse(validator.test(map));
+ public void test_whenValue_unallowedCombination_shouldReturnFalse() {
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withAdd(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue("problem")
+ .withOneOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue("value")
+ .withSubsetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "problem"))
+ .withSubsetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue("value")
+ .withSupersetOfValues(List.of("value"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "another"))
+ .withSupersetOfValues(List.of("value", "problem"))
+ .build())));
}
@Test
- public void test_whenSupersetOfAndAdd_listAddNotBeingInSuperset_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withAdd(List.of("mockValue"))
- .withSupersetOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertFalse(validator.test(map));
+ public void test_whenAdd_allowedCombination_shouldReturnTrue() {
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withAdd(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "another"))
+ .withAdd(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withAdd(List.of("value"))
+ .withDefaultValue(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withAdd(List.of("value"))
+ .withSubsetOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withAdd(List.of("value"))
+ .withSubsetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withAdd(List.of("value"))
+ .withSupersetOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withAdd(List.of("value"))
+ .withSupersetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withAdd(List.of("value"))
+ .withEssential(true)
+ .build())));
}
@Test
- public void test_whenSubsetOfAndDefault_singleDefaultNotBeingInSubset_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withDefaultValue("mockValue")
- .withSubsetOfValues(List.of("mockValue2", "mockValue3"))
- .build());
- Assert.assertFalse(validator.test(map));
+ public void test_whenAdd_unallowedCombination_shouldReturnFalse() {
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withAdd(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withAdd(List.of("value"))
+ .withOneOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withAdd(List.of("value", "problem"))
+ .withSubsetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withAdd(List.of("value", "problem"))
+ .withOneOfValues(List.of("value", "problem"))
+ .build())));
}
-
+
@Test
- public void test_whenSubsetOfAndDefault_listDefaultNotBeingInSubset_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withDefaultValue(List.of("mockValue"))
- .withSubsetOfValues(List.of("mockValue2", "mockValue3"))
- .build());
- Assert.assertFalse(validator.test(map));
+ public void test_whenOneOf_allowedCombination_shouldReturnTrue() {
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue("value")
+ .withOneOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue("value")
+ .withOneOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withOneOfValues(List.of("value"))
+ .withDefaultValue("value")
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withOneOfValues(List.of("value"))
+ .withEssential(true)
+ .build())));
}
@Test
- public void test_whenSupersetOfAndDefault_singleDefaultNotBeingInSuperset_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withDefaultValue("mockValue")
- .withSupersetOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertFalse(validator.test(map));
+ public void test_whenOneOf_unallowedCombination_shouldReturnFalse() {
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withOneOfValues(List.of(List.of("value")))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withOneOfValues(CollectionSupport.emptyList())
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withOneOfValues(List.of("value"))
+ .withAdd(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withOneOfValues(List.of("value"))
+ .withSubsetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withOneOfValues(List.of("value"))
+ .withSupersetOfValues(List.of("value"))
+ .build())));
}
@Test
- public void test_whenSupersetOfAndDefault_listDefaultNotBeingInSuperset_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withDefaultValue(List.of("mockValue"))
- .withSupersetOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertFalse(validator.test(map));
- }
-
- @Test
- public void test_whenOneOfAndAdd_singleAddInOneOf_shouldReturnTrue() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withAdd("mockValue")
- .withOneOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertTrue(validator.test(map));
-
- }
+ public void test_whenSubsetOf_allowedCombination_shouldReturnTrue() {
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withSubsetOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withSubsetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value"))
+ .withAdd(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value", "another"))
+ .withAdd(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value"))
+ .withDefaultValue("value")
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value"))
+ .withSupersetOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value", "another"))
+ .withSupersetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value"))
+ .withEssential(true)
+ .build())));
- @Test
- public void test_whenOneOfAndAdd_singleAddNotInOneOf_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withAdd("mockValue3")
- .withOneOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertFalse(validator.test(map));
-
}
@Test
- public void test_whenOneOfAndAdd_listAddInOneOf_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withAdd(List.of("mockValue"))
- .withOneOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertFalse(validator.test(map));
-
+ public void test_whenSubsetOf_unallowedCombination_shouldReturnFalse() {
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value"))
+ .withOneOfValues(List.of("value"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "problem"))
+ .withSubsetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value"))
+ .withAdd(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value", "another"))
+ .withSupersetOfValues(List.of("value", "problem"))
+ .build())));
}
@Test
- public void test_whenOneOfAndDefault_singleDefaultInOneOf_shouldReturnTrue() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withDefaultValue("mockValue")
- .withOneOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertTrue(validator.test(map));
-
- }
+ public void test_whenSupersetOf_allowedCombination_shouldReturnTrue() {
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value"))
+ .withSupersetOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "another"))
+ .withSupersetOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSupersetOfValues(List.of("value"))
+ .withAdd(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSupersetOfValues(List.of("value", "another"))
+ .withAdd(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSupersetOfValues(List.of("value"))
+ .withDefaultValue("value")
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value", "another"))
+ .withSupersetOfValues(List.of("value"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value", "another"))
+ .withSupersetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertTrue(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSupersetOfValues(List.of("value"))
+ .withEssential(true)
+ .build())));
- @Test
- public void test_whenOneOfAndDefault_singleDefaultNotInOneOf_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withDefaultValue("mockValue3")
- .withOneOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertFalse(validator.test(map));
-
}
@Test
- public void test_whenOneOfAndDefault_listDefaultInOneOf_shouldReturnFalse() {
- final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
- .withDefaultValue(List.of("mockValue"))
- .withOneOfValues(List.of("mockValue", "mockValue2"))
- .build());
- Assert.assertFalse(validator.test(map));
-
+ public void test_whenSupersetOf_unallowedCombination_shouldReturnFalse() {
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSupersetOfValues(List.of("value"))
+ .withOneOfValues(List.of("value"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withValue(List.of("value", "problem"))
+ .withSupersetOfValues(List.of("value", "another"))
+ .build())));
+ Assert.assertFalse(validator.test(Map.of("mockClaim", new MetadataPolicy.Builder()
+ .withSubsetOfValues(List.of("value", "another"))
+ .withSupersetOfValues(List.of("value", "problem"))
+ .build())));
}
@Test
@@ -288,10 +402,18 @@ public class DefaultMetadataPolicyValidatorTest {
}
@Test
- public void test_whenCustomOperatorExists_noOtherPolicyItems_shouldReturnFalse_customValidationFails() {
+ public void test_whenCustomOperatorExists_noOtherPolicyItems_shouldReturnFalse_customValidationFails()
+ throws ComponentInitializationException {
final CustomMetadataPolicyOperator operator = Mockito.mock(CustomMetadataPolicyOperator.class);
Mockito.when(operator.validate(Mockito.any())).thenReturn(false);
- validator.setCustomMetadataPolicyOperators(CollectionSupport.singletonMap("customOperator", operator));
+ Mockito.when(operator.getOperatorName()).thenReturn("customOperator");
+ validator = new DefaultMetadataPolicyValidator();
+ final List<MetadataPolicyOperator> operators =
+ new ArrayList<>(MetadataPolicyHelper.standardMetadataPolicyOperatorsWithoutEssential());
+ operators.add(operator);
+ operators.add(new DefaultMetadataPolicyEssentialOperator());
+ validator.setMetadataPolicyOperators(operators);
+ validator.initialize();
final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
.withCustomOperator("customOperator", "obsoleteValue")
.build());
@@ -299,10 +421,18 @@ public class DefaultMetadataPolicyValidatorTest {
}
@Test
- public void test_whenCustomOperatorExists_noOtherPolicyItems_shouldReturnTrue() {
+ public void test_whenCustomOperatorExists_noOtherPolicyItems_shouldReturnTrue()
+ throws ComponentInitializationException {
final CustomMetadataPolicyOperator operator = Mockito.mock(CustomMetadataPolicyOperator.class);
Mockito.when(operator.validate(Mockito.any())).thenReturn(true);
- validator.setCustomMetadataPolicyOperators(CollectionSupport.singletonMap("customOperator", operator));
+ Mockito.when(operator.getOperatorName()).thenReturn("customOperator");
+ validator = new DefaultMetadataPolicyValidator();
+ final List<MetadataPolicyOperator> operators =
+ new ArrayList<>(MetadataPolicyHelper.standardMetadataPolicyOperatorsWithoutEssential());
+ operators.add(operator);
+ operators.add(new DefaultMetadataPolicyEssentialOperator());
+ validator.setMetadataPolicyOperators(operators);
+ validator.initialize();
final Map<String, MetadataPolicy> map = Map.of("mockClaim", new MetadataPolicy.Builder()
.withCustomOperator("customOperator", "obsoleteValue")
.build());
diff --git a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/MetadataPolicyHelperTest.java b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/MetadataPolicyHelperTest.java
index 35115dca..2536ea58 100644
--- a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/MetadataPolicyHelperTest.java
+++ b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/MetadataPolicyHelperTest.java
@@ -145,7 +145,7 @@ public class MetadataPolicyHelperTest {
Set.of("value2", "value3"));
}
- @Test
+ @Test(expectedExceptions = { ConstraintViolationException.class })
public void mergeMetadataPolicies_bothOneOfDifferentTypes_shouldReturnEmptyList() {
final MetadataPolicy superior = new MetadataPolicy.Builder()
.withOneOfValues(List.of("1", "2", "3"))
@@ -153,9 +153,7 @@ public class MetadataPolicyHelperTest {
final MetadataPolicy subordinate = new MetadataPolicy.Builder()
.withOneOfValues(List.of(2, 3, 4))
.build();
- final MetadataPolicy merged = MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
- assert merged != null;
- Assert.assertEquals(merged.getOneOfValues(), Collections.emptyList());
+ MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
}
@Test
@@ -182,7 +180,7 @@ public class MetadataPolicyHelperTest {
Assert.assertEquals(merged.getOneOfValues(), subordinate.getOneOfValues());
}
- @Test
+ @Test(expectedExceptions = { ConstraintViolationException.class })
public void mergeMetadataPolicies_oneOneOf_anotherEmpty_shouldReturnEmpty() {
final MetadataPolicy superior = new MetadataPolicy.Builder()
.withOneOfValues(List.of("value1", "value2", "value3"))
@@ -190,12 +188,10 @@ public class MetadataPolicyHelperTest {
final MetadataPolicy subordinate = new MetadataPolicy.Builder()
.withOneOfValues(Collections.emptyList())
.build();
- final MetadataPolicy merged = MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
- assert merged != null;
- Assert.assertEquals(merged.getOneOfValues(), Collections.emptyList());
+ MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
}
- @Test
+ @Test(expectedExceptions = { ConstraintViolationException.class })
public void mergeMetadataPolicies_oneOneOf_anotherEmpty_shouldReturnEmpty2() {
final MetadataPolicy superior = new MetadataPolicy.Builder()
.withOneOfValues(Collections.emptyList())
@@ -203,9 +199,7 @@ public class MetadataPolicyHelperTest {
final MetadataPolicy subordinate = new MetadataPolicy.Builder()
.withOneOfValues(List.of("value1", "value2", "value3"))
.build();
- final MetadataPolicy merged = MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
- assert merged != null;
- Assert.assertEquals(merged.getOneOfValues(), Collections.emptyList());
+ MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
}
@Test
@@ -485,14 +479,14 @@ public class MetadataPolicyHelperTest {
@Test
public void mergeMetadataPolicies_bothSameRegexp_shouldReturnSame() {
final MetadataPolicy superior = new MetadataPolicy.Builder()
- .withRegexp("singleValue1")
+ .withCustomOperator("regexp", "singleValue1")
.build();
final MetadataPolicy subordinate = new MetadataPolicy.Builder()
- .withRegexp("singleValue1")
+ .withCustomOperator("regexp", "singleValue1")
.build();
final MetadataPolicy merged = MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
assert merged != null;
- Assert.assertEquals(merged.getRegexp(), "singleValue1");
+ Assert.assertEquals(merged.getCustomOperators().get("regexp"), "singleValue1");
}
@Test
@@ -500,32 +494,32 @@ public class MetadataPolicyHelperTest {
final MetadataPolicy superior = new MetadataPolicy.Builder()
.build();
final MetadataPolicy subordinate = new MetadataPolicy.Builder()
- .withRegexp("singleValue1")
+ .withCustomOperator("regexp", "singleValue1")
.build();
final MetadataPolicy merged = MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
assert merged != null;
- Assert.assertEquals(merged.getRegexp(), "singleValue1");
+ Assert.assertEquals(merged.getCustomOperators().get("regexp"), "singleValue1");
}
@Test
public void mergeMetadataPolicies_nullSubordinateRegexp_shouldReturnSuperior() {
final MetadataPolicy superior = new MetadataPolicy.Builder()
- .withRegexp("singleValue1")
+ .withCustomOperator("regexp", "singleValue1")
.build();
final MetadataPolicy subordinate = new MetadataPolicy.Builder()
.build();
final MetadataPolicy merged = MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
assert merged != null;
- Assert.assertEquals(merged.getRegexp(), "singleValue1");
+ Assert.assertEquals(merged.getCustomOperators().get("regexp"), "singleValue1");
}
@Test(expectedExceptions = { ConstraintViolationException.class })
public void mergeMetadataPolicies_bothDifferentRegexp_shouldThrow() {
final MetadataPolicy superior = new MetadataPolicy.Builder()
- .withRegexp("singleValue1")
+ .withCustomOperator("regexp", "singleValue1")
.build();
final MetadataPolicy subordinate = new MetadataPolicy.Builder()
- .withRegexp("singleValue2")
+ .withCustomOperator("regexp", "singleValue2")
.build();
MetadataPolicyHelper.mergeMetadataPolicies(superior, subordinate);
}
@@ -678,7 +672,7 @@ public class MetadataPolicyHelperTest {
Assert.assertEquals(actual.getValue(), expected.getValue());
Assert.assertEquals(actual.getOneOfValues(), expected.getOneOfValues());
Assert.assertEquals(actual.getSupersetOfValues(), expected.getSupersetOfValues());
- Assert.assertEquals(actual.getRegexp(), expected.getRegexp());
+ Assert.assertEquals(actual.getCustomOperators().get("regexp"), expected.getCustomOperators().get("regexp"));
Assert.assertEquals(actual.isEssential(), expected.isEssential());
Assert.assertEquals(actual.getCustomOperators(), expected.getCustomOperators());
}
diff --git a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/OIDCMetadataPolicyResolverTest.java b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/OIDCMetadataPolicyResolverTest.java
index 9f751d49..8b680c8a 100644
--- a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/OIDCMetadataPolicyResolverTest.java
+++ b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/OIDCMetadataPolicyResolverTest.java
@@ -16,6 +16,7 @@ package net.shibboleth.oidc.metadata.policy.impl;
import java.io.IOException;
import java.time.Duration;
+import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -36,7 +37,7 @@ import net.shibboleth.oidc.metadata.cache.impl.DefaultJSONMapParsingStrategy;
import net.shibboleth.oidc.metadata.cache.impl.DefaultSourceMetadataExpirationTimeStrategy;
import net.shibboleth.oidc.metadata.cache.impl.MetadataCacheBuilder;
import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
-import net.shibboleth.shared.collection.CollectionSupport;
+import net.shibboleth.oidc.metadata.policy.MetadataPolicyOperator;
import net.shibboleth.shared.component.ComponentInitializationException;
import net.shibboleth.shared.logic.ConstraintViolationException;
import net.shibboleth.shared.resolver.CriteriaSet;
@@ -59,7 +60,7 @@ public class OIDCMetadataPolicyResolverTest {
resolver.initialize();
}
- @SuppressWarnings("null")
+ @SuppressWarnings({ "null", "unchecked" })
@Nonnull protected BatchMetadataCache<String, Map<String, MetadataPolicy>> buildCache(final String filename,
final CustomMetadataPolicyOperator customOperator)
throws IOException, ComponentInitializationException {
@@ -76,9 +77,16 @@ public class OIDCMetadataPolicyResolverTest {
spec.setCriteriaToIdentifierStrategy(crit -> "id");
spec.setIdentifierExtractionStrategy(crit -> "id");
final DefaultMetadataPolicyValidator policyValidator = new DefaultMetadataPolicyValidator();
+
+ final List<MetadataPolicyOperator> operators =
+ new ArrayList<>(MetadataPolicyHelper.standardMetadataPolicyOperatorsWithoutEssential());
+ operators.add(new RegexpMetadataPolicyOperator());
if (customOperator != null) {
- policyValidator.setCustomMetadataPolicyOperators(CollectionSupport.singletonMap("bean", customOperator));
+ operators.add(customOperator);
}
+ operators.add(new DefaultMetadataPolicyEssentialOperator());
+ policyValidator.setMetadataPolicyOperators(operators);
+ policyValidator.initialize();
spec.setMetadataValidPredicate(policyValidator);
spec.setMatchRequired(true);
@@ -86,10 +94,10 @@ public class OIDCMetadataPolicyResolverTest {
spec.setRefreshDelayFactor(0.75f);
spec.setMetadataFilterStrategy((metadata, context) -> metadata);
final MetadataCache<Map<String, MetadataPolicy>> cache = builder.build(spec);
- if (!(cache instanceof BatchMetadataCache)) {
- throw new ComponentInitializationException("Wrong cache type");
+ if (cache instanceof BatchMetadataCache batchCache) {
+ return batchCache;
}
- return (BatchMetadataCache<String, Map<String, MetadataPolicy>>) cache;
+ throw new ComponentInitializationException("Wrong cache type");
}
@Test
@@ -130,7 +138,11 @@ public class OIDCMetadataPolicyResolverTest {
throws ConstraintViolationException {
return null;
}
-
+
+ @Override
+ public String getOperatorName() {
+ return "bean";
+ }
};
initTest("/net/shibboleth/oidc/metadata/impl/metadata-policy1-custom.json", customOperator);
final Iterator<Map<String, MetadataPolicy>> iter = resolver.resolve(new CriteriaSet()).iterator();
@@ -160,6 +172,10 @@ public class OIDCMetadataPolicyResolverTest {
return null;
}
+ @Override
+ public String getOperatorName() {
+ return "mock";
+ }
};
initTest("/net/shibboleth/oidc/metadata/impl/metadata-policy1-custom.json", customOperator);
final Iterator<Map<String, MetadataPolicy>> iter = resolver.resolve(new CriteriaSet()).iterator();
@@ -181,7 +197,7 @@ public class OIDCMetadataPolicyResolverTest {
Assert.assertNull(grantTypes.getDefaultValue());
Assert.assertNull(grantTypes.getValue());
Assert.assertFalse(grantTypes.isEssential());
- Assert.assertNull(grantTypes.getRegexp());
+ Assert.assertNull(grantTypes.getCustomOperators().get("regexp"));
Assert.assertNull(grantTypes.getSubsetOfValues());
Assert.assertNull(grantTypes.getSupersetOfValues());
@@ -192,7 +208,7 @@ public class OIDCMetadataPolicyResolverTest {
Assert.assertNull(clientName.getValue());
Assert.assertFalse(clientName.isEssential());
Assert.assertNull(clientName.getOneOfValues());
- Assert.assertNull(clientName.getRegexp());
+ Assert.assertNull(clientName.getCustomOperators().get("regexp"));
Assert.assertNull(clientName.getSubsetOfValues());
Assert.assertNull(clientName.getSupersetOfValues());
@@ -203,7 +219,7 @@ public class OIDCMetadataPolicyResolverTest {
Assert.assertEquals(organizationName.getValue(), "A trusted organization");
Assert.assertFalse(organizationName.isEssential());
Assert.assertNull(organizationName.getOneOfValues());
- Assert.assertNull(organizationName.getRegexp());
+ Assert.assertNull(organizationName.getCustomOperators().get("regexp"));
Assert.assertNull(organizationName.getSubsetOfValues());
Assert.assertNull(organizationName.getSupersetOfValues());
@@ -215,7 +231,7 @@ public class OIDCMetadataPolicyResolverTest {
Assert.assertNull(redirectUris.getValue());
Assert.assertTrue(redirectUris.isEssential());
Assert.assertNull(redirectUris.getOneOfValues());
- Assert.assertEquals(redirectUris.getRegexp(), "^https:\\/\\/(?:([^.]+).)?example.org\\/(.*)");
+ Assert.assertEquals(redirectUris.getCustomOperators().get("regexp"), "^https:\\/\\/(?:([^.]+).)?example.org\\/(.*)");
Assert.assertNull(redirectUris.getSubsetOfValues());
Assert.assertNull(redirectUris.getSupersetOfValues());
@@ -226,7 +242,7 @@ public class OIDCMetadataPolicyResolverTest {
Assert.assertNull(algValuesSupported.getValue());
Assert.assertFalse(algValuesSupported.isEssential());
Assert.assertNull(algValuesSupported.getOneOfValues());
- Assert.assertNull(algValuesSupported.getRegexp());
+ Assert.assertNull(algValuesSupported.getCustomOperators().get("regexp"));
Assert.assertEquals(algValuesSupported.getSubsetOfValues(), List.of("RS256", "RS384", "RS512"));
Assert.assertNull(algValuesSupported.getSupersetOfValues());
@@ -237,7 +253,7 @@ public class OIDCMetadataPolicyResolverTest {
Assert.assertNull(scopes.getValue());
Assert.assertFalse(scopes.isEssential());
Assert.assertNull(scopes.getOneOfValues());
- Assert.assertNull(scopes.getRegexp());
+ Assert.assertNull(scopes.getCustomOperators().get("regexp"));
Assert.assertEquals(scopes.getSubsetOfValues(), List.of("openid", "profile", "email", "phone"));
Assert.assertNull(scopes.getSupersetOfValues());
diff --git a/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/RegexpMetadataPolicyOperatorTest.java b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/RegexpMetadataPolicyOperatorTest.java
new file mode 100644
index 00000000..823e1430
--- /dev/null
+++ b/oidc-common-metadata-impl/src/test/java/net/shibboleth/oidc/metadata/policy/impl/RegexpMetadataPolicyOperatorTest.java
@@ -0,0 +1,171 @@
+/*
+ * Licensed 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.policy.impl;
+
+import java.util.Arrays;
+import java.util.List;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import net.shibboleth.oidc.metadata.policy.MetadataPolicy;
+import net.shibboleth.shared.logic.ConstraintViolationException;
+
+/**
+ * Unit tests for {@link RegexpMetadataPolicyOperator}.
+ */
+public class RegexpMetadataPolicyOperatorTest {
+
+ private static final String REDIRECT_PATTERN = "^https://(?:[^./]+\\.)?example\\.org/.*";
+
+ RegexpMetadataPolicyOperator operator;
+
+ @BeforeMethod
+ public void init() {
+ operator = new RegexpMetadataPolicyOperator();
+ }
+
+ @Test
+ public void testOperatorName() {
+ Assert.assertEquals(operator.getOperatorName(), "regexp");
+ }
+
+ @Test
+ public void testValidateNoRegexp() {
+ Assert.assertTrue(operator.validate(new MetadataPolicy.Builder().build()));
+ }
+
+ @Test
+ public void testValidateValidRegexp() {
+ Assert.assertTrue(operator.validate(regexpPolicy(REDIRECT_PATTERN)));
+ }
+
+ @Test
+ public void testValidateInvalidSyntax() {
+ Assert.assertFalse(operator.validate(regexpPolicy("^(https")));
+ }
+
+ @Test
+ public void testValidateNonStringRegexp() {
+ Assert.assertFalse(operator.validate(regexpPolicy(Integer.valueOf(123))));
+ }
+
+ @Test
+ public void testValidateNullRegexp() {
+ Assert.assertFalse(operator.validate(regexpPolicy(null)));
+ }
+
+ @Test
+ public void testValidateWhitespaceRegexp() {
+ Assert.assertFalse(operator.validate(regexpPolicy(" ")));
+ }
+
+ @Test
+ public void testApplyNoRegexp() throws ConstraintViolationException {
+ final MetadataPolicy policy = new MetadataPolicy.Builder().build();
+ Assert.assertEquals(operator.apply("anything", policy), "anything");
+ Assert.assertNull(operator.apply(null, policy));
+ }
+
+ @Test
+ public void testApplyAbsentValue() throws ConstraintViolationException {
+ Assert.assertNull(operator.apply(null, regexpPolicy(REDIRECT_PATTERN)));
+ }
+
+ @Test
+ public void testApplyMatchingString() throws ConstraintViolationException {
+ final String candidate = "https://rp.example.org/cb";
+ Assert.assertEquals(operator.apply(candidate, regexpPolicy(REDIRECT_PATTERN)), candidate);
+ }
+
+ @Test(expectedExceptions = ConstraintViolationException.class)
+ public void testApplyNonMatchingString() throws ConstraintViolationException {
+ operator.apply("https://evil.example.com/cb", regexpPolicy(REDIRECT_PATTERN));
+ }
+
+ @Test(expectedExceptions = ConstraintViolationException.class)
+ public void testApplyPartialMatchIsRejected() throws ConstraintViolationException {
+ operator.apply("prefix-https://rp.example.org/cb", regexpPolicy("https://rp\\.example\\.org/cb"));
+ }
+
+ @Test
+ public void testApplyMatchingList() throws ConstraintViolationException {
+ final List<String> candidate = List.of("https://rp.example.org/cb", "https://example.org/other");
+ Assert.assertEquals(operator.apply(candidate, regexpPolicy(REDIRECT_PATTERN)), candidate);
+ }
+
+ @Test(expectedExceptions = ConstraintViolationException.class)
+ public void testApplyMatchingListWithNull() throws ConstraintViolationException {
+ final List<String> candidate = Arrays.asList("https://rp.example.org/cb", "https://example.org/other", null);
+ operator.apply(candidate, regexpPolicy(REDIRECT_PATTERN));
+ }
+
+ @Test
+ public void testApplyEmptyList() throws ConstraintViolationException {
+ final List<String> candidate = List.of();
+ Assert.assertEquals(operator.apply(candidate, regexpPolicy(REDIRECT_PATTERN)), candidate);
+ }
+
+ @Test(expectedExceptions = ConstraintViolationException.class)
+ public void testApplyListWithOneNonMatchingItem() throws ConstraintViolationException {
+ operator.apply(List.of("https://rp.example.org/cb", "https://evil.example.com/cb"),
+ regexpPolicy(REDIRECT_PATTERN));
+ }
+
+ @Test
+ public void testApplyListOfNonStrings() throws ConstraintViolationException {
+ final List<Integer> candidate = List.of(Integer.valueOf(1), Integer.valueOf(22));
+ Assert.assertEquals(operator.apply(candidate, regexpPolicy("\\d+")), candidate);
+ }
+
+ @Test
+ public void testApplyIntegerCandidateType() throws ConstraintViolationException {
+ operator.apply(Integer.valueOf(123), regexpPolicy("\\d+"));
+ }
+
+ @Test(expectedExceptions = ConstraintViolationException.class)
+ public void testApplyBlankRegexp() throws ConstraintViolationException {
+ operator.apply("value", regexpPolicy(" "));
+ }
+
+ @Test(expectedExceptions = ConstraintViolationException.class)
+ public void testApplyInvalidSyntax() throws ConstraintViolationException {
+ operator.apply("value", regexpPolicy("^(https"));
+ }
+
+ @Test(expectedExceptions = ConstraintViolationException.class)
+ public void testApplyNonStringRegexp() throws ConstraintViolationException {
+ operator.apply("value", regexpPolicy(Integer.valueOf(123)));
+ }
+
+ @Test(expectedExceptions = ConstraintViolationException.class)
+ public void testApplyNullRegexp() throws ConstraintViolationException {
+ operator.apply("value", regexpPolicy(null));
+ }
+
+ @Test(expectedExceptions = ConstraintViolationException.class)
+ public void testApplyNonStringRegexpWithAbsentValue() throws ConstraintViolationException {
+ operator.apply(null, regexpPolicy(Integer.valueOf(123)));
+ }
+
+ @Nonnull private static MetadataPolicy regexpPolicy(@Nullable final Object regexp) {
+ return new MetadataPolicy.Builder().withCustomOperator("regexp", regexp).build();
+ }
+
+}
\ No newline at end of file
--
To stop receiving notification emails like this one, please contact
the administrator of this repository.
More information about the commits
mailing list