Search in sources :

Example 1 with MachinaRuntimeException

use of com.checkmarx.flow.exception.MachinaRuntimeException in project cx-flow by checkmarx-ltd.

the class IssueService method process.

public void process(ScanResults results, ScanRequest request) throws MachinaException {
    Map<String, ScanResults.XIssue> xMap;
    Map<String, Issue> iMap;
    List<String> newIssues = new ArrayList<>();
    List<String> updatedIssues = new ArrayList<>();
    List<String> closedIssues = new ArrayList<>();
    BugTracker bugTracker = request.getBugTracker();
    String customBean = bugTracker.getCustomBean();
    if (!bugTracker.getType().equals(BugTracker.Type.CUSTOM) && !ScanUtils.empty(customBean)) {
        throw new MachinaException("A valid custom bean must be used here.");
    }
    try {
        IssueTracker tracker = (IssueTracker) context.getBean(customBean);
        tracker.init(request, results);
        String fpLabel = tracker.getFalsePositiveLabel();
        codeBashingService.createLessonsMap();
        log.info("Processing Issues with custom bean {}", customBean);
        List<Issue> issues = tracker.getIssues(request);
        if (issues == null) {
            issues = Collections.emptyList();
        }
        xMap = this.getXIssueMap(tracker, results, request);
        iMap = this.getIssueMap(tracker, issues, request);
        for (Map.Entry<String, ScanResults.XIssue> xIssue : xMap.entrySet()) {
            try {
                String fileUrl;
                ScanResults.XIssue currentIssue = xIssue.getValue();
                codeBashingService.addCodebashingUrlToIssue(currentIssue);
                /*Issue already exists -> update and comment*/
                if (iMap.containsKey(xIssue.getKey())) {
                    Issue i = iMap.get(xIssue.getKey());
                    if (xIssue.getValue().isAllFalsePositive()) {
                        // All issues are false positive, so issue should be closed
                        Issue fpIssue;
                        log.debug("All issues are false positives");
                        if (properties.isListFalsePositives()) {
                            // Update the ticket if flag is set
                            log.debug("Issue is being updated to reflect false positive references.  Updating issue with key {}", xIssue.getKey());
                            tracker.updateIssue(i, currentIssue, request);
                        }
                        if (tracker.isIssueOpened(i, request)) {
                            /*Close the issue if in an open state*/
                            log.info("Closing issue with key {}", i.getId());
                            tracker.closeIssue(i, request);
                            closedIssues.add(i.getId());
                        }
                    } else if (!i.getLabels().contains(fpLabel)) {
                        /*Ignore any with label indicating false positive*/
                        log.info("Issue still exists.  Updating issue with key {}", xIssue.getKey());
                        fileUrl = ScanUtils.getFileUrl(request, currentIssue.getFilename());
                        currentIssue.setGitUrl(fileUrl);
                        Issue updatedIssue = tracker.updateIssue(i, currentIssue, request);
                        if (updatedIssue != null) {
                            updatedIssues.add(updatedIssue.getId());
                            log.debug("Update completed for issue #{}", updatedIssue.getId());
                        }
                    } else {
                        log.info("Skipping issue marked as false positive with key {}", xIssue.getKey());
                    }
                } else {
                    /*Create the new issue*/
                    if (!xIssue.getValue().isAllFalsePositive()) {
                        fileUrl = ScanUtils.getFileUrl(request, currentIssue.getFilename());
                        xIssue.getValue().setGitUrl(fileUrl);
                        log.info("Creating new issue with key {}", xIssue.getKey());
                        Issue newIssue = tracker.createIssue(xIssue.getValue(), request);
                        if (newIssue != null) {
                            newIssues.add(newIssue.getId());
                            log.info("New issue created. #{}", newIssue.getId());
                        }
                    }
                }
            } catch (HttpClientErrorException e) {
                log.error("Error occurred while processing issue with key {}", xIssue.getKey(), e);
            }
        }
        /*Check if an issue exists in GitLab but not within results and close if not*/
        for (Map.Entry<String, Issue> issueMap : iMap.entrySet()) {
            String key = issueMap.getKey();
            Issue issue = issueMap.getValue();
            try {
                if (!xMap.containsKey(key) && tracker.isIssueOpened(issue, request)) {
                    /*Close the issue*/
                    tracker.closeIssue(issue, request);
                    closedIssues.add(issue.getId());
                    log.info("Closing issue #{} with key {}", issue.getId(), key);
                }
            } catch (HttpClientErrorException e) {
                log.error("Error occurred while processing issue with key {}", key, e);
            }
        }
        Map<String, List<String>> issuesMap = new HashMap<>();
        issuesMap.put("new", newIssues);
        issuesMap.put("updated", updatedIssues);
        issuesMap.put("closed", closedIssues);
        tracker.complete(request, results);
    } catch (BeansException e) {
        log.error("Specified bug tracker bean was not found or properly loaded.", e);
        throw new MachinaRuntimeException();
    } catch (ClassCastException e) {
        log.error("Bean must implement the IssueTracker Interface", e);
        throw new MachinaRuntimeException();
    }
}
Also used : Issue(com.checkmarx.flow.dto.Issue) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) IssueTracker(com.checkmarx.flow.custom.IssueTracker) ScanResults(com.checkmarx.sdk.dto.ScanResults) BugTracker(com.checkmarx.flow.dto.BugTracker) MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) MachinaException(com.checkmarx.flow.exception.MachinaException) BeansException(org.springframework.beans.BeansException)

