[java-opensaml] branch main updated: OSJ-458: AssertionValidator for assertion replay checking

Codeberg noreply at shibboleth.net
Wed Nov 18 01:47:18 UTC 2026


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

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

View the commit online:
https://codeberg.org/Shibboleth/java-opensaml/commit/104fc86426a34356240cfaeeaa6bd10d46d77c0a

The following commit(s) were added to refs/heads/main by this push:
     new 104fc8642 OSJ-458: AssertionValidator for assertion replay checking
104fc8642 is described below

commit 104fc86426a34356240cfaeeaa6bd10d46d77c0a
Author: Brent Putman <putmanb at georgetown.edu>
AuthorDate: Tue Nov 17 20:01:00 2026 -0500

    OSJ-458: AssertionValidator for assertion replay checking
    
    Refactored most of the original OneTimeUseConditionValidator to an
    abstract base class for use by the now 2 similar concrete classes.
---
 .../SAML2AssertionValidationParameters.java        |   9 +-
 ...ava => AbstractAssertionIDReplayValidator.java} | 132 +++++++---------
 .../assertion/impl/AssertionReplayValidator.java   |  80 ++++++++++
 .../impl/OneTimeUseConditionValidator.java         | 118 ++------------
 .../impl/AssertionReplayValidatorTest.java         | 171 +++++++++++++++++++++
 5 files changed, 329 insertions(+), 181 deletions(-)

