Search in sources :

Example 11 with ScanRequest

use of com.checkmarx.flow.dto.ScanRequest in project cx-flow by checkmarx-ltd.

the class GitHubController method deleteBranchRequest.

/**
 * Delete Request event submitted (JSON), along with the Product (cx for example)
 */
@PostMapping(value = { "/{product}", "/" }, headers = DELETE)
public ResponseEntity<EventResponse> deleteBranchRequest(@RequestBody String body, @RequestHeader(value = SIGNATURE) String signature, @PathVariable(value = "product", required = false) String product, @RequestParam(value = "application", required = false) String application, @RequestParam(value = "project", required = false) String project, @RequestParam(value = "team", required = false) String team) {
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    log.info("Processing GitHub DELETE Branch request");
    DeleteEvent event;
    ObjectMapper mapper = new ObjectMapper();
    try {
        event = mapper.readValue(body, DeleteEvent.class);
    } catch (NullPointerException | IOException | IllegalArgumentException e) {
        throw new MachinaRuntimeException(e);
    }
    if (flowProperties == null) {
        log.error("Properties have null values");
        throw new MachinaRuntimeException();
    }
    // verify message signature
    verifyHmacSignature(body, signature, null);
    if (!event.getRefType().equalsIgnoreCase("branch")) {
        log.error("Nothing to do for delete tag");
        return ResponseEntity.status(HttpStatus.OK).body(EventResponse.builder().message("Nothing to do for delete tag").success(true).build());
    }
    String app = event.getRepository().getName();
    if (!ScanUtils.empty(application)) {
        app = application;
    }
    if (ScanUtils.empty(product)) {
        product = ScanRequest.Product.CX.getProduct();
    }
    ScanRequest.Product p = ScanRequest.Product.valueOf(product.toUpperCase(Locale.ROOT));
    String currentBranch = ScanUtils.getBranchFromRef(event.getRef());
    Repository repository = event.getRepository();
    String namespace;
    if (StringUtils.isBlank(repository.getOwner().getName())) {
        namespace = repository.getOwner().getLogin();
    } else {
        namespace = repository.getOwner().getName().replace(" ", "_");
    }
    ScanRequest request = ScanRequest.builder().application(app).product(p).project(project).team(team).namespace(namespace).repoName(repository.getName()).repoUrl(repository.getCloneUrl()).repoType(ScanRequest.Repository.NA).branch(currentBranch).defaultBranch(repository.getDefaultBranch()).refs(event.getRef()).build();
    request.setScanPresetOverride(false);
    CxConfig cxConfig = gitHubService.getCxConfigOverride(request);
    request = configOverrider.overrideScanRequestProperties(cxConfig, request);
    // Check if an installation Id is provided and store it for later use
    if (event.getInstallation() != null && event.getInstallation().getId() != null) {
        request.putAdditionalMetadata(FlowConstants.GITHUB_APP_INSTALLATION_ID, event.getInstallation().getId().toString());
    }
    // deletes a project which is not in the middle of a scan, otherwise it will not be deleted
    flowService.deleteProject(request);
    final String MESSAGE = "Branch deletion event was handled successfully.";
    log.info(MESSAGE);
    return ResponseEntity.status(HttpStatus.OK).body(EventResponse.builder().message(MESSAGE).success(true).build());
}
Also used : ScanRequest(com.checkmarx.flow.dto.ScanRequest) MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) CxConfig(com.checkmarx.sdk.dto.sast.CxConfig) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 12 with ScanRequest

use of com.checkmarx.flow.dto.ScanRequest in project cx-flow by checkmarx-ltd.

the class GitHubController method pushRequest.

/**
 * Push Request event submitted (JSON), along with the Product (cx for example)
 */
