Search in sources :

Example 31 with CatsResponse

use of com.endava.cats.model.CatsResponse in project cats by Endava.

the class ExtraHeaderFuzzerTest method givenASetOfHeaders_whenCallingTheExtraHeadersFuzzer_thenTheResultsAreCorrectlyReported.

@Test
void givenASetOfHeaders_whenCallingTheExtraHeadersFuzzer_thenTheResultsAreCorrectlyReported() {
    Map<String, List<String>> responses = new HashMap<>();
    responses.put("200", Collections.singletonList("response"));
    FuzzingData data = FuzzingData.builder().headers(Collections.singleton(CatsHeader.builder().name("header").value("value").build())).responses(responses).reqSchema(new StringSchema()).build();
    CatsResponse catsResponse = CatsResponse.builder().body("{}").responseCode(200).build();
    Mockito.when(serviceCaller.call(Mockito.any())).thenReturn(catsResponse);
    Mockito.doNothing().when(testCaseListener).reportResult(Mockito.any(), Mockito.eq(data), Mockito.any(), Mockito.any());
    extraHeaderFuzzer.fuzz(data);
    Mockito.verify(testCaseListener, Mockito.times(1)).reportResult(Mockito.any(), Mockito.eq(data), Mockito.eq(catsResponse), Mockito.eq(ResponseCodeFamily.TWOXX));
}
Also used : CatsResponse(com.endava.cats.model.CatsResponse) HashMap(java.util.HashMap) FuzzingData(com.endava.cats.model.FuzzingData) List(java.util.List) StringSchema(io.swagger.v3.oas.models.media.StringSchema) QuarkusTest(io.quarkus.test.junit.QuarkusTest) Test(org.junit.jupiter.api.Test)

Example 32 with CatsResponse

use of com.endava.cats.model.CatsResponse in project cats by Endava.

the class ServiceCaller method callService.

public CatsResponse callService(CatsRequest catsRequest, Set<String> fuzzedFields) throws IOException {
    long startTime = System.currentTimeMillis();
    RequestBody requestBody = null;
    Headers.Builder headers = new Headers.Builder();
    catsRequest.getHeaders().forEach(header -> headers.addUnsafeNonAscii(header.getName(), header.getValue()));
    if (HttpMethod.requiresBody(catsRequest.getHttpMethod())) {
        requestBody = RequestBody.create(catsRequest.getPayload().getBytes(StandardCharsets.UTF_8));
    }
    Response response = okHttpClient.newCall(new Request.Builder().url(catsRequest.getUrl()).headers(headers.build()).method(catsRequest.getHttpMethod(), requestBody).build()).execute();
    long endTime = System.currentTimeMillis();
    LOGGER.complete("Protocol: {}, Method: {}, ReasonPhrase: {}, ResponseCode: {}, ResponseTimeInMs: {}", response.protocol(), catsRequest.getHttpMethod(), response.message(), response.code(), endTime - startTime);
    String responseBody = this.getAsJson(response);
    List<CatsHeader> responseHeaders = response.headers().toMultimap().entrySet().stream().map(header -> CatsHeader.builder().name(header.getKey()).value(header.getValue().get(0)).build()).collect(Collectors.toList());
    return CatsResponse.from(response.code(), responseBody, catsRequest.getHttpMethod(), endTime - startTime, responseHeaders, fuzzedFields);
}
Also used : CatsResponse(com.endava.cats.model.CatsResponse) Response(okhttp3.Response) X509Certificate(java.security.cert.X509Certificate) ADDITIONAL_PROPERTIES(com.endava.cats.dsl.CatsDSLWords.ADDITIONAL_PROPERTIES) JsonObject(com.google.gson.JsonObject) SSLContext(javax.net.ssl.SSLContext) Arrays(java.util.Arrays) CatsGlobalContext(com.endava.cats.model.CatsGlobalContext) CatsDSLWords(com.endava.cats.dsl.CatsDSLWords) TrustManager(javax.net.ssl.TrustManager) HtmlEscapers(com.google.common.html.HtmlEscapers) CatsResponse(com.endava.cats.model.CatsResponse) PrettyLogger(io.github.ludovicianul.prettylogger.PrettyLogger) StringUtils(org.apache.commons.lang3.StringUtils) SecureRandom(java.security.SecureRandom) GeneralSecurityException(java.security.GeneralSecurityException) FilesArguments(com.endava.cats.args.FilesArguments) Map(java.util.Map) ResponseBody(okhttp3.ResponseBody) CatsUtil(com.endava.cats.util.CatsUtil) Request(okhttp3.Request) Set(java.util.Set) KeyStore(java.security.KeyStore) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) AuthArguments(com.endava.cats.args.AuthArguments) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) List(java.util.List) CatsDSLParser(com.endava.cats.dsl.CatsDSLParser) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) CatsRequest(com.endava.cats.model.CatsRequest) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) HttpUrl(okhttp3.HttpUrl) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) WordUtils(com.endava.cats.util.WordUtils) PrettyLoggerFactory(io.github.ludovicianul.prettylogger.PrettyLoggerFactory) HashMap(java.util.HashMap) RateLimiter(com.google.common.util.concurrent.RateLimiter) Headers(okhttp3.Headers) TreeSet(java.util.TreeSet) RequestBody(okhttp3.RequestBody) ArrayList(java.util.ArrayList) JsonElement(com.google.gson.JsonElement) Inject(javax.inject.Inject) NOT_SET(com.endava.cats.model.util.JsonUtils.NOT_SET) Response(okhttp3.Response) ProcessingArguments(com.endava.cats.args.ProcessingArguments) FuzzingStrategy(com.endava.cats.model.FuzzingStrategy) ApiArguments(com.endava.cats.args.ApiArguments) TestCaseListener(com.endava.cats.report.TestCaseListener) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) JsonUtils(com.endava.cats.model.util.JsonUtils) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) HttpMethod(com.endava.cats.http.HttpMethod) X509TrustManager(javax.net.ssl.X509TrustManager) DryRun(com.endava.cats.annotations.DryRun) ConnectionPool(okhttp3.ConnectionPool) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) CatsHeader(com.endava.cats.model.CatsHeader) InputStream(java.io.InputStream) Headers(okhttp3.Headers) RequestBody(okhttp3.RequestBody) CatsHeader(com.endava.cats.model.CatsHeader)

