com.networknt.status.Status Java Examples

The following examples show how to use com.networknt.status.Status. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validatePathParameters(final NormalisedPath requestPath,
                                      final SwaggerOperation swaggerOperation) {
    Status status = null;
    for (int i = 0; i < swaggerOperation.getPathString().parts().size(); i++) {
        if (!swaggerOperation.getPathString().isParam(i)) {
            continue;
        }

        final String paramName = swaggerOperation.getPathString().paramName(i);
        final String paramValue = requestPath.part(i);

        final Optional<Parameter> parameter = swaggerOperation.getOperation().getParameters()
                .stream()
                .filter(p -> p.getIn().equalsIgnoreCase("PATH"))
                .filter(p -> p.getName().equalsIgnoreCase(paramName))
                .findFirst();

        if (parameter.isPresent()) {
            status = parameterValidators.validate(paramValue, parameter.get());
        }
    }
    return status;
}
 
Example #2
Source File: LightHttpHandler.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * There are situations that the downstream service returns an error status response and we just
 * want to bubble up to the caller and eventually to the original caller.
 *
 * @param exchange HttpServerExchange
 * @param status error status
 */
default void setExchangeStatus(HttpServerExchange exchange, Status status) {
    exchange.setStatusCode(status.getStatusCode());
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
    status.setDescription(status.getDescription().replaceAll("\\\\", "\\\\\\\\"));
    exchange.getResponseSender().send(status.toString());
    StackTraceElement[] elements = Thread.currentThread().getStackTrace();
    logger.error(status.toString() + " at " + elements[2].getClassName() + "." + elements[2].getMethodName() + "(" + elements[2].getFileName() + ":" + elements[2].getLineNumber() + ")");
    // In normal case, the auditInfo shouldn't be null as it is created by OpenApiHandler with
    // endpoint and openapiOperation available. This handler will enrich the auditInfo.
    @SuppressWarnings("unchecked")
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    if(auditInfo == null) {
        auditInfo = new HashMap<>();
        exchange.putAttachment(AttachmentConstants.AUDIT_INFO, auditInfo);
    }

    // save info for auditing purposes in case of an error
    if(auditOnError)
        auditInfo.put(Constants.STATUS, status);
    if(auditStackTrace) {
        auditInfo.put(Constants.STACK_TRACE, Arrays.toString(elements));
    }
}
 
Example #3
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private ValidationResult validateDeserializedValues(final HttpServerExchange exchange, final Collection<Parameter> parameters, final ParameterType type) {
	ValidationResult validationResult = new ValidationResult();
	
	parameters.stream()
      .filter(p -> ParameterType.is(p.getIn(), type))
      .forEach(p->{
      	Object deserializedValue = getDeserializedValue(exchange, p.getName(), type);
      	if (null==deserializedValue) {
      		validationResult.addSkipped(p);
      	}else {
      		Status s = schemaValidator.validate(deserializedValue, Overlay.toJson((SchemaImpl)(p.getSchema())), p.getName());
      		validationResult.addStatus(s);
      	}
      });
	
	return validationResult;
}
 
Example #4
Source File: ValidatorHandler.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    SwaggerOperation swaggerOperation = null;
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    if(auditInfo != null) {
        swaggerOperation = (SwaggerOperation)auditInfo.get(Constants.SWAGGER_OPERATION_STRING);
    }
    if(swaggerOperation == null) {
        setExchangeStatus(exchange, STATUS_MISSING_SWAGGER_OPERATION);
        return;
    }

    Status status = requestValidator.validateRequest(requestPath, exchange, swaggerOperation);
    if(status != null) {
        exchange.setStatusCode(status.getStatusCode());
        status.setDescription(status.getDescription().replaceAll("\\\\", "\\\\\\\\"));
        exchange.getResponseSender().send(status.toString());
        if(config.isLogError()) logger.error("ValidationError:" + status.toString());
        return;
    }
    Handler.next(exchange, next);
}
 
