mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iot): keep MQTT shadow replies, rules and saved shadows in the shadow's account (#9629)
#9623 moved MQTT shadow requests to the device certificate's account and Region, but the broker still fanned each shadow reply out to every live session whose subscription matched, so a device of another account received the shadow's document. Shadow replies now go only to the sessions of the shadow's account and Region, as AWS keeps each account's topic namespace apart in each Region, and a message with no owner counts in the default account and Region rather than in all of them. Shadow events also evaluated their topic rules on the broker's rule worker with no request scope, so the default account's rules fired and the device account's never did. Each shadow event now evaluates its rules, and runs their actions, as the shadow's account and Region. The shadow paths now read, write and delete as the shadow's account. A shadow saved before stores kept accounts apart sits under its bare key and belongs to the default account, so only the default account finds it and moves it under its own key on that first read. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
fd2eef7f74
commit
fb03dff2a5
5 files changed
+256
-41
No files matched your search
@@ -66,6 +66,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -395,6 +396,19 @@ public class IotMqttBrokerService implements Resettable {
|
||||
fanOut(topic, payload, qos, MqttProperties.NO_PROPERTIES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivers {@code payload} at QoS 0 only to the live sessions of {@code accountId} in {@code region}, for a
|
||||
* message that carries one account's data, as a shadow reply does: AWS gives each account a broker of its own
|
||||
* in each region. A plaintext session counts in the default account and region.
|
||||
*/
|
||||
void publishInAccount(String accountId, String region, String topic, byte[] payload) {
|
||||
// Fails closed: a message without an owner counts in the default account and region, never in all of them.
|
||||
String owner = accountId != null ? accountId : config.defaultAccountId();
|
||||
String ownerRegion = region != null ? region : config.defaultRegion();
|
||||
fanOut(topic, payload, 0, MqttProperties.NO_PROPERTIES,
|
||||
session -> owner.equals(session.accountId()) && ownerRegion.equals(session.region()));
|
||||
}
|
||||
|
||||
boolean disconnectClient(String clientId, boolean cleanSession) {
|
||||
ClientSession session;
|
||||
synchronized (sessionLock) {
|
||||
@@ -932,6 +946,11 @@ public class IotMqttBrokerService implements Resettable {
|
||||
* {@code iot:Receive} is checked when it is delivered on the reconnect.
|
||||
*/
|
||||
private void fanOut(String topic, byte[] payload, int qos, MqttProperties properties) {
|
||||
fanOut(topic, payload, qos, properties, session -> true);
|
||||
}
|
||||
|
||||
private void fanOut(String topic, byte[] payload, int qos, MqttProperties properties,
|
||||
Predicate<ClientSession> audience) {
|
||||
byte[] safePayload = payload == null ? new byte[0] : payload.clone();
|
||||
if (qos > 0) {
|
||||
storedSessions.forEach((key, stored) -> {
|
||||
@@ -948,7 +967,8 @@ public class IotMqttBrokerService implements Resettable {
|
||||
for (ClientSession session : sessionsByClient.values()) {
|
||||
Map<String, Subscription> subscriptions = subscriptionsByClient.get(session.clientId());
|
||||
int granted = subscriptions == null ? -1 : grantedQos(subscriptions.values(), topic);
|
||||
if (!session.endpoint().isConnected() || granted < 0 || !isAllowed(session, "iot:Receive", "topic/" + topic)) {
|
||||
if (!session.endpoint().isConnected() || granted < 0 || !audience.test(session)
|
||||
|| !isAllowed(session, "iot:Receive", "topic/" + topic)) {
|
||||
continue;
|
||||
}
|
||||
MqttQoS delivered = MqttQoS.valueOf(Math.min(qos, granted));
|
||||
|
||||
@@ -14,6 +14,7 @@ import io.floci.aws.core.common.CertificateMaterialException;
|
||||
import io.floci.aws.core.common.Digests;
|
||||
import io.floci.aws.core.common.Pem;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.common.SmithyValidationErrors;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.StorageBackend;
|
||||
@@ -954,7 +955,7 @@ public class IotService {
|
||||
|
||||
/** 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))
|
||||
IotShadow shadow = shadowIn(accountId, shadowKey(region, thingName, shadowName))
|
||||
.orElseThrow(() -> shadowNotFound(thingName));
|
||||
ObjectNode document = storedShadowDocument(shadow);
|
||||
ObjectNode state = (ObjectNode) document.get("state");
|
||||
@@ -986,10 +987,10 @@ public class IotService {
|
||||
update = writeShadowUpdate(thingName, shadowName, request, accountId, region);
|
||||
}
|
||||
ReservedShadowTopic topics = new ReservedShadowTopic(thingName, shadowName, "update");
|
||||
publishShadowEvent(topics.acceptedTopic(), update.accepted(), region, ruleRunner);
|
||||
publishShadowEvent(topics.documentsTopic(), update.documents(), region, ruleRunner);
|
||||
publishShadowEvent(topics.acceptedTopic(), update.accepted(), accountId, region, ruleRunner);
|
||||
publishShadowEvent(topics.documentsTopic(), update.documents(), accountId, region, ruleRunner);
|
||||
if (update.delta() != null) {
|
||||
publishShadowEvent(topics.deltaTopic(), update.delta(), region, ruleRunner);
|
||||
publishShadowEvent(topics.deltaTopic(), update.delta(), accountId, region, ruleRunner);
|
||||
}
|
||||
return update.accepted();
|
||||
}
|
||||
@@ -1004,14 +1005,14 @@ public class IotService {
|
||||
ObjectNode accepted = objectMapper.createObjectNode();
|
||||
synchronized (shadowWriteLock) {
|
||||
String key = shadowKey(region, thingName, shadowName);
|
||||
IotShadow shadow = getInAccount(shadowStore, accountId, key).orElseThrow(() -> shadowNotFound(thingName));
|
||||
IotShadow shadow = shadowIn(accountId, key).orElseThrow(() -> shadowNotFound(thingName));
|
||||
deleteInAccount(shadowStore, accountId, key);
|
||||
accepted.put("version", shadow.getVersion());
|
||||
}
|
||||
accepted.put("timestamp", Instant.now().getEpochSecond());
|
||||
withClientToken(accepted, clientToken);
|
||||
publishShadowEvent(new ReservedShadowTopic(thingName, shadowName, "delete").acceptedTopic(), accepted, region,
|
||||
ruleRunner);
|
||||
publishShadowEvent(new ReservedShadowTopic(thingName, shadowName, "delete").acceptedTopic(), accepted, accountId,
|
||||
region, ruleRunner);
|
||||
return accepted;
|
||||
}
|
||||
|
||||
@@ -1019,7 +1020,7 @@ public class IotService {
|
||||
private ShadowUpdate writeShadowUpdate(String thingName, String shadowName, JsonNode request, String accountId,
|
||||
String region) {
|
||||
String key = shadowKey(region, thingName, shadowName);
|
||||
IotShadow existing = getInAccount(shadowStore, accountId, key).orElse(null);
|
||||
IotShadow existing = shadowIn(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);
|
||||
@@ -1176,12 +1177,16 @@ public class IotService {
|
||||
|
||||
/**
|
||||
* Publishes one shadow response: fanned out to MQTT subscribers once, recorded once and
|
||||
* evaluated once against the topic rules of the shadow's region, as a message with no MQTT client.
|
||||
* evaluated once against the topic rules of the account and region that own the shadow, as a
|
||||
* message with no MQTT client. The rules and their actions run as that account in that region,
|
||||
* since a broker worker has no request of its own.
|
||||
*/
|
||||
private void publishShadowEvent(String topic, JsonNode payload, String region, Executor ruleRunner) {
|
||||
private void publishShadowEvent(String topic, JsonNode payload, String accountId, String region,
|
||||
Executor ruleRunner) {
|
||||
byte[] bytes = payload.toString().getBytes(StandardCharsets.UTF_8);
|
||||
mqttBrokerService.publish(topic, bytes);
|
||||
handlePublish(topic, bytes, true, region, null, ruleRunner);
|
||||
mqttBrokerService.publishInAccount(accountId, region, topic, bytes);
|
||||
handlePublish(topic, bytes, true, region, null,
|
||||
rules -> ruleRunner.execute(() -> RequestScopes.runAs(accountId, region, rules)));
|
||||
}
|
||||
|
||||
public List<String> listNamedShadowsForThing(String thingName, String region) {
|
||||
@@ -1695,7 +1700,7 @@ public class IotService {
|
||||
request = objectMapper.readTree(payload == null || payload.length == 0 ? "{}".getBytes(StandardCharsets.UTF_8) : payload);
|
||||
} catch (IOException e) {
|
||||
LOG.debugv("IoT shadow request on {0} is not JSON: {1}", topic, e.getMessage());
|
||||
publishShadowRejected(shadowTopic, 400, "Invalid JSON", null, region, ruleRunner);
|
||||
publishShadowRejected(shadowTopic, 400, "Invalid JSON", null, accountId, region, ruleRunner);
|
||||
return;
|
||||
}
|
||||
String clientToken = request.path("clientToken").asText(null);
|
||||
@@ -1706,28 +1711,30 @@ public class IotService {
|
||||
case "get" -> publishShadowEvent(shadowTopic.acceptedTopic(),
|
||||
withClientToken(getThingShadow(shadowTopic.thingName(), shadowTopic.shadowName(), accountId, region),
|
||||
clientToken),
|
||||
region, ruleRunner);
|
||||
accountId, 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);
|
||||
"Unsupported shadow operation: " + shadowTopic.operation(), clientToken, accountId, region,
|
||||
ruleRunner);
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
publishShadowRejected(shadowTopic, e.getHttpStatus(), e.getMessage(), clientToken, region, ruleRunner);
|
||||
publishShadowRejected(shadowTopic, e.getHttpStatus(), e.getMessage(), clientToken, accountId, region,
|
||||
ruleRunner);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "IoT shadow request on {0} failed", topic);
|
||||
publishShadowRejected(shadowTopic, 400, Objects.requireNonNullElse(e.getMessage(), e.getClass().getSimpleName()),
|
||||
clientToken, region, ruleRunner);
|
||||
clientToken, accountId, region, ruleRunner);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishShadowRejected(ReservedShadowTopic topic, int code, String message, String clientToken,
|
||||
String region, Executor ruleRunner) {
|
||||
String accountId, String region, Executor ruleRunner) {
|
||||
ObjectNode rejected = objectMapper.createObjectNode();
|
||||
rejected.put("code", code);
|
||||
rejected.put("message", message);
|
||||
withClientToken(rejected, clientToken);
|
||||
publishShadowEvent(topic.rejectedTopic(), rejected, region, ruleRunner);
|
||||
publishShadowEvent(topic.rejectedTopic(), rejected, accountId, region, ruleRunner);
|
||||
}
|
||||
|
||||
private void validateThingName(String thingName) {
|
||||
@@ -1798,6 +1805,19 @@ public class IotService {
|
||||
private String policyKey(String region, String policyName) { return "policy:" + region + ":" + policyName; }
|
||||
private String policyAttachmentKey(String region, String policyName) { return "policy-attachment:" + region + ":" + policyName; }
|
||||
private String thingPrincipalKey(String region, String thingName) { return "thing-principal:" + region + ":" + thingName; }
|
||||
/**
|
||||
* The shadow at {@code key} in {@code accountId}. A shadow saved before stores kept accounts apart sits under
|
||||
* its bare key and belongs to the default account only, so only the default account finds it, and moves it
|
||||
* under its own key on that first read; any other account finds nothing there.
|
||||
*/
|
||||
private Optional<IotShadow> shadowIn(String accountId, String key) {
|
||||
if (accountId != null && shadowStore instanceof AccountAwareStorageBackend<IotShadow> aware) {
|
||||
return aware.getForAccountMigratingLegacy(accountId, key,
|
||||
legacy -> aware.getLegacyForAccount(accountId, key).isPresent());
|
||||
}
|
||||
return shadowStore.get(key);
|
||||
}
|
||||
|
||||
private String shadowKey(String region, String thingName, String shadowName) {
|
||||
if (shadowName == null || shadowName.isEmpty()) {
|
||||
return "shadow:" + region + ":" + thingName + ":";
|
||||
|
||||
@@ -26,6 +26,7 @@ final class IotDeviceIdentity {
|
||||
|
||||
private static final char[] PASSWORD = "device".toCharArray();
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
private static final String DEFAULT_ACCESS_KEY = "test";
|
||||
|
||||
final String certificateId;
|
||||
final String certificateArn;
|
||||
@@ -33,19 +34,22 @@ final class IotDeviceIdentity {
|
||||
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;
|
||||
/** The access key every signed request about this device names; a 12-digit key signs as that account. */
|
||||
private final String accessKeyId;
|
||||
|
||||
private IotDeviceIdentity(String certificateId, String certificateArn, X509Certificate certificate, PrivateKey privateKey,
|
||||
String region) {
|
||||
String region, String accessKeyId) {
|
||||
this.certificateId = certificateId;
|
||||
this.certificateArn = certificateArn;
|
||||
this.certificate = certificate;
|
||||
this.privateKey = privateKey;
|
||||
this.region = region;
|
||||
this.accessKeyId = accessKeyId;
|
||||
}
|
||||
|
||||
/** Provisions a device over the REST API, as an onboarding flow does. */
|
||||
static IotDeviceIdentity provision(boolean active) {
|
||||
return provisionIn(null, active);
|
||||
return provisionIn(null, DEFAULT_ACCESS_KEY, active);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,13 +57,24 @@ final class IotDeviceIdentity {
|
||||
* {@code cleanup} deactivate and delete its certificate after the test.
|
||||
*/
|
||||
static IotDeviceIdentity provision(String region, boolean active, PartitionCleanup cleanup) {
|
||||
IotDeviceIdentity device = provisionIn(region, active);
|
||||
IotDeviceIdentity device = provisionIn(region, DEFAULT_ACCESS_KEY, active);
|
||||
cleanup.register(device::delete);
|
||||
return device;
|
||||
}
|
||||
|
||||
private static IotDeviceIdentity provisionIn(String region, boolean active) {
|
||||
JsonPath created = request(region)
|
||||
/**
|
||||
* Provisions a device in account {@code accountId} and {@code region}, every request about it
|
||||
* signed as that account for that region, and has {@code cleanup} deactivate and delete its
|
||||
* certificate after the test.
|
||||
*/
|
||||
static IotDeviceIdentity provisionInAccount(String accountId, String region, boolean active, PartitionCleanup cleanup) {
|
||||
IotDeviceIdentity device = provisionIn(region, accountId, active);
|
||||
cleanup.register(device::delete);
|
||||
return device;
|
||||
}
|
||||
|
||||
private static IotDeviceIdentity provisionIn(String region, String accessKeyId, boolean active) {
|
||||
JsonPath created = request(region, accessKeyId)
|
||||
.queryParam("setAsActive", active)
|
||||
.when().post("/keys-and-certificate")
|
||||
.then().statusCode(200)
|
||||
@@ -69,15 +84,15 @@ final class IotDeviceIdentity {
|
||||
created.getString("certificateArn"),
|
||||
Pem.parseCertificate(created.getString("certificatePem")),
|
||||
Pem.parsePrivateKey(created.getString("keyPair.PrivateKey")),
|
||||
region);
|
||||
region, accessKeyId);
|
||||
}
|
||||
|
||||
private static RequestSpecification request(String region) {
|
||||
return region == null ? given() : given().header("Authorization", auth("test", region, "iot"));
|
||||
private static RequestSpecification request(String region, String accessKeyId) {
|
||||
return region == null ? given() : given().header("Authorization", auth(accessKeyId, region, "iot"));
|
||||
}
|
||||
|
||||
private RequestSpecification request() {
|
||||
return request(region);
|
||||
return request(region, accessKeyId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,7 +146,8 @@ final class IotDeviceIdentity {
|
||||
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()), null);
|
||||
Pem.parseCertificate(issued.certificatePem()), Pem.parsePrivateKey(issued.privateKeyPem()), null,
|
||||
DEFAULT_ACCESS_KEY);
|
||||
}
|
||||
|
||||
/** Presents the device certificate and trusts only the Floci CA. */
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package io.floci.aws.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.config.TlsCertificateManager;
|
||||
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 io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
@@ -244,6 +246,111 @@ class IotMqttTlsIntegrationTest {
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shadowEventsOfADeviceInAnotherAccountFireThatAccountsRules() throws Exception {
|
||||
String account = "222222222222";
|
||||
String region = "us-east-1";
|
||||
long id = System.nanoTime();
|
||||
String thing = "tlsAccountThing" + id;
|
||||
String ownTarget = "tls/account/own/" + id;
|
||||
String defaultTarget = "tls/account/default/" + id;
|
||||
String acceptedTopic = "$aws/things/" + thing + "/shadow/update/accepted";
|
||||
IotDeviceIdentity otherAccountDevice = IotDeviceIdentity.provisionInAccount(account, region, true, cleanup);
|
||||
otherAccountDevice.attachNewPolicy(ALLOW_ALL_MQTT, cleanup);
|
||||
otherAccountDevice.attachNewThing(thing, cleanup);
|
||||
SSLContext otherAccountContext = otherAccountDevice.sslContext(TLS_DIR);
|
||||
String ownRule = "tlsAccountOwnRule" + id;
|
||||
String defaultRule = "tlsAccountDefaultRule" + id;
|
||||
putRepublishRule(auth(account, region, "iot"), ownRule, acceptedTopic, ownTarget, account);
|
||||
putRepublishRule(null, defaultRule, acceptedTopic, defaultTarget, "000000000000");
|
||||
|
||||
try (TlsClient subscriber = TlsClient.connect("tls-account-sub-" + id, otherAccountContext);
|
||||
TlsClient publisher = TlsClient.connect("tls-account-pub-" + id, otherAccountContext)) {
|
||||
subscriber.subscribe(ownTarget, 0);
|
||||
subscriber.subscribe(defaultTarget, 0);
|
||||
publisher.publish("$aws/things/" + thing + "/shadow/update",
|
||||
"{\"state\":{\"reported\":{\"color\":\"blue\"}}}".getBytes(StandardCharsets.UTF_8), 0);
|
||||
assertRepublishedColor(subscriber.take(), ownTarget, "blue");
|
||||
|
||||
// The broker runs every publish's rules on one worker in order, so the next update's rules run only after
|
||||
// the first update's have all run: whatever they republished arrives before the second update's.
|
||||
publisher.publish("$aws/things/" + thing + "/shadow/update",
|
||||
"{\"state\":{\"reported\":{\"color\":\"red\"}}}".getBytes(StandardCharsets.UTF_8), 0);
|
||||
assertRepublishedColor(subscriber.take(), ownTarget, "red");
|
||||
}
|
||||
cleanup.register(() -> given().header("Authorization", auth(account, region, "iotdata"))
|
||||
.when().delete("/things/" + thing + "/shadow").then().statusCode(200));
|
||||
}
|
||||
|
||||
/**
|
||||
* The broker answers a shadow request on its reserved topics with the shadow's document. Each account has its
|
||||
* own broker on AWS, so a device of another account subscribed to the same topics must not receive it.
|
||||
*/
|
||||
@Test
|
||||
void aShadowReplyReachesOnlyTheShadowsAccount() throws Exception {
|
||||
String account = "222222222222";
|
||||
String region = "us-east-1";
|
||||
long id = System.nanoTime();
|
||||
String thing = "tlsReplyThing" + id;
|
||||
String accepted = "$aws/things/" + thing + "/shadow/update/accepted";
|
||||
IotDeviceIdentity owner = IotDeviceIdentity.provisionInAccount(account, region, true, cleanup);
|
||||
owner.attachNewPolicy(ALLOW_ALL_MQTT, cleanup);
|
||||
owner.attachNewThing(thing, cleanup);
|
||||
SSLContext ownerContext = owner.sslContext(TLS_DIR);
|
||||
|
||||
try (TlsClient ownerSubscriber = TlsClient.connect("tls-reply-owner-" + id, ownerContext);
|
||||
TlsClient otherAccount = connectTls("tls-reply-other-" + id)) {
|
||||
ownerSubscriber.subscribe(accepted, 0);
|
||||
otherAccount.subscribe(accepted, 0);
|
||||
try (TlsClient publisher = TlsClient.connect("tls-reply-pub-" + id, ownerContext)) {
|
||||
publisher.publish("$aws/things/" + thing + "/shadow/update",
|
||||
"{\"state\":{\"reported\":{\"secret\":\"owner-only\"}}}".getBytes(StandardCharsets.UTF_8), 0);
|
||||
}
|
||||
String reply = new String(ownerSubscriber.takePayload(), StandardCharsets.UTF_8);
|
||||
assertEquals("owner-only", OBJECT_MAPPER.readTree(reply).path("state").path("reported").path("secret").asText());
|
||||
|
||||
// The default account's device then updates its own shadow of the same name. Its reply is the first
|
||||
// thing it receives only when the other account's reply never reached it.
|
||||
otherAccount.publish("$aws/things/" + thing + "/shadow/update",
|
||||
"{\"state\":{\"reported\":{\"secret\":\"default-own\"}}}".getBytes(StandardCharsets.UTF_8), 0);
|
||||
String next = new String(otherAccount.takePayload(), StandardCharsets.UTF_8);
|
||||
assertEquals("default-own", OBJECT_MAPPER.readTree(next).path("state").path("reported").path("secret").asText(),
|
||||
"a device of the default account received account " + account + "'s shadow reply");
|
||||
}
|
||||
cleanup.register(() -> given().header("Authorization", auth(account, region, "iotdata"))
|
||||
.when().delete("/things/" + thing + "/shadow").then().statusCode(200));
|
||||
cleanup.register(() -> given()
|
||||
.when().delete("/things/" + thing + "/shadow").then().statusCode(200));
|
||||
}
|
||||
|
||||
private static void assertRepublishedColor(TlsClient.Received received, String topic, String color)
|
||||
throws Exception {
|
||||
assertEquals(topic, received.topic(), "a rule of the default account fired on another account's shadow event");
|
||||
assertEquals(color, OBJECT_MAPPER.readTree(received.payload()).path("state").path("reported").path("color")
|
||||
.asText());
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a rule republishing every message on {@code sourceTopic} to {@code targetTopic}, signed
|
||||
* with {@code authorization} (unsigned when null), and has {@code cleanup} delete it after the test.
|
||||
*/
|
||||
private void putRepublishRule(String authorization, String ruleName, String sourceTopic, String targetTopic,
|
||||
String roleAccount) {
|
||||
ObjectNode body = OBJECT_MAPPER.createObjectNode();
|
||||
ObjectNode payload = body.putObject("topicRulePayload");
|
||||
payload.put("sql", "SELECT * FROM '" + sourceTopic + "'");
|
||||
payload.putArray("actions").addObject().putObject("republish")
|
||||
.put("roleArn", "arn:aws:iam::" + roleAccount + ":role/iot-rule-role")
|
||||
.put("topic", targetTopic);
|
||||
ruleRequest(authorization).contentType("application/json").body(body.toString())
|
||||
.when().put("/rules/" + ruleName).then().statusCode(200);
|
||||
cleanup.register(() -> ruleRequest(authorization).when().delete("/rules/" + ruleName).then().statusCode(200));
|
||||
}
|
||||
|
||||
private static RequestSpecification ruleRequest(String authorization) {
|
||||
return authorization == null ? given() : given().header("Authorization", authorization);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishOfTheAwsMaximumPayloadIsDeliveredOverTls() throws Exception {
|
||||
String topic = "tls/limit/" + System.nanoTime();
|
||||
@@ -318,7 +425,10 @@ class IotMqttTlsIntegrationTest {
|
||||
/** A Paho MQTT 3.1.1 client on {@code ssl://}, with Paho's default hostname verification on. */
|
||||
private static final class TlsClient implements AutoCloseable {
|
||||
private final MqttClient client;
|
||||
private final BlockingQueue<byte[]> payloads = new LinkedBlockingQueue<>();
|
||||
private final BlockingQueue<Received> received = new LinkedBlockingQueue<>();
|
||||
|
||||
record Received(String topic, byte[] payload) {
|
||||
}
|
||||
|
||||
private TlsClient(MqttClient client) {
|
||||
this.client = client;
|
||||
@@ -335,7 +445,7 @@ class IotMqttTlsIntegrationTest {
|
||||
|
||||
@Override
|
||||
public void messageArrived(String topic, MqttMessage message) {
|
||||
tlsClient.payloads.add(message.getPayload());
|
||||
tlsClient.received.add(new Received(topic, message.getPayload()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -364,9 +474,13 @@ class IotMqttTlsIntegrationTest {
|
||||
}
|
||||
|
||||
byte[] takePayload() throws InterruptedException {
|
||||
byte[] payload = payloads.poll(10, TimeUnit.SECONDS);
|
||||
assertNotNull(payload, "no publish received over TLS within 10s");
|
||||
return payload;
|
||||
return take().payload();
|
||||
}
|
||||
|
||||
Received take() throws InterruptedException {
|
||||
Received next = received.poll(10, TimeUnit.SECONDS);
|
||||
assertNotNull(next, "no publish received over TLS within 10s");
|
||||
return next;
|
||||
}
|
||||
|
||||
void awaitDisconnected() throws InterruptedException {
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.floci.aws.config.FlociCertificateAuthority;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.AccountAwareStorageBackend;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import io.floci.aws.services.acm.model.KeyAlgorithm;
|
||||
import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService;
|
||||
@@ -119,7 +120,9 @@ class IotServiceTest {
|
||||
private final CloudWatchLogsService logs = mock(CloudWatchLogsService.class);
|
||||
private final IotPublishEventRecorder recorder = new IotPublishEventRecorder();
|
||||
private final IotMqttBrokerService broker = mock(IotMqttBrokerService.class);
|
||||
private final AccountAwareStorageBackend<IotShadow> shadows = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
private final InMemoryStorage<String, IotShadow> shadowEntries = new InMemoryStorage<>();
|
||||
private final AccountAwareStorageBackend<IotShadow> shadows =
|
||||
new AccountAwareStorageBackend<>(shadowEntries, null, ACCOUNT);
|
||||
private IotService service;
|
||||
|
||||
@BeforeEach
|
||||
@@ -158,6 +161,48 @@ class IotServiceTest {
|
||||
new IamPolicyEvaluator(mapper));
|
||||
}
|
||||
|
||||
/**
|
||||
* A shadow saved before stores kept accounts apart sits under its bare key. It belongs to the default account,
|
||||
* so the shadow paths, which now name their account, still read, update and delete it.
|
||||
*/
|
||||
@Test
|
||||
void aShadowSavedBeforeAccountsWereKeptApartIsStillTheDefaultAccountsShadow() throws Exception {
|
||||
service.updateThingShadow("sensor-legacy", null, json("{\"state\":{\"reported\":{\"on\":true}}}"), REGION);
|
||||
String stored = shadowEntries.keys().stream().filter(key -> key.contains("sensor-legacy")).findFirst()
|
||||
.orElseThrow();
|
||||
String bare = stored.substring(stored.indexOf("shadow:"));
|
||||
shadowEntries.put(bare, shadowEntries.get(stored).orElseThrow());
|
||||
shadowEntries.delete(stored);
|
||||
|
||||
assertEquals(json("{\"on\":true}"), service.getThingShadow("sensor-legacy", null, REGION)
|
||||
.get("state").get("reported"));
|
||||
assertEquals(2, service.updateThingShadow("sensor-legacy", null,
|
||||
json("{\"state\":{\"reported\":{\"on\":false}}}"), REGION).get("version").asLong());
|
||||
service.deleteThingShadow("sensor-legacy", null, REGION);
|
||||
assertTrue(shadowEntries.keys().stream().noneMatch(key -> key.contains("sensor-legacy")),
|
||||
shadowEntries.keys().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* A bare-key shadow belongs to the default account only: another account asking for the same thing must not
|
||||
* read it, nor move it into its own partition, and the default account must still find it afterwards.
|
||||
*/
|
||||
@Test
|
||||
void anotherAccountNeitherReadsNorTakesTheDefaultAccountsLegacyShadow() throws Exception {
|
||||
service.updateThingShadow("sensor-owned", null, json("{\"state\":{\"reported\":{\"on\":true}}}"), REGION);
|
||||
String stored = shadowEntries.keys().stream().filter(key -> key.contains("sensor-owned")).findFirst()
|
||||
.orElseThrow();
|
||||
String bare = stored.substring(stored.indexOf("shadow:"));
|
||||
shadowEntries.put(bare, shadowEntries.get(stored).orElseThrow());
|
||||
shadowEntries.delete(stored);
|
||||
|
||||
AwsException notFound = assertThrows(AwsException.class,
|
||||
() -> service.getThingShadow("sensor-owned", null, "999999999999", REGION));
|
||||
assertEquals(404, notFound.getHttpStatus());
|
||||
assertEquals(json("{\"on\":true}"), service.getThingShadow("sensor-owned", null, REGION)
|
||||
.get("state").get("reported"));
|
||||
}
|
||||
|
||||
private IotTopicRule createRule(String name, String payloadJson) throws Exception {
|
||||
return service.createTopicRule(name, mapper.readTree(payloadJson), REGION);
|
||||
}
|
||||
@@ -908,7 +953,7 @@ class IotServiceTest {
|
||||
""".formatted(first, leaf(first))), recordedPayload(BUILDING_UPDATE + "/delta"));
|
||||
for (String topic : recordedTopics()) {
|
||||
ArgumentCaptor<byte[]> fannedOut = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(broker, times(1)).publish(eq(topic), fannedOut.capture());
|
||||
verify(broker, times(1)).publishInAccount(eq(ACCOUNT), eq(REGION), eq(topic), fannedOut.capture());
|
||||
assertEquals(recordedPayload(topic), mapper.readTree(fannedOut.getValue()));
|
||||
}
|
||||
|
||||
@@ -1328,7 +1373,7 @@ class IotServiceTest {
|
||||
assertEquals(2, deleted.get("version").asLong());
|
||||
assertEquals(List.of("$aws/things/sensor-4/shadow/delete/accepted"), recordedTopics());
|
||||
assertEquals(reparse(deleted), recordedPayload("$aws/things/sensor-4/shadow/delete/accepted"));
|
||||
verify(broker, times(1)).publish(eq("$aws/things/sensor-4/shadow/delete/accepted"), any());
|
||||
verify(broker, times(1)).publishInAccount(eq(ACCOUNT), eq(REGION), eq("$aws/things/sensor-4/shadow/delete/accepted"), any());
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.getThingShadow("sensor-4", null, REGION));
|
||||
assertEquals(404, e.getHttpStatus());
|
||||
}
|
||||
@@ -1458,7 +1503,7 @@ class IotServiceTest {
|
||||
/** The payload fanned out on the topic, verifying the broker received exactly one publish on it. */
|
||||
private JsonNode fannedOut(String topic) throws Exception {
|
||||
ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(broker, times(1)).publish(eq(topic), payload.capture());
|
||||
verify(broker, times(1)).publishInAccount(eq(ACCOUNT), eq(REGION), eq(topic), payload.capture());
|
||||
return mapper.readTree(payload.getValue());
|
||||
}
|
||||
|
||||
@@ -1474,7 +1519,7 @@ class IotServiceTest {
|
||||
assertEquals(recordedPayload(topic), fannedOut(topic));
|
||||
assertEquals("c-1", recordedPayload(topic).get("clientToken").asText());
|
||||
}
|
||||
verify(broker, times(3)).publish(anyString(), any());
|
||||
verify(broker, times(3)).publishInAccount(eq(ACCOUNT), eq(REGION), anyString(), any());
|
||||
assertEquals("blue", service.getThingShadow("sensor-7", "building", REGION).at("/state/desired/color").asText());
|
||||
}
|
||||
|
||||
@@ -1540,7 +1585,7 @@ class IotServiceTest {
|
||||
assertEquals(json("{\"code\":409,\"message\":\"Version conflict\",\"clientToken\":\"c-9\"}"),
|
||||
fannedOut("$aws/things/sensor-9/shadow/update/rejected"));
|
||||
assertEquals(List.of("$aws/things/sensor-9/shadow/update/rejected"), recordedTopics());
|
||||
verify(broker, times(1)).publish(anyString(), any());
|
||||
verify(broker, times(1)).publishInAccount(eq(ACCOUNT), eq(REGION), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user