Search in sources :

Example 41 with SpanContext

use of io.opentracing.SpanContext in project hono by eclipse.

the class CredentialsApiAuthProvider method authenticate.

@Override
public final void authenticate(final T deviceCredentials, final SpanContext spanContext, final Handler<AsyncResult<DeviceUser>> resultHandler) {
    Objects.requireNonNull(deviceCredentials);
    Objects.requireNonNull(resultHandler);
    final Span currentSpan = TracingHelper.buildServerChildSpan(tracer, spanContext, "authenticate device", getClass().getSimpleName()).withTag(MessageHelper.APP_PROPERTY_TENANT_ID, deviceCredentials.getTenantId()).withTag(TracingHelper.TAG_AUTH_ID.getKey(), deviceCredentials.getAuthId()).start();
    getCredentialsForDevice(deviceCredentials, currentSpan.context()).recover(t -> Future.failedFuture(mapNotFoundToBadCredentialsException(t))).compose(credentialsOnRecord -> validateCredentials(deviceCredentials, credentialsOnRecord, currentSpan.context())).map(device -> new DeviceUser(device.getTenantId(), device.getDeviceId())).onComplete(authAttempt -> {
        if (authAttempt.succeeded()) {
            currentSpan.log("successfully authenticated device");
        } else {
            currentSpan.log("authentication of device failed");
            TracingHelper.logError(currentSpan, authAttempt.cause());
        }
        currentSpan.finish();
        resultHandler.handle(authAttempt);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) LoggerFactory(org.slf4j.LoggerFactory) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) User(io.vertx.ext.auth.User) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) Span(io.opentracing.Span) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) CredentialsObject(org.eclipse.hono.util.CredentialsObject) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) Span(io.opentracing.Span)

Example 42 with SpanContext

use of io.opentracing.SpanContext in project hono by eclipse.

the class CredentialsApiAuthProvider method validateCredentials.

/**
 * Verifies that the credentials provided by a device during the authentication
 * process match the credentials on record for that device.
 *
 * @param deviceCredentials The credentials provided by the device.
 * @param credentialsOnRecord The credentials to match against.
 * @param spanContext The OpenTracing context to use for tracking the operation.
 * @return A future that is succeeded with the authenticated device if the
 *         credentials have been validated successfully. Otherwise, the
 *         future is failed with a {@link ServiceInvocationException}.
 */
private Future<Device> validateCredentials(final T deviceCredentials, final CredentialsObject credentialsOnRecord, final SpanContext spanContext) {
    final Span currentSpan = TracingHelper.buildServerChildSpan(tracer, spanContext, "validate credentials", getClass().getSimpleName()).withTag(MessageHelper.APP_PROPERTY_TENANT_ID, deviceCredentials.getTenantId()).withTag(TracingHelper.TAG_AUTH_ID.getKey(), deviceCredentials.getAuthId()).withTag(TracingHelper.TAG_CREDENTIALS_TYPE.getKey(), deviceCredentials.getType()).start();
    final Promise<Device> result = Promise.promise();
    if (!deviceCredentials.getAuthId().equals(credentialsOnRecord.getAuthId())) {
        currentSpan.log(String.format("Credentials service returned wrong credentials-on-record [auth-id: %s]", credentialsOnRecord.getAuthId()));
        result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR));
    } else if (!deviceCredentials.getType().equals(credentialsOnRecord.getType())) {
        currentSpan.log(String.format("Credentials service returned wrong credentials-on-record [type: %s]", credentialsOnRecord.getType()));
        result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR));
    } else if (!credentialsOnRecord.isEnabled()) {
        currentSpan.log("credentials-on-record are disabled");
        result.fail(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED));
    } else {
        doValidateCredentials(deviceCredentials, credentialsOnRecord).onComplete(result);
    }
    return result.future().map(device -> {
        currentSpan.log("validation of credentials succeeded");
        currentSpan.finish();
        return device;
    }).recover(t -> {
        currentSpan.log("validation of credentials failed");
        TracingHelper.logError(currentSpan, t);
        currentSpan.finish();
        return Future.failedFuture(t);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) LoggerFactory(org.slf4j.LoggerFactory) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) User(io.vertx.ext.auth.User) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) Span(io.opentracing.Span) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) CredentialsObject(org.eclipse.hono.util.CredentialsObject) Device(org.eclipse.hono.auth.Device) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Span(io.opentracing.Span)

