Search in sources :

Example 1 with CredentialsDto

use of org.eclipse.hono.service.management.credentials.CredentialsDto in project hono by eclipse.

the class MongoDbBasedCredentialsDao method update.

/**
 * {@inheritDoc}
 */
@Override
public Future<String> update(final CredentialsDto credentials, final Optional<String> resourceVersion, final SpanContext tracingContext) {
    Objects.requireNonNull(credentials);
    Objects.requireNonNull(resourceVersion);
    final Span span = tracer.buildSpan("update Credentials").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, credentials.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, credentials.getDeviceId()).start();
    resourceVersion.ifPresent(v -> TracingHelper.TAG_RESOURCE_VERSION.set(span, v));
    credentials.getCredentials().stream().forEach(cred -> cred.encryptFields(fieldLevelEncryption));
    final JsonObject replaceCredentialsQuery = MongoDbDocumentBuilder.builder().withVersion(resourceVersion).withTenantId(credentials.getTenantId()).withDeviceId(credentials.getDeviceId()).document();
    final var document = JsonObject.mapFrom(credentials);
    if (LOG.isTraceEnabled()) {
        LOG.trace("updating credentials of device [tenant: {}, device-id: {}, resource-version; {}]:{}{}", credentials.getTenantId(), credentials.getDeviceId(), resourceVersion.orElse(null), System.lineSeparator(), document.encodePrettily());
    }
    return mongoClient.findOneAndReplaceWithOptions(collectionName, replaceCredentialsQuery, document, new FindOptions(), new UpdateOptions().setReturningNewDocument(true)).compose(result -> {
        if (result == null) {
            return MongoDbBasedDao.checkForVersionMismatchAndFail(String.format("credentials [tenant-id: %s, device-id: %s]", credentials.getTenantId(), credentials.getDeviceId()), resourceVersion, getByDeviceId(credentials.getTenantId(), credentials.getDeviceId()));
        } else {
            LOG.debug("successfully updated credentials for device [tenant: {}, device-id: {}]", credentials.getTenantId(), credentials.getDeviceId());
            span.log("successfully updated credentials");
            if (LOG.isTraceEnabled()) {
                LOG.trace("new document in DB:{}{}", System.lineSeparator(), result.encodePrettily());
            }
            return Future.succeededFuture(result.getString(CredentialsDto.FIELD_VERSION));
        }
    }).recover(error -> {
        if (MongoDbBasedDao.isDuplicateKeyError(error)) {
            return Future.failedFuture(new ClientErrorException(credentials.getTenantId(), HttpURLConnection.HTTP_CONFLICT, "credentials (type, auth-id) must be unique for device"));
        } else {
            return Future.failedFuture(error);
        }
    }).onFailure(error -> {
        LOG.debug("error updating credentials", error);
        TracingHelper.logError(span, "error updating credentials", error);
    }).recover(this::mapError).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Status(io.vertx.ext.healthchecks.Status) FieldLevelEncryption(org.eclipse.hono.deviceregistry.util.FieldLevelEncryption) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) HealthCheckProvider(org.eclipse.hono.service.HealthCheckProvider) References(io.opentracing.References) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) MongoClient(io.vertx.ext.mongo.MongoClient) UUID(java.util.UUID) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) Span(io.opentracing.Span) FindOptions(io.vertx.ext.mongo.FindOptions) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) MongoDbDocumentBuilder(org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder) FindOptions(io.vertx.ext.mongo.FindOptions) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Span(io.opentracing.Span) UpdateOptions(io.vertx.ext.mongo.UpdateOptions)

Example 2 with CredentialsDto

use of org.eclipse.hono.service.management.credentials.CredentialsDto in project hono by eclipse.

the class MongoDbBasedCredentialsDao method getByAuthIdAndType.

/**
 * {@inheritDoc}
 */
