Search in sources :

Example 21 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class ResultSetRegressionTest method tstBug24525461assertResults1.

private void tstBug24525461assertResults1(boolean testJSON, Statement st) throws Exception {
    String fAsText = versionMeetsMinimum(5, 6, 1) ? "ST_AsText" : "AsText";
    Properties props = new Properties();
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.name());
    props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
    props.setProperty(PropertyKey.connectionTimeZone.getKeyName(), "LOCAL");
    Connection testConn = getConnectionWithProps(props);
    TimeZone serverTz = ((MysqlConnection) testConn).getSession().getServerSession().getSessionTimeZone();
    ZonedDateTime expZdt = LocalDateTime.of(2000, 1, 1, 0, 0).atZone(serverTz.toZoneId()).withZoneSameInstant(ZoneId.systemDefault());
    String expTimestamp = expZdt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));
    ResultSet rs2 = st.executeQuery("SELECT *, " + fAsText + "(f30), " + fAsText + "(f31) FROM testBug24525461");
    assertTrue(rs2.next());
    assertEquals(0, rs2.getInt(1));
    assertEquals(BigDecimal.valueOf(10), rs2.getBigDecimal(2));
    assertEquals(1, rs2.getInt(3));
    assertTrue(rs2.getBoolean(4));
    assertEquals(1, rs2.getInt(5));
    assertEquals(1, rs2.getInt(6));
    assertEquals(Float.valueOf(1), rs2.getFloat(7));
    assertEquals(Double.valueOf(1), rs2.getDouble(8));
    assertEquals(expTimestamp, rs2.getTimestamp(9).toString());
    assertEquals(BigDecimal.valueOf(1), rs2.getBigDecimal(10));
    assertEquals(1, rs2.getInt(11));
    assertEquals("2000-01-01", rs2.getDate(12).toString());
    assertEquals("12:00:00", rs2.getTime(13).toString());
    assertEquals("2000-01-01 00:00:00.0", rs2.getTimestamp(14).toString());
    assertEquals("2000-01-01", rs2.getDate(15).toString());
    assertEquals("aaa", rs2.getString(16));
    Blob blob = rs2.getBlob(17);
    assertTrue(Arrays.equals(new byte[] { 49 }, blob.getBytes(1, (int) blob.length())));
    assertEquals(1, rs2.getInt(18));
    assertEquals("x", rs2.getString(19));
    assertEquals("a", rs2.getString(20));
    blob = rs2.getBlob(21);
    assertTrue(Arrays.equals(new byte[] { 49 }, blob.getBytes(1, (int) blob.length())));
    assertEquals("1", rs2.getString(22));
    blob = rs2.getBlob(23);
    assertTrue(Arrays.equals(new byte[] { 49 }, blob.getBytes(1, (int) blob.length())));
    assertEquals("1", rs2.getString(24));
    blob = rs2.getBlob(25);
    assertTrue(Arrays.equals(new byte[] { 49 }, blob.getBytes(1, (int) blob.length())));
    assertEquals("1", rs2.getString(26));
    blob = rs2.getBlob(27);
    assertTrue(Arrays.equals(new byte[] { 49 }, blob.getBytes(1, (int) blob.length())));
    assertEquals("1", rs2.getString(28));
    assertEquals("1", rs2.getString(29));
    blob = rs2.getBlob(30);
    assertTrue(Arrays.equals(new byte[] { 49 }, blob.getBytes(1, (int) blob.length())));
    assertEquals("aaa", rs2.getString(33));
    assertEquals("aaa", rs2.getString(34));
    assertEquals("aaa", rs2.getString(35));
    assertEquals("aaa", rs2.getString(36));
    blob = rs2.getBlob(37);
    assertTrue(Arrays.equals(new byte[] { 49 }, blob.getBytes(1, (int) blob.length())));
    blob = rs2.getBlob(38);
    assertTrue(Arrays.equals(new byte[] { 49 }, blob.getBytes(1, (int) blob.length())));
    assertEquals("aaa", rs2.getString(39));
    assertEquals("aaa", rs2.getString(40));
    assertEquals("aaa", rs2.getString(41));
    assertEquals("aaa", rs2.getString(42));
    assertEquals("aaa", rs2.getString(43));
    assertEquals("1", rs2.getString(44));
    SQLXML xml = rs2.getSQLXML(45);
    assertEquals(null, xml.getString());
    if (testJSON) {
        assertEquals("{\"key1\": \"value1\"}", rs2.getString(46));
        assertEquals("POINT(1 1)", rs2.getString(47));
        assertEquals("POINT(2 2)", rs2.getString(48));
    } else {
        assertEquals("POINT(1 1)", rs2.getString(46));
        assertEquals("POINT(2 2)", rs2.getString(47));
    }
    assertFalse(rs2.next());
}
Also used : TimeZone(java.util.TimeZone) Blob(java.sql.Blob) SQLXML(java.sql.SQLXML) MysqlSQLXML(com.mysql.cj.jdbc.MysqlSQLXML) ZonedDateTime(java.time.ZonedDateTime) Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) ResultSet(java.sql.ResultSet) UpdatableResultSet(com.mysql.cj.jdbc.result.UpdatableResultSet) MysqlConnection(com.mysql.cj.MysqlConnection) Properties(java.util.Properties)