@PostMapping(value = { "/{product}", "/" }, headers = PUSH)
public ResponseEntity<EventResponse> pushRequest(@RequestBody String body, @RequestHeader(value = SIGNATURE) String signature, @PathVariable(value = "product", required = false) String product, ControllerRequest controllerRequest) {
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    log.info("Processing GitHub PUSH request");
    PushEvent event;
    Integer installationId = null;
    ObjectMapper mapper = new ObjectMapper();
    controllerRequest = ensureNotNull(controllerRequest);
    try {
        event = mapper.readValue(body, PushEvent.class);
    } catch (NullPointerException | IOException | IllegalArgumentException e) {
        throw new MachinaRuntimeException(e);
    }
    // Delete event is triggering a push event that needs to be ignored
    if (event.getDeleted() != null && event.getDeleted()) {
        log.info("Push event is associated with a Delete branch event...ignoring request");
        return getSuccessMessage();
    }
    gitHubService.initConfigProviderOnPushEvent(uid, event);
    if (flowProperties == null) {
        log.error("Properties have null values");
        throw new MachinaRuntimeException();
    }
    // verify message signature
    verifyHmacSignature(body, signature, controllerRequest);
    try {
        String app = event.getRepository().getName();
        if (!ScanUtils.empty(controllerRequest.getApplication())) {
            app = controllerRequest.getApplication();
        }
        // If user has pushed their changes into an important branch (e.g. master) and the code has some issues,
        // use the bug tracker from the config. As a result, "real" issues will be opened in the bug tracker and
        // not just notifications for the user. The "push" case also includes merging a pull request.
        // See the comment for the pullRequest method for further details.
        // However, if the bug tracker is overridden in the query string, use the override value.
        setBugTracker(flowProperties, controllerRequest);
        BugTracker.Type bugType = ScanUtils.getBugTypeEnum(controllerRequest.getBug(), flowProperties.getBugTrackerImpl());
        if (controllerRequest.getAppOnly() != null) {
            flowProperties.setTrackApplicationOnly(controllerRequest.getAppOnly());
        }
        if (ScanUtils.empty(product)) {
            product = ScanRequest.Product.CX.getProduct();
        }
        ScanRequest.Product p = ScanRequest.Product.valueOf(product.toUpperCase(Locale.ROOT));
        // determine branch (without refs)
        String currentBranch = ScanUtils.getBranchFromRef(event.getRef());
        List<String> branches = getBranches(controllerRequest, flowProperties);
        BugTracker bt = ScanUtils.getBugTracker(controllerRequest.getAssignee(), bugType, jiraProperties, controllerRequest.getBug());
        FilterConfiguration filter = filterFactory.getFilter(controllerRequest, flowProperties);
        Map<FindingSeverity, Integer> thresholdMap = getThresholds(controllerRequest);
        // build request object
        Repository repository = event.getRepository();
        String gitUrl = repository.getCloneUrl();
        String token;
        String gitAuthUrl;
        log.info("Using url: {}", gitUrl);
        if (event.getInstallation() != null && event.getInstallation().getId() != null) {
            installationId = event.getInstallation().getId();
            token = gitHubAppAuthService.getInstallationToken(installationId);
            token = FlowConstants.GITHUB_APP_CLONE_USER.concat(":").concat(token);
        } else {
            token = scmConfigOverrider.determineConfigToken(properties, controllerRequest.getScmInstance());
            if (ScanUtils.empty(token)) {
                log.error("No token was provided for Github");
                throw new MachinaRuntimeException();
            }
        }
        gitAuthUrl = gitAuthUrlGenerator.addCredToUrl(ScanRequest.Repository.GITHUB, gitUrl, token);
        ScanRequest request = ScanRequest.builder().application(app).product(p).project(controllerRequest.getProject()).team(controllerRequest.getTeam()).namespace(repository.getOwner().getName().replace(" ", "_")).repoName(repository.getName()).repoUrl(repository.getCloneUrl()).repoUrlWithAuth(gitAuthUrl).repoType(ScanRequest.Repository.GITHUB).branch(currentBranch).defaultBranch(repository.getDefaultBranch()).refs(event.getRef()).email(determineEmails(event)).scanPreset(controllerRequest.getPreset()).incremental(controllerRequest.getIncremental()).excludeFolders(controllerRequest.getExcludeFolders()).excludeFiles(controllerRequest.getExcludeFiles()).bugTracker(bt).filter(filter).thresholds(thresholdMap).organizationId(getOrganizationid(repository)).gitUrl(gitUrl).hash(event.getAfter()).build();
        setScmInstance(controllerRequest, request);
        // Check if an installation Id is provided and store it for later use
        if (installationId != null) {
            request.putAdditionalMetadata(FlowConstants.GITHUB_APP_INSTALLATION_ID, installationId.toString());
        }
        /*Check for Config as code (cx.config) and override*/
        CxConfig cxConfig = gitHubService.getCxConfigOverride(request);
        request = configOverrider.overrideScanRequestProperties(cxConfig, request);
        request.putAdditionalMetadata(HTMLHelper.WEB_HOOK_PAYLOAD, body);
        request.setId(uid);
        // only initiate scan/automation if branch is applicable
        if (helperService.isBranch2Scan(request, branches)) {
            flowService.initiateAutomation(request);
        }
    } catch (IllegalArgumentException e) {
        return getBadRequestMessage(e, controllerRequest, product);
    }
    return getSuccessMessage();
}
Also used : FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) CxConfig(com.checkmarx.sdk.dto.sast.CxConfig) IOException(java.io.IOException) BugTracker(com.checkmarx.flow.dto.BugTracker) ScanRequest(com.checkmarx.flow.dto.ScanRequest) MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 13 with ScanRequest

