use of org.eclipse.hono.auth.Device in project hono by eclipse.
the class LoraProtocolAdapter method registerCommandConsumerIfNeeded.
private void registerCommandConsumerIfNeeded(final LoraProvider provider, final Device gatewayDevice, final SpanContext context) {
final String tenantId = gatewayDevice.getTenantId();
final String gatewayId = gatewayDevice.getDeviceId();
final SubscriptionKey key = new SubscriptionKey(tenantId, gatewayId);
if (commandSubscriptions.containsKey(key)) {
return;
}
// use FOLLOWS_FROM span since this operation is decoupled from the rest of the request handling
final Span currentSpan = TracingHelper.buildFollowsFromSpan(tracer, context, "create command consumer").withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).start();
TracingHelper.setDeviceTags(currentSpan, tenantId, gatewayId);
TAG_LORA_PROVIDER.set(currentSpan, provider.getProviderName());
getRegistrationClient().assertRegistration(tenantId, gatewayId, null, currentSpan.context()).onFailure(thr -> {
LOG.debug("error asserting gateway registration, no command consumer will be created [tenant: {}, gateway-id: {}]", tenantId, gatewayId);
TracingHelper.logError(currentSpan, "error asserting gateway registration, no command consumer will be created", thr);
}).compose(assertion -> {
if (assertion.getCommandEndpoint() == null) {
LOG.debug("gateway has no command endpoint defined, skipping command consumer creation [tenant: {}, gateway-id: {}]", tenantId, gatewayId);
currentSpan.log("gateway has no command endpoint defined, skipping command consumer creation");
return Future.succeededFuture((Void) null);
}
return getCommandConsumerFactory().createCommandConsumer(tenantId, gatewayId, this::handleCommand, null, currentSpan.context()).onFailure(thr -> TracingHelper.logError(currentSpan, thr)).map(commandConsumer -> commandSubscriptions.put(key, Pair.of(commandConsumer, provider))).mapEmpty();
}).onComplete(ar -> currentSpan.finish());
}
use of org.eclipse.hono.auth.Device 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);
});
}
use of org.eclipse.hono.auth.Device 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);
});
}
use of org.eclipse.hono.auth.Device 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);
}
});
}
use of org.eclipse.hono.auth.Device in project hono by eclipse.
the class UsernamePasswordAuthProvider method doValidateCredentials.
@Override
protected Future<Device> doValidateCredentials(final UsernamePasswordCredentials deviceCredentials, final CredentialsObject credentialsOnRecord) {
final Context currentContext = Vertx.currentContext();
if (currentContext == null) {
return Future.failedFuture(new IllegalStateException("not running on vert.x Context"));
} else {
final Promise<Device> result = Promise.promise();
currentContext.executeBlocking(blockingCodeHandler -> {
log.debug("validating password hash on vert.x worker thread [{}]", Thread.currentThread().getName());
final boolean isValid = credentialsOnRecord.getCandidateSecrets().stream().anyMatch(candidateSecret -> pwdEncoder.matches(deviceCredentials.getPassword(), candidateSecret));
if (isValid) {
blockingCodeHandler.complete(new Device(deviceCredentials.getTenantId(), credentialsOnRecord.getDeviceId()));
} else {
blockingCodeHandler.fail(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "bad credentials"));
}
}, false, result);
return result.future();
}
}
Aggregations