Example 22 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class ResultSetRegressionTest method testBug94457.

/**
 * Tests fix for BUG#94457 (29402209), CONNECTOR/J RESULTSET.GETOBJECT( ..., OFFSETDATETIME.CLASS ) THROWS.
 *
 * @throws Exception
 *             if the test fails
 */
@Test
public void testBug94457() throws Exception {
    // fractional seconds are not supported in previous versions
    boolean withFract = versionMeetsMinimum(5, 6, 4);
    createTable("testBug94457", withFract ? "(dt DATETIME(4) NOT NULL, ts TIMESTAMP(4) NOT NULL, t TIME(4) NOT NULL, odt VARCHAR(30), ot VARCHAR(20))" : "(dt DATETIME NOT NULL, ts TIMESTAMP NOT NULL, t TIME NOT NULL, odt VARCHAR(30), ot VARCHAR(20))");
    Properties props = new Properties();
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.name());
    props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
    props.setProperty(PropertyKey.cacheDefaultTimeZone.getKeyName(), "false");
    for (boolean preserveInstants : new boolean[] { false, true }) {
        props.setProperty(PropertyKey.connectionTimeZone.getKeyName(), "SERVER");
        props.setProperty(PropertyKey.preserveInstants.getKeyName(), "" + preserveInstants);
        Connection c1 = getConnectionWithProps(props);
        TimeZone serverTz = ((MysqlConnection) c1).getSession().getServerSession().getSessionTimeZone();
        Statement st1 = c1.createStatement();
        st1.execute("INSERT INTO testBug94457 VALUES( NOW(4), NOW(4), NOW(4), '2019-01-20T12:00:00.12+06:00', '12:00:00.123+06:00' )");
        this.rs = st1.executeQuery("SELECT CONCAT('',dt) as origDate, dt, ts, CONCAT('',t) as origTime, t, odt, ot FROM testBug94457");
        this.rs.next();
        String origDate = this.rs.getString("origDate");
        String origTime = this.rs.getString("origTime");
        System.out.println("Original date string                 : " + origDate + " (" + serverTz + ")");
        System.out.println("getString(dt)                        : " + this.rs.getString("dt"));
        System.out.println("getString(ts)                        : " + this.rs.getString("ts"));
        System.out.println("Original time string                 : " + origTime + " (" + serverTz + ")");
        System.out.println("getString(t)                         : " + this.rs.getString("t"));
        assertEquals(this.rs.getString("origDate"), this.rs.getString("dt"));
        assertEquals(this.rs.getString("origDate"), this.rs.getString("ts"));
        assertEquals(this.rs.getString("origTime"), this.rs.getString("t"));
        Timestamp ts1 = this.rs.getTimestamp("dt");
        Timestamp ts2 = this.rs.getTimestamp("dt", Calendar.getInstance(preserveInstants ? serverTz : TimeZone.getDefault()));
        Timestamp ts3 = this.rs.getTimestamp("ts");
        Timestamp ts4 = this.rs.getTimestamp("ts", Calendar.getInstance(preserveInstants ? serverTz : TimeZone.getDefault()));
        ts1.setNanos(0);
        ts2.setNanos(0);
        ts3.setNanos(0);
        ts4.setNanos(0);
        System.out.println("getTimestamp(dt))                    : " + ts1 + " (" + ts1.getTime() + ")");
        System.out.println("getTimestamp(dt, GMT+10))            : " + ts2 + " (" + ts2.getTime() + ")");
        System.out.println("getTimestamp(ts))                    : " + ts3 + " (" + ts3.getTime() + ")");
        System.out.println("getTimestamp(ts, GMT+10))            : " + ts4 + " (" + ts4.getTime() + ")");
        assertEquals(ts1, ts2);
        assertEquals(ts3, ts4);
        assertEquals(ts1, ts4);
        Time t1 = this.rs.getTime("t");
        Time t2 = this.rs.getTime("t", Calendar.getInstance(TimeZone.getDefault()));
        System.out.println("getTime(t))                          : " + t1 + " (" + t1.getTime() + ")");
        System.out.println("getTime(t, GMT+10))                  : " + t2 + " (" + t2.getTime() + ")");
        assertEquals(t1, t2);
        Calendar cal1 = Calendar.getInstance(preserveInstants ? serverTz : TimeZone.getDefault());
        cal1.set(Integer.valueOf(origDate.substring(0, 4)), Integer.valueOf(origDate.substring(5, 7)) - 1, Integer.valueOf(origDate.substring(8, 10)), Integer.valueOf(origDate.substring(11, 13)), Integer.valueOf(origDate.substring(14, 16)), Integer.valueOf(origDate.substring(17, 19)));
        Timestamp ts = new Timestamp(cal1.getTimeInMillis());
        ts.setNanos(0);
        System.out.println("Manually constructed Timestamp       : " + ts + " (" + ts.getTime() + ")");
        assertEquals(ts1, ts);
        Calendar cal2 = Calendar.getInstance(TimeZone.getDefault());
        cal2.set(1970, 0, 1, Integer.valueOf(origTime.substring(0, 2)), Integer.valueOf(origTime.substring(3, 5)), Integer.valueOf(origTime.substring(6, 8)));
        cal2.set(Calendar.MILLISECOND, 0);
        int millis = 0;
        if (withFract) {
            StringBuilder millisStr = new StringBuilder("1" + origTime.substring(9));
            for (int i = millisStr.length(); i < 10; i++) {
                millisStr.append('0');
            }
            millis = (int) (Long.valueOf(millisStr.toString()) / 1000000) - 1000;
        }
        Time t3 = new Time(cal2.getTimeInMillis() + millis);
        System.out.println("Manually constructed Time            : " + t3 + " (" + t3.getTime() + ")");
        assertEquals(t1, t3);
        OffsetDateTime odt1 = this.rs.getObject("dt", OffsetDateTime.class);
        OffsetDateTime odt2 = this.rs.getObject("ts", OffsetDateTime.class);
        OffsetDateTime odt3 = this.rs.getObject("odt", OffsetDateTime.class);
        System.out.println("getObject(dt, OffsetDateTime.class)  : " + odt1 + " (" + odt1.toEpochSecond() + ")");
        System.out.println("getObject(ts, OffsetDateTime.class)  : " + odt2 + " (" + odt2.toEpochSecond() + ")");
        System.out.println("getObject(odt, OffsetDateTime.class) : " + odt3 + " (" + odt3.toEpochSecond() + ")");
        int localOffset = TimeZone.getDefault().getRawOffset() / 1000;
        int serverOffset = serverTz.getRawOffset() / 1000;
        int expOffset = 6 * 60 * 60;
        assertEquals(preserveInstants ? serverOffset : localOffset, odt1.getOffset().getTotalSeconds());
        assertEquals(preserveInstants ? serverOffset : localOffset, odt2.getOffset().getTotalSeconds());
        assertEquals(expOffset, odt3.getOffset().getTotalSeconds());
        assertEquals(ts1.getTime(), odt1.toEpochSecond() * 1000);
        assertEquals(ts1.getTime(), odt2.toEpochSecond() * 1000);
        assertEquals(LocalDate.of(2019, 1, 20), odt3.toLocalDate());
        ZonedDateTime zdt1 = this.rs.getObject("dt", ZonedDateTime.class);
        ZonedDateTime zdt2 = this.rs.getObject("ts", ZonedDateTime.class);
        System.out.println("getObject(dt, ZonedDateTime.class)   : " + odt1 + " (" + zdt1.toEpochSecond() + ")");
        System.out.println("getObject(ts, ZonedDateTime.class)   : " + odt2 + " (" + zdt2.toEpochSecond() + ")");
        assertEquals(preserveInstants ? serverOffset : localOffset, zdt1.getOffset().getTotalSeconds());
        assertEquals(preserveInstants ? serverOffset : localOffset, zdt2.getOffset().getTotalSeconds());
        assertEquals(ts1.getTime(), zdt1.toEpochSecond() * 1000);
        assertEquals(ts1.getTime(), zdt2.toEpochSecond() * 1000);
        OffsetTime ot1 = this.rs.getObject("ot", OffsetTime.class);
        System.out.println("getObject(ot, OffsetTime.class)      : " + ot1);
        assertEquals(expOffset, ot1.getOffset().getTotalSeconds());
        assertEquals(LocalTime.of(12, 0, 0, 123000000), ot1.toLocalTime());
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) CallableStatement(java.sql.CallableStatement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) Statement(java.sql.Statement) GregorianCalendar(java.util.GregorianCalendar) Calendar(java.util.Calendar) Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) MysqlConnection(com.mysql.cj.MysqlConnection) Time(java.sql.Time) ZonedDateTime(java.time.ZonedDateTime) LocalTime(java.time.LocalTime) OffsetTime(java.time.OffsetTime) OffsetDateTime(java.time.OffsetDateTime) LocalDateTime(java.time.LocalDateTime) Properties(java.util.Properties) Timestamp(java.sql.Timestamp) TimeZone(java.util.TimeZone) OffsetDateTime(java.time.OffsetDateTime) ZonedDateTime(java.time.ZonedDateTime) OffsetTime(java.time.OffsetTime) Test(org.junit.jupiter.api.Test)

