Search in sources :

Example 6 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class AbstractVertxBasedMqttProtocolAdapterTest method testEndpointHandlerRejectsDeviceOfDisabledTenant.

/**
 * Verifies that an adapter rejects a connection attempt from a device that belongs to a tenant for which the
 * adapter is disabled.
 */
@Test
public void testEndpointHandlerRejectsDeviceOfDisabledTenant() {
    // GIVEN an adapter
    givenAnAdapter(properties);
    // which is disabled for tenant "my-tenant"
    final TenantObject myTenantConfig = TenantObject.from("my-tenant", true);
    myTenantConfig.addAdapter(new Adapter(ADAPTER_TYPE).setEnabled(Boolean.FALSE));
    when(tenantClient.get(eq("my-tenant"), (SpanContext) any())).thenReturn(Future.succeededFuture(myTenantConfig));
    when(authHandler.authenticateDevice(any(MqttConnectContext.class))).thenReturn(Future.succeededFuture(new DeviceUser("my-tenant", "4711")));
    // WHEN a device of "my-tenant" tries to connect
    final MqttEndpoint endpoint = mockEndpoint();
    adapter.handleEndpointConnection(endpoint);
    // THEN the connection is not established
    verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
    verify(metrics).reportConnectionAttempt(ConnectionAttemptOutcome.ADAPTER_DISABLED, "my-tenant", null);
}
Also used : TenantObject(org.eclipse.hono.util.TenantObject) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) Adapter(org.eclipse.hono.util.Adapter) Test(org.junit.jupiter.api.Test)

Example 7 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class AbstractVertxBasedMqttProtocolAdapterTest method verifyEventMessageUsesTtlValueGivenInPropertyBag.

/**
 * Verifies that the TTL for a downstream event is set to the given <em>time-to-live</em> value in the
 * <em>property-bag</em>.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void verifyEventMessageUsesTtlValueGivenInPropertyBag(final VertxTestContext ctx) {
    // Given an adapter
    givenAnAdapter(properties);
    givenAnEventSenderForAnyTenant();
    // WHEN a "device" of "tenant" publishes an event message with a TTL value of 30 seconds.
    final MqttPublishMessage msg = mock(MqttPublishMessage.class);
    when(msg.topicName()).thenReturn("e/tenant/device/?hono-ttl=30&param2=value2");
    when(msg.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
    adapter.uploadEventMessage(newMqttContext(msg, mockEndpoint(), span), "tenant", "device", Buffer.buffer("test")).onComplete(ctx.succeeding(t -> {
        ctx.verify(() -> {
            // THEN the TTL value of the amqp message is 30 seconds.
            assertEventHasBeenSentDownstream("tenant", "device", null, 30L);
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) Context(io.vertx.core.Context) Timeout(io.vertx.junit5.Timeout) AfterAll(org.junit.jupiter.api.AfterAll) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) MessagingType(org.eclipse.hono.util.MessagingType) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BeforeAll(org.junit.jupiter.api.BeforeAll) Mockito.doAnswer(org.mockito.Mockito.doAnswer) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) AuthHandler(org.eclipse.hono.adapter.auth.device.AuthHandler) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Test(org.junit.jupiter.api.Test) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) QoS(org.eclipse.hono.util.QoS) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AbstractNotification(org.eclipse.hono.notification.AbstractNotification) VertxTestContext(io.vertx.junit5.VertxTestContext) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) MqttConnectReturnCode(io.netty.handler.codec.mqtt.MqttConnectReturnCode) ClientErrorException(org.eclipse.hono.client.ClientErrorException) OptionalInt(java.util.OptionalInt) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) Commands(org.eclipse.hono.client.command.Commands) Constants(org.eclipse.hono.util.Constants) ArrayList(java.util.ArrayList) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) MqttServer(io.vertx.mqtt.MqttServer) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) SSLSession(javax.net.ssl.SSLSession) ArgumentCaptor(org.mockito.ArgumentCaptor) MqttTopicSubscription(io.vertx.mqtt.MqttTopicSubscription) BiConsumer(java.util.function.BiConsumer) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) Promise(io.vertx.core.Promise) MqttSubscribeMessage(io.vertx.mqtt.messages.MqttSubscribeMessage) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) TimeUnit(java.util.concurrent.TimeUnit) Mockito.never(org.mockito.Mockito.never) Adapter(org.eclipse.hono.util.Adapter) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) MqttAuth(io.vertx.mqtt.MqttAuth) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) Handler(io.vertx.core.Handler) Collections(java.util.Collections) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) Test(org.junit.jupiter.api.Test)

Example 8 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class AbstractVertxBasedMqttProtocolAdapterTest method testUploadTelemetryMessageFailsForDisabledTenant.

/**
 * Verifies that the adapter does not forward a message published by a device if the device belongs to a tenant for
 * which the adapter has been disabled and that the adapter closes the connection to the device.
 */