use of com.checkmarx.flow.dto.ScanRequest in project cx-flow by checkmarx-ltd.

the class PostRequestData method initiateScan.

@PostMapping("/scan")
public ResponseEntity<EventResponse> initiateScan(@RequestBody CxScanRequest scanRequest, @RequestHeader(value = TOKEN_HEADER) String token) {
    String uid = helperService.getShortUid();
    String errorMessage = "Error submitting Scan Request.";
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    log.info("Processing Scan initiation request");
    validateToken(token);
    try {
        log.trace(scanRequest.toString());
        ScanRequest.Product product = ScanRequest.Product.CX;
        String project = scanRequest.getProject();
        String branch = scanRequest.getBranch();
        String application = scanRequest.getApplication();
        String team = scanRequest.getTeam();
        if (ScanUtils.empty(application)) {
            application = project;
        }
        if (ScanUtils.empty(team)) {
            team = cxScannerService.getProperties().getTeam();
        }
        properties.setTrackApplicationOnly(scanRequest.isApplicationOnly());
        if (ScanUtils.anyEmpty(project, branch, scanRequest.getGitUrl())) {
            log.error("{}  The project | branch | git_url was not provided", errorMessage);
            ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(EventResponse.builder().message(errorMessage).success(false).build());
        }
        String scanPreset = cxScannerService.getProperties().getScanPreset();
        if (!ScanUtils.empty(scanRequest.getPreset())) {
            scanPreset = scanRequest.getPreset();
        }
        boolean inc = cxScannerService.getProperties().getIncremental();
        if (scanRequest.isIncremental()) {
            inc = true;
        }
        BugTracker.Type bugType;
        if (!ScanUtils.empty(scanRequest.getBug())) {
            bugType = ScanUtils.getBugTypeEnum(scanRequest.getBug(), properties.getBugTrackerImpl());
        } else {
            bugType = ScanUtils.getBugTypeEnum(properties.getBugTracker(), properties.getBugTrackerImpl());
        }
        if (!ScanUtils.empty(scanRequest.getProduct())) {
            product = ScanRequest.Product.valueOf(scanRequest.getProduct().toUpperCase(Locale.ROOT));
        }
        FilterConfiguration filter = determineFilter(scanRequest);
        String bug = properties.getBugTracker();
        if (!ScanUtils.empty(scanRequest.getBug())) {
            bug = scanRequest.getBug();
        }
        BugTracker bt = ScanUtils.getBugTracker(scanRequest.getAssignee(), bugType, jiraProperties, bug);
        List<String> excludeFiles = scanRequest.getExcludeFiles();
        List<String> excludeFolders = scanRequest.getExcludeFolders();
        if ((excludeFiles == null) && !ScanUtils.empty(cxScannerService.getProperties().getExcludeFiles())) {
            excludeFiles = Arrays.asList(cxScannerService.getProperties().getExcludeFiles().split(","));
        }
        if (excludeFolders == null && !ScanUtils.empty(cxScannerService.getProperties().getExcludeFolders())) {
            excludeFolders = Arrays.asList(cxScannerService.getProperties().getExcludeFolders().split(","));
        }
        ScanRequest request = ScanRequest.builder().application(application).product(product).project(project).team(team).namespace(scanRequest.getNamespace()).repoName(scanRequest.getRepoName()).repoUrl(scanRequest.getGitUrl()).repoUrlWithAuth(scanRequest.getGitUrl()).repoType(ScanRequest.Repository.NA).branch(branch).refs(Constants.CX_BRANCH_PREFIX.concat(branch)).email(null).incremental(inc).scanPreset(scanPreset).excludeFolders(excludeFolders).excludeFiles(excludeFiles).bugTracker(bt).filter(filter).build();
        request.setId(uid);
        request.putAdditionalMetadata(HTMLHelper.WEB_HOOK_PAYLOAD, scanRequest.toString());
        if (!ScanUtils.empty(scanRequest.getResultUrl())) {
            request.putAdditionalMetadata("result_url", scanRequest.getResultUrl());
        }
        scanService.initiateAutomation(request);
    } catch (Exception e) {
        log.error("Error submitting Scan Request. {}", ExceptionUtils.getMessage(e), e);
        ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(EventResponse.builder().message(errorMessage).success(false).build());
    }
    return ResponseEntity.status(HttpStatus.OK).body(EventResponse.builder().message("Scan Request Successfully Submitted").success(true).build());
}
Also used : ScanRequest(com.checkmarx.flow.dto.ScanRequest) FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) BugTracker(com.checkmarx.flow.dto.BugTracker) InvalidTokenException(com.checkmarx.flow.exception.InvalidTokenException)

