Search in sources :

Example 1 with CredentialsManagementService

use of org.eclipse.hono.service.management.credentials.CredentialsManagementService in project hono by eclipse.

the class DeviceAndGatewayAutoProvisionerTest method testDeviceRegistrationIsRemovedWhenAutoProvisionFails.

/**
 * Verifies that if auto-provisioning fails, then the device registered during auto-provisioning process is removed.
 *
 * @param ctx The vert.x test context.
 * @throws CertificateEncodingException if the certificate cannot be encoded.
 */
@Test
public void testDeviceRegistrationIsRemovedWhenAutoProvisionFails(final VertxTestContext ctx) throws CertificateEncodingException {
    // GIVEN a tenant CA with auto-provisioning enabled
    tenant.getTrustedCertificateAuthorities().get(0).setAutoProvisioningEnabled(true);
    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(credentialsManagementService.updateCredentials(eq(tenantId), eq(deviceId), any(), any(), any())).thenReturn(Future.succeededFuture(OperationResult.empty(HttpURLConnection.HTTP_INTERNAL_ERROR)));
    when(deviceManagementService.deleteDevice(eq(tenantId), eq(deviceId), any(), any())).thenReturn(Future.succeededFuture(Result.from(HttpURLConnection.HTTP_NO_CONTENT)));
    // WHEN provisioning a device from a certificate
    deviceAndGatewayAutoProvisioner.provisionIfEnabled(tenantId, tenant, subjectDn, clientContext, NoopSpan.INSTANCE).onComplete(ctx.succeeding(result -> {
        ctx.verify(() -> {
            // THEN the device is registered
            verify(deviceManagementService).createDevice(eq(tenantId), any(), any(), any());
            // WHEN update credentials fails
            verify(credentialsManagementService).updateCredentials(eq(tenantId), eq(deviceId), any(), any(), any());
            // THEN the device registration is deleted
            verify(deviceManagementService).deleteDevice(eq(tenantId), eq(deviceId), any(), any());
            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) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.jupiter.api.Test)

Example 2 with CredentialsManagementService

use of org.eclipse.hono.service.management.credentials.CredentialsManagementService in project hono by eclipse.

the class DeviceAndGatewayAutoProvisionerTest method provisionAndVerifySuccessfulResult.

@SuppressWarnings("unchecked")
private void provisionAndVerifySuccessfulResult(final VertxTestContext ctx, final boolean isGateway, final String expectedDeviceId) throws CertificateEncodingException {
    final JsonObject clientContext = new JsonObject().put(CredentialsConstants.FIELD_CLIENT_CERT, cert.getEncoded());
    // WHEN provisioning a device/gateway from a certificate
    deviceAndGatewayAutoProvisioner.provisionIfEnabled(tenantId, tenant, subjectDn, clientContext, NoopSpan.INSTANCE).onComplete(ctx.succeeding(result -> {
        ctx.verify(() -> {
            // VERIFY that that the device/gateway has been registered.
            final ArgumentCaptor<Device> deviceCaptor = ArgumentCaptor.forClass(Device.class);
            verify(deviceManagementService).createDevice(eq(tenantId), any(), deviceCaptor.capture(), any());
            if (isGateway) {
                // VERIFY that a gateway has been provisioned by checking the relevant property
                assertThat(deviceCaptor.getValue().getAuthorities()).contains(RegistryManagementConstants.AUTHORITY_AUTO_PROVISIONING_ENABLED);
            }
            // VERIFY that the correct credentials are stored
            final ArgumentCaptor<List<CommonCredential>> credentialsCaptor = ArgumentCaptor.forClass(List.class);
            verify(credentialsManagementService).updateCredentials(eq(tenantId), eq(expectedDeviceId), credentialsCaptor.capture(), any(), any());
            final List<CommonCredential> credentialsCaptorValue = credentialsCaptor.getValue();
            assertThat(credentialsCaptorValue.size()).isEqualTo(1);
            assertThat(credentialsCaptorValue.get(0).getType()).isEqualTo(RegistryManagementConstants.SECRETS_TYPE_X509_CERT);
            assertThat(credentialsCaptorValue.get(0).getAuthId()).isEqualTo(subjectDn);
            // VERIFY the returned credentials result after successful auto-provisioning
            assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_CREATED);
            final JsonObject returnedCredential = result.getPayload();
            assertThat(returnedCredential.getString(RegistryManagementConstants.FIELD_PAYLOAD_DEVICE_ID)).isEqualTo(expectedDeviceId);
            assertThat(returnedCredential.getString(RegistryManagementConstants.FIELD_AUTH_ID)).isEqualTo(subjectDn);
            assertThat(returnedCredential.getString(RegistryManagementConstants.FIELD_TYPE)).isEqualTo(RegistryManagementConstants.SECRETS_TYPE_X509_CERT);
            // VERIFY that a auto-provisioning notification has been sent
            final ArgumentCaptor<Map<String, Object>> messagePropertiesArgumentCaptor = ArgumentCaptor.forClass(Map.class);
            verify(sender).sendEvent(argThat(tenant -> tenant.getTenantId().equals(tenantId)), argThat(assertion -> assertion.getDeviceId().equals(expectedDeviceId)), eq(EventConstants.CONTENT_TYPE_DEVICE_PROVISIONING_NOTIFICATION), any(), messagePropertiesArgumentCaptor.capture(), any());
            final Map<String, Object> eventProperties = messagePropertiesArgumentCaptor.getValue();
            assertThat(eventProperties.get(MessageHelper.APP_PROPERTY_REGISTRATION_STATUS)).isEqualTo(EventConstants.RegistrationStatus.NEW.name());
            assertThat(eventProperties.get(MessageHelper.APP_PROPERTY_TENANT_ID)).isEqualTo(tenantId);
            // VERIFY that the device registration has been updated as the auto-provisioning event has been
            // successfully sent
            verify(deviceManagementService).updateDevice(eq(tenantId), eq(expectedDeviceId), deviceCaptor.capture(), any(), any());
            final DeviceStatus deviceStatus = deviceCaptor.getValue().getStatus();
            assertThat(deviceStatus.isAutoProvisioned()).isTrue();
            assertThat(deviceStatus.isAutoProvisioningNotificationSent()).isTrue();
        });
        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) ArgumentCaptor(org.mockito.ArgumentCaptor) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) JsonObject(io.vertx.core.json.JsonObject) List(java.util.List) JsonObject(io.vertx.core.json.JsonObject) TenantObject(org.eclipse.hono.util.TenantObject) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Map(java.util.Map)

Example 3 with CredentialsManagementService

use of org.eclipse.hono.service.management.credentials.CredentialsManagementService in project hono by eclipse.

the class DeviceAndGatewayAutoProvisionerTest method init.

/**
 * Initializes common fixture.
 *
 * @throws GeneralSecurityException if the self signed certificate cannot be created.
 * @throws IOException if the self signed certificate cannot be read.
 */
@SuppressWarnings("unchecked")
@BeforeEach
public void init() throws GeneralSecurityException, IOException {
    tenantId = UUID.randomUUID().toString();
    deviceId = UUID.randomUUID().toString();
    commonName = UUID.randomUUID().toString();
    final SelfSignedCertificate ssc = SelfSignedCertificate.create(String.format("%s,OU=Hono,O=Eclipse", commonName));
    cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(ssc.certificatePath()));
    subjectDn = cert.getSubjectX500Principal().getName(X500Principal.RFC2253);
    final TrustedCertificateAuthority trustedCertificateAuthority = new TrustedCertificateAuthority().setCertificate(cert.getEncoded());
    tenant = new Tenant().setTrustedCertificateAuthorities(List.of(trustedCertificateAuthority));
    deviceManagementService = mock(DeviceManagementService.class);
    credentialsManagementService = mock(CredentialsManagementService.class);
    sender = mock(EventSender.class);
    when(sender.getMessagingType()).thenReturn(MessagingType.amqp);
    when(sender.sendEvent(any(TenantObject.class), any(RegistrationAssertion.class), anyString(), any(), any(Map.class), any())).thenReturn(Future.succeededFuture());
    deviceAndGatewayAutoProvisioner = new DeviceAndGatewayAutoProvisioner(mock(Vertx.class), deviceManagementService, credentialsManagementService, new MessagingClientProvider<EventSender>().setClient(sender));
}
Also used : TenantObject(org.eclipse.hono.util.TenantObject) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) Tenant(org.eclipse.hono.service.management.tenant.Tenant) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) EventSender(org.eclipse.hono.client.telemetry.EventSender) TrustedCertificateAuthority(org.eclipse.hono.service.management.tenant.TrustedCertificateAuthority) CredentialsManagementService(org.eclipse.hono.service.management.credentials.CredentialsManagementService) Map(java.util.Map) FileInputStream(java.io.FileInputStream) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

SelfSignedCertificate (io.vertx.core.net.SelfSignedCertificate)3 FileInputStream (java.io.FileInputStream)3 Map (java.util.Map)3 EventSender (org.eclipse.hono.client.telemetry.EventSender)3 CredentialsManagementService (org.eclipse.hono.service.management.credentials.CredentialsManagementService)3 Tenant (org.eclipse.hono.service.management.tenant.Tenant)3 TrustedCertificateAuthority (org.eclipse.hono.service.management.tenant.TrustedCertificateAuthority)3 RegistrationAssertion (org.eclipse.hono.util.RegistrationAssertion)3 TenantObject (org.eclipse.hono.util.TenantObject)3 BeforeEach (org.junit.jupiter.api.BeforeEach)3 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 NoopSpan (io.opentracing.noop.NoopSpan)2 Future (io.vertx.core.Future)2 Vertx (io.vertx.core.Vertx)2 JsonObject (io.vertx.core.json.JsonObject)2 VertxExtension (io.vertx.junit5.VertxExtension)2 VertxTestContext (io.vertx.junit5.VertxTestContext)2 IOException (java.io.IOException)2 HttpURLConnection (java.net.HttpURLConnection)2 GeneralSecurityException (java.security.GeneralSecurityException)2