Search in sources :

Example 6 with ValidationResult

use of org.graylog2.plugin.database.validators.ValidationResult in project graylog2-server by Graylog2.

the class EventDefinitionsResource method update.

@PUT
@Path("{definitionId}")
@ApiOperation("Update existing event definition")
@AuditEvent(type = EventsAuditEventTypes.EVENT_DEFINITION_UPDATE)
public Response update(@ApiParam(name = "definitionId") @PathParam("definitionId") @NotBlank String definitionId, @ApiParam("schedule") @QueryParam("schedule") @DefaultValue("true") boolean schedule, @ApiParam(name = "JSON Body") EventDefinitionDto dto) {
    checkPermission(RestPermissions.EVENT_DEFINITIONS_EDIT, definitionId);
    checkEventDefinitionPermissions(dto, "update");
    dbService.get(definitionId).orElseThrow(() -> new NotFoundException("Event definition <" + definitionId + "> doesn't exist"));
    final ValidationResult result = dto.validate();
    if (!definitionId.equals(dto.id())) {
        result.addError("id", "Event definition IDs don't match");
    }
    if (result.failed()) {
        return Response.status(Response.Status.BAD_REQUEST).entity(result).build();
    }
    return Response.ok().entity(eventDefinitionHandler.update(dto, schedule)).build();
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) ValidationResult(org.graylog2.plugin.rest.ValidationResult) Path(javax.ws.rs.Path) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent) AuditEvent(org.graylog2.audit.jersey.AuditEvent) PUT(javax.ws.rs.PUT)

Example 7 with ValidationResult

use of org.graylog2.plugin.database.validators.ValidationResult in project graylog2-server by Graylog2.

the class PersistedServiceImpl method validate.

@Override
public Map<String, List<ValidationResult>> validate(Map<String, Validator> validators, Map<String, Object> fields) {
    if (validators == null || validators.isEmpty()) {
        return Collections.emptyMap();
    }
    final Map<String, List<ValidationResult>> validationErrors = new HashMap<>();
    for (Map.Entry<String, Validator> validation : validators.entrySet()) {
        Validator v = validation.getValue();
        String field = validation.getKey();
        try {
            ValidationResult validationResult = v.validate(fields.get(field));
            if (validationResult instanceof ValidationResult.ValidationFailed) {
                LOG.debug("Validation failure: [{}] on field [{}]", v.getClass().getCanonicalName(), field);
                validationErrors.computeIfAbsent(field, k -> new ArrayList<>());
                validationErrors.get(field).add(validationResult);
            }
        } catch (Exception e) {
            final String error = "Error while trying to validate <" + field + ">, got exception: " + e;
            LOG.debug(error);
            validationErrors.computeIfAbsent(field, k -> new ArrayList<>());
            validationErrors.get(field).add(new ValidationResult.ValidationFailed(error));
        }
    }
    return validationErrors;
}
Also used : Logger(org.slf4j.Logger) Validator(org.graylog2.plugin.database.validators.Validator) Persisted(org.graylog2.plugin.database.Persisted) BasicDBObject(com.mongodb.BasicDBObject) DBCollection(com.mongodb.DBCollection) DateTime(org.joda.time.DateTime) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) PersistedService(org.graylog2.plugin.database.PersistedService) Maps(com.google.common.collect.Maps) ArrayList(java.util.ArrayList) List(java.util.List) Lists(com.google.common.collect.Lists) DBObject(com.mongodb.DBObject) NodeId(org.graylog2.plugin.system.NodeId) DBCursor(com.mongodb.DBCursor) ValidationException(org.graylog2.plugin.database.ValidationException) Map(java.util.Map) EmbeddedPersistable(org.graylog2.plugin.database.EmbeddedPersistable) ValidationResult(org.graylog2.plugin.database.validators.ValidationResult) ObjectId(org.bson.types.ObjectId) Collections(java.util.Collections) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ValidationResult(org.graylog2.plugin.database.validators.ValidationResult) ValidationException(org.graylog2.plugin.database.ValidationException) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) Validator(org.graylog2.plugin.database.validators.Validator)

