Search in sources :

Example 1 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class ConnectionRegressionTest method subTestBug22848249A.

/*
     * Tests removing and adding hosts (excluding the host from the underlying physical connection) to the connection group with the option to propagate
     * changes to all active load-balanced connections.
     */
private void subTestBug22848249A() throws Exception {
    final String defaultHost = getPropertiesFromTestsuiteUrl().getProperty(PropertyKey.HOST.getKeyName());
    final String defaultPort = getPropertiesFromTestsuiteUrl().getProperty(PropertyKey.PORT.getKeyName());
    final String host1 = "first";
    final String host2 = "second";
    final String host3 = "third";
    final String host4 = "fourth";
    final String hostPort1 = host1 + ":" + defaultPort;
    final String hostPort2 = host2 + ":" + defaultPort;
    final String hostPort3 = host3 + ":" + defaultPort;
    final String hostPort4 = host4 + ":" + defaultPort;
    final String lbConnGroup = "Bug22848249A";
    System.out.println("testBug22848249A:");
    System.out.println("********************************************************************************");
    Properties props = new Properties();
    props.setProperty(PropertyKey.sslMode.getKeyName(), "DISABLED");
    props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
    props.setProperty(PropertyKey.loadBalanceHostRemovalGracePeriod.getKeyName(), "0");
    props.setProperty(PropertyKey.loadBalanceConnectionGroup.getKeyName(), lbConnGroup);
    Connection testConn = getUnreliableLoadBalancedConnection(new String[] { host1, host2, host3 }, props);
    testConn.setAutoCommit(false);
    String connectedHost = ((JdbcConnection) testConn).getHost();
    assertConnectionsHistory(UnreliableSocketFactory.getHostConnectedStatus(connectedHost));
    assertEquals(3, ConnectionGroupManager.getActiveHostCount(lbConnGroup));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort1));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort2));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort3));
    /*
         * The l/b connection won't be able to use removed unused hosts.
         */
    // Remove a non-connected host: host2 or host3.
    String removedHost = connectedHost.equals(host3) ? host2 : host3;
    String removedHostPort = removedHost + ":" + defaultPort;
    ConnectionGroupManager.removeHost(lbConnGroup, removedHostPort, true);
    // Still connected to the initital host.
    assertEquals(connectedHost, ((JdbcConnection) testConn).getHost());
    assertEquals(2, ConnectionGroupManager.getActiveHostCount(lbConnGroup));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort1));
    // Only one can be true.
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort2) ^ removedHostPort.equals(hostPort2));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort3) ^ removedHostPort.equals(hostPort3));
    // Force some transaction boundaries while checking that the removed host is never used.
    int connectionSwaps = 0;
    for (int i = 0; i < 100; i++) {
        testConn.rollback();
        String newConnectedHost = ((JdbcConnection) testConn).getHost();
        assertFalse(newConnectedHost.equals(removedHost));
        if (!connectedHost.equals(newConnectedHost)) {
            connectedHost = newConnectedHost;
            connectionSwaps++;
        }
    }
    System.out.println("\t1. Swapped connections " + connectionSwaps + " times out of 100, without hitting the removed host(s).");
    // Non-deterministic, but something must be wrong if there are no swaps after 100 transaction boundaries.
    assertTrue(connectionSwaps > 0);
    assertFalse(UnreliableSocketFactory.getHostsFromAllConnections().contains(UnreliableSocketFactory.getHostConnectedStatus(removedHost)));
    /*
         * The l/b connection will be able to use a host added back to the connection group.
         */
    // Add back the previously removed host.
    ConnectionGroupManager.addHost(lbConnGroup, removedHostPort, true);
    assertEquals(3, ConnectionGroupManager.getActiveHostCount(lbConnGroup));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort1));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort2));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort3));
    // Force transaction boundaries until the new host is selected or a limit number of attempts is reached.
    String newHost = removedHost;
    connectionSwaps = 0;
    int attemptsLeft = 100;
    while (!(connectedHost = ((JdbcConnection) testConn).getHost()).equals(newHost)) {
        testConn.rollback();
        String newConnectedHost = ((JdbcConnection) testConn).getHost();
        if (!connectedHost.equals(newConnectedHost)) {
            connectedHost = newConnectedHost;
            connectionSwaps++;
        }
        assertFalse(--attemptsLeft == 0, "Failed to swap to the newly added host after 100 transaction boundaries and " + connectionSwaps + " connection swaps.");
    }
    System.out.println("\t2. Swapped connections " + connectionSwaps + " times before hitting the new host.");
    // Non-deterministic, but something must be wrong if there are no swaps after 100 transaction boundaries.
    assertTrue(connectionSwaps > 0);
    assertTrue(UnreliableSocketFactory.getHostsFromAllConnections().contains(UnreliableSocketFactory.getHostConnectedStatus(newHost)));
    /*
         * The l/b connection will be able to use new hosts added to the connection group.
         */
    // Add a completely new host.
    UnreliableSocketFactory.mapHost(host4, defaultHost);
    ConnectionGroupManager.addHost(lbConnGroup, hostPort4, true);
    assertEquals(4, ConnectionGroupManager.getActiveHostCount(lbConnGroup));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort1));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort2));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort3));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort4));
    // Force transaction boundaries until the new host is selected or a limit number of attempts is reached.
    newHost = host4;
    connectionSwaps = 0;
    attemptsLeft = 100;
    while (!(connectedHost = ((JdbcConnection) testConn).getHost()).equals(newHost)) {
        testConn.rollback();
        String newConnectedHost = ((JdbcConnection) testConn).getHost();
        if (!connectedHost.equals(newConnectedHost)) {
            connectedHost = newConnectedHost;
            connectionSwaps++;
        }
        assertFalse(--attemptsLeft == 0, "Failed to swap to the newly added host after 100 transaction boundaries and " + connectionSwaps + " connection swaps.");
    }
    System.out.println("\t3. Swapped connections " + connectionSwaps + " times before hitting the new host.");
    // Non-deterministic, but something must be wrong if there are no swaps after 100 transaction boundaries.
    assertTrue(connectionSwaps > 0);
    assertTrue(UnreliableSocketFactory.getHostsFromAllConnections().contains(UnreliableSocketFactory.getHostConnectedStatus(newHost)));
    /*
         * The l/b connection won't be able to use any number of removed hosts (excluding the current active host).
         */
    // Remove any two hosts, other than the one used in the active connection.
    String removedHost1 = connectedHost.equals(host2) ? host1 : host2;
    String removedHostPort1 = removedHost1 + ":" + defaultPort;
    ConnectionGroupManager.removeHost(lbConnGroup, removedHostPort1, true);
    String removedHost2 = connectedHost.equals(host4) ? host3 : host4;
    String removedHostPort2 = removedHost2 + ":" + defaultPort;
    ConnectionGroupManager.removeHost(lbConnGroup, removedHostPort2, true);
    // Still connected to the same host.
    assertEquals(connectedHost, ((JdbcConnection) testConn).getHost());
    assertEquals(2, ConnectionGroupManager.getActiveHostCount(lbConnGroup));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort1) ^ removedHostPort1.equals(hostPort1));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort2) ^ removedHostPort1.equals(hostPort2));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort3) ^ removedHostPort2.equals(hostPort3));
    assertTrue(ConnectionGroupManager.getActiveHostLists(lbConnGroup).contains(hostPort4) ^ removedHostPort2.equals(hostPort4));
    // Force some transaction boundaries while checking that the removed hosts are never used.
    connectionSwaps = 0;
    for (int i = 0; i < 100; i++) {
        testConn.rollback();
        String newConnectedHost = ((JdbcConnection) testConn).getHost();
        assertFalse(newConnectedHost.equals(removedHost1));
        assertFalse(newConnectedHost.equals(removedHost2));
        if (!connectedHost.equals(newConnectedHost)) {
            connectedHost = newConnectedHost;
            connectionSwaps++;
        }
    }
    System.out.println("\t4. Swapped connections " + connectionSwaps + " times out of 100, without hitting the removed host(s).");
    // Non-deterministic, but something must be wrong if there are no swaps after 100 transaction boundaries.
    assertTrue(connectionSwaps > 0);
    // Make sure the connection is working fine.
    this.rs = testConn.createStatement().executeQuery("SELECT 'testBug22848249'");
    assertTrue(this.rs.next());
    assertEquals("testBug22848249", this.rs.getString(1));
    testConn.close();
}
Also used : ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) MysqlPooledConnection(com.mysql.cj.jdbc.MysqlPooledConnection) SuspendableXAConnection(com.mysql.cj.jdbc.SuspendableXAConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) PooledConnection(javax.sql.PooledConnection) MysqlXAConnection(com.mysql.cj.jdbc.MysqlXAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) Properties(java.util.Properties)

