Search in sources :

Example 41 with Tenant

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

the class MongoDbBasedTenantDaoTest method testCreateSetsCreationDate.

/**
 * Verifies that the DAO sets the initial version and creation date when creating a tenant.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateSetsCreationDate(final VertxTestContext ctx) {
    when(mongoClient.insert(anyString(), any(JsonObject.class))).thenReturn(Future.succeededFuture("initial-version"));
    final var dto = TenantDto.forCreation("tenantId", new Tenant(), "initial-version");
    dao.create(dto, NoopSpan.INSTANCE.context()).onComplete(ctx.succeeding(version -> {
        ctx.verify(() -> {
            assertThat(version).isEqualTo("initial-version");
            final var document = ArgumentCaptor.forClass(JsonObject.class);
            verify(mongoClient).insert(eq("tenants"), document.capture());
            MongoDbBasedTenantDaoTest.assertCreationDocumentContainsStatusProperties(document.getValue(), "initial-version");
        });
        ctx.completeNow();
    }));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) JsonObject(io.vertx.core.json.JsonObject) TenantDto(org.eclipse.hono.service.management.tenant.TenantDto) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Vertx(io.vertx.core.Vertx) MongoClient(io.vertx.ext.mongo.MongoClient) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) ChronoUnit(java.time.temporal.ChronoUnit) BaseDto(org.eclipse.hono.service.management.BaseDto) Buffer(io.vertx.core.buffer.Buffer) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) FindOptions(io.vertx.ext.mongo.FindOptions) NoopSpan(io.opentracing.noop.NoopSpan) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) Tenant(org.eclipse.hono.service.management.tenant.Tenant) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.jupiter.api.Test)

Example 42 with Tenant

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

the class MongoDbBasedTenantDaoTest method testCreateIndicesDropsObsoleteIndex.

/**
 * Verifies that when creating indices for the Tenant collection, an existing unique index on
 * <em>tenant.trusted-ca.subject-dn</em> is getting dropped.
 *
 * @param ctx The vert.x test context.
 * @param vertx The vert.x instance to run on.
 */
@Test
public void testCreateIndicesDropsObsoleteIndex(final VertxTestContext ctx, final Vertx vertx) {
    // GIVEN a set of existing indices including a unique, partial index on tenant.trusted-ca.subject-dn
    final Buffer existingIndices = vertx.fileSystem().readFileBlocking("target/test-classes/indexes.json");
    when(mongoClient.createIndexWithOptions(anyString(), any(JsonObject.class), any(IndexOptions.class))).thenReturn(Future.succeededFuture());
    when(mongoClient.dropIndex(anyString(), anyString())).thenReturn(Future.succeededFuture());
    when(mongoClient.listIndexes(anyString())).thenReturn(Future.succeededFuture(existingIndices.toJsonArray()));
    // WHEN creating indices for the tenant collection
    dao.createIndices().onComplete(ctx.succeeding(ok -> {
        ctx.verify(() -> {
            // THEN the unique index is being dropped
            verify(mongoClient).dropIndex(anyString(), eq("tenant.trusted-ca.subject-dn_1"));
        });
        ctx.completeNow();
    }));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) JsonObject(io.vertx.core.json.JsonObject) TenantDto(org.eclipse.hono.service.management.tenant.TenantDto) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Vertx(io.vertx.core.Vertx) MongoClient(io.vertx.ext.mongo.MongoClient) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) ChronoUnit(java.time.temporal.ChronoUnit) BaseDto(org.eclipse.hono.service.management.BaseDto) Buffer(io.vertx.core.buffer.Buffer) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) FindOptions(io.vertx.ext.mongo.FindOptions) NoopSpan(io.opentracing.noop.NoopSpan) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) IndexOptions(io.vertx.ext.mongo.IndexOptions) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.jupiter.api.Test)

Example 43 with Tenant

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

the class EventCoapIT 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 VertxTestContext setup = new VertxTestContext();
    final String messagePayload = UUID.randomUUID().toString();
    helper.registry.addDeviceForTenant(tenantId, new Tenant(), deviceId, SECRET).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
    final Promise<OptionSet> sendEvent = Promise.promise();
    final CoapClient client = getCoapClient();
    final Request eventRequest = createCoapRequest(CoAP.Code.PUT, Type.CON, getPutResource(tenantId, deviceId), messagePayload.getBytes());
    client.advanced(getHandler(sendEvent), eventRequest);
    sendEvent.future().onSuccess(eventSent -> {
        logger.debug("event message has been sent");
        // 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();
        });
    }).onFailure(ctx::failNow);
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) CoapClient(org.eclipse.californium.core.CoapClient) 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) 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) Request(org.eclipse.californium.core.coap.Request) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) CoAP(org.eclipse.californium.core.coap.CoAP) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) OptionSet(org.eclipse.californium.core.coap.OptionSet) Handler(io.vertx.core.Handler) Type(org.eclipse.californium.core.coap.CoAP.Type) Tenant(org.eclipse.hono.service.management.tenant.Tenant) VertxTestContext(io.vertx.junit5.VertxTestContext) Request(org.eclipse.californium.core.coap.Request) OptionSet(org.eclipse.californium.core.coap.OptionSet) CoapClient(org.eclipse.californium.core.CoapClient) Test(org.junit.jupiter.api.Test)

Example 44 with Tenant

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

the class TelemetryCoapIT method testUploadFailsForLargePayload.

