diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotCustomAuthorizerTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotCustomAuthorizerTest.java index 17c29bcef3..b0e3562727 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotCustomAuthorizerTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IotCustomAuthorizerTest.java @@ -2,6 +2,7 @@ package com.floci.test; import com.fasterxml.jackson.databind.ObjectMapper; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.eclipse.paho.client.mqttv3.IMqttMessageListener; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; @@ -67,7 +68,6 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; @@ -290,6 +290,12 @@ class IotCustomAuthorizerTest { big = json.loads(policy) big["Statement"][1]["Resource"] = [ARN_PREFIX + ":topic/big/%040d" % i for i in range(60)] return response([json.dumps(big)]) + if secret == "scoped": + return response([json.dumps({"Version": "2012-10-17", "Statement": [ + {"Effect": "Allow", "Action": "iot:Connect", "Resource": ARN_PREFIX + ":client/" + NAME_PREFIX + "-other"}, + {"Effect": "Allow", "Action": "iot:Subscribe", "Resource": ARN_PREFIX + ":topicfilter/" + NAME_PREFIX + "/*"}, + {"Effect": "Allow", "Action": ["iot:Publish", "iot:Receive"], + "Resource": ARN_PREFIX + ":topic/" + NAME_PREFIX + "/scoped/*"}]})]) if secret == "objpolicy": return response([json.loads(policy)]) return {"isAuthenticated": False} @@ -656,6 +662,53 @@ class IotCustomAuthorizerTest { } } + @ParameterizedTest(name = "{0}") + @EnumSource(Mqtt.class) + @DisplayName("a SUBSCRIBE outside the returned policies is refused") + void mqttSubscribeOutsideTheReturnedPolicyIsRefused(Mqtt version) throws Exception { + String filter = prefix + "-outside/" + version.name().toLowerCase() + "/#"; + try (Session scoped = open(version, scopedTarget())) { + if (version == Mqtt.V3_1_1) { + assertThat(catchThrowable(() -> scoped.subscribe(filter))).isInstanceOf(MqttException.class); + } else { + assertThat(scoped.subscribe(filter)).isEqualTo(MQTT5_NOT_AUTHORIZED); + } + } + } + + @ParameterizedTest(name = "{0}") + @EnumSource(Mqtt.class) + @DisplayName("a PUBLISH outside the returned policies is refused and not delivered") + void mqttPublishOutsideTheReturnedPolicyIsRefused(Mqtt version) throws Exception { + String topic = prefix + "/published/" + version.name().toLowerCase(); + try (Session observer = open(version, target(namedUsername(authorizer), "allow-me")); + Session scoped = open(version, scopedTarget())) { + observer.subscribe(topic); + if (version == Mqtt.V3_1_1) { + assertThat(catchThrowable(() -> scoped.publish(topic, "denied"))).isInstanceOf(MqttException.class); + } else { + assertThat(scoped.publish(topic, "denied")).isEqualTo(MQTT5_NOT_AUTHORIZED); + } + observer.publish(topic, "marker"); + assertThat(observer.nextMessage()).isEqualTo("marker"); + } + } + + @ParameterizedTest(name = "{0}") + @EnumSource(Mqtt.class) + @DisplayName("a subscriber receives only on topics the returned policies allow") + void mqttReceiveOutsideTheReturnedPolicyIsSkipped(Mqtt version) throws Exception { + String level = version.name().toLowerCase(); + try (Session scoped = open(version, scopedTarget()); + Session observer = open(version, target(namedUsername(authorizer), "allow-me"))) { + assertThat(scoped.subscribe(prefix + "/+/" + level)).isEqualTo(1); + observer.publish(prefix + "/outside/" + level, "outside"); + observer.publish(prefix + "/scoped/" + level, "inside"); + assertThat(scoped.nextMessage()).isEqualTo("inside"); + assertThat(scoped.roundTrip(prefix + "/scoped/own-" + level, "own")).isEqualTo("own"); + } + } + enum Refusal { DENY("deny", AuthorizerKind.ACTIVE, false), CLIENT_ID_NOT_IN_POLICY("allow-me", AuthorizerKind.ACTIVE, true), @@ -990,6 +1043,11 @@ class IotCustomAuthorizerTest { return new Target(mqttUri, clientId, username, secret.getBytes(StandardCharsets.UTF_8), Map.of()); } + private Target scopedTarget() { + return new Target(mqttUri, otherClientId, otherClientId + "?" + NAME_PARAM + authorizer, + "scoped".getBytes(StandardCharsets.UTF_8), Map.of()); + } + private static String sign(PrivateKey key, String token) throws GeneralSecurityException { Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(key); @@ -1032,7 +1090,17 @@ class IotCustomAuthorizerTest { Map headers) {} private interface Session extends AutoCloseable { - String roundTrip(String topic, String payload) throws Exception; + int subscribe(String topicFilter) throws Exception; + + int publish(String topic, String payload) throws Exception; + + String nextMessage() throws InterruptedException; + + default String roundTrip(String topic, String payload) throws Exception { + subscribe(topic); + publish(topic, payload); + return nextMessage(); + } @Override void close(); @@ -1115,14 +1183,25 @@ class IotCustomAuthorizerTest { closeV3(client); throw new ConnectRefused(e); } + BlockingQueue messages = new LinkedBlockingQueue<>(); return new Session() { @Override - public String roundTrip(String topic, String payload) throws Exception { - CompletableFuture received = new CompletableFuture<>(); - client.subscribe(topic, 1, (t, message) -> - received.complete(new String(message.getPayload(), StandardCharsets.UTF_8))); + public int subscribe(String topicFilter) throws Exception { + int[] granted = {1}; + client.subscribe(new String[] {topicFilter}, granted, new IMqttMessageListener[] {(t, message) -> + messages.add(new String(message.getPayload(), StandardCharsets.UTF_8))}); + return granted[0]; + } + + @Override + public int publish(String topic, String payload) throws Exception { client.publish(topic, payload.getBytes(StandardCharsets.UTF_8), 1, false); - return received.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + return 0; + } + + @Override + public String nextMessage() throws InterruptedException { + return messages.poll(TIMEOUT_SECONDS, TimeUnit.SECONDS); } @Override @@ -1187,10 +1266,21 @@ class IotCustomAuthorizerTest { } return new Session() { @Override - public String roundTrip(String topic, String payload) throws Exception { - client.subscribe(topic, 1).waitForCompletion(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); - client.publish(topic, payload.getBytes(StandardCharsets.UTF_8), 1, false) - .waitForCompletion(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + public int subscribe(String topicFilter) throws Exception { + IMqttToken token = client.subscribe(topicFilter, 1); + token.waitForCompletion(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + return token.getReasonCodes()[0]; + } + + @Override + public int publish(String topic, String payload) throws Exception { + IMqttToken token = client.publish(topic, payload.getBytes(StandardCharsets.UTF_8), 1, false); + token.waitForCompletion(TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)); + return token.getReasonCodes()[0]; + } + + @Override + public String nextMessage() throws InterruptedException { return messages.poll(TIMEOUT_SECONDS, TimeUnit.SECONDS); } diff --git a/docs/services/iot.md b/docs/services/iot.md index 981bc7ebc0..2122a8b493 100644 --- a/docs/services/iot.md +++ b/docs/services/iot.md @@ -19,7 +19,7 @@ Supported MVP 1 behavior: Current MVP 1 limitations: -- The plaintext MQTT listener on 1883 stays permissive. The TLS listener on 8883 admits a device only when its certificate is registered and `ACTIVE` and an attached policy allows `iot:Connect` for the client id, see [Device verification on 8883](#device-verification-on-8883). `Publish`, `Subscribe` and `Receive` are not evaluated yet on either port. +- The plaintext MQTT listener on 1883 stays permissive. The TLS listener on 8883 admits a device only when its certificate is registered and `ACTIVE` and an attached policy allows `iot:Connect` for the client id, see [Device verification on 8883](#device-verification-on-8883). A session admitted by its certificate or by a custom authorizer publishes, subscribes and receives only where its policies allow, see [Topic authorization](#topic-authorization); a plaintext session that names no authorizer, or a WebSocket session signed with SigV4, is not restricted. - Rules evaluate the SQL subset described under [Rule SQL](#rule-sql); substitution templates remain follow-up scope. ## MVP 2 Coverage @@ -92,12 +92,12 @@ The function is invoked synchronously with the event AWS IoT sends (`protocolDat - An MQTT `CONNECT` on the plaintext listener or on [MQTT over WebSocket](#mqtt-over-websocket) that names an authorizer, in the username (`?x-amz-customauthorizer-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:::client/`. 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` 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. +- The returned policies also decide the session's `iot:Publish`, `iot:Subscribe` and `iot:Receive`, see [Topic authorization](#topic-authorization). Current limitations: - 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. - The function's resource policy is not checked, so `AddPermission` for `iot.amazonaws.com` is not required. - A WebSocket upgrade without the `mqtt` subprotocol is not answered with AWS's 426. - A refused WebSocket client sees a close frame with status `1000`. AWS sends an empty close frame to an MQTT 3.1.1 client and closes the connection without a close frame after the MQTT 5 `CONNACK`. @@ -221,7 +221,7 @@ Broker scope: - Accept PUBLISH payloads up to 128 KB on 1883, 8883 and `/mqtt`, the AWS IoT Core quota (packets up to 146 KB including the variable header). A larger publish disconnects the client without acknowledgement, delivery or rule evaluation, as on AWS. - Forward an MQTT 5 publish's user properties to each MQTT 5 subscriber unchanged and in the order sent, a repeated name included, as AWS does. An MQTT 3.1.1 subscriber gets the message without them. The publish's other MQTT 5 properties, and those of a retained message, are not forwarded. - Serve MQTT over TLS on 8883 next to plaintext 1883 when TLS is enabled, and verify the device certificate and its `iot:Connect` permission there. -- Keep the plaintext listener permissive except for a `CONNECT` that names a [custom authorizer](#authorizers); topic-level authorization (`Publish`, `Subscribe`, `Receive`) is follow-up scope. +- Keep the plaintext listener permissive except for a `CONNECT` that names a [custom authorizer](#authorizers), and authorize the topics of every session a certificate or a custom authorizer admitted, see [Topic authorization](#topic-authorization). - Keep MQTT broker logging minimal. - Validate the relevant IoT compatibility tests against the native binary before considering the phase complete. @@ -237,7 +237,7 @@ curl http://localhost:4566/_floci/ca.pem -o ca.pem aws --endpoint-url http://localhost:4566 iot create-keys-and-certificate --set-as-active \ --certificate-pem-outfile device.crt --private-key-outfile device.key --query certificateArn --output text aws --endpoint-url http://localhost:4566 iot create-policy --policy-name connect \ - --policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"iot:Connect","Resource":"arn:aws:iot:*:*:client/*"}]}' + --policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["iot:Connect","iot:Subscribe","iot:Receive"],"Resource":"*"}]}' aws --endpoint-url http://localhost:4566 iot attach-policy --policy-name connect --target mosquitto_sub -h localhost -p 8883 --cafile ca.pem --cert device.crt --key device.key -t 'devices/#' ``` @@ -252,7 +252,28 @@ The connection is admitted when all of these hold, otherwise the broker answers The connection carries these condition keys: `iot:ClientId`, `aws:SourceIp`, `iot:DomainName` (the server name the client sent in the TLS handshake, absent when it dialled an IP address), `iot:Connection.Thing.IsAttached` and, only when the client id names a thing attached to the certificate with `AttachThingPrincipal`, `iot:Connection.Thing.ThingName`, `iot:Connection.Thing.ThingTypeName` and `iot:Connection.Thing.Attributes[name]`. They are also what the policy's own `${...}` resolves against, in the `Resource` and `Condition` elements and nowhere else, read by the same resolver as an IAM policy's variables: key names are case-insensitive, `${*}`, `${?}` and `${$}` stand for those three characters, and a variable with no value, the certificate variables `iot:Certificate.*` among them, leaves a `Resource` pattern matching no resource and a `Condition` value null. A document that does not declare `"Version": "2012-10-17"` has no variables at all, `${iot:ClientId}` there being the literal text it looks like. -Differences from AWS: AWS rejects an unregistered, inactive or expired certificate during the TLS handshake and closes an MQTT 3.1.1 connection it does not authorize without a `CONNACK`; Floci completes the handshake and always answers with the return code, so the reason is visible to the client. Deactivating the certificate or detaching the policy takes effect on the next connect; established sessions are not dropped. Policies attached to thing groups are not consulted, and exclusive thing attachment (`thingPrincipalType`) is not modelled: the thing is always the one named by the client id. +Differences from AWS: AWS rejects an unregistered, inactive or expired certificate during the TLS handshake and closes an MQTT 3.1.1 connection it does not authorize without a `CONNACK`; Floci completes the handshake and always answers with the return code, so the reason is visible to the client. Deactivating the certificate takes effect on the next connect, and so does a policy change for the `iot:Connect` decision; established sessions are not dropped for either. Attaching, detaching or changing a policy does apply to an established session's next publish, subscribe and delivery, see [Topic authorization](#topic-authorization). Policies attached to thing groups are not consulted, and exclusive thing attachment (`thingPrincipalType`) is not modelled: the thing is always the one named by the client id. + +#### Topic authorization + +A session admitted on 8883 by its certificate, or on 1883 or `/mqtt` by a custom authorizer (the +default authorizer for unsigned MQTT over WebSocket), is authorized per packet against the policies attached to its certificate at that moment, or against +the policies the authorizer returned at connect. The resources are +`arn:aws:iot:::topicfilter/` for `iot:Subscribe` and +`arn:aws:iot:::topic/` for `iot:Publish` and `iot:Receive`, reserved +`$aws/` topics included, and the condition keys and policy variables are those of the connect, so +`${iot:Connection.Thing.ThingName}` and `${iot:ClientId}` scope a device to its own topics. + +| Denied | MQTT 3.1.1 | MQTT 5 | +|---|---|---| +| `SUBSCRIBE` | Connection closed, no `SUBACK` | `SUBACK` reason code `0x87` for that filter, session kept | +| `PUBLISH` QoS 1 | Connection closed, no `PUBACK` | `PUBACK` reason code `0x87`, session kept | +| `PUBLISH` QoS 0 | Connection closed | `DISCONNECT` reason code `0x87` | +| `Receive` | The message, retained ones and those stored for a resumed persistent session included, is not delivered to that subscriber | Same | + +A denied publish is neither recorded, nor evaluated by topic rules, nor delivered. A connection the +broker closes for a denial ends with the lifecycle `disconnectReason` `AUTH_ERROR`. A plaintext session +that names no authorizer, or a WebSocket session signed with SigV4, is not restricted. `iot:RetainPublish` is not evaluated. ### Endpoint address @@ -382,7 +403,7 @@ Implementation notes: Current accepted limitation: -- Certificate and `iot:Connect` checks are enforced on 8883 only; topic-level authorization is not enforced on either port yet. +- Certificate checks are enforced on 8883 only; custom authorizers, the default one included, decide `iot:Connect` on 1883 and `/mqtt`. Topic-level authorization applies to sessions a certificate or an authorizer admitted, see [Topic authorization](#topic-authorization). - QoS 2 and advanced MQTT 5 property semantics remain follow-up scope. - At most 1,000 MQTT publishes are pending rule evaluation, running or waiting. While that many are pending, further publishes are still delivered to subscribers but their topic rules are skipped, with one warning logged until the backlog drains. - REST shadow errors are not published to `rejected`. diff --git a/src/main/java/io/floci/aws/services/iot/IotMqttBrokerService.java b/src/main/java/io/floci/aws/services/iot/IotMqttBrokerService.java index 81c55d9637..74c7944fc2 100644 --- a/src/main/java/io/floci/aws/services/iot/IotMqttBrokerService.java +++ b/src/main/java/io/floci/aws/services/iot/IotMqttBrokerService.java @@ -30,6 +30,9 @@ import io.vertx.mqtt.MqttTopicSubscription; import io.vertx.mqtt.messages.MqttPublishMessage; import io.vertx.mqtt.messages.MqttSubscribeMessage; import io.vertx.mqtt.messages.MqttUnsubscribeMessage; +import io.vertx.mqtt.messages.codes.MqttDisconnectReasonCode; +import io.vertx.mqtt.messages.codes.MqttPubAckReasonCode; +import io.vertx.mqtt.messages.codes.MqttSubAckReasonCode; import jakarta.annotation.Priority; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Observes; @@ -131,6 +134,7 @@ public class IotMqttBrokerService implements Resettable { static final String DUPLICATE_CLIENTID = "DUPLICATE_CLIENTID"; static final String API_INITIATED_DISCONNECT = "API_INITIATED_DISCONNECT"; private static final String CLIENT_ERROR = "CLIENT_ERROR"; + private static final String AUTH_ERROR = "AUTH_ERROR"; private static final long KEEP_ALIVE_SLACK_NANOS = TimeUnit.MILLISECONDS.toNanos(250); private static final long RULES_RESETTING = 1; @@ -475,6 +479,7 @@ public class IotMqttBrokerService implements Resettable { String sourceIp = remoteAddress == null ? null : remoteAddress.host(); int sourcePort = remoteAddress == null ? -1 : remoteAddress.port(); IotService.RegisteredDevice device = null; + IotService.ConnectionPolicies policies = null; if (verifyDevice) { device = admittedDevice(endpoint, clientId, sourceIp); if (device == null) { @@ -483,6 +488,7 @@ public class IotMqttBrokerService implements Resettable { : MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED); return; } + policies = iotService.get().devicePolicies(device, clientId, sourceIp, requestedServerName(endpoint.sslSession())); } else { IotCustomAuthorizer.WebSocketUpgrade upgrade = remoteAddress == null ? null : webSocketUpgrades.remove(remoteAddress); if (upgrade != null && upgrade.sourceIp() != null) { @@ -496,15 +502,16 @@ public class IotMqttBrokerService implements Resettable { return; } } - admit(endpoint, device, sourceIp, sourcePort, connectNanos); + admit(endpoint, device, policies, sourceIp, sourcePort, connectNanos); } /** * 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. + * set it is refused. Those policies then decide the session's publish, subscribe and receive. + * 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) { @@ -516,13 +523,14 @@ public class IotMqttBrokerService implements Resettable { endpoint.closeHandler(ignored -> closed.set(true)); vertx.executeBlocking(() -> { List policies = customAuthorizer.connectPolicies(authorizerName, clientId, username, password, upgrade); - return iotService.get().isConnectAllowedBy(policies, clientId, sourceIp, serverName); + return iotService.get().isConnectAllowedBy(policies, clientId, sourceIp, serverName) ? policies : null; }, false).onComplete(decision -> { if (closed.get()) { return; } - if (decision.succeeded() && decision.result()) { - admit(endpoint, null, sourceIp, sourcePort, connectNanos); + if (decision.succeeded() && decision.result() != null) { + admit(endpoint, null, iotService.get().authorizerPolicies(decision.result(), clientId, sourceIp, serverName), + sourceIp, sourcePort, connectNanos); return; } LOG.debugv("IoT MQTT client {0} refused by custom authorizer {1}: {2}", clientId, @@ -532,26 +540,33 @@ public class IotMqttBrokerService implements Resettable { endpoint.close(); return; } - MqttProperties properties = new MqttProperties(); - properties.add(new MqttProperties.StringProperty(MqttProperties.MqttPropertyType.REASON_STRING.value(), - "CONNACK:Client is not authenticated/authorized to send the message:" + UUID.randomUUID())); - endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED_5, properties); + endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED_5, notAuthorizedReason("CONNACK")); }); } + private static MqttProperties notAuthorizedReason(String packet) { + MqttProperties properties = new MqttProperties(); + properties.add(new MqttProperties.StringProperty(MqttProperties.MqttPropertyType.REASON_STRING.value(), + packet + ":Client is not authenticated/authorized to send the message:" + UUID.randomUUID())); + return properties; + } + /** * {@code device} is the registered device a TLS client was admitted as, null otherwise; its * certificate id is the session's principal, and its account and region the session's. - * {@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 + * {@code policies} decide the session's publish, subscribe and receive, null for a session that + * went through no authorizer on the plaintext listener or the WebSocket bridge, which is + * unrestricted. {@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. A CONNECT without a clean session resumes the client id's * persistent session created in the same account and region over the same MQTT version: the - * CONNACK reports it present and its stored messages follow; any other CONNECT from that - * account and region discards it, and one from elsewhere leaves it stored. + * CONNACK reports it present and its stored messages follow, each only if the new session's + * policies allow {@code iot:Receive} on its topic; any other CONNECT from that account and + * region discards it, and one from elsewhere leaves it stored. */ - private void admit(MqttEndpoint endpoint, IotService.RegisteredDevice device, String clientIp, int clientPort, - long connectNanos) { + private void admit(MqttEndpoint endpoint, IotService.RegisteredDevice device, IotService.ConnectionPolicies policies, + String clientIp, int clientPort, long connectNanos) { String clientId = endpoint.clientIdentifier(); boolean cleanSession = endpoint.isCleanSession(); int protocolVersion = endpoint.protocolVersion(); @@ -582,7 +597,8 @@ public class IotMqttBrokerService implements Resettable { device == null ? config.defaultRegion() : device.region(), System.currentTimeMillis(), endpoint.keepAliveTimeSeconds(), - new AtomicInteger()); + new AtomicInteger(), + policies); ClientSession previous = sessionsByClient.put(clientId, session); boolean takeover = previous != null && previous.endpoint() != endpoint; StoredSession stored = storedSessions.get(session.historyKey()); @@ -638,6 +654,9 @@ public class IotMqttBrokerService implements Resettable { } } for (QueuedMessage message : resumed) { + if (!isAllowed(session, "iot:Receive", "topic/" + message.topic())) { + continue; + } endpoint.publish(message.topic(), Buffer.buffer(message.payload()), MqttQoS.AT_LEAST_ONCE, false, false, session.packetId(MqttQoS.AT_LEAST_ONCE), message.properties()); } @@ -731,20 +750,29 @@ public class IotMqttBrokerService implements Resettable { private void handleSubscribe(ClientSession session, MqttSubscribeMessage message) { received(session); - List grantedQos = new ArrayList<>(); + List reasonCodes = new ArrayList<>(); List accepted = new ArrayList<>(); for (MqttTopicSubscription requested : message.topicSubscriptions()) { String topicFilter = requested.topicName(); MqttQoS qos = requested.qualityOfService(); if (!isValidTopicFilter(topicFilter) || qos == MqttQoS.EXACTLY_ONCE) { - grantedQos.add(MqttQoS.FAILURE); + reasonCodes.add(MqttSubAckReasonCode.qosGranted(MqttQoS.FAILURE)); + continue; + } + if (!isAllowed(session, "iot:Subscribe", "topicfilter/" + topicFilter)) { + if (session.endpoint().protocolVersion() != 5) { + endSession(session, AUTH_ERROR); + session.endpoint().close(); + return; + } + reasonCodes.add(MqttSubAckReasonCode.NOT_AUTHORIZED); continue; } int granted = qos == MqttQoS.AT_LEAST_ONCE ? 1 : 0; accepted.add(new Subscription(topicFilter, granted)); - grantedQos.add(granted == 1 ? MqttQoS.AT_LEAST_ONCE : MqttQoS.AT_MOST_ONCE); + reasonCodes.add(MqttSubAckReasonCode.qosGranted(MqttQoS.valueOf(granted))); } synchronized (sessionLock) { // An ended session no longer owns its client id's subscriptions; a newer connection may. @@ -758,7 +786,7 @@ public class IotMqttBrokerService implements Resettable { } } - session.endpoint().subscribeAcknowledge(message.messageId(), grantedQos); + session.endpoint().subscribeAcknowledge(message.messageId(), reasonCodes, MqttProperties.NO_PROPERTIES); deliverRetained(session, accepted); } @@ -796,11 +824,15 @@ public class IotMqttBrokerService implements Resettable { session.endpoint().close(); return; } + String topic = message.topicName(); + if (!isAllowed(session, "iot:Publish", "topic/" + topic)) { + refusePublish(session, message); + return; + } if (message.qosLevel() == MqttQoS.AT_LEAST_ONCE) { session.endpoint().publishAcknowledge(message.messageId()); } - String topic = message.topicName(); if (topic.startsWith("$aws/")) { iotService.get().handleReservedMqttPublish(topic, payload, rules -> evaluateRulesOnWorker(topic, rules)); return; @@ -811,6 +843,23 @@ public class IotMqttBrokerService implements Resettable { fanOut(topic, payload, message.qosLevel().value(), userProperties(message.properties())); } + private void refusePublish(ClientSession session, MqttPublishMessage message) { + if (session.endpoint().protocolVersion() == 5 && message.qosLevel() == MqttQoS.AT_LEAST_ONCE) { + session.endpoint().publishAcknowledge(message.messageId(), MqttPubAckReasonCode.NOT_AUTHORIZED, MqttProperties.NO_PROPERTIES); + return; + } + endSession(session, AUTH_ERROR); + if (session.endpoint().protocolVersion() == 5) { + session.endpoint().disconnect(MqttDisconnectReasonCode.NOT_AUTHORIZED, notAuthorizedReason("DISCONNECT")); + return; + } + session.endpoint().close(); + } + + private boolean isAllowed(ClientSession session, String action, String resource) { + return session.policies() == null || iotService.get().isAllowed(session.policies(), action, resource); + } + /** A publish's user properties in the order sent, which AWS IoT forwards unchanged to an MQTT 5 subscriber. */ private static MqttProperties userProperties(MqttProperties received) { MqttProperties forwarded = new MqttProperties(); @@ -874,10 +923,12 @@ public class IotMqttBrokerService implements Resettable { } /** - * Delivers a live copy, RETAIN 0 as on AWS, to each subscriber with a matching subscription, at the - * lower of {@code qos} and the highest QoS among its matching subscriptions. Netty encodes + * Delivers a live copy, RETAIN 0 as on AWS, to each subscriber with a matching subscription, + * unless the subscriber's policies deny {@code iot:Receive} on {@code topic}, at the lower of + * {@code qos} and the highest QoS among its matching subscriptions. Netty encodes * {@code properties} only for an MQTT 5 subscriber. A QoS 1 publish matching a QoS 1 - * subscription of a disconnected persistent session is stored for it instead. + * subscription of a disconnected persistent session is stored for it instead, and its + * {@code iot:Receive} is checked when it is delivered on the reconnect. */ private void fanOut(String topic, byte[] payload, int qos, MqttProperties properties) { byte[] safePayload = payload == null ? new byte[0] : payload.clone(); @@ -896,7 +947,7 @@ public class IotMqttBrokerService implements Resettable { for (ClientSession session : sessionsByClient.values()) { Map subscriptions = subscriptionsByClient.get(session.clientId()); int granted = subscriptions == null ? -1 : grantedQos(subscriptions.values(), topic); - if (!session.endpoint().isConnected() || granted < 0) { + if (!session.endpoint().isConnected() || granted < 0 || !isAllowed(session, "iot:Receive", "topic/" + topic)) { continue; } MqttQoS delivered = MqttQoS.valueOf(Math.min(qos, granted)); @@ -928,7 +979,7 @@ public class IotMqttBrokerService implements Resettable { continue; } int granted = grantedQos(subscriptions, retained.getTopic()); - if (granted < 0) { + if (granted < 0 || !isAllowed(session, "iot:Receive", "topic/" + retained.getTopic())) { continue; } byte[] payload = Base64.getDecoder().decode(retained.getPayload()); @@ -1107,7 +1158,8 @@ public class IotMqttBrokerService implements Resettable { String region, long connectedAt, int keepAliveDuration, - AtomicInteger packetIds) { + AtomicInteger packetIds, + IotService.ConnectionPolicies policies) { /** * The packet identifier of a copy sent at {@code qos}: none at QoS 0, otherwise the session's diff --git a/src/main/java/io/floci/aws/services/iot/IotService.java b/src/main/java/io/floci/aws/services/iot/IotService.java index db7f6bc09a..b292164244 100644 --- a/src/main/java/io/floci/aws/services/iot/IotService.java +++ b/src/main/java/io/floci/aws/services/iot/IotService.java @@ -77,6 +77,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.function.Consumer; import java.util.function.Predicate; +import java.util.function.Supplier; import java.util.regex.Pattern; import static io.floci.aws.core.storage.AccountAwareStorageBackend.getInAccount; @@ -519,6 +520,9 @@ public class IotService { public record RegisteredDevice(String accountId, String region, IotCertificate certificate) { } + public record ConnectionPolicies(Supplier> documents, Map variables, String region, String accountId) { + } + private record CertificateLocation(String accountId, String key) { } @@ -586,9 +590,7 @@ public class IotService { if (clientId == null || clientId.isBlank() || !"ACTIVE".equals(certificate.getStatus()) || !isWithinValidity(certificate)) { return false; } - List documents = attachedPolicyDocuments(certificate.getCertificateArn(), device.region(), device.accountId()); - return isConnectAllowed(documents, connectionVariables(device, clientId, sourceIp, domainName), - device.region(), device.accountId(), clientId); + return isAllowed(devicePolicies(device, clientId, sourceIp, domainName), "iot:Connect", "client/" + clientId); } /** @@ -597,29 +599,46 @@ public class IotService { * variables do not resolve. */ public boolean isConnectAllowedBy(List documents, String clientId, String sourceIp, String domainName) { - // ponytail: the broker has no request context, so a custom-auth client connects to the default account and region. - return isConnectAllowed(documents, basicConnectionVariables(clientId, sourceIp, domainName), - regionResolver.getDefaultRegion(), regionResolver.getDefaultAccountId(), clientId); + return isAllowed(authorizerPolicies(documents, clientId, sourceIp, domainName), "iot:Connect", "client/" + clientId); } /** - * Decides {@code iot:Connect} for the client ARN against the documents as they are written, - * with the connection's variables offered as condition keys. The {@code ${...}} placeholders - * are the evaluator's to resolve, from that same context, because the developer guide gives - * IoT no policy language of its own: its policies "follow the same conventions as IAM - * policies" and "the same policy evaluation logic", and a variable is one "that can be used - * in AWS IoT Core policies in the Resource or Condition block", which is where that resolver - * substitutes and the only place AWS says a variable has meaning. + * The policies of a device's certificate, re-read on every check, so an attach, a detach or a + * new default version applies to a session that is already open. */ - private boolean isConnectAllowed(List documents, Map variables, String region, String accountId, - String clientId) { + public ConnectionPolicies devicePolicies(RegisteredDevice device, String clientId, String sourceIp, String domainName) { + return new ConnectionPolicies(() -> attachedPolicyDocuments(device.certificate().getCertificateArn(), device.region(), device.accountId()), + connectionVariables(device, clientId, sourceIp, domainName), device.region(), device.accountId()); + } + + /** The policies a custom authorizer returned, fixed for the session at connect. */ + public ConnectionPolicies authorizerPolicies(List documents, String clientId, String sourceIp, String domainName) { + // ponytail: the broker has no request context, so a custom-auth client connects to the default account and region. + return new ConnectionPolicies(() -> documents, basicConnectionVariables(clientId, sourceIp, domainName), + regionResolver.getDefaultRegion(), regionResolver.getDefaultAccountId()); + } + + /** + * Decides {@code action} on the IoT ARN of {@code resource} in the policies' account and region: + * {@code iot:Connect} on {@code client/}, {@code iot:Publish} and {@code iot:Receive} on + * {@code topic/}, {@code iot:Subscribe} on {@code topicfilter/}. The documents are + * evaluated as they are written, with the connection's variables offered as condition keys. The + * {@code ${...}} placeholders are the evaluator's to resolve, from that same context, because the + * developer guide gives IoT no policy language of its own: its policies "follow the same + * conventions as IAM policies" and "the same policy evaluation logic", and a variable is one + * "that can be used in AWS IoT Core policies in the Resource or Condition block", which is where + * that resolver substitutes and the only place AWS says a variable has meaning. No policy means + * deny; an explicit deny wins. + */ + public boolean isAllowed(ConnectionPolicies policies, String action, String resource) { + List documents = policies.documents().get(); if (documents.isEmpty()) { return false; } Map> conditionContext = new LinkedHashMap<>(); - variables.forEach((key, value) -> conditionContext.put(key, List.of(value))); - String clientArn = AwsArnUtils.Arn.of("iot", region, accountId, "client/" + clientId).toString(); - return policyEvaluator.evaluate(CallerContext.of(documents), null, "iot:Connect", clientArn, conditionContext) + policies.variables().forEach((key, value) -> conditionContext.put(key, List.of(value))); + String arn = AwsArnUtils.Arn.of("iot", policies.region(), policies.accountId(), resource).toString(); + return policyEvaluator.evaluate(CallerContext.of(documents), null, action, arn, conditionContext) == IamPolicyEvaluator.Decision.ALLOW; } diff --git a/src/test/java/io/floci/aws/services/iot/IotCustomAuthorizerIntegrationTest.java b/src/test/java/io/floci/aws/services/iot/IotCustomAuthorizerIntegrationTest.java index 3b4e5e7c8d..593121ec96 100644 --- a/src/test/java/io/floci/aws/services/iot/IotCustomAuthorizerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iot/IotCustomAuthorizerIntegrationTest.java @@ -289,6 +289,47 @@ class IotCustomAuthorizerIntegrationTest { assertEquals(base64("deny"), takeEvent().path("protocolData").path("mqtt").path("password").asText()); } + @Test + void aWebSocketClientReceivesOnlyTheTopicsTheAuthorizerPoliciesAllow() throws Exception { + String clientId = "cauth-receive-" + System.nanoTime(); + String prefix = "cauth/" + System.nanoTime(); + answerWithTopicPolicy(clientId, prefix); + MqttClient subscriber = connectV3(ws(""), clientId, clientId + "?" + NAME_PARAM + authorizer, "allow", Map.of()); + MqttClient publisher = new MqttClient(tcp(), "cauth-publisher-" + System.nanoTime(), new MemoryPersistence()); + publisher.connect(); + try { + BlockingQueue received = new LinkedBlockingQueue<>(); + subscriber.subscribe(prefix + "/#", 1, (topic, message) -> received.add(topic)); + + publisher.publish(prefix + "/someone-else/events", "x".getBytes(StandardCharsets.UTF_8), 1, false); + publisher.publish(prefix + "/" + clientId + "/events", "x".getBytes(StandardCharsets.UTF_8), 1, false); + + assertEquals(prefix + "/" + clientId + "/events", received.poll(10, TimeUnit.SECONDS)); + } finally { + publisher.disconnect(); + publisher.close(); + subscriber.disconnect(); + subscriber.close(); + } + } + + @Test + void mqtt3PublishOutsideTheAuthorizerPoliciesClosesTheWebSocketConnection() throws Exception { + String clientId = "cauth-publish-" + System.nanoTime(); + String prefix = "cauth/" + System.nanoTime(); + answerWithTopicPolicy(clientId, prefix); + MqttClient client = connectV3(ws(""), clientId, clientId + "?" + NAME_PARAM + authorizer, "allow", Map.of()); + try { + client.publish(prefix + "/" + clientId + "/events", "x".getBytes(StandardCharsets.UTF_8), 1, false); + + assertThrows(MqttException.class, + () -> client.publish(prefix + "/someone-else/events", "x".getBytes(StandardCharsets.UTF_8), 1, false)); + assertFalse(client.isConnected()); + } finally { + client.close(); + } + } + @Test void mqtt3UnsignedConnectNamingNoAuthorizerWithoutADefaultIsRefused() { String clientId = "cauth-v3-none-" + System.nanoTime(); @@ -416,9 +457,23 @@ class IotCustomAuthorizerIntegrationTest { return protocols; } + private void answerWithTopicPolicy(String clientId, String prefix) { + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[" + + "{\"Effect\":\"Allow\",\"Action\":\"iot:Connect\",\"Resource\":\"arn:aws:iot:us-east-1:000000000000:client/" + clientId + "\"}," + + "{\"Effect\":\"Allow\",\"Action\":\"iot:Subscribe\",\"Resource\":\"arn:aws:iot:us-east-1:000000000000:topicfilter/" + prefix + "/*\"}," + + "{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Receive\"]," + + "\"Resource\":\"arn:aws:iot:us-east-1:000000000000:topic/" + prefix + "/${iot:ClientId}/*\"}]}"; + when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse))) + .thenReturn(new InvokeResult(200, null, allowWith(policy).getBytes(StandardCharsets.UTF_8), null, "id")); + } + private static String allow(String clientId) { + return allowWith(policy(clientId)); + } + + private static String allowWith(String policyDocument) { return "{\"isAuthenticated\": true, \"principalId\": \"itprincipal\", \"policyDocuments\": [" - + MAPPER.valueToTree(policy(clientId)) + "]}"; + + MAPPER.valueToTree(policyDocument) + "]}"; } private static String policy(String clientId) { diff --git a/src/test/java/io/floci/aws/services/iot/IotDeviceIdentity.java b/src/test/java/io/floci/aws/services/iot/IotDeviceIdentity.java index 58d92eaa8a..266b9d8f33 100644 --- a/src/test/java/io/floci/aws/services/iot/IotDeviceIdentity.java +++ b/src/test/java/io/floci/aws/services/iot/IotDeviceIdentity.java @@ -80,6 +80,18 @@ final class IotDeviceIdentity { return policy; } + /** + * Creates thing {@code thingName} and attaches this device's certificate to it as a principal; + * {@code cleanup} detaches and deletes it after the test. + */ + void attachNewThing(String thingName, PartitionCleanup cleanup) { + given().contentType("application/json").body("{}").when().post("/things/" + thingName).then().statusCode(200); + cleanup.register(() -> given().when().delete("/things/" + thingName).then().statusCode(200)); + given().header("x-amzn-principal", certificateArn).when().put("/things/" + thingName + "/principals").then().statusCode(200); + cleanup.register(() -> given().header("x-amzn-principal", certificateArn) + .when().delete("/things/" + thingName + "/principals").then().statusCode(200)); + } + /** IoT Core deletes only an inactive certificate with nothing attached. */ private void delete() { given().queryParam("newStatus", "INACTIVE").when().put("/certificates/" + certificateId).then().statusCode(200); diff --git a/src/test/java/io/floci/aws/services/iot/IotMqttMutualTlsIntegrationTest.java b/src/test/java/io/floci/aws/services/iot/IotMqttMutualTlsIntegrationTest.java index 91c9acf766..9b7f0cff4a 100644 --- a/src/test/java/io/floci/aws/services/iot/IotMqttMutualTlsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iot/IotMqttMutualTlsIntegrationTest.java @@ -181,11 +181,7 @@ class IotMqttMutualTlsIntegrationTest { void thingPolicyVariableAdmitsOnlyTheAttachedThingName() throws Exception { IotDeviceIdentity device = provisionWithPolicy(true, CONNECT_AS_ATTACHED_THING); String thingName = "thing" + System.nanoTime(); - given().contentType("application/json").body("{}").when().post("/things/" + thingName).then().statusCode(200); - cleanup.register(() -> given().when().delete("/things/" + thingName).then().statusCode(200)); - given().header("x-amzn-principal", device.certificateArn).when().put("/things/" + thingName + "/principals").then().statusCode(200); - cleanup.register(() -> given().header("x-amzn-principal", device.certificateArn) - .when().delete("/things/" + thingName + "/principals").then().statusCode(200)); + device.attachNewThing(thingName, cleanup); MqttClient asThing = connectTls(device, thingName); assertTrue(asThing.isConnected()); @@ -279,22 +275,14 @@ class IotMqttMutualTlsIntegrationTest { return device; } - private static MqttClient connectTls(IotDeviceIdentity device, String clientId) throws Exception { + static MqttClient connectTls(IotDeviceIdentity device, String clientId) throws Exception { return connect("ssl://127.0.0.1:" + TLS_PORT, clientId, device.sslContext(TLS_DIR).getSocketFactory()); } - private static MqttClient connect(String uri, String clientId, SSLSocketFactory socketFactory) throws Exception { + static MqttClient connect(String uri, String clientId, SSLSocketFactory socketFactory) throws Exception { MqttClient client = new MqttClient(uri, clientId, new MemoryPersistence()); - MqttConnectOptions options = new MqttConnectOptions(); - options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); - options.setCleanSession(true); - options.setConnectionTimeout(10); - options.setAutomaticReconnect(false); - if (socketFactory != null) { - options.setSocketFactory(socketFactory); - } try { - client.connect(options); + client.connect(mqtt3Options(socketFactory, true)); } catch (MqttException e) { client.close(); throw e; @@ -302,11 +290,23 @@ class IotMqttMutualTlsIntegrationTest { return client; } + static MqttConnectOptions mqtt3Options(SSLSocketFactory socketFactory, boolean cleanSession) { + MqttConnectOptions options = new MqttConnectOptions(); + options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); + options.setCleanSession(cleanSession); + options.setConnectionTimeout(10); + options.setAutomaticReconnect(false); + if (socketFactory != null) { + options.setSocketFactory(socketFactory); + } + return options; + } + private static org.eclipse.paho.mqttv5.client.MqttClient mqtt5Client(String clientId) throws Exception { return new org.eclipse.paho.mqttv5.client.MqttClient("ssl://127.0.0.1:" + TLS_PORT, clientId, null); } - private static MqttConnectionOptions mqtt5Options(SSLSocketFactory socketFactory) { + static MqttConnectionOptions mqtt5Options(SSLSocketFactory socketFactory) { MqttConnectionOptions options = new MqttConnectionOptions(); options.setCleanStart(true); options.setConnectionTimeout(10); diff --git a/src/test/java/io/floci/aws/services/iot/IotMqttTlsIntegrationTest.java b/src/test/java/io/floci/aws/services/iot/IotMqttTlsIntegrationTest.java index 584c7d6ab8..96971664ee 100644 --- a/src/test/java/io/floci/aws/services/iot/IotMqttTlsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iot/IotMqttTlsIntegrationTest.java @@ -61,8 +61,8 @@ class IotMqttTlsIntegrationTest { static final int TLS_PORT = IotMqttTlsProfile.TLS_PORT; static final String LEARNED_HOST = "iot.dev.localhost.floci.io"; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - private static final String CONNECT_ANY_CLIENT = - "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"iot:Connect\",\"Resource\":\"arn:aws:iot:*:*:client/*\"}]}"; + private static final String ALLOW_ALL_MQTT = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":[\"iot:Connect\",\"iot:Publish\",\"iot:Subscribe\",\"iot:Receive\"],\"Resource\":\"*\"}]}"; @Inject TlsCertificateManager certificateManager; @@ -76,14 +76,14 @@ class IotMqttTlsIntegrationTest { private IotDeviceIdentity device; /** - * One registered device with a policy allowing iot:Connect for any client id, shared by the + * One registered device with a policy allowing every MQTT action on any resource, shared by the * TLS clients of a test and removed after it. Provisioned on first use, since the plaintext * tests need none. */ private IotDeviceIdentity device() { if (device == null) { device = IotDeviceIdentity.provision(true, cleanup); - device.attachNewPolicy(CONNECT_ANY_CLIENT, cleanup); + device.attachNewPolicy(ALLOW_ALL_MQTT, cleanup); } return device; } diff --git a/src/test/java/io/floci/aws/services/iot/IotMqttTopicAuthorizationIntegrationTest.java b/src/test/java/io/floci/aws/services/iot/IotMqttTopicAuthorizationIntegrationTest.java new file mode 100644 index 0000000000..3b2a2e2c15 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iot/IotMqttTopicAuthorizationIntegrationTest.java @@ -0,0 +1,337 @@ +package io.floci.aws.services.iot; + +import io.floci.aws.testing.IotMqttTlsProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.mqttv5.client.IMqttToken; +import org.eclipse.paho.mqttv5.client.MqttAsyncClient; +import org.eclipse.paho.mqttv5.client.MqttCallback; +import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse; +import org.eclipse.paho.mqttv5.client.persist.MemoryPersistence; +import org.eclipse.paho.mqttv5.common.MqttMessage; +import org.eclipse.paho.mqttv5.common.packet.MqttProperties; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import static io.floci.aws.services.iot.IotMqttMutualTlsIntegrationTest.connect; +import static io.floci.aws.services.iot.IotMqttMutualTlsIntegrationTest.connectTls; +import static io.floci.aws.services.iot.IotMqttMutualTlsIntegrationTest.mqtt3Options; +import static io.floci.aws.services.iot.IotMqttMutualTlsIntegrationTest.mqtt5Options; +import static io.restassured.RestAssured.given; +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; + +@QuarkusTest +@TestProfile(IotMqttTlsProfile.class) +class IotMqttTopicAuthorizationIntegrationTest { + + private static final Path TLS_DIR = Path.of(IotMqttTlsProfile.TLS_DIR); + private static final int NOT_AUTHORIZED = 0x87; + private static final String THING_TOPICS_ONLY = "{\"Version\":\"2012-10-17\",\"Statement\":[" + + "{\"Effect\":\"Allow\",\"Action\":\"iot:Connect\",\"Resource\":\"arn:aws:iot:*:*:client/${iot:Connection.Thing.ThingName}\"}," + + "{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Receive\"]," + + "\"Resource\":\"arn:aws:iot:*:*:topic/things/${iot:Connection.Thing.ThingName}/*\"}," + + "{\"Effect\":\"Allow\",\"Action\":\"iot:Subscribe\"," + + "\"Resource\":\"arn:aws:iot:*:*:topicfilter/things/${iot:Connection.Thing.ThingName}/*\"}]}"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aDeviceSubscribesPublishesAndReceivesOnItsOwnThingTopics() throws Exception { + String thing = "a" + System.nanoTime(); + IotDeviceIdentity device = thingDevice(thing); + byte[] payload = "own".getBytes(StandardCharsets.UTF_8); + + MqttClient client = connectTls(device, thing); + try { + CompletableFuture received = new CompletableFuture<>(); + client.subscribe("things/" + thing + "/#", 1, (topic, message) -> received.complete(message.getPayload())); + client.publish("things/" + thing + "/telemetry", payload, 1, false); + + assertArrayEquals(payload, received.get(10, TimeUnit.SECONDS)); + } finally { + closeV3(client); + } + } + + @Test + void mqtt3SubscribeToAnotherThingsTopicClosesTheConnection() throws Exception { + String thing = "a" + System.nanoTime(); + MqttClient client = connectTls(thingDevice(thing), thing); + try { + assertThrows(MqttException.class, () -> client.subscribe("things/b" + thing + "/#", 1)); + assertFalse(client.isConnected()); + } finally { + closeV3(client); + } + } + + @Test + void mqtt3PublishToAnotherThingsTopicClosesTheConnectionUndelivered() throws Exception { + String thing = "a" + System.nanoTime(); + String otherTopic = "things/b" + thing + "/telemetry"; + MqttClient listener = connectPlain("listener-" + System.nanoTime()); + MqttClient client = null; + try { + client = connectTls(thingDevice(thing), thing); + MqttClient device = client; + BlockingQueue received = new LinkedBlockingQueue<>(); + listener.subscribe(otherTopic, 1, + (topic, message) -> received.add(new String(message.getPayload(), StandardCharsets.UTF_8))); + + assertThrows(MqttException.class, () -> device.publish(otherTopic, "denied".getBytes(StandardCharsets.UTF_8), 1, false)); + listener.publish(otherTopic, "marker".getBytes(StandardCharsets.UTF_8), 1, false); + + assertFalse(device.isConnected()); + assertEquals("marker", received.poll(10, TimeUnit.SECONDS)); + } finally { + if (client != null) { + closeV3(client); + } + closeV3(listener); + } + } + + @Test + void mqtt5DeniedSubscribeAndQos1PublishAreAnsweredNotAuthorizedAndTheSessionStays() throws Exception { + String thing = "a" + System.nanoTime(); + DisconnectRecorder recorder = new DisconnectRecorder(); + MqttAsyncClient client = connectV5(thingDevice(thing), thing, recorder); + try { + IMqttToken subscribe = client.subscribe("things/b" + thing + "/#", 1); + subscribe.waitForCompletion(10_000); + assertEquals(NOT_AUTHORIZED, subscribe.getReasonCodes()[0]); + + IMqttToken publish = client.publish("things/b" + thing + "/telemetry", "x".getBytes(StandardCharsets.UTF_8), 1, false); + publish.waitForCompletion(10_000); + assertEquals(NOT_AUTHORIZED, publish.getReasonCodes()[0]); + + IMqttToken own = client.subscribe("things/" + thing + "/#", 1); + own.waitForCompletion(10_000); + assertEquals(1, own.getReasonCodes()[0]); + assertTrue(client.isConnected()); + } finally { + closeV5(client); + } + } + + @Test + void mqtt5DeniedQos0PublishIsDisconnectedNotAuthorized() throws Exception { + String thing = "a" + System.nanoTime(); + DisconnectRecorder recorder = new DisconnectRecorder(); + MqttAsyncClient client = connectV5(thingDevice(thing), thing, recorder); + try { + client.publish("things/b" + thing + "/telemetry", "x".getBytes(StandardCharsets.UTF_8), 0, false); + + MqttDisconnectResponse disconnect = recorder.disconnects.poll(10, TimeUnit.SECONDS); + assertEquals(NOT_AUTHORIZED, disconnect.getReturnCode()); + } finally { + closeV5(client); + } + } + + @Test + void aSubscriberReceivesOnlyTheTopicsItsPolicyAllowsReceiveOn() throws Exception { + String prefix = "receive/" + System.nanoTime(); + IotDeviceIdentity device = IotDeviceIdentity.provision(true, cleanup); + device.attachNewPolicy(receiveOnly(prefix + "/ok"), cleanup); + MqttClient subscriber = connectTls(device, "sub-" + System.nanoTime()); + MqttClient publisher = null; + try { + publisher = connectPlain("pub-" + System.nanoTime()); + BlockingQueue received = new LinkedBlockingQueue<>(); + subscriber.subscribe(prefix + "/+", 1, (topic, message) -> received.add(topic)); + + publisher.publish(prefix + "/denied", "x".getBytes(StandardCharsets.UTF_8), 1, false); + publisher.publish(prefix + "/ok", "x".getBytes(StandardCharsets.UTF_8), 1, false); + + assertEquals(prefix + "/ok", received.poll(10, TimeUnit.SECONDS)); + assertTrue(subscriber.isConnected()); + } finally { + if (publisher != null) { + closeV3(publisher); + } + closeV3(subscriber); + } + } + + @Test + void retainedMessagesAreDeliveredOnlyOnTopicsThePolicyAllowsReceiveOn() throws Exception { + String prefix = "retained/" + System.nanoTime(); + IotDeviceIdentity device = IotDeviceIdentity.provision(true, cleanup); + device.attachNewPolicy(receiveOnly(prefix + "/ok"), cleanup); + MqttClient publisher = connectPlain("pub-" + System.nanoTime()); + MqttClient subscriber = null; + try { + publisher.publish(prefix + "/denied", "retained-denied".getBytes(StandardCharsets.UTF_8), 1, true); + publisher.publish(prefix + "/ok", "retained-ok".getBytes(StandardCharsets.UTF_8), 1, true); + subscriber = connectTls(device, "sub-" + System.nanoTime()); + BlockingQueue received = new LinkedBlockingQueue<>(); + subscriber.subscribe(prefix + "/+", 1, + (topic, message) -> received.add(new String(message.getPayload(), StandardCharsets.UTF_8))); + // The retained copies go out with the SUBACK, so this live one arrives after all of them. + publisher.publish(prefix + "/ok", "live".getBytes(StandardCharsets.UTF_8), 1, false); + + assertEquals("retained-ok", received.poll(10, TimeUnit.SECONDS)); + assertEquals("live", received.poll(10, TimeUnit.SECONDS)); + } finally { + if (subscriber != null) { + closeV3(subscriber); + } + closeV3(publisher); + } + } + + @Test + void aNewDefaultPolicyVersionAppliesToAnEstablishedSession() throws Exception { + String prefix = "revoke/" + System.nanoTime(); + IotDeviceIdentity device = IotDeviceIdentity.provision(true, cleanup); + String policy = device.attachNewPolicy(receiveOnly("*"), cleanup); + MqttClient subscriber = connectTls(device, "sub-" + System.nanoTime()); + MqttClient publisher = null; + try { + publisher = connectPlain("pub-" + System.nanoTime()); + BlockingQueue received = new LinkedBlockingQueue<>(); + subscriber.subscribe(prefix + "/+", 1, (topic, message) -> received.add(topic)); + given().contentType("application/json").body(Map.of("policyDocument", receiveOnly(prefix + "/kept"))) + .queryParam("setAsDefault", true) + .when().post("/policies/" + policy + "/version").then().statusCode(200); + + publisher.publish(prefix + "/revoked", "x".getBytes(StandardCharsets.UTF_8), 1, false); + publisher.publish(prefix + "/kept", "x".getBytes(StandardCharsets.UTF_8), 1, false); + + assertEquals(prefix + "/kept", received.poll(10, TimeUnit.SECONDS)); + } finally { + if (publisher != null) { + closeV3(publisher); + } + closeV3(subscriber); + } + } + + // Catches: the QoS 1 messages stored for a disconnected persistent session reaching it on the + // reconnect although its policies deny iot:Receive on their topic. + @Test + void messagesStoredForAPersistentSessionAreDeliveredOnlyOnTopicsThePolicyAllowsReceiveOn() throws Exception { + String prefix = "stored/" + System.nanoTime(); + String clientId = "persistent-" + System.nanoTime(); + IotDeviceIdentity device = IotDeviceIdentity.provision(true, cleanup); + device.attachNewPolicy(receiveOnly(prefix + "/ok"), cleanup); + MqttConnectOptions options = mqtt3Options(device.sslContext(TLS_DIR).getSocketFactory(), false); + MqttClient publisher = connectPlain("pub-" + System.nanoTime()); + MqttClient subscriber = new MqttClient("ssl://127.0.0.1:" + IotMqttTlsProfile.TLS_PORT, clientId, null); + try { + BlockingQueue ended = new LinkedBlockingQueue<>(); + publisher.subscribe("$aws/events/presence/disconnected/" + clientId, 1, (topic, message) -> ended.add(topic)); + BlockingQueue received = new LinkedBlockingQueue<>(); + subscriber.connect(options); + subscriber.subscribe(prefix + "/+", 1, + (topic, message) -> received.add(new String(message.getPayload(), StandardCharsets.UTF_8))); + subscriber.disconnect(); + // The disconnected event goes out once the session is stored for its reconnect. + assertEquals("$aws/events/presence/disconnected/" + clientId, ended.poll(10, TimeUnit.SECONDS)); + + publisher.publish(prefix + "/denied", "denied".getBytes(StandardCharsets.UTF_8), 1, false); + publisher.publish(prefix + "/ok", "ok".getBytes(StandardCharsets.UTF_8), 1, false); + subscriber.connect(options); + + assertEquals("ok", received.poll(10, TimeUnit.SECONDS)); + } finally { + closeV3(subscriber); + closeV3(publisher); + } + } + + private static String receiveOnly(String topic) { + String resource = topic.equals("*") ? "*" : "arn:aws:iot:*:*:topic/" + topic; + return "{\"Version\":\"2012-10-17\",\"Statement\":[" + + "{\"Effect\":\"Allow\",\"Action\":[\"iot:Connect\",\"iot:Subscribe\"],\"Resource\":\"*\"}," + + "{\"Effect\":\"Allow\",\"Action\":\"iot:Receive\",\"Resource\":\"" + resource + "\"}]}"; + } + + private IotDeviceIdentity thingDevice(String thing) { + IotDeviceIdentity device = IotDeviceIdentity.provision(true, cleanup); + device.attachNewPolicy(THING_TOPICS_ONLY, cleanup); + device.attachNewThing(thing, cleanup); + return device; + } + + private static MqttClient connectPlain(String clientId) throws Exception { + return connect("tcp://127.0.0.1:" + IotMqttTlsProfile.PLAIN_PORT, clientId, null); + } + + private static void closeV3(MqttClient client) { + try { + if (client.isConnected()) { + client.disconnect(); + } + client.close(); + } catch (MqttException ignored) { + // Safe to ignore teardown close errors on partially-connected or already closed clients. + } + } + + private static MqttAsyncClient connectV5(IotDeviceIdentity device, String clientId, MqttCallback callback) throws Exception { + MqttAsyncClient client = new MqttAsyncClient("ssl://127.0.0.1:" + IotMqttTlsProfile.TLS_PORT, clientId, + new MemoryPersistence()); + client.setCallback(callback); + client.connect(mqtt5Options(device.sslContext(TLS_DIR).getSocketFactory())).waitForCompletion(10_000); + return client; + } + + private static void closeV5(MqttAsyncClient client) { + try { + if (client.isConnected()) { + client.disconnect().waitForCompletion(5_000); + } + client.close(); + } catch (org.eclipse.paho.mqttv5.common.MqttException ignored) { + // Safe to ignore teardown close errors on partially-connected or already closed clients. + } + } + + private static final class DisconnectRecorder implements MqttCallback { + final BlockingQueue disconnects = new LinkedBlockingQueue<>(); + + @Override + public void disconnected(MqttDisconnectResponse response) { + disconnects.add(response); + } + + @Override + public void mqttErrorOccurred(org.eclipse.paho.mqttv5.common.MqttException exception) { + } + + @Override + public void messageArrived(String topic, MqttMessage message) { + } + + @Override + public void deliveryComplete(IMqttToken token) { + } + + @Override + public void connectComplete(boolean reconnect, String serverUri) { + } + + @Override + public void authPacketArrived(int reasonCode, MqttProperties properties) { + } + } +} diff --git a/src/test/java/io/floci/aws/services/iot/IotServiceDeviceAuthTest.java b/src/test/java/io/floci/aws/services/iot/IotServiceDeviceAuthTest.java index d1ffc36fc5..cbcac911e3 100644 --- a/src/test/java/io/floci/aws/services/iot/IotServiceDeviceAuthTest.java +++ b/src/test/java/io/floci/aws/services/iot/IotServiceDeviceAuthTest.java @@ -496,6 +496,44 @@ class IotServiceDeviceAuthTest { assertFalse(service.isConnectAllowedBy(List.of(policy), "sensor-1", "10.1.2.3", null)); } + @Test + void topicActionsAreDecidedOnTheTopicAndTopicFilterArnsWithTheThingName() { + RegisteredDevice device = registeredDevice(true); + service.createThing("sensor-1", Map.of(), REGION); + service.attachThingPrincipal("sensor-1", device.certificate().getCertificateArn(), REGION); + createAndAttach("p", "{\"Version\":\"2012-10-17\",\"Statement\":[" + + "{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Receive\"]," + + "\"Resource\":\"arn:aws:iot:*:*:topic/devices/${iot:Connection.Thing.ThingName}/*\"}," + + "{\"Effect\":\"Allow\",\"Action\":\"iot:Subscribe\"," + + "\"Resource\":\"arn:aws:iot:*:*:topicfilter/devices/${iot:Connection.Thing.ThingName}/*\"}]}", device); + + IotService.ConnectionPolicies policies = service.devicePolicies(device, "sensor-1", "127.0.0.1", null); + + assertTrue(service.isAllowed(policies, "iot:Publish", "topic/devices/sensor-1/telemetry")); + assertTrue(service.isAllowed(policies, "iot:Receive", "topic/devices/sensor-1/telemetry")); + assertTrue(service.isAllowed(policies, "iot:Subscribe", "topicfilter/devices/sensor-1/#")); + assertFalse(service.isAllowed(policies, "iot:Publish", "topic/devices/sensor-2/telemetry")); + assertFalse(service.isAllowed(policies, "iot:Receive", "topic/devices/sensor-2/telemetry")); + assertFalse(service.isAllowed(policies, "iot:Subscribe", "topicfilter/devices/sensor-2/#")); + assertFalse(service.isAllowed(policies, "iot:Subscribe", "topicfilter/other/sensor-1/telemetry")); + assertFalse(service.isAllowed(service.devicePolicies(device, "sensor-2", "127.0.0.1", null), + "iot:Publish", "topic/devices/sensor-2/telemetry"), "the thing variable resolves only for the attached thing"); + } + + @Test + void customAuthorizerPoliciesDecideTopicActionsWithTheClientId() { + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":[\"iot:Publish\",\"iot:Receive\"],\"Resource\":\"arn:aws:iot:*:*:topic/clients/${iot:ClientId}/*\"}]}"; + + IotService.ConnectionPolicies policies = service.authorizerPolicies(List.of(policy), "browser-1", "127.0.0.1", null); + + assertTrue(service.isAllowed(policies, "iot:Receive", "topic/clients/browser-1/events")); + assertFalse(service.isAllowed(policies, "iot:Receive", "topic/clients/browser-2/events")); + assertFalse(service.isAllowed(policies, "iot:Subscribe", "topicfilter/clients/browser-1/events")); + assertFalse(service.isAllowed(service.authorizerPolicies(List.of(), "browser-1", null, null), + "iot:Publish", "topic/clients/browser-1/events"), "no policy means deny"); + } + private RegisteredDevice registeredDevice(boolean active) { IotCertificate created = service.createKeysAndCertificate(active, REGION); return service.findRegisteredCertificate(parse(created)).orElseThrow();