Example 2 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class ConnectionRegressionTest method testBug37570.

@Test
public void testBug37570() throws Exception {
    Properties props = new Properties();
    props.setProperty(PropertyKey.sslMode.getKeyName(), "DISABLED");
    props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
    props.setProperty(PropertyKey.characterEncoding.getKeyName(), "utf-8");
    props.setProperty(PropertyKey.passwordCharacterEncoding.getKeyName(), "utf-8");
    Connection con = getConnectionWithProps(props);
    // Cyrillic string
    String unicodePassword = "\u0430\u0431\u0432";
    String user = "bug37570";
    Statement st = con.createStatement();
    createUser(st, "'" + user + "'@'%'", "identified WITH mysql_native_password");
    st.executeUpdate("grant all on *.* to '" + user + "'@'%'");
    st.executeUpdate(versionMeetsMinimum(5, 7, 6) ? "ALTER USER '" + user + "'@'%' IDENTIFIED BY '" + unicodePassword + "'" : "SET PASSWORD FOR '" + user + "'@'%' = PASSWORD('" + unicodePassword + "')");
    st.executeUpdate("flush privileges");
    try {
        ((JdbcConnection) con).changeUser(user, unicodePassword);
    } catch (SQLException sqle) {
        sqle.printStackTrace();
        fail("Connection with non-latin1 password failed");
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) MysqlPooledConnection(com.mysql.cj.jdbc.MysqlPooledConnection) SuspendableXAConnection(com.mysql.cj.jdbc.SuspendableXAConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) PooledConnection(javax.sql.PooledConnection) MysqlXAConnection(com.mysql.cj.jdbc.MysqlXAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) Properties(java.util.Properties) Test(org.junit.jupiter.api.Test)

Example 3 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class ConnectionRegressionTest method testBug27102307.

/**
 * Tests fix for BUG#27102307, CHANGE USESSL AND VERIFYSERVERCERTIFICATE TO SSLMODE OPTION.
 *
 * @throws Exception
 */
@Test
public void testBug27102307() throws Exception {
    assumeTrue(supportsTestCertificates(this.stmt), "This test requires the server configured with SSL certificates from ConnectorJ/src/test/config/ssl-test-certs");
    // Basic SSL properties translation is tested in testBug21947042(). Testing only missing variants here.
    System.setProperty("javax.net.ssl.trustStore", "");
    System.setProperty("javax.net.ssl.trustStorePassword", "");
    Connection sslConn = null;
    Properties props = new Properties();
    // 1. Explicit sslMode, no explicit useSSL
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.toString());
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.DISABLED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertFalse(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    sslConn.close();
    // 2. Explicit sslMode, explicit useSSL=false
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.REQUIRED.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "false");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.REQUIRED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    sslConn.close();
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.REQUIRED.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "no");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.REQUIRED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    sslConn.close();
    // 3. Explicit sslMode, explicit useSSL=true
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.DISABLED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertFalse(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    sslConn.close();
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.DISABLED.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "yes");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.DISABLED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertFalse(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    sslConn.close();
    // 4. Explicit sslMode=REQUIRED, explicit useSSL=true, verifyServerCertificate=true, no trust store
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.REQUIRED.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "true");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.REQUIRED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    sslConn.close();
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.REQUIRED.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "yes");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.REQUIRED, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    sslConn.close();
    // 5. Explicit sslMode=VERIFY_CA, explicit useSSL=true, verifyServerCertificate=false, no trust store
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.VERIFY_CA.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "false");
    assertThrows(SQLException.class, new Callable<Void>() {

        public Void call() throws Exception {
            getConnectionWithProps(props);
            return null;
        }
    });
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.VERIFY_CA.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "no");
    assertThrows(SQLException.class, new Callable<Void>() {

        public Void call() throws Exception {
            getConnectionWithProps(props);
            return null;
        }
    });
    // 5. Explicit sslMode=VERIFY_CA, explicit useSSL=false, verifyServerCertificate=false, with trust store
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.VERIFY_CA.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "false");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "false");
    props.setProperty(PropertyKey.trustCertificateKeyStoreUrl.getKeyName(), "file:src/test/config/ssl-test-certs/ca-truststore");
    props.setProperty(PropertyKey.trustCertificateKeyStoreType.getKeyName(), "JKS");
    props.setProperty(PropertyKey.trustCertificateKeyStorePassword.getKeyName(), "password");
    sslConn = getConnectionWithProps(props);
    assertTrue(((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).isExplicitlySet());
    assertEquals(SslMode.VERIFY_CA, ((JdbcConnection) sslConn).getPropertySet().getEnumProperty(PropertyKey.sslMode).getValue());
    assertTrue(((MysqlConnection) sslConn).getSession().isSSLEstablished());
    sslConn.close();
    // 6. Explicit sslMode=VERIFY_IDENTITY, explicit useSSL=true, verifyServerCertificate=false, no trust store
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.VERIFY_IDENTITY.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "true");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "false");
    assertThrows(SQLException.class, new Callable<Void>() {

        public Void call() throws Exception {
            getConnectionWithProps(props);
            return null;
        }
    });
    // 7. Explicit sslMode=VERIFY_IDENTITY, explicit useSSL=false, verifyServerCertificate=false, with trust store
    // The server certificate used in this test has "CN=MySQL Connector/J Server" and several SAN entries that don't match thus identity check failure
    props.setProperty(PropertyKey.sslMode.getKeyName(), SslMode.VERIFY_IDENTITY.toString());
    props.setProperty(PropertyKey.useSSL.getKeyName(), "false");
    props.setProperty(PropertyKey.verifyServerCertificate.getKeyName(), "false");
    props.setProperty(PropertyKey.trustCertificateKeyStoreUrl.getKeyName(), "file:src/test/config/ssl-test-certs/ca-truststore");
    props.setProperty(PropertyKey.trustCertificateKeyStoreType.getKeyName(), "JKS");
    props.setProperty(PropertyKey.trustCertificateKeyStorePassword.getKeyName(), "password");
    Throwable cause = null;
    try {
        sslConn = getConnectionWithProps(props);
        fail("CertificateException expected but not thrown.");
    } catch (Throwable t) {
        cause = t.getCause();
        while (cause != null && !(cause instanceof CertificateException)) {
            cause = cause.getCause();
        }
        assertTrue(cause != null && cause instanceof CertificateException, "CertificateException expected");
        String errMsg = cause.getMessage();
        if (errMsg.startsWith("java.security.cert.CertificateException: ")) {
            errMsg = errMsg.substring("java.security.cert.CertificateException: ".length());
        }
        assertEquals("Server identity verification failed. None of the DNS or IP Subject Alternative Name " + "entries matched the server hostname/IP '" + getHostFromTestsuiteUrl() + "'.", errMsg);
    }
}
Also used : ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) MysqlPooledConnection(com.mysql.cj.jdbc.MysqlPooledConnection) SuspendableXAConnection(com.mysql.cj.jdbc.SuspendableXAConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) PooledConnection(javax.sql.PooledConnection) MysqlXAConnection(com.mysql.cj.jdbc.MysqlXAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) MysqlConnection(com.mysql.cj.MysqlConnection) CertificateException(java.security.cert.CertificateException) Properties(java.util.Properties) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SQLTransientException(java.sql.SQLTransientException) InvocationTargetException(java.lang.reflect.InvocationTargetException) XAException(javax.transaction.xa.XAException) SocketException(java.net.SocketException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) PasswordExpiredException(com.mysql.cj.exceptions.PasswordExpiredException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) SQLNonTransientConnectionException(java.sql.SQLNonTransientConnectionException) CommunicationsException(com.mysql.cj.jdbc.exceptions.CommunicationsException) CertificateException(java.security.cert.CertificateException) ClosedOnExpiredPasswordException(com.mysql.cj.exceptions.ClosedOnExpiredPasswordException) PropertyNotModifiableException(com.mysql.cj.exceptions.PropertyNotModifiableException) Test(org.junit.jupiter.api.Test)