Example #5
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateQueryParameters(final HttpServerExchange exchange,
                                       final OpenApiOperation openApiOperation) {
	ValidationResult result = validateDeserializedValues(exchange, openApiOperation.getOperation().getParameters(), ParameterType.QUERY);
	
	if (null!=result.getStatus() || result.getSkippedParameters().isEmpty()) {
		return result.getStatus();
	}
	
	// validate values that cannot be deserialized or do not need to be deserialized
    Optional<Status> optional = result.getSkippedParameters()
    		.stream()
            .map(p -> validateQueryParameter(exchange, openApiOperation, p))
            .filter(s -> s != null)
            .findFirst();
    
    return optional.orElse(null);
}
 
Example #6
Source File: BaseParameterValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public Status validate(final String value, final Parameter p) {

    if (!supports(p)) {
        return null;
    }

    final SerializableParameter parameter = (SerializableParameter)p;

    if (parameter.getRequired() && (value == null || value.trim().isEmpty())) {
        return new Status("ERR11001", p.getName());
    }

    if (value == null || value.trim().isEmpty()) {
        return null;
    }

    if (!matchesEnumIfDefined(value, parameter)) {
        return new Status("ERR11002", value, parameter.getName(), parameter.getEnum());
    }
    return doValidate(value, parameter);
}
 
Example #7
Source File: ParameterValidators.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
public Status validate(final String value, final Parameter parameter) {
    requireNonNull(parameter);

    if ((parameter instanceof SerializableParameter) &&
            ((SerializableParameter)parameter).getType().equalsIgnoreCase("array")) {
        return arrayValidator.validate(value, parameter);
    }


    Optional<Status> optional = validators.stream()
            .filter(v -> v.supports(parameter))
            .map(v -> v.validate(value, parameter))
            .filter(s -> s != null)
            .findFirst();
    if(optional.isPresent()) {
        return optional.get();
    } else {
        return null;
    }
}
 
Example #8
Source File: ResponseValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
/**
 * validate a given response content object
 * @param responseContent response content needs to be validated
 * @param openApiOperation OpenApi Operation which is located by uri and httpMethod
 * @param statusCode eg. 200, 400
 * @param mediaTypeName eg. "application/json"
 * @return Status return null if no validation errors
 */
public Status validateResponseContent(Object responseContent, OpenApiOperation openApiOperation, String statusCode, String mediaTypeName) {
    //try to convert json string to structured object
    if(responseContent instanceof String) {
        responseContent = convertStrToObjTree((String)responseContent);
    }
    JsonNode schema = getContentSchema(openApiOperation, statusCode, mediaTypeName);
    //if cannot find schema based on status code, try to get from "default"
    if(schema == null || schema.isMissingNode()) {
        // if corresponding response exist but also does not contain any schema, pass validation
        if (openApiOperation.getOperation().getResponses().containsKey(String.valueOf(statusCode))) {
            return null;
        }
        schema = getContentSchema(openApiOperation, DEFAULT_STATUS_CODE, mediaTypeName);
        // if default also does not contain any schema, pass validation
        if (schema == null || schema.isMissingNode()) return null;
    }
    if ((responseContent != null && schema == null) ||
            (responseContent == null && schema != null)) {
        return new Status(VALIDATOR_RESPONSE_CONTENT_UNEXPECTED, openApiOperation.getMethod(), openApiOperation.getPathString().original());
    }
    config.setTypeLoose(false);
    config.setHandleNullableField(ValidatorHandler.config.isHandleNullableField());
    return schemaValidator.validate(responseContent, schema, config);
}
 
Example #9
Source File: ArrayParameterValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
public Status validate(final Collection<String> values, final Parameter p) {
    if (p == null) {
        return null;
    }

    final SerializableParameter parameter = (SerializableParameter)p;
    if (parameter.getRequired() && (values == null || values.isEmpty())) {
        return new Status("ERR11001", parameter.getName());
    }

    if (values == null) {
        return null;
    }

    if (!parameter.getCollectionFormat().equalsIgnoreCase(CollectionFormat.MULTI.name())) {
        return new Status("ERR11005", p.getName(), parameter.getCollectionFormat(), "multi");
    }

    return doValidate(values, parameter);
}
 
