Search in sources :

Example 56 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class HttpTestBase method testUploadFailsForWrongCredentials.

/**
 * Verifies that the adapter fails to authenticate a device that is providing
 * wrong credentials.
 *
 * @param ctx The vert.x test context.
 * @throws InterruptedException if the test fails.
 */
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
public void testUploadFailsForWrongCredentials(final VertxTestContext ctx) throws InterruptedException {
    final VertxTestContext setup = new VertxTestContext();
    final Tenant tenant = new Tenant();
    final MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/plain").add(HttpHeaders.AUTHORIZATION, getBasicAuth(tenantId, deviceId, "wrong password")).add(HttpHeaders.ORIGIN, ORIGIN_URI);
    // GIVEN a device
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).onComplete(setup.succeedingThenComplete());
    assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
        return;
    }
    // WHEN a device tries to upload data and authenticate using wrong credentials
    httpClient.create(getEndpointUri(), Buffer.buffer("hello"), requestHeaders, ResponsePredicate.status(HttpURLConnection.HTTP_UNAUTHORIZED)).onComplete(ctx.succeedingThenComplete());
}
Also used : MultiMap(io.vertx.core.MultiMap) Tenant(org.eclipse.hono.service.management.tenant.Tenant) VertxTestContext(io.vertx.junit5.VertxTestContext) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Timeout(io.vertx.junit5.Timeout)

Example 57 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class HttpTestBase method testUploadMessagesUsingBasicAuth.

/**
 * Verifies that a number of messages uploaded to Hono's HTTP adapter
 * using HTTP Basic auth can be successfully consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessagesUsingBasicAuth(final VertxTestContext ctx) throws InterruptedException {
    final VertxTestContext setup = new VertxTestContext();
    final Tenant tenant = new Tenant();
    final MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/plain").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI);
    final MultiMap requestHeadersWithEncodedCredentials = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/plain").add(HttpHeaders.AUTHORIZATION, getBasicAuthWithEncodedCredentials(tenantId, deviceId, PWD)).add(HttpHeaders.ORIGIN, ORIGIN_URI);
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).onComplete(setup.succeedingThenComplete());
    assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
        return;
    }
    final var clientOptions = new HttpClientOptions(defaultOptions).setEnabledSecureTransportProtocols(Set.of("TLSv1.3"));
    final var tls13BasedClient = new CrudHttpClient(vertx, new HttpClientOptions(clientOptions));
    testUploadMessages(ctx, tenantId, count -> {
        return tls13BasedClient.create(getEndpointUri(), Buffer.buffer("hello " + count), count % 2 == 0 ? requestHeaders : requestHeadersWithEncodedCredentials, ResponsePredicate.status(HttpURLConnection.HTTP_ACCEPTED)).compose(this::verifyAccessControlExposedHeaders);
    });
}
Also used : MultiMap(io.vertx.core.MultiMap) Tenant(org.eclipse.hono.service.management.tenant.Tenant) VertxTestContext(io.vertx.junit5.VertxTestContext) HttpClientOptions(io.vertx.core.http.HttpClientOptions) CrudHttpClient(org.eclipse.hono.tests.CrudHttpClient) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 58 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class TelemetryHttpIT method testUploadQos1MessageFailsIfDeliveryStateNotUpdated.

/**
 * Verifies that the upload of a QoS 1 telemetry message fails with a 503 status code
 * when the consumer doesn't update the message delivery state and the
 * <em>sendMessageTimeout</em> has elapsed.
 *
 * @param vertx The vert.x instance.
 * @param ctx The test context
 * @throws InterruptedException if test is interrupted while running.
 */