Example 23 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class ConnectionTest method testEnableEscapeProcessing.

/**
 * Test the new connection property 'enableEscapeProcessing', as well as the old connection property 'processEscapeCodesForPrepStmts' and interrelation
 * between them.
 *
 * This test uses a QueryInterceptor to capture the query sent to the server and assert whether escape processing has been done in the client side or if
 * the query is sent untouched and escape processing will be done at server side, according to provided connection properties and type of Statement objects
 * in use.
 *
 * @throws Exception
 */
@Test
public void testEnableEscapeProcessing() throws Exception {
    // make sure the connection string doesn't contain 'enableEscapeProcessing'
    String testUrl = BaseTestCase.dbUrl;
    int b = testUrl.indexOf("enableEscapeProcessing");
    if (b != -1) {
        int e = testUrl.indexOf('&', b);
        if (e == -1) {
            e = testUrl.length();
            b--;
        } else {
            e++;
        }
        testUrl = testUrl.substring(0, b) + testUrl.substring(e, testUrl.length());
    }
    String query = "SELECT /* testEnableEscapeProcessing: (%d) */ {fn sin(pi()/2)}, {ts '2015-08-16 11:22:33'}, {fn ucase('this is mysql')}";
    Timestamp testTimestamp = new Timestamp(TimeUtil.getSimpleDateFormat(null, "yyyy-MM-dd HH:mm:ss", null).parse("2015-08-16 11:22:33").getTime());
    for (int tst = 0; tst < 8; tst++) {
        boolean enableEscapeProcessing = (tst & 0x1) != 0;
        boolean processEscapeCodesForPrepStmts = (tst & 0x2) != 0;
        boolean useServerPrepStmts = (tst & 0x4) != 0;
        Properties props = new Properties();
        props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.name());
        props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
        props.setProperty(PropertyKey.queryInterceptors.getKeyName(), TestEnableEscapeProcessingQueryInterceptor.class.getName());
        props.setProperty(PropertyKey.enableEscapeProcessing.getKeyName(), Boolean.toString(enableEscapeProcessing));
        props.setProperty(PropertyKey.processEscapeCodesForPrepStmts.getKeyName(), Boolean.toString(processEscapeCodesForPrepStmts));
        props.setProperty(PropertyKey.useServerPrepStmts.getKeyName(), Boolean.toString(useServerPrepStmts));
        props.setProperty(PropertyKey.connectionTimeZone.getKeyName(), "LOCAL");
        Connection testConn = getConnectionWithProps(testUrl, props);
        this.stmt = testConn.createStatement();
        this.rs = this.stmt.executeQuery(String.format(query, tst));
        String testCase = String.format("Case: %d [ %s | %s | %s ]/Statement", tst, enableEscapeProcessing ? "enEscProc" : "-", processEscapeCodesForPrepStmts ? "procEscProcPS" : "-", useServerPrepStmts ? "useSSPS" : "-");
        assertTrue(this.rs.next(), testCase);
        assertEquals(1d, this.rs.getDouble(1), testCase);
        Timestamp ts = !enableEscapeProcessing && this.rs.getMetaData().getColumnType(2) == Types.VARCHAR ? // MySQL 5.5 returns {ts '2015-08-16 11:22:33'} as a VARCHAR column, while newer servers return it as a DATETIME
        Timestamp.from(ZonedDateTime.of(2015, 8, 16, 11, 22, 33, 0, ((MysqlConnection) testConn).getSession().getServerSession().getSessionTimeZone().toZoneId()).withZoneSameInstant(ZoneId.systemDefault()).toInstant()) : testTimestamp;
        assertEquals(ts, this.rs.getTimestamp(2), testCase);
        assertEquals("THIS IS MYSQL", this.rs.getString(3), testCase);
        assertFalse(this.rs.next(), testCase);
        this.pstmt = testConn.prepareStatement(String.format(query, tst));
        this.rs = this.pstmt.executeQuery();
        ts = !processEscapeCodesForPrepStmts && this.rs.getMetaData().getColumnType(2) == Types.VARCHAR ? // MySQL 5.5 returns {ts '2015-08-16 11:22:33'} as a VARCHAR column, while newer servers return it as a DATETIME
        Timestamp.from(ZonedDateTime.of(2015, 8, 16, 11, 22, 33, 0, ((MysqlConnection) testConn).getSession().getServerSession().getSessionTimeZone().toZoneId()).withZoneSameInstant(ZoneId.systemDefault()).toInstant()) : testTimestamp;
        testCase = String.format("Case: %d [ %s | %s | %s ]/PreparedStatement", tst, enableEscapeProcessing ? "enEscProc" : "-", processEscapeCodesForPrepStmts ? "procEscProcPS" : "-", useServerPrepStmts ? "useSSPS" : "-");
        assertTrue(this.rs.next(), testCase);
        assertEquals(1d, this.rs.getDouble(1), testCase);
        assertEquals(ts, this.rs.getTimestamp(2), testCase);
        assertEquals("THIS IS MYSQL", this.rs.getString(3), testCase);
        assertFalse(this.rs.next(), testCase);
        testConn.close();
    }
}
Also used : Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) MysqlConnection(com.mysql.cj.MysqlConnection) Properties(java.util.Properties) Timestamp(java.sql.Timestamp) Savepoint(java.sql.Savepoint) Test(org.junit.jupiter.api.Test)