@Test
public void testUploadTelemetryMessageFailsForDisabledTenant() {
    // GIVEN an adapter
    properties.setAuthenticationRequired(false);
    givenAnAdapter(properties);
    givenATelemetrySenderForAnyTenant();
    // which is disabled for tenant "my-tenant"
    final TenantObject myTenantConfig = TenantObject.from("my-tenant", true);
    myTenantConfig.addAdapter(new Adapter(ADAPTER_TYPE).setEnabled(Boolean.FALSE));
    when(tenantClient.get(eq("my-tenant"), (SpanContext) any())).thenReturn(Future.succeededFuture(myTenantConfig));
    // WHEN a device of "my-tenant" publishes a telemetry message
    final MqttEndpoint endpoint = mockEndpoint();
    when(endpoint.isConnected()).thenReturn(Boolean.TRUE);
    adapter.handleEndpointConnection(endpoint);
    final ArgumentCaptor<Handler<MqttPublishMessage>> messageHandler = VertxMockSupport.argumentCaptorHandler();
    verify(endpoint).publishHandler(messageHandler.capture());
    final MqttPublishMessage msg = mock(MqttPublishMessage.class);
    when(msg.topicName()).thenReturn("t/my-tenant/the-device");
    when(msg.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
    when(msg.payload()).thenReturn(Buffer.buffer("hello"));
    messageHandler.getValue().handle(msg);
    // THEN the message has not been sent downstream
    assertNoTelemetryMessageHasBeenSentDownstream();
    verify(metrics, never()).reportTelemetry(any(MetricsTags.EndpointType.class), anyString(), any(), eq(MetricsTags.ProcessingOutcome.FORWARDED), any(MetricsTags.QoS.class), anyInt(), any());
    // and the connection to the client has been closed
    verify(endpoint).close();
}
Also used : TenantObject(org.eclipse.hono.util.TenantObject) QoS(org.eclipse.hono.util.QoS) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) AuthHandler(org.eclipse.hono.adapter.auth.device.AuthHandler) Handler(io.vertx.core.Handler) Adapter(org.eclipse.hono.util.Adapter) Test(org.junit.jupiter.api.Test)

Example 9 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class AmqpConnectionIT method testConnectFailsAfterDeviceDeleted.

/**
 * Verifies that after a device has already connected successfully to the adapter, the deletion of device
 * registration data causes the adapter to refuse any following connection attempts.
 * <p>
 * This test relies upon the registration client cache data in the adapter getting deleted when the device is
 * deleted (triggered via a corresponding notification from the device registry).
 *
 * @param ctx The test context.
 */
@Test
public void testConnectFailsAfterDeviceDeleted(final VertxTestContext ctx) {
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String password = "secret";
    final Tenant tenant = new Tenant();
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, password).compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), password)).compose(con -> {
        // first connection attempt successful
        con.close();
        // now remove device
        return helper.registry.deregisterDevice(tenantId, deviceId);
    }).compose(ok -> {
        final Promise<Void> resultPromise = Promise.promise();
        // device deleted, now wait a bit for the device registry notifications to trigger registration cache invalidation
        vertx.setTimer(500, tid -> resultPromise.complete());
        return resultPromise.future();
    }).compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), password)).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(t).isInstanceOf(AuthenticationException.class));
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) KeyPair(java.security.KeyPair) CsvSource(org.junit.jupiter.params.provider.CsvSource) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) ClientErrorException(org.eclipse.hono.client.ClientErrorException) SaslException(javax.security.sasl.SaslException) Supplier(java.util.function.Supplier) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) GeneralSecurityException(java.security.GeneralSecurityException) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) JsonObject(io.vertx.core.json.JsonObject) Tenants(org.eclipse.hono.tests.Tenants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) ValueSource(org.junit.jupiter.params.provider.ValueSource) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Promise(io.vertx.core.Promise) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) UUID(java.util.UUID) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Adapter(org.eclipse.hono.util.Adapter) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) AuthenticationException(javax.security.sasl.AuthenticationException) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 10 with Adapter

use of org.eclipse.hono.util.Adapter in project hono by eclipse.

the class CoapTestBase method testUploadMessageFailsForDisabledGateway.

