diff --git a/apps/dashboard/src/main/java/com/akto/action/testing/StartTestAction.java b/apps/dashboard/src/main/java/com/akto/action/testing/StartTestAction.java index 7ab4be3d8d..deb67bd947 100644 --- a/apps/dashboard/src/main/java/com/akto/action/testing/StartTestAction.java +++ b/apps/dashboard/src/main/java/com/akto/action/testing/StartTestAction.java @@ -74,6 +74,8 @@ public class StartTestAction extends UserAction { private Map issuesSummaryInfoMap = new HashMap<>(); private String testRoleId; + private boolean cleanUpTestingResources; + private static final Gson gson = new Gson(); private static List getTestingRunListFromSummary(Bson filters){ @@ -147,7 +149,7 @@ private TestingRun createTestingRun(int scheduleTimestamp, int periodInSeconds) } if (this.selectedTests != null) { int id = UUID.randomUUID().hashCode() & 0xfffffff; - TestingRunConfig testingRunConfig = new TestingRunConfig(id, null, this.selectedTests, authMechanism.getId(), this.overriddenTestAppUrl, this.testRoleId); + TestingRunConfig testingRunConfig = new TestingRunConfig(id, null, this.selectedTests, authMechanism.getId(), this.overriddenTestAppUrl, this.testRoleId, this.cleanUpTestingResources); // add advanced setting here if(this.testConfigsAdvancedSettings != null && !this.testConfigsAdvancedSettings.isEmpty()){ testingRunConfig.setConfigsAdvancedSettings(this.testConfigsAdvancedSettings); @@ -1401,4 +1403,12 @@ public Map getTestCountMap() { public void setReportFilterList(Map> reportFilterList) { this.reportFilterList = reportFilterList; } + + public boolean getCleanUpTestingResources() { + return cleanUpTestingResources; + } + + public void setCleanUpTestingResources(boolean cleanUpTestingResources) { + this.cleanUpTestingResources = cleanUpTestingResources; + } } diff --git a/apps/dashboard/web/polaris_web/web/src/apps/dashboard/pages/observe/api.js b/apps/dashboard/web/polaris_web/web/src/apps/dashboard/pages/observe/api.js index 1a425949a9..f17426ffb7 100644 --- a/apps/dashboard/web/polaris_web/web/src/apps/dashboard/pages/observe/api.js +++ b/apps/dashboard/web/polaris_web/web/src/apps/dashboard/pages/observe/api.js @@ -573,20 +573,20 @@ export default { data: {} }) }, - scheduleTestForCollection(apiCollectionId, startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, testRoleId, continuousTesting, sendSlackAlert, testConfigsAdvancedSettings) { + scheduleTestForCollection(apiCollectionId, startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, testRoleId, continuousTesting, sendSlackAlert, testConfigsAdvancedSettings, cleanUpTestingResources) { return request({ url: '/api/startTest', method: 'post', - data: { apiCollectionId, type: "COLLECTION_WISE", startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, testRoleId, continuousTesting, sendSlackAlert, testConfigsAdvancedSettings} + data: { apiCollectionId, type: "COLLECTION_WISE", startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, testRoleId, continuousTesting, sendSlackAlert, testConfigsAdvancedSettings, cleanUpTestingResources} }).then((resp) => { return resp }) }, - scheduleTestForCustomEndpoints(apiInfoKeyList, startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, source, testRoleId, continuousTesting, sendSlackAlert, testConfigsAdvancedSettings) { + scheduleTestForCustomEndpoints(apiInfoKeyList, startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, source, testRoleId, continuousTesting, sendSlackAlert, testConfigsAdvancedSettings, cleanUpTestingResources) { return request({ url: '/api/startTest', method: 'post', - data: {apiInfoKeyList, type: "CUSTOM", startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, source, testRoleId, continuousTesting, sendSlackAlert, testConfigsAdvancedSettings} + data: {apiInfoKeyList, type: "CUSTOM", startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, source, testRoleId, continuousTesting, sendSlackAlert, testConfigsAdvancedSettings, cleanUpTestingResources} }).then((resp) => { return resp }) diff --git a/apps/dashboard/web/polaris_web/web/src/apps/dashboard/pages/observe/api_collections/RunTest.jsx b/apps/dashboard/web/polaris_web/web/src/apps/dashboard/pages/observe/api_collections/RunTest.jsx index 7365689c4f..e6a714b94c 100644 --- a/apps/dashboard/web/polaris_web/web/src/apps/dashboard/pages/observe/api_collections/RunTest.jsx +++ b/apps/dashboard/web/polaris_web/web/src/apps/dashboard/pages/observe/api_collections/RunTest.jsx @@ -35,7 +35,8 @@ function RunTest({ endpoints, filtered, apiCollectionId, disabled, runTestFromOu authMechanismPresent: false, testRoleLabel: "No test role selected", testRoleId: "", - sendSlackAlert: false + sendSlackAlert: false, + cleanUpTestingResources: false } const navigate = useNavigate() @@ -413,7 +414,7 @@ function RunTest({ endpoints, filtered, apiCollectionId, disabled, runTestFromOu } async function handleRun() { - const { startTimestamp, recurringDaily, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, testRoleId, continuousTesting, sendSlackAlert } = testRun + const { startTimestamp, recurringDaily, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, testRoleId, continuousTesting, sendSlackAlert, cleanUpTestingResources } = testRun const collectionId = parseInt(apiCollectionId) const tests = testRun.tests @@ -454,9 +455,9 @@ function RunTest({ endpoints, filtered, apiCollectionId, disabled, runTestFromOu } if (filtered || selectedResourcesForPrimaryAction.length > 0) { - await observeApi.scheduleTestForCustomEndpoints(apiInfoKeyList, startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, "TESTING_UI", testRoleId, continuousTesting, sendSlackAlert, finalAdvancedConditions) + await observeApi.scheduleTestForCustomEndpoints(apiInfoKeyList, startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, "TESTING_UI", testRoleId, continuousTesting, sendSlackAlert, finalAdvancedConditions, cleanUpTestingResources) } else { - await observeApi.scheduleTestForCollection(collectionId, startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, testRoleId, continuousTesting, sendSlackAlert, finalAdvancedConditions) + await observeApi.scheduleTestForCollection(collectionId, startTimestamp, recurringDaily, selectedTests, testName, testRunTime, maxConcurrentRequests, overriddenTestAppUrl, testRoleId, continuousTesting, sendSlackAlert, finalAdvancedConditions, cleanUpTestingResources) } setActive(false) @@ -767,6 +768,13 @@ function RunTest({ endpoints, filtered, apiCollectionId, disabled, runTestFromOu } + {window.ACTIVE_ACCOUNT === 1723492815 && + setTestRun(prev => ({ ...prev, cleanUpTestingResources: !prev.cleanUpTestingResources }))} + /> + } diff --git a/apps/testing/src/main/java/com/akto/test_editor/execution/Executor.java b/apps/testing/src/main/java/com/akto/test_editor/execution/Executor.java index 9dd96167cb..43d8bcfde7 100644 --- a/apps/testing/src/main/java/com/akto/test_editor/execution/Executor.java +++ b/apps/testing/src/main/java/com/akto/test_editor/execution/Executor.java @@ -485,7 +485,7 @@ private static boolean removeCustomAuth(RawApi rawApi, List cust return removed; } - private ExecutorSingleOperationResp modifyAuthTokenInRawApi(TestRoles testRole, RawApi rawApi) { + public static ExecutorSingleOperationResp modifyAuthTokenInRawApi(TestRoles testRole, RawApi rawApi) { Map> rawHeaders = rawApi.fetchReqHeaders(); for(AuthWithCond authWithCond: testRole.getAuthWithCondList()) { diff --git a/apps/testing/src/main/java/com/akto/testing/TestExecutor.java b/apps/testing/src/main/java/com/akto/testing/TestExecutor.java index 7e1b799bcc..447f85399d 100644 --- a/apps/testing/src/main/java/com/akto/testing/TestExecutor.java +++ b/apps/testing/src/main/java/com/akto/testing/TestExecutor.java @@ -5,8 +5,10 @@ import com.akto.dao.ActivitiesDao; import com.akto.dao.ApiInfoDao; import com.akto.dao.CustomAuthTypeDao; +import com.akto.dao.DependencyNodeDao; import com.akto.dao.context.Context; import com.akto.dao.test_editor.YamlTemplateDao; +import com.akto.dao.testing.TestRolesDao; import com.akto.dao.testing.TestingRunResultDao; import com.akto.dao.testing.TestingRunResultSummariesDao; import com.akto.dao.testing.WorkflowTestResultsDao; @@ -14,8 +16,13 @@ import com.akto.dto.ApiInfo; import com.akto.dto.ApiInfo.ApiInfoKey; import com.akto.dto.billing.SyncLimit; +import com.akto.dto.dependency_flow.KVPair; +import com.akto.dto.dependency_flow.ReplaceDetail; import com.akto.dto.CustomAuthType; +import com.akto.dto.DependencyNode; +import com.akto.dto.DependencyNode.ParamInfo; import com.akto.dto.OriginalHttpRequest; +import com.akto.dto.OriginalHttpResponse; import com.akto.dto.RawApi; import com.akto.dto.api_workflow.Graph; import com.akto.dto.test_editor.*; @@ -26,12 +33,14 @@ import com.akto.dto.type.RequestTemplate; import com.akto.dto.type.SingleTypeInfo; import com.akto.dto.type.URLMethods; +import com.akto.dto.type.URLMethods.Method; import com.akto.github.GithubUtils; import com.akto.log.LoggerMaker; import com.akto.log.LoggerMaker.LogDb; import com.akto.store.AuthMechanismStore; import com.akto.store.SampleMessageStore; import com.akto.store.TestingUtil; +import com.akto.test_editor.execution.Build; import com.akto.test_editor.execution.Executor; import com.akto.test_editor.execution.VariableResolver; import com.akto.test_editor.filter.data_operands_impl.ValidationResult; @@ -48,12 +57,16 @@ import com.mongodb.WriteConcern; import com.mongodb.client.model.*; +import org.apache.commons.lang3.StringUtils; +import org.bson.conversions.Bson; import org.bson.types.ObjectId; import org.json.JSONObject; import org.mortbay.util.ajax.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static com.akto.test_editor.execution.Build.modifyRequest; + import java.net.URI; import java.net.URISyntaxException; import java.util.*; @@ -651,6 +664,7 @@ public void startTestNew(ApiInfo.ApiInfoKey apiInfoKey, ObjectId testRunId, } insertResultsAndMakeIssues(testingRunResults, testRunResultSummaryId); + }else{ if(GetRunningTestsStatus.getRunningTests().getCurrentState(testRunId) != null && GetRunningTestsStatus.getRunningTests().getCurrentState(testRunId).equals(TestingRun.State.STOPPED)){ logger.info("Test stopped for id: " + testRunId.toString()); @@ -664,6 +678,140 @@ public void startTestNew(ApiInfo.ApiInfoKey apiInfoKey, ObjectId testRunId, } + private Map> cleanUpTestArtifacts(List testingRunResults, ApiInfoKey apiInfoKey, TestingUtil testingUtil, TestingRunConfig testingRunConfig) { + + Map> cleanedUpRequests = new HashMap<>(); + + for (TestingRunResult trr: testingRunResults) { + + for(GenericTestResult gtr: trr.getTestResults()) { + for(String message: gtr.getResponses()) { + if (message != null) { + String formattedMessage = null; + try { + formattedMessage = com.akto.runtime.utils.Utils.convertToSampleMessage(message); + } catch (Exception e) { + loggerMaker.errorAndAddToDb("Error while formatting message: " + e.getMessage(), LogDb.TESTING); + } + if (formattedMessage == null) { + continue; + } + RawApi rawApiToBeReplayed = RawApi.buildFromMessage(formattedMessage); + if (rawApiToBeReplayed.getResponse().getStatusCode() >= 300) { + continue; + } + switch (apiInfoKey.getMethod()) { + case POST: + Bson filterQ = DependencyNodeDao.generateChildrenFilter(apiInfoKey.getApiCollectionId(), apiInfoKey.getUrl(), apiInfoKey.getMethod()); + // TODO: Handle cases where the delete API does not have the delete method + Bson delFilterQ = Filters.and(filterQ, Filters.eq(DependencyNode.METHOD_REQ, Method.DELETE.name())); + List children = DependencyNodeDao.instance.findAll(delFilterQ); + + if (!children.isEmpty()) { + for(DependencyNode node: children) { + Map> valuesMap = Build.getValuesMap(rawApiToBeReplayed.getResponse()); + + ApiInfoKey cleanUpApiInfoKey = new ApiInfoKey(Integer.valueOf(node.getApiCollectionIdReq()), node.getUrlReq(), Method.valueOf(node.getMethodReq())); + List samples = testingUtil.getSampleMessages().get(cleanUpApiInfoKey); + if (samples == null || samples.isEmpty()) { + continue; + } else { + RawApi nextApi = RawApi.buildFromMessage(samples.get(0)); + + List kvPairs = new ArrayList<>(); + boolean fullReplace = true; + for(ParamInfo paramInfo: node.getParamInfos()) { + if (paramInfo.isHeader()) continue; + Set valuesFromResponse = valuesMap.get(paramInfo.getResponseParam()); + + if (valuesFromResponse == null || valuesFromResponse.isEmpty()) { + fullReplace = false; + break; + } + Object valueFromResponse = valuesFromResponse.iterator().next(); + + KVPair.KVType type = valueFromResponse instanceof Integer ? KVPair.KVType.INTEGER : KVPair.KVType.STRING; + KVPair kvPair = new KVPair(paramInfo.getRequestParam(), valueFromResponse.toString(), false, false, type); + kvPairs.add(kvPair); + } + + if (!fullReplace) { + continue; + } + + if (testingRunConfig != null && StringUtils.isNotBlank(testingRunConfig.getTestRoleId())) { + TestRoles role = TestRolesDao.instance.findOne(Filters.eq("_id", new ObjectId(testingRunConfig.getTestRoleId()))); + if (role != null) { + EndpointLogicalGroup endpointLogicalGroup = role.fetchEndpointLogicalGroup(); + if (endpointLogicalGroup != null && endpointLogicalGroup.getTestingEndpoints() != null && endpointLogicalGroup.getTestingEndpoints().containsApi(apiInfoKey)) { + if (role.getDefaultAuthMechanism() != null) { + loggerMaker.infoAndAddToDb("attempting to override auth ", LogDb.TESTING); + Executor.modifyAuthTokenInRawApi(role, nextApi); + } else { + loggerMaker.infoAndAddToDb("Default auth mechanism absent", LogDb.TESTING); + } + } else { + loggerMaker.infoAndAddToDb("Endpoint didn't satisfy endpoint condition for testRole", LogDb.TESTING); + } + } else { + String reason = "Test role has been deleted"; + loggerMaker.infoAndAddToDb(reason + ", going ahead with sample auth", LogDb.TESTING); + } + } + + ReplaceDetail replaceDetail = new ReplaceDetail(apiInfoKey.getApiCollectionId(), apiInfoKey.getUrl(), apiInfoKey.getMethod().name(), kvPairs); + modifyRequest(nextApi.getRequest(), replaceDetail); + loggerMaker.infoAndAddToDb("cleanUpTestArtifacts: ====REQUEST===="); + loggerMaker.infoAndAddToDb("cleanUpTestArtifacts: REQUEST: " + nextApi.getRequest().getMethod() + " " + nextApi.getRequest().getUrl() + "?" + nextApi.getRequest().getQueryParams()); + loggerMaker.infoAndAddToDb("cleanUpTestArtifacts: REQUEST headers: " + nextApi.getRequest().getHeaders()); + loggerMaker.infoAndAddToDb("cleanUpTestArtifacts: REQUEST body: " + nextApi.getRequest().getBody()); + loggerMaker.infoAndAddToDb("cleanUpTestArtifacts: ====RESPONSE===="); + try { + OriginalHttpResponse nextResponse = ApiExecutor.sendRequest(nextApi.getRequest(), true, testingRunConfig, false, new ArrayList<>()); + loggerMaker.infoAndAddToDb("cleanUpTestArtifacts: RESPONSE headers: " + nextApi.getResponse().getHeaders()); + loggerMaker.infoAndAddToDb("cleanUpTestArtifacts: RESPONSE body: " + nextResponse.getBody()); + loggerMaker.infoAndAddToDb("cleanUpTestArtifacts: RESPONSE status code: " + nextResponse.getStatusCode()); + + if(nextResponse.getStatusCode() < 300) { + if(cleanedUpRequests.get(apiInfoKey) != null) { + cleanedUpRequests.get(apiInfoKey).add(cleanUpApiInfoKey); + } else { + cleanedUpRequests.put(apiInfoKey, Arrays.asList(cleanUpApiInfoKey)); + } + } + + } catch (Exception e) { + e.printStackTrace(); + System.out.println("exception in sending api request for cleanup" + e.getMessage()); + } + } + } + } + + break; + // TODO: implement for other methods + case PUT: + + break; + case PATCH: + + break; + case DELETE: + + break; + + case GET: + default: + break; + } + } + } + } + } + + return cleanedUpRequests; + } + public boolean applyRunOnceCheck(ApiInfoKey apiInfoKey, TestConfig testConfig, ConcurrentHashMap subCategoryEndpointMap, Map apiInfoKeyToHostMap, String testSubCategory) { if (testConfig.getStrategy() == null || testConfig.getStrategy().getRunOnce() == null) { @@ -776,11 +924,21 @@ public TestingRunResult runTestNew(ApiInfo.ApiInfoKey apiInfoKey, ObjectId testR int confidencePercentage = 100; - return new TestingRunResult( - testRunId, apiInfoKey, testSuperType, testSubType ,testResults.getTestResults(), - vulnerable,singleTypeInfos,confidencePercentage,startTime, - endTime, testRunResultSummaryId, testResults.getWorkflowTest(), testLogs - ); + + TestingRunResult ret = new TestingRunResult( + testRunId, apiInfoKey, testSuperType, testSubType ,testResults.getTestResults(), + vulnerable,singleTypeInfos,confidencePercentage,startTime, + endTime, testRunResultSummaryId, testResults.getWorkflowTest(), testLogs); + + if (testingRunConfig!=null && testingRunConfig.getCleanUp()) { + try { + cleanUpTestArtifacts(Collections.singletonList(ret), apiInfoKey, testingUtil, testingRunConfig); + } catch(Exception e){ + loggerMaker.errorAndAddToDb("Error while cleaning up test artifacts: " + e.getMessage(), LogDb.TESTING); + } + } + + return ret; } public Confidence getConfidenceForTests(TestConfig testConfig, YamlTestTemplate template) { diff --git a/libs/dao/src/main/java/com/akto/dto/OriginalHttpResponse.java b/libs/dao/src/main/java/com/akto/dto/OriginalHttpResponse.java index 3964e35eb0..1d011082a2 100644 --- a/libs/dao/src/main/java/com/akto/dto/OriginalHttpResponse.java +++ b/libs/dao/src/main/java/com/akto/dto/OriginalHttpResponse.java @@ -36,7 +36,11 @@ public void buildFromSampleMessage(String message) { String responsePayload = (String) json.get("responsePayload"); this.body = responsePayload != null ? responsePayload.trim() : null; this.headers = OriginalHttpRequest.buildHeadersMap(json, "responseHeaders"); - this.statusCode = Integer.parseInt(json.get("statusCode").toString()); + Object obj = json.get("statusCode"); + if(obj instanceof Double){ + obj = ((Double) obj).intValue(); + } + this.statusCode = Integer.parseInt(obj.toString()); } public void addHeaderFromLine(String line) { diff --git a/libs/dao/src/main/java/com/akto/dto/testing/GenericTestResult.java b/libs/dao/src/main/java/com/akto/dto/testing/GenericTestResult.java index 7e97f1be21..4443b36d2f 100644 --- a/libs/dao/src/main/java/com/akto/dto/testing/GenericTestResult.java +++ b/libs/dao/src/main/java/com/akto/dto/testing/GenericTestResult.java @@ -1,5 +1,7 @@ package com.akto.dto.testing; +import java.util.List; + import com.akto.dto.testing.TestResult.Confidence; public abstract class GenericTestResult { @@ -43,5 +45,6 @@ public String toString() { ", confidence='" + getConfidence() + "'" + "}"; } - + + public abstract List getResponses(); } diff --git a/libs/dao/src/main/java/com/akto/dto/testing/MultiExecTestResult.java b/libs/dao/src/main/java/com/akto/dto/testing/MultiExecTestResult.java index b6fc941b40..387854cce5 100644 --- a/libs/dao/src/main/java/com/akto/dto/testing/MultiExecTestResult.java +++ b/libs/dao/src/main/java/com/akto/dto/testing/MultiExecTestResult.java @@ -91,4 +91,28 @@ public List convertToExistingTestResult(TestingRunResult test return runResults; } + @Override + public List getResponses() { + List ret = new ArrayList<>(); + + Map nodeResultMap = this.getNodeResultMap(); + for (int i=0; i < this.executionOrder.size(); i++) { + String k = this.executionOrder.get(i); + NodeResult nodeRes = nodeResultMap.get(k); + List messageList = Arrays.asList(nodeRes.getMessage().split("\"request\": ")); + + for (int j = 1; j getResponses() { + return Collections.singletonList(message); + } } diff --git a/libs/dao/src/main/java/com/akto/dto/testing/TestingRunConfig.java b/libs/dao/src/main/java/com/akto/dto/testing/TestingRunConfig.java index 637b473760..49033ce3aa 100644 --- a/libs/dao/src/main/java/com/akto/dto/testing/TestingRunConfig.java +++ b/libs/dao/src/main/java/com/akto/dto/testing/TestingRunConfig.java @@ -22,17 +22,25 @@ public class TestingRunConfig { private String overriddenTestAppUrl; private List configsAdvancedSettings; + private boolean cleanUp; public TestingRunConfig() {} + + public TestingRunConfig(int id, Map> collectionWiseApiInfoKey, + List testSubCategoryList, + ObjectId authMechanismId, String overriddenTestAppUrl, String testRoleId) { + this(id, collectionWiseApiInfoKey, testSubCategoryList, authMechanismId, overriddenTestAppUrl, testRoleId, false); + } public TestingRunConfig(int id, Map> collectionWiseApiInfoKey, List testSubCategoryList, - ObjectId authMechanismId, String overriddenTestAppUrl, String testRoleId) { + ObjectId authMechanismId, String overriddenTestAppUrl, String testRoleId, boolean cleanUp) { this.id = id; this.collectionWiseApiInfoKey = collectionWiseApiInfoKey; this.testSubCategoryList = testSubCategoryList; this.authMechanismId = authMechanismId; this.overriddenTestAppUrl = overriddenTestAppUrl; this.testRoleId = testRoleId; + this.cleanUp = cleanUp; } public List getTestSubCategoryList() { @@ -99,7 +107,10 @@ public void rebaseOn(TestingRunConfig that) { if(this.testRoleId == null) { this.testRoleId = that.testRoleId; } + + this.cleanUp = that.cleanUp; } + public String getTestRoleId() { return testRoleId; @@ -115,4 +126,13 @@ public List getConfigsAdvancedSettings() { public void setConfigsAdvancedSettings(List configsAdvancedSettings) { this.configsAdvancedSettings = configsAdvancedSettings; } + + public boolean getCleanUp() { + return this.cleanUp; + } + + public void setCleanUp(boolean cleanUp) { + this.cleanUp = cleanUp; + } + } diff --git a/libs/utils/src/main/java/com/akto/runtime/utils/Utils.java b/libs/utils/src/main/java/com/akto/runtime/utils/Utils.java index 701a39c3b9..e9b5537fbe 100644 --- a/libs/utils/src/main/java/com/akto/runtime/utils/Utils.java +++ b/libs/utils/src/main/java/com/akto/runtime/utils/Utils.java @@ -87,6 +87,45 @@ public static BasicDBObject convertOriginalReqRespToStringUtil(OriginalHttpReque return ret; } + public static String convertToSampleMessage(String message) throws Exception { + JSONObject jsonObject = JSON.parseObject(message); + JSONObject request = (JSONObject) jsonObject.get("request"); + JSONObject response = (JSONObject) jsonObject.get("response"); + + JSONObject sampleMessage = new JSONObject(); + if(request != null) { + if(request.get("body") != null) { + sampleMessage.put("requestPayload", request.get("body")); + } + if(request.get("headers") != null) { + sampleMessage.put("requestHeaders", request.get("headers")); + } + // TODO: add query params to url + if(request.get("url") != null) { + sampleMessage.put("path", request.get("url")); + } + if(request.get("method") != null) { + sampleMessage.put("method", request.get("method")); + } + if(request.get("type") != null) { + sampleMessage.put("type", request.get("type")); + } + } + if(response != null) { + if(response.get("body") != null) { + sampleMessage.put("responsePayload", response.get("body")); + } + if(response.get("headers") != null) { + sampleMessage.put("responseHeaders", response.get("headers")); + } + if(response.get("statusCode") != null) { + sampleMessage.put("statusCode", (Integer)response.getInteger("statusCode")); + } + + } + return sampleMessage.toJSONString(); + } + public static Map parseCookie(List cookieList){ Map cookieMap = new HashMap<>(); if(cookieList==null)return cookieMap;