/**
 * Verifies that the upload of a telemetry message containing a payload that
 * exceeds the CoAP adapter's configured max payload size fails with a 4.13
 * response code.
 *
 * @param ctx The test context.
 * @throws IOException if the CoAP request cannot be sent to the adapter.
 * @throws ConnectorException  if the CoAP request cannot be sent to the adapter.
 */
@Test
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
public void testUploadFailsForLargePayload(final VertxTestContext ctx) throws ConnectorException, IOException {
    final Tenant tenant = new Tenant();
    helper.registry.addPskDeviceForTenant(tenantId, tenant, deviceId, SECRET).compose(ok -> {
        final CoapClient client = getCoapsClient(deviceId, tenantId, SECRET);
        final Request request = createCoapsRequest(Code.POST, Type.CON, getPostResource(), IntegrationTestSupport.getPayload(4096));
        final Promise<OptionSet> result = Promise.promise();
        client.advanced(getHandler(result, ResponseCode.REQUEST_ENTITY_TOO_LARGE), request);
        return result.future();
    }).onComplete(ctx.succeedingThenComplete());
}
Also used : X509Certificate(java.security.cert.X509Certificate) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) VertxTestContext(io.vertx.junit5.VertxTestContext) CoapClient(org.eclipse.californium.core.CoapClient) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) ConnectorException(org.eclipse.californium.elements.exception.ConnectorException) KeyLoader(org.eclipse.hono.config.KeyLoader) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) Tenants(org.eclipse.hono.tests.Tenants) Type(org.eclipse.californium.core.coap.CoAP.Type) MessageContext(org.eclipse.hono.application.client.MessageContext) Promise(io.vertx.core.Promise) IOException(java.io.IOException) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Code(org.eclipse.californium.core.coap.CoAP.Code) Request(org.eclipse.californium.core.coap.Request) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) OptionSet(org.eclipse.californium.core.coap.OptionSet) Handler(io.vertx.core.Handler) QoS(org.eclipse.hono.util.QoS) Promise(io.vertx.core.Promise) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Request(org.eclipse.californium.core.coap.Request) CoapClient(org.eclipse.californium.core.CoapClient) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Example 45 with Tenant

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

the class TelemetryCoapIT method testUploadMessagesUsingClientCertificateWithAlias.

/**
 * Verifies that a number of messages uploaded to Hono's CoAP adapter using TLS_ECDSA based authentication can be
 * successfully consumed via the messaging infrastructure.
 * <p>
 * The device's tenant is being determined using the requested host name contained in the client's SNI TLS
 * extension.
 *
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@Test
public void testUploadMessagesUsingClientCertificateWithAlias(final VertxTestContext ctx) throws InterruptedException {
    assumeTrue(IntegrationTestSupport.isTrustAnchorGroupsSupported(), "device registry does not support trust anchor groups");
    assumeTrue(IntegrationTestSupport.isTenantAliasSupported(), "device registry does not support tenant aliases");
    final var clientCertLoader = KeyLoader.fromFiles(vertx, PATH_DEVICE_KEY, PATH_DEVICE_CERT);
    final var clientCert = (X509Certificate) clientCertLoader.getCertificateChain()[0];
    final VertxTestContext setup = new VertxTestContext();
    helper.getCertificate(PATH_CA_CERT).compose(caCert -> helper.registry.addTenant(helper.getRandomTenantId(), Tenants.createTenantForTrustAnchor(caCert).setTrustAnchorGroup("test-group")).map(caCert)).compose(caCert -> {
        return helper.registry.addDeviceForTenant(tenantId, Tenants.createTenantForTrustAnchor(caCert).setTrustAnchorGroup("test-group").setAlias("test-alias"), deviceId, clientCert);
    }).onComplete(setup.succeedingThenComplete());
    assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
        return;
    }
    final CoapClient client = getCoapsClient(clientCertLoader);
    testUploadMessages(ctx, tenantId, () -> warmUp(client, createCoapsRequest(Code.POST, getMessageType(), "test-alias." + IntegrationTestSupport.COAP_HOST, getPostResource(), "hello 0".getBytes(StandardCharsets.UTF_8))), count -> {
        final Promise<OptionSet> result = Promise.promise();
        final String payload = "hello " + count;
        final Request request = createCoapsRequest(Code.POST, getMessageType(), "test-alias." + IntegrationTestSupport.COAP_HOST, getPostResource(), payload.getBytes(StandardCharsets.UTF_8));
        client.advanced(getHandler(result), request);
        return result.future();
    });
}
Also used : X509Certificate(java.security.cert.X509Certificate) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) VertxTestContext(io.vertx.junit5.VertxTestContext) CoapClient(org.eclipse.californium.core.CoapClient) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) ConnectorException(org.eclipse.californium.elements.exception.ConnectorException) KeyLoader(org.eclipse.hono.config.KeyLoader) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) Tenants(org.eclipse.hono.tests.Tenants) Type(org.eclipse.californium.core.coap.CoAP.Type) MessageContext(org.eclipse.hono.application.client.MessageContext) Promise(io.vertx.core.Promise) IOException(java.io.IOException) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Code(org.eclipse.californium.core.coap.CoAP.Code) Request(org.eclipse.californium.core.coap.Request) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) OptionSet(org.eclipse.californium.core.coap.OptionSet) Handler(io.vertx.core.Handler) QoS(org.eclipse.hono.util.QoS) VertxTestContext(io.vertx.junit5.VertxTestContext) Request(org.eclipse.californium.core.coap.Request) OptionSet(org.eclipse.californium.core.coap.OptionSet) X509Certificate(java.security.cert.X509Certificate) CoapClient(org.eclipse.californium.core.CoapClient) 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