Example 2 with MachinaRuntimeException

use of com.checkmarx.flow.exception.MachinaRuntimeException in project cx-flow by checkmarx-ltd.

the class BitbucketServerController method doMergeEvent.

private ResponseEntity<EventResponse> doMergeEvent(String body, String product, String signature, ControllerRequest controllerRequest) {
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    log.info("Processing BitBucket MERGE request");
    verifyHmacSignature(body, signature);
    ObjectMapper mapper = new ObjectMapper();
    PullEvent event;
    try {
        event = mapper.readValue(body, PullEvent.class);
        log.debug("Successfully consumed request payload : {}", body);
    } catch (IOException e) {
        log.debug("Error occurred while consuming request payload, body {}, error {}", body, e);
        throw new MachinaRuntimeException(e);
    }
    String application = event.getPullRequest().getFromRef().getRepository().getName();
    if (!ScanUtils.empty(controllerRequest.getApplication())) {
        application = controllerRequest.getApplication();
    }
    if (ScanUtils.empty(product)) {
        product = ScanRequest.Product.CX.getProduct();
    }
    BitbucketServerEventHandler handler = BitbucketServerMergeHandler.builder().controllerRequest(controllerRequest).application(application).currentBranch(event.getPullRequest().getFromRef().getDisplayId()).targetBranch(event.getPullRequest().getToRef().getDisplayId()).fromRefLatestCommit(event.getPullRequest().getFromRef().getLatestCommit()).fromProjectKey(event.getPullRequest().getFromRef().getRepository().getProject().getKey()).fromSlug(event.getPullRequest().getFromRef().getRepository().getSlug()).toProjectKey(event.getPullRequest().getToRef().getRepository().getProject().getKey()).toSlug(event.getPullRequest().getToRef().getRepository().getSlug()).pullRequestId(event.getPullRequest().getId().toString()).repositoryName(event.getPullRequest().getFromRef().getRepository().getName()).refId(event.getPullRequest().getFromRef().getId()).browseUrl(event.getPullRequest().getFromRef().getRepository().getLinks().getSelf().get(INDEX_FROM_SELF).getHref()).webhookPayload(body).configProvider(this).product(product).build();
    return handler.execute(uid);
}
Also used : MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) BitbucketServerEventHandler(com.checkmarx.flow.handlers.bitbucket.server.BitbucketServerEventHandler) PullEvent(com.checkmarx.flow.dto.bitbucketserver.PullEvent) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 3 with MachinaRuntimeException

use of com.checkmarx.flow.exception.MachinaRuntimeException in project cx-flow by checkmarx-ltd.

the class BitbucketServerController method pushRequest.

/**
 * Receive Push event submitted from Bitbucket
 */
@PostMapping(value = { "/{product}", "/" }, headers = PUSH)
public ResponseEntity<EventResponse> pushRequest(@RequestBody String body, @PathVariable(value = "product", required = false) String product, @RequestHeader(value = SIGNATURE) String signature, ControllerRequest controllerRequest) {
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    log.info("Processing BitBucket PUSH request");
    verifyHmacSignature(body, signature);
    ObjectMapper mapper = new ObjectMapper();
    PushEvent event;
    try {
        event = mapper.readValue(body, PushEvent.class);
    } catch (IOException e) {
        throw new MachinaRuntimeException(e);
    }
    if (event.getChanges().get(0).getType().equalsIgnoreCase("DELETE")) {
        log.info("Push event is associated with a Delete branch event...ignoring request");
        return handleDeleteEvent(body, uid, event, signature, product, controllerRequest);
    }
    String application = event.getRepository().getName();
    if (!ScanUtils.empty(controllerRequest.getApplication())) {
        application = controllerRequest.getApplication();
    }
    if (ScanUtils.empty(product)) {
        product = ScanRequest.Product.CX.getProduct();
    }
    BitbucketServerEventHandler handler = BitbucketServerPushHandler.builder().controllerRequest(controllerRequest).branchFromRef(event.getChanges().get(INDEX_FROM_CHANGES).getRefId()).toHash(event.getChanges().get(INDEX_FROM_CHANGES).getToHash()).email(event.getActor().getEmailAddress()).fromProjectKey(event.getRepository().getProject().getKey()).fromSlug(event.getRepository().getSlug()).toProjectKey(event.getRepository().getProject().getKey()).toSlug(event.getRepository().getSlug()).repositoryName(event.getRepository().getName()).refId(event.getChanges().get(INDEX_FROM_CHANGES).getRefId()).browseUrl(event.getRepository().getLinks().getSelf().get(INDEX_FROM_SELF).getHref()).webhookPayload(body).configProvider(this).product(product).application(application).build();
    return handler.execute(uid);
}
Also used : PushEvent(com.checkmarx.flow.dto.bitbucketserver.PushEvent) MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) BitbucketServerEventHandler(com.checkmarx.flow.handlers.bitbucket.server.BitbucketServerEventHandler) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 4 with MachinaRuntimeException

