You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@artemis.apache.org by cl...@apache.org on 2026/09/10 17:09:14 UTC
(artemis) 01/11: Improve Core connection handshake
This is an automated email from the ASF dual-hosted git repository.
clebertsuconic pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/artemis.git
commit 8542c574f020cbd31ea2c0d9cb81cae160ea88d0
Author: Domenico Francesco Bruscino <br...@apache.org>
AuthorDate: Mon Jul 13 08:35:56 2026 +0200
Improve Core connection handshake
Replace the legacy failover-check packet with ConnectMessage and
ConnectResponseMessage, adding optional connection authentication and
client/server version fields. Propagate credentials through cluster
links, JMS, and management clients via createSessionFactory and
setConnectionCredentials. Add configurable Core frame size limits
and connection handshake settings on acceptors, with docs and tests.
Assisted-by: Cursor
(cherry picked from commit 51b067484e3581d261fb755fb80483584ed1aed6)
ARTEMIS-6244
---
.../cli/commands/tools/xml/XmlDataImporter.java | 2 +-
.../artemis/api/config/ServerLocatorConfig.java | 6 +
.../artemis/api/core/client/ServerLocator.java | 16 ++
.../core/management/ActiveMQManagementProxy.java | 2 +-
.../api/core/management/ManagementHelper.java | 2 +-
.../api/core/management/SimpleManagement.java | 2 +-
.../artemis/core/client/ActiveMQClientLogger.java | 3 +
.../core/client/impl/ClientSessionFactoryImpl.java | 101 ++++---
.../core/client/impl/ServerLocatorImpl.java | 22 +-
.../artemis/core/client/impl/Topology.java | 3 +
.../core/impl/ActiveMQClientProtocolManager.java | 18 +-
.../core/protocol/core/impl/ChannelImpl.java | 8 +-
.../core/protocol/core/impl/PacketDecoder.java | 15 +-
.../core/protocol/core/impl/PacketImpl.java | 24 +-
.../core/impl/wireformat/CheckFailoverMessage.java | 55 ----
.../impl/wireformat/CheckFailoverReplyMessage.java | 60 ----
.../core/impl/wireformat/ConnectMessage.java | 301 +++++++++++++++++++++
.../impl/wireformat/ConnectResponseMessage.java | 136 ++++++++++
.../core/remoting/AuthenticationListener.java | 25 ++
.../impl/netty/CoreFrameWithSizeLimitDecoder.java | 68 +++++
.../core/protocol/AbstractRemotingConnection.java | 37 +++
.../spi/core/protocol/RemotingConnection.java | 28 ++
.../spi/core/remoting/ClientProtocolManager.java | 2 +-
.../core/impl/wireformat/ConnectMessageTest.java | 214 +++++++++++++++
.../wireformat/ConnectResponseMessageTest.java | 74 +++++
.../protocol/AbstractRemotingConnectionTest.java | 190 +++++++++++++
.../jms/client/ActiveMQConnectionFactory.java | 7 +-
.../junit/AbstractActiveMQClientDelegate.java | 2 +-
.../activemq/artemis/maven/ArtemisCLIPlugin.java | 2 +-
.../amqp/client/ProtonClientProtocolManager.java | 2 +-
.../amqp/connect/AMQPBrokerConnectionManager.java | 2 +-
.../client/HornetQClientProtocolManager.java | 4 +-
.../artemis/ra/ActiveMQResourceAdapter.java | 9 +
.../artemis/ra/inflow/ActiveMQActivation.java | 2 +-
.../impl/ManagementRemotingConnection.java | 19 ++
.../protocol/core/impl/ActiveMQPacketHandler.java | 50 +++-
.../protocol/core/impl/CoreProtocolManager.java | 136 +++++++++-
.../core/security/impl/SecurityStoreImpl.java | 4 +
.../artemis/core/server/ActiveMQMessageBundle.java | 2 +
.../artemis/core/server/ActiveMQServerLogger.java | 6 +
.../activemq/artemis/core/server/NodeLocator.java | 8 -
.../artemis/core/server/cluster/BackupManager.java | 1 +
.../core/server/cluster/ClusterController.java | 20 +-
.../core/server/cluster/ClusterManager.java | 1 +
.../core/server/cluster/impl/BridgeImpl.java | 2 +-
.../server/cluster/impl/ClusterConnectionImpl.java | 4 +
.../server/federation/FederationConnection.java | 2 +-
.../server/impl/BackupRecoveryJournalLoader.java | 2 +-
.../core/server/impl/PrimaryOnlyActivation.java | 3 +-
.../server/impl/ReplicationBackupActivation.java | 9 +-
.../server/impl/SharedNothingBackupActivation.java | 62 +++--
.../impl/SharedNothingPrimaryActivation.java | 3 +-
.../server/routing/targets/ActiveMQTarget.java | 2 +-
.../core/impl/ActiveMQPacketHandlerTest.java | 262 ++++++++++++++++++
.../core/security/impl/SecurityStoreImplTest.java | 37 +++
.../xa/recovery/ActiveMQXAResourceWrapper.java | 2 +-
docs/user-manual/core.adoc | 68 +++++
docs/user-manual/versions.adoc | 12 +
.../multiVersionReplica/mainServer.groovy | 3 +-
.../compatibility/MultiVersionReplicaTest.java | 4 +-
.../client/CoreConnectHandshakeTest.java | 124 +++++++++
.../cluster/failover/BackupAuthenticationTest.java | 34 +--
.../cluster/failover/SecurityFailoverTest.java | 9 +
.../LockManagerBackupAuthenticationTest.java | 36 +--
...ListenerForConnectionTimedOutExceptionTest.java | 4 +-
.../compat/HQClientProtocolManagerTest.java | 2 +-
.../netty/CoreFrameWithSizeLimitDecoderTest.java | 77 ++++++
.../activemq/artemis/common/AbstractAdmin.java | 1 +
.../artemis/tests/unit/ra/ResourceAdapterTest.java | 45 ++-
69 files changed, 2209 insertions(+), 291 deletions(-)
diff --git a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/xml/XmlDataImporter.java b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/xml/XmlDataImporter.java
index 4c3780fdae..63865b4a83 100644
--- a/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/xml/XmlDataImporter.java
+++ b/artemis-cli/src/main/java/org/apache/activemq/artemis/cli/commands/tools/xml/XmlDataImporter.java
@@ -182,7 +182,7 @@ public final class XmlDataImporter extends ConnectionConfigurationAbtract {
} else {
serverLocator = ActiveMQClient.createServerLocator(brokerURL);
}
- ClientSessionFactory sf = serverLocator.createSessionFactory();
+ ClientSessionFactory sf = serverLocator.createSessionFactory(user, password);
ClientSession session = null;
ClientSession managementSession = null;
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/config/ServerLocatorConfig.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/config/ServerLocatorConfig.java
index cd57f98449..96a146c696 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/config/ServerLocatorConfig.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/config/ServerLocatorConfig.java
@@ -53,6 +53,10 @@ public class ServerLocatorConfig {
public boolean compressLargeMessage = ActiveMQClient.DEFAULT_COMPRESS_LARGE_MESSAGES;
public boolean useTopologyForLoadBalancing = ActiveMQClient.DEFAULT_USE_TOPOLOGY_FOR_LOADBALANCING;
+ public String connectionUser;
+
+ public String connectionPassword;
+
public ServerLocatorConfig() {
}
@@ -89,5 +93,7 @@ public class ServerLocatorConfig {
initialMessagePacketSize = locator.initialMessagePacketSize;
useTopologyForLoadBalancing = locator.useTopologyForLoadBalancing;
compressionLevel = locator.compressionLevel;
+ connectionUser = locator.connectionUser;
+ connectionPassword = locator.connectionPassword;
}
}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ServerLocator.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ServerLocator.java
index 0f6848f8bf..9bee04b649 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ServerLocator.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/client/ServerLocator.java
@@ -58,6 +58,15 @@ public interface ServerLocator extends AutoCloseable {
*/
ClientSessionFactory createSessionFactory() throws Exception;
+ /**
+ * Creates a ClientSessionFactory using whatever load balancing policy is in force
+ *
+ * @param connectionUser connection user
+ * @param connectionPassword connection password
+ * @return The ClientSessionFactory
+ */
+ ClientSessionFactory createSessionFactory(String connectionUser, String connectionPassword) throws Exception;
+
/**
* Creates a {@link ClientSessionFactory} to a specific server. The server must already be known about by this
* ServerLocator. This method allows the user to make a connection to a specific server bypassing any load balancing
@@ -893,4 +902,11 @@ public interface ServerLocator extends AutoCloseable {
ServerLocator setPasswordCodec(String passwordCodec);
String getPasswordCodec();
+
+ /**
+ * Sets connection-level credentials sent in {@code CONNECT} after connecting.
+ *
+ * @return this
+ */
+ ServerLocator setConnectionCredentials(String connectionUser, String connectionPassword);
}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQManagementProxy.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQManagementProxy.java
index 6df336a7c3..3d010aa072 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQManagementProxy.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQManagementProxy.java
@@ -41,7 +41,7 @@ public class ActiveMQManagementProxy implements AutoCloseable {
public ActiveMQManagementProxy(final ServerLocator locator, final String username, final String password) throws Exception {
serverLocator = locator;
- sessionFactory = locator.createSessionFactory();
+ sessionFactory = locator.createSessionFactory(username, password);
clientSession = sessionFactory.createSession(username, password, false, true, true, false, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE).start();
}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java
index f63a6ea90c..76af6a7504 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ManagementHelper.java
@@ -106,7 +106,7 @@ public final class ManagementHelper {
}
public static void doManagement(ServerLocator locator, String user, String password, MessageAcceptor setup, MessageAcceptor ok, MessageAcceptor failed) throws Exception {
- try (ClientSessionFactory sessionFactory = locator.createSessionFactory();
+ try (ClientSessionFactory sessionFactory = locator.createSessionFactory(user, password);
ClientSession session = sessionFactory.createSession(user, password, false, true, true, false, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE)) {
doManagement(session, setup, ok, failed);
}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/SimpleManagement.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/SimpleManagement.java
index dbf1f61112..f904dd50c6 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/SimpleManagement.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/SimpleManagement.java
@@ -62,7 +62,7 @@ public class SimpleManagement implements AutoCloseable {
public SimpleManagement open() throws Exception {
if (session == null) {
locator = ServerLocatorImpl.newLocator(uri);
- sessionFactory = locator.createSessionFactory();
+ sessionFactory = locator.createSessionFactory(user, password);
session = sessionFactory.createSession(user, password, false, true, true, false, ActiveMQClient.DEFAULT_ACK_BATCH_SIZE);
}
return this;
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientLogger.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientLogger.java
index ce5007d0a0..314bd8b4b9 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientLogger.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/ActiveMQClientLogger.java
@@ -352,4 +352,7 @@ public interface ActiveMQClientLogger {
@LogMessage(id = 214036, value = "Connection closure to {} has been detected: {} [code={}]", level = LogMessage.Level.INFO)
void connectionClosureDetected(String remoteAddress, String message, ActiveMQExceptionType type);
+
+ @LogMessage(id = 214037, value = "Failed to execute authentication listener", level = LogMessage.Level.ERROR)
+ void errorCallingAuthenticationListener(Throwable e);
}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryImpl.java
index 267d38f03b..999fe90456 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryImpl.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ClientSessionFactoryImpl.java
@@ -166,6 +166,10 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
private final TransportConfiguration[] connectorConfigs;
+ private final String connectionUser;
+
+ private final String connectionPassword;
+
public ClientSessionFactoryImpl(final ServerLocatorInternal serverLocator,
final TransportConfiguration connectorConfig,
final ServerLocatorConfig locatorConfig,
@@ -175,12 +179,11 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
final Executor flowControlThreadPool,
final List<Interceptor> incomingInterceptors,
final List<Interceptor> outgoingInterceptors) {
- this(serverLocator, new Pair<>(connectorConfig, null),
- locatorConfig, reconnectAttempts, threadPool,
- scheduledThreadPool, flowControlThreadPool, incomingInterceptors, outgoingInterceptors);
+ this(serverLocator, new Pair<>(connectorConfig, null), locatorConfig, reconnectAttempts, threadPool,
+ scheduledThreadPool, flowControlThreadPool, incomingInterceptors, outgoingInterceptors, null,
+ locatorConfig.connectionUser, locatorConfig.connectionPassword);
}
-
ClientSessionFactoryImpl(final ServerLocatorInternal serverLocator,
final Pair<TransportConfiguration, TransportConfiguration> connectorConfig,
final ServerLocatorConfig locatorConfig,
@@ -189,22 +192,10 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
final ScheduledExecutorService scheduledThreadPool,
final Executor flowControlThreadPool,
final List<Interceptor> incomingInterceptors,
- final List<Interceptor> outgoingInterceptors) {
- this(serverLocator, connectorConfig,
- locatorConfig, reconnectAttempts, threadPool,
- scheduledThreadPool, flowControlThreadPool, incomingInterceptors, outgoingInterceptors, null);
- }
-
- ClientSessionFactoryImpl(final ServerLocatorInternal serverLocator,
- final Pair<TransportConfiguration, TransportConfiguration> connectorConfig,
- final ServerLocatorConfig locatorConfig,
- final int reconnectAttempts,
- final Executor threadPool,
- final ScheduledExecutorService scheduledThreadPool,
- final Executor flowControlThreadPool,
- final List<Interceptor> incomingInterceptors,
- final List<Interceptor> outgoingInterceptors,
- final TransportConfiguration[] connectorConfigs) {
+ final List<Interceptor> outgoingInterceptors,
+ final TransportConfiguration[] connectorConfigs,
+ final String connectionUser,
+ final String connectionPassword) {
this.serverLocator = serverLocator;
this.clientProtocolManager = serverLocator.newProtocolManager();
@@ -268,6 +259,10 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
}
this.connectorConfigs = connectorConfigs;
+
+ this.connectionUser = connectionUser;
+
+ this.connectionPassword = connectionPassword;
}
@Override
@@ -279,7 +274,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
@Override
public void connect(final int initialConnectAttempts) throws ActiveMQException {
// Get the connection
- getConnectionWithRetry(initialConnectAttempts, null);
+ internalConnectWithRetry(initialConnectAttempts, null);
if (connection == null) {
StringBuilder msg = new StringBuilder("Unable to connect to server using configuration ").append(currentConnectorConfig);
@@ -689,7 +684,11 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
while (reconnectRetryPredicate.test(sessionsReconnected, reconnectRetries)) {
int remainingReconnectRetries = reconnectAttempts == -1 ? -1 : reconnectAttempts - reconnectRetries;
- reconnectRetries += getConnectionWithRetry(remainingReconnectRetries, oldConnection);
+ try {
+ reconnectRetries += internalConnectWithRetry(remainingReconnectRetries, oldConnection);
+ } catch (ActiveMQException ignore) {
+ reconnectRetries++;
+ }
if (connection != null) {
sessionsReconnected = reconnectSessions(sessionsToFailover, oldConnection, me);
@@ -934,7 +933,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
return !sessionFailoverError;
}
- private int getConnectionWithRetry(final int reconnectAttempts, RemotingConnection oldConnection) {
+ private int internalConnectWithRetry(final int reconnectAttempts, RemotingConnection oldConnection) throws ActiveMQException {
if (!clientProtocolManager.isAlive()) {
return 0;
}
@@ -952,8 +951,8 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
logger.debug("Trying reconnection attempt {}/{}", count, reconnectAttempts);
}
- if (getConnection() != null) {
- if (oldConnection != null && oldConnection instanceof CoreRemotingConnection oldRemotingConnection) {
+ if (internalConnect() != null) {
+ if (oldConnection instanceof CoreRemotingConnection oldRemotingConnection) {
// transferring old connection version into the new connection
((CoreRemotingConnection)connection).setChannelVersion(oldRemotingConnection.getChannelVersion());
}
@@ -1042,12 +1041,20 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
}
}
+ @Override
+ public RemotingConnection getConnection() {
+ try {
+ return internalConnect();
+ } catch (ActiveMQException ignore) {
+ return null;
+ }
+ }
+
//The order of connector configs to try to get a connection:
//currentConnectorConfig, backupConfig and then lastConnectorConfig.
//On each successful connect, the current and last will be
//updated properly.
- @Override
- public RemotingConnection getConnection() {
+ public RemotingConnection internalConnect() throws ActiveMQException {
if (closed) {
throw new IllegalStateException("ClientSessionFactory is closed!");
}
@@ -1063,12 +1070,33 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
this.connection = connection;
+ if (connection != null) {
+ if (logger.isTraceEnabled()) {
+ logger.trace("Initialize connection with user {} from {} to {} ", connectionUser,
+ connection.getTransportLocalAddress(), connection.getRemoteAddress(), new Exception("trace"));
+ }
+ }
+
//we check if we can actually connect.
// we do it here as to receive the reply connection has to be not null
//make sure to reset this.connection == null
- if (connection != null && primaryNodeID != null) {
+ if (connection != null && (primaryNodeID != null || connectionUser != null)) {
try {
- if (!clientProtocolManager.checkForFailover(primaryNodeID)) {
+ String connectionUser = this.connectionUser;
+ String connectionPassword = this.connectionPassword;
+
+ if (connectionUser != null) {
+ try {
+ connectionUser = PasswordMaskingUtil.resolveMask(connectionUser, serverLocator.getPasswordCodec());
+ connectionPassword = PasswordMaskingUtil.resolveMask(connectionPassword, serverLocator.getPasswordCodec());
+ } catch (Exception e) {
+ connection.destroy();
+ this.connection = null;
+ throw new ActiveMQException(e.getMessage(), e, ActiveMQExceptionType.GENERIC_EXCEPTION);
+ }
+ }
+
+ if (!clientProtocolManager.sendConnect(primaryNodeID, connectionUser, connectionPassword)) {
connection.destroy();
this.connection = null;
return null;
@@ -1076,7 +1104,7 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
} catch (ActiveMQException e) {
connection.destroy();
this.connection = null;
- return null;
+ throw e;
}
}
@@ -1526,12 +1554,15 @@ public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, C
boolean isLast) {
try {
- // if it is our connector then set the primary id used for failover
- if (connectorPair.getA() != null && TransportConfigurationUtil.isSameHost(connectorPair.getA(), currentConnectorConfig)) {
- primaryNodeID = nodeID;
- }
+ // Skip notifications for PRE_AUTH_NODE_ID
+ if (!Topology.PRE_AUTH_NODE_ID.equals(nodeID)) {
+ // if it is our connector then set the primary id used for failover
+ if (connectorPair.getA() != null && TransportConfigurationUtil.isSameHost(connectorPair.getA(), currentConnectorConfig)) {
+ primaryNodeID = nodeID;
+ }
- serverLocator.notifyNodeUp(uniqueEventID, nodeID, backupGroupName, scaleDownGroupName, connectorPair, isLast);
+ serverLocator.notifyNodeUp(uniqueEventID, nodeID, backupGroupName, scaleDownGroupName, connectorPair, isLast);
+ }
} finally {
if (isLast) {
topologyReady = true;
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorImpl.java
index b8d05736b4..6a53e704f4 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorImpl.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/ServerLocatorImpl.java
@@ -45,6 +45,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQExceptionType;
import org.apache.activemq.artemis.api.core.ActiveMQIllegalStateException;
import org.apache.activemq.artemis.api.core.ActiveMQInternalErrorException;
import org.apache.activemq.artemis.api.core.ActiveMQInterruptedException;
+import org.apache.activemq.artemis.api.core.ActiveMQSecurityException;
import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration;
import org.apache.activemq.artemis.api.core.Interceptor;
import org.apache.activemq.artemis.api.core.Pair;
@@ -326,6 +327,14 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
return this.passwordCodec;
}
+ @Override
+ public ServerLocatorImpl setConnectionCredentials(final String connectionUser, final String connectionPassword) {
+ checkWrite();
+ config.connectionUser = connectionUser;
+ config.connectionPassword = connectionPassword;
+ return this;
+ }
+
private static DiscoveryGroup createDiscoveryGroup(String nodeID,
DiscoveryGroupConfiguration config) throws Exception {
return new DiscoveryGroup(nodeID, config.getName(), config.getRefreshTimeout(), config.getStoppingTimeout(), config.getBroadcastEndpointFactory(), null);
@@ -671,6 +680,11 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
@Override
public ClientSessionFactory createSessionFactory() throws ActiveMQException {
+ return createSessionFactory(config.connectionUser, config.connectionPassword);
+ }
+
+ @Override
+ public ClientSessionFactory createSessionFactory(String connectionUser, String connectionPassword) throws ActiveMQException {
assertOpen();
initialize();
@@ -707,7 +721,9 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
// try each factory in the list until we find one which works
try {
- factory = new ClientSessionFactoryImpl(this, tc, config, config.reconnectAttempts, threadPool, scheduledThreadPool, flowControlThreadPool, incomingInterceptors, outgoingInterceptors, initialConnectors);
+ factory = new ClientSessionFactoryImpl(this, tc, config, config.reconnectAttempts, threadPool,
+ scheduledThreadPool, flowControlThreadPool, incomingInterceptors, outgoingInterceptors, initialConnectors,
+ connectionUser, connectionPassword);
try {
addToConnecting(factory);
// We always try to connect here with only one attempt,
@@ -1824,6 +1840,8 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
}
logger.trace("Rejected execution", e);
throw e;
+ } catch (ActiveMQSecurityException e) {
+ throw e;
} catch (Exception e) {
if (isClosed() || skipWarnings) {
return null;
@@ -1894,6 +1912,8 @@ public final class ServerLocatorImpl implements ServerLocatorInternal, Discovery
}
}
return factoryToUse;
+ } catch (ActiveMQSecurityException e) {
+ throw e;
} catch (ActiveMQException e) {
logger.trace("{}::Exception on establish connector initial connection", this, e);
return null;
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/Topology.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/Topology.java
index 99ff680447..c24c1d1e29 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/Topology.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/client/impl/Topology.java
@@ -43,6 +43,9 @@ public final class Topology {
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
+ public static final String PRE_AUTH_NODE_ID = "00000000-0000-0000-0000-000000000000";
+ public static final String PRE_AUTH_CONNECTOR_NAME = "PRE_AUTH_CONNECTOR";
+
private final Set<ClusterTopologyListener> topologyListeners;
private Executor executor;
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManager.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManager.java
index 97ff1fbd43..5e3f3d5858 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManager.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQClientProtocolManager.java
@@ -42,8 +42,8 @@ import org.apache.activemq.artemis.core.protocol.core.Channel;
import org.apache.activemq.artemis.core.protocol.core.ChannelHandler;
import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection;
import org.apache.activemq.artemis.core.protocol.core.Packet;
-import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverMessage;
-import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverReplyMessage;
+import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ConnectMessage;
+import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ConnectResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterTopologyChangeMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterTopologyChangeMessage_V2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterTopologyChangeMessage_V3;
@@ -424,9 +424,13 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager {
}
@Override
- public boolean checkForFailover(String nodeID) throws ActiveMQException {
- CheckFailoverMessage packet = new CheckFailoverMessage(nodeID);
- CheckFailoverReplyMessage message = (CheckFailoverReplyMessage) getChannel1().sendBlocking(packet, PacketImpl.CHECK_FOR_FAILOVER_REPLY);
+ public boolean sendConnect(String nodeID, String connectionUser, String connectionPassword) throws ActiveMQException {
+ int clientVersion = VersionLoader.getVersion().getIncrementingVersion();
+ ConnectMessage packet = (connectionUser != null)
+ ? ConnectMessage.withPlainCredentials(nodeID, clientVersion, connectionUser, connectionPassword)
+ : new ConnectMessage(nodeID, clientVersion);
+ ConnectResponseMessage message = (ConnectResponseMessage) getChannel1().sendBlocking(packet, PacketImpl.CONNECT_RESPONSE);
+ connection.setChannelVersion(message.getServerVersion());
return message.isOkToFailover();
}
@@ -497,8 +501,8 @@ public class ActiveMQClientProtocolManager implements ClientProtocolManager {
ClusterTopologyChangeMessage_V4 topMessage = (ClusterTopologyChangeMessage_V4) packet;
notifyTopologyChange(updateTransportConfiguration(topMessage));
connection.setChannelVersion(topMessage.getServerVersion());
- } else if (type == PacketImpl.CHECK_FOR_FAILOVER_REPLY) {
- System.out.println("Channel0Handler.handlePacket");
+ } else if (type == PacketImpl.CONNECT_RESPONSE) {
+ logger.debug("Handle connect response: {}", packet);
}
}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImpl.java
index bc33403ed6..f2d5c9cfec 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImpl.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ChannelImpl.java
@@ -241,7 +241,13 @@ public final class ChannelImpl implements Channel {
if (responseAsyncCache != null) {
responseAsyncCache.errorAll(activeMQException);
}
- response = new ActiveMQExceptionMessage(activeMQException);
+
+ // Preserve an already-delivered EXCEPTION (e.g. security failure that raced with connection
+ // close) over AMQ219016. Other packets could not unblock sendBlocking unless type and
+ // correlation match, so replacing them here is fine.
+ if (response == null || response.getType() != EXCEPTION) {
+ response = new ActiveMQExceptionMessage(activeMQException);
+ }
sendCondition.signal();
} finally {
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketDecoder.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketDecoder.java
index e2d2f22d46..d33f1a797f 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketDecoder.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketDecoder.java
@@ -24,8 +24,8 @@ import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection;
import org.apache.activemq.artemis.core.protocol.core.Packet;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQExceptionMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQExceptionMessage_V2;
-import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverMessage;
-import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverReplyMessage;
+import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ConnectMessage;
+import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ConnectResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterTopologyChangeMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterTopologyChangeMessage_V2;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ClusterTopologyChangeMessage_V3;
@@ -100,7 +100,7 @@ import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionXAS
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SubscribeClusterTopologyUpdatesMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SubscribeClusterTopologyUpdatesMessageV2;
-import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CHECK_FOR_FAILOVER;
+import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CONNECT;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CLUSTER_TOPOLOGY;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CLUSTER_TOPOLOGY_V2;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CLUSTER_TOPOLOGY_V3;
@@ -122,6 +122,7 @@ import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.EXC
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.FEDERATION_DOWNSTREAM_CONNECT;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.NULL_RESPONSE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.PACKETS_CONFIRMED;
+import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.CONNECT_RESPONSE;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.PING;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.REATTACH_SESSION;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.REATTACH_SESSION_RESP;
@@ -223,8 +224,8 @@ public abstract class PacketDecoder implements Serializable {
packet = new CreateSessionMessage();
break;
}
- case CHECK_FOR_FAILOVER: {
- packet = new CheckFailoverMessage();
+ case CONNECT: {
+ packet = new ConnectMessage();
break;
}
case CREATESESSION_RESP: {
@@ -485,8 +486,8 @@ public abstract class PacketDecoder implements Serializable {
packet = new SessionUniqueAddMetaDataMessage();
break;
}
- case PacketImpl.CHECK_FOR_FAILOVER_REPLY: {
- packet = new CheckFailoverReplyMessage();
+ case CONNECT_RESPONSE: {
+ packet = new ConnectResponseMessage();
break;
}
case PacketImpl.DISCONNECT_CONSUMER_KILL: {
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketImpl.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketImpl.java
index e6406ef727..6d9ef60390 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketImpl.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/PacketImpl.java
@@ -272,9 +272,29 @@ public class PacketImpl implements Packet {
public static final byte QUORUM_VOTE_REPLY = -3;
- public static final byte CHECK_FOR_FAILOVER = -4;
+ /**
+ * Core connect handshake sent after the transport is established.
+ * Reuses wire packet ID {@code -4}, formerly {@link #CHECK_FOR_FAILOVER}.
+ */
+ public static final byte CONNECT = -4;
+
+ /**
+ * @deprecated Renamed to {@link #CONNECT}; retained for the same wire packet ID ({@code -4}).
+ */
+ @Deprecated
+ public static final byte CHECK_FOR_FAILOVER = CONNECT;
- public static final byte CHECK_FOR_FAILOVER_REPLY = -5;
+ /**
+ * Response to a {@link #CONNECT} packet.
+ * Reuses wire packet ID {@code -5}, formerly {@link #CHECK_FOR_FAILOVER_REPLY}.
+ */
+ public static final byte CONNECT_RESPONSE = -5;
+
+ /**
+ * @deprecated Renamed to {@link #CONNECT_RESPONSE}; retained for the same wire packet ID ({@code -5}).
+ */
+ @Deprecated
+ public static final byte CHECK_FOR_FAILOVER_REPLY = CONNECT_RESPONSE;
public static final byte SCALEDOWN_ANNOUNCEMENT = -6;
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverMessage.java
deleted file mode 100644
index 807fe1f812..0000000000
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverMessage.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.activemq.artemis.core.protocol.core.impl.wireformat;
-
-import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
-import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;
-
-public class CheckFailoverMessage extends PacketImpl {
-
- private String nodeID;
-
- public CheckFailoverMessage(final String nodeID) {
- super(CHECK_FOR_FAILOVER);
- this.nodeID = nodeID;
- }
-
- public CheckFailoverMessage() {
- super(CHECK_FOR_FAILOVER);
- }
-
- @Override
- public void encodeRest(ActiveMQBuffer buffer) {
- buffer.writeNullableString(nodeID);
- }
-
- @Override
- public void decodeRest(ActiveMQBuffer buffer) {
- nodeID = buffer.readNullableString();
- }
-
- @Override
- protected String getPacketString() {
- StringBuilder sb = new StringBuilder(super.getPacketString());
- sb.append(", nodeID=" + nodeID);
- return sb.toString();
- }
-
- public String getNodeID() {
- return nodeID;
- }
-}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverReplyMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverReplyMessage.java
deleted file mode 100644
index af3e48f278..0000000000
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/CheckFailoverReplyMessage.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.activemq.artemis.core.protocol.core.impl.wireformat;
-
-import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
-import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;
-
-public class CheckFailoverReplyMessage extends PacketImpl {
-
- private boolean okToFailover;
-
- public CheckFailoverReplyMessage(boolean okToFailover) {
- super(CHECK_FOR_FAILOVER_REPLY);
- this.okToFailover = okToFailover;
- }
-
- public CheckFailoverReplyMessage() {
- super(CHECK_FOR_FAILOVER_REPLY);
- }
-
- @Override
- public boolean isResponse() {
- return true;
- }
-
- @Override
- public void encodeRest(ActiveMQBuffer buffer) {
- buffer.writeBoolean(okToFailover);
- }
-
- @Override
- public void decodeRest(ActiveMQBuffer buffer) {
- okToFailover = buffer.readBoolean();
- }
-
- @Override
- protected String getPacketString() {
- StringBuilder sb = new StringBuilder(super.getPacketString());
- sb.append(", okToFailover=" + okToFailover);
- return sb.toString();
- }
-
- public boolean isOkToFailover() {
- return okToFailover;
- }
-}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectMessage.java
new file mode 100644
index 0000000000..28f1e3d99c
--- /dev/null
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectMessage.java
@@ -0,0 +1,301 @@
+/*
+ * 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.activemq.artemis.core.protocol.core.impl.wireformat;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Objects;
+
+import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
+import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;
+import org.apache.activemq.artemis.utils.AbstractMapPersister;
+
+/**
+ * Core connect handshake sent after the transport is established.
+ * <p>
+ * Replaces the former {@code CheckFailoverMessage} on the same wire packet ID
+ * ({@link PacketImpl#CONNECT}, {@code -4}). The node id field is unchanged;
+ * optional client version and auth fields may follow as extension fields for
+ * backward-compatible decoding.
+ * <p>
+ * Supported auth mechanisms:
+ * <ul>
+ * <li>{@link #MECHANISM_PLAIN} – SASL PLAIN as defined in
+ * <a href="https://www.rfc-editor.org/rfc/rfc4616">RFC 4616</a>;
+ * {@code FIELD_AUTH_DATA} encodes
+ * {@code authzid NUL authcid NUL passwd} as UTF-8 bytes,
+ * where {@code authzid} (authorization identity) is always empty.</li>
+ * </ul>
+ */
+public class ConnectMessage extends PacketImpl {
+
+ /**
+ * SASL PLAIN mechanism name as defined in
+ * <a href="https://www.rfc-editor.org/rfc/rfc4616">RFC 4616</a>.
+ */
+ public static final String MECHANISM_PLAIN = "PLAIN";
+
+ static final short FIELD_CLIENT_VERSION = 1;
+ /**
+ * Auth mechanism name, e.g. {@code "PLAIN"}.
+ */
+ static final short FIELD_AUTH_MECHANISM = 2;
+ /**
+ * Auth data bytes. For PLAIN (RFC 4616):
+ * {@code authzid NUL authcid NUL passwd} encoded as UTF-8,
+ * where {@code authzid} is always empty.
+ */
+ static final short FIELD_AUTH_DATA = 3;
+
+ // ConnectMapSerializer is stateless and safe to be used from multiple threads.
+ // The state needed is on ConnectMessage and ActiveMQBuffer only
+ private static final ConnectMapSerializer mapSerializer = new ConnectMapSerializer();
+
+ private static class ConnectMapSerializer extends AbstractMapPersister<ConnectMessage> {
+ public void encode(ActiveMQBuffer buffer, ConnectMessage message) {
+ int headerPosition = buffer.writerIndex();
+ writeHeader(buffer, 0, 0); // to reserve the header, will be rewritten at the end
+
+ int fields = 0;
+
+ if (message.clientVersion > 0) {
+ writeInteger(buffer, FIELD_CLIENT_VERSION, message.clientVersion);
+ fields++;
+ }
+
+ if (message.authMechanism != null) {
+ writeString(buffer, FIELD_AUTH_MECHANISM, message.authMechanism);
+ fields++;
+ }
+
+ if (message.authData != null) {
+ byte[] data = message.authData;
+ writeByteArray(buffer, FIELD_AUTH_DATA, data.length, buf -> buf.writeBytes(data));
+ fields++;
+ }
+
+ int endPosition = buffer.writerIndex();
+ buffer.writerIndex(headerPosition);
+ writeHeader(buffer, endPosition - headerPosition, fields);
+ buffer.writerIndex(endPosition);
+ }
+
+ @Override
+ protected int getMaxAllowedElements() {
+ return 10;
+ }
+
+ @Override
+ protected void onMapReadInteger(short key, int value, ConnectMessage decodingObject) {
+ switch (key) {
+ case FIELD_CLIENT_VERSION -> {
+ decodingObject.clientVersion = value;
+ }
+ }
+ }
+
+ @Override
+ protected void onMapReadByte(short key, byte value, ConnectMessage decodingObject) {
+ }
+
+ @Override
+ protected void onMapReadBoolean(short key, boolean value, ConnectMessage decodingObject) {
+ }
+
+ @Override
+ protected void onMapReadLong(short key, long value, ConnectMessage decodingObject) {
+ }
+
+ @Override
+ protected void onMapReadString(short key, String value, ConnectMessage decodingObject) {
+ switch (key) {
+ case FIELD_AUTH_MECHANISM -> {
+ decodingObject.authMechanism = value;
+ }
+ }
+ }
+
+ @Override
+ protected void onMapReadByteArray(short key, ActiveMQBuffer slice, ConnectMessage decodingObject) {
+ switch (key) {
+ case FIELD_AUTH_DATA -> {
+ int len = slice.readableBytes();
+ byte[] bytes = new byte[len];
+ slice.readBytes(bytes);
+ decodingObject.authData = bytes;
+ }
+ }
+ }
+ }
+
+ private String nodeID;
+
+ private int clientVersion;
+
+ /**
+ * Auth mechanism name; {@code null} means legacy client — skip connection auth.
+ */
+ private String authMechanism;
+
+ /**
+ * Raw auth data; {@code null} for legacy clients.
+ */
+ private byte[] authData;
+
+ /**
+ * Creates a ConnectMessage with PLAIN credentials.
+ * <p>
+ * The auth data is encoded per
+ * <a href="https://www.rfc-editor.org/rfc/rfc4616">RFC 4616</a>:
+ * {@code authzid NUL authcid NUL passwd} as UTF-8 bytes.
+ * The authorization identity ({@code authzid}) is always empty;
+ * {@code authcid} and {@code passwd} are set from the supplied arguments.
+ */
+ public static ConnectMessage withPlainCredentials(String nodeID, int clientVersion, String username, String password) {
+ ConnectMessage msg = new ConnectMessage(nodeID, clientVersion);
+ msg.authMechanism = MECHANISM_PLAIN;
+ String authcid = username != null ? username : "";
+ String passwd = password != null ? password : "";
+ // RFC 4616: authzid NUL authcid NUL passwd
+ msg.authData = ("\0" + authcid + "\0" + passwd).getBytes(StandardCharsets.UTF_8);
+ return msg;
+ }
+
+ public ConnectMessage() {
+ super(CONNECT);
+ }
+
+ public ConnectMessage(String nodeID, int clientVersion) {
+ super(CONNECT);
+ this.nodeID = nodeID;
+ this.clientVersion = clientVersion;
+ }
+
+ @Override
+ public void encodeRest(ActiveMQBuffer buffer) {
+ buffer.writeNullableString(nodeID);
+
+ mapSerializer.encode(buffer, this);
+ }
+
+ @Override
+ public void decodeRest(ActiveMQBuffer buffer) {
+ nodeID = buffer.readNullableString();
+
+ if (buffer.readableBytes() > 0) {
+ mapSerializer.decode(buffer, this);
+ }
+ }
+
+ @Override
+ protected String getPacketString() {
+ StringBuilder sb = new StringBuilder(super.getPacketString());
+ sb.append(", nodeID=").append(nodeID);
+ sb.append(", clientVersion=").append(clientVersion);
+ if (authMechanism != null) {
+ sb.append(", authMechanism=").append(authMechanism);
+ }
+ return sb.toString();
+ }
+
+ public String getNodeID() {
+ return nodeID;
+ }
+
+ public int getClientVersion() {
+ return clientVersion;
+ }
+
+ /**
+ * Returns the auth mechanism name (e.g. {@code "PLAIN"}),
+ * or {@code null} if no mechanism was sent (legacy client — skip connection auth).
+ */
+ public String getAuthMechanism() {
+ return authMechanism;
+ }
+
+ /**
+ * Sets the auth mechanism.
+ */
+ public void setAuthMechanism(String authMechanism) {
+ this.authMechanism = authMechanism;
+ }
+
+ /**
+ * Returns the raw auth data bytes, or {@code null} if not present
+ * (e.g. legacy client).
+ */
+ public byte[] getAuthData() {
+ return authData;
+ }
+
+ /**
+ * Sets the raw auth data bytes.
+ */
+ void setAuthData(byte[] authData) {
+ this.authData = authData;
+ }
+
+ /**
+ * Decodes PLAIN auth data per
+ * <a href="https://www.rfc-editor.org/rfc/rfc4616">RFC 4616</a>
+ * ({@code authzid NUL authcid NUL passwd}) and returns a two-element array
+ * {@code [authcid, passwd]} (i.e. {@code [username, password]}).
+ * The {@code authzid} field is parsed but not returned, as it is always empty.
+ */
+ public String[] decodePlainAuthData() {
+ byte[] data = authData;
+
+ if (data == null || data.length == 0) {
+ return new String[]{"", ""};
+ }
+
+ // RFC 4616: authzid NUL authcid NUL passwd
+ // Split on NUL to obtain the three fields. Limit 3 keeps a NUL inside
+ // passwd intact should one ever appear.
+ String payload = new String(data, StandardCharsets.UTF_8);
+ String[] fields = payload.split("\0", 3);
+
+ // fields[0] = authzid (always empty), fields[1] = authcid, fields[2] = passwd
+ String authcid = fields.length > 1 ? fields[1] : "";
+ String passwd = fields.length > 2 ? fields[2] : "";
+ return new String[]{authcid, passwd};
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode() + Objects.hash(nodeID, clientVersion, authMechanism) + Arrays.hashCode(authData);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!super.equals(obj)) {
+ return false;
+ }
+ if (!(obj instanceof ConnectMessage other)) {
+ return false;
+ }
+
+ return Objects.equals(nodeID, other.nodeID)
+ && Objects.equals(clientVersion, other.clientVersion)
+ && Objects.equals(authMechanism, other.authMechanism)
+ && Arrays.equals(authData, other.authData);
+ }
+}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectResponseMessage.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectResponseMessage.java
new file mode 100644
index 0000000000..236f66247f
--- /dev/null
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectResponseMessage.java
@@ -0,0 +1,136 @@
+/*
+ * 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.activemq.artemis.core.protocol.core.impl.wireformat;
+
+import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
+import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;
+import org.apache.activemq.artemis.utils.AbstractMapPersister;
+
+/**
+ * Response to a {@link ConnectMessage}.
+ * <p>
+ * Replaces the former {@code CheckFailoverReplyMessage} on the same wire packet ID
+ * ({@link PacketImpl#CONNECT_RESPONSE}, {@code -5}). The {@code okToFailover}
+ * field is unchanged; an optional server version may follow as an extension
+ * field for backward-compatible decoding.
+ */
+public class ConnectResponseMessage extends PacketImpl {
+
+ static final short FIELD_SERVER_VERSION = 1;
+
+ private static final ConnectResponseMapSerializer mapSerializer = new ConnectResponseMapSerializer();
+
+ private static class ConnectResponseMapSerializer extends AbstractMapPersister<ConnectResponseMessage> {
+ public void encode(ActiveMQBuffer buffer, ConnectResponseMessage message) {
+ int recordSize = headerSize() + (message.serverVersion > 0 ? payloadSizeInteger() : 0);
+ int fields = message.serverVersion > 0 ? 1 : 0;
+ // since we don't use strings, we can calculate the size ahead, no need to rewrite the header like how it's done in ConnectMessage
+ writeHeader(buffer, recordSize, fields);
+
+ if (message.serverVersion > 0) {
+ writeInteger(buffer, FIELD_SERVER_VERSION, message.serverVersion);
+ }
+
+ }
+
+ @Override
+ protected int getMaxAllowedElements() {
+ return 10;
+ }
+
+ @Override
+ protected void onMapReadInteger(short key, int value, ConnectResponseMessage decodingObject) {
+ switch (key) {
+ case FIELD_SERVER_VERSION -> {
+ decodingObject.serverVersion = value;
+ }
+ }
+ }
+
+ @Override
+ protected void onMapReadByte(short key, byte value, ConnectResponseMessage decodingObject) {
+ }
+
+ @Override
+ protected void onMapReadBoolean(short key, boolean value, ConnectResponseMessage decodingObject) {
+ }
+
+ @Override
+ protected void onMapReadLong(short key, long value, ConnectResponseMessage decodingObject) {
+ }
+
+ @Override
+ protected void onMapReadString(short key, String value, ConnectResponseMessage decodingObject) {
+ }
+
+ @Override
+ protected void onMapReadByteArray(short key, ActiveMQBuffer slice, ConnectResponseMessage decodingObject) {
+ }
+ }
+
+ private boolean okToFailover;
+
+ private int serverVersion;
+
+ public ConnectResponseMessage(boolean okToFailover, int serverVersion) {
+ super(CONNECT_RESPONSE);
+ this.okToFailover = okToFailover;
+ this.serverVersion = serverVersion;
+ }
+
+ public ConnectResponseMessage() {
+ super(CONNECT_RESPONSE);
+ }
+
+ @Override
+ public boolean isResponse() {
+ return true;
+ }
+
+ @Override
+ public void encodeRest(ActiveMQBuffer buffer) {
+ buffer.writeBoolean(okToFailover);
+
+ mapSerializer.encode(buffer, this);
+ }
+
+ @Override
+ public void decodeRest(ActiveMQBuffer buffer) {
+ okToFailover = buffer.readBoolean();
+
+ if (buffer.readableBytes() > 0) {
+ mapSerializer.decode(buffer, this);
+ }
+ }
+
+ @Override
+ protected String getPacketString() {
+ StringBuilder sb = new StringBuilder(super.getPacketString());
+ sb.append(", okToFailover=" + okToFailover);
+ sb.append(", serverVersion=" + serverVersion);
+ return sb.toString();
+ }
+
+ public boolean isOkToFailover() {
+ return okToFailover;
+ }
+
+ public int getServerVersion() {
+ return serverVersion;
+ }
+
+}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/AuthenticationListener.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/AuthenticationListener.java
new file mode 100644
index 0000000000..6e9cd2cee1
--- /dev/null
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/AuthenticationListener.java
@@ -0,0 +1,25 @@
+/*
+ * 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.activemq.artemis.core.remoting;
+
+public interface AuthenticationListener {
+
+ /**
+ * called when the connection is authenticated
+ */
+ void connectionAuthenticated();
+}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/CoreFrameWithSizeLimitDecoder.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/CoreFrameWithSizeLimitDecoder.java
new file mode 100644
index 0000000000..46f3b3779d
--- /dev/null
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/core/remoting/impl/netty/CoreFrameWithSizeLimitDecoder.java
@@ -0,0 +1,68 @@
+/*
+ * 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.activemq.artemis.core.remoting.impl.netty;
+
+import java.nio.ByteOrder;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.TooLongFrameException;
+import io.netty.util.AttributeKey;
+
+/**
+ * Decoder that enforces a variable maximum frame size limit
+ */
+public class CoreFrameWithSizeLimitDecoder extends ActiveMQFrameDecoder2 {
+
+ public static final AttributeKey<Integer> FRAME_SIZE_LIMIT =
+ AttributeKey.valueOf("frameSizeLimit");
+
+ private final int initialFrameSizeLimit;
+
+ private Channel channel;
+
+ public CoreFrameWithSizeLimitDecoder(final int initialFrameSizeLimit) {
+ this.initialFrameSizeLimit = initialFrameSizeLimit;
+ }
+
+ public static void setFrameSizeLimit(final Channel channel, final int frameSizeLimit) {
+ channel.attr(FRAME_SIZE_LIMIT).set(frameSizeLimit);
+ }
+
+ private static int getFrameSizeLimit(final Channel channel) {
+ final Integer limit = channel.attr(FRAME_SIZE_LIMIT).get();
+ return limit == null ? 0 : limit;
+ }
+
+ @Override
+ public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
+ channel = ctx.channel();
+ setFrameSizeLimit(channel, initialFrameSizeLimit);
+ super.handlerAdded(ctx);
+ }
+
+ @Override
+ protected long getUnadjustedFrameLength(final ByteBuf buf, final int offset, final int length, final ByteOrder order) {
+ final long unadjustedFrameLength = super.getUnadjustedFrameLength(buf, offset, length, order);
+ final int frameSizeLimit = getFrameSizeLimit(channel);
+ if (frameSizeLimit > 0 && unadjustedFrameLength > frameSizeLimit) {
+ throw new TooLongFrameException("Frame size exceeded: " + unadjustedFrameLength);
+ }
+ return unadjustedFrameLength;
+ }
+}
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnection.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnection.java
index 8814d60af1..9313878b66 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnection.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnection.java
@@ -18,6 +18,7 @@ package org.apache.activemq.artemis.spi.core.protocol;
import java.util.ArrayList;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
@@ -29,6 +30,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQInterruptedException;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.client.ActiveMQClientLogger;
import org.apache.activemq.artemis.core.client.ActiveMQClientMessageBundle;
+import org.apache.activemq.artemis.core.remoting.AuthenticationListener;
import org.apache.activemq.artemis.core.remoting.CloseListener;
import org.apache.activemq.artemis.core.remoting.FailureListener;
import org.apache.activemq.artemis.spi.core.remoting.Connection;
@@ -45,6 +47,7 @@ public abstract class AbstractRemotingConnection implements RemotingConnection {
protected final List<FailureListener> failureListeners = new CopyOnWriteArrayList<>();
protected final List<CloseListener> closeListeners = new CopyOnWriteArrayList<>();
+ protected final List<AuthenticationListener> authenticationListeners = new CopyOnWriteArrayList<>();
protected final Connection transportConnection;
protected final Executor executor;
protected final long creationTime;
@@ -52,6 +55,7 @@ public abstract class AbstractRemotingConnection implements RemotingConnection {
protected volatile boolean dataReceived;
private String clientId;
private Subject subject;
+ private volatile boolean authenticated;
public AbstractRemotingConnection(final Connection transportConnection, final Executor executor) {
this.transportConnection = transportConnection;
@@ -282,6 +286,39 @@ public abstract class AbstractRemotingConnection implements RemotingConnection {
return subject;
}
+ @Override
+ public void setAuthenticated() {
+ if (!this.authenticated) {
+ this.authenticated = true;
+
+ final List<AuthenticationListener> listeners = new ArrayList<>(authenticationListeners);
+ for (final AuthenticationListener listener : listeners) {
+ try {
+ listener.connectionAuthenticated();
+ } catch (final Throwable t) {
+ ActiveMQClientLogger.LOGGER.errorCallingAuthenticationListener(t);
+ }
+ }
+ }
+ }
+
+ @Override
+ public boolean isAuthenticated() {
+ return authenticated;
+ }
+
+ @Override
+ public void addAuthenticationListener(final AuthenticationListener listener) {
+ Objects.requireNonNull(listener);
+ authenticationListeners.add(listener);
+ }
+
+ @Override
+ public boolean removeAuthenticationListener(final AuthenticationListener listener) {
+ Objects.requireNonNull(listener);
+ return authenticationListeners.remove(listener);
+ }
+
@Override
public void setClientID(String clientId) {
this.clientId = clientId;
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/RemotingConnection.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/RemotingConnection.java
index e24875e287..9d1e9cdb1d 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/RemotingConnection.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/protocol/RemotingConnection.java
@@ -25,6 +25,7 @@ import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.DisconnectReason;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
+import org.apache.activemq.artemis.core.remoting.AuthenticationListener;
import org.apache.activemq.artemis.core.remoting.CloseListener;
import org.apache.activemq.artemis.core.remoting.FailureListener;
import org.apache.activemq.artemis.spi.core.remoting.BufferHandler;
@@ -219,6 +220,33 @@ public interface RemotingConnection extends BufferHandler {
*/
Subject getSubject();
+ /**
+ * marks this connection as authenticated
+ */
+ void setAuthenticated();
+
+ /**
+ * {@return true if the {@link RemotingConnection} is authenticated, otherwise false}
+ */
+ boolean isAuthenticated();
+
+ /**
+ * add a AuthenticationListener.
+ * <p>
+ * This will be called when the connection is authenticated.
+ *
+ * @param listener the listener to add
+ */
+ void addAuthenticationListener(AuthenticationListener listener);
+
+ /**
+ * remove a AuthenticationListener
+ *
+ * @param listener the listener to remove
+ * @return true if removed
+ */
+ boolean removeAuthenticationListener(AuthenticationListener listener);
+
/**
* {@return the name of the protocol for this Remoting Connection}
*/
diff --git a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManager.java b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManager.java
index 28b6c62bc0..6fecb97bff 100644
--- a/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManager.java
+++ b/artemis-core-client/src/main/java/org/apache/activemq/artemis/spi/core/remoting/ClientProtocolManager.java
@@ -74,7 +74,7 @@ public interface ClientProtocolManager {
boolean cleanupBeforeFailover(ActiveMQException cause);
- boolean checkForFailover(String nodeID) throws ActiveMQException;
+ boolean sendConnect(String nodeID, String connectionUser, String connectionPassword) throws ActiveMQException;
void setSessionFactory(ClientSessionFactory factory);
diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectMessageTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectMessageTest.java
new file mode 100644
index 0000000000..d966b9ae8b
--- /dev/null
+++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectMessageTest.java
@@ -0,0 +1,214 @@
+/*
+ * 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.activemq.artemis.core.protocol.core.impl.wireformat;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import java.nio.charset.StandardCharsets;
+
+import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
+import org.apache.activemq.artemis.api.core.ActiveMQBuffers;
+import org.junit.jupiter.api.Test;
+
+public class ConnectMessageTest {
+
+ static final int TEST_VERSION = 123;
+
+ @Test
+ public void testRoundTrip() {
+ ConnectMessage encoded = new ConnectMessage("node-1", TEST_VERSION);
+
+ ConnectMessage decoded = roundTrip(encoded);
+
+ assertEquals("node-1", decoded.getNodeID());
+ assertEquals(TEST_VERSION, decoded.getClientVersion());
+ assertNull(decoded.getAuthMechanism());
+ assertNull(decoded.getAuthData());
+ }
+
+ @Test
+ public void testRoundTripPlainWithCredentials() {
+ ConnectMessage encoded = ConnectMessage.withPlainCredentials("node-1", TEST_VERSION, "cluster-user", "cluster-pass");
+
+ ConnectMessage decoded = roundTrip(encoded);
+
+ assertEquals("node-1", decoded.getNodeID());
+ assertEquals(TEST_VERSION, decoded.getClientVersion());
+ assertEquals(ConnectMessage.MECHANISM_PLAIN, decoded.getAuthMechanism());
+ assertPlainAuthData(decoded.getAuthData(), "cluster-user", "cluster-pass");
+ }
+
+ @Test
+ public void testRoundTripPlainWithNullOrEmptyPassword() {
+ // Both null and "" password must encode identically as an empty passwd field.
+ for (String password : new String[]{null, ""}) {
+ ConnectMessage encoded = ConnectMessage.withPlainCredentials("node-1", TEST_VERSION, "cluster-user", password);
+ ConnectMessage decoded = roundTrip(encoded);
+ assertEquals(ConnectMessage.MECHANISM_PLAIN, decoded.getAuthMechanism());
+ assertPlainAuthData(decoded.getAuthData(), "cluster-user", "");
+ }
+ }
+
+ @Test
+ public void testLegacyMessageNoMechanism() {
+ // A message with no auth mechanism simulates a legacy client — authMechanism must be null.
+ ConnectMessage decoded = new ConnectMessage();
+ ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(256);
+ decoded.encodeRest(buffer); // encode the empty no-op message
+ ConnectMessage redecoded = new ConnectMessage();
+ redecoded.decodeRest(buffer);
+
+ assertNull(redecoded.getAuthMechanism(), "legacy client must yield null authMechanism");
+ assertNull(redecoded.getAuthData());
+ }
+
+ @Test
+ public void testDecodeIgnoresUnknownFutureSections() {
+ ConnectMessage encoded = ConnectMessage.withPlainCredentials("node-1", TEST_VERSION, "cluster-user", "cluster-pass");
+ ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(256);
+ encoded.encodeRest(buffer);
+ buffer.writeByte((byte) 99);
+ buffer.writeInt(42);
+
+ ConnectMessage decoded = new ConnectMessage();
+ decoded.decodeRest(buffer);
+
+ assertEquals("node-1", decoded.getNodeID());
+ assertEquals(TEST_VERSION, decoded.getClientVersion());
+ assertEquals(ConnectMessage.MECHANISM_PLAIN, decoded.getAuthMechanism());
+ assertPlainAuthData(decoded.getAuthData(), "cluster-user", "cluster-pass");
+ }
+
+ @Test
+ public void testDecodePlainAuthDataEmptyUsername() {
+ ConnectMessage msg = ConnectMessage.withPlainCredentials("node-1", TEST_VERSION, "", "mypass");
+ String[] decoded = msg.decodePlainAuthData();
+ assertEquals("", decoded[0]);
+ assertEquals("mypass", decoded[1]);
+ }
+
+ @Test
+ public void testDecodePlainAuthDataBothEmpty() {
+ ConnectMessage msg = ConnectMessage.withPlainCredentials("node-1", TEST_VERSION, "", "");
+ String[] decoded = msg.decodePlainAuthData();
+ assertEquals("", decoded[0]);
+ assertEquals("", decoded[1]);
+ }
+
+ @Test
+ public void testDecodePlainAuthDataNullAuthData() {
+ // decodePlainAuthData on a message with no auth data returns empty strings
+ ConnectMessage msg = new ConnectMessage("node-1", TEST_VERSION);
+ String[] decoded = msg.decodePlainAuthData();
+ assertEquals("", decoded[0], "username must be empty");
+ assertEquals("", decoded[1], "password must be empty");
+ }
+
+ @Test
+ public void testDecodePlainAuthDataAfterRoundTrip() {
+ ConnectMessage msg = ConnectMessage.withPlainCredentials("node-1", TEST_VERSION, "cluster-user", "cluster-pass");
+ ConnectMessage decoded = roundTrip(msg);
+ String[] credentials = decoded.decodePlainAuthData();
+ assertEquals("cluster-user", credentials[0]);
+ assertEquals("cluster-pass", credentials[1]);
+ }
+
+ @Test
+ public void testRfc4616WireStructure() {
+ // Verify the raw bytes follow RFC 4616: authzid NUL authcid NUL passwd
+ // With empty authzid the bytes must be: NUL "alice" NUL "secret"
+ ConnectMessage msg = ConnectMessage.withPlainCredentials("node-1", TEST_VERSION, "alice", "secret");
+ byte[] data = msg.getAuthData();
+ byte[] expected = new byte[]{0, 'a', 'l', 'i', 'c', 'e', 0, 's', 'e', 'c', 'r', 'e', 't'};
+ assertArrayEquals(expected, data, "authData must be RFC 4616 authzid NUL authcid NUL passwd");
+ }
+
+ @Test
+ public void testDecodePlainAuthDataFromRfc4616Bytes() {
+ // Manually construct RFC 4616 bytes: authzid="" NUL authcid="bob" NUL passwd="pw"
+ // and verify decodePlainAuthData extracts authcid and passwd correctly.
+ ConnectMessage msg = new ConnectMessage("node-1", TEST_VERSION);
+ msg.setAuthData(new byte[]{0, 'b', 'o', 'b', 0, 'p', 'w'});
+ String[] credentials = msg.decodePlainAuthData();
+ assertEquals("bob", credentials[0], "authcid must be extracted from RFC 4616 bytes");
+ assertEquals("pw", credentials[1], "passwd must be extracted from RFC 4616 bytes");
+ }
+
+ @Test
+ public void testDecodePlainAuthDataFromRfc4616BytesWithNonEmptyAuthzid() {
+ // RFC 4616 allows a non-empty authzid: authzid="proxy" NUL authcid="bob" NUL passwd="pw"
+ // decodePlainAuthData must ignore authzid and still return [authcid, passwd].
+ ConnectMessage msg = new ConnectMessage("node-1", TEST_VERSION);
+ msg.setAuthData(("proxy" + "\0" + "bob" + "\0" + "pw").getBytes(StandardCharsets.UTF_8));
+ String[] credentials = msg.decodePlainAuthData();
+ assertEquals("bob", credentials[0], "authcid must be extracted even when authzid is non-empty");
+ assertEquals("pw", credentials[1], "passwd must be extracted even when authzid is non-empty");
+ }
+
+ @Test
+ public void testDecodePlainAuthDataMalformedNoNul() {
+ // No NUL at all — not a valid RFC 4616 payload.
+ // Decoder treats the entire bytes as authzid (fields[0] only), so authcid and passwd default to empty.
+ ConnectMessage msg = new ConnectMessage("node-1", TEST_VERSION);
+ msg.setAuthData("justtext".getBytes(StandardCharsets.UTF_8));
+ String[] credentials = msg.decodePlainAuthData();
+ assertEquals("", credentials[0], "malformed: no NUL — authcid must be empty");
+ assertEquals("", credentials[1], "malformed: no NUL — passwd must be empty");
+ }
+
+ @Test
+ public void testDecodePlainAuthDataMalformedOnlyOneNul() {
+ // Only one NUL: authzid NUL authcid — passwd field is missing.
+ // Decoder returns authcid from fields[1] and empty string for the missing passwd.
+ ConnectMessage msg = new ConnectMessage("node-1", TEST_VERSION);
+ msg.setAuthData(("authzid" + "\0" + "authcid").getBytes(StandardCharsets.UTF_8));
+ String[] credentials = msg.decodePlainAuthData();
+ assertEquals("authcid", credentials[0], "malformed: one NUL — authcid must be fields[1]");
+ assertEquals("", credentials[1], "malformed: one NUL — missing passwd must be empty");
+ }
+
+ @Test
+ public void testDecodePlainAuthDataMalformedLeadingNulOnly() {
+ // Leading NUL but no second NUL: authzid="" NUL authcid — passwd field is missing.
+ ConnectMessage msg = new ConnectMessage("node-1", TEST_VERSION);
+ msg.setAuthData(("\0" + "authcid").getBytes(StandardCharsets.UTF_8));
+ String[] credentials = msg.decodePlainAuthData();
+ assertEquals("authcid", credentials[0], "malformed: leading NUL only — authcid must be fields[1]");
+ assertEquals("", credentials[1], "malformed: leading NUL only — missing passwd must be empty");
+ }
+
+ /**
+ * Asserts that {@code authData} matches the RFC 4616 SASL PLAIN wire format:
+ * {@code authzid NUL authcid NUL passwd} where {@code authzid} is always empty.
+ */
+ private static void assertPlainAuthData(byte[] authData, String expectedUser, String expectedPass) {
+ // RFC 4616: authzid NUL authcid NUL passwd (authzid is empty)
+ byte[] expected = ("" + "\0" + expectedUser + "\0" + expectedPass).getBytes(StandardCharsets.UTF_8);
+ assertArrayEquals(expected, authData);
+ }
+
+ private static ConnectMessage roundTrip(ConnectMessage encoded) {
+ ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(256);
+ encoded.encodeRest(buffer);
+
+ ConnectMessage decoded = new ConnectMessage();
+ decoded.decodeRest(buffer);
+ return decoded;
+ }
+}
diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectResponseMessageTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectResponseMessageTest.java
new file mode 100644
index 0000000000..aa6f8b92f9
--- /dev/null
+++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/wireformat/ConnectResponseMessageTest.java
@@ -0,0 +1,74 @@
+/*
+ * 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.activemq.artemis.core.protocol.core.impl.wireformat;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
+import org.apache.activemq.artemis.api.core.ActiveMQBuffers;
+import org.junit.jupiter.api.Test;
+
+public class ConnectResponseMessageTest {
+
+ static final int TEST_VERSION = 456;
+
+ @Test
+ public void testRoundTripWithServerVersion() {
+ ConnectResponseMessage encoded = new ConnectResponseMessage(true, TEST_VERSION);
+
+ ConnectResponseMessage decoded = roundTrip(encoded);
+
+ assertTrue(decoded.isOkToFailover());
+ assertEquals(TEST_VERSION, decoded.getServerVersion());
+ }
+
+ @Test
+ public void testRoundTripWithoutServerVersion() {
+ ConnectResponseMessage encoded = new ConnectResponseMessage(false, 0);
+
+ ConnectResponseMessage decoded = roundTrip(encoded);
+
+ assertFalse(decoded.isOkToFailover());
+ assertEquals(0, decoded.getServerVersion());
+ }
+
+ @Test
+ public void testDecodeIgnoresUnknownFutureSections() {
+ ConnectResponseMessage encoded = new ConnectResponseMessage(true, TEST_VERSION);
+ ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(256);
+ encoded.encodeRest(buffer);
+ buffer.writeByte((byte) 99);
+ buffer.writeInt(42);
+
+ ConnectResponseMessage decoded = new ConnectResponseMessage();
+ decoded.decodeRest(buffer);
+
+ assertTrue(decoded.isOkToFailover());
+ assertEquals(TEST_VERSION, decoded.getServerVersion());
+ }
+
+ private static ConnectResponseMessage roundTrip(ConnectResponseMessage encoded) {
+ ActiveMQBuffer buffer = ActiveMQBuffers.dynamicBuffer(256);
+ encoded.encodeRest(buffer);
+
+ ConnectResponseMessage decoded = new ConnectResponseMessage();
+ decoded.decodeRest(buffer);
+ return decoded;
+ }
+}
diff --git a/artemis-core-client/src/test/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnectionTest.java b/artemis-core-client/src/test/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnectionTest.java
new file mode 100644
index 0000000000..84139e8485
--- /dev/null
+++ b/artemis-core-client/src/test/java/org/apache/activemq/artemis/spi/core/protocol/AbstractRemotingConnectionTest.java
@@ -0,0 +1,190 @@
+/*
+ * 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.activemq.artemis.spi.core.protocol;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.activemq.artemis.core.remoting.AuthenticationListener;
+import org.apache.activemq.artemis.spi.core.remoting.Connection;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class AbstractRemotingConnectionTest {
+
+ /** Minimal concrete subclass — only what the constructor requires. */
+ private static class TestRemotingConnection extends AbstractRemotingConnection {
+ TestRemotingConnection(Connection transport) {
+ super(transport, Runnable::run);
+ }
+
+ @Override
+ public void bufferReceived(Object connectionID, org.apache.activemq.artemis.api.core.ActiveMQBuffer buffer) {
+ }
+
+ @Override
+ public void fail(org.apache.activemq.artemis.api.core.ActiveMQException me) {
+ }
+
+ @Override
+ public void fail(org.apache.activemq.artemis.api.core.ActiveMQException me, String scaleDownTargetNodeID) {
+ }
+
+ @Override
+ public void destroy() {
+ }
+
+ @Override
+ public void disconnect(boolean criticalError) {
+ }
+
+ @Override
+ public void disconnect(String scaleDownNodeID, boolean criticalError) {
+ }
+
+ @Override
+ public String getProtocolName() {
+ return "TEST";
+ }
+ }
+
+ private TestRemotingConnection connection;
+
+ @BeforeEach
+ public void setUp() {
+ connection = new TestRemotingConnection(Mockito.mock(Connection.class));
+ }
+
+ @Test
+ public void testIsAuthenticatedFalseByDefault() {
+ assertFalse(connection.isAuthenticated());
+ }
+
+ @Test
+ public void testSetAuthenticatedMarksConnectionAsAuthenticated() {
+ connection.setAuthenticated();
+ assertTrue(connection.isAuthenticated());
+ }
+
+ @Test
+ public void testSetAuthenticatedIsIdempotent() {
+ connection.setAuthenticated();
+ connection.setAuthenticated(); // second call must be a no-op
+ assertTrue(connection.isAuthenticated());
+ }
+
+ @Test
+ public void testListenerIsCalledOnSetAuthenticated() {
+ AtomicInteger callCount = new AtomicInteger(0);
+ connection.addAuthenticationListener(callCount::incrementAndGet);
+
+ connection.setAuthenticated();
+
+ assertEquals(1, callCount.get());
+ }
+
+ @Test
+ public void testListenerIsNotCalledWhenAlreadyAuthenticated() {
+ connection.setAuthenticated(); // first call marks authenticated
+
+ AtomicInteger callCount = new AtomicInteger(0);
+ connection.addAuthenticationListener(callCount::incrementAndGet);
+
+ connection.setAuthenticated(); // second call must be a no-op
+ assertEquals(0, callCount.get());
+ }
+
+ @Test
+ public void testMultipleListenersAreAllCalled() {
+ AtomicInteger countA = new AtomicInteger(0);
+ AtomicInteger countB = new AtomicInteger(0);
+ connection.addAuthenticationListener(countA::incrementAndGet);
+ connection.addAuthenticationListener(countB::incrementAndGet);
+
+ connection.setAuthenticated();
+
+ assertEquals(1, countA.get());
+ assertEquals(1, countB.get());
+ }
+
+ @Test
+ public void testRemovedListenerIsNotCalled() {
+ AtomicInteger callCount = new AtomicInteger(0);
+ AuthenticationListener listener = callCount::incrementAndGet;
+ connection.addAuthenticationListener(listener);
+
+ boolean removed = connection.removeAuthenticationListener(listener);
+ assertTrue(removed);
+
+ connection.setAuthenticated();
+ assertEquals(0, callCount.get());
+ }
+
+ @Test
+ public void testRemoveReturnsFalseForUnknownListener() {
+ AuthenticationListener listener = () -> { };
+ assertFalse(connection.removeAuthenticationListener(listener));
+ }
+
+ @Test
+ public void testListenerThatThrowsDoesNotPreventOtherListeners() {
+ AuthenticationListener throwing = () -> {
+ throw new RuntimeException("simulated error");
+ };
+ AtomicInteger callCount = new AtomicInteger(0);
+ connection.addAuthenticationListener(throwing);
+ connection.addAuthenticationListener(callCount::incrementAndGet);
+
+ connection.setAuthenticated(); // must not propagate the exception
+
+ assertTrue(connection.isAuthenticated());
+ assertEquals(1, callCount.get());
+ }
+
+ @Test
+ public void testAddListenerRejectsNull() {
+ assertThrows(NullPointerException.class, () -> connection.addAuthenticationListener(null));
+ }
+
+ @Test
+ public void testRemoveListenerRejectsNull() {
+ assertThrows(NullPointerException.class, () -> connection.removeAuthenticationListener(null));
+ }
+
+ @Test
+ public void testListenerCanRemoveItselfDuringFiring() {
+ AtomicInteger callCount = new AtomicInteger(0);
+ AuthenticationListener[] holder = new AuthenticationListener[1];
+ holder[0] = () -> {
+ callCount.incrementAndGet();
+ connection.removeAuthenticationListener(holder[0]);
+ };
+ connection.addAuthenticationListener(holder[0]);
+
+ connection.setAuthenticated();
+
+ assertEquals(1, callCount.get());
+ // Listener removed itself — a second setAuthenticated on a fresh connection
+ // would not call it again; verify removal succeeded
+ assertFalse(connection.removeAuthenticationListener(holder[0]));
+ }
+}
diff --git a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionFactory.java b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionFactory.java
index f28eaf994d..d7b39c25ce 100644
--- a/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionFactory.java
+++ b/artemis-jms-client/src/main/java/org/apache/activemq/artemis/jms/client/ActiveMQConnectionFactory.java
@@ -42,6 +42,7 @@ import java.security.PrivilegedAction;
import java.util.Map;
import java.util.Properties;
+import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration;
import org.apache.activemq.artemis.api.core.Interceptor;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
@@ -837,6 +838,7 @@ public class ActiveMQConnectionFactory extends JNDIStorable implements Connectio
public ActiveMQConnectionFactory setUser(String user) {
checkWrite();
this.user = user;
+ serverLocator.setConnectionCredentials(user, password);
return this;
}
@@ -851,6 +853,7 @@ public class ActiveMQConnectionFactory extends JNDIStorable implements Connectio
public ActiveMQConnectionFactory setPassword(String password) {
checkWrite();
this.password = password;
+ serverLocator.setConnectionCredentials(user, password);
return this;
}
@@ -913,7 +916,9 @@ public class ActiveMQConnectionFactory extends JNDIStorable implements Connectio
ClientSessionFactory factory;
try {
- factory = serverLocator.createSessionFactory();
+ factory = serverLocator.createSessionFactory(username, password);
+ } catch (ActiveMQException e) {
+ throw JMSExceptionHelper.convertFromActiveMQException(e);
} catch (Exception e) {
JMSException jmse = new JMSException("Failed to create session factory");
diff --git a/artemis-junit/artemis-junit-commons/src/main/java/org/apache/activemq/artemis/junit/AbstractActiveMQClientDelegate.java b/artemis-junit/artemis-junit-commons/src/main/java/org/apache/activemq/artemis/junit/AbstractActiveMQClientDelegate.java
index 19a3668ad5..e1f990e480 100644
--- a/artemis-junit/artemis-junit-commons/src/main/java/org/apache/activemq/artemis/junit/AbstractActiveMQClientDelegate.java
+++ b/artemis-junit/artemis-junit-commons/src/main/java/org/apache/activemq/artemis/junit/AbstractActiveMQClientDelegate.java
@@ -89,7 +89,7 @@ public abstract class AbstractActiveMQClientDelegate {
void start() {
log.info("Starting {}", this.getClass().getSimpleName());
try {
- sessionFactory = serverLocator.createSessionFactory();
+ sessionFactory = serverLocator.createSessionFactory(username, password);
session = sessionFactory.createSession(username, password, false, true, true, serverLocator.isPreAcknowledge(),
serverLocator.getAckBatchSize());
} catch (RuntimeException runtimeEx) {
diff --git a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCLIPlugin.java b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCLIPlugin.java
index 3a25ab1c24..88ef4903c7 100644
--- a/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCLIPlugin.java
+++ b/artemis-maven-plugin/src/main/java/org/apache/activemq/artemis/maven/ArtemisCLIPlugin.java
@@ -98,7 +98,7 @@ public class ArtemisCLIPlugin extends ArtemisAbstractPlugin {
while (System.currentTimeMillis() <= timeout) {
try (ServerLocator locator = ActiveMQClient.createServerLocator(testURI)) {
if (testUser != null || testPassword != null || testClientID != null) {
- locator.createSessionFactory().createSession(testUser, testPassword, false, false, false, false, 0, testClientID).close();
+ locator.createSessionFactory(testUser, testPassword).createSession(testUser, testPassword, false, false, false, false, 0, testClientID).close();
} else {
locator.createSessionFactory().createSession().close();
}
diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/client/ProtonClientProtocolManager.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/client/ProtonClientProtocolManager.java
index 82744e4c5a..3fcc568a98 100644
--- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/client/ProtonClientProtocolManager.java
+++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/client/ProtonClientProtocolManager.java
@@ -106,7 +106,7 @@ public class ProtonClientProtocolManager extends ProtonProtocolManager implement
}
@Override
- public boolean checkForFailover(String nodeID) throws ActiveMQException {
+ public boolean sendConnect(String nodeID, String connectionUser, String connectionPassword) throws ActiveMQException {
throw new UnsupportedOperationException();
}
diff --git a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/connect/AMQPBrokerConnectionManager.java b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/connect/AMQPBrokerConnectionManager.java
index f4d4ad5704..05fe29019a 100644
--- a/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/connect/AMQPBrokerConnectionManager.java
+++ b/artemis-protocols/artemis-amqp-protocol/src/main/java/org/apache/activemq/artemis/protocol/amqp/connect/AMQPBrokerConnectionManager.java
@@ -348,7 +348,7 @@ public class AMQPBrokerConnectionManager implements ActiveMQComponent, ClientCon
}
@Override
- public boolean checkForFailover(String nodeID) throws ActiveMQException {
+ public boolean sendConnect(String nodeID, String connectionUser, String connectionPassword) throws ActiveMQException {
return false;
}
diff --git a/artemis-protocols/artemis-hqclient-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/client/HornetQClientProtocolManager.java b/artemis-protocols/artemis-hqclient-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/client/HornetQClientProtocolManager.java
index 089a0d77e4..86d096bf01 100644
--- a/artemis-protocols/artemis-hqclient-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/client/HornetQClientProtocolManager.java
+++ b/artemis-protocols/artemis-hqclient-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/hornetq/client/HornetQClientProtocolManager.java
@@ -67,8 +67,8 @@ public class HornetQClientProtocolManager extends ActiveMQClientProtocolManager
}
@Override
- public boolean checkForFailover(String nodeID) throws ActiveMQException {
- //HornetQ doesn't support CheckFailoverMessage packet
+ public boolean sendConnect(String nodeID, String connectionUser, String connectionPassword) throws ActiveMQException {
+ //HornetQ doesn't support connect handshake
return true;
}
diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQResourceAdapter.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQResourceAdapter.java
index 831fa3f7d9..6477a2b0ed 100644
--- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQResourceAdapter.java
+++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/ActiveMQResourceAdapter.java
@@ -1198,6 +1198,10 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable {
throw new IllegalArgumentException("must provide either TransportType or DiscoveryGroupAddress and DiscoveryGroupPort for ResourceAdapter Connection Factory");
}
+ cf.setUser(getUserName());
+ cf.setPassword(getPassword());
+ cf.setPasswordCodec(getPasswordCodec());
+
cf.setUseTopologyForLoadBalancing(raProperties.isUseTopologyForLoadBalancing());
cf.setEnableSharedClientID(true);
@@ -1260,6 +1264,11 @@ public class ActiveMQResourceAdapter implements ResourceAdapter, Serializable {
cf = ActiveMQJMSClient.createConnectionFactoryWithoutHA(JMSFactoryType.XA_CF, transportConfigurations);
}
+
+ cf.setUser(getUserName());
+ cf.setPassword(getPassword());
+ cf.setPasswordCodec(getPasswordCodec());
+
setParams(cf, overrideProperties);
//now make sure we are HA in any way
diff --git a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivation.java b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivation.java
index 26b2250659..eb0045b4ba 100644
--- a/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivation.java
+++ b/artemis-ra/src/main/java/org/apache/activemq/artemis/ra/inflow/ActiveMQActivation.java
@@ -252,7 +252,7 @@ public class ActiveMQActivation {
try {
if (cf == null) {
- cf = factory.getServerLocator().createSessionFactory();
+ cf = factory.getServerLocator().createSessionFactory(spec.getUser(), spec.getPassword());
}
session = setupSession(cf);
ActiveMQMessageHandler handler = new ActiveMQMessageHandler(factory, this, ra.getTSR(), (ClientSessionInternal) session, cf, i);
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ManagementRemotingConnection.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ManagementRemotingConnection.java
index b3487a54d0..c7850b6f4d 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ManagementRemotingConnection.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/management/impl/ManagementRemotingConnection.java
@@ -24,6 +24,7 @@ import java.util.concurrent.Future;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.SimpleString;
+import org.apache.activemq.artemis.core.remoting.AuthenticationListener;
import org.apache.activemq.artemis.core.remoting.CloseListener;
import org.apache.activemq.artemis.core.remoting.FailureListener;
import org.apache.activemq.artemis.core.server.MessageReference;
@@ -180,6 +181,24 @@ public class ManagementRemotingConnection implements RemotingConnection {
return subject;
}
+ @Override
+ public void setAuthenticated() {
+ }
+
+ @Override
+ public boolean isAuthenticated() {
+ return subject != null;
+ }
+
+ @Override
+ public void addAuthenticationListener(AuthenticationListener listener) {
+ }
+
+ @Override
+ public boolean removeAuthenticationListener(AuthenticationListener listener) {
+ return false;
+ }
+
@Override
public String getProtocolName() {
return null;
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandler.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandler.java
index 87fc1c00c1..789e14bafc 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandler.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandler.java
@@ -33,8 +33,8 @@ import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection;
import org.apache.activemq.artemis.core.protocol.core.Packet;
import org.apache.activemq.artemis.core.protocol.core.ServerSessionPacketHandler;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQExceptionMessage;
-import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverMessage;
-import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CheckFailoverReplyMessage;
+import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ConnectMessage;
+import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ConnectResponseMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateQueueMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateSessionMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.CreateSessionMessage_V2;
@@ -70,6 +70,8 @@ public class ActiveMQPacketHandler implements ChannelHandler {
private final Actor<Packet> packetActor;
+ private boolean connectReceived;
+
public ActiveMQPacketHandler(final CoreProtocolManager protocolManager,
final ActiveMQServer server,
final Channel channel1,
@@ -107,10 +109,10 @@ public class ActiveMQPacketHandler implements ChannelHandler {
break;
}
- case PacketImpl.CHECK_FOR_FAILOVER: {
- CheckFailoverMessage request = (CheckFailoverMessage) packet;
+ case PacketImpl.CONNECT: {
+ ConnectMessage request = (ConnectMessage) packet;
- handleCheckForFailover(request);
+ handleConnect(request);
break;
}
@@ -136,10 +138,42 @@ public class ActiveMQPacketHandler implements ChannelHandler {
}
}
- private void handleCheckForFailover(CheckFailoverMessage failoverMessage) {
- String nodeID = failoverMessage.getNodeID();
+ private void handleConnect(ConnectMessage connectMessage) {
+ if (connectReceived) {
+ ActiveMQServerLogger.LOGGER.invalidPacket(connectMessage);
+ connection.close();
+ return;
+ }
+ connectReceived = true;
+
+ connection.setChannelVersion(connectMessage.getClientVersion());
+
+ // Legacy clients omit authMechanism; skip connection auth and rely on session creation.
+ if (server.getSecurityStore().isSecurityEnabled() &&
+ protocolManager.isCoreConnectionSecurityEnabled() &&
+ connectMessage.getAuthMechanism() != null) {
+
+ try {
+ if (ConnectMessage.MECHANISM_PLAIN.equals(connectMessage.getAuthMechanism())) {
+ String[] credentials = connectMessage.decodePlainAuthData();
+ server.validateUser(credentials[0], credentials[1], connection, protocolManager.getSecurityDomain());
+ } else {
+ throw ActiveMQMessageBundle.BUNDLE.authenticationMechanismNotSupported(connectMessage.getAuthMechanism());
+ }
+ } catch (Exception e) {
+ // Flush before close so the exception is on the wire ahead of TCP FIN.
+ // ChannelImpl.returnBlocking preserves an already-delivered EXCEPTION to avoid AMQ219016.
+ ActiveMQException messageException = e instanceof ActiveMQException ? (ActiveMQException) e
+ : new ActiveMQInternalErrorException("Connection authentication failed", e);
+ channel1.sendAndFlush(new ActiveMQExceptionMessage(messageException));
+ connection.close();
+ return;
+ }
+ }
+
+ String nodeID = connectMessage.getNodeID();
boolean okToFailover = nodeID == null || server.getNodeID().toString().equals(nodeID) || !(server.getHAPolicy().canScaleDown() && !server.hasScaledDown(SimpleString.of(nodeID)));
- channel1.send(new CheckFailoverReplyMessage(okToFailover));
+ channel1.send(new ConnectResponseMessage(okToFailover, server.getVersion().getIncrementingVersion()));
}
private void handleCreateSession(final CreateSessionMessage request) {
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManager.java
index c8a17b09a5..ce8cad8d2f 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManager.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/protocol/core/impl/CoreProtocolManager.java
@@ -38,6 +38,7 @@ import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.api.core.client.ClusterTopologyListener;
import org.apache.activemq.artemis.api.core.client.TopologyMember;
+import org.apache.activemq.artemis.core.client.impl.Topology;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.FederationConfiguration;
import org.apache.activemq.artemis.core.config.federation.FederationConnectionConfiguration;
@@ -60,9 +61,12 @@ import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.Federation
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.Ping;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SubscribeClusterTopologyUpdatesMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SubscribeClusterTopologyUpdatesMessageV2;
+import org.apache.activemq.artemis.core.remoting.AuthenticationListener;
import org.apache.activemq.artemis.core.remoting.FailureListener;
import org.apache.activemq.artemis.core.remoting.impl.invm.InVMConnection;
import org.apache.activemq.artemis.core.remoting.impl.netty.ActiveMQFrameDecoder2;
+import org.apache.activemq.artemis.core.remoting.impl.netty.CoreFrameWithSizeLimitDecoder;
+import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnection;
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyServerConnection;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
@@ -76,10 +80,15 @@ import org.apache.activemq.artemis.spi.core.security.jaas.UserPrincipal;
import org.apache.activemq.artemis.utils.SecurityManagerUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
import java.lang.invoke.MethodHandles;
public class CoreProtocolManager implements ProtocolManager<Interceptor, ActiveMQRoutingHandler> {
+ public static final int CORE_INITIAL_MAX_FRAME_SIZE = 4 * 1024;
+
+ public static final int CORE_MAX_FRAME_SIZE = 128 * 1024;
+
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final List<String> websocketRegistryNames = Collections.emptyList();
@@ -98,6 +107,12 @@ public class CoreProtocolManager implements ProtocolManager<Interceptor, ActiveM
private final ActiveMQRoutingHandler routingHandler;
+ private boolean coreConnectionSecurityEnabled = true;
+
+ private int coreInitialMaxFrameSize = CORE_INITIAL_MAX_FRAME_SIZE;
+
+ private int coreMaxFrameSize = CORE_MAX_FRAME_SIZE;
+
public CoreProtocolManager(final CoreProtocolManagerFactory factory,
final ActiveMQServer server,
final List<Interceptor> incomingInterceptors,
@@ -118,6 +133,30 @@ public class CoreProtocolManager implements ProtocolManager<Interceptor, ActiveM
return protocolManagerFactory;
}
+ public boolean isCoreConnectionSecurityEnabled() {
+ return coreConnectionSecurityEnabled;
+ }
+
+ public void setCoreConnectionSecurityEnabled(boolean coreConnectionSecurityEnabled) {
+ this.coreConnectionSecurityEnabled = coreConnectionSecurityEnabled;
+ }
+
+ public int getCoreInitialMaxFrameSize() {
+ return coreInitialMaxFrameSize;
+ }
+
+ public void setCoreInitialMaxFrameSize(int coreInitialMaxFrameSize) {
+ this.coreInitialMaxFrameSize = coreInitialMaxFrameSize;
+ }
+
+ public int getCoreMaxFrameSize() {
+ return coreMaxFrameSize;
+ }
+
+ public void setCoreMaxFrameSize(int coreMaxFrameSize) {
+ this.coreMaxFrameSize = coreMaxFrameSize;
+ }
+
@Override
public void updateInterceptors(List<BaseInterceptor> incoming, List<BaseInterceptor> outgoing) {
this.incomingInterceptors.clear();
@@ -168,6 +207,16 @@ public class CoreProtocolManager implements ProtocolManager<Interceptor, ActiveM
rc.getChannel(CHANNEL_ID.FEDERATION.id, -1).setHandler(new FederationChannelHandler(acceptorUsed, rc));
+ final Connection transportConnection = rc.getTransportConnection();
+ if (transportConnection instanceof NettyConnection nettyConnection) {
+ rc.addAuthenticationListener(new AuthenticationListener() {
+ @Override
+ public void connectionAuthenticated() {
+ rc.removeAuthenticationListener(this);
+ CoreFrameWithSizeLimitDecoder.setFrameSizeLimit(nettyConnection.getChannel(), getCoreMaxFrameSize());
+ }
+ });
+ }
return entry;
}
@@ -192,7 +241,11 @@ public class CoreProtocolManager implements ProtocolManager<Interceptor, ActiveM
@Override
public void addChannelHandlers(ChannelPipeline pipeline) {
- pipeline.addLast("activemq-decoder", new ActiveMQFrameDecoder2());
+ if (server.getSecurityStore().isSecurityEnabled() && isCoreConnectionSecurityEnabled()) {
+ pipeline.addLast("activemq-decoder", new CoreFrameWithSizeLimitDecoder(getCoreInitialMaxFrameSize()));
+ } else {
+ pipeline.addLast("activemq-decoder", new ActiveMQFrameDecoder2());
+ }
}
@Override
@@ -270,6 +323,10 @@ public class CoreProtocolManager implements ProtocolManager<Interceptor, ActiveM
private final Acceptor acceptorUsed;
private final CoreRemotingConnection rc;
+ private boolean preAuthTopologySent = false;
+ private boolean postAuthTopologySent = false;
+ private boolean topologySubscribed = false;
+
private LocalChannelHandler(final Configuration config,
final ConnectionEntry entry,
final Channel channel0,
@@ -296,11 +353,82 @@ public class CoreProtocolManager implements ProtocolManager<Interceptor, ActiveM
channel0.send(packet);
} else if (packet.getType() == PacketImpl.SUBSCRIBE_TOPOLOGY
|| packet.getType() == PacketImpl.SUBSCRIBE_TOPOLOGY_V2) {
- SubscribeClusterTopologyUpdatesMessage msg = (SubscribeClusterTopologyUpdatesMessage) packet;
+ // Reject multiple subscriptions: only one topology subscription is permitted per connection.
+ // A second request indicates a misbehaving or malicious client; close the connection immediately.
+ if (topologySubscribed) {
+ ActiveMQServerLogger.LOGGER.multipleTopologySubscriptions(rc.getRemoteAddress());
+ rc.close();
+ return;
+ }
+ topologySubscribed = true;
if (packet.getType() == PacketImpl.SUBSCRIBE_TOPOLOGY_V2) {
channel0.getConnection().setChannelVersion(
- ((SubscribeClusterTopologyUpdatesMessageV2) msg).getClientVersion());
+ ((SubscribeClusterTopologyUpdatesMessageV2) packet).getClientVersion());
+ }
+
+ if (server.getSecurityStore().isSecurityEnabled() && isCoreConnectionSecurityEnabled() && !rc.isAuthenticated()) {
+ if (((SubscribeClusterTopologyUpdatesMessage)packet).isClusterConnection()) {
+ ActiveMQServerLogger.LOGGER.unauthenticatedClusterTopologySubscriptionRequest(rc.getRemoteAddress());
+ }
+
+ sendPreAuthTopology();
+ } else {
+ sendPostAuthTopology();
+ }
+ }
+ }
+
+ // Send a single dummy topology response to unblock the client's isLast=true wait (the client blocks
+ // until it receives a topology message before proceeding to CREATE_SESSION). The dummy response
+ // uses PRE_AUTH_NODE_ID and an empty connector pair so no real broker identity or connectivity
+ // information is disclosed to unauthenticated callers.
+ private void sendPreAuthTopology() {
+ preAuthTopologySent = true;
+ Pair<TransportConfiguration, TransportConfiguration> preAuthConfig = new Pair<>(null, new TransportConfiguration(
+ rc.getTransportConnection().getConnectorConfig().getFactoryClassName(), null, Topology.PRE_AUTH_CONNECTOR_NAME));
+
+ logger.debug("Sending pre-authentication topology to unauthenticated connection from {}.", rc.getRemoteAddress());
+
+ entry.connectionExecutor.execute(() -> {
+ if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V4)) {
+ channel0.send(new ClusterTopologyChangeMessage_V4(System.currentTimeMillis(), Topology.PRE_AUTH_NODE_ID,
+ null, null, preAuthConfig, true, server.getVersion().getIncrementingVersion()));
+ } else if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V2)) {
+ channel0.send(new ClusterTopologyChangeMessage_V2(System.currentTimeMillis(),
+ Topology.PRE_AUTH_NODE_ID, null, preAuthConfig, true));
+ } else {
+ channel0.send(new ClusterTopologyChangeMessage(Topology.PRE_AUTH_NODE_ID, preAuthConfig, true));
+ }
+ });
+
+ // Defer the real topology subscription until authentication completes. The subject
+ // listener fires once when setSubject() is called with a non-null subject (i.e. after
+ // a successful CONNECT or CREATE_SESSION), then removes itself to avoid further executions.
+ rc.addAuthenticationListener(new AuthenticationListener() {
+ @Override
+ public void connectionAuthenticated() {
+ rc.removeAuthenticationListener(this);
+ sendPostAuthTopology();
+ }
+ });
+ }
+
+ private void sendPostAuthTopology() {
+ if (!postAuthTopologySent) {
+ postAuthTopologySent = true;
+
+ if (preAuthTopologySent) {
+ // Remove the placeholder entry the client added when it received the pre-auth dummy response.
+ // Without this nodeDown the client's topology map would contain PRE_AUTH_NODE_ID alongside
+ // the real nodes delivered below.
+ entry.connectionExecutor.execute(() -> {
+ if (channel0.supports(PacketImpl.CLUSTER_TOPOLOGY_V2)) {
+ channel0.send(new ClusterTopologyChangeMessage_V2(System.currentTimeMillis(), Topology.PRE_AUTH_NODE_ID));
+ } else {
+ channel0.send(new ClusterTopologyChangeMessage(Topology.PRE_AUTH_NODE_ID));
+ }
+ });
}
final ClusterTopologyListener listener = new ClusterTopologyListener() {
@@ -426,7 +554,7 @@ public class CoreProtocolManager implements ProtocolManager<Interceptor, ActiveM
public void handlePacket(final Packet packet) {
if (packet.getType() == PacketImpl.FEDERATION_DOWNSTREAM_CONNECT) {
if (server.getSecurityStore().isSecurityEnabled()) {
- if (rc.getSubject() == null) {
+ if (!rc.isAuthenticated()) {
ActiveMQServerLogger.LOGGER.federationDownstreamUnauthenticated(rc.getRemoteAddress());
rc.close();
return;
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImpl.java
index 1b3822a61a..3370faca3c 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImpl.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImpl.java
@@ -241,6 +241,7 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC
if (connection != null) {
connection.setSubject(subject);
+ connection.setAuthenticated();
}
if (AuditLogger.isResourceLoggingEnabled()) {
if (connection != null) {
@@ -380,6 +381,9 @@ public class SecurityStoreImpl implements SecurityStore, HierarchicalRepositoryC
if (checkResult == ClusterCredentialsCheckResult.VALID) {
AUTHENTICATION_SUCCESS_COUNT_UPDATER.incrementAndGet(this);
+ if (connection != null) {
+ connection.setAuthenticated();
+ }
return user;
} else if (checkResult == ClusterCredentialsCheckResult.INVALID) {
AUTHENTICATION_FAILURE_COUNT_UPDATER.incrementAndGet(this);
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQMessageBundle.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQMessageBundle.java
index 9ab509ae6a..3a1027dc01 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQMessageBundle.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQMessageBundle.java
@@ -545,4 +545,6 @@ public interface ActiveMQMessageBundle {
@Message(id = 229260, value = "Wildcard addresses are not supported on producers. Only on consumers. Please send to a real address. {}")
ActiveMQException wildcardOnProducerNotSupported(String val);
+ @Message(id = 229261, value = "Authentication mechanism not supported: {}")
+ ActiveMQSecurityException authenticationMechanismNotSupported(String authMechanism);
}
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java
index 31966da0a5..33847c5cac 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/ActiveMQServerLogger.java
@@ -1551,6 +1551,12 @@ public interface ActiveMQServerLogger {
@LogMessage(id = 224164, value = "Failed to recover stored configuration for divert named '{}': {}. To repair this record create a new divert with the same name via the management API.", level = LogMessage.Level.WARN)
void failedToRecoverStoredDivertConfiguration(String divertName, String divert);
+ @LogMessage(id = 224165, value = "Unauthenticated cluster topology subscription request. Update the remote broker to authenticate the cluster connection from {}.", level = LogMessage.Level.WARN)
+ void unauthenticatedClusterTopologySubscriptionRequest(String remoteAddress);
+
+ @LogMessage(id = 224166, value = "Multiple topology subscriptions to connection from {}. Closing connection.", level = LogMessage.Level.WARN)
+ void multipleTopologySubscriptions(String remoteAddress);
+
@LogMessage(id = 224170, value = "Server is stopping. Unable to process redelivery during rollback; ref: {}; transaction: {}; exception message: {}", level = LogMessage.Level.WARN)
void unableToProcessRedeliveryDuringRollback(String messageRef, String transaction, String exceptionMessage);
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/NodeLocator.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/NodeLocator.java
index 7e49a82e82..7e706b687b 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/NodeLocator.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/NodeLocator.java
@@ -20,7 +20,6 @@ import org.apache.activemq.artemis.api.core.ActiveMQException;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ClusterTopologyListener;
-import org.apache.activemq.artemis.core.client.impl.ServerLocatorInternal;
/**
* A class that will locate a particular server running in a cluster. How this server is chosen is a job for the
@@ -77,11 +76,4 @@ public abstract class NodeLocator implements ClusterTopologyListener {
backupRegistrationListener.onBackupRegistrationFailed(alreadyReplicating);
}
}
-
- /**
- * connects to the cluster
- */
- public void connectToCluster(ServerLocatorInternal serverLocator) throws ActiveMQException {
- serverLocator.connect();
- }
}
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BackupManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BackupManager.java
index 20e0596d97..e61706da70 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BackupManager.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/BackupManager.java
@@ -250,6 +250,7 @@ public class BackupManager implements ActiveMQComponent {
backupServerLocator.setIdentity("backupLocatorFor='" + server + "'");
backupServerLocator.setReconnectAttempts(-1);
backupServerLocator.setInitialConnectAttempts(-1);
+ backupServerLocator.setConnectionCredentials(configuration.getClusterUser(), configuration.getClusterPassword());
backupServerLocator.setCallTimeout(config.getCallTimeout());
backupServerLocator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance(backupServerLocator, server.getStorageManager()));
}
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterController.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterController.java
index fcc0d77ae2..28c9725b80 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterController.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterController.java
@@ -24,6 +24,7 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.api.core.ActiveMQException;
+import org.apache.activemq.artemis.api.core.ActiveMQSecurityException;
import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration;
import org.apache.activemq.artemis.api.core.Interceptor;
import org.apache.activemq.artemis.api.core.Pair;
@@ -50,6 +51,7 @@ import org.apache.activemq.artemis.core.server.ActiveMQComponent;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.apache.activemq.artemis.core.server.cluster.quorum.QuorumManager;
+import org.apache.activemq.artemis.core.server.cluster.ClusterManager.IncomingInterceptorLookingForExceptionMessage;
import org.apache.activemq.artemis.core.server.impl.Activation;
import org.apache.activemq.artemis.spi.core.remoting.Acceptor;
import org.slf4j.Logger;
@@ -78,6 +80,7 @@ public class ClusterController implements ActiveMQComponent {
private final Executor executor;
private CountDownLatch replicationClusterConnectedLatch;
+ private Exception replicationClusterConnectingException;
private boolean started;
private SimpleString replicatedClusterName;
@@ -232,6 +235,7 @@ public class ClusterController implements ActiveMQComponent {
//if the cluster isn't available we want to hang around until it is
serverLocator.setReconnectAttempts(config.getReconnectAttempts());
serverLocator.setInitialConnectAttempts(config.getInitialConnectAttempts());
+ serverLocator.setConnectionCredentials(server.getConfiguration().getClusterUser(), server.getConfiguration().getClusterPassword());
serverLocator.setCallTimeout(config.getCallTimeout());
serverLocator.setCallFailoverTimeout(config.getCallFailoverTimeout());
serverLocator.setRetryInterval(config.getRetryInterval());
@@ -240,6 +244,7 @@ public class ClusterController implements ActiveMQComponent {
//this is used for replication so need to use the server packet decoder
serverLocator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance(serverLocator, server.getStorageManager()));
serverLocator.setThreadPools(server.getThreadPool(), server.getScheduledPool(), server.getThreadPool());
+ serverLocator.addIncomingInterceptor(new IncomingInterceptorLookingForExceptionMessage(server.getClusterManager(), executor));
if (connector != null) {
serverLocator.setClusterTransportConfiguration(connector);
}
@@ -318,8 +323,12 @@ public class ClusterController implements ActiveMQComponent {
/**
* wait until we have connected to the cluster.
*/
- public void awaitConnectionToReplicationCluster() throws InterruptedException {
+ public void awaitConnectionToReplicationCluster() throws Exception {
replicationClusterConnectedLatch.await();
+
+ if (replicationClusterConnectingException != null) {
+ throw replicationClusterConnectingException;
+ }
}
/**
@@ -409,7 +418,7 @@ public class ClusterController implements ActiveMQComponent {
boolean userIsValid = false;
try {
- server.validateUser(msg.getClusterUser(), msg.getClusterPassword(), null, null);
+ server.validateUser(msg.getClusterUser(), msg.getClusterPassword(), remotingConnection, null);
userIsValid = true;
} catch (Exception e) {
// cluster user isn't valid
@@ -489,6 +498,13 @@ public class ClusterController implements ActiveMQComponent {
replicationClusterConnectedLatch.countDown();
}
}
+ } catch (ActiveMQSecurityException e) {
+ if (serverLocator == replicationLocator) {
+ replicationClusterConnectingException = e;
+ replicationClusterConnectedLatch.countDown();
+ }
+
+ logger.warn("failed to connect with " + serverLocator);
} catch (ActiveMQException e) {
if (!started) {
return;
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterManager.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterManager.java
index 4661afac34..ecac84215b 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterManager.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/ClusterManager.java
@@ -452,6 +452,7 @@ public class ClusterManager implements ActiveMQComponent {
// We are going to manually retry on the bridge in case of failure
serverLocator.setReconnectAttempts(0);
serverLocator.setInitialConnectAttempts(0);
+ serverLocator.setConnectionCredentials(config.getUser(), config.getPassword());
serverLocator.setRetryInterval(config.getRetryInterval());
serverLocator.setMaxRetryInterval(config.getMaxRetryInterval());
serverLocator.setRetryIntervalMultiplier(config.getRetryIntervalMultiplier());
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BridgeImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BridgeImpl.java
index 6cce715848..73ecc2e271 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BridgeImpl.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/BridgeImpl.java
@@ -915,7 +915,7 @@ public class BridgeImpl implements Bridge, SessionFailureListener, SendAcknowled
csf = reconnectOnOriginalNode();
} else {
serverLocator.resetToInitialConnectors();
- csf = (ClientSessionFactoryInternal) serverLocator.createSessionFactory();
+ csf = (ClientSessionFactoryInternal) serverLocator.createSessionFactory(configuration.getUser(), configuration.getPassword());
}
// null here means the targetNodeIS is not available yet
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionImpl.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionImpl.java
index 3cbccd655d..9c49805fa9 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionImpl.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/cluster/impl/ClusterConnectionImpl.java
@@ -725,11 +725,13 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
try (ServerLocatorInternal targetLocator = new ServerLocatorImpl(topology, true, transportConfiguration)) {
targetLocator.setReconnectAttempts(0);
targetLocator.setInitialConnectAttempts(0);
+ targetLocator.setConnectionCredentials(clusterUser, clusterPassword);
targetLocator.setConnectionTTL(connectionTTL);
targetLocator.setCallTimeout(callTimeout);
targetLocator.setNodeID(nodeManager.getNodeId().toString());
targetLocator.setClusterTransportConfiguration(connector);
targetLocator.setIdentity("(Cluster-topology-scanner::" + server.toString() + ")");
+ targetLocator.addIncomingInterceptor(new IncomingInterceptorLookingForExceptionMessage(manager, executor));
try {
try (ClientSessionFactoryInternal targetClientSessionFactory = targetLocator.connect()) {
@@ -880,6 +882,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
serverLocator.setClusterConnection(true);
serverLocator.setClusterTransportConfiguration(connector);
serverLocator.setInitialConnectAttempts(-1);
+ serverLocator.setConnectionCredentials(clusterUser, clusterPassword);
serverLocator.setClientFailureCheckPeriod(clientFailureCheckPeriod);
serverLocator.setConnectionTTL(connectionTTL);
serverLocator.setConfirmationWindowSize(confirmationWindowSize);
@@ -1065,6 +1068,7 @@ public final class ClusterConnectionImpl implements ClusterConnection, AfterConn
targetLocator.setReconnectAttempts(0);
targetLocator.setInitialConnectAttempts(0);
+ targetLocator.setConnectionCredentials(clusterUser, clusterPassword);
targetLocator.setClientFailureCheckPeriod(clientFailureCheckPeriod);
targetLocator.setConnectionTTL(connectionTTL);
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/federation/FederationConnection.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/federation/FederationConnection.java
index 132e0bf460..791ecbb423 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/federation/FederationConnection.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/federation/FederationConnection.java
@@ -171,7 +171,7 @@ public class FederationConnection {
if (clientSessionFactory != null && !clientSessionFactory.isClosed()) {
return clientSessionFactory;
} else {
- clientSessionFactory = serverLocator.createSessionFactory();
+ clientSessionFactory = serverLocator.createSessionFactory(config.getUsername(), config.getPassword());
this.clientSessionFactory = clientSessionFactory;
return clientSessionFactory;
}
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupRecoveryJournalLoader.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupRecoveryJournalLoader.java
index 4a39855aed..4e607591b3 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupRecoveryJournalLoader.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/BackupRecoveryJournalLoader.java
@@ -95,7 +95,7 @@ public class BackupRecoveryJournalLoader extends PostOfficeJournalLoader {
ScaleDownHandler scaleDownHandler = new ScaleDownHandler(pagingManager, postOffice, nodeManager, clusterController, parentServer != null ? parentServer.getStorageManager() : storageManager, parentServer != null ? parentServer.getHAPolicy().getScaleDownCommitInterval() : -1);
locator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance(locator, storageManager));
- try (ClientSessionFactory sessionFactory = locator.createSessionFactory()) {
+ try (ClientSessionFactory sessionFactory = locator.createSessionFactory(configuration.getClusterUser(), configuration.getClusterPassword())) {
scaleDownHandler.scaleDown(sessionFactory, resourceManager, duplicateIDMap, parentServer != null ? parentServer.getConfiguration().getManagementAddress() : configuration.getManagementAddress(), parentServer != null ? parentServer.getNodeID() : null);
}
}
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/PrimaryOnlyActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/PrimaryOnlyActivation.java
index 098d9a1c11..0efedb9032 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/PrimaryOnlyActivation.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/PrimaryOnlyActivation.java
@@ -147,11 +147,12 @@ public class PrimaryOnlyActivation extends Activation {
try {
scaleDownServerLocator = ScaleDownPolicy.getScaleDownConnector(scaleDownPolicy, activeMQServer);
//use a Node Locator to connect to the cluster
+ scaleDownServerLocator.setConnectionCredentials(activeMQServer.getConfiguration().getClusterUser(), activeMQServer.getConfiguration().getClusterPassword());
scaleDownServerLocator.setProtocolManagerFactory(ActiveMQServerSideProtocolManagerFactory.getInstance(scaleDownServerLocator, activeMQServer.getStorageManager()));
NodeLocator nodeLocator = scaleDownPolicy.getGroupName() == null ? new AnyNodeLocatorForScaleDown(activeMQServer) : new NamedNodeLocatorForScaleDown(scaleDownPolicy.getGroupName(), activeMQServer);
scaleDownServerLocator.addClusterTopologyListener(nodeLocator);
- nodeLocator.connectToCluster(scaleDownServerLocator);
+ scaleDownServerLocator.connect();
// a timeout is necessary here in case we use a NamedNodeLocatorForScaleDown and there's no matching node in the cluster
// should the timeout be configurable?
nodeLocator.locateNode(ActiveMQClient.DEFAULT_DISCOVERY_INITIAL_WAIT_TIMEOUT);
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ReplicationBackupActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ReplicationBackupActivation.java
index d46d1f18be..28bebbcf3c 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ReplicationBackupActivation.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/ReplicationBackupActivation.java
@@ -212,7 +212,14 @@ public final class ReplicationBackupActivation extends Activation implements Dis
logger.info("Apache ActiveMQ Artemis Backup Server version {} [{}] started, awaiting connection to a primary to start replication", activeMQServer.getVersion().getFullVersion(),
activeMQServer.toString());
- clusterController.awaitConnectionToReplicationCluster();
+ try {
+ clusterController.awaitConnectionToReplicationCluster();
+ } catch (Exception e) {
+ logger.error("Stopping the broker because the connection to the replication cluster failed", e);
+ asyncRestartServer(activeMQServer, false);
+ return;
+ }
+
activeMQServer.getBackupManager().start();
final DistributedLock primaryLock = replicateAndFailover(clusterController);
if (primaryLock == null) {
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingBackupActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingBackupActivation.java
index 206bfc1d48..bc8b4b3eb2 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingBackupActivation.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingBackupActivation.java
@@ -150,7 +150,13 @@ public final class SharedNothingBackupActivation extends Activation implements R
clusterController.addClusterTopologyListenerForReplication(nodeLocator);
logger.trace("Waiting on cluster connection");
- clusterController.awaitConnectionToReplicationCluster();
+ try {
+ clusterController.awaitConnectionToReplicationCluster();
+ } catch (Exception e) {
+ logger.error("Stopping the broker because the connection to the replication cluster failed", e);
+ asyncStopServer(activeMQServer, false);
+ return;
+ }
logger.trace("Cluster Connected");
@@ -239,30 +245,7 @@ public final class SharedNothingBackupActivation extends Activation implements R
break;
} else if (signal == SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAILURE_REPLICATING || signal == SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAILURE_RETRY) {
// something has gone badly run restart from scratch
- logger.trace("Starting a new thread to stop the server!");
-
- final SharedNothingBackupQuorum.BACKUP_ACTIVATION signalToStop = signal;
-
- Thread startThread = new Thread(() -> {
- try {
- logger.trace("Calling activeMQServer.stop() as initialization failed");
-
- if (activeMQServer.getState() != ActiveMQServer.SERVER_STATE.STOPPED &&
- activeMQServer.getState() != ActiveMQServer.SERVER_STATE.STOPPING) {
-
- if (signalToStop == SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAILURE_RETRY) {
- activeMQServer.stop(false);
- logger.trace("The server was shutdown for a network isolation, we keep retrying");
- activeMQServer.start();
- } else {
- activeMQServer.stop();
- }
- }
- } catch (Exception e) {
- ActiveMQServerLogger.LOGGER.errorRestartingBackupServer(activeMQServer, e);
- }
- });
- startThread.start();
+ asyncStopServer(activeMQServer, signal == SharedNothingBackupQuorum.BACKUP_ACTIVATION.FAILURE_RETRY);
return;
}
//ok, this primary is no good, let's reset and try again
@@ -335,6 +318,35 @@ public final class SharedNothingBackupActivation extends Activation implements R
}
}
+ private void asyncStopServer(final ActiveMQServer server, boolean restart) {
+ logger.trace("Starting a new thread to stop the server!");
+
+ Thread stopThread = new Thread(() -> {
+ try {
+ logger.trace("Calling activeMQServer.stop() as initialization failed");
+
+ if (server.getState() != ActiveMQServer.SERVER_STATE.STOPPED &&
+ server.getState() != ActiveMQServer.SERVER_STATE.STOPPING) {
+
+ if (restart) {
+ server.stop(false);
+ logger.trace("The server was shutdown for a network isolation, we keep retrying");
+ server.start();
+ } else {
+ server.stop();
+ }
+ }
+ } catch (Exception e) {
+ if (restart) {
+ ActiveMQServerLogger.LOGGER.errorRestartingBackupServer(activeMQServer, e);
+ } else {
+ ActiveMQServerLogger.LOGGER.errorStoppingServer(e);
+ }
+ }
+ });
+ stopThread.start();
+ }
+
private static ClusterControl tryConnectToNodeInReplicatedCluster(ClusterController clusterController, TransportConfiguration tc) {
try {
logger.trace("Calling clusterController.connectToNodeInReplicatedCluster({})", tc);
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingPrimaryActivation.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingPrimaryActivation.java
index 97475f40b7..2d300db21b 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingPrimaryActivation.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/impl/SharedNothingPrimaryActivation.java
@@ -312,6 +312,7 @@ public class SharedNothingPrimaryActivation extends PrimaryActivation {
try (ServerLocatorInternal locator = getLocator(config)) {
locator.addClusterTopologyListener(listener);
locator.setReconnectAttempts(0);
+ locator.setConnectionCredentials(activeMQServer.getConfiguration().getClusterUser(), activeMQServer.getConfiguration().getClusterPassword());
try (ClientSessionFactoryInternal factory = locator.connectNoWarnings()) {
// Just try connecting
listener.latch.await(5, TimeUnit.SECONDS);
@@ -417,7 +418,7 @@ public class SharedNothingPrimaryActivation extends PrimaryActivation {
boolean result = false;
try (ServerLocator serverLocator = ActiveMQClient.createServerLocator(false, transportConfiguration);
- ClientSessionFactory clientSessionFactory = serverLocator.createSessionFactory();
+ ClientSessionFactory clientSessionFactory = serverLocator.createSessionFactory(user, password);
ClientSession clientSession = clientSessionFactory.createSession(user, password, false, false, false, false, 0)) {
result = true;
} catch (Exception e) {
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/routing/targets/ActiveMQTarget.java b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/routing/targets/ActiveMQTarget.java
index f9e69f53d5..1312801801 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/routing/targets/ActiveMQTarget.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/core/server/routing/targets/ActiveMQTarget.java
@@ -61,7 +61,7 @@ public class ActiveMQTarget extends AbstractTarget implements FailureListener {
@Override
public void connect() throws Exception {
- sessionFactory = serverLocator.createSessionFactory();
+ sessionFactory = serverLocator.createSessionFactory(getUsername(), getPassword());
remotingConnection = sessionFactory.getConnection();
remotingConnection.addFailureListener(this);
diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandlerTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandlerTest.java
new file mode 100644
index 0000000000..762898ebc0
--- /dev/null
+++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/protocol/core/impl/ActiveMQPacketHandlerTest.java
@@ -0,0 +1,262 @@
+/*
+ * 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.activemq.artemis.core.protocol.core.impl;
+
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.activemq.artemis.api.core.ActiveMQSecurityException;
+import org.apache.activemq.artemis.api.core.SimpleString;
+import org.mockito.ArgumentCaptor;
+import org.apache.activemq.artemis.core.protocol.core.Channel;
+import org.apache.activemq.artemis.core.protocol.core.CoreRemotingConnection;
+import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ActiveMQExceptionMessage;
+import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ConnectMessage;
+import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.ConnectResponseMessage;
+import org.apache.activemq.artemis.core.security.SecurityStore;
+import org.apache.activemq.artemis.core.server.ActiveMQServer;
+import org.apache.activemq.artemis.core.server.cluster.ha.HAPolicy;
+import org.apache.activemq.artemis.core.version.Version;
+import org.apache.activemq.artemis.utils.ExecutorFactory;
+import org.apache.activemq.artemis.utils.actors.ArtemisExecutor;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.stubbing.Answer;
+
+public class ActiveMQPacketHandlerTest {
+
+ private static final long LATCH_TIMEOUT_MS = 5000;
+
+ private ActiveMQServer server;
+ private Channel channel1;
+ private CoreRemotingConnection connection;
+ private CoreProtocolManager protocolManager;
+ private SecurityStore securityStore;
+
+ @BeforeEach
+ public void setUp() {
+ server = mock(ActiveMQServer.class);
+ channel1 = mock(Channel.class);
+ connection = mock(CoreRemotingConnection.class);
+ protocolManager = mock(CoreProtocolManager.class);
+ securityStore = mock(SecurityStore.class);
+
+ Version version = mock(Version.class);
+ when(version.getIncrementingVersion()).thenReturn(1);
+
+ ExecutorFactory executorFactory = () -> ArtemisExecutor.delegate(Executors.newSingleThreadExecutor());
+ when(server.getExecutorFactory()).thenReturn(executorFactory);
+ when(server.getSecurityStore()).thenReturn(securityStore);
+ when(server.getVersion()).thenReturn(version);
+ when(server.getNodeID()).thenReturn(SimpleString.of("test-node"));
+ when(server.getHAPolicy()).thenReturn(mock(HAPolicy.class));
+ }
+
+ /**
+ * When security is enabled, coreConnectionSecurity is enabled, and PLAIN credentials
+ * are supplied, validateUser must be called with the decoded username and password.
+ */
+ @Test
+ public void testHandleConnectPlainCredentialsCallsValidateUser() throws Exception {
+ when(securityStore.isSecurityEnabled()).thenReturn(true);
+ when(protocolManager.isCoreConnectionSecurityEnabled()).thenReturn(true);
+ when(server.validateUser(any(), any(), any(), any())).thenReturn("cluster-user");
+
+ CountDownLatch latch = countdownOnChannelSend();
+
+ ConnectMessage msg = ConnectMessage.withPlainCredentials("test-node", 1, "cluster-user", "cluster-pass");
+ newHandler().handlePacket(msg);
+
+ latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+ verify(server).validateUser(eq("cluster-user"), eq("cluster-pass"), eq(connection), isNull());
+ verify(channel1).send(any(ConnectResponseMessage.class));
+ }
+
+ /**
+ * When authMechanism is null (legacy client), authentication must be skipped
+ * regardless of security/coreConnectionSecurity settings.
+ */
+ @Test
+ public void testHandleConnectLegacyClientSkipsAuth() throws Exception {
+ when(securityStore.isSecurityEnabled()).thenReturn(true);
+ when(protocolManager.isCoreConnectionSecurityEnabled()).thenReturn(true);
+
+ CountDownLatch latch = countdownOnChannelSend();
+
+ ConnectMessage legacyMsg = new ConnectMessage("test-node", 1);
+ newHandler().handlePacket(legacyMsg);
+
+ latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+ verify(server, never()).validateUser(any(), any(), any(), any());
+ verify(channel1).send(any(ConnectResponseMessage.class));
+ }
+
+ /**
+ * When security is disabled, validateUser must not be called even when PLAIN
+ * credentials are present.
+ */
+ @Test
+ public void testHandleConnectSecurityDisabledSkipsAuth() throws Exception {
+ when(securityStore.isSecurityEnabled()).thenReturn(false);
+ when(protocolManager.isCoreConnectionSecurityEnabled()).thenReturn(true);
+
+ CountDownLatch latch = countdownOnChannelSend();
+
+ ConnectMessage msg = ConnectMessage.withPlainCredentials("test-node", 1, "u", "p");
+ newHandler().handlePacket(msg);
+
+ latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+ verify(server, never()).validateUser(any(), any(), any(), any());
+ verify(channel1).send(any(ConnectResponseMessage.class));
+ }
+
+ /**
+ * When coreConnectionSecurity is disabled, validateUser must not be called even
+ * when PLAIN credentials are present.
+ */
+ @Test
+ public void testHandleConnectCoreConnectionSecurityDisabledSkipsAuth() throws Exception {
+ when(securityStore.isSecurityEnabled()).thenReturn(true);
+ when(protocolManager.isCoreConnectionSecurityEnabled()).thenReturn(false);
+
+ CountDownLatch latch = countdownOnChannelSend();
+
+ ConnectMessage msg = ConnectMessage.withPlainCredentials("test-node", 1, "u", "p");
+ newHandler().handlePacket(msg);
+
+ latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+ verify(server, never()).validateUser(any(), any(), any(), any());
+ verify(channel1).send(any(ConnectResponseMessage.class));
+ }
+
+ /**
+ * When validateUser throws, an ActiveMQExceptionMessage containing an
+ * ActiveMQSecurityException must be sent back and the connection must be closed.
+ */
+ @Test
+ public void testHandleConnectBadCredentialsSendsExceptionAndClosesConnection() throws Exception {
+ when(securityStore.isSecurityEnabled()).thenReturn(true);
+ when(protocolManager.isCoreConnectionSecurityEnabled()).thenReturn(true);
+ when(server.validateUser(any(), any(), any(), any()))
+ .thenThrow(new ActiveMQSecurityException("bad credentials"));
+
+ CountDownLatch latch = countdownOnChannelSendAndFlush();
+
+ ConnectMessage msg = ConnectMessage.withPlainCredentials("test-node", 1, "wrong", "wrong");
+ newHandler().handlePacket(msg);
+
+ latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+ ArgumentCaptor<ActiveMQExceptionMessage> captor = ArgumentCaptor.forClass(ActiveMQExceptionMessage.class);
+ verify(channel1).sendAndFlush(captor.capture());
+ assertInstanceOf(ActiveMQSecurityException.class, captor.getValue().getException(),
+ "exception message must carry an ActiveMQSecurityException");
+ verify(connection).close();
+ verify(channel1, never()).send(any(ConnectResponseMessage.class));
+ }
+
+ /**
+ * When an unsupported auth mechanism is sent, an ActiveMQExceptionMessage containing
+ * an ActiveMQSecurityException must be sent back and the connection must be closed.
+ */
+ @Test
+ public void testHandleConnectUnsupportedMechanismSendsExceptionAndClosesConnection() throws Exception {
+ when(securityStore.isSecurityEnabled()).thenReturn(true);
+ when(protocolManager.isCoreConnectionSecurityEnabled()).thenReturn(true);
+
+ CountDownLatch latch = countdownOnChannelSendAndFlush();
+
+ ConnectMessage msg = new ConnectMessage("test-node", 1);
+ msg.setAuthMechanism("GSSAPI");
+
+ newHandler().handlePacket(msg);
+
+ latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+ ArgumentCaptor<ActiveMQExceptionMessage> captor = ArgumentCaptor.forClass(ActiveMQExceptionMessage.class);
+ verify(channel1).sendAndFlush(captor.capture());
+ assertInstanceOf(ActiveMQSecurityException.class, captor.getValue().getException(),
+ "exception message must carry an ActiveMQSecurityException");
+ verify(connection).close();
+ verify(channel1, never()).send(any(ConnectResponseMessage.class));
+ }
+
+ /**
+ * A second CONNECT packet on the same connection must be ignored and the
+ * connection must be closed — only one ConnectResponseMessage must be sent.
+ */
+ @Test
+ public void testHandleConnectDuplicateConnectClosesConnection() throws Exception {
+ when(securityStore.isSecurityEnabled()).thenReturn(false);
+
+ // Two packets: first latch counts down on the response, second triggers connection.close()
+ CountDownLatch responseLatch = countdownOnChannelSend();
+ CountDownLatch closeLatch = new CountDownLatch(1);
+ doAnswer((Answer<Void>) inv -> {
+ closeLatch.countDown();
+ return null;
+ }).when(connection).close();
+
+ ConnectMessage msg = new ConnectMessage("test-node", 1);
+ ActiveMQPacketHandler handler = newHandler();
+ handler.handlePacket(msg);
+ responseLatch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+ handler.handlePacket(msg);
+ closeLatch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+
+ verify(channel1).send(any(ConnectResponseMessage.class));
+ verify(connection).close();
+ }
+
+ private ActiveMQPacketHandler newHandler() {
+ return new ActiveMQPacketHandler(protocolManager, server, channel1, connection);
+ }
+
+ private CountDownLatch countdownOnChannelSend() {
+ CountDownLatch latch = new CountDownLatch(1);
+ doAnswer((Answer<Void>) inv -> {
+ latch.countDown();
+ return null;
+ }).when(channel1).send(any());
+ return latch;
+ }
+
+ private CountDownLatch countdownOnChannelSendAndFlush() {
+ CountDownLatch latch = new CountDownLatch(1);
+ doAnswer((Answer<Void>) inv -> {
+ latch.countDown();
+ return null;
+ }).when(channel1).sendAndFlush(any());
+ return latch;
+ }
+}
diff --git a/artemis-server/src/test/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImplTest.java b/artemis-server/src/test/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImplTest.java
index 915ea76b03..d7a1b23ce0 100644
--- a/artemis-server/src/test/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImplTest.java
+++ b/artemis-server/src/test/java/org/apache/activemq/artemis/core/security/impl/SecurityStoreImplTest.java
@@ -875,6 +875,43 @@ public class SecurityStoreImplTest {
}
}
+ @Test
+ public void testAuthenticateCallsSetAuthenticatedOnConnection() throws Exception {
+ SecurityStoreImpl securityStore = new SecurityStoreImpl(new HierarchicalObjectRepository<>(), permitAll, 999, true, "", null, null, 10, 10);
+ RemotingConnection connection = Mockito.mock(RemotingConnection.class);
+
+ securityStore.authenticate("user", "password", connection, null);
+
+ Mockito.verify(connection, Mockito.times(1)).setAuthenticated();
+ }
+
+ @Test
+ public void testClusterAuthenticateCallsSetAuthenticatedOnConnection() throws Exception {
+ final String clusterUser = "clusterUser";
+ final String clusterPassword = "clusterPassword";
+ SecurityStoreImpl securityStore = new SecurityStoreImpl(new HierarchicalObjectRepository<>(), permitAll, 999, true, clusterUser, clusterPassword, null, 10, 10);
+ RemotingConnection connection = Mockito.mock(RemotingConnection.class);
+
+ securityStore.authenticate(clusterUser, clusterPassword, connection, null);
+
+ Mockito.verify(connection, Mockito.times(1)).setAuthenticated();
+ }
+
+ @Test
+ public void testAuthenticateDoesNotCallSetAuthenticatedOnFailure() throws Exception {
+ SecurityStoreImpl securityStore = new SecurityStoreImpl(new HierarchicalObjectRepository<>(), denyAll, 999, true, "", null, null, 10, 10);
+ RemotingConnection connection = Mockito.mock(RemotingConnection.class);
+
+ try {
+ securityStore.authenticate("user", "password", connection, null);
+ fail("Authentication must fail");
+ } catch (Exception ignored) {
+ // expected
+ }
+
+ Mockito.verify(connection, Mockito.never()).setAuthenticated();
+ }
+
private static SecurityAuth getSecurityAuth(String user, String password) {
SecurityAuth session = Mockito.mock(SecurityAuth.class);
Mockito.when(session.getUsername()).thenReturn(user);
diff --git a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceWrapper.java b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceWrapper.java
index b2b7b30c62..d10a472fed 100644
--- a/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceWrapper.java
+++ b/artemis-service-extensions/src/main/java/org/apache/activemq/artemis/service/extensions/xa/recovery/ActiveMQXAResourceWrapper.java
@@ -289,7 +289,7 @@ public class ActiveMQXAResourceWrapper implements XAResource, SessionFailureList
serverLocator.setLocatorConfig(xaRecoveryConfig.getLocatorConfig());
}
serverLocator.setProtocolManagerFactory(xaRecoveryConfig.getClientProtocolManager());
- csf = serverLocator.createSessionFactory();
+ csf = serverLocator.createSessionFactory(xaRecoveryConfig.getUsername(), xaRecoveryConfig.getPassword());
if (xaRecoveryConfig.getUsername() == null) {
cs = csf.createSession(true, false, false);
} else {
diff --git a/docs/user-manual/core.adoc b/docs/user-manual/core.adoc
index 2d4cef8eaf..dcc52915fd 100644
--- a/docs/user-manual/core.adoc
+++ b/docs/user-manual/core.adoc
@@ -61,6 +61,74 @@ In JMS terms think of them as JMS Connections.
`ClientSessionFactory` instances are created using the `ServerLocator` class.
+[[core-connection-handshake]]
+=== Connection handshake
+
+When a Core client connects to a broker it sends:
+
+* the expected node id in case of failover
+* the client's protocol version
+* optional connection-level username and password
+
+Core application clients can pass credentials when creating a session factory to authenticate the underlying connection:
+
+[,java]
+----
+ServerLocator locator = ...;
+locator.setConnectionCredentials(user, password);
+ClientSessionFactory factory = locator.createSessionFactory(user, password);
+----
+
+The JMS connection factory sets connection credentials automatically when `setUser` / `setPassword` are called.
+
+Cluster-internal components on current brokers (cluster connections, bridges, replicated backups, federation links, etc.) pass their configured `cluster-user` / `cluster-password` or bridge credentials in the connect handshake automatically.
+
+When security is enabled and no connection credentials are supplied, the broker responds to topology subscription with a placeholder entry so the client can complete its handshake, but real broker topology is sent only after authentication succeeds.
+
+==== Server-side configuration
+
+Core connection security applies only when broker security is enabled (`security-enabled` in `broker.xml`).
+It is configured per acceptor on the Core protocol manager using URL parameters, in the same way as other protocol-specific acceptor settings (see xref:configuring-transports.adoc#configuring-the-transport[Configuring the Transport]).
+
+The following parameters are supported on any acceptor that handles the Core protocol:
+
+`coreConnectionSecurityEnabled`::
+Whether connection-level security is enabled for Core on this acceptor.
+When `true` (the default) and broker security is enabled, the broker:
+
+* validates optional credentials in the connect packet
+* sends a placeholder topology response to unauthenticated clients
+* installs a reduced Netty frame size limit until the connection is authenticated
+
+`coreInitialMaxFrameSize`::
+Maximum Core frame size in bytes allowed on a Netty connection *before* authentication completes.
+Default: `4096` (4 KiB).
+Frames larger than this limit are rejected with a decoder error and the connection is closed.
+
+`coreMaxFrameSize`::
+Maximum Core frame size in bytes allowed on a Netty connection *after* authentication completes.
+Default: `131072` (128 KiB).
+The limit is raised automatically once the connection `Subject` is set (for example after a successful `CONNECT` with credentials or after `CREATE_SESSION`).
+
+Example disabling Core connection security on an acceptor:
+
+[,xml]
+----
+<acceptor name="artemis">tcp://0.0.0.0:61616?protocols=CORE,AMQP;coreConnectionSecurityEnabled=false</acceptor>
+----
+
+Example keeping Core connection security enabled but increasing the post-authentication frame limit:
+
+[,xml]
+----
+<acceptor name="artemis">tcp://0.0.0.0:61616?protocols=CORE,AMQP;coreInitialMaxFrameSize=4096;coreMaxFrameSize=1048576</acceptor>
+----
+
+NOTE: These frame size limits apply to Netty-based Core connections.
+In-VM Core connections do not use the size-limited decoder.
+
+For embedded brokers, the same settings can be applied programmatically on `CoreProtocolManager` via `setCoreConnectionSecurityEnabled`, `setCoreInitialMaxFrameSize`, and `setCoreMaxFrameSize`.
+
=== ClientSession
A client uses a ``ClientSession``for consuming and producing messages and for grouping them in transactions.
diff --git a/docs/user-manual/versions.adoc b/docs/user-manual/versions.adoc
index 518c121fbb..94a52598bd 100644
--- a/docs/user-manual/versions.adoc
+++ b/docs/user-manual/versions.adoc
@@ -30,6 +30,18 @@ See xref:persistence.adoc#configuring-the-message-journal[configuring the messag
=== Upgrading from 2.55.0
+* The Core protocol connect handshake packet was extended in a backward-compatible way on the wire (same packet type identifiers).
+When security is enabled, Core clients that authenticate at connection time should pass credentials via `ServerLocator.setConnectionCredentials(user, password)` or `ServerLocator.createSessionFactory(user, password)`.
+Cluster components on new brokers (cluster connections, bridges, backups, federation) do this automatically using the configured `cluster-user` / `cluster-password` or bridge `user` / `password`.
+See xref:core.adoc#core-connection-handshake[Core connection handshake] for details.
+* On secured Core connections the broker initially limits frame size to 4 KiB until the connection is authenticated, then raises the limit to 128 KiB.
+Unauthenticated clients no longer receive real cluster topology; they receive a placeholder response until authentication succeeds.
+Both behaviors can be tuned or disabled per acceptor; see xref:core.adoc#core-connection-handshake[Core connection handshake].
+* *Upgrade brokers before mixing old and new versions in a secured cluster.*
+An old broker connecting to a broker that has already been upgraded does not send connection-level credentials in the Core connect handshake.
+The upgraded broker therefore treats the connection as unauthenticated and responds with only the placeholder topology entry, not the real cluster view.
+Until that old broker is upgraded as well, it may be unable to discover or connect properly to the new brokers (cluster connections, bridges, replication, backup registration, and similar Core links can fail or stall).
+Upgrade every broker in the cluster, or temporarily disable `coreConnectionSecurityEnabled` on acceptors during a transitional window, before relying on cross-version cluster connectivity.
* Due to https://issues.apache.org/jira/browse/ARTEMIS-6128[ARTEMIS-6128] the `Alder32` and `fileAlder32` properties have been deprecated in favor of `Adler32` and `fileAdler32` respectively.
* Due to https://issues.apache.org/jira/browse/ARTEMIS-6172[ARTEMIS-6172] the HTTP-specific transport parameters deprecated by https://issues.apache.org/jira/browse/ARTEMIS-5819[ARTEMIS-5819] (`httpClientIdleTime`, `httpClientIdleScanPeriod`, `httpResponseTime`, `httpServerScanPeriod`) are restored.
These are required so HTTP-tunneled Core connections can create response slots for server-initiated packets (for example cluster topology updates) without starving replies to client requests.
diff --git a/tests/compatibility-tests/src/main/resources/multiVersionReplica/mainServer.groovy b/tests/compatibility-tests/src/main/resources/multiVersionReplica/mainServer.groovy
index d2b361a2b3..f910ab4f26 100644
--- a/tests/compatibility-tests/src/main/resources/multiVersionReplica/mainServer.groovy
+++ b/tests/compatibility-tests/src/main/resources/multiVersionReplica/mainServer.groovy
@@ -38,11 +38,12 @@ String id = arg[1];
String port = arg[2];
String backupPort = arg[3]
boolean security = Boolean.valueOf(arg[4]);
+boolean coreConnectionSecurity = Boolean.valueOf(arg[5]);
configuration = new ConfigurationImpl();
configuration.setJournalType(JournalType.NIO);
configuration.setBrokerInstance(new File(folder + "/" + id));
-configuration.addAcceptorConfiguration("artemis", "tcp://localhost:" + port);
+configuration.addAcceptorConfiguration("artemis", "tcp://localhost:" + port + "?coreConnectionSecurityEnabled=" + coreConnectionSecurity);
configuration.addConnectorConfiguration("local", "tcp://localhost:" + port);
configuration.setSecurityEnabled(security);
if (security) {
diff --git a/tests/compatibility-tests/src/test/java/org/apache/activemq/artemis/tests/compatibility/MultiVersionReplicaTest.java b/tests/compatibility-tests/src/test/java/org/apache/activemq/artemis/tests/compatibility/MultiVersionReplicaTest.java
index ead61556f0..b4925d7e14 100644
--- a/tests/compatibility-tests/src/test/java/org/apache/activemq/artemis/tests/compatibility/MultiVersionReplicaTest.java
+++ b/tests/compatibility-tests/src/test/java/org/apache/activemq/artemis/tests/compatibility/MultiVersionReplicaTest.java
@@ -110,7 +110,9 @@ public class MultiVersionReplicaTest extends ClasspathBase {
@TestTemplate
public void testReplica() throws Throwable {
System.out.println("Starting live");
- evaluate(mainClassloader, "multiVersionReplica/mainServer.groovy", serverFolder.getAbsolutePath(), "1", "61000", "61001", String.valueOf(security));
+ // To ensure backward compatibility, core connection security must be disabled on newer live brokers so legacy backup brokers can connect.
+ boolean coreConnectionSecurity = security && (!SNAPSHOT.equals(main) || SNAPSHOT.equals(backup));
+ evaluate(mainClassloader, "multiVersionReplica/mainServer.groovy", serverFolder.getAbsolutePath(), "1", "61000", "61001", String.valueOf(security), String.valueOf(coreConnectionSecurity));
System.out.println("Starting backup");
evaluate(backupClassLoader, "multiVersionReplica/backupServer.groovy", serverFolder.getAbsolutePath(), "2", "61001", "61000", String.valueOf(security));
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CoreConnectHandshakeTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CoreConnectHandshakeTest.java
new file mode 100644
index 0000000000..4b3e0aec55
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/client/CoreConnectHandshakeTest.java
@@ -0,0 +1,124 @@
+/*
+ * 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.activemq.artemis.tests.integration.client;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.activemq.artemis.api.core.ActiveMQSecurityException;
+import org.apache.activemq.artemis.api.core.QueueConfiguration;
+import org.apache.activemq.artemis.api.core.TransportConfiguration;
+import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
+import org.apache.activemq.artemis.api.core.client.ClientSession;
+import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
+import org.apache.activemq.artemis.api.core.client.ServerLocator;
+import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
+import org.apache.activemq.artemis.core.security.Role;
+import org.apache.activemq.artemis.core.server.ActiveMQServer;
+import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl;
+import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager;
+import org.apache.activemq.artemis.spi.core.security.jaas.InVMLoginModule;
+import org.apache.activemq.artemis.core.config.impl.SecurityConfiguration;
+import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
+import org.apache.activemq.artemis.tests.util.Wait;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class CoreConnectHandshakeTest extends ActiveMQTestBase {
+
+ private static final String CONNECT_USER = "connectUser";
+
+ private static final String CONNECT_PASS = "connectPass";
+
+ private ActiveMQServer server;
+
+ private TransportConfiguration connector;
+
+ @Override
+ @BeforeEach
+ public void setUp() throws Exception {
+ super.setUp();
+
+ connector = getNettyConnectorTransportConfiguration(true);
+
+ final ConfigurationImpl config = (ConfigurationImpl) createDefaultNettyConfig();
+ config.setSecurityEnabled(true);
+ config.setClusterUser("clusterUser");
+ config.setClusterPassword(CLUSTER_PASSWORD);
+ config.addConnectorConfiguration(connector.getName(), connector);
+ config.addClusterConfiguration(basicClusterConnectionConfig(connector.getName(), connector.getName()));
+
+ final SecurityConfiguration securityConfiguration = new SecurityConfiguration();
+ securityConfiguration.addUser(CONNECT_USER, CONNECT_PASS);
+ securityConfiguration.addRole(CONNECT_USER, "role");
+
+ final ActiveMQJAASSecurityManager securityManager =
+ new ActiveMQJAASSecurityManager(InVMLoginModule.class.getName(), securityConfiguration);
+
+ server = addServer(new ActiveMQServerImpl(config, securityManager));
+
+ final Role role = new Role("role", true, true, true, true, true, true, true, true, true, true, false, false);
+ final Set<Role> roles = new HashSet<>();
+ roles.add(role);
+ server.getSecurityRepository().addMatch("#", roles);
+
+ server.start();
+ }
+
+ @Test
+ public void testWrongConnectionCredentialsRejectedAtConnect() throws Exception {
+ try (ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(connector))) {
+ locator.setConnectionCredentials("wrong", "wrong");
+
+ assertThrows(ActiveMQSecurityException.class, () -> locator.createSessionFactory("wrong", "wrong"));
+ }
+ }
+
+ @Test
+ public void testPreAuthTopologyHiddenUntilSessionAuth() throws Exception {
+ try (ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(connector))) {
+ try (ClientSessionFactory sessionFactory = locator.createSessionFactory()) {
+ assertTrue(locator.getTopology().getMembers().isEmpty(),
+ "topology must not expose broker nodes before session authentication");
+
+ try (ClientSession session = sessionFactory.createSession(CONNECT_USER, CONNECT_PASS, false, true, true, false, 1)) {
+ Wait.assertTrue(() -> locator.getTopology().getMember(server.getNodeID().toString()) != null,
+ 5000, 100);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testConnectionCredentialsAuthenticateBeforeTopology() throws Exception {
+ try (ServerLocator locator = addServerLocator(ActiveMQClient.createServerLocatorWithoutHA(connector))) {
+ locator.setConnectionCredentials(CONNECT_USER, CONNECT_PASS);
+
+ try (ClientSessionFactory sessionFactory = locator.createSessionFactory(CONNECT_USER, CONNECT_PASS)) {
+ Wait.assertTrue(() -> locator.getTopology().getMember(server.getNodeID().toString()) != null,
+ 5000, 100);
+
+ try (ClientSession session = sessionFactory.createSession(CONNECT_USER, CONNECT_PASS, false, true, true, false, 1)) {
+ session.createQueue(QueueConfiguration.of("queue-" + getName()));
+ }
+ }
+ }
+ }
+}
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupAuthenticationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupAuthenticationTest.java
index 31ed9f1310..037ee7237b 100644
--- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupAuthenticationTest.java
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/BackupAuthenticationTest.java
@@ -19,16 +19,12 @@ package org.apache.activemq.artemis.tests.integration.cluster.failover;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import org.apache.activemq.artemis.api.core.ActiveMQException;
-import org.apache.activemq.artemis.api.core.Interceptor;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
-import org.apache.activemq.artemis.core.protocol.core.Packet;
-import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;
-import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
+import org.apache.activemq.artemis.core.server.ActiveMQServer;
+import org.apache.activemq.artemis.core.server.plugin.ActiveMQServerBasePlugin;
import org.apache.activemq.artemis.tests.util.TransportConfigurationUtils;
import org.apache.activemq.artemis.tests.util.Wait;
import org.junit.jupiter.api.BeforeEach;
@@ -53,11 +49,9 @@ public class BackupAuthenticationTest extends FailoverTestBase {
waitForServerToStart(primaryServer.getServer());
backupServer.start();
backupServer.getServer().addExternalComponent(fakeServiceComponent, true);
+ // wait for the backup to register its broker plugins (server started) before
+ // asserting it stops due to the wrong cluster password
assertTrue(latch.await(5, TimeUnit.SECONDS));
- /*
- * can't intercept the message at the backup, so we intercept the registration message at the
- * live.
- */
Wait.waitFor(() -> !backupServer.isStarted());
assertFalse(backupServer.isStarted(), "backup should have stopped");
Wait.assertFalse(fakeServiceComponent::isStarted);
@@ -69,9 +63,14 @@ public class BackupAuthenticationTest extends FailoverTestBase {
protected void createConfigs() throws Exception {
createReplicatedConfigs();
backupConfig.setClusterPassword("crocodile");
- primaryConfig.setIncomingInterceptorClassNames(Arrays.asList(NotifyingInterceptor.class.getName()));
backupConfig.setSecurityEnabled(true);
primaryConfig.setSecurityEnabled(true);
+ backupConfig.registerBrokerPlugin(new ActiveMQServerBasePlugin() {
+ @Override
+ public void registered(ActiveMQServer server) {
+ latch.countDown();
+ }
+ });
}
@Override
@@ -83,17 +82,4 @@ public class BackupAuthenticationTest extends FailoverTestBase {
protected TransportConfiguration getConnectorTransportConfiguration(boolean live) {
return TransportConfigurationUtils.getInVMConnector(live);
}
-
- public static final class NotifyingInterceptor implements Interceptor {
-
- @Override
- public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException {
- if (packet.getType() == PacketImpl.BACKUP_REGISTRATION) {
- latch.countDown();
- } else if (packet.getType() == PacketImpl.CLUSTER_CONNECT) {
- latch.countDown();
- }
- return true;
- }
- }
}
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SecurityFailoverTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SecurityFailoverTest.java
index 867e2dc48f..131fcffc1e 100644
--- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SecurityFailoverTest.java
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/SecurityFailoverTest.java
@@ -28,6 +28,7 @@ import org.apache.activemq.artemis.core.security.Role;
import org.apache.activemq.artemis.core.server.impl.InVMNodeManager;
import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager;
import org.apache.activemq.artemis.tests.integration.cluster.util.TestableServer;
+import org.junit.jupiter.api.BeforeEach;
public class SecurityFailoverTest extends FailoverTest {
@@ -94,6 +95,14 @@ public class SecurityFailoverTest extends FailoverTest {
installSecurity(primaryServer1);
}
+ @Override
+ @BeforeEach
+ public void setUp() throws Exception {
+ super.setUp();
+
+ locator.setConnectionCredentials("a", "b");
+ }
+
protected ActiveMQJAASSecurityManager installSecurity(TestableServer server) {
ActiveMQJAASSecurityManager securityManager = (ActiveMQJAASSecurityManager) server.getServer().getSecurityManager();
securityManager.getConfiguration().addUser("a", "b");
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/lockmanager/LockManagerBackupAuthenticationTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/lockmanager/LockManagerBackupAuthenticationTest.java
index b9e32dfc02..bc030f7df9 100644
--- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/lockmanager/LockManagerBackupAuthenticationTest.java
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/cluster/failover/lockmanager/LockManagerBackupAuthenticationTest.java
@@ -20,17 +20,13 @@ import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import org.apache.activemq.artemis.api.core.ActiveMQException;
-import org.apache.activemq.artemis.api.core.Interceptor;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.core.config.ha.ReplicationBackupPolicyConfiguration;
-import org.apache.activemq.artemis.core.protocol.core.Packet;
-import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;
-import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection;
+import org.apache.activemq.artemis.core.server.ActiveMQServer;
+import org.apache.activemq.artemis.core.server.plugin.ActiveMQServerBasePlugin;
import org.apache.activemq.artemis.tests.extensions.parameterized.Parameter;
import org.apache.activemq.artemis.tests.extensions.parameterized.ParameterizedTestExtension;
import org.apache.activemq.artemis.tests.extensions.parameterized.Parameters;
@@ -70,11 +66,9 @@ public class LockManagerBackupAuthenticationTest extends FailoverTestBase {
waitForServerToStart(primaryServer.getServer());
backupServer.start();
backupServer.getServer().addExternalComponent(fakeServiceComponent, true);
- assertTrue(registrationStarted .await(5, TimeUnit.SECONDS));
- /*
- * can't intercept the message at the backup, so we intercept the registration message at the
- * live.
- */
+ // wait for the backup to register its broker plugins (server started) before
+ // asserting it stops due to the wrong cluster password
+ assertTrue(registrationStarted.await(5, TimeUnit.SECONDS));
Wait.waitFor(() -> !backupServer.isStarted());
assertFalse(backupServer.isStarted(), "backup should have stopped");
Wait.assertFalse(fakeServiceComponent::isStarted);
@@ -86,9 +80,14 @@ public class LockManagerBackupAuthenticationTest extends FailoverTestBase {
protected void createConfigs() throws Exception {
createPluggableReplicatedConfigs();
backupConfig.setClusterPassword("crocodile");
- primaryConfig.setIncomingInterceptorClassNames(Arrays.asList(NotifyingInterceptor.class.getName()));
backupConfig.setSecurityEnabled(true);
primaryConfig.setSecurityEnabled(true);
+ backupConfig.registerBrokerPlugin(new ActiveMQServerBasePlugin() {
+ @Override
+ public void registered(ActiveMQServer server) {
+ registrationStarted.countDown();
+ }
+ });
}
@Override
@@ -107,17 +106,4 @@ public class LockManagerBackupAuthenticationTest extends FailoverTestBase {
return useNetty ? getNettyConnectorTransportConfiguration(live) :
TransportConfigurationUtils.getInVMConnector(live);
}
-
- public static final class NotifyingInterceptor implements Interceptor {
-
- @Override
- public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException {
- if (packet.getType() == PacketImpl.BACKUP_REGISTRATION) {
- registrationStarted.countDown();
- } else if (packet.getType() == PacketImpl.CLUSTER_CONNECT) {
- registrationStarted.countDown();
- }
- return true;
- }
- }
}
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ExceptionListenerForConnectionTimedOutExceptionTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ExceptionListenerForConnectionTimedOutExceptionTest.java
index 5a8f49d8c9..7bd07a630c 100644
--- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ExceptionListenerForConnectionTimedOutExceptionTest.java
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/jms/connection/ExceptionListenerForConnectionTimedOutExceptionTest.java
@@ -222,7 +222,7 @@ public class ExceptionListenerForConnectionTimedOutExceptionTest extends JMSTest
@Override
public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException {
// CheckForFailoverReply is ignored here, as this is simulating an issue where the server is completely not responding, the blocked call should throw an exception asynchrnously to the retry
- if (packet.getType() == PacketImpl.CHECK_FOR_FAILOVER_REPLY) {
+ if (packet.getType() == PacketImpl.CONNECT_RESPONSE) {
block();
return true;
}
@@ -239,7 +239,7 @@ public class ExceptionListenerForConnectionTimedOutExceptionTest extends JMSTest
@Override
public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException {
// CheckForFailoverReply is ignored here, as this is simulating an issue where the server is completely not responding, the blocked call should throw an exception asynchrnously to the retry
- if (packet.getType() == PacketImpl.CHECK_FOR_FAILOVER_REPLY) {
+ if (packet.getType() == PacketImpl.CONNECT_RESPONSE) {
block();
return true;
}
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/compat/HQClientProtocolManagerTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/compat/HQClientProtocolManagerTest.java
index ebbe14c25e..cc948bf03e 100644
--- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/compat/HQClientProtocolManagerTest.java
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/remoting/compat/HQClientProtocolManagerTest.java
@@ -88,7 +88,7 @@ public class HQClientProtocolManagerTest extends ActiveMQTestBase {
private static Set<Byte> receivedTypes = new HashSet<>();
private static Set<Byte> unsupportedTypes = new HashSet<>();
static {
- unsupportedTypes.add(PacketImpl.CHECK_FOR_FAILOVER);
+ unsupportedTypes.add(PacketImpl.CONNECT);
}
@Override
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/CoreFrameWithSizeLimitDecoderTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/CoreFrameWithSizeLimitDecoderTest.java
new file mode 100644
index 0000000000..bcde488146
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/transports/netty/CoreFrameWithSizeLimitDecoderTest.java
@@ -0,0 +1,77 @@
+/*
+ * 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.activemq.artemis.tests.integration.transports.netty;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.embedded.EmbeddedChannel;
+import io.netty.handler.codec.TooLongFrameException;
+import org.apache.activemq.artemis.core.protocol.core.impl.CoreProtocolManager;
+import org.apache.activemq.artemis.core.remoting.impl.netty.CoreFrameWithSizeLimitDecoder;
+import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
+import org.apache.activemq.artemis.utils.DataConstants;
+import org.junit.jupiter.api.Test;
+
+public class CoreFrameWithSizeLimitDecoderTest extends ActiveMQTestBase {
+
+ private static final int FRAME_PAYLOAD_SIZE = CoreProtocolManager.CORE_INITIAL_MAX_FRAME_SIZE + 1;
+
+ @Test
+ public void testRejectsOversizedFrameBeforeAuthentication() {
+ final EmbeddedChannel decoder = new EmbeddedChannel(new CoreFrameWithSizeLimitDecoder(CoreProtocolManager.CORE_INITIAL_MAX_FRAME_SIZE));
+
+ assertThrows(TooLongFrameException.class, () -> decoder.writeInbound(frameBuffer(FRAME_PAYLOAD_SIZE)));
+ }
+
+ @Test
+ public void testRejectsOversizedFrameFromLengthPrefixOnly() {
+ final EmbeddedChannel decoder = new EmbeddedChannel(new CoreFrameWithSizeLimitDecoder(CoreProtocolManager.CORE_INITIAL_MAX_FRAME_SIZE));
+
+ final ByteBuf lengthPrefixOnly = Unpooled.buffer(DataConstants.SIZE_INT);
+ lengthPrefixOnly.writeInt(FRAME_PAYLOAD_SIZE);
+
+ assertThrows(TooLongFrameException.class, () -> decoder.writeInbound(lengthPrefixOnly));
+ assertNull(decoder.readInbound());
+ }
+
+ @Test
+ public void testAcceptsLargerFrameAfterLimitRaised() throws Exception {
+ final EmbeddedChannel decoder = new EmbeddedChannel(new CoreFrameWithSizeLimitDecoder(CoreProtocolManager.CORE_INITIAL_MAX_FRAME_SIZE));
+
+ CoreFrameWithSizeLimitDecoder.setFrameSizeLimit(decoder, CoreProtocolManager.CORE_MAX_FRAME_SIZE);
+
+ decoder.writeInbound(frameBuffer(FRAME_PAYLOAD_SIZE));
+
+ final ByteBuf frame = decoder.readInbound();
+ assertNotNull(frame);
+ assertEquals(FRAME_PAYLOAD_SIZE, frame.readableBytes());
+ frame.release();
+ assertNull(decoder.readInbound());
+ }
+
+ private static ByteBuf frameBuffer(final int payloadSize) {
+ final ByteBuf buffer = Unpooled.buffer(4 + payloadSize);
+ buffer.writeInt(payloadSize);
+ buffer.writeZero(payloadSize);
+ return buffer;
+ }
+}
diff --git a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/common/AbstractAdmin.java b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/common/AbstractAdmin.java
index 3a842222db..a7a277e161 100644
--- a/tests/joram-tests/src/test/java/org/apache/activemq/artemis/common/AbstractAdmin.java
+++ b/tests/joram-tests/src/test/java/org/apache/activemq/artemis/common/AbstractAdmin.java
@@ -74,6 +74,7 @@ public class AbstractAdmin implements Admin {
@Override
public void start() throws Exception {
serverLocator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName()));
+ serverLocator.setConnectionCredentials(ActiveMQDefaultConfiguration.getDefaultClusterUser(), ActiveMQDefaultConfiguration.getDefaultClusterPassword());
sf = serverLocator.createSessionFactory();
clientSession = sf.createSession(ActiveMQDefaultConfiguration.getDefaultClusterUser(), ActiveMQDefaultConfiguration.getDefaultClusterPassword(), false, true, true, false, 1);
requestor = new ClientRequestor(clientSession, ActiveMQDefaultConfiguration.getDefaultManagementAddress());
diff --git a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java
index 6ff073c3a8..dbd384dfe3 100644
--- a/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java
+++ b/tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/ra/ResourceAdapterTest.java
@@ -42,6 +42,7 @@ import org.apache.activemq.artemis.ra.ConnectionFactoryProperties;
import org.apache.activemq.artemis.ra.inflow.ActiveMQActivation;
import org.apache.activemq.artemis.ra.inflow.ActiveMQActivationSpec;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
+import org.apache.activemq.artemis.utils.Wait;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -646,7 +647,7 @@ public class ResourceAdapterTest extends ActiveMQTestBase {
// ignore
}
- assertEquals(0, server.getRemotingService().getConnections().size());
+ Wait.assertEquals(0, () -> server.getRemotingService().getConnections().size());
} finally {
if (activation != null) {
activation.stop();
@@ -657,6 +658,48 @@ public class ResourceAdapterTest extends ActiveMQTestBase {
server.stop();
}
}
+ @Test
+ public void testConnectionFactoryPropagatesUserCredentials() throws Exception {
+ ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter();
+ ra.setConnectorClassName(InVMConnectorFactory.class.getName());
+ ra.setUserName("testUser");
+ ra.setPassword("testPassword");
+ ra.setPasswordCodec("org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec");
+
+ ActiveMQConnectionFactory factory = ra.getConnectionFactory(new ConnectionFactoryProperties());
+ assertEquals("testUser", factory.getUser());
+ assertEquals("testPassword", factory.getPassword());
+ assertEquals("org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec", factory.getPasswordCodec());
+ }
+
+ @Test
+ public void testRecoveryConnectionFactoryPropagatesUserCredentials() throws Exception {
+ ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter();
+ ra.setConnectorClassName(InVMConnectorFactory.class.getName());
+ ra.setUserName("recoveryUser");
+ ra.setPassword("recoveryPassword");
+ ra.setPasswordCodec("org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec");
+
+ ActiveMQConnectionFactory factory = ra.createRecoveryActiveMQConnectionFactory(new ConnectionFactoryProperties());
+ assertEquals("recoveryUser", factory.getUser());
+ assertEquals("recoveryPassword", factory.getPassword());
+ assertEquals("org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec", factory.getPasswordCodec());
+ }
+
+ @Test
+ public void testDefaultConnectionFactoryPropagatesUserCredentials() throws Exception {
+ ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter();
+ ra.setConnectorClassName(InVMConnectorFactory.class.getName());
+ ra.setUserName("defaultUser");
+ ra.setPassword("defaultPassword");
+ ra.setPasswordCodec("org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec");
+
+ ActiveMQConnectionFactory factory = ra.getDefaultActiveMQConnectionFactory();
+ assertEquals("defaultUser", factory.getUser());
+ assertEquals("defaultPassword", factory.getPassword());
+ assertEquals("org.apache.activemq.artemis.utils.DefaultSensitiveStringCodec", factory.getPasswordCodec());
+ }
+
@Test
public void testCloseConnectionFactoryMultipleTimesDoesNotThrow() throws Exception {
ActiveMQResourceAdapter ra = new ActiveMQResourceAdapter();
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@artemis.apache.org
For additional commands, e-mail: commits-help@artemis.apache.org