@Test
@AssumeMessagingSystem(type = MessagingType.amqp)
public void testUploadQos1MessageFailsIfDeliveryStateNotUpdated(final Vertx vertx, final VertxTestContext ctx) throws InterruptedException {
    final AmqpApplicationClient amqpApplicationClient = (AmqpApplicationClient) helper.applicationClient;
    // GIVEN a device and a north bound message consumer that doesn't update the message delivery state
    final Tenant tenant = new Tenant();
    final Checkpoint messageReceived = ctx.checkpoint();
    final Checkpoint deliveryStateCheckDone = ctx.checkpoint();
    final Checkpoint httpResponseReceived = ctx.checkpoint();
    final VertxTestContext setup = new VertxTestContext();
    final AtomicReference<ProtonDelivery> deliveryRef = new AtomicReference<>();
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).compose(ok -> amqpApplicationClient.createTelemetryConsumer(tenantId, msg -> {
        final Promise<Void> result = Promise.promise();
        final var delivery = msg.getMessageContext().getDelivery();
        deliveryRef.set(delivery);
        logger.debug("received message: {}", msg.getMessageContext().getRawMessage());
        ctx.verify(() -> {
            assertThat(delivery.remotelySettled()).isFalse();
            assertThat(delivery.getRemoteState()).isNull();
        });
        messageReceived.flag();
        // don't update the delivery state here
        return result.future();
    }, remoteClose -> {
    })).onComplete(setup.succeedingThenComplete());
    assertThat(setup.awaitCompletion(IntegrationTestSupport.getTestSetupTimeout(), TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
        return;
    }
    // WHEN the device tries to upload a telemetry message
    final MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "binary/octet-stream").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI).add(Constants.HEADER_QOS_LEVEL, "1");
    final Future<HttpResponse<Buffer>> httpResponseFuture = httpClient.create(getEndpointUri(), Buffer.buffer("hello"), requestHeaders, // THEN the message gets rejected by the HTTP adapter with a 503
    ResponsePredicate.status(HttpURLConnection.HTTP_UNAVAILABLE));
    httpResponseFuture.onComplete(ctx.succeeding(response -> {
        ctx.verify(() -> {
            final var body = response.bodyAsJsonObject();
            assertThat(body.getString(RequestResponseApiConstants.FIELD_ERROR)).isEqualTo(ServiceInvocationException.getLocalizedMessage(SendMessageTimeoutException.CLIENT_FACING_MESSAGE_KEY));
        });
        httpResponseReceived.flag();
        // verify that the telemetry message delivery is remotely settled via the timeout handling in the adapter
        vertx.setTimer(50, tid -> {
            ctx.verify(() -> {
                final ProtonDelivery delivery = deliveryRef.get();
                assertThat(delivery).isNotNull();
                assertThat(delivery.remotelySettled()).isTrue();
                assertThat(delivery.getRemoteState()).isNotNull();
                assertThat(delivery.getRemoteState().getType()).isEqualTo(DeliveryState.DeliveryStateType.Released);
            });
            deliveryStateCheckDone.flag();
        });
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) ResponsePredicate(io.vertx.ext.web.client.predicate.ResponsePredicate) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) HttpResponse(io.vertx.ext.web.client.HttpResponse) ProtonDelivery(io.vertx.proton.ProtonDelivery) MultiMap(io.vertx.core.MultiMap) RequestOptions(io.vertx.core.http.RequestOptions) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Constants(org.eclipse.hono.util.Constants) NoConsumerException(org.eclipse.hono.client.NoConsumerException) Tenant(org.eclipse.hono.service.management.tenant.Tenant) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) MessagingType(org.eclipse.hono.util.MessagingType) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) DeliveryState(org.apache.qpid.proton.amqp.transport.DeliveryState) Tenants(org.eclipse.hono.tests.Tenants) MessageContext(org.eclipse.hono.application.client.MessageContext) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) HttpHeaders(io.vertx.core.http.HttpHeaders) Truth.assertThat(com.google.common.truth.Truth.assertThat) RequestResponseApiConstants(org.eclipse.hono.util.RequestResponseApiConstants) VertxExtension(io.vertx.junit5.VertxExtension) AssumeMessagingSystem(org.eclipse.hono.tests.AssumeMessagingSystem) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Buffer(io.vertx.core.buffer.Buffer) AmqpApplicationClient(org.eclipse.hono.application.client.amqp.AmqpApplicationClient) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) SendMessageTimeoutException(org.eclipse.hono.client.SendMessageTimeoutException) Checkpoint(io.vertx.junit5.Checkpoint) Handler(io.vertx.core.Handler) QoS(org.eclipse.hono.util.QoS) ProtonDelivery(io.vertx.proton.ProtonDelivery) VertxTestContext(io.vertx.junit5.VertxTestContext) HttpResponse(io.vertx.ext.web.client.HttpResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) AmqpApplicationClient(org.eclipse.hono.application.client.amqp.AmqpApplicationClient) MultiMap(io.vertx.core.MultiMap) Checkpoint(io.vertx.junit5.Checkpoint) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Test(org.junit.jupiter.api.Test) AssumeMessagingSystem(org.eclipse.hono.tests.AssumeMessagingSystem)

