Search in sources :

Example 36 with Device

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

the class VertxBasedAmqpProtocolAdapterTest method testUploadEventRejectsPresettledMessage.

/**
 * Verifies that the adapter rejects presettled messages with an event address.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUploadEventRejectsPresettledMessage(final VertxTestContext ctx) {
    // GIVEN an adapter
    givenAnAdapter(properties);
    givenAnEventSenderForAnyTenant();
    // with an enabled tenant
    givenAConfiguredTenant(TEST_TENANT_ID, true);
    // WHEN a device uploads an event using a presettled message
    final Device gateway = new Device(TEST_TENANT_ID, "device");
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    // AT MOST ONCE
    when(delivery.remotelySettled()).thenReturn(true);
    final String to = ResourceIdentifier.fromString(EventConstants.EVENT_ENDPOINT).toString();
    final Buffer payload = Buffer.buffer("some payload");
    adapter.onMessageReceived(AmqpContext.fromMessage(delivery, getFakeMessage(to, payload), span, gateway)).onComplete(ctx.failing(t -> {
        ctx.verify(() -> {
            // THEN the adapter does not forward the event
            assertNoEventHasBeenSentDownstream();
            // AND notifies the device by sending back a REJECTED disposition
            verify(delivery).disposition(any(Rejected.class), eq(true));
        });
        ctx.completeNow();
    }));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) MessagingType(org.eclipse.hono.util.MessagingType) EventBus(io.vertx.core.eventbus.EventBus) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) DeliveryState(org.apache.qpid.proton.amqp.transport.DeliveryState) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) CommandContext(org.eclipse.hono.client.command.CommandContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) EventConstants(org.eclipse.hono.util.EventConstants) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) Mockito.mock(org.mockito.Mockito.mock) VertxTestContext(io.vertx.junit5.VertxTestContext) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) Target(org.apache.qpid.proton.amqp.messaging.Target) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) Commands(org.eclipse.hono.client.command.Commands) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Vertx(io.vertx.core.Vertx) Mockito.times(org.mockito.Mockito.times) ProtonHelper(io.vertx.proton.ProtonHelper) Released(org.apache.qpid.proton.amqp.messaging.Released) SpanContext(io.opentracing.SpanContext) Mockito.never(org.mockito.Mockito.never) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ProtonReceiver(io.vertx.proton.ProtonReceiver) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Context(io.vertx.core.Context) ProtonServer(io.vertx.proton.ProtonServer) Timeout(io.vertx.junit5.Timeout) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) NotificationType(org.eclipse.hono.notification.NotificationType) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Binary(org.apache.qpid.proton.amqp.Binary) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) Data(org.apache.qpid.proton.amqp.messaging.Data) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) ProtonQoS(io.vertx.proton.ProtonQoS) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Test(org.junit.jupiter.api.Test) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) Buffer(io.vertx.core.buffer.Buffer) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Mockito.inOrder(org.mockito.Mockito.inOrder) ProtonSender(io.vertx.proton.ProtonSender) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) QoS(org.eclipse.hono.util.QoS) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AbstractNotification(org.eclipse.hono.notification.AbstractNotification) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ProtonDelivery(io.vertx.proton.ProtonDelivery) ConnectionLimitManager(org.eclipse.hono.adapter.limiting.ConnectionLimitManager) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ConnectionEventProducer(org.eclipse.hono.adapter.monitoring.ConnectionEventProducer) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) Constants(org.eclipse.hono.util.Constants) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) RecordImpl(org.apache.qpid.proton.engine.impl.RecordImpl) Message(org.apache.qpid.proton.message.Message) HttpUtils(org.eclipse.hono.service.http.HttpUtils) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) InOrder(org.mockito.InOrder) Promise(io.vertx.core.Promise) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) ApplicationProperties(org.apache.qpid.proton.amqp.messaging.ApplicationProperties) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Source(org.apache.qpid.proton.amqp.transport.Source) Adapter(org.eclipse.hono.util.Adapter) Handler(io.vertx.core.Handler) Record(org.apache.qpid.proton.engine.Record) ProtonDelivery(io.vertx.proton.ProtonDelivery) Device(org.eclipse.hono.auth.Device) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test)

Example 37 with Device

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

the class VertxBasedAmqpProtocolAdapterTest method testUploadEventFailsForGatewayOfDifferentTenant.

/**
 * Verifies that a request from a gateway to upload an event on behalf of a device that belongs
 * to another tenant than the gateway fails.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUploadEventFailsForGatewayOfDifferentTenant(final VertxTestContext ctx) {
    // GIVEN an adapter
    givenAnAdapter(properties);
    givenAnEventSenderForAnyTenant();
    // with an enabled tenant
    givenAConfiguredTenant(TEST_TENANT_ID, true);
    // WHEN a gateway uploads an event on behalf of a device of another tenant
    final Device gateway = new Device(TEST_TENANT_ID, "gw");
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    // AT LEAST ONCE
    when(delivery.remotelySettled()).thenReturn(false);
    final String to = ResourceIdentifier.from(EventConstants.EVENT_ENDPOINT, "other-tenant", TEST_DEVICE).toString();
    final Buffer payload = Buffer.buffer("some payload");
    adapter.onMessageReceived(AmqpContext.fromMessage(delivery, getFakeMessage(to, payload), span, gateway)).onComplete(ctx.failing(t -> {
        ctx.verify(() -> {
            // THEN the adapter does not send the event
            assertNoEventHasBeenSentDownstream();
            // AND notifies the device by sending back a REJECTED disposition
            verify(delivery).disposition(any(Rejected.class), eq(true));
        });
        ctx.completeNow();
    }));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) MessagingType(org.eclipse.hono.util.MessagingType) EventBus(io.vertx.core.eventbus.EventBus) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) DeliveryState(org.apache.qpid.proton.amqp.transport.DeliveryState) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) CommandContext(org.eclipse.hono.client.command.CommandContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) EventConstants(org.eclipse.hono.util.EventConstants) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) Mockito.mock(org.mockito.Mockito.mock) VertxTestContext(io.vertx.junit5.VertxTestContext) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) Target(org.apache.qpid.proton.amqp.messaging.Target) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) Commands(org.eclipse.hono.client.command.Commands) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Vertx(io.vertx.core.Vertx) Mockito.times(org.mockito.Mockito.times) ProtonHelper(io.vertx.proton.ProtonHelper) Released(org.apache.qpid.proton.amqp.messaging.Released) SpanContext(io.opentracing.SpanContext) Mockito.never(org.mockito.Mockito.never) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ProtonReceiver(io.vertx.proton.ProtonReceiver) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Context(io.vertx.core.Context) ProtonServer(io.vertx.proton.ProtonServer) Timeout(io.vertx.junit5.Timeout) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) NotificationType(org.eclipse.hono.notification.NotificationType) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Binary(org.apache.qpid.proton.amqp.Binary) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) Data(org.apache.qpid.proton.amqp.messaging.Data) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) ProtonQoS(io.vertx.proton.ProtonQoS) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Test(org.junit.jupiter.api.Test) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) Buffer(io.vertx.core.buffer.Buffer) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Mockito.inOrder(org.mockito.Mockito.inOrder) ProtonSender(io.vertx.proton.ProtonSender) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) QoS(org.eclipse.hono.util.QoS) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AbstractNotification(org.eclipse.hono.notification.AbstractNotification) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ProtonDelivery(io.vertx.proton.ProtonDelivery) ConnectionLimitManager(org.eclipse.hono.adapter.limiting.ConnectionLimitManager) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ConnectionEventProducer(org.eclipse.hono.adapter.monitoring.ConnectionEventProducer) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) Constants(org.eclipse.hono.util.Constants) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) RecordImpl(org.apache.qpid.proton.engine.impl.RecordImpl) Message(org.apache.qpid.proton.message.Message) HttpUtils(org.eclipse.hono.service.http.HttpUtils) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) InOrder(org.mockito.InOrder) Promise(io.vertx.core.Promise) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) ApplicationProperties(org.apache.qpid.proton.amqp.messaging.ApplicationProperties) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Source(org.apache.qpid.proton.amqp.transport.Source) Adapter(org.eclipse.hono.util.Adapter) Handler(io.vertx.core.Handler) Record(org.apache.qpid.proton.engine.Record) ProtonDelivery(io.vertx.proton.ProtonDelivery) Device(org.eclipse.hono.auth.Device) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test)

Example 38 with Device

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

the class VertxBasedAmqpProtocolAdapterTest method testUploadCommandResponseWithoutPayloadSucceeds.

/**
 * Verify that the AMQP adapter forwards command responses that do not contain a payload downstream.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUploadCommandResponseWithoutPayloadSucceeds(final VertxTestContext ctx) {
    // GIVEN an AMQP adapter
    givenAnAdapter(properties);
    final CommandResponseSender responseSender = givenACommandResponseSenderForAnyTenant();
    when(responseSender.sendCommandResponse(any(TenantObject.class), any(RegistrationAssertion.class), any(CommandResponse.class), (SpanContext) any())).thenReturn(Future.succeededFuture());
    // which is enabled for the test tenant
    final TenantObject tenantObject = givenAConfiguredTenant(TEST_TENANT_ID, true);
    // WHEN an unauthenticated device publishes a command response
    final String replyToAddress = String.format("%s/%s/%s", getCommandResponseEndpoint(), TEST_TENANT_ID, Commands.getDeviceFacingReplyToId("test-reply-id", TEST_DEVICE, MessagingType.amqp));
    final Map<String, Object> propertyMap = new HashMap<>();
    propertyMap.put(MessageHelper.APP_PROPERTY_STATUS, 200);
    final ApplicationProperties props = new ApplicationProperties(propertyMap);
    final Message message = getFakeMessage(replyToAddress, null);
    message.setCorrelationId("correlation-id");
    message.setApplicationProperties(props);
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    adapter.onMessageReceived(AmqpContext.fromMessage(delivery, message, span, null)).onComplete(ctx.succeeding(ok -> {
        ctx.verify(() -> {
            // THEN the adapter forwards the command response message downstream
            verify(responseSender).sendCommandResponse(eq(tenantObject), any(RegistrationAssertion.class), any(CommandResponse.class), (SpanContext) any());
            // and reports the forwarded message
            verify(metrics).reportCommand(eq(Direction.RESPONSE), eq(TEST_TENANT_ID), eq(tenantObject), eq(ProcessingOutcome.FORWARDED), eq(0), any());
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) MessagingType(org.eclipse.hono.util.MessagingType) EventBus(io.vertx.core.eventbus.EventBus) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) DeliveryState(org.apache.qpid.proton.amqp.transport.DeliveryState) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) CommandContext(org.eclipse.hono.client.command.CommandContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) EventConstants(org.eclipse.hono.util.EventConstants) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) Mockito.mock(org.mockito.Mockito.mock) VertxTestContext(io.vertx.junit5.VertxTestContext) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) Target(org.apache.qpid.proton.amqp.messaging.Target) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) Commands(org.eclipse.hono.client.command.Commands) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Vertx(io.vertx.core.Vertx) Mockito.times(org.mockito.Mockito.times) ProtonHelper(io.vertx.proton.ProtonHelper) Released(org.apache.qpid.proton.amqp.messaging.Released) SpanContext(io.opentracing.SpanContext) Mockito.never(org.mockito.Mockito.never) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ProtonReceiver(io.vertx.proton.ProtonReceiver) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Context(io.vertx.core.Context) ProtonServer(io.vertx.proton.ProtonServer) Timeout(io.vertx.junit5.Timeout) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) NotificationType(org.eclipse.hono.notification.NotificationType) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Binary(org.apache.qpid.proton.amqp.Binary) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) Data(org.apache.qpid.proton.amqp.messaging.Data) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) ProtonQoS(io.vertx.proton.ProtonQoS) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Test(org.junit.jupiter.api.Test) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) Buffer(io.vertx.core.buffer.Buffer) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Mockito.inOrder(org.mockito.Mockito.inOrder) ProtonSender(io.vertx.proton.ProtonSender) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) QoS(org.eclipse.hono.util.QoS) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AbstractNotification(org.eclipse.hono.notification.AbstractNotification) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ProtonDelivery(io.vertx.proton.ProtonDelivery) ConnectionLimitManager(org.eclipse.hono.adapter.limiting.ConnectionLimitManager) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ConnectionEventProducer(org.eclipse.hono.adapter.monitoring.ConnectionEventProducer) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) Constants(org.eclipse.hono.util.Constants) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) RecordImpl(org.apache.qpid.proton.engine.impl.RecordImpl) Message(org.apache.qpid.proton.message.Message) HttpUtils(org.eclipse.hono.service.http.HttpUtils) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) InOrder(org.mockito.InOrder) Promise(io.vertx.core.Promise) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Mockito.verify(org.mockito.Mockito.verify) ApplicationProperties(org.apache.qpid.proton.amqp.messaging.ApplicationProperties) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Source(org.apache.qpid.proton.amqp.transport.Source) Adapter(org.eclipse.hono.util.Adapter) Handler(io.vertx.core.Handler) Record(org.apache.qpid.proton.engine.Record) SpanContext(io.opentracing.SpanContext) Message(org.apache.qpid.proton.message.Message) ProtonDelivery(io.vertx.proton.ProtonDelivery) HashMap(java.util.HashMap) CommandResponse(org.eclipse.hono.client.command.CommandResponse) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) TenantObject(org.eclipse.hono.util.TenantObject) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) ApplicationProperties(org.apache.qpid.proton.amqp.messaging.ApplicationProperties) TenantObject(org.eclipse.hono.util.TenantObject) Test(org.junit.jupiter.api.Test)

Example 39 with Device

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

the class VertxBasedAmqpProtocolAdapter method openCommandSenderLink.

private Future<CommandConsumer> openCommandSenderLink(final ProtonConnection connection, final ProtonSender sender, final ResourceIdentifier address, final Device authenticatedDevice, final Span span, final OptionalInt traceSamplingPriority) {
    return createCommandConsumer(sender, address, authenticatedDevice, span).map(consumer -> {
        final String tenantId = address.getTenantId();
        final String deviceId = address.getResourceId();
        sender.setSource(sender.getRemoteSource());
        sender.setTarget(sender.getRemoteTarget());
        sender.setQoS(ProtonQoS.AT_LEAST_ONCE);
        final Handler<AsyncResult<ProtonSender>> detachHandler = link -> {
            final Span detachHandlerSpan = newSpan("detach device command receiver link", authenticatedDevice, traceSamplingPriority);
            removeCommandSubscription(connection, address.toString());
            onLinkDetach(sender);
            closeCommandConsumer(consumer, address, authenticatedDevice, true, detachHandlerSpan).onComplete(v -> detachHandlerSpan.finish());
        };
        HonoProtonHelper.setCloseHandler(sender, detachHandler);
        HonoProtonHelper.setDetachHandler(sender, detachHandler);
        sender.open();
        // At this point, the remote peer's receiver link is successfully opened and is ready to receive
        // commands. Send "device ready for command" notification downstream.
        log.debug("established link [address: {}] for sending commands to device", address);
        sendConnectedTtdEvent(tenantId, deviceId, authenticatedDevice, span.context());
        registerCommandSubscription(connection, new CommandSubscription(consumer, address));
        return consumer;
    }).recover(t -> Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "cannot create command consumer")));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Tags(io.opentracing.tag.Tags) ProtonServer(io.vertx.proton.ProtonServer) HonoProtonHelper(org.eclipse.hono.util.HonoProtonHelper) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) Modified(org.apache.qpid.proton.amqp.messaging.Modified) DeviceCredentials(org.eclipse.hono.adapter.auth.device.DeviceCredentials) Map(java.util.Map) DeliveryState(org.apache.qpid.proton.amqp.transport.DeliveryState) AuthorizationException(org.eclipse.hono.adapter.AuthorizationException) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Fields(io.opentracing.log.Fields) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) TracingHelper(org.eclipse.hono.tracing.TracingHelper) ProtonSaslAuthenticatorFactory(io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) TenantServiceBasedX509Authentication(org.eclipse.hono.adapter.auth.device.TenantServiceBasedX509Authentication) Predicate(java.util.function.Predicate) Collection(java.util.Collection) CommandContext(org.eclipse.hono.client.command.CommandContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ProtonQoS(io.vertx.proton.ProtonQoS) MessageHelper(org.eclipse.hono.util.MessageHelper) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) List(java.util.List) QoS(org.eclipse.hono.service.metric.MetricsTags.QoS) TenantTraceSamplingHelper(org.eclipse.hono.tracing.TenantTraceSamplingHelper) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Optional(java.util.Optional) Span(io.opentracing.Span) ProtonSender(io.vertx.proton.ProtonSender) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) ProtonLink(io.vertx.proton.ProtonLink) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) ProtonServerOptions(io.vertx.proton.ProtonServerOptions) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) ConnectionLimitManager(org.eclipse.hono.adapter.limiting.ConnectionLimitManager) Command(org.eclipse.hono.client.command.Command) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) AdapterDisabledException(org.eclipse.hono.adapter.AdapterDisabledException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) OptionalInt(java.util.OptionalInt) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Commands(org.eclipse.hono.client.command.Commands) Constants(org.eclipse.hono.util.Constants) CompositeFuture(io.vertx.core.CompositeFuture) ProtonSession(io.vertx.proton.ProtonSession) Symbol(org.apache.qpid.proton.amqp.Symbol) AdapterConnectionsExceededException(org.eclipse.hono.adapter.AdapterConnectionsExceededException) Target(org.apache.qpid.proton.amqp.transport.Target) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) Message(org.apache.qpid.proton.message.Message) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) Strings(org.eclipse.hono.util.Strings) UsernamePasswordAuthProvider(org.eclipse.hono.adapter.auth.device.UsernamePasswordAuthProvider) CredentialsApiAuthProvider(org.eclipse.hono.adapter.auth.device.CredentialsApiAuthProvider) AbstractProtocolAdapterBase(org.eclipse.hono.adapter.AbstractProtocolAdapterBase) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ProtonHelper(io.vertx.proton.ProtonHelper) Sample(io.micrometer.core.instrument.Timer.Sample) Released(org.apache.qpid.proton.amqp.messaging.Released) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) Source(org.apache.qpid.proton.amqp.transport.Source) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) MemoryBasedConnectionLimitStrategy(org.eclipse.hono.adapter.limiting.MemoryBasedConnectionLimitStrategy) X509AuthProvider(org.eclipse.hono.adapter.auth.device.X509AuthProvider) Handler(io.vertx.core.Handler) Collections(java.util.Collections) DefaultConnectionLimitManager(org.eclipse.hono.adapter.limiting.DefaultConnectionLimitManager) ProtonSender(io.vertx.proton.ProtonSender) Handler(io.vertx.core.Handler) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Span(io.opentracing.Span)

Example 40 with Device

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

the class VertxBasedAmqpProtocolAdapter method handleRemoteReceiverOpen.

/**
 * This method is invoked when a device wants to open a link for uploading messages.
 * <p>
 * The same link is used by the device to upload telemetry data, events and command
 * responses to be forwarded downstream.
 * <p>
 * If the attach frame contains a target address, this method simply closes the link,
 * otherwise, it accepts and opens the link.
 *
 * @param conn The connection through which the request is initiated.
 * @param receiver The receiver link for receiving the data.
 */
