mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iot): authenticate unsigned MQTT over WebSocket with the default authorizer (#8653)
This commit is contained in:
1 parent
6871348ea6
commit
813f89bd8e
15 files changed
+235
-67
No files matched your search
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.parallel.ResourceLock;
|
||||
import software.amazon.awssdk.regions.PartitionMetadata;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.iot.IotClient;
|
||||
@@ -43,6 +44,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowableOfType;
|
||||
import static org.assertj.core.api.Assumptions.assumeThat;
|
||||
|
||||
@ResourceLock("iot-default-authorizer")
|
||||
@DisplayName("IoT custom authorizer management")
|
||||
class IotAuthorizerTest {
|
||||
|
||||
|
||||
+33
@@ -19,6 +19,7 @@ import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestInstance;
|
||||
import org.junit.jupiter.api.parallel.ResourceLock;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
@@ -93,6 +94,7 @@ import static org.assertj.core.api.Assertions.fail;
|
||||
* ones are imported and the v5 ones are written fully qualified.
|
||||
*/
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
@ResourceLock("iot-default-authorizer")
|
||||
@DisplayName("IoT custom authorizer invocation and enforcement")
|
||||
class IotCustomAuthorizerTest {
|
||||
|
||||
@@ -735,6 +737,37 @@ class IotCustomAuthorizerTest {
|
||||
"allow-me".getBytes(StandardCharsets.UTF_8), Map.of(NAME_HEADER, authorizer)));
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@EnumSource(Mqtt.class)
|
||||
@DisplayName("a CONNECT that names no authorizer and carries no SigV4 is refused")
|
||||
void mqttUnsignedWithoutAuthorizerRefused(Mqtt version) {
|
||||
assertRefused(version, target(clientId, "allow-me"));
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@EnumSource(Mqtt.class)
|
||||
@DisplayName("a CONNECT that names no authorizer and carries no SigV4 goes through the default authorizer")
|
||||
void mqttUnsignedGoesThroughTheDefaultAuthorizer(Mqtt version) throws Exception {
|
||||
iot.setDefaultAuthorizer(r -> r.authorizerName(authorizer));
|
||||
try {
|
||||
assertConnects(version, target(clientId, "allow-me"));
|
||||
} finally {
|
||||
iot.clearDefaultAuthorizer(r -> { });
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@EnumSource(Mqtt.class)
|
||||
@DisplayName("the default authorizer refuses an unsigned CONNECT its function denies")
|
||||
void mqttUnsignedDeniedByTheDefaultAuthorizer(Mqtt version) {
|
||||
iot.setDefaultAuthorizer(r -> r.authorizerName(authorizer));
|
||||
try {
|
||||
assertRefused(version, target(clientId, "deny"));
|
||||
} finally {
|
||||
iot.clearDefaultAuthorizer(r -> { });
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "{0}")
|
||||
@EnumSource(Mqtt.class)
|
||||
@DisplayName("WebSocket event: name in the username, empty query, lower-case headers")
|
||||
|
||||
@@ -88,11 +88,11 @@ The function is invoked synchronously with the event AWS IoT sends (`protocolDat
|
||||
|
||||
- `TestInvokeAuthorizer` works on `ACTIVE` and `INACTIVE` authorizers. It returns the request errors (`InvalidRequestException`) and answer errors (`InvalidResponseException`) with AWS's messages, and passes the contexts on as given: header case is kept and `queryString` keeps its leading `?`.
|
||||
- An MQTT `CONNECT` on the plaintext listener or on [MQTT over WebSocket](#mqtt-over-websocket) that names an authorizer, in the username (`<clientId>?x-amz-customauthorizer-name=<name>`), the WebSocket URL query or the `x-amz-customauthorizer-name` upgrade header, is admitted only when the authorizer exists and is `ACTIVE`, the signature verifies for a signed authorizer, the answer is valid, `isAuthenticated` is `true`, and the returned policies allow `iot:Connect` on `arn:aws:iot:<region>:<account>:client/<clientId>`. The event carries the username with its query, the password in base64, and for WebSocket the lower-cased upgrade headers, the query string without `?` and, over TLS, the server name.
|
||||
- A refused MQTT 3.1.1 client is disconnected without a `CONNACK`; an MQTT 5 client gets `CONNACK` reason code `0x87` with the reason string AWS sends, then the connection closes. A `CONNECT` that names no authorizer is handled as before.
|
||||
- A refused MQTT 3.1.1 client is disconnected without a `CONNACK`; an MQTT 5 client gets `CONNACK` reason code `0x87` with the reason string AWS sends, then the connection closes.
|
||||
- A `CONNECT` over MQTT over WebSocket that names no authorizer and whose upgrade URL carries no SigV4 signature (`X-Amz-Signature` in the query) goes through the account's default authorizer (`SetDefaultAuthorizer`), as on AWS. Without a default authorizer it is refused the same way. On the plaintext listener a `CONNECT` that names no authorizer is admitted.
|
||||
|
||||
Current limitations:
|
||||
|
||||
- The default authorizer is not used: a `CONNECT` that names no authorizer is not authenticated.
|
||||
- HTTPS publish does not invoke authorizers, and `enableCachingForHttp` has no effect.
|
||||
- `refreshAfterInSeconds` and `disconnectAfterInSeconds` are returned but do not schedule a re-invocation or a disconnect.
|
||||
- The returned policies decide `iot:Connect` only; publish, subscribe and receive are not checked against them.
|
||||
@@ -276,8 +276,9 @@ No client certificate is requested on this path. On AWS it authenticates by SigV
|
||||
string on the upgrade URL) or by a custom authorizer (`<clientId>?x-amz-customauthorizer-name=<name>`
|
||||
as the MQTT username with a token as the password). Floci enforces a custom authorizer named in the
|
||||
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.
|
||||
[Authorizers](#authorizers). A CONNECT that names no authorizer is admitted when the upgrade URL
|
||||
carries a SigV4 query string, which Floci does not verify; otherwise it goes through the default
|
||||
authorizer and is refused when none is set.
|
||||
|
||||
### Lifecycle events
|
||||
|
||||
|
||||
@@ -62,6 +62,11 @@ public class IotCustomAuthorizer {
|
||||
*/
|
||||
record WebSocketUpgrade(Map<String, String> headers, String queryString, String serverName, String sourceIp,
|
||||
int sourcePort) {
|
||||
|
||||
boolean isSigV4Signed() {
|
||||
String signature = params(null, Map.of(), queryString).get("X-Amz-Signature");
|
||||
return signature != null && !signature.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Inject
|
||||
@@ -134,14 +139,19 @@ public class IotCustomAuthorizer {
|
||||
}
|
||||
|
||||
/**
|
||||
* The policies an MQTT CONNECT through the named authorizer is admitted with. None when the
|
||||
* authorizer is not ACTIVE, which never invokes the function, or when the function denies or
|
||||
* returns no policy; an {@link AwsException} when the authorizer does not exist, a signature
|
||||
* does not verify (the function is not invoked) or the answer is one TestInvokeAuthorizer rejects.
|
||||
* The policies an MQTT CONNECT through the named authorizer, or the default authorizer when
|
||||
* {@code name} is null, is admitted with. None when the authorizer is not ACTIVE, which never
|
||||
* invokes the function, or when the function denies or returns no policy; an
|
||||
* {@link AwsException} when the authorizer does not exist or no default authorizer is set, a
|
||||
* signature does not verify (the function is not invoked) or the answer is one
|
||||
* TestInvokeAuthorizer rejects.
|
||||
*/
|
||||
List<String> connectPolicies(String name, String clientId, String username, String password, WebSocketUpgrade upgrade) {
|
||||
// ponytail: the broker has no request context, so a connection finds authorizers in the default account and region.
|
||||
IotAuthorizer authorizer = authorizers.describeAuthorizer(name, regionResolver.getDefaultRegion());
|
||||
String region = regionResolver.getDefaultRegion();
|
||||
IotAuthorizer authorizer = name == null
|
||||
? authorizers.describeDefaultAuthorizer(region)
|
||||
: authorizers.describeAuthorizer(name, region);
|
||||
if (!"ACTIVE".equals(authorizer.getStatus())) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@@ -446,8 +446,9 @@ public class IotMqttBrokerService implements Resettable {
|
||||
* has registered and whose attached policies allow {@code iot:Connect} for the client id;
|
||||
* anything else is answered with CONNACK not authorized (return code 5, reason code 0x87 on
|
||||
* MQTT 5) and never becomes a session, so a client already holding that client id keeps its
|
||||
* connection. The plaintext listener, which the WebSocket bridge also lands on, stays open to
|
||||
* every client except one that names a custom authorizer, see {@link #authorizeCustom}.
|
||||
* connection. The plaintext listener stays open to every client except one that names a custom
|
||||
* authorizer, see {@link #authorizeCustom}. A WebSocket client that names none goes through the
|
||||
* default authorizer unless its upgrade carries a SigV4 signature, which is not verified.
|
||||
*/
|
||||
void handleEndpoint(MqttEndpoint endpoint, boolean verifyDevice) {
|
||||
long connectNanos = nanoTime.getAsLong();
|
||||
@@ -472,7 +473,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
String username = endpoint.auth() == null ? null : endpoint.auth().getUsername();
|
||||
String authorizerName = IotCustomAuthorizer.authorizerName(username, upgrade);
|
||||
if (authorizerName != null) {
|
||||
if (authorizerName != null || (upgrade != null && !upgrade.isSigV4Signed())) {
|
||||
authorizeCustom(endpoint, authorizerName, upgrade, sourceIp, sourcePort, connectNanos);
|
||||
return;
|
||||
}
|
||||
@@ -481,10 +482,11 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* A CONNECT naming a custom authorizer is admitted only when the authorizer's function allows
|
||||
* it and the policies it returns allow {@code iot:Connect} for the client id. The function runs
|
||||
* off the event loop. A refusal closes an MQTT 3.1.1 connection without a CONNACK and answers
|
||||
* MQTT 5 with reason code 0x87, as AWS IoT does.
|
||||
* A CONNECT through the named custom authorizer, or the default authorizer when
|
||||
* {@code authorizerName} is null, is admitted only when the authorizer's function allows it and
|
||||
* the policies it returns allow {@code iot:Connect} for the client id; with no default authorizer
|
||||
* set it is refused. The function runs off the event loop. A refusal closes an MQTT 3.1.1
|
||||
* connection without a CONNACK and answers MQTT 5 with reason code 0x87, as AWS IoT does.
|
||||
*/
|
||||
private void authorizeCustom(MqttEndpoint endpoint, String authorizerName, IotCustomAuthorizer.WebSocketUpgrade upgrade,
|
||||
String sourceIp, int sourcePort, long connectNanos) {
|
||||
@@ -505,7 +507,8 @@ public class IotMqttBrokerService implements Resettable {
|
||||
admit(endpoint, null, sourceIp, sourcePort, connectNanos);
|
||||
return;
|
||||
}
|
||||
LOG.debugv("IoT MQTT client {0} refused by custom authorizer {1}: {2}", clientId, authorizerName,
|
||||
LOG.debugv("IoT MQTT client {0} refused by custom authorizer {1}: {2}", clientId,
|
||||
authorizerName == null ? "(default)" : authorizerName,
|
||||
decision.failed() ? decision.cause().getMessage() : "iot:Connect is not allowed");
|
||||
if (endpoint.protocolVersion() != 5) {
|
||||
endpoint.close();
|
||||
|
||||
@@ -24,9 +24,9 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
* are piped byte for byte to the broker's plaintext listener, so every broker feature and every
|
||||
* authorization rule applies without a second code path. No client certificate is involved: on
|
||||
* AWS this path authenticates by SigV4 or a custom authorizer. The broker enforces a custom
|
||||
* authorizer named in the MQTT username, the URL query or an upgrade header, and stays permissive
|
||||
* otherwise; the upgrade's headers, query, server name and client address reach it through
|
||||
* {@link IotMqttBrokerService#webSocketUpgrades()}.
|
||||
* authorizer named in the MQTT username, the URL query or an upgrade header, else the default
|
||||
* authorizer unless the upgrade carries a SigV4 signature; the upgrade's headers, query, server
|
||||
* name and client address reach it through {@link IotMqttBrokerService#webSocketUpgrades()}.
|
||||
*
|
||||
* <p>Everything for one session runs on the event loop of the WebSocket's connection, the
|
||||
* broker socket included, so the handlers below never race each other.
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.config;
|
||||
|
||||
import io.floci.aws.services.iot.IotMqttWebSocketIntegrationTest;
|
||||
import io.floci.aws.testing.IotMqttTlsProfile;
|
||||
import io.floci.aws.testing.IotWebSocketSigV4;
|
||||
import io.floci.aws.testutil.FreePorts;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -83,9 +84,9 @@ class IotMqttWebSocketProxyIntegrationTest {
|
||||
String topic = "proxy/" + System.nanoTime();
|
||||
byte[] payload = "through the proxy".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
try (PahoClient subscriber = PahoClient.connect("wss://127.0.0.1:" + publicPort + "/mqtt", "proxy-wss-" + System.nanoTime())) {
|
||||
try (PahoClient subscriber = PahoClient.connect("wss://127.0.0.1:" + publicPort + "/mqtt" + IotWebSocketSigV4.QUERY, "proxy-wss-" + System.nanoTime())) {
|
||||
subscriber.client.subscribe(topic, 1);
|
||||
try (PahoClient publisher = PahoClient.connect("ws://127.0.0.1:" + publicPort + "/mqtt", "proxy-ws-" + System.nanoTime())) {
|
||||
try (PahoClient publisher = PahoClient.connect("ws://127.0.0.1:" + publicPort + "/mqtt" + IotWebSocketSigV4.QUERY, "proxy-ws-" + System.nanoTime())) {
|
||||
publisher.client.publish(topic, payload, 1, false);
|
||||
}
|
||||
assertArrayEquals(payload, subscriber.take(), "a TLS ClientHello and a plain GET on the same port both reach /mqtt");
|
||||
@@ -145,7 +146,7 @@ class IotMqttWebSocketProxyIntegrationTest {
|
||||
socket.startHandshake();
|
||||
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write(("GET /mqtt HTTP/1.1\r\nHost: " + host + ":" + testSslPort + "\r\nUpgrade: websocket\r\n"
|
||||
out.write(("GET /mqtt" + IotWebSocketSigV4.QUERY + " HTTP/1.1\r\nHost: " + host + ":" + testSslPort + "\r\nUpgrade: websocket\r\n"
|
||||
+ "Connection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n"
|
||||
+ "Sec-WebSocket-Protocol: mqtt\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
|
||||
out.flush();
|
||||
|
||||
@@ -6,6 +6,7 @@ import io.floci.aws.services.lambda.LambdaService;
|
||||
import io.floci.aws.services.lambda.model.InvocationType;
|
||||
import io.floci.aws.services.lambda.model.InvokeResult;
|
||||
import io.floci.aws.testing.IotMqttTlsProfile;
|
||||
import io.floci.aws.testing.IotWebSocketSigV4;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
@@ -288,8 +289,69 @@ class IotCustomAuthorizerIntegrationTest {
|
||||
assertEquals(base64("deny"), takeEvent().path("protocolData").path("mqtt").path("password").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt3UnsignedConnectNamingNoAuthorizerWithoutADefaultIsRefused() {
|
||||
String clientId = "cauth-v3-none-" + System.nanoTime();
|
||||
|
||||
MqttException refused = assertThrows(MqttException.class,
|
||||
() -> connectV3(ws(""), clientId, clientId, "allow", Map.of()));
|
||||
|
||||
assertEquals(MqttException.REASON_CODE_CONNECTION_LOST, refused.getReasonCode());
|
||||
verify(lambdaService, never()).invokeArn(anyString(), any(byte[].class), any(InvocationType.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mqtt5UnsignedConnectNamingNoAuthorizerWithoutADefaultGetsReasonCode135() {
|
||||
String clientId = "cauth-v5-none-" + System.nanoTime();
|
||||
|
||||
org.eclipse.paho.mqttv5.common.MqttException refused = assertThrows(org.eclipse.paho.mqttv5.common.MqttException.class,
|
||||
() -> connectV5(ws(""), clientId, clientId, "allow"));
|
||||
|
||||
assertEquals(135, refused.getReasonCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsignedConnectNamingNoAuthorizerGoesThroughTheDefaultAuthorizer() throws Exception {
|
||||
setDefaultAuthorizer();
|
||||
String clientId = "cauth-default-" + System.nanoTime();
|
||||
|
||||
connectV3(ws(""), clientId, clientId, "allow", Map.of()).disconnect();
|
||||
|
||||
JsonNode event = takeEvent();
|
||||
assertEquals(clientId, event.path("protocolData").path("mqtt").path("username").asText());
|
||||
assertEquals(base64("allow"), event.path("protocolData").path("mqtt").path("password").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDefaultAuthorizerRefusesAConnectItDenies() {
|
||||
setDefaultAuthorizer();
|
||||
String clientId = "cauth-default-deny-" + System.nanoTime();
|
||||
|
||||
MqttException refused = assertThrows(MqttException.class,
|
||||
() -> connectV3(ws(""), clientId, clientId, "deny", Map.of()));
|
||||
|
||||
assertEquals(MqttException.REASON_CODE_CONNECTION_LOST, refused.getReasonCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSigV4SignedConnectNamingNoAuthorizerSkipsTheDefaultAuthorizer() throws Exception {
|
||||
setDefaultAuthorizer();
|
||||
String clientId = "cauth-default-sigv4-" + System.nanoTime();
|
||||
|
||||
connectV3(ws(IotWebSocketSigV4.QUERY), clientId, clientId, "deny", Map.of()).disconnect();
|
||||
|
||||
verify(lambdaService, never()).invokeArn(anyString(), any(byte[].class), any(InvocationType.class));
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
private void setDefaultAuthorizer() {
|
||||
given().contentType("application/json").body("{\"authorizerName\": \"" + authorizer + "\"}")
|
||||
.when().post("/default-authorizer")
|
||||
.then().statusCode(200);
|
||||
cleanup.register(() -> given().when().delete("/default-authorizer").then().statusCode(200));
|
||||
}
|
||||
|
||||
private MqttClient connectV3(String url, String clientId, String username, String password, Map<String, String> headers)
|
||||
throws Exception {
|
||||
MqttClient client = new MqttClient(url, clientId, new MemoryPersistence());
|
||||
|
||||
@@ -451,6 +451,21 @@ class IotCustomAuthorizerTest {
|
||||
verifyNotInvoked();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConnectNamingNoAuthorizerGoesThroughTheDefaultAuthorizer() {
|
||||
authorizers.setDefaultAuthorizer("a", REGION);
|
||||
|
||||
assertEquals(List.of(POLICY), customAuthorizer.connectPolicies(null, "c", "c", "secret", null));
|
||||
assertEquals("c", events.getLast().path("protocolData").path("mqtt").path("username").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConnectNamingNoAuthorizerFailsWithoutADefaultAndInvokesNothing() {
|
||||
assertAwsError("ResourceNotFoundException", 404, "Default authorizer not found",
|
||||
() -> customAuthorizer.connectPolicies(null, "c", "c", "secret", null));
|
||||
verifyNotInvoked();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignedConnectSendsTheTokenAfterTheProtocols() throws GeneralSecurityException {
|
||||
String username = signedUsername(sign(key2, "allow-me"), "allow-me");
|
||||
@@ -486,6 +501,17 @@ class IotCustomAuthorizerTest {
|
||||
verifyNotInvoked();
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyAnUpgradeWhoseQueryCarriesASigV4SignatureIsSigV4Signed() {
|
||||
assertTrue(new WebSocketUpgrade(Map.of(), "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Signature=00", null, null, -1)
|
||||
.isSigV4Signed());
|
||||
assertFalse(new WebSocketUpgrade(Map.of(), "", null, null, -1).isSigV4Signed());
|
||||
assertFalse(new WebSocketUpgrade(Map.of(), "X-Amz-Algorithm=AWS4-HMAC-SHA256", null, null, -1).isSigV4Signed());
|
||||
assertFalse(new WebSocketUpgrade(Map.of(), "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Signature=", null, null, -1)
|
||||
.isSigV4Signed());
|
||||
assertFalse(new WebSocketUpgrade(Map.of("x-amz-signature", "00"), "", null, null, -1).isSigV4Signed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAuthorizerNameComesFromTheUsernameTheWebSocketQueryOrTheUpgradeHeader() {
|
||||
assertEquals("u", IotCustomAuthorizer.authorizerName("c?" + NAME_PARAM + "u&tok=t", null));
|
||||
|
||||
@@ -22,6 +22,7 @@ import io.floci.aws.services.lambda.LambdaService;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.services.sns.SnsService;
|
||||
import io.floci.aws.services.sqs.SqsService;
|
||||
import io.floci.aws.testing.IotWebSocketSigV4;
|
||||
import io.floci.aws.testing.ThreadStates;
|
||||
import io.floci.aws.testutil.FreePorts;
|
||||
import io.netty.handler.codec.mqtt.MqttProperties;
|
||||
@@ -123,6 +124,7 @@ import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
@@ -533,33 +535,36 @@ class IotMqttBrokerServiceTest {
|
||||
when(iotService.get()).thenReturn(service);
|
||||
when(customAuthorizer.connectPolicies(eq("ws-auth"), eq("ws-client"), any(), any(), any()))
|
||||
.thenReturn(List.of("{}"));
|
||||
SocketAddress bridge = SocketAddress.inetSocketAddress(50123, "127.0.0.1");
|
||||
broker.webSocketUpgrades().put(bridge, new IotCustomAuthorizer.WebSocketUpgrade(
|
||||
Map.of(), IotCustomAuthorizer.NAME_PARAM + "=ws-auth", null, "203.0.113.7", 41233));
|
||||
MqttEndpoint endpoint = mock(MqttEndpoint.class);
|
||||
when(endpoint.clientIdentifier()).thenReturn("ws-client");
|
||||
when(endpoint.remoteAddress()).thenReturn(bridge);
|
||||
MqttEndpoint endpoint = bridgedEndpoint("ws-client", IotCustomAuthorizer.NAME_PARAM + "=ws-auth");
|
||||
|
||||
broker.handleEndpoint(endpoint, false);
|
||||
|
||||
verify(service, timeout(10_000)).isConnectAllowedBy(List.of("{}"), "ws-client", "203.0.113.7", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsignedWebSocketConnectNamingNoAuthorizerGoesThroughTheDefaultAuthorizer() {
|
||||
IotService service = mock(IotService.class);
|
||||
when(iotService.get()).thenReturn(service);
|
||||
when(customAuthorizer.connectPolicies(isNull(), eq("ws-unsigned"), any(), any(), any())).thenReturn(List.of("{}"));
|
||||
MqttEndpoint endpoint = bridgedEndpoint("ws-unsigned", "");
|
||||
|
||||
broker.handleEndpoint(endpoint, false);
|
||||
|
||||
verify(service, timeout(10_000)).isConnectAllowedBy(List.of("{}"), "ws-unsigned", "203.0.113.7", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWebSocketClientsConnectedEventCarriesTheWebSocketClientsAddress() throws Exception {
|
||||
startBrokerRecordingPublishes();
|
||||
SocketAddress bridge = SocketAddress.inetSocketAddress(50124, "127.0.0.1");
|
||||
broker.webSocketUpgrades().put(bridge, new IotCustomAuthorizer.WebSocketUpgrade(Map.of(), "", null, "203.0.113.7", 41234));
|
||||
MqttEndpoint endpoint = mock(MqttEndpoint.class);
|
||||
when(endpoint.clientIdentifier()).thenReturn("ws-client");
|
||||
when(endpoint.remoteAddress()).thenReturn(bridge);
|
||||
MqttEndpoint endpoint = bridgedEndpoint("ws-client", IotWebSocketSigV4.QUERY.substring(1));
|
||||
when(endpoint.isConnected()).thenReturn(true);
|
||||
|
||||
broker.handleEndpoint(endpoint, false);
|
||||
|
||||
assertEquals("203.0.113.7", awaitPresence("connected", "ws-client", 1).get(0).get("ipAddress").asText(),
|
||||
"the WebSocket client's address, not the bridge's loopback socket");
|
||||
assertEquals(new IotMqttBrokerService.ConnectionInfo("ws-client", "203.0.113.7", 41234),
|
||||
assertEquals(new IotMqttBrokerService.ConnectionInfo("ws-client", "203.0.113.7", 41233),
|
||||
broker.getConnection("ws-client").orElseThrow(), "the WebSocket client's address and port");
|
||||
}
|
||||
|
||||
@@ -1213,12 +1218,7 @@ class IotMqttBrokerServiceTest {
|
||||
return List.of("""
|
||||
{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "iot:Connect", "Resource": "*"}]}""");
|
||||
});
|
||||
SocketAddress bridge = SocketAddress.inetSocketAddress(50125, "127.0.0.1");
|
||||
broker.webSocketUpgrades().put(bridge, new IotCustomAuthorizer.WebSocketUpgrade(
|
||||
Map.of(), IotCustomAuthorizer.NAME_PARAM + "=slow-auth", null, "203.0.113.7", 41235));
|
||||
MqttEndpoint endpoint = mock(MqttEndpoint.class);
|
||||
when(endpoint.clientIdentifier()).thenReturn("slow");
|
||||
when(endpoint.remoteAddress()).thenReturn(bridge);
|
||||
MqttEndpoint endpoint = bridgedEndpoint("slow", IotCustomAuthorizer.NAME_PARAM + "=slow-auth");
|
||||
when(endpoint.keepAliveTimeSeconds()).thenReturn(1);
|
||||
|
||||
broker.handleEndpoint(endpoint, false);
|
||||
@@ -1902,6 +1902,16 @@ class IotMqttBrokerServiceTest {
|
||||
return message;
|
||||
}
|
||||
|
||||
private MqttEndpoint bridgedEndpoint(String clientId, String queryString) {
|
||||
SocketAddress bridge = SocketAddress.inetSocketAddress(50123, "127.0.0.1");
|
||||
broker.webSocketUpgrades().put(bridge, new IotCustomAuthorizer.WebSocketUpgrade(
|
||||
Map.of(), queryString, null, "203.0.113.7", 41233));
|
||||
MqttEndpoint endpoint = mock(MqttEndpoint.class);
|
||||
when(endpoint.clientIdentifier()).thenReturn(clientId);
|
||||
when(endpoint.remoteAddress()).thenReturn(bridge);
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
/** A connected client with a one-second keep-alive. */
|
||||
private MqttEndpoint keepAliveEndpoint(String clientId) {
|
||||
MqttEndpoint endpoint = mock(MqttEndpoint.class);
|
||||
|
||||
+3
-2
@@ -3,6 +3,7 @@ package io.floci.aws.services.iot;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.testing.IotMqttTlsProfile;
|
||||
import io.floci.aws.testing.IotWebSocketSigV4;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -405,11 +406,11 @@ class IotMqttWebSocketContractIntegrationTest {
|
||||
// ==================== helpers ====================
|
||||
|
||||
private String ws() {
|
||||
return "ws://127.0.0.1:" + testHttpPort + "/mqtt";
|
||||
return "ws://127.0.0.1:" + testHttpPort + "/mqtt" + IotWebSocketSigV4.QUERY;
|
||||
}
|
||||
|
||||
private String wss() {
|
||||
return "wss://127.0.0.1:" + testSslPort + "/mqtt";
|
||||
return "wss://127.0.0.1:" + testSslPort + "/mqtt" + IotWebSocketSigV4.QUERY;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.iot;
|
||||
|
||||
import io.floci.aws.testing.IotMqttTlsProfile;
|
||||
import io.floci.aws.testing.IotWebSocketSigV4;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -136,7 +137,7 @@ class IotMqttWebSocketFramingIntegrationTest {
|
||||
}
|
||||
|
||||
private String ws() {
|
||||
return "ws://127.0.0.1:" + testHttpPort + "/mqtt";
|
||||
return "ws://127.0.0.1:" + testHttpPort + "/mqtt" + IotWebSocketSigV4.QUERY;
|
||||
}
|
||||
|
||||
/** MQTT 3.1.1 CONNECT, clean session, keep alive 60, no will, no credentials. */
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.iot;
|
||||
|
||||
import io.floci.aws.testing.IotMqttTlsProfile;
|
||||
import io.floci.aws.testing.IotWebSocketSigV4;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -60,6 +61,7 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
private static final int PLAIN_PORT = IotMqttTlsProfile.PLAIN_PORT;
|
||||
private static final short CLOSE_UNSUPPORTED_DATA = 1003;
|
||||
private static final int CHURN_THREADS = 10;
|
||||
private static final String SIGNED_MQTT = "/mqtt" + IotWebSocketSigV4.QUERY;
|
||||
|
||||
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
|
||||
int testSslPort;
|
||||
@@ -75,9 +77,9 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
String topic = "ws/roundtrip/" + System.nanoTime();
|
||||
byte[] payload = "over websocket".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
try (WsClient subscriber = WsClient.connect(wss("/mqtt"), "ws-sub-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient subscriber = WsClient.connect(wss(SIGNED_MQTT), "ws-sub-" + System.nanoTime(), null, null)) {
|
||||
subscriber.subscribe(topic);
|
||||
try (WsClient publisher = WsClient.connect(wss("/mqtt"), "ws-pub-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient publisher = WsClient.connect(wss(SIGNED_MQTT), "ws-pub-" + System.nanoTime(), null, null)) {
|
||||
publisher.publish(topic, payload, 1);
|
||||
}
|
||||
assertArrayEquals(payload, subscriber.takePayload());
|
||||
@@ -89,7 +91,7 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
String topic = "ws/plain/" + System.nanoTime();
|
||||
byte[] payload = "plain websocket".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
try (WsClient client = WsClient.connect(ws("/mqtt"), "ws-plain-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient client = WsClient.connect(ws(SIGNED_MQTT), "ws-plain-" + System.nanoTime(), null, null)) {
|
||||
assertTrue(client.isConnected());
|
||||
client.subscribe(topic);
|
||||
client.publish(topic, payload, 0);
|
||||
@@ -102,7 +104,7 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
String topic = "ws/shared/" + System.nanoTime();
|
||||
byte[] payload = "from tcp".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
try (WsClient subscriber = WsClient.connect(wss("/mqtt"), "ws-shared-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient subscriber = WsClient.connect(wss(SIGNED_MQTT), "ws-shared-" + System.nanoTime(), null, null)) {
|
||||
subscriber.subscribe(topic);
|
||||
MqttClient tcp = new MqttClient("tcp://127.0.0.1:" + PLAIN_PORT, "tcp-pub-" + System.nanoTime(), new MemoryPersistence());
|
||||
tcp.connect();
|
||||
@@ -122,13 +124,16 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
assertEquals(MqttException.REASON_CODE_CONNECTION_LOST, refused.getReasonCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsignedConnectNamingNoAuthorizerIsRefused() {
|
||||
MqttException refused = assertThrows(MqttException.class,
|
||||
() -> WsClient.connect(wss("/mqtt"), "ws-unsigned-" + System.nanoTime(), null, null));
|
||||
assertEquals(MqttException.REASON_CODE_CONNECTION_LOST, refused.getReasonCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sigV4QueryStringOnTheMqttPathIsAccepted() throws Exception {
|
||||
String query = "?X-Amz-Algorithm=AWS4-HMAC-SHA256"
|
||||
+ "&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20260906%2Fus-east-1%2Fiotdevicegateway%2Faws4_request"
|
||||
+ "&X-Amz-Date=20260906T120000Z&X-Amz-SignedHeaders=host"
|
||||
+ "&X-Amz-Signature=0000000000000000000000000000000000000000000000000000000000000000";
|
||||
try (WsClient client = WsClient.connect(wss("/mqtt" + query), "ws-sigv4-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient client = WsClient.connect(wss(SIGNED_MQTT), "ws-sigv4-" + System.nanoTime(), null, null)) {
|
||||
assertTrue(client.isConnected());
|
||||
}
|
||||
}
|
||||
@@ -152,7 +157,7 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
CompletableFuture<Integer> closeCode = new CompletableFuture<>();
|
||||
WebSocket socket = HttpClient.newHttpClient().newWebSocketBuilder()
|
||||
.subprotocols("mqtt")
|
||||
.buildAsync(URI.create(ws("/mqtt")), new WebSocket.Listener() {
|
||||
.buildAsync(URI.create(ws(SIGNED_MQTT)), new WebSocket.Listener() {
|
||||
@Override
|
||||
public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
|
||||
closeCode.complete(statusCode);
|
||||
@@ -175,7 +180,7 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
@Test
|
||||
void brokerSideDisconnectDropsTheWebSocket() throws Exception {
|
||||
String clientId = "ws-dropped-" + System.nanoTime();
|
||||
try (WsClient client = WsClient.connect(ws("/mqtt"), clientId, null, null)) {
|
||||
try (WsClient client = WsClient.connect(ws(SIGNED_MQTT), clientId, null, null)) {
|
||||
assertTrue(broker.getConnection(clientId).isPresent(), "the bridged session is a broker session");
|
||||
|
||||
assertTrue(broker.disconnectClient(clientId, true));
|
||||
@@ -187,7 +192,7 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
@Test
|
||||
void clientDisconnectFreesTheBrokerSession() throws Exception {
|
||||
String clientId = "ws-leaving-" + System.nanoTime();
|
||||
WsClient client = WsClient.connect(ws("/mqtt"), clientId, null, null);
|
||||
WsClient client = WsClient.connect(ws(SIGNED_MQTT), clientId, null, null);
|
||||
assertTrue(broker.getConnection(clientId).isPresent());
|
||||
|
||||
client.close();
|
||||
@@ -205,9 +210,9 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
int count = 1000;
|
||||
byte[] filler = new byte[4096];
|
||||
|
||||
try (WsClient subscriber = WsClient.connect(wss("/mqtt"), "ws-burst-sub-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient subscriber = WsClient.connect(wss(SIGNED_MQTT), "ws-burst-sub-" + System.nanoTime(), null, null)) {
|
||||
subscriber.subscribe(topic);
|
||||
try (WsClient publisher = WsClient.connect(wss("/mqtt"), "ws-burst-pub-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient publisher = WsClient.connect(wss(SIGNED_MQTT), "ws-burst-pub-" + System.nanoTime(), null, null)) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
byte[] payload = ByteBuffer.allocate(4 + filler.length).putInt(i).put(filler).array();
|
||||
publisher.publish(topic, payload, 0);
|
||||
@@ -226,9 +231,9 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
String topic = "ws/limit/" + System.nanoTime();
|
||||
byte[] payload = randomPayload(AWS_MAX_PAYLOAD);
|
||||
|
||||
try (WsClient subscriber = WsClient.connect(wss("/mqtt"), "ws-limit-sub-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient subscriber = WsClient.connect(wss(SIGNED_MQTT), "ws-limit-sub-" + System.nanoTime(), null, null)) {
|
||||
subscriber.subscribe(topic);
|
||||
try (WsClient publisher = WsClient.connect(wss("/mqtt"), "ws-limit-pub-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient publisher = WsClient.connect(wss(SIGNED_MQTT), "ws-limit-pub-" + System.nanoTime(), null, null)) {
|
||||
publisher.publish(topic, payload, 1);
|
||||
}
|
||||
assertArrayEquals(payload, subscriber.takePayload());
|
||||
@@ -240,13 +245,13 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
String topic = "ws/over-limit/" + System.nanoTime();
|
||||
byte[] after = "after".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
try (WsClient subscriber = WsClient.connect(wss("/mqtt"), "ws-over-sub-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient subscriber = WsClient.connect(wss(SIGNED_MQTT), "ws-over-sub-" + System.nanoTime(), null, null)) {
|
||||
subscriber.subscribe(topic);
|
||||
try (WsClient publisher = WsClient.connect(wss("/mqtt"), "ws-over-pub-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient publisher = WsClient.connect(wss(SIGNED_MQTT), "ws-over-pub-" + System.nanoTime(), null, null)) {
|
||||
assertThrows(MqttException.class, () -> publisher.publish(topic, randomPayload(AWS_MAX_PAYLOAD + 1), 1));
|
||||
assertTrue(publisher.awaitConnectionLost(10, TimeUnit.SECONDS));
|
||||
}
|
||||
try (WsClient next = WsClient.connect(wss("/mqtt"), "ws-over-next-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient next = WsClient.connect(wss(SIGNED_MQTT), "ws-over-next-" + System.nanoTime(), null, null)) {
|
||||
next.publish(topic, after, 0);
|
||||
}
|
||||
assertArrayEquals(after, subscriber.takePayload(), "the oversized publish is never delivered");
|
||||
@@ -268,7 +273,7 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
Thread thread = new Thread(() -> {
|
||||
WsClient subscriber = null;
|
||||
try {
|
||||
subscriber = WsClient.connect(ws("/mqtt"), clientId, null, null);
|
||||
subscriber = WsClient.connect(ws(SIGNED_MQTT), clientId, null, null);
|
||||
subscribers.add(subscriber);
|
||||
subscriber.subscribe(topic);
|
||||
} catch (Exception e) {
|
||||
@@ -284,7 +289,7 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
assertTrue(failures.isEmpty(), "every concurrent handshake succeeds: " + failures);
|
||||
assertEquals(clients, subscribers.size());
|
||||
|
||||
try (WsClient publisher = WsClient.connect(ws("/mqtt"), "ws-fanout-pub-" + System.nanoTime(), null, null)) {
|
||||
try (WsClient publisher = WsClient.connect(ws(SIGNED_MQTT), "ws-fanout-pub-" + System.nanoTime(), null, null)) {
|
||||
publisher.publish(topic, payload, 1);
|
||||
}
|
||||
for (WsClient subscriber : subscribers) {
|
||||
@@ -324,7 +329,7 @@ public class IotMqttWebSocketIntegrationTest {
|
||||
for (int i = 0; i < 30; i++) {
|
||||
String clientId = "churn-" + i + "-" + System.nanoTime();
|
||||
clientIds.add(clientId);
|
||||
String url = i % 2 == 0 ? ws("/mqtt") : wss("/mqtt");
|
||||
String url = i % 2 == 0 ? ws(SIGNED_MQTT) : wss(SIGNED_MQTT);
|
||||
cycles.add(pool.submit(() -> {
|
||||
try (WsClient client = WsClient.connect(url, clientId, null, null)) {
|
||||
assertTrue(client.isConnected());
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package io.floci.aws.services.iot;
|
||||
|
||||
import io.floci.aws.testing.IotWebSocketSigV4;
|
||||
import io.floci.aws.testing.ServicesOffSettingsProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
@@ -145,7 +146,7 @@ class IotMqttWebSocketLazyStartIntegrationTest {
|
||||
}
|
||||
|
||||
private String ws() {
|
||||
return "ws://127.0.0.1:" + testHttpPort + "/mqtt";
|
||||
return "ws://127.0.0.1:" + testHttpPort + "/mqtt" + IotWebSocketSigV4.QUERY;
|
||||
}
|
||||
|
||||
/** The close future can resolve before the OS releases the port; wait until it refuses. */
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
public final class IotWebSocketSigV4 {
|
||||
|
||||
public static final String QUERY = "?X-Amz-Algorithm=AWS4-HMAC-SHA256"
|
||||
+ "&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20260906%2Fus-east-1%2Fiotdevicegateway%2Faws4_request"
|
||||
+ "&X-Amz-Date=20260906T120000Z&X-Amz-SignedHeaders=host"
|
||||
+ "&X-Amz-Signature=0000000000000000000000000000000000000000000000000000000000000000";
|
||||
|
||||
private IotWebSocketSigV4() {
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user