diff --git a/opensaml-saml-api/src/main/java/org/opensaml/saml/saml2/assertion/SAML2AssertionValidationParameters.java b/opensaml-saml-api/src/main/java/org/opensaml/saml/saml2/assertion/SAML2AssertionValidationParameters.java
index 82249c7ea..f68be3580 100644
--- a/opensaml-saml-api/src/main/java/org/opensaml/saml/saml2/assertion/SAML2AssertionValidationParameters.java
+++ b/opensaml-saml-api/src/main/java/org/opensaml/saml/saml2/assertion/SAML2AssertionValidationParameters.java
@@ -56,6 +56,13 @@ public final class SAML2AssertionValidationParameters {
     @Nonnull @NotEmpty public static final String CONFIRMED_SUBJECT_CONFIRMATION =
             STD_PREFIX + ".ConfirmedSubjectConfirmation";
     
+    /**
+     * Carries a {@link java.time.Duration} representing the per-invocation value for the Assertion 
+     * replay cache expiration.
+     */
+    @Nonnull @NotEmpty public static final String EXPIRES =
+            STD_PREFIX + ".Expires";
+    
     /**
      * Carries a {@link java.util.Set}<code><</code>{@link java.lang.String}<code>></code>
      * whose values are the acceptable 
@@ -201,7 +208,7 @@ public final class SAML2AssertionValidationParameters {
 
     /**
      * Carries a {@link java.time.Duration} representing the per-invocation value for the Assertion 
-     * replay cache expiration.
+     * OneTimeUse Condition replay cache expiration.
      */
     @Nonnull @NotEmpty public static final String COND_ONE_TIME_USE_EXPIRES =
             STD_PREFIX + COND_INFIX + ".OneTimeUseExpires";
diff --git a/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/OneTimeUseConditionValidator.java b/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/AbstractAssertionIDReplayValidator.java
similarity index 54%
copy from opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/OneTimeUseConditionValidator.java
copy to opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/AbstractAssertionIDReplayValidator.java
index 630a9509c..a92a83650 100644
--- a/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/OneTimeUseConditionValidator.java
+++ b/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/AbstractAssertionIDReplayValidator.java
@@ -16,59 +16,30 @@ package org.opensaml.saml.saml2.assertion.impl;
 
 import java.time.Duration;
 import java.time.Instant;
-import java.util.Objects;
 
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 import javax.annotation.concurrent.ThreadSafe;
-import javax.xml.namespace.QName;
 
-import net.shibboleth.shared.annotation.constraint.NotEmpty;
 import net.shibboleth.shared.logic.Constraint;
 import net.shibboleth.shared.primitive.LoggerFactory;
 import net.shibboleth.shared.primitive.StringSupport;
 
 import org.opensaml.saml.common.assertion.AssertionValidationException;
 import org.opensaml.saml.common.assertion.ValidationContext;
-import org.opensaml.saml.common.assertion.ValidationResult;
-import org.opensaml.saml.saml2.assertion.ConditionValidator;
-import org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters;
 import org.opensaml.saml.saml2.core.Assertion;
-import org.opensaml.saml.saml2.core.Condition;
 import org.opensaml.saml.saml2.core.Issuer;
-import org.opensaml.saml.saml2.core.OneTimeUse;
 import org.opensaml.storage.ReplayCache;
 import org.slf4j.Logger;
 
 /**
- * {@link ConditionValidator} used for {@link OneTimeUse} conditions.
- * 
- * <p>
- * Supports the following {@link ValidationContext} static parameters:
- * </p>
- * <ul>
- * <li>
- * {@link SAML2AssertionValidationParameters#COND_ONE_TIME_USE_EXPIRES}:
- * Optional. If not supplied, defaults to the validator-wide value supplied at construction, or
- * the default value, as retrieved via {@link #getReplayCacheExpires()}.
- * </li>
- * </ul>
- * 
- * <p>
- * Supports the following {@link ValidationContext} dynamic parameters:
- * </p>
- * <ul>
- *   <li>None.</li>
- * </ul>
+ * An abstract class for validators that enforce that an Assertion ID is not replayed/reused.
  */
 @ThreadSafe
-public class OneTimeUseConditionValidator implements ConditionValidator {
-    
-    /** Cache context name. */
-    @Nonnull @NotEmpty public static final String CACHE_CONTEXT = OneTimeUseConditionValidator.class.getName();
+public abstract class AbstractAssertionIDReplayValidator {
     
     /** Logger. */
-    @Nonnull private Logger log = LoggerFactory.getLogger(OneTimeUseConditionValidator.class);
+    @Nonnull private Logger log = LoggerFactory.getLogger(AbstractAssertionIDReplayValidator.class);
     
     /** Replay cache used to track which assertions have been used. */
     @Nonnull private final ReplayCache replayCache;
@@ -83,7 +54,7 @@ public class OneTimeUseConditionValidator implements ConditionValidator {
      * @param expires time for disposal of tracked assertion from the replay cache.
      *      May be null, then defaults to 8 hours
      */
-    public OneTimeUseConditionValidator(@Nonnull final ReplayCache replay, @Nullable final Duration expires) {
+    public AbstractAssertionIDReplayValidator(@Nonnull final ReplayCache replay, @Nullable final Duration expires) {
         replayCache = Constraint.isNotNull(replay, "Replay cache was null");
         
         if (expires == null) {
@@ -97,33 +68,6 @@ public class OneTimeUseConditionValidator implements ConditionValidator {
         }
     }
 
-    /** {@inheritDoc} */
-    @Nonnull public QName getServicedCondition() {
-        return OneTimeUse.DEFAULT_ELEMENT_NAME;
-    }
-
-    /** {@inheritDoc} */
-    @Nonnull public ValidationResult validate(@Nonnull final Condition condition, @Nonnull final Assertion assertion,
-            @Nonnull final ValidationContext context) throws AssertionValidationException {
-        
-        if (!(condition instanceof OneTimeUse) 
-                && !Objects.equals(condition.getElementQName(), getServicedCondition())) {
-            context.getValidationFailureMessages().add(
-                    String.format("Condition '%s' of type '%s' in assertion '%s' was not an '%s' condition",
-                            condition.getElementQName(), condition.getSchemaType(), assertion.getID(),
-                            getServicedCondition()));
-            return ValidationResult.INDETERMINATE;
-        }
-        
-        if (!replayCache.check(CACHE_CONTEXT, getCacheValue(assertion), getExpires(assertion, context))) {
-            context.getValidationFailureMessages().add(String.format(
-                    "Assertion '%s' has a one time use condition and has been used before", assertion.getID()));
-            return ValidationResult.INVALID;
-        }
-
-        return ValidationResult.VALID;
-    }
-    
     /**
      * Get the configured validator cache expiration interval.
      * 
@@ -134,7 +78,42 @@ public class OneTimeUseConditionValidator implements ConditionValidator {
     }
     
     /**
-     * Get the one-time use expiration time for the assertion being evaluated.
+     * Get the cache context used with the replay cache.
+     * 
+     * @return the cache context
+     */
+    @Nonnull protected abstract String getCacheContext();
+    
+    /**
+     * Get the optional validation context param name to use for the per-validation expiration
+     * 
+     * <p>
+     * This is the name of the parameter in the supplied {@link ValidationContext} which holds an
+     * optional {@link Duration} value.
+     * </p>
+     * 
+     * @return param name, or null
+     */
+    @Nullable protected abstract String getExpirationParameterName();
+    
+    /**
+     * Evaluate an Assertion for replay.
+     * 
+     * @param assertion the assertion to evaluate
+     * @param context the current validation contexxt
+     * 
+     * @return false if replay detected, true if not
+     * 
+     * @throws AssertionValidationException if there is a fatal error evaluating the Assertion
+     */
+    protected boolean doValidate(@Nonnull final Assertion assertion, @Nonnull final ValidationContext context)
+            throws AssertionValidationException {
+        
+        return replayCache.check(getCacheContext(), getCacheValue(assertion), getExpires(assertion, context));
+    }
+    
+    /**
+     * Get the replay cache expiration time for the assertion being evaluated.
      * 
      * <p>
      * Defaults to <code>Instant.now().plus(getReplayCacheExpires())</code>.
@@ -147,39 +126,44 @@ public class OneTimeUseConditionValidator implements ConditionValidator {
      * @param assertion the SAML 2 Assertion being evaluated
      * @param context the current validation context
      * 
-     * @return the effective one-time use expiration for the assertion being evaluated
+     * @return the effective expiration for the assertion being evaluated
      */
-    @Nonnull protected Instant getExpires(final Assertion assertion, final ValidationContext context) {
+    @Nonnull protected Instant getExpires(@Nonnull final Assertion assertion,
+            @Nonnull final ValidationContext context) {
+
         Duration expires = null;
-        final Object raw = context.getStaticParameters().get(
-                SAML2AssertionValidationParameters.COND_ONE_TIME_USE_EXPIRES);
-        if (raw instanceof Duration) {
-            expires = (Duration) raw;
+        if (getExpirationParameterName() != null) {
+            final Object raw = context.getStaticParameters().get(getExpirationParameterName());
+            if (raw instanceof Duration) {
+                expires = (Duration) raw;
+            } else if (raw != null){
+                log.warn("Saw non-null value for context param '{}', but value '{}' was not a java.time.Duration: {}",
+                        getExpirationParameterName(), raw, raw.getClass().getName());
+            }
         }
-        
-        log.debug("Saw one-time use cache expires context param: {}", expires);
+        log.debug("Saw Assertion replay cache expiration context param: {}", expires);
         
         Duration suppliedExpiration = null;
         
         if (expires == null || expires.isZero()) {
             suppliedExpiration = getReplayCacheExpires();
         } else if (expires.isNegative()) {
-            log.warn("Supplied context param for replay cache expires '{}' was negative, using configured expiration", 
+            log.warn("Context param for replay cache expiration '{}' was negative, using configured expiration", 
                     expires);
             suppliedExpiration = getReplayCacheExpires();
         } else {
             suppliedExpiration = expires;
         }
              
-        log.debug("Effective one-time use cache expires of: {}", suppliedExpiration);
+        log.debug("Effective Assertion replay cache expiration of: {}", suppliedExpiration);
         
         final Instant computedExpiration = Instant.now().plus(suppliedExpiration);
-        log.debug("Computed one-time use cache effective expiration time of: {}", computedExpiration);
+        log.debug("Computed Assertion replay cache effective expiration time of: {}", computedExpiration);
         return computedExpiration;
     }
 
     /**
-     * Get the string value which will be tracked in the cache for purposes of one-time use detection.
+     * Get the string value which will be tracked in the cache for purposes of replay detection.
      * 
      * @param assertion the SAML 2 Assertion to evaluate
      * 
@@ -204,7 +188,7 @@ public class OneTimeUseConditionValidator implements ConditionValidator {
         }
         
         final String value = String.format("%s--%s", issuer, id);
-        log.debug("Generated one-time use cache value of: {}", value);
+        log.debug("Generated Assertion replay use cache value of: {}", value);
         return value;
     }
    
diff --git a/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/AssertionReplayValidator.java b/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/AssertionReplayValidator.java
new file mode 100644
index 000000000..a7902c4da
--- /dev/null
+++ b/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/AssertionReplayValidator.java
@@ -0,0 +1,80 @@
+/*
+ * 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 org.opensaml.saml.saml2.assertion.impl;
+
+import java.time.Duration;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.opensaml.saml.common.assertion.AssertionValidationException;
+import org.opensaml.saml.common.assertion.ValidationContext;
+import org.opensaml.saml.common.assertion.ValidationResult;
+import org.opensaml.saml.saml2.assertion.AssertionValidator;
+import org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters;
+import org.opensaml.saml.saml2.core.Assertion;
+import org.opensaml.storage.ReplayCache;
+
+import net.shibboleth.shared.annotation.constraint.NotEmpty;
+
+/**
+ * An implementation of {@link AssertionValidator} which checks for assertion replay/reuse.
+ */
+public class AssertionReplayValidator extends AbstractAssertionIDReplayValidator implements AssertionValidator {
+    
+    /** Cache context name. */
+    @Nonnull @NotEmpty public static final String CACHE_CONTEXT = AssertionReplayValidator.class.getName();
+
+    /**
+     * Constructor.
+     * 
+     * @param replay reply cache used to track which assertions have been used
+     * @param expires time for disposal of tracked assertion from the replay cache.
+     *      May be null, then defaults to 8 hours
+     */
+    public AssertionReplayValidator(@Nonnull final ReplayCache replay, @Nullable final Duration expires) {
+        super(replay, expires);
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    @Nonnull
+    protected String getCacheContext() {
+        return CACHE_CONTEXT;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    @Nullable
+    protected String getExpirationParameterName() {
+        return SAML2AssertionValidationParameters.EXPIRES;
+    }
+
+    /** {@inheritDoc} */
+    @Override
+    @Nonnull
+    public ValidationResult validate(@Nonnull final Assertion assertion, @Nonnull final ValidationContext context)
+            throws AssertionValidationException {
+        
+        if (!doValidate(assertion, context)) {
+            context.getValidationFailureMessages().add(String.format(
+                    "Assertion '%s' has been used before", assertion.getID()));
+            return ValidationResult.INVALID;
+        }
+
+        return ValidationResult.VALID;
+    }
+
+}
diff --git a/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/OneTimeUseConditionValidator.java b/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/OneTimeUseConditionValidator.java
index 630a9509c..f8e83c06d 100644
--- a/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/OneTimeUseConditionValidator.java
+++ b/opensaml-saml-impl/src/main/java/org/opensaml/saml/saml2/assertion/impl/OneTimeUseConditionValidator.java
@@ -15,7 +15,6 @@
 package org.opensaml.saml.saml2.assertion.impl;
 
 import java.time.Duration;
-import java.time.Instant;
 import java.util.Objects;
 
 import javax.annotation.Nonnull;
@@ -24,9 +23,7 @@ import javax.annotation.concurrent.ThreadSafe;
 import javax.xml.namespace.QName;
 
 import net.shibboleth.shared.annotation.constraint.NotEmpty;
-import net.shibboleth.shared.logic.Constraint;
 import net.shibboleth.shared.primitive.LoggerFactory;
-import net.shibboleth.shared.primitive.StringSupport;
 
 import org.opensaml.saml.common.assertion.AssertionValidationException;
 import org.opensaml.saml.common.assertion.ValidationContext;
@@ -35,7 +32,6 @@ import org.opensaml.saml.saml2.assertion.ConditionValidator;
 import org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters;
 import org.opensaml.saml.saml2.core.Assertion;
 import org.opensaml.saml.saml2.core.Condition;
-import org.opensaml.saml.saml2.core.Issuer;
 import org.opensaml.saml.saml2.core.OneTimeUse;
 import org.opensaml.storage.ReplayCache;
 import org.slf4j.Logger;
@@ -62,7 +58,7 @@ import org.slf4j.Logger;
  * </ul>
  */
 @ThreadSafe
-public class OneTimeUseConditionValidator implements ConditionValidator {
+public class OneTimeUseConditionValidator extends AbstractAssertionIDReplayValidator implements ConditionValidator {
     
     /** Cache context name. */
     @Nonnull @NotEmpty public static final String CACHE_CONTEXT = OneTimeUseConditionValidator.class.getName();
@@ -70,12 +66,6 @@ public class OneTimeUseConditionValidator implements ConditionValidator {
     /** Logger. */
     @Nonnull private Logger log = LoggerFactory.getLogger(OneTimeUseConditionValidator.class);
     
-    /** Replay cache used to track which assertions have been used. */
-    @Nonnull private final ReplayCache replayCache;
-    
-    /** Time for disposal of value from cache. */
-    @Nonnull private final Duration replayCacheExpires;
-
     /**
      * Constructor.
      * 
@@ -84,17 +74,7 @@ public class OneTimeUseConditionValidator implements ConditionValidator {
      *      May be null, then defaults to 8 hours
      */
     public OneTimeUseConditionValidator(@Nonnull final ReplayCache replay, @Nullable final Duration expires) {
-        replayCache = Constraint.isNotNull(replay, "Replay cache was null");
-        
-        if (expires == null) {
-            replayCacheExpires = Duration.ofHours(8);
-        } else if (expires.isNegative()) {
-            replayCacheExpires = Duration.ofHours(8);
-            log.warn("Supplied value for replay cache expires '{}' was negative, using default expiration", 
-                    replayCacheExpires);
-        } else {
-            replayCacheExpires = expires;
-        }
+        super(replay, expires);
     }
 
     /** {@inheritDoc} */
@@ -102,6 +82,15 @@ public class OneTimeUseConditionValidator implements ConditionValidator {
         return OneTimeUse.DEFAULT_ELEMENT_NAME;
     }
 
+    /** {@inheritDoc} */
+    @Nonnull protected String getCacheContext() {
+        return CACHE_CONTEXT;
+    }
+    
+    @Nullable protected String getExpirationParameterName() {
+        return SAML2AssertionValidationParameters.COND_ONE_TIME_USE_EXPIRES;
+    }
+
     /** {@inheritDoc} */
     @Nonnull public ValidationResult validate(@Nonnull final Condition condition, @Nonnull final Assertion assertion,
             @Nonnull final ValidationContext context) throws AssertionValidationException {
@@ -115,97 +104,14 @@ public class OneTimeUseConditionValidator implements ConditionValidator {
             return ValidationResult.INDETERMINATE;
         }
         
-        if (!replayCache.check(CACHE_CONTEXT, getCacheValue(assertion), getExpires(assertion, context))) {
+        if (!doValidate(assertion, context)) {
             context.getValidationFailureMessages().add(String.format(
                     "Assertion '%s' has a one time use condition and has been used before", assertion.getID()));
             return ValidationResult.INVALID;
         }
 
         return ValidationResult.VALID;
-    }
-    
-    /**
-     * Get the configured validator cache expiration interval.
-     * 
-     * @return the configured cache expiration interval
-     */
-    @Nonnull protected Duration getReplayCacheExpires() {
-        return replayCacheExpires;
-    }
-    
-    /**
-     * Get the one-time use expiration time for the assertion being evaluated.
-     * 
-     * <p>
-     * Defaults to <code>Instant.now().plus(getReplayCacheExpires())</code>.
-     * </p>
-     * 
-     * <p>
-     * A subclass might override this to base expiration on data from the assertion or the validation context.
-     * </p>
-     * 
-     * @param assertion the SAML 2 Assertion being evaluated
-     * @param context the current validation context
-     * 
-     * @return the effective one-time use expiration for the assertion being evaluated
-     */
-    @Nonnull protected Instant getExpires(final Assertion assertion, final ValidationContext context) {
-        Duration expires = null;
-        final Object raw = context.getStaticParameters().get(
-                SAML2AssertionValidationParameters.COND_ONE_TIME_USE_EXPIRES);
-        if (raw instanceof Duration) {
-            expires = (Duration) raw;
-        }
-        
-        log.debug("Saw one-time use cache expires context param: {}", expires);
-        
-        Duration suppliedExpiration = null;
-        
-        if (expires == null || expires.isZero()) {
-            suppliedExpiration = getReplayCacheExpires();
-        } else if (expires.isNegative()) {
-            log.warn("Supplied context param for replay cache expires '{}' was negative, using configured expiration", 
-                    expires);
-            suppliedExpiration = getReplayCacheExpires();
-        } else {
-            suppliedExpiration = expires;
-        }
-             
-        log.debug("Effective one-time use cache expires of: {}", suppliedExpiration);
-        
-        final Instant computedExpiration = Instant.now().plus(suppliedExpiration);
-        log.debug("Computed one-time use cache effective expiration time of: {}", computedExpiration);
-        return computedExpiration;
-    }
-
-    /**
-     * Get the string value which will be tracked in the cache for purposes of one-time use detection.
-     * 
-     * @param assertion the SAML 2 Assertion to evaluate
-     * 
-     * @return the cache value
-     * 
-     * @throws AssertionValidationException thrown if there is a problem calculating the cached value
-     */
-    @Nonnull protected String getCacheValue(@Nonnull final Assertion assertion) throws AssertionValidationException {
-        String issuer = null;
-        final Issuer issuerObject = assertion.getIssuer();
-        if (issuerObject != null) {
-            issuer = StringSupport.trimOrNull(issuerObject.getValue());
-        }
-        
-        if (issuer == null) {
-            issuer = "NoIssuer";
-        }
-        
-        String id = StringSupport.trimOrNull(assertion.getID());
-        if (id == null) {
-            id = "NoID";
-        }
         
-        final String value = String.format("%s--%s", issuer, id);
-        log.debug("Generated one-time use cache value of: {}", value);
-        return value;
     }
    
 }
\ No newline at end of file
diff --git a/opensaml-saml-impl/src/test/java/org/opensaml/saml/saml2/assertion/impl/AssertionReplayValidatorTest.java b/opensaml-saml-impl/src/test/java/org/opensaml/saml/saml2/assertion/impl/AssertionReplayValidatorTest.java
new file mode 100644
index 000000000..7c1925ae6
--- /dev/null
+++ b/opensaml-saml-impl/src/test/java/org/opensaml/saml/saml2/assertion/impl/AssertionReplayValidatorTest.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 org.opensaml.saml.saml2.assertion.impl;
+
+import java.time.Duration;
+import java.util.Map;
+
+import net.shibboleth.shared.component.ComponentInitializationException;
+import net.shibboleth.shared.primitive.AnnotationsSupport;
+import net.shibboleth.shared.primitive.StringSupport;
+
+import org.opensaml.saml.common.assertion.AssertionValidationException;
+import org.opensaml.saml.common.assertion.ValidationContext;
+import org.opensaml.saml.common.assertion.ValidationResult;
+import org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters;
+import org.opensaml.saml.saml2.assertion.tests.BaseAssertionValidationTest;
+import org.opensaml.saml.saml2.core.Assertion;
+import org.opensaml.storage.impl.MemoryStorageService;
+import org.opensaml.storage.impl.StorageServiceReplayCache;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/**
+ * Unit test for {@link AssertionReplayValidator}.
+ */
+ at SuppressWarnings({"null", "javadoc"})
+public class AssertionReplayValidatorTest extends BaseAssertionValidationTest {
+    
+    private MemoryStorageService storageService;
+    private StorageServiceReplayCache replayCache;
+    
+    private AssertionReplayValidator validator;
+    
+    @BeforeMethod(dependsOnMethods="setUpBasicAssertion")
+    public void setUp() throws ComponentInitializationException {
+        storageService = new MemoryStorageService();
+        storageService.setId("mySS");
+        storageService.initialize();
+        
+        replayCache = new StorageServiceReplayCache();
+        replayCache.setId("myRC");
+        replayCache.setStorage(storageService);
+        replayCache.initialize();
+        
+        validator = new AssertionReplayValidator(replayCache, null);
+    }
+    
+    @AfterMethod
+    public void tearDown() {
+        AnnotationsSupport.callOnTeardownAnnotations(replayCache);
+        AnnotationsSupport.callOnTeardownAnnotations(storageService);
+    }
+    
+    @Test
+    public void testNoReplay() throws AssertionValidationException, InterruptedException {
+        Assertion assertion = getAssertion();
+        Assert.assertNotNull(StringSupport.trimOrNull(assertion.getID()));
+        
+        ValidationContext validationContext = new ValidationContext(buildBasicStaticParameters());
+        
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.VALID);
+        
+        Thread.sleep(1000);
+        
+        assertion.setID(assertion.getID() + "moreID");
+        
+        validationContext = new ValidationContext(buildBasicStaticParameters());
+        
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.VALID);
+    }
+    
+    @Test
+    public void testReplay() throws AssertionValidationException, InterruptedException {
+        Assertion assertion = getAssertion();
+        Assert.assertNotNull(StringSupport.trimOrNull(assertion.getID()));
+        
+        ValidationContext validationContext = new ValidationContext(buildBasicStaticParameters());
+        
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.VALID);
+        
+        Thread.sleep(1000);
+        
+        validationContext = new ValidationContext(buildBasicStaticParameters());
+        
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.INVALID);
+    }
+
+    @Test
+    public void testReplayWithGlobalExpiration() throws AssertionValidationException, InterruptedException {
+        // Set validator expiration to 500ms.
+        validator = new AssertionReplayValidator(replayCache, Duration.ofMillis(500));
+        
+        Assertion assertion = getAssertion();
+        Assert.assertNotNull(StringSupport.trimOrNull(assertion.getID()));
+        
+        ValidationContext validationContext = new ValidationContext(buildBasicStaticParameters());
+        
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.VALID);
+        
+        // Sleep past the expiration
+        Thread.sleep(1000);
+        
+        validationContext = new ValidationContext(buildBasicStaticParameters());
+        
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.VALID);
+    }
+    
+    @Test
+    public void testReplayWithExpirationParam() throws AssertionValidationException, InterruptedException {
+        Assertion assertion = getAssertion();
+        Assert.assertNotNull(StringSupport.trimOrNull(assertion.getID()));
+        
+        Map<String, Object> staticParams = buildBasicStaticParameters();
+        staticParams.put(SAML2AssertionValidationParameters.EXPIRES, Duration.ofMillis(500));
+        ValidationContext validationContext = new ValidationContext(staticParams);
+        
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.VALID);
+        
+        // Sleep past the expiration
+        Thread.sleep(1000);
+        
+        validationContext = new ValidationContext(buildBasicStaticParameters());
+        
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.VALID);
+    }
+    
+    @Test
+    public void testInvalidExpirationParam() throws AssertionValidationException, InterruptedException {
+        Assertion assertion = getAssertion();
+        Assert.assertNotNull(StringSupport.trimOrNull(assertion.getID()));
+        
+        Map<String, Object> staticParams = buildBasicStaticParameters();
+        // This value is not a Duration or Long and so will be effectively ignored
+        staticParams.put(SAML2AssertionValidationParameters.EXPIRES, "500");
+        ValidationContext validationContext = new ValidationContext(staticParams);
+        
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.VALID);
+        
+        Thread.sleep(1000);
+        
+        validationContext = new ValidationContext(buildBasicStaticParameters());
+        
+        // Invalid b/c the param was ignored and so global expiration in effect
+        Assert.assertEquals(validator.validate(assertion, validationContext), 
+                ValidationResult.INVALID);
+    }
+
+}

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


More information about the commits mailing list