Search in sources :

Example 6 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent 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 7 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent 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 8 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent in project graylog2-server by Graylog2.

the class EntitySharesResource method updateEntityShares.

@POST
@ApiOperation(value = "Create / update shares for an entity or collection")
@Path("entities/{entityGRN}")
@NoAuditEvent("Audit events are created within EntitySharesService")
public Response updateEntityShares(@ApiParam(name = "entityGRN", required = true) @PathParam("entityGRN") @NotBlank String entityGRN, @ApiParam(name = "JSON Body", required = true) @NotNull @Valid EntityShareRequest request) {
    final GRN entity = grnRegistry.parse(entityGRN);
    checkOwnership(entity);
    final EntityShareResponse entityShareResponse = entitySharesService.updateEntityShares(entity, request, requireNonNull(getCurrentUser()));
    if (entityShareResponse.validationResult().failed()) {
        return Response.status(Response.Status.BAD_REQUEST).entity(entityShareResponse).build();
    } else {
        return Response.ok(entityShareResponse).build();
    }
}
Also used : EntityShareResponse(org.graylog.security.shares.EntityShareResponse) GRN(org.graylog.grn.GRN) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 9 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent in project graylog2-server by Graylog2.

the class StreamResource method testMatch.

@POST
@Path("/{streamId}/testMatch")
@Timed
@ApiOperation(value = "Test matching of a stream against a supplied message")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Stream not found."), @ApiResponse(code = 400, message = "Invalid or missing Stream id.") })
@NoAuditEvent("only used for testing stream matches")
public TestMatchResponse testMatch(@ApiParam(name = "streamId", required = true) @PathParam("streamId") String streamId, @ApiParam(name = "JSON body", required = true) @NotNull Map<String, Map<String, Object>> serialisedMessage) throws NotFoundException {
    checkPermission(RestPermissions.STREAMS_READ, streamId);
    final Stream stream = streamService.load(streamId);
    // This is such a hack...
    final Map<String, Object> m = new HashMap<>(serialisedMessage.get("message"));
    final String timeStamp = firstNonNull((String) m.get(Message.FIELD_TIMESTAMP), DateTime.now(DateTimeZone.UTC).toString(ISODateTimeFormat.dateTime()));
    m.put(Message.FIELD_TIMESTAMP, Tools.dateTimeFromString(timeStamp));
    final Message message = new Message(m);
    final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("stream-" + streamId + "-test-match-%d").build());
    final StreamRouterEngine streamRouterEngine = streamRouterEngineFactory.create(Lists.newArrayList(stream), executor);
    final List<StreamRouterEngine.StreamTestMatch> streamTestMatches = streamRouterEngine.testMatch(message);
    final StreamRouterEngine.StreamTestMatch streamTestMatch = streamTestMatches.get(0);
    final Map<String, Boolean> rules = Maps.newHashMap();
    for (Map.Entry<StreamRule, Boolean> match : streamTestMatch.getMatches().entrySet()) {
        rules.put(match.getKey().getId(), match.getValue());
    }
    return TestMatchResponse.create(streamTestMatch.isMatched(), rules);
}
Also used : Message(org.graylog2.plugin.Message) HashMap(java.util.HashMap) StreamRule(org.graylog2.plugin.streams.StreamRule) StreamRouterEngine(org.graylog2.streams.StreamRouterEngine) ExecutorService(java.util.concurrent.ExecutorService) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Stream(org.graylog2.plugin.streams.Stream) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Timed(com.codahale.metrics.annotation.Timed) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Example 10 with NoAuditEvent

use of org.graylog2.audit.jersey.NoAuditEvent in project graylog2-server by Graylog2.

the class SessionsResource method newSession.

@POST
@ApiOperation(value = "Create a new session", notes = "This request creates a new session for a user or " + "reactivates an existing session: the equivalent of logging in.")
@NoAuditEvent("dispatches audit events in the method body")
public JsonNode newSession(@Context ContainerRequestContext requestContext, @ApiParam(name = "Login request", value = "Credentials. The default " + "implementation requires presence of two properties: 'username' and " + "'password'. However a plugin may customize which kind of credentials " + "are accepted and therefore expect different properties.", required = true) @NotNull JsonNode createRequest) {
    final SecurityContext securityContext = requestContext.getSecurityContext();
    if (!(securityContext instanceof ShiroSecurityContext)) {
        throw new InternalServerErrorException("Unsupported SecurityContext class, this is a bug!");
    }
    final ShiroSecurityContext shiroSecurityContext = (ShiroSecurityContext) securityContext;
    final ActorAwareAuthenticationToken authToken;
    try {
        authToken = tokenFactory.forRequestBody(createRequest);
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
    // we treat the BASIC auth username as the sessionid
    final String sessionId = shiroSecurityContext.getUsername();
    final String host = RestTools.getRemoteAddrFromRequest(grizzlyRequest, trustedSubnets);
    try {
        Optional<Session> session = sessionCreator.create(sessionId, host, authToken);
        if (session.isPresent()) {
            return sessionResponseFactory.forSession(session.get());
        } else {
            throw new NotAuthorizedException("Invalid credentials.", "Basic realm=\"Graylog Server session\"");
        }
    } catch (AuthenticationServiceUnavailableException e) {
        throw new ServiceUnavailableException("Authentication service unavailable");
    }
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) ActorAwareAuthenticationToken(org.graylog2.shared.security.ActorAwareAuthenticationToken) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) BadRequestException(javax.ws.rs.BadRequestException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) AuthenticationServiceUnavailableException(org.graylog2.shared.security.AuthenticationServiceUnavailableException) AuthenticationServiceUnavailableException(org.graylog2.shared.security.AuthenticationServiceUnavailableException) ShiroSecurityContext(org.graylog2.shared.security.ShiroSecurityContext) Session(org.apache.shiro.session.Session) POST(javax.ws.rs.POST) ApiOperation(io.swagger.annotations.ApiOperation) NoAuditEvent(org.graylog2.audit.jersey.NoAuditEvent)

Aggregations

ApiOperation (io.swagger.annotations.ApiOperation)33 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)33 POST (javax.ws.rs.POST)30 Path (javax.ws.rs.Path)27 Timed (com.codahale.metrics.annotation.Timed)14 ApiResponses (io.swagger.annotations.ApiResponses)10 Produces (javax.ws.rs.Produces)10 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)10 BadRequestException (javax.ws.rs.BadRequestException)9 Consumes (javax.ws.rs.Consumes)6 Stream (org.graylog2.plugin.streams.Stream)6 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)5 PUT (javax.ws.rs.PUT)5 Search (org.graylog.plugins.views.search.Search)5 RequiresAuthentication (org.apache.shiro.authz.annotation.RequiresAuthentication)4 ValidationResult (org.graylog2.plugin.rest.ValidationResult)4 Api (io.swagger.annotations.Api)3 ApiParam (io.swagger.annotations.ApiParam)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3