You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by co...@apache.org on 2020/04/16 07:19:34 UTC
[cxf] branch master updated: CXF-7594 - Support EhCache 3+ (#658)
This is an automated email from the ASF dual-hosted git repository.
coheigea pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/cxf.git
The following commit(s) were added to refs/heads/master by this push:
new 74816c5 CXF-7594 - Support EhCache 3+ (#658)
74816c5 is described below
commit 74816c53c77e814bb6a1422b9ec525b839c7f078
Author: Colm O hEigeartaigh <co...@users.noreply.github.com>
AuthorDate: Thu Apr 16 08:19:21 2020 +0100
CXF-7594 - Support EhCache 3+ (#658)
* Rebasing
* Fixing systests CachingTest
* Ported SAML SSO TokenReplayCache
* Removing persistence configuration from the TokenStore, where it's not required
* Refactoring TokenStore tests into a single parameterized test
* Finished porting SAML SSO to Ehcache3
* Fixing (some) OSGi issues
* Removing accidental change
* osgi: avoid javax.xml.bind version range to support Java 8
* Porting XKMS client cache to use ehcache3
* Fixing STS EhCache IdentityCache issues
Co-authored-by: Alexey Markevich <bu...@gmail.com>
---
distribution/javadoc/pom.xml | 4 +-
osgi/bundle/compatible/pom.xml | 2 +-
.../karaf/features/src/main/resources/features.xml | 6 +-
parent/pom.xml | 1 -
rt/rs/security/sso/saml/pom.xml | 6 +-
.../AbstractRequestAssertionConsumerHandler.java | 4 +-
.../security/saml/sso/EHCacheTokenReplayCache.java | 166 +++++++++-----------
.../cxf/rs/security/saml/sso/EHCacheUtil.java | 88 -----------
.../saml/sso/SAMLSSOResponseValidator.java | 7 +-
.../cxf/rs/security/saml/sso/TokenReplayCache.java | 5 +-
.../saml/sso/state/EHCacheSPStateManager.java | 173 +++++++++------------
.../rs/security/saml/sso/state/RequestState.java | 26 ++++
.../rs/security/saml/sso/state/ResponseState.java | 23 +++
.../saml/src/main/resources/cxf-samlp-ehcache.xml | 47 +++++-
.../cxf/rs/security/saml/sso/EHCacheUtilTest.java | 59 -------
.../rs/security/saml/sso/SPStateManagerTest.java | 133 ++++++++++++++++
.../rs/security/saml/sso/TokenReplayCacheTest.java | 108 +++++++++++++
.../saml/src/test/resources/cxf-test-ehcache.xml | 5 -
rt/ws/security/pom.xml | 6 +-
.../CXFEHCacheExpiry.java} | 14 +-
.../ws/security/cache/CXFEHCacheReplayCache.java | 5 +-
.../apache/cxf/ws/security/cache/EHCacheUtils.java | 59 -------
.../KerberosTokenInterceptorProvider.java | 22 ++-
.../policy/interceptors/NegotiationUtils.java | 3 +-
.../SecureConversationInInterceptor.java | 52 ++++---
.../SecureConversationOutInterceptor.java | 47 +++---
.../SpnegoContextTokenInInterceptor.java | 35 +++--
.../SpnegoContextTokenOutInterceptor.java | 40 +++--
.../ws/security/tokenstore/EHCacheTokenStore.java | 141 ++++++-----------
.../tokenstore/EHCacheTokenStoreFactory.java | 3 +-
.../tokenstore/MemoryTokenStoreFactory.java | 1 +
...nStoreFactory.java => TokenStoreException.java} | 12 +-
.../ws/security/tokenstore/TokenStoreFactory.java | 4 +-
.../ws/security/tokenstore/TokenStoreUtils.java | 6 +-
.../ws/security/trust/DefaultSTSTokenCacher.java | 14 +-
.../cxf/ws/security/trust/STSLoginModule.java | 3 +-
.../cxf/ws/security/trust/STSTokenCacher.java | 13 +-
.../cxf/ws/security/trust/STSTokenRetriever.java | 7 +-
.../cxf/ws/security/trust/STSTokenValidator.java | 3 +-
.../wss4j/PolicyBasedWSS4JOutInterceptor.java | 3 +-
.../cxf/ws/security/wss4j/WSS4JInInterceptor.java | 13 +-
.../ws/security/wss4j/WSS4JStaxInInterceptor.java | 3 +-
.../ws/security/wss4j/WSS4JStaxOutInterceptor.java | 7 +-
.../apache/cxf/ws/security/wss4j/WSS4JUtils.java | 19 ++-
.../policyhandlers/AbstractBindingBuilder.java | 13 +-
.../AbstractCommonBindingHandler.java | 3 +-
.../policyhandlers/AbstractStaxBindingHandler.java | 3 +-
.../policyhandlers/AsymmetricBindingHandler.java | 55 ++++---
.../StaxSymmetricBindingHandler.java | 23 ++-
.../StaxTransportBindingHandler.java | 16 +-
.../policyhandlers/SymmetricBindingHandler.java | 3 +-
.../KerberosTokenPolicyValidator.java | 11 +-
rt/ws/security/src/main/resources/cxf-ehcache.xml | 42 ++++-
.../cxf/ws/security/cache/EHCacheUtilsTest.java | 75 ---------
.../security/tokenstore/MemoryTokenStoreTest.java | 91 -----------
.../ws/security/tokenstore/SecurityTokenTest.java | 14 ++
...acheTokenStoreTest.java => TokenStoreTest.java} | 32 ++--
.../security/wss4j/AbstractPolicySecurityTest.java | 11 +-
.../src/test/resources/cxf-test-ehcache.xml | 16 --
services/sts/sts-core/pom.xml | 6 +-
.../cxf/sts/cache/AbstractIdentityCache.java | 6 +-
.../cxf/sts/cache/DefaultInMemoryTokenStore.java | 11 +-
.../apache/cxf/sts/cache/EHCacheIdentityCache.java | 65 +++-----
...dentityCache.java => EHCacheIdentityValue.java} | 19 ++-
.../org/apache/cxf/sts/cache/IdentityCache.java | 4 -
.../apache/cxf/sts/cache/MemoryIdentityCache.java | 12 --
.../sts-core/src/main/resources/sts-ehcache.xml | 26 +++-
.../cxf/sts/cache/MemoryIdentityCacheTest.java | 6 -
.../cxf/sts/operation/CancelSCTUnitTest.java | 10 +-
.../apache/cxf/sts/operation/IssueJWTUnitTest.java | 9 +-
.../apache/cxf/sts/operation/IssueSCTUnitTest.java | 10 +-
.../cxf/sts/operation/RenewSamlUnitTest.java | 3 +-
.../cxf/sts/operation/ValidateSCTUnitTest.java | 10 +-
.../cxf/sts/token/canceller/SCTCancellerTest.java | 10 +-
.../sts/token/provider/JWTTokenProviderTest.java | 9 +-
.../cxf/sts/token/provider/SCTProviderTest.java | 10 +-
.../renewer/SAMLTokenRenewerLifetimeTest.java | 3 +-
.../sts/token/renewer/SAMLTokenRenewerPOPTest.java | 3 +-
.../token/renewer/SAMLTokenRenewerRealmTest.java | 3 +-
.../sts/token/renewer/SAMLTokenRenewerTest.java | 3 +-
.../validator/JWTTokenValidatorRealmTest.java | 10 +-
.../sts/token/validator/JWTTokenValidatorTest.java | 10 +-
.../SAMLTokenValidatorCachedRealmTest.java | 3 +-
.../token/validator/SAMLTokenValidatorTest.java | 3 +-
.../cxf/sts/token/validator/SCTValidatorTest.java | 10 +-
services/sts/systests/advanced/pom.xml | 4 +-
.../cxf/systest/sts/caching/CachingTest.java | 2 -
.../cxf/systest/sts/caching/ServerCachingTest.java | 2 -
services/sts/systests/basic/pom.xml | 4 +-
services/xkms/xkms-client/pom.xml | 4 +-
.../org/apache/cxf/xkms/cache/EHCacheUtil.java | 88 -----------
.../cxf/xkms/cache/EHCacheXKMSClientCache.java | 101 ++++++------
.../cxf/xkms/cache/XKMSClientCacheException.java | 18 +--
.../xkms/crypto/provider/XkmsCryptoProvider.java | 8 +-
.../crypto/provider/XkmsCryptoProviderFactory.java | 40 ++++-
.../src/main/resources/cxf-xkms-client-ehcache.xml | 23 ++-
.../xkms-features/src/main/resources/features.xml | 2 +-
systests/rs-security/pom.xml | 14 --
.../apache/cxf/systest/ws/cache/CachingTest.java | 89 +++++++++--
.../cxf/systest/ws/cache/per-proxy-cache.xml | 57 +++++--
100 files changed, 1323 insertions(+), 1213 deletions(-)
diff --git a/distribution/javadoc/pom.xml b/distribution/javadoc/pom.xml
index b6517bf..01770bd 100644
--- a/distribution/javadoc/pom.xml
+++ b/distribution/javadoc/pom.xml
@@ -206,9 +206,9 @@
<artifactId>bcprov-jdk15on</artifactId>
</dependency>
<dependency>
- <groupId>net.sf.ehcache</groupId>
+ <groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
- <version>${cxf.ehcache.version}</version>
+ <version>${cxf.ehcache3.version}</version>
</dependency>
<dependency>
<groupId>rhino</groupId>
diff --git a/osgi/bundle/compatible/pom.xml b/osgi/bundle/compatible/pom.xml
index 03006be..43b54c4 100644
--- a/osgi/bundle/compatible/pom.xml
+++ b/osgi/bundle/compatible/pom.xml
@@ -154,7 +154,7 @@
antlr*;resolution:=optional,
com.sun*;resolution:=optional,
com.ctc.wstx.msv*;resolution:=optional,
- net.sf.ehcache*;resolution:=optional,
+ org.ehcache*;resolution:=optional,
org.codehaus.stax2*;resolution:=optional,
commonj.sdo*;resolution:=optional,
javax.ws.rs*;resolution:=optional,
diff --git a/osgi/karaf/features/src/main/resources/features.xml b/osgi/karaf/features/src/main/resources/features.xml
index cabfa74..7057bcf 100644
--- a/osgi/karaf/features/src/main/resources/features.xml
+++ b/osgi/karaf/features/src/main/resources/features.xml
@@ -128,12 +128,13 @@
<bundle start-level="40">mvn:org.apache.cxf/cxf-rt-ws-mex/${project.version}</bundle>
</feature>
<feature name="cxf-ws-security" version="${project.version}">
+ <feature prerequisite="true">wrap</feature>
<feature version="${cxf.wss4j.version}">wss4j</feature>
<feature version="${project.version}">cxf-rt-security-saml</feature>
<feature version="${project.version}">cxf-ws-policy</feature>
<feature version="${project.version}">cxf-ws-addr</feature>
<bundle dependency="true">mvn:org.apache.geronimo.specs/geronimo-jta_1.1_spec/${cxf.geronimo.jta.version}</bundle>
- <bundle start-level="40" dependency="true">mvn:net.sf.ehcache/ehcache/${cxf.ehcache.version}</bundle>
+ <bundle start-level="40" dependency="true">wrap:mvn:org.ehcache/ehcache/${cxf.ehcache3.version}$overwrite=merge&Import-Package=javax.xml.bind*,*;resolution:=optional</bundle>
<bundle start-level="40">mvn:org.apache.cxf/cxf-rt-ws-security/${project.version}</bundle>
</feature>
<feature name="cxf-rt-security" version="${project.version}">
@@ -496,8 +497,9 @@
<bundle>mvn:org.apache.cxf/cxf-wstx-msv-validation/${project.version}</bundle-->
</feature>
<feature name="cxf-sts" version="${project.version}">
+ <feature prerequisite="true">wrap</feature>
<bundle start-level="40" dependency="true">mvn:com.hazelcast/hazelcast/${cxf.hazelcast.version}</bundle>
- <bundle start-level="40" dependency="true">mvn:net.sf.ehcache/ehcache/${cxf.ehcache.version}</bundle>
+ <bundle start-level="40" dependency="true">wrap:mvn:org.ehcache/ehcache/${cxf.ehcache3.version}$overwrite=merge&Import-Package=javax.xml.bind*,*;resolution:=optional</bundle>
<bundle start-level="40">mvn:org.apache.cxf/cxf-rt-rs-json-basic/${project.version}</bundle>
<bundle start-level="40">mvn:org.apache.cxf/cxf-rt-rs-security-jose/${project.version}</bundle>
<feature version="${project.version}">cxf-core</feature>
diff --git a/parent/pom.xml b/parent/pom.xml
index 5f93219..49d5d55 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -105,7 +105,6 @@
<cxf.dom4j.version>2.1.1</cxf.dom4j.version>
<cxf.dropwizard3.version>3.2.6</cxf.dropwizard3.version>
<cxf.dropwizard4.version>4.1.2</cxf.dropwizard4.version>
- <cxf.ehcache.version>2.10.6</cxf.ehcache.version>
<cxf.ehcache3.version>3.8.1</cxf.ehcache3.version>
<cxf.el-api.version>3.0.3</cxf.el-api.version>
<cxf.findbugs.version>3.0.2</cxf.findbugs.version>
diff --git a/rt/rs/security/sso/saml/pom.xml b/rt/rs/security/sso/saml/pom.xml
index b932556..4b4fe77 100644
--- a/rt/rs/security/sso/saml/pom.xml
+++ b/rt/rs/security/sso/saml/pom.xml
@@ -34,7 +34,7 @@
<cxf.module.name>org.apache.cxf.rs.security.sso.saml</cxf.module.name>
<cxf.osgi.import>
javax.servlet*;version="${cxf.osgi.javax.servlet.version}",
- net.sf.ehcache*;resolution:=optional;version="[2.5, 3.0.0)",
+ org.ehcache*;resolution:=optional;version="[3.0.0, 4.0.0)",
org.opensaml*;version="${cxf.opensaml.osgi.version.range}",
javax.xml.bind*;version="${cxf.osgi.javax.bind.version}",
javax.annotation*;version="${cxf.osgi.javax.annotation.version}"
@@ -66,9 +66,9 @@
<artifactId>${cxf.servlet-api.artifact}</artifactId>
</dependency>
<dependency>
- <groupId>net.sf.ehcache</groupId>
+ <groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
- <version>${cxf.ehcache.version}</version>
+ <version>${cxf.ehcache3.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
diff --git a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/AbstractRequestAssertionConsumerHandler.java b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/AbstractRequestAssertionConsumerHandler.java
index 8bf89e2..82c7492 100644
--- a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/AbstractRequestAssertionConsumerHandler.java
+++ b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/AbstractRequestAssertionConsumerHandler.java
@@ -92,7 +92,7 @@ public abstract class AbstractRequestAssertionConsumerHandler extends AbstractSS
this.replayCache = replayCache;
}
- public TokenReplayCache<String> getReplayCache() {
+ public TokenReplayCache<String> getReplayCache() throws Exception {
if (replayCache == null) {
Bus bus = (Bus)messageContext.getContextualProperty(Bus.class.getName());
replayCache = new EHCacheTokenReplayCache(bus);
@@ -359,7 +359,7 @@ public abstract class AbstractRequestAssertionConsumerHandler extends AbstractSS
}
return ssoResponseValidator.validateSamlResponse(samlResponse, postBinding);
- } catch (WSSecurityException ex) {
+ } catch (Exception ex) {
reportError("INVALID_SAML_RESPONSE");
throw ExceptionUtils.toBadRequestException(ex, null);
}
diff --git a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/EHCacheTokenReplayCache.java b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/EHCacheTokenReplayCache.java
index 61cc5dd..58b96ee 100644
--- a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/EHCacheTokenReplayCache.java
+++ b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/EHCacheTokenReplayCache.java
@@ -22,155 +22,137 @@ package org.apache.cxf.rs.security.saml.sso;
import java.io.File;
import java.io.IOException;
import java.net.URL;
+import java.time.Instant;
+import java.util.Random;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-import net.sf.ehcache.config.DiskStoreConfiguration;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.jaxrs.utils.ResourceUtils;
+import org.apache.wss4j.common.cache.EHCacheReplayCache;
+import org.apache.wss4j.common.cache.EHCacheValue;
+import org.apache.wss4j.common.util.Loader;
+import org.ehcache.Cache;
+import org.ehcache.CacheManager;
+import org.ehcache.Status;
+import org.ehcache.config.builders.CacheConfigurationBuilder;
+import org.ehcache.config.builders.CacheManagerBuilder;
+import org.ehcache.xml.XmlConfiguration;
/**
* An in-memory EHCache implementation of the TokenReplayCache interface.
* The default TTL is 60 minutes and the max TTL is 12 hours.
*/
+
public class EHCacheTokenReplayCache implements TokenReplayCache<String> {
- public static final long DEFAULT_TTL = 3600L;
- public static final long MAX_TTL = DEFAULT_TTL * 12L;
public static final String CACHE_KEY = "cxf.samlp.replay.cache";
+
+ private static final org.slf4j.Logger LOG =
+ org.slf4j.LoggerFactory.getLogger(EHCacheReplayCache.class);
private static final String DEFAULT_CONFIG_URL = "/cxf-samlp-ehcache.xml";
- private Ehcache cache;
- private CacheManager cacheManager;
- private long ttl = DEFAULT_TTL;
+ private final Cache<String, EHCacheValue> cache;
+ private final CacheManager cacheManager;
- public EHCacheTokenReplayCache() {
+ public EHCacheTokenReplayCache()
+ throws IllegalAccessException, InstantiationException, ClassNotFoundException {
this(DEFAULT_CONFIG_URL, null);
}
- public EHCacheTokenReplayCache(Bus bus) {
+ public EHCacheTokenReplayCache(Bus bus)
+ throws IllegalAccessException, InstantiationException, ClassNotFoundException {
this(DEFAULT_CONFIG_URL, bus);
}
- public EHCacheTokenReplayCache(String configFileURL) {
- this(configFileURL, null);
+ public EHCacheTokenReplayCache(String configFile)
+ throws IllegalAccessException, InstantiationException, ClassNotFoundException {
+ this(configFile, null);
}
- public EHCacheTokenReplayCache(String configFileURL, Bus bus) {
- createCache(configFileURL, bus);
- }
-
- private void createCache(String configFile, Bus bus) {
+ public EHCacheTokenReplayCache(String configFile, Bus bus)
+ throws IllegalAccessException, ClassNotFoundException, InstantiationException {
if (bus == null) {
bus = BusFactory.getThreadDefaultBus(true);
}
URL configFileURL = null;
try {
configFileURL =
- ResourceUtils.getClasspathResourceURL(configFile, EHCacheTokenReplayCache.class, bus);
+ ResourceUtils.getClasspathResourceURL(configFile, EHCacheTokenReplayCache.class, bus);
} catch (Exception ex) {
// ignore
}
- if (configFileURL == null) {
- cacheManager = EHCacheUtil.createCacheManager();
- } else {
- Configuration conf = ConfigurationFactory.parseConfiguration(configFileURL);
-
- if (bus != null) {
- conf.setName(bus.getId());
- DiskStoreConfiguration dsc = conf.getDiskStoreConfiguration();
- if (dsc != null && "java.io.tmpdir".equals(dsc.getOriginalPath())) {
- String path = conf.getDiskStoreConfiguration().getPath() + File.separator
- + bus.getId();
- conf.getDiskStoreConfiguration().setPath(path);
- }
- }
-
- cacheManager = EHCacheUtil.createCacheManager(conf);
- }
- CacheConfiguration cc = EHCacheUtil.getCacheConfiguration(CACHE_KEY, cacheManager);
+ XmlConfiguration xmlConfig = new XmlConfiguration(getConfigFileURL(configFileURL));
+ CacheConfigurationBuilder<String, EHCacheValue> configurationBuilder =
+ xmlConfig.newCacheConfigurationBuilderFromTemplate(CACHE_KEY,
+ String.class, EHCacheValue.class);
+ // Note, we don't require strong random values here
+ String diskKey = CACHE_KEY + "-" + Math.abs(new Random().nextInt());
+ cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache(CACHE_KEY, configurationBuilder)
+ .with(CacheManagerBuilder.persistence(new File(System.getProperty("java.io.tmpdir"), diskKey))).build();
- Ehcache newCache = new Cache(cc);
- cache = cacheManager.addCacheIfAbsent(newCache);
- }
+ cacheManager.init();
+ cache = cacheManager.getCache(CACHE_KEY, String.class, EHCacheValue.class);
- /**
- * Set a new (default) TTL value in seconds
- * @param newTtl a new (default) TTL value in seconds
- */
- public void setTTL(long newTtl) {
- ttl = newTtl;
}
- /**
- * Get the (default) TTL value in seconds
- * @return the (default) TTL value in seconds
- */
- public long getTTL() {
- return ttl;
+ private URL getConfigFileURL(URL suppliedConfigFileURL) {
+ if (suppliedConfigFileURL == null) {
+ //using the default
+ URL configFileURL = null;
+ try {
+ configFileURL = Loader.getResource(DEFAULT_CONFIG_URL);
+ if (configFileURL == null) {
+ configFileURL = new URL(DEFAULT_CONFIG_URL);
+ }
+ return configFileURL;
+ } catch (IOException e) {
+ // Do nothing
+ LOG.debug(e.getMessage());
+ }
+ }
+ return suppliedConfigFileURL;
}
/**
* Add the given identifier to the cache. It will be cached for a default amount of time.
- * @param id The identifier to be added
+ * @param identifier The identifier to be added
*/
- public void putId(String id) {
- putId(id, ttl);
+ public void putId(String identifier) {
+ putId(identifier, null);
}
/**
- * Add the given identifier to the cache.
- * @param id The identifier to be added
- * @param timeToLive The length of time to cache the Identifier in seconds
+ * Add the given identifier to the cache to be cached for the given time
+ * @param identifier The identifier to be added
+ * @param expiry A custom expiry time for the identifier. Can be null in which case, the default expiry is used.
*/
- public void putId(String id, long timeToLive) {
- if (id == null || "".equals(id)) {
+ public void putId(String identifier, Instant expiry) {
+ if (identifier == null || "".equals(identifier)) {
return;
}
- int parsedTTL = (int)timeToLive;
- if (timeToLive != parsedTTL || parsedTTL < 0 || parsedTTL > MAX_TTL) {
- // Default to configured value
- parsedTTL = (int)ttl;
- if (ttl != parsedTTL) {
- // Fall back to 60 minutes if the default TTL is set incorrectly
- parsedTTL = 3600;
- }
- }
- Element element = new Element(id, id, parsedTTL, parsedTTL);
- element.resetAccessStatistics();
- cache.put(element);
+ cache.put(identifier, new EHCacheValue(identifier, expiry));
}
/**
- * Return the given identifier if it is contained in the cache, otherwise null.
- * @param id The identifier to check
+ * Return true if the given identifier is contained in the cache
+ * @param identifier The identifier to check
*/
- public String getId(String id) {
- Element element = cache.get(id);
- if (element != null) {
- if (cache.isExpired(element)) {
- cache.remove(id);
- return null;
- }
- return (String)element.getObjectValue();
+ public boolean contains(String identifier) {
+ if (cache == null) {
+ return false;
}
- return null;
+ EHCacheValue element = cache.get(identifier);
+ return element != null;
}
- public void close() throws IOException {
- if (cacheManager != null) {
- cacheManager.shutdown();
- cacheManager = null;
- cache = null;
+ public void close() {
+ if (cacheManager.getStatus() == Status.AVAILABLE) {
+ cacheManager.removeCache(CACHE_KEY);
+ cacheManager.close();
}
}
+
}
diff --git a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/EHCacheUtil.java b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/EHCacheUtil.java
deleted file mode 100644
index 73c31bd..0000000
--- a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/EHCacheUtil.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.rs.security.saml.sso;
-
-import java.lang.reflect.Method;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-
-/**
- */
-public final class EHCacheUtil {
- private static Method cacheManagerCreateMethodNoArg;
- private static Method cacheManagerCreateMethodConfigurationArg;
- static {
- // these methods are either completely available or absent (valid assumption from 2.5.0 to 2.7.2 so far)
- try {
- // from 2.5.2
- cacheManagerCreateMethodNoArg = CacheManager.class.getMethod("newInstance", (Class<?>[])null);
- cacheManagerCreateMethodConfigurationArg = CacheManager.class.getMethod("newInstance", Configuration.class);
- } catch (NoSuchMethodException e) {
- try {
- // before 2.5.2
- cacheManagerCreateMethodNoArg = CacheManager.class.getMethod("create", (Class<?>[])null);
- cacheManagerCreateMethodConfigurationArg = CacheManager.class.getMethod("create", Configuration.class);
- } catch (Throwable t) {
- // ignore
- }
- }
- }
-
- private EHCacheUtil() {
- //
- }
-
- public static CacheConfiguration getCacheConfiguration(String key, CacheManager cacheManager) {
- CacheConfiguration cc = cacheManager.getConfiguration().getCacheConfigurations().get(key);
- if (cc == null && key.contains("-")) {
- cc = cacheManager.getConfiguration().getCacheConfigurations().get(
- key.substring(0, key.lastIndexOf('-') - 1));
- }
- if (cc == null) {
- cc = cacheManager.getConfiguration().getDefaultCacheConfiguration();
- }
- if (cc == null) {
- cc = new CacheConfiguration();
- } else {
- cc = cc.clone();
- }
- cc.setName(key);
- return cc;
- }
-
- public static CacheManager createCacheManager() throws CacheException {
- try {
- return (CacheManager)cacheManagerCreateMethodNoArg.invoke(null, (Object[])null);
- } catch (Exception e) {
- throw new CacheException(e);
- }
- }
-
- public static CacheManager createCacheManager(Configuration conf) throws CacheException {
- try {
- return (CacheManager)cacheManagerCreateMethodConfigurationArg.invoke(null, new Object[]{conf});
- } catch (Exception e) {
- throw new CacheException(e);
- }
- }
-}
diff --git a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/SAMLSSOResponseValidator.java b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/SAMLSSOResponseValidator.java
index 6772436..3f6de43 100644
--- a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/SAMLSSOResponseValidator.java
+++ b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/SAMLSSOResponseValidator.java
@@ -18,7 +18,6 @@
*/
package org.apache.cxf.rs.security.saml.sso;
-import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.logging.Logger;
@@ -240,11 +239,9 @@ public class SAMLSSOResponseValidator {
// Need to keep bearer assertion IDs based on NotOnOrAfter to detect replay attacks
if (postBinding && replayCache != null) {
- if (replayCache.getId(id) == null) {
+ if (!replayCache.contains(id)) {
Instant expires = Instant.ofEpochMilli(subjectConfData.getNotOnOrAfter().toDate().getTime());
- Instant currentTime = Instant.now();
- long ttl = Duration.between(currentTime, expires).getSeconds();
- replayCache.putId(id, ttl);
+ replayCache.putId(id, expires);
} else {
LOG.warning("Replay attack with token id: " + id);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
diff --git a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCache.java b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCache.java
index 828aaa1..6175e6d 100644
--- a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCache.java
+++ b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCache.java
@@ -21,14 +21,15 @@ package org.apache.cxf.rs.security.saml.sso;
import java.io.Closeable;
import java.io.IOException;
+import java.time.Instant;
public interface TokenReplayCache<T> extends Closeable {
- T getId(T id);
+ boolean contains(T id);
void putId(T id);
- void putId(T id, long timeToLive);
+ void putId(T id, Instant expiry);
void close() throws IOException;
}
\ No newline at end of file
diff --git a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/EHCacheSPStateManager.java b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/EHCacheSPStateManager.java
index 2ae0e06..f79dad3 100644
--- a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/EHCacheSPStateManager.java
+++ b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/EHCacheSPStateManager.java
@@ -21,19 +21,18 @@ package org.apache.cxf.rs.security.saml.sso.state;
import java.io.File;
import java.io.IOException;
import java.net.URL;
+import java.util.Random;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-import net.sf.ehcache.config.DiskStoreConfiguration;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.jaxrs.utils.ResourceUtils;
-import org.apache.cxf.rs.security.saml.sso.EHCacheUtil;
+import org.apache.wss4j.common.util.Loader;
+import org.ehcache.Cache;
+import org.ehcache.CacheManager;
+import org.ehcache.Status;
+import org.ehcache.config.builders.CacheConfigurationBuilder;
+import org.ehcache.config.builders.CacheManagerBuilder;
+import org.ehcache.xml.XmlConfiguration;
/**
* An in-memory EHCache implementation of the SPStateManager interface.
@@ -41,33 +40,33 @@ import org.apache.cxf.rs.security.saml.sso.EHCacheUtil;
*/
public class EHCacheSPStateManager implements SPStateManager {
- public static final long DEFAULT_TTL = 60L * 5L;
public static final String REQUEST_CACHE_KEY = "cxf.samlp.request.state.cache";
public static final String RESPONSE_CACHE_KEY = "cxf.samlp.response.state.cache";
private static final String DEFAULT_CONFIG_URL = "/cxf-samlp-ehcache.xml";
+ private static final org.slf4j.Logger LOG =
+ org.slf4j.LoggerFactory.getLogger(EHCacheSPStateManager.class);
- private Ehcache requestCache;
- private Ehcache responseCache;
- private CacheManager cacheManager;
- private long ttl = DEFAULT_TTL;
+ private final Cache<String, RequestState> requestCache;
+ private final Cache<String, ResponseState> responseCache;
+ private final CacheManager requestCacheManager;
+ private final CacheManager responseCacheManager;
- public EHCacheSPStateManager() {
+ public EHCacheSPStateManager() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
this(DEFAULT_CONFIG_URL, null);
}
- public EHCacheSPStateManager(Bus bus) {
+ public EHCacheSPStateManager(Bus bus)
+ throws IllegalAccessException, InstantiationException, ClassNotFoundException {
this(DEFAULT_CONFIG_URL, bus);
}
- public EHCacheSPStateManager(String configFileURL) {
+ public EHCacheSPStateManager(String configFileURL)
+ throws IllegalAccessException, InstantiationException, ClassNotFoundException {
this(configFileURL, null);
}
- public EHCacheSPStateManager(String configFileURL, Bus bus) {
- createCaches(configFileURL, bus);
- }
-
- private void createCaches(String configFile, Bus bus) {
+ public EHCacheSPStateManager(String configFile, Bus bus)
+ throws IllegalAccessException, ClassNotFoundException, InstantiationException {
if (bus == null) {
bus = BusFactory.getThreadDefaultBus(true);
}
@@ -79,70 +78,63 @@ public class EHCacheSPStateManager implements SPStateManager {
} catch (Exception ex) {
// ignore
}
- if (configFileURL == null) {
- cacheManager = EHCacheUtil.createCacheManager();
- } else {
- Configuration conf = ConfigurationFactory.parseConfiguration(configFileURL);
-
- if (bus != null) {
- conf.setName(bus.getId());
- DiskStoreConfiguration dsc = conf.getDiskStoreConfiguration();
- if (dsc != null && "java.io.tmpdir".equals(dsc.getOriginalPath())) {
- String path = conf.getDiskStoreConfiguration().getPath() + File.separator
- + bus.getId();
- conf.getDiskStoreConfiguration().setPath(path);
- }
- }
- cacheManager = EHCacheUtil.createCacheManager(conf);
- }
+ XmlConfiguration xmlConfig = new XmlConfiguration(getConfigFileURL(configFileURL));
+ CacheConfigurationBuilder<String, RequestState> requestConfigurationBuilder =
+ xmlConfig.newCacheConfigurationBuilderFromTemplate(REQUEST_CACHE_KEY,
+ String.class, RequestState.class);
- CacheConfiguration requestCC = EHCacheUtil.getCacheConfiguration(REQUEST_CACHE_KEY, cacheManager);
+ // Note, we don't require strong random values here
+ String diskKey = REQUEST_CACHE_KEY + "-" + Math.abs(new Random().nextInt());
+ requestCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
+ .withCache(REQUEST_CACHE_KEY, requestConfigurationBuilder)
+ .with(CacheManagerBuilder.persistence(new File(System.getProperty("java.io.tmpdir"), diskKey))).build();
- Ehcache newCache = new Cache(requestCC);
- requestCache = cacheManager.addCacheIfAbsent(newCache);
+ requestCacheManager.init();
+ requestCache = requestCacheManager.getCache(REQUEST_CACHE_KEY, String.class, RequestState.class);
- CacheConfiguration responseCC = EHCacheUtil.getCacheConfiguration(RESPONSE_CACHE_KEY, cacheManager);
+ CacheConfigurationBuilder<String, ResponseState> responseConfigurationBuilder =
+ xmlConfig.newCacheConfigurationBuilderFromTemplate(RESPONSE_CACHE_KEY,
+ String.class, ResponseState.class);
- newCache = new Cache(responseCC);
- responseCache = cacheManager.addCacheIfAbsent(newCache);
- }
+ // Note, we don't require strong random values here
+ diskKey = RESPONSE_CACHE_KEY + "-" + Math.abs(new Random().nextInt());
+ responseCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
+ .withCache(RESPONSE_CACHE_KEY, responseConfigurationBuilder)
+ .with(CacheManagerBuilder.persistence(new File(System.getProperty("java.io.tmpdir"), diskKey))).build();
- /**
- * Set a new (default) TTL value in seconds
- * @param newTtl a new (default) TTL value in seconds
- */
- public void setTTL(long newTtl) {
- ttl = newTtl;
+ responseCacheManager.init();
+ responseCache = responseCacheManager.getCache(RESPONSE_CACHE_KEY, String.class, ResponseState.class);
}
- /**
- * Get the (default) TTL value in seconds
- * @return the (default) TTL value in seconds
- */
- public long getTTL() {
- return ttl;
+ private URL getConfigFileURL(URL suppliedConfigFileURL) {
+ if (suppliedConfigFileURL == null) {
+ //using the default
+ URL configFileURL = null;
+ try {
+ configFileURL = Loader.getResource(DEFAULT_CONFIG_URL);
+ if (configFileURL == null) {
+ configFileURL = new URL(DEFAULT_CONFIG_URL);
+ }
+ return configFileURL;
+ } catch (IOException e) {
+ // Do nothing
+ LOG.debug(e.getMessage());
+ }
+ }
+ return suppliedConfigFileURL;
}
public ResponseState getResponseState(String securityContextKey) {
- Element element = responseCache.get(securityContextKey);
- if (element != null) {
- if (responseCache.isExpired(element)) {
- responseCache.remove(securityContextKey);
- return null;
- }
- return (ResponseState)element.getObjectValue();
- }
- return null;
+ return responseCache.get(securityContextKey);
}
public ResponseState removeResponseState(String securityContextKey) {
- Element element = responseCache.get(securityContextKey);
- if (element != null) {
+ ResponseState responseState = getResponseState(securityContextKey);
+ if (responseState != null) {
responseCache.remove(securityContextKey);
- return (ResponseState)element.getObjectValue();
}
- return null;
+ return responseState;
}
public void setResponseState(String securityContextKey, ResponseState state) {
@@ -150,16 +142,7 @@ public class EHCacheSPStateManager implements SPStateManager {
return;
}
- int parsedTTL = (int)ttl;
- if (ttl != parsedTTL) {
- // Fall back to 5 minutes if the default TTL is set incorrectly
- parsedTTL = 60 * 5;
- }
- Element element = new Element(securityContextKey, state);
- element.setTimeToLive(parsedTTL);
- element.setTimeToIdle(parsedTTL);
-
- responseCache.put(element);
+ responseCache.put(securityContextKey, state);
}
public void setRequestState(String relayState, RequestState state) {
@@ -167,33 +150,25 @@ public class EHCacheSPStateManager implements SPStateManager {
return;
}
- int parsedTTL = (int)ttl;
- if (ttl != parsedTTL) {
- // Fall back to 60 minutes if the default TTL is set incorrectly
- parsedTTL = 3600;
- }
-
- Element element = new Element(relayState, state);
- element.setTimeToLive(parsedTTL);
- element.setTimeToIdle(parsedTTL);
- requestCache.put(element);
+ requestCache.put(relayState, state);
}
public RequestState removeRequestState(String relayState) {
- Element element = requestCache.get(relayState);
- if (element != null) {
+ RequestState state = requestCache.get(relayState);
+ if (state != null) {
requestCache.remove(relayState);
- return (RequestState)element.getObjectValue();
}
- return null;
+ return state;
}
public void close() throws IOException {
- if (cacheManager != null) {
- cacheManager.shutdown();
- cacheManager = null;
- requestCache = null;
- responseCache = null;
+ if (requestCacheManager.getStatus() == Status.AVAILABLE) {
+ requestCacheManager.removeCache(REQUEST_CACHE_KEY);
+ requestCacheManager.close();
+ }
+ if (responseCacheManager.getStatus() == Status.AVAILABLE) {
+ responseCacheManager.removeCache(RESPONSE_CACHE_KEY);
+ responseCacheManager.close();
}
}
diff --git a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/RequestState.java b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/RequestState.java
index 06f3d71..b0848a2 100644
--- a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/RequestState.java
+++ b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/RequestState.java
@@ -19,6 +19,7 @@
package org.apache.cxf.rs.security.saml.sso.state;
import java.io.Serializable;
+import java.util.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@@ -94,4 +95,29 @@ public class RequestState implements Serializable {
public String getWebAppDomain() {
return webAppDomain;
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ RequestState that = (RequestState) o;
+ return createdAt == that.createdAt
+ && timeToLive == that.timeToLive
+ && Objects.equals(targetAddress, that.targetAddress)
+ && Objects.equals(idpServiceAddress, that.idpServiceAddress)
+ && Objects.equals(samlRequestId, that.samlRequestId)
+ && Objects.equals(issuerId, that.issuerId)
+ && Objects.equals(webAppContext, that.webAppContext)
+ && Objects.equals(webAppDomain, that.webAppDomain);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(targetAddress, idpServiceAddress, samlRequestId, issuerId,
+ webAppContext, webAppDomain, createdAt, timeToLive);
+ }
}
diff --git a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/ResponseState.java b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/ResponseState.java
index aa63987..6de02ca 100644
--- a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/ResponseState.java
+++ b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/state/ResponseState.java
@@ -19,6 +19,7 @@
package org.apache.cxf.rs.security.saml.sso.state;
import java.io.Serializable;
+import java.util.Objects;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@@ -78,4 +79,26 @@ public class ResponseState implements Serializable {
public String getAssertion() {
return assertion;
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ ResponseState that = (ResponseState) o;
+ return createdAt == that.createdAt
+ && expiresAt == that.expiresAt
+ && Objects.equals(assertion, that.assertion)
+ && Objects.equals(relayState, that.relayState)
+ && Objects.equals(webAppContext, that.webAppContext)
+ && Objects.equals(webAppDomain, that.webAppDomain);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(assertion, relayState, webAppContext, webAppDomain, createdAt, expiresAt);
+ }
}
diff --git a/rt/rs/security/sso/saml/src/main/resources/cxf-samlp-ehcache.xml b/rt/rs/security/sso/saml/src/main/resources/cxf-samlp-ehcache.xml
index 1a3f43d..f3b7355 100644
--- a/rt/rs/security/sso/saml/src/main/resources/cxf-samlp-ehcache.xml
+++ b/rt/rs/security/sso/saml/src/main/resources/cxf-samlp-ehcache.xml
@@ -1,5 +1,44 @@
<?xml version="1.0"?>
-<ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true">
- <diskStore path="java.io.tmpdir"/>
- <defaultCache maxEntriesLocalHeap="5000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>
-</ehcache>
+<config
+ xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
+ xmlns='http://www.ehcache.org/v3'
+ xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.8.xsd">
+
+ <cache-template name="cxf.samlp.replay.cache">
+ <key-type>java.lang.String</key-type>
+ <value-type>org.apache.wss4j.common.cache.EHCacheValue</value-type>
+ <expiry>
+ <class>org.apache.wss4j.common.cache.EHCacheExpiry</class>
+ </expiry>
+ <resources>
+ <heap unit="entries">5000</heap>
+ <disk unit="MB" persistent="false">10</disk>
+ </resources>
+ </cache-template>
+
+ <cache-template name="cxf.samlp.request.state.cache">
+ <key-type>java.lang.String</key-type>
+ <value-type>org.apache.cxf.rs.security.saml.sso.state.RequestState</value-type>
+ <expiry>
+ <ttl unit="seconds">300</ttl>
+ </expiry>
+ <resources>
+ <heap unit="entries">5000</heap>
+ <disk unit="MB" persistent="false">10</disk>
+ </resources>
+ </cache-template>
+
+ <cache-template name="cxf.samlp.response.state.cache">
+ <key-type>java.lang.String</key-type>
+ <value-type>org.apache.cxf.rs.security.saml.sso.state.ResponseState</value-type>
+ <expiry>
+ <ttl unit="seconds">300</ttl>
+ </expiry>
+ <resources>
+ <heap unit="entries">5000</heap>
+ <disk unit="MB" persistent="false">10</disk>
+ </resources>
+ </cache-template>
+
+</config>
+
diff --git a/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/EHCacheUtilTest.java b/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/EHCacheUtilTest.java
deleted file mode 100644
index d61320d..0000000
--- a/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/EHCacheUtilTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.rs.security.saml.sso;
-
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-/**
- *
- */
-public class EHCacheUtilTest {
-
- @Test
- public void testCreateCacheManager() {
- Configuration conf =
- ConfigurationFactory.parseConfiguration(EHCacheUtil.class.getResource("/cxf-test-ehcache.xml"));
-
- assertNotNull(conf);
- conf.setName("testCache");
-
- CacheManager manager1 = EHCacheUtil.createCacheManager(conf);
- assertNotNull(manager1);
- CacheManager manager2 = EHCacheUtil.createCacheManager();
- assertNotNull(manager2);
-
- manager1.shutdown();
- assertEquals(Status.STATUS_SHUTDOWN, manager1.getStatus());
-
- assertEquals(Status.STATUS_ALIVE, manager2.getStatus());
-
- manager2.shutdown();
- assertEquals(Status.STATUS_SHUTDOWN, manager2.getStatus());
-
- }
-}
\ No newline at end of file
diff --git a/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/SPStateManagerTest.java b/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/SPStateManagerTest.java
new file mode 100644
index 0000000..3e8867d
--- /dev/null
+++ b/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/SPStateManagerTest.java
@@ -0,0 +1,133 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.rs.security.saml.sso;
+
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Collection;
+
+import org.apache.cxf.rs.security.saml.sso.state.EHCacheSPStateManager;
+import org.apache.cxf.rs.security.saml.sso.state.MemorySPStateManager;
+import org.apache.cxf.rs.security.saml.sso.state.RequestState;
+import org.apache.cxf.rs.security.saml.sso.state.ResponseState;
+import org.apache.cxf.rs.security.saml.sso.state.SPStateManager;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+/**
+ * Some unit tests for the SPStateManager implementations
+ */
+@RunWith(value = org.junit.runners.Parameterized.class)
+public class SPStateManagerTest {
+
+ private final Class<? extends SPStateManager> stateManagerClass;
+ private SPStateManager stateManager;
+
+ public SPStateManagerTest(Class<? extends SPStateManager> stateManagerClass) {
+ this.stateManagerClass = stateManagerClass;
+ }
+
+ @Parameterized.Parameters(name = "{0}")
+ public static Collection<Class<? extends SPStateManager>> data() {
+ return Arrays.asList(MemorySPStateManager.class, EHCacheSPStateManager.class);
+ }
+
+ @Before
+ public void setUp() throws IllegalAccessException, InstantiationException {
+ stateManager = stateManagerClass.newInstance();
+ }
+
+ @After
+ public void close() throws IOException {
+ stateManager.close();
+ }
+
+ @Test
+ public void testRequestState() throws Exception {
+ RequestState requestState = new RequestState("https://www.apache.org/target",
+ "https://idp.apache.org",
+ "some-request_id",
+ "some-issuer-id",
+ "/",
+ null,
+ Instant.now().toEpochMilli(),
+ SSOConstants.DEFAULT_STATE_TIME);
+
+ stateManager.setRequestState("some-relay-state", requestState);
+ RequestState retrievedState = stateManager.removeRequestState("some-relay-state");
+ assertEquals(retrievedState, requestState);
+
+ // Check we can't remove again
+ retrievedState = stateManager.removeRequestState("some-relay-state");
+ assertNull(retrievedState);
+
+ retrievedState = stateManager.removeRequestState("some-other-relay-state");
+ assertNull(retrievedState);
+ }
+
+ @Test
+ public void testResponseState() throws Exception {
+ ResponseState responseState = new ResponseState("some-assertion",
+ null,
+ "/",
+ null,
+ Instant.now().toEpochMilli(),
+ SSOConstants.DEFAULT_STATE_TIME);
+
+ stateManager.setResponseState("some-context-key", responseState);
+ ResponseState retrievedState = stateManager.getResponseState("some-context-key");
+ assertEquals(retrievedState, responseState);
+
+ retrievedState = stateManager.removeResponseState("some-context-key");
+ assertEquals(retrievedState, responseState);
+
+ // Check we can't remove again
+ retrievedState = stateManager.removeResponseState("some-context-state");
+ assertNull(retrievedState);
+
+ retrievedState = stateManager.removeResponseState("some-other-context-state");
+ assertNull(retrievedState);
+ }
+
+ @Test
+ public void testCloseTwice() throws Exception {
+ RequestState requestState = new RequestState("https://www.apache.org/target",
+ "https://idp.apache.org",
+ "some-request_id",
+ "some-issuer-id",
+ "/",
+ null,
+ Instant.now().toEpochMilli(),
+ SSOConstants.DEFAULT_STATE_TIME);
+
+ stateManager.setRequestState("some-relay-state", requestState);
+
+ stateManager.close();
+ }
+
+}
\ No newline at end of file
diff --git a/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCacheTest.java b/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCacheTest.java
new file mode 100644
index 0000000..0283d48
--- /dev/null
+++ b/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCacheTest.java
@@ -0,0 +1,108 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.rs.security.saml.sso;
+
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.UUID;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Some unit tests for the TokenReplayCache implementations
+ */
+public class TokenReplayCacheTest {
+
+ @Test
+ public void testEhCacheTokenReplayCache() throws Exception {
+
+ TokenReplayCache<String> replayCache = new EHCacheTokenReplayCache();
+
+ testTokenReplayCacheInstance(replayCache);
+
+ replayCache.close();
+ }
+
+ @Test
+ public void testEhCacheCloseCacheTwice() throws Exception {
+ TokenReplayCache replayCache = new EHCacheTokenReplayCache();
+ replayCache.close();
+ replayCache.close();
+ }
+
+ // No expiry specified so it falls back to the default
+ @Test
+ public void testEhCacheTokenReplayCacheNoExpirySpecified() throws Exception {
+ TokenReplayCache replayCache = new EHCacheTokenReplayCache();
+
+ String id = UUID.randomUUID().toString();
+ replayCache.putId(id);
+ assertTrue(replayCache.contains(id));
+
+ replayCache.close();
+ }
+
+ // The negative expiry is rejected and it falls back to the default
+ @Test
+ public void testEhCacheTokenReplayCacheNegativeExpiry() throws Exception {
+ TokenReplayCache replayCache = new EHCacheTokenReplayCache();
+
+ String id = UUID.randomUUID().toString();
+ replayCache.putId(id, Instant.now().minusSeconds(100L));
+ assertTrue(replayCache.contains(id));
+
+ replayCache.close();
+ }
+
+ // The huge expiry is rejected and it falls back to the default
+ @Test
+ public void testEhCacheTokenReplayCacheHugeExpiry() throws Exception {
+ TokenReplayCache replayCache = new EHCacheTokenReplayCache();
+
+ String id = UUID.randomUUID().toString();
+ replayCache.putId(id, Instant.now().plus(14, ChronoUnit.HOURS));
+ assertTrue(replayCache.contains(id));
+
+ replayCache.close();
+ }
+
+ private void testTokenReplayCacheInstance(TokenReplayCache<String> replayCache) throws InterruptedException {
+
+ // Test default TTL caches OK
+ String id = UUID.randomUUID().toString();
+ replayCache.putId(id);
+ assertTrue(replayCache.contains(id));
+
+ // Test specifying TTL caches OK
+ id = UUID.randomUUID().toString();
+ replayCache.putId(id, Instant.now().plusSeconds(100L));
+ assertTrue(replayCache.contains(id));
+
+ // Test expiration
+ id = UUID.randomUUID().toString();
+ replayCache.putId(id, Instant.now().plusSeconds(1L));
+ Thread.sleep(1250L);
+ assertFalse(replayCache.contains(id));
+
+ }
+}
\ No newline at end of file
diff --git a/rt/rs/security/sso/saml/src/test/resources/cxf-test-ehcache.xml b/rt/rs/security/sso/saml/src/test/resources/cxf-test-ehcache.xml
deleted file mode 100644
index 1a3f43d..0000000
--- a/rt/rs/security/sso/saml/src/test/resources/cxf-test-ehcache.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0"?>
-<ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true">
- <diskStore path="java.io.tmpdir"/>
- <defaultCache maxEntriesLocalHeap="5000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>
-</ehcache>
diff --git a/rt/ws/security/pom.xml b/rt/ws/security/pom.xml
index 4d36ec2..b1f506d 100644
--- a/rt/ws/security/pom.xml
+++ b/rt/ws/security/pom.xml
@@ -35,7 +35,7 @@
<cxf.osgi.import>
javax.xml.soap;version="${cxf.osgi.saaj.version}",
javax.activation;version="${cxf.osgi.javax.activation.version}",
- net.sf.ehcache*;resolution:=optional;version="[2.5, 3.0.0)",
+ org.ehcache*;resolution:=optional;version="[3.0.0, 4.0.0)",
org.opensaml*;version="${cxf.opensaml.osgi.version.range}",
javax.xml.ws*;version="${cxf.osgi.javax.xml.ws.version}",
javax.xml.bind*;version="${cxf.osgi.javax.bind.version}",
@@ -90,9 +90,9 @@
<optional>true</optional>
</dependency>
<dependency>
- <groupId>net.sf.ehcache</groupId>
+ <groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
- <version>${cxf.ehcache.version}</version>
+ <version>${cxf.ehcache3.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/CXFEHCacheExpiry.java
similarity index 71%
copy from rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java
copy to rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/CXFEHCacheExpiry.java
index a739e36..03ab4b9 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/CXFEHCacheExpiry.java
@@ -17,18 +17,18 @@
* under the License.
*/
-package org.apache.cxf.ws.security.tokenstore;
-
-import org.apache.cxf.message.Message;
+package org.apache.cxf.ws.security.cache;
+import org.apache.wss4j.common.cache.EHCacheExpiry;
/**
- * A factory to return a MemoryTokenStore instance.
+ * This class doesn't do anything, but it's needed as otherwise the WSS4J EHCacheExpiry doesn't load in an OSGi
+ * container.
*/
-public class MemoryTokenStoreFactory extends TokenStoreFactory {
+public class CXFEHCacheExpiry extends EHCacheExpiry {
- public TokenStore newTokenStore(String key, Message message) {
- return new MemoryTokenStore();
+ public CXFEHCacheExpiry() {
+ super();
}
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/CXFEHCacheReplayCache.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/CXFEHCacheReplayCache.java
index 6783b52..6198253 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/CXFEHCacheReplayCache.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/CXFEHCacheReplayCache.java
@@ -25,6 +25,7 @@ import org.apache.cxf.Bus;
import org.apache.cxf.buslifecycle.BusLifeCycleListener;
import org.apache.cxf.buslifecycle.BusLifeCycleManager;
import org.apache.wss4j.common.cache.EHCacheReplayCache;
+import org.apache.wss4j.common.ext.WSSecurityException;
/**
* Wrap the default WSS4J EHCacheReplayCache in a BusLifeCycleListener, to make sure that
@@ -33,8 +34,8 @@ import org.apache.wss4j.common.cache.EHCacheReplayCache;
public class CXFEHCacheReplayCache extends EHCacheReplayCache implements BusLifeCycleListener {
private final Bus bus;
- public CXFEHCacheReplayCache(String key, Bus bus, URL configFileURL) {
- super(key, EHCacheUtils.getCacheManager(bus, configFileURL));
+ public CXFEHCacheReplayCache(String key, Bus bus, URL configFileURL) throws WSSecurityException {
+ super(key, configFileURL);
this.bus = bus;
if (bus != null) {
bus.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(this);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/EHCacheUtils.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/EHCacheUtils.java
deleted file mode 100644
index 37cf33d..0000000
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/cache/EHCacheUtils.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.ws.security.cache;
-
-import java.net.URL;
-
-import net.sf.ehcache.CacheManager;
-import org.apache.cxf.Bus;
-import org.apache.wss4j.common.cache.EHCacheManagerHolder;
-
-public final class EHCacheUtils {
- public static final String GLOBAL_EHCACHE_MANAGER_NAME =
- "ws-security.global.ehcachemanager";
-
- private EHCacheUtils() {
- }
-
- public static CacheManager getCacheManager(Bus bus, URL configFileURL) {
- CacheManager cacheManager = null;
-
- String globalCacheManagerName = getGlobalCacheManagerName(bus);
- if (globalCacheManagerName != null) {
- cacheManager = CacheManager.getCacheManager(globalCacheManagerName);
- }
-
- if (cacheManager == null) {
- String confName = "";
- if (bus != null) {
- confName = bus.getId();
- }
- cacheManager = EHCacheManagerHolder.getCacheManager(confName, configFileURL);
- }
- return cacheManager;
- }
-
- private static String getGlobalCacheManagerName(Bus bus) {
- if (bus != null) {
- return (String) bus.getProperty(GLOBAL_EHCACHE_MANAGER_NAME);
- }
- return null;
- }
-}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/KerberosTokenInterceptorProvider.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/KerberosTokenInterceptorProvider.java
index d031a70..8d49175 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/KerberosTokenInterceptorProvider.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/KerberosTokenInterceptorProvider.java
@@ -44,6 +44,7 @@ import org.apache.cxf.ws.security.kerberos.KerberosClient;
import org.apache.cxf.ws.security.kerberos.KerberosUtils;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.wss4j.KerberosTokenInterceptor;
import org.apache.cxf.ws.security.wss4j.PolicyBasedWSS4JInInterceptor;
@@ -134,11 +135,15 @@ public class KerberosTokenInterceptorProvider extends AbstractPolicyInterceptorP
tok.getId());
message.getExchange().put(SecurityConstants.TOKEN_ID,
tok.getId());
- TokenStoreUtils.getTokenStore(message).add(tok);
+ try {
+ TokenStoreUtils.getTokenStore(message).add(tok);
- // Create another cache entry with the SHA1 Identifier as the key for easy retrieval
- if (tok.getSHA1() != null) {
- TokenStoreUtils.getTokenStore(message).add(tok.getSHA1(), tok);
+ // Create another cache entry with the SHA1 Identifier as the key for easy retrieval
+ if (tok.getSHA1() != null) {
+ TokenStoreUtils.getTokenStore(message).add(tok.getSHA1(), tok);
+ }
+ } catch (TokenStoreException ex) {
+ throw new Fault(ex);
}
}
} else {
@@ -244,7 +249,11 @@ public class KerberosTokenInterceptorProvider extends AbstractPolicyInterceptorP
KerberosServiceSecurityToken kerberosToken =
((KerberosTokenSecurityEvent)event).getSecurityToken();
if (kerberosToken != null) {
- storeKerberosToken(message, kerberosToken);
+ try {
+ storeKerberosToken(message, kerberosToken);
+ } catch (TokenStoreException ex) {
+ throw new Fault(ex);
+ }
}
}
} else {
@@ -259,7 +268,8 @@ public class KerberosTokenInterceptorProvider extends AbstractPolicyInterceptorP
}
}
- private void storeKerberosToken(Message message, KerberosServiceSecurityToken kerberosToken) {
+ private void storeKerberosToken(Message message, KerberosServiceSecurityToken kerberosToken)
+ throws TokenStoreException {
SecurityToken token = new SecurityToken(kerberosToken.getId());
token.setTokenType(kerberosToken.getKerberosTokenValueType());
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/NegotiationUtils.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/NegotiationUtils.java
index bba37c9..7aa0562 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/NegotiationUtils.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/NegotiationUtils.java
@@ -46,6 +46,7 @@ import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.trust.STSUtils;
import org.apache.neethi.Assertion;
@@ -201,7 +202,7 @@ final class NegotiationUtils {
/**
* Return true on successfully parsing a SecurityContextToken result
*/
- static boolean parseSCTResult(SoapMessage message) {
+ static boolean parseSCTResult(SoapMessage message) throws TokenStoreException {
List<WSHandlerResult> results =
CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));
if (results == null) {
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SecureConversationInInterceptor.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SecureConversationInInterceptor.java
index 4893943..b3e7d09 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SecureConversationInInterceptor.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SecureConversationInInterceptor.java
@@ -52,6 +52,7 @@ import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.policy.interceptors.HttpsTokenInterceptorProvider.HttpsTokenInInterceptor;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.trust.DefaultSymmetricBinding;
import org.apache.cxf.ws.security.trust.STSClient;
@@ -426,7 +427,7 @@ class SecureConversationInInterceptor extends AbstractPhaseInterceptor<SoapMessa
}
}
- private SecurityToken getBootstrapToken(Message message) {
+ private SecurityToken getBootstrapToken(Message message) throws TokenStoreException {
SecurityToken st = (SecurityToken)message.getContextualProperty(SecurityConstants.TOKEN);
if (st == null) {
String id = (String)message.getContextualProperty(SecurityConstants.TOKEN_ID);
@@ -454,26 +455,30 @@ class SecureConversationInInterceptor extends AbstractPhaseInterceptor<SoapMessa
}
public void handleMessage(SoapMessage message) throws Fault {
- boolean foundSCT = NegotiationUtils.parseSCTResult(message);
-
- AssertionInfoMap aim = message.get(AssertionInfoMap.class);
- // extract Assertion information
- if (aim != null) {
- Collection<AssertionInfo> ais =
- PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.SECURE_CONVERSATION_TOKEN);
- if (ais.isEmpty()) {
- return;
- }
- for (AssertionInfo inf : ais) {
- SecureConversationToken token = (SecureConversationToken)inf.getAssertion();
- IncludeTokenType inclusion = token.getIncludeTokenType();
- if (foundSCT || token.isOptional()
- || (!foundSCT && inclusion == IncludeTokenType.INCLUDE_TOKEN_NEVER)) {
- inf.setAsserted(true);
- } else {
- inf.setNotAsserted("No SecureConversation token found in message.");
+ try {
+ boolean foundSCT = NegotiationUtils.parseSCTResult(message);
+
+ AssertionInfoMap aim = message.get(AssertionInfoMap.class);
+ // extract Assertion information
+ if (aim != null) {
+ Collection<AssertionInfo> ais =
+ PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.SECURE_CONVERSATION_TOKEN);
+ if (ais.isEmpty()) {
+ return;
+ }
+ for (AssertionInfo inf : ais) {
+ SecureConversationToken token = (SecureConversationToken) inf.getAssertion();
+ IncludeTokenType inclusion = token.getIncludeTokenType();
+ if (foundSCT || token.isOptional()
+ || (!foundSCT && inclusion == IncludeTokenType.INCLUDE_TOKEN_NEVER)) {
+ inf.setAsserted(true);
+ } else {
+ inf.setNotAsserted("No SecureConversation token found in message.");
+ }
}
}
+ } catch (TokenStoreException ex) {
+ throw new Fault(ex);
}
}
}
@@ -498,10 +503,15 @@ class SecureConversationInInterceptor extends AbstractPhaseInterceptor<SoapMessa
}
SecureConversationToken tok = (SecureConversationToken)ai.getAssertion();
- doCancel(message, aim, tok);
+ try {
+ doCancel(message, aim, tok);
+ } catch (TokenStoreException ex) {
+ throw new Fault(ex);
+ }
}
- private void doCancel(SoapMessage message, AssertionInfoMap aim, SecureConversationToken itok) {
+ private void doCancel(SoapMessage message, AssertionInfoMap aim, SecureConversationToken itok)
+ throws TokenStoreException {
Message m2 = message.getExchange().getOutMessage();
SecurityToken tok = (SecurityToken)m2.getContextualProperty(SecurityConstants.TOKEN);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SecureConversationOutInterceptor.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SecureConversationOutInterceptor.java
index b2ea4c9..c667bc6 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SecureConversationOutInterceptor.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SecureConversationOutInterceptor.java
@@ -38,6 +38,7 @@ import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.policy.interceptors.IssuedTokenInterceptorProvider.IssuedTokenOutInterceptor;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.trust.STSClient;
import org.apache.cxf.ws.security.trust.STSUtils;
@@ -70,29 +71,33 @@ class SecureConversationOutInterceptor extends AbstractPhaseInterceptor<SoapMess
SecureConversationToken itok = (SecureConversationToken)ais.iterator()
.next().getAssertion();
- SecurityToken tok = (SecurityToken)message.getContextualProperty(SecurityConstants.TOKEN);
- if (tok == null) {
- String tokId = (String)message.getContextualProperty(SecurityConstants.TOKEN_ID);
- if (tokId != null) {
- tok = TokenStoreUtils.getTokenStore(message).getToken(tokId);
+ try {
+ SecurityToken tok = (SecurityToken) message.getContextualProperty(SecurityConstants.TOKEN);
+ if (tok == null) {
+ String tokId = (String) message.getContextualProperty(SecurityConstants.TOKEN_ID);
+ if (tokId != null) {
+ tok = TokenStoreUtils.getTokenStore(message).getToken(tokId);
+ }
}
- }
- if (tok == null) {
- tok = issueToken(message, aim, itok);
- } else {
- tok = renewToken(message, aim, tok, itok);
- }
- if (tok != null) {
- for (AssertionInfo ai : ais) {
- ai.setAsserted(true);
+ if (tok == null) {
+ tok = issueToken(message, aim, itok);
+ } else {
+ tok = renewToken(message, aim, tok, itok);
}
- message.getExchange().getEndpoint().put(SecurityConstants.TOKEN, tok);
- message.getExchange().getEndpoint().put(SecurityConstants.TOKEN_ID, tok.getId());
- message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getId());
- message.getExchange().put(SecurityConstants.TOKEN, tok);
- TokenStoreUtils.getTokenStore(message).add(tok);
+ if (tok != null) {
+ for (AssertionInfo ai : ais) {
+ ai.setAsserted(true);
+ }
+ message.getExchange().getEndpoint().put(SecurityConstants.TOKEN, tok);
+ message.getExchange().getEndpoint().put(SecurityConstants.TOKEN_ID, tok.getId());
+ message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getId());
+ message.getExchange().put(SecurityConstants.TOKEN, tok);
+ TokenStoreUtils.getTokenStore(message).add(tok);
+ }
+ PolicyUtils.assertPolicy(aim, SPConstants.BOOTSTRAP_POLICY);
+ } catch (TokenStoreException ex) {
+ throw new Fault(ex);
}
- PolicyUtils.assertPolicy(aim, SPConstants.BOOTSTRAP_POLICY);
} else {
//server side should be checked on the way in
for (AssertionInfo ai : ais) {
@@ -107,7 +112,7 @@ class SecureConversationOutInterceptor extends AbstractPhaseInterceptor<SoapMess
private SecurityToken renewToken(SoapMessage message,
AssertionInfoMap aim,
SecurityToken tok,
- SecureConversationToken itok) {
+ SecureConversationToken itok) throws TokenStoreException {
if (!tok.isExpired()) {
return tok;
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SpnegoContextTokenInInterceptor.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SpnegoContextTokenInInterceptor.java
index bec33e8..b0d99d6 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SpnegoContextTokenInInterceptor.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SpnegoContextTokenInInterceptor.java
@@ -47,6 +47,7 @@ import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.policy.interceptors.HttpsTokenInterceptorProvider.HttpsTokenInInterceptor;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.trust.STSUtils;
import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
import org.apache.cxf.ws.security.wss4j.WSS4JStaxInInterceptor;
@@ -371,23 +372,27 @@ class SpnegoContextTokenInInterceptor extends AbstractPhaseInterceptor<SoapMessa
}
public void handleMessage(SoapMessage message) throws Fault {
- boolean foundSCT = NegotiationUtils.parseSCTResult(message);
-
- AssertionInfoMap aim = message.get(AssertionInfoMap.class);
- // extract Assertion information
- if (aim != null) {
- Collection<AssertionInfo> ais =
- PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.SPNEGO_CONTEXT_TOKEN);
- if (ais.isEmpty()) {
- return;
- }
- for (AssertionInfo inf : ais) {
- if (foundSCT) {
- inf.setAsserted(true);
- } else {
- inf.setNotAsserted("No SecurityContextToken token found in message.");
+ try {
+ boolean foundSCT = NegotiationUtils.parseSCTResult(message);
+
+ AssertionInfoMap aim = message.get(AssertionInfoMap.class);
+ // extract Assertion information
+ if (aim != null) {
+ Collection<AssertionInfo> ais =
+ PolicyUtils.getAllAssertionsByLocalname(aim, SPConstants.SPNEGO_CONTEXT_TOKEN);
+ if (ais.isEmpty()) {
+ return;
+ }
+ for (AssertionInfo inf : ais) {
+ if (foundSCT) {
+ inf.setAsserted(true);
+ } else {
+ inf.setNotAsserted("No SecurityContextToken token found in message.");
+ }
}
}
+ } catch (TokenStoreException ex) {
+ throw new Fault(ex);
}
}
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SpnegoContextTokenOutInterceptor.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SpnegoContextTokenOutInterceptor.java
index 45aa99d..5388151 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SpnegoContextTokenOutInterceptor.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/policy/interceptors/SpnegoContextTokenOutInterceptor.java
@@ -34,6 +34,7 @@ import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.trust.STSClient;
import org.apache.cxf.ws.security.trust.STSUtils;
@@ -48,6 +49,7 @@ class SpnegoContextTokenOutInterceptor extends AbstractPhaseInterceptor<SoapMess
SpnegoContextTokenOutInterceptor() {
super(Phase.PREPARE_SEND);
}
+
public void handleMessage(SoapMessage message) throws Fault {
AssertionInfoMap aim = message.get(AssertionInfoMap.class);
// extract Assertion information
@@ -60,26 +62,30 @@ class SpnegoContextTokenOutInterceptor extends AbstractPhaseInterceptor<SoapMess
if (isRequestor(message)) {
String tokId = (String)message.getContextualProperty(SecurityConstants.TOKEN_ID);
SecurityToken tok = null;
- if (tokId != null) {
- tok = TokenStoreUtils.getTokenStore(message).getToken(tokId);
-
- if (tok != null && tok.isExpired()) {
- message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN_ID);
- message.getExchange().remove(SecurityConstants.TOKEN_ID);
- TokenStoreUtils.getTokenStore(message).remove(tokId);
- tok = null;
+ try {
+ if (tokId != null) {
+ tok = TokenStoreUtils.getTokenStore(message).getToken(tokId);
+
+ if (tok != null && tok.isExpired()) {
+ message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN_ID);
+ message.getExchange().remove(SecurityConstants.TOKEN_ID);
+ TokenStoreUtils.getTokenStore(message).remove(tokId);
+ tok = null;
+ }
}
- }
- if (tok == null) {
- tok = issueToken(message, aim);
- }
- for (AssertionInfo ai : ais) {
- ai.setAsserted(true);
+ if (tok == null) {
+ tok = issueToken(message, aim);
+ }
+ for (AssertionInfo ai : ais) {
+ ai.setAsserted(true);
+ }
+ message.getExchange().getEndpoint().put(SecurityConstants.TOKEN_ID, tok.getId());
+ message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getId());
+ TokenStoreUtils.getTokenStore(message).add(tok);
+ } catch (TokenStoreException ex) {
+ throw new Fault(ex);
}
- message.getExchange().getEndpoint().put(SecurityConstants.TOKEN_ID, tok.getId());
- message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getId());
- TokenStoreUtils.getTokenStore(message).add(tok);
} else {
// server side should be checked on the way in
for (AssertionInfo ai : ais) {
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStore.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStore.java
index ba04e4b..591ae8d 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStore.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStore.java
@@ -22,99 +22,74 @@ package org.apache.cxf.ws.security.tokenstore;
import java.io.Closeable;
import java.net.URL;
import java.util.Collection;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.config.CacheConfiguration;
+import java.util.HashSet;
+import java.util.Set;
+
import org.apache.cxf.Bus;
import org.apache.cxf.buslifecycle.BusLifeCycleListener;
import org.apache.cxf.buslifecycle.BusLifeCycleManager;
import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.ws.security.cache.EHCacheUtils;
-import org.apache.wss4j.common.cache.EHCacheManagerHolder;
+import org.ehcache.Cache;
+import org.ehcache.CacheManager;
+import org.ehcache.Status;
+import org.ehcache.config.builders.CacheConfigurationBuilder;
+import org.ehcache.config.builders.CacheManagerBuilder;
+import org.ehcache.xml.XmlConfiguration;
/**
* An in-memory EHCache implementation of the TokenStore interface. The default TTL is 60 minutes
* and the max TTL is 12 hours.
*/
public class EHCacheTokenStore implements TokenStore, Closeable, BusLifeCycleListener {
- public static final long DEFAULT_TTL = 3600L;
- public static final long MAX_TTL = DEFAULT_TTL * 12L;
-
- private Ehcache cache;
- private Bus bus;
- private CacheManager cacheManager;
- private long ttl = DEFAULT_TTL;
+ private final Bus bus;
+ private final Cache<String, SecurityToken> cache;
+ private final CacheManager cacheManager;
+ private final String key;
- public EHCacheTokenStore(String key, Bus b, URL configFileURL) {
+ public EHCacheTokenStore(String key, Bus b, URL configFileURL) throws TokenStoreException {
bus = b;
if (bus != null) {
b.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(this);
}
- cacheManager = EHCacheUtils.getCacheManager(bus, configFileURL);
- // Cannot overflow to disk as SecurityToken Elements can't be serialized
- @SuppressWarnings("deprecation")
- CacheConfiguration cc = EHCacheManagerHolder.getCacheConfiguration(key, cacheManager)
- .overflowToDisk(false); //tokens not writable
-
- Cache newCache = new RefCountCache(cc);
- cache = cacheManager.addCacheIfAbsent(newCache);
- synchronized (cache) {
- if (cache.getStatus() != Status.STATUS_ALIVE) {
- cache = cacheManager.addCacheIfAbsent(newCache);
- }
- if (cache instanceof RefCountCache) {
- ((RefCountCache)cache).incrementAndGet();
+
+ this.key = key;
+ try {
+ XmlConfiguration xmlConfig = new XmlConfiguration(configFileURL);
+
+ // Exclude the endpoint info bit added in TokenStoreUtils when getting the template name
+ String template = key;
+ if (template.contains("-")) {
+ template = key.substring(0, key.lastIndexOf('-'));
}
- }
- // Set the TimeToLive value from the CacheConfiguration
- ttl = cc.getTimeToLiveSeconds();
- }
+ CacheConfigurationBuilder<String, SecurityToken> configurationBuilder =
+ xmlConfig.newCacheConfigurationBuilderFromTemplate(template,
+ String.class, SecurityToken.class);
- private static class RefCountCache extends Cache {
- AtomicInteger count = new AtomicInteger();
- RefCountCache(CacheConfiguration cc) {
- super(cc);
- }
- public int incrementAndGet() {
- return count.incrementAndGet();
- }
- public int decrementAndGet() {
- return count.decrementAndGet();
- }
- }
+ cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache(key, configurationBuilder).build();
+
+ cacheManager.init();
+ cache = cacheManager.getCache(key, String.class, SecurityToken.class);
- /**
- * Set a new (default) TTL value in seconds
- * @param newTtl a new (default) TTL value in seconds
- */
- public void setTTL(long newTtl) {
- ttl = newTtl;
+ } catch (Exception e) {
+ throw new TokenStoreException(e);
+ }
}
public void add(SecurityToken token) {
if (token != null && !StringUtils.isEmpty(token.getId())) {
- Element element = new Element(token.getId(), token, getTTL(), getTTL());
- element.resetAccessStatistics();
- cache.put(element);
+ cache.put(token.getId(), token);
}
}
public void add(String identifier, SecurityToken token) {
if (token != null && !StringUtils.isEmpty(identifier)) {
- Element element = new Element(identifier, token, getTTL(), getTTL());
- element.resetAccessStatistics();
- cache.put(element);
+ cache.put(identifier, token);
}
}
public void remove(String identifier) {
- if (cache != null && !StringUtils.isEmpty(identifier) && cache.isKeyInCache(identifier)) {
+ if (cache != null && !StringUtils.isEmpty(identifier)) {
cache.remove(identifier);
}
}
@@ -124,47 +99,27 @@ public class EHCacheTokenStore implements TokenStore, Closeable, BusLifeCycleLis
if (cache == null) {
return null;
}
- return cache.getKeysWithExpiryCheck();
+
+ // Not very efficient, but we are only using this method for testing
+ Set<String> keys = new HashSet<>();
+ for (Cache.Entry<String, SecurityToken> entry : cache) {
+ keys.add(entry.getKey());
+ }
+
+ return keys;
}
public SecurityToken getToken(String identifier) {
if (cache == null) {
return null;
}
- Element element = cache.get(identifier);
- if (element != null && !cache.isExpired(element)) {
- return (SecurityToken)element.getObjectValue();
- }
- return null;
- }
-
- private int getTTL() {
- int parsedTTL = (int)ttl;
- if (ttl != parsedTTL) {
- // Fall back to 60 minutes if the default TTL is set incorrectly
- parsedTTL = 3600;
- }
- return parsedTTL;
+ return cache.get(identifier);
}
public void close() {
- if (cacheManager != null) {
- // this step is especially important for global shared cache manager
- if (cache != null) {
- synchronized (cache) {
- if (cache instanceof RefCountCache
- && ((RefCountCache)cache).decrementAndGet() == 0) {
- cacheManager.removeCache(cache.getName());
- }
- }
- }
-
- EHCacheManagerHolder.releaseCacheManger(cacheManager);
- cacheManager = null;
- cache = null;
- if (bus != null) {
- bus.getExtension(BusLifeCycleManager.class).unregisterLifeCycleListener(this);
- }
+ if (cacheManager.getStatus() == Status.AVAILABLE) {
+ cacheManager.removeCache(key);
+ cacheManager.close();
}
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStoreFactory.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStoreFactory.java
index 774ce3f..f1d6c7b 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStoreFactory.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStoreFactory.java
@@ -34,7 +34,8 @@ public class EHCacheTokenStoreFactory extends TokenStoreFactory {
private static final String DEFAULT_CONFIG_FILE = "cxf-ehcache.xml";
- public TokenStore newTokenStore(String key, Message message) {
+ @Override
+ public TokenStore newTokenStore(String key, Message message) throws TokenStoreException {
URL configFileURL = SecurityUtils.getConfigFileURL(message, SecurityConstants.CACHE_CONFIG_FILE,
DEFAULT_CONFIG_FILE);
if (configFileURL == null) {
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java
index a739e36..eeefc65 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java
@@ -27,6 +27,7 @@ import org.apache.cxf.message.Message;
*/
public class MemoryTokenStoreFactory extends TokenStoreFactory {
+ @Override
public TokenStore newTokenStore(String key, Message message) {
return new MemoryTokenStore();
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreException.java
similarity index 76%
copy from rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java
copy to rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreException.java
index a739e36..f21ede3 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreFactory.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreException.java
@@ -19,16 +19,10 @@
package org.apache.cxf.ws.security.tokenstore;
-import org.apache.cxf.message.Message;
+public class TokenStoreException extends Exception {
-
-/**
- * A factory to return a MemoryTokenStore instance.
- */
-public class MemoryTokenStoreFactory extends TokenStoreFactory {
-
- public TokenStore newTokenStore(String key, Message message) {
- return new MemoryTokenStore();
+ public TokenStoreException(Throwable cause) {
+ super(cause);
}
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreFactory.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreFactory.java
index 68be28a..728fa3a 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreFactory.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreFactory.java
@@ -31,7 +31,7 @@ public abstract class TokenStoreFactory {
static {
try {
- Class<?> cacheManagerClass = Class.forName("net.sf.ehcache.CacheManager");
+ Class<?> cacheManagerClass = Class.forName("org.ehcache.CacheManager");
if (cacheManagerClass != null) {
ehCacheInstalled = true;
}
@@ -52,6 +52,6 @@ public abstract class TokenStoreFactory {
return new MemoryTokenStoreFactory();
}
- public abstract TokenStore newTokenStore(String key, Message message);
+ public abstract TokenStore newTokenStore(String key, Message message) throws TokenStoreException;
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreUtils.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreUtils.java
index 9a9ad94..438e5e7 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreUtils.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/tokenstore/TokenStoreUtils.java
@@ -31,7 +31,7 @@ public final class TokenStoreUtils {
// complete
}
- public static TokenStore getTokenStore(Message message) {
+ public static TokenStore getTokenStore(Message message) throws TokenStoreException {
EndpointInfo info = message.getExchange().getEndpoint().getEndpointInfo();
synchronized (info) {
TokenStore tokenStore =
@@ -46,13 +46,15 @@ public final class TokenStoreUtils {
(String)message.getContextualProperty(SecurityConstants.CACHE_IDENTIFIER);
if (cacheIdentifier != null) {
cacheKey.append('-').append(cacheIdentifier);
- } else if (info.getName() != null) {
+ }
+ if (info.getName() != null) {
int hashcode = info.getName().toString().hashCode();
if (hashcode >= 0) {
cacheKey.append('-');
}
cacheKey.append(hashcode);
}
+
tokenStore = tokenStoreFactory.newTokenStore(cacheKey.toString(), message);
info.setProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, tokenStore);
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/DefaultSTSTokenCacher.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/DefaultSTSTokenCacher.java
index cd8191f..cc3acc6 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/DefaultSTSTokenCacher.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/DefaultSTSTokenCacher.java
@@ -31,6 +31,7 @@ import org.apache.cxf.message.Message;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.ext.WSSecurityException;
@@ -39,7 +40,7 @@ import org.apache.wss4j.common.util.XMLUtils;
public class DefaultSTSTokenCacher implements STSTokenCacher {
- public SecurityToken retrieveToken(Message message, boolean retrieveTokenFromEndpoint) {
+ public SecurityToken retrieveToken(Message message, boolean retrieveTokenFromEndpoint) throws TokenStoreException {
SecurityToken tok = null;
if (retrieveTokenFromEndpoint) {
tok = (SecurityToken)message.getContextualProperty(SecurityConstants.TOKEN);
@@ -61,7 +62,8 @@ public class DefaultSTSTokenCacher implements STSTokenCacher {
return tok;
}
- public SecurityToken retrieveToken(Message message, Element delegationToken, String cacheKey) {
+ public SecurityToken retrieveToken(Message message, Element delegationToken, String cacheKey)
+ throws TokenStoreException {
if (delegationToken == null) {
return null;
}
@@ -85,7 +87,8 @@ public class DefaultSTSTokenCacher implements STSTokenCacher {
return null;
}
- public void storeToken(Message message, SecurityToken securityToken, boolean storeTokenInEndpoint) {
+ public void storeToken(Message message, SecurityToken securityToken, boolean storeTokenInEndpoint)
+ throws TokenStoreException {
if (storeTokenInEndpoint && !isOneTimeUse(securityToken)) {
message.getExchange().getEndpoint().put(SecurityConstants.TOKEN, securityToken);
message.getExchange().put(SecurityConstants.TOKEN, securityToken);
@@ -100,7 +103,8 @@ public class DefaultSTSTokenCacher implements STSTokenCacher {
TokenStoreUtils.getTokenStore(message).add(securityToken);
}
- public void storeToken(Message message, Element delegationToken, String secTokenId, String cacheKey) {
+ public void storeToken(Message message, Element delegationToken, String secTokenId, String cacheKey)
+ throws TokenStoreException {
if (secTokenId == null || delegationToken == null) {
return;
}
@@ -122,7 +126,7 @@ public class DefaultSTSTokenCacher implements STSTokenCacher {
tokenStore.add(cachedToken);
}
- public void removeToken(Message message, SecurityToken securityToken) {
+ public void removeToken(Message message, SecurityToken securityToken) throws TokenStoreException {
// Remove token from cache
message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN);
message.getExchange().getEndpoint().remove(SecurityConstants.TOKEN_ID);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSLoginModule.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSLoginModule.java
index fe132d5..4f926b1 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSLoginModule.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSLoginModule.java
@@ -59,6 +59,7 @@ import org.apache.cxf.rt.security.utils.SecurityUtils;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.EHCacheTokenStore;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreFactory;
import org.apache.cxf.ws.security.trust.claims.RoleClaimsCallbackHandler;
import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
@@ -331,7 +332,7 @@ public class STSLoginModule implements LoginModule {
return c;
}
- private TokenStore configureTokenStore() throws MalformedURLException {
+ private TokenStore configureTokenStore() throws MalformedURLException, TokenStoreException {
if (TokenStoreFactory.isEhCacheInstalled()) {
String cfg = "cxf-ehcache.xml";
URL url = ClassLoaderUtils.getResource(cfg, STSLoginModule.class);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenCacher.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenCacher.java
index f090e30..8cf1c1d 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenCacher.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenCacher.java
@@ -23,6 +23,7 @@ import org.w3c.dom.Element;
import org.apache.cxf.message.Message;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
/**
* This interface allows you to plug in some custom logic when storing/retrieving STS tokens in/from the cache
@@ -33,29 +34,31 @@ public interface STSTokenCacher {
* Retrieve a cached STS token. The retrieveTokenFromEndpoint boolean lets us known whether we want to retrieve the
* token from the endpoint or not.
*/
- SecurityToken retrieveToken(Message message, boolean retrieveTokenFromEndpoint);
+ SecurityToken retrieveToken(Message message, boolean retrieveTokenFromEndpoint) throws TokenStoreException;
/**
* Retrieve a cached STS token for a given delegation token Element
*/
- SecurityToken retrieveToken(Message message, Element delegationToken, String cacheKey);
+ SecurityToken retrieveToken(Message message, Element delegationToken, String cacheKey) throws TokenStoreException;
/**
* Store a token in the cache. The storeTokenInEndpoint boolean lets us know whether we want to store the token
* in the endpoint or not.
*/
- void storeToken(Message message, SecurityToken securityToken, boolean storeTokenInEndpoint);
+ void storeToken(Message message, SecurityToken securityToken, boolean storeTokenInEndpoint)
+ throws TokenStoreException;
/**
* Store a given delegation token in the cache (or update it if it's already there), with a reference to the
* security token obtained from the STS.
*/
- void storeToken(Message message, Element delegationToken, String secTokenId, String cacheKey);
+ void storeToken(Message message, Element delegationToken, String secTokenId, String cacheKey)
+ throws TokenStoreException;
/**
* Remove a cached STS token
*/
- void removeToken(Message message, SecurityToken securityToken);
+ void removeToken(Message message, SecurityToken securityToken) throws TokenStoreException;
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenRetriever.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenRetriever.java
index 3a8ad9e..7d6d7c6 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenRetriever.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenRetriever.java
@@ -32,6 +32,7 @@ import org.apache.cxf.rt.security.utils.SecurityUtils;
import org.apache.cxf.ws.addressing.AddressingProperties;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.policy.model.Trust10;
import org.apache.wss4j.policy.model.Trust13;
@@ -158,7 +159,11 @@ public final class STSTokenRetriever {
}
// Remove token from cache
- tokenCacher.removeToken(message, tok);
+ try {
+ tokenCacher.removeToken(message, tok);
+ } catch (TokenStoreException ex) {
+ throw new Fault(ex);
+ }
// If the user has explicitly disabled Renewing then we can't renew a token,
// so just get a new one
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenValidator.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenValidator.java
index 4db06d7..e1b4e3e 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenValidator.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/trust/STSTokenValidator.java
@@ -33,6 +33,7 @@ import org.apache.cxf.message.Message;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.trust.delegation.DelegationCallback;
import org.apache.wss4j.common.ext.WSSecurityException;
@@ -170,7 +171,7 @@ public class STSTokenValidator implements Validator {
}
}
- static final TokenStore getTokenStore(Message message) {
+ static final TokenStore getTokenStore(Message message) throws TokenStoreException {
if (message == null) {
return null;
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/PolicyBasedWSS4JOutInterceptor.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/PolicyBasedWSS4JOutInterceptor.java
index 9cb373e..520bb23 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/PolicyBasedWSS4JOutInterceptor.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/PolicyBasedWSS4JOutInterceptor.java
@@ -43,6 +43,7 @@ import org.apache.cxf.phase.PhaseInterceptor;
import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.wss4j.policyhandlers.AsymmetricBindingHandler;
import org.apache.cxf.ws.security.wss4j.policyhandlers.SymmetricBindingHandler;
import org.apache.cxf.ws.security.wss4j.policyhandlers.TransportBindingHandler;
@@ -184,7 +185,7 @@ public class PolicyBasedWSS4JOutInterceptor extends AbstractPhaseInterceptor<Soa
new AsymmetricBindingHandler(config, (AsymmetricBinding)binding, saaj,
secHeader, aim, message).handleBinding();
}
- } catch (SOAPException e) {
+ } catch (SOAPException | TokenStoreException e) {
throw new SoapFault(
new Message("SECURITY_FAILED", LOG), e, message.getVersion().getSender()
);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JInInterceptor.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JInInterceptor.java
index 56a722c..5ea6209 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JInInterceptor.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JInInterceptor.java
@@ -65,6 +65,7 @@ import org.apache.cxf.security.transport.TLSSessionInfo;
import org.apache.cxf.staxutils.StaxUtils;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.wss4j.common.ConfigurationConstants;
import org.apache.wss4j.common.cache.ReplayCache;
@@ -504,7 +505,7 @@ public class WSS4JInInterceptor extends AbstractWSS4JInterceptor {
}
protected void configureReplayCaches(RequestData reqData, List<Integer> actions, SoapMessage msg)
- throws WSSecurityException {
+ throws WSSecurityException {
if (isNonceCacheRequired(actions, msg)) {
ReplayCache nonceCache =
getReplayCache(
@@ -626,10 +627,14 @@ public class WSS4JInInterceptor extends AbstractWSS4JInterceptor {
}
return new DelegatingCallbackHandler(pwdCallback);
}
- return getCallback(reqData);
+ try {
+ return getCallback(reqData);
+ } catch (TokenStoreException ex) {
+ throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
+ }
}
- protected CallbackHandler getCallback(RequestData reqData) throws WSSecurityException {
+ protected CallbackHandler getCallback(RequestData reqData) throws WSSecurityException, TokenStoreException {
Object o =
SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER,
(SoapMessage)reqData.getMsgContext());
@@ -723,7 +728,7 @@ public class WSS4JInInterceptor extends AbstractWSS4JInterceptor {
*/
protected ReplayCache getReplayCache(
SoapMessage message, String booleanKey, String instanceKey
- ) {
+ ) throws WSSecurityException {
return WSS4JUtils.getReplayCache(message, booleanKey, instanceKey);
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JStaxInInterceptor.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JStaxInInterceptor.java
index c5c42e2..25e1457 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JStaxInInterceptor.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JStaxInInterceptor.java
@@ -46,6 +46,7 @@ import org.apache.cxf.phase.Phase;
import org.apache.cxf.rt.security.saml.utils.SAMLUtils;
import org.apache.cxf.rt.security.utils.SecurityUtils;
import org.apache.cxf.ws.security.SecurityConstants;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.wss4j.common.ConfigurationConstants;
import org.apache.wss4j.common.WSSPolicyException;
@@ -175,7 +176,7 @@ public class WSS4JStaxInInterceptor extends AbstractWSS4JStaxInterceptor {
soapMessage.put(SECURITY_PROCESSED, Boolean.TRUE);
} catch (WSSecurityException e) {
throw WSS4JUtils.createSoapFault(soapMessage, soapMessage.getVersion(), e);
- } catch (XMLSecurityException e) {
+ } catch (XMLSecurityException | TokenStoreException e) {
throw new SoapFault(new Message("STAX_EX", LOG), e, soapMessage.getVersion().getSender());
} catch (WSSPolicyException e) {
throw new SoapFault(e.getMessage(), e, soapMessage.getVersion().getSender());
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JStaxOutInterceptor.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JStaxOutInterceptor.java
index 8bccbdd..052b98f 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JStaxOutInterceptor.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JStaxOutInterceptor.java
@@ -42,6 +42,7 @@ import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.rt.security.utils.SecurityUtils;
import org.apache.cxf.ws.security.SecurityConstants;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.ConfigurationConstants;
import org.apache.wss4j.common.WSSPolicyException;
import org.apache.wss4j.common.crypto.Crypto;
@@ -207,7 +208,11 @@ public class WSS4JStaxOutInterceptor extends AbstractWSS4JStaxInterceptor {
if (securityEvent.getSecurityEventType() == WSSecurityEventConstants.SAML_TOKEN) {
// Store SAML keys in case we need them on the inbound side
TokenSecurityEvent<?> tokenSecurityEvent = (TokenSecurityEvent<?>)securityEvent;
- WSS4JUtils.parseAndStoreStreamingSecurityToken(tokenSecurityEvent.getSecurityToken(), msg);
+ try {
+ WSS4JUtils.parseAndStoreStreamingSecurityToken(tokenSecurityEvent.getSecurityToken(), msg);
+ } catch (TokenStoreException e) {
+ throw new XMLSecurityException(e);
+ }
} else if (securityEvent.getSecurityEventType() == WSSecurityEventConstants.SignatureValue) {
// Required for Signature Confirmation
outgoingSecurityEventList.add(securityEvent);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JUtils.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JUtils.java
index cbd08df..8ada5c6 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JUtils.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/WSS4JUtils.java
@@ -46,6 +46,7 @@ import org.apache.cxf.service.model.EndpointInfo;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.cache.CXFEHCacheReplayCache;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.wss4j.common.cache.ReplayCache;
import org.apache.wss4j.common.cache.ReplayCacheFactory;
@@ -104,7 +105,7 @@ public final class WSS4JUtils {
*/
public static ReplayCache getReplayCache(
SoapMessage message, String booleanKey, String instanceKey
- ) {
+ ) throws WSSecurityException {
boolean specified = false;
Object o = message.getContextualProperty(booleanKey);
if (o != null) {
@@ -117,15 +118,14 @@ public final class WSS4JUtils {
if (!specified && MessageUtils.isRequestor(message)) {
return null;
}
+
+ ReplayCache replayCache = (ReplayCache)message.getContextualProperty(instanceKey);
Endpoint ep = message.getExchange().getEndpoint();
- if (ep != null && ep.getEndpointInfo() != null) {
+ if (replayCache == null && ep != null && ep.getEndpointInfo() != null) {
EndpointInfo info = ep.getEndpointInfo();
synchronized (info) {
- ReplayCache replayCache =
- (ReplayCache)message.getContextualProperty(instanceKey);
- if (replayCache == null) {
- replayCache = (ReplayCache)info.getProperty(instanceKey);
- }
+ replayCache = (ReplayCache)info.getProperty(instanceKey);
+
if (replayCache == null) {
String cacheKey = instanceKey;
if (info.getName() != null) {
@@ -153,16 +153,15 @@ public final class WSS4JUtils {
info.setProperty(instanceKey, replayCache);
}
- return replayCache;
}
}
- return null;
+ return replayCache;
}
public static String parseAndStoreStreamingSecurityToken(
org.apache.xml.security.stax.securityToken.SecurityToken securityToken,
Message message
- ) throws XMLSecurityException {
+ ) throws XMLSecurityException, TokenStoreException {
if (securityToken == null) {
return null;
}
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java
index f49061a..7bda697 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractBindingBuilder.java
@@ -78,6 +78,7 @@ import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler;
import org.apache.cxf.ws.security.wss4j.CXFCallbackLookup;
@@ -340,7 +341,7 @@ public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandle
}
}
- protected final TokenStore getTokenStore() {
+ protected final TokenStore getTokenStore() throws TokenStoreException {
return TokenStoreUtils.getTokenStore(message);
}
@@ -445,7 +446,7 @@ public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandle
assertionInfo.setAsserted(true);
try {
handleSupportingTokens((SupportingTokens)assertionInfo.getAssertion(), endorse, ret);
- } catch (SOAPException ex) {
+ } catch (SOAPException | TokenStoreException ex) {
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex);
}
}
@@ -458,7 +459,7 @@ public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandle
SupportingTokens suppTokens,
boolean endorse,
List<SupportingToken> ret
- ) throws WSSecurityException, SOAPException {
+ ) throws WSSecurityException, SOAPException, TokenStoreException {
if (suppTokens == null) {
return ret;
}
@@ -899,7 +900,7 @@ public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandle
return null;
}
- protected SamlAssertionWrapper addSamlToken(SamlToken token) throws WSSecurityException {
+ protected SamlAssertionWrapper addSamlToken(SamlToken token) throws WSSecurityException, TokenStoreException {
assertToken(token);
if (!isTokenRequired(token.getIncludeTokenType())) {
return null;
@@ -982,7 +983,7 @@ public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandle
/**
* Store a SAML Assertion as a SecurityToken
*/
- protected void storeAssertionAsSecurityToken(SamlAssertionWrapper assertion) {
+ protected void storeAssertionAsSecurityToken(SamlAssertionWrapper assertion) throws TokenStoreException {
String id = findIDFromSamlToken(assertion.getElement());
if (id == null) {
return;
@@ -1785,7 +1786,7 @@ public abstract class AbstractBindingBuilder extends AbstractCommonBindingHandle
protected WSSecSignature getSignatureBuilder(
AbstractToken token, boolean attached, boolean endorse
- ) throws WSSecurityException {
+ ) throws WSSecurityException, TokenStoreException {
WSSecSignature sig = new WSSecSignature(secHeader);
sig.setIdAllocator(wssConfig.getIdAllocator());
sig.setCallbackLookup(callbackLookup);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractCommonBindingHandler.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractCommonBindingHandler.java
index 4f9b25e..aab8cee 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractCommonBindingHandler.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractCommonBindingHandler.java
@@ -35,6 +35,7 @@ import org.apache.cxf.ws.policy.PolicyException;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.neethi.Assertion;
import org.apache.wss4j.policy.SP13Constants;
@@ -448,7 +449,7 @@ public abstract class AbstractCommonBindingHandler {
return null;
}
- protected SecurityToken getSecurityToken() {
+ protected SecurityToken getSecurityToken() throws TokenStoreException {
SecurityToken st = (SecurityToken)message.getContextualProperty(SecurityConstants.TOKEN);
if (st == null) {
String id = (String)message.getContextualProperty(SecurityConstants.TOKEN_ID);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractStaxBindingHandler.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractStaxBindingHandler.java
index b5a2d6b..5ea7bab 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractStaxBindingHandler.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AbstractStaxBindingHandler.java
@@ -48,6 +48,7 @@ import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.ext.WSPasswordCallback;
import org.apache.wss4j.common.ext.WSSecurityException;
@@ -202,7 +203,7 @@ public abstract class AbstractStaxBindingHandler extends AbstractCommonBindingHa
protected SecurePart addKerberosToken(
KerberosToken token, boolean signed, boolean endorsing, boolean encrypting
- ) throws WSSecurityException {
+ ) throws WSSecurityException, TokenStoreException {
assertToken(token);
IncludeTokenType includeToken = token.getIncludeTokenType();
if (!isTokenRequired(includeToken)) {
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AsymmetricBindingHandler.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AsymmetricBindingHandler.java
index 18e452d..9dc3043 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AsymmetricBindingHandler.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/AsymmetricBindingHandler.java
@@ -47,6 +47,7 @@ import org.apache.cxf.ws.policy.AssertionInfo;
import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler;
import org.apache.cxf.ws.security.wss4j.StaxSerializer;
import org.apache.cxf.ws.security.wss4j.WSS4JUtils;
@@ -114,9 +115,13 @@ public class AsymmetricBindingHandler extends AbstractBindingBuilder {
if (abinding.getProtectionOrder()
== AbstractSymmetricAsymmetricBinding.ProtectionOrder.EncryptBeforeSigning) {
- doEncryptBeforeSign();
- assertPolicy(
- new QName(abinding.getName().getNamespaceURI(), SPConstants.ENCRYPT_BEFORE_SIGNING));
+ try {
+ doEncryptBeforeSign();
+ assertPolicy(
+ new QName(abinding.getName().getNamespaceURI(), SPConstants.ENCRYPT_BEFORE_SIGNING));
+ } catch (TokenStoreException ex) {
+ throw new Fault(ex);
+ }
} else {
doSignBeforeEncrypt();
assertPolicy(
@@ -272,7 +277,7 @@ public class AsymmetricBindingHandler extends AbstractBindingBuilder {
return wrapper;
}
- private void doEncryptBeforeSign() {
+ private void doEncryptBeforeSign() throws TokenStoreException {
AbstractTokenWrapper wrapper = getEncryptBeforeSignWrapper();
AbstractToken encryptionToken = null;
if (wrapper != null) {
@@ -387,7 +392,7 @@ public class AsymmetricBindingHandler extends AbstractBindingBuilder {
}
}
}
- } catch (WSSecurityException | SOAPException ex) {
+ } catch (WSSecurityException | SOAPException | TokenStoreException ex) {
LOG.log(Level.FINE, ex.getMessage(), ex);
throw new Fault(ex);
}
@@ -487,25 +492,31 @@ public class AsymmetricBindingHandler extends AbstractBindingBuilder {
Crypto crypto = getEncryptionCrypto();
- SecurityToken securityToken = getSecurityToken();
- if (!isRequestor() && securityToken != null
- && recToken.getToken() instanceof SamlToken) {
- String tokenType = securityToken.getTokenType();
- if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
- || WSS4JConstants.SAML_NS.equals(tokenType)) {
- encr.setCustomEKTokenValueType(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
- encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
- encr.setCustomEKTokenId(securityToken.getId());
- } else if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
- || WSS4JConstants.SAML2_NS.equals(tokenType)) {
- encr.setCustomEKTokenValueType(WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE);
- encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
- encr.setCustomEKTokenId(securityToken.getId());
+ SecurityToken securityToken = null;
+ try {
+ securityToken = getSecurityToken();
+ if (!isRequestor() && securityToken != null
+ && recToken.getToken() instanceof SamlToken) {
+ String tokenType = securityToken.getTokenType();
+ if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
+ || WSS4JConstants.SAML_NS.equals(tokenType)) {
+ encr.setCustomEKTokenValueType(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
+ encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
+ encr.setCustomEKTokenId(securityToken.getId());
+ } else if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
+ || WSS4JConstants.SAML2_NS.equals(tokenType)) {
+ encr.setCustomEKTokenValueType(WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE);
+ encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
+ encr.setCustomEKTokenId(securityToken.getId());
+ } else {
+ setKeyIdentifierType(encr, encrToken);
+ }
} else {
setKeyIdentifierType(encr, encrToken);
}
- } else {
- setKeyIdentifierType(encr, encrToken);
+ } catch (TokenStoreException ex) {
+ LOG.log(Level.FINE, ex.getMessage(), ex);
+ throw new Fault(ex);
}
//
// Using a stored cert is only suitable for the Issued Token case, where
@@ -650,7 +661,7 @@ public class AsymmetricBindingHandler extends AbstractBindingBuilder {
}
private void doSignature(AbstractTokenWrapper wrapper, List<WSEncryptionPart> sigParts, boolean attached)
- throws WSSecurityException, SOAPException {
+ throws WSSecurityException, SOAPException, TokenStoreException {
if (!isRequestor()) {
assertUnusedTokens(abinding.getInitiatorToken());
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/StaxSymmetricBindingHandler.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/StaxSymmetricBindingHandler.java
index b1d0900..3d54678 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/StaxSymmetricBindingHandler.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/StaxSymmetricBindingHandler.java
@@ -22,6 +22,8 @@ package org.apache.cxf.ws.security.wss4j.policyhandlers;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
@@ -29,6 +31,7 @@ import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import org.apache.cxf.binding.soap.SoapMessage;
+import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.MessageUtils;
@@ -36,6 +39,7 @@ import org.apache.cxf.rt.security.utils.SecurityUtils;
import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.wss4j.TokenStoreCallbackHandler;
import org.apache.cxf.ws.security.wss4j.WSS4JUtils;
@@ -76,6 +80,8 @@ import org.apache.xml.security.stax.securityEvent.SecurityEvent;
*/
public class StaxSymmetricBindingHandler extends AbstractStaxBindingHandler {
+ private static final Logger LOG = LogUtils.getL7dLogger(StaxSymmetricBindingHandler.class);
+
private SymmetricBinding sbinding;
private SoapMessage message;
@@ -122,11 +128,16 @@ public class StaxSymmetricBindingHandler extends AbstractStaxBindingHandler {
// Set up CallbackHandler which wraps the configured Handler
WSSSecurityProperties properties = getProperties();
- TokenStoreCallbackHandler callbackHandler =
- new TokenStoreCallbackHandler(
- properties.getCallbackHandler(), TokenStoreUtils.getTokenStore(message)
- );
- properties.setCallbackHandler(callbackHandler);
+ try {
+ TokenStoreCallbackHandler callbackHandler =
+ new TokenStoreCallbackHandler(
+ properties.getCallbackHandler(), TokenStoreUtils.getTokenStore(message)
+ );
+ properties.setCallbackHandler(callbackHandler);
+ } catch (TokenStoreException e) {
+ LOG.log(Level.FINE, e.getMessage(), e);
+ throw new Fault(e);
+ }
if (sbinding.getProtectionOrder()
== AbstractSymmetricAsymmetricBinding.ProtectionOrder.EncryptBeforeSigning) {
@@ -596,7 +607,7 @@ public class StaxSymmetricBindingHandler extends AbstractStaxBindingHandler {
}
}
- private String setupEncryptedKey() throws WSSecurityException {
+ private String setupEncryptedKey() throws WSSecurityException, TokenStoreException {
Instant created = Instant.now();
Instant expires = created.plusSeconds(WSS4JUtils.getSecurityTokenLifetime(message) / 1000L);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/StaxTransportBindingHandler.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/StaxTransportBindingHandler.java
index b64e186..88a957e 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/StaxTransportBindingHandler.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/StaxTransportBindingHandler.java
@@ -35,6 +35,7 @@ import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.cxf.ws.security.wss4j.TokenStoreCallbackHandler;
import org.apache.wss4j.policy.SP11Constants;
@@ -104,12 +105,17 @@ public class StaxTransportBindingHandler extends AbstractStaxBindingHandler {
TransportToken token = tbinding.getTransportToken();
if (token.getToken() instanceof IssuedToken) {
- SecurityToken secToken = getSecurityToken();
- if (secToken == null) {
- unassertPolicy(token.getToken(), "No transport token id");
- return;
+ try {
+ SecurityToken secToken = getSecurityToken();
+ if (secToken == null) {
+ unassertPolicy(token.getToken(), "No transport token id");
+ return;
+ }
+ addIssuedToken(token.getToken(), secToken, false, false);
+ } catch (TokenStoreException e) {
+ LOG.log(Level.FINE, e.getMessage(), e);
+ throw new Fault(e);
}
- addIssuedToken(token.getToken(), secToken, false, false);
}
assertToken(token.getToken());
assertTokenWrapper(token);
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/SymmetricBindingHandler.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/SymmetricBindingHandler.java
index 15ba85a..0497f17 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/SymmetricBindingHandler.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyhandlers/SymmetricBindingHandler.java
@@ -45,6 +45,7 @@ import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler;
import org.apache.cxf.ws.security.wss4j.StaxSerializer;
import org.apache.cxf.ws.security.wss4j.WSS4JUtils;
@@ -101,7 +102,7 @@ public class SymmetricBindingHandler extends AbstractBindingBuilder {
SOAPMessage saaj,
WSSecHeader secHeader,
AssertionInfoMap aim,
- SoapMessage message) throws SOAPException {
+ SoapMessage message) throws SOAPException, TokenStoreException {
super(config, binding, saaj, secHeader, aim, message);
this.sbinding = binding;
tokenStore = getTokenStore();
diff --git a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyvalidators/KerberosTokenPolicyValidator.java b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyvalidators/KerberosTokenPolicyValidator.java
index 386bdb3..70ee722 100644
--- a/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyvalidators/KerberosTokenPolicyValidator.java
+++ b/rt/ws/security/src/main/java/org/apache/cxf/ws/security/wss4j/policyvalidators/KerberosTokenPolicyValidator.java
@@ -22,14 +22,17 @@ package org.apache.cxf.ws.security.wss4j.policyvalidators;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import java.util.logging.Logger;
import javax.xml.namespace.QName;
+import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.ws.policy.AssertionInfo;
import org.apache.cxf.ws.policy.AssertionInfoMap;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.policy.PolicyUtils;
import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.tokenstore.TokenStoreUtils;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.token.BinarySecurity;
@@ -50,6 +53,8 @@ import org.apache.xml.security.utils.XMLUtils;
*/
public class KerberosTokenPolicyValidator extends AbstractSecurityPolicyValidator {
+ private static final Logger LOG = LogUtils.getL7dLogger(KerberosTokenPolicyValidator.class);
+
/**
* Return true if this SecurityPolicyValidator implementation is capable of validating a
* policy defined by the AssertionInfo parameter
@@ -101,7 +106,11 @@ public class KerberosTokenPolicyValidator extends AbstractSecurityPolicyValidato
if (asserted) {
SecurityToken token = createSecurityToken(kerberosToken);
token.setSecret((byte[])kerberosResult.get(WSSecurityEngineResult.TAG_SECRET));
- TokenStoreUtils.getTokenStore(parameters.getMessage()).add(token);
+ try {
+ TokenStoreUtils.getTokenStore(parameters.getMessage()).add(token);
+ } catch (TokenStoreException ex) {
+ LOG.warning(ex.getMessage());
+ }
parameters.getMessage().getExchange().put(SecurityConstants.TOKEN_ID, token.getId());
return;
}
diff --git a/rt/ws/security/src/main/resources/cxf-ehcache.xml b/rt/ws/security/src/main/resources/cxf-ehcache.xml
index 0aa370f..f2690d3 100644
--- a/rt/ws/security/src/main/resources/cxf-ehcache.xml
+++ b/rt/ws/security/src/main/resources/cxf-ehcache.xml
@@ -1,12 +1,38 @@
<?xml version="1.0"?>
-<ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true" name="cxfSecurityCache">
- <diskStore path="java.io.tmpdir"/>
- <defaultCache maxEntriesLocalHeap="5000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>
- <!--
+<config
+ xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
+ xmlns='http://www.ehcache.org/v3'
+ xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.8.xsd">
+
+ <cache-template name="wss4jCache">
+ <key-type>java.lang.String</key-type>
+ <!-- Note: This won't load in OSGi, but we can just leave it out to treat it as an Object
+ <value-type>org.apache.wss4j.common.cache.EHCacheValue</value-type>
+ -->
+ <expiry>
+ <class>org.apache.cxf.ws.security.cache.CXFEHCacheExpiry</class>
+ </expiry>
+ <resources>
+ <heap unit="entries">5000</heap>
+ <disk unit="MB" persistent="false">10</disk>
+ </resources>
+ </cache-template>
+
+ <!--
Security Tokens are not writable to Disk so use a memory only
cache with a bit larger maxEntriesLocalHeap. However, this
cache is per-endpoint so not "too large" to not consume the
- entire heap.
- -->
- <cache name="org.apache.cxf.ws.security.tokenstore.TokenStore" overflowToDisk="false" maxEntriesLocalHeap="10000" timeToIdleSeconds="3600" timeToLiveSeconds="3600"/>
-</ehcache>
+ entire heap.
+ -->
+ <cache-template name="org.apache.cxf.ws.security.tokenstore.TokenStore">
+ <key-type>java.lang.String</key-type>
+ <value-type>org.apache.cxf.ws.security.tokenstore.SecurityToken</value-type>
+ <expiry>
+ <ttl unit="seconds">3600</ttl>
+ </expiry>
+ <resources>
+ <heap unit="entries">10000</heap>
+ </resources>
+ </cache-template>
+
+</config>
diff --git a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/cache/EHCacheUtilsTest.java b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/cache/EHCacheUtilsTest.java
deleted file mode 100644
index 54f3566..0000000
--- a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/cache/EHCacheUtilsTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.ws.security.cache;
-
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-import org.apache.cxf.Bus;
-import org.apache.cxf.BusFactory;
-import org.apache.wss4j.common.cache.EHCacheManagerHolder;
-
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-
-public class EHCacheUtilsTest {
- @Test
- public void testUseGlobalManager() {
- Bus bus = BusFactory.getThreadDefaultBus();
-
- Configuration conf =
- ConfigurationFactory.parseConfiguration(
- EHCacheManagerHolder.class.getResource("/cxf-test-ehcache.xml"));
- conf.setName("myGlobalConfig");
-
- CacheManager.newInstance(conf);
-
- CacheManager manager = EHCacheUtils.getCacheManager(bus,
- EHCacheManagerHolder.class.getResource("/cxf-test-ehcache.xml"));
-
- assertFalse("myGlobalConfig".equals(manager.getName()));
- EHCacheManagerHolder.releaseCacheManger(manager);
- assertEquals(Status.STATUS_SHUTDOWN, manager.getStatus());
-
- bus.setProperty(EHCacheUtils.GLOBAL_EHCACHE_MANAGER_NAME, "myGlobalConfig");
-
- manager = EHCacheUtils.getCacheManager(bus,
- EHCacheManagerHolder.class.getResource("/cxf-test-ehcache.xml"));
-
- assertEquals("myGlobalConfig", manager.getName());
- EHCacheManagerHolder.releaseCacheManger(manager);
- assertEquals(Status.STATUS_ALIVE, manager.getStatus());
-
- manager.shutdown();
- assertEquals(Status.STATUS_SHUTDOWN, manager.getStatus());
-
- bus.setProperty(EHCacheUtils.GLOBAL_EHCACHE_MANAGER_NAME, "myGlobalConfigXXX");
-
- manager = EHCacheUtils.getCacheManager(bus,
- EHCacheManagerHolder.class.getResource("/cxf-test-ehcache.xml"));
-
- assertFalse("myGlobalConfig".equals(manager.getName()));
- EHCacheManagerHolder.releaseCacheManger(manager);
- assertEquals(Status.STATUS_SHUTDOWN, manager.getStatus());
- }
-}
\ No newline at end of file
diff --git a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreTest.java b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreTest.java
deleted file mode 100644
index 8337c93..0000000
--- a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/MemoryTokenStoreTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.ws.security.tokenstore;
-
-import java.time.Instant;
-
-import org.apache.cxf.message.Message;
-import org.apache.cxf.message.MessageImpl;
-import org.apache.cxf.ws.security.SecurityConstants;
-
-import org.junit.BeforeClass;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-public class MemoryTokenStoreTest {
-
- private static TokenStore store;
-
- @BeforeClass
- public static void init() {
- TokenStoreFactory tokenStoreFactory = new MemoryTokenStoreFactory();
- Message message = new MessageImpl();
- store = tokenStoreFactory.newTokenStore(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, message);
- }
-
- // tests TokenStore apis for storing in the cache.
- @org.junit.Test
- public void testTokenAdd() throws Exception {
- String key = "key";
- SecurityToken token = new SecurityToken(key);
- store.add(token);
- assertEquals(token, store.getToken(key));
- store.remove(token.getId());
- assertNull(store.getToken(key));
-
- String newKey = "xyz";
- store.add(newKey, token);
- assertNull(store.getToken(key));
- assertEquals(token, store.getToken(newKey));
- store.remove(newKey);
- assertNull(store.getToken(newKey));
- }
-
- // tests TokenStore apis for removing from the cache.
- @org.junit.Test
- public void testTokenRemove() {
- SecurityToken token1 = new SecurityToken("token1");
- SecurityToken token2 = new SecurityToken("token2");
- SecurityToken token3 = new SecurityToken("token3");
- store.add(token1);
- store.add(token2);
- store.add(token3);
- assertTrue(store.getTokenIdentifiers().size() == 3);
- store.remove(token3.getId());
- assertNull(store.getToken("test3"));
- store.remove(token1.getId());
- store.remove(token2.getId());
- assertTrue(store.getTokenIdentifiers().isEmpty());
- }
-
- @org.junit.Test
- public void testTokenExpiry() {
- SecurityToken token = new SecurityToken();
-
- Instant expires = Instant.now().plusSeconds(5L * 60L);
- token.setExpires(expires);
-
- assertFalse(token.isExpired());
- assertFalse(token.isAboutToExpire(100L));
- assertTrue(token.isAboutToExpire((5L * 60L * 1000L) + 1L));
- }
-}
diff --git a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/SecurityTokenTest.java b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/SecurityTokenTest.java
index a4c08e9..df343cd 100644
--- a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/SecurityTokenTest.java
+++ b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/SecurityTokenTest.java
@@ -31,8 +31,10 @@ import org.apache.wss4j.common.util.DateUtil;
import static org.apache.wss4j.common.WSS4JConstants.WST_NS_05_12;
import static org.apache.wss4j.common.WSS4JConstants.WSU_NS;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
public class SecurityTokenTest {
@@ -119,4 +121,16 @@ public class SecurityTokenTest {
assertEquals(created, token.getCreated());
assertNull(token.getExpires());
}
+
+ @org.junit.Test
+ public void testTokenExpiry() {
+ SecurityToken token = new SecurityToken();
+
+ Instant expires = Instant.now().plusSeconds(5L * 60L);
+ token.setExpires(expires);
+
+ assertFalse(token.isExpired());
+ assertFalse(token.isAboutToExpire(100L));
+ assertTrue(token.isAboutToExpire((5L * 60L * 1000L) + 1L));
+ }
}
diff --git a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStoreTest.java b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/TokenStoreTest.java
similarity index 73%
rename from rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStoreTest.java
rename to rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/TokenStoreTest.java
index bc1efd4..506bb78 100644
--- a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/EHCacheTokenStoreTest.java
+++ b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/tokenstore/TokenStoreTest.java
@@ -18,32 +18,43 @@
*/
package org.apache.cxf.ws.security.tokenstore;
-import org.apache.cxf.common.classloader.ClassLoaderUtils;
+import java.util.Arrays;
+import java.util.Collection;
+
import org.apache.cxf.message.ExchangeImpl;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageImpl;
import org.apache.cxf.ws.security.SecurityConstants;
+import org.apache.xml.security.utils.ClassLoaderUtils;
-import org.junit.BeforeClass;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-public class EHCacheTokenStoreTest {
+@RunWith(value = org.junit.runners.Parameterized.class)
+public class TokenStoreTest {
+
+ private TokenStore store;
- private static TokenStore store;
+ public TokenStoreTest(TokenStore store) {
+ this.store = store;
+ }
- @BeforeClass
- public static void init() {
- TokenStoreFactory tokenStoreFactory = new EHCacheTokenStoreFactory();
+ @Parameterized.Parameters(name = "{0}")
+ public static Collection<TokenStore> data() throws TokenStoreException {
Message message = new MessageImpl();
message.put(
- SecurityConstants.CACHE_CONFIG_FILE,
- ClassLoaderUtils.getResource("cxf-ehcache.xml", EHCacheTokenStoreTest.class)
+ SecurityConstants.CACHE_CONFIG_FILE,
+ ClassLoaderUtils.getResource("cxf-ehcache.xml", TokenStoreTest.class)
);
message.setExchange(new ExchangeImpl());
- store = tokenStoreFactory.newTokenStore(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, message);
+ return Arrays.asList(
+ new MemoryTokenStoreFactory().newTokenStore(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, message),
+ new EHCacheTokenStoreFactory().newTokenStore(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, message)
+ );
}
// tests TokenStore apis for storing in the cache.
@@ -80,4 +91,5 @@ public class EHCacheTokenStoreTest {
store.remove(token2.getId());
assertTrue(store.getTokenIdentifiers().isEmpty());
}
+
}
diff --git a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/wss4j/AbstractPolicySecurityTest.java b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/wss4j/AbstractPolicySecurityTest.java
index 9246a1b..e2ddd59 100644
--- a/rt/ws/security/src/test/java/org/apache/cxf/ws/security/wss4j/AbstractPolicySecurityTest.java
+++ b/rt/ws/security/src/test/java/org/apache/cxf/ws/security/wss4j/AbstractPolicySecurityTest.java
@@ -260,8 +260,7 @@ public abstract class AbstractPolicySecurityTest extends AbstractSecurityTest {
protected void runInInterceptorAndValidateWss(Document document, AssertionInfoMap aim,
List<CoverageType> types) throws Exception {
- PolicyBasedWSS4JInInterceptor inHandler =
- this.getInInterceptor(types);
+ PolicyBasedWSS4JInInterceptor inHandler = this.getInInterceptor(types);
SoapMessage inmsg = this.getSoapMessageForDom(document, aim);
@@ -273,6 +272,10 @@ public abstract class AbstractPolicySecurityTest extends AbstractSecurityTest {
inmsg.getHeaders().add(securityHeader);
}
+ final Endpoint endpoint = inmsg.getExchange().getEndpoint();
+ if (endpoint != null && endpoint.getEndpointInfo().getProperty(TokenStore.class.getName()) == null) {
+ inmsg.put(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, new MemoryTokenStore());
+ }
inHandler.handleMessage(inmsg);
for (CoverageType type : types) {
@@ -308,6 +311,10 @@ public abstract class AbstractPolicySecurityTest extends AbstractSecurityTest {
List<QName> assertedOutAssertions,
List<QName> notAssertedOutAssertions) throws Exception {
+ if (msg.getExchange().getEndpoint() != null
+ && msg.getExchange().getEndpoint().getEndpointInfo().getProperty(TokenStore.class.getName()) == null) {
+ msg.put(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, new MemoryTokenStore());
+ }
this.getOutInterceptor().handleMessage(msg);
try {
diff --git a/rt/ws/security/src/test/resources/cxf-test-ehcache.xml b/rt/ws/security/src/test/resources/cxf-test-ehcache.xml
deleted file mode 100644
index eaef32e..0000000
--- a/rt/ws/security/src/test/resources/cxf-test-ehcache.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true">
-
- <diskStore path="java.io.tmpdir"/>
-
- <defaultCache
- maxEntriesLocalHeap="5000"
- eternal="false"
- timeToIdleSeconds="3600"
- timeToLiveSeconds="3600"
- overflowToDisk="true"
- maxElementsOnDisk="10000000"
- diskPersistent="false"
- diskExpiryThreadIntervalSeconds="120"
- memoryStoreEvictionPolicy="LRU"
- />
-</ehcache>
diff --git a/services/sts/sts-core/pom.xml b/services/sts/sts-core/pom.xml
index fabeae5..90203f3 100644
--- a/services/sts/sts-core/pom.xml
+++ b/services/sts/sts-core/pom.xml
@@ -59,9 +59,9 @@
<scope>compile</scope>
</dependency>
<dependency>
- <groupId>net.sf.ehcache</groupId>
+ <groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
- <version>${cxf.ehcache.version}</version>
+ <version>${cxf.ehcache3.version}</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
@@ -172,7 +172,7 @@
org.apache.cxf.*,
javax.xml.ws*;version="[0.0,3)",
org.springframework.ldap*;resolution:=optional,
- net.sf.ehcache*;resolution:=optional;version="[2.5, 3.0.0)",
+ org.ehcache*;resolution:=optional;version="[3.0.0, 4.0.0)",
org.opensaml*;version="${cxf.opensaml.osgi.version.range}",
javax.xml.bind;version="${cxf.osgi.javax.bind.version}",
*
diff --git a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/AbstractIdentityCache.java b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/AbstractIdentityCache.java
index e17378c..ffc6bcf 100644
--- a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/AbstractIdentityCache.java
+++ b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/AbstractIdentityCache.java
@@ -91,7 +91,11 @@ public abstract class AbstractIdentityCache implements IdentityCache, IdentityMa
//Merge into identities object
this.mergeMap(identities, cachedItem);
}
- this.add(targetPrincipal.getName(), targetRealm, identities);
+
+ // Update existing entries
+ for (Map.Entry<String, String> entry : identities.entrySet()) {
+ this.add(entry.getValue(), entry.getKey(), identities);
+ }
} else {
getStatistics().increaseCacheHit();
if (LOG.isLoggable(Level.INFO)) {
diff --git a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/DefaultInMemoryTokenStore.java b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/DefaultInMemoryTokenStore.java
index 9bd6869..877d526 100644
--- a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/DefaultInMemoryTokenStore.java
+++ b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/DefaultInMemoryTokenStore.java
@@ -23,14 +23,17 @@ import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.common.classloader.ClassLoaderUtils;
import org.apache.cxf.ws.security.tokenstore.EHCacheTokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
public class DefaultInMemoryTokenStore extends EHCacheTokenStore {
- public DefaultInMemoryTokenStore(Bus b) {
- super("STS", b, ClassLoaderUtils.getResource("cxf-ehcache.xml", DefaultInMemoryTokenStore.class));
+ public DefaultInMemoryTokenStore(Bus b) throws TokenStoreException {
+ super(TokenStore.class.getName() + "-STS", b,
+ ClassLoaderUtils.getResource("cxf-ehcache.xml", DefaultInMemoryTokenStore.class));
}
- public DefaultInMemoryTokenStore() {
- super("STS", BusFactory.getDefaultBus(),
+ public DefaultInMemoryTokenStore() throws TokenStoreException {
+ super(TokenStore.class.getName() + "-STS", BusFactory.getDefaultBus(),
ClassLoaderUtils.getResource("cxf-ehcache.xml", DefaultInMemoryTokenStore.class));
}
diff --git a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/EHCacheIdentityCache.java b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/EHCacheIdentityCache.java
index ea6a486..005a01c 100644
--- a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/EHCacheIdentityCache.java
+++ b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/EHCacheIdentityCache.java
@@ -29,11 +29,6 @@ import java.util.logging.Logger;
import javax.management.JMException;
import javax.management.ObjectName;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
import org.apache.cxf.Bus;
import org.apache.cxf.buslifecycle.BusLifeCycleListener;
import org.apache.cxf.buslifecycle.BusLifeCycleManager;
@@ -45,9 +40,13 @@ import org.apache.cxf.management.annotation.ManagedOperation;
import org.apache.cxf.management.annotation.ManagedResource;
import org.apache.cxf.resource.ResourceManager;
import org.apache.cxf.sts.IdentityMapper;
-import org.apache.cxf.ws.security.cache.EHCacheUtils;
import org.apache.cxf.ws.security.tokenstore.TokenStoreFactory;
-import org.apache.wss4j.common.cache.EHCacheManagerHolder;
+import org.ehcache.Cache;
+import org.ehcache.CacheManager;
+import org.ehcache.Status;
+import org.ehcache.config.Configuration;
+import org.ehcache.config.builders.CacheManagerBuilder;
+import org.ehcache.xml.XmlConfiguration;
/**
* A EH-Cache based cache to cache identities in different realms where
@@ -58,9 +57,9 @@ public class EHCacheIdentityCache extends AbstractIdentityCache
implements Closeable, BusLifeCycleListener {
private static final Logger LOG = LogUtils.getL7dLogger(EHCacheIdentityCache.class);
-
- private Ehcache cache;
- private CacheManager cacheManager;
+ private static final String KEY = "org.apache.cxf.sts.cache.EHCacheIdentityCache";
+ private Cache<String, EHCacheIdentityValue> cache;
+ private final CacheManager cacheManager;
public EHCacheIdentityCache(
@@ -85,30 +84,27 @@ public class EHCacheIdentityCache extends AbstractIdentityCache
}
}
- if (configFileURL != null) {
- cacheManager = EHCacheUtils.getCacheManager(b, configFileURL);
- } else {
- cacheManager = EHCacheUtils.getCacheManager(b, getDefaultConfigFileURL());
- }
- CacheConfiguration cc = EHCacheManagerHolder.getCacheConfiguration(key, cacheManager);
+ URL xmlConfigURL = configFileURL != null ? configFileURL : getDefaultConfigFileURL();
+ Configuration xmlConfig = new XmlConfiguration(xmlConfigURL);
+ cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
- Ehcache newCache = new Cache(cc);
- cache = cacheManager.addCacheIfAbsent(newCache);
+ cacheManager.init();
+ cache = cacheManager.getCache(KEY, String.class, EHCacheIdentityValue.class);
}
@Override
public void add(String user, String realm, Map<String, String> identities) {
- cache.put(new Element(user + "@" + realm, identities));
+ cache.put(user + "@" + realm, new EHCacheIdentityValue(identities));
}
- @SuppressWarnings("unchecked")
@ManagedOperation()
@Override
public Map<String, String> get(String user, String realm) {
- Element element = cache.get(user + "@" + realm);
- if (element != null && !cache.isExpired(element)) {
- return (Map<String, String>)element.getObjectValue();
+ EHCacheIdentityValue value = cache.get(user + "@" + realm);
+ if (value != null) {
+ return value.getValue();
}
+
return null;
}
@@ -118,32 +114,15 @@ public class EHCacheIdentityCache extends AbstractIdentityCache
}
@ManagedOperation()
- @Override
- public void clear() {
- cache.removeAll();
- }
-
- @ManagedOperation()
- @Override
- public int size() {
- return cache.getSize();
- }
-
- @ManagedOperation()
public String getContent() {
return this.cache.toString();
}
public void close() {
- if (cacheManager != null) {
- // this step is especially important for global shared cache manager
- if (cache != null) {
- cacheManager.removeCache(cache.getName());
- }
+ if (cacheManager.getStatus() == Status.AVAILABLE) {
+ cacheManager.removeCache(KEY);
+ cacheManager.close();
- EHCacheManagerHolder.releaseCacheManger(cacheManager);
- cacheManager = null;
- cache = null;
if (super.getBus() != null) {
super.getBus().getExtension(BusLifeCycleManager.class).unregisterLifeCycleListener(this);
}
diff --git a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/IdentityCache.java b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/EHCacheIdentityValue.java
similarity index 69%
copy from services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/IdentityCache.java
copy to services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/EHCacheIdentityValue.java
index 37a2635..545447b 100644
--- a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/IdentityCache.java
+++ b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/EHCacheIdentityValue.java
@@ -19,18 +19,23 @@
package org.apache.cxf.sts.cache;
+import java.io.Serializable;
import java.util.Map;
-public interface IdentityCache {
-
- void add(String user, String realm, Map<String, String> identities);
+/**
+ * A cache value for EHCache. It's just a wrapper for Map<String, String>.
+ */
+public class EHCacheIdentityValue implements Serializable {
- Map<String, String> get(String user, String realm);
+ private final Map<String, String> value;
- void remove(String user, String realm);
+ public EHCacheIdentityValue(Map<String, String> value) {
+ this.value = value;
+ }
- void clear();
+ public Map<String, String> getValue() {
+ return value;
+ }
- int size();
}
diff --git a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/IdentityCache.java b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/IdentityCache.java
index 37a2635..43018e7 100644
--- a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/IdentityCache.java
+++ b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/IdentityCache.java
@@ -29,8 +29,4 @@ public interface IdentityCache {
void remove(String user, String realm);
- void clear();
-
- int size();
-
}
diff --git a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/MemoryIdentityCache.java b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/MemoryIdentityCache.java
index bccf8b8..8ea543b 100644
--- a/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/MemoryIdentityCache.java
+++ b/services/sts/sts-core/src/main/java/org/apache/cxf/sts/cache/MemoryIdentityCache.java
@@ -100,18 +100,6 @@ public class MemoryIdentityCache extends AbstractIdentityCache {
}
@ManagedOperation()
- @Override
- public void clear() {
- cache.clear();
- }
-
- @ManagedOperation()
- @Override
- public int size() {
- return cache.size();
- }
-
- @ManagedOperation()
public String getContent() {
return this.cache.toString();
}
diff --git a/services/sts/sts-core/src/main/resources/sts-ehcache.xml b/services/sts/sts-core/src/main/resources/sts-ehcache.xml
index a28c42a..c1a307f 100644
--- a/services/sts/sts-core/src/main/resources/sts-ehcache.xml
+++ b/services/sts/sts-core/src/main/resources/sts-ehcache.xml
@@ -1,5 +1,23 @@
<?xml version="1.0"?>
-<ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true" name="cxfSTSSecurityCache">
- <diskStore path="java.io.tmpdir"/>
- <cache name="org.apache.cxf.sts.cache.EHCacheIdentityCache" maxEntriesLocalHeap="5000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>
-</ehcache>
+<config
+ xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
+ xmlns='http://www.ehcache.org/v3'
+ xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.8.xsd">
+
+ <persistence directory="${java.io.tmpdir}" />
+
+ <cache alias="org.apache.cxf.sts.cache.EHCacheIdentityCache">
+ <key-type>java.lang.String</key-type>
+ <value-type>org.apache.cxf.sts.cache.EHCacheIdentityValue</value-type>
+ <expiry>
+ <ttl unit="seconds">3600</ttl>
+ </expiry>
+ <resources>
+ <heap unit="entries">5000</heap>
+ <disk unit="MB" persistent="false">10</disk>
+ </resources>
+ </cache>
+
+</config>
+
+
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/cache/MemoryIdentityCacheTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/cache/MemoryIdentityCacheTest.java
index 3a7c58a..39c9dd5 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/cache/MemoryIdentityCacheTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/cache/MemoryIdentityCacheTest.java
@@ -44,7 +44,6 @@ public class MemoryIdentityCacheTest {
AbstractIdentityCache cache = getIdentityCache(mapper);
cache.mapPrincipal("REALM_A", new CustomTokenPrincipal("user_aaa"), "REALM_B");
- assertEquals(2, cache.size());
assertNotNull(cache.get("user_aaa", "REALM_A"));
assertNotNull(cache.get("user_bbb", "REALM_B"));
@@ -60,7 +59,6 @@ public class MemoryIdentityCacheTest {
cache.mapPrincipal("REALM_A", new CustomTokenPrincipal("user_aaa"), "REALM_B");
cache.mapPrincipal("REALM_C", new CustomTokenPrincipal("user_ccc"), "REALM_D");
- assertEquals(4, cache.size());
assertNotNull(cache.get("user_aaa", "REALM_A"));
assertNotNull(cache.get("user_bbb", "REALM_B"));
assertNotNull(cache.get("user_ccc", "REALM_C"));
@@ -80,7 +78,6 @@ public class MemoryIdentityCacheTest {
cache.mapPrincipal("REALM_C", new CustomTokenPrincipal("user_ccc"), "REALM_D");
cache.mapPrincipal("REALM_A", new CustomTokenPrincipal("user_aaa"), "REALM_D");
//now, mapping from A -> D and B -> D are cached as well
- assertEquals(4, cache.size());
assertNotNull(cache.get("user_aaa", "REALM_A"));
assertNotNull(cache.get("user_bbb", "REALM_B"));
assertNotNull(cache.get("user_ccc", "REALM_C"));
@@ -102,7 +99,6 @@ public class MemoryIdentityCacheTest {
cache.mapPrincipal("REALM_A", new CustomTokenPrincipal("user_aaa"), "REALM_B");
cache.mapPrincipal("REALM_D", new CustomTokenPrincipal("user_ddd"), "REALM_E");
- assertEquals(4, cache.size());
//No Mapping occured between A,B and D,E (C not involved at all)
assertEquals(2, cache.get("user_aaa", "REALM_A").size());
assertEquals(2, cache.get("user_bbb", "REALM_B").size());
@@ -110,7 +106,6 @@ public class MemoryIdentityCacheTest {
assertEquals(2, cache.get("user_eee", "REALM_E").size());
cache.mapPrincipal("REALM_B", new CustomTokenPrincipal("user_bbb"), "REALM_C");
- assertEquals(5, cache.size());
assertNotNull(cache.get("user_aaa", "REALM_A"));
assertNotNull(cache.get("user_bbb", "REALM_B"));
assertNotNull(cache.get("user_ccc", "REALM_C"));
@@ -125,7 +120,6 @@ public class MemoryIdentityCacheTest {
cache.mapPrincipal("REALM_C", new CustomTokenPrincipal("user_ccc"), "REALM_E");
//All mappings are known now
- assertEquals(5, cache.size());
assertNotNull(cache.get("user_aaa", "REALM_A"));
assertNotNull(cache.get("user_bbb", "REALM_B"));
assertNotNull(cache.get("user_ccc", "REALM_C"));
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/CancelSCTUnitTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/CancelSCTUnitTest.java
index f7be7ec..0b67171 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/CancelSCTUnitTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/CancelSCTUnitTest.java
@@ -50,12 +50,15 @@ import org.apache.cxf.ws.security.sts.provider.model.CancelTargetType;
import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType;
import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.trust.STSUtils;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.CustomTokenPrincipal;
+import org.junit.BeforeClass;
+
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -69,7 +72,12 @@ public class CancelSCTUnitTest {
private static final QName QNAME_REQ_TOKEN_CANCELLED =
QNameConstants.WS_TRUST_FACTORY.createRequestedTokenCancelled(null).getName();
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
+
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
/**
* Test to successfully cancel a SecurityContextToken
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/IssueJWTUnitTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/IssueJWTUnitTest.java
index 291d0a9..3dd6ea6 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/IssueJWTUnitTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/IssueJWTUnitTest.java
@@ -54,6 +54,7 @@ import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenRespons
import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType;
import org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -61,6 +62,7 @@ import org.apache.wss4j.common.crypto.CryptoType;
import org.apache.wss4j.common.principal.CustomTokenPrincipal;
import org.junit.Assert;
+import org.junit.BeforeClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -78,7 +80,12 @@ public class IssueJWTUnitTest {
public static final QName UNATTACHED_REFERENCE =
QNameConstants.WS_TRUST_FACTORY.createRequestedUnattachedReference(null).getName();
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
+
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
/**
* Test to successfully issue a JWT Token
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/IssueSCTUnitTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/IssueSCTUnitTest.java
index dee45dc..e5fb9f4 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/IssueSCTUnitTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/IssueSCTUnitTest.java
@@ -51,6 +51,7 @@ import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenRespons
import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType;
import org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.trust.STSUtils;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
@@ -58,6 +59,8 @@ import org.apache.wss4j.common.crypto.CryptoFactory;
import org.apache.wss4j.common.principal.CustomTokenPrincipal;
import org.apache.wss4j.common.util.DOM2Writer;
+import org.junit.BeforeClass;
+
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -74,7 +77,7 @@ public class IssueSCTUnitTest {
public static final QName UNATTACHED_REFERENCE =
QNameConstants.WS_TRUST_FACTORY.createRequestedUnattachedReference(null).getName();
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
private static boolean unrestrictedPoliciesInstalled;
@@ -82,6 +85,11 @@ public class IssueSCTUnitTest {
unrestrictedPoliciesInstalled = TestUtilities.checkUnrestrictedPoliciesInstalled();
};
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
+
/**
* Test to successfully issue a SecurityContextToken
*/
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/RenewSamlUnitTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/RenewSamlUnitTest.java
index 7cfb6e1..2b04461 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/RenewSamlUnitTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/RenewSamlUnitTest.java
@@ -59,6 +59,7 @@ import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenRespons
import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType;
import org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -85,7 +86,7 @@ public class RenewSamlUnitTest {
private static TokenStore tokenStore;
@BeforeClass
- public static void init() {
+ public static void init() throws TokenStoreException {
tokenStore = new DefaultInMemoryTokenStore();
}
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/ValidateSCTUnitTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/ValidateSCTUnitTest.java
index 8792d24..39ad68e 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/ValidateSCTUnitTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/operation/ValidateSCTUnitTest.java
@@ -51,12 +51,15 @@ import org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType;
import org.apache.cxf.ws.security.sts.provider.model.StatusType;
import org.apache.cxf.ws.security.sts.provider.model.ValidateTargetType;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.trust.STSUtils;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.CustomTokenPrincipal;
+import org.junit.BeforeClass;
+
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -72,7 +75,12 @@ public class ValidateSCTUnitTest {
private static final QName QNAME_WST_STATUS =
QNameConstants.WS_TRUST_FACTORY.createStatus(null).getName();
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
+
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
/**
* Test to successfully validate a SecurityContextToken
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/canceller/SCTCancellerTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/canceller/SCTCancellerTest.java
index 39d53f3..7d1b7dd 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/canceller/SCTCancellerTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/canceller/SCTCancellerTest.java
@@ -39,6 +39,7 @@ import org.apache.cxf.sts.token.provider.TokenProvider;
import org.apache.cxf.sts.token.provider.TokenProviderParameters;
import org.apache.cxf.sts.token.provider.TokenProviderResponse;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.trust.STSUtils;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -46,6 +47,8 @@ import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.CustomTokenPrincipal;
import org.apache.wss4j.dom.message.token.SecurityContextToken;
+import org.junit.BeforeClass;
+
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -55,7 +58,12 @@ import static org.junit.Assert.assertTrue;
*/
public class SCTCancellerTest {
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
+
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
/**
* Get a (valid) SecurityContextToken and successfully cancel it.
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/provider/JWTTokenProviderTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/provider/JWTTokenProviderTest.java
index faecd48..a6ca998 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/provider/JWTTokenProviderTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/provider/JWTTokenProviderTest.java
@@ -45,6 +45,7 @@ import org.apache.cxf.sts.service.EncryptionProperties;
import org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider;
import org.apache.cxf.test.TestUtilities;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
import org.apache.wss4j.common.crypto.CryptoType;
@@ -54,6 +55,7 @@ import org.apache.wss4j.common.principal.CustomTokenPrincipal;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Assert;
+import org.junit.BeforeClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -64,12 +66,17 @@ import static org.junit.Assert.assertTrue;
*/
public class JWTTokenProviderTest {
private static boolean unrestrictedPoliciesInstalled;
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
static {
unrestrictedPoliciesInstalled = TestUtilities.checkUnrestrictedPoliciesInstalled();
};
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
+
@org.junit.Test
public void testCreateUnsignedJWT() throws Exception {
TokenProvider jwtTokenProvider = new JWTTokenProvider();
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/provider/SCTProviderTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/provider/SCTProviderTest.java
index 134f6f6..3a1a88e 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/provider/SCTProviderTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/provider/SCTProviderTest.java
@@ -31,6 +31,7 @@ import org.apache.cxf.sts.request.KeyRequirements;
import org.apache.cxf.sts.request.TokenRequirements;
import org.apache.cxf.sts.service.EncryptionProperties;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.trust.STSUtils;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -40,6 +41,8 @@ import org.apache.wss4j.common.principal.CustomTokenPrincipal;
import org.apache.wss4j.common.util.DOM2Writer;
import org.apache.wss4j.dom.message.token.SecurityContextToken;
+import org.junit.BeforeClass;
+
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -50,7 +53,12 @@ import static org.junit.Assert.assertTrue;
*/
public class SCTProviderTest {
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
+
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
/**
* Create a SecurityContextToken
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerLifetimeTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerLifetimeTest.java
index 0cde131..64d2767 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerLifetimeTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerLifetimeTest.java
@@ -46,6 +46,7 @@ import org.apache.cxf.sts.token.provider.TokenProviderParameters;
import org.apache.cxf.sts.token.provider.TokenProviderResponse;
import org.apache.cxf.ws.security.sts.provider.STSException;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -68,7 +69,7 @@ public class SAMLTokenRenewerLifetimeTest {
private static TokenStore tokenStore;
@BeforeClass
- public static void init() {
+ public static void init() throws TokenStoreException {
tokenStore = new DefaultInMemoryTokenStore();
}
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerPOPTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerPOPTest.java
index eafd86f..e51c2d3 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerPOPTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerPOPTest.java
@@ -54,6 +54,7 @@ import org.apache.cxf.sts.token.validator.TokenValidator;
import org.apache.cxf.sts.token.validator.TokenValidatorParameters;
import org.apache.cxf.sts.token.validator.TokenValidatorResponse;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -81,7 +82,7 @@ public class SAMLTokenRenewerPOPTest {
private static TokenStore tokenStore;
@BeforeClass
- public static void init() {
+ public static void init() throws TokenStoreException {
tokenStore = new DefaultInMemoryTokenStore();
}
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerRealmTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerRealmTest.java
index 2fccc17..a097599 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerRealmTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerRealmTest.java
@@ -55,6 +55,7 @@ import org.apache.cxf.sts.token.validator.TokenValidator;
import org.apache.cxf.sts.token.validator.TokenValidatorParameters;
import org.apache.cxf.sts.token.validator.TokenValidatorResponse;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -76,7 +77,7 @@ public class SAMLTokenRenewerRealmTest {
private static TokenStore tokenStore;
@BeforeClass
- public static void init() {
+ public static void init() throws TokenStoreException {
tokenStore = new DefaultInMemoryTokenStore();
}
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerTest.java
index 7079ada..da75a59 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/renewer/SAMLTokenRenewerTest.java
@@ -50,6 +50,7 @@ import org.apache.cxf.sts.token.validator.TokenValidatorParameters;
import org.apache.cxf.sts.token.validator.TokenValidatorResponse;
import org.apache.cxf.ws.security.sts.provider.STSException;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -73,7 +74,7 @@ public class SAMLTokenRenewerTest {
private static TokenStore tokenStore;
@BeforeClass
- public static void init() {
+ public static void init() throws TokenStoreException {
tokenStore = new DefaultInMemoryTokenStore();
}
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/JWTTokenValidatorRealmTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/JWTTokenValidatorRealmTest.java
index 4f1fc1d..281481e 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/JWTTokenValidatorRealmTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/JWTTokenValidatorRealmTest.java
@@ -48,11 +48,14 @@ import org.apache.cxf.sts.token.realm.JWTRealmCodec;
import org.apache.cxf.sts.token.realm.RealmProperties;
import org.apache.cxf.sts.token.validator.jwt.JWTTokenValidator;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.CustomTokenPrincipal;
+import org.junit.BeforeClass;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -62,7 +65,12 @@ import static org.junit.Assert.assertTrue;
* Some unit tests for validating JWTTokens in different realms
*/
public class JWTTokenValidatorRealmTest {
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
+
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
@org.junit.Test
public void testRealmA() throws Exception {
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/JWTTokenValidatorTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/JWTTokenValidatorTest.java
index 95350e4..59304d3 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/JWTTokenValidatorTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/JWTTokenValidatorTest.java
@@ -53,12 +53,15 @@ import org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider;
import org.apache.cxf.sts.token.validator.jwt.DefaultJWTRoleParser;
import org.apache.cxf.sts.token.validator.jwt.JWTTokenValidator;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
import org.apache.wss4j.common.ext.WSPasswordCallback;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.CustomTokenPrincipal;
+import org.junit.BeforeClass;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -67,7 +70,12 @@ import static org.junit.Assert.assertTrue;
* Some unit tests for validating JWTTokens.
*/
public class JWTTokenValidatorTest {
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
+
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
@org.junit.Test
public void testCreateAndValidateSignedJWT() throws Exception {
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SAMLTokenValidatorCachedRealmTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SAMLTokenValidatorCachedRealmTest.java
index a6416a5..305176b 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SAMLTokenValidatorCachedRealmTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SAMLTokenValidatorCachedRealmTest.java
@@ -46,6 +46,7 @@ import org.apache.cxf.sts.token.provider.TokenProviderResponse;
import org.apache.cxf.sts.token.realm.RealmProperties;
import org.apache.cxf.sts.token.realm.SAMLRealmCodec;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -67,7 +68,7 @@ public class SAMLTokenValidatorCachedRealmTest {
private static TokenStore tokenStore;
@BeforeClass
- public static void init() {
+ public static void init() throws TokenStoreException {
tokenStore = new DefaultInMemoryTokenStore();
}
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SAMLTokenValidatorTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SAMLTokenValidatorTest.java
index cfe5d79..3cb5028 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SAMLTokenValidatorTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SAMLTokenValidatorTest.java
@@ -61,6 +61,7 @@ import org.apache.cxf.sts.token.provider.TokenProvider;
import org.apache.cxf.sts.token.provider.TokenProviderParameters;
import org.apache.cxf.sts.token.provider.TokenProviderResponse;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.wss4j.common.WSS4JConstants;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -83,7 +84,7 @@ public class SAMLTokenValidatorTest {
private static TokenStore tokenStore;
@BeforeClass
- public static void init() {
+ public static void init() throws TokenStoreException {
tokenStore = new DefaultInMemoryTokenStore();
}
diff --git a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SCTValidatorTest.java b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SCTValidatorTest.java
index 3528a34..3a897a0 100644
--- a/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SCTValidatorTest.java
+++ b/services/sts/sts-core/src/test/java/org/apache/cxf/sts/token/validator/SCTValidatorTest.java
@@ -39,6 +39,7 @@ import org.apache.cxf.sts.token.provider.TokenProvider;
import org.apache.cxf.sts.token.provider.TokenProviderParameters;
import org.apache.cxf.sts.token.provider.TokenProviderResponse;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
+import org.apache.cxf.ws.security.tokenstore.TokenStoreException;
import org.apache.cxf.ws.security.trust.STSUtils;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
@@ -46,6 +47,8 @@ import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.CustomTokenPrincipal;
import org.apache.wss4j.dom.message.token.SecurityContextToken;
+import org.junit.BeforeClass;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -56,7 +59,12 @@ import static org.junit.Assert.assertTrue;
*/
public class SCTValidatorTest {
- private static TokenStore tokenStore = new DefaultInMemoryTokenStore();
+ private static TokenStore tokenStore;
+
+ @BeforeClass
+ public static void init() throws TokenStoreException {
+ tokenStore = new DefaultInMemoryTokenStore();
+ }
/**
* Test a valid SecurityContextToken
diff --git a/services/sts/systests/advanced/pom.xml b/services/sts/systests/advanced/pom.xml
index 7e12515..6cc36a9 100644
--- a/services/sts/systests/advanced/pom.xml
+++ b/services/sts/systests/advanced/pom.xml
@@ -129,9 +129,9 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>net.sf.ehcache</groupId>
+ <groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
- <version>${cxf.ehcache.version}</version>
+ <version>${cxf.ehcache3.version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
diff --git a/services/sts/systests/advanced/src/test/java/org/apache/cxf/systest/sts/caching/CachingTest.java b/services/sts/systests/advanced/src/test/java/org/apache/cxf/systest/sts/caching/CachingTest.java
index 140386e..1620810 100644
--- a/services/sts/systests/advanced/src/test/java/org/apache/cxf/systest/sts/caching/CachingTest.java
+++ b/services/sts/systests/advanced/src/test/java/org/apache/cxf/systest/sts/caching/CachingTest.java
@@ -84,9 +84,7 @@ public class CachingTest extends AbstractBusClientServerTestBase {
stopAllServers();
}
- // @Ignore'd because failing too often on slow Jenkins machines
@org.junit.Test
- @org.junit.Ignore
public void testSTSClientCaching() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
diff --git a/services/sts/systests/advanced/src/test/java/org/apache/cxf/systest/sts/caching/ServerCachingTest.java b/services/sts/systests/advanced/src/test/java/org/apache/cxf/systest/sts/caching/ServerCachingTest.java
index dab4481..c0b3853 100644
--- a/services/sts/systests/advanced/src/test/java/org/apache/cxf/systest/sts/caching/ServerCachingTest.java
+++ b/services/sts/systests/advanced/src/test/java/org/apache/cxf/systest/sts/caching/ServerCachingTest.java
@@ -93,9 +93,7 @@ public class ServerCachingTest extends AbstractBusClientServerTestBase {
stopAllServers();
}
- // Disabled due to continually failing on Jenkins build
@org.junit.Test
- @org.junit.Ignore
public void testServerSideSAMLTokenCaching() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
diff --git a/services/sts/systests/basic/pom.xml b/services/sts/systests/basic/pom.xml
index 910d923..09f16ef 100644
--- a/services/sts/systests/basic/pom.xml
+++ b/services/sts/systests/basic/pom.xml
@@ -118,9 +118,9 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>net.sf.ehcache</groupId>
+ <groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
- <version>${cxf.ehcache.version}</version>
+ <version>${cxf.ehcache3.version}</version>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
diff --git a/services/xkms/xkms-client/pom.xml b/services/xkms/xkms-client/pom.xml
index bb534df..baf878e 100644
--- a/services/xkms/xkms-client/pom.xml
+++ b/services/xkms/xkms-client/pom.xml
@@ -91,9 +91,9 @@
<version>${project.version}</version>
</dependency>
<dependency>
- <groupId>net.sf.ehcache</groupId>
+ <groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
- <version>${cxf.ehcache.version}</version>
+ <version>${cxf.ehcache3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
diff --git a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/EHCacheUtil.java b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/EHCacheUtil.java
deleted file mode 100644
index f0fd29a..0000000
--- a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/EHCacheUtil.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.cxf.xkms.cache;
-
-import java.lang.reflect.Method;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-
-/**
- */
-public final class EHCacheUtil {
- private static Method cacheManagerCreateMethodNoArg;
- private static Method cacheManagerCreateMethodConfigurationArg;
- static {
- // these methods are either completely available or absent (valid assumption from 2.5.0 to 2.7.2 so far)
- try {
- // from 2.5.2
- cacheManagerCreateMethodNoArg = CacheManager.class.getMethod("newInstance", (Class<?>[])null);
- cacheManagerCreateMethodConfigurationArg = CacheManager.class.getMethod("newInstance", Configuration.class);
- } catch (NoSuchMethodException e) {
- try {
- // before 2.5.2
- cacheManagerCreateMethodNoArg = CacheManager.class.getMethod("create", (Class<?>[])null);
- cacheManagerCreateMethodConfigurationArg = CacheManager.class.getMethod("create", Configuration.class);
- } catch (Throwable t) {
- // ignore
- }
- }
- }
-
- private EHCacheUtil() {
- //
- }
-
- public static CacheConfiguration getCacheConfiguration(String key, CacheManager cacheManager) {
- CacheConfiguration cc = cacheManager.getConfiguration().getCacheConfigurations().get(key);
- if (cc == null && key.contains("-")) {
- cc = cacheManager.getConfiguration().getCacheConfigurations().get(
- key.substring(0, key.lastIndexOf('-') - 1));
- }
- if (cc == null) {
- cc = cacheManager.getConfiguration().getDefaultCacheConfiguration();
- }
- if (cc == null) {
- cc = new CacheConfiguration();
- } else {
- cc = cc.clone();
- }
- cc.setName(key);
- return cc;
- }
-
- public static CacheManager createCacheManager() throws CacheException {
- try {
- return (CacheManager)cacheManagerCreateMethodNoArg.invoke(null, (Object[])null);
- } catch (Exception e) {
- throw new CacheException(e);
- }
- }
-
- public static CacheManager createCacheManager(Configuration conf) throws CacheException {
- try {
- return (CacheManager)cacheManagerCreateMethodConfigurationArg.invoke(null, new Object[]{conf});
- } catch (Exception e) {
- throw new CacheException(e);
- }
- }
-}
diff --git a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/EHCacheXKMSClientCache.java b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/EHCacheXKMSClientCache.java
index c5c365c..396ca29 100644
--- a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/EHCacheXKMSClientCache.java
+++ b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/EHCacheXKMSClientCache.java
@@ -21,57 +21,55 @@ package org.apache.cxf.xkms.cache;
import java.io.File;
import java.net.URL;
+import java.util.UUID;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-import net.sf.ehcache.config.DiskStoreConfiguration;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.buslifecycle.BusLifeCycleListener;
import org.apache.cxf.buslifecycle.BusLifeCycleManager;
import org.apache.cxf.common.classloader.ClassLoaderUtils;
+import org.apache.wss4j.common.util.Loader;
+import org.ehcache.Cache;
+import org.ehcache.CacheManager;
+import org.ehcache.Status;
+import org.ehcache.config.builders.CacheConfigurationBuilder;
+import org.ehcache.config.builders.CacheManagerBuilder;
+import org.ehcache.xml.XmlConfiguration;
/**
* An in-memory EHCache implementation of the XKMSClientCache interface.
*/
public class EHCacheXKMSClientCache implements XKMSClientCache, BusLifeCycleListener {
- public static final String CACHE_KEY = "cxf.xkms.client.cache";
+ public static final String TEMPLATE_KEY = "cxf.xkms.client.cache";
private static final String DEFAULT_CONFIG_URL = "cxf-xkms-client-ehcache.xml";
- private Ehcache cache;
- private CacheManager cacheManager;
- private Bus bus;
+ private final Cache<String, XKMSCacheToken> cache;
+ private final CacheManager cacheManager;
+ private final Bus bus;
+ private final String cacheKey;
- public EHCacheXKMSClientCache() {
+ public EHCacheXKMSClientCache() throws XKMSClientCacheException {
this(DEFAULT_CONFIG_URL, null);
}
- public EHCacheXKMSClientCache(Bus cxfBus) {
+ public EHCacheXKMSClientCache(Bus cxfBus) throws XKMSClientCacheException {
this(DEFAULT_CONFIG_URL, cxfBus);
}
- public EHCacheXKMSClientCache(String configFileURL) {
+ public EHCacheXKMSClientCache(String configFileURL) throws XKMSClientCacheException {
this(configFileURL, null);
}
- public EHCacheXKMSClientCache(String configFileURL, Bus cxfBus) {
- createCache(configFileURL, cxfBus);
+ public EHCacheXKMSClientCache(String configFile, Bus cxfBus) throws XKMSClientCacheException {
+ if (cxfBus == null) {
+ cxfBus = BusFactory.getThreadDefaultBus(true);
+ }
this.bus = cxfBus;
if (bus != null) {
bus.getExtension(BusLifeCycleManager.class).registerLifeCycleListener(this);
}
- }
-
- private void createCache(String configFile, Bus cxfBus) {
- if (cxfBus == null) {
- cxfBus = BusFactory.getThreadDefaultBus(true);
- }
+
URL configFileURL = null;
try {
configFileURL =
@@ -80,56 +78,49 @@ public class EHCacheXKMSClientCache implements XKMSClientCache, BusLifeCycleList
// ignore
}
if (configFileURL == null) {
- cacheManager = EHCacheUtil.createCacheManager();
- } else {
- Configuration conf = ConfigurationFactory.parseConfiguration(configFileURL);
-
- if (cxfBus != null) {
- conf.setName(cxfBus.getId());
- DiskStoreConfiguration dsc = conf.getDiskStoreConfiguration();
- if (dsc != null && "java.io.tmpdir".equals(dsc.getOriginalPath())) {
- String path = conf.getDiskStoreConfiguration().getPath() + File.separator
- + cxfBus.getId();
- conf.getDiskStoreConfiguration().setPath(path);
- }
- }
-
- cacheManager = EHCacheUtil.createCacheManager(conf);
+ configFileURL = Loader.getResource(this.getClass().getClassLoader(), configFile);
}
- CacheConfiguration cc = EHCacheUtil.getCacheConfiguration(CACHE_KEY, cacheManager);
+ XmlConfiguration xmlConfig = new XmlConfiguration(configFileURL);
+
+ try {
+ CacheConfigurationBuilder<String, XKMSCacheToken> configurationBuilder =
+ xmlConfig.newCacheConfigurationBuilderFromTemplate(TEMPLATE_KEY,
+ String.class, XKMSCacheToken.class);
+
+ cacheKey = UUID.randomUUID().toString();
- Ehcache newCache = new Cache(cc);
- cache = cacheManager.addCacheIfAbsent(newCache);
+ cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache(cacheKey,
+ configurationBuilder)
+ .with(CacheManagerBuilder.persistence(new File(System.getProperty("java.io.tmpdir"), cacheKey)))
+ .build();
+
+ cacheManager.init();
+ cache = cacheManager.getCache(cacheKey, String.class, XKMSCacheToken.class);
+ } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
+ throw new XKMSClientCacheException(e);
+ }
}
/**
* Store an XKMSCacheToken in the Cache using the given key
*/
public void put(String key, XKMSCacheToken cacheToken) {
- cache.put(new Element(key, cacheToken, false));
+ cache.put(key, cacheToken);
}
/**
* Get an XKMSCacheToken from the cache matching the given key. Returns null if there
- * is no such XKMSCacheToken in the cache, or if the certificate has expired in the cache
+ * is no such XKMSCacheToken in the cache.
*/
public XKMSCacheToken get(String key) {
- Element element = cache.get(key);
- if (element != null && !element.isExpired()) {
- return (XKMSCacheToken)element.getObjectValue();
- }
- return null;
+ return cache.get(key);
}
public void close() {
- if (cacheManager != null) {
- if (cache != null) {
- cache.removeAll();
- }
- cacheManager.shutdown();
- cacheManager = null;
- cache = null;
+ if (cacheManager.getStatus() == Status.AVAILABLE) {
+ cacheManager.removeCache(cacheKey);
+ cacheManager.close();
if (bus != null) {
bus.getExtension(BusLifeCycleManager.class).unregisterLifeCycleListener(this);
diff --git a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCache.java b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/XKMSClientCacheException.java
similarity index 74%
copy from rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCache.java
copy to services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/XKMSClientCacheException.java
index 828aaa1..5ca1630 100644
--- a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/TokenReplayCache.java
+++ b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/cache/XKMSClientCacheException.java
@@ -17,18 +17,12 @@
* under the License.
*/
-package org.apache.cxf.rs.security.saml.sso;
+package org.apache.cxf.xkms.cache;
-import java.io.Closeable;
-import java.io.IOException;
+public class XKMSClientCacheException extends Exception {
-public interface TokenReplayCache<T> extends Closeable {
+ public XKMSClientCacheException(Throwable cause) {
+ super(cause);
+ }
- T getId(T id);
-
- void putId(T id);
-
- void putId(T id, long timeToLive);
-
- void close() throws IOException;
-}
\ No newline at end of file
+}
diff --git a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/crypto/provider/XkmsCryptoProvider.java b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/crypto/provider/XkmsCryptoProvider.java
index ef4e213..0ce93c9 100644
--- a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/crypto/provider/XkmsCryptoProvider.java
+++ b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/crypto/provider/XkmsCryptoProvider.java
@@ -34,6 +34,7 @@ import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.xkms.cache.EHCacheXKMSClientCache;
import org.apache.cxf.xkms.cache.XKMSCacheToken;
import org.apache.cxf.xkms.cache.XKMSClientCache;
+import org.apache.cxf.xkms.cache.XKMSClientCacheException;
import org.apache.cxf.xkms.client.XKMSInvoker;
import org.apache.cxf.xkms.crypto.CryptoProviderException;
import org.apache.cxf.xkms.handlers.Applications;
@@ -53,15 +54,16 @@ public class XkmsCryptoProvider extends CryptoBase {
private XKMSClientCache xkmsClientCache;
private boolean allowX509FromJKS = true;
- public XkmsCryptoProvider(XKMSPortType xkmsConsumer) {
+ public XkmsCryptoProvider(XKMSPortType xkmsConsumer) throws XKMSClientCacheException {
this(xkmsConsumer, null);
}
- public XkmsCryptoProvider(XKMSPortType xkmsConsumer, Crypto fallbackCrypto) {
+ public XkmsCryptoProvider(XKMSPortType xkmsConsumer, Crypto fallbackCrypto) throws XKMSClientCacheException {
this(xkmsConsumer, fallbackCrypto, new EHCacheXKMSClientCache(), true);
}
- public XkmsCryptoProvider(XKMSPortType xkmsConsumer, Crypto fallbackCrypto, boolean allowX509FromJKS) {
+ public XkmsCryptoProvider(XKMSPortType xkmsConsumer, Crypto fallbackCrypto, boolean allowX509FromJKS)
+ throws XKMSClientCacheException {
this(xkmsConsumer, fallbackCrypto, new EHCacheXKMSClientCache(), allowX509FromJKS);
}
diff --git a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/crypto/provider/XkmsCryptoProviderFactory.java b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/crypto/provider/XkmsCryptoProviderFactory.java
index 26527bb..ca90168 100644
--- a/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/crypto/provider/XkmsCryptoProviderFactory.java
+++ b/services/xkms/xkms-client/src/main/java/org/apache/cxf/xkms/crypto/provider/XkmsCryptoProviderFactory.java
@@ -23,6 +23,7 @@ import java.util.Properties;
import org.apache.cxf.message.Message;
import org.apache.cxf.rt.security.utils.SecurityUtils;
+import org.apache.cxf.xkms.cache.XKMSClientCacheException;
import org.apache.cxf.xkms.crypto.CryptoProviderException;
import org.apache.cxf.xkms.crypto.CryptoProviderFactory;
import org.apache.wss4j.common.crypto.Crypto;
@@ -47,7 +48,12 @@ public class XkmsCryptoProviderFactory implements CryptoProviderFactory {
Object crypto = SecurityUtils
.getSecurityPropertyValue(org.apache.cxf.rt.security.SecurityConstants.SIGNATURE_CRYPTO, message);
if (crypto instanceof Crypto) {
- new XkmsCryptoProvider(xkmsConsumer, (Crypto)crypto);
+ try {
+ return new XkmsCryptoProvider(xkmsConsumer, (Crypto)crypto);
+ } catch (XKMSClientCacheException e) {
+ throw new CryptoProviderException("Cannot instantiate crypto factory: "
+ + e.getMessage(), e);
+ }
}
Properties keystoreProps = CryptoProviderUtils
@@ -56,7 +62,7 @@ public class XkmsCryptoProviderFactory implements CryptoProviderFactory {
try {
Crypto defaultCrypto = CryptoFactory.getInstance(keystoreProps);
return new XkmsCryptoProvider(xkmsConsumer, defaultCrypto);
- } catch (WSSecurityException e) {
+ } catch (WSSecurityException | XKMSClientCacheException e) {
throw new CryptoProviderException("Cannot instantiate crypto factory: "
+ e.getMessage(), e);
}
@@ -64,22 +70,42 @@ public class XkmsCryptoProviderFactory implements CryptoProviderFactory {
@Override
public Crypto create() {
- return new XkmsCryptoProvider(xkmsConsumer);
+ try {
+ return new XkmsCryptoProvider(xkmsConsumer);
+ } catch (XKMSClientCacheException e) {
+ throw new CryptoProviderException("Cannot instantiate crypto factory: "
+ + e.getMessage(), e);
+ }
}
@Override
public Crypto create(Crypto fallbackCrypto) {
- return new XkmsCryptoProvider(xkmsConsumer, fallbackCrypto);
+ try {
+ return new XkmsCryptoProvider(xkmsConsumer, fallbackCrypto);
+ } catch (XKMSClientCacheException e) {
+ throw new CryptoProviderException("Cannot instantiate crypto factory: "
+ + e.getMessage(), e);
+ }
}
@Override
public Crypto create(XKMSPortType xkmsClient, Crypto fallbackCrypto) {
- return new XkmsCryptoProvider(xkmsClient, fallbackCrypto);
+ try {
+ return new XkmsCryptoProvider(xkmsClient, fallbackCrypto);
+ } catch (XKMSClientCacheException e) {
+ throw new CryptoProviderException("Cannot instantiate crypto factory: "
+ + e.getMessage(), e);
+ }
}
@Override
public Crypto create(XKMSPortType xkmsClient, Crypto fallbackCrypto, boolean allowX509FromJKS) {
- return new XkmsCryptoProvider(xkmsClient, fallbackCrypto, allowX509FromJKS);
+ try {
+ return new XkmsCryptoProvider(xkmsClient, fallbackCrypto, allowX509FromJKS);
+ } catch (XKMSClientCacheException e) {
+ throw new CryptoProviderException("Cannot instantiate crypto factory: "
+ + e.getMessage(), e);
+ }
}
@Override
@@ -92,7 +118,7 @@ public class XkmsCryptoProviderFactory implements CryptoProviderFactory {
}
Crypto defaultCrypto = CryptoFactory.getInstance(keystoreProps);
return new XkmsCryptoProvider(xkmsConsumer, defaultCrypto);
- } catch (WSSecurityException e) {
+ } catch (WSSecurityException | XKMSClientCacheException e) {
throw new CryptoProviderException("Cannot instantiate crypto factory: "
+ e.getMessage(), e);
}
diff --git a/services/xkms/xkms-client/src/main/resources/cxf-xkms-client-ehcache.xml b/services/xkms/xkms-client/src/main/resources/cxf-xkms-client-ehcache.xml
index f60e506..2206eac 100644
--- a/services/xkms/xkms-client/src/main/resources/cxf-xkms-client-ehcache.xml
+++ b/services/xkms/xkms-client/src/main/resources/cxf-xkms-client-ehcache.xml
@@ -1,5 +1,20 @@
<?xml version="1.0"?>
-<ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true" name="xkmsClientCache">
- <diskStore path="java.io.tmpdir"/>
- <defaultCache maxEntriesLocalHeap="5000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="false" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>
-</ehcache>
+<config
+ xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
+ xmlns='http://www.ehcache.org/v3'
+ xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.8.xsd">
+
+ <cache-template name="cxf.xkms.client.cache">
+ <key-type>java.lang.String</key-type>
+ <value-type>org.apache.cxf.xkms.cache.XKMSCacheToken</value-type>
+ <expiry>
+ <ttl unit="seconds">3600</ttl>
+ </expiry>
+ <resources>
+ <heap unit="entries">5000</heap>
+ <disk unit="MB" persistent="false">10</disk>
+ </resources>
+ </cache-template>
+
+</config>
+
diff --git a/services/xkms/xkms-features/src/main/resources/features.xml b/services/xkms/xkms-features/src/main/resources/features.xml
index 47e1823..481e1fd 100644
--- a/services/xkms/xkms-features/src/main/resources/features.xml
+++ b/services/xkms/xkms-features/src/main/resources/features.xml
@@ -24,7 +24,7 @@
<feature>cxf-jaxws</feature>
<feature>cxf-http</feature>
<feature>cxf-ws-security</feature>
- <bundle start-level="40" dependency="true">mvn:net.sf.ehcache/ehcache/${cxf.ehcache.version}</bundle>
+ <bundle start-level="40" dependency="true">wrap:mvn:org.ehcache/ehcache/${cxf.ehcache3.version}$overwrite=merge&Import-Package=javax.xml.bind*,*;resolution:=optional</bundle>
<bundle>mvn:${project.groupId}/cxf-services-xkms-common/${project.version}</bundle>
<bundle>mvn:${project.groupId}/cxf-services-xkms-client/${project.version}</bundle>
<configfile finalname="/etc/org.apache.cxf.xkms.client.cfg">
diff --git a/systests/rs-security/pom.xml b/systests/rs-security/pom.xml
index e91e938..27f6ca0 100644
--- a/systests/rs-security/pom.xml
+++ b/systests/rs-security/pom.xml
@@ -58,13 +58,6 @@
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-security-oauth2-saml</artifactId>
<version>${project.version}</version>
- <!-- TODO Remove when we pick up WSS4J 2.3.0-SNAPSHOT -->
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache</artifactId>
- </exclusion>
- </exclusions>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
@@ -85,13 +78,6 @@
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-security-sso-saml</artifactId>
<version>${project.version}</version>
- <!-- TODO Remove when we pick up WSS4J 2.3.0-SNAPSHOT -->
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache</artifactId>
- </exclusion>
- </exclusions>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
diff --git a/systests/ws-security/src/test/java/org/apache/cxf/systest/ws/cache/CachingTest.java b/systests/ws-security/src/test/java/org/apache/cxf/systest/ws/cache/CachingTest.java
index 21e3f14..b45c1fe 100644
--- a/systests/ws-security/src/test/java/org/apache/cxf/systest/ws/cache/CachingTest.java
+++ b/systests/ws-security/src/test/java/org/apache/cxf/systest/ws/cache/CachingTest.java
@@ -22,6 +22,7 @@ package org.apache.cxf.systest.ws.cache;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Random;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
@@ -30,12 +31,14 @@ import javax.xml.ws.Service;
import org.apache.cxf.Bus;
import org.apache.cxf.BusFactory;
import org.apache.cxf.bus.spring.SpringBusFactory;
+import org.apache.cxf.common.classloader.ClassLoaderUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.systest.ws.common.SecurityTestUtil;
import org.apache.cxf.systest.ws.common.TestParam;
import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase;
import org.apache.cxf.ws.security.SecurityConstants;
+import org.apache.cxf.ws.security.tokenstore.EHCacheTokenStore;
import org.apache.cxf.ws.security.tokenstore.TokenStore;
import org.example.contract.doubleit.DoubleItPortType;
@@ -45,7 +48,6 @@ import org.junit.runners.Parameterized.Parameters;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
@@ -88,6 +90,7 @@ public class CachingTest extends AbstractBusClientServerTestBase {
stopAllServers();
}
+ // By default, we have one cache per-proxy
@org.junit.Test
public void testSymmetric() throws Exception {
@@ -122,7 +125,6 @@ public class CachingTest extends AbstractBusClientServerTestBase {
// We expect two tokens as the identifier + SHA-1 are cached
assertEquals(2, tokenStore.getTokenIdentifiers().size());
-
// Second invocation
DoubleItPortType port2 = service.getPort(portQName, DoubleItPortType.class);
updateAddressPort(port2, test.getPort());
@@ -140,20 +142,85 @@ public class CachingTest extends AbstractBusClientServerTestBase {
);
assertNotNull(tokenStore);
- // There should now be 4 tokens as both proxies share the same TokenStore
- assertEquals(4, tokenStore.getTokenIdentifiers().size());
+ // We expect two tokens as the identifier + SHA-1 are cached
+ assertEquals(2, tokenStore.getTokenIdentifiers().size());
((java.io.Closeable)port).close();
- //port2 is still holding onto the cache, thus, this should still be 4
+ //port2 is still holding onto the cache, thus, this should still be 2
+ assertEquals(2, tokenStore.getTokenIdentifiers().size());
+ ((java.io.Closeable)port2).close();
+
+ bus.shutdown(true);
+ }
+
+ // Here we manually create a cache and share it for both proxies
+ @org.junit.Test
+ public void testSymmetricSharedCache() throws Exception {
+
+ SpringBusFactory bf = new SpringBusFactory();
+ URL busFile = CachingTest.class.getResource("client.xml");
+
+ Bus bus = bf.createBus(busFile.toString());
+ BusFactory.setDefaultBus(bus);
+ BusFactory.setThreadDefaultBus(bus);
+
+ URL wsdl = CachingTest.class.getResource("DoubleItCache.wsdl");
+ Service service = Service.create(wsdl, SERVICE_QNAME);
+ QName portQName = new QName(NAMESPACE, "DoubleItCacheSymmetricPort");
+
+ // First invocation
+ DoubleItPortType port =
+ service.getPort(portQName, DoubleItPortType.class);
+ updateAddressPort(port, test.getPort());
+
+ // Create shared cache
+ String cacheKey = SecurityConstants.TOKEN_STORE_CACHE_INSTANCE + '-' + Math.abs(new Random().nextInt());
+ TokenStore tokenStore = new EHCacheTokenStore(cacheKey, bus,
+ ClassLoaderUtils.getResource("cxf-ehcache.xml", this.getClass()));
+ Client client = ClientProxy.getClient(port);
+ client.getEndpoint().getEndpointInfo().setProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, tokenStore);
+
+ if (test.isStreaming()) {
+ SecurityTestUtil.enableStreaming(port);
+ }
+
+ assertEquals(50, port.doubleIt(25));
+
+ // We expect two tokens as the identifier + SHA-1 are cached
+ assertEquals(2, tokenStore.getTokenIdentifiers().size());
+
+ // Second invocation
+ DoubleItPortType port2 = service.getPort(portQName, DoubleItPortType.class);
+ updateAddressPort(port2, test.getPort());
+
+ client = ClientProxy.getClient(port2);
+ client.getEndpoint().getEndpointInfo().setProperty(SecurityConstants.TOKEN_STORE_CACHE_INSTANCE, tokenStore);
+
+ if (test.isStreaming()) {
+ SecurityTestUtil.enableStreaming(port2);
+ }
+
+ port2.doubleIt(35);
+
+ client = ClientProxy.getClient(port2);
+ tokenStore =
+ (TokenStore)client.getEndpoint().getEndpointInfo().getProperty(
+ SecurityConstants.TOKEN_STORE_CACHE_INSTANCE
+ );
+
+ assertNotNull(tokenStore);
+ // We expect four tokens as the identifier + SHA-1 are cached
assertEquals(4, tokenStore.getTokenIdentifiers().size());
+
+ ((java.io.Closeable)port).close();
((java.io.Closeable)port2).close();
- //port2 is now closed, this should be null
- assertNull(tokenStore.getTokenIdentifiers());
+
bus.shutdown(true);
}
+ // Here we supply custom caching configuration
@org.junit.Test
- public void testCachePerProxySymmetric() throws Exception {
+ public void testSymmetricCustom() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = CachingTest.class.getResource("client.xml");
@@ -175,7 +242,8 @@ public class CachingTest extends AbstractBusClientServerTestBase {
SecurityConstants.CACHE_IDENTIFIER, "proxy1"
);
((BindingProvider)port).getRequestContext().put(
- SecurityConstants.CACHE_CONFIG_FILE, "per-proxy-cache.xml"
+ SecurityConstants.CACHE_CONFIG_FILE,
+ ClassLoaderUtils.getResource("per-proxy-cache.xml", this.getClass())
);
if (test.isStreaming()) {
@@ -201,7 +269,8 @@ public class CachingTest extends AbstractBusClientServerTestBase {
SecurityConstants.CACHE_IDENTIFIER, "proxy2"
);
((BindingProvider)port2).getRequestContext().put(
- SecurityConstants.CACHE_CONFIG_FILE, "per-proxy-cache.xml"
+ SecurityConstants.CACHE_CONFIG_FILE,
+ ClassLoaderUtils.getResource("per-proxy-cache.xml", this.getClass())
);
if (test.isStreaming()) {
diff --git a/systests/ws-security/src/test/resources/org/apache/cxf/systest/ws/cache/per-proxy-cache.xml b/systests/ws-security/src/test/resources/org/apache/cxf/systest/ws/cache/per-proxy-cache.xml
index de11dff..dcbf079 100644
--- a/systests/ws-security/src/test/resources/org/apache/cxf/systest/ws/cache/per-proxy-cache.xml
+++ b/systests/ws-security/src/test/resources/org/apache/cxf/systest/ws/cache/per-proxy-cache.xml
@@ -1,10 +1,49 @@
<?xml version="1.0"?>
-<ehcache xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false" monitoring="autodetect" dynamicConfig="true" name="perProxyCache">
- <diskStore path="java.io.tmpdir"/>
- <defaultCache maxEntriesLocalHeap="5000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>
-
- <cache name="org.apache.cxf.ws.security.tokenstore.TokenStore-proxy1" overflowToDisk="false" maxEntriesLocalHeap="1000" timeToIdleSeconds="3600" timeToLiveSeconds="3600"/>
-
- <cache name="org.apache.cxf.ws.security.tokenstore.TokenStore-proxy2" overflowToDisk="false" maxEntriesLocalHeap="500" timeToIdleSeconds="3600" timeToLiveSeconds="3600"/>
-
-</ehcache>
+<config
+ xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
+ xmlns='http://www.ehcache.org/v3'
+ xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">
+
+ <cache-template name="wss4jCache">
+ <key-type>java.lang.String</key-type>
+ <value-type>org.apache.wss4j.common.cache.EHCacheIdentityValue</value-type>
+ <expiry>
+ <class>org.apache.wss4j.common.cache.EHCacheExpiry</class>
+ </expiry>
+ <resources>
+ <heap unit="entries">5000</heap>
+ <disk unit="MB" persistent="false">10</disk>
+ </resources>
+ </cache-template>
+
+ <!--
+ Security Tokens are not writable to Disk so use a memory only
+ cache with a bit larger maxEntriesLocalHeap. However, this
+ cache is per-endpoint so not "too large" to not consume the
+ entire heap.
+ -->
+
+ <cache-template name="org.apache.cxf.ws.security.tokenstore.TokenStore-proxy1">
+ <key-type>java.lang.String</key-type>
+ <value-type>org.apache.cxf.ws.security.tokenstore.SecurityToken</value-type>
+ <expiry>
+ <ttl unit="seconds">3600</ttl>
+ </expiry>
+ <resources>
+ <heap unit="entries">10000</heap>
+ </resources>
+ </cache-template>
+
+ <cache-template name="org.apache.cxf.ws.security.tokenstore.TokenStore-proxy2">
+ <key-type>java.lang.String</key-type>
+ <value-type>org.apache.cxf.ws.security.tokenstore.SecurityToken</value-type>
+ <expiry>
+ <ttl unit="seconds">3600</ttl>
+ </expiry>
+ <resources>
+ <heap unit="entries">10000</heap>
+ </resources>
+ </cache-template>
+
+</config>
+