Skip to content

Commit

Permalink
including github checks functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
shivam-rawat-akto committed Oct 26, 2023
1 parent 088287d commit a0aa9eb
Show file tree
Hide file tree
Showing 5 changed files with 124 additions and 21 deletions.
28 changes: 20 additions & 8 deletions .github/scripts/akto-cicd.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,7 @@ echo "### Akto test summary" >> $GITHUB_STEP_SUMMARY
while true; do
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))

if ((elapsed_time >= MAX_POLL_INTERVAL)); then
echo "Max poll interval reached. Exiting."
break
fi


current_time=$(date +%s)
recency_period=$((60 * 24 * 60 * 60))
Expand All @@ -36,22 +32,21 @@ while true; do
}")

state=$(echo "$response" | jq -r '.testingRunResultSummaries[0].state // empty')
testingRunSummaryhexId=$(echo "$response" | jq -r '.testingRunResultSummaries[0].hexId // empty')

if [[ "$state" == "COMPLETED" ]]; then
count=$(echo "$response" | jq -r '.testingRunResultSummaries[0].countIssues // empty')
high=$(echo "$response" | jq -r '.testingRunResultSummaries[0].countIssues.HIGH // empty')
medium=$(echo "$response" | jq -r '.testingRunResultSummaries[0].countIssues.MEDIUM // empty')
low=$(echo "$response" | jq -r '.testingRunResultSummaries[0].countIssues.LOW // empty')
testingRunSummaryhexId=$(echo "$response" | jq -r '.testingRunResultSummaries[0].hexId // empty')

