Search in sources :

Example 1 with Device

use of org.eclipse.hono.service.auth.device.Device in project hono by eclipse.

the class AbstractProtocolAdapterBaseTest method testGetRegistrationAssertionSucceedsForExistingDevice.

/**
 * Verifies that the adapter successfully retrieves a registration assertion
 * for an existing device.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetRegistrationAssertionSucceedsForExistingDevice(final TestContext ctx) {
    // GIVEN an adapter connected to a registration service
    final JsonObject assertionResult = newRegistrationAssertionResult("token");
    when(registrationClient.assertRegistration(eq("device"), any())).thenReturn(Future.succeededFuture(assertionResult));
    // WHEN an assertion for the device is retrieved
    adapter.getRegistrationAssertion("tenant", "device", null).setHandler(ctx.asyncAssertSuccess(result -> {
        // THEN the result contains the registration assertion
        ctx.assertEquals(assertionResult, result);
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) RunWith(org.junit.runner.RunWith) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Assert.assertThat(org.junit.Assert.assertThat) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) JsonObject(io.vertx.core.json.JsonObject) HonoClient(org.eclipse.hono.client.HonoClient) Before(org.junit.Before) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Mockito(org.mockito.Mockito) HonoClientBasedAuthProvider(org.eclipse.hono.service.auth.device.HonoClientBasedAuthProvider) Rule(org.junit.Rule) Device(org.eclipse.hono.service.auth.device.Device) Handler(io.vertx.core.Handler) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Example 2 with Device

use of org.eclipse.hono.service.auth.device.Device in project hono by eclipse.

the class VertxBasedHttpProtocolAdapter method handlePostEvent.

void handlePostEvent(final RoutingContext ctx) {
    if (Device.class.isInstance(ctx.user())) {
        Device device = (Device) ctx.user();
        uploadEventMessage(ctx, device.getTenantId(), device.getDeviceId());
    } else {
        handle401(ctx);
    }
}
Also used : Device(org.eclipse.hono.service.auth.device.Device)

Example 3 with Device

use of org.eclipse.hono.service.auth.device.Device in project hono by eclipse.

the class VertxBasedHttpProtocolAdapterTest method testBasicAuthSuccess.

@SuppressWarnings("unchecked")
@Test
public final void testBasicAuthSuccess(final TestContext context) throws Exception {
    final Async async = context.async();
    final String encodedUserPass = Base64.getEncoder().encodeToString("existinguser@DEFAULT_TENANT:password123".getBytes(StandardCharsets.UTF_8));
    doAnswer(invocation -> {
        Handler<AsyncResult<User>> resultHandler = invocation.getArgument(1);
        resultHandler.handle(Future.succeededFuture(new Device("DEFAULT_TENANT", "device_1")));
        return null;
    }).when(credentialsAuthProvider).authenticate(any(JsonObject.class), any(Handler.class));
    vertx.createHttpClient().get(httpAdapter.getInsecurePort(), HOST, "/somenonexistingroute").putHeader(HttpHeaders.CONTENT_TYPE, HttpUtils.CONTENT_TYPE_JSON).putHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedUserPass).putHeader(HttpHeaders.ORIGIN, "hono.org").handler(response -> {
        context.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.statusCode());
        context.assertEquals("*", response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
        response.bodyHandler(totalBuffer -> {
            async.complete();
        });
    }).exceptionHandler(context::fail).end();
}
Also used : Async(io.vertx.ext.unit.Async) Device(org.eclipse.hono.service.auth.device.Device) JsonObject(io.vertx.core.json.JsonObject) Handler(io.vertx.core.Handler) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.Test)

Example 4 with Device

use of org.eclipse.hono.service.auth.device.Device in project hono by eclipse.

the class AbstractVertxBasedMqttProtocolAdapter method uploadMessage.

private Future<Void> uploadMessage(final MqttContext ctx, final String tenant, final String deviceId, final Buffer payload, final Future<MessageSender> senderTracker, final String endpointName) {
    if (payload.length() == 0) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "payload must not be empty"));
    } else {
        final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId, ctx.authenticatedDevice());
        final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant);
        return CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> {
            if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) {
                final Message downstreamMessage = newMessage(String.format("%s/%s", endpointName, tenant), deviceId, ctx.message().topicName(), ctx.contentType(), payload, tokenTracker.result());
                customizeDownstreamMessage(downstreamMessage, ctx);
                return senderTracker.result().send(downstreamMessage);
            } else {
                // this adapter is not enabled for the tenant
                return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
            }
        }).compose(delivery -> {
            LOG.trace("successfully processed message [topic: {}, QoS: {}] for device [tenantId: {}, deviceId: {}]", ctx.message().topicName(), ctx.message().qosLevel(), tenant, deviceId);
            metrics.incrementProcessedMqttMessages(endpointName, tenant);
            onMessageSent(ctx);
            // check that the remote MQTT client is still connected before sending PUBACK
            if (ctx.deviceEndpoint().isConnected() && ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) {
                ctx.deviceEndpoint().publishAcknowledge(ctx.message().messageId());
            }
            return Future.<Void>succeededFuture();
        }).recover(t -> {
            if (ClientErrorException.class.isInstance(t)) {
                ClientErrorException e = (ClientErrorException) t;
                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]: {} - {}", tenant, deviceId, endpointName, e.getErrorCode(), e.getMessage());
            } else {
                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]", tenant, deviceId, endpointName, t);
                metrics.incrementUndeliverableMqttMessages(endpointName, tenant);
                onMessageUndeliverable(ctx);
            }
            return Future.failedFuture(t);
        });
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) MqttConnectReturnCode(io.netty.handler.codec.mqtt.MqttConnectReturnCode) LoggerFactory(org.slf4j.LoggerFactory) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) Autowired(org.springframework.beans.factory.annotation.Autowired) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) MqttServer(io.vertx.mqtt.MqttServer) CompositeFuture(io.vertx.core.CompositeFuture) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) MessageSender(org.eclipse.hono.client.MessageSender) AbstractProtocolAdapterBase(org.eclipse.hono.service.AbstractProtocolAdapterBase) Message(org.apache.qpid.proton.message.Message) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) UsernamePasswordCredentials(org.eclipse.hono.service.auth.device.UsernamePasswordCredentials) Logger(org.slf4j.Logger) MqttServerOptions(io.vertx.mqtt.MqttServerOptions) DeviceCredentials(org.eclipse.hono.service.auth.device.DeviceCredentials) ServerErrorException(org.eclipse.hono.client.ServerErrorException) EndpointType(org.eclipse.hono.util.EndpointType) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) MqttAuth(io.vertx.mqtt.MqttAuth) Device(org.eclipse.hono.service.auth.device.Device) TenantObject(org.eclipse.hono.util.TenantObject) Message(org.apache.qpid.proton.message.Message) ClientErrorException(org.eclipse.hono.client.ClientErrorException) JsonObject(io.vertx.core.json.JsonObject)

Example 5 with Device

use of org.eclipse.hono.service.auth.device.Device in project hono by eclipse.

the class AbstractVertxBasedMqttProtocolAdapterTest method testUploadTelemetryMessageFailsForDisabledTenant.

/**
 * Verifies that the adapter does not forward a message published by a device
 * if the device belongs to a tenant for which the adapter has been disabled.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUploadTelemetryMessageFailsForDisabledTenant(final TestContext ctx) {
    // GIVEN an adapter
    final MqttServer server = getMqttServer(false);
    // which is disabled for tenant "my-tenant"
    final TenantObject myTenantConfig = TenantObject.from("my-tenant", true);
    myTenantConfig.addAdapterConfiguration(new JsonObject().put(TenantConstants.FIELD_ADAPTERS_TYPE, ADAPTER_TYPE).put(TenantConstants.FIELD_ENABLED, false));
    when(tenantClient.get("my-tenant")).thenReturn(Future.succeededFuture(myTenantConfig));
    final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();
    final MessageSender sender = mock(MessageSender.class);
    when(messagingClient.getOrCreateTelemetrySender(anyString())).thenReturn(Future.succeededFuture(sender));
    // WHEN a device of "my-tenant" publishes a telemetry message
    adapter.uploadTelemetryMessage(new MqttContext(mock(MqttPublishMessage.class), mock(MqttEndpoint.class)), "my-tenant", "the-device", Buffer.buffer("test")).setHandler(ctx.asyncAssertFailure(t -> {
        // THEN the message has not been sent downstream
        verify(sender, never()).send(any(Message.class));
        // because the tenant is not enabled
        ctx.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, ((ClientErrorException) t).getErrorCode());
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) ArgumentMatchers(org.mockito.ArgumentMatchers) ProtonDelivery(io.vertx.proton.ProtonDelivery) MqttConnectReturnCode(io.netty.handler.codec.mqtt.MqttConnectReturnCode) TenantConstants(org.eclipse.hono.util.TenantConstants) RunWith(org.junit.runner.RunWith) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Context(io.vertx.core.Context) MqttServer(io.vertx.mqtt.MqttServer) Assert.assertThat(org.junit.Assert.assertThat) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) TenantClient(org.eclipse.hono.client.TenantClient) MessageSender(org.eclipse.hono.client.MessageSender) BiConsumer(java.util.function.BiConsumer) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) HonoClient(org.eclipse.hono.client.HonoClient) Before(org.junit.Before) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) AfterClass(org.junit.AfterClass) UsernamePasswordCredentials(org.eclipse.hono.service.auth.device.UsernamePasswordCredentials) DeviceCredentials(org.eclipse.hono.service.auth.device.DeviceCredentials) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) HonoClientBasedAuthProvider(org.eclipse.hono.service.auth.device.HonoClientBasedAuthProvider) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) MqttAuth(io.vertx.mqtt.MqttAuth) Device(org.eclipse.hono.service.auth.device.Device) Handler(io.vertx.core.Handler) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) TenantObject(org.eclipse.hono.util.TenantObject) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MessageSender(org.eclipse.hono.client.MessageSender) MqttServer(io.vertx.mqtt.MqttServer) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Test(org.junit.Test)

Aggregations

Device (org.eclipse.hono.service.auth.device.Device)16 Future (io.vertx.core.Future)13 ProtocolAdapterProperties (org.eclipse.hono.config.ProtocolAdapterProperties)13 MqttQoS (io.netty.handler.codec.mqtt.MqttQoS)12 Buffer (io.vertx.core.buffer.Buffer)12 MqttEndpoint (io.vertx.mqtt.MqttEndpoint)12 EventConstants (org.eclipse.hono.util.EventConstants)12 ResourceIdentifier (org.eclipse.hono.util.ResourceIdentifier)12 TelemetryConstants (org.eclipse.hono.util.TelemetryConstants)12 Test (org.junit.Test)12 Async (io.vertx.ext.unit.Async)11 TestContext (io.vertx.ext.unit.TestContext)11 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)11 CoreMatchers.is (org.hamcrest.CoreMatchers.is)11 Assert.assertThat (org.junit.Assert.assertThat)11 Rule (org.junit.Rule)11 Timeout (org.junit.rules.Timeout)11 RunWith (org.junit.runner.RunWith)11 MqttPublishMessage (io.vertx.mqtt.messages.MqttPublishMessage)10 EndpointType (org.eclipse.hono.util.EndpointType)10