feat(iot): MQTT over TLS listener on 8883 (#3142)

* feat(iot): floci.services.iot.mqtt.tls-port (default 8883)

* feat(iot): key manager that follows the TLS registry's current default certificate

* feat(iot): MQTT over TLS listener on 8883

Second MqttServer sharing the plaintext handlers, opened when floci.tls.enabled
is true. Its key material is the TLS registry's default configuration through a
reloading key manager, so a server certificate reissued for a learned hostname
is presented on the next handshake without rebuilding the listener. Client
certificates are requested and carried through the handshake, not yet verified.

* docs(iot): MQTT over TLS on 8883

* feat(iot): keep retired server key material readable for the life of a handshake

A retired generation of ReloadingKeyManager stays readable for 60 seconds after
its replacement, longer than Vert.x's 10 second handshake timeout, and is dropped
on the next reload after that. Any number of reloads between JSSE choosing an
alias and reading its key and chain now resolve to matching material.

* fix(iot): wait for a failed MQTT listener to close before reporting the start failure
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-06 15:55:19 -05:00
1 parent e3230a74ab
commit ee2f55b784
10 files changed
+1348 -14

No files matched your search

@@ -793,6 +793,13 @@ public interface EmulatorConfig {
@WithDefault("1883")
int port();
/**
* MQTT over TLS listener, the port AWS IoT serves for X.509 device connections. Opened only
* while {@code floci.tls.enabled} is true; {@code 0} disables it. Env: FLOCI_SERVICES_IOT_MQTT_TLS_PORT
*/
@WithDefault("8883")
int tlsPort();
}
interface IotDataServiceConfig {
@@ -5,9 +5,16 @@ import io.github.hectorvent.floci.services.iot.model.IotRetainedMessage;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import io.quarkus.tls.CertificateUpdatedEvent;
import io.quarkus.tls.TlsConfiguration;
import io.quarkus.tls.TlsConfigurationRegistry;
import io.quarkus.tls.runtime.config.TlsConfig;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.ClientAuth;
import io.vertx.core.net.KeyCertOptions;
import io.vertx.core.net.SocketAddress;
import io.vertx.core.net.TrustOptions;
import io.vertx.mqtt.MqttEndpoint;
import io.vertx.mqtt.MqttServer;
import io.vertx.mqtt.MqttServerOptions;
@@ -20,6 +27,11 @@ import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
@@ -34,18 +46,63 @@ 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.
*/
static final X509ExtendedTrustManager ACCEPT_ANY_CLIENT_CERTIFICATE = new X509ExtendedTrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
throw new CertificateException("server-side trust manager");
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
throw new CertificateException("server-side trust manager");
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
throw new CertificateException("server-side trust manager");
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
private final EmulatorConfig config;
private final Vertx vertx;
private final Instance<IotService> iotService;
private final TlsConfigurationRegistry tlsRegistry;
private final Map<String, ClientSession> sessionsByClient = new ConcurrentHashMap<>();
private final Map<String, Map<String, Subscription>> subscriptionsByClient = new ConcurrentHashMap<>();
private MqttServer server;
private MqttServer tlsServer;
private ReloadingKeyManager keyManager;
@Inject
public IotMqttBrokerService(EmulatorConfig config, Vertx vertx, Instance<IotService> iotService) {
public IotMqttBrokerService(EmulatorConfig config, Vertx vertx, Instance<IotService> iotService,
TlsConfigurationRegistry tlsRegistry) {
this.config = config;
this.vertx = vertx;
this.iotService = iotService;
this.tlsRegistry = tlsRegistry;
}
void onStart(@Observes StartupEvent ignored) {
@@ -72,33 +129,100 @@ public class IotMqttBrokerService {
return;
}
MqttServer mqttServer = MqttServer.create(vertx, new MqttServerOptions()
MqttServer mqttServer = listen(new MqttServerOptions()
.setHost(config.services().iot().mqtt().host())
.setPort(config.services().iot().mqtt().port()));
mqttServer.endpointHandler(this::handleEndpoint);
mqttServer.exceptionHandler(error -> LOG.warnv("IoT MQTT broker error: {0}", error.getMessage()));
.setPort(config.services().iot().mqtt().port()), "IoT MQTT broker");
try {
startTlsListener();
} catch (RuntimeException e) {
mqttServer.close().toCompletionStage().toCompletableFuture().join();
throw e;
}
server = mqttServer;
}
/**
* 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.
*/
private void startTlsListener() {
int tlsPort = config.services().iot().mqtt().tlsPort();
if (tlsPort <= 0) {
return;
}
if (!config.tls().enabled()) {
LOG.infov("IoT MQTT TLS listener not started on port {0}: floci.tls.enabled is false", Integer.toString(tlsPort));
return;
}
TlsConfiguration tls = tlsRegistry.getDefault().orElse(null);
if (tls == null) {
LOG.warnv("IoT MQTT TLS listener not started on port {0}: no default TLS configuration is registered",
Integer.toString(tlsPort));
return;
}
ReloadingKeyManager manager = new ReloadingKeyManager(ReloadingKeyManager.keyManagerOf(vertx, tls.getKeyStoreOptions()));
tlsServer = listen(new MqttServerOptions()
.setHost(config.services().iot().mqtt().host())
.setPort(tlsPort)
.setSsl(true)
.setKeyCertOptions(KeyCertOptions.wrap(manager))
.setTrustOptions(TrustOptions.wrap(ACCEPT_ANY_CLIENT_CERTIFICATE))
.setClientAuth(ClientAuth.REQUEST), "IoT MQTT TLS broker");
keyManager = manager;
}
private MqttServer listen(MqttServerOptions options, String name) {
MqttServer mqttServer = MqttServer.create(vertx, options);
mqttServer.endpointHandler(this::handleEndpoint);
mqttServer.exceptionHandler(error -> LOG.warnv("{0} error: {1}", name, error.getMessage()));
try {
mqttServer.listen().toCompletionStage().toCompletableFuture().join();
server = mqttServer;
LOG.infov("IoT MQTT broker started on {0}:{1}",
config.services().iot().mqtt().host(), config.services().iot().mqtt().port());
} catch (Exception e) {
mqttServer.close();
throw new IllegalStateException("Failed to start IoT MQTT broker", e);
mqttServer.close().toCompletionStage().toCompletableFuture().join();
throw new IllegalStateException("Failed to start " + name + " on port " + options.getPort(), e);
}
LOG.infov("{0} started on {1}:{2}", name, options.getHost(), Integer.toString(options.getPort()));
return mqttServer;
}
/**
* The HTTPS server switches to a reissued server certificate through this event (a hostname
* learned by {@code TlsCertificateManager.ensureHost}, or a reload). The TLS listener follows
* by handing its key manager the reloaded key store: the next handshake presents the new
* certificate, established sessions keep theirs, and a failed reload keeps the previous one.
*/
synchronized void onCertificateUpdated(@Observes CertificateUpdatedEvent event) {
ReloadingKeyManager manager = keyManager;
if (manager == null || !TlsConfig.DEFAULT_NAME.equalsIgnoreCase(event.name())) {
return;
}
try {
manager.reload(ReloadingKeyManager.keyManagerOf(vertx, event.tlsConfiguration().getKeyStoreOptions()));
LOG.debug("IoT MQTT TLS broker serves the reloaded server certificate");
} catch (Exception e) {
LOG.warnv(e, "IoT MQTT TLS broker keeps its previous server certificate: {0}", e.getMessage());
}
}
synchronized void stop() {
MqttServer mqttServer = server;
if (mqttServer == null) {
MqttServer mqttTlsServer = tlsServer;
if (mqttServer == null && mqttTlsServer == null) {
return;
}
server = null;
tlsServer = null;
keyManager = null;
sessionsByClient.values().forEach(session -> session.endpoint().close());
sessionsByClient.clear();
subscriptionsByClient.clear();
mqttServer.close().toCompletionStage().toCompletableFuture().join();
if (mqttServer != null) {
mqttServer.close().toCompletionStage().toCompletableFuture().join();
}
if (mqttTlsServer != null) {
mqttTlsServer.close().toCompletionStage().toCompletableFuture().join();
}
LOG.info("IoT MQTT broker stopped");
}
@@ -0,0 +1,172 @@
package io.github.hectorvent.floci.services.iot;
import io.vertx.core.Vertx;
import io.vertx.core.net.KeyCertOptions;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509KeyManager;
import java.net.Socket;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.function.LongSupplier;
/**
* Server key manager for the MQTT TLS listener that answers every handshake from the key material
* it was last given, so a reissued server certificate is served without rebuilding the listener's
* SSL context: Vert.x drops the connections it accepts while a context is being rebuilt, whereas
* JSSE asks the key manager for an alias, then that alias's key and chain, on every handshake.
*
* <p>The alias handed to JSSE names the generation it came from, and a retired generation stays
* readable for {@link #RETIRED_GENERATION_RETENTION} after its replacement, longer than any
* handshake can live (Vert.x closes a connection whose handshake exceeds its 10 second timeout), so
* a handshake that began before any number of reloads still reads a matching key and chain.
* Retired generations are dropped on the next reload after that window.
*/
final class ReloadingKeyManager extends X509ExtendedKeyManager {
static final Duration RETIRED_GENERATION_RETENTION = Duration.ofSeconds(60);
private record Generation(long number, X509KeyManager delegate, long retiredAtNanos) {
}
private final LongSupplier nanoTime;
private volatile Generation current;
/** Superseded generations, newest first, each within the retention window at its last reload. */
private volatile List<Generation> retired = List.of();
ReloadingKeyManager(X509KeyManager delegate) {
this(delegate, System::nanoTime);
}
ReloadingKeyManager(X509KeyManager delegate, LongSupplier nanoTime) {
this.nanoTime = nanoTime;
this.current = new Generation(0, delegate, 0);
}
/** The first X.509 key manager of {@code options}, the TLS registry's default key store. */
static X509KeyManager keyManagerOf(Vertx vertx, KeyCertOptions options) {
if (options == null) {
throw new IllegalStateException("the default TLS configuration has no key store");
}
KeyManagerFactory factory;
try {
factory = options.getKeyManagerFactory(vertx);
} catch (Exception e) {
throw new IllegalStateException("the default TLS configuration's key store cannot be loaded: " + e.getMessage(), e);
}
if (factory != null) {
for (KeyManager manager : factory.getKeyManagers()) {
if (manager instanceof X509KeyManager x509) {
return x509;
}
}
}
throw new IllegalStateException("the default TLS configuration has no X.509 key manager");
}
/** Serves {@code delegate} from the next handshake on; the generations before it stay readable for a while. */
synchronized void reload(X509KeyManager delegate) {
long now = nanoTime.getAsLong();
List<Generation> kept = new ArrayList<>();
kept.add(new Generation(current.number(), current.delegate(), now));
for (Generation generation : retired) {
if (now - generation.retiredAtNanos() < RETIRED_GENERATION_RETENTION.toNanos()) {
kept.add(generation);
}
}
retired = List.copyOf(kept);
current = new Generation(current.number() + 1, delegate, 0);
}
int retiredGenerations() {
return retired.size();
}
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
Generation generation = current;
return qualify(generation, generation.delegate() instanceof X509ExtendedKeyManager extended
? extended.chooseEngineServerAlias(keyType, issuers, engine)
: generation.delegate().chooseServerAlias(keyType, issuers, null));
}
@Override
public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
Generation generation = current;
return qualify(generation, generation.delegate().chooseServerAlias(keyType, issuers, socket));
}
@Override
public String[] getServerAliases(String keyType, Principal[] issuers) {
Generation generation = current;
String[] aliases = generation.delegate().getServerAliases(keyType, issuers);
if (aliases == null) {
return new String[0];
}
String[] qualified = new String[aliases.length];
for (int i = 0; i < aliases.length; i++) {
qualified[i] = qualify(generation, aliases[i]);
}
return qualified;
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
Generation generation = generationOf(alias);
return generation == null ? null : generation.delegate().getCertificateChain(unqualified(alias));
}
@Override
public PrivateKey getPrivateKey(String alias) {
Generation generation = generationOf(alias);
return generation == null ? null : generation.delegate().getPrivateKey(unqualified(alias));
}
@Override
public String[] getClientAliases(String keyType, Principal[] issuers) {
return new String[0];
}
@Override
public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
return null;
}
@Override
public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {
return null;
}
private static String qualify(Generation generation, String alias) {
return alias == null ? null : generation.number() + ":" + alias;
}
private static String unqualified(String alias) {
return alias.substring(alias.indexOf(':') + 1);
}
private Generation generationOf(String alias) {
int separator = alias == null ? -1 : alias.indexOf(':');
if (separator <= 0) {
return null;
}
String number = alias.substring(0, separator);
Generation candidate = current;
if (Long.toString(candidate.number()).equals(number)) {
return candidate;
}
for (Generation generation : retired) {
if (Long.toString(generation.number()).equals(number)) {
return generation;
}
}
return null;
}
}