Search in sources :

Example 81 with Tenant

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

the class ManagementStore method delete.

/**
 * Delete the tenant.
 *
 * @param tenantId The tenant to delete.
 * @param resourceVersion The version of the resource to delete.
 * @param spanContext The span to contribute to.
 * @return The future, tracking the outcome of the operation.
 */
public Future<UpdateResult> delete(final String tenantId, final Optional<String> resourceVersion, final SpanContext spanContext) {
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "delete tenant", getClass().getSimpleName()).withTag(TracingHelper.TAG_TENANT_ID, tenantId).start();
    resourceVersion.ifPresent(version -> span.setTag("version", version));
    final Statement statement;
    if (resourceVersion.isPresent()) {
        statement = this.deleteVersionedStatement;
    } else {
        statement = this.deleteStatement;
    }
    final var expanded = statement.expand(map -> {
        map.put("tenant_id", tenantId);
        resourceVersion.ifPresent(version -> map.put("expected_version", version));
    });
    log.debug("delete - statement: {}", expanded);
    final var result = expanded.trace(this.tracer, span.context()).update(this.client);
    return checkOptimisticLock(result, span, resourceVersion, checkSpan -> readTenantEntryById(this.client, tenantId, checkSpan.context())).onComplete(x -> span.finish());
}
Also used : SQL(org.eclipse.hono.service.base.jdbc.store.SQL) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) TenantConstants(org.eclipse.hono.util.TenantConstants) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) SpanContext(io.opentracing.SpanContext) CompositeFuture(io.vertx.core.CompositeFuture) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) JDBCClient(io.vertx.ext.jdbc.JDBCClient) UpdateResult(io.vertx.ext.sql.UpdateResult) EntityNotFoundException(org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException) SQLConnection(io.vertx.ext.sql.SQLConnection) Optional(java.util.Optional) Span(io.opentracing.Span) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) SQLOperations(io.vertx.ext.sql.SQLOperations) StatementConfiguration(org.eclipse.hono.service.base.jdbc.store.StatementConfiguration) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) Span(io.opentracing.Span)

Example 82 with Tenant

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

the class ManagementStore method update.

/**
 * Create a new tenant.
 * <p>
 * The operation may fail with a {@link org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException} if the
 * specified tenant does not exist.
 * <p>
 * The operation may fail with a {@link org.eclipse.hono.service.base.jdbc.store.DuplicateKeyException} if a
 * tenant with the ID or trust anchor already exists.
 * <p>
 * The operation may fail with an {@link org.eclipse.hono.service.base.jdbc.store.OptimisticLockingException} if
 * an expected resource version was provided, but the current version did not match.
 *
 * @param tenantId The ID of the new tenant.
 * @param tenant The tenant information.
 * @param resourceVersion An optional resource version.
 * @param spanContext The span to contribute to.
 * @return A future, tracking the outcome of the operation.
 */
public Future<Versioned<Void>> update(final String tenantId, final Tenant tenant, final Optional<String> resourceVersion, final SpanContext spanContext) {
    final var json = tenantToJson(tenant);
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "update tenant", getClass().getSimpleName()).withTag(TracingHelper.TAG_TENANT_ID, tenantId).start();
    final var nextVersion = UUID.randomUUID().toString();
    resourceVersion.ifPresent(version -> span.setTag("version", version));
    final Statement statement = resourceVersion.isPresent() ? this.updateVersionedStatement : this.updateStatement;
    return SQL.runTransactionally(this.client, this.tracer, span.context(), (connection, context) -> updateJsonField(connection, tenantId, statement, json, resourceVersion, nextVersion, span).flatMap(r -> {
        if (r.getUpdated() <= 0) {
            return Future.failedFuture(new EntityNotFoundException());
        } else {
            return Future.succeededFuture();
        }
    }).flatMap(x -> deleteAllTrustAnchors(connection, tenantId, span)).flatMap(r -> insertAllTrustAnchors(connection, tenantId, tenant, span))).map(new Versioned<Void>(nextVersion, null)).onComplete(x -> span.finish());
}
Also used : SQL(org.eclipse.hono.service.base.jdbc.store.SQL) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) TenantConstants(org.eclipse.hono.util.TenantConstants) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) SpanContext(io.opentracing.SpanContext) CompositeFuture(io.vertx.core.CompositeFuture) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) JDBCClient(io.vertx.ext.jdbc.JDBCClient) UpdateResult(io.vertx.ext.sql.UpdateResult) EntityNotFoundException(org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException) SQLConnection(io.vertx.ext.sql.SQLConnection) Optional(java.util.Optional) Span(io.opentracing.Span) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) SQLOperations(io.vertx.ext.sql.SQLOperations) StatementConfiguration(org.eclipse.hono.service.base.jdbc.store.StatementConfiguration) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) EntityNotFoundException(org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException) Span(io.opentracing.Span)

Example 83 with Tenant

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

the class DeviceAndGatewayAutoProvisionerTest method testProvisionFailsWhenEventNotificationFails.

