Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test library Screen #2119

Merged
merged 16 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
package com.akto.action.test_editor;

import com.akto.DaoInit;
import com.akto.action.UserAction;
import com.akto.action.testing_issues.IssuesAction;
import com.akto.dao.AccountSettingsDao;
import com.akto.dao.AuthMechanismsDao;
import com.akto.dao.CustomAuthTypeDao;
import com.akto.dao.SampleDataDao;
import com.akto.dao.SingleTypeInfoDao;
import com.akto.dao.context.Context;
import com.akto.dao.test_editor.TestConfigYamlParser;
import com.akto.dao.test_editor.YamlTemplateDao;
Expand All @@ -16,9 +13,7 @@
import com.akto.dao.testing.TestingRunResultDao;
import com.akto.dto.AccountSettings;
import com.akto.dto.ApiInfo;
import com.akto.dto.ApiInfo.ApiInfoKey;
import com.akto.dto.CustomAuthType;
import com.akto.dto.User;
import com.akto.dto.test_editor.Category;
import com.akto.dto.test_editor.Info;
import com.akto.dto.test_editor.TestConfig;
Expand All @@ -31,12 +26,8 @@
import com.akto.dto.testing.MultiExecTestResult;
import com.akto.dto.testing.TestResult;
import com.akto.dto.testing.TestingRunConfig;
import com.akto.dto.testing.TestResult.Confidence;
import com.akto.dto.testing.TestingRunResult;
import com.akto.dto.testing.WorkflowNodeDetails;
import com.akto.dto.testing.WorkflowTestResult.NodeResult;
import com.akto.dto.traffic.SampleData;
import com.akto.dto.type.SingleTypeInfo;
import com.akto.dto.type.URLMethods;
import com.akto.listener.InitializerListener;
import com.akto.log.LoggerMaker;
Expand All @@ -50,13 +41,11 @@
import com.akto.util.Constants;
import com.akto.util.enums.GlobalEnums;
import com.akto.util.enums.GlobalEnums.Severity;
import com.akto.util.enums.GlobalEnums.YamlTemplateSource;
import com.akto.utils.GithubSync;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.mongodb.BasicDBObject;
import com.mongodb.ConnectionString;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Updates;
Expand All @@ -67,9 +56,6 @@
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
Expand Down Expand Up @@ -535,33 +521,30 @@ public String fetchCustomTestsCount(){
return SUCCESS.toUpperCase();
}