publishGithubCommentResponse=$(curl -s "$AKTO_DASHBOARD_URL/api/publishGithubComments" \
publishGithubCommentResponse = $(curl -s "$AKTO_DASHBOARD_URL/api/publishGithubComments" \
--header 'content-type: application/json' \
--header "X-API-KEY: $AKTO_API_KEY" \
--data "{
\"testingRunSummaryHexId\": \"$testingRunSummaryhexId\"
}")

echo "$publishGithubCommentResponse" >> $GITHUB_STEP_SUMMARY
echo "[Results]($AKTO_DASHBOARD_URL/dashboard/testing/$AKTO_TEST_ID/results)" >> $GITHUB_STEP_SUMMARY
echo "HIGH: $high" >> $GITHUB_STEP_SUMMARY
echo "MEDIUM: $medium" >> $GITHUB_STEP_SUMMARY
Expand All @@ -64,11 +59,28 @@ while true; do
fi
break
elif [[ "$state" == "STOPPED" ]]; then
publishGithubCommentResponse = $(curl -s "$AKTO_DASHBOARD_URL/api/publishGithubComments" \
--header 'content-type: application/json' \
--header "X-API-KEY: $AKTO_API_KEY" \
--data "{
\"testingRunSummaryHexId\": \"$testingRunSummaryhexId\"
}")
echo "Test stopped" >> $GITHUB_STEP_SUMMARY
exit 1
break
else
echo "Waiting for akto test to be completed..."
sleep 5 # Adjust the polling interval as needed
fi

if ((elapsed_time >= MAX_POLL_INTERVAL)); then
publishGithubCommentResponse = $(curl -s "$AKTO_DASHBOARD_URL/api/publishGithubComments" \
--header 'content-type: application/json' \
--header "X-API-KEY: $AKTO_API_KEY" \
--data "{
\"testingRunSummaryHexId\": \"$testingRunSummaryhexId\"
}")
echo "Max poll interval reached. Exiting."
break
fi
done
2 changes: 1 addition & 1 deletion .github/workflows/staging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ jobs:
# run: bash ./.github/scripts/akto-testsigma.sh

- name: Run Akto CI/CD tests
uses: shivam-rawat-akto/run-scan@v1.0.2
uses: shivam-rawat-akto/run-scan@v1.0.3
with:
AKTO_DASHBOARD_URL: https://flash.staging.akto.io
AKTO_API_KEY: ${{secrets.AKTO_API_KEY}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,7 @@
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.*;
import java.util.stream.Collectors;

public class StartTestAction extends UserAction {
Expand Down Expand Up @@ -202,7 +196,8 @@ public String startTest() {
if(metadata!=null){
summary.setMetadata(metadata);
}
TestingRunResultSummariesDao.instance.insertOne(summary);
testingRunResultSummaryHexId = Objects.requireNonNull(TestingRunResultSummariesDao.instance.insertOne(summary).getInsertedId())
.asObjectId().getValue().toHexString();
}

this.startTimestamp = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.akto.DaoInit;
import com.akto.action.UserAction;
import com.akto.action.testing.StartTestAction;
import com.akto.dao.AccountSettingsDao;
import com.akto.dao.ConfigsDao;
import com.akto.dao.RBACDao;
Expand All @@ -11,7 +12,9 @@
import com.akto.dto.AccountSettings;
import com.akto.dto.Config;
import com.akto.dto.User;
import com.akto.dto.testing.TestingRun;
import com.akto.dto.testing.TestingRunResultSummary;
import com.akto.log.LoggerMaker;
import com.akto.utils.DashboardMode;
import com.akto.utils.JWT;
import com.mongodb.BasicDBObject;
Expand All @@ -24,13 +27,15 @@

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.akto.dao.AccountSettingsDao.generateFilter;
import static com.akto.dao.MCollection.ID;

public class GithubSsoAction extends UserAction {
private static final LoggerMaker loggerMaker = new LoggerMaker(StartTestAction.class);

public String deleteGithubSso() {

Expand Down Expand Up @@ -73,6 +78,53 @@ public String deleteGithubAppSecretKey() {
addActionMessage("Deleted github app ID and secret key");
return SUCCESS.toUpperCase();
}

public String updateGithubStatus() {
AccountSettings accountSettings = AccountSettingsDao.instance.findOne(generateFilter());
String privateKey = accountSettings.getGithubAppSecretKey();
String githubAppId = accountSettings.getGithubAppId();
String jwtToken;
TestingRunResultSummary testingRunResultSummary = TestingRunResultSummariesDao.instance.findOne(Filters.eq(ID,new ObjectId(testingRunSummaryHexId)));
try {
Map<String, String> metaData = testingRunResultSummary.getMetadata();
String repository = metaData.get("repository");
String commitSHA = metaData.get("commit_sha");
jwtToken = JWT.createJWT(githubAppId,privateKey, 10 * 60 * 1000);
GitHub gitHub = new GitHubBuilder().withJwtToken(jwtToken).build();
GHApp ghApp = gitHub.getApp();

//Getting appInstallations
List<GHAppInstallation> appInstallations = ghApp.listInstallations().toList();
if (appInstallations.isEmpty()) {
addActionError("Github app was not installed");
return ERROR.toUpperCase();
}

GHAppInstallation appInstallation = appInstallations.get(0);
GHAppCreateTokenBuilder builder = appInstallation.createToken();
GHAppInstallationToken token = builder.create();
GitHub githubAccount = new GitHubBuilder().withAppInstallationToken(token.getToken())
.build();

GHRepository ghRepository = githubAccount.getRepository(repository);
if (ghRepository == null) {
addActionError("Github app doesn't have access to repository");
return ERROR.toUpperCase();
}
GHCheckRunBuilder ghCheckRunBuilder = ghRepository.createCheckRun("Akto Security Checks", commitSHA);
ghCheckRunBuilder.withStatus(GHCheckRun.Status.IN_PROGRESS)
.withStartedAt(new Date())
.add(new GHCheckRunBuilder.Output("Akto CI/CD test running", ""))
.create();
} catch (Exception e) {
addActionError("Error while publishing github checks");
loggerMaker.errorAndAddToDb("Github checks error : " + e.getMessage(), LoggerMaker.LogDb.DASHBOARD);
return ERROR.toUpperCase();
}


return SUCCESS.toUpperCase();
}
public String publishGithubComments() {
AccountSettings accountSettings = AccountSettingsDao.instance.findOne(generateFilter());
String privateKey = accountSettings.getGithubAppSecretKey();
Expand All @@ -82,10 +134,17 @@ public String publishGithubComments() {
Map<String, String> metaData = testingRunResultSummary.getMetadata();
String repository = metaData.get("repository");
String pullRequestId = metaData.get("pull_request_id");
Map<String, Integer> countIssues = testingRunResultSummary.getCountIssues();
StringBuilder messageStringBuilder = new StringBuilder("Akto vulnerability report\n");
for (String severity : countIssues.keySet()) {
messageStringBuilder.append(severity).append(" - ").append(countIssues.get(severity)).append("\n");
String commitSHA = metaData.get("commit_sha");
boolean isCompleted = testingRunResultSummary.getState() == TestingRun.State.COMPLETED;
StringBuilder messageStringBuilder = new StringBuilder();
if (isCompleted) {
Map<String, Integer> countIssues = testingRunResultSummary.getCountIssues();
messageStringBuilder.append("Akto vulnerability report\n");
for (String severity : countIssues.keySet()) {
messageStringBuilder.append(severity).append(" - ").append(countIssues.get(severity)).append("\n");
}
} else {
messageStringBuilder.append("Akto CI/CD test is currently in ").append(testingRunResultSummary.getState().name()).append(" state");
}
String message = messageStringBuilder.toString();
//JWT Token creation for github app
Expand Down Expand Up @@ -120,6 +179,32 @@ public String publishGithubComments() {
int pullRequestNumber = Integer.parseInt(prArray[2]);// typical pr GITHUB_REF is refs/pull/662/merge
GHIssue issue = ghRepository.getIssue(pullRequestNumber);
issue.comment(message);

List<GHCheckRun> checkRunList = ghRepository.getCheckRuns(commitSHA).toList();
GHCheckRun ghCheckRun = null;
for (GHCheckRun checkRun : checkRunList) {
if ("Akto Security Checks".equals(checkRun.getName())) {
ghCheckRun = checkRun;
break;
}
}
if (ghCheckRun != null) {
if (isCompleted) {
ghCheckRun.update()
.withStatus(GHCheckRun.Status.COMPLETED)
.withConclusion(GHCheckRun.Conclusion.SUCCESS)
.withCompletedAt(new Date())
.add(new GHCheckRunBuilder.Output("Akto Vulnerability report", "Conclusion").withText(message))
.create();
} else {
ghCheckRun.update()
.withStatus(GHCheckRun.Status.COMPLETED)
.withConclusion(GHCheckRun.Conclusion.TIMED_OUT)
.withCompletedAt(new Date())
.add(new GHCheckRunBuilder.Output("Akto Vulnerability report", "Conclusion").withText(message))
.create();
}
}
} catch (Exception e) {
addActionError("Error while publishing github comment");
return ERROR.toUpperCase();
Expand Down
11 changes: 11 additions & 0 deletions apps/dashboard/src/main/resources/struts.xml
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,17 @@
</result>
</action>

<action name="api/updateGithubStatus" class="com.akto.action.user.GithubSsoAction" method="updateGithubStatus">
<interceptor-ref name="json"/>
<interceptor-ref name="defaultStack" />
<result name="SUCCESS" type="json"/>
<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/addGithubAppSecretKey" class="com.akto.action.user.GithubSsoAction" method="addGithubAppSecretKey">
<interceptor-ref name="json"/>
<interceptor-ref name="defaultStack" />
Expand Down

0 comments on commit a0aa9eb

Please sign in to comment.