Example #10
Source File: ArrayParameterValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
@Override
public Status validate(final String value, final Parameter p) {

    if (!supports(p)) {
        return null;
    }

    final SerializableParameter parameter = (SerializableParameter)p;

    if (parameter.getRequired() && (value == null || value.trim().isEmpty())) {
        return new Status("ERR11001", parameter.getName());
    }

    if (value == null || value.trim().isEmpty()) {
        return null;
    }

    return doValidate(value, parameter);
}
 
Example #11
Source File: CommandServiceManager.java    From light-4j with Apache License 2.0 6 votes vote down vote up
private void buildWeightsMap(Map<String, Integer> weights, RpcCommand.ClientCommand command) {
    for (String rule : command.getMergeGroups()) {
        String[] gw = rule.split(":");
        int weight = 1;
        if (gw.length > 1) {
            try {
                weight = Integer.parseInt(gw[1]);
            } catch (NumberFormatException e) {
                throw new FrameworkException(new Status(WEIGHT_OUT_OF_RANGE, weight));
            }
            if (weight < 0 || weight > 100) {
                throw new FrameworkException(new Status(WEIGHT_OUT_OF_RANGE, weight));
            }
        }
        weights.put(gw[0], weight);
    }
}
 
Example #12
Source File: ResponseValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateHeaders(HttpServerExchange exchange, OpenApiOperation operation, String statusCode) {
    Optional<Response> response = Optional.ofNullable(operation.getOperation().getResponse(statusCode));
    if(response.isPresent()) {
        Map<String, Header> headerMap = response.get().getHeaders();
        Optional<Status> optional = headerMap.entrySet()
                .stream()
                //based on OpenAPI specification, ignore "Content-Type" header
                //If a response header is defined with the name "Content-Type", it SHALL be ignored. - https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#responseObject
                .filter(entry -> !Headers.CONTENT_TYPE_STRING.equals(entry.getKey()))
                .map(p -> validateHeader(exchange, p.getKey(), p.getValue()))
                .filter(s -> s != null)
                .findFirst();
        if(optional.isPresent()) {
            return optional.get();
        }
    }
    return null;
}
 
Example #13
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the request against the given API operation
 * @param requestPath normalised path
 * @param exchange The HttpServerExchange to validate
 * @param openApiOperation OpenAPI operation
 * @return A validation report containing validation errors
 */
public Status validateRequest(final NormalisedPath requestPath, HttpServerExchange exchange, OpenApiOperation openApiOperation) {
    requireNonNull(requestPath, "A request path is required");
    requireNonNull(exchange, "An exchange is required");
    requireNonNull(openApiOperation, "An OpenAPI operation is required");

    Status status = validateRequestParameters(exchange, requestPath, openApiOperation);
    if(status != null) return status;
    String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (contentType==null || contentType.startsWith("application/json")) {
        Object body = exchange.getAttachment(BodyHandler.REQUEST_BODY);
        // skip the body validation if body parser is not in the request chain.
        if(body == null && ValidatorHandler.config.skipBodyValidation) return null;
        status = validateRequestBody(body, openApiOperation);
    }
    return status;
}
 
Example #14
Source File: ResponseValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the given response against the API operation.
 *
 * @param exchange The exchange to validate
 * @param swaggerOperation The API operation to validate the response against
 *
 * @return A status containing validation error
 */
