Elffuss BraidHub

kikocis/java-driver public

Merge pull request #295 from tolbertam/sslTests

Add Integration Tests for validating SSL connectivity & authentication.
Changeseta9f1d098ef3cc3b277b23ca83a9a40e256e5bb0adf9728bbced67fc6fa6f7aa2
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-03-16 14:56 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-03-16 14:56 +01:00
Parents1a137538a085, aac33c624741

Browse the files at this changeset

8 files changed

modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +93 −9
@@ -21,16 +21,14 @@
2121 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2222
2323 import com.google.common.base.Joiner;
24-import com.google.common.io.Files;
24+import com.google.common.collect.ImmutableMap;
25+import com.google.common.io.*;
2526 import org.slf4j.Logger;
2627 import org.slf4j.LoggerFactory;
2728 import org.testng.annotations.AfterClass;
2829 import org.testng.annotations.BeforeClass;
2930
30-import java.io.BufferedReader;
31-import java.io.File;
32-import java.io.IOException;
33-import java.io.InputStreamReader;
31+import java.io.*;
3432 import java.net.InetAddress;
3533 import java.net.InetSocketAddress;
3634 import java.net.Socket;
@@ -54,6 +52,22 @@
5452
5553 private static final String CASSANDRA_VERSION_REGEXP = "\\d\\.\\d\\.\\d+(-\\w+)?";
5654
55+ public static final String DEFAULT_CLIENT_TRUSTSTORE_PASSWORD = "cassandra1sfun";
56+ public static final String DEFAULT_CLIENT_TRUSTSTORE_PATH = "/client.truststore";
57+
58+ public static final String DEFAULT_CLIENT_KEYSTORE_PASSWORD = "cassandra1sfun";
59+ public static final String DEFAULT_CLIENT_KEYSTORE_PATH = "/client.keystore";
60+
61+ public static final String DEFAULT_SERVER_TRUSTSTORE_PASSWORD = "cassandra1sfun";
62+ public static final String DEFAULT_SERVER_TRUSTSTORE_PATH = "/server.truststore";
63+
64+ private static final File DEFAULT_SERVER_TRUSTSTORE_FILE = createTempStore(DEFAULT_SERVER_TRUSTSTORE_PATH);
65+
66+ public static final String DEFAULT_SERVER_KEYSTORE_PASSWORD = "cassandra1sfun";
67+ public static final String DEFAULT_SERVER_KEYSTORE_PATH = "/server.keystore";
68+
69+ private static final File DEFAULT_SERVER_KEYSTORE_FILE = createTempStore(DEFAULT_SERVER_KEYSTORE_PATH);
70+
5771 static final File CASSANDRA_DIR;
5872 static final String CASSANDRA_VERSION;
5973 static {
@@ -81,12 +95,47 @@
8195 this.ccmDir = Files.createTempDir();
8296 }
8397
84- public static CCMBridge create(String name) {
98+ /**
99+ * <p>
100+ * Extracts a keystore from the classpath into a temporary file.
101+ * </p>
102+ *
103+ * <p>
104+ * This is needed as the keystore could be part of a built test jar used by other
105+ * projects, and they need to be extracted to a file system so cassandra may use them.
106+ * </p>
107+ * @param storePath Path in classpath where the keystore exists.
108+ * @return The generated File.
109+ */
110+ private static File createTempStore(String storePath) {
111+ File f = null;
112+ Closer closer = Closer.create();
113+ try {
114+ InputStream trustStoreIs = CCMBridge.class.getResourceAsStream(storePath);
115+ closer.register(trustStoreIs);
116+ f = File.createTempFile("server", ".store");
117+ logger.debug("Created store file {} for {}.", f, storePath);
118+ OutputStream trustStoreOs = new FileOutputStream(f);
119+ closer.register(trustStoreOs);
120+ ByteStreams.copy(trustStoreIs, trustStoreOs);
121+ } catch(IOException e) {
122+ logger.warn("Failure to write keystore, SSL-enabled servers may fail to start.", e);
123+ } finally {
124+ try {
125+ closer.close();
126+ } catch (IOException e) {
127+ logger.warn("Failure closing streams.", e);
128+ }
129+ }
130+ return f;
131+ }
132+
133+ public static CCMBridge create(String name, String... options) {
85134 // This leads to a confusing CCM error message so check explicitly:
86135 checkArgument(!"current".equals(name.toLowerCase()),
87- "cluster can't be called \"current\"");
136+ "cluster can't be called \"current\"");
88137 CCMBridge bridge = new CCMBridge();
89- bridge.execute("ccm create %s -b -i %s %s", name, IP_PREFIX, CASSANDRA_VERSION);
138+ bridge.execute("ccm create %s -b -i %s %s " + Joiner.on(" ").join(options), name, IP_PREFIX, CASSANDRA_VERSION);
90139 return bridge;
91140 }
92141
@@ -189,7 +238,15 @@
189238 }
190239
191240 public void updateConfig(String name, String value) {
192- execute("ccm updateconf %s:%s", name, value);
241+ updateConfig(ImmutableMap.of(name, value));
242+ }
243+
244+ public void updateConfig(Map<String, String> configs) {
245+ StringBuilder confStr = new StringBuilder();
246+ for(Map.Entry<String,String> entry : configs.entrySet()) {
247+ confStr.append(entry.getKey() + ":" + entry.getValue() + " ");
248+ }
249+ execute("ccm updateconf " + confStr);
193250 }
194251
195252 public void populate(int n) {
@@ -270,6 +327,33 @@
270327 }
271328 }
272329
330+ /**
331+ * Enables SSL without client authentication. Does not apply to already started nodes.
332+ */
333+ public void enableSSL() {
334+ enableSSL(false);
335+ }
336+
337+ /**
338+ * Enables SSL. Does not apply to already started nodes.
339+ * @param requireClientAuth Whether or not to require Clients used authentication.
340+ */
341+ public void enableSSL(boolean requireClientAuth) {
342+ ImmutableMap.Builder<String,String> configs = ImmutableMap.builder();
343+
344+ configs.put("client_encryption_options.enabled", "true");
345+ configs.put("client_encryption_options.keystore", DEFAULT_SERVER_KEYSTORE_FILE.getAbsolutePath());
346+ configs.put("client_encryption_options.keystore_password", DEFAULT_SERVER_KEYSTORE_PASSWORD);
347+
348+ if(requireClientAuth) {
349+ configs.put("client_encryption_options.require_client_auth", "true");
350+ configs.put("client_encryption_options.truststore", DEFAULT_SERVER_TRUSTSTORE_FILE.getAbsolutePath());
351+ configs.put("client_encryption_options.truststore_password", DEFAULT_SERVER_TRUSTSTORE_PASSWORD);
352+ }
353+
354+ updateConfig(configs.build());
355+ }
356+
273357 private static void busyWaitForPort(InetAddress address, int port, boolean expectedConnectionState) {
274358 long maxAcceptableWaitTime = TimeUnit.SECONDS.toMillis(10);
275359 long waitQuantum = TimeUnit.MILLISECONDS.toMillis(500);
added driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +47 −0
@@ -0,0 +1,47 @@
1+package com.datastax.driver.core;
2+
3+import com.google.common.base.Optional;
4+import org.testng.annotations.Test;
5+
6+import com.datastax.driver.core.exceptions.NoHostAvailableException;
7+
8+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH;
9+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH;
10+
11+public class SSLAuthenticatedEncryptionTest extends SSLTestBase {
12+
13+ public SSLAuthenticatedEncryptionTest() {
14+ super(true);
15+ }
16+
17+ /**
18+ * <p>
19+ * Validates that an SSL connection can be established with client auth if the target
20+ * cassandra cluster is using SSL, requires client auth and would validate with the client's
21+ * certificate.
22+ * </p>
23+ *
24+ * @test_category connection:ssl, authentication
25+ * @expected_result Connection can be established to a cassandra node using SSL that requires client auth.
26+ */
27+ @Test(groups="short")
28+ public void should_connect_with_ssl_with_client_auth_and_node_requires_auth() throws Exception {
29+ connectWithSSLOptions(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
30+ }
31+
32+
33+ /**
34+ * <p>
35+ * Validates that an SSL connection can not be established with if the target
36+ * cassandra cluster is using SSL, requires client auth, but the client does not provide
37+ * sufficient certificate authentication.
38+ * </p>
39+ *
40+ * @test_category connection:ssl, authentication
41+ * @expected_result Connection is not established.
42+ */
43+ @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
44+ public void should_not_connect_without_client_auth_but_node_requires_auth() throws Exception {
45+ connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
46+ }
47+}
added driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +106 −0
@@ -0,0 +1,106 @@
1+package com.datastax.driver.core;
2+
3+import java.util.concurrent.TimeUnit;
4+
5+import com.google.common.base.Optional;
6+import org.testng.annotations.Test;
7+
8+import com.datastax.driver.core.exceptions.NoHostAvailableException;
9+
10+import static com.datastax.driver.core.Assertions.assertThat;
11+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH;
12+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH;
13+
14+public class SSLEncryptionTest extends SSLTestBase {
15+
16+ public SSLEncryptionTest() {
17+ super(false);
18+ }
19+
20+ /**
21+ * <p>
22+ * Validates that an SSL connection can be established without client auth if the target
23+ * cassandra cluster is using SSL and does not require auth.
24+ * </p>
25+ *
26+ * @test_category connection:ssl
27+ * @expected_result Connection can be established to a cassandra node using SSL.
28+ */
29+ @Test(groups="short")
30+ public void should_connect_with_ssl_without_client_auth_and_node_doesnt_require_auth() throws Exception {
31+ connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
32+ }
33+
34+ /**
35+ * <p>
36+ * Validates that an SSL connection can not be established if the client does not trust
37+ * the cassandra node's certificate.
38+ * </p>
39+ *
40+ * @test_category connection:ssl
41+ * @expected_result Connection can not be established to a cassandra node using SSL with an untrusted cert.
42+ */
43+ @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
44+ public void should_not_connect_with_ssl_without_trusting_server_cert() throws Exception {
45+ connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.<String>absent()));
46+ }
47+
48+ /**
49+ * <p>
50+ * Validates that an SSL connection can not be established if the client is not specifying SSL, but
51+ * the cassandra node is using SSL.
52+ * </p>
53+ *
54+ * <p>
55+ * Note that future versions of cassandra may support both SSL-encrypted and non-SSL connections
56+ * simultaneously (CASSANDRA-8803)
57+ * </p>
58+ *
59+ * @test_category connection:ssl
60+ * @expected_result Connection can not be established to a cassandra node using SSL and the client not using SSL.
61+ */
62+ @Test(groups="short", expectedExceptions={NoHostAvailableException.class})
63+ public void should_not_connect_without_ssl_but_node_uses_ssl() throws Exception {
64+ Cluster cluster = null;
65+ try {
66+ cluster = Cluster.builder()
67+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
68+ .build();
69+
70+ cluster.connect();
71+ } finally {
72+ if (cluster != null)
73+ cluster.close();
74+ }
75+ }
76+
77+ /**
78+ * <p>
79+ * Validates that if connection is lost to a node that is using SSL authentication, that connection can be
80+ * re-established when the node becomes available again.
81+ * </p>
82+ *
83+ * @test_category connection:ssl
84+ * @expected_result Connection is re-established within a sufficient amount of time after a node comes back online.
85+ */
86+ @Test(groups="long")
87+ public void should_reconnect_with_ssl_on_node_up() throws Exception {
88+ Cluster cluster = null;
89+ try {
90+ cluster = Cluster.builder()
91+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
92+ .withSSL(getSSLOptions(Optional.of(DEFAULT_CLIENT_KEYSTORE_PATH), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)))
93+ .build();
94+
95+ cluster.connect();
96+
97+ ccm.stop(1);
98+ ccm.start(1);
99+
100+ assertThat(cluster).host(1).comesUpWithin(TestUtils.TEST_BASE_NODE_WAIT, TimeUnit.SECONDS);
101+ } finally {
102+ if (cluster != null)
103+ cluster.close();
104+ }
105+ }
106+}
added driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +100 −0
@@ -0,0 +1,100 @@
1+package com.datastax.driver.core;
2+
3+import java.security.KeyStore;
4+import java.security.SecureRandom;
5+import java.util.concurrent.TimeUnit;
6+
7+import com.google.common.base.Optional;
8+import javax.net.ssl.KeyManagerFactory;
9+import javax.net.ssl.SSLContext;
10+import javax.net.ssl.TrustManagerFactory;
11+import org.testng.annotations.AfterClass;
12+import org.testng.annotations.BeforeClass;
13+import org.testng.annotations.Test;
14+
15+import com.datastax.driver.core.exceptions.NoHostAvailableException;
16+
17+import static com.datastax.driver.core.Assertions.assertThat;
18+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD;
19+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH;
20+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD;
21+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH;
22+public abstract class SSLTestBase {
23+
24+ private final boolean requireClientAuth;
25+
26+ protected CCMBridge ccm;
27+
28+ public SSLTestBase(boolean requireClientAuth) {
29+ this.requireClientAuth = requireClientAuth;
30+ }
31+
32+ @BeforeClass(groups={"short", "long"})
33+ public void beforeClass() {
34+ ccm = CCMBridge.create("test");
35+ ccm.enableSSL(requireClientAuth);
36+ ccm.bootstrapNode(1);
37+ }
38+
39+ @AfterClass(groups={"short", "long"})
40+ public void afterClass() {
41+ ccm.remove();
42+ }
43+
44+ /**
45+ * <p>
46+ * Attempts to connect to a cassandra cluster with the given SSLOptions and then closes the
47+ * created {@link Cluster} instance.
48+ * </p>
49+ *
50+ * @param sslOptions SSLOptions to use.
51+ * @throws Exception A {@link com.datastax.driver.core.exceptions.NoHostAvailableException} will be
52+ * raised here if connection cannot be established.
53+ */
54+ protected void connectWithSSLOptions(SSLOptions sslOptions) throws Exception {
55+ Cluster cluster = null;
56+ try {
57+ cluster = Cluster.builder()
58+ .addContactPoint(CCMBridge.IP_PREFIX + '1')
59+ .withSSL(sslOptions)
60+ .build();
61+
62+ cluster.connect();
63+ } finally {
64+ if (cluster != null)
65+ cluster.close();
66+ }
67+ }
68+
69+ /**
70+ * @param keyStorePath Path to keystore, if absent is not used.
71+ * @param trustStorePath Path to truststore, if absent is not used.
72+ * @return {@link com.datastax.driver.core.SSLOptions} with the given keystore and truststore path's for
73+ * server certificate validation and client certificate authentication.
74+ */
75+ public SSLOptions getSSLOptions(Optional<String> keyStorePath, Optional<String> trustStorePath) throws Exception {
76+
77+ TrustManagerFactory tmf = null;
78+ if(trustStorePath.isPresent()) {
79+ KeyStore ks = KeyStore.getInstance("JKS");
80+ ks.load(this.getClass().getResourceAsStream(trustStorePath.get()), DEFAULT_CLIENT_TRUSTSTORE_PASSWORD.toCharArray());
81+
82+ tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
83+ tmf.init(ks);
84+ }
85+
86+ KeyManagerFactory kmf = null;
87+ if(keyStorePath.isPresent()) {
88+ KeyStore ks = KeyStore.getInstance("JKS");
89+ ks.load(this.getClass().getResourceAsStream(keyStorePath.get()), DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
90+
91+ kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
92+ kmf.init(ks, DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
93+ }
94+
95+ SSLContext sslContext = SSLContext.getInstance("TLS");
96+ sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null, new SecureRandom());
97+
98+ return new SSLOptions(sslContext, SSLOptions.DEFAULT_SSL_CIPHER_SUITES);
99+ }
100+}
added driver-core/src/test/resources/client.keystore +0 −0

Binary content is not shown. View the file.

added driver-core/src/test/resources/client.truststore +0 −0

Binary content is not shown. View the file.

added driver-core/src/test/resources/server.keystore +0 −0

Binary content is not shown. View the file.

added driver-core/src/test/resources/server.truststore +0 −0

Binary content is not shown. View the file.