@Override
public Future<CredentialsDto> getByAuthIdAndType(final String tenantId, final String authId, final String type, final SpanContext tracingContext) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(type);
    final Span span = tracer.buildSpan("get Credentials by auth ID and type").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, tenantId).withTag(TracingHelper.TAG_AUTH_ID, authId).withTag(TracingHelper.TAG_CREDENTIALS_TYPE, type).start();
    final JsonObject filter = MongoDbDocumentBuilder.builder().withTenantId(tenantId).withAuthId(authId).withType(type).document();
    if (LOG.isTraceEnabled()) {
        LOG.trace("retrieving credentials using filter:{}{}", System.lineSeparator(), filter.encodePrettily());
    }
    return mongoClient.findOne(collectionName, filter, PROJECTION_CREDS_BY_TYPE_AND_AUTH_ID).map(result -> {
        if (result == null) {
            throw new ClientErrorException(tenantId, HttpURLConnection.HTTP_NOT_FOUND, "no matching credentials on record");
        } else {
            if (LOG.isTraceEnabled()) {
                LOG.trace("credentials data from collection:{}{}", System.lineSeparator(), result.encodePrettily());
            }
            final var dto = result.mapTo(CredentialsDto.class);
            dto.getCredentials().stream().forEach(cred -> cred.decryptFields(fieldLevelEncryption));
            return dto;
        }
    }).onFailure(t -> {
        LOG.debug("error retrieving credentials by auth-id and type", t);
        TracingHelper.logError(span, "error retrieving credentials by auth-id and type", t);
    }).recover(this::mapError).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Status(io.vertx.ext.healthchecks.Status) FieldLevelEncryption(org.eclipse.hono.deviceregistry.util.FieldLevelEncryption) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) HealthCheckProvider(org.eclipse.hono.service.HealthCheckProvider) References(io.opentracing.References) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) MongoClient(io.vertx.ext.mongo.MongoClient) UUID(java.util.UUID) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) Span(io.opentracing.Span) FindOptions(io.vertx.ext.mongo.FindOptions) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) MongoDbDocumentBuilder(org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Span(io.opentracing.Span)

Example 3 with CredentialsDto

use of org.eclipse.hono.service.management.credentials.CredentialsDto in project hono by eclipse.

the class MongoDbBasedCredentialsDao method create.

/**
 * {@inheritDoc}
 */
@Override
public Future<String> create(final CredentialsDto credentials, final SpanContext tracingContext) {
    Objects.requireNonNull(credentials);
    final Span span = tracer.buildSpan("add Credentials").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, credentials.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, credentials.getDeviceId()).start();
    credentials.getCredentials().stream().forEach(cred -> cred.encryptFields(fieldLevelEncryption));
    final var document = JsonObject.mapFrom(credentials);
    if (LOG.isTraceEnabled()) {
        LOG.trace("creating credentials for device [tenant: {}, device-id: {}, resource-version; {}]:{}{}", credentials.getTenantId(), credentials.getDeviceId(), credentials.getVersion(), System.lineSeparator(), document.encodePrettily());
    }
    return mongoClient.insert(collectionName, document).map(added -> {
        span.log("successfully added credentials");
        LOG.debug("successfully added credentials for device [tenant: {}, device-id: {}, resource-version: {}]", credentials.getTenantId(), credentials.getDeviceId(), credentials.getVersion());
        return credentials.getVersion();
    }).onFailure(t -> {
        LOG.debug("error adding credentials for device [tenant: {}, device-id: {}]", credentials.getTenantId(), credentials.getDeviceId(), t);
        TracingHelper.logError(span, "error adding credentials", t);
    }).recover(this::mapError).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Status(io.vertx.ext.healthchecks.Status) FieldLevelEncryption(org.eclipse.hono.deviceregistry.util.FieldLevelEncryption) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) HealthCheckProvider(org.eclipse.hono.service.HealthCheckProvider) References(io.opentracing.References) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) MongoClient(io.vertx.ext.mongo.MongoClient) UUID(java.util.UUID) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) Span(io.opentracing.Span) FindOptions(io.vertx.ext.mongo.FindOptions) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) MongoDbDocumentBuilder(org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder) Span(io.opentracing.Span)

Example 4 with CredentialsDto

use of org.eclipse.hono.service.management.credentials.CredentialsDto in project hono by eclipse.

the class TableManagementStore method setCredentials.

/**
 * Set all credentials for a device.
 * <p>
 * This will set/update all credentials of the device. If the device does not exist, the result
 * will be {@code false}. If the update was successful, then the result will be {@code true}.
 * If the resource version was provided, but the provided version was no longer the current version,
 * then the future will fail with a {@link OptimisticLockingException}.
 *
 * @param key The key of the device to update.
 * @param credentials The credentials to set.
 * @param resourceVersion The optional resource version to update.
 * @param spanContext The span to contribute to.
 * @return A future, tracking the outcome of the operation.
 */