Example 43 with SpanContext

use of io.opentracing.SpanContext in project hono by eclipse.

the class AbstractProtocolAdapterBase method getRegistrationAssertion.

@Override
public final Future<RegistrationAssertion> getRegistrationAssertion(final String tenantId, final String deviceId, final Device authenticatedDevice, final SpanContext context) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    final Future<String> gatewayId = getGatewayId(tenantId, deviceId, authenticatedDevice);
    return gatewayId.compose(gwId -> getRegistrationClient().assertRegistration(tenantId, deviceId, gwId, context)).onSuccess(assertion -> {
        // the updateLastGateway invocation shouldn't delay or possibly fail the surrounding operation
        // so don't wait for the outcome here
        updateLastGateway(assertion, tenantId, deviceId, authenticatedDevice, context).onFailure(t -> {
            log.warn("failed to update last gateway [tenantId: {}, deviceId: {}]", tenantId, deviceId, t);
        });
    }).recover(error -> {
        final int errorCode = ServiceInvocationException.extractStatusCode(error);
        if (errorCode == HttpURLConnection.HTTP_NOT_FOUND) {
            return Future.failedFuture(new DeviceDisabledOrNotRegisteredException(tenantId, errorCode));
        } else if (errorCode == HttpURLConnection.HTTP_FORBIDDEN) {
            return Future.failedFuture(new GatewayDisabledOrNotRegisteredException(tenantId, errorCode));
        } else {
            return Future.failedFuture(error);
        }
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) DecodeException(io.vertx.core.json.DecodeException) Context(io.vertx.core.Context) NoopResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.NoopResourceLimitChecks) TelemetrySender(org.eclipse.hono.client.telemetry.TelemetrySender) MessagingType(org.eclipse.hono.util.MessagingType) Map(java.util.Map) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) EventSender(org.eclipse.hono.client.telemetry.EventSender) CommandContext(org.eclipse.hono.client.command.CommandContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) TenantClient(org.eclipse.hono.client.registry.TenantClient) MessageHelper(org.eclipse.hono.util.MessageHelper) ServiceBaseUtils(org.eclipse.hono.service.util.ServiceBaseUtils) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) TrustOptions(io.vertx.core.net.TrustOptions) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) CommandRouterClient(org.eclipse.hono.client.command.CommandRouterClient) Optional(java.util.Optional) QoS(org.eclipse.hono.util.QoS) ConnectionLimitManager(org.eclipse.hono.adapter.limiting.ConnectionLimitManager) Lifecycle(org.eclipse.hono.util.Lifecycle) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TenantDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException) ConnectionEventProducer(org.eclipse.hono.adapter.monitoring.ConnectionEventProducer) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) ArrayList(java.util.ArrayList) DeviceDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException) CompositeFuture(io.vertx.core.CompositeFuture) Status(io.vertx.ext.healthchecks.Status) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) DeviceRegistrationClient(org.eclipse.hono.client.registry.DeviceRegistrationClient) GatewayDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.GatewayDisabledOrNotRegisteredException) TelemetryExecutionContext(org.eclipse.hono.util.TelemetryExecutionContext) Strings(org.eclipse.hono.util.Strings) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Sample(io.micrometer.core.instrument.Timer.Sample) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) CommandConsumerFactory(org.eclipse.hono.client.command.CommandConsumerFactory) ValidityBasedTrustOptions(org.eclipse.hono.service.auth.ValidityBasedTrustOptions) ServiceClient(org.eclipse.hono.client.util.ServiceClient) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) AbstractServiceBase(org.eclipse.hono.service.AbstractServiceBase) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) DeviceDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException) GatewayDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.GatewayDisabledOrNotRegisteredException)

