Skip to content

Commit 0209325

Browse files
author
Zhen Li
committed
Fixed failing tests in the code
1 parent 3b6c3a1 commit 0209325

File tree

13 files changed

+84
-198
lines changed

13 files changed

+84
-198
lines changed

driver/src/main/java/org/neo4j/driver/internal/connector/socket/SocketClient.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ public static ByteChannel create( String host, int port, Config config, Logger l
204204
channel = new TLSSocketChannel( host, port, soChannel, logger, config.trustStrategy() );
205205
break;
206206
}
207-
case REJECTED:
207+
case NONE:
208208
{
209209
channel = new AllOrNothingChannel( soChannel );
210210
break;

driver/src/main/java/org/neo4j/driver/internal/connector/socket/TrustOnFirstUseTrustManager.java

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
* References:
4040
* http://stackoverflow.com/questions/6802421/how-to-compare-distinct-implementations-of-java-security-cert-x509certificate?answertab=votes#tab-top
4141
*/
42-
class TrustOnFirstUseTrustManager implements X509TrustManager
42+
public class TrustOnFirstUseTrustManager implements X509TrustManager
4343
{
4444
/**
4545
* A list of pairs (known_server certificate) are stored in this file.
@@ -48,7 +48,7 @@ class TrustOnFirstUseTrustManager implements X509TrustManager
4848
* Then when we try to connect to a known server again, we will authenticate the server by checking if it provides
4949
* the same certificate as the one saved in this file.
5050
*/
51-
private final File knownCerts;
51+
private final File knownHosts;
5252

5353
/** The server ip:port (in digits) of the server that we are currently connected to */
5454
private final String serverId;
@@ -57,11 +57,11 @@ class TrustOnFirstUseTrustManager implements X509TrustManager
5757
/** The known certificate we've registered for this server */
5858
private String fingerprint;
5959

60-
TrustOnFirstUseTrustManager( String host, int port, File knownCerts, Logger logger ) throws IOException
60+
TrustOnFirstUseTrustManager( String host, int port, File knownHosts, Logger logger ) throws IOException
6161
{
6262
this.logger = logger;
6363
this.serverId = host + ":" + port;
64-
this.knownCerts = knownCerts;
64+
this.knownHosts = knownHosts;
6565
load();
6666
}
6767

@@ -72,12 +72,12 @@ class TrustOnFirstUseTrustManager implements X509TrustManager
7272
*/
7373
private void load() throws IOException
7474
{
75-
if ( !knownCerts.exists() )
75+
if ( !knownHosts.exists() )
7676
{
7777
return;
7878
}
7979

80-
BufferedReader reader = new BufferedReader( new FileReader( knownCerts ) );
80+
BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) );
8181
String line;
8282
while ( (line = reader.readLine()) != null )
8383
{
@@ -96,7 +96,7 @@ private void load() throws IOException
9696
}
9797

9898
/**
99-
* Save a new (server_ip, cert) pair into knownCerts file
99+
* Save a new (server_ip, cert) pair into knownHosts file
100100
*
101101
* @param fingerprint the SHA-512 fingerprint of the host certificate
102102
*/
@@ -107,7 +107,7 @@ private void saveTrustedHost( String fingerprint ) throws IOException
107107
logger.warn( "Adding %s as known and trusted certificate for %s.", fingerprint, serverId );
108108
createKnownCertFileIfNotExists();
109109

110-
BufferedWriter writer = new BufferedWriter( new FileWriter( knownCerts, true ) );
110+
BufferedWriter writer = new BufferedWriter( new FileWriter( knownHosts, true ) );
111111
writer.write( serverId + " " + this.fingerprint );
112112
writer.newLine();
113113
writer.close();
@@ -143,7 +143,7 @@ public void checkServerTrusted( X509Certificate[] chain, String authType )
143143
throw new CertificateException( String.format(
144144
"Failed to save the server ID and the certificate received from the server to file %s.\n" +
145145
"Server ID: %s\nReceived cert:\n%s",
146-
knownCerts.getAbsolutePath(), serverId, X509CertToString( cert ) ), e );
146+
knownHosts.getAbsolutePath(), serverId, X509CertToString( cert ) ), e );
147147
}
148148
}
149149
else
@@ -157,7 +157,7 @@ public void checkServerTrusted( X509Certificate[] chain, String authType )
157157
"`%s` " +
158158
"in the file `%s`.\n" +
159159
"The old certificate saved in file is:\n%sThe New certificate received is:\n%s",
160-
serverId, serverId, knownCerts.getAbsolutePath(),
160+
serverId, serverId, knownHosts.getAbsolutePath(),
161161
X509CertToString( this.fingerprint ), X509CertToString( cert ) ) );
162162
}
163163
}
@@ -183,31 +183,42 @@ public static String fingerprint( X509Certificate cert ) throws CertificateExcep
183183

