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);
}));
}
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);
}
}
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();
}
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);
});
}
}
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());
}));
}
Aggregations