Skip to content

Commit

Permalink
Merge pull request #1724 from akto-api-security/fix/test_related_bugs
Browse files Browse the repository at this point in the history
Fix/test related bugs
  • Loading branch information
Ark2307 authored Nov 14, 2024
2 parents c4117a8 + 6efd7db commit fde99d3
Show file tree
Hide file tree
Showing 14 changed files with 88 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export default function LeftNav(){
label: <Text variant="bodyMd" fontWeight="medium" color={leftNavSelected.includes("testing") ? (active === 'active' ? "subdued" : ""): ""}>Testing</Text>,
icon: MarketingFilledMinor,
onClick: ()=>{
navigate('/dashboard/testing')
navigate('/dashboard/testing/')
handleSelect('dashboard_testing')
setActive("normal")
},
Expand All @@ -105,7 +105,7 @@ export default function LeftNav(){
{
label: 'Results',
onClick: ()=>{
navigate('/dashboard/testing')
navigate('/dashboard/testing/')
handleSelect('dashboard_testing')
setActive('active')
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Autocomplete, Avatar, Checkbox, Icon, TextContainer } from '@shopify/polaris';
import { Autocomplete, Avatar, Checkbox, HorizontalStack, Icon, Link, Text, TextContainer } from '@shopify/polaris';
import { SearchMinor, ChevronDownMinor } from '@shopify/polaris-icons';
import React, { useState, useCallback, useEffect } from 'react';
import func from "@/util/func";
Expand Down Expand Up @@ -174,7 +174,7 @@ function DropdownSearch(props) {
);

const showSelectAll = (allowMultiple && optionsList.length > 5)
const checkboxLabel = checked ? "Deselect all" : "Select all"
const checkboxLabel = checked ? <Link removeUnderline>Deselect all</Link> : <Link removeUnderline>Select all</Link>

const emptyState = (
<React.Fragment>
Expand All @@ -196,7 +196,7 @@ function DropdownSearch(props) {
textField={textField}
preferredPosition='below'
{...(showSelectAll ? {actionBefore:{
content:(<Checkbox label={checkboxLabel} checked={checked} onChange={() => selectAllFunc()}/>),
content: checkboxLabel,
onAction: () => selectAllFunc(),
}} : {})}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,10 @@ const transform = {
})
}
finalData = finalData.split("\n").sort().join("\n");
return (localFirstLine + "\n\n" + finalData + "\n\n" + this.formatJson(payLoad))
const isPayloadEmpty = Object.keys(payLoad).length === 0
return (localFirstLine + "\n" + finalData + (finalData.trim().length === 0 || isPayloadEmpty ? "\n" : "\n\n") + (!isPayloadEmpty ? this.formatJson(payLoad) : ''))
}
return (data?.firstLine ? data?.firstLine + "\n\n" : "") + (data?.json ? this.formatJson(data.json) : "");
return (data?.firstLine ? data?.firstLine + "\n" : "") + (data?.json && Object.keys(data?.json).length > 0 ? this.formatJson(data.json) : "");
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,12 @@ function GithubServerTable(props) {
const setFiltersMap = PersistStore(state => state.setFiltersMap)
const tableInitialState = PersistStore(state => state.tableInitialState)
const setTableInitialState = PersistStore(state => state.setTableInitialState)
const tableSelectedMap = PersistStore(state => state.tableSelectedTab)
const setTableSelectedMap = PersistStore(state => state.setTableSelectedTab)
const currentPageKey = props?.filterStateUrl || (window.location.pathname + "/" + window.location.hash)
const pageFiltersMap = filtersMap[currentPageKey];

const { selectedItems, selectItems } = useTable();
const { selectedItems, selectItems, applyFilter } = useTable();

const handleRemoveAppliedFilter = (key) => {
let temp = appliedFilters
Expand Down Expand Up @@ -73,7 +75,6 @@ function GithubServerTable(props) {
const pageLimit = props?.pageLimit || 20;
const [appliedFilters, setAppliedFilters] = useState(initialStateFilters);
const [queryValue, setQueryValue] = useState('');
const { applyFilter } = useTable()
const [fullDataIds, setFullDataIds] = useState([])

const [sortableColumns, setSortableColumns] = useState([])
Expand Down Expand Up @@ -132,6 +133,11 @@ function GithubServerTable(props) {
const handleSelectedTab = (x) => {
const tableTabs = props.tableTabs ? props.tableTabs : props.tabs
if(tableTabs){
const id = tableTabs[x]?.id;
setTableSelectedMap({
...tableSelectedMap,
[window.location.pathname]: id
})
const primitivePath = window.location.origin + window.location.pathname + window.location?.search
const newUrl = primitivePath + "#" + tableTabs[x].id
window.history.replaceState(null, null, newUrl)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ export const TableContextProvider = ({ children }) => {
}
});
};
const tableSelectedTab = (items) => {
dispatch({
type: "TABLE_SELECTED_TAB",
payload: {
tableSelectedTab: items
}
})
}

const selectItems = (items) => {
dispatch({
Expand All @@ -38,7 +46,8 @@ export const TableContextProvider = ({ children }) => {
selectItems,
selectedItems: state.selectedItems,
openedRows: state.openedRows,
modifyOpenedLevels
modifyOpenedLevels,
tableSelectedTab
};
return <TableContext.Provider value={value}>{children}</TableContext.Provider>;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import TableStore from "./TableStore";
const tableInitialState = PersistStore.getState().tableInitialState[window.location.pathname + "/" + window.location.hash] || 0
const selectedItems = TableStore.getState().selectedItems
const openedRows = TableStore.getState().openedLevels
const tableSelectedTab = PersistStore.getState().tableSelectedTab
export const initialState = {
tabsInfo : tableInitialState,
selectedItems: selectedItems,
openedRows: openedRows
openedRows: openedRows,
tableSelectedTab: tableSelectedTab
}

const tableReducer = (state, action) =>{
Expand All @@ -17,6 +19,12 @@ const tableReducer = (state, action) =>{
...state,
tabsInfo: payload.tabsInfo,
};
case "TABLE_SELECTED_TAB": {
return {
...state,
tableSelectedTab: payload.tableSelectedTab
}
}
case "SELECT_ROW_ITEMS": {
return {
...state,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,6 @@ function HomeDashboard() {

// Prepare the result array with values from 5 to 0
const result = [
{ "badgeValue": 5, "progressValue": "0%", "text": 0, "topColor": "#E45357", "backgroundColor": "#FFDCDD", "badgeColor": "critical" },
{ "badgeValue": 4, "progressValue": "0%", "text": 0, "topColor": "#EF864C", "backgroundColor": "#FFD9C4", "badgeColor": "attention" },
{ "badgeValue": 3, "progressValue": "0%", "text": 0, "topColor": "#F6C564", "backgroundColor": "#FFF1D4", "badgeColor": "warning" },
{ "badgeValue": 2, "progressValue": "0%", "text": 0, "topColor": "#F5D8A1", "backgroundColor": "#FFF6E6", "badgeColor": "info" },
Expand All @@ -366,7 +365,7 @@ function HomeDashboard() {

// Update progress and text based on riskScoreMap values
Object.keys(apiStats.riskScoreMap).forEach((key) => {
const badgeIndex = 5 - parseInt(key, 10);
const badgeIndex = 4 - parseInt(key, 10);
const value = apiStats.riskScoreMap[key];
result[badgeIndex].text = value ? value : 0;
if (!totalApisCount || totalApisCount === 0) {
Expand Down Expand Up @@ -451,11 +450,6 @@ function HomeDashboard() {
const countMap = apiStats ? apiStats.criticalMap : {};

const result = {
"Critical": {
"text": countMap.CRITICAL || 0,
"color": "#E45357",
"filterKey": "Critical",
},
"High": {
"text": countMap.HIGH || 0,
"color": "#EF864C",
Expand Down Expand Up @@ -514,7 +508,7 @@ function HomeDashboard() {
</div>
}
title="Vulnerable APIs by Severity"
titleToolTip="Breakdown of vulnerable APIs categorized by severity level (Critical, High, Medium, Low). Click to see details for each category."
titleToolTip="Breakdown of vulnerable APIs categorized by severity level (High, Medium, Low). Click to see details for each category."
linkText="Fix critical issues"
linkUrl="/dashboard/issues"
/> : <EmptyCard title="Vulnerable APIs by Severity" subTitleComponent={showTestingComponents ? <Text alignment='center' color='subdued'>No vulnerable APIs found</Text>: runTestEmptyCardComponent}/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,14 @@ function AllSensitiveData() {
})
const [countMap, setCountMap] = useState({})
const [severityCountMap, setSeverityCountMap] = useState([])

const [selectedTab, setSelectedTab] = useState("enabled")
const [selected, setSelected] = useState(1)
const [loading, setLoading] = useState(false)

const definedTableTabs = ["All", "Enabled", "Disabled"]
const tableSelectedTab = PersistStore.getState().tableSelectedTab[window.location.pathname]
const initialSelectedTab = tableSelectedTab || "enabled"
const [selectedTab, setSelectedTab] = useState(initialSelectedTab)
let initialTabIdx = func.getTableTabIndexById(1, definedTableTabs, initialSelectedTab)
const [selected, setSelected] = useState(initialTabIdx)

const { tabsInfo } = useTable()
const tableCountObj = func.getTabsCount(definedTableTabs, data)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,8 @@ function ApiCollections() {
const [data, setData] = useState({'hostname':[]})
const [active, setActive] = useState(false);
const [loading, setLoading] = useState(false)
const [selectedTab, setSelectedTab] = useState("hostname")
const [selected, setSelected] = useState(1)


const [summaryData, setSummaryData] = useState({totalEndpoints:0 , totalTestedEndpoints: 0, totalSensitiveEndpoints: 0, totalCriticalEndpoints: 0})
const [hasUsageEndpoints, setHasUsageEndpoints] = useState(true)
const [envTypeMap, setEnvTypeMap] = useState({})
Expand All @@ -211,6 +211,12 @@ function ApiCollections() {
const definedTableTabs = ['All', 'Hostname', 'Groups', 'Custom', 'Deactivated']

const { tabsInfo, selectItems } = useTable()
const tableSelectedTab = PersistStore.getState().tableSelectedTab[window.location.pathname]
const initialSelectedTab = tableSelectedTab || "hostname";
const [selectedTab, setSelectedTab] = useState(initialSelectedTab)
let initialTabIdx = func.getTableTabIndexById(1, definedTableTabs, initialSelectedTab)
const [selected, setSelected] = useState(initialTabIdx)

const tableCountObj = func.getTabsCount(definedTableTabs, data)
const tableTabs = func.getTableTabsContent(definedTableTabs, tableCountObj, setSelectedTab, selectedTab, tabsInfo)

Expand Down Expand Up @@ -273,7 +279,7 @@ function ApiCollections() {
res.groups = dataObj.prettify.filter((c) => c.type === "API_GROUP" && !c.deactivated)
res.custom = res.all.filter(x => !res.hostname.includes(x) && !x.deactivated && !res.groups.includes(x));
setData(res);
if (res.hostname.length === 0) {
if (res.hostname.length === 0 && (tableSelectedTab === undefined || tableSelectedTab.length === 0)) {
setTimeout(() => {
setSelectedTab("custom");
setSelected(3);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,6 @@ function TestRolesPage(){

return [{
items: [
{
content: 'Edit',
onAction: () => navigate("details", {state: {
name: item.name,
endpoints: item.endpointLogicalGroup.testingEndpoints,
authWithCondList: item.authWithCondList
}})
},
{
content: 'Access matrix',
onAction: () => navigate("access-matrix", {state: {
Expand Down Expand Up @@ -90,6 +82,12 @@ function TestRolesPage(){
fetchData();
}, [])

const onTestRoleClick = (item) => navigate("details", {state: {
name: item.name,
endpoints: item.endpointLogicalGroup.testingEndpoints,
authWithCondList: item.authWithCondList
}})

return (
<PageWithMultipleCards
title={"Test roles"}
Expand All @@ -114,6 +112,7 @@ function TestRolesPage(){
resourceName={resourceName}
headers={headers}
loading={loading}
onRowClick={onTestRoleClick}
getActions={getActions}
hasRowActions={true}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,21 @@ const endTimestamp = getTimeEpoch("until") + 86400


const [loading, setLoading] = useState(true);
const [currentTab, setCurrentTab] = useState("one_time");
const [updateTable, setUpdateTable] = useState(false);
const [countMap, setCountMap] = useState({});
const [selected, setSelected] = useState(1);

const definedTableTabs = ['All', 'One time', 'Continuous Testing', 'Scheduled', 'CI/CD']
const initialCount = [countMap['allTestRuns'], countMap['oneTime'], countMap['continuous'], countMap['scheduled'], countMap['cicd']]

const { tabsInfo } = useTable()
const tableSelectedTab = PersistStore.getState().tableSelectedTab[window.location.pathname]
const initialSelectedTab = tableSelectedTab || "one_time";
const [currentTab, setCurrentTab] = useState(initialSelectedTab);
let initialTabIdx = func.getTableTabIndexById(1, definedTableTabs, initialSelectedTab)
const [selected, setSelected] = useState(initialTabIdx)

const tableCountObj = func.getTabsCount(definedTableTabs, {}, initialCount)
const tableTabs = func.getTableTabsContent(definedTableTabs, tableCountObj, setCurrentTab, currentTab, tabsInfo)

const [severityCountMap, setSeverityCountMap] = useState({
HIGH: {text : 0, color: func.getColorForCharts("HIGH")},
Expand Down Expand Up @@ -246,13 +257,6 @@ function processData(testingRuns, latestTestingRunResultSummaries, cicd){
})
}

const definedTableTabs = ['All', 'One time', 'Continuous Testing', 'Scheduled', 'CI/CD']
const initialCount = [countMap['allTestRuns'], countMap['oneTime'], countMap['continuous'], countMap['scheduled'], countMap['cicd']]

const { tabsInfo } = useTable()
const tableCountObj = func.getTabsCount(definedTableTabs, {}, initialCount)
const tableTabs = func.getTableTabsContent(definedTableTabs, tableCountObj, setCurrentTab, currentTab, tabsInfo)

const fetchTotalCount = () =>{
setLoading(true)
api.getUserTestRuns().then((resp)=> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,10 @@ const transform = {
obj['name'] = data.name || "Test"
obj['number_of_tests'] = data.testIdConfig == 1 ? "-" : getTestsInfo(testingRunResultSummary?.testResultsCount, state)
obj['run_type'] = getTestingRunType(data, testingRunResultSummary, cicd);
obj['run_time_epoch'] = Math.max(data.scheduleTimestamp,data.endTimestamp)
obj['run_time_epoch'] = Math.max(data.scheduleTimestamp, (cicd ? testingRunResultSummary.endTimestamp : data.endTimestamp))
obj['scheduleTimestamp'] = data.scheduleTimestamp
obj['pickedUpTimestamp'] = data.pickedUpTimestamp
obj['run_time'] = getRuntime(data.scheduleTimestamp ,data.endTimestamp, state)
obj['run_time'] = getRuntime(data.scheduleTimestamp , (cicd ? testingRunResultSummary.endTimestamp : data.endTimestamp), state)
obj['severity'] = func.getSeverity(testingRunResultSummary.countIssues)
obj['total_severity'] = getTotalSeverity(testingRunResultSummary.countIssues);
obj['severityStatus'] = func.getSeverityStatus(testingRunResultSummary.countIssues)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ const initialState = {
filtersMap:{},
tableInitialState: {},
trafficAlerts: [],
sendEventOnLogin: false
sendEventOnLogin: false,
tableSelectedTab: {}
};

let persistStore = (set) => ({
Expand All @@ -47,6 +48,7 @@ let persistStore = (set) => ({
setFiltersMap: (filtersMap) => set({ filtersMap }),
setTableInitialState: (tableInitialState) => set({ tableInitialState }),
setTrafficAlerts: (trafficAlerts) =>set ({trafficAlerts}),
setTableSelectedTab: (tableSelectedTab) => set({tableSelectedTab}),

resetAll: () => set(initialState), // Reset function
})
Expand Down
12 changes: 12 additions & 0 deletions apps/dashboard/web/polaris_web/web/src/util/func.js
Original file line number Diff line number Diff line change
Expand Up @@ -1709,6 +1709,18 @@ showConfirmationModal(modalContent, primaryActionContent, primaryAction) {
subcategory["content"] = ""
},

getTableTabIndexById(defaultTabIndex, definedTableTabs, selectedTabId) {
let initialIdx = defaultTabIndex;
for(let x = 0; x < definedTableTabs.length; x++) {
const tempId = func.getKeyFromName(definedTableTabs[x]);
if (tempId === selectedTabId) {
initialIdx = x;
break;
}
}
return initialIdx
},

}

export default func

0 comments on commit fde99d3

Please sign in to comment.