feat(iot): publish connection lifecycle events (#5277)

* feat(iot): publish connection lifecycle events

The MQTT broker publishes $aws/events/presence/connected and disconnected
for every session, with its session identifier, certificate principal,
version number and disconnect reason, through topic rules and to
subscribers. Topic filters starting with a wildcard no longer match $ topics,
as on AWS.

Closes #5275

* fix(iot): keep lifecycle events within the reset guard

A lifecycle event admits its topic rules under the rule state at the time
of the event, so one queued before an emulator reset skips them. A
DeleteConnection that wins the session tolerates an endpoint the client's
DISCONNECT already closed.

* fix(iot): serialize session transitions and report keep-alive timeouts

Admission, takeover, DeleteConnection and session end now allocate the
versionNumber and change the session map under one lock, with endpoint
I/O kept outside it. A takeover of an endpoint that is already closed
still accepts the new connection.

A close after a full keep-alive period without a packet from the client
is reported as MQTT_KEEP_ALIVE_TIMEOUT, as AWS IoT does. The WebSocket
upgrade carries the client's port, and the wildcard-first exclusion is
limited to the lifecycle topics, which AWS does not deliver to such
filters while it does deliver shadow topics.

* fix(iot): keep ended sessions out of subscriptions and time keep-alive from CONNECT

* test(iot): drive keep-alive tests from an injected nano-time source

The broker takes a LongSupplier nano-time source, as ReloadingKeyManager
does, so the keep-alive unit tests move a fake clock forward instead of
sleeping. The race test uses ThreadStates.awaitBlockedOrDone.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-19 16:18:54 -04:00
1 parent fcb41966a8
commit 87aa6f38a1
12 files changed
+1488 -79

No files matched your search

@@ -135,6 +135,7 @@ import software.amazon.awssdk.services.iotjobsdataplane.model.UpdateJobExecution
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse;
@@ -149,6 +150,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -1067,6 +1069,75 @@ class IotTest {
}
}
@Test
void mqttPresenceEventsReachTopicRulesOverSqs() throws Exception {
String suffix = Long.toString(System.nanoTime());
String clientId = "tklocal-java-" + suffix;
String queueUrl = sqs.createQueue(CreateQueueRequest.builder()
.queueName("java-iot-presence-" + suffix)
.build()).queueUrl();
String connectedRule = "java_iot_presence_connected_" + suffix;
String disconnectedRule = "java_iot_presence_disconnected_" + suffix;
createSqsRule(connectedRule,
"SELECT * FROM '$aws/events/presence/connected/+' WHERE startswith(clientId, 'tklocal-')", queueUrl);
createSqsRule(disconnectedRule,
"SELECT * FROM '$aws/events/presence/disconnected/+' WHERE startswith(clientId, 'tklocal-')", queueUrl);
try {
try (Socket client = mqttConnect(clientId)) {
client.getOutputStream().write(new byte[] {(byte) 0xe0, 0x00});
}
Map<String, JsonNode> byType = new HashMap<>();
long deadline = System.currentTimeMillis() + 10_000;
while (byType.size() < 2 && System.currentTimeMillis() < deadline) {
for (Message message : sqs.receiveMessage(ReceiveMessageRequest.builder()
.queueUrl(queueUrl)
.maxNumberOfMessages(10)
.build()).messages()) {
JsonNode event = OBJECT_MAPPER.readTree(message.body());
if (clientId.equals(event.path("clientId").asText())) {
byType.put(event.path("eventType").asText(), event);
}
}
Thread.sleep(100);
}
assertThat(byType).containsOnlyKeys("connected", "disconnected");
JsonNode connected = byType.get("connected");
JsonNode disconnected = byType.get("disconnected");
assertThat(connected.path("timestamp").isIntegralNumber()).isTrue();
assertThat(connected.path("ipAddress").asText()).isNotEmpty();
assertThat(disconnected.path("sessionIdentifier").asText())
.isNotEmpty()
.isEqualTo(connected.path("sessionIdentifier").asText());
assertThat(disconnected.path("versionNumber").asLong()).isEqualTo(connected.path("versionNumber").asLong());
assertThat(disconnected.path("clientInitiatedDisconnect").asBoolean()).isTrue();
assertThat(disconnected.path("disconnectReason").asText()).isEqualTo("CLIENT_INITIATED_DISCONNECT");
} finally {
iot.deleteTopicRule(DeleteTopicRuleRequest.builder().ruleName(connectedRule).build());
iot.deleteTopicRule(DeleteTopicRuleRequest.builder().ruleName(disconnectedRule).build());
sqs.deleteQueue(DeleteQueueRequest.builder().queueUrl(queueUrl).build());
}
}
private void createSqsRule(String ruleName, String sql, String queueUrl) {
iot.createTopicRule(CreateTopicRuleRequest.builder()
.ruleName(ruleName)
.topicRulePayload(TopicRulePayload.builder()
.sql(sql)
.awsIotSqlVersion("2016-03-23")
.ruleDisabled(false)
.actions(Action.builder()
.sqs(SqsAction.builder()
.roleArn(TestFixtures.globalArn("iam", "000000000000", "role/iot-rule-role"))
.queueUrl(queueUrl)
.useBase64(false)
.build())
.build())
.build())
.build());
}
private Socket mqttConnect(String clientId) throws IOException {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("floci", 1883), 5_000);
+44 -1
View File
@@ -248,6 +248,49 @@ username, the URL query or the `x-amz-customauthorizer-name` upgrade header, see
[Authorizers](#authorizers); it does not verify a SigV4 signature, and a CONNECT that names no
authorizer is accepted as is.
### Lifecycle events
The broker publishes AWS IoT's lifecycle events for every MQTT session, on 1883, 8883 and `/mqtt`:
`$aws/events/presence/connected/<clientId>` once the client is accepted, and
`$aws/events/presence/disconnected/<clientId>` once its session ends. The payloads carry AWS's fields
in AWS's order:
```json
{"clientId":"sensor-1","timestamp":1791399692873,"eventType":"connected","sessionIdentifier":"64b3ed16-3f27-4a75-8dfc-388884c2c216","principalIdentifier":"<certificateId>","versionNumber":0,"ipAddress":"203.0.113.7"}
{"clientId":"sensor-1","timestamp":1791399695210,"eventType":"disconnected","sessionIdentifier":"64b3ed16-3f27-4a75-8dfc-388884c2c216","principalIdentifier":"<certificateId>","versionNumber":0,"clientInitiatedDisconnect":true,"disconnectReason":"CLIENT_INITIATED_DISCONNECT"}
```
- `timestamp` is epoch milliseconds.
- `sessionIdentifier` is a random UUID, the same on the connected and the disconnected event of one session.
- `principalIdentifier` is the device certificate ID on 8883. It is omitted on 1883, on `/mqtt` (Floci does not verify SigV4) and for a connection admitted by a custom authorizer.
- `ipAddress`, on the connected event only, is the client's address. A WebSocket client reports its own address, not the bridge's loopback socket; `GetConnection` returns the same address, with the WebSocket client's own port as `sourcePort`.
- `versionNumber` counts per client id: `0` for a new client id, `+2` when the client id reconnects after its session ended (`0`, `2`, `4`), and `+1` for a session that takes over the client id from a connected one. AWS starts again from `0` after about an hour without a connection; Floci keeps counting, across state resets, until the process restarts.
`clientInitiatedDisconnect` is `true` only for `CLIENT_INITIATED_DISCONNECT`:
| Cause | `disconnectReason` |
|---|---|
| The client sent `DISCONNECT` (MQTT 3.1.1 or 5) | `CLIENT_INITIATED_DISCONNECT` |
| The connection closed without `DISCONNECT` | `CONNECTION_LOST` |
| No packet from the client for 1.5 times its keep-alive | `MQTT_KEEP_ALIVE_TIMEOUT` |
| A new connection took over the client id; published for the old session, before the new session's connected event | `DUPLICATE_CLIENTID` |
| IoT Data `DeleteConnection` | `API_INITIATED_DISCONNECT` |
| A PUBLISH above 128 KB, or a QoS 2 PUBLISH | `CLIENT_ERROR` |
An event goes the way a client publish goes: it is evaluated by the topic rules of every region,
where `clientid()` returns the client id the event is about and `topic(3)` is `presence`, and
delivered to matching MQTT subscribers. As on AWS, a topic filter whose first level is `#` or `+`
does not match the lifecycle topics, both for subscriptions and for a rule's `FROM`: `#` and
`+/events/presence/+/+` receive no lifecycle events, `$aws/events/presence/connected/+` does.
As on AWS, events can arrive out of order across connections; `versionNumber` orders them.
Differences from AWS and limits:
- A client id containing `#` or `+` gets no lifecycle events, as on AWS.
- A broker shutdown publishes no disconnected events.
- `connect_failed`, `subscribed` and `unsubscribed` events are not emitted.
## Reserved Topics
AWS IoT reserved topics such as `$aws/things/{thingName}/shadow/update` are service control topics, not ordinary application topics. Floci should handle these publishes by invoking IoT shadow behavior and then publishing the AWS-compatible response topics through the broker.
@@ -285,7 +328,7 @@ Implementation notes:
- Normal client publishes call `IotService.publish(...)` so retained-message storage, event recording, and rule evaluation remain service-owned.
- An MQTT publish stores the retained message and records the publish on the event loop, then hands topic rule evaluation to a single-thread worker the broker owns, which runs the rules of MQTT publishes one at a time in the order they arrived. A slow rule action therefore delays the rules of later publishes from every connection, but not their PUBACK or fan-out, and not other services' work.
- A state reset or a broker shutdown skips the rules of MQTT publishes still waiting, and an MQTT publish received during the reset or while the broker is stopped never runs its rules. An evaluation already running finishes.
- Internal broker publishes fan out only to MQTT subscribers and do not recursively evaluate IoT topic rules.
- Shadow responses the broker publishes internally fan out only to MQTT subscribers and do not recursively evaluate IoT topic rules. [Lifecycle events](#lifecycle-events) do evaluate topic rules.
Current accepted limitation:
@@ -57,9 +57,11 @@ public class IotCustomAuthorizer {
/**
* What a WebSocket upgrade carried: the header names lower-cased, the raw query without its
* {@code ?} ({@code ""} when there was none), the server name, null unless it came over TLS, and
* the client's IP address, as the broker sees only the bridge's loopback socket.
* the client's IP address and port ({@code -1} when unknown), as the broker sees only the
* bridge's loopback socket.
*/
record WebSocketUpgrade(Map<String, String> headers, String queryString, String serverName, String sourceIp) {
record WebSocketUpgrade(Map<String, String> headers, String queryString, String serverName, String sourceIp,
int sourcePort) {
}
@Inject
@@ -1,8 +1,11 @@
package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.services.iot.model.IotRetainedMessage;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.netty.handler.codec.mqtt.MqttProperties;
import io.netty.handler.codec.mqtt.MqttQoS;
@@ -40,6 +43,7 @@ import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509ExtendedTrustManager;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
@@ -52,9 +56,11 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;
import java.util.regex.Pattern;
@ApplicationScoped
@@ -113,6 +119,15 @@ public class IotMqttBrokerService implements Resettable {
static final int MAX_PENDING_RULE_EVALUATIONS = 1_000;
static final String CLIENT_INITIATED_DISCONNECT = "CLIENT_INITIATED_DISCONNECT";
static final String CONNECTION_LOST = "CONNECTION_LOST";
static final String MQTT_KEEP_ALIVE_TIMEOUT = "MQTT_KEEP_ALIVE_TIMEOUT";
static final String PRESENCE_TOPIC_PREFIX = "$aws/events/presence/";
private static final String DUPLICATE_CLIENTID = "DUPLICATE_CLIENTID";
private static final String API_INITIATED_DISCONNECT = "API_INITIATED_DISCONNECT";
private static final String CLIENT_ERROR = "CLIENT_ERROR";
private static final long KEEP_ALIVE_SLACK_NANOS = TimeUnit.MILLISECONDS.toNanos(250);
private static final long RULES_RESETTING = 1;
private static final long RULES_STOPPED = 2;
private static final long RULE_STATE_STEP = 4;
@@ -122,9 +137,14 @@ public class IotMqttBrokerService implements Resettable {
private final Instance<IotService> iotService;
private final IotCustomAuthorizer customAuthorizer;
private final TlsConfigurationRegistry tlsRegistry;
private final LongSupplier nanoTime;
final WorkerExecutor ruleWorker;
private final Map<String, ClientSession> sessionsByClient = new ConcurrentHashMap<>();
private final Map<String, Map<String, Subscription>> subscriptionsByClient = new ConcurrentHashMap<>();
/** Serializes admitting and ending sessions and the versionNumbers they take; never held across endpoint I/O. */
private final Object sessionLock = new Object();
/** The last lifecycle event versionNumber per client id; neither a state reset nor a broker restart clears it. */
private final Map<String, Long> presenceVersions = new ConcurrentHashMap<>();
private final AtomicInteger pendingRuleEvaluations = new AtomicInteger();
private final AtomicBoolean ruleEvaluationsThrottled = new AtomicBoolean();
/**
@@ -141,11 +161,17 @@ public class IotMqttBrokerService implements Resettable {
@Inject
public IotMqttBrokerService(EmulatorConfig config, Vertx vertx, Instance<IotService> iotService,
IotCustomAuthorizer customAuthorizer, TlsConfigurationRegistry tlsRegistry) {
this(config, vertx, iotService, customAuthorizer, tlsRegistry, System::nanoTime);
}
IotMqttBrokerService(EmulatorConfig config, Vertx vertx, Instance<IotService> iotService,
IotCustomAuthorizer customAuthorizer, TlsConfigurationRegistry tlsRegistry, LongSupplier nanoTime) {
this.config = config;
this.vertx = vertx;
this.iotService = iotService;
this.customAuthorizer = customAuthorizer;
this.tlsRegistry = tlsRegistry;
this.nanoTime = nanoTime;
this.ruleWorker = vertx.createSharedWorkerExecutor("floci-iot-mqtt-rules", 1);
}
@@ -305,11 +331,9 @@ public class IotMqttBrokerService implements Resettable {
tlsServer = null;
keyManager = null;
sessionsByClient.values().forEach(session -> {
try {
session.endpoint().close();
} catch (IllegalStateException e) {
LOG.debugv("IoT MQTT client {0} was already closed during broker shutdown", session.clientId());
}
// Ended before the close, so a broker shutdown publishes no disconnected event.
session.ended().set(true);
closeEndpoint(session);
});
sessionsByClient.clear();
subscriptionsByClient.clear();
@@ -348,17 +372,28 @@ public class IotMqttBrokerService implements Resettable {
}
boolean disconnectClient(String clientId, boolean cleanSession) {
ClientSession session = sessionsByClient.remove(clientId);
if (session == null) {
return false;
ClientSession session;
synchronized (sessionLock) {
session = sessionsByClient.get(clientId);
if (session == null || !endSession(session, API_INITIATED_DISCONNECT)) {
return false;
}
if (cleanSession) {
subscriptionsByClient.remove(clientId);
}
}
if (cleanSession) {
subscriptionsByClient.remove(clientId);
}
session.endpoint().close();
closeEndpoint(session);
return true;
}
private static void closeEndpoint(ClientSession session) {
try {
session.endpoint().close();
} catch (IllegalStateException e) {
LOG.debugv("IoT MQTT client {0} was already closed", session.clientId());
}
}
Optional<ConnectionInfo> getConnection(String clientId) {
if (server == null) {
return Optional.empty();
@@ -385,9 +420,11 @@ public class IotMqttBrokerService implements Resettable {
* every client except one that names a custom authorizer, see {@link #authorizeCustom}.
*/
void handleEndpoint(MqttEndpoint endpoint, boolean verifyDevice) {
long connectNanos = nanoTime.getAsLong();
String clientId = endpoint.clientIdentifier();
SocketAddress remoteAddress = endpoint.remoteAddress();
String sourceIp = remoteAddress == null ? null : remoteAddress.host();
int sourcePort = remoteAddress == null ? -1 : remoteAddress.port();
String principal = null;
if (verifyDevice) {
principal = admittedDevice(endpoint, clientId, sourceIp);
@@ -399,14 +436,18 @@ public class IotMqttBrokerService implements Resettable {
}
} else {
IotCustomAuthorizer.WebSocketUpgrade upgrade = remoteAddress == null ? null : webSocketUpgrades.remove(remoteAddress);
if (upgrade != null && upgrade.sourceIp() != null) {
sourceIp = upgrade.sourceIp();
sourcePort = upgrade.sourcePort();
}
String username = endpoint.auth() == null ? null : endpoint.auth().getUsername();
String authorizerName = IotCustomAuthorizer.authorizerName(username, upgrade);
if (authorizerName != null) {
authorizeCustom(endpoint, authorizerName, upgrade, upgrade == null ? sourceIp : upgrade.sourceIp());
authorizeCustom(endpoint, authorizerName, upgrade, sourceIp, sourcePort, connectNanos);
return;
}
}
admit(endpoint, principal);
admit(endpoint, principal, sourceIp, sourcePort, connectNanos);
}
/**
@@ -416,7 +457,7 @@ public class IotMqttBrokerService implements Resettable {
* MQTT 5 with reason code 0x87, as AWS IoT does.
*/
private void authorizeCustom(MqttEndpoint endpoint, String authorizerName, IotCustomAuthorizer.WebSocketUpgrade upgrade,
String sourceIp) {
String sourceIp, int sourcePort, long connectNanos) {
String clientId = endpoint.clientIdentifier();
String username = endpoint.auth() == null ? null : endpoint.auth().getUsername();
String password = endpoint.auth() == null ? null : endpoint.auth().getPassword();
@@ -431,7 +472,7 @@ public class IotMqttBrokerService implements Resettable {
return;
}
if (decision.succeeded() && decision.result()) {
admit(endpoint, null);
admit(endpoint, null, sourceIp, sourcePort, connectNanos);
return;
}
LOG.debugv("IoT MQTT client {0} refused by custom authorizer {1}: {2}", clientId, authorizerName,
@@ -447,39 +488,72 @@ public class IotMqttBrokerService implements Resettable {
});
}
private void admit(MqttEndpoint endpoint, String principal) {
/**
* {@code principal} is the certificate id a TLS client was admitted with, null otherwise.
* {@code clientIp} and {@code clientPort} are the address the client connected from: the
* socket's, or for a WebSocket client the one the bridge recorded at the upgrade, as the
* bridge's own socket is loopback. {@code connectNanos} is when the CONNECT arrived, which
* the keep-alive runs from.
*/
private void admit(MqttEndpoint endpoint, String principal, String clientIp, int clientPort, long connectNanos) {
String clientId = endpoint.clientIdentifier();
SocketAddress remoteAddress = endpoint.remoteAddress();
String sourceIp = remoteAddress == null ? null : remoteAddress.host();
ClientSession session = new ClientSession(
clientId,
endpoint,
sourceIp,
remoteAddress == null ? -1 : remoteAddress.port(),
endpoint.isCleanSession());
endpoint.subscriptionAutoAck(false);
endpoint.publishAutoAck(false);
endpoint.exceptionHandler(error -> LOG.warnv("IoT MQTT client {0} error: {1}", clientId, error.getMessage()));
endpoint.subscribeHandler(message -> handleSubscribe(session, message));
endpoint.unsubscribeHandler(message -> handleUnsubscribe(session, message));
endpoint.publishHandler(message -> handlePublish(session, message));
endpoint.disconnectHandler(ignored -> removeSession(session));
endpoint.closeHandler(ignored -> removeSession(session));
ClientSession previous = sessionsByClient.put(clientId, session);
if (previous != null && previous.endpoint() != endpoint) {
previous.endpoint().close();
boolean cleanSession = endpoint.isCleanSession();
ClientSession session;
ClientSession replaced = null;
synchronized (sessionLock) {
long versionNumber = presenceVersions.merge(clientId, 0L, (last, unused) -> last + 1);
session = new ClientSession(
clientId,
endpoint,
clientIp,
clientPort,
cleanSession,
UUID.randomUUID().toString(),
principal,
versionNumber,
new AtomicBoolean(),
new AtomicLong(connectNanos));
ClientSession previous = sessionsByClient.put(clientId, session);
if (previous != null && previous.endpoint() != endpoint) {
endSession(previous, DUPLICATE_CLIENTID);
replaced = previous;
}
}
if (replaced != null) {
closeEndpoint(replaced);
}
endpoint.accept();
try {
endpoint.subscriptionAutoAck(false);
endpoint.publishAutoAck(false);
endpoint.exceptionHandler(error -> {
LOG.warnv("IoT MQTT client {0} error: {1}", clientId, error.getMessage());
if (error instanceof TooLongFrameException) {
endSession(session, CLIENT_ERROR);
endpoint.close();
}
});
endpoint.subscribeHandler(message -> handleSubscribe(session, message));
endpoint.unsubscribeHandler(message -> handleUnsubscribe(session, message));
endpoint.publishHandler(message -> handlePublish(session, message));
endpoint.pingHandler(ignored -> received(session));
endpoint.publishAcknowledgeHandler(ignored -> received(session));
endpoint.disconnectHandler(ignored -> endSession(session, CLIENT_INITIATED_DISCONNECT));
endpoint.closeHandler(ignored -> endSession(session, keepAliveExpired(session) ? MQTT_KEEP_ALIVE_TIMEOUT : CONNECTION_LOST));
endpoint.accept();
} catch (IllegalStateException e) {
// Only another thread closes the endpoint here: a takeover, DeleteConnection or stop,
// each of which has already ended the session, so its connected event pairs with that.
LOG.debugv("IoT MQTT client {0} closed before it was accepted: {1}", clientId, e.getMessage());
}
if (principal != null) {
LOG.debugv("IoT MQTT TLS client {0} admitted as {1}", clientId, principal);
}
publishPresence(session, "connected", null);
}
/**
* The certificate ARN of the device behind the connection when it may connect, otherwise null.
* The certificate id of the device behind the connection when it may connect, otherwise null.
* A failure while deciding refuses the client rather than leaving the CONNECT unanswered. A
* refusal is the client's own doing and reaches it as the CONNACK, so it is logged at debug
* only: the CONNECT is reachable by anyone.
@@ -491,12 +565,12 @@ public class IotMqttBrokerService implements Resettable {
LOG.debugv("IoT MQTT TLS client {0} refused: no registered certificate presented", clientId);
return null;
}
String certificateArn = device.get().certificate().getCertificateArn();
String certificateId = device.get().certificate().getCertificateId();
if (!iotService.get().isConnectAllowed(device.get(), clientId, sourceIp, requestedServerName(endpoint.sslSession()))) {
LOG.debugv("IoT MQTT TLS client {0} refused: iot:Connect is not allowed for {1}", clientId, certificateArn);
LOG.debugv("IoT MQTT TLS client {0} refused: iot:Connect is not allowed for {1}", clientId, certificateId);
return null;
}
return certificateArn;
return certificateId;
} catch (RuntimeException e) {
LOG.warnv(e, "IoT MQTT TLS client {0} refused: device verification failed: {1}", clientId, e.getMessage());
return null;
@@ -545,8 +619,7 @@ public class IotMqttBrokerService implements Resettable {
}
private void handleSubscribe(ClientSession session, MqttSubscribeMessage message) {
Map<String, Subscription> clientSubscriptions = subscriptionsByClient.computeIfAbsent(
session.clientId(), ignored -> new ConcurrentHashMap<>());
received(session);
List<MqttQoS> grantedQos = new ArrayList<>();
List<Subscription> accepted = new ArrayList<>();
@@ -559,38 +632,56 @@ public class IotMqttBrokerService implements Resettable {
}
int granted = qos == MqttQoS.AT_LEAST_ONCE ? 1 : 0;
Subscription subscription = new Subscription(topicFilter, granted);
clientSubscriptions.put(topicFilter, subscription);
accepted.add(subscription);
accepted.add(new Subscription(topicFilter, granted));
grantedQos.add(granted == 1 ? MqttQoS.AT_LEAST_ONCE : MqttQoS.AT_MOST_ONCE);
}
synchronized (sessionLock) {
// An ended session no longer owns its client id's subscriptions; a newer connection may.
if (session.ended().get()) {
return;
}
Map<String, Subscription> clientSubscriptions = subscriptionsByClient.computeIfAbsent(
session.clientId(), ignored -> new ConcurrentHashMap<>());
for (Subscription subscription : accepted) {
clientSubscriptions.put(subscription.topicFilter(), subscription);
}
}
session.endpoint().subscribeAcknowledge(message.messageId(), grantedQos);
deliverRetained(session, accepted);
}
private void handleUnsubscribe(ClientSession session, MqttUnsubscribeMessage message) {
Map<String, Subscription> clientSubscriptions = subscriptionsByClient.get(session.clientId());
if (clientSubscriptions != null) {
for (String topic : message.topics()) {
clientSubscriptions.remove(topic);
received(session);
synchronized (sessionLock) {
if (session.ended().get()) {
return;
}
if (clientSubscriptions.isEmpty()) {
subscriptionsByClient.remove(session.clientId(), clientSubscriptions);
Map<String, Subscription> clientSubscriptions = subscriptionsByClient.get(session.clientId());
if (clientSubscriptions != null) {
for (String topic : message.topics()) {
clientSubscriptions.remove(topic);
}
if (clientSubscriptions.isEmpty()) {
subscriptionsByClient.remove(session.clientId(), clientSubscriptions);
}
}
}
session.endpoint().unsubscribeAcknowledge(message.messageId());
}
private void handlePublish(ClientSession session, MqttPublishMessage message) {
received(session);
if (message.payload().length() > MAX_PAYLOAD_SIZE) {
LOG.debugv("IoT MQTT client {0} disconnected: {1} byte payload on {2} exceeds the AWS limit",
session.clientId(), Integer.toString(message.payload().length()), message.topicName());
endSession(session, CLIENT_ERROR);
session.endpoint().close();
return;
}
byte[] payload = message.payload().getBytes();
if (message.qosLevel() == MqttQoS.EXACTLY_ONCE) {
endSession(session, CLIENT_ERROR);
session.endpoint().close();
return;
}
@@ -619,7 +710,10 @@ public class IotMqttBrokerService implements Resettable {
* its rules.
*/
void evaluateRulesOnWorker(String topic, Runnable rules) {
long admitted = ruleState.get();
evaluateRulesOnWorker(topic, rules, ruleState.get());
}
void evaluateRulesOnWorker(String topic, Runnable rules, long admitted) {
if ((admitted & (RULES_RESETTING | RULES_STOPPED)) != 0) {
return;
}
@@ -688,13 +782,66 @@ public class IotMqttBrokerService implements Resettable {
}
}
private void removeSession(ClientSession session) {
sessionsByClient.remove(session.clientId(), session);
if (session.cleanSession()) {
subscriptionsByClient.remove(session.clientId());
/**
* Ends the session once: the first reason reported wins, and only that one publishes the
* disconnected event and gets true. The versionNumber counts up only while the session is still
* the client id's current one, so a session replaced by a newer connection leaves it alone.
*/
private boolean endSession(ClientSession session, String reason) {
synchronized (sessionLock) {
if (!session.ended().compareAndSet(false, true)) {
return false;
}
if (sessionsByClient.remove(session.clientId(), session)) {
presenceVersions.computeIfPresent(session.clientId(), (id, version) -> version + 1);
}
if (session.cleanSession()) {
subscriptionsByClient.remove(session.clientId());
}
publishPresence(session, "disconnected", reason);
return true;
}
}
/**
* Publishes the AWS lifecycle event of a session the way a client publish goes: recorded, run
* through every region's topic rules on the rule worker, then fanned out to subscribers. A
* client id holding {@code #} or {@code +} gets none, as on AWS: its topic would not be valid.
*/
private void publishPresence(ClientSession session, String eventType, String disconnectReason) {
if (session.clientId().contains("#") || session.clientId().contains("+")) {
return;
}
String topic = PRESENCE_TOPIC_PREFIX + eventType + "/" + session.clientId();
ObjectNode event = JsonNodeFactory.instance.objectNode();
event.put("clientId", session.clientId());
event.put("timestamp", System.currentTimeMillis());
event.put("eventType", eventType);
event.put("sessionIdentifier", session.sessionIdentifier());
if (session.principalIdentifier() != null) {
event.put("principalIdentifier", session.principalIdentifier());
}
event.put("versionNumber", session.versionNumber());
if (disconnectReason == null) {
if (session.sourceIp() != null) {
event.put("ipAddress", session.sourceIp());
}
} else {
event.put("clientInitiatedDisconnect", CLIENT_INITIATED_DISCONNECT.equals(disconnectReason));
event.put("disconnectReason", disconnectReason);
}
byte[] payload = event.toString().getBytes(StandardCharsets.UTF_8);
// Vert.x runs an endpoint callback holding that endpoint's monitor and the fan-out takes each subscriber's,
// so the event is published once the callback returns; events scheduled from one thread keep their order.
// Its rules are admitted under the rule state at the time of the event.
long admitted = ruleState.get();
vertx.runOnContext(ignored -> {
iotService.get().publish(topic, payload, false, 0, null, session.clientId(),
rules -> evaluateRulesOnWorker(topic, rules, admitted));
fanOut(topic, payload, false);
});
}
private boolean isValidTopicFilter(String topicFilter) {
if (topicFilter == null || topicFilter.isBlank()) {
return false;
@@ -717,6 +864,10 @@ public class IotMqttBrokerService implements Resettable {
return true;
}
String[] filterLevels = topicFilter.split("/", -1);
// Measured on AWS IoT: a wildcard first level matches the $aws/things shadow topics but not the lifecycle topics.
if (topic.startsWith(PRESENCE_TOPIC_PREFIX) && ("#".equals(filterLevels[0]) || "+".equals(filterLevels[0]))) {
return false;
}
String[] topicLevels = topic.split("/", -1);
for (int i = 0; i < filterLevels.length; i++) {
String filterLevel = filterLevels[i];
@@ -733,12 +884,29 @@ public class IotMqttBrokerService implements Resettable {
return filterLevels.length == topicLevels.length;
}
private void received(ClientSession session) {
session.lastPacketNanos().set(nanoTime.getAsLong());
}
private boolean keepAliveExpired(ClientSession session) {
int keepAlive = session.endpoint().keepAliveTimeSeconds();
// Vert.x closes a client silent for ceil(1.5 * keep-alive) seconds since Netty's last read.
// Every packet is stamped here before Netty stamps it, the CONNECT microseconds after.
long timeout = TimeUnit.SECONDS.toNanos((long) Math.ceil(keepAlive * 1.5)) - KEEP_ALIVE_SLACK_NANOS;
return keepAlive > 0 && nanoTime.getAsLong() - session.lastPacketNanos().get() >= timeout;
}
private record ClientSession(
String clientId,
MqttEndpoint endpoint,
String sourceIp,
int sourcePort,
boolean cleanSession) {
boolean cleanSession,
String sessionIdentifier,
String principalIdentifier,
long versionNumber,
AtomicBoolean ended,
AtomicLong lastPacketNanos) {
}
private record Subscription(String topicFilter, int qos) {
@@ -120,7 +120,8 @@ public class IotMqttWebSocketBridge {
/**
* The upgrade as AWS hands it to a custom authorizer; the server name only over TLS, from SNI or
* else the Host header. The client's address rides along for the broker's policy evaluation.
* else the Host header. The client's address and port ride along for the broker's policy
* evaluation and GetConnection.
*/
private static IotCustomAuthorizer.WebSocketUpgrade upgradeOf(ServerWebSocket ws) {
Map<String, String> headers = new LinkedHashMap<>();
@@ -135,7 +136,7 @@ public class IotMqttWebSocketBridge {
}
SocketAddress client = ws.remoteAddress();
return new IotCustomAuthorizer.WebSocketUpgrade(headers, ws.query() == null ? "" : ws.query(), serverName,
client == null ? null : client.host());
client == null ? null : client.host(), client == null ? -1 : client.port());
}
static final class BridgeSession {
@@ -2035,6 +2035,11 @@ public class IotService {
return false;
}
String[] filterParts = filter.split("/", -1);
// Measured on AWS IoT: a wildcard first level matches the $aws/things shadow topics but not the lifecycle topics.
if (topic.startsWith(IotMqttBrokerService.PRESENCE_TOPIC_PREFIX)
&& ("#".equals(filterParts[0]) || "+".equals(filterParts[0]))) {
return false;
}
String[] topicParts = topic.split("/", -1);
int i = 0;
for (; i < filterParts.length; i++) {
@@ -389,7 +389,7 @@ class IotCustomAuthorizerTest {
headers.put("sec-websocket-protocol", "mqtt");
List<String> policies = customAuthorizer.connectPolicies("a", "c", "c?" + NAME_PARAM + "a", "secret",
new WebSocketUpgrade(headers, "", "iot.example.com", null));
new WebSocketUpgrade(headers, "", "iot.example.com", null, -1));
assertEquals(List.of(POLICY), policies);
assertEquals("{\"protocolData\":{\"tls\":{\"serverName\":\"iot.example.com\"},\"mqtt\":{\"username\":"
@@ -401,7 +401,7 @@ class IotCustomAuthorizerTest {
@Test
void aConnectWithoutUsernamePasswordOrTlsLeavesThemOut() {
customAuthorizer.connectPolicies("a", "c", null, null, new WebSocketUpgrade(Map.of(), NAME_PARAM + "a", null, null));
customAuthorizer.connectPolicies("a", "c", null, null, new WebSocketUpgrade(Map.of(), NAME_PARAM + "a", null, null, -1));
assertEquals("{\"protocolData\":{\"mqtt\":{\"clientId\":\"c\"},\"http\":{\"headers\":{},"
+ "\"queryString\":\"x-amz-customauthorizer-name=a\"}},\"protocols\":[\"http\",\"mqtt\"],"
@@ -467,11 +467,11 @@ class IotCustomAuthorizerTest {
String signature = sign(key1, "allow-me");
customAuthorizer.connectPolicies("s", "c", "c", null, new WebSocketUpgrade(Map.of(),
NAME_PARAM + "s&" + SIGNATURE_PARAM + urlEncoded(signature) + "&tok=allow-me", null, null));
NAME_PARAM + "s&" + SIGNATURE_PARAM + urlEncoded(signature) + "&tok=allow-me", null, null, -1));
assertEquals("allow-me", events.getLast().path("token").asText());
customAuthorizer.connectPolicies("s", "c", "c", null, new WebSocketUpgrade(
Map.of("x-amz-customauthorizer-signature", signature, "tok", "allow-me"), "", null, null));
Map.of("x-amz-customauthorizer-signature", signature, "tok", "allow-me"), "", null, null, -1));
assertEquals("allow-me", events.getLast().path("token").asText());
}
@@ -489,9 +489,9 @@ class IotCustomAuthorizerTest {
@Test
void theAuthorizerNameComesFromTheUsernameTheWebSocketQueryOrTheUpgradeHeader() {
assertEquals("u", IotCustomAuthorizer.authorizerName("c?" + NAME_PARAM + "u&tok=t", null));
assertEquals("q", IotCustomAuthorizer.authorizerName("c", new WebSocketUpgrade(Map.of(), NAME_PARAM + "q", null, null)));
assertEquals("q", IotCustomAuthorizer.authorizerName("c", new WebSocketUpgrade(Map.of(), NAME_PARAM + "q", null, null, -1)));
assertEquals("h", IotCustomAuthorizer.authorizerName(null,
new WebSocketUpgrade(Map.of("x-amz-customauthorizer-name", "h"), "", null, null)));
new WebSocketUpgrade(Map.of("x-amz-customauthorizer-name", "h"), "", null, null, -1)));
}
@Test
@@ -499,7 +499,7 @@ class IotCustomAuthorizerTest {
assertNull(IotCustomAuthorizer.authorizerName(null, null));
assertNull(IotCustomAuthorizer.authorizerName("plain-user", null));
assertNull(IotCustomAuthorizer.authorizerName("c?X-Amz-Algorithm=AWS4-HMAC-SHA256", new WebSocketUpgrade(
Map.of("sec-websocket-protocol", "mqtt"), "X-Amz-Signature=00", null, null)));
Map.of("sec-websocket-protocol", "mqtt"), "X-Amz-Signature=00", null, null, -1)));
assertEquals("%zz", IotCustomAuthorizer.authorizerName("c?" + NAME_PARAM + "%zz", null),
"a malformed escape is kept as sent instead of failing the CONNECT");
}
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.Pem;
@@ -25,6 +27,7 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.ArgumentCaptor;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
@@ -35,6 +38,7 @@ import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -50,6 +54,7 @@ import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -186,6 +191,24 @@ class IotMqttBrokerDeviceVerificationTest {
}
}
@Test
void anAdmittedDevicesLifecycleEventsCarryItsCertificateIdAsPrincipal() throws Exception {
RegisteredDevice device = registered(deviceLeaf);
when(service.findRegisteredCertificate(certificate(deviceLeaf))).thenReturn(Optional.of(device));
when(service.isConnectAllowed(eq(device), eq("sensor-1"), eq("127.0.0.1"), isNull())).thenReturn(true);
MqttClient client = connectTls("sensor-1", deviceLeaf, null);
client.disconnect();
client.close();
JsonNode connected = publishedEvent("$aws/events/presence/connected/sensor-1");
JsonNode disconnected = publishedEvent("$aws/events/presence/disconnected/sensor-1");
assertEquals(List.of("clientId", "timestamp", "eventType", "sessionIdentifier", "principalIdentifier",
"versionNumber", "ipAddress"), fieldNames(connected));
assertEquals(device.certificate().getCertificateId(), connected.get("principalIdentifier").asText());
assertEquals(device.certificate().getCertificateId(), disconnected.get("principalIdentifier").asText());
}
@Test
void aDeniedDeviceIsAnsweredWithConnackNotAuthorized() throws Exception {
RegisteredDevice device = registered(deviceLeaf);
@@ -254,7 +277,8 @@ class IotMqttBrokerDeviceVerificationTest {
client.connect();
assertTrue(client.isConnected());
verifyNoInteractions(service);
verify(service, never()).findRegisteredCertificate(any());
verify(service, never()).isConnectAllowed(any(), anyString(), any(), any());
} finally {
client.disconnect();
client.close();
@@ -306,6 +330,19 @@ class IotMqttBrokerDeviceVerificationTest {
assertFalse(refused.getMessage().isBlank());
}
/** The payload the broker handed the IoT service for the one publish on {@code topic}, an MQTT client's publish. */
private JsonNode publishedEvent(String topic) throws IOException {
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
verify(service, timeout(10_000)).publish(eq(topic), payload.capture(), eq(false), eq(0), isNull(), eq("sensor-1"), any());
return new ObjectMapper().readTree(payload.getValue());
}
private static List<String> fieldNames(JsonNode node) {
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
return names;
}
private static RegisteredDevice registered(CertificateGenerator.GeneratedCertificate leaf) {
IotCertificate certificate = new IotCertificate();
certificate.setCertificateId("id-" + leaf.hashCode());
File diff suppressed because it is too large. Load diff
@@ -20,16 +20,21 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
@@ -38,6 +43,7 @@ import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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;
@@ -50,6 +56,10 @@ class IotMqttEnabledIntegrationTest {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final String BUILDING_RULE_SQL = "SELECT *, topic() AS topic, clientid() AS cid "
+ "FROM '$aws/things/+/shadow/name/building/update/accepted' WHERE endswith(clientToken, 'inbound')";
private static final String TKLOCAL_CONNECTED_SQL =
"SELECT * FROM '$aws/events/presence/connected/+' WHERE startswith(clientId, 'tklocal-')";
private static final String TKLOCAL_DISCONNECTED_SQL =
"SELECT * FROM '$aws/events/presence/disconnected/+' WHERE startswith(clientId, 'tklocal-')";
@Inject
IotPublishEventRecorder eventRecorder;
@@ -581,6 +591,46 @@ class IotMqttEnabledIntegrationTest {
}
}
@Test
void tklocalPresenceRulesReceiveTheConnectAndCleanDisconnectOfATklocalClientOnly() throws Exception {
long suffix = System.nanoTime();
String queueUrl = createQueue("presence-clean-" + suffix);
String connectedRule = "presenceConnected" + suffix;
String disconnectedRule = "presenceDisconnected" + suffix;
createSqsRule(connectedRule, TKLOCAL_CONNECTED_SQL, queueUrl);
createSqsRule(disconnectedRule, TKLOCAL_DISCONNECTED_SQL, queueUrl);
try {
String clientId = "tklocal-" + suffix;
try (MqttTestClient other = connectMqttClientId("other-" + suffix)) {
assertTrue(other.isConnected());
}
try (MqttTestClient client = connectMqttClientId(clientId)) {
assertTrue(client.isConnected());
}
// One worker runs the rules in publish order, so the other client's events were evaluated first.
List<JsonNode> messages = awaitMessages(queueUrl, 2);
assertEquals(2, messages.size(), "only the tklocal client's two events: " + messages);
Map<String, JsonNode> byType = new HashMap<>();
for (JsonNode message : messages) {
assertEquals(clientId, message.path("clientId").asText(), message.toString());
byType.put(message.path("eventType").asText(), message);
}
JsonNode connected = byType.get("connected");
JsonNode disconnected = byType.get("disconnected");
assertEquals(Set.of("connected", "disconnected"), byType.keySet());
assertEquals(connected.path("sessionIdentifier").asText(), disconnected.path("sessionIdentifier").asText());
assertEquals(0, connected.path("versionNumber").asLong());
assertEquals(0, disconnected.path("versionNumber").asLong());
assertEquals("127.0.0.1", connected.path("ipAddress").asText());
assertTrue(disconnected.path("clientInitiatedDisconnect").asBoolean(), disconnected.toString());
assertEquals("CLIENT_INITIATED_DISCONNECT", disconnected.path("disconnectReason").asText());
} finally {
deleteRule(connectedRule);
deleteRule(disconnectedRule);
}
}
@Test
void mqttSubscriberReceivesTheAcceptedEventOfARestShadowUpdate() throws Exception {
String thing = "shadowRestToMqtt" + System.nanoTime();
@@ -600,6 +650,74 @@ class IotMqttEnabledIntegrationTest {
}
}
@Test
void tklocalDisconnectedRuleReceivesConnectionLostWhenTheClientVanishesWithoutDisconnect() throws Exception {
long suffix = System.nanoTime();
String queueUrl = createQueue("presence-lost-" + suffix);
String disconnectedRule = "presenceLost" + suffix;
createSqsRule(disconnectedRule, TKLOCAL_DISCONNECTED_SQL, queueUrl);
try {
String clientId = "tklocal-lost-" + suffix;
MqttTestClient client = connectMqttClientId(clientId);
client.closeWithoutDisconnect();
List<JsonNode> messages = awaitMessages(queueUrl, 1);
assertEquals(1, messages.size(), messages.toString());
JsonNode disconnected = messages.get(0);
assertEquals(clientId, disconnected.path("clientId").asText());
assertEquals("CONNECTION_LOST", disconnected.path("disconnectReason").asText());
assertTrue(disconnected.path("clientInitiatedDisconnect").isBoolean(), disconnected.toString());
assertFalse(disconnected.path("clientInitiatedDisconnect").asBoolean());
} finally {
deleteRule(disconnectedRule);
}
}
@Test
void tklocalDisconnectedRuleReceivesKeepAliveTimeoutWhenTheClientFallsSilent() throws Exception {
long suffix = System.nanoTime();
String queueUrl = createQueue("presence-silent-" + suffix);
String disconnectedRule = "presenceSilent" + suffix;
createSqsRule(disconnectedRule, TKLOCAL_DISCONNECTED_SQL, queueUrl);
try (Socket socket = rawConnect("tklocal-silent-" + suffix, 1)) {
List<JsonNode> messages = awaitMessages(queueUrl, 1);
assertEquals(1, messages.size(), messages.toString());
JsonNode disconnected = messages.get(0);
assertEquals("tklocal-silent-" + suffix, disconnected.path("clientId").asText());
assertEquals("MQTT_KEEP_ALIVE_TIMEOUT", disconnected.path("disconnectReason").asText());
assertTrue(disconnected.path("clientInitiatedDisconnect").isBoolean(), disconnected.toString());
assertFalse(disconnected.path("clientInitiatedDisconnect").asBoolean());
} finally {
deleteRule(disconnectedRule);
}
}
@Test
void tklocalDisconnectedRuleReceivesConnectionLostWhenAPingingClientDrops() throws Exception {
long suffix = System.nanoTime();
String queueUrl = createQueue("presence-pinging-" + suffix);
String disconnectedRule = "presencePinging" + suffix;
createSqsRule(disconnectedRule, TKLOCAL_DISCONNECTED_SQL, queueUrl);
try {
try (Socket socket = rawConnect("tklocal-pinging-" + suffix, 1)) {
Instant pingUntil = Instant.now().plusMillis(2_500);
while (Instant.now().isBefore(pingUntil)) {
socket.getOutputStream().write(new byte[] {(byte) 0xc0, 0x00});
assertArrayEquals(new byte[] {(byte) 0xd0, 0x00}, socket.getInputStream().readNBytes(2), "PINGRESP");
Thread.sleep(400);
}
}
List<JsonNode> messages = awaitMessages(queueUrl, 1);
assertEquals(1, messages.size(), messages.toString());
assertEquals("CONNECTION_LOST", messages.get(0).path("disconnectReason").asText());
assertFalse(messages.get(0).path("clientInitiatedDisconnect").asBoolean());
} finally {
deleteRule(disconnectedRule);
}
}
private String createQueue(String queueName) {
return given()
.contentType("application/x-www-form-urlencoded")
@@ -638,12 +756,31 @@ class IotMqttEnabledIntegrationTest {
throw new AssertionError("No message arrived on " + queueUrl);
}
/** Receives until {@code count} messages arrived or ten seconds passed, then once more, so a surplus one shows too. */
private List<JsonNode> awaitMessages(String queueUrl, int count) throws Exception {
List<JsonNode> messages = new ArrayList<>();
Instant deadline = Instant.now().plus(Duration.ofSeconds(10));
while (messages.size() < count && Instant.now().isBefore(deadline)) {
for (String body : receiveMessages(queueUrl)) {
messages.add(OBJECT_MAPPER.readTree(body));
}
if (messages.size() < count) {
Thread.sleep(50);
}
}
for (String body : receiveMessages(queueUrl)) {
messages.add(OBJECT_MAPPER.readTree(body));
}
return messages;
}
private void createSqsRule(String ruleName, String sql, String queueUrl) {
ObjectNode sqs = OBJECT_MAPPER.createObjectNode()
.put("roleArn", "arn:aws:iam::000000000000:role/iot-rule-role")
.put("queueUrl", queueUrl);
ObjectNode payload = OBJECT_MAPPER.createObjectNode()
.put("sql", sql)
.put("awsIotSqlVersion", "2016-03-23")
.put("ruleDisabled", false);
payload.putArray("actions").addObject().set("sqs", sqs);
ObjectNode body = OBJECT_MAPPER.createObjectNode();
@@ -726,6 +863,34 @@ class IotMqttEnabledIntegrationTest {
throw new AssertionError("MQTT publish event was not recorded");
}
/** An MQTT 3.1.1 CONNECT over a plain socket, so the test decides exactly which packets follow it. */
private static Socket rawConnect(String clientId, int keepAliveSeconds) throws IOException {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("127.0.0.1", IotMqttTlsProfile.PLAIN_PORT), 5_000);
socket.setSoTimeout(5_000);
ByteArrayOutputStream body = new ByteArrayOutputStream();
writeUtf8(body, "MQTT");
body.write(0x04);
body.write(0x02);
body.write(keepAliveSeconds >>> 8);
body.write(keepAliveSeconds & 0xff);
writeUtf8(body, clientId);
ByteArrayOutputStream connect = new ByteArrayOutputStream();
connect.write(0x10);
connect.write(body.size());
connect.writeBytes(body.toByteArray());
socket.getOutputStream().write(connect.toByteArray());
assertArrayEquals(new byte[] {0x20, 0x02, 0x00, 0x00}, socket.getInputStream().readNBytes(4), "CONNACK accepted");
return socket;
}
private static void writeUtf8(ByteArrayOutputStream out, String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
out.write(bytes.length >>> 8);
out.write(bytes.length & 0xff);
out.writeBytes(bytes);
}
private record MqttPublish(String topic, byte[] payload) {
}
@@ -795,6 +960,12 @@ class IotMqttEnabledIntegrationTest {
throw new AssertionError("MQTT connection stayed open");
}
/** Drops the TCP connection without sending DISCONNECT, as a crashed device would. */
void closeWithoutDisconnect() throws MqttException {
client.disconnectForcibly(0, 0, false);
client.close();
}
@Override
public void close() throws MqttException {
if (client.isConnected()) {
@@ -142,8 +142,8 @@ class IotMqttWebSocketBridgeTest {
@Test
void closingAnOlderSessionKeepsANewerSessionsEqualUpgradeOnTheSameAddress() {
SocketAddress address = SocketAddress.inetSocketAddress(50000, "127.0.0.1");
IotCustomAuthorizer.WebSocketUpgrade older = new IotCustomAuthorizer.WebSocketUpgrade(Map.of("host", "h"), "", null, null);
IotCustomAuthorizer.WebSocketUpgrade newer = new IotCustomAuthorizer.WebSocketUpgrade(Map.of("host", "h"), "", null, null);
IotCustomAuthorizer.WebSocketUpgrade older = new IotCustomAuthorizer.WebSocketUpgrade(Map.of("host", "h"), "", null, null, -1);
IotCustomAuthorizer.WebSocketUpgrade newer = new IotCustomAuthorizer.WebSocketUpgrade(Map.of("host", "h"), "", null, null, -1);
Map<SocketAddress, IotCustomAuthorizer.WebSocketUpgrade> upgrades = new ConcurrentHashMap<>(Map.of(address, newer));
IotMqttWebSocketBridge.forgetting(upgrades, address, older).run();
@@ -206,6 +206,28 @@ class IotServiceTest {
verify(lambda).invoke(eq(REGION), eq(FUNCTION_ARN), any(), eq(InvocationType.Event));
}
/** As AWS IoT does for rule topic filters: a wildcard first level does not match a lifecycle topic. */
@Test
void aRuleWhoseTopicFilterStartsWithAWildcardDoesNotFireForALifecycleTopic() throws Exception {
String everything = "http://localhost:4566/000000000000/everything";
String anyPresence = "http://localhost:4566/000000000000/any-presence";
String presence = "http://localhost:4566/000000000000/presence";
createRule("everything", sqsRule("SELECT * FROM '#'", everything));
createRule("anyPresence", sqsRule("SELECT * FROM '+/events/presence/+/+'", anyPresence));
createRule("presence", sqsRule("SELECT * FROM '$aws/events/presence/connected/+'", presence));
service.handlePublish("$aws/events/presence/connected/x", "{\"clientId\":\"x\"}".getBytes(StandardCharsets.UTF_8),
true, REGION, "x", Runnable::run);
verify(sqs, never()).sendMessage(eq(everything), anyString(), anyInt(), anyString());
verify(sqs, never()).sendMessage(eq(anyPresence), anyString(), anyInt(), anyString());
verify(sqs).sendMessage(eq(presence), eq("{\"clientId\":\"x\"}"), eq(0), eq(REGION));
service.handlePublish("a/b", "{\"v\":1}".getBytes(StandardCharsets.UTF_8), true, REGION, null, Runnable::run);
verify(sqs).sendMessage(eq(everything), eq("{\"v\":1}"), eq(0), eq(REGION));
}
@Test
void aFailingActionDoesNotFailThePublishOrStopTheOtherActions() throws Exception {
createRule("metricsRule", sqsThenLambdaRule(null));