Example 59 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class EventMqttIT method testEventMessageAlreadySentIsDeliveredWhenConsumerConnects.

/**
 * Verifies that an event message from a device has been successfully sent and a north bound application,
 * which connects after the event has been sent, can successfully receive those event message.
 *
 * @param ctx The vert.x test context.
 * @throws InterruptedException if test execution gets interrupted.
 */
@Test
public void testEventMessageAlreadySentIsDeliveredWhenConsumerConnects(final VertxTestContext ctx) throws InterruptedException {
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String messagePayload = UUID.randomUUID().toString();
    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addDeviceForTenant(tenantId, new Tenant(), deviceId, password).compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), password)).onComplete(setup.succeedingThenComplete());
    assertThat(setup.awaitCompletion(IntegrationTestSupport.getTestSetupTimeout(), TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
        return;
    }
    // WHEN a device that belongs to the tenant publishes an event
    send(tenantId, deviceId, Buffer.buffer(messagePayload), false, null, (sendAttempt, result) -> {
        if (sendAttempt.succeeded()) {
            LOGGER.debug("successfully sent event [tenant-id: {}, device-id: {}]", tenantId, deviceId);
            // THEN create a consumer once the event message has been successfully sent
            LOGGER.debug("opening event consumer for tenant [{}]", tenantId);
            createConsumer(tenantId, msg -> {
                // THEN verify that the event message has been received by the consumer
                LOGGER.debug("event message has been received by the consumer");
                ctx.verify(() -> assertThat(msg.getPayload().toString()).isEqualTo(messagePayload));
                ctx.completeNow();
            });
        } else {
            ctx.failNow(sendAttempt.cause());
        }
    });
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) MessageContext(org.eclipse.hono.application.client.MessageContext) Promise(io.vertx.core.Promise) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) UUID(java.util.UUID) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Tenant(org.eclipse.hono.service.management.tenant.Tenant) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Buffer(io.vertx.core.buffer.Buffer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Tenant(org.eclipse.hono.service.management.tenant.Tenant) VertxTestContext(io.vertx.junit5.VertxTestContext) Test(org.junit.jupiter.api.Test)

Example 60 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class MqttPublishTestBase method testUploadMessagesWithWrongContentTypeSendsErrors.

/**
 * Verifies that sending a number of messages to Hono's MQTT adapter with an invalid content type causes
 * corresponding error messages to be published to the client if it is subscribed on the error topic.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessagesWithWrongContentTypeSendsErrors(final VertxTestContext ctx) throws InterruptedException {
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final Tenant tenant = new Tenant();
    final VertxTestContext setup = new VertxTestContext();
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, password).onComplete(setup.succeedingThenComplete());
    assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
        return;
    }
    testUploadMessageWithInvalidContentType(ctx, tenantId, deviceId, deviceId);
}
Also used : Tenant(org.eclipse.hono.service.management.tenant.Tenant) VertxTestContext(io.vertx.junit5.VertxTestContext) Test(org.junit.jupiter.api.Test)

Aggregations

Tenant (org.eclipse.hono.service.management.tenant.Tenant)165 Test (org.junit.jupiter.api.Test)138 VertxTestContext (io.vertx.junit5.VertxTestContext)137 HttpURLConnection (java.net.HttpURLConnection)122 Truth.assertThat (com.google.common.truth.Truth.assertThat)113 TimeUnit (java.util.concurrent.TimeUnit)109 JsonObject (io.vertx.core.json.JsonObject)108 Future (io.vertx.core.Future)107 Timeout (io.vertx.junit5.Timeout)99 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)98 RegistryManagementConstants (org.eclipse.hono.util.RegistryManagementConstants)97 Constants (org.eclipse.hono.util.Constants)95 Tenants (org.eclipse.hono.tests.Tenants)92 Optional (java.util.Optional)91 Promise (io.vertx.core.Promise)86 Device (org.eclipse.hono.service.management.device.Device)80 Adapter (org.eclipse.hono.util.Adapter)78 VertxExtension (io.vertx.junit5.VertxExtension)77 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)77 Logger (org.slf4j.Logger)74