Search in sources :

Example 6 with Credentials

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

the class CredentialsApiTests method testGetCredentialsFailsForNonMatchingClientContext.

/**
 * Verifies that a request for credentials using a client context that does not match
 * the credentials on record fails with a 404.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetCredentialsFailsForNonMatchingClientContext(final VertxTestContext ctx) {
    final String deviceId = getHelper().getRandomDeviceId(tenantId);
    final String authId = UUID.randomUUID().toString();
    final CommonCredential credentials = getRandomHashedPasswordCredential(authId).putExtension("client-id", UUID.randomUUID().toString());
    final JsonObject clientContext = new JsonObject().put("client-id", "non-matching");
    getHelper().registry.registerDevice(tenantId, deviceId).compose(httpResponse -> getHelper().registry.addCredentials(tenantId, deviceId, List.of(credentials))).compose(ok -> getClient().get(tenantId, CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD, authId, clientContext, spanContext)).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertErrorCode(t, HttpURLConnection.HTTP_NOT_FOUND));
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) X500Principal(javax.security.auth.x500.X500Principal) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) CertificateFactory(java.security.cert.CertificateFactory) LoggerFactory(org.slf4j.LoggerFactory) Credentials(org.eclipse.hono.service.management.credentials.Credentials) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) OptionalInt(java.util.OptionalInt) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) JsonObject(io.vertx.core.json.JsonObject) Tenants(org.eclipse.hono.tests.Tenants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Device(org.eclipse.hono.service.management.device.Device) Logger(org.slf4j.Logger) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Vertx(io.vertx.core.Vertx) FileInputStream(java.io.FileInputStream) CertificateException(java.security.cert.CertificateException) UUID(java.util.UUID) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) DeviceStatus(org.eclipse.hono.service.management.device.DeviceStatus) MessageHelper(org.eclipse.hono.util.MessageHelper) EventConstants(org.eclipse.hono.util.EventConstants) FileNotFoundException(java.io.FileNotFoundException) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) AuthenticationConstants(org.eclipse.hono.util.AuthenticationConstants) SpanContext(io.opentracing.SpanContext) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) List(java.util.List) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) Checkpoint(io.vertx.junit5.Checkpoint) NoopSpan(io.opentracing.noop.NoopSpan) Collections(java.util.Collections) CredentialsObject(org.eclipse.hono.util.CredentialsObject) PasswordCredential(org.eclipse.hono.service.management.credentials.PasswordCredential) CertificateEncodingException(java.security.cert.CertificateEncodingException) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Example 7 with Credentials

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

the class CredentialsApiTests method testAutoProvisioningSucceeds.

private void testAutoProvisioningSucceeds(final VertxTestContext ctx, final Tenant tenant, final X509Certificate cert, final boolean isGateway, final String expectedDeviceId) throws CertificateEncodingException {
    final Checkpoint autoProvisioningEventReceived = ctx.checkpoint(1);
    final Checkpoint autoProvisioningCompleted = ctx.checkpoint(1);
    // GIVEN a client context that contains a client certificate
    final JsonObject clientCtx = new JsonObject().put(CredentialsConstants.FIELD_CLIENT_CERT, cert.getEncoded());
    final String authId = cert.getSubjectX500Principal().getName(X500Principal.RFC2253);
    tenantId = getHelper().getRandomTenantId();
    getHelper().applicationClient.createEventConsumer(tenantId, msg -> ctx.verify(() -> {
        // VERIFY that the auto-provisioning event for the device has been received
        verifyAutoProvisioningEventNotification(tenantId, expectedDeviceId, msg);
        autoProvisioningEventReceived.flag();
    }), close -> {
    }).compose(ok -> getHelper().registry.addTenant(tenantId, tenant)).compose(ok -> getClient().get(tenantId, CredentialsConstants.SECRETS_TYPE_X509_CERT, authId, clientCtx, spanContext)).compose(result -> {
        if (LOG.isDebugEnabled()) {
            LOG.debug("received get Credentials result from Credentials service:{}{}", System.lineSeparator(), JsonObject.mapFrom(result).encodePrettily());
        }
        // VERIFY the newly created credentials
        ctx.verify(() -> {
            assertThat(result).isNotNull();
            assertThat(result.isEnabled()).isTrue();
            assertThat(result.getDeviceId()).isNotNull();
            assertThat(result.getAuthId()).isEqualTo(authId);
            assertThat(result.getType()).isEqualTo(CredentialsConstants.SECRETS_TYPE_X509_CERT);
            assertThat(result.getSecrets()).isNotNull();
            assertThat(result.getSecrets()).hasSize(1);
            if (expectedDeviceId != null) {
                // VERIFY the generated device-id
                assertThat(result.getDeviceId()).isEqualTo(expectedDeviceId);
            }
        });
        // WHEN getting device registration information
        return getHelper().registry.getRegistrationInfo(tenantId, result.getDeviceId());
    }).onComplete(ctx.succeeding(result -> {
        ctx.verify(() -> {
            final JsonObject resultBody = result.bodyAsJsonObject();
            if (LOG.isDebugEnabled()) {
                LOG.debug("received get Device result from Registry Management API:{}{}", System.lineSeparator(), resultBody.encodePrettily());
            }
            // VERIFY that the device/gateway has been registered as well
            final Device device = resultBody.mapTo(Device.class);
            assertThat(device.isEnabled()).isTrue();
            if (isGateway) {
                // VERIFY that the gateway related attributes are set
                assertThat(device.getAuthorities()).contains(RegistryManagementConstants.AUTHORITY_AUTO_PROVISIONING_ENABLED);
            }
            // VERIFY that the property "auto-provisioning-notification-sent" is updated to true.
            final DeviceStatus deviceStatus = resultBody.getJsonObject(RegistryManagementConstants.FIELD_STATUS).mapTo(DeviceStatus.class);
            assertWithMessage("device auto-provisioned").that(deviceStatus.isAutoProvisioned()).isTrue();
            assertWithMessage("auto-provisioning notification for device sent").that(deviceStatus.isAutoProvisioningNotificationSent()).isTrue();
        });
        autoProvisioningCompleted.flag();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) X500Principal(javax.security.auth.x500.X500Principal) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) CertificateFactory(java.security.cert.CertificateFactory) LoggerFactory(org.slf4j.LoggerFactory) Credentials(org.eclipse.hono.service.management.credentials.Credentials) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) OptionalInt(java.util.OptionalInt) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) JsonObject(io.vertx.core.json.JsonObject) Tenants(org.eclipse.hono.tests.Tenants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Device(org.eclipse.hono.service.management.device.Device) Logger(org.slf4j.Logger) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Vertx(io.vertx.core.Vertx) FileInputStream(java.io.FileInputStream) CertificateException(java.security.cert.CertificateException) UUID(java.util.UUID) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) DeviceStatus(org.eclipse.hono.service.management.device.DeviceStatus) MessageHelper(org.eclipse.hono.util.MessageHelper) EventConstants(org.eclipse.hono.util.EventConstants) FileNotFoundException(java.io.FileNotFoundException) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) AuthenticationConstants(org.eclipse.hono.util.AuthenticationConstants) SpanContext(io.opentracing.SpanContext) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) List(java.util.List) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) Checkpoint(io.vertx.junit5.Checkpoint) NoopSpan(io.opentracing.noop.NoopSpan) Collections(java.util.Collections) CredentialsObject(org.eclipse.hono.util.CredentialsObject) PasswordCredential(org.eclipse.hono.service.management.credentials.PasswordCredential) CertificateEncodingException(java.security.cert.CertificateEncodingException) Checkpoint(io.vertx.junit5.Checkpoint) Device(org.eclipse.hono.service.management.device.Device) JsonObject(io.vertx.core.json.JsonObject) DeviceStatus(org.eclipse.hono.service.management.device.DeviceStatus)

Example 8 with Credentials

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

the class CredentialsApiTests method testGetCredentialsSucceedsForNonExistingClientContext.

/**
 * Verifies that a request for credentials using a client context succeeds if the credentials on record
 * do not have any extension properties with keys matching the provided client context.
 *
 * @param ctx The vert.x test context.
 */
