mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iot): authorize MQTT publish, subscribe and receive against session policies (#8660)
A session admitted on 8883 by its certificate, or by a custom authorizer (the default one for unsigned MQTT over WebSocket), is now authorized per packet: iot:Subscribe on topicfilter/<filter>, iot:Publish and iot:Receive on topic/<topic>, with the connect's condition keys and policy variables. A certificate's policies are re-read on every check, so an attach, a detach or a new default version reaches an open session. A denied SUBSCRIBE or PUBLISH closes an MQTT 3.1.1 connection with the lifecycle reason AUTH_ERROR and gets reason code 0x87 on MQTT 5 (SUBACK, QoS 1 PUBACK, or DISCONNECT for QoS 0). A denied publish is not recorded, run through topic rules or delivered, and iot:Receive is checked on every delivery, retained messages and those stored for a resumed persistent session included. Closes #8643
This commit is contained in:
1 parent
fbedde4c2c
commit
c6824948dd
10 files changed
+710
-86
No files matched your search
@@ -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<String> 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) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+337
@@ -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<byte[]> 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<String> 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<String> 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<String> 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<String> 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<String> ended = new LinkedBlockingQueue<>();
|
||||
publisher.subscribe("$aws/events/presence/disconnected/" + clientId, 1, (topic, message) -> ended.add(topic));
|
||||
BlockingQueue<String> 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<MqttDisconnectResponse> 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) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user