@Test public void testFailedCreateConsumerConnectionStillWorks() throws JMSException { Connection connection = pooledConnFact.createConnection("guest", "password"); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(name.getMethodName()); try { session.createConsumer(queue); fail("Should fail to create consumer"); } catch (JMSSecurityException ex) { LOG.info("Caught expected security error"); } queue = session.createQueue("GUESTS." + name.getMethodName()); MessageProducer producer = session.createProducer(queue); producer.close(); connection.close(); }
private void ensureConnected() throws JMSException { if (isConnected() || closed.get()) { return; } synchronized(this.connectionId) { if (isConnected() || closed.get()) { return; } if (clientID == null || clientID.trim().isEmpty()) { throw new IllegalArgumentException("Client ID cannot be null or empty string"); } if (!user.isValid()) { executor.shutdown(); throw new JMSSecurityException(user.getFailureCause()); } connected.set(true); } }
private MockJMSConnection createMockConnection(String username, String password) throws JMSException { MockJMSUser user = validateUser(username, password); if (!user.isValid() && !deferAuthenticationToConnection) { throw new JMSSecurityException(user.getFailureCause()); } MockJMSConnection connection = new MockJMSConnection(user); if (clientID != null && !clientID.isEmpty()) { connection.setClientID(clientID, true); } else { connection.setClientID(UUID.randomUUID().toString(), false); } try { connection.initialize(); } catch (JMSException e) { connection.close(); } return connection; }
@Test public void testFailedConnectThenSucceeds() throws JMSException { Connection connection = pooledConnFact.createConnection("invalid", "credentials"); try { connection.start(); fail("Should fail to connect"); } catch (JMSSecurityException ex) { LOG.info("Caught expected security error"); } connection = pooledConnFact.createConnection("system", "manager"); connection.start(); LOG.info("Successfully create new connection."); connection.close(); }
@Test public void testFailedConnectThenSucceedsWithListener() throws JMSException { Connection connection = pooledConnFact.createConnection("invalid", "credentials"); connection.setExceptionListener(new ExceptionListener() { @Override public void onException(JMSException exception) { LOG.warn("Connection get error: {}", exception.getMessage()); } }); try { connection.start(); fail("Should fail to connect"); } catch (JMSSecurityException ex) { LOG.info("Caught expected security error"); } connection = pooledConnFact.createConnection("system", "manager"); connection.start(); LOG.info("Successfully create new connection."); connection.close(); }
@Test public void testFailoverWithInvalidCredentialsCanConnect() throws JMSException { ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory( "failover:(" + connectionURI + ")"); pooledConnFact = new JmsPoolConnectionFactory(); pooledConnFact.setConnectionFactory(cf); pooledConnFact.setMaxConnections(1); Connection connection = pooledConnFact.createConnection("invalid", "credentials"); try { connection.start(); fail("Should fail to connect"); } catch (JMSSecurityException ex) { LOG.info("Caught expected security error"); } connection = pooledConnFact.createConnection("system", "manager"); connection.start(); LOG.info("Successfully create new connection."); connection.close(); }
@Test public void testAutoCreateOnSendToQueueSecurity() throws Exception { ((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().addUser("guest", "guest"); ((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().setDefaultUser("guest"); ((ActiveMQJAASSecurityManager) server.getSecurityManager()).getConfiguration().addRole("guest", "rejectAll"); Role role = new Role("rejectAll", false, false, false, false, false, false, false, false, false, false); Set<Role> roles = new HashSet<>(); roles.add(role); server.getSecurityRepository().addMatch("#", roles); Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = ActiveMQJMSClient.createQueue(QUEUE_NAME); try { session.createProducer(queue); Assert.fail("Sending a message here should throw a JMSSecurityException"); } catch (Exception e) { Assert.assertTrue(e instanceof JMSSecurityException); } connection.close(); }
@Test(timeout = 30000) public void testRepeatedWrongPasswordAttempts() throws Exception { for (int i = 0; i < 25; ++i) { Connection connection = null; try { connection = createConnection(fullUser, "wrongPassword", null, false); connection.start(); fail("Expected JMSException"); } catch (JMSSecurityException ex) { IntegrationTestLogger.LOGGER.debug("Failed to authenticate connection with incorrect password."); } finally { if (connection != null) { connection.close(); } } } }
@Test(timeout = 30000) public void testConsumerNotAuthorized() throws Exception { Connection connection = createConnection(noprivUser, noprivPass); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue(getQueueName()); try { session.createConsumer(queue); fail("Should not be able to consume here."); } catch (JMSSecurityException jmsSE) { IntegrationTestLogger.LOGGER.info("Caught expected exception"); } } finally { connection.close(); } }
@Test(timeout = 30000) public void testBrowserNotAuthorized() throws Exception { Connection connection = createConnection(noprivUser, noprivPass); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue(getQueueName()); try { QueueBrowser browser = session.createBrowser(queue); // Browser is not created until an enumeration is requesteda browser.getEnumeration(); fail("Should not be able to consume here."); } catch (JMSSecurityException jmsSE) { IntegrationTestLogger.LOGGER.info("Caught expected exception"); } } finally { connection.close(); } }
@Test(timeout = 30000) public void testConsumerNotAuthorizedToCreateQueues() throws Exception { Connection connection = createConnection(noprivUser, noprivPass); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue(getQueueName(getPrecreatedQueueSize() + 1)); try { session.createConsumer(queue); fail("Should not be able to consume here."); } catch (JMSSecurityException jmsSE) { IntegrationTestLogger.LOGGER.info("Caught expected exception"); } } finally { connection.close(); } }
@Test(timeout = 30000) public void testProducerNotAuthorized() throws Exception { Connection connection = createConnection(guestUser, guestPass); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue(getQueueName()); try { session.createProducer(queue); fail("Should not be able to produce here."); } catch (JMSSecurityException jmsSE) { IntegrationTestLogger.LOGGER.info("Caught expected exception"); } } finally { connection.close(); } }
@Test(timeout = 30000) public void testAnonymousProducerNotAuthorized() throws Exception { Connection connection = createConnection(guestUser, guestPass); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); javax.jms.Queue queue = session.createQueue(getQueueName()); MessageProducer producer = session.createProducer(null); try { producer.send(queue, session.createTextMessage()); fail("Should not be able to produce here."); } catch (JMSSecurityException jmsSE) { IntegrationTestLogger.LOGGER.info("Caught expected exception"); } } finally { connection.close(); } }
@Test(timeout = 30000) public void testCreateTemporaryQueueNotAuthorized() throws JMSException { Connection connection = createConnection(guestUser, guestPass); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { session.createTemporaryQueue(); } catch (JMSSecurityException jmsse) { IntegrationTestLogger.LOGGER.info("Client should have thrown a JMSSecurityException but only threw JMSException"); } // Should not be fatal assertNotNull(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)); } finally { connection.close(); } }
@Test(timeout = 30000) public void testCreateTemporaryTopicNotAuthorized() throws JMSException { Connection connection = createConnection(guestUser, guestPass); try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { session.createTemporaryTopic(); } catch (JMSSecurityException jmsse) { IntegrationTestLogger.LOGGER.info("Client should have thrown a JMSSecurityException but only threw JMSException"); } // Should not be fatal assertNotNull(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)); } finally { connection.close(); } }
private void doMechanismSelectedTestImpl(String username, String password, Symbol clientSelectedMech, Symbol[] serverMechs, boolean wait) throws Exception { try (TestAmqpPeer testPeer = new TestAmqpPeer();) { testPeer.expectFailingSaslAuthentication(serverMechs, clientSelectedMech); ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + "?jms.clientID=myclientid"); try { factory.createConnection(username, password); fail("Excepted exception to be thrown"); }catch (JMSSecurityException jmsse) { // Expected, we deliberately failed the SASL process, // we only wanted to verify the correct mechanism // was selected, other tests verify the remainder. LOG.info("Caught expected security exception: {}", jmsse.getMessage()); } if (wait) { Thread.sleep(200); } testPeer.waitForAllHandlersToComplete(1000); } }
private void doMechanismSelectionRestrictedTestImpl(String username, String password, Symbol clientSelectedMech, Symbol[] serverMechs, String mechanismsOptionValue) throws Exception { try (TestAmqpPeer testPeer = new TestAmqpPeer();) { testPeer.expectFailingSaslAuthentication(serverMechs, clientSelectedMech); String uriOptions = "?jms.clientID=myclientid"; if(mechanismsOptionValue != null) { uriOptions += "&amqp.saslMechanisms=" + mechanismsOptionValue; } ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions); try { factory.createConnection(username, password); fail("Excepted exception to be thrown"); }catch (JMSSecurityException jmsse) { // Expected, we deliberately failed the SASL process, // we only wanted to verify the correct mechanism // was selected, other tests verify the remainder. } testPeer.waitForAllHandlersToComplete(1000); } }
@Test(timeout = 20000) public void testSaslGssApiKrbConfigError() throws Exception { final String loginConfigScope = "KRB5-CLIENT-DOES-NOT-EXIST"; try (TestAmqpPeer testPeer = new TestAmqpPeer();) { testPeer.expectSaslGSSAPIFail(); String uriOptions = "?sasl.options.configScope=" + loginConfigScope + "&amqp.saslMechanisms=" + GSSAPI; ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions); factory.createConnection(); fail("Expect exception on no login config"); } catch (JMSSecurityException expected) { assertTrue(expected.getMessage().contains(loginConfigScope)); } }
private void doMechanismSelectedTestImpl(String username, String password, Symbol clientSelectedMech, Symbol[] serverMechs, boolean enableGssapiExplicitly) throws Exception { try (TestAmqpPeer testPeer = new TestAmqpPeer();) { testPeer.expectFailingSaslAuthentication(serverMechs, clientSelectedMech); String uriOptions = "?jms.clientID=myclientid"; if(enableGssapiExplicitly) { uriOptions += "&amqp.saslMechanisms=PLAIN," + GSSAPI; } ConnectionFactory factory = new JmsConnectionFactory("amqp://localhost:" + testPeer.getServerPort() + uriOptions); try { factory.createConnection(username, password); fail("Excepted exception to be thrown"); }catch (JMSSecurityException jmsse) { // Expected, we deliberately failed the SASL process, // we only wanted to verify the correct mechanism // was selected, other tests verify the remainder. LOG.info("Caught expected security exception: {}", jmsse.getMessage()); } testPeer.waitForAllHandlersToComplete(1000); } }
@Test public void testContextClosePreservesSessionCloseException() throws JMSException { JmsConnection connection = Mockito.mock(JmsConnection.class); JmsSession session = Mockito.mock(JmsSession.class); Mockito.when(connection.createSession(Mockito.anyInt())).thenReturn(session); JmsContext context = new JmsContext(connection, JMSContext.AUTO_ACKNOWLEDGE); Mockito.doThrow(IllegalStateException.class).when(session).close(); Mockito.doThrow(JMSSecurityException.class).when(connection).close(); context.createTemporaryTopic(); Mockito.verify(connection, Mockito.times(1)).createSession(JMSContext.AUTO_ACKNOWLEDGE); try { context.close(); fail("Should throw ISRE"); } catch (IllegalStateRuntimeException isre) { } }
@Test(timeout = 30000) public void testAnonymousProducerNotAuthorized() throws Exception { connection = createAmqpConnection("guest", "password"); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue("USERS.txQueue"); MessageProducer producer = session.createProducer(null); try { producer.send(queue, session.createTextMessage()); fail("Should not be able to produce here."); } catch (JMSSecurityException jmsSE) { LOG.info("Caught expected exception"); } catch (JMSException jms) { LOG.info("Caught expected exception"); } }
/** * Process the SASL authentication cycle until such time as an outcome is * determine. This method must be called by the managing entity until the * return value is true indicating a successful authentication or a * JMSSecurityException is thrown indicating that the handshake failed. * * @throws JMSSecurityException */ public boolean authenticate() throws JMSSecurityException { switch(sasl.getState()) { case PN_SASL_IDLE: handleSaslInit(); break; case PN_SASL_STEP: handleSaslStep(); break; case PN_SASL_FAIL: handleSaslFail(); break; case PN_SASL_PASS: return true; default: } return false; }
private void handleSaslInit() throws JMSSecurityException { String[] remoteMechanisms = sasl.getRemoteMechanisms(); if (remoteMechanisms != null && remoteMechanisms.length != 0) { mechanism = SaslMechanismFinder.findMatchingMechanism(remoteMechanisms); if (mechanism != null) { mechanism.setUsername(info.getUsername()); mechanism.setPassword(info.getPassword()); // TODO - set additional options from URI. // TODO - set a host value. sasl.setMechanisms(mechanism.getName()); byte[] response = mechanism.getInitialResponse(); if (response != null && response.length != 0) { sasl.send(response, 0, response.length); } } else { // TODO - Better error message. throw new JMSSecurityException("Could not find a matching SASL mechanism for the remote peer."); } } }
public void checkCanProduce(MockJMSDestination destination) throws JMSSecurityException { if (destination == null) { if (isCanProducerAnonymously()) { return; } else { throw new JMSSecurityException("User " + username + " not allowed for create anonymous produders."); } } if (!isCanProduceAll() && !writableDestinations.contains(destination.getName())) { throw new JMSSecurityException("User " + username + " cannot read from destination: " + destination.getName()); } }
@Test public void testCreateUsesCauseIfJMSExceptionPresent() { IOException ioe = new IOException("Ignore me", new JMSSecurityException("error")); JMSException result = JMSExceptionSupport.create(ERROR_MESSAGE, ioe); assertNotNull(result); assertTrue(result instanceof JMSSecurityException); }
@Test public void testConectionCreateAuthentication() throws JMSException { try { cf.createConnection("admin", "admin"); } catch (JMSSecurityException jmsse) { fail("Should not be able to create connection using bad credentials"); } assertEquals(1, cf.getNumConnections()); }
@Test public void testConectionCreateAuthenticationError() throws JMSException { try { cf.createConnection("guest", "guest"); fail("Should not be able to create connection using bad credentials"); } catch (JMSSecurityException jmsse) {} assertEquals(0, cf.getNumConnections()); }
@Test public void testFailedCreateConsumerConnectionStillWorks() throws JMSException { // User can write but not read user.setCanConsumeAll(false); Connection connection = null; try { connection = cf.createConnection("admin", "admin"); } catch (JMSSecurityException jmsse) { fail("Should not be able to create connection using bad credentials"); } connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue("test"); try { session.createConsumer(queue); fail("Should fail to create consumer"); } catch (JMSSecurityException ex) { LOG.debug("Caught expected security error"); } MessageProducer producer = session.createProducer(queue); producer.close(); connection.close(); }
public static JMSRuntimeException convertToRuntimeException(JMSException e) { if (e instanceof javax.jms.IllegalStateException) { return new IllegalStateRuntimeException(e.getMessage(), e.getErrorCode(), e); } if (e instanceof InvalidClientIDException) { return new InvalidClientIDRuntimeException(e.getMessage(), e.getErrorCode(), e); } if (e instanceof InvalidDestinationException) { return new InvalidDestinationRuntimeException(e.getMessage(), e.getErrorCode(), e); } if (e instanceof InvalidSelectorException) { return new InvalidSelectorRuntimeException(e.getMessage(), e.getErrorCode(), e); } if (e instanceof JMSSecurityException) { return new JMSSecurityRuntimeException(e.getMessage(), e.getErrorCode(), e); } if (e instanceof MessageFormatException) { return new MessageFormatRuntimeException(e.getMessage(), e.getErrorCode(), e); } if (e instanceof MessageNotWriteableException) { return new MessageNotWriteableRuntimeException(e.getMessage(), e.getErrorCode(), e); } if (e instanceof ResourceAllocationException) { return new ResourceAllocationRuntimeException(e.getMessage(), e.getErrorCode(), e); } if (e instanceof TransactionInProgressException) { return new TransactionInProgressRuntimeException(e.getMessage(), e.getErrorCode(), e); } if (e instanceof TransactionRolledBackException) { return new TransactionRolledBackRuntimeException(e.getMessage(), e.getErrorCode(), e); } return new JMSRuntimeException(e.getMessage(), e.getErrorCode(), e); }
/** * Verifies that the Device Registry rejects an unauthorized request to open a receiver * link for a tenant. * * @throws JMSException if the test succeeds. */ @Test(expected = JMSSecurityException.class) public void testOpenReceiverNotAllowedForOtherTenant() throws JMSException { final RegistrationTestSupport registrationForOtherTenant = client.getRegistrationTestSupport("someOtherTenant", false); registrationForOtherTenant.createConsumer(); }
/** * Verifies that the Device Registry rejects an unauthorized request to open a sender * link for a tenant. * * @throws JMSException if the test succeeds. */ @Test(expected = JMSSecurityException.class) public void testOpenSenderNotAllowedForOtherTenant() throws JMSException { final RegistrationTestSupport registrationForOtherTenant = client.getRegistrationTestSupport("someOtherTenant", false); registrationForOtherTenant.createProducer(); }
public void testConnectionStartWithUnknownUserThrowsJMSSecurityException() throws Exception { Connection connection = factory.createConnection("badUser", "password"); try { connection.start(); fail("Should throw JMSSecurityException"); } catch (JMSSecurityException jmsEx) { } catch (Exception e) { LOG.info("Expected JMSSecurityException but was: {}", e.getClass()); fail("Should throw JMSSecurityException"); } }
public void testConnectionStartWithDisabledUserThrowsJMSSecurityException() throws Exception { Connection connection = factory.createConnection("disableduser", "password"); try { connection.start(); fail("Should throw JMSSecurityException"); } catch (JMSSecurityException jmsEx) { } catch (Exception e) { LOG.info("Expected JMSSecurityException but was: {}", e.getClass()); fail("Should throw JMSSecurityException"); } }
@Test public void testCreateQueueConnection() throws Exception { ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getSecurityManager(); securityManager.getConfiguration().addUser("IDo", "Exist"); try { QueueConnection queueC = ((QueueConnectionFactory) cf).createQueueConnection("IDont", "Exist"); fail("supposed to throw exception"); queueC.close(); } catch (JMSSecurityException e) { // expected } JMSContext ctx = cf.createContext("IDo", "Exist"); ctx.close(); }
@Test public void testCreateTempDestinationAuthorization() throws Exception { Connection conn1 = null; Connection conn2 = null; //Sender try { conn1 = factory.createConnection("openwireGuest", "GuEsT"); conn1.start(); conn2 = factory.createConnection("openwireDestinationManager", "DeStInAtIoN"); conn2.start(); Session session1 = conn1.createSession(false, Session.AUTO_ACKNOWLEDGE); try { session1.createTemporaryQueue(); fail("user shouldn't be able to create temp queue"); } catch (JMSSecurityException e) { //expected } Session session2 = conn2.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue q = session2.createTemporaryQueue(); assertNotNull(q); } finally { if (conn1 != null) { conn1.close(); } if (conn2 != null) { conn2.close(); } } }
@Test(timeout = 10000) public void testNoUserOrPassword() throws Exception { Connection connection = null; try { connection = createConnection("", "", null, false); connection.start(); fail("Expected JMSException"); } catch (JMSSecurityException ex) { IntegrationTestLogger.LOGGER.debug("Failed to authenticate connection with no user / password."); } finally { if (connection != null) { connection.close(); } } }
@Test(timeout = 10000) public void testUnknownUser() throws Exception { Connection connection = null; try { connection = createConnection("nosuchuser", "blah", null, false); connection.start(); fail("Expected JMSException"); } catch (JMSSecurityException ex) { IntegrationTestLogger.LOGGER.debug("Failed to authenticate connection with unknown user ID"); } finally { if (connection != null) { connection.close(); } } }
@Test(timeout = 10000) public void testKnownUserWrongPassword() throws Exception { Connection connection = null; try { connection = createConnection(fullUser, "wrongPassword", null, false); connection.start(); fail("Expected JMSException"); } catch (JMSSecurityException ex) { IntegrationTestLogger.LOGGER.debug("Failed to authenticate connection with incorrect password."); } finally { if (connection != null) { connection.close(); } } }
@Test(timeout = 600000) public void testSaslPlainConnectionDenied() throws Exception { JmsConnectionFactory factory = new JmsConnectionFactory(new URI("amqp://localhost:" + AMQP_PORT + "?amqp.saslMechanisms=PLAIN")); try { factory.createConnection("plain", "secret"); fail("Expect sasl failure"); } catch (JMSSecurityException expected) { assertTrue(expected.getMessage().contains("SASL")); } }
public void testConnectionStartThrowsJMSSecurityException() throws Exception { Connection connection = factory.createConnection("badUser", "password"); try { connection.start(); fail("Should throw JMSSecurityException"); } catch (JMSSecurityException jmsEx) { } catch (Exception e) { LOG.info("Expected JMSSecurityException but was: {}", e.getClass()); fail("Should throw JMSSecurityException"); } }