Skip to content

Commit

Permalink
Merge pull request #1153 from akto-api-security/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
shivam-rawat-akto authored May 29, 2024
2 parents 56c302b + f52ff7a commit f1ac782
Show file tree
Hide file tree
Showing 46 changed files with 543 additions and 267 deletions.
3 changes: 3 additions & 0 deletions apps/dashboard/src/main/java/com/akto/action/HomeAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ public String execute() {
if (GithubLogin.getClientId() != null) {
servletRequest.setAttribute("githubClientId", new String(Base64.getEncoder().encode(GithubLogin.getClientId().getBytes())));
}
if (GithubLogin.getGithubUrl() != null) {
servletRequest.setAttribute("githubUrl", GithubLogin.getGithubUrl());
}
if(OktaLogin.getAuthorisationUrl() != null){
servletRequest.setAttribute("oktaAuthUrl", new String(Base64.getEncoder().encode(OktaLogin.getAuthorisationUrl().getBytes())));
}
Expand Down
43 changes: 40 additions & 3 deletions apps/dashboard/src/main/java/com/akto/action/SignupAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -434,35 +434,72 @@ public String registerViaEmail() {
}

public String registerViaGithub() {
logger.info("registerViaGithub");
if (!DashboardMode.isOnPremDeployment()) return Action.ERROR.toUpperCase();
GithubLogin ghLoginInstance = GithubLogin.getInstance();
if (ghLoginInstance == null) {
return ERROR.toUpperCase();
}
logger.info("Found github instance");
Config.GithubConfig githubConfig = GithubLogin.getInstance().getGithubConfig();
if (githubConfig == null) {
return ERROR.toUpperCase();
}
logger.info("Found github configuration");
BasicDBObject params = new BasicDBObject();
params.put("client_id", githubConfig.getClientId());
params.put("client_secret", githubConfig.getClientSecret());
params.put("code", this.code);
logger.info("Github code length: {}", this.code.length());
try {
Map<String,Object> tokenData = CustomHttpRequest.postRequest("https://github.com/login/oauth/access_token", params);
String githubUrl = githubConfig.getGithubUrl();
if (StringUtils.isEmpty(githubUrl)) githubUrl = "https://github.com";

String githubApiUrl = githubConfig.getGithubApiUrl();
if (StringUtils.isEmpty(githubApiUrl)) githubApiUrl = "https://api.github.com";

if (githubApiUrl.endsWith("/")) githubApiUrl = githubApiUrl.substring(0, githubApiUrl.length() - 1);
if (githubUrl.endsWith("/")) githubUrl = githubUrl.substring(0, githubUrl.length() - 1);

logger.info("Github URL: {}", githubUrl);
logger.info("Github API URL: {}", githubApiUrl);

Map<String,Object> tokenData = CustomHttpRequest.postRequest(githubUrl + "/login/oauth/access_token", params);
logger.info("Post request to {} success", githubUrl);

String accessToken = tokenData.get("access_token").toString();
if (StringUtils.isEmpty(accessToken)){
logger.info("Access token empty");
} else {
logger.info("Access token length: {}", accessToken.length());
}

String refreshToken = tokenData.getOrDefault("refresh_token", "").toString();
int refreshTokenExpiry = Integer.parseInt(tokenData.getOrDefault("refresh_token_expires_in", "0").toString());
Map<String,Object> userData = CustomHttpRequest.getRequest("https://api.github.com/user", "Bearer " + accessToken);
if (StringUtils.isEmpty(refreshToken)){
logger.info("Refresh token empty");
} else {
logger.info("Refresh token length: {}", refreshToken.length());
}

int refreshTokenExpiry = (int) Double.parseDouble(tokenData.getOrDefault("refresh_token_expires_in", "0").toString());
Map<String,Object> userData = CustomHttpRequest.getRequest(githubApiUrl + "/user", "Bearer " + accessToken);
logger.info("Get request to {} success", githubApiUrl);
String company = "sso";
String username = userData.get("login").toString() + "@" + company;
logger.info("username {}", username);
SignupInfo.GithubSignupInfo ghSignupInfo = new SignupInfo.GithubSignupInfo(accessToken, refreshToken, refreshTokenExpiry, username);
shouldLogin = "true";
createUserAndRedirect(username, username, ghSignupInfo, 1000000, Config.ConfigType.GITHUB.toString());
code = "";
logger.info("Executed registerViaGithub");

} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
return ERROR.toUpperCase();
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
return SUCCESS.toUpperCase();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,6 @@ public String stopAllTests() {
}

public String stopTest() {
// stop only scheduled and running tests
Bson filter = Filters.or(
Filters.eq(TestingRun.STATE, State.SCHEDULED),
Filters.eq(TestingRun.STATE, State.RUNNING));
Expand All @@ -701,6 +700,11 @@ public String stopTest() {
TestingRunDao.instance.updateOne(
Filters.and(filter, Filters.eq(Constants.ID, testingId)),
Updates.set(TestingRun.STATE, State.STOPPED));
Bson testingSummaryFilter = Filters.and(
Filters.eq(TestingRunResultSummary.TESTING_RUN_ID,testingId),
filter
);
TestingRunResultSummariesDao.instance.updateManyNoUpsert(testingSummaryFilter, Updates.set(TestingRunResultSummary.STATE, State.STOPPED));
return SUCCESS.toUpperCase();
} catch (Exception e) {
loggerMaker.errorAndAddToDb(e, "ERROR: Stop test failed - " + e.toString(), LogDb.DASHBOARD);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,13 @@ public String fetchTestingRunResult() {
Filters.eq(TestingRunResult.API_INFO_KEY, issue.getId().getApiInfoKey())
);
testingRunResult = TestingRunResultDao.instance.findOne(filterForRunResult);
if (issue.isUnread()) {
logger.info("Issue id from db to be marked as read " + issueId);
Bson update = Updates.combine(Updates.set(TestingRunIssues.UNREAD, false),
Updates.set(TestingRunIssues.LAST_UPDATED, Context.now()));
TestingRunIssues updatedIssue = TestingRunIssuesDao.instance.updateOneNoUpsert(Filters.eq(ID, issueId), update);
issueId = updatedIssue.getId();
}
return SUCCESS.toUpperCase();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import okhttp3.OkHttpClient;

import org.apache.commons.lang3.StringUtils;
import org.kohsuke.github.GitHub;
import org.kohsuke.github.GitHubBuilder;
import org.kohsuke.github.connector.GitHubConnector;
Expand Down Expand Up @@ -123,6 +124,8 @@ public String addGithubAppSecretKey() {
private String githubAppSecretKey;
private String githubAppId;
private String testingRunSummaryHexId;
private String githubUrl;
private String githubApiUrl;
public String addGithubSso() {

if(!DashboardMode.isOnPremDeployment()){
Expand All @@ -146,6 +149,8 @@ public String addGithubSso() {
Config.GithubConfig ghConfig = new Config.GithubConfig();
ghConfig.setClientId(githubClientId);
ghConfig.setClientSecret(githubClientSecret);
if (!StringUtils.isEmpty(githubUrl)) ghConfig.setGithubUrl(githubUrl);
if (!StringUtils.isEmpty(githubApiUrl)) ghConfig.setGithubApiUrl(githubApiUrl);

ConfigsDao.instance.insertOne(ghConfig);

Expand All @@ -168,6 +173,8 @@ public String execute() throws Exception {

if (githubConfig != null) {
this.githubClientId = githubConfig.getClientId();
this.githubApiUrl = githubConfig.getGithubApiUrl();
this.githubUrl = githubConfig.getGithubUrl();
}

return SUCCESS.toUpperCase();
Expand Down Expand Up @@ -208,4 +215,20 @@ public String getGithubAppId() {
public void setGithubAppId(String githubAppId) {
this.githubAppId = githubAppId;
}

public void setGithubUrl(String githubUrl) {
this.githubUrl = githubUrl;
}

public void setGithubApiUrl(String githubApiUrl) {
this.githubApiUrl = githubApiUrl;
}

public String getGithubUrl() {
return githubUrl;
}

public String getGithubApiUrl() {
return githubApiUrl;
}
}
12 changes: 12 additions & 0 deletions apps/dashboard/src/main/java/com/akto/utils/GithubLogin.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ public static String getClientId() {
return ghConfig.getClientId();
}

public static String getGithubUrl() {
if (getInstance() == null) return null;

GithubConfig ghConfig = getInstance().getGithubConfig();
if (ghConfig == null) return null;

String githubUrl = ghConfig.getGithubUrl();
if (githubUrl == null) return null;
if (githubUrl.endsWith("/")) githubUrl = githubUrl.substring(0, githubUrl.length() - 1);
return githubUrl;
}

private GithubLogin() {
}

Expand Down
1 change: 1 addition & 0 deletions apps/dashboard/web/pages/login.jsp
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
window.RELEASE_VERSION_GLOBAL = '${requestScope.AktoVersionGlobal}';
window.AKTO_UI_MODE = '${requestScope.aktoUIMode}'
window.GITHUB_CLIENT_ID=atob('${requestScope.githubClientId}')
window.GITHUB_URL='${requestScope.githubUrl}'
window.STIGG_CUSTOMER_ID='${requestScope.stiggCustomerId}'
window.STIGG_CUSTOMER_TOKEN='${requestScope.stiggCustomerToken}'
window.STIGG_CLIENT_KEY='${requestScope.stiggClientKey}'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Button, LegacyCard, VerticalStack, Text } from '@shopify/polaris'
import { Button, LegacyCard, VerticalStack } from '@shopify/polaris'
import React from 'react'
import Dropdown from './layouts/Dropdown';
import {DeleteMinor} from "@shopify/polaris-icons"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Button, LegacyCard, VerticalStack, Box, HorizontalStack } from '@shopify/polaris'
import { Button, LegacyCard, VerticalStack } from '@shopify/polaris'
import React from 'react'
import ConditionComponent from './ConditionComponent';
import Dropdown from './layouts/Dropdown';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,8 @@ function SampleData(props) {
lightbulb: { enabled: false },
scrollbar:{
alwaysConsumeMouseWheel: false
}
},
fixedOverflowWidgets: true
}
let instance = "";
if(editorLanguage.includes("custom")){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,23 @@ import tableFunc from './transform';
import useTable from './TableContext';
import { debounce } from 'lodash';

import { useSearchParams } from 'react-router-dom';

function GithubServerTable(props) {

const [searchParams, setSearchParams] = useSearchParams();

const updateQueryParams = (key, value) => {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.set(key, value);
setSearchParams(newSearchParams);
};

const filtersMap = PersistStore(state => state.filtersMap)
const setFiltersMap = PersistStore(state => state.setFiltersMap)
const tableInitialState = PersistStore(state => state.tableInitialState)
const setTableInitialState = PersistStore(state => state.setTableInitialState)
const currentPageKey = props?.filterStateUrl || window.location.href
const currentPageKey = props?.filterStateUrl || (window.location.pathname + "/" + window.location.hash)
const pageFiltersMap = filtersMap[currentPageKey]

const handleRemoveAppliedFilter = (key) => {
Expand Down Expand Up @@ -70,17 +80,28 @@ function GithubServerTable(props) {
const handleSelectedTab = (x) => {
const tableTabs = props.tableTabs ? props.tableTabs : props.tabs
if(tableTabs){
const primitivePath = window.location.origin + window.location.pathname
const primitivePath = window.location.origin + window.location.pathname + window.location?.search
const newUrl = primitivePath + "#" + tableTabs[x].id
window.history.replaceState(null, null, newUrl)
}
}

useEffect(()=> {
setAppliedFilters(initialStateFilters)
let queryFilters
if (performance.getEntriesByType('navigation')[0].type === 'reload') {
queryFilters = []
}else{
queryFilters = tableFunc.getFiltersMapFromUrl(decodeURIComponent(searchParams.get("filters") || ""), props?.disambiguateLabel, handleRemoveAppliedFilter, currentPageKey)
}
const currentFilters = tableFunc.mergeFilters(queryFilters,initialStateFilters,props?.disambiguateLabel, handleRemoveAppliedFilter)
setAppliedFilters(currentFilters)
setSortSelected(tableFunc.getInitialSortSelected(props.sortOptions, pageFiltersMap))
},[currentPageKey])

useEffect(() => {
updateQueryParams("filters",tableFunc.getPrettifiedFilter(appliedFilters))
},[appliedFilters])

async function fetchData(searchVal) {
let [sortKey, sortOrder] = sortSelected.length == 0 ? ["", ""] : sortSelected[0].split(" ");
let filters = props.headers.reduce((map, e) => { map[e.filterKey || e.value] = []; return map }, {})
Expand All @@ -91,11 +112,12 @@ function GithubServerTable(props) {
tempData ? setData([...tempData.value]) : setData([])
tempData ? setTotal(tempData.total) : setTotal(0)
applyFilter(tempData.total)

setTableInitialState({
...tableInitialState,
[currentPageKey]: tempData.total
})
if(!performance.getEntriesByType('navigation')[0].type === 'reload'){
setTableInitialState({
...tableInitialState,
[currentPageKey]: tempData.total
})
}
}

useEffect(() => {
Expand All @@ -108,6 +130,10 @@ function GithubServerTable(props) {
setSortableColumns(tableFunc.getSortableChoices(props?.headers))
},[props?.headers])

useEffect(() => {
fetchData(queryValue)
},[props?.callFromOutside])

const handleSort = (col, dir) => {
let tempSortSelected = props?.sortOptions.filter(x => x.columnIndex === (col + 1))
let sortVal = [tempSortSelected[0].value]
Expand Down Expand Up @@ -275,12 +301,18 @@ function GithubServerTable(props) {
setPage((page) => (page - 1));
}

const handleTabChange = (x) => {
props?.onSelect(x);
updateQueryParams("filters", tableFunc.getPrettifiedFilter([])) ;
handleSelectedTab(x)
}

let tableHeightClass = props.increasedHeight ? "control-row" : (props.condensedHeight ? "condensed-row" : '')
let tableClass = props.useNewRow ? "new-table" : (props.selectable ? "removeHeaderColor" : "hideTableHead")
return (
<div className={tableClass}>
<LegacyCard>
{props.tabs && <Tabs tabs={props.tabs} selected={props.selected} onSelect={(x) => {props?.onSelect(x); handleSelectedTab(x)}}></Tabs>}
{props.tabs && <Tabs tabs={props.tabs} selected={props.selected} onSelect={(x) => handleTabChange(x)}></Tabs>}
{props.tabs && props.tabs[props.selected].component ? props.tabs[props.selected].component :
<div>
<LegacyCard.Section flush>
Expand All @@ -306,7 +338,7 @@ function GithubServerTable(props) {
setMode={setMode}
loading={props.loading || false}
selected={props?.selected}
onSelect={(x) => {props?.onSelect(x); handleSelectedTab(x)}}
onSelect={(x) => handleTabChange(x)}
/>
<div className={tableHeightClass}>
<IndexTable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function GithubCell(props){

const {data, headers, getStatus, width, nameWidth, isBadgeClickable, badgeClicked} = props
return (
<HorizontalStack gap="1">
<HorizontalStack gap="1" wrap={false}>
{
headers?.filter((header) => {
return header.itemOrder==0
Expand Down Expand Up @@ -138,7 +138,7 @@ function GithubCell(props){
</div>

: <Badge key={item} status={getStatus(item)}>
<Text {...header.dataProps}>
<Text {...header.dataProps} breakWord>
{item}
</Text>
</Badge>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import PersistStore from "../../../main/PersistStore";
const tableInitialState = PersistStore.getState().tableInitialState[window.location.href] || 0

const tableInitialState = PersistStore.getState().tableInitialState[window.location.pathname + "/" + window.location.hash] || 0
export const initialState = {
tabsInfo : tableInitialState
}
Expand Down
Loading

0 comments on commit f1ac782

Please sign in to comment.