Search in sources :

Example 11 with DeviceUser

use of org.eclipse.hono.service.auth.DeviceUser in project hono by eclipse.

the class ExecutionContextAuthHandlerTest method testPreCredentialsValidationHandlerGetsInvoked.

/**
 * Verifies that the PreCredentialsValidationHandler given for the AuthHandler is invoked
 * when authenticating.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testPreCredentialsValidationHandlerGetsInvoked(final VertxTestContext ctx) {
    final Checkpoint preCredValidationHandlerInvokedCheckpoint = ctx.checkpoint();
    final Checkpoint testPassedCheckpoint = ctx.checkpoint();
    final TestExecutionContext context = new TestExecutionContext();
    final JsonObject parsedCredentials = new JsonObject().put("someKey", "someValue");
    final AbstractDeviceCredentials deviceCredentials = mock(AbstractDeviceCredentials.class);
    final DeviceUser deviceUser = new DeviceUser("tenant", "device");
    // prepare authProvider
    final DeviceCredentialsAuthProvider<?> provider = mock(DeviceCredentialsAuthProvider.class);
    doReturn(deviceCredentials).when(provider).getCredentials(any(JsonObject.class));
    doAnswer(invocation -> {
        final Handler handler = invocation.getArgument(2);
        handler.handle(Future.succeededFuture(deviceUser));
        return null;
    }).when(provider).authenticate(any(), any(), any());
    // prepare PreCredentialsValidationHandler
    final PreCredentialsValidationHandler<TestExecutionContext> preCredValidationHandler = mock(PreCredentialsValidationHandler.class);
    doAnswer(invocation -> {
        preCredValidationHandlerInvokedCheckpoint.flag();
        return Future.succeededFuture();
    }).when(preCredValidationHandler).handle(eq(deviceCredentials), eq(context));
    // GIVEN an auth handler
    final ExecutionContextAuthHandler<TestExecutionContext> authHandler = new ExecutionContextAuthHandler<>(provider, preCredValidationHandler) {

        @Override
        public Future<JsonObject> parseCredentials(final TestExecutionContext context) {
            return Future.succeededFuture(parsedCredentials);
        }
    };
    // WHEN a device gets authenticated
    authHandler.authenticateDevice(context).onComplete(ctx.succeeding(user -> {
        // THEN the returned user is the one from the auth provider
        ctx.verify(() -> {
            assertThat(user).isEqualTo(deviceUser);
        });
        testPassedCheckpoint.flag();
    }));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) Test(org.junit.jupiter.api.Test) MapBasedExecutionContext(org.eclipse.hono.util.MapBasedExecutionContext) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.doAnswer(org.mockito.Mockito.doAnswer) JsonObject(io.vertx.core.json.JsonObject) Checkpoint(io.vertx.junit5.Checkpoint) NoopSpan(io.opentracing.noop.NoopSpan) Handler(io.vertx.core.Handler) Mockito.doReturn(org.mockito.Mockito.doReturn) Mockito.mock(org.mockito.Mockito.mock) Checkpoint(io.vertx.junit5.Checkpoint) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) JsonObject(io.vertx.core.json.JsonObject) Handler(io.vertx.core.Handler) Test(org.junit.jupiter.api.Test)

Example 12 with DeviceUser

use of org.eclipse.hono.service.auth.DeviceUser in project hono by eclipse.

the class ExecutionContextAuthHandler method authenticateDevice.

private <C extends AbstractDeviceCredentials> Future<DeviceUser> authenticateDevice(final T context, final JsonObject authInfo, final DeviceCredentialsAuthProvider<C> authProvider) {
    // instead of calling "authProvider.authenticate(authInfo, handler)" directly,
    // we invoke its two main parts here (getCredentials, authenticate(credentials))
    // in order to invoke the preCredentialsValidationHandler in between and in order to pass on the tracing context
    final C credentials = authProvider.getCredentials(authInfo);
    if (credentials == null) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "malformed credentials"));
    }
    final Promise<DeviceUser> authResult = Promise.promise();
    Optional.ofNullable(preCredentialsValidationHandler).map(handler -> handler.handle(credentials, context)).orElseGet(Future::succeededFuture).onFailure(authResult::fail).onSuccess(ok -> authProvider.authenticate(credentials, context.getTracingContext(), authResult));
    return authResult.future();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Objects(java.util.Objects) Logger(org.slf4j.Logger) ExecutionContext(org.eclipse.hono.util.ExecutionContext) Promise(io.vertx.core.Promise) LoggerFactory(org.slf4j.LoggerFactory) Optional(java.util.Optional) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Future(io.vertx.core.Future) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Future(io.vertx.core.Future)

Example 13 with DeviceUser

use of org.eclipse.hono.service.auth.DeviceUser in project hono by eclipse.

the class AbstractVertxBasedMqttProtocolAdapterTest method testEndpointHandlerFailsWithoutDownstreamConnections.

// TODO: startup fail test
/**
 * Verifies that a connection attempt from a device is refused if the adapter is not connected to all of the
 * services it depends on.
 */
