fix(iot): answer MQTT shadow topics in the device's account and region (#9623)

A shadow request published on a $aws/things/.../shadow topic always read
and wrote the shadow of the default account and region, so a device whose
certificate is registered in another region updated a shadow that
GetThingShadow in its own region never saw. The broker session already
carries the account and region of the device's certificate; the reserved
topic handler now takes them and reads, writes and deletes the shadow
there. A plaintext session keeps the default account and region, as
before.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-27 18:52:01 -04:00
1 parent 4e2bd570b5
commit b3f1c508a1
5 files changed
+110 -38

No files matched your search

@@ -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;
}
@@ -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);
}
@@ -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. */
@@ -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();
@@ -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<Runnable> 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");