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

@@ -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));