@Test
public void testEndpointHandlerFailsWithoutDownstreamConnections() {
    // GIVEN an adapter that is not connected to
    // all of its required services
    givenAnAdapter(properties);
    when(tenantClient.get(anyString(), any())).thenReturn(Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE)));
    when(authHandler.authenticateDevice(any(MqttConnectContext.class))).thenReturn(Future.succeededFuture(new DeviceUser(Constants.DEFAULT_TENANT, "4711")));
    // WHEN a client tries to connect
    final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
    adapter.handleEndpointConnection(endpoint);
    // THEN the connection request is rejected
    verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
}
Also used : DeviceUser(org.eclipse.hono.service.auth.DeviceUser) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Test(org.junit.jupiter.api.Test)

Example 14 with DeviceUser

use of org.eclipse.hono.service.auth.DeviceUser 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.
 */
@Test
public void testAuthenticatedMqttAdapterCreatesMessageHandlersForAuthenticatedDevices() {
    // GIVEN an adapter
    givenAnAdapter(properties);
    when(authHandler.authenticateDevice(any(MqttConnectContext.class))).thenReturn(Future.succeededFuture(new DeviceUser(Constants.DEFAULT_TENANT, "4711")));
    // 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
    verify(authHandler).authenticateDevice(any(MqttConnectContext.class));
    verify(endpoint).accept(false);
    verify(endpoint).publishHandler(VertxMockSupport.anyHandler());
    verify(endpoint, times(2)).closeHandler(VertxMockSupport.anyHandler());
    verify(metrics).reportConnectionAttempt(ConnectionAttemptOutcome.SUCCEEDED, Constants.DEFAULT_TENANT, "BUMLUX_CIPHER");
}
Also used : DeviceUser(org.eclipse.hono.service.auth.DeviceUser) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) Test(org.junit.jupiter.api.Test)

Aggregations

DeviceUser (org.eclipse.hono.service.auth.DeviceUser)14 Test (org.junit.jupiter.api.Test)11 MqttEndpoint (io.vertx.mqtt.MqttEndpoint)7 Handler (io.vertx.core.Handler)5 JsonObject (io.vertx.core.json.JsonObject)5 SpanContext (io.opentracing.SpanContext)4 Future (io.vertx.core.Future)4 ClientErrorException (org.eclipse.hono.client.ClientErrorException)4 TenantObject (org.eclipse.hono.util.TenantObject)4 HttpServerRequest (io.vertx.core.http.HttpServerRequest)3 HttpServerResponse (io.vertx.core.http.HttpServerResponse)3 Truth.assertThat (com.google.common.truth.Truth.assertThat)2 Span (io.opentracing.Span)2 NoopSpan (io.opentracing.noop.NoopSpan)2 Promise (io.vertx.core.Promise)2 RoutingContext (io.vertx.ext.web.RoutingContext)2 Checkpoint (io.vertx.junit5.Checkpoint)2 VertxExtension (io.vertx.junit5.VertxExtension)2 VertxTestContext (io.vertx.junit5.VertxTestContext)2 HttpURLConnection (java.net.HttpURLConnection)2