feat(iot): verify device certificates on the MQTT TLS listener (#3180)

* feat(iot): registered-certificate lookup and iot:Connect evaluation

* feat(iot): verify device certificates and iot:Connect on the MQTT TLS listener

* docs(iot): device verification on the MQTT TLS listener

* test(iot): device evaluation over plain stores and under racing policy and thing changes

* fix(iot): remember where a device certificate was found and log refusals at debug

* fix(iot): treat any address literal in SNI as no domain name
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-07 13:08:39 -04:00
1 parent a1d0597ffe
commit 19a85360e1
10 files changed
+1729 -67

No files matched your search

+23 -7
View File
@@ -19,8 +19,7 @@ Supported MVP 1 behavior:
Current MVP 1 limitations:
- The MQTT listener does not verify device certificates yet.
- MQTT auth remains permissive; certificate and policy resources are modeled for provisioning compatibility, not enforced as broker authorization yet.
- The plaintext MQTT listener on 1883 stays permissive. The TLS listener on 8883 admits a device only when its certificate is registered and `ACTIVE` and an attached policy allows `iot:Connect` for the client id, see [Device verification on 8883](#device-verification-on-8883). `Publish`, `Subscribe` and `Receive` are not evaluated yet on either port.
- Rules evaluate the SQL subset described under [Rule SQL](#rule-sql); substitution templates remain follow-up scope.
## MVP 2 Coverage
@@ -79,8 +78,8 @@ Broker scope:
- Target real AWS IoT/device SDK style MQTT clients, not only handcrafted packet tests.
- Support MQTT v3 and MQTT 5 CONNECT handling used by local compatibility tests.
- Support QoS 0 and QoS 1 publish/subscribe behavior for the local AWS IoT slice.
- Serve MQTT over TLS on 8883 next to plaintext 1883 when TLS is enabled; verifying device certificates (mutual TLS) is follow-up scope.
- Keep MQTT authorization permissive for now, but leave room for a later pluggable IoT certificate and policy authorizer.
- Serve MQTT over TLS on 8883 next to plaintext 1883 when TLS is enabled, and verify the device certificate and its `iot:Connect` permission there.
- Keep the plaintext listener permissive; topic-level authorization (`Publish`, `Subscribe`, `Receive`) is follow-up scope.
- Keep MQTT broker logging minimal.
- Validate the relevant IoT compatibility tests against the native binary before considering the phase complete.
@@ -88,14 +87,31 @@ Broker scope:
With `FLOCI_TLS_ENABLED=true` the broker also listens on `FLOCI_SERVICES_IOT_MQTT_TLS_PORT` (default `8883`, the port AWS IoT uses for X.509 device connections; `0` disables it). It presents the same certificate as the HTTPS endpoint, issued by the Floci CA, over TLS 1.2 or 1.3. A device connects with `ssl://localhost:8883` trusting `GET /_floci/ca.pem`, as it would trust Amazon Root CA 1 against AWS IoT. A custom domain added to the server certificate at runtime (see [TLS](../configuration/tls.md#custom-domains-learned-at-runtime)) is served on 8883 from the next connection on, without a restart.
The listener asks for a client certificate and accepts the connection whether or not one is presented and whoever signed it: 8883 is as permissive as 1883 until certificate verification lands. Sessions, subscriptions and reserved topics are shared with the plaintext listener, so a client id connecting on one port replaces its session on the other, as on AWS. Both listeners start together: with the first IoT API call, or at boot with `FLOCI_SERVICES_IOT_MQTT_AUTO_START=true`.
The listener asks for a client certificate and decides the connection when the `CONNECT` arrives, see [Device verification on 8883](#device-verification-on-8883). Sessions, subscriptions and reserved topics are shared with the plaintext listener, so a client id connecting on one port replaces its session on the other, as on AWS. Both listeners start together: with the first IoT API call, or at boot with `FLOCI_SERVICES_IOT_MQTT_AUTO_START=true`.
```bash
docker run -e FLOCI_TLS_ENABLED=true -e FLOCI_SERVICES_IOT_MQTT_AUTO_START=true -p 4566:4566 -p 8883:8883 floci/floci:latest
curl http://localhost:4566/_floci/ca.pem -o ca.pem
mosquitto_sub -h localhost -p 8883 --cafile ca.pem -t 'devices/#'
aws --endpoint-url http://localhost:4566 iot create-keys-and-certificate --set-as-active \
--certificate-pem-outfile device.crt --private-key-outfile device.key --query certificateArn --output text
aws --endpoint-url http://localhost:4566 iot create-policy --policy-name connect \
--policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"iot:Connect","Resource":"arn:aws:iot:*:*:client/*"}]}'
aws --endpoint-url http://localhost:4566 iot attach-policy --policy-name connect --target <certificateArn>
mosquitto_sub -h localhost -p 8883 --cafile ca.pem --cert device.crt --key device.key -t 'devices/#'
```
#### Device verification on 8883
The connection is admitted when all of these hold, otherwise the broker answers `CONNACK` not authorized (return code `5`, reason code `0x87` on MQTT 5) and closes the connection:
1. A certificate was presented and the SHA-256 of its DER encoding is a registered `certificateId` (`CreateKeysAndCertificate` or `CreateCertificateFromCsr`), in any account and region. Who signed it does not matter, registration does, as on AWS.
2. The certificate is `ACTIVE` and inside its validity dates.
3. The default versions of the policies attached to the certificate (`AttachPolicy` with the certificate ARN as target, in the certificate's own account and region) allow `iot:Connect` on `arn:aws:iot:<region>:<account>:client/<clientId>`. No attached policy means deny, and an explicit `Deny` wins.
Policy variables are substituted and are also available as condition keys: `iot:ClientId`, `aws:SourceIp`, `iot:DomainName` (the server name the client sent in the TLS handshake, absent when it dialled an IP address), `iot:Connection.Thing.IsAttached` and, only when the client id names a thing attached to the certificate with `AttachThingPrincipal`, `iot:Connection.Thing.ThingName`, `iot:Connection.Thing.ThingTypeName` and `iot:Connection.Thing.Attributes[name]`. A statement that uses a variable Floci cannot resolve, such as the certificate variables `iot:Certificate.*`, matches nothing.
Differences from AWS: AWS rejects an unregistered, inactive or expired certificate during the TLS handshake and closes an MQTT 3.1.1 connection it does not authorize without a `CONNACK`; Floci completes the handshake and always answers with the return code, so the reason is visible to the client. Deactivating the certificate or detaching the policy takes effect on the next connect; established sessions are not dropped. Policies attached to thing groups are not consulted, and exclusive thing attachment (`thingPrincipalType`) is not modelled: the thing is always the one named by the client id.
## Reserved Topics
AWS IoT reserved topics such as `$aws/things/{thingName}/shadow/update` are service control topics, not ordinary application topics. Floci should handle these publishes by invoking IoT shadow behavior and then publishing the AWS-compatible response topics through the broker.
@@ -118,7 +134,7 @@ Implementation notes:
Current accepted limitation:
- Certificate and policy authorization are not enforced at the broker layer yet, on either port.
- Certificate and `iot:Connect` checks are enforced on 8883 only; topic-level authorization is not enforced on either port yet.
- Persistent offline sessions are not modeled yet.
- QoS 2 and advanced MQTT 5 property semantics remain follow-up scope.
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iot;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.iot.model.IotRetainedMessage;
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
@@ -27,9 +28,14 @@ import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import javax.net.ssl.ExtendedSSLSession;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509ExtendedTrustManager;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
@@ -40,6 +46,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@ApplicationScoped
public class IotMqttBrokerService {
@@ -47,10 +54,11 @@ public class IotMqttBrokerService {
private static final Logger LOG = Logger.getLogger(IotMqttBrokerService.class);
/**
* The TLS listener asks for a client certificate and accepts whichever one is presented: AWS
* IoT trusts a device certificate because it is registered, not because of its issuer, and
* that lookup belongs to the broker, not to the handshake. Until it exists, 8883 admits every
* client exactly as 1883 does.
* The TLS listener asks for a client certificate and lets the handshake complete with whichever
* one is presented: AWS IoT trusts a device certificate because it is registered, not because
* of its issuer, and that lookup happens on the CONNECT in {@link #handleEndpoint}, where a
* certificate that is missing, unregistered, inactive or not allowed to connect is answered
* with CONNACK not authorized.
*/
static final X509ExtendedTrustManager ACCEPT_ANY_CLIENT_CERTIFICATE = new X509ExtendedTrustManager() {
@Override
@@ -86,6 +94,8 @@ public class IotMqttBrokerService {
}
};
private static final Pattern IPV4_LITERAL = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}");
private final EmulatorConfig config;
private final Vertx vertx;
private final Instance<IotService> iotService;
@@ -131,7 +141,7 @@ public class IotMqttBrokerService {
MqttServer mqttServer = listen(new MqttServerOptions()
.setHost(config.services().iot().mqtt().host())
.setPort(config.services().iot().mqtt().port()), "IoT MQTT broker");
.setPort(config.services().iot().mqtt().port()), "IoT MQTT broker", false);
try {
startTlsListener();
} catch (RuntimeException e) {
@@ -142,9 +152,10 @@ public class IotMqttBrokerService {
}
/**
* The MQTT over TLS listener, AWS IoT's 8883, sharing every handler with the plaintext one.
* Its key material is the TLS registry's default configuration, the same certificate the HTTPS
* endpoint presents. Not opened when the port is 0 or TLS is off.
* The MQTT over TLS listener, AWS IoT's 8883, sharing every handler with the plaintext one but
* admitting only registered devices whose policies allow the connect. Its key material is the
* TLS registry's default configuration, the same certificate the HTTPS endpoint presents. Not
* opened when the port is 0 or TLS is off.
*/
private void startTlsListener() {
int tlsPort = config.services().iot().mqtt().tlsPort();
@@ -168,13 +179,13 @@ public class IotMqttBrokerService {
.setSsl(true)
.setKeyCertOptions(KeyCertOptions.wrap(manager))
.setTrustOptions(TrustOptions.wrap(ACCEPT_ANY_CLIENT_CERTIFICATE))
.setClientAuth(ClientAuth.REQUEST), "IoT MQTT TLS broker");
.setClientAuth(ClientAuth.REQUEST), "IoT MQTT TLS broker", true);
keyManager = manager;
}
private MqttServer listen(MqttServerOptions options, String name) {
private MqttServer listen(MqttServerOptions options, String name, boolean verifyDevice) {
MqttServer mqttServer = MqttServer.create(vertx, options);
mqttServer.endpointHandler(this::handleEndpoint);
mqttServer.endpointHandler(endpoint -> handleEndpoint(endpoint, verifyDevice));
mqttServer.exceptionHandler(error -> LOG.warnv("{0} error: {1}", name, error.getMessage()));
try {
mqttServer.listen().toCompletionStage().toCompletableFuture().join();
@@ -266,13 +277,32 @@ public class IotMqttBrokerService {
.toList();
}
private void handleEndpoint(MqttEndpoint endpoint) {
/**
* On the TLS listener the CONNECT is admitted only for a presented certificate that IoT Core
* has registered and whose attached policies allow {@code iot:Connect} for the client id;
* anything else is answered with CONNACK not authorized (return code 5, reason code 0x87 on
* MQTT 5) and never becomes a session, so a client already holding that client id keeps its
* connection. The plaintext listener, which the WebSocket bridge also lands on, stays open to
* every client.
*/
private void handleEndpoint(MqttEndpoint endpoint, boolean verifyDevice) {
String clientId = endpoint.clientIdentifier();
SocketAddress remoteAddress = endpoint.remoteAddress();
String sourceIp = remoteAddress == null ? null : remoteAddress.host();
String principal = null;
if (verifyDevice) {
principal = admittedDevice(endpoint, clientId, sourceIp);
if (principal == null) {
endpoint.reject(endpoint.protocolVersion() == 5
? MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED_5
: MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
return;
}
}
ClientSession session = new ClientSession(
clientId,
endpoint,
remoteAddress == null ? null : remoteAddress.host(),
sourceIp,
remoteAddress == null ? -1 : remoteAddress.port(),
endpoint.isCleanSession());
@@ -291,6 +321,75 @@ public class IotMqttBrokerService {
}
endpoint.accept();
if (principal != null) {
LOG.debugv("IoT MQTT TLS client {0} admitted as {1}", clientId, principal);
}
}
/**
* The certificate ARN of the device behind the connection when it may connect, otherwise null.
* A failure while deciding refuses the client rather than leaving the CONNECT unanswered. A
* refusal is the client's own doing and reaches it as the CONNACK, so it is logged at debug
* only: the CONNECT is reachable by anyone.
*/
private String admittedDevice(MqttEndpoint endpoint, String clientId, String sourceIp) {
try {
Optional<IotService.RegisteredDevice> device = presentedDevice(endpoint);
if (device.isEmpty()) {
LOG.debugv("IoT MQTT TLS client {0} refused: no registered certificate presented", clientId);
return null;
}
String certificateArn = device.get().certificate().getCertificateArn();
if (!iotService.get().isConnectAllowed(device.get(), clientId, sourceIp, requestedServerName(endpoint))) {
LOG.debugv("IoT MQTT TLS client {0} refused: iot:Connect is not allowed for {1}", clientId, certificateArn);
return null;
}
return certificateArn;
} catch (RuntimeException e) {
LOG.warnv(e, "IoT MQTT TLS client {0} refused: device verification failed: {1}", clientId, e.getMessage());
return null;
}
}
/** The registered certificate behind the peer's leaf, if the client presented one at all. */
private Optional<IotService.RegisteredDevice> presentedDevice(MqttEndpoint endpoint) {
SSLSession session = endpoint.isSsl() ? endpoint.sslSession() : null;
if (session == null) {
return Optional.empty();
}
Certificate[] chain;
try {
chain = session.getPeerCertificates();
} catch (SSLPeerUnverifiedException e) {
LOG.debugv("IoT MQTT TLS client {0} presented no certificate", endpoint.clientIdentifier());
return Optional.empty();
}
if (chain.length == 0 || !(chain[0] instanceof X509Certificate leaf)) {
return Optional.empty();
}
return iotService.get().findRegisteredCertificate(leaf);
}
/**
* The server name the client sent in the handshake, which AWS IoT exposes as
* {@code iot:DomainName}. An address literal is not a domain name: some clients send the
* host they dialled as SNI even when it is an IP.
*/
private static String requestedServerName(MqttEndpoint endpoint) {
if (!(endpoint.sslSession() instanceof ExtendedSSLSession session)) {
return null;
}
return session.getRequestedServerNames().stream()
.filter(SNIHostName.class::isInstance)
.map(name -> ((SNIHostName) name).getAsciiName())
.filter(name -> !isAddressLiteral(name))
.findFirst()
.orElse(null);
}
/** An IPv4 dotted quad, or anything carrying a colon, which only an IPv6 literal does. */
static boolean isAddressLiteral(String name) {
return name.indexOf(':') >= 0 || IPV4_LITERAL.matcher(name).matches();
}
private void handleSubscribe(ClientSession session, MqttSubscribeMessage message) {
@@ -6,13 +6,17 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iot.model.IotCertificate;
import io.github.hectorvent.floci.services.iot.model.IotJob;
@@ -46,6 +50,8 @@ import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.ArrayList;
@@ -55,13 +61,17 @@ import java.util.Comparator;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.regex.Pattern;
@ApplicationScoped
@@ -74,11 +84,16 @@ public class IotService {
private static final Pattern THING_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]{1,128}");
/** The {@code FirehoseSeparator} shape of the IoT API model. */
private static final Pattern FIREHOSE_SEPARATOR = Pattern.compile("([\\n\\t])|(\\r\\n)|(,)");
/** An AWS policy variable such as {@code ${iot:ClientId}}. */
private static final Pattern POLICY_VARIABLE = Pattern.compile("\\$\\{[^}]*\\}");
public static final int MAX_POLICY_VERSIONS = 5;
/** One lock for every policy version write and the policy delete, so a cap check, an append and a delete cannot interleave. */
private final Object policyWriteLock = new Object();
/** certificateId to the partition and key it was last found under; see {@link #findRegisteredCertificate}. */
private final Map<String, CertificateLocation> certificateLocations = new ConcurrentHashMap<>();
private final StorageBackend<String, Thing> thingStore;
private final StorageBackend<String, IotCertificate> certificateStore;
private final StorageBackend<String, IotPolicy> policyStore;
@@ -106,6 +121,7 @@ public class IotService {
private final FirehoseService firehoseService;
private final CloudWatchLogsService cloudWatchLogsService;
private final FlociCertificateAuthority certificateAuthority;
private final IamPolicyEvaluator policyEvaluator;
private final RuleSqlEvaluator ruleSqlEvaluator;
@Inject
@@ -123,7 +139,8 @@ public class IotService {
LambdaService lambdaService,
FirehoseService firehoseService,
CloudWatchLogsService cloudWatchLogsService,
FlociCertificateAuthority certificateAuthority) {
FlociCertificateAuthority certificateAuthority,
IamPolicyEvaluator policyEvaluator) {
this(storageFactory.create("iot", "iot-things.json", new TypeReference<Map<String, Thing>>() {}),
storageFactory.create("iot", "iot-certificates.json", new TypeReference<Map<String, IotCertificate>>() {}),
storageFactory.create("iot", "iot-policies.json", new TypeReference<Map<String, IotPolicy>>() {}),
@@ -138,7 +155,8 @@ public class IotService {
storageFactory.create("iot", "iot-thing-groups.json", new TypeReference<Map<String, IotThingGroup>>() {}),
storageFactory.create("iot", "iot-thing-group-memberships.json", new TypeReference<Map<String, Set<String>>>() {}),
config, regionResolver, objectMapper, publishEventRecorder, mqttBrokerService, sqsService, snsService,
s3Service, kinesisService, dynamoDbService, lambdaService, firehoseService, cloudWatchLogsService, certificateAuthority);
s3Service, kinesisService, dynamoDbService, lambdaService, firehoseService, cloudWatchLogsService, certificateAuthority,
policyEvaluator);
}
IotService(StorageBackend<String, Thing> thingStore,
@@ -167,7 +185,8 @@ public class IotService {
LambdaService lambdaService,
FirehoseService firehoseService,
CloudWatchLogsService cloudWatchLogsService,
FlociCertificateAuthority certificateAuthority) {
FlociCertificateAuthority certificateAuthority,
IamPolicyEvaluator policyEvaluator) {
this.thingStore = thingStore;
this.certificateStore = certificateStore;
this.policyStore = policyStore;
@@ -195,6 +214,7 @@ public class IotService {
this.firehoseService = firehoseService;
this.cloudWatchLogsService = cloudWatchLogsService;
this.certificateAuthority = certificateAuthority;
this.policyEvaluator = policyEvaluator;
this.ruleSqlEvaluator = new RuleSqlEvaluator(objectMapper);
}
@@ -370,16 +390,20 @@ public class IotService {
}
}
/** AWS IoT's certificateId is the lowercase hex SHA-256 of the certificate's DER encoding. */
private static void fill(IotCertificate certificate, X509Certificate x509) throws Exception {
CertificateGenerator pem = new CertificateGenerator();
certificate.setCertificateId(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(x509.getEncoded())));
certificate.setCertificateId(certificateIdOf(x509));
certificate.setCertificatePem(pem.toPem(x509));
certificate.setPublicKey(pem.toPem(x509.getPublicKey()));
certificate.setNotBefore(x509.getNotBefore().toInstant());
certificate.setNotAfter(x509.getNotAfter().toInstant());
}
/** AWS IoT's certificateId is the lowercase hex SHA-256 of the certificate's DER encoding. */
private static String certificateIdOf(X509Certificate x509) throws CertificateEncodingException, NoSuchAlgorithmException {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(x509.getEncoded()));
}
public IotCertificate describeCertificate(String certificateId, String region) {
return certificateStore.get(certificateKey(region, certificateId))
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Certificate not found: " + certificateId, 404));
@@ -408,6 +432,205 @@ public class IotService {
throw new AwsException("InvalidRequestException", "Cannot delete attached certificate", 400);
}
certificateStore.delete(certificateKey(region, certificateId));
certificateLocations.remove(certificateId);
}
/** A device certificate the registry holds, with the account partition and region it was registered in. */
public record RegisteredDevice(String accountId, String region, IotCertificate certificate) {
}
private record CertificateLocation(String accountId, String key) {
}
/**
* AWS IoT trusts a device certificate because it is registered, not because of who signed it.
* The lookup key is the certificateId, which is the SHA-256 of the DER encoding, searched
* across every account partition: a connecting device carries no request context. The
* partition and key a certificate was found under are remembered, so a device's next connect
* is one keyed read; a remembered location that no longer resolves is dropped and the scan
* runs again.
*/
public Optional<RegisteredDevice> findRegisteredCertificate(X509Certificate presented) {
String certificateId;
try {
certificateId = certificateIdOf(presented);
} catch (CertificateEncodingException | NoSuchAlgorithmException e) {
LOG.debugv("Could not fingerprint the presented device certificate: {0}", e.getMessage());
return Optional.empty();
}
CertificateLocation known = certificateLocations.get(certificateId);
if (known != null) {
Optional<IotCertificate> current = getForAccount(certificateStore, known.accountId(), known.key());
if (current.isPresent()) {
return Optional.of(new RegisteredDevice(known.accountId(), regionOfCertificateKey(known.key()), current.get()));
}
certificateLocations.remove(certificateId, known);
}
String suffix = ":" + certificateId;
Optional<AccountAwareStorageBackend.AccountEntry<IotCertificate>> found =
registeredCertificates(key -> key.startsWith("cert:") && key.endsWith(suffix)).stream()
.sorted(Comparator.comparing((AccountAwareStorageBackend.AccountEntry<IotCertificate> entry) -> entry.accountId())
.thenComparing(AccountAwareStorageBackend.AccountEntry::key))
.findFirst();
found.ifPresent(entry -> certificateLocations.put(certificateId, new CertificateLocation(entry.accountId(), entry.key())));
return found.map(entry -> new RegisteredDevice(entry.accountId(), regionOfCertificateKey(entry.key()), entry.value()));
}
private static String regionOfCertificateKey(String key) {
return key.split(":", 3)[1];
}
/**
* Decides {@code iot:Connect} for a client id the way AWS IoT does on a CONNECT: the certificate
* must be ACTIVE and within its validity dates, the policies are the default versions attached
* to the certificate in its own account and region, and the connection's policy variables are
* substituted and offered as condition keys. No policy means deny; an explicit deny wins.
*/
public boolean isConnectAllowed(RegisteredDevice device, String clientId, String sourceIp, String domainName) {
IotCertificate certificate = device.certificate();
if (clientId == null || clientId.isBlank() || !"ACTIVE".equals(certificate.getStatus()) || !isWithinValidity(certificate)) {
return false;
}
List<String> documents = attachedPolicyDocuments(certificate.getCertificateArn(), device.region(), device.accountId());
if (documents.isEmpty()) {
return false;
}
Map<String, String> variables = connectionVariables(device, clientId, sourceIp, domainName);
List<String> resolved = documents.stream().map(document -> resolvePolicyVariables(document, variables)).toList();
Map<String, List<String>> conditionContext = new LinkedHashMap<>();
variables.forEach((key, value) -> conditionContext.put(key, List.of(value)));
String clientArn = AwsArnUtils.Arn.of("iot", device.region(), device.accountId(), "client/" + clientId).toString();
return policyEvaluator.evaluate(CallerContext.of(resolved), null, "iot:Connect", clientArn, conditionContext)
== IamPolicyEvaluator.Decision.ALLOW;
}
private static boolean isWithinValidity(IotCertificate certificate) {
Instant now = Instant.now();
return (certificate.getNotBefore() == null || !now.isBefore(certificate.getNotBefore()))
&& (certificate.getNotAfter() == null || now.isBefore(certificate.getNotAfter()));
}
private List<String> attachedPolicyDocuments(String certificateArn, String region, String accountId) {
String prefix = "policy-attachment:" + region + ":";
return keysForAccount(policyAttachmentStore, accountId).stream()
.filter(key -> key.startsWith(prefix))
.filter(key -> getForAccount(policyAttachmentStore, accountId, key).orElse(Set.of()).contains(certificateArn))
.map(key -> key.substring(prefix.length()))
.sorted()
.map(policyName -> getForAccount(policyStore, accountId, policyKey(region, policyName)))
.flatMap(Optional::stream)
.map(IotPolicy::getPolicyDocument)
.filter(Objects::nonNull)
.toList();
}
/**
* The policy variables AWS IoT defines for a connection: the basic ones (client id, source
* address, the domain name the client connected to) and the thing ones, which resolve only when
* the client id names a thing attached to the certificate, as on AWS.
*/
private Map<String, String> connectionVariables(RegisteredDevice device, String clientId, String sourceIp, String domainName) {
Map<String, String> variables = new LinkedHashMap<>();
variables.put("iot:ClientId", clientId);
if (sourceIp != null) {
variables.put("aws:SourceIp", sourceIp);
}
if (domainName != null) {
variables.put("iot:DomainName", domainName);
}
Optional<Thing> thing = getForAccount(thingStore, device.accountId(), thingKey(device.region(), clientId));
boolean attached = thing.isPresent()
&& getForAccount(thingPrincipalStore, device.accountId(), thingPrincipalKey(device.region(), clientId))
.orElse(Set.of()).contains(device.certificate().getCertificateArn());
variables.put("iot:Connection.Thing.IsAttached", Boolean.toString(attached));
if (attached) {
variables.put("iot:Connection.Thing.ThingName", clientId);
if (thing.get().getThingTypeName() != null) {
variables.put("iot:Connection.Thing.ThingTypeName", thing.get().getThingTypeName());
}
thing.get().getAttributes().forEach((name, value) -> variables.put("iot:Connection.Thing.Attributes[" + name + "]", value));
}
return variables;
}
/**
* Substitutes the connection's variables into every string of the document on the parsed tree,
* so a client id is never read as JSON. A statement still holding a variable Floci cannot
* resolve matches nothing, as an unresolvable variable does on AWS, and is dropped. A document
* that does not parse is returned as is: the evaluator logs it and skips it.
*/
private String resolvePolicyVariables(String document, Map<String, String> variables) {
JsonNode root;
try {
root = objectMapper.readTree(document);
} catch (JsonProcessingException e) {
return document;
}
if (!(root instanceof ObjectNode policy)) {
return document;
}
JsonNode statements = policy.get("Statement");
Iterable<JsonNode> each = statements == null ? List.of() : statements.isArray() ? statements : List.of(statements);
ArrayNode resolved = objectMapper.createArrayNode();
for (JsonNode statement : each) {
JsonNode substituted = substituteVariables(statement.deepCopy(), variables);
if (!hasUnresolvedVariable(substituted)) {
resolved.add(substituted);
}
}
policy.set("Statement", resolved);
return policy.toString();
}
private static JsonNode substituteVariables(JsonNode node, Map<String, String> variables) {
if (node.isTextual()) {
String text = node.asText();
for (Map.Entry<String, String> variable : variables.entrySet()) {
text = text.replace("${" + variable.getKey() + "}", variable.getValue());
}
return TextNode.valueOf(text);
}
if (node instanceof ObjectNode object) {
for (Map.Entry<String, JsonNode> property : object.properties()) {
property.setValue(substituteVariables(property.getValue(), variables));
}
} else if (node instanceof ArrayNode array) {
for (int i = 0; i < array.size(); i++) {
array.set(i, substituteVariables(array.get(i), variables));
}
}
return node;
}
private static boolean hasUnresolvedVariable(JsonNode node) {
if (node.isTextual()) {
return POLICY_VARIABLE.matcher(node.asText()).find();
}
for (JsonNode child : node) {
if (hasUnresolvedVariable(child)) {
return true;
}
}
return false;
}
private List<AccountAwareStorageBackend.AccountEntry<IotCertificate>> registeredCertificates(Predicate<String> keyFilter) {
if (certificateStore instanceof AccountAwareStorageBackend<IotCertificate> aware) {
return aware.scanAllAccountEntries(keyFilter);
}
return certificateStore.keys().stream()
.filter(keyFilter)
.flatMap(key -> certificateStore.get(key).stream()
.map(value -> new AccountAwareStorageBackend.AccountEntry<>(regionResolver.getDefaultAccountId(), key, value)))
.toList();
}
private static <V> Optional<V> getForAccount(StorageBackend<String, V> store, String accountId, String key) {
return store instanceof AccountAwareStorageBackend<V> aware ? aware.getForAccount(accountId, key) : store.get(key);
}
private static <V> Set<String> keysForAccount(StorageBackend<String, V> store, String accountId) {
return store instanceof AccountAwareStorageBackend<V> aware ? aware.keysForAccount(accountId) : store.keys();
}
public IotPolicy createPolicy(String policyName, String policyDocument, String region) {
@@ -0,0 +1,85 @@
package io.github.hectorvent.floci.services.iot;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.restassured.path.json.JsonPath;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import static io.restassured.RestAssured.given;
/** A device provisioned through CreateKeysAndCertificate, ready to present itself on the TLS listener. */
final class IotDeviceIdentity {
private static final char[] PASSWORD = "device".toCharArray();
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
final String certificateId;
final String certificateArn;
final X509Certificate certificate;
final PrivateKey privateKey;
private IotDeviceIdentity(String certificateId, String certificateArn, X509Certificate certificate, PrivateKey privateKey) {
this.certificateId = certificateId;
this.certificateArn = certificateArn;
this.certificate = certificate;
this.privateKey = privateKey;
}
/** Provisions a device over the REST API, as an onboarding flow does. */
static IotDeviceIdentity provision(boolean active) {
JsonPath created = given()
.queryParam("setAsActive", active)
.when().post("/keys-and-certificate")
.then().statusCode(200)
.extract().jsonPath();
return new IotDeviceIdentity(
created.getString("certificateId"),
created.getString("certificateArn"),
GENERATOR.parseCertificate(created.getString("certificatePem")),
GENERATOR.parsePrivateKey(created.getString("keyPair.PrivateKey")));
}
/** 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",
GENERATOR.parseCertificate(issued.certificatePem()), GENERATOR.parsePrivateKey(issued.privateKeyPem()));
}
/** Presents the device certificate and trusts only the Floci CA. */
SSLContext sslContext(Path tlsDir) throws Exception {
KeyStore identity = KeyStore.getInstance("PKCS12");
identity.load(null, null);
identity.setKeyEntry("device", privateKey, PASSWORD, new Certificate[] {certificate});
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(identity, PASSWORD);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), trustManagers(tlsDir), null);
return context;
}
/** Trusts only the Floci CA and presents nothing: an anonymous client. */
static SSLContext trustOnlySslContext(Path tlsDir) throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustManagers(tlsDir), null);
return context;
}
private static TrustManager[] trustManagers(Path tlsDir) throws Exception {
KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());
trust.load(null, null);
trust.setCertificateEntry("floci", FlociCertificateAuthority.loadOrCreate(tlsDir).certificate());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trust);
return tmf.getTrustManagers();
}
}
@@ -0,0 +1,337 @@
package io.github.hectorvent.floci.services.iot;
import io.github.hectorvent.floci.config.EmulatorConfig;
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.services.iot.IotService.RegisteredDevice;
import io.github.hectorvent.floci.services.iot.model.IotCertificate;
import io.quarkus.tls.TlsConfiguration;
import io.quarkus.tls.TlsConfigurationRegistry;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.PemKeyCertOptions;
import jakarta.enterprise.inject.Instance;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.file.Path;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* How the TLS listener turns the registry's answers into CONNACKs, against a real Vert.x broker
* and a mocked {@link IotService}: which connections are refused, with which code, what the
* evaluation is given, and that a refusal touches nothing else.
*/
class IotMqttBrokerDeviceVerificationTest {
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
private static Vertx vertx;
private static FlociCertificateAuthority ca;
private static CertificateGenerator.GeneratedCertificate serverLeaf;
private static CertificateGenerator.GeneratedCertificate deviceLeaf;
private static CertificateGenerator.GeneratedCertificate otherLeaf;
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
private final TlsConfigurationRegistry registry = mock(TlsConfigurationRegistry.class);
private final TlsConfiguration tls = mock(TlsConfiguration.class);
private final IotService service = mock(IotService.class);
@SuppressWarnings("unchecked")
private final Instance<IotService> iotService = mock(Instance.class);
private int plainPort;
private int tlsPort;
private IotMqttBrokerService broker;
@BeforeAll
static void keyMaterial(@TempDir Path dir) {
vertx = Vertx.vertx();
ca = FlociCertificateAuthority.loadOrCreate(dir);
serverLeaf = ca.issueServerCertificate("localhost", List.of("localhost", "127.0.0.1"), KeyAlgorithm.RSA_2048, null);
deviceLeaf = ca.issueClientCertificate("device");
otherLeaf = ca.issueClientCertificate("other");
}
@AfterAll
static void closeVertx() {
vertx.close().toCompletionStage().toCompletableFuture().join();
}
@BeforeEach
void brokerWithTlsOn() throws IOException {
plainPort = freePort();
do {
tlsPort = freePort();
} while (tlsPort == plainPort);
when(config.services().iot().enabled()).thenReturn(true);
when(config.services().iot().mqtt().enabled()).thenReturn(true);
when(config.services().iot().mqtt().host()).thenReturn("127.0.0.1");
when(config.services().iot().mqtt().port()).thenReturn(plainPort);
when(config.services().iot().mqtt().tlsPort()).thenReturn(tlsPort);
when(config.tls().enabled()).thenReturn(true);
when(registry.getDefault()).thenReturn(Optional.of(tls));
when(tls.getKeyStoreOptions()).thenReturn(new PemKeyCertOptions()
.addCertValue(Buffer.buffer(serverLeaf.certificatePem()))
.addKeyValue(Buffer.buffer(serverLeaf.privateKeyPem())));
when(iotService.get()).thenReturn(service);
broker = new IotMqttBrokerService(config, vertx, iotService, registry);
broker.startIfEnabled();
}
@AfterEach
void stopBroker() {
broker.stop();
}
@Test
void anUnregisteredCertificateIsAnsweredWithConnackNotAuthorized() throws Exception {
when(service.findRegisteredCertificate(any())).thenReturn(Optional.empty());
assertNotAuthorized(() -> connectTls("unknown", deviceLeaf, null));
verify(service).findRegisteredCertificate(certificate(deviceLeaf));
verify(service, never()).isConnectAllowed(any(), anyString(), any(), any());
}
@Test
void anMqtt5ClientIsRefusedWithTheMqtt5ReasonCode() throws Exception {
when(service.findRegisteredCertificate(any())).thenReturn(Optional.empty());
org.eclipse.paho.mqttv5.client.MqttClient client =
new org.eclipse.paho.mqttv5.client.MqttClient("ssl://127.0.0.1:" + tlsPort, "v5-unknown", null);
org.eclipse.paho.mqttv5.client.MqttConnectionOptions options = new org.eclipse.paho.mqttv5.client.MqttConnectionOptions();
options.setConnectionTimeout(10);
options.setAutomaticReconnect(false);
options.setSocketFactory(sslContext(keyManagers(deviceLeaf)).getSocketFactory());
try {
org.eclipse.paho.mqttv5.common.MqttException refused =
assertThrows(org.eclipse.paho.mqttv5.common.MqttException.class, () -> client.connect(options));
assertEquals(0x87, refused.getReasonCode());
} finally {
client.close();
}
}
@Test
void aClientWithoutACertificateIsRefusedWithoutConsultingTheRegistry() throws Exception {
assertNotAuthorized(() -> connectTls("anonymous", null, null));
verifyNoInteractions(service);
}
/** Paho sends the dialled host as the TLS server name; an address literal is not a domain name. */
@Test
void anAdmittedDeviceIsEvaluatedWithItsClientIdAndAddress() throws Exception {
RegisteredDevice device = registered(deviceLeaf);
when(service.findRegisteredCertificate(certificate(deviceLeaf))).thenReturn(Optional.of(device));
when(service.isConnectAllowed(eq(device), eq("sensor-1"), eq("127.0.0.1"), isNull())).thenReturn(true);
MqttClient client = connectTls("sensor-1", deviceLeaf, null);
try {
assertTrue(client.isConnected());
assertTrue(broker.getConnection("sensor-1").isPresent());
verify(service).isConnectAllowed(device, "sensor-1", "127.0.0.1", null);
} finally {
client.disconnect();
client.close();
}
}
@Test
void theServerNameTheClientSentIsTheDomainNameOfTheEvaluation() throws Exception {
RegisteredDevice device = registered(deviceLeaf);
when(service.findRegisteredCertificate(certificate(deviceLeaf))).thenReturn(Optional.of(device));
when(service.isConnectAllowed(eq(device), eq("sensor-1"), eq("127.0.0.1"), eq("localhost"))).thenReturn(true);
MqttClient client = connectTls("sensor-1", deviceLeaf, "localhost");
try {
assertTrue(client.isConnected());
verify(service).isConnectAllowed(device, "sensor-1", "127.0.0.1", "localhost");
} finally {
client.disconnect();
client.close();
}
}
@Test
void aDeniedDeviceIsAnsweredWithConnackNotAuthorized() throws Exception {
RegisteredDevice device = registered(deviceLeaf);
when(service.findRegisteredCertificate(certificate(deviceLeaf))).thenReturn(Optional.of(device));
when(service.isConnectAllowed(any(), anyString(), any(), any())).thenReturn(false);
assertNotAuthorized(() -> connectTls("sensor-1", deviceLeaf, null));
assertTrue(broker.getConnection("sensor-1").isEmpty(), "no session is registered for a refused connect");
}
@Test
void aRefusedConnectLeavesTheSessionHoldingThatClientIdConnected() throws Exception {
RegisteredDevice device = registered(deviceLeaf);
when(service.findRegisteredCertificate(certificate(deviceLeaf))).thenReturn(Optional.of(device));
when(service.findRegisteredCertificate(certificate(otherLeaf))).thenReturn(Optional.empty());
when(service.isConnectAllowed(eq(device), anyString(), any(), any())).thenReturn(true);
MqttClient holder = connectTls("shared-id", deviceLeaf, null);
try {
assertNotAuthorized(() -> connectTls("shared-id", otherLeaf, null));
Thread.sleep(200);
assertTrue(holder.isConnected());
assertTrue(broker.getConnection("shared-id").isPresent());
} finally {
holder.disconnect();
holder.close();
}
}
@Test
void aFailureInsideTheRegistryLookupRefusesTheClientAndKeepsTheListenerServing() throws Exception {
RegisteredDevice device = registered(deviceLeaf);
when(service.findRegisteredCertificate(any()))
.thenThrow(new IllegalStateException("storage unavailable"))
.thenReturn(Optional.of(device));
when(service.isConnectAllowed(eq(device), anyString(), any(), any())).thenReturn(true);
assertNotAuthorized(() -> connectTls("sensor-1", deviceLeaf, null));
MqttClient client = connectTls("sensor-1", deviceLeaf, null);
try {
assertTrue(client.isConnected(), "the listener still serves after a failed evaluation");
} finally {
client.disconnect();
client.close();
}
}
@Test
void addressLiteralsAreNeverADomainName() {
assertTrue(IotMqttBrokerService.isAddressLiteral("127.0.0.1"));
assertTrue(IotMqttBrokerService.isAddressLiteral("::1"));
assertTrue(IotMqttBrokerService.isAddressLiteral("[fe80::1]"));
assertTrue(IotMqttBrokerService.isAddressLiteral("2001:db8::1"));
assertFalse(IotMqttBrokerService.isAddressLiteral("localhost"));
assertFalse(IotMqttBrokerService.isAddressLiteral("iot.dev.localhost.floci.io"));
assertFalse(IotMqttBrokerService.isAddressLiteral("device1.example"));
}
@Test
void thePlaintextListenerNeverConsultsTheRegistry() throws Exception {
MqttClient client = new MqttClient("tcp://127.0.0.1:" + plainPort, "plain", new MemoryPersistence());
try {
client.connect();
assertTrue(client.isConnected());
verifyNoInteractions(service);
} finally {
client.disconnect();
client.close();
}
}
/** Dials {@code host}, which Paho also sends as the TLS server name; MQTT 3.1.1 pinned so a refusal is not retried as 3.1. */
private MqttClient connectTls(String clientId, CertificateGenerator.GeneratedCertificate leaf, String host) throws Exception {
MqttClient client = new MqttClient("ssl://" + (host == null ? "127.0.0.1" : host) + ":" + tlsPort, clientId, new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
options.setConnectionTimeout(10);
options.setAutomaticReconnect(false);
options.setSocketFactory(sslContext(leaf == null ? null : keyManagers(leaf)).getSocketFactory());
try {
client.connect(options);
} catch (MqttException e) {
client.close();
throw e;
}
return client;
}
private interface Connect {
MqttClient run() throws Exception;
}
private static void assertNotAuthorized(Connect connect) {
MqttException refused = assertThrows(MqttException.class, () -> {
MqttClient client = connect.run();
client.disconnect();
client.close();
});
assertInstanceOf(MqttSecurityException.class, refused, "expected CONNACK not authorized, got: " + refused);
assertEquals(MqttException.REASON_CODE_NOT_AUTHORIZED, refused.getReasonCode());
assertFalse(refused.getMessage().isBlank());
}
private static RegisteredDevice registered(CertificateGenerator.GeneratedCertificate leaf) {
IotCertificate certificate = new IotCertificate();
certificate.setCertificateId("id-" + leaf.hashCode());
certificate.setCertificateArn("arn:aws:iot:us-east-1:000000000000:cert/id-" + leaf.hashCode());
certificate.setCertificatePem(leaf.certificatePem());
certificate.setStatus("ACTIVE");
return new RegisteredDevice("000000000000", "us-east-1", certificate);
}
private static X509Certificate certificate(CertificateGenerator.GeneratedCertificate leaf) {
return GENERATOR.parseCertificate(leaf.certificatePem());
}
private static SSLContext sslContext(KeyManager[] clientKeys) throws Exception {
KeyStore trust = KeyStore.getInstance(KeyStore.getDefaultType());
trust.load(null, null);
trust.setCertificateEntry("floci", ca.certificate());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trust);
SSLContext context = SSLContext.getInstance("TLS");
context.init(clientKeys, tmf.getTrustManagers(), null);
return context;
}
private static KeyManager[] keyManagers(CertificateGenerator.GeneratedCertificate leaf) throws Exception {
KeyStore keys = KeyStore.getInstance(KeyStore.getDefaultType());
keys.load(null, null);
keys.setKeyEntry("device", GENERATOR.parsePrivateKey(leaf.privateKeyPem()), new char[0],
new Certificate[] {GENERATOR.parseCertificate(leaf.certificatePem())});
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keys, new char[0]);
return kmf.getKeyManagers();
}
private static int freePort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
}
@@ -0,0 +1,395 @@
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.model.KeyAlgorithm;
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;
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 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;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The MQTT over TLS listener admits a device only when its certificate is registered and ACTIVE
* and a policy attached to it allows {@code iot:Connect} for the client id, evaluated with the
* connection's policy variables. The plaintext listener stays permissive.
*/
@QuarkusTest
@TestProfile(IotMqttMutualTlsIntegrationTest.Profile.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;
/** 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);
@Test
void activeCertificateWithConnectPolicyIsAdmitted() throws Exception {
IotDeviceIdentity device = provisionWithPolicy(true, CONNECT_ANY_CLIENT);
String clientId = "sensor-" + System.nanoTime();
MqttClient client = connectTls(device, clientId);
try {
assertTrue(client.isConnected());
given()
.when().get("/connections/{clientId}", clientId)
.then().statusCode(200).body("connected", equalTo(true));
} finally {
client.disconnect();
client.close();
}
}
@Test
void mqtt5DeviceWithConnectPolicyIsAdmitted() throws Exception {
IotDeviceIdentity device = provisionWithPolicy(true, CONNECT_ANY_CLIENT);
org.eclipse.paho.mqttv5.client.MqttClient client = mqtt5Client("v5-" + System.nanoTime());
try {
client.connect(mqtt5Options(device.sslContext(TLS_DIR).getSocketFactory()));
assertTrue(client.isConnected());
client.disconnect();
} finally {
client.close();
}
}
@Test
void mqtt5DeviceWithoutPolicyIsRefusedWithTheNotAuthorizedReasonCode() throws Exception {
IotDeviceIdentity device = IotDeviceIdentity.provision(true);
org.eclipse.paho.mqttv5.client.MqttClient client = mqtt5Client("v5-no-policy-" + System.nanoTime());
try {
org.eclipse.paho.mqttv5.common.MqttException refused = assertThrows(
org.eclipse.paho.mqttv5.common.MqttException.class,
() -> client.connect(mqtt5Options(device.sslContext(TLS_DIR).getSocketFactory())));
assertEquals(0x87, refused.getReasonCode(), "MQTT 5 CONNACK reason code Not authorized");
} finally {
client.close();
}
}
@Test
void activeCertificateWithoutPolicyIsRefused() {
IotDeviceIdentity device = IotDeviceIdentity.provision(true);
assertNotAuthorized(() -> connectTls(device, "no-policy-" + System.nanoTime()));
}
@Test
void inactiveCertificateIsRefused() {
IotDeviceIdentity device = provisionWithPolicy(false, CONNECT_ANY_CLIENT);
assertNotAuthorized(() -> connectTls(device, "inactive-" + System.nanoTime()));
}
@Test
void deactivatedCertificateIsRefusedOnTheNextConnect() throws Exception {
IotDeviceIdentity device = provisionWithPolicy(true, CONNECT_ANY_CLIENT);
MqttClient first = connectTls(device, "deactivate-1-" + System.nanoTime());
first.disconnect();
first.close();
given().queryParam("newStatus", "INACTIVE").when().put("/certificates/" + device.certificateId).then().statusCode(200);
assertNotAuthorized(() -> connectTls(device, "deactivate-2-" + System.nanoTime()));
}
@Test
void detachedPolicyIsRefusedOnTheNextConnect() throws Exception {
IotDeviceIdentity device = IotDeviceIdentity.provision(true);
String policy = "detach-" + System.nanoTime();
createPolicy(policy, CONNECT_ANY_CLIENT);
attachPolicy(policy, device.certificateArn);
MqttClient first = connectTls(device, "detach-1-" + System.nanoTime());
first.disconnect();
first.close();
given().queryParam("target", device.certificateArn).when().post("/target-policies/" + policy).then().statusCode(200);
assertNotAuthorized(() -> connectTls(device, "detach-2-" + System.nanoTime()));
}
@Test
void unregisteredCertificateIsRefusedEvenThoughTheFlociCaSignedIt() {
IotDeviceIdentity stranger = IotDeviceIdentity.stranger(TLS_DIR);
assertNotAuthorized(() -> connectTls(stranger, "stranger-" + System.nanoTime()));
}
@Test
void noClientCertificateIsRefused() {
assertNotAuthorized(() -> connect("ssl://127.0.0.1:" + TLS_PORT, "anon-" + System.nanoTime(),
IotDeviceIdentity.trustOnlySslContext(TLS_DIR).getSocketFactory()));
}
@Test
void plaintextListenerStaysPermissive() throws Exception {
MqttClient client = connect("tcp://127.0.0.1:" + PLAIN_PORT, "plain-" + System.nanoTime(), null);
assertTrue(client.isConnected());
client.disconnect();
client.close();
}
@Test
void aRefusedConnectDoesNotDisconnectTheClientHoldingThatId() throws Exception {
IotDeviceIdentity device = provisionWithPolicy(true, CONNECT_ANY_CLIENT);
String clientId = "held-" + System.nanoTime();
MqttClient holder = connectTls(device, clientId);
try {
assertNotAuthorized(() -> connectTls(IotDeviceIdentity.stranger(TLS_DIR), clientId));
Thread.sleep(200);
assertTrue(holder.isConnected(), "the admitted session survives a refused connect with its client id");
given()
.when().get("/connections/{clientId}", clientId)
.then().statusCode(200).body("connected", equalTo(true));
} finally {
holder.disconnect();
holder.close();
}
}
@Test
void thingPolicyVariableAdmitsOnlyTheAttachedThingName() throws Exception {
IotDeviceIdentity device = provisionWithPolicy(true, CONNECT_AS_ATTACHED_THING);
String thingName = "thing" + System.nanoTime();
given().contentType("application/json").body("{}").when().post("/things/" + thingName).then().statusCode(200);
given().header("x-amzn-principal", device.certificateArn).when().put("/things/" + thingName + "/principals").then().statusCode(200);
MqttClient asThing = connectTls(device, thingName);
assertTrue(asThing.isConnected());
asThing.disconnect();
asThing.close();
assertNotAuthorized(() -> connectTls(device, "not-" + thingName));
}
@Test
void domainNameConditionSeesTheServerNameTheDeviceSent() throws Exception {
IotDeviceIdentity device = provisionWithPolicy(true, policy("Allow", "arn:aws:iot:*:*:client/*",
"{\"StringEquals\":{\"iot:DomainName\":\"" + DOMAIN + "\"}}"));
MqttClient named = connect("ssl://" + DOMAIN + ":" + TLS_PORT, "sni-" + System.nanoTime(),
device.sslContext(TLS_DIR).getSocketFactory());
assertTrue(named.isConnected());
named.disconnect();
named.close();
assertNotAuthorized(() -> connectTls(device, "by-ip-" + System.nanoTime()));
}
@Test
void sourceIpConditionSeesTheClientAddress() throws Exception {
IotDeviceIdentity local = provisionWithPolicy(true, policy("Allow", "arn:aws:iot:*:*:client/*",
"{\"IpAddress\":{\"aws:SourceIp\":\"127.0.0.1/32\"}}"));
IotDeviceIdentity remote = provisionWithPolicy(true, policy("Allow", "arn:aws:iot:*:*:client/*",
"{\"IpAddress\":{\"aws:SourceIp\":\"10.0.0.0/8\"}}"));
MqttClient admitted = connectTls(local, "local-" + System.nanoTime());
assertTrue(admitted.isConnected());
admitted.disconnect();
admitted.close();
assertNotAuthorized(() -> connectTls(remote, "remote-" + System.nanoTime()));
}
@Test
void concurrentConnectsAreEachDecidedOnTheirOwnCertificate() throws Exception {
int devices = 8;
List<IotDeviceIdentity> admitted = new ArrayList<>();
List<IotDeviceIdentity> refused = new ArrayList<>();
for (int i = 0; i < devices; i++) {
admitted.add(provisionWithPolicy(true, CONNECT_ANY_CLIENT));
refused.add(IotDeviceIdentity.provision(true));
}
CountDownLatch start = new CountDownLatch(1);
ExecutorService pool = Executors.newFixedThreadPool(devices * 2);
List<Future<Boolean>> outcomes = new ArrayList<>();
try {
for (int i = 0; i < devices; i++) {
IotDeviceIdentity good = admitted.get(i);
IotDeviceIdentity bad = refused.get(i);
outcomes.add(pool.submit(() -> {
start.await();
MqttClient client = connectTls(good, "burst-ok-" + System.nanoTime());
boolean connected = client.isConnected();
client.disconnect();
client.close();
return connected;
}));
outcomes.add(pool.submit(() -> {
start.await();
try {
MqttClient client = connectTls(bad, "burst-no-" + System.nanoTime());
client.disconnect();
client.close();
return true;
} catch (MqttSecurityException e) {
return false;
}
}));
}
start.countDown();
int connected = 0;
for (Future<Boolean> outcome : outcomes) {
if (outcome.get(30, TimeUnit.SECONDS)) {
connected++;
}
}
assertEquals(devices, connected, "exactly the devices with a policy were admitted");
} finally {
pool.shutdownNow();
}
}
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);
return device;
}
private static MqttClient connectTls(IotDeviceIdentity device, String clientId) throws Exception {
return connect("ssl://127.0.0.1:" + TLS_PORT, clientId, device.sslContext(TLS_DIR).getSocketFactory());
}
private static MqttClient connect(String uri, String clientId, SSLSocketFactory socketFactory) throws Exception {
MqttClient client = new MqttClient(uri, clientId, new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
options.setCleanSession(true);
options.setConnectionTimeout(10);
options.setAutomaticReconnect(false);
if (socketFactory != null) {
options.setSocketFactory(socketFactory);
}
try {
client.connect(options);
} catch (MqttException e) {
client.close();
throw e;
}
return client;
}
private static org.eclipse.paho.mqttv5.client.MqttClient mqtt5Client(String clientId) throws Exception {
return new org.eclipse.paho.mqttv5.client.MqttClient("ssl://127.0.0.1:" + TLS_PORT, clientId, null);
}
private static org.eclipse.paho.mqttv5.client.MqttConnectionOptions mqtt5Options(SSLSocketFactory socketFactory) {
org.eclipse.paho.mqttv5.client.MqttConnectionOptions options = new org.eclipse.paho.mqttv5.client.MqttConnectionOptions();
options.setCleanStart(true);
options.setConnectionTimeout(10);
options.setAutomaticReconnect(false);
options.setSocketFactory(socketFactory);
return options;
}
private interface Connect {
MqttClient run() throws Exception;
}
/** The broker answered CONNACK not authorized (return code 5), which Paho reports as a security exception. */
private static void assertNotAuthorized(Connect connect) {
MqttException refused = assertThrows(MqttException.class, () -> {
MqttClient client = connect.run();
client.disconnect();
client.close();
});
assertInstanceOf(MqttSecurityException.class, refused, "expected CONNACK not authorized, got: " + refused);
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");
var 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)));
}
}
}
@@ -4,7 +4,6 @@ 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.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
@@ -19,20 +18,15 @@ import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.junit.jupiter.api.Test;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
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.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.time.Instant;
@@ -55,8 +49,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Devices connect to the MQTT over TLS listener the way they connect to AWS IoT's 8883: over
* {@code ssl://}, trusting one CA, verifying the endpoint name, with MQTT 3.1.1 or MQTT 5, and
* with the same broker behaviour as the plaintext listener.
* {@code ssl://}, trusting one CA, verifying the endpoint name, presenting a registered device
* certificate whose policy allows the connect, with MQTT 3.1.1 or MQTT 5, and with the same
* broker behaviour as the plaintext listener.
*/
@QuarkusTest
@TestProfile(IotMqttTlsIntegrationTest.Profile.class)
@@ -69,20 +64,43 @@ class IotMqttTlsIntegrationTest {
static final String LEARNED_HOST = "iot.dev.localhost.floci.io";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static IotDeviceIdentity device;
@Inject
TlsCertificateManager certificateManager;
@Inject
IotMqttBrokerService broker;
/**
* 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.
*/
private static synchronized 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;
}
return device;
}
@Test
void 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(), null)) {
try (TlsClient subscriber = TlsClient.connect("tls-sub-" + System.nanoTime())) {
subscriber.subscribe(topic, 1);
try (TlsClient publisher = TlsClient.connect("tls-pub-" + System.nanoTime(), null)) {
try (TlsClient publisher = TlsClient.connect("tls-pub-" + System.nanoTime())) {
publisher.publish(topic, payload, 1);
}
assertArrayEquals(payload, subscriber.takePayload());
@@ -97,7 +115,7 @@ class IotMqttTlsIntegrationTest {
new org.eclipse.paho.mqttv5.client.MqttConnectionOptions();
options.setCleanStart(true);
options.setConnectionTimeout(10);
options.setSocketFactory(trustOnlyTheCa(null).getSocketFactory());
options.setSocketFactory(device().sslContext(TLS_DIR).getSocketFactory());
try {
client.connect(options);
assertTrue(client.isConnected());
@@ -108,11 +126,10 @@ class IotMqttTlsIntegrationTest {
}
@Test
void aDeviceCertificateIssuedByTheCaIsAcceptedAndTheSessionIsVisibleToTheConnectionApi() throws Exception {
void aRegisteredDeviceIsAdmittedAndTheSessionIsVisibleToTheConnectionApi() throws Exception {
String clientId = "tls-device-" + System.nanoTime();
var device = FlociCertificateAuthority.loadOrCreate(TLS_DIR).issueClientCertificate("device-" + clientId);
try (TlsClient client = TlsClient.connect(clientId, keyManagers(device))) {
try (TlsClient client = TlsClient.connect(clientId)) {
assertTrue(client.isConnected());
given()
.queryParam("includeSocketInformation", true)
@@ -168,7 +185,7 @@ class IotMqttTlsIntegrationTest {
void aClientIdReconnectingOnThePlaintextListenerTakesOverTheTlsSession() throws Exception {
String clientId = "tls-takeover-" + System.nanoTime();
try (TlsClient first = TlsClient.connect(clientId, null)) {
try (TlsClient first = TlsClient.connect(clientId)) {
MqttClient second = new MqttClient("tcp://127.0.0.1:" + PLAIN_PORT, clientId, new MemoryPersistence());
try {
second.connect();
@@ -184,9 +201,9 @@ class IotMqttTlsIntegrationTest {
@Test
void shadowUpdateOverTlsPublishesTheAcceptedResponseOverTls() throws Exception {
String thing = "tlsThing" + System.nanoTime();
try (TlsClient subscriber = TlsClient.connect("tls-shadow-sub-" + System.nanoTime(), null)) {
try (TlsClient subscriber = TlsClient.connect("tls-shadow-sub-" + System.nanoTime())) {
subscriber.subscribe("$aws/things/" + thing + "/shadow/update/accepted", 0);
try (TlsClient publisher = TlsClient.connect("tls-shadow-pub-" + System.nanoTime(), null)) {
try (TlsClient publisher = TlsClient.connect("tls-shadow-pub-" + System.nanoTime())) {
publisher.publish("$aws/things/" + thing + "/shadow/update",
"{\"state\":{\"desired\":{\"color\":\"blue\"}},\"clientToken\":\"tls-token\"}".getBytes(StandardCharsets.UTF_8), 0);
}
@@ -201,7 +218,7 @@ class IotMqttTlsIntegrationTest {
broker.stop();
broker.startIfEnabled();
try (TlsClient client = TlsClient.connect("tls-restart-" + System.nanoTime(), null)) {
try (TlsClient client = TlsClient.connect("tls-restart-" + System.nanoTime())) {
assertTrue(client.isConnected());
}
}
@@ -213,7 +230,7 @@ class IotMqttTlsIntegrationTest {
*/
private static X509Certificate handshakeVerifying(String host) throws Exception {
try (Socket raw = new Socket("127.0.0.1", TLS_PORT);
SSLSocket socket = (SSLSocket) trustOnlyTheCa(null).getSocketFactory().createSocket(raw, host, TLS_PORT, true)) {
SSLSocket socket = (SSLSocket) trustOnlyTheCa().getSocketFactory().createSocket(raw, host, TLS_PORT, true)) {
SSLParameters params = socket.getSSLParameters();
params.setEndpointIdentificationAlgorithm("HTTPS");
socket.setSSLParameters(params);
@@ -222,26 +239,9 @@ class IotMqttTlsIntegrationTest {
}
}
private static SSLContext trustOnlyTheCa(KeyManager[] clientKeys) 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 context = SSLContext.getInstance("TLS");
context.init(clientKeys, tmf.getTrustManagers(), null);
return context;
}
private static KeyManager[] keyManagers(CertificateGenerator.GeneratedCertificate leaf) throws Exception {
CertificateGenerator generator = new CertificateGenerator();
KeyStore keys = KeyStore.getInstance(KeyStore.getDefaultType());
keys.load(null, null);
keys.setKeyEntry("device", generator.parsePrivateKey(leaf.privateKeyPem()), new char[0],
new Certificate[] {generator.parseCertificate(leaf.certificatePem())});
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keys, new char[0]);
return kmf.getKeyManagers();
/** A handshake with no client certificate: enough to read the served leaf, never followed by a CONNECT. */
private static SSLContext trustOnlyTheCa() throws Exception {
return IotDeviceIdentity.trustOnlySslContext(TLS_DIR);
}
private static Set<String> sans(X509Certificate leaf) throws Exception {
@@ -261,7 +261,7 @@ class IotMqttTlsIntegrationTest {
this.client = client;
}
static TlsClient connect(String clientId, KeyManager[] clientKeys) throws Exception {
static TlsClient connect(String clientId) throws Exception {
MqttClient client = new MqttClient("ssl://127.0.0.1:" + TLS_PORT, clientId, new MemoryPersistence());
TlsClient tlsClient = new TlsClient(client);
client.setCallback(new MqttCallback() {
@@ -282,7 +282,7 @@ class IotMqttTlsIntegrationTest {
options.setCleanSession(true);
options.setConnectionTimeout(10);
options.setAutomaticReconnect(false);
options.setSocketFactory(trustOnlyTheCa(clientKeys).getSocketFactory());
options.setSocketFactory(device().sslContext(TLS_DIR).getSocketFactory());
client.connect(options);
return tlsClient;
}
@@ -0,0 +1,422 @@
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.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.iot.IotService.RegisteredDevice;
import io.github.hectorvent.floci.services.iot.model.IotCertificate;
import io.github.hectorvent.floci.services.iot.model.IotPolicy;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* What lets a device onto the MQTT TLS listener: its certificate is registered, ACTIVE and within
* its validity, and the policies attached to it allow {@code iot:Connect} for the client id, with
* the AWS IoT policy variables and condition keys a connection carries.
*/
class IotServiceDeviceAuthTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = IotServiceTestSupport.ACCOUNT;
private static final String OTHER_ACCOUNT = "111111111111";
private static final CertificateGenerator GENERATOR = new CertificateGenerator();
private static final String CONNECT_ANY_CLIENT = statement("Allow", "arn:aws:iot:*:*:client/*", null);
private static final String CONNECT_AS_THING =
statement("Allow", "arn:aws:iot:*:*:client/${iot:Connection.Thing.ThingName}", null);
private static final String CONNECT_ATTACHED_THINGS_ONLY = statement("Allow", "arn:aws:iot:*:*:client/*",
"{\"Bool\":{\"iot:Connection.Thing.IsAttached\":\"true\"}}");
private static FlociCertificateAuthority ca;
private IotServiceTestSupport support;
private IotService service;
@BeforeAll
static void certificateAuthority(@TempDir Path tlsDir) {
ca = FlociCertificateAuthority.loadOrCreate(tlsDir);
}
@BeforeEach
void setUp() {
support = new IotServiceTestSupport(REGION, ca);
service = support.service;
}
@Test
void registeredActiveCertificateIsFoundByItsDerFingerprint() {
IotCertificate created = service.createKeysAndCertificate(true, REGION);
RegisteredDevice device = service.findRegisteredCertificate(parse(created)).orElseThrow();
assertEquals(created.getCertificateArn(), device.certificate().getCertificateArn());
assertEquals(ACCOUNT, device.accountId());
assertEquals(REGION, device.region());
}
@Test
void unknownCertificateIsNotFoundEvenWhenTheFlociCaSignedIt() {
service.createKeysAndCertificate(true, REGION);
X509Certificate stranger = GENERATOR.parseCertificate(ca.issueClientCertificate("stranger").certificatePem());
assertTrue(service.findRegisteredCertificate(stranger).isEmpty());
}
@Test
void aCertificateRegisteredInAnotherAccountIsFoundWithItsAccount() {
IotCertificate created = service.createKeysAndCertificate(true, "eu-west-1");
IotCertificate stored = service.describeCertificate(created.getCertificateId(), "eu-west-1");
support.certificates.delete("cert:eu-west-1:" + created.getCertificateId());
support.certificates.putForAccount(OTHER_ACCOUNT, "cert:eu-west-1:" + created.getCertificateId(), stored);
RegisteredDevice device = service.findRegisteredCertificate(parse(created)).orElseThrow();
assertEquals(OTHER_ACCOUNT, device.accountId());
assertEquals("eu-west-1", device.region());
assertEquals(created.getCertificateId(), device.certificate().getCertificateId());
}
@Test
void plainStoresWithoutAccountPartitionsWorkTheSameWay() {
IotService plain = new IotServiceTestSupport(REGION, ca, false).service;
IotCertificate created = plain.createKeysAndCertificate(true, REGION);
plain.createPolicy("p", CONNECT_ANY_CLIENT, REGION);
plain.attachPolicy("p", created.getCertificateArn(), REGION);
RegisteredDevice device = plain.findRegisteredCertificate(parse(created)).orElseThrow();
assertEquals(ACCOUNT, device.accountId(), "the resolver's default account stands in for the partition");
assertEquals(REGION, device.region());
assertTrue(plain.isConnectAllowed(device, "sensor-1", "127.0.0.1", null));
assertTrue(plain.findRegisteredCertificate(
GENERATOR.parseCertificate(ca.issueClientCertificate("stranger").certificatePem())).isEmpty());
}
/**
* Policy attachments, policy versions and thing attributes are replaced under a connecting
* device: every evaluation completes with a decision, never an exception, and the state the
* writers leave behind is the one the next evaluation sees.
*/
@Test
void evaluationsRacingPolicyAndThingChangesAlwaysComplete() throws Exception {
RegisteredDevice device = registeredDevice(true);
service.createThing("sensor-1", Map.of("envType", "prod"), REGION);
service.attachThingPrincipal("sensor-1", device.certificate().getCertificateArn(), REGION);
createAndAttach("p", statement("Allow", "arn:aws:iot:*:*:client/${iot:Connection.Thing.ThingName}",
"{\"StringEquals\":{\"iot:Connection.Thing.Attributes[envType]\":\"prod\"}}"), device);
int rounds = 200;
CountDownLatch start = new CountDownLatch(1);
ExecutorService pool = Executors.newFixedThreadPool(8);
List<Future<?>> outcomes = new ArrayList<>();
try {
for (int i = 0; i < 4; i++) {
outcomes.add(pool.submit(() -> {
start.await();
for (int round = 0; round < rounds; round++) {
service.detachPolicy("p", device.certificate().getCertificateArn(), REGION);
service.updateThing("sensor-1", Map.of("envType", round % 2 == 0 ? "test" : "prod"), null, REGION);
service.attachPolicy("p", device.certificate().getCertificateArn(), REGION);
}
return null;
}));
outcomes.add(pool.submit(() -> {
start.await();
for (int round = 0; round < rounds; round++) {
connect(device, "sensor-1");
}
return null;
}));
}
start.countDown();
for (Future<?> outcome : outcomes) {
outcome.get(60, TimeUnit.SECONDS);
}
} finally {
pool.shutdownNow();
}
service.updateThing("sensor-1", Map.of("envType", "prod"), null, REGION);
assertTrue(connect(device, "sensor-1"));
service.detachPolicy("p", device.certificate().getCertificateArn(), REGION);
assertFalse(connect(device, "sensor-1"));
}
/** The location a certificate was found at is remembered, and forgotten again the moment it stops resolving. */
@Test
void aCertificateFoundOnceIsFoundAgainAfterItMovesAndReflectsItsCurrentStatus() {
IotCertificate created = service.createKeysAndCertificate(true, REGION);
X509Certificate presented = parse(created);
String key = "cert:" + REGION + ":" + created.getCertificateId();
assertEquals(ACCOUNT, service.findRegisteredCertificate(presented).orElseThrow().accountId());
service.updateCertificate(created.getCertificateId(), "INACTIVE", REGION);
assertEquals("INACTIVE", service.findRegisteredCertificate(presented).orElseThrow().certificate().getStatus());
IotCertificate stored = service.describeCertificate(created.getCertificateId(), REGION);
support.certificates.delete(key);
assertTrue(service.findRegisteredCertificate(presented).isEmpty(), "deleted: no longer found");
support.certificates.putForAccount(OTHER_ACCOUNT, key, stored);
assertEquals(OTHER_ACCOUNT, service.findRegisteredCertificate(presented).orElseThrow().accountId());
assertEquals(OTHER_ACCOUNT, service.findRegisteredCertificate(presented).orElseThrow().accountId());
}
@Test
void activeCertificateWithConnectPolicyIsAllowed() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", CONNECT_ANY_CLIENT, device);
assertTrue(connect(device, "sensor-1"));
}
@Test
void activeCertificateWithoutPolicyIsDenied() {
assertFalse(connect(registeredDevice(true), "sensor-1"));
}
@Test
void inactiveCertificateIsDenied() {
RegisteredDevice device = registeredDevice(false);
createAndAttach("p", CONNECT_ANY_CLIENT, device);
assertFalse(connect(device, "sensor-1"));
}
@Test
void revokedCertificateIsDenied() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", CONNECT_ANY_CLIENT, device);
service.updateCertificate(device.certificate().getCertificateId(), "REVOKED", REGION);
assertFalse(connect(service.findRegisteredCertificate(parse(device.certificate())).orElseThrow(), "sensor-1"));
}
@Test
void expiredCertificateIsDenied() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", CONNECT_ANY_CLIENT, device);
device.certificate().setNotAfter(Instant.now().minusSeconds(1));
assertFalse(connect(device, "sensor-1"));
}
@Test
void notYetValidCertificateIsDenied() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", CONNECT_ANY_CLIENT, device);
device.certificate().setNotBefore(Instant.now().plusSeconds(3600));
assertFalse(connect(device, "sensor-1"));
}
@Test
void aBlankClientIdIsDenied() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", CONNECT_ANY_CLIENT, device);
assertFalse(connect(device, ""));
assertFalse(connect(device, null));
}
@Test
void detachedPolicyNoLongerAllows() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", CONNECT_ANY_CLIENT, device);
service.detachPolicy("p", device.certificate().getCertificateArn(), REGION);
assertFalse(connect(device, "sensor-1"));
}
@Test
void theDefaultPolicyVersionIsTheOneEvaluated() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", statement("Allow", "arn:aws:iot:*:*:client/only-this-one", null), device);
assertFalse(connect(device, "sensor-1"));
service.createPolicyVersion("p", CONNECT_ANY_CLIENT, true, REGION);
assertTrue(connect(device, "sensor-1"));
}
@Test
void aPolicyAttachedInAnotherRegionDoesNotCount() {
RegisteredDevice device = registeredDevice(true);
service.createPolicy("p", CONNECT_ANY_CLIENT, "eu-west-1");
service.attachPolicy("p", device.certificate().getCertificateArn(), "eu-west-1");
assertFalse(connect(device, "sensor-1"));
}
@Test
void policiesAreReadFromTheCertificatesOwnAccount() {
IotCertificate created = service.createKeysAndCertificate(true, REGION);
IotCertificate stored = service.describeCertificate(created.getCertificateId(), REGION);
support.certificates.delete("cert:" + REGION + ":" + created.getCertificateId());
support.certificates.putForAccount(OTHER_ACCOUNT, "cert:" + REGION + ":" + created.getCertificateId(), stored);
RegisteredDevice device = service.findRegisteredCertificate(parse(created)).orElseThrow();
createAndAttach("p", CONNECT_ANY_CLIENT, device);
assertFalse(connect(device, "sensor-1"), "a policy attached in the default account is not the device's");
IotPolicy policy = service.getPolicy("p", REGION);
support.policies.putForAccount(OTHER_ACCOUNT, "policy:" + REGION + ":p", policy);
support.policyAttachments.putForAccount(OTHER_ACCOUNT, "policy-attachment:" + REGION + ":p",
Set.of(created.getCertificateArn()));
assertTrue(connect(device, "sensor-1"));
}
@Test
void explicitDenyWins() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("allow", CONNECT_ANY_CLIENT, device);
createAndAttach("deny", statement("Deny", "arn:aws:iot:*:*:client/blocked", null), device);
assertTrue(connect(device, "sensor-1"));
assertFalse(connect(device, "blocked"));
}
@Test
void clientIdVariableResolvesToTheConnectingClientId() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", statement("Allow", "arn:aws:iot:" + REGION + ":" + ACCOUNT + ":client/${iot:ClientId}", null),
device);
assertTrue(connect(device, "sensor-1"));
}
@Test
void thingNameVariableResolvesOnlyForAThingAttachedToTheCertificate() {
RegisteredDevice device = registeredDevice(true);
service.createThing("sensor-1", Map.of(), REGION);
service.createThing("sensor-2", Map.of(), REGION);
service.attachThingPrincipal("sensor-1", device.certificate().getCertificateArn(), REGION);
createAndAttach("p", CONNECT_AS_THING, device);
assertTrue(connect(device, "sensor-1"));
assertFalse(connect(device, "sensor-2"), "a thing that exists but is not attached to this certificate");
assertFalse(connect(device, "sensor-3"), "a client id that names no thing");
}
@Test
void isAttachedConditionAdmitsOnlyAClientIdNamingAnAttachedThing() {
RegisteredDevice device = registeredDevice(true);
service.createThing("sensor-1", Map.of(), REGION);
service.attachThingPrincipal("sensor-1", device.certificate().getCertificateArn(), REGION);
createAndAttach("p", CONNECT_ATTACHED_THINGS_ONLY, device);
assertTrue(connect(device, "sensor-1"));
assertFalse(connect(device, "sensor-9"));
}
@Test
void thingTypeAndAttributesResolveForTheAttachedThing() {
RegisteredDevice device = registeredDevice(true);
service.createThingType("gateway", new ObjectMapper().createObjectNode(), REGION);
service.createThing("gw-prod", Map.of("envType", "prod"), "gateway", REGION);
service.createThing("gw-test", Map.of("envType", "prod"), "gateway", REGION);
service.attachThingPrincipal("gw-prod", device.certificate().getCertificateArn(), REGION);
service.attachThingPrincipal("gw-test", device.certificate().getCertificateArn(), REGION);
createAndAttach("p", statement("Allow", "arn:aws:iot:*:*:client/*",
"{\"StringEquals\":{\"iot:Connection.Thing.ThingTypeName\":\"gateway\"},"
+ "\"StringLike\":{\"iot:ClientId\":\"*${iot:Connection.Thing.Attributes[envType]}\"}}"), device);
assertTrue(connect(device, "gw-prod"), "the client id ends with the thing's envType attribute");
assertFalse(connect(device, "gw-test"), "the client id does not end with the attribute value");
}
@Test
void sourceIpConditionIsEvaluatedAgainstTheConnectionAddress() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", statement("Allow", "arn:aws:iot:*:*:client/*",
"{\"IpAddress\":{\"aws:SourceIp\":\"10.0.0.0/8\"}}"), device);
assertTrue(service.isConnectAllowed(device, "sensor-1", "10.1.2.3", null));
assertFalse(service.isConnectAllowed(device, "sensor-1", "127.0.0.1", null));
assertFalse(service.isConnectAllowed(device, "sensor-1", null, null), "no address, so the condition cannot hold");
}
@Test
void domainNameConditionIsEvaluatedAgainstTheNameTheClientConnectedTo() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("p", statement("Allow", "arn:aws:iot:*:*:client/*",
"{\"StringEquals\":{\"iot:DomainName\":\"iot.dev.localhost.floci.io\"}}"), device);
assertTrue(service.isConnectAllowed(device, "sensor-1", null, "iot.dev.localhost.floci.io"));
assertFalse(service.isConnectAllowed(device, "sensor-1", null, "other.localhost.floci.io"));
assertFalse(service.isConnectAllowed(device, "sensor-1", null, null));
}
@Test
void aStatementWithAVariableThatCannotBeResolvedNeverMatches() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("thing", CONNECT_AS_THING, device);
createAndAttach("cert", statement("Allow", "arn:aws:iot:*:*:client/${iot:Certificate.Subject.CommonName}", null),
device);
assertFalse(connect(device, "${iot:Connection.Thing.ThingName}"),
"an unattached client cannot match the unresolved variable by spelling it out");
assertFalse(connect(device, "AWS IoT Certificate"), "certificate policy variables are not resolved");
assertFalse(connect(device, "${iot:Certificate.Subject.CommonName}"));
}
@Test
void aClientIdCarryingJsonSyntaxIsDataNotPolicy() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("allow", CONNECT_ANY_CLIENT, device);
createAndAttach("deny", statement("Deny", "arn:aws:iot:*:*:client/${iot:ClientId}", null), device);
assertFalse(connect(device, "sensor-1"), "the deny names every client id");
assertFalse(connect(device, "x\",\"Effect\":\"Allow\",\"Z\":\""),
"a client id that would rewrite the statement as text is still just a client id");
}
@Test
void anUnparseablePolicyDocumentDenies() {
RegisteredDevice device = registeredDevice(true);
createAndAttach("broken", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"", device);
assertFalse(connect(device, "sensor-1"));
}
private RegisteredDevice registeredDevice(boolean active) {
IotCertificate created = service.createKeysAndCertificate(active, REGION);
return service.findRegisteredCertificate(parse(created)).orElseThrow();
}
private void createAndAttach(String policyName, String document, RegisteredDevice device) {
service.createPolicy(policyName, document, REGION);
service.attachPolicy(policyName, device.certificate().getCertificateArn(), REGION);
}
private boolean connect(RegisteredDevice device, String clientId) {
return service.isConnectAllowed(device, clientId, "127.0.0.1", null);
}
private static X509Certificate parse(IotCertificate certificate) {
return GENERATOR.parseCertificate(certificate.getCertificatePem());
}
private static String statement(String effect, String resource, String condition) {
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"" + effect + "\",\"Action\":\"iot:Connect\","
+ "\"Resource\":\"" + resource + "\"" + (condition == null ? "" : ",\"Condition\":" + condition) + "}]}";
}
}
@@ -105,7 +105,8 @@ class IotServiceTest {
lambda,
firehose,
logs,
mock(io.github.hectorvent.floci.config.FlociCertificateAuthority.class));
mock(io.github.hectorvent.floci.config.FlociCertificateAuthority.class),
new io.github.hectorvent.floci.services.iam.IamPolicyEvaluator(mapper));
}
private IotTopicRule createRule(String name, String payloadJson) throws Exception {
@@ -0,0 +1,84 @@
package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iot.model.IotCertificate;
import io.github.hectorvent.floci.services.iot.model.IotPolicy;
import io.github.hectorvent.floci.services.iot.model.Thing;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import java.util.Set;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* An {@link IotService} over in-memory stores, account-aware as in production or plain, with
* every collaborator that a device authorization test does not exercise mocked. The account-aware
* stores stay reachable so a test can place a record in another account's partition, which no
* API call does.
*/
final class IotServiceTestSupport {
static final String ACCOUNT = "000000000000";
final AccountAwareStorageBackend<Thing> things = AccountAwareStorageBackend.inMemory(ACCOUNT);
final AccountAwareStorageBackend<IotCertificate> certificates = AccountAwareStorageBackend.inMemory(ACCOUNT);
final AccountAwareStorageBackend<IotPolicy> policies = AccountAwareStorageBackend.inMemory(ACCOUNT);
final AccountAwareStorageBackend<Set<String>> policyAttachments = AccountAwareStorageBackend.inMemory(ACCOUNT);
final AccountAwareStorageBackend<Set<String>> thingPrincipals = AccountAwareStorageBackend.inMemory(ACCOUNT);
final IotService service;
IotServiceTestSupport(String region, FlociCertificateAuthority certificateAuthority) {
this(region, certificateAuthority, true);
}
IotServiceTestSupport(String region, FlociCertificateAuthority certificateAuthority, boolean accountAware) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultRegion()).thenReturn(region);
when(config.services().iot().ruleSqlStrict()).thenReturn(false);
ObjectMapper objectMapper = new ObjectMapper();
service = new IotService(
accountAware ? things : new InMemoryStorage<>(),
accountAware ? certificates : new InMemoryStorage<>(),
accountAware ? policies : new InMemoryStorage<>(),
accountAware ? policyAttachments : new InMemoryStorage<>(),
accountAware ? thingPrincipals : new InMemoryStorage<>(),
AccountAwareStorageBackend.inMemory(ACCOUNT), // shadows
AccountAwareStorageBackend.inMemory(ACCOUNT), // topic rules
AccountAwareStorageBackend.inMemory(ACCOUNT), // retained messages
AccountAwareStorageBackend.inMemory(ACCOUNT), // jobs
AccountAwareStorageBackend.inMemory(ACCOUNT), // job executions
AccountAwareStorageBackend.inMemory(ACCOUNT), // thing types
AccountAwareStorageBackend.inMemory(ACCOUNT), // thing groups
AccountAwareStorageBackend.inMemory(ACCOUNT), // thing group memberships
config,
new RegionResolver(region, ACCOUNT),
objectMapper,
new IotPublishEventRecorder(),
mock(IotMqttBrokerService.class),
mock(SqsService.class),
mock(SnsService.class),
mock(S3Service.class),
mock(KinesisService.class),
mock(DynamoDbService.class),
mock(LambdaService.class),
mock(FirehoseService.class),
mock(CloudWatchLogsService.class),
certificateAuthority,
new IamPolicyEvaluator(objectMapper));
}
}