Example 8 with ValidationResult

use of org.graylog2.plugin.database.validators.ValidationResult in project graylog2-server by Graylog2.

the class LookupTableResource method validateTable.

@POST
@Path("tables/validate")
@NoAuditEvent("Validation only")
@ApiOperation(value = "Validate the lookup table config")
@RequiresPermissions(RestPermissions.LOOKUP_TABLES_READ)
public ValidationResult validateTable(@Valid @ApiParam LookupTableApi toValidate) {
    final ValidationResult validation = new ValidationResult();
    final Optional<LookupTableDto> dtoOptional = dbTableService.get(toValidate.name());
    if (dtoOptional.isPresent()) {
        // a table exist with the given name, check that the IDs are the same, this might be an update
        final LookupTableDto tableDto = dtoOptional.get();
        // noinspection ConstantConditions
        if (!tableDto.id().equals(toValidate.id())) {
            // a table exists with a different id, so the name is already in use, fail validation
            validation.addError("name", "The lookup table name is already in use.");
        }
    }
    try {
        LookupDefaultSingleValue.create(toValidate.defaultSingleValue(), toValidate.defaultSingleValueType());
    } catch (Exception e) {
        validation.addError(LookupTableApi.FIELD_DEFAULT_SINGLE_VALUE, e.getMessage());
    }
    try {
        LookupDefaultMultiValue.create(toValidate.defaultMultiValue(), toValidate.defaultMultiValueType());
    } catch (Exception e) {
        validation.addError(LookupTableApi.FIELD_DEFAULT_MULTI_VALUE, e.getMessage());
    }
    return validation;
}
Also used : LookupTableDto(org.graylog2.lookup.dto.LookupTableDto) ValidationResult(org.graylog2.plugin.rest.ValidationResult) BadRequestException(javax.ws.rs.BadRequestException) NotFoundException(javax.ws.rs.NotFoundException) DuplicateKeyException(com.mongodb.DuplicateKeyException) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 9 with ValidationResult

use of org.graylog2.plugin.database.validators.ValidationResult in project graylog2-server by Graylog2.

the class LookupTableResource method validateCache.

@POST
@Path("caches/validate")
@NoAuditEvent("Validation only")
@ApiOperation(value = "Validate the cache config")
@RequiresPermissions(RestPermissions.LOOKUP_TABLES_READ)
public ValidationResult validateCache(@Valid @ApiParam CacheApi toValidate) {
    final ValidationResult validation = new ValidationResult();
    final Optional<CacheDto> dtoOptional = dbCacheService.get(toValidate.name());
    if (dtoOptional.isPresent()) {
        // a cache exist with the given name, check that the IDs are the same, this might be an update
        final CacheDto cacheDto = dtoOptional.get();
        // noinspection ConstantConditions
        if (!cacheDto.id().equals(toValidate.id())) {
            // a ache exists with a different id, so the name is already in use, fail validation
            validation.addError("name", "The cache name is already in use.");
        }
    }
    final Optional<Multimap<String, String>> configValidations = toValidate.config().validate();
    configValidations.ifPresent(validation::addAll);
    return validation;
}
Also used : Multimap(com.google.common.collect.Multimap) ValidationResult(org.graylog2.plugin.rest.ValidationResult) CacheDto(org.graylog2.lookup.dto.CacheDto) Path(javax.ws.rs.Path) RequiresPermissions(org.apache.shiro.authz.annotation.RequiresPermissions) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 10 with ValidationResult

use of org.graylog2.plugin.database.validators.ValidationResult in project graylog2-server by Graylog2.

the class EntitySharesServiceTest method ignoreInvisibleOwners.

