Skip to content

Commit

Permalink
Merge branch 'master' into feature/logs_in_fetching_test_run_result
Browse files Browse the repository at this point in the history
  • Loading branch information
Ark2307 committed Jan 2, 2025
2 parents 39fd83b + ad2ccd4 commit d20fad7
Show file tree
Hide file tree
Showing 55 changed files with 917 additions and 177 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,26 @@ public List<ApiCollection> fillApiCollectionsUrlCount(List<ApiCollection> apiCol
int apiCollectionId = apiCollection.getId();
Integer count = countMap.get(apiCollectionId);
int fallbackCount = apiCollection.getUrls()!=null ? apiCollection.getUrls().size() : apiCollection.getUrlsCount();

if (count != null && (apiCollection.getHostName() != null)) {
apiCollection.setUrlsCount(count);
} else if(ApiCollection.Type.API_GROUP.equals(apiCollection.getType())){
if (count == null) {
int conditionsCount = 0;
if(!apiCollection.getAutomated()){
ApiCollection apiCollectionWithCond = ApiCollectionsDao.instance.findOne(Filters.eq(Constants.ID, apiCollection.getId()), Projections.include("conditions"));
if(apiCollectionWithCond.getConditions() != null && !apiCollectionWithCond.getConditions().isEmpty() && apiCollectionWithCond.getConditions().get(0) != null){
if(apiCollectionWithCond.getConditions().get(0).getType().equals(TestingEndpoints.Type.CUSTOM)){
CustomTestingEndpoints testingEndpoints = (CustomTestingEndpoints) apiCollectionWithCond.getConditions().get(0);
if (testingEndpoints.getApisList() != null && !testingEndpoints.getApisList().isEmpty()) {
conditionsCount = testingEndpoints.getApisList().size();
loggerMaker.infoAndAddToDb("fillApiCollectionsUrlCount collection: " + apiCollectionWithCond.getDisplayName() + " count: " + conditionsCount);
}
}
}
}

if (conditionsCount != 0) {
count = conditionsCount;
} else if (count == null) {
count = fallbackCount;
}
apiCollection.setUrlsCount(count);
Expand Down Expand Up @@ -396,8 +411,11 @@ public String addApisToCustomCollection(){
return ERROR.toUpperCase();
}

loggerMaker.infoAndAddToDb("Started adding " + this.apiList.size() + " apis into custom collection.", LogDb.DASHBOARD);

CustomTestingEndpoints condition = new CustomTestingEndpoints(apiList, CustomTestingEndpoints.Operator.OR);
apiCollection.addToConditions(condition);
loggerMaker.infoAndAddToDb("Final conditions for collection: " + apiCollection.getName() + " are: " + apiCollection.getConditions().toString());
ApiCollectionUsers.updateApiCollection(apiCollection.getConditions(), apiCollection.getId());
ApiCollectionUsers.addToCollectionsForCollectionId(apiCollection.getConditions(), apiCollection.getId());

Expand Down Expand Up @@ -510,7 +528,7 @@ public String getEndpointsListFromConditions() {
InventoryAction inventoryAction = new InventoryAction();
inventoryAction.attachAPIInfoListInResponse(list,-1);
this.setResponse(inventoryAction.getResponse());
response.put("apiCount", ApiCollectionUsers.getApisCountFromConditions(conditions, new ArrayList<>(deactivatedCollections)));
response.put("apiCount", ApiCollectionUsers.getApisCountFromConditionsWithStis(conditions, new ArrayList<>(deactivatedCollections)));
return SUCCESS.toUpperCase();
}
public String getEndpointsFromConditions(){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ public String execute() {

private AktoDataType aktoDataType;

public String saveAktoDataType(){
public String saveAktoDataType() {

aktoDataType = AktoDataTypeDao.instance.findOne("name",name);
if(aktoDataType==null){
Expand Down Expand Up @@ -305,7 +305,8 @@ public String saveAktoDataType(){
Updates.set(AktoDataType.KEY_CONDITIONS, keyConditions),
Updates.set(AktoDataType.VALUE_CONDITIONS, valueConditions),
Updates.set(AktoDataType.OPERATOR, mainOperator),
Updates.set(AktoDataType.DATA_TYPE_PRIORITY, dataTypePriority)
Updates.set(AktoDataType.DATA_TYPE_PRIORITY, dataTypePriority),
Updates.set(AktoDataType._INACTIVE, !active)
),
options
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public String execute() {
if (GithubLogin.getGithubUrl() != null) {
servletRequest.setAttribute("githubUrl", GithubLogin.getGithubUrl());
}
if(OktaLogin.getAuthorisationUrl() != null){
if(DashboardMode.isOnPremDeployment() && OktaLogin.getAuthorisationUrl() != null){
servletRequest.setAttribute("oktaAuthUrl", new String(Base64.getEncoder().encode(OktaLogin.getAuthorisationUrl().getBytes())));
}
if (InitializerListener.aktoVersion != null && InitializerListener.aktoVersion.contains("akto-release-version")) {
Expand Down
76 changes: 48 additions & 28 deletions apps/dashboard/src/main/java/com/akto/action/SignupAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -509,32 +509,38 @@ public String registerViaGithub() {
}

public String registerViaOkta() throws IOException{
if (!DashboardMode.isOnPremDeployment()) return Action.ERROR.toUpperCase();
OktaLogin oktaLoginInstance = OktaLogin.getInstance();
if(oktaLoginInstance == null){
servletResponse.sendRedirect("/login");
return ERROR.toUpperCase();
}
try {
Config.OktaConfig oktaConfig;
if(DashboardMode.isOnPremDeployment()) {
OktaLogin oktaLoginInstance = OktaLogin.getInstance();
if(oktaLoginInstance == null){
servletResponse.sendRedirect("/login");
return ERROR.toUpperCase();
}

Config.OktaConfig oktaConfig = OktaLogin.getInstance().getOktaConfig();
if (oktaConfig == null) {
servletResponse.sendRedirect("/login");
return ERROR.toUpperCase();
}
setAccountId(1000000);
oktaConfig = OktaLogin.getInstance().getOktaConfig();
} else {
setAccountId(Integer.parseInt(state));
oktaConfig = Config.getOktaConfig(accountId);
}
if(oktaConfig == null) {
servletResponse.sendRedirect("/login");
return ERROR.toUpperCase();
}

String domainUrl = "https://" + oktaConfig.getOktaDomainUrl() + "/oauth2/" + oktaConfig.getAuthorisationServerId() + "/v1";
String clientId = oktaConfig.getClientId();
String clientSecret = oktaConfig.getClientSecret();
String redirectUri = oktaConfig.getRedirectUri();
String domainUrl = "https://" + oktaConfig.getOktaDomainUrl() + "/oauth2/" + oktaConfig.getAuthorisationServerId() + "/v1";
String clientId = oktaConfig.getClientId();
String clientSecret = oktaConfig.getClientSecret();
String redirectUri = oktaConfig.getRedirectUri();

BasicDBObject params = new BasicDBObject();
params.put("grant_type", "authorization_code");
params.put("code", this.code);
params.put("client_id", clientId);
params.put("client_secret", clientSecret);
params.put("redirect_uri", redirectUri);
BasicDBObject params = new BasicDBObject();
params.put("grant_type", "authorization_code");
params.put("code", this.code);
params.put("client_id", clientId);
params.put("client_secret", clientSecret);
params.put("redirect_uri", redirectUri);

try {
Map<String,Object> tokenData = CustomHttpRequest.postRequestEncodedType(domainUrl +"/token",params);
String accessToken = tokenData.get("access_token").toString();
Map<String,Object> userInfo = CustomHttpRequest.getRequest( domainUrl + "/userinfo","Bearer " + accessToken);
Expand All @@ -544,7 +550,7 @@ public String registerViaOkta() throws IOException{
SignupInfo.OktaSignupInfo oktaSignupInfo= new SignupInfo.OktaSignupInfo(accessToken, username);

shouldLogin = "true";
createUserAndRedirect(email, username, oktaSignupInfo, 1000000, Config.ConfigType.OKTA.toString());
createUserAndRedirect(email, username, oktaSignupInfo, accountId, Config.ConfigType.OKTA.toString(), RBAC.Role.MEMBER);
code = "";
} catch (Exception e) {
loggerMaker.errorAndAddToDb("Error while signing in via okta sso \n" + e.getMessage(), LogDb.DASHBOARD);
Expand All @@ -560,7 +566,7 @@ public String registerViaOkta() throws IOException{
public String sendRequestToSamlIdP() throws IOException{
String queryString = servletRequest.getQueryString();
String emailId = Util.getValueFromQueryString(queryString, "email");
if(emailId.length() == 0){
if(emailId.isEmpty()){
code = "Error, user email cannot be empty";
logger.error(code);
servletResponse.sendRedirect("/login");
Expand All @@ -569,11 +575,10 @@ public String sendRequestToSamlIdP() throws IOException{
logger.info("Trying to sign in for: " + emailId);
setUserEmail(emailId);
SAMLConfig samlConfig = SSOConfigsDao.instance.getSSOConfig(userEmail);
if(samlConfig == null){
code = "Error, cannot login via SSO, redirecting to login";
if(samlConfig == null) {
code = "Error, cannot login via SSO, trying to login with okta sso";
logger.error(code);
servletResponse.sendRedirect("/login");
return ERROR.toUpperCase();
return oktaAuthUrlCreator(emailId);
}
int tempAccountId = Integer.parseInt(samlConfig.getId());
logger.info("Account id: " + tempAccountId + " found for " + emailId);
Expand All @@ -599,6 +604,21 @@ public String sendRequestToSamlIdP() throws IOException{
return SUCCESS.toUpperCase();
}

public String oktaAuthUrlCreator(String emailId) throws IOException {
logger.info("Trying to create auth url for okta sso for: " + emailId);
Config.OktaConfig oktaConfig = Config.getOktaConfig(emailId);
if(oktaConfig == null) {
code= "Error, cannot find okta sso for this organization, redirecting to login";
logger.error(code);
servletResponse.sendRedirect("/login");
return ERROR.toUpperCase();
}

String authorisationUrl = OktaLogin.getAuthorisationUrl(emailId);
servletResponse.sendRedirect(authorisationUrl);
return SUCCESS.toUpperCase();
}

public String registerViaAzure() throws Exception{
Auth auth;
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ public class StartTestAction extends UserAction {
private Map<String,Integer> issuesSummaryInfoMap = new HashMap<>();

private String testRoleId;
private boolean cleanUpTestingResources;

private static final Gson gson = new Gson();

private static List<ObjectId> getTestingRunListFromSummary(Bson filters){
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -1418,4 +1420,12 @@ public void setReportFilterList(Map<String, List<String>> reportFilterList) {
public List<TestingRunIssues> getIssueslist() {
return issueslist;
}

public boolean getCleanUpTestingResources() {
return cleanUpTestingResources;
}

public void setCleanUpTestingResources(boolean cleanUpTestingResources) {
this.cleanUpTestingResources = cleanUpTestingResources;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private AuthWithCond makeAuthWithConditionFromParamData(TestRoles role){

for (AuthParamData authParamDataElem : authParamData) {
AuthParam param = null;
if (authAutomationType.equals(LoginFlowEnums.AuthMechanismTypes.HARDCODED.toString())) {
if (authAutomationType.toUpperCase().equals(LoginFlowEnums.AuthMechanismTypes.HARDCODED.toString())) {
param = new HardcodedAuthParam(authParamDataElem.getWhere(), authParamDataElem.getKey(), authParamDataElem.getValue(), true);
} else {
param = new LoginRequestAuthParam(authParamDataElem.getWhere(), authParamDataElem.getKey(), authParamDataElem.getValue(), authParamDataElem.getShowHeader());
Expand Down Expand Up @@ -180,8 +180,8 @@ public String updateTestRoles() {
isAttackerRole = role.getId().equals(attackerRole.getId());
}
if (isAttackerRole) {
addActionError("Unable to update endpoint conditions for attacker role");
return ERROR.toUpperCase();
this.orConditions = null;
this.andConditions = null;
}

Conditions orConditions = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.*;
import com.mongodb.client.result.InsertOneResult;
import com.opensymphony.xwork2.Action;

import org.bson.Document;
import org.bson.conversions.Bson;
Expand All @@ -55,7 +56,7 @@

public class IssuesAction extends UserAction {

private static final LoggerMaker loggerMaker = new LoggerMaker(IssuesAction.class);
private static final LoggerMaker loggerMaker = new LoggerMaker(IssuesAction.class, LogDb.DASHBOARD);
private static final Logger logger = LoggerFactory.getLogger(IssuesAction.class);
private List<TestingRunIssues> issues;
private TestingIssuesId issueId;
Expand All @@ -74,6 +75,8 @@ public class IssuesAction extends UserAction {
private List<TestingRunIssues> similarlyAffectedIssues;
private int startEpoch;
long endTimeStamp;
private Map<Integer,Map<String,Integer>> severityInfo = new HashMap<>();

private Bson createFilters (boolean useFilterStatus) {
Bson filters = Filters.empty();
if (useFilterStatus && filterStatus != null && !filterStatus.isEmpty()) {
Expand All @@ -89,8 +92,12 @@ private Bson createFilters (boolean useFilterStatus) {
filters = Filters.and(filters, Filters.in(ID + "."
+ TestingIssuesId.TEST_SUB_CATEGORY, filterSubCategory));
}
if (startEpoch != 0 && endTimeStamp != 0) {

if (startEpoch != 0) {
filters = Filters.and(filters, Filters.gte(TestingRunIssues.CREATION_TIME, startEpoch));
}

if(endTimeStamp != 0){
filters = Filters.and(filters, Filters.lt(TestingRunIssues.CREATION_TIME, endTimeStamp));
}

Expand Down Expand Up @@ -628,6 +635,18 @@ public String getReportFilters () {
return SUCCESS.toUpperCase();
}

public String fetchSeverityInfoForIssues() {
Bson filter = createFilters(true);

if (issuesIds != null && !issuesIds.isEmpty()) {
filter = Filters.and(filter, Filters.in(Constants.ID, issuesIds));
}

this.severityInfo = TestingRunIssuesDao.instance.getSeveritiesMapForCollections(filter, false);
return Action.SUCCESS.toUpperCase();
}


public List<TestingRunIssues> getIssues() {
return issues;
}
Expand Down Expand Up @@ -877,4 +896,12 @@ public void setIssuesIdsForReport(List<TestingIssuesId> issuesIdsForReport) {
public BasicDBObject getResponse() {
return response;
}

public Map<Integer, Map<String, Integer>> getSeverityInfo() {
return severityInfo;
}

public void setSeverityInfo(Map<Integer, Map<String, Integer>> severityInfo) {
this.severityInfo = severityInfo;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ public class OktaSsoAction extends UserAction {
private String redirectUri;

public String addOktaSso() {

if(!DashboardMode.isOnPremDeployment()){
addActionError("This feature is only available in on-prem deployment");
return ERROR.toUpperCase();
}

if (SsoUtils.isAnySsoActive()) {
addActionError("A SSO Integration already exists.");
return ERROR.toUpperCase();
Expand All @@ -41,20 +35,30 @@ public String addOktaSso() {
oktaConfig.setAuthorisationServerId(authorisationServerId);
oktaConfig.setOktaDomainUrl(oktaDomain);
oktaConfig.setRedirectUri(redirectUri);

if(!DashboardMode.isOnPremDeployment()){
oktaConfig.setAccountId(Context.accountId.get());
String userLogin = getSUser().getLogin();
String domain = userLogin.split("@")[1];
oktaConfig.setOrganizationDomain(domain);
}
ConfigsDao.instance.insertOne(oktaConfig);

return SUCCESS.toUpperCase();
}

public String deleteOktaSso() {
if(!DashboardMode.isOnPremDeployment()){
addActionError("This feature is only available in on-prem deployment");
return ERROR.toUpperCase();
DeleteResult result;
if(DashboardMode.isOnPremDeployment()) {
result = ConfigsDao.instance.deleteAll(Filters.eq("_id", "OKTA-ankush"));
} else {
result = ConfigsDao.instance.deleteAll(
Filters.and(
Filters.eq("_id", "OKTA-ankush"),
Filters.eq(Config.OktaConfig.ACCOUNT_ID, Context.accountId.get())
)
);
}

DeleteResult result = ConfigsDao.instance.deleteAll(Filters.eq("_id", "OKTA-ankush"));

if (result.getDeletedCount() > 0) {
for (Object obj : UsersDao.instance.getAllUsersInfoForTheAccount(Context.accountId.get())) {
BasicDBObject detailsObj = (BasicDBObject) obj;
Expand All @@ -68,13 +72,13 @@ public String deleteOktaSso() {

@Override
public String execute() throws Exception {

if(!DashboardMode.isOnPremDeployment()){
addActionError("This feature is only available in on-prem deployment");
return ERROR.toUpperCase();
Config.OktaConfig oktaConfig;
if(DashboardMode.isOnPremDeployment()) {
oktaConfig = (Config.OktaConfig) ConfigsDao.instance.findOne("_id", "OKTA-ankush");
} else {
String email = getSUser().getLogin();
oktaConfig = Config.getOktaConfig(email);
}

Config.OktaConfig oktaConfig = (Config.OktaConfig) ConfigsDao.instance.findOne("_id", "OKTA-ankush");
if (SsoUtils.isAnySsoActive() && oktaConfig == null) {
addActionError("A different SSO Integration already exists.");
return ERROR.toUpperCase();
Expand Down
Loading

0 comments on commit d20fad7

Please sign in to comment.