Example 14 with ScanRequest

use of com.checkmarx.flow.dto.ScanRequest in project cx-flow by checkmarx-ltd.

the class RunPublishProcessSteps method createExistingIssueForUpdate.

@Given("there is an existing issue")
public void createExistingIssueForUpdate() throws IOException, ExitThrowable, InterruptedException {
    ScanRequest request = getScanRequestWithDefaults();
    File file = getFileFromResourcePath("cucumber/data/sample-sast-results/1-finding-create-for-update.xml");
    innerPublishRequest(request, file);
    updateTime = jiraUtils.getIssueUpdatedTime(jiraProperties.getProject());
    issueId = jiraUtils.getFirstIssueId(jiraProperties.getProject());
    issueUpdateVulnerabilityType = jiraUtils.getIssueVulnerability(jiraProperties.getProject());
    issueUpdateFilename = jiraUtils.getIssueFilename(jiraProperties.getProject());
    Assert.assertTrue("Issue priority before update is incorrect", assertIssuePriority(ISSUE_PRIORITY_BEFORE_UPDATE));
    TimeUnit.SECONDS.sleep(2);
}
Also used : ScanRequest(com.checkmarx.flow.dto.ScanRequest) File(java.io.File) Given(io.cucumber.java.en.Given)

Example 15 with ScanRequest

use of com.checkmarx.flow.dto.ScanRequest in project cx-flow by checkmarx-ltd.

the class RunPublishProcessSteps method closeIssie.

@When("all issue's findings are false-positive")
public void closeIssie() throws IOException, ExitThrowable {
    ScanRequest request = getScanRequestWithDefaults();
    File file = getFileFromResourcePath("cucumber/data/sample-sast-results/1-finding-closed.xml");
    innerPublishRequest(request, file);
}
Also used : ScanRequest(com.checkmarx.flow.dto.ScanRequest) File(java.io.File) When(io.cucumber.java.en.When)

Aggregations

ScanRequest (com.checkmarx.flow.dto.ScanRequest)68 BugTracker (com.checkmarx.flow.dto.BugTracker)24 ScanResults (com.checkmarx.sdk.dto.ScanResults)20 When (io.cucumber.java.en.When)14 FilterConfiguration (com.checkmarx.sdk.dto.filtering.FilterConfiguration)12 MachinaException (com.checkmarx.flow.exception.MachinaException)11 CxConfig (com.checkmarx.sdk.dto.sast.CxConfig)11 Test (org.junit.Test)11 File (java.io.File)10 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)7 Issue (com.checkmarx.flow.dto.Issue)5 MachinaRuntimeException (com.checkmarx.flow.exception.MachinaRuntimeException)5 IOException (java.io.IOException)5 ExecutionException (java.util.concurrent.ExecutionException)5 TimeoutException (java.util.concurrent.TimeoutException)5 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)4 IfProfileValue (org.springframework.test.annotation.IfProfileValue)4 EventResponse (com.checkmarx.flow.dto.EventResponse)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 FlowProperties (com.checkmarx.flow.config.FlowProperties)2