@DisplayName("The validation should ignore invisble owners")
@Test
void ignoreInvisibleOwners() {
    final GRN entity = grnRegistry.newGRN(GRNTypes.STREAM, "54e3deadbeefdeadbeefaffe");
    final EntityShareRequest shareRequest = EntityShareRequest.create(ImmutableMap.of());
    final Set<GRN> allGrantees = dbGrantService.getAll().stream().map(GrantDTO::grantee).collect(Collectors.toSet());
    lenient().when(granteeService.getAvailableGrantees(any())).thenReturn(allGrantees.stream().filter(g -> g.toString().equals("grn::::user:invisible")).map(g -> Grantee.createUser(g, g.entity())).collect(Collectors.toSet()));
    final User user = createMockUser("hans");
    final Subject subject = mock(Subject.class);
    final EntityShareResponse entityShareResponse = entitySharesService.prepareShare(entity, shareRequest, user, subject);
    assertThat(entityShareResponse.validationResult()).satisfies(validationResult -> {
        assertThat(validationResult.failed()).isFalse();
    });
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) EntityDependencyPermissionChecker(org.graylog.security.entities.EntityDependencyPermissionChecker) BeforeEach(org.junit.jupiter.api.BeforeEach) Mock(org.mockito.Mock) BuiltinCapabilities(org.graylog.security.BuiltinCapabilities) Capability(org.graylog.security.Capability) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Mockito.lenient(org.mockito.Mockito.lenient) GRNRegistry(org.graylog.grn.GRNRegistry) EventBus(com.google.common.eventbus.EventBus) MongoDBTestService(org.graylog.testing.mongodb.MongoDBTestService) DBGrantService(org.graylog.security.DBGrantService) GrantDTO(org.graylog.security.GrantDTO) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Subject(org.apache.shiro.subject.Subject) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ImmutableSet(com.google.common.collect.ImmutableSet) EntityDependencyResolver(org.graylog.security.entities.EntityDependencyResolver) ImmutableMap(com.google.common.collect.ImmutableMap) GRNTypes(org.graylog.grn.GRNTypes) MongoJackObjectMapperProvider(org.graylog2.bindings.providers.MongoJackObjectMapperProvider) Set(java.util.Set) Mockito.when(org.mockito.Mockito.when) Collectors(java.util.stream.Collectors) MongoJackExtension(org.graylog.testing.mongodb.MongoJackExtension) GRN(org.graylog.grn.GRN) DisplayName(org.junit.jupiter.api.DisplayName) Test(org.junit.jupiter.api.Test) MongoDBExtension(org.graylog.testing.mongodb.MongoDBExtension) GRNExtension(org.graylog.testing.GRNExtension) MongoDBFixtures(org.graylog.testing.mongodb.MongoDBFixtures) User(org.graylog2.plugin.database.users.User) Mockito.mock(org.mockito.Mockito.mock) GRN(org.graylog.grn.GRN) User(org.graylog2.plugin.database.users.User) Subject(org.apache.shiro.subject.Subject) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Aggregations

ValidationResult (org.graylog2.plugin.rest.ValidationResult)43 Test (org.junit.Test)24 ApiOperation (io.swagger.annotations.ApiOperation)16 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)16 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)14 Path (javax.ws.rs.Path)12 AuditEvent (org.graylog2.audit.jersey.AuditEvent)12 POST (javax.ws.rs.POST)11 List (java.util.List)10 Subject (org.apache.shiro.subject.Subject)8 GRN (org.graylog.grn.GRN)8 User (org.graylog2.plugin.database.users.User)8 ArrayList (java.util.ArrayList)7 Produces (javax.ws.rs.Produces)7 ValidationException (org.graylog2.plugin.database.ValidationException)6 DisplayName (org.junit.jupiter.api.DisplayName)6 Test (org.junit.jupiter.api.Test)6 BasicDBObject (com.mongodb.BasicDBObject)5 Collectors (java.util.stream.Collectors)5 NotFoundException (javax.ws.rs.NotFoundException)5