public Status validateResponse(final HttpServerExchange exchange, final SwaggerOperation swaggerOperation) {
    requireNonNull(exchange, "An exchange is required");
    requireNonNull(swaggerOperation, "A swagger operation is required");

    io.swagger.models.Response swaggerResponse = swaggerOperation.getOperation().getResponses().get(Integer.toString(exchange.getStatusCode()));
    if (swaggerResponse == null) {
        swaggerResponse = swaggerOperation.getOperation().getResponses().get("default"); // try the default response
    }

    if (swaggerResponse == null) {
        return new Status("ERR11015", exchange.getStatusCode(), swaggerOperation.getPathString().original());
    }

    if (swaggerResponse.getSchema() == null) {
        return null;
    }
    String body = exchange.getOutputStream().toString();

    if (body == null || body.length() == 0) {
        return new Status("ERR11016", swaggerOperation.getMethod(), swaggerOperation.getPathString().original());
    }
    return schemaValidator.validate(body, swaggerResponse.getSchema());
}
 
Example #15
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateHeader(final HttpServerExchange exchange,
                              final SwaggerOperation swaggerOperation,
                              final Parameter headerParameter) {

    final HeaderValues headerValues = exchange.getRequestHeaders().get(headerParameter.getName());
    if ((headerValues == null || headerValues.isEmpty())) {
        if(headerParameter.getRequired()) {
            return new Status(VALIDATOR_REQUEST_PARAMETER_HEADER_MISSING, headerParameter.getName(), swaggerOperation.getPathString().original());
        }
    } else {

        Optional<Status> optional = headerValues
                .stream()
                .map((v) -> parameterValidators.validate(v, headerParameter))
                .filter(s -> s != null)
                .findFirst();
        if(optional.isPresent()) {
            return optional.get();
        }
    }
    return null;
}
 
Example #16
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateHeader(final HttpServerExchange exchange,
                              final SwaggerOperation swaggerOperation) {
    Optional<Status> optional = swaggerOperation
            .getOperation()
            .getParameters()
            .stream()
            .filter(p -> p.getIn().equalsIgnoreCase("header"))
            .map(p -> validateHeader(exchange, swaggerOperation, p))
            .filter(s -> s != null)
            .findFirst();
    if(optional.isPresent()) {
        return optional.get();
    } else {
        return null;
    }
}
 
Example #17
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 6 votes vote down vote up
private Status validateQueryParameter(final HttpServerExchange exchange,
                                      final SwaggerOperation swaggerOperation,
                                      final Parameter queryParameter) {

    final Collection<String> queryParameterValues = exchange.getQueryParameters().get(queryParameter.getName());

    if ((queryParameterValues == null || queryParameterValues.isEmpty())) {
        if(queryParameter.getRequired()) {
            return new Status(VALIDATOR_REQUEST_PARAMETER_QUERY_MISSING, queryParameter.getName(), swaggerOperation.getPathString().original());
        }
    } else {

        Optional<Status> optional = queryParameterValues
                .stream()
                .map((v) -> parameterValidators.validate(v, queryParameter))
                .filter(s -> s != null)
                .findFirst();
        if(optional.isPresent()) {
            return optional.get();
        }
    }
    return null;
}
 
Example #18
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
private Status validateCookieParameters(final HttpServerExchange exchange,
		final OpenApiOperation openApiOperation) {

	// validate path level parameters for cookies first.
	Optional<Status> optional = validatePathLevelCookies(exchange, openApiOperation);
	if (optional.isPresent()) {
		return optional.get();
	} else {
		// validate operation level parameter for cookies second.
		optional = validateOperationLevelCookies(exchange, openApiOperation);
		return optional.orElse(null);
	}
}
 
Example #19
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
private Optional<Status> validatePathLevelCookies(final HttpServerExchange exchange, final OpenApiOperation openApiOperation) {
	ValidationResult result = validateDeserializedValues(exchange, openApiOperation.getPathObject().getParameters(), ParameterType.COOKIE);
	
	if (null!=result.getStatus() || result.getSkippedParameters().isEmpty()) {
		return Optional.ofNullable(result.getStatus());
	}
	
	return result.getSkippedParameters().stream()
        .map(p -> validateHeader(exchange, openApiOperation, p))
        .filter(s -> s != null)
        .findFirst();
}
 