@Timeout(value = 5, timeUnit = TimeUnit.SECONDS)
@Test
public void testGetCredentialsSucceedsForNonExistingClientContext(final VertxTestContext ctx) {
    final String deviceId = getHelper().getRandomDeviceId(tenantId);
    final String authId = UUID.randomUUID().toString();
    final CommonCredential credentials = getRandomHashedPasswordCredential(authId).putExtension("other", "property");
    final JsonObject clientContext = new JsonObject().put("client-id", "gateway-one");
    getHelper().registry.registerDevice(tenantId, deviceId).compose(httpResponse -> getHelper().registry.addCredentials(tenantId, deviceId, List.of(credentials))).compose(httpResponse -> getClient().get(tenantId, CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD, authId, clientContext, spanContext)).onComplete(ctx.succeeding(credentialsObject -> {
        ctx.verify(() -> {
            assertThat(credentialsObject.getSecrets()).isNotEmpty();
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) X500Principal(javax.security.auth.x500.X500Principal) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) CertificateFactory(java.security.cert.CertificateFactory) LoggerFactory(org.slf4j.LoggerFactory) Credentials(org.eclipse.hono.service.management.credentials.Credentials) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) OptionalInt(java.util.OptionalInt) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) JsonObject(io.vertx.core.json.JsonObject) Tenants(org.eclipse.hono.tests.Tenants) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Device(org.eclipse.hono.service.management.device.Device) Logger(org.slf4j.Logger) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Vertx(io.vertx.core.Vertx) FileInputStream(java.io.FileInputStream) CertificateException(java.security.cert.CertificateException) UUID(java.util.UUID) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) DeviceStatus(org.eclipse.hono.service.management.device.DeviceStatus) MessageHelper(org.eclipse.hono.util.MessageHelper) EventConstants(org.eclipse.hono.util.EventConstants) FileNotFoundException(java.io.FileNotFoundException) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) AuthenticationConstants(org.eclipse.hono.util.AuthenticationConstants) SpanContext(io.opentracing.SpanContext) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) List(java.util.List) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) Checkpoint(io.vertx.junit5.Checkpoint) NoopSpan(io.opentracing.noop.NoopSpan) Collections(java.util.Collections) CredentialsObject(org.eclipse.hono.util.CredentialsObject) PasswordCredential(org.eclipse.hono.service.management.credentials.PasswordCredential) CertificateEncodingException(java.security.cert.CertificateEncodingException) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.jupiter.api.Test) Timeout(io.vertx.junit5.Timeout)