Example 4 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class ConnectionRegressionTest method testExpiredPassword.

@Test
public void testExpiredPassword() throws Exception {
    assumeTrue(versionMeetsMinimum(5, 6, 10), "MySQL 5.6.10+ is required to run this test.");
    Connection testConn = null;
    Statement testSt = null;
    ResultSet testRs = null;
    Properties urlProps = getPropertiesFromTestsuiteUrl();
    String dbname = urlProps.getProperty(PropertyKey.DBNAME.getKeyName());
    try {
        createUser("'must_change1'@'%'", "IDENTIFIED BY 'aha'");
        this.stmt.executeUpdate("grant all on `" + dbname + "`.* to 'must_change1'@'%'");
        createUser("'must_change2'@'%'", "IDENTIFIED BY 'aha'");
        this.stmt.executeUpdate("grant all on `" + dbname + "`.* to 'must_change2'@'%'");
        // workaround for Bug#77732
        if (versionMeetsMinimum(5, 7, 6) && !versionMeetsMinimum(8, 0, 5)) {
            this.stmt.executeUpdate("GRANT SELECT ON `performance_schema`.`session_variables` TO 'must_change1'@'%'");
            this.stmt.executeUpdate("GRANT SELECT ON `performance_schema`.`session_variables` TO 'must_change2'@'%'");
        }
        this.stmt.executeUpdate(versionMeetsMinimum(5, 7, 6) ? "ALTER USER 'must_change1'@'%', 'must_change2'@'%' PASSWORD EXPIRE" : "ALTER USER 'must_change1'@'%' PASSWORD EXPIRE, 'must_change2'@'%' PASSWORD EXPIRE");
        Properties props = new Properties();
        props.setProperty(PropertyKey.sslMode.getKeyName(), "DISABLED");
        props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
        // ALTER USER can be prepared as of 5.6.8 (BUG#14646014)
        if (versionMeetsMinimum(5, 6, 8)) {
            props.setProperty(PropertyKey.useServerPrepStmts.getKeyName(), "true");
            testConn = getConnectionWithProps(props);
            this.pstmt = testConn.prepareStatement(versionMeetsMinimum(5, 7, 6) ? "ALTER USER 'must_change1'@'%', 'must_change2'@'%' PASSWORD EXPIRE" : "ALTER USER 'must_change1'@'%' PASSWORD EXPIRE, 'must_change2'@'%' PASSWORD EXPIRE");
            this.pstmt.executeUpdate();
            this.pstmt.close();
            this.pstmt = testConn.prepareStatement(versionMeetsMinimum(5, 7, 6) ? "ALTER USER ?, 'must_change2'@'%' PASSWORD EXPIRE" : "ALTER USER ? PASSWORD EXPIRE, 'must_change2'@'%' PASSWORD EXPIRE");
            this.pstmt.setString(1, "must_change1");
            this.pstmt.executeUpdate();
            this.pstmt.close();
            testConn.close();
        }
        props.setProperty(PropertyKey.USER.getKeyName(), "must_change1");
        props.setProperty(PropertyKey.PASSWORD.getKeyName(), "aha");
        try {
            testConn = getConnectionWithProps(props);
            fail("SQLException expected due to password expired");
        } catch (PasswordExpiredException | ClosedOnExpiredPasswordException | SQLException e1) {
            if ((e1 instanceof SQLException && (((SQLException) e1).getErrorCode() == MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD || ((SQLException) e1).getErrorCode() == MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD_LOGIN)) || e1 instanceof PasswordExpiredException || e1 instanceof ClosedOnExpiredPasswordException) {
                props.setProperty(PropertyKey.disconnectOnExpiredPasswords.getKeyName(), "false");
                try {
                    testConn = getConnectionWithProps(props);
                    testSt = testConn.createStatement();
                    testRs = testSt.executeQuery("SHOW VARIABLES LIKE 'disconnect_on_expired_password'");
                    testRs.close();
                    fail("SQLException expected due to password expired");
                } catch (PasswordExpiredException | ClosedOnExpiredPasswordException | SQLException e3) {
                    if (e3 instanceof SQLException && (((SQLException) e3).getErrorCode() == MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD_LOGIN) || e3 instanceof ClosedOnExpiredPasswordException) {
                        testSt.close();
                        testConn = getConnectionWithProps(props);
                        testSt = testConn.createStatement();
                    }
                    if (testSt == null) {
                        testSt = testConn.createStatement();
                    }
                    testSt.executeUpdate(versionMeetsMinimum(5, 7, 6) ? "ALTER USER USER() IDENTIFIED BY 'newpwd'" : "SET PASSWORD = PASSWORD('newpwd')");
                    testConn.close();
                    props.setProperty(PropertyKey.USER.getKeyName(), "must_change1");
                    props.setProperty(PropertyKey.PASSWORD.getKeyName(), "newpwd");
                    props.setProperty(PropertyKey.disconnectOnExpiredPasswords.getKeyName(), "true");
                    testConn = getConnectionWithProps(props);
                    testSt = testConn.createStatement();
                    testRs = testSt.executeQuery("SHOW VARIABLES LIKE 'disconnect_on_expired_password'");
                    assertTrue(testRs.next());
                    // change user
                    try {
                        ((JdbcConnection) testConn).changeUser("must_change2", "aha");
                        fail("SQLException expected due to password expired");
                    } catch (PasswordExpiredException | ClosedOnExpiredPasswordException | SQLException e4) {
                        if (e4 instanceof SQLException && (((SQLException) e4).getErrorCode() == MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD || ((SQLException) e4).getErrorCode() == MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD_LOGIN) || e4 instanceof PasswordExpiredException || e4 instanceof ClosedOnExpiredPasswordException) {
                            props.setProperty(PropertyKey.disconnectOnExpiredPasswords.getKeyName(), "false");
                            testConn = getConnectionWithProps(props);
                            try {
                                ((JdbcConnection) testConn).changeUser("must_change2", "aha");
                                testSt = testConn.createStatement();
                                testRs = testSt.executeQuery("SHOW VARIABLES LIKE 'disconnect_on_expired_password'");
                                fail("SQLException expected due to password expired");
                            } catch (PasswordExpiredException | ClosedOnExpiredPasswordException | SQLException e5) {
                                if (e5 instanceof SQLException && ((SQLException) e5).getErrorCode() == MysqlErrorNumbers.ER_MUST_CHANGE_PASSWORD_LOGIN || e5 instanceof ClosedOnExpiredPasswordException) {
                                    testConn = getConnectionWithProps(props);
                                    testSt = testConn.createStatement();
                                }
                                testSt = testConn.createStatement();
                                testSt.executeUpdate(versionMeetsMinimum(5, 7, 6) ? "ALTER USER USER() IDENTIFIED BY 'newpwd'" : "SET PASSWORD = PASSWORD('newpwd')");
                                testConn.close();
                                props.setProperty(PropertyKey.USER.getKeyName(), "must_change2");
                                props.setProperty(PropertyKey.PASSWORD.getKeyName(), "newpwd");
                                props.setProperty(PropertyKey.disconnectOnExpiredPasswords.getKeyName(), "true");
                                testConn = getConnectionWithProps(props);
                                testSt = testConn.createStatement();
                                testRs = testSt.executeQuery("SHOW VARIABLES LIKE 'disconnect_on_expired_password'");
                                assertTrue(testRs.next());
                            }
                        } else {
                            throw e4;
                        }
                    }
                }
            } else {
                throw e1;
            }
        }
    } finally {
        if (testRs != null) {
            testRs.close();
        }
        if (testSt != null) {
            testSt.close();
        }
        if (testConn != null) {
            testConn.close();
        }
    }
}
Also used : PasswordExpiredException(com.mysql.cj.exceptions.PasswordExpiredException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ServerPreparedStatement(com.mysql.cj.jdbc.ServerPreparedStatement) ClientPreparedStatement(com.mysql.cj.jdbc.ClientPreparedStatement) ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) MysqlPooledConnection(com.mysql.cj.jdbc.MysqlPooledConnection) SuspendableXAConnection(com.mysql.cj.jdbc.SuspendableXAConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) PooledConnection(javax.sql.PooledConnection) MysqlXAConnection(com.mysql.cj.jdbc.MysqlXAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) ResultSet(java.sql.ResultSet) ClosedOnExpiredPasswordException(com.mysql.cj.exceptions.ClosedOnExpiredPasswordException) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) Properties(java.util.Properties) Test(org.junit.jupiter.api.Test)

