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 74c7944fc2..31c9bf1a0c 100644 --- a/src/main/java/io/floci/aws/services/iot/IotMqttBrokerService.java +++ b/src/main/java/io/floci/aws/services/iot/IotMqttBrokerService.java @@ -834,7 +834,8 @@ public class IotMqttBrokerService implements Resettable { } if (topic.startsWith("$aws/")) { - iotService.get().handleReservedMqttPublish(topic, payload, rules -> evaluateRulesOnWorker(topic, rules)); + iotService.get().handleReservedMqttPublish(topic, payload, session.accountId(), session.region(), + rules -> evaluateRulesOnWorker(topic, rules)); return; } 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 b292164244..50aab166ec 100644 --- a/src/main/java/io/floci/aws/services/iot/IotService.java +++ b/src/main/java/io/floci/aws/services/iot/IotService.java @@ -80,7 +80,9 @@ import java.util.function.Predicate; import java.util.function.Supplier; import java.util.regex.Pattern; +import static io.floci.aws.core.storage.AccountAwareStorageBackend.deleteInAccount; import static io.floci.aws.core.storage.AccountAwareStorageBackend.getInAccount; +import static io.floci.aws.core.storage.AccountAwareStorageBackend.putInAccount; @ApplicationScoped public class IotService { @@ -947,7 +949,12 @@ public class IotService { * one, the stored metadata, the version and the current time. Publishes nothing. */ public JsonNode getThingShadow(String thingName, String shadowName, String region) { - IotShadow shadow = shadowStore.get(shadowKey(region, thingName, shadowName)) + return getThingShadow(thingName, shadowName, regionResolver.getAccountId(), region); + } + + /** The shadow as {@link #getThingShadow(String, String, String)} returns it, read in {@code accountId}. */ + JsonNode getThingShadow(String thingName, String shadowName, String accountId, String region) { + IotShadow shadow = getInAccount(shadowStore, accountId, shadowKey(region, thingName, shadowName)) .orElseThrow(() -> shadowNotFound(thingName)); ObjectNode document = storedShadowDocument(shadow); ObjectNode state = (ObjectNode) document.get("state"); @@ -964,7 +971,7 @@ public class IotService { } public JsonNode updateThingShadow(String thingName, String shadowName, JsonNode request, String region) { - return updateThingShadow(thingName, shadowName, request, region, Runnable::run); + return updateThingShadow(thingName, shadowName, request, regionResolver.getAccountId(), region, Runnable::run); } /** @@ -972,11 +979,11 @@ public class IotService { * UpdateThingShadow response, after publishing accepted, documents and, when desired and * reported differ, delta, each handing its rule evaluation to {@code ruleRunner}. */ - JsonNode updateThingShadow(String thingName, String shadowName, JsonNode request, String region, + JsonNode updateThingShadow(String thingName, String shadowName, JsonNode request, String accountId, String region, Executor ruleRunner) { ShadowUpdate update; synchronized (shadowWriteLock) { - update = writeShadowUpdate(thingName, shadowName, request, region); + update = writeShadowUpdate(thingName, shadowName, request, accountId, region); } ReservedShadowTopic topics = new ReservedShadowTopic(thingName, shadowName, "update"); publishShadowEvent(topics.acceptedTopic(), update.accepted(), region, ruleRunner); @@ -988,17 +995,17 @@ public class IotService { } public JsonNode deleteThingShadow(String thingName, String shadowName, String region) { - return deleteThingShadow(thingName, shadowName, null, region, Runnable::run); + return deleteThingShadow(thingName, shadowName, null, regionResolver.getAccountId(), region, Runnable::run); } /** Deletes the shadow and returns the delete/accepted document after publishing it. */ - JsonNode deleteThingShadow(String thingName, String shadowName, String clientToken, String region, - Executor ruleRunner) { + JsonNode deleteThingShadow(String thingName, String shadowName, String clientToken, String accountId, + String region, Executor ruleRunner) { ObjectNode accepted = objectMapper.createObjectNode(); synchronized (shadowWriteLock) { String key = shadowKey(region, thingName, shadowName); - IotShadow shadow = shadowStore.get(key).orElseThrow(() -> shadowNotFound(thingName)); - shadowStore.delete(key); + IotShadow shadow = getInAccount(shadowStore, accountId, key).orElseThrow(() -> shadowNotFound(thingName)); + deleteInAccount(shadowStore, accountId, key); accepted.put("version", shadow.getVersion()); } accepted.put("timestamp", Instant.now().getEpochSecond()); @@ -1009,9 +1016,10 @@ public class IotService { } /** The read-modify-write of one update; the caller holds {@link #shadowWriteLock}. */ - private ShadowUpdate writeShadowUpdate(String thingName, String shadowName, JsonNode request, String region) { + private ShadowUpdate writeShadowUpdate(String thingName, String shadowName, JsonNode request, String accountId, + String region) { String key = shadowKey(region, thingName, shadowName); - IotShadow existing = shadowStore.get(key).orElse(null); + IotShadow existing = getInAccount(shadowStore, accountId, key).orElse(null); long currentVersion = existing == null ? 0 : existing.getVersion(); if (request.hasNonNull("version") && request.path("version").asLong() != currentVersion) { throw new AwsException("ConflictException", "Version conflict", 409); @@ -1034,7 +1042,7 @@ public class IotService { shadow.setShadowName(blankToNull(shadowName)); shadow.setVersion(version); shadow.setDocument(document.toString()); - shadowStore.put(key, shadow); + putInAccount(shadowStore, accountId, key, shadow); ObjectNode accepted = objectMapper.createObjectNode(); if (!requestState.isMissingNode()) { @@ -1672,15 +1680,16 @@ public class IotService { } /** - * Answers a device shadow request published on an MQTT reserved topic. Every response goes - * through {@link #publishShadowEvent}, and a failure after the request parsed keeps its clientToken. + * Answers a device shadow request published on an MQTT reserved topic by a session of + * {@code accountId} in {@code region}, which own the shadow. Every response goes through + * {@link #publishShadowEvent}, and a failure after the request parsed keeps its clientToken. */ - void handleReservedMqttPublish(String topic, byte[] payload, Executor ruleRunner) { + void handleReservedMqttPublish(String topic, byte[] payload, String accountId, String region, + Executor ruleRunner) { ReservedShadowTopic shadowTopic = parseReservedShadowTopic(topic); if (shadowTopic == null) { return; } - String region = config.defaultRegion(); JsonNode request; try { request = objectMapper.readTree(payload == null || payload.length == 0 ? "{}".getBytes(StandardCharsets.UTF_8) : payload); @@ -1692,12 +1701,14 @@ public class IotService { String clientToken = request.path("clientToken").asText(null); try { switch (shadowTopic.operation()) { - case "update" -> updateThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), request, region, ruleRunner); - case "get" -> publishShadowEvent(shadowTopic.acceptedTopic(), - withClientToken(getThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), region), clientToken), + case "update" -> updateThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), request, accountId, region, ruleRunner); - case "delete" -> deleteThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), clientToken, region, - ruleRunner); + case "get" -> publishShadowEvent(shadowTopic.acceptedTopic(), + withClientToken(getThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), accountId, region), + clientToken), + region, ruleRunner); + case "delete" -> deleteThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), clientToken, + accountId, region, ruleRunner); default -> publishShadowRejected(shadowTopic, 400, "Unsupported shadow operation: " + shadowTopic.operation(), clientToken, region, ruleRunner); } 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 266b9d8f33..f2c5871e59 100644 --- a/src/test/java/io/floci/aws/services/iot/IotDeviceIdentity.java +++ b/src/test/java/io/floci/aws/services/iot/IotDeviceIdentity.java @@ -6,6 +6,7 @@ import io.floci.aws.core.common.Pem; import io.floci.aws.services.acm.CertificateGenerator; import io.floci.aws.testing.PartitionCleanup; import io.restassured.path.json.JsonPath; +import io.restassured.specification.RequestSpecification; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -17,6 +18,7 @@ import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import static io.floci.aws.testing.EnforcementFixtures.auth; import static io.restassured.RestAssured.given; /** A device provisioned through CreateKeysAndCertificate, ready to present itself on the TLS listener. */ @@ -29,17 +31,35 @@ final class IotDeviceIdentity { final String certificateArn; final X509Certificate certificate; final PrivateKey privateKey; + /** The region every request about this device is signed for; null sends them unsigned, to the default region. */ + private final String region; - private IotDeviceIdentity(String certificateId, String certificateArn, X509Certificate certificate, PrivateKey privateKey) { + private IotDeviceIdentity(String certificateId, String certificateArn, X509Certificate certificate, PrivateKey privateKey, + String region) { this.certificateId = certificateId; this.certificateArn = certificateArn; this.certificate = certificate; this.privateKey = privateKey; + this.region = region; } /** Provisions a device over the REST API, as an onboarding flow does. */ static IotDeviceIdentity provision(boolean active) { - JsonPath created = given() + return provisionIn(null, active); + } + + /** + * Provisions a device in {@code region}, every request about it signed for that region, and has + * {@code cleanup} deactivate and delete its certificate after the test. + */ + static IotDeviceIdentity provision(String region, boolean active, PartitionCleanup cleanup) { + IotDeviceIdentity device = provisionIn(region, active); + cleanup.register(device::delete); + return device; + } + + private static IotDeviceIdentity provisionIn(String region, boolean active) { + JsonPath created = request(region) .queryParam("setAsActive", active) .when().post("/keys-and-certificate") .then().statusCode(200) @@ -48,7 +68,16 @@ final class IotDeviceIdentity { created.getString("certificateId"), created.getString("certificateArn"), Pem.parseCertificate(created.getString("certificatePem")), - Pem.parsePrivateKey(created.getString("keyPair.PrivateKey"))); + Pem.parsePrivateKey(created.getString("keyPair.PrivateKey")), + region); + } + + private static RequestSpecification request(String region) { + return region == null ? given() : given().header("Authorization", auth("test", region, "iot")); + } + + private RequestSpecification request() { + return request(region); } /** @@ -67,16 +96,16 @@ final class IotDeviceIdentity { */ String attachNewPolicy(String document, PartitionCleanup cleanup) { String policy = "device-policy-" + System.nanoTime(); - given() + request() .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); + request().queryParam("target", certificateArn).when().post("/target-policies/" + policy).then().statusCode(200); + request().when().delete("/policies/" + policy).then().statusCode(200); }); - given().queryParam("target", certificateArn).when().put("/target-policies/" + policy).then().statusCode(200); + request().queryParam("target", certificateArn).when().put("/target-policies/" + policy).then().statusCode(200); return policy; } @@ -85,24 +114,24 @@ final class IotDeviceIdentity { * {@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) + request().contentType("application/json").body("{}").when().post("/things/" + thingName).then().statusCode(200); + cleanup.register(() -> request().when().delete("/things/" + thingName).then().statusCode(200)); + request().header("x-amzn-principal", certificateArn).when().put("/things/" + thingName + "/principals").then().statusCode(200); + cleanup.register(() -> request().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); - given().when().delete("/certificates/" + certificateId).then().statusCode(200); + request().queryParam("newStatus", "INACTIVE").when().put("/certificates/" + certificateId).then().statusCode(200); + request().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"); return new IotDeviceIdentity("unregistered", "arn:aws:iot:us-east-1:000000000000:cert/unregistered", - Pem.parseCertificate(issued.certificatePem()), Pem.parsePrivateKey(issued.privateKeyPem())); + Pem.parseCertificate(issued.certificatePem()), Pem.parsePrivateKey(issued.privateKeyPem()), null); } /** Presents the device certificate and trusts only the Floci CA. */ 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 96971664ee..6c0ee7eb7b 100644 --- a/src/test/java/io/floci/aws/services/iot/IotMqttTlsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iot/IotMqttTlsIntegrationTest.java @@ -37,6 +37,7 @@ import java.util.concurrent.TimeUnit; import static io.floci.aws.services.iot.IotMqttEnabledIntegrationTest.AWS_MAX_PAYLOAD; import static io.floci.aws.services.iot.IotMqttEnabledIntegrationTest.randomPayload; +import static io.floci.aws.testing.EnforcementFixtures.auth; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertArrayEquals; @@ -214,6 +215,35 @@ class IotMqttTlsIntegrationTest { } } + @Test + void shadowUpdateOverTlsFromADeviceInAnotherRegionLandsInThatRegion() throws Exception { + String region = "eu-west-1"; + String thing = "tlsRegionThing" + System.nanoTime(); + IotDeviceIdentity euDevice = IotDeviceIdentity.provision(region, true, cleanup); + euDevice.attachNewPolicy(ALLOW_ALL_MQTT, cleanup); + euDevice.attachNewThing(thing, cleanup); + SSLContext euContext = euDevice.sslContext(TLS_DIR); + + try (TlsClient subscriber = TlsClient.connect("tls-region-sub-" + System.nanoTime(), euContext)) { + subscriber.subscribe("$aws/things/" + thing + "/shadow/update/accepted", 0); + try (TlsClient publisher = TlsClient.connect("tls-region-pub-" + System.nanoTime(), euContext)) { + publisher.publish("$aws/things/" + thing + "/shadow/update", + "{\"state\":{\"reported\":{\"color\":\"green\"}}}".getBytes(StandardCharsets.UTF_8), 0); + } + assertNotNull(subscriber.takePayload()); + } + cleanup.register(() -> given().header("Authorization", auth("test", region, "iotdata")) + .when().delete("/things/" + thing + "/shadow").then().statusCode(200)); + + given().header("Authorization", auth("test", region, "iotdata")) + .when().get("/things/" + thing + "/shadow") + .then().statusCode(200) + .body("state.reported.color", equalTo("green")); + given() + .when().get("/things/" + thing + "/shadow") + .then().statusCode(404); + } + @Test void publishOfTheAwsMaximumPayloadIsDeliveredOverTls() throws Exception { String topic = "tls/limit/" + System.nanoTime(); diff --git a/src/test/java/io/floci/aws/services/iot/IotServiceTest.java b/src/test/java/io/floci/aws/services/iot/IotServiceTest.java index b8fd547575..26f838b0a1 100644 --- a/src/test/java/io/floci/aws/services/iot/IotServiceTest.java +++ b/src/test/java/io/floci/aws/services/iot/IotServiceTest.java @@ -1452,7 +1452,7 @@ class IotServiceTest { private void mqttShadowRequest(String topic, String payload) { Executor inline = Runnable::run; - service.handleReservedMqttPublish(topic, payload.getBytes(StandardCharsets.UTF_8), inline); + service.handleReservedMqttPublish(topic, payload.getBytes(StandardCharsets.UTF_8), ACCOUNT, REGION, inline); } /** The payload fanned out on the topic, verifying the broker received exactly one publish on it. */ @@ -1485,7 +1485,8 @@ class IotServiceTest { List deferred = new ArrayList<>(); service.handleReservedMqttPublish("$aws/things/sensor-10/shadow/update", - "{\"state\":{\"desired\":{\"color\":\"blue\"}}}".getBytes(StandardCharsets.UTF_8), deferred::add); + "{\"state\":{\"desired\":{\"color\":\"blue\"}}}".getBytes(StandardCharsets.UTF_8), ACCOUNT, REGION, + deferred::add); verifyNoInteractions(sqs); assertEquals(3, deferred.size(), "one rule evaluation per event");