Example 9 with Credentials

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

the class MongoDbBasedCredentialServiceTest method testUpdateCredentialsFailsForExceededCredentialsPerDeviceLimit.

/**
 * Verifies that a request to update credentials of a device fails with a 403 status code
 * if the number of credentials exceeds the tenant's configured limit.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateCredentialsFailsForExceededCredentialsPerDeviceLimit(final VertxTestContext ctx) {
    final var tenantId = UUID.randomUUID().toString();
    final var deviceId = UUID.randomUUID().toString();
    when(tenantInformationService.getTenant(anyString(), any())).thenReturn(Future.succeededFuture(new Tenant().setRegistrationLimits(new RegistrationLimits().setMaxCredentialsPerDevice(1))));
    credentialsManagementService.updateCredentials(tenantId, deviceId, List.of(Credentials.createPasswordCredential("device1", "secret"), Credentials.createPasswordCredential("device2", "secret")), Optional.empty(), NoopSpan.INSTANCE).onComplete(ctx.failing(t -> {
        ctx.verify(() -> {
            Assertions.assertServiceInvocationException(t, HttpURLConnection.HTTP_FORBIDDEN);
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) CredentialsManagementService(org.eclipse.hono.service.management.credentials.CredentialsManagementService) LoggerFactory(org.slf4j.LoggerFactory) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) AfterAll(org.junit.jupiter.api.AfterAll) TestInstance(org.junit.jupiter.api.TestInstance) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BeforeAll(org.junit.jupiter.api.BeforeAll) JsonObject(io.vertx.core.json.JsonObject) TenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.TenantInformationService) MongoClient(io.vertx.ext.mongo.MongoClient) MongoDbBasedRegistrationConfigProperties(org.eclipse.hono.deviceregistry.mongodb.config.MongoDbBasedRegistrationConfigProperties) UUID(java.util.UUID) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) TestInfo(org.junit.jupiter.api.TestInfo) Test(org.junit.jupiter.api.Test) List(java.util.List) SpringBasedHonoPasswordEncoder(org.eclipse.hono.auth.SpringBasedHonoPasswordEncoder) Optional(java.util.Optional) TenantKey(org.eclipse.hono.deviceregistry.service.tenant.TenantKey) Assertions(org.eclipse.hono.deviceregistry.util.Assertions) OperationResult(org.eclipse.hono.service.management.OperationResult) Checkpoint(io.vertx.junit5.Checkpoint) JsonPointer(io.vertx.core.json.pointer.JsonPointer) Mockito.mock(org.mockito.Mockito.mock) MongoDbDocumentBuilder(org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) Credentials(org.eclipse.hono.service.management.credentials.Credentials) CredentialsServiceTestBase(org.eclipse.hono.service.credentials.CredentialsServiceTestBase) DeviceManagementService(org.eclipse.hono.service.management.device.DeviceManagementService) CompositeFuture(io.vertx.core.CompositeFuture) MongoDbBasedCredentialsDao(org.eclipse.hono.deviceregistry.mongodb.model.MongoDbBasedCredentialsDao) RegistrationLimits(org.eclipse.hono.service.management.tenant.RegistrationLimits) Logger(org.slf4j.Logger) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) MongoDbBasedCredentialsConfigProperties(org.eclipse.hono.deviceregistry.mongodb.config.MongoDbBasedCredentialsConfigProperties) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) TimeUnit(java.util.concurrent.TimeUnit) AfterEach(org.junit.jupiter.api.AfterEach) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) CredentialsService(org.eclipse.hono.service.credentials.CredentialsService) MongoDbBasedDeviceDao(org.eclipse.hono.deviceregistry.mongodb.model.MongoDbBasedDeviceDao) NoopSpan(io.opentracing.noop.NoopSpan) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Tenant(org.eclipse.hono.service.management.tenant.Tenant) RegistrationLimits(org.eclipse.hono.service.management.tenant.RegistrationLimits) Test(org.junit.jupiter.api.Test)

Example 10 with Credentials

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

the class JdbcBasedCredentialsServiceTest method testUpdateCredentialsFailsForExceededCredentialsPerDeviceLimit.

/**
 * Verifies that a request to update credentials of a device fails with a 403 status code
 * if the number of credentials exceeds the tenant's configured limit.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateCredentialsFailsForExceededCredentialsPerDeviceLimit(final VertxTestContext ctx) {
    final var tenantId = UUID.randomUUID().toString();
    final var deviceId = UUID.randomUUID().toString();
    when(tenantInformationService.getTenant(anyString(), any())).thenReturn(Future.succeededFuture(new Tenant().setRegistrationLimits(new RegistrationLimits().setMaxCredentialsPerDevice(1))));
    getDeviceManagementService().createDevice(tenantId, Optional.of(deviceId), new Device(), NoopSpan.INSTANCE).onFailure(ctx::failNow).compose(ok -> getCredentialsManagementService().updateCredentials(tenantId, deviceId, List.of(Credentials.createPasswordCredential("device1", "secret"), Credentials.createPasswordCredential("device2", "secret")), Optional.empty(), NoopSpan.INSTANCE)).onComplete(ctx.failing(t -> {
        ctx.verify(() -> {
            Assertions.assertServiceInvocationException(t, HttpURLConnection.HTTP_FORBIDDEN);
        });
        ctx.completeNow();
    }));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) Device(org.eclipse.hono.service.management.device.Device) RegistrationLimits(org.eclipse.hono.service.management.tenant.RegistrationLimits) Credentials(org.eclipse.hono.service.management.credentials.Credentials) Mockito.when(org.mockito.Mockito.when) UUID(java.util.UUID) CredentialsServiceTestBase(org.eclipse.hono.service.credentials.CredentialsServiceTestBase) Future(io.vertx.core.Future) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Test(org.junit.jupiter.api.Test) List(java.util.List) Optional(java.util.Optional) Assertions(org.eclipse.hono.deviceregistry.util.Assertions) NoopSpan(io.opentracing.noop.NoopSpan) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Tenant(org.eclipse.hono.service.management.tenant.Tenant) RegistrationLimits(org.eclipse.hono.service.management.tenant.RegistrationLimits) Device(org.eclipse.hono.service.management.device.Device) Test(org.junit.jupiter.api.Test)

Aggregations

VertxTestContext (io.vertx.junit5.VertxTestContext)12 HttpURLConnection (java.net.HttpURLConnection)12 List (java.util.List)12 UUID (java.util.UUID)12 Credentials (org.eclipse.hono.service.management.credentials.Credentials)12 Test (org.junit.jupiter.api.Test)12 Truth.assertThat (com.google.common.truth.Truth.assertThat)11 JsonObject (io.vertx.core.json.JsonObject)11 Timeout (io.vertx.junit5.Timeout)11 TimeUnit (java.util.concurrent.TimeUnit)11 CredentialsConstants (org.eclipse.hono.util.CredentialsConstants)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 Logger (org.slf4j.Logger)11 LoggerFactory (org.slf4j.LoggerFactory)11 Instant (java.time.Instant)9 OptionalInt (java.util.OptionalInt)9 CommonCredential (org.eclipse.hono.service.management.credentials.CommonCredential)9 PasswordCredential (org.eclipse.hono.service.management.credentials.PasswordCredential)9 NoopSpan (io.opentracing.noop.NoopSpan)8 Vertx (io.vertx.core.Vertx)7