Example 5 with JdbcConnection

use of com.mysql.cj.jdbc.JdbcConnection in project JavaSegundasQuintas by ecteruel.

the class ConnectionRegressionTest method testOldPasswordPlugin.

@Test
public void testOldPasswordPlugin() throws Exception {
    assumeTrue(versionMeetsMinimum(5, 5, 7) && !versionMeetsMinimum(5, 7, 5), "testOldPasswordPlugin was skipped: This test only run for 5.5.7 - 5.7.4 server versions.");
    Connection testConn = null;
    try {
        this.stmt.executeUpdate("SET @current_secure_auth = @@global.secure_auth");
        this.stmt.executeUpdate("SET GLOBAL secure_auth= off");
        createUser("'bug64983user1'@'%'", "IDENTIFIED WITH mysql_old_password");
        this.stmt.executeUpdate("SET PASSWORD FOR 'bug64983user1'@'%' = OLD_PASSWORD('pwd')");
        this.stmt.executeUpdate("GRANT ALL on *.* TO 'bug64983user1'@'%'");
        createUser("'bug64983user2'@'%'", "IDENTIFIED WITH mysql_old_password");
        this.stmt.executeUpdate("SET PASSWORD FOR 'bug64983user2'@'%' = OLD_PASSWORD('')");
        this.stmt.executeUpdate("GRANT ALL ON *.* TO 'bug64983user2'@'%'");
        createUser("'bug64983user3'@'%'", "IDENTIFIED WITH mysql_old_password");
        this.stmt.executeUpdate("GRANT ALL ON *.* TO 'bug64983user3'@'%'");
        this.stmt.executeUpdate("flush privileges");
        Properties props = new Properties();
        props.setProperty(PropertyKey.sslMode.getKeyName(), "DISABLED");
        props.setProperty(PropertyKey.allowPublicKeyRetrieval.getKeyName(), "true");
        // connect with default plugin
        props.setProperty(PropertyKey.USER.getKeyName(), "bug64983user1");
        props.setProperty(PropertyKey.PASSWORD.getKeyName(), "pwd");
        testConn = getConnectionWithProps(props);
        ResultSet testRs = testConn.createStatement().executeQuery("SELECT USER()");
        testRs.next();
        assertEquals("bug64983user1", testRs.getString(1).split("@")[0]);
        testConn.close();
        props.setProperty(PropertyKey.USER.getKeyName(), "bug64983user2");
        props.setProperty(PropertyKey.PASSWORD.getKeyName(), "");
        testConn = getConnectionWithProps(props);
        testRs = testConn.createStatement().executeQuery("SELECT USER()");
        testRs.next();
        assertEquals("bug64983user2", testRs.getString(1).split("@")[0]);
        testConn.close();
        props.setProperty(PropertyKey.USER.getKeyName(), "bug64983user3");
        props.setProperty(PropertyKey.PASSWORD.getKeyName(), "");
        testConn = getConnectionWithProps(props);
        testRs = testConn.createStatement().executeQuery("SELECT USER()");
        testRs.next();
        assertEquals("bug64983user3", testRs.getString(1).split("@")[0]);
        testConn.close();
        // connect with MysqlOldPasswordPlugin plugin
        props.setProperty(PropertyKey.defaultAuthenticationPlugin.getKeyName(), MysqlOldPasswordPlugin.class.getName());
        props.setProperty(PropertyKey.USER.getKeyName(), "bug64983user1");
        props.setProperty(PropertyKey.PASSWORD.getKeyName(), "pwd");
        testConn = getConnectionWithProps(props);
        testRs = testConn.createStatement().executeQuery("SELECT USER()");
        testRs.next();
        assertEquals("bug64983user1", testRs.getString(1).split("@")[0]);
        testConn.close();
        props.setProperty(PropertyKey.USER.getKeyName(), "bug64983user2");
        props.setProperty(PropertyKey.PASSWORD.getKeyName(), "");
        testConn = getConnectionWithProps(props);
        testRs = testConn.createStatement().executeQuery("SELECT USER()");
        testRs.next();
        assertEquals("bug64983user2", testRs.getString(1).split("@")[0]);
        testConn.close();
        props.setProperty(PropertyKey.USER.getKeyName(), "bug64983user3");
        props.setProperty(PropertyKey.PASSWORD.getKeyName(), "");
        testConn = getConnectionWithProps(props);
        testRs = testConn.createStatement().executeQuery("SELECT USER()");
        testRs.next();
        assertEquals("bug64983user3", testRs.getString(1).split("@")[0]);
        // changeUser
        ((JdbcConnection) testConn).changeUser("bug64983user1", "pwd");
        testRs = testConn.createStatement().executeQuery("SELECT USER()");
        testRs.next();
        assertEquals("bug64983user1", testRs.getString(1).split("@")[0]);
        ((JdbcConnection) testConn).changeUser("bug64983user2", "");
        testRs = testConn.createStatement().executeQuery("SELECT USER()");
        testRs.next();
        assertEquals("bug64983user2", testRs.getString(1).split("@")[0]);
        ((JdbcConnection) testConn).changeUser("bug64983user3", "");
        testRs = testConn.createStatement().executeQuery("SELECT USER()");
        testRs.next();
        assertEquals("bug64983user3", testRs.getString(1).split("@")[0]);
    } finally {
        try {
            this.stmt.executeUpdate("SET GLOBAL secure_auth = @current_secure_auth");
            if (testConn != null) {
                testConn.close();
            }
        } catch (Exception ex) {
            System.err.println("Exception during cleanup:");
            ex.printStackTrace();
        }
    }
}
Also used : MysqlOldPasswordPlugin(com.mysql.cj.protocol.a.authentication.MysqlOldPasswordPlugin) ReplicationConnection(com.mysql.cj.jdbc.ha.ReplicationConnection) MysqlPooledConnection(com.mysql.cj.jdbc.MysqlPooledConnection) SuspendableXAConnection(com.mysql.cj.jdbc.SuspendableXAConnection) Connection(java.sql.Connection) XAConnection(javax.sql.XAConnection) PooledConnection(javax.sql.PooledConnection) MysqlXAConnection(com.mysql.cj.jdbc.MysqlXAConnection) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) MysqlConnection(com.mysql.cj.MysqlConnection) ResultSet(java.sql.ResultSet) JdbcConnection(com.mysql.cj.jdbc.JdbcConnection) Properties(java.util.Properties) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SQLTransientException(java.sql.SQLTransientException) InvocationTargetException(java.lang.reflect.InvocationTargetException) XAException(javax.transaction.xa.XAException) SocketException(java.net.SocketException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) PasswordExpiredException(com.mysql.cj.exceptions.PasswordExpiredException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) SQLNonTransientConnectionException(java.sql.SQLNonTransientConnectionException) CommunicationsException(com.mysql.cj.jdbc.exceptions.CommunicationsException) CertificateException(java.security.cert.CertificateException) ClosedOnExpiredPasswordException(com.mysql.cj.exceptions.ClosedOnExpiredPasswordException) PropertyNotModifiableException(com.mysql.cj.exceptions.PropertyNotModifiableException) Test(org.junit.jupiter.api.Test)

Aggregations

JdbcConnection (com.mysql.cj.jdbc.JdbcConnection)280 Properties (java.util.Properties)216 Test (org.junit.jupiter.api.Test)207 Connection (java.sql.Connection)175 MysqlConnection (com.mysql.cj.MysqlConnection)149 XAConnection (javax.sql.XAConnection)100 SQLException (java.sql.SQLException)97 ReplicationConnection (com.mysql.cj.jdbc.ha.ReplicationConnection)96 PooledConnection (javax.sql.PooledConnection)90 MysqlPooledConnection (com.mysql.cj.jdbc.MysqlPooledConnection)81 MysqlXAConnection (com.mysql.cj.jdbc.MysqlXAConnection)79 SuspendableXAConnection (com.mysql.cj.jdbc.SuspendableXAConnection)78 Statement (java.sql.Statement)77 ServerPreparedStatement (com.mysql.cj.jdbc.ServerPreparedStatement)66 PreparedStatement (java.sql.PreparedStatement)66 ResultSet (java.sql.ResultSet)65 ClientPreparedStatement (com.mysql.cj.jdbc.ClientPreparedStatement)60 CommunicationsException (com.mysql.cj.jdbc.exceptions.CommunicationsException)60 IOException (java.io.IOException)54 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)45