184184
private File createKnownCertFileIfNotExists() throws IOException
185185
{
186-
if ( !knownCerts.exists() )
186+
if ( !knownHosts.exists() )
187187
{
188-
File parentDir = knownCerts.getParentFile();
189-
if( parentDir != null && !parentDir.exists() )
188+
File parentDir = knownHosts.getParentFile();
189+
try
190190
{
191-
if(!parentDir.mkdirs()) {
192-
throw new IOException( "Failed to create directories for the known hosts file in " + knownCerts.getAbsolutePath() + ". This is usually " +
193-
"because you do not have write permissions to the directory. Try configuring the Neo4j driver to use a file " +
194-
"system location you do have write permissions to." );
191+
if ( parentDir != null && !parentDir.exists() )
192+
{
193+
if ( !parentDir.mkdirs() )
194+
{
195+
throw new IOException( "Failed to create directories for the known hosts file in " + knownHosts.getAbsolutePath() +
196+
". This is usually because you do not have write permissions to the directory. " +
197+
"Try configuring the Neo4j driver to use a file system location you do have write permissions to." );
198+
}
199+
}
200+
if ( !knownHosts.createNewFile() )
201+
{
202+
throw new IOException( "Failed to create a known hosts file at " + knownHosts.getAbsolutePath() +
203+
". This is usually because you do not have write permissions to the directory. " +
204+
"Try configuring the Neo4j driver to use a file system location you do have write permissions to." );
195205
}
196206
}
197-
if(!knownCerts.createNewFile()) {
198-
throw new IOException( "Failed to create a known hosts file at " + knownCerts.getAbsolutePath() + ". This is usually " +
199-
"because you do not have write permissions to the directory. Try configuring the Neo4j driver to use a file " +
200-
"system location you do have write permissions to." );
207+
catch( SecurityException e )
208+
{
209+
throw new IOException( "Failed to create known host file and/or parent directories at " + knownHosts.getAbsolutePath() +
210+
". This is usually because you do not have write permission to the directory. " +
211+
"Try configuring the Neo4j driver to use a file location you have write permissions to." );
201212
}
202-
BufferedWriter writer = new BufferedWriter( new FileWriter( knownCerts ) );
213+
BufferedWriter writer = new BufferedWriter( new FileWriter( knownHosts ) );
203214
writer.write( "# This file contains trusted certificates for Neo4j servers, it's created by Neo4j drivers." );
204215
writer.newLine();
205216
writer.write( "# You can configure the location of this file in `org.neo4j.driver.Config`" );
206217
writer.newLine();
207218
writer.close();
208219
}
209220

210-
return knownCerts;
221+
return knownHosts;
211222
}
212223

213224
/**

driver/src/main/java/org/neo4j/driver/v1/Config.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import org.neo4j.driver.internal.logging.JULogging;
2525
import org.neo4j.driver.internal.spi.Logging;
2626

27+
import static java.lang.System.getProperty;
2728
import static org.neo4j.driver.v1.Config.TrustStrategy.*;
2829

2930
/**
@@ -138,7 +139,8 @@ public static class ConfigBuilder
138139
private int connectionPoolSize = 50;
139140
private long idleTimeBeforeConnectionTest = 200;
140141
private EncryptionLevel encruptionLevel = EncryptionLevel.REQUIRED;
141-
private TrustStrategy trustStrategy = trustOnFirstUse( new File( System.getProperty( "user.home" ), ".neo4j/neo4j_known_certs" ) );
142+
private TrustStrategy trustStrategy = trustOnFirstUse(
143+
new File( getProperty( "user.home" ), ".neo4j/neo4j_known_hosts" ) );
142144

143145
private ConfigBuilder() {}
144146

@@ -246,7 +248,7 @@ public Config toConfig()
246248
public enum EncryptionLevel
247249
{
248250
/** With this level, the driver will only connect to the server if it can do it without encryption. */
249-
REJECTED,
251+
NONE,
250252

251253
/** With this level, the driver will only connect to the server it if can do it with encryption. */
252254
REQUIRED

driver/src/test/java/org/neo4j/driver/internal/ConfigTest.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,14 @@
2424

2525
import org.neo4j.driver.v1.Config;
2626

27+
import static java.lang.System.getProperty;
2728
import static org.hamcrest.CoreMatchers.equalTo;
2829
import static org.junit.Assert.assertEquals;
2930
import static org.junit.Assert.assertThat;
3031

3132
public class ConfigTest
3233
{
33-
private static final File DEFAULT_KNOWN_CERTS = new File( System.getProperty( "user.home" ), ".neo4j/neo4j_known_certs" );
34+
private static final File DEFAULT_KNOWN_HOSTS = new File( getProperty( "user.home" ), ".neo4j/neo4j_known_hosts" );
3435

3536
@Test
3637
public void shouldDefaultToKnownCerts()
@@ -43,14 +44,14 @@ public void shouldDefaultToKnownCerts()
4344

4445
// Then
4546
assertEquals( authConfig.strategy(), Config.TrustStrategy.Strategy.TRUST_ON_FIRST_USE );
46-
assertEquals( DEFAULT_KNOWN_CERTS.getAbsolutePath(), authConfig.certFile().getAbsolutePath() );
47+
assertEquals( DEFAULT_KNOWN_HOSTS.getAbsolutePath(), authConfig.certFile().getAbsolutePath() );
4748
}
4849

4950
@Test
5051
public void shouldChangeToNewKnownCerts()
5152
{
5253
// Given
53-
File knownCerts = new File( "new_known_certs" );
54+
File knownCerts = new File( "new_known_hosts" );
5455
Config config = Config.build().withTrustStrategy( Config.TrustStrategy.trustOnFirstUse( knownCerts ) ).toConfig();
5556

5657
// When
@@ -83,14 +84,14 @@ public void shouldConfigureMinIdleTime() throws Throwable
8384
Config config = Config.build().withSessionLivenessCheckTimeout( 1337 ).toConfig();
8485

8586
// then
86-
assertThat( config.idleTimeBeforeConnectionTest(), equalTo( 1337l ));
87+
assertThat( config.idleTimeBeforeConnectionTest(), equalTo( 1337l ) );
8788
}
8889

8990
public static void deleteDefaultKnownCertFileIfExists()
9091
{
91-
if( DEFAULT_KNOWN_CERTS.exists() )
92+
if( DEFAULT_KNOWN_HOSTS.exists() )
9293
{
93-
DEFAULT_KNOWN_CERTS.delete();
94+
DEFAULT_KNOWN_HOSTS.delete();
9495
}
9596
}
9697

driver/src/test/java/org/neo4j/driver/v1/integration/TLSSocketChannelIT.java

Lines changed: 19 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -18,24 +18,21 @@
1818
*/
1919
package org.neo4j.driver.v1.integration;
2020

21+
import org.junit.BeforeClass;
22+
import org.junit.Rule;
23+
import org.junit.Test;
24+
2125
import java.io.BufferedWriter;
2226
import java.io.File;
2327
import java.io.FileWriter;
2428
import java.io.IOException;
25-
import java.io.InputStream;
2629
import java.net.InetAddress;
2730
import java.net.InetSocketAddress;
2831
import java.net.URI;
2932
import java.nio.channels.SocketChannel;
3033
import java.security.cert.X509Certificate;
31-
import java.util.Scanner;
3234
import javax.net.ssl.SSLHandshakeException;
33-
import javax.xml.bind.DatatypeConverter;
3435

35-
import org.junit.Rule;
36-
import org.junit.Test;
37-
38-
import org.neo4j.driver.internal.ConfigTest;
3936
import org.neo4j.driver.internal.connector.socket.TLSSocketChannel;
4037
import org.neo4j.driver.internal.spi.Logger;
4138
import org.neo4j.driver.internal.util.CertificateTool;
@@ -44,6 +41,7 @@
4441
import org.neo4j.driver.v1.GraphDatabase;
4542
import org.neo4j.driver.v1.ResultCursor;
4643
import org.neo4j.driver.v1.util.CertificateToolTest;
44+
import org.neo4j.driver.v1.util.Neo4jInstaller;
4745
import org.neo4j.driver.v1.util.Neo4jRunner;
4846
import org.neo4j.driver.v1.util.TestNeo4j;
4947

@@ -53,16 +51,24 @@
5351
import static org.mockito.Mockito.atLeastOnce;
5452
import static org.mockito.Mockito.mock;
5553
import static org.mockito.Mockito.verify;
54+
import static org.neo4j.driver.internal.connector.socket.TrustOnFirstUseTrustManager.fingerprint;
5655

5756
public class TLSSocketChannelIT
5857
{
5958
@Rule
6059
public TestNeo4j neo4j = new TestNeo4j();
6160

61+
@BeforeClass
62+
public static void setup() throws IOException, InterruptedException
63+
{
64+
/* uncomment for JSSE debugging info */
65+
// System.setProperty( "javax.net.debug", "all" );
66+
}
67+
6268
@Test
6369
public void shouldPerformTLSHandshakeWithEmptyKnownCertsFile() throws Throwable
6470
{
65-
File knownCerts = File.createTempFile( "neo4j_known_certs", ".tmp" );
71+
File knownCerts = File.createTempFile( "neo4j_known_hosts", ".tmp" );
6672
knownCerts.deleteOnExit();
6773

6874
performTLSHandshakeUsingKnownCerts( knownCerts );
@@ -92,7 +98,7 @@ public void shouldFailTLSHandshakeDueToWrongCertInKnownCertsFile() throws Throwa
9298
// Given
9399
SocketChannel channel = SocketChannel.open();
94100
channel.connect( new InetSocketAddress( "localhost", 7687 ) );
95-
File knownCerts = File.createTempFile( "neo4j_known_certs", ".tmp" );
101+
File knownCerts = File.createTempFile( "neo4j_known_hosts", ".tmp" );
96102
knownCerts.deleteOnExit();
97103

98104
//create a Fake Cert for the server in knownCert
@@ -129,7 +135,7 @@ private void createFakeServerCertPairInKnownCerts( String host, int port, File k
129135
String serverId = ip + ":" + port;
130136

131137
X509Certificate cert = CertificateToolTest.generateSelfSignedCertificate();
132-
String certStr = DatatypeConverter.printBase64Binary( cert.getEncoded() );
138+
String certStr = fingerprint(cert);
133139

134140
BufferedWriter writer = new BufferedWriter( new FileWriter( knownCerts, true ) );
135141
writer.write( serverId + "," + certStr );
@@ -174,17 +180,15 @@ public void shouldFailTLSHandshakeDueToServerCertNotSignedByKnownCA() throws Thr
174180
@Test
175181
public void shouldPerformTLSHandshakeWithTrustedServerCert() throws Throwable
176182
{
177-
// Given
178-
TestKeys keys = testKeys();
179-
neo4j.restartServerOnEmptyDatabase( Neo4jSettings.DEFAULT.usingEncryptionKeyAndCert( keys.serverKey, keys.serverCert ) );
180183

181184
Logger logger = mock( Logger.class );
182185
SocketChannel channel = SocketChannel.open();
183186
channel.connect( new InetSocketAddress( "localhost", 7687 ) );
184187

185188
// When
186189
TLSSocketChannel sslChannel = new TLSSocketChannel( "localhost", 7687, channel, logger,
187-
Config.TrustStrategy.trustSignedBy( keys.signingCert ) );
190+
Config.TrustStrategy.trustSignedBy(
191+
new File( Neo4jInstaller.neo4jHomeDir, "conf/ssl/snakeoil.cert") ) );
188192
sslChannel.close();
189193

190194
// Then
@@ -196,7 +200,7 @@ public void shouldPerformTLSHandshakeWithTrustedServerCert() throws Throwable
196200
@Test
197201
public void shouldEstablishTLSConnection() throws Throwable
198202
{
199-
ConfigTest.deleteDefaultKnownCertFileIfExists();
203+
200204
Config config = Config.build().withEncryptionLevel( Config.EncryptionLevel.REQUIRED ).toConfig();
201205

202206
Driver driver = GraphDatabase.driver(
@@ -210,33 +214,4 @@ public void shouldEstablishTLSConnection() throws Throwable
210214

211215
driver.close();
212216
}
213-
214-
class TestKeys
215-
{
216-
final File serverKey;
217-
final File serverCert;
218-
final File signingCert;
219-
220-
TestKeys( File serverKey, File serverCert, File signingCert )
221-
{
222-
this.serverKey = serverKey;
223-
this.serverCert = serverCert;
224-
this.signingCert = signingCert;
225-
}
226-
}
227-
228-
TestKeys testKeys() throws IOException
229-
{
230-
return new TestKeys( fileFromCertResource( "server.key" ), fileFromCertResource( "server.crt" ), fileFromCertResource( "ca.crt" ) );
231-
}
232-
233-
private File fileFromCertResource( String fileName ) throws IOException
234-
{
235-
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream( "certificates/" + fileName );
236-
try ( Scanner scanner = new Scanner( resourceAsStream ).useDelimiter( "\\A" ) )
237-
{
238-
String contents = scanner.next();
239-
return new File( neo4j.putTmpFile( fileName, "", contents ).getFile() );
240-
}
241-
}
242217
}

driver/src/test/java/org/neo4j/driver/v1/util/CertificateToolTest.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,19 @@
1818
*/
1919
package org.neo4j.driver.v1.util;
2020

21-
import java.io.File;
2221
import java.io.IOException;
2322
import java.math.BigInteger;
2423
import java.security.GeneralSecurityException;
25-
import java.security.KeyPair;
2624
import java.security.KeyPairGenerator;
27-
import java.security.KeyStore;
28-
import java.security.SecureRandom;
2925
import java.security.Security;
3026
import java.security.cert.Certificate;
3127
import java.security.cert.X509Certificate;
3228
import java.util.Date;
3329
import java.util.Enumeration;
30+
import java.security.KeyPair;
31+
import java.security.KeyStore;
32+
import java.security.SecureRandom;
33+
import java.io.File;
3434

3535
import org.bouncycastle.asn1.x500.X500Name;
3636
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;

0 commit comments

Comments
 (0)