public Future<Versioned<Boolean>> setCredentials(final DeviceKey key, final List<CommonCredential> credentials, final Optional<String> resourceVersion, final SpanContext spanContext) {
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "set credentials", getClass().getSimpleName()).withTag(TracingHelper.TAG_TENANT_ID, key.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, key.getDeviceId()).withTag("num_credentials", credentials.size()).start();
    resourceVersion.ifPresent(version -> span.setTag("version", version));
    final String nextVersion = UUID.randomUUID().toString();
    return SQL.runTransactionally(this.client, this.tracer, span.context(), (connection, context) -> readDeviceForUpdate(connection, key, context).compose(result -> extractVersionForUpdate(result, resourceVersion)).compose(version -> Future.succeededFuture().compose(x -> {
        final Promise<CredentialsDto> result = Promise.promise();
        final var updatedCredentialsDto = CredentialsDto.forUpdate(key.getTenantId(), key.getDeviceId(), credentials, nextVersion);
        if (updatedCredentialsDto.requiresMerging()) {
            getCredentialsDto(key, connection, span).map(updatedCredentialsDto::merge).onComplete(result);
        } else {
            // simply replace the existing credentials with the
            // updated ones provided by the client
            result.complete(updatedCredentialsDto);
        }
        return result.future();
    }).compose(updatedCredentials -> this.deleteAllCredentialsStatement.expand(map -> {
        map.put("tenant_id", key.getTenantId());
        map.put("device_id", key.getDeviceId());
    }).trace(this.tracer, span.context()).update(connection).map(updatedCredentials)).compose(updatedCredentials -> {
        updatedCredentials.createMissingSecretIds();
        return CompositeFuture.all(updatedCredentials.getData().stream().map(JsonObject::mapFrom).filter(c -> c.containsKey("type") && c.containsKey("auth-id")).map(c -> this.insertCredentialEntryStatement.expand(map -> {
            map.put("tenant_id", key.getTenantId());
            map.put("device_id", key.getDeviceId());
            map.put("type", c.getString("type"));
            map.put("auth_id", c.getString("auth-id"));
            map.put("data", c.toString());
        }).trace(this.tracer, span.context()).update(connection)).collect(Collectors.toList())).mapEmpty();
    }).compose(x -> this.updateDeviceVersionStatement.expand(map -> {
        map.put("tenant_id", key.getTenantId());
        map.put("device_id", key.getDeviceId());
        map.put("expected_version", version);
        map.put("next_version", nextVersion);
    }).trace(this.tracer, span.context()).update(connection).compose(TableManagementStore::checkUpdateOutcome)).map(true))).recover(err -> recoverNotFound(span, err, () -> false)).map(ok -> new Versioned<>(nextVersion, ok)).onComplete(x -> span.finish());
}
Also used : SQL(org.eclipse.hono.service.base.jdbc.store.SQL) Json(io.vertx.core.json.Json) JdbcBasedDeviceDto(org.eclipse.hono.service.base.jdbc.store.model.JdbcBasedDeviceDto) LoggerFactory(org.slf4j.LoggerFactory) Supplier(java.util.function.Supplier) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) Map(java.util.Map) Fields(io.opentracing.log.Fields) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) Device(org.eclipse.hono.service.management.device.Device) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Timestamp(java.sql.Timestamp) Promise(io.vertx.core.Promise) Set(java.util.Set) DeviceKey(org.eclipse.hono.deviceregistry.service.device.DeviceKey) OptimisticLockingException(org.eclipse.hono.service.base.jdbc.store.OptimisticLockingException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) List(java.util.List) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) JDBCClient(io.vertx.ext.jdbc.JDBCClient) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) UpdateResult(io.vertx.ext.sql.UpdateResult) EntityNotFoundException(org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException) ResultSet(io.vertx.ext.sql.ResultSet) SQLConnection(io.vertx.ext.sql.SQLConnection) Optional(java.util.Optional) Span(io.opentracing.Span) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Collections(java.util.Collections) StatementConfiguration(org.eclipse.hono.service.base.jdbc.store.StatementConfiguration) Promise(io.vertx.core.Promise) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) JsonObject(io.vertx.core.json.JsonObject) Span(io.opentracing.Span)

Aggregations

Span (io.opentracing.Span)4 SpanContext (io.opentracing.SpanContext)4 Tracer (io.opentracing.Tracer)4 Future (io.vertx.core.Future)4 Promise (io.vertx.core.Promise)4 JsonObject (io.vertx.core.json.JsonObject)4 Objects (java.util.Objects)4 Optional (java.util.Optional)4 UUID (java.util.UUID)4 CredentialsDto (org.eclipse.hono.service.management.credentials.CredentialsDto)4 TracingHelper (org.eclipse.hono.tracing.TracingHelper)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 References (io.opentracing.References)3 HealthCheckHandler (io.vertx.ext.healthchecks.HealthCheckHandler)3 Status (io.vertx.ext.healthchecks.Status)3 FindOptions (io.vertx.ext.mongo.FindOptions)3 IndexOptions (io.vertx.ext.mongo.IndexOptions)3 MongoClient (io.vertx.ext.mongo.MongoClient)3 UpdateOptions (io.vertx.ext.mongo.UpdateOptions)3