Example 44 with SpanContext

use of io.opentracing.SpanContext in project hono by eclipse.

the class AbstractMessageSenderConnectionEventProducer method sendNotificationEvent.

private Future<Void> sendNotificationEvent(final Context context, final Device authenticatedDevice, final String protocolAdapter, final String remoteId, final String cause, final JsonObject data, final SpanContext spanContext) {
    if (authenticatedDevice == null) {
        // we only handle authenticated devices
        return Future.succeededFuture();
    }
    final String tenantId = authenticatedDevice.getTenantId();
    final String deviceId = authenticatedDevice.getDeviceId();
    return context.getTenantClient().get(tenantId, spanContext).compose(tenant -> {
        final JsonObject payload = new JsonObject();
        payload.put("cause", cause);
        payload.put("remote-id", remoteId);
        payload.put("source", protocolAdapter);
        if (data != null) {
            payload.put("data", data);
        }
        return Optional.ofNullable(context.getMessageSenderClient()).map(client -> client.sendEvent(tenant, new RegistrationAssertion(deviceId), EventConstants.EVENT_CONNECTION_NOTIFICATION_CONTENT_TYPE, payload.toBuffer(), null, spanContext)).orElseGet(Future::succeededFuture);
    });
}
Also used : Optional(java.util.Optional) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) JsonObject(io.vertx.core.json.JsonObject) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) SpanContext(io.opentracing.SpanContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) JsonObject(io.vertx.core.json.JsonObject) Future(io.vertx.core.Future)

Example 45 with SpanContext

use of io.opentracing.SpanContext in project hono by eclipse.

the class KafkaHeadersInjectExtractAdapterTest method testJaegerTracerCanUseAdapter.

/**
 * Verifies that the Jaeger tracer implementation can successfully use the adapters to inject and extract
 * a SpanContext.
 */
@Test
public void testJaegerTracerCanUseAdapter() {
    final Configuration config = new Configuration("test");
    final Tracer tracer = config.getTracer();
    final Span span = tracer.buildSpan("do").start();
    final List<KafkaHeader> headers = new ArrayList<>();
    final KafkaHeadersInjectAdapter injectAdapter = new KafkaHeadersInjectAdapter(headers);
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, injectAdapter);
    final SpanContext context = tracer.extract(Format.Builtin.TEXT_MAP, new KafkaHeadersExtractAdapter(headers));
    assertThat(context.toSpanId()).isEqualTo(span.context().toSpanId());
}
Also used : SpanContext(io.opentracing.SpanContext) Configuration(io.jaegertracing.Configuration) Tracer(io.opentracing.Tracer) ArrayList(java.util.ArrayList) Span(io.opentracing.Span) KafkaHeader(io.vertx.kafka.client.producer.KafkaHeader) Test(org.junit.jupiter.api.Test)

Aggregations

SpanContext (io.opentracing.SpanContext)118 Span (io.opentracing.Span)81 Future (io.vertx.core.Future)70 Tracer (io.opentracing.Tracer)60 Objects (java.util.Objects)57 HttpURLConnection (java.net.HttpURLConnection)56 JsonObject (io.vertx.core.json.JsonObject)55 TracingHelper (org.eclipse.hono.tracing.TracingHelper)55 Logger (org.slf4j.Logger)54 LoggerFactory (org.slf4j.LoggerFactory)54 List (java.util.List)51 Promise (io.vertx.core.Promise)45 Optional (java.util.Optional)45 Map (java.util.Map)40 ClientErrorException (org.eclipse.hono.client.ClientErrorException)39 MessageHelper (org.eclipse.hono.util.MessageHelper)33 UUID (java.util.UUID)31 Collectors (java.util.stream.Collectors)31 HashMap (java.util.HashMap)25 Vertx (io.vertx.core.Vertx)24