This is an automated email from the ASF dual-hosted git repository.

coheigea pushed a commit to branch 3_0_x-fixes
in repository https://gitbox.apache.org/repos/asf/ws-wss4j.git


The following commit(s) were added to refs/heads/3_0_x-fixes by this push:
     new 84cce1ce4 Keep OneTimeUse identifiers cached for as long as the 
assertion is valid (#771)
84cce1ce4 is described below

commit 84cce1ce4f4390aed25b464fa01937fe050c4120
Author: Colm O hEigeartaigh <[email protected]>
AuthorDate: Thu Nov 5 11:44:06 2026 +0000

    Keep OneTimeUse identifiers cached for as long as the assertion is valid 
(#771)
---
 .../apache/wss4j/common/cache/EHCacheExpiry.java   |   9 +-
 .../wss4j/common/cache/EHCacheReplayCache.java     |   6 +
 .../wss4j/common/cache/MemoryReplayCache.java      |  12 +-
 .../org/apache/wss4j/common/cache/ReplayCache.java |  12 ++
 .../wss4j/common/cache/EHCacheExpiryTest.java      |   3 +-
 .../apache/wss4j/common/cache/ReplayCacheTest.java |  13 +-
 .../wss4j/dom/validate/SamlAssertionValidator.java |  41 ++++-
 .../org/apache/wss4j/dom/message/ReplayTest.java   | 170 +++++++++++++++++++++
 .../stax/validate/SamlTokenValidatorImpl.java      |  41 ++++-
 .../org/apache/wss4j/stax/test/ReplayTest.java     |  57 ++++++-
 10 files changed, 356 insertions(+), 8 deletions(-)

diff --git 
a/ws-security-common/src/main/java/org/apache/wss4j/common/cache/EHCacheExpiry.java
 
b/ws-security-common/src/main/java/org/apache/wss4j/common/cache/EHCacheExpiry.java
index 721931c0e..50576dbaa 100644
--- 
a/ws-security-common/src/main/java/org/apache/wss4j/common/cache/EHCacheExpiry.java
+++ 
b/ws-security-common/src/main/java/org/apache/wss4j/common/cache/EHCacheExpiry.java
@@ -28,7 +28,8 @@ import org.ehcache.expiry.ExpiryPolicy;
 
 /**
  * A custom Expiry implementation for EhCache. It uses the supplied expiry 
which is part of the cache value.
- * If it doesn't exist, it falls back to the default value (3600 seconds).
+ * If it doesn't exist (or is in the past), it falls back to the default value 
(3600 seconds). If it exceeds
+ * the max value (12 hours), it is clamped to the max value.
  */
 public class EHCacheExpiry implements ExpiryPolicy<String, EHCacheValue> {
 
@@ -48,8 +49,12 @@ public class EHCacheExpiry implements ExpiryPolicy<String, 
EHCacheValue> {
         Instant expiry = ehCacheValue.getExpiry();
         Instant now = Instant.now();
 
-        if (expiry == null || expiry.isBefore(now) || 
expiry.isAfter(now.plusSeconds(MAX_TTL))) {
+        if (expiry == null || expiry.isBefore(now)) {
             return Duration.of(DEFAULT_TTL, ChronoUnit.SECONDS);
+        } else if (expiry.isAfter(now.plusSeconds(MAX_TTL))) {
+            // Clamp to the max TTL rather than falling back to the (shorter) 
default TTL, so that
+            // an identifier is not dropped from the cache while the token it 
belongs to is still valid
+            return Duration.of(MAX_TTL, ChronoUnit.SECONDS);
         }
 
         return Duration.of(expiry.toEpochMilli() - now.toEpochMilli(), 
ChronoUnit.MILLIS);
diff --git 
a/ws-security-common/src/main/java/org/apache/wss4j/common/cache/EHCacheReplayCache.java
 
b/ws-security-common/src/main/java/org/apache/wss4j/common/cache/EHCacheReplayCache.java
index db2a1ede7..8bfe38bfb 100644
--- 
a/ws-security-common/src/main/java/org/apache/wss4j/common/cache/EHCacheReplayCache.java
+++ 
b/ws-security-common/src/main/java/org/apache/wss4j/common/cache/EHCacheReplayCache.java
@@ -21,6 +21,7 @@ package org.apache.wss4j.common.cache;
 
 import java.io.File;
 import java.nio.file.Path;
+import java.time.Duration;
 import java.time.Instant;
 
 import org.apache.wss4j.common.ext.WSSecurityException;
@@ -161,6 +162,11 @@ public class EHCacheReplayCache implements ReplayCache {
         return cache.get(identifier);
     }
 
+    @Override
+    public Duration getMaxTTL() {
+        return Duration.ofSeconds(EHCacheExpiry.MAX_TTL);
+    }
+
     @Override
     public synchronized void close() {
         if (cacheManager.getStatus() == Status.AVAILABLE) {
diff --git 
a/ws-security-common/src/main/java/org/apache/wss4j/common/cache/MemoryReplayCache.java
 
b/ws-security-common/src/main/java/org/apache/wss4j/common/cache/MemoryReplayCache.java
index bfe777a96..d39ad5c3c 100644
--- 
a/ws-security-common/src/main/java/org/apache/wss4j/common/cache/MemoryReplayCache.java
+++ 
b/ws-security-common/src/main/java/org/apache/wss4j/common/cache/MemoryReplayCache.java
@@ -20,6 +20,7 @@
 package org.apache.wss4j.common.cache;
 
 import java.io.IOException;
+import java.time.Duration;
 import java.time.Instant;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -98,8 +99,12 @@ public class MemoryReplayCache implements ReplayCache {
     private static Instant getCacheExpiry(Instant expiry) {
         Instant now = Instant.now();
         Instant maxTTL = now.plusSeconds(MAX_TTL);
-        if (expiry == null || expiry.isBefore(now) || expiry.isAfter(maxTTL)) {
+        if (expiry == null || expiry.isBefore(now)) {
             return now.plusSeconds(DEFAULT_TTL);
+        } else if (expiry.isAfter(maxTTL)) {
+            // Clamp to the max TTL rather than falling back to the (shorter) 
default TTL, so that
+            // an identifier is not dropped from the cache while the token it 
belongs to is still valid
+            return maxTTL;
         }
         return expiry;
     }
@@ -135,6 +140,11 @@ public class MemoryReplayCache implements ReplayCache {
         }
     }
 
+    @Override
+    public Duration getMaxTTL() {
+        return Duration.ofSeconds(MAX_TTL);
+    }
+
     @Override
     public synchronized void close() throws IOException {
         cache.clear();
diff --git 
a/ws-security-common/src/main/java/org/apache/wss4j/common/cache/ReplayCache.java
 
b/ws-security-common/src/main/java/org/apache/wss4j/common/cache/ReplayCache.java
index 74ee08c86..fd23f9823 100644
--- 
a/ws-security-common/src/main/java/org/apache/wss4j/common/cache/ReplayCache.java
+++ 
b/ws-security-common/src/main/java/org/apache/wss4j/common/cache/ReplayCache.java
@@ -20,6 +20,7 @@
 package org.apache.wss4j.common.cache;
 
 import java.io.Closeable;
+import java.time.Duration;
 import java.time.Instant;
 
 /**
@@ -80,4 +81,15 @@ public interface ReplayCache extends Closeable {
         }
     }
 
+    /**
+     * Return the maximum time for which this cache holds an identifier. A 
custom expiry passed to
+     * add(String, Instant) or addIfAbsent(String, Instant) that is further in 
the future than this is
+     * reduced to it, so an identifier whose token is valid for longer can be 
replayed once it has
+     * expired from the cache.
+     * @return the maximum time for which this cache holds an identifier, or 
null if this is not known
+     */
+    default Duration getMaxTTL() {
+        return null;
+    }
+
 }
diff --git 
a/ws-security-common/src/test/java/org/apache/wss4j/common/cache/EHCacheExpiryTest.java
 
b/ws-security-common/src/test/java/org/apache/wss4j/common/cache/EHCacheExpiryTest.java
index fd3b3ca39..e427eb606 100644
--- 
a/ws-security-common/src/test/java/org/apache/wss4j/common/cache/EHCacheExpiryTest.java
+++ 
b/ws-security-common/src/test/java/org/apache/wss4j/common/cache/EHCacheExpiryTest.java
@@ -95,6 +95,7 @@ public class EHCacheExpiryTest {
                         new EHCacheValue("xyz", Instant.now().plus(14, 
ChronoUnit.HOURS)));
         assertNotNull(expiryForCreation);
 
-        assertEquals(EHCacheExpiry.DEFAULT_TTL, 
expiryForCreation.getSeconds());
+        // A huge expiry is clamped to the max TTL, not reduced to the default 
TTL
+        assertEquals(EHCacheExpiry.MAX_TTL, expiryForCreation.getSeconds());
     }
 }
\ No newline at end of file
diff --git 
a/ws-security-common/src/test/java/org/apache/wss4j/common/cache/ReplayCacheTest.java
 
b/ws-security-common/src/test/java/org/apache/wss4j/common/cache/ReplayCacheTest.java
index dc6bf94e9..aa0976b5a 100644
--- 
a/ws-security-common/src/test/java/org/apache/wss4j/common/cache/ReplayCacheTest.java
+++ 
b/ws-security-common/src/test/java/org/apache/wss4j/common/cache/ReplayCacheTest.java
@@ -21,6 +21,7 @@ package org.apache.wss4j.common.cache;
 
 import java.io.IOException;
 import java.nio.file.Path;
+import java.time.Duration;
 import java.time.Instant;
 import java.time.temporal.ChronoUnit;
 import java.util.ArrayList;
@@ -140,7 +141,7 @@ public class ReplayCacheTest {
         replayCache.close();
     }
 
-    // The huge expiry is rejected and it falls back to the default
+    // The huge expiry is clamped to the max TTL
     @Test
     public void testEhCacheReplayCacheHugeExpiry() throws Exception {
         ReplayCache replayCache = new EHCacheReplayCache("xyz", tempDir);
@@ -157,6 +158,16 @@ public class ReplayCacheTest {
         replayCache.close();
     }
 
+    @Test
+    public void testMaxTTL() throws Exception {
+        try (ReplayCache replayCache = new MemoryReplayCache()) {
+            assertEquals(Duration.ofSeconds(MemoryReplayCache.MAX_TTL), 
replayCache.getMaxTTL());
+        }
+        try (ReplayCache replayCache = new EHCacheReplayCache("xyz", tempDir)) 
{
+            assertEquals(Duration.ofSeconds(EHCacheExpiry.MAX_TTL), 
replayCache.getMaxTTL());
+        }
+    }
+
     @Test
     public void testNullKey() throws Exception {
         Assertions.assertThrows(NullPointerException.class, () ->
diff --git 
a/ws-security-dom/src/main/java/org/apache/wss4j/dom/validate/SamlAssertionValidator.java
 
b/ws-security-dom/src/main/java/org/apache/wss4j/dom/validate/SamlAssertionValidator.java
index c4ae14faa..0858039e9 100644
--- 
a/ws-security-dom/src/main/java/org/apache/wss4j/dom/validate/SamlAssertionValidator.java
+++ 
b/ws-security-dom/src/main/java/org/apache/wss4j/dom/validate/SamlAssertionValidator.java
@@ -19,6 +19,7 @@
 
 package org.apache.wss4j.dom.validate;
 
+import java.time.Duration;
 import java.time.Instant;
 import java.util.List;
 
@@ -79,6 +80,13 @@ public class SamlAssertionValidator extends 
SignatureTrustValidator {
      */
     private boolean requireBearerSignature = true;
 
+    /**
+     * Whether to accept an Assertion with a OneTimeUse Condition that is 
valid for longer than the
+     * replay cache can hold its identifier. Such an Assertion can be replayed 
once its identifier has
+     * expired from the cache, so it is rejected by default.
+     */
+    private boolean allowOneTimeUseBeyondCacheTTL;
+
     /**
      * Set the time in seconds in the future within which the NotBefore time 
of an incoming
      * Assertion is valid. The default is 60 seconds.
@@ -253,9 +261,27 @@ public class SamlAssertionValidator extends 
SignatureTrustValidator {
             String identifier = samlAssertion.getId();
 
             ReplayCache replayCache = data.getSamlOneTimeUseReplayCache();  
//NOPMD
+            Instant expires = 
samlAssertion.getSaml2().getConditions().getNotOnOrAfter();
+            if (expires == null && samlAssertion.getSaml2().getIssueInstant() 
!= null) {
+                // With no NotOnOrAfter, checkIssueInstant accepts the 
assertion until IssueInstant + ttl,
+                // so it must stay in the cache until then
+                expires = 
samlAssertion.getSaml2().getIssueInstant().plusSeconds(ttl);
+            }
+
+            // The cache only holds the identifier for so long. An Assertion 
that is valid for longer
+            // could be replayed once its identifier has expired from the 
cache, so reject it
+            Duration maxTTL = replayCache.getMaxTTL();
+            if (!allowOneTimeUseBeyondCacheTTL && maxTTL != null && expires != 
null
+                && expires.isAfter(Instant.now().plus(maxTTL))) {
+                LOG.warn("A OneTimeUse Assertion is valid for longer than the 
replay cache can hold it");
+                throw new WSSecurityException(
+                    WSSecurityException.ErrorCode.INVALID_SECURITY,
+                    "badSamlToken",
+                    new Object[] {"A OneTimeUse Assertion is valid for longer 
than the replay cache can hold it"});
+            }
+
             // Check and cache the identifier atomically, so that concurrent 
requests carrying the
             // same Assertion cannot all pass the check before any of them has 
cached it
-            Instant expires = 
samlAssertion.getSaml2().getConditions().getNotOnOrAfter();
             if (!replayCache.addIfAbsent(identifier, expires)) {
                 throw new WSSecurityException(
                     WSSecurityException.ErrorCode.INVALID_SECURITY,
@@ -314,6 +340,19 @@ public class SamlAssertionValidator extends 
SignatureTrustValidator {
         this.requireBearerSignature = requireBearerSignature;
     }
 
+    /**
+     * Whether to accept an Assertion with a OneTimeUse Condition that is 
valid for longer than the
+     * replay cache can hold its identifier (see ReplayCache#getMaxTTL()). The 
default is false.
+     * Such an Assertion can be replayed once its identifier has expired from 
the cache.
+     */
+    public boolean isAllowOneTimeUseBeyondCacheTTL() {
+        return allowOneTimeUseBeyondCacheTTL;
+    }
+
+    public void setAllowOneTimeUseBeyondCacheTTL(boolean 
allowOneTimeUseBeyondCacheTTL) {
+        this.allowOneTimeUseBeyondCacheTTL = allowOneTimeUseBeyondCacheTTL;
+    }
+
     public int getTtl() {
         return ttl;
     }
diff --git 
a/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/ReplayTest.java 
b/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/ReplayTest.java
index 0ea35a38b..158c15369 100644
--- a/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/ReplayTest.java
+++ b/ws-security-dom/src/test/java/org/apache/wss4j/dom/message/ReplayTest.java
@@ -63,6 +63,7 @@ import org.w3c.dom.Element;
 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 
@@ -965,6 +966,175 @@ public class ReplayTest {
         replayCache.close();
     }
 
+    /**
+     * Test that a OneTimeUse assertion with no NotOnOrAfter is cached until 
IssueInstant + ttl,
+     * which is how long checkIssueInstant accepts it for, rather than for the 
cache's default TTL.
+     */
+    @Test
+    public void testSAML2OneTimeUseNoNotOnOrAfterCacheExpiry() throws 
Exception {
+        SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
+        callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
+        callbackHandler.setIssuer("www.example.com");
+        callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
+
+        ConditionsBean conditions = new ConditionsBean();
+        conditions.setOneTimeUse(true);
+
+        callbackHandler.setConditions(conditions);
+
+        SAMLCallback samlCallback = new SAMLCallback();
+        SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
+        SamlAssertionWrapper samlAssertion = new 
SamlAssertionWrapper(samlCallback);
+        samlAssertion.getSaml2().getConditions().setNotOnOrAfter(null);
+        Instant issueInstant = samlAssertion.getSaml2().getIssueInstant();
+        assertNotNull(issueInstant);
+
+        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+        WSSecHeader secHeader = new WSSecHeader(doc);
+        secHeader.insertSecurityHeader();
+
+        WSSecSAMLToken wsSign = new WSSecSAMLToken(secHeader);
+
+        Document unsignedDoc = wsSign.build(samlAssertion);
+
+        String outputString =
+            XMLUtils.prettyDocumentToString(unsignedDoc);
+        assertTrue(outputString.contains("OneTimeUse"));
+        assertTrue(!outputString.contains("NotOnOrAfter"));
+
+        WSSConfig wssConfig = WSSConfig.getNewInstance();
+        SamlAssertionValidator assertionValidator = new 
SamlAssertionValidator();
+        assertionValidator.setRequireBearerSignature(false);
+        wssConfig.setValidator(WSConstants.SAML_TOKEN, assertionValidator);
+        wssConfig.setValidator(WSConstants.SAML2_TOKEN, assertionValidator);
+
+        RequestData data = new RequestData();
+        data.setWssConfig(wssConfig);
+        data.setCallbackHandler(callbackHandler);
+        RecordingReplayCache replayCache = new RecordingReplayCache();
+        data.setSamlOneTimeUseReplayCache(replayCache);
+
+        // Successfully verify SAML Token
+        verify(unsignedDoc, wssConfig, data);
+
+        // The IssueInstant is serialized with millisecond precision, so the 
validator sees it truncated
+        
assertEquals(issueInstant.truncatedTo(ChronoUnit.MILLIS).plusSeconds(assertionValidator.getTtl()),
+                     replayCache.lastExpiry);
+
+        // Now try again - a replay attack should be detected
+        try {
+            verify(unsignedDoc, wssConfig, data);
+            fail("Expected failure on a replay attack");
+        } catch (WSSecurityException ex) {
+            assertTrue(ex.getErrorCode() == 
WSSecurityException.ErrorCode.INVALID_SECURITY);
+        }
+
+        replayCache.close();
+    }
+
+    /**
+     * A OneTimeUse assertion that is valid for longer than the replay cache 
can hold its identifier
+     * could be replayed once the identifier has expired from the cache, so it 
must be rejected
+     */
+    @Test
+    public void testSAML2OneTimeUseBeyondCacheTTL() throws Exception {
+        // Valid for 2 hours, but a MemoryReplayCache only holds an identifier 
for 1 hour
+        Document doc = createOneTimeUseAssertionDoc(2 * 60);
+
+        SamlAssertionValidator assertionValidator = new 
SamlAssertionValidator();
+        ReplayCache replayCache = new MemoryReplayCache();
+        RequestData data = createOneTimeUseRequestData(assertionValidator, 
replayCache);
+
+        try {
+            verify(doc, data.getWssConfig(), data);
+            fail("Expected failure as the assertion is valid for longer than 
the cache can hold it");
+        } catch (WSSecurityException ex) {
+            assertTrue(ex.getErrorCode() == 
WSSecurityException.ErrorCode.INVALID_SECURITY);
+        }
+
+        replayCache.close();
+    }
+
+    /**
+     * The check can be disabled, in which case the identifier is held for as 
long as the cache can
+     */
+    @Test
+    public void testSAML2OneTimeUseBeyondCacheTTLAllowed() throws Exception {
+        Document doc = createOneTimeUseAssertionDoc(2 * 60);
+
+        SamlAssertionValidator assertionValidator = new 
SamlAssertionValidator();
+        assertionValidator.setAllowOneTimeUseBeyondCacheTTL(true);
+        ReplayCache replayCache = new MemoryReplayCache();
+        RequestData data = createOneTimeUseRequestData(assertionValidator, 
replayCache);
+
+        verify(doc, data.getWssConfig(), data);
+
+        // Now try again - a replay attack should be detected
+        try {
+            verify(doc, data.getWssConfig(), data);
+            fail("Expected failure on a replay attack");
+        } catch (WSSecurityException ex) {
+            assertTrue(ex.getErrorCode() == 
WSSecurityException.ErrorCode.INVALID_SECURITY);
+        }
+
+        replayCache.close();
+    }
+
+    /**
+     * A custom replay cache that does not say how long it holds an identifier 
for is not checked
+     */
+    @Test
+    public void testSAML2OneTimeUseUnknownCacheTTL() throws Exception {
+        Document doc = createOneTimeUseAssertionDoc(2 * 60);
+
+        SamlAssertionValidator assertionValidator = new 
SamlAssertionValidator();
+        RecordingReplayCache replayCache = new RecordingReplayCache();
+        RequestData data = createOneTimeUseRequestData(assertionValidator, 
replayCache);
+
+        verify(doc, data.getWssConfig(), data);
+        assertNotNull(replayCache.lastExpiry);
+
+        replayCache.close();
+    }
+
+    private Document createOneTimeUseAssertionDoc(int tokenPeriodMinutes) 
throws Exception {
+        SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
+        callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
+        callbackHandler.setIssuer("www.example.com");
+        callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
+
+        ConditionsBean conditions = new ConditionsBean();
+        conditions.setTokenPeriodMinutes(tokenPeriodMinutes);
+        conditions.setOneTimeUse(true);
+        callbackHandler.setConditions(conditions);
+
+        SAMLCallback samlCallback = new SAMLCallback();
+        SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
+        SamlAssertionWrapper samlAssertion = new 
SamlAssertionWrapper(samlCallback);
+
+        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
+        WSSecHeader secHeader = new WSSecHeader(doc);
+        secHeader.insertSecurityHeader();
+
+        WSSecSAMLToken wsSign = new WSSecSAMLToken(secHeader);
+        return wsSign.build(samlAssertion);
+    }
+
+    private RequestData createOneTimeUseRequestData(
+        SamlAssertionValidator assertionValidator, ReplayCache replayCache
+    ) {
+        WSSConfig wssConfig = WSSConfig.getNewInstance();
+        assertionValidator.setRequireBearerSignature(false);
+        wssConfig.setValidator(WSConstants.SAML_TOKEN, assertionValidator);
+        wssConfig.setValidator(WSConstants.SAML2_TOKEN, assertionValidator);
+
+        RequestData data = new RequestData();
+        data.setWssConfig(wssConfig);
+        data.setCallbackHandler(callbackHandler);
+        data.setSamlOneTimeUseReplayCache(replayCache);
+        return data;
+    }
+
     /**
      * Verifies the soap envelope
      *
diff --git 
a/ws-security-stax/src/main/java/org/apache/wss4j/stax/validate/SamlTokenValidatorImpl.java
 
b/ws-security-stax/src/main/java/org/apache/wss4j/stax/validate/SamlTokenValidatorImpl.java
index 7a793e811..7d96f2759 100644
--- 
a/ws-security-stax/src/main/java/org/apache/wss4j/stax/validate/SamlTokenValidatorImpl.java
+++ 
b/ws-security-stax/src/main/java/org/apache/wss4j/stax/validate/SamlTokenValidatorImpl.java
@@ -18,6 +18,7 @@
  */
 package org.apache.wss4j.stax.validate;
 
+import java.time.Duration;
 import java.time.Instant;
 import java.util.List;
 
@@ -74,6 +75,13 @@ public class SamlTokenValidatorImpl extends 
SignatureTokenValidatorImpl implemen
      */
     private boolean requireBearerSignature = true;
 
+    /**
+     * Whether to accept an Assertion with a OneTimeUse Condition that is 
valid for longer than the
+     * replay cache can hold its identifier. Such an Assertion can be replayed 
once its identifier has
+     * expired from the cache, so it is rejected by default.
+     */
+    private boolean allowOneTimeUseBeyondCacheTTL;
+
     /**
      * Set the time in seconds in the future within which the NotBefore time 
of an incoming
      * Assertion is valid. The default is 60 seconds.
@@ -251,9 +259,27 @@ public class SamlTokenValidatorImpl extends 
SignatureTokenValidatorImpl implemen
             && samlAssertion.getSaml2().getConditions().getOneTimeUse() != 
null) {
             String identifier = samlAssertion.getId();
 
+            Instant expires = 
samlAssertion.getSaml2().getConditions().getNotOnOrAfter();
+            if (expires == null && samlAssertion.getSaml2().getIssueInstant() 
!= null) {
+                // With no NotOnOrAfter, checkIssueInstant accepts the 
assertion until IssueInstant + ttl,
+                // so it must stay in the cache until then
+                expires = 
samlAssertion.getSaml2().getIssueInstant().plusSeconds(ttl);
+            }
+
+            // The cache only holds the identifier for so long. An Assertion 
that is valid for longer
+            // could be replayed once its identifier has expired from the 
cache, so reject it
+            Duration maxTTL = replayCache.getMaxTTL();
+            if (!allowOneTimeUseBeyondCacheTTL && maxTTL != null && expires != 
null
+                && expires.isAfter(Instant.now().plus(maxTTL))) {
+                LOG.warn("A OneTimeUse Assertion is valid for longer than the 
replay cache can hold it");
+                throw new WSSecurityException(
+                    WSSecurityException.ErrorCode.INVALID_SECURITY,
+                    "badSamlToken",
+                    new Object[] {"A OneTimeUse Assertion is valid for longer 
than the replay cache can hold it"});
+            }
+
             // Check and cache the identifier atomically, so that concurrent 
requests carrying the
             // same Assertion cannot all pass the check before any of them has 
cached it
-            Instant expires = 
samlAssertion.getSaml2().getConditions().getNotOnOrAfter();
             if (!replayCache.addIfAbsent(identifier, expires)) {
                 throw new WSSecurityException(
                     WSSecurityException.ErrorCode.INVALID_SECURITY,
@@ -288,6 +314,19 @@ public class SamlTokenValidatorImpl extends 
SignatureTokenValidatorImpl implemen
         this.requireBearerSignature = requireBearerSignature;
     }
 
+    /**
+     * Whether to accept an Assertion with a OneTimeUse Condition that is 
valid for longer than the
+     * replay cache can hold its identifier (see ReplayCache#getMaxTTL()). The 
default is false.
+     * Such an Assertion can be replayed once its identifier has expired from 
the cache.
+     */
+    public boolean isAllowOneTimeUseBeyondCacheTTL() {
+        return allowOneTimeUseBeyondCacheTTL;
+    }
+
+    public void setAllowOneTimeUseBeyondCacheTTL(boolean 
allowOneTimeUseBeyondCacheTTL) {
+        this.allowOneTimeUseBeyondCacheTTL = allowOneTimeUseBeyondCacheTTL;
+    }
+
     public int getTtl() {
         return ttl;
     }
diff --git 
a/ws-security-stax/src/test/java/org/apache/wss4j/stax/test/ReplayTest.java 
b/ws-security-stax/src/test/java/org/apache/wss4j/stax/test/ReplayTest.java
index a237504ac..fe03da244 100644
--- a/ws-security-stax/src/test/java/org/apache/wss4j/stax/test/ReplayTest.java
+++ b/ws-security-stax/src/test/java/org/apache/wss4j/stax/test/ReplayTest.java
@@ -33,6 +33,7 @@ import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
 
 import org.apache.wss4j.common.cache.EHCacheReplayCache;
+import org.apache.wss4j.common.cache.MemoryReplayCache;
 import org.apache.wss4j.common.cache.ReplayCache;
 import org.apache.wss4j.common.ext.WSSecurityException;
 import org.apache.wss4j.common.saml.bean.ConditionsBean;
@@ -543,4 +544,58 @@ public class ReplayTest extends AbstractTestBase {
         replayCache.close();
     }
 
-}
\ No newline at end of file
+    /**
+     * A OneTimeUse assertion that is valid for longer than the replay cache 
can hold its identifier
+     * could be replayed once the identifier has expired from the cache, so it 
must be rejected
+     */
+    @Test
+    public void testSAML2OneTimeUseBeyondCacheTTL() throws Exception {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        {
+            SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
+            callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
+            callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
+            callbackHandler.setIssuer("www.example.com");
+            callbackHandler.setSignAssertion(false);
+
+            // Valid for 2 hours, but a MemoryReplayCache only holds an 
identifier for 1 hour
+            ConditionsBean conditions = new ConditionsBean();
+            conditions.setTokenPeriodMinutes(2 * 60);
+            conditions.setOneTimeUse(true);
+            callbackHandler.setConditions(conditions);
+
+            InputStream sourceDocument = 
this.getClass().getClassLoader().getResourceAsStream("testdata/plain-soap-1.1.xml");
+            String action = WSHandlerConstants.SAML_TOKEN_UNSIGNED;
+            Properties properties = new Properties();
+            properties.put(WSHandlerConstants.SAML_CALLBACK_REF, 
callbackHandler);
+            Document securedDocument = 
doOutboundSecurityWithWSS4J(sourceDocument, action, properties);
+
+            javax.xml.transform.Transformer transformer = 
TRANSFORMER_FACTORY.newTransformer();
+            transformer.transform(new DOMSource(securedDocument), new 
StreamResult(baos));
+        }
+
+        ReplayCache replayCache = new MemoryReplayCache();
+        {
+            WSSSecurityProperties securityProperties = new 
WSSSecurityProperties();
+
+            SamlTokenValidatorImpl validator = new SamlTokenValidatorImpl();
+            validator.setRequireBearerSignature(false);
+            securityProperties.addValidator(WSSConstants.TAG_SAML2_ASSERTION, 
validator);
+            securityProperties.addValidator(WSSConstants.TAG_SAML_ASSERTION, 
validator);
+
+            securityProperties.setSamlOneTimeUseReplayCache(replayCache);
+            InboundWSSec wsSecIn = WSSec.getInboundWSSec(securityProperties);
+            XMLStreamReader xmlStreamReader = 
wsSecIn.processInMessage(xmlInputFactory.createXMLStreamReader(new 
ByteArrayInputStream(baos.toByteArray())));
+
+            try {
+                StAX2DOM.readDoc(documentBuilderFactory.newDocumentBuilder(), 
xmlStreamReader);
+                fail("Exception expected");
+            } catch (XMLStreamException e) {
+                assertTrue(e.getCause() instanceof XMLSecurityException);
+            }
+        }
+
+        replayCache.close();
+    }
+
+}

Reply via email to