protected void handleRemoteReceiverOpen(final ProtonConnection conn, final ProtonReceiver receiver) {
    final Device authenticatedDevice = getAuthenticatedDevice(conn);
    final OptionalInt traceSamplingPriority = getTraceSamplingPriority(conn);
    final Span span = newSpan("attach device sender link", authenticatedDevice, traceSamplingPriority);
    span.log(Map.of("snd-settle-mode", receiver.getRemoteQoS()));
    final String remoteTargetAddress = Optional.ofNullable(receiver.getRemoteTarget()).map(Target::getAddress).orElse(null);
    if (!Strings.isNullOrEmpty(remoteTargetAddress)) {
        log.debug("client provided target address [{}] in open frame, closing link [container: {}, {}]", remoteTargetAddress, conn.getRemoteContainer(), authenticatedDevice);
        span.log(Map.of("target address", remoteTargetAddress));
        final Exception ex = new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "container supports anonymous terminus only");
        closeLinkWithError(receiver, ex, span);
    } else {
        receiver.setTarget(receiver.getRemoteTarget());
        receiver.setSource(receiver.getRemoteSource());
        receiver.setQoS(receiver.getRemoteQoS());
        receiver.setPrefetch(30);
        // manage disposition handling manually
        receiver.setAutoAccept(false);
        receiver.maxMessageSizeExceededHandler(recv -> {
            final Span errorSpan = newSpan("upload message", authenticatedDevice, traceSamplingPriority);
            log.debug("incoming message size exceeds configured maximum of {} bytes; link will be detached [container: {}, {}]", getConfig().getMaxPayloadSize(), conn.getRemoteContainer(), authenticatedDevice);
            TracingHelper.logError(errorSpan, String.format("incoming message size exceeds configured maximum of %s bytes", getConfig().getMaxPayloadSize()));
            errorSpan.log("device sender link will be detached");
            errorSpan.finish();
        });
        HonoProtonHelper.setCloseHandler(receiver, remoteDetach -> onLinkDetach(receiver));
        HonoProtonHelper.setDetachHandler(receiver, remoteDetach -> onLinkDetach(receiver));
        receiver.handler((delivery, message) -> {
            try {
                final SpanContext spanContext = TracingHelper.extractSpanContext(tracer, message);
                final Span msgSpan = newSpan("upload message", authenticatedDevice, traceSamplingPriority, spanContext);
                HonoProtonHelper.onReceivedMessageDeliveryUpdatedFromRemote(delivery, d -> {
                    log.debug("got unexpected disposition update for message received from device [remote state: {}, container: {}, {}]", delivery.getRemoteState(), conn.getRemoteContainer(), authenticatedDevice);
                    msgSpan.log("got unexpected disposition from device [remote state: " + delivery.getRemoteState() + "]");
                });
                msgSpan.log(Map.of(Tags.MESSAGE_BUS_DESTINATION.getKey(), message.getAddress(), "settled", delivery.remotelySettled()));
                final AmqpContext ctx = AmqpContext.fromMessage(delivery, message, msgSpan, authenticatedDevice);
                ctx.setTimer(metrics.startTimer());
                final Future<Void> spanPreparationFuture = authenticatedDevice == null ? applyTraceSamplingPriorityForAddressTenant(ctx.getAddress(), msgSpan) : Future.succeededFuture();
                spanPreparationFuture.compose(ar -> onMessageReceived(ctx).onSuccess(ok -> msgSpan.finish()).onFailure(error -> closeConnectionOnTerminalError(error, conn, ctx, msgSpan)));
            } catch (final Exception ex) {
                log.warn("error handling message [container: {}, {}]", conn.getRemoteContainer(), authenticatedDevice, ex);
                if (!conn.isDisconnected()) {
                    ProtonHelper.released(delivery, true);
                }
            }
        });
        receiver.open();
        log.debug("established link for receiving messages from device [container: {}, {}]", conn.getRemoteContainer(), authenticatedDevice);
        span.log("link established");
    }
    span.finish();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Tags(io.opentracing.tag.Tags) ProtonServer(io.vertx.proton.ProtonServer) HonoProtonHelper(org.eclipse.hono.util.HonoProtonHelper) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) Modified(org.apache.qpid.proton.amqp.messaging.Modified) DeviceCredentials(org.eclipse.hono.adapter.auth.device.DeviceCredentials) Map(java.util.Map) DeliveryState(org.apache.qpid.proton.amqp.transport.DeliveryState) AuthorizationException(org.eclipse.hono.adapter.AuthorizationException) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) Fields(io.opentracing.log.Fields) AmqpError(org.apache.qpid.proton.amqp.transport.AmqpError) TracingHelper(org.eclipse.hono.tracing.TracingHelper) ProtonSaslAuthenticatorFactory(io.vertx.proton.sasl.ProtonSaslAuthenticatorFactory) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) TenantServiceBasedX509Authentication(org.eclipse.hono.adapter.auth.device.TenantServiceBasedX509Authentication) Predicate(java.util.function.Predicate) Collection(java.util.Collection) CommandContext(org.eclipse.hono.client.command.CommandContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ProtonQoS(io.vertx.proton.ProtonQoS) MessageHelper(org.eclipse.hono.util.MessageHelper) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) List(java.util.List) QoS(org.eclipse.hono.service.metric.MetricsTags.QoS) TenantTraceSamplingHelper(org.eclipse.hono.tracing.TenantTraceSamplingHelper) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Optional(java.util.Optional) Span(io.opentracing.Span) ProtonSender(io.vertx.proton.ProtonSender) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) ProtonLink(io.vertx.proton.ProtonLink) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) ProtonServerOptions(io.vertx.proton.ProtonServerOptions) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) ConnectionLimitManager(org.eclipse.hono.adapter.limiting.ConnectionLimitManager) Command(org.eclipse.hono.client.command.Command) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) AdapterDisabledException(org.eclipse.hono.adapter.AdapterDisabledException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) OptionalInt(java.util.OptionalInt) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Commands(org.eclipse.hono.client.command.Commands) Constants(org.eclipse.hono.util.Constants) CompositeFuture(io.vertx.core.CompositeFuture) ProtonSession(io.vertx.proton.ProtonSession) Symbol(org.apache.qpid.proton.amqp.Symbol) AdapterConnectionsExceededException(org.eclipse.hono.adapter.AdapterConnectionsExceededException) Target(org.apache.qpid.proton.amqp.transport.Target) UnsignedLong(org.apache.qpid.proton.amqp.UnsignedLong) Message(org.apache.qpid.proton.message.Message) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) Strings(org.eclipse.hono.util.Strings) UsernamePasswordAuthProvider(org.eclipse.hono.adapter.auth.device.UsernamePasswordAuthProvider) CredentialsApiAuthProvider(org.eclipse.hono.adapter.auth.device.CredentialsApiAuthProvider) AbstractProtocolAdapterBase(org.eclipse.hono.adapter.AbstractProtocolAdapterBase) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ProtonHelper(io.vertx.proton.ProtonHelper) Sample(io.micrometer.core.instrument.Timer.Sample) Released(org.apache.qpid.proton.amqp.messaging.Released) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) Source(org.apache.qpid.proton.amqp.transport.Source) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) MemoryBasedConnectionLimitStrategy(org.eclipse.hono.adapter.limiting.MemoryBasedConnectionLimitStrategy) X509AuthProvider(org.eclipse.hono.adapter.auth.device.X509AuthProvider) Handler(io.vertx.core.Handler) Collections(java.util.Collections) DefaultConnectionLimitManager(org.eclipse.hono.adapter.limiting.DefaultConnectionLimitManager) SpanContext(io.opentracing.SpanContext) Device(org.eclipse.hono.auth.Device) ClientErrorException(org.eclipse.hono.client.ClientErrorException) OptionalInt(java.util.OptionalInt) Span(io.opentracing.Span) AuthorizationException(org.eclipse.hono.adapter.AuthorizationException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) AdapterDisabledException(org.eclipse.hono.adapter.AdapterDisabledException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) AdapterConnectionsExceededException(org.eclipse.hono.adapter.AdapterConnectionsExceededException) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Aggregations

Device (org.eclipse.hono.auth.Device)115 HttpURLConnection (java.net.HttpURLConnection)74 Test (org.junit.jupiter.api.Test)72 Future (io.vertx.core.Future)69 ClientErrorException (org.eclipse.hono.client.ClientErrorException)67 Buffer (io.vertx.core.buffer.Buffer)66 Handler (io.vertx.core.Handler)63 TenantObject (org.eclipse.hono.util.TenantObject)63 Promise (io.vertx.core.Promise)59 Constants (org.eclipse.hono.util.Constants)58 Span (io.opentracing.Span)55 RegistrationAssertion (org.eclipse.hono.util.RegistrationAssertion)55 SpanContext (io.opentracing.SpanContext)53 VertxTestContext (io.vertx.junit5.VertxTestContext)52 VertxExtension (io.vertx.junit5.VertxExtension)51 MessageHelper (org.eclipse.hono.util.MessageHelper)51 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)51 Mockito.when (org.mockito.Mockito.when)51 Truth.assertThat (com.google.common.truth.Truth.assertThat)50 ResourceIdentifier (org.eclipse.hono.util.ResourceIdentifier)47