/**
 * Verifies that the CoAP adapter rejects messages from a disabled gateway
 * for an enabled device with a 403.
 *
 * @param ctx The test context
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadMessageFailsForDisabledGateway(final VertxTestContext ctx) {
    // GIVEN a device that is connected via a disabled gateway
    final Tenant tenant = new Tenant();
    final String gatewayId = helper.getRandomDeviceId(tenantId);
    final Device gatewayData = new Device();
    gatewayData.setEnabled(false);
    final Device deviceData = new Device();
    deviceData.setVia(Collections.singletonList(gatewayId));
    helper.registry.addPskDeviceForTenant(tenantId, tenant, gatewayId, gatewayData, SECRET).compose(ok -> helper.registry.registerDevice(tenantId, deviceId, deviceData)).compose(ok -> {
        // WHEN the gateway tries to upload a message for the device
        final Promise<OptionSet> result = Promise.promise();
        final CoapClient client = getCoapsClient(gatewayId, tenantId, SECRET);
        // THEN a FORBIDDEN response code is returned
        client.advanced(getHandler(result, ResponseCode.FORBIDDEN), createCoapsRequest(Code.PUT, getPutResource(tenantId, deviceId), 0));
        return result.future();
    }).onComplete(ctx.succeedingThenComplete());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) KeyPair(java.security.KeyPair) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) AdvancedPskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedPskStore) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) CertificateType(org.eclipse.californium.scandium.dtls.CertificateType) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) CoapResponse(org.eclipse.californium.core.CoapResponse) NetworkConfig(org.eclipse.californium.core.network.config.NetworkConfig) GeneralSecurityException(java.security.GeneralSecurityException) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Utils(org.eclipse.californium.core.Utils) JsonObject(io.vertx.core.json.JsonObject) URI(java.net.URI) Tenants(org.eclipse.hono.tests.Tenants) MethodSource(org.junit.jupiter.params.provider.MethodSource) Device(org.eclipse.hono.service.management.device.Device) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) MessageContext(org.eclipse.hono.application.client.MessageContext) SubscriberRole(org.eclipse.hono.tests.CommandEndpointConfiguration.SubscriberRole) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) InetSocketAddress(java.net.InetSocketAddress) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) Request(org.eclipse.californium.core.coap.Request) Buffer(io.vertx.core.buffer.Buffer) Optional(java.util.Optional) QoS(org.eclipse.hono.util.QoS) VertxTestContext(io.vertx.junit5.VertxTestContext) CoapClient(org.eclipse.californium.core.CoapClient) X500Principal(javax.security.auth.x500.X500Principal) KeyLoader(org.eclipse.hono.config.KeyLoader) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Constants(org.eclipse.hono.util.Constants) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) MediaTypeRegistry(org.eclipse.californium.core.coap.MediaTypeRegistry) StaticNewAdvancedCertificateVerifier(org.eclipse.californium.scandium.dtls.x509.StaticNewAdvancedCertificateVerifier) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Type(org.eclipse.californium.core.coap.CoAP.Type) Logger(org.slf4j.Logger) AdvancedSinglePskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedSinglePskStore) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Truth.assertThat(com.google.common.truth.Truth.assertThat) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Code(org.eclipse.californium.core.coap.CoAP.Code) Adapter(org.eclipse.hono.util.Adapter) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) CoapHandler(org.eclipse.californium.core.CoapHandler) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) OptionSet(org.eclipse.californium.core.coap.OptionSet) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Promise(io.vertx.core.Promise) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Device(org.eclipse.hono.service.management.device.Device) CoapClient(org.eclipse.californium.core.CoapClient) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Timeout(io.vertx.junit5.Timeout)

Aggregations

Adapter (org.eclipse.hono.util.Adapter)77 Test (org.junit.jupiter.api.Test)74 Truth.assertThat (com.google.common.truth.Truth.assertThat)64 VertxTestContext (io.vertx.junit5.VertxTestContext)64 HttpURLConnection (java.net.HttpURLConnection)64 Timeout (io.vertx.junit5.Timeout)63 TimeUnit (java.util.concurrent.TimeUnit)63 Constants (org.eclipse.hono.util.Constants)62 Future (io.vertx.core.Future)61 Promise (io.vertx.core.Promise)61 JsonObject (io.vertx.core.json.JsonObject)47 Tenant (org.eclipse.hono.service.management.tenant.Tenant)47 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)47 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)45 Tenants (org.eclipse.hono.tests.Tenants)45 BeforeEach (org.junit.jupiter.api.BeforeEach)45 RegistryManagementConstants (org.eclipse.hono.util.RegistryManagementConstants)44 VertxExtension (io.vertx.junit5.VertxExtension)42 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)42 Buffer (io.vertx.core.buffer.Buffer)40