@SuppressWarnings("unchecked")
private void testProvisionFailsWhenEventNotificationFails(final VertxTestContext ctx, final boolean isGateway, final String expectedDeviceId) throws CertificateEncodingException {
    configureTenant(isGateway, null);
    final JsonObject clientContext = new JsonObject().put(CredentialsConstants.FIELD_CLIENT_CERT, cert.getEncoded());
    when(deviceManagementService.createDevice(eq(tenantId), any(), any(), any())).thenReturn(Future.succeededFuture(OperationResult.ok(HttpURLConnection.HTTP_CREATED, Id.of(deviceId), Optional.empty(), Optional.empty())));
    when(deviceManagementService.updateDevice(eq(tenantId), eq(expectedDeviceId), any(), any(), any())).thenReturn(Future.succeededFuture(OperationResult.empty(HttpURLConnection.HTTP_NO_CONTENT)));
    when(credentialsManagementService.updateCredentials(eq(tenantId), eq(expectedDeviceId), any(), any(), any())).thenReturn(Future.succeededFuture(OperationResult.empty(HttpURLConnection.HTTP_NO_CONTENT)));
    // WHEN sending an auto-provisioning event fails
    when(sender.sendEvent(any(TenantObject.class), any(RegistrationAssertion.class), anyString(), any(), any(Map.class), any())).thenReturn(Future.failedFuture(ServiceInvocationException.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "error sending event")));
    // WHEN provisioning a device/gateway from a certificate
    deviceAndGatewayAutoProvisioner.provisionIfEnabled(tenantId, tenant, subjectDn, clientContext, NoopSpan.INSTANCE).onComplete(ctx.succeeding(result -> {
        // VERIFY that the status code corresponds to an error.
        assertThat(result.isError()).isTrue();
        assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_INTERNAL_ERROR);
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) BeforeEach(org.junit.jupiter.api.BeforeEach) CredentialsManagementService(org.eclipse.hono.service.management.credentials.CredentialsManagementService) CertificateFactory(java.security.cert.CertificateFactory) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Tenant(org.eclipse.hono.service.management.tenant.Tenant) GeneralSecurityException(java.security.GeneralSecurityException) MessagingType(org.eclipse.hono.util.MessagingType) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TrustedCertificateAuthority(org.eclipse.hono.service.management.tenant.TrustedCertificateAuthority) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) EventSender(org.eclipse.hono.client.telemetry.EventSender) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) UUID(java.util.UUID) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) List(java.util.List) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Id(org.eclipse.hono.service.management.Id) Mockito.mock(org.mockito.Mockito.mock) CertificateEncodingException(java.security.cert.CertificateEncodingException) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) X500Principal(javax.security.auth.x500.X500Principal) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ArgumentCaptor(org.mockito.ArgumentCaptor) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) MessagingClientProvider(org.eclipse.hono.client.util.MessagingClientProvider) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) FileInputStream(java.io.FileInputStream) Truth.assertThat(com.google.common.truth.Truth.assertThat) Result(org.eclipse.hono.service.management.Result) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Mockito.verify(org.mockito.Mockito.verify) TenantObject(org.eclipse.hono.util.TenantObject) Mockito.never(org.mockito.Mockito.never) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) NoopSpan(io.opentracing.noop.NoopSpan) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) TenantObject(org.eclipse.hono.util.TenantObject) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) JsonObject(io.vertx.core.json.JsonObject) Map(java.util.Map)

Example 84 with Tenant

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

the class AmqpConnectionIT method testConnectFailsForDisabledAdapter.

/**
 * Verifies that the adapter rejects connection attempts from devices belonging
 * to a tenant for which the AMQP adapter has been disabled.
 *
 * @param ctx The test context
 */
@Test
public void testConnectFailsForDisabledAdapter(final VertxTestContext ctx) {
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final String password = "secret";
    // GIVEN a tenant for which the AMQP adapter is disabled
    final Tenant tenant = new Tenant();
    tenant.addAdapterConfig(new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_HTTP).setEnabled(true));
    tenant.addAdapterConfig(new Adapter(Constants.PROTOCOL_ADAPTER_TYPE_AMQP).setEnabled(false));
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, password).compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), password)).onComplete(ctx.failing(t -> {
        // THEN the connection is refused
        ctx.verify(() -> assertThat(((ClientErrorException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_FORBIDDEN));
        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) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Adapter(org.eclipse.hono.util.Adapter) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 85 with Tenant

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

the class AmqpConnectionIT method testConnectFailsForNonMatchingTrustAnchor.

/**
 * Verifies that the adapter fails to authenticate a device if the device's client certificate's signature cannot be
 * validated using the trust anchor that is registered for the tenant that the device belongs to.
 *
 * @param ctx The test context.
 * @throws GeneralSecurityException if the tenant's trust anchor cannot be generated
 */
@Test
public void testConnectFailsForNonMatchingTrustAnchor(final VertxTestContext ctx) throws GeneralSecurityException {
    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);
    final KeyPair keyPair = helper.newEcKeyPair();
    final SelfSignedCertificate deviceCert = SelfSignedCertificate.create(UUID.randomUUID().toString());
    // GIVEN a tenant configured with a trust anchor
    helper.getCertificate(deviceCert.certificatePath()).compose(cert -> {
        final Tenant tenant = Tenants.createTenantForTrustAnchor(cert.getSubjectX500Principal(), keyPair.getPublic());
        return helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, cert);
    }).compose(ok -> {
        // using the trust anchor registered for the device's tenant
        return connectToAdapter(deviceCert);
    }).onComplete(ctx.failing(t -> {
        // THEN the connection is not established
        ctx.verify(() -> assertThat(t).isInstanceOf(SaslException.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) KeyPair(java.security.KeyPair) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

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