1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
|
/*
Derby - Class org.apache.derbyTesting.functionTests.tests.jdbc4.LoginTimeoutTest
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derbyTesting.functionTests.tests.jdbc4;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLTimeoutException;
import java.util.Properties;
import javax.sql.CommonDataSource;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.XADataSource;
import junit.framework.Test;
import org.apache.derby.authentication.UserAuthenticator;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
import org.apache.derbyTesting.junit.BaseTestCase;
import org.apache.derbyTesting.junit.BaseTestSuite;
import org.apache.derbyTesting.junit.Derby;
import org.apache.derbyTesting.junit.J2EEDataSource;
import org.apache.derbyTesting.junit.JDBCClient;
import org.apache.derbyTesting.junit.JDBCClientSetup;
import org.apache.derbyTesting.junit.JDBCDataSource;
import org.apache.derbyTesting.junit.NetworkServerTestSetup;
import org.apache.derbyTesting.junit.SystemPropertyTestSetup;
import org.apache.derbyTesting.junit.TestConfiguration;
/**
* Test login timeouts.
*/
public class LoginTimeoutTest extends BaseJDBCTestCase
{
///////////////////////////////////////////////////////////////////////////////////
//
// CONSTANTS
//
///////////////////////////////////////////////////////////////////////////////////
private static final String[][] SYSTEM_PROPERTIES =
{
{ "derby.connection.requireAuthentication", "true" },
{ "derby.authentication.provider", LoginTimeoutTest.class.getName() + "$SluggishAuthenticator" },
};
private static final boolean SUCCEED = true;
private static final boolean FAIL = false;
private static final int LONG_TIMEOUT = 10;
///////////////////////////////////////////////////////////////////////////////////
//
// STATE
//
///////////////////////////////////////////////////////////////////////////////////
private static final String RUTH = "RUTH";
private static final String RUTH_PASSWORD = "RUTHPASSWORD";
private static final String LOGIN_TIMEOUT = "XBDA0";
private static final String LOGIN_FAILED = "08004";
///////////////////////////////////////////////////////////////////////////////////
//
// NESTED CLASSES
//
///////////////////////////////////////////////////////////////////////////////////
/** User authenticator which sleeps for a while */
public static final class SluggishAuthenticator implements UserAuthenticator
{
public static boolean debugPrinting = false;
private static final long MILLIS_PER_SECOND = 1000L;
public static long secondsToSleep = 2;
public static boolean returnValue = true;
public SluggishAuthenticator() {}
public boolean authenticateUser
(
String userName,
String userPassword,
String databaseName,
Properties info
)
throws SQLException
{
// sleepy...
try {
long sleepTime = secondsToSleep * MILLIS_PER_SECOND;
printText( "SluggishAuthenticator going to sleep for " + sleepTime + " milliseconds." );
Thread.sleep( secondsToSleep * MILLIS_PER_SECOND );
printText( "...SluggishAuthenticator waking up after " + sleepTime + " milliseconds." );
} catch (Exception e) { throw new SQLException( e.getMessage(), e ); }
// ...and vacuous.
return returnValue;
}
private static void printText( String text )
{
if ( debugPrinting )
{
BaseTestCase.println( text );
}
}
}
/** Behavior shared by DataSource and DriverManager */
public static interface Connector
{
public Connection getConnection( String user, String password ) throws SQLException;
public void setLoginTimeout( int seconds ) throws SQLException;
}
public static final class DriverManagerConnector implements Connector
{
private BaseJDBCTestCase _test;
public DriverManagerConnector( BaseJDBCTestCase test ) { _test = test; }
public Connection getConnection( String user, String password ) throws SQLException
{
return _test.openDefaultConnection( user, password );
}
public void setLoginTimeout( int seconds ) { DriverManager.setLoginTimeout( seconds ); }
public String toString() { return "DriverManagerConnector"; }
}
public static final class DataSourceConnector implements Connector
{
private CommonDataSource _dataSource;
public DataSourceConnector( CommonDataSource dataSource )
{
_dataSource = dataSource;
}
public Connection getConnection( String user, String password ) throws SQLException
{
if ( _dataSource instanceof DataSource )
{
return ((DataSource) _dataSource).getConnection( user, password );
}
else if ( _dataSource instanceof ConnectionPoolDataSource )
{
return ((ConnectionPoolDataSource) _dataSource).getPooledConnection( user, password ).getConnection();
}
else if ( _dataSource instanceof XADataSource )
{
return ((XADataSource) _dataSource).getXAConnection( user, password ).getConnection();
}
else { throw new SQLException( "Unknown data source type: " + _dataSource.getClass().getName() ); }
}
public void setLoginTimeout( int seconds ) throws SQLException
{ _dataSource.setLoginTimeout( seconds ); }
public String toString()
{
return "DataSourceConnector( " + _dataSource.getClass().getName() + " )";
}
}
///////////////////////////////////////////////////////////////////////////////////
//
// CONSTRUCTORS
//
///////////////////////////////////////////////////////////////////////////////////
/**
*
* Create a test with the given name.
*/
public LoginTimeoutTest(String name) { super(name); }
///////////////////////////////////////////////////////////////////////////////////
//
// JUnit MACHINERY
//
///////////////////////////////////////////////////////////////////////////////////
/**
* Return suite with all tests of the class.
*/
public static Test suite()
{
BaseTestSuite suite = new BaseTestSuite();
Test embedded = new BaseTestSuite(
LoginTimeoutTest.class, "embedded LoginTimeoutTest" );
embedded = TestConfiguration.singleUseDatabaseDecorator( embedded );
embedded = new SystemPropertyTestSetup( embedded, systemProperties() );
suite.addTest( embedded );
if (Derby.hasServer() && Derby.hasClient()) {
Test clientServer = new BaseTestSuite(
LoginTimeoutTest.class, "client/server LoginTimeoutTest");
clientServer =
TestConfiguration.singleUseDatabaseDecorator(clientServer);
clientServer = new JDBCClientSetup(
clientServer, JDBCClient.DERBYNETCLIENT);
clientServer = new NetworkServerTestSetup(clientServer,
systemPropertiesArray(), new String[]{}, true);
suite.addTest(clientServer);
}
return suite;
}
private static Properties systemProperties()
{
Properties props = new Properties();
for ( int i = 0; i < SYSTEM_PROPERTIES.length; i++ )
{
String[] raw = SYSTEM_PROPERTIES[ i ];
props.put( raw[ 0 ], raw[ 1 ] );
}
return props;
}
private static String[] systemPropertiesArray()
{
String[] result = new String[ SYSTEM_PROPERTIES.length ];
for ( int i = 0; i < SYSTEM_PROPERTIES.length; i++ )
{
String[] raw = SYSTEM_PROPERTIES[ i ];
result[ i ] = raw[ 0 ] + "=" + raw[ 1 ];
}
return result;
}
///////////////////////////////////////////////////////////////////////////////////
//
// TESTS
//
///////////////////////////////////////////////////////////////////////////////////
/**
* Basic test of login timeouts.
*/
public void testBasic() throws Exception
{
SluggishAuthenticator.debugPrinting = TestConfiguration.getCurrent().isVerbose();
// make sure the database is created in order to eliminate asymmetries
// in running the tests
Connection conn = openDefaultConnection( RUTH, RUTH_PASSWORD );
conn.close();
vetConnector( new DriverManagerConnector( this ), true );
vetConnector( new DataSourceConnector( JDBCDataSource.getDataSource() ), true );
vetConnector( new DataSourceConnector( J2EEDataSource.getConnectionPoolDataSource() ), true );
vetConnector( new DataSourceConnector( J2EEDataSource.getXADataSource() ), true );
if ( usingEmbedded() ) { vetExceptionPassthrough(); }
if ( usingDerbyNetClient() ) { vetServerTimeouts(); }
}
private void vetConnector( Connector connector, boolean shouldSucceed ) throws Exception
{
try {
// sometimes this succeeds when we expect not, see DERBY-6250,
// give more time to the slug sleep
if (usingEmbedded())
SluggishAuthenticator.secondsToSleep = 4;
tryTimeout( connector, 1, FAIL && shouldSucceed );
// set back.
if (usingEmbedded())
SluggishAuthenticator.secondsToSleep = 2;
tryTimeout( connector, LONG_TIMEOUT, SUCCEED && shouldSucceed );
tryTimeout( connector, 0, SUCCEED && shouldSucceed );
}
finally
{
// revert to default state
connector.setLoginTimeout( 0 );
// set sluggishauthenticator sleep back
SluggishAuthenticator.secondsToSleep = 2;
}
}
private void tryTimeout( Connector connector, int timeout, boolean shouldSucceed ) throws Exception
{
println( "Setting timeout " + timeout + " on " + connector );
connector.setLoginTimeout( timeout );
tryTimeout( connector, shouldSucceed );
}
private void tryTimeout( Connector connector, boolean shouldSucceed ) throws Exception
{
long startTime = System.currentTimeMillis();
try {
Connection conn = connector.getConnection( RUTH, RUTH_PASSWORD );
println( " Got a " + conn.getClass().getName() );
conn.close();
if ( !shouldSucceed )
{
// sometimes the connect succeeds, see DERBY-6250.
// adding more details to fail message.
long duration = System.currentTimeMillis() - startTime;
String message ="Should not have been able to connect! \n " +
" connector: " + connector +
" Experiment took " + duration + " milliseconds. \n " +
" seconds sleep time was: " + SluggishAuthenticator.secondsToSleep;
fail( message );
}
}
catch (SQLException se)
{
if ( shouldSucceed ) { fail( "Should have been able to connect!", se ); }
assertTrue( "Didn't expect to see a " + se.getClass().getName(), (se instanceof SQLTimeoutException) );
assertSQLState( LOGIN_TIMEOUT, se );
}
long duration = System.currentTimeMillis() - startTime;
println( " Experiment took " + duration + " milliseconds." );
}
private void vetExceptionPassthrough() throws Exception
{
try {
println( "Verifying that exceptions are not swallowed by the embedded login timer." );
// set a long timeout which we won't exceed
DriverManager.setLoginTimeout( LONG_TIMEOUT );
// tell the authenticator to always fail
SluggishAuthenticator.returnValue = false;
try {
Connection conn = openDefaultConnection( RUTH, RUTH_PASSWORD );
conn.close();
fail( "Didn't expect to get a connection!" );
}
catch (SQLException se) { assertSQLState( LOGIN_FAILED, se ); }
}
finally
{
// return to default position
DriverManager.setLoginTimeout( 0 );
SluggishAuthenticator.returnValue = true;
}
}
private void vetServerTimeouts() throws Exception
{
println( "Verifying behavior when timeouts are also set on the server." );
Connection controlConnection = openDefaultConnection( RUTH, RUTH_PASSWORD );
// create a procedure for changing the login timeout on the server
String createProc =
"create procedure setLoginTimeout( timeout int ) language java parameter style java no sql\n" +
"external name '" + getClass().getName() + ".setLoginTimeout'";
println( createProc );
controlConnection.prepareStatement( createProc ).execute();
createProc =
"create procedure setAuthenticatorSleep( seconds int ) language java parameter style java no sql\n" +
"external name '" + getClass().getName() + ".setAuthenticatorSleep'";
controlConnection.prepareStatement( createProc ).execute();
println( createProc );
Connector connector = new DriverManagerConnector( this );
vetServerTimeout( controlConnection, connector, 1, FAIL );
vetServerTimeout( controlConnection, connector, LONG_TIMEOUT, SUCCEED );
vetServerTimeout( controlConnection, connector, 0, SUCCEED );
// reset server timeout to default
setServerTimeout( controlConnection, 0 );
controlConnection.close();
}
private void vetServerTimeout
( Connection controlConnection, Connector connector, int serverTimeout, boolean shouldSucceed )
throws Exception
{
setServerTimeout( controlConnection, serverTimeout );
// Sometimes we get an unexpected connection when we expect
// the timeout to work, see DERBY-6250.
// Setting the sleep Authenticator sleep time longer on the server.
// for those cases to make the chance of this occurring smaller.
if (!shouldSucceed)
setServerAuthenticatorSleep(controlConnection, 4);
else
setServerAuthenticatorSleep(controlConnection, 2);
vetConnector( connector, shouldSucceed );
}
private void setServerTimeout( Connection conn, int seconds ) throws Exception
{
CallableStatement cs = conn.prepareCall( "call setLoginTimeout( ? )" );
cs.setInt( 1, seconds );
cs.execute();
cs.close();
}
private void setServerAuthenticatorSleep( Connection conn, int seconds )
throws Exception
{
CallableStatement cs = conn.prepareCall( "call setAuthenticatorSleep( ? )" );
cs.setInt( 1, seconds );
cs.execute();
cs.close();
}
///////////////////////////////////////////////////////////////////////////////////
//
// SQL ROUTINES
//
///////////////////////////////////////////////////////////////////////////////////
/** Routine to set the DriverManager login timeout on the server */
public static void setLoginTimeout( int seconds ) throws Exception
{
DriverManager.setLoginTimeout( seconds );
}
/** Routine to set the SluggishAuthenticator Sleep
* time on the server */
public static void setAuthenticatorSleep( int seconds ) throws Exception
{
SluggishAuthenticator.secondsToSleep = seconds ;
}
///////////////////////////////////////////////////////////////////////////////////
//
// MINIONS
//
///////////////////////////////////////////////////////////////////////////////////
}
|