Example 24 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class ConnectionTest method testFallbackToSystemTrustStore.

/**
 * Tests connection property 'testFallbackToSystemTrustStore' behavior.
 *
 * @throws Exception
 */
@Test
public void testFallbackToSystemTrustStore() throws Exception {
    assumeTrue((((MysqlConnection) this.conn).getSession().getServerSession().getCapabilities().getCapabilityFlags() & NativeServerSession.CLIENT_SSL) != 0, "This test requires server with SSL support.");
    assumeTrue(supportsTLSv1_2(((MysqlConnection) this.conn).getSession().getServerSession().getServerVersion()), "This test requires server with TLSv1.2+ support.");
    assumeTrue(supportsTestCertificates(this.stmt), "This test requires the server configured with SSL certificates from ConnectorJ/src/test/config/ssl-test-certs");
    Connection testConn;
    /*
         * Valid system-wide TrustStore.
         */
    System.setProperty("javax.net.ssl.trustStore", "file:src/test/config/ssl-test-certs/ca-truststore");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");
    System.setProperty("javax.net.ssl.trustStorePassword", "password");
    // No connection-local TrustStore.
    testConn = getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=REQUIRED");
    assertSecureConnection(testConn);
    testConn.close();
    testConn = getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA");
    assertSecureConnection(testConn);
    testConn.close();
    testConn = getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,fallbackToSystemTrustStore=true");
    assertSecureConnection(testConn);
    testConn.close();
    assertThrows(CommunicationsException.class, () -> getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,fallbackToSystemTrustStore=false"));
    // Invalid connection-local TrustStore:
    testConn = getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=REQUIRED,trustCertificateKeyStoreUrl=file:src/test/config/ssl-test-certs/ca-truststore-ext," + "trustCertificateKeyStoreType=JKS,trustCertificateKeyStorePassword=password");
    assertSecureConnection(testConn);
    testConn.close();
    assertThrows(CommunicationsException.class, () -> getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,trustCertificateKeyStoreUrl=file:src/test/config/ssl-test-certs/ca-truststore-ext," + "trustCertificateKeyStoreType=JKS,trustCertificateKeyStorePassword=password"));
    assertThrows(CommunicationsException.class, () -> getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,fallbackToSystemTrustStore=true,trustCertificateKeyStoreUrl=file:src/test/config/ssl-test-certs/ca-truststore-ext," + "trustCertificateKeyStoreType=JKS,trustCertificateKeyStorePassword=password"));
    assertThrows(CommunicationsException.class, () -> getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,fallbackToSystemTrustStore=false,trustCertificateKeyStoreUrl=file:src/test/config/ssl-test-certs/ca-truststore-ext," + "trustCertificateKeyStoreType=JKS,trustCertificateKeyStorePassword=password"));
    /*
         * Invalid system-wide TrustStore.
         */
    System.setProperty("javax.net.ssl.trustStore", "file:src/test/config/ssl-test-certs/ca-truststore-ext");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");
    System.setProperty("javax.net.ssl.trustStorePassword", "password");
    // No connection-local TrustStore.
    testConn = getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=REQUIRED");
    assertSecureConnection(testConn);
    testConn.close();
    assertThrows(CommunicationsException.class, () -> getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA"));
    assertThrows(CommunicationsException.class, () -> getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,fallbackToSystemTrustStore=true"));
    assertThrows(CommunicationsException.class, () -> getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,fallbackToSystemTrustStore=false"));
    // Valid connection-local TrustStore:
    testConn = getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=REQUIRED,trustCertificateKeyStoreUrl=file:src/test/config/ssl-test-certs/ca-truststore," + "trustCertificateKeyStoreType=JKS,trustCertificateKeyStorePassword=password");
    assertSecureConnection(testConn);
    testConn.close();
    testConn = getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,trustCertificateKeyStoreUrl=file:src/test/config/ssl-test-certs/ca-truststore," + "trustCertificateKeyStoreType=JKS,trustCertificateKeyStorePassword=password");
    assertSecureConnection(testConn);
    testConn.close();
    testConn = getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,fallbackToSystemTrustStore=true,trustCertificateKeyStoreUrl=file:src/test/config/ssl-test-certs/ca-truststore," + "trustCertificateKeyStoreType=JKS,trustCertificateKeyStorePassword=password");
    assertSecureConnection(testConn);
    testConn.close();
    testConn = getConnectionWithProps(this.sslFreeBaseUrl, "sslMode=VERIFY_CA,fallbackToSystemTrustStore=false,trustCertificateKeyStoreUrl=file:src/test/config/ssl-test-certs/ca-truststore," + "trustCertificateKeyStoreType=JKS,trustCertificateKeyStorePassword=password");
    assertSecureConnection(testConn);
    testConn.close();
}
Also used : Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) MysqlConnection(com.mysql.cj.MysqlConnection) Test(org.junit.jupiter.api.Test)

Example 25 with MysqlConnection

use of com.mysql.cj.MysqlConnection in project aws-mysql-jdbc by awslabs.

the class ConnectionTest method testTLSVersionRemoval.

/**
 * Tests fix for WL#14805, Remove support for TLS 1.0 and 1.1.
 *
 * @throws Exception
 */
@Test
public void testTLSVersionRemoval() throws Exception {
    assumeTrue((((MysqlConnection) this.conn).getSession().getServerSession().getCapabilities().getCapabilityFlags() & NativeServerSession.CLIENT_SSL) != 0, "This test requires server with SSL support.");
    assumeTrue(supportsTLSv1_2(((MysqlConnection) this.conn).getSession().getServerSession().getServerVersion()), "This test requires server with TLSv1.2+ support.");
    assumeTrue(supportsTestCertificates(this.stmt), "This test requires the server configured with SSL certificates from ConnectorJ/src/test/config/ssl-test-certs");
    Connection con = null;
    Properties props = new Properties();
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.REQUIRED.name());
    props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
    // TS.FR.1_1. Create a Connection with the connection property tlsVersions=TLSv1.2. Assess that the connection is created successfully and it is using TLSv1.2.
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "TLSv1.2");
    con = getConnectionWithProps(props);
    assertTrue(((MysqlConnection) con).getSession().isSSLEstablished());
    assertSessionStatusEquals(con.createStatement(), "ssl_version", "TLSv1.2");
    con.close();
    // TS.FR.1_2. Create a Connection with the connection property enabledTLSProtocols=TLSv1.2. Assess that the connection is created successfully and it is using TLSv1.2.
    props.remove(PropertyKey.tlsVersions.getKeyName());
    props.setProperty("enabledTLSProtocols", "TLSv1.2");
    con = getConnectionWithProps(props);
    assertTrue(((MysqlConnection) con).getSession().isSSLEstablished());
    assertSessionStatusEquals(con.createStatement(), "ssl_version", "TLSv1.2");
    con.close();
    props.remove("enabledTLSProtocols");
    // TS.FR.2_1. Create a Connection with the connection property tlsCiphersuites=[valid-cipher-suite]. Assess that the connection is created successfully and it is using the cipher suite specified.
    props.setProperty(PropertyKey.tlsCiphersuites.getKeyName(), "TLS_DHE_RSA_WITH_AES_128_CBC_SHA");
    con = getConnectionWithProps(props);
    assertTrue(((MysqlConnection) con).getSession().isSSLEstablished());
    assertSessionStatusEquals(con.createStatement(), "ssl_cipher", "DHE-RSA-AES128-SHA");
    con.close();
    // TS.FR.2_2. Create a Connection with the connection property enabledSSLCipherSuites=[valid-cipher-suite] . Assess that the connection is created successfully and it is using the cipher suite specified.
    props.remove(PropertyKey.tlsCiphersuites.getKeyName());
    props.setProperty("enabledSSLCipherSuites", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA");
    con = getConnectionWithProps(props);
    assertTrue(((MysqlConnection) con).getSession().isSSLEstablished());
    assertSessionStatusEquals(con.createStatement(), "ssl_cipher", "DHE-RSA-AES128-SHA");
    con.close();
    props.remove("enabledSSLCipherSuites");
    // TS.FR.3_1. Create a Connection with the connection property tlsVersions=TLSv1. Assess that the connection fails.
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "TLSv1");
    assertThrows(SQLException.class, "TLS protocols TLSv1 and TLSv1.1 are not supported. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    // TS.FR.3_2. Create a Connection with the connection property tlsVersions=TLSv1.1. Assess that the connection fails.
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "TLSv1.1");
    assertThrows(SQLException.class, "TLS protocols TLSv1 and TLSv1.1 are not supported. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    // TS.FR.3_3. Create a Connection with the connection property enabledTLSProtocols=TLSv1. Assess that the connection fails.
    props.setProperty("enabledTLSProtocols", "TLSv1");
    assertThrows(SQLException.class, "TLS protocols TLSv1 and TLSv1.1 are not supported. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    // TS.FR.3_4. Create a Connection with the connection property enabledTLSProtocols=TLSv1.1. Assess that the connection fails.
    props.setProperty("enabledTLSProtocols", "TLSv1.1");
    assertThrows(SQLException.class, "TLS protocols TLSv1 and TLSv1.1 are not supported. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    props.remove("enabledTLSProtocols");
    // TS.FR.4. Create a Connection with the connection property tlsVersions=TLSv1 and sslMode=DISABLED. Assess that the connection is created successfully and it is not using encryption.
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "TLSv1");
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.name());
    con = getConnectionWithProps(props);
    assertFalse(((MysqlConnection) con).getSession().isSSLEstablished());
    con.close();
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.REQUIRED.name());
    // TS.FR.5_1. Create a Connection with the connection property tlsVersions=FOO,BAR.
    // Assess that the connection fails with the error message "Specified list of TLS versions only contains non valid TLS protocols. Accepted values are TLSv1.2 and TLSv1.3."
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "FOO,BAR");
    assertThrows(SQLException.class, "Specified list of TLS versions only contains non valid TLS protocols. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "FOO,,,BAR");
    assertThrows(SQLException.class, "Specified list of TLS versions only contains non valid TLS protocols. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    // TS.FR.5_2. Create a Connection with the connection property tlsVersions=FOO,TLSv1.1.
    // Assess that the connection fails with the error message "TLS protocols TLSv1 and TLSv1.1 are not supported. Accepted values are TLSv1.2 and TLSv1.3."
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "FOO,TLSv1.1");
    assertThrows(SQLException.class, "TLS protocols TLSv1 and TLSv1.1 are not supported. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    // TS.FR.5_3. Create a Connection with the connection property tlsVersions=TLSv1,TLSv1.1.
    // Assess that the connection fails with the error message "TLS protocols TLSv1 and TLSv1.1 are not supported. Accepted values are TLSv1.2 and TLSv1.3."
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "TLSv1,TLSv1.1");
    assertThrows(SQLException.class, "TLS protocols TLSv1 and TLSv1.1 are not supported. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    // TS.FR.6. Create a Connection with the connection property tlsVersions= (empty value).
    // Assess that the connection fails with the error message "Specified list of TLS versions is empty. Accepted values are TLSv1.2 and TLSv13."
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "");
    assertThrows(SQLException.class, "Specified list of TLS versions is empty. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "   ");
    assertThrows(SQLException.class, "Specified list of TLS versions is empty. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), ",,,");
    assertThrows(SQLException.class, "Specified list of TLS versions is empty. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), ",  ,,");
    assertThrows(SQLException.class, "Specified list of TLS versions is empty. Accepted values are TLSv1.2 and TLSv1.3.+", () -> getConnectionWithProps(props));
    // TS.FR.7. Create a Connection with the connection property tlsVersions=FOO,TLSv1,TLSv1.1,TLSv1.2.
    // Assess that the connection is created successfully and it is using TLSv1.2.
    props.setProperty(PropertyKey.tlsVersions.getKeyName(), "FOO,TLSv1,TLSv1.1,TLSv1.2");
    con = getConnectionWithProps(props);
    assertTrue(((MysqlConnection) con).getSession().isSSLEstablished());
    assertSessionStatusEquals(con.createStatement(), "ssl_version", "TLSv1.2");
    con.close();
}
Also used : Connection(java.sql.Connection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) MysqlConnection(com.mysql.cj.MysqlConnection) Properties(java.util.Properties) Test(org.junit.jupiter.api.Test)

Aggregations

MysqlConnection (com.mysql.cj.MysqlConnection)70 Test (org.junit.jupiter.api.Test)65 Properties (java.util.Properties)57 Connection (java.sql.Connection)55 JdbcConnection (com.mysql.cj.jdbc.JdbcConnection)42 TimeZone (java.util.TimeZone)26 XAConnection (javax.sql.XAConnection)24 ReplicationConnection (com.mysql.cj.jdbc.ha.ReplicationConnection)23 PooledConnection (javax.sql.PooledConnection)22 MysqlPooledConnection (com.mysql.cj.jdbc.MysqlPooledConnection)21 MysqlXAConnection (com.mysql.cj.jdbc.MysqlXAConnection)21 SuspendableXAConnection (com.mysql.cj.jdbc.SuspendableXAConnection)21 ZonedDateTime (java.time.ZonedDateTime)21 SQLException (java.sql.SQLException)18 PreparedStatement (java.sql.PreparedStatement)16 Statement (java.sql.Statement)16 CommunicationsException (com.mysql.cj.jdbc.exceptions.CommunicationsException)14 IOException (java.io.IOException)14 ExecutionException (java.util.concurrent.ExecutionException)14 TimeoutException (java.util.concurrent.TimeoutException)14