Search in sources :

Example 6 with Device

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

the class VertxBasedMqttProtocolAdapterTest method testOnPublishedMessageFailsForMissingDeviceId.

/**
 * Verifies that the adapter fails to map a topic without a device ID received from an anonymous device.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@Test
public void testOnPublishedMessageFailsForMissingDeviceId(final TestContext ctx) {
    givenAnAdapter();
    // WHEN an anonymous device publishes a message to a topic that does not contain a device ID
    final MqttContext context = newContext(MqttQoS.AT_MOST_ONCE, TelemetryConstants.TELEMETRY_ENDPOINT + "/my-tenant");
    adapter.onPublishedMessage(context).setHandler(ctx.asyncAssertFailure(t -> {
    // THEN the message cannot be mapped to an address
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) RunWith(org.junit.runner.RunWith) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) EndpointType(org.eclipse.hono.util.EndpointType) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Assert.assertThat(org.junit.Assert.assertThat) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) Timeout(org.junit.rules.Timeout) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Device(org.eclipse.hono.service.auth.device.Device) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) Test(org.junit.Test)

Example 7 with Device

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

the class VertxBasedMqttProtocolAdapterTest method testOnPublishedMessageFailsForMissingTenant.

/**
 * Verifies that the adapter fails to map a topic without a tenant ID received from an anonymous device.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@Test
public void testOnPublishedMessageFailsForMissingTenant(final TestContext ctx) {
    givenAnAdapter();
    // WHEN an anonymous device publishes a message to a topic that does not contain a tenant ID
    final MqttContext context = newContext(MqttQoS.AT_MOST_ONCE, TelemetryConstants.TELEMETRY_ENDPOINT);
    adapter.onPublishedMessage(context).setHandler(ctx.asyncAssertFailure(t -> {
    // THEN the message cannot be mapped to an address
    }));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) RunWith(org.junit.runner.RunWith) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) EndpointType(org.eclipse.hono.util.EndpointType) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Assert.assertThat(org.junit.Assert.assertThat) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) Timeout(org.junit.rules.Timeout) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Device(org.eclipse.hono.service.auth.device.Device) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) Test(org.junit.Test)

Example 8 with Device

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

the class VertxBasedHttpProtocolAdapter method handlePostTelemetry.

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

Example 9 with Device

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

the class AbstractVertxBasedMqttProtocolAdapter method handleEndpointConnectionWithAuthentication.

private void handleEndpointConnectionWithAuthentication(final MqttEndpoint endpoint) {
    if (endpoint.auth() == null) {
        LOG.debug("connection request from device [clientId: {}] rejected: {}", endpoint.clientIdentifier(), "device did not provide credentials in CONNECT packet");
        endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);
    } else {
        final DeviceCredentials credentials = getCredentials(endpoint.auth());
        if (credentials == null) {
            LOG.debug("connection request from device [clientId: {}] rejected: {}", endpoint.clientIdentifier(), "device provided malformed credentials in CONNECT packet");
            endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);
        } else {
            getTenantConfiguration(credentials.getTenantId()).compose(tenantConfig -> {
                if (tenantConfig.isAdapterEnabled(getTypeName())) {
                    LOG.debug("protocol adapter [{}] is enabled for tenant [{}]", getTypeName(), credentials.getTenantId());
                    return Future.succeededFuture(tenantConfig);
                } else {
                    LOG.debug("protocol adapter [{}] is disabled for tenant [{}]", getTypeName(), credentials.getTenantId());
                    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN, "adapter disabled for tenant"));
                }
            }).compose(tenantConfig -> {
                final Future<Device> result = Future.future();
                getCredentialsAuthProvider().authenticate(credentials, result.completer());
                return result;
            }).map(authenticatedDevice -> {
                LOG.debug("successfully authenticated device [tenant-id: {}, auth-id: {}, device-id: {}]", authenticatedDevice.getTenantId(), credentials.getAuthId(), authenticatedDevice.getDeviceId());
                onAuthenticationSuccess(endpoint, authenticatedDevice);
                return null;
            }).otherwise(t -> {
                LOG.debug("cannot authenticate device [tenant-id: {}, auth-id: {}]", credentials.getTenantId(), credentials.getAuthId(), t);
                if (ServerErrorException.class.isInstance(t)) {
                    // one of the services we depend on might not be available (yet)
                    endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
                } else {
                    // validation of credentials has failed
                    endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
                }
                return null;
            });
        }
    }
}
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) Device(org.eclipse.hono.service.auth.device.Device) ClientErrorException(org.eclipse.hono.client.ClientErrorException) DeviceCredentials(org.eclipse.hono.service.auth.device.DeviceCredentials)

Example 10 with Device

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

the class AbstractVertxBasedMqttProtocolAdapterTest method testAuthenticatedMqttAdapterCreatesMessageHandlersForAuthenticatedDevices.

/**
 * Verifies that on successful authentication the adapter sets appropriate message and close
 * handlers on the client endpoint.
 */
@SuppressWarnings({ "unchecked" })
@Test
public void testAuthenticatedMqttAdapterCreatesMessageHandlersForAuthenticatedDevices() {
    // GIVEN an adapter
    final MqttServer server = getMqttServer(false);
    final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
    forceClientMocksToConnected();
    doAnswer(invocation -> {
        Handler<AsyncResult<Device>> resultHandler = invocation.getArgument(1);
        resultHandler.handle(Future.succeededFuture(new Device("DEFAULT_TENANT", "4711")));
        return null;
    }).when(credentialsAuthProvider).authenticate(any(DeviceCredentials.class), any(Handler.class));
    // WHEN a device tries to connect with valid credentials
    final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
    adapter.handleEndpointConnection(endpoint);
    // THEN the device's logical ID is successfully established and corresponding handlers
    // are registered
    final ArgumentCaptor<DeviceCredentials> credentialsCaptor = ArgumentCaptor.forClass(DeviceCredentials.class);
    verify(credentialsAuthProvider).authenticate(credentialsCaptor.capture(), any(Handler.class));
    assertThat(credentialsCaptor.getValue().getAuthId(), is("sensor1"));
    verify(endpoint).accept(false);
    verify(endpoint).publishHandler(any(Handler.class));
    verify(endpoint).closeHandler(any(Handler.class));
}
Also used : ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) Device(org.eclipse.hono.service.auth.device.Device) MqttServer(io.vertx.mqtt.MqttServer) Handler(io.vertx.core.Handler) DeviceCredentials(org.eclipse.hono.service.auth.device.DeviceCredentials) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.Test)

Aggregations

Device (org.eclipse.hono.service.auth.device.Device)17 ProtocolAdapterProperties (org.eclipse.hono.config.ProtocolAdapterProperties)14 Future (io.vertx.core.Future)13 MqttEndpoint (io.vertx.mqtt.MqttEndpoint)13 Test (org.junit.Test)13 MqttQoS (io.netty.handler.codec.mqtt.MqttQoS)12 Buffer (io.vertx.core.buffer.Buffer)12 EventConstants (org.eclipse.hono.util.EventConstants)12 ResourceIdentifier (org.eclipse.hono.util.ResourceIdentifier)12 TelemetryConstants (org.eclipse.hono.util.TelemetryConstants)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