public static void main(String[] args) throws Exception {
DaoInit.init(new ConnectionString("mongodb://localhost:27017/admini"));
Context.accountId.set(1_000_000);
String folderPath = "/Users/shivamrawat/akto_code_openSource/akto/libs/dao/src/main/java/com/akto/dao/test_editor/inbuilt_test_yaml_files";
Path dir = Paths.get(folderPath);
List<String> files = new ArrayList<>();
Files.walk(dir).forEach(path -> showFile(path.toFile(), files));
for (String filePath : files) {
logger.info(filePath);
List<String> lines = Files.readAllLines(Paths.get(filePath));
String content = String.join("\n", lines);
SaveTestEditorAction saveTestEditorAction = new SaveTestEditorAction();
saveTestEditorAction.setContent(content);
Map<String,Object> session = new HashMap<>();
User user = new User();
user.setLogin("AKTO");
session.put("user",user);
saveTestEditorAction.setSession(session);
String success = SUCCESS.toUpperCase();
logger.info(success);
public String fetchTestContent(){
if (originalTestId == null || originalTestId.trim().isEmpty()) {
addActionError("TestId cannot be null or empty");
return ERROR.toUpperCase();
}

YamlTemplate template = YamlTemplateDao.instance.findOne(Filters.eq(Constants.ID, originalTestId), Projections.include(YamlTemplate.CONTENT));
if (template == null) {
addActionError("test not found");
return ERROR.toUpperCase();
}

this.content = template.getContent();
return SUCCESS.toUpperCase();
}

public void setContent(String content) {
this.content = content;
}

public String getContent() {
return content;
}

public String getTestingRunHexId() {
return testingRunHexId;
}
Expand Down
22 changes: 22 additions & 0 deletions apps/dashboard/src/main/resources/struts.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6380,6 +6380,28 @@
</result>
</action>

<action name="api/fetchTestContent" class="com.akto.action.test_editor.SaveTestEditorAction" method="fetchTestContent">
<interceptor-ref name="json"/>
<interceptor-ref name="defaultStack" />
<interceptor-ref name="roleAccessInterceptor">
<param name="featureLabel">TEST_EDITOR</param>
<param name="accessType">READ</param>
</interceptor-ref>

<result name="FORBIDDEN" type="json">
<param name="statusCode">403</param>
<param name="ignoreHierarchy">false</param>
<param name="includeProperties">^actionErrors.*</param>
</result>
<result name="SUCCESS" type="json">
<param name="root">content</param>
</result>
<result name="ERROR" type="json">
<param name="statusCode">422</param>
<param name="ignoreHierarchy">false</param>
<param name="includeProperties">^actionErrors.*</param>
</result>
</action>

<action name="api/toggleDebugLogsFeature" class="com.akto.action.AdminSettingsAction" method="toggleDebugLogsFeature">
<interceptor-ref name="json"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,64 @@ public void testSetTestInactive() {
assertEquals(true, template.getInactive());
}

@Test
public void testFetchTestContent() {
SaveTestEditorAction action = new SaveTestEditorAction();
saveTest(action);
action.setOriginalTestId("REMOVE_TOKENS");

String result = action.fetchTestContent();
assertEquals("SUCCESS", result);
assertEquals(outputContent, action.getContent());

action.setOriginalTestId(null);
assertEquals("ERROR", action.fetchTestContent());

action.setOriginalTestId("NON_EXISTENT_TEST");
assertEquals("ERROR", action.fetchTestContent());

action.setOriginalTestId("");
assertEquals("ERROR", action.fetchTestContent());
}

private final String outputContent = "---\n" +
"id: REMOVE_TOKENS\n" +
"info:\n" +
" name: Broken Authentication by removing auth token\n" +
" description: API doesn't validate the authenticity of token. Attacker can remove the auth token and access the endpoint.\n" +
" details: |\n" +
" \"The endpoint appears to be vulnerable to broken authentication attack. The original request was replayed by removing victim's <b>auth</b> token. The server responded with 2XX success codes.<br>\" \"<b>Background:</b> Authentication is the process of attempting to verify the digital identity of the sender of a communication. Testing the authentication schema means understanding how the authentication process works and using that information to circumvent the authentication mechanism. While most applications require authentication to gain access to private information or to execute tasks, not every authentication method is able to provide adequate security. Negligence, ignorance, or simple understatement of security threats often result in authentication schemes that can be bypassed by simply skipping the log in page and directly calling an internal page that is supposed to be accessed only after authentication has been performed.\"\n" +
" impact: \"Broken User authentication is a serious vulnerability. Attackers can gain control to other users’ accounts in the system, read their personal data, and perform sensitive actions on their behalf, like money transactions and sending personal messages.\"\n" +
" category:\n" +
" name: NO_AUTH\n" +
" shortName: Broken Authentication\n" +
" displayName: Broken User Authentication (BUA)\n" +
" subCategory: REMOVE_TOKENS\n" +
" severity: HIGH\n" +
" tags:\n" +
" - Business logic\n" +
" - OWASP top 10\n" +
" - HackerOne top 10\n" +
" references:\n" +
" - https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/\n" +
" - https://github.com/OWASP/API-Security/blob/master/2019/en/src/0xa2-broken-user-authentication.md\n" +
" - https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html\n" +
" - https://cwe.mitre.org/data/definitions/798.html\n" +
"api_selection_filters:\n" +
" response_code:\n" +
" gte: 200\n" +
" lt: 300\n" +
"execute:\n" +
" type: single\n" +
" requests:\n" +
" - req:\n" +
" - remove_auth_header: true\n" +
"validate:\n" +
" response_code:\n" +
" gte: 200\n" +
" lt: 300\n";


private final static String content = "id: REMOVE_TOKENS\n" +
"info:\n" +
" name: \"Broken Authentication by removing auth token\"\n" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
AnalyticsFilledMinor,
ReportFilledMinor,
DiamondAlertMinor,
FinancesMinor,
} from "@shopify/polaris-icons";
import {useLocation, useNavigate} from "react-router-dom";

Expand Down Expand Up @@ -196,18 +197,39 @@ export default function LeftNav() {
key: "4",
},
{
url: "#",
label: (
<Text variant="bodyMd" fontWeight="medium">
Test Editor
Test library
</Text>
),
icon: FileFilledMinor,
icon: FinancesMinor,
onClick: () => {
handleSelect("dashboard_test_editor");
navigate("/dashboard/test-editor/REMOVE_TOKENS");
handleSelect("dashboard_test_library_tests");
navigate("/dashboard/test-library/tests");
setActive("normal");
},
selected: leftNavSelected.includes("dashboard_test_editor"),
selected: leftNavSelected.includes("_test_library"),
subNavigationItems: [
{
label: "Tests",
onClick: () => {
navigate("/dashboard/test-library/tests");
handleSelect("dashboard_test_library_tests");
setActive("active");
},
selected: leftNavSelected === "dashboard_test_library_tests",
},
{
label: "Editor",
onClick: () => {
navigate("/dashboard/test-editor");
handleSelect("dashboard_test_library_test_editor");
setActive("active");
},
selected: leftNavSelected === "dashboard_test_library_test_editor",
},
],
key: "5",
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,21 @@ import { Badge, Box, HorizontalStack } from '@shopify/polaris'
import React from 'react'
import TooltipText from './TooltipText'

function ShowListInBadge({itemsArr, maxWidth, status, maxItems, itemWidth}) {
function ShowListInBadge({itemsArr, maxWidth, status, maxItems, itemWidth, useBadge}) {
return (
<Box maxWidth={maxWidth}>
<HorizontalStack gap={"1"} wrap={false}>
{itemsArr.slice(0,maxItems).map((item, index) => {
return(
(useBadge === undefined || useBadge) ?
<Badge key={index + item} size="medium" status={status}>
<Box maxWidth={itemWidth || maxWidth}>
<TooltipText tooltip={item} text={item} />
</Box>
</Badge>
</Badge>:
<Box maxWidth={itemWidth || maxWidth}>
{item}
</Box>
)
})}
{(itemsArr.length - maxItems) > 0 ? <Badge status={status} size="medium">+ {itemsArr.length - maxItems}</Badge> : null}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const TestEditor = () => {


const handleExit = () => {
navigate("/dashboard/testing")
navigate("/dashboard/test-library/tests")
setActive('active')
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ const testEditorRequests = {
}
})
},
async fetchTestContent(testId) {
return await request({
url: '/api/fetchTestContent',
method: 'post',
data: {
originalTestId: testId,
}
})
}

}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { Box, Button, HorizontalStack, VerticalStack, Text, Badge, Tooltip } from "@shopify/polaris";
import FlyLayout from "../../../components/layouts/FlyLayout";
import { FileMinor } from "@shopify/polaris-icons"
import { useEffect, useRef, useState } from "react";
import observeFunc from "../../observe/transform"
import YamlComponent from "./YamlComponent";
import func from "../../../../../util/func";
import api from "../api";

function TestsFlyLayout({ data, showDetails, setShowDetails }) {

const TitleComponent = () => {
return (
<Box paddingInlineStart={4} paddingInlineEnd={4} paddingBlockEnd={4}>
<HorizontalStack align="space-between" wrap={false}>
<Box width="80%">
<VerticalStack gap="2">
<div style={{ display: 'flex', gap: '8px' }} className='test-title'>
<Text truncate variant="headingSm" alignment="start">{data?.name}</Text>
{data?.severityText ? (
<Box className={`badge-wrapper-${data?.severityText.toUpperCase()}`}>
<Badge size="small" status={observeFunc.getColor(data.severityText)}>
{func.toSentenceCase(data?.severityText.replace(/_/g, " "))}
</Badge>
</Box>
) : null}
</div>
<HorizontalStack align="start" gap="2">
<Text color="subdued" variant="bodySm">{data?.category}</Text>
<Box width="1px" borderColor="border-subdued" borderInlineStartWidth="1" minHeight='16px' />
<Text color="subdued" variant="bodySm">{`By ${data?.author}`}</Text>
</HorizontalStack>
</VerticalStack>
</Box>
<Tooltip content="Open in Test Editor">
<Button icon={FileMinor} onClick={openEditor}></Button>
</Tooltip>
</HorizontalStack>
</Box>
);
};

const [testContent, setTestContent] = useState("");
useEffect(() => {
if(!data || !data.value) return;
api.fetchTestContent(data?.value).then((resp) => {
setTestContent(resp);
})
},[data]);

const ref = useRef(null)

const onClickFunc = () => {
func.copyToClipboard(data?.content, ref,"Test details copied to clipboard successfully!")
}

const openEditor = () => {
window.open(`${window.location.origin}/dashboard/test-editor/${data?.value}`);
}

const currentComponents = [
<TitleComponent />,
<Box paddingBlockStart={5} paddingInlineEnd={4} paddingInlineStart={4}>

<YamlComponent onClickFunc={onClickFunc} dataString={testContent} language="text" minHeight="70vh"></YamlComponent>

</Box>
]

return <FlyLayout
title={"Test Details"}
show={showDetails}
setShow={setShowDetails}
components={currentComponents}
loading={false}
showDivider={true}
newComp={true}
isHandleClose={false}
/>
}



export default TestsFlyLayout;
Loading
Loading