Example #20
Source File: ResponseValidator.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
/**
 * validate a given response content object with schema coordinate (uri, httpMethod, statusCode, mediaTypeName)
 * uri, httpMethod, statusCode, mediaTypeName is to locate the schema to validate
 * @param responseContent response content needs to be validated
 * @param uri original uri of the request
 * @param httpMethod eg. "put" or "get"
 * @param statusCode eg. 200, 400
 * @param mediaTypeName eg. "application/json"
 * @return Status return null if no validation errors
 */
public Status validateResponseContent(Object responseContent, String uri, String httpMethod, String statusCode, String mediaTypeName) {
    OpenApiOperation operation = null;
    try {
        operation = getOpenApiOperation(uri, httpMethod);
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        return new Status(VALIDATOR_RESPONSE_CONTENT_UNEXPECTED, httpMethod, uri);
    }
    if(operation == null) {
        return new Status(VALIDATOR_RESPONSE_CONTENT_UNEXPECTED, httpMethod, uri);
    }
    return validateResponseContent(responseContent, operation, statusCode, mediaTypeName);
}
 
Example #21
Source File: ZooKeeperRegistry.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void subscribeService(final URL url, final ServiceListener serviceListener) {
    try {
        clientLock.lock();
        ConcurrentHashMap<ServiceListener, IZkChildListener> childChangeListeners = serviceListeners.get(url);
        if (childChangeListeners == null) {
            serviceListeners.putIfAbsent(url, new ConcurrentHashMap<ServiceListener, IZkChildListener>());
            childChangeListeners = serviceListeners.get(url);
        }
        IZkChildListener zkChildListener = childChangeListeners.get(serviceListener);
        if (zkChildListener == null) {
            childChangeListeners.putIfAbsent(serviceListener, new IZkChildListener() {
                @Override
                public void handleChildChange(String parentPath, List<String> currentChilds) {
                    serviceListener.notifyService(url, getUrl(), nodeChildsToUrls(parentPath, currentChilds));
                    if(logger.isInfoEnabled()) logger.info(String.format("[ZooKeeperRegistry] service list change: path=%s, currentChilds=%s", parentPath, currentChilds.toString()));
                }
            });
            zkChildListener = childChangeListeners.get(serviceListener);
        }

        // prevent old node unregistered
        removeNode(url, ZkNodeType.CLIENT);
        createNode(url, ZkNodeType.CLIENT);

        String serverTypePath = ZkUtils.toNodeTypePath(url, ZkNodeType.AVAILABLE_SERVER);
        client.subscribeChildChanges(serverTypePath, zkChildListener);
        if(logger.isInfoEnabled()) logger.info(String.format("[ZooKeeperRegistry] subscribe service: path=%s, info=%s", ZkUtils.toNodePath(url, ZkNodeType.AVAILABLE_SERVER), url.toFullStr()));
    } catch (Throwable e) {
        throw new FrameworkException(new Status(SUBSCRIBE_ZOOKEEPER_SERVICE_ERROR, url, getUrl(), e.getMessage()), e);
    } finally {
        clientLock.unlock();
    }
}
 
Example #22
Source File: ResponseValidatorTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {

    String responseBody = null;
    if(exchange.getAttachment(BodyHandler.REQUEST_BODY) != null) {
        responseBody = Config.getInstance().getMapper().writeValueAsString(exchange.getAttachment(BodyHandler.REQUEST_BODY));
    }
    Status status = validator.validateResponseContent(responseBody, exchange);
    if(status == null) {
        exchange.getResponseSender().send("good");
    } else {
        exchange.setStatusCode(400);
        exchange.getResponseSender().send("bad");
    }
}
 
Example #23
Source File: ValidatorHandler.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
private void validateResponse(HttpServerExchange exchange, OpenApiOperation openApiOperation) {
    exchange.addResponseWrapper((factory, exchange12) -> new StoreResponseStreamSinkConduit(factory.create(), exchange12));

    exchange.addExchangeCompleteListener((exchange1, nextListener) ->{
        Status status = responseValidator.validateResponse(exchange, openApiOperation);
        if(status != null) {
            logger.error("Response validation error: {} \n with response body: {}", status.getDescription(), new String(exchange.getAttachment(StoreResponseStreamSinkConduit.RESPONSE)));
        }
        nextListener.proceed();
    });
}
 
Example #24
Source File: Oauth2DerefGetHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private String authenticate(String authHeader) throws ApiException {
    String result = null;
    if (authHeader.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {
        String base64Challenge = authHeader.substring(PREFIX_LENGTH);
        String plainChallenge;
        try {
            ByteBuffer decode = FlexBase64.decode(base64Challenge);
            // assume charset is UTF_8
            Charset charset = StandardCharsets.UTF_8;
            plainChallenge = new String(decode.array(), decode.arrayOffset(), decode.limit(), charset);
            logger.debug("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, authHeader);
            int colonPos;
            if ((colonPos = plainChallenge.indexOf(COLON)) > -1) {
                String clientId = plainChallenge.substring(0, colonPos);
                String clientSecret = plainChallenge.substring(colonPos + 1);
                // match with db/cached user credentials.
                IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
                Client client = clients.get(clientId);
                if(client == null) {
                    throw new ApiException(new Status(CLIENT_NOT_FOUND, clientId));
                }
                if(!HashUtil.validatePassword(clientSecret.toCharArray(), client.getClientSecret())) {
                    throw new ApiException(new Status(UNAUTHORIZED_CLIENT));
                }
                result = clientId;
            }
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            logger.error("Exception:", e);
            throw new ApiException(new Status(RUNTIME_EXCEPTION));
        }
    }
    return result;
}
 
Example #25
Source File: TestMergeStatusConfig.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public void testEmptyAppStatus() {
    config.clear();
    File appStatus = new File(homeDir + "/app-status.yml");
    appStatus.delete();
    new File(homeDir + "/app-status.yml");
    // test default element without merging with app-status
    Status status0 = new Status("ERR10053", "url");
    Assert.assertEquals(401, status0.getStatusCode());
    Server.mergeStatusConfig();
    // test default element after merging
    Status status1 = new Status("ERR10053", "url");
    Assert.assertEquals(401, status1.getStatusCode());
}
 
Example #26
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
private Optional<Status> validatePathLevelHeaders(final HttpServerExchange exchange, final OpenApiOperation openApiOperation) {
	ValidationResult result = validateDeserializedValues(exchange, openApiOperation.getPathObject().getParameters(), ParameterType.HEADER);
	
	if (null!=result.getStatus() || result.getSkippedParameters().isEmpty()) {
		return Optional.ofNullable(result.getStatus());
	}
	
	return result.getSkippedParameters().stream()
        .map(p -> validateHeader(exchange, openApiOperation, p))
        .filter(s -> s != null)
        .findFirst();
}
 
Example #27
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
private Status validateQueryParameter(final HttpServerExchange exchange,
                                      final OpenApiOperation openApiOperation,
                                      final Parameter queryParameter) {

    final Collection<String> queryParameterValues = exchange.getQueryParameters().get(queryParameter.getName());

    if ((queryParameterValues == null || queryParameterValues.isEmpty())) {
        if(queryParameter.getRequired() != null && queryParameter.getRequired()) {
            return new Status(VALIDATOR_REQUEST_PARAMETER_QUERY_MISSING, queryParameter.getName(), openApiOperation.getPathString().original());
        }
    // Validate the value contains by queryParameterValue, if it is the only elements inside the array deque.
    // Since if the queryParameterValue's length smaller than 2, it means the query parameter is not an array,
    // thus not necessary to apply array validation to this value.
    } else if (queryParameterValues.size() < 2) {

        Optional<Status> optional = queryParameterValues
                .stream()
                .map((v) -> schemaValidator.validate(v, Overlay.toJson((SchemaImpl)queryParameter.getSchema()), queryParameter.getName()))
                .filter(s -> s != null)
                .findFirst();
        
        return optional.orElse(null);
    // Validate the queryParameterValue directly instead of validating its elements, if the length of this array deque larger than 2.
    // Since if the queryParameterValue's length larger than 2, it means the query parameter is an array.
    // thus array validation should be applied, for example, validate the length of the array.
    } else {
        return schemaValidator.validate(queryParameterValues, Overlay.toJson((SchemaImpl)queryParameter.getSchema()), queryParameter.getName());
    }
    return null;
}
 
Example #28
Source File: Oauth2KeyKeyIdGetHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private String authenticate(String authHeader) throws ApiException {
    String result = null;
    if (authHeader.toLowerCase(Locale.ENGLISH).startsWith(LOWERCASE_BASIC_PREFIX)) {
        String base64Challenge = authHeader.substring(PREFIX_LENGTH);
        String plainChallenge;
        try {
            ByteBuffer decode = FlexBase64.decode(base64Challenge);
            // assume charset is UTF_8
            Charset charset = StandardCharsets.UTF_8;
            plainChallenge = new String(decode.array(), decode.arrayOffset(), decode.limit(), charset);
            logger.debug("Found basic auth header %s (decoded using charset %s) in %s", plainChallenge, charset, authHeader);
            int colonPos;
            if ((colonPos = plainChallenge.indexOf(COLON)) > -1) {
                String clientId = plainChallenge.substring(0, colonPos);
                String clientSecret = plainChallenge.substring(colonPos + 1);
                // match with db/cached user credentials.
                IMap<String, Client> clients = CacheStartupHookProvider.hz.getMap("clients");
                Client client = clients.get(clientId);
                if(client == null) {
                    throw new ApiException(new Status(CLIENT_NOT_FOUND, clientId));
                }
                if(!HashUtil.validatePassword(clientSecret.toCharArray(), client.getClientSecret())) {
                    throw new ApiException(new Status(UNAUTHORIZED_CLIENT));
                }
                result = clientId;
            }
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            logger.error("Exception:", e);
            throw new ApiException(new Status(RUNTIME_EXCEPTION));
        }
    }
    return result;
}
 
Example #29
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
private Status validatePathParameters(final HttpServerExchange exchange, final NormalisedPath requestPath, final OpenApiOperation openApiOperation) {
	ValidationResult result = validateDeserializedValues(exchange, openApiOperation.getOperation().getParameters(), ParameterType.PATH);
	
	if (null!=result.getStatus() || result.getSkippedParameters().isEmpty()) {
		return result.getStatus();
	}
	
	// validate values that cannot be deserialized or do not need to be deserialized
	Status status = null;
    for (int i = 0; i < openApiOperation.getPathString().parts().size(); i++) {
        if (!openApiOperation.getPathString().isParam(i)) {
            continue;
        }

        final String paramName = openApiOperation.getPathString().paramName(i);
        final Optional<Parameter> parameter = result.getSkippedParameters()
                .stream()
                .filter(p -> p.getName().equalsIgnoreCase(paramName))
                .findFirst();

        if (parameter.isPresent()) {
         String paramValue = requestPath.part(i); // If it can't be UTF-8 decoded, use directly.
         try {
             paramValue = URLDecoder.decode(requestPath.part(i), "UTF-8");
         } catch (Exception e) {
             logger.info("Path parameter cannot be decoded, it will be used directly");
         }

            return schemaValidator.validate(paramValue, Overlay.toJson((SchemaImpl)(parameter.get().getSchema())), paramName);
        }
    }
    return status;
}
 
Example #30
Source File: RequestValidator.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
private Status validateRequestParameters(final HttpServerExchange exchange, final NormalisedPath requestPath, final OpenApiOperation openApiOperation) {
    Status status = validatePathParameters(exchange, requestPath, openApiOperation);
    if(status != null) return status;

    status = validateQueryParameters(exchange, openApiOperation);
    if(status != null) return status;

    status = validateHeaderParameters(exchange, openApiOperation);
    if(status != null) return status;
    
    status = validateCookieParameters(exchange, openApiOperation);
    if(status != null) return status;  
    
    return null;
}