Light, fluffy, and always free - The AWS Local Emulator alternative
test(iot): share one profile across eight MQTT integration tests (#5684)
Priamo Germosene357353472fb
diff --git a/src/test/java/io/github/hectorvent/floci/config/IotMqttWebSocketProxyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/IotMqttWebSocketProxyIntegrationTest.javaindex c3eb57919b..7707e08e92 100644--- a/src/test/java/io/github/hectorvent/floci/config/IotMqttWebSocketProxyIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/IotMqttWebSocketProxyIntegrationTest.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.config;import io.github.hectorvent.floci.services.iot.IotMqttWebSocketIntegrationTest;+import io.github.hectorvent.floci.testing.IotMqttTlsProfile;import io.quarkus.test.junit.QuarkusTest;import io.quarkus.test.junit.TestProfile;import io.vertx.core.Vertx;@@ -48,7 +49,7 @@ import static org.mockito.Mockito.when;* dial the Quarkus test ports directly.*/@QuarkusTest-@TestProfile(IotMqttWebSocketIntegrationTest.Profile.class)+@TestProfile(IotMqttTlsProfile.class)class IotMqttWebSocketProxyIntegrationTest {static final String LEARNED_HOST = "iot.example.localhost.floci.io";@@ -95,10 +96,14 @@ class IotMqttWebSocketProxyIntegrationTest {assertThrows(SSLHandshakeException.class, () -> upgradeAs(LEARNED_HOST),"precondition: the boot leaf covers one label under localhost.floci.io, not two");- certificateManager.ensureHost(LEARNED_HOST);+ try {+ certificateManager.ensureHost(LEARNED_HOST);- assertArrayEquals(CONNACK_ACCEPTED, upgradeAs(LEARNED_HOST),- "after ensureHost a client verifying the learned name gets an MQTT session on /mqtt");+ assertArrayEquals(CONNACK_ACCEPTED, upgradeAs(LEARNED_HOST),+ "after ensureHost a client verifying the learned name gets an MQTT session on /mqtt");+ } finally {+ certificateManager.clear();+ }}private int startProxy() throws Exception {diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.javaindex 79eb6ec504..20ab750161 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsHttp2HostRoutingIntegrationTest.java@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup;import io.github.hectorvent.floci.services.cloudfront.model.Origin;import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;import io.github.hectorvent.floci.services.s3.S3Service;+import io.github.hectorvent.floci.testing.PartitionCleanup;import io.quarkus.test.junit.QuarkusTest;import io.quarkus.test.junit.TestProfile;import io.restassured.http.ContentType;@@ -21,8 +22,8 @@ import io.vertx.core.net.PemTrustOptions;import io.vertx.core.net.SocketAddress;import jakarta.inject.Inject;import org.eclipse.microprofile.config.inject.ConfigProperty;-import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.RegisterExtension;import java.nio.charset.StandardCharsets;import java.nio.file.Path;@@ -30,7 +31,6 @@ import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.Signature;import java.time.Instant;-import java.util.ArrayList;import java.util.Base64;import java.util.LinkedHashMap;import java.util.List;@@ -67,25 +67,18 @@ class TlsHttp2HostRoutingIntegrationTest {@InjectCloudFrontService cloudFrontService;- /** What the test created, removed newest first: every class on this profile shares one application. */- private final List<Runnable> cleanup = new ArrayList<>();-- @AfterEach- void removeWhatTheTestCreated() {- for (int i = cleanup.size() - 1; i >= 0; i--) {- cleanup.get(i).run();- }- }+ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();@Testvoid cloudFrontServesACannedSignedUrlOnEachLocalDeliveryHost() throws Exception {String suffix = Long.toString(System.nanoTime(), 36);String bucket = "cf-h2-" + suffix;s3Service.createBucket(bucket, REGION);- cleanup.add(() -> s3Service.deleteBucket(bucket));+ cleanup.register(() -> s3Service.deleteBucket(bucket));s3Service.putObject(bucket, "private/report.txt", ("H2-" + suffix).getBytes(StandardCharsets.UTF_8),"text/plain", Map.of());- cleanup.add(() -> s3Service.deleteObject(bucket, "private/report.txt"));+ cleanup.register(() -> s3Service.deleteObject(bucket, "private/report.txt"));KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");generator.initialize(2048);@@ -98,14 +91,14 @@ class TlsHttp2HostRoutingIntegrationTest {+ "\n-----END PUBLIC KEY-----");publicKey = cloudFrontService.createPublicKey(publicKey);String publicKeyId = publicKey.getId();- cleanup.add(() -> cloudFrontService.deletePublicKey(publicKeyId,+ cleanup.register(() -> cloudFrontService.deletePublicKey(publicKeyId,cloudFrontService.getPublicKey(publicKeyId).getEtag()));KeyGroup keyGroup = new KeyGroup();keyGroup.setName("kg-" + suffix);keyGroup.setItems(List.of(publicKey.getId()));keyGroup = cloudFrontService.createKeyGroup(keyGroup);String keyGroupId = keyGroup.getId();- cleanup.add(() -> cloudFrontService.deleteKeyGroup(keyGroupId,+ cleanup.register(() -> cloudFrontService.deleteKeyGroup(keyGroupId,cloudFrontService.getKeyGroup(keyGroupId).getEtag()));Origin origin = new Origin();@@ -125,7 +118,7 @@ class TlsHttp2HostRoutingIntegrationTest {distribution = cloudFrontService.createDistribution(distribution, Map.of());String distributionId = distribution.getId();// The test owns the distribution, so it skips the disable-then-delete round trip.- cleanup.add(() -> cloudFrontService.removeDistribution(distributionId));+ cleanup.register(() -> cloudFrontService.removeDistribution(distributionId));// A browser sends the host in lower case, and a canned policy signs the port too.String id = distribution.getId().toLowerCase(Locale.ROOT);@@ -151,7 +144,7 @@ class TlsHttp2HostRoutingIntegrationTest {.body("{\"name\":\"h2-host-routing\"}").when().post("/restapis").then().statusCode(201).extract().path("id");- cleanup.add(() -> given().when().delete("/restapis/" + apiId).then().statusCode(202));+ cleanup.register(() -> given().when().delete("/restapis/" + apiId).then().statusCode(202));String rootId = given().when().get("/restapis/" + apiId + "/resources").then().statusCode(200).extract().path("item[0].id");String resourceId = given().contentType(ContentType.JSON)@@ -179,11 +172,11 @@ class TlsHttp2HostRoutingIntegrationTest {given().contentType(ContentType.JSON).body("{\"domainName\":\"" + API_DOMAIN + "\"}").when().post("/domainnames").then().statusCode(201);- cleanup.add(() -> given().when().delete("/domainnames/" + API_DOMAIN).then().statusCode(202));+ cleanup.register(() -> given().when().delete("/domainnames/" + API_DOMAIN).then().statusCode(202));given().contentType(ContentType.JSON).body("{\"basePath\":\"v1\",\"restApiId\":\"" + apiId + "\",\"stage\":\"dev\"}").when().post("/domainnames/" + API_DOMAIN + "/basepathmappings").then().statusCode(201);- cleanup.add(() -> given().when().delete("/domainnames/" + API_DOMAIN + "/basepathmappings/v1")+ cleanup.register(() -> given().when().delete("/domainnames/" + API_DOMAIN + "/basepathmappings/v1").then().statusCode(202));Http2Response response = getOverHttp2(API_DOMAIN, "/v1/ping");diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotCustomAuthorizerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotCustomAuthorizerIntegrationTest.javaindex e0683550e2..3996638e9a 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotCustomAuthorizerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotCustomAuthorizerIntegrationTest.java@@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.services.lambda.LambdaService;import io.github.hectorvent.floci.services.lambda.model.InvocationType;import io.github.hectorvent.floci.services.lambda.model.InvokeResult;+import io.github.hectorvent.floci.testing.IotMqttTlsProfile;+import io.github.hectorvent.floci.testing.PartitionCleanup;import io.quarkus.test.InjectMock;import io.quarkus.test.junit.QuarkusTest;import io.quarkus.test.junit.TestProfile;@@ -17,6 +19,7 @@ import org.eclipse.paho.mqttv5.client.MqttAsyncClient;import org.eclipse.paho.mqttv5.client.MqttConnectionOptions;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.RegisterExtension;import java.nio.charset.StandardCharsets;import java.util.ArrayList;@@ -51,7 +54,7 @@ import static org.mockito.Mockito.when;* received is asserted as the event.*/@QuarkusTest-@TestProfile(IotMqttWebSocketIntegrationTest.Profile.class)+@TestProfile(IotMqttTlsProfile.class)class IotCustomAuthorizerIntegrationTest {private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:it-custom-auth";@@ -67,6 +70,9 @@ class IotCustomAuthorizerIntegrationTest {@InjectMockLambdaService lambdaService;+ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();+private final BlockingQueue<JsonNode> events = new LinkedBlockingQueue<>();private String authorizer;@@ -91,6 +97,13 @@ class IotCustomAuthorizerIntegrationTest {.body("{\"authorizerFunctionArn\": \"" + FUNCTION_ARN + "\", \"signingDisabled\": true, \"status\": \"ACTIVE\"}").when().post("/authorizer/" + authorizer).then().statusCode(200);+ String created = authorizer;+ cleanup.register(() -> {+ given().contentType("application/json").body("{\"status\": \"INACTIVE\"}")+ .when().put("/authorizer/" + created)+ .then().statusCode(200);+ given().when().delete("/authorizer/" + created).then().statusCode(200);+ });}@Test@@ -326,7 +339,7 @@ class IotCustomAuthorizerIntegrationTest {}private static String tcp() {- return "tcp://127.0.0.1:" + IotMqttWebSocketIntegrationTest.PLAIN_PORT;+ return "tcp://127.0.0.1:" + IotMqttTlsProfile.PLAIN_PORT;}private JsonNode takeEvent() throws InterruptedException {diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceIdentity.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceIdentity.javaindex 27cb42c1dd..a299d8205e 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceIdentity.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotDeviceIdentity.java@@ -1,8 +1,10 @@package io.github.hectorvent.floci.services.iot;+import com.fasterxml.jackson.databind.ObjectMapper;import io.github.hectorvent.floci.config.FlociCertificateAuthority;import io.github.hectorvent.floci.core.common.Pem;import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.testing.PartitionCleanup;import io.restassured.path.json.JsonPath;import javax.net.ssl.KeyManagerFactory;@@ -21,6 +23,7 @@ import static io.restassured.RestAssured.given;final class IotDeviceIdentity {private static final char[] PASSWORD = "device".toCharArray();+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();final String certificateId;final String certificateArn;@@ -48,6 +51,41 @@ final class IotDeviceIdentity {Pem.parsePrivateKey(created.getString("keyPair.PrivateKey")));}+ /**+ * Provisions a device as {@link #provision(boolean)} does, and has {@code cleanup} deactivate+ * and delete its certificate after the test, once whatever was attached to it is detached.+ */+ static IotDeviceIdentity provision(boolean active, PartitionCleanup cleanup) {+ IotDeviceIdentity device = provision(active);+ cleanup.register(device::delete);+ return device;+ }++ /**+ * Creates a policy of {@code document} under a fresh name and attaches it to this device's+ * certificate; {@code cleanup} detaches and deletes it after the test. Returns the policy name.+ */+ String attachNewPolicy(String document, PartitionCleanup cleanup) {+ String policy = "device-policy-" + System.nanoTime();+ given()+ .contentType("application/json")+ .body(OBJECT_MAPPER.createObjectNode().put("policyDocument", document).toString())+ .when().post("/policies/" + policy)+ .then().statusCode(200);+ cleanup.register(() -> {+ given().queryParam("target", certificateArn).when().post("/target-policies/" + policy).then().statusCode(200);+ given().when().delete("/policies/" + policy).then().statusCode(200);+ });+ given().queryParam("target", certificateArn).when().put("/target-policies/" + policy).then().statusCode(200);+ return policy;+ }++ /** IoT Core deletes only an inactive certificate with nothing attached. */+ private void delete() {+ given().queryParam("newStatus", "INACTIVE").when().put("/certificates/" + certificateId).then().statusCode(200);+ given().when().delete("/certificates/" + certificateId).then().statusCode(200);+ }+/** A certificate the Floci CA signed but IoT Core never registered. */static IotDeviceIdentity stranger(Path tlsDir) {CertificateGenerator.GeneratedCertificate issued = FlociCertificateAuthority.loadOrCreate(tlsDir).issueClientCertificate("stranger");diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttEnabledIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttEnabledIntegrationTest.javaindex 5c4dd66579..173b6d4c83 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttEnabledIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttEnabledIntegrationTest.java@@ -2,8 +2,9 @@ package io.github.hectorvent.floci.services.iot;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.testing.IotMqttTlsProfile;+import io.github.hectorvent.floci.testing.PartitionCleanup;import io.quarkus.test.junit.QuarkusTest;-import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;import jakarta.inject.Inject;import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;@@ -15,13 +16,13 @@ import org.eclipse.paho.client.mqttv3.MqttMessage;import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.RegisterExtension;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.time.Duration;import java.time.Instant;import java.util.Arrays;-import java.util.Map;import java.util.Optional;import java.util.Random;import java.util.concurrent.BlockingQueue;@@ -36,17 +37,19 @@ import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;@QuarkusTest-@TestProfile(IotMqttEnabledIntegrationTest.EnabledMqttProfile.class)+@TestProfile(IotMqttTlsProfile.class)class IotMqttEnabledIntegrationTest {static final int AWS_MAX_PAYLOAD = 128 * 1024;- private static final int PORT = 18831;- private static final String BROKER_URI = "tcp://127.0.0.1:" + PORT;+ private static final String BROKER_URI = "tcp://127.0.0.1:" + IotMqttTlsProfile.PLAIN_PORT;private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();@InjectIotPublishEventRecorder eventRecorder;+ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();+@BeforeEachvoid clearEvents() {eventRecorder.clear();@@ -260,6 +263,7 @@ class IotMqttEnabledIntegrationTest {try (MqttTestClient publisher = connectMqtt("phase7-update-pub")) {publisher.publish("$aws/things/phase7Thing/shadow/update",json("{\"state\":{\"desired\":{\"color\":\"blue\"}},\"clientToken\":\"token-1\"}"));+ removeShadowAfterTheTest("phase7Thing");}MqttPublish accepted = subscriber.takePublish();@@ -278,6 +282,7 @@ class IotMqttEnabledIntegrationTest {try (Mqtt5TestClient publisher = connectMqtt5("phase7-mqtt5-update-pub")) {publisher.publish("$aws/things/phase7Mqtt5Thing/shadow/update",json("{\"state\":{\"desired\":{\"color\":\"purple\"}},\"clientToken\":\"mqtt5-token\"}"));+ removeShadowAfterTheTest("phase7Mqtt5Thing");}MqttPublish accepted = subscriber.takePublish();@@ -341,6 +346,7 @@ class IotMqttEnabledIntegrationTest {try (MqttTestClient publisher = connectMqtt("phase7-docs-delta-pub")) {publisher.publish("$aws/things/phase7Documents/shadow/update",json("{\"state\":{\"reported\":{\"color\":\"red\"}}}"));+ removeShadowAfterTheTest("phase7Documents");subscriber.takePublish();publisher.publish("$aws/things/phase7Documents/shadow/update",@@ -377,6 +383,8 @@ class IotMqttEnabledIntegrationTest {try (MqttTestClient publisher = connectMqtt("phase7-named-pub")) {publisher.publish(updateTopic,json("{\"state\":{\"desired\":{\"mode\":\"auto\"}},\"clientToken\":\"named-update\"}"));+ cleanup.register(() -> given().queryParam("name", "settings")+ .when().delete("/things/" + thingName + "/shadow").then().statusCode(200));MqttPublish updateAccepted = subscriber.takePublish();JsonNode updatePayload = readJson(updateAccepted.payload());assertEquals(updateTopic + "/accepted", updateAccepted.topic());@@ -416,6 +424,7 @@ class IotMqttEnabledIntegrationTest {.put("/rules/phase8MqttRepublishRule").then().statusCode(200);+ cleanup.register(() -> given().when().delete("/rules/phase8MqttRepublishRule").then().statusCode(200));try (MqttTestClient subscriber = connectMqtt("phase8-republish-sub")) {subscriber.subscribe("devices/phase8/mqtt/target");@@ -453,6 +462,7 @@ class IotMqttEnabledIntegrationTest {.put("/rules/phase8MqttClientIdRule").then().statusCode(200);+ cleanup.register(() -> given().when().delete("/rules/phase8MqttClientIdRule").then().statusCode(200));try (MqttTestClient subscriber = connectMqtt("phase8-clientid-sub")) {subscriber.subscribe("devices/phase8/mqtt/clientid-target");@@ -484,6 +494,10 @@ class IotMqttEnabledIntegrationTest {return Mqtt5TestClient.connect(uniqueClientId(clientId));}+ private void removeShadowAfterTheTest(String thingName) {+ cleanup.register(() -> given().when().delete("/things/" + thingName + "/shadow").then().statusCode(200));+ }+static byte[] randomPayload(int size) {byte[] payload = new byte[size];new Random(size).nextBytes(payload);@@ -684,16 +698,4 @@ class IotMqttEnabledIntegrationTest {return options;}}-- public static final class EnabledMqttProfile implements QuarkusTestProfile {- @Override- public Map<String, String> getConfigOverrides() {- return Map.of(- "floci.services.iot.mqtt.enabled", "true",- "floci.services.iot.mqtt.auto-start", "true",- "floci.services.iot.mqtt.host", "127.0.0.1",- "floci.services.iot.mqtt.port", Integer.toString(PORT)- );- }- }}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttMutualTlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttMutualTlsIntegrationTest.javaindex 9ac9ba49fe..646b224d41 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttMutualTlsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttMutualTlsIntegrationTest.java@@ -1,12 +1,8 @@package io.github.hectorvent.floci.services.iot;-import com.fasterxml.jackson.databind.ObjectMapper;-import io.github.hectorvent.floci.config.CertificateMetadata;-import io.github.hectorvent.floci.config.FlociCertificateAuthority;-import io.github.hectorvent.floci.services.acm.CertificateGenerator;-import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.testing.IotMqttTlsProfile;+import io.github.hectorvent.floci.testing.PartitionCleanup;import io.quarkus.test.junit.QuarkusTest;-import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;import org.eclipse.paho.client.mqttv3.MqttClient;import org.eclipse.paho.client.mqttv3.MqttConnectOptions;@@ -14,14 +10,12 @@ import org.eclipse.paho.client.mqttv3.MqttException;import org.eclipse.paho.client.mqttv3.MqttSecurityException;import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.RegisterExtension;import javax.net.ssl.SSLSocketFactory;-import java.io.IOException;-import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;-import java.util.Map;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;@@ -41,21 +35,22 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* connection's policy variables. The plaintext listener stays permissive.*/@QuarkusTest-@TestProfile(IotMqttMutualTlsIntegrationTest.Profile.class)+@TestProfile(IotMqttTlsProfile.class)class IotMqttMutualTlsIntegrationTest {- static final Path DATA_DIR = Path.of("target", "floci-iot-mqtt-mtls-test").toAbsolutePath();- static final Path TLS_DIR = DATA_DIR.resolve("tls");- static final int PLAIN_PORT = 18838;- static final int TLS_PORT = 18839;+ static final Path TLS_DIR = Path.of(IotMqttTlsProfile.TLS_DIR);+ static final int PLAIN_PORT = IotMqttTlsProfile.PLAIN_PORT;+ static final int TLS_PORT = IotMqttTlsProfile.TLS_PORT;/** The name the device dials, which Paho also sends as the TLS server name. */static final String DOMAIN = "localhost";- private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();private static final String CONNECT_ANY_CLIENT = policy("Allow", "arn:aws:iot:*:*:client/*", null);private static final String CONNECT_AS_ATTACHED_THING =policy("Allow", "arn:aws:iot:*:*:client/${iot:Connection.Thing.ThingName}", null);+ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();+@Testvoid activeCertificateWithConnectPolicyIsAdmitted() throws Exception {IotDeviceIdentity device = provisionWithPolicy(true, CONNECT_ANY_CLIENT);@@ -89,7 +84,7 @@ class IotMqttMutualTlsIntegrationTest {@Testvoid mqtt5DeviceWithoutPolicyIsRefusedWithTheNotAuthorizedReasonCode() throws Exception {- IotDeviceIdentity device = IotDeviceIdentity.provision(true);+ IotDeviceIdentity device = IotDeviceIdentity.provision(true, cleanup);org.eclipse.paho.mqttv5.client.MqttClient client = mqtt5Client("v5-no-policy-" + System.nanoTime());try {@@ -104,7 +99,7 @@ class IotMqttMutualTlsIntegrationTest {@Testvoid activeCertificateWithoutPolicyIsRefused() {- IotDeviceIdentity device = IotDeviceIdentity.provision(true);+ IotDeviceIdentity device = IotDeviceIdentity.provision(true, cleanup);assertNotAuthorized(() -> connectTls(device, "no-policy-" + System.nanoTime()));}@@ -130,10 +125,8 @@ class IotMqttMutualTlsIntegrationTest {@Testvoid detachedPolicyIsRefusedOnTheNextConnect() throws Exception {- IotDeviceIdentity device = IotDeviceIdentity.provision(true);- String policy = "detach-" + System.nanoTime();- createPolicy(policy, CONNECT_ANY_CLIENT);- attachPolicy(policy, device.certificateArn);+ IotDeviceIdentity device = IotDeviceIdentity.provision(true, cleanup);+ String policy = device.attachNewPolicy(CONNECT_ANY_CLIENT, cleanup);MqttClient first = connectTls(device, "detach-1-" + System.nanoTime());first.disconnect();first.close();@@ -188,7 +181,10 @@ class IotMqttMutualTlsIntegrationTest {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));MqttClient asThing = connectTls(device, thingName);assertTrue(asThing.isConnected());@@ -234,7 +230,7 @@ class IotMqttMutualTlsIntegrationTest {List<IotDeviceIdentity> refused = new ArrayList<>();for (int i = 0; i < devices; i++) {admitted.add(provisionWithPolicy(true, CONNECT_ANY_CLIENT));- refused.add(IotDeviceIdentity.provision(true));+ refused.add(IotDeviceIdentity.provision(true, cleanup));}CountDownLatch start = new CountDownLatch(1);ExecutorService pool = Executors.newFixedThreadPool(devices * 2);@@ -276,11 +272,9 @@ class IotMqttMutualTlsIntegrationTest {}}- private static IotDeviceIdentity provisionWithPolicy(boolean active, String document) {- IotDeviceIdentity device = IotDeviceIdentity.provision(active);- String policy = "connect-" + System.nanoTime();- createPolicy(policy, document);- attachPolicy(policy, device.certificateArn);+ private IotDeviceIdentity provisionWithPolicy(boolean active, String document) {+ IotDeviceIdentity device = IotDeviceIdentity.provision(active, cleanup);+ device.attachNewPolicy(document, cleanup);return device;}@@ -335,62 +329,8 @@ class IotMqttMutualTlsIntegrationTest {assertEquals(MqttException.REASON_CODE_NOT_AUTHORIZED, refused.getReasonCode());}- private static void createPolicy(String name, String document) {- given()- .contentType("application/json")- .body(OBJECT_MAPPER.createObjectNode().put("policyDocument", document).toString())- .when().post("/policies/" + name)- .then().statusCode(200);- }-- private static void attachPolicy(String name, String certificateArn) {- given().queryParam("target", certificateArn).when().put("/target-policies/" + name).then().statusCode(200);- }-private static String policy(String effect, String resource, String condition) {return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"" + effect + "\",\"Action\":\"iot:Connect\","+ "\"Resource\":\"" + resource + "\"" + (condition == null ? "" : ",\"Condition\":" + condition) + "}]}";}-- /**- * TLS on with a CA-issued leaf on disk, as in {@link IotMqttTlsIntegrationTest}, on ports and a- * data directory of its own so both classes can run in one JVM.- */- public static final class Profile implements QuarkusTestProfile {-- static {- try {- Files.createDirectories(TLS_DIR);- for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {- Files.deleteIfExists(TLS_DIR.resolve(name));- }- FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);- List<String> sans = List.of("localhost", "127.0.0.1", "*.localhost.floci.io");- CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);- Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());- Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());- Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),- OBJECT_MAPPER.writeValueAsString(CertificateMetadata.create(sans, "dev")));- } catch (IOException e) {- throw new IllegalStateException("could not prepare the TLS fixtures", e);- }- }-- @Override- public Map<String, String> getConfigOverrides() {- return Map.ofEntries(- Map.entry("floci.tls.enabled", "true"),- Map.entry("floci.tls.self-signed", "true"),- Map.entry("floci.tls.aws-https-port", "0"),- Map.entry("floci.storage.persistent-path", DATA_DIR.toString()),- Map.entry("quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString()),- Map.entry("quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString()),- Map.entry("quarkus.http.insecure-requests", "enabled"),- Map.entry("floci.services.iot.mqtt.enabled", "true"),- Map.entry("floci.services.iot.mqtt.auto-start", "true"),- Map.entry("floci.services.iot.mqtt.host", "127.0.0.1"),- Map.entry("floci.services.iot.mqtt.port", Integer.toString(PLAIN_PORT)),- Map.entry("floci.services.iot.mqtt.tls-port", Integer.toString(TLS_PORT)));- }- }}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttTlsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttTlsIntegrationTest.javaindex e758f9f317..aa041696f3 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttTlsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttTlsIntegrationTest.java@@ -1,13 +1,10 @@package io.github.hectorvent.floci.services.iot;import com.fasterxml.jackson.databind.ObjectMapper;-import io.github.hectorvent.floci.config.CertificateMetadata;-import io.github.hectorvent.floci.config.FlociCertificateAuthority;import io.github.hectorvent.floci.config.TlsCertificateManager;-import io.github.hectorvent.floci.services.acm.CertificateGenerator;-import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.testing.IotMqttTlsProfile;+import io.github.hectorvent.floci.testing.PartitionCleanup;import io.quarkus.test.junit.QuarkusTest;-import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;import jakarta.inject.Inject;import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;@@ -18,21 +15,19 @@ import org.eclipse.paho.client.mqttv3.MqttException;import org.eclipse.paho.client.mqttv3.MqttMessage;import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.RegisterExtension;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLHandshakeException;import javax.net.ssl.SSLParameters;import javax.net.ssl.SSLSocket;-import java.io.IOException;import java.net.Socket;import java.nio.charset.StandardCharsets;-import java.nio.file.Files;import java.nio.file.Path;import java.security.cert.X509Certificate;import java.time.Duration;import java.time.Instant;import java.util.List;-import java.util.Map;import java.util.Set;import java.util.TreeSet;import java.util.concurrent.BlockingQueue;@@ -57,17 +52,16 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* broker behaviour as the plaintext listener.*/@QuarkusTest-@TestProfile(IotMqttTlsIntegrationTest.Profile.class)+@TestProfile(IotMqttTlsProfile.class)class IotMqttTlsIntegrationTest {- static final Path DATA_DIR = Path.of("target", "floci-iot-mqtt-tls-test").toAbsolutePath();- static final Path TLS_DIR = DATA_DIR.resolve("tls");- static final int PLAIN_PORT = 18834;- static final int TLS_PORT = 18835;+ static final Path TLS_DIR = Path.of(IotMqttTlsProfile.TLS_DIR);+ static final int PLAIN_PORT = IotMqttTlsProfile.PLAIN_PORT;+ 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 IotDeviceIdentity device;+ private static final String CONNECT_ANY_CLIENT =+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"iot:Connect\",\"Resource\":\"arn:aws:iot:*:*:client/*\"}]}";@InjectTlsCertificateManager certificateManager;@@ -75,35 +69,36 @@ class IotMqttTlsIntegrationTest {@InjectIotMqttBrokerService broker;+ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();++ private IotDeviceIdentity device;+/*** One registered device with a policy allowing iot:Connect for any client id, shared by the- * TLS clients. Provisioned by the first test that needs it: RestAssured is pointed at the- * test port before each test, not before the class.+ * TLS clients of a test and removed after it. Provisioned on first use, since the plaintext+ * tests need none.*/- private static synchronized IotDeviceIdentity device() {+ private IotDeviceIdentity device() {if (device == null) {- IotDeviceIdentity provisioned = IotDeviceIdentity.provision(true);- String policy = "tls-roundtrip-" + System.nanoTime();- given()- .contentType("application/json")- .body(OBJECT_MAPPER.createObjectNode().put("policyDocument",- "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"iot:Connect\",\"Resource\":\"arn:aws:iot:*:*:client/*\"}]}").toString())- .when().post("/policies/" + policy)- .then().statusCode(200);- given().queryParam("target", provisioned.certificateArn).when().put("/target-policies/" + policy).then().statusCode(200);- device = provisioned;+ device = IotDeviceIdentity.provision(true, cleanup);+ device.attachNewPolicy(CONNECT_ANY_CLIENT, cleanup);}return device;}+ private TlsClient connectTls(String clientId) throws Exception {+ return TlsClient.connect(clientId, device().sslContext(TLS_DIR));+ }+@Testvoid connectSubscribePublishOverTlsTrustingOnlyTheFlociCa() throws Exception {String topic = "tls/roundtrip/" + System.nanoTime();byte[] payload = "hello over 8883".getBytes(StandardCharsets.UTF_8);- try (TlsClient subscriber = TlsClient.connect("tls-sub-" + System.nanoTime())) {+ try (TlsClient subscriber = connectTls("tls-sub-" + System.nanoTime())) {subscriber.subscribe(topic, 1);- try (TlsClient publisher = TlsClient.connect("tls-pub-" + System.nanoTime())) {+ try (TlsClient publisher = connectTls("tls-pub-" + System.nanoTime())) {publisher.publish(topic, payload, 1);}assertArrayEquals(payload, subscriber.takePayload());@@ -132,7 +127,7 @@ class IotMqttTlsIntegrationTest {void aRegisteredDeviceIsAdmittedAndTheSessionIsVisibleToTheConnectionApi() throws Exception {String clientId = "tls-device-" + System.nanoTime();- try (TlsClient client = TlsClient.connect(clientId)) {+ try (TlsClient client = connectTls(clientId)) {assertTrue(client.isConnected());given().queryParam("includeSocketInformation", true)@@ -177,6 +172,7 @@ class IotMqttTlsIntegrationTest {assertThrows(SSLHandshakeException.class, () -> handshakeVerifying(LEARNED_HOST),"precondition: a device verifying the custom domain rejects the boot leaf");+ cleanup.register(certificateManager::clear);certificateManager.ensureHost(LEARNED_HOST);Set<String> sans = sans(handshakeVerifying(LEARNED_HOST));@@ -188,7 +184,7 @@ class IotMqttTlsIntegrationTest {void aClientIdReconnectingOnThePlaintextListenerTakesOverTheTlsSession() throws Exception {String clientId = "tls-takeover-" + System.nanoTime();- try (TlsClient first = TlsClient.connect(clientId)) {+ try (TlsClient first = connectTls(clientId)) {MqttClient second = new MqttClient("tcp://127.0.0.1:" + PLAIN_PORT, clientId, new MemoryPersistence());try {second.connect();@@ -204,11 +200,12 @@ class IotMqttTlsIntegrationTest {@Testvoid shadowUpdateOverTlsPublishesTheAcceptedResponseOverTls() throws Exception {String thing = "tlsThing" + System.nanoTime();- try (TlsClient subscriber = TlsClient.connect("tls-shadow-sub-" + System.nanoTime())) {+ try (TlsClient subscriber = connectTls("tls-shadow-sub-" + System.nanoTime())) {subscriber.subscribe("$aws/things/" + thing + "/shadow/update/accepted", 0);- try (TlsClient publisher = TlsClient.connect("tls-shadow-pub-" + System.nanoTime())) {+ try (TlsClient publisher = connectTls("tls-shadow-pub-" + System.nanoTime())) {publisher.publish("$aws/things/" + thing + "/shadow/update","{\"state\":{\"desired\":{\"color\":\"blue\"}},\"clientToken\":\"tls-token\"}".getBytes(StandardCharsets.UTF_8), 0);+ cleanup.register(() -> given().when().delete("/things/" + thing + "/shadow").then().statusCode(200));}String accepted = new String(subscriber.takePayload(), StandardCharsets.UTF_8);assertEquals("blue", OBJECT_MAPPER.readTree(accepted).path("state").path("desired").path("color").asText());@@ -221,9 +218,9 @@ class IotMqttTlsIntegrationTest {String topic = "tls/limit/" + System.nanoTime();byte[] payload = randomPayload(AWS_MAX_PAYLOAD);- try (TlsClient subscriber = TlsClient.connect("tls-limit-sub-" + System.nanoTime())) {+ try (TlsClient subscriber = connectTls("tls-limit-sub-" + System.nanoTime())) {subscriber.subscribe(topic, 1);- try (TlsClient publisher = TlsClient.connect("tls-limit-pub-" + System.nanoTime())) {+ try (TlsClient publisher = connectTls("tls-limit-pub-" + System.nanoTime())) {publisher.publish(topic, payload, 1);}assertArrayEquals(payload, subscriber.takePayload());@@ -235,13 +232,13 @@ class IotMqttTlsIntegrationTest {String topic = "tls/over-limit/" + System.nanoTime();byte[] after = "after".getBytes(StandardCharsets.UTF_8);- try (TlsClient subscriber = TlsClient.connect("tls-over-sub-" + System.nanoTime())) {+ try (TlsClient subscriber = connectTls("tls-over-sub-" + System.nanoTime())) {subscriber.subscribe(topic, 1);- try (TlsClient publisher = TlsClient.connect("tls-over-pub-" + System.nanoTime())) {+ try (TlsClient publisher = connectTls("tls-over-pub-" + System.nanoTime())) {assertThrows(MqttException.class, () -> publisher.publish(topic, randomPayload(AWS_MAX_PAYLOAD + 1), 1));publisher.awaitDisconnected();}- try (TlsClient next = TlsClient.connect("tls-over-next-" + System.nanoTime())) {+ try (TlsClient next = connectTls("tls-over-next-" + System.nanoTime())) {next.publish(topic, after, 0);}assertArrayEquals(after, subscriber.takePayload(), "the oversized publish is never delivered");@@ -253,7 +250,7 @@ class IotMqttTlsIntegrationTest {broker.stop();broker.startIfEnabled();- try (TlsClient client = TlsClient.connect("tls-restart-" + System.nanoTime())) {+ try (TlsClient client = connectTls("tls-restart-" + System.nanoTime())) {assertTrue(client.isConnected());}}@@ -296,7 +293,7 @@ class IotMqttTlsIntegrationTest {this.client = client;}- static TlsClient connect(String clientId) throws Exception {+ static TlsClient connect(String clientId, SSLContext deviceContext) throws Exception {MqttClient client = new MqttClient("ssl://127.0.0.1:" + TLS_PORT, clientId, new MemoryPersistence());client.setTimeToWait(10_000);TlsClient tlsClient = new TlsClient(client);@@ -318,7 +315,7 @@ class IotMqttTlsIntegrationTest {options.setCleanSession(true);options.setConnectionTimeout(10);options.setAutomaticReconnect(false);- options.setSocketFactory(device().sslContext(TLS_DIR).getSocketFactory());+ options.setSocketFactory(deviceContext.getSocketFactory());client.connect(options);return tlsClient;}@@ -360,48 +357,4 @@ class IotMqttTlsIntegrationTest {client.close();}}-- /**- * TLS on with a CA-issued leaf on disk, as TlsConfigSource leaves it in production. The- * bootstrap reads system properties, not profile overrides, so the profile lays the files- * down itself and points the TLS registry's default entry at them. The leaf carries- * {@code 127.0.0.1} so Paho's hostname verification passes against {@code ssl://127.0.0.1}.- */- public static final class Profile implements QuarkusTestProfile {-- static {- try {- Files.createDirectories(TLS_DIR);- for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {- Files.deleteIfExists(TLS_DIR.resolve(name));- }- FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);- List<String> sans = List.of("localhost", "127.0.0.1", "*.localhost.floci.io");- CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);- Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());- Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());- Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),- OBJECT_MAPPER.writeValueAsString(CertificateMetadata.create(sans, "dev")));- } catch (IOException e) {- throw new IllegalStateException("could not prepare the TLS fixtures", e);- }- }-- @Override- public Map<String, String> getConfigOverrides() {- return Map.ofEntries(- Map.entry("floci.tls.enabled", "true"),- Map.entry("floci.tls.self-signed", "true"),- Map.entry("floci.tls.aws-https-port", "0"),- Map.entry("floci.storage.persistent-path", DATA_DIR.toString()),- Map.entry("quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString()),- Map.entry("quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString()),- Map.entry("quarkus.http.insecure-requests", "enabled"),- Map.entry("floci.services.iot.mqtt.enabled", "true"),- Map.entry("floci.services.iot.mqtt.auto-start", "true"),- Map.entry("floci.services.iot.mqtt.host", "127.0.0.1"),- Map.entry("floci.services.iot.mqtt.port", Integer.toString(PLAIN_PORT)),- Map.entry("floci.services.iot.mqtt.tls-port", Integer.toString(TLS_PORT)));- }- }}diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketContractIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketContractIntegrationTest.javaindex 1ff5aff6d0..f809c0b741 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketContractIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketContractIntegrationTest.java@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.iot;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.testing.IotMqttTlsProfile;+import io.github.hectorvent.floci.testing.PartitionCleanup;import io.quarkus.test.junit.QuarkusTest;import io.quarkus.test.junit.TestProfile;import org.eclipse.microprofile.config.inject.ConfigProperty;@@ -17,6 +19,7 @@ import org.eclipse.paho.mqttv5.client.MqttDisconnectResponse;import org.eclipse.paho.mqttv5.common.packet.MqttProperties;import org.jboss.logging.Logger;import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.RegisterExtension;import java.io.BufferedReader;import java.io.InputStreamReader;@@ -52,18 +55,22 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* covered by {@link IotMqttWebSocketFramingIntegrationTest}.*/@QuarkusTest-@TestProfile(IotMqttWebSocketIntegrationTest.Profile.class)+@TestProfile(IotMqttTlsProfile.class)class IotMqttWebSocketContractIntegrationTest {private static final Logger LOG = Logger.getLogger(IotMqttWebSocketContractIntegrationTest.class);private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();- private static final int PLAIN_PORT = IotMqttWebSocketIntegrationTest.PLAIN_PORT;+ private static final int PLAIN_PORT = IotMqttTlsProfile.PLAIN_PORT;+@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")int testSslPort;@ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0")int testHttpPort;+ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();+// ==================== Handshake ====================@Test@@ -122,6 +129,7 @@ class IotMqttWebSocketContractIntegrationTest {.then().statusCode(201).extract().path("apiId");+ cleanup.register(() -> given().when().delete("/v2/apis/" + apiId).then().statusCode(204));given().contentType("application/json").body("{\"stageName\":\"probe\"}")@@ -256,6 +264,8 @@ class IotMqttWebSocketContractIntegrationTest {MqttClient tcp = new MqttClient("tcp://127.0.0.1:" + PLAIN_PORT, "retain-pub-" + System.nanoTime(), new MemoryPersistence());tcp.connect();tcp.publish(topic, payload, 1, true);+ // A retained publish with an empty payload deletes the topic's retained message.+ cleanup.register(() -> given().queryParam("retain", true).when().post("/topics/" + topic).then().statusCode(200));tcp.disconnect();tcp.close();@@ -286,6 +296,7 @@ class IotMqttWebSocketContractIntegrationTest {client.client.subscribe("$aws/things/" + thing + "/shadow/update/accepted", 1);client.client.publish("$aws/things/" + thing + "/shadow/update","{\"state\":{\"desired\":{\"led\":\"on\"}},\"clientToken\":\"ws-token\"}".getBytes(StandardCharsets.UTF_8), 1, false);+ cleanup.register(() -> given().when().delete("/things/" + thing + "/shadow").then().statusCode(200));JsonNode accepted = OBJECT_MAPPER.readTree(client.take());assertEquals("on", accepted.path("state").path("desired").path("led").asText());@@ -297,6 +308,7 @@ class IotMqttWebSocketContractIntegrationTest {void topicRuleFiresForAWebSocketPublish() throws Exception {String source = "contract/rule/source/" + System.nanoTime();String target = "contract/rule/target/" + System.nanoTime();+ String rule = "wsRepublish" + System.nanoTime();given().contentType("application/json").body("""@@ -315,9 +327,10 @@ class IotMqttWebSocketContractIntegrationTest {}""".formatted(source, target)).when()- .put("/rules/wsRepublish" + System.nanoTime())+ .put("/rules/" + rule).then().statusCode(200);+ cleanup.register(() -> given().when().delete("/rules/" + rule).then().statusCode(200));try (PahoWs subscriber = PahoWs.connect(wss(), "rule-sub-" + System.nanoTime())) {subscriber.client.subscribe(target, 1);diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketFramingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketFramingIntegrationTest.javaindex 55d09f014d..300d40013d 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketFramingIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketFramingIntegrationTest.java@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.iot;+import io.github.hectorvent.floci.testing.IotMqttTlsProfile;import io.quarkus.test.junit.QuarkusTest;import io.quarkus.test.junit.TestProfile;import jakarta.inject.Inject;@@ -30,7 +31,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* and that a broken stream or an oversized frame ends the session rather than hanging it.*/@QuarkusTest-@TestProfile(IotMqttWebSocketIntegrationTest.Profile.class)+@TestProfile(IotMqttTlsProfile.class)class IotMqttWebSocketFramingIntegrationTest {private static final Logger LOG = Logger.getLogger(IotMqttWebSocketFramingIntegrationTest.class);diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketIntegrationTest.javaindex 670b904724..9771ba1583 100644--- a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttWebSocketIntegrationTest.java@@ -1,12 +1,7 @@package io.github.hectorvent.floci.services.iot;-import com.fasterxml.jackson.databind.ObjectMapper;-import io.github.hectorvent.floci.config.CertificateMetadata;-import io.github.hectorvent.floci.config.FlociCertificateAuthority;-import io.github.hectorvent.floci.services.acm.CertificateGenerator;-import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.github.hectorvent.floci.testing.IotMqttTlsProfile;import io.quarkus.test.junit.QuarkusTest;-import io.quarkus.test.junit.QuarkusTestProfile;import io.quarkus.test.junit.TestProfile;import jakarta.inject.Inject;import org.eclipse.microprofile.config.inject.ConfigProperty;@@ -20,8 +15,6 @@ import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;import org.junit.jupiter.api.Test;import javax.net.ssl.SSLContext;-import javax.net.ssl.TrustManagerFactory;-import java.io.IOException;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;@@ -30,12 +23,9 @@ import java.net.http.WebSocket;import java.net.http.WebSocketHandshakeException;import java.nio.ByteBuffer;import java.nio.charset.StandardCharsets;-import java.nio.file.Files;import java.nio.file.Path;-import java.security.KeyStore;import java.util.ArrayList;import java.util.List;-import java.util.Map;import java.util.concurrent.BlockingQueue;import java.util.concurrent.CompletableFuture;import java.util.concurrent.CompletionStage;@@ -64,14 +54,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;* like one on the plaintext TCP listener because that is where the frames end up.*/@QuarkusTest-@TestProfile(IotMqttWebSocketIntegrationTest.Profile.class)+@TestProfile(IotMqttTlsProfile.class)public class IotMqttWebSocketIntegrationTest {- static final Path DATA_DIR = Path.of("target", "floci-iot-mqtt-ws-test").toAbsolutePath();- static final Path TLS_DIR = DATA_DIR.resolve("tls");- static final int PLAIN_PORT = 18836;- static final int TLS_PORT = 18837;- private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();+ private static final int PLAIN_PORT = IotMqttTlsProfile.PLAIN_PORT;private static final short CLOSE_UNSUPPORTED_DATA = 1003;private static final int CHURN_THREADS = 10;@@ -393,14 +379,7 @@ public class IotMqttWebSocketIntegrationTest {}public static SSLContext trustOnlyFlociCa() throws Exception {- KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());- trust.load(null, null);- trust.setCertificateEntry("floci", FlociCertificateAuthority.loadOrCreate(TLS_DIR).certificate());- TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());- tmf.init(trust);- SSLContext ctx = SSLContext.getInstance("TLS");- ctx.init(null, tmf.getTrustManagers(), null);- return ctx;+ return IotDeviceIdentity.trustOnlySslContext(Path.of(IotMqttTlsProfile.TLS_DIR));}private static final class WsClient implements AutoCloseable {@@ -476,48 +455,4 @@ public class IotMqttWebSocketIntegrationTest {client.close();}}-- /**- * TLS on with a CA-issued leaf on disk, exactly what TlsConfigSource produces in production.- * TlsConfigSource reads system properties, not profile overrides, so the profile lays the files- * down and points the TLS registry at them. The broker's plaintext listener is the bridge's- * target.- */- public static final class Profile implements QuarkusTestProfile {-- static {- try {- Files.createDirectories(TLS_DIR);- for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {- Files.deleteIfExists(TLS_DIR.resolve(name));- }- FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(TLS_DIR);- List<String> sans = List.of("localhost", "127.0.0.1", "*.localhost.floci.io");- CertificateGenerator.GeneratedCertificate leaf = ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);- Files.writeString(TLS_DIR.resolve("floci-server.crt"), leaf.certificatePem());- Files.writeString(TLS_DIR.resolve("floci-server.key"), leaf.privateKeyPem());- Files.writeString(TLS_DIR.resolve("floci-server.metadata.json"),- OBJECT_MAPPER.writeValueAsString(CertificateMetadata.create(sans, "dev")));- } catch (IOException e) {- throw new IllegalStateException("could not prepare the TLS fixtures", e);- }- }-- @Override- public Map<String, String> getConfigOverrides() {- return Map.ofEntries(- Map.entry("floci.tls.enabled", "true"),- Map.entry("floci.tls.self-signed", "true"),- Map.entry("floci.tls.aws-https-port", "0"),- Map.entry("floci.storage.persistent-path", DATA_DIR.toString()),- Map.entry("quarkus.tls.key-store.pem.0.cert", TLS_DIR.resolve("floci-server.crt").toString()),- Map.entry("quarkus.tls.key-store.pem.0.key", TLS_DIR.resolve("floci-server.key").toString()),- Map.entry("quarkus.http.insecure-requests", "enabled"),- Map.entry("floci.services.iot.mqtt.enabled", "true"),- Map.entry("floci.services.iot.mqtt.auto-start", "true"),- Map.entry("floci.services.iot.mqtt.host", "127.0.0.1"),- Map.entry("floci.services.iot.mqtt.port", Integer.toString(PLAIN_PORT)),- Map.entry("floci.services.iot.mqtt.tls-port", Integer.toString(TLS_PORT)));- }- }}diff --git a/src/test/java/io/github/hectorvent/floci/testing/IotMqttTlsProfile.java b/src/test/java/io/github/hectorvent/floci/testing/IotMqttTlsProfile.javanew file mode 100644index 0000000000..29d85b3186--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/testing/IotMqttTlsProfile.java@@ -0,0 +1,103 @@+package io.github.hectorvent.floci.testing;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.config.CertificateMetadata;+import io.github.hectorvent.floci.config.FlociCertificateAuthority;+import io.github.hectorvent.floci.services.acm.CertificateGenerator;+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;+import io.quarkus.test.junit.QuarkusTestProfile;++import java.io.IOException;+import java.nio.file.Files;+import java.nio.file.Path;+import java.util.List;+import java.util.Map;++/**+ * The IoT MQTT broker started at boot on a plaintext and a TLS listener, with TLS on in Floci's+ * self-signed mode, for the classes that test what devices reach: the TLS and mutual TLS+ * listeners, MQTT over WebSocket on the HTTP and HTTPS ports, custom authorizers and the plain+ * broker. Quarkus builds the application once per distinct profile class, so they share one+ * rather than each declaring their own.+ *+ * <p>Under {@code @QuarkusTest} the server serves the leaf this class writes before boot, issued by+ * the local CA in {@link #TLS_DIR}, as TlsConfigSource leaves it in production. TlsConfigSource+ * reads system properties, not profile overrides, so the profile lays the files down itself and+ * points the TLS registry's default entry at them. The leaf carries {@code 127.0.0.1}, so Paho's+ * hostname verification passes against {@code ssl://127.0.0.1} and {@code wss://127.0.0.1}. Its+ * wildcard covers one label below {@code localhost.floci.io}, so a name two labels below stays+ * uncovered until a test adds it. Each run writes a fresh leaf and metadata, which also drops+ * hostnames an earlier run learned at runtime. The CA is kept.+ *+ * <p>The overrides, and who relies on them:+ * <ul>+ * <li>{@code floci.tls.*} and the two {@code quarkus.tls.key-store} entries serve that leaf on+ * HTTPS and open the MQTT TLS listener, which Floci opens only while TLS is on. The TLS, mutual+ * TLS, {@code wss://} and custom authorizer tests connect through them.+ * {@code aws-https-port=0} keeps the TLS proxy from also binding 443, which an unprivileged test+ * JVM cannot do and no class here uses.</li>+ * <li>{@code floci.storage.persistent-path} is where the server keeps its TLS directory, so the CA+ * it signs with is the one the tests trust from {@link #TLS_DIR}.</li>+ * <li>{@code quarkus.http.insecure-requests} keeps plain HTTP served next to HTTPS, for RestAssured+ * and the {@code ws://} tests.</li>+ * <li>The {@code floci.services.iot.mqtt} entries start the broker at boot on fixed loopback ports,+ * which every class dials. They differ from the ports of the other MQTT test profiles.</li>+ * </ul>+ *+ * <p>The TLS listener admits only registered device certificates whose policy allows the connect,+ * and the plaintext one stays permissive; the WebSocket bridge hands its sessions to the plaintext+ * listener. A class that only uses the plaintext listener and plain HTTP, such as+ * {@code IotMqttEnabledIntegrationTest}, never reaches the TLS listener or the HTTPS port, so TLS+ * is inert for it.+ *+ * <p>The paths and ports are compile-time constants so a test can use them without initializing+ * this class, which would write a new leaf under the running application.+ */+public class IotMqttTlsProfile implements QuarkusTestProfile {++ public static final String DATA_DIR = "target/floci-iot-mqtt-tls-test";++ public static final String TLS_DIR = DATA_DIR + "/tls";++ public static final int PLAIN_PORT = 18834;++ public static final int TLS_PORT = 18835;++ static {+ Path tlsDir = Path.of(TLS_DIR);+ try {+ Files.createDirectories(tlsDir);+ for (String name : List.of("floci-server.crt", "floci-server.key", "floci-server.metadata.json")) {+ Files.deleteIfExists(tlsDir.resolve(name));+ }+ FlociCertificateAuthority ca = FlociCertificateAuthority.loadOrCreate(tlsDir);+ List<String> sans = List.of("localhost", "127.0.0.1", "*.localhost.floci.io");+ CertificateGenerator.GeneratedCertificate leaf =+ ca.issueServerCertificate("localhost", sans, KeyAlgorithm.RSA_2048, null);+ Files.writeString(tlsDir.resolve("floci-server.crt"), leaf.certificatePem());+ Files.writeString(tlsDir.resolve("floci-server.key"), leaf.privateKeyPem());+ Files.writeString(tlsDir.resolve("floci-server.metadata.json"),+ new ObjectMapper().writeValueAsString(CertificateMetadata.create(sans, "dev")));+ } catch (IOException e) {+ throw new IllegalStateException("Could not prepare the TLS fixtures in " + tlsDir, e);+ }+ }++ @Override+ public Map<String, String> getConfigOverrides() {+ Path tlsDir = Path.of(TLS_DIR).toAbsolutePath();+ return Map.ofEntries(+ Map.entry("floci.tls.enabled", "true"),+ Map.entry("floci.tls.self-signed", "true"),+ Map.entry("floci.tls.aws-https-port", "0"),+ Map.entry("floci.storage.persistent-path", Path.of(DATA_DIR).toAbsolutePath().toString()),+ Map.entry("quarkus.tls.key-store.pem.0.cert", tlsDir.resolve("floci-server.crt").toString()),+ Map.entry("quarkus.tls.key-store.pem.0.key", tlsDir.resolve("floci-server.key").toString()),+ Map.entry("quarkus.http.insecure-requests", "enabled"),+ Map.entry("floci.services.iot.mqtt.enabled", "true"),+ Map.entry("floci.services.iot.mqtt.auto-start", "true"),+ Map.entry("floci.services.iot.mqtt.host", "127.0.0.1"),+ Map.entry("floci.services.iot.mqtt.port", Integer.toString(PLAIN_PORT)),+ Map.entry("floci.services.iot.mqtt.tls-port", Integer.toString(TLS_PORT)));+ }+}