mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 09:47:56 -05:00
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:
1 parent
a1d0597ffe
commit
19a85360e1
10 files changed
+1729
-67
No files matched your search
@@ -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();
|
||||
}
|
||||
}
|
||||
+337
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+395
@@ -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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
-41
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user