use of com.checkmarx.flow.exception.MachinaRuntimeException in project cx-flow by checkmarx-ltd.

the class PostWebhookController method doMerge.

private ResponseEntity<EventResponse> doMerge(String body, String product, String credentials, String token, ControllerRequest controllerRequest, String eventType) {
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    log.info("Processing BitBucket(Post Web Hook) {} request", eventType);
    validateCredentials(credentials, token);
    ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    BitbucketServerPullRequestEvent event;
    try {
        event = mapper.readValue(body, BitbucketServerPullRequestEvent.class);
    } catch (IOException e) {
        throw new MachinaRuntimeException(e);
    }
    String application = event.getPullrequest().getFromRef().getRepository().getSlug();
    if (!ScanUtils.empty(controllerRequest.getApplication())) {
        application = controllerRequest.getApplication();
    }
    if (ScanUtils.empty(product)) {
        product = ScanRequest.Product.CX.getProduct();
    }
    BitbucketServerEventHandler handler = BitbucketServerMergeHandler.builder().controllerRequest(controllerRequest).currentBranch(event.getPullrequest().getFromRef().getBranch().getName()).targetBranch(event.getPullrequest().getToRef().getBranch().getName()).fromRefLatestCommit(event.getPullrequest().getFromRef().getCommit().getHash()).fromProjectKey(event.getPullrequest().getFromRef().getRepository().getProject().getKey()).fromSlug(event.getPullrequest().getFromRef().getRepository().getSlug()).toProjectKey(event.getPullrequest().getToRef().getRepository().getProject().getKey()).toSlug(event.getPullrequest().getToRef().getRepository().getSlug()).pullRequestId(event.getPullrequest().getId()).repositoryName(event.getPullrequest().getFromRef().getRepository().getSlug()).refId(event.getPullrequest().getFromRef().getBranch().getName()).browseUrl(event.getPullrequest().getFromRef().getRepository().getLinks().get("self").get(BROWSE_URL_INDEX).getHref()).webhookPayload(body).configProvider(this).product(product).application(application).build();
    return handler.execute(uid);
}
Also used : BitbucketServerPullRequestEvent(com.checkmarx.flow.dto.bitbucketserver.plugin.postwebhook.BitbucketServerPullRequestEvent) MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) BitbucketServerEventHandler(com.checkmarx.flow.handlers.bitbucket.server.BitbucketServerEventHandler) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with MachinaRuntimeException

use of com.checkmarx.flow.exception.MachinaRuntimeException in project cx-flow by checkmarx-ltd.

the class ServiceNowTracker method createServiceNowRequest.

/**
 * Create Service Now request based on the ScanRequest params.
 * @param request
 * @return query string value.
 */
private String createServiceNowRequest(ScanRequest request) throws MachinaException {
    if (ScanUtils.emptyObj(request)) {
        throw new RuntimeException("ScanRequest object is empty");
    }
    String serviceNowTagSearchURL = null;
    String tag = createServiceNowTag(request);
    try {
        log.debug("ServiceNow tag to search for: {}", tag);
        serviceNowTagSearchURL = String.format("%s%s?sysparm_limit=%s&comments=%s", properties.getApiUrl(), INCIDENTS, MAX_RECORDS, URLEncoder.encode(tag, StandardCharsets.UTF_8.toString()));
        log.debug("ServiceNow Get Issues URL: {}", serviceNowTagSearchURL);
    } catch (UnsupportedEncodingException e) {
        log.error("Error occurred while encoding ServiceNow tag: {}", tag);
        log.error(ExceptionUtils.getStackTrace(e));
        throw new MachinaRuntimeException();
    }
    return serviceNowTagSearchURL;
}
Also used : MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

MachinaRuntimeException (com.checkmarx.flow.exception.MachinaRuntimeException)23 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)10 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8 IOException (java.io.IOException)8 Issue (com.checkmarx.flow.dto.Issue)5 ScanRequest (com.checkmarx.flow.dto.ScanRequest)5 Incident (com.checkmarx.flow.dto.servicenow.Incident)5 BitbucketServerEventHandler (com.checkmarx.flow.handlers.bitbucket.server.BitbucketServerEventHandler)5 BugTracker (com.checkmarx.flow.dto.BugTracker)4 MachinaException (com.checkmarx.flow.exception.MachinaException)4 ScanResults (com.checkmarx.sdk.dto.ScanResults)3 CxConfig (com.checkmarx.sdk.dto.sast.CxConfig)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 URI (java.net.URI)3 List (java.util.List)3 FlowProperties (com.checkmarx.flow.config.FlowProperties)2 ServiceNowProperties (com.checkmarx.flow.config.ServiceNowProperties)2 Result (com.checkmarx.flow.dto.servicenow.Result)2 HTMLHelper (com.checkmarx.flow.utils.HTMLHelper)2 ScanUtils (com.checkmarx.flow.utils.ScanUtils)2