Example 33 with CatsResponse

use of com.endava.cats.model.CatsResponse in project cats by Endava.

the class CustomFuzzerUtil method process.

public void process(FuzzingData data, String testName, Map<String, String> currentPathValues) {
    String expectedResponseCode = currentPathValues.get(CatsDSLWords.EXPECTED_RESPONSE_CODE);
    this.startCustomTest(testName, currentPathValues, expectedResponseCode);
    String payloadWithCustomValuesReplaced = this.getJsonWithCustomValuesFromFile(data, currentPathValues);
    catsUtil.setAdditionalPropertiesToPayload(currentPathValues, payloadWithCustomValuesReplaced);
    String servicePath = this.replacePathVariablesWithCustomValues(data, currentPathValues);
    CatsResponse response = serviceCaller.call(ServiceData.builder().relativePath(servicePath).replaceRefData(false).httpMethod(data.getMethod()).headers(data.getHeaders()).payload(payloadWithCustomValuesReplaced).queryParams(data.getQueryParams()).build());
    this.setOutputVariables(currentPathValues, response, payloadWithCustomValuesReplaced);
    String verify = currentPathValues.get(CatsDSLWords.VERIFY);
    if (verify != null) {
        this.checkVerifiesAndReport(payloadWithCustomValuesReplaced, response, verify, expectedResponseCode);
    } else {
        testCaseListener.reportResult(log, data, response, ResponseCodeFamily.from(expectedResponseCode));
    }
}
Also used : CatsResponse(com.endava.cats.model.CatsResponse)

Example 34 with CatsResponse

use of com.endava.cats.model.CatsResponse in project cats by Endava.

the class CustomFuzzerUtil method checkVerifiesAndReport.

private void checkVerifiesAndReport(String request, CatsResponse response, String verify, String expectedResponseCode) {
    Map<String, String> verifies = this.parseYmlEntryIntoMap(verify);
    Map<String, String> responseValues = this.matchVariablesWithTheResponse(response, verifies, Map.Entry::getKey);
    log.info("Parameters to verify: {}", verifies);
    log.info("Parameters matched to response: {}", responseValues);
    if (responseValues.entrySet().stream().anyMatch(entry -> entry.getValue().equalsIgnoreCase(NOT_SET))) {
        log.error("There are Verify parameters which were not present in the response!");
        testCaseListener.reportError(log, "The following Verify parameters were not present in the response: {}", responseValues.entrySet().stream().filter(entry -> entry.getValue().equalsIgnoreCase(NOT_SET)).map(Map.Entry::getKey).collect(Collectors.toList()));
    } else {
        StringBuilder errorMessages = new StringBuilder();
        verifies.forEach((key, value) -> {
            String valueToCheck = responseValues.get(key);
            String parsedVerifyValue = this.getVerifyValue(request, response, value);
            Matcher verifyMatcher = Pattern.compile(parsedVerifyValue).matcher(valueToCheck);
            if (!verifyMatcher.matches()) {
                errorMessages.append(String.format(NOT_MATCHING_ERROR, key, valueToCheck, parsedVerifyValue));
            }
        });
        if (errorMessages.length() == 0 && expectedResponseCode.equalsIgnoreCase(response.responseCodeAsString())) {
            testCaseListener.reportInfo(log, "Response matches all 'verify' parameters");
        } else if (errorMessages.length() == 0) {
            testCaseListener.reportWarn(log, "Response matches all 'verify' parameters, but response code doesn't match expected response code: expected [{}], actual [{}]", expectedResponseCode, response.responseCodeAsString());
        } else {
            testCaseListener.reportError(log, errorMessages.toString());
        }
    }
}
Also used : Arrays(java.util.Arrays) PrettyLoggerFactory(io.github.ludovicianul.prettylogger.PrettyLoggerFactory) CatsDSLWords(com.endava.cats.dsl.CatsDSLWords) HashMap(java.util.HashMap) CatsResponse(com.endava.cats.model.CatsResponse) PrettyLogger(io.github.ludovicianul.prettylogger.PrettyLogger) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Matcher(java.util.regex.Matcher) NOT_SET(com.endava.cats.model.util.JsonUtils.NOT_SET) Map(java.util.Map) FuzzingData(com.endava.cats.model.FuzzingData) CustomFuzzerBase(com.endava.cats.fuzzer.fields.base.CustomFuzzerBase) CatsUtil(com.endava.cats.util.CatsUtil) FuzzingStrategy(com.endava.cats.model.FuzzingStrategy) TestCaseListener(com.endava.cats.report.TestCaseListener) IOException(java.io.IOException) JsonUtils(com.endava.cats.model.util.JsonUtils) Collectors(java.util.stream.Collectors) ResponseCodeFamily(com.endava.cats.http.ResponseCodeFamily) ServiceData(com.endava.cats.io.ServiceData) AbstractMap(java.util.AbstractMap) List(java.util.List) ServiceCaller(com.endava.cats.io.ServiceCaller) CatsDSLParser(com.endava.cats.dsl.CatsDSLParser) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) Matcher(java.util.regex.Matcher)

Example 35 with CatsResponse

use of com.endava.cats.model.CatsResponse in project cats by Endava.

the class HappyFuzzer method process.

private void process(FuzzingData data) {
    testCaseListener.addScenario(LOGGER, "Send a 'happy' flow request with all fields and all headers in: {}", data.getMethod());
    testCaseListener.addExpectedResult(LOGGER, "Should get a 2XX response code");
    CatsResponse response = serviceCaller.call(ServiceData.builder().relativePath(data.getPath()).headers(data.getHeaders()).payload(data.getPayload()).queryParams(data.getQueryParams()).httpMethod(data.getMethod()).build());
    testCaseListener.reportResult(LOGGER, data, response, ResponseCodeFamily.TWOXX);
}
Also used : CatsResponse(com.endava.cats.model.CatsResponse)

Aggregations

CatsResponse (com.endava.cats.model.CatsResponse)67 FuzzingData (com.endava.cats.model.FuzzingData)44 QuarkusTest (io.quarkus.test.junit.QuarkusTest)42 Test (org.junit.jupiter.api.Test)42 StringSchema (io.swagger.v3.oas.models.media.StringSchema)23 List (java.util.List)15 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)15 HashMap (java.util.HashMap)14 CatsHeader (com.endava.cats.model.CatsHeader)7 PathItem (io.swagger.v3.oas.models.PathItem)7 ServiceData (com.endava.cats.io.ServiceData)6 CatsTestCase (com.endava.cats.model.report.CatsTestCase)5 CsvSource (org.junit.jupiter.params.provider.CsvSource)5 ResponseCodeFamily (com.endava.cats.http.ResponseCodeFamily)4 ArrayList (java.util.ArrayList)4 FuzzingStrategy (com.endava.cats.model.FuzzingStrategy)3 TestCaseListener (com.endava.cats.report.TestCaseListener)3 JsonObject (com.google.gson.JsonObject)3 PrettyLogger (io.github.ludovicianul.prettylogger.PrettyLogger)3 PrettyLoggerFactory (io.github.ludovicianul.prettylogger.PrettyLoggerFactory)3