Search in sources :

Example 16 with FilterConfiguration

use of com.checkmarx.sdk.dto.filtering.FilterConfiguration in project cx-flow by checkmarx-ltd.

the class CxFlowRunner method commandLineRunner.

private void commandLineRunner(ApplicationArguments args) throws ExitThrowable {
    String bugTracker;
    String application;
    String namespace;
    String repoName;
    String repoUrl;
    String branch;
    String mergeId;
    String mergeNoteUri = null;
    int mergeProjectId = 0;
    String projectId;
    String assignee;
    List<String> emails;
    String file;
    String libFile;
    String preset;
    String team;
    String cxProject;
    String altProject;
    String altFields;
    String config;
    String scanTag;
    List<String> severity;
    List<String> cwe;
    List<String> category;
    List<String> status;
    List<String> excludeFiles;
    List<String> excludeFolders;
    ScanRequest.Repository repoType = ScanRequest.Repository.NA;
    boolean osa;
    boolean force;
    FlowOverride flowOverride = null;
    ObjectMapper mapper = new ObjectMapper();
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    if (args.containsOption("branch-create")) {
        exit(ExitCode.SUCCESS);
    }
    if (args.containsOption("branch-delete")) {
        exit(ExitCode.SUCCESS);
    }
    if (!args.containsOption("scan") && !args.containsOption(PARSE_OPTION) && !args.containsOption(BATCH_OPTION) && !args.containsOption("project") && !args.containsOption(IAST_OPTION)) {
        log.error("--scan | --parse | --batch | --iast | --project option must be specified");
        exit(1);
    }
    // override with config
    if (args.containsOption("config")) {
        config = args.getOptionValues("config").get(0);
        try {
            flowOverride = mapper.readValue(new File(config), FlowOverride.class);
        } catch (IOException e) {
            log.error("Error reading config file, ignoring...", e);
        }
    }
    /*Collect command line options (String)*/
    bugTracker = getOptionValues(args, "bug-tracker");
    file = getOptionValues(args, "f");
    libFile = getOptionValues(args, "lib-file");
    repoName = getOptionValues(args, "repo-name");
    repoUrl = getOptionValues(args, "repo-url");
    branch = getOptionValues(args, "branch");
    namespace = getOptionValues(args, "namespace");
    projectId = getOptionValues(args, "project-id");
    team = getOptionValues(args, "cx-team");
    altProject = getOptionValues(args, "alt-project");
    altFields = getOptionValues(args, "alt-fields");
    cxProject = getOptionValues(args, "cx-project");
    application = getOptionValues(args, "app");
    assignee = getOptionValues(args, "assignee");
    mergeId = getOptionValues(args, "merge-id");
    preset = getOptionValues(args, "preset");
    scanTag = getOptionValues(args, "scan-tag");
    osa = args.getOptionValues("osa") != null;
    force = args.getOptionValues("forcescan") != null;
    /*Collect command line options (List of Strings)*/
    emails = args.getOptionValues("emails");
    severity = args.getOptionValues("severity");
    category = args.getOptionValues("category");
    cwe = args.getOptionValues("cwe");
    status = args.getOptionValues("status");
    excludeFiles = args.getOptionValues("exclude-files");
    excludeFolders = args.getOptionValues("exclude-folders");
    boolean usingBitBucketCloud = args.containsOption("bb");
    boolean usingBitBucketServer = args.containsOption("bbs");
    boolean disableCertificateValidation = args.containsOption("trust-cert");
    CxPropertiesBase cxProperties = cxScannerService.getProperties();
    Map<String, String> projectCustomFields = makeCustomFieldMap(args.getOptionValues("project-custom-field"));
    Map<String, String> scanCustomFields = makeCustomFieldMap(args.getOptionValues("scan-custom-field"));
    if (((ScanUtils.empty(namespace) && ScanUtils.empty(repoName) && ScanUtils.empty(branch)) && ScanUtils.empty(application)) && !args.containsOption(BATCH_OPTION) && !args.containsOption(IAST_OPTION)) {
        log.error("Namespace/Repo/Branch or Application (app) must be provided");
        exit(1);
    }
    if (args.containsOption(IAST_OPTION) && StringUtils.isEmpty(scanTag)) {
        log.error("--scan-tag must be provided for IAST tracking");
        exit(1);
    }
    ControllerRequest controllerRequest = new ControllerRequest(severity, cwe, category, status, null);
    FilterConfiguration filter = filterFactory.getFilter(controllerRequest, flowProperties);
    // Adding default file/folder exclusions from properties if they are not provided as an override
    if (excludeFiles == null && !ScanUtils.empty(cxProperties.getExcludeFiles())) {
        excludeFiles = Arrays.asList(cxProperties.getExcludeFiles().split(","));
    }
    if (excludeFolders == null && !ScanUtils.empty(cxProperties.getExcludeFolders())) {
        excludeFolders = Arrays.asList(cxProperties.getExcludeFolders().split(","));
    }
    if (ScanUtils.empty(bugTracker)) {
        bugTracker = flowProperties.getBugTracker();
    }
    BugTracker.Type bugType = getBugTrackerType(bugTracker);
    ScanRequest.Product product;
    if (osa) {
        if (libFile == null) {
            log.error("Both vulnerabilities file (f) and libraries file (lib-file) must be provided for OSA");
            exit(1);
        }
        product = ScanRequest.Product.CXOSA;
    } else {
        product = ScanRequest.Product.CX;
    }
    if (ScanUtils.empty(preset)) {
        preset = cxProperties.getScanPreset();
    }
    BugTracker bt = null;
    String gitAuthUrl = null;
    switch(bugType) {
        case WAIT:
        case wait:
            log.info("No bug tracker will be used...waiting for scan to complete");
            bugType = BugTracker.Type.WAIT;
            bt = BugTracker.builder().type(bugType).build();
            break;
        case NONE:
            log.info("No bug tracker will be used");
            bugType = BugTracker.Type.NONE;
            bt = BugTracker.builder().type(bugType).build();
            break;
        case JIRA:
            bt = jiraPropertiesToBugTracker().type(bugType).assignee(assignee).build();
            break;
        case ADOPULL:
        case adopull:
            bugType = BugTracker.Type.ADOPULL;
            bt = BugTracker.builder().type(bugType).build();
            repoType = ScanRequest.Repository.ADO;
            if (ScanUtils.empty(namespace) || ScanUtils.empty(repoName) || ScanUtils.empty(mergeId)) {
                log.error("Namespace/Repo/MergeId must be provided for ADOPULL bug tracking");
                exit(1);
            }
            mergeNoteUri = adoProperties.getMergeNoteUri(namespace, repoName, mergeId);
            break;
        case GITHUBPULL:
        case githubpull:
            bugType = BugTracker.Type.GITHUBPULL;
            bt = BugTracker.builder().type(bugType).build();
            repoType = ScanRequest.Repository.GITHUB;
            if (ScanUtils.empty(namespace) || ScanUtils.empty(repoName) || ScanUtils.empty(mergeId)) {
                log.error("--namespace, --repo and --merge-id must be provided for GITHUBPULL bug tracking");
                exit(1);
            }
            mergeNoteUri = gitHubProperties.getMergeNoteUri(namespace, repoName, mergeId);
            repoUrl = getNonEmptyRepoUrl(namespace, repoName, repoUrl, gitHubProperties.getGitUri(namespace, repoName));
            break;
        case GITLABMERGE:
        case gitlabmerge:
            log.info("Handling GitLab merge request for project: {}, merge id: {}", projectId, mergeId);
            bugType = BugTracker.Type.GITLABMERGE;
            bt = BugTracker.builder().type(bugType).build();
            repoType = ScanRequest.Repository.GITLAB;
            if (ScanUtils.empty(projectId) || ScanUtils.empty(mergeId)) {
                log.error("--project-id and --merge-id must be provided for GITLABMERGE bug tracking");
                exit(1);
            }
            mergeNoteUri = gitLabProperties.getMergeNoteUri(projectId, mergeId);
            mergeProjectId = Integer.parseInt(projectId);
            if (!ScanUtils.empty(namespace) && !ScanUtils.empty(repoName)) {
                repoUrl = getNonEmptyRepoUrl(namespace, repoName, repoUrl, gitLabProperties.getGitUri(namespace, repoName));
            }
            break;
        case BITBUCKETPULL:
        case bitbucketserverpull:
            log.info("BitBucket Pull not currently supported from command line");
            exit(1);
            break;
        case EMAIL:
            break;
        case CUSTOM:
            log.info("Using custom bean implementation  for bug tracking");
            bt = BugTracker.builder().type(bugType).customBean(bugTracker).build();
            break;
        default:
            log.warn("No supported bug tracking type provided");
    }
    ScanRequest request = ScanRequest.builder().application(application).product(product).namespace(namespace).team(team).project(cxProject).repoName(repoName).mergeNoteUri(mergeNoteUri).repoUrl(repoUrl).repoUrlWithAuth(gitAuthUrl).repoType(repoType).branch(branch).refs(null).email(emails).incremental(cxProperties.getIncremental()).scanPreset(preset).excludeFolders(excludeFolders).excludeFiles(excludeFiles).bugTracker(bt).filter(filter).altProject(altProject).altFields(altFields).forceScan(force).disableCertificateValidation(disableCertificateValidation).cxFields(projectCustomFields).scanFields(scanCustomFields).build();
    if (projectId != null) {
        try {
            Integer repoProjectId = Integer.parseInt(projectId);
            request.setRepoProjectId(repoProjectId);
        } catch (RuntimeException e) {
            log.error("Can't parse project-id", e);
        }
    }
    request = configOverrider.overrideScanRequestProperties(flowOverride, request);
    /*Determine if BitBucket Cloud/Server is being used - this will determine formatting of URL that links to file/line in repository */
    request.setId(uid);
    if (usingBitBucketCloud) {
        request.setRepoType(ScanRequest.Repository.BITBUCKETSERVER);
    // TODO create browse code url
    } else if (usingBitBucketServer) {
        request.setRepoType(ScanRequest.Repository.BITBUCKETSERVER);
        repoUrl = getBitBuckerServerBrowseUrl(repoUrl);
        request.putAdditionalMetadata("BITBUCKET_BROWSE", repoUrl);
    } else if (bugType.equals(BugTracker.Type.GITLABMERGE)) {
        request.setRepoProjectId(mergeProjectId);
        request.putAdditionalMetadata(FlowConstants.MERGE_ID, mergeId);
    }
    try {
        if (args.containsOption(PARSE_OPTION)) {
            File f = new File(file);
            if (!f.exists()) {
                log.error("Result File not found {}", file);
                exit(ExitCode.ARGUMENT_NOT_PROVIDED);
            }
            if (osa) {
                // grab the libs file if OSA results
                File libs = new File(libFile);
                if (!libs.exists()) {
                    log.error("Library File not found {}", file);
                    exit(ExitCode.ARGUMENT_NOT_PROVIDED);
                }
                cxOsaParse(request, f, libs);
            } else {
                // SAST
                List<String> enabledScanners = flowProperties.getEnabledVulnerabilityScanners();
                if (args.containsOption("offline")) {
                    cxProperties.setOffline(true);
                }
                log.info("Processing Checkmarx result file {}", file);
                if ((bugType.equals(BugTracker.Type.CUSTOM))) {
                    if (request.getBugTracker().getCustomBean().equalsIgnoreCase("CxXml")) {
                        log.error("The CxXml bugtracker is not support for parse mode{}");
                        exit(ExitCode.BUILD_INTERRUPTED);
                    }
                }
                if (enabledScanners.contains("sast") && enabledScanners.contains("sca")) {
                    log.error("At a time only single scanner type is supported for parse mode implementation{}");
                    exit(ExitCode.BUILD_INTERRUPTED);
                }
                cxParse(request, f);
            }
        } else if (args.containsOption(BATCH_OPTION)) {
            log.info("Executing batch process");
            cxBatch(request);
        } else if (args.containsOption("project")) {
            if (ScanUtils.empty(cxProject)) {
                log.error("cx-project must be provided when --project option is used");
                exit(ExitCode.ARGUMENT_NOT_PROVIDED);
            }
            request.setCliMode(CliMode.PROJECT);
            publishLatestScanResults(request);
        } else if (args.containsOption("scan") || args.containsOption(IAST_OPTION)) {
            log.info("Executing scan process");
            request.setCliMode(CliMode.SCAN);
            // GitHub Scan with Git Clone
            if (args.containsOption("github")) {
                repoUrl = getNonEmptyRepoUrl(namespace, repoName, repoUrl, gitHubProperties.getGitUri(namespace, repoName));
                String token = gitHubProperties.getToken();
                gitAuthUrl = repoUrl.replace(Constants.HTTPS, Constants.HTTPS.concat(token).concat("@"));
                gitAuthUrl = gitAuthUrl.replace(Constants.HTTP, Constants.HTTP.concat(token).concat("@"));
                scanRemoteRepo(request, repoUrl, gitAuthUrl, branch, ScanRequest.Repository.GITHUB, args);
            } else // GitLab Scan with Git Clone
            if (args.containsOption("gitlab") && !ScanUtils.anyEmpty(namespace, repoName)) {
                repoUrl = getNonEmptyRepoUrl(namespace, repoName, repoUrl, gitLabProperties.getGitUri(namespace, repoName));
                String token = gitLabProperties.getToken();
                gitAuthUrl = repoUrl.replace(Constants.HTTPS, Constants.HTTPS_OAUTH2.concat(token).concat("@"));
                gitAuthUrl = gitAuthUrl.replace(Constants.HTTP, Constants.HTTP_OAUTH2.concat(token).concat("@"));
                scanRemoteRepo(request, repoUrl, gitAuthUrl, branch, ScanRequest.Repository.GITLAB, args);
            } else if (args.containsOption("bitbucket") && containsRepoArgs(namespace, repoName, branch)) {
                log.warn("Bitbucket git clone scan not implemented");
            } else if (args.containsOption("ado") && containsRepoArgs(namespace, repoName, branch)) {
                if (!args.containsOption(IAST_OPTION)) {
                    // Azure implement for IAST integration
                    log.warn("Azure DevOps git clone scan not implemented");
                }
            } else if (file != null) {
                scanLocalPath(request, file);
            } else {
                log.error("No valid option was provided for driving scan");
            }
            if (args.containsOption(IAST_OPTION)) {
                configureIast(request, scanTag, args);
            }
        }
    } catch (Exception e) {
        log.error("An error occurred while processing request", e);
        exit(ExitCode.BUILD_INTERRUPTED);
    }
    log.info("Completed Successfully");
    exit(ExitCode.SUCCESS);
}
Also used : CxPropertiesBase(com.checkmarx.sdk.config.CxPropertiesBase) FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) IOException(java.io.IOException) JiraClientException(com.checkmarx.flow.exception.JiraClientException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) MachinaException(com.checkmarx.flow.exception.MachinaException) MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 17 with FilterConfiguration

use of com.checkmarx.sdk.dto.filtering.FilterConfiguration in project cx-flow by checkmarx-ltd.

the class ADOController method pullRequest.

/**
 * Pull Request event submitted (JSON)
 */
@PostMapping(value = { "/{product}/ado/pull", "/ado/pull" })
public ResponseEntity<EventResponse> pullRequest(@RequestBody PullEvent body, @RequestHeader(value = AUTHORIZATION) String auth, @PathVariable(value = "product", required = false) String product, ControllerRequest controllerRequest, AdoDetailsRequest adoDetailsRequest) {
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    log.info("Processing Azure PULL request");
    Action action = Action.PULL;
    controllerRequest = ensureNotNull(controllerRequest);
    validateBasicAuth(auth, controllerRequest);
    adoDetailsRequest = ensureDetailsNotNull(adoDetailsRequest);
    ResourceContainers resourceContainers = body.getResourceContainers();
    if (!PULL_EVENT.contains(body.getEventType()) || !body.getResource().getStatus().equals("active")) {
        log.info("Pull requested not processed.  Event was not opened ({})", body.getEventType());
        return ResponseEntity.status(HttpStatus.OK).body(EventResponse.builder().message("No processing occurred for updates to Pull Request").success(true).build());
    }
    try {
        Resource resource = body.getResource();
        Repository repository = resource.getRepository();
        String pullUrl = resource.getUrl();
        String app = repository.getName();
        if (repository.getName().startsWith(properties.getTestRepository())) {
            log.info("Handling ADO Test Event");
            return ResponseEntity.status(HttpStatus.OK).body(EventResponse.builder().message("Test Event").success(true).build());
        }
        if (StringUtils.isNotEmpty(controllerRequest.getApplication())) {
            app = controllerRequest.getApplication();
        }
        BugTracker.Type bugType = BugTracker.Type.ADOPULL;
        if (StringUtils.isNotEmpty(controllerRequest.getBug())) {
            bugType = ScanUtils.getBugTypeEnum(controllerRequest.getBug(), flowProperties.getBugTrackerImpl());
        }
        if (controllerRequest.getAppOnly() != null) {
            flowProperties.setTrackApplicationOnly(controllerRequest.getAppOnly());
        }
        initAdoSpecificParams(adoDetailsRequest);
        if (StringUtils.isEmpty(product)) {
            product = ScanRequest.Product.CX.getProduct();
        }
        ScanRequest.Product p = ScanRequest.Product.valueOf(product.toUpperCase(Locale.ROOT));
        String ref = resource.getSourceRefName();
        String currentBranch = ScanUtils.getBranchFromRef(ref);
        String targetBranch = ScanUtils.getBranchFromRef(resource.getTargetRefName());
        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
        String gitUrl = repository.getWebUrl();
        String token = scmConfigOverrider.determineConfigToken(properties, controllerRequest.getScmInstance());
        log.info("Using url: {}", gitUrl);
        String gitAuthUrl = gitAuthUrlGenerator.addCredToUrl(ScanRequest.Repository.ADO, gitUrl, token);
        ScanRequest request = ScanRequest.builder().application(app).product(p).project(controllerRequest.getProject()).team(controllerRequest.getTeam()).namespace(determineNamespace(resourceContainers)).repoName(repository.getName()).repoUrl(gitUrl).repoUrlWithAuth(gitAuthUrl).repoType(ScanRequest.Repository.ADO).branch(currentBranch).refs(ref).mergeNoteUri(pullUrl.concat("/threads")).mergeTargetBranch(targetBranch).email(null).scanPreset(controllerRequest.getPreset()).incremental(controllerRequest.getIncremental()).excludeFolders(controllerRequest.getExcludeFolders()).excludeFiles(controllerRequest.getExcludeFiles()).bugTracker(bt).filter(filter).thresholds(thresholdMap).organizationId(determineNamespace(resourceContainers)).gitUrl(gitUrl).build();
        setScmInstance(controllerRequest, request);
        request.putAdditionalMetadata(ADOService.PROJECT_SELF_URL, getTheProjectURL(body.getResourceContainers()));
        fillRequestWithAdditionalData(request, repository, body.toString());
        checkForConfigAsCode(request, getConfigBranch(request, resource, action));
        request.putAdditionalMetadata("statuses_url", pullUrl.concat("/statuses"));
        addMetadataToScanRequest(adoDetailsRequest, request);
        request.setId(uid);
        // only initiate scan/automation if target 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) BugTracker(com.checkmarx.flow.dto.BugTracker) ScanRequest(com.checkmarx.flow.dto.ScanRequest)

Example 18 with FilterConfiguration

use of com.checkmarx.sdk.dto.filtering.FilterConfiguration in project cx-flow by checkmarx-ltd.

the class ADOController method pushRequest.

/**
 * Push Request event submitted (JSON), along with the Product (cx for example)
 */
@PostMapping(value = { "/{product}/ado/push", "/ado/push" })
public ResponseEntity<EventResponse> pushRequest(@RequestBody PushEvent body, @RequestHeader(value = AUTHORIZATION) String auth, @PathVariable(value = "product", required = false) String product, ControllerRequest controllerRequest, AdoDetailsRequest adoDetailsRequest) {
    // TODO handle different state (Active/Closed)
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    log.info("Processing Azure Push request");
    Action action = Action.PUSH;
    controllerRequest = ensureNotNull(controllerRequest);
    validateBasicAuth(auth, controllerRequest);
    adoDetailsRequest = ensureDetailsNotNull(adoDetailsRequest);
    ResourceContainers resourceContainers = body.getResourceContainers();
    try {
        Resource resource = body.getResource();
        Repository repository = resource.getRepository();
        String app = repository.getName();
        if (repository.getName().startsWith(properties.getTestRepository())) {
            log.info("Handling ADO Test Event");
            return ResponseEntity.status(HttpStatus.OK).body(EventResponse.builder().message("Test Event").success(true).build());
        }
        if (StringUtils.isNotEmpty(controllerRequest.getApplication())) {
            app = controllerRequest.getApplication();
        }
        // set the default bug tracker as per yml
        setBugTracker(flowProperties, controllerRequest);
        BugTracker.Type bugType = ScanUtils.getBugTypeEnum(controllerRequest.getBug(), flowProperties.getBugTrackerImpl());
        initAdoSpecificParams(adoDetailsRequest);
        if (controllerRequest.getAppOnly() != null) {
            flowProperties.setTrackApplicationOnly(controllerRequest.getAppOnly());
        }
        if (StringUtils.isEmpty(product)) {
            product = ScanRequest.Product.CX.getProduct();
        }
        ScanRequest.Product p = ScanRequest.Product.valueOf(product.toUpperCase(Locale.ROOT));
        // determine branch (without refs)
        String ref = resource.getRefUpdates().get(0).getName();
        String currentBranch = ScanUtils.getBranchFromRef(ref);
        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);
        List<String> emails = determineEmails(resource);
        // build request object
        String gitUrl = repository.getRemoteUrl();
        log.debug("Using url: {}", gitUrl);
        String configToken = scmConfigOverrider.determineConfigToken(properties, controllerRequest.getScmInstance());
        String gitAuthUrl = gitAuthUrlGenerator.addCredToUrl(ScanRequest.Repository.ADO, gitUrl, configToken);
        String defaultBranch = ScanUtils.getBranchFromRef(Optional.ofNullable(repository.getDefaultBranch()).orElse(ref));
        ScanRequest request = ScanRequest.builder().application(app).product(p).project(controllerRequest.getProject()).team(controllerRequest.getTeam()).namespace(determineNamespace(resourceContainers)).altProject(determineAzureProject(repository)).repoName(repository.getName()).repoUrl(gitUrl).repoUrlWithAuth(gitAuthUrl).repoType(ScanRequest.Repository.ADO).branch(currentBranch).defaultBranch(defaultBranch).refs(ref).email(emails).scanPreset(controllerRequest.getPreset()).incremental(controllerRequest.getIncremental()).excludeFolders(controllerRequest.getExcludeFolders()).excludeFiles(controllerRequest.getExcludeFiles()).bugTracker(bt).filter(filter).thresholds(thresholdMap).organizationId(determineNamespace(resourceContainers)).gitUrl(gitUrl).build();
        setScmInstance(controllerRequest, request);
        request.putAdditionalMetadata(ADOService.PROJECT_SELF_URL, getTheProjectURL(body.getResourceContainers()));
        addMetadataToScanRequest(adoDetailsRequest, request);
        fillRequestWithAdditionalData(request, repository, body.toString());
        // if an override blob/file is provided, substitute these values
        checkForConfigAsCode(request, getConfigBranch(request, resource, action));
        request.setId(uid);
        // only initiate scan/automation if target branch is applicable
        if (helperService.isBranch2Scan(request, branches)) {
            flowService.initiateAutomation(request);
        } else if (isDeleteBranchEvent(resource) && properties.getDeleteCxProject()) {
            flowService.deleteProject(request);
        }
    } catch (IllegalArgumentException e) {
        return getBadRequestMessage(e, controllerRequest, product);
    }
    return getSuccessMessage();
}
Also used : FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) BugTracker(com.checkmarx.flow.dto.BugTracker) ScanRequest(com.checkmarx.flow.dto.ScanRequest)

Example 19 with FilterConfiguration

use of com.checkmarx.sdk.dto.filtering.FilterConfiguration in project cx-flow by checkmarx-ltd.

the class PostRequestData method latestScanResults.

@GetMapping(value = "/scanresults", produces = "application/json")
public ScanResults latestScanResults(// Mandatory parameters
@RequestParam(value = "project") String project, @RequestHeader(value = TOKEN_HEADER) String token, // Optional parameters
@RequestParam(value = "team", required = false) String team, @RequestParam(value = "application", required = false) String application, @RequestParam(value = "severity", required = false) List<String> severity, @RequestParam(value = "cwe", required = false) List<String> cwe, @RequestParam(value = "category", required = false) List<String> category, @RequestParam(value = "status", required = false) List<String> status, @RequestParam(value = "assignee", required = false) String assignee, @RequestParam(value = "override", required = false) String override, @RequestParam(value = "bug", required = false) String bug) {
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    // Validate shared API token from header
    validateToken(token);
    // This primes the shard when Shard Manager is turned on
    if (cxProperties.getEnableShardManager()) {
        ShardSession shard = sessionTracker.getShardSession();
        // ensures this gets fixed like this: /CxServer/CHECKMARX
        if (team.charAt(0) != '/') {
            team = ("/" + team);
        }
        shard.setTeam(team);
        shard.setProject(project);
    }
    // Create bug tracker
    BugTracker bugTracker = getBugTracker(assignee, bug);
    // Create filters if available
    ControllerRequest request = new ControllerRequest(severity, cwe, category, status, null);
    FilterConfiguration filter = filterFactory.getFilter(request, properties);
    // Create the scan request
    ScanRequest scanRequest = ScanRequest.builder().application(ScanUtils.empty(application) ? project : application).product(// Default product: CX
    ScanRequest.Product.CX).project(project).team(team).bugTracker(bugTracker).filter(filter).build();
    scanRequest.setId(uid);
    // If an override blob/file is provided, substitute these values
    if (!ScanUtils.empty(override)) {
        FlowOverride ovr = ScanUtils.getMachinaOverride(override);
        scanRequest = configOverrider.overrideScanRequestProperties(ovr, scanRequest);
    }
    // Fetch the Checkmarx Scan Results based on given ScanRequest.
    // The cxProject parameter is null because the required project metadata
    // is already contained in the scanRequest parameter.
    ScanResults scanResults = CxScannerService.getScanner(cxgoScanner, sastScanner).getLatestScanResults(scanRequest);
    log.debug("ScanResults {}", scanResults);
    return scanResults;
}
Also used : ScanRequest(com.checkmarx.flow.dto.ScanRequest) ShardSession(com.checkmarx.sdk.ShardManager.ShardSession) ScanResults(com.checkmarx.sdk.dto.ScanResults) FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) BugTracker(com.checkmarx.flow.dto.BugTracker) ControllerRequest(com.checkmarx.flow.dto.ControllerRequest) FlowOverride(com.checkmarx.flow.dto.FlowOverride)

Example 20 with FilterConfiguration

use of com.checkmarx.sdk.dto.filtering.FilterConfiguration in project cx-flow by checkmarx-ltd.

the class PostRequestData method determineFilter.

private FilterConfiguration determineFilter(CxScanRequest scanRequest) {
    FilterConfiguration filter;
    boolean hasSimpleFilters = CollectionUtils.isNotEmpty(scanRequest.getFilters());
    boolean hasFilterScript = StringUtils.isNotEmpty(scanRequest.getFilterScript());
    if (hasSimpleFilters || hasFilterScript) {
        filter = filterFactory.getFilterFromComponents(scanRequest.getFilterScript(), scanRequest.getFilters());
    } else {
        filter = filterFactory.getFilter(null, properties);
    }
    return filter;
}
Also used : FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration)

Aggregations

FilterConfiguration (com.checkmarx.sdk.dto.filtering.FilterConfiguration)26 BugTracker (com.checkmarx.flow.dto.BugTracker)13 ScanRequest (com.checkmarx.flow.dto.ScanRequest)12 ScanResults (com.checkmarx.sdk.dto.ScanResults)6 Filter (com.checkmarx.sdk.dto.sast.Filter)6 EngineFilterConfiguration (com.checkmarx.sdk.dto.filtering.EngineFilterConfiguration)5 CxConfig (com.checkmarx.sdk.dto.sast.CxConfig)4 IOException (java.io.IOException)4 ControllerRequest (com.checkmarx.flow.dto.ControllerRequest)3 MachinaRuntimeException (com.checkmarx.flow.exception.MachinaRuntimeException)3 CheckmarxException (com.checkmarx.sdk.exception.CheckmarxException)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 ArrayList (java.util.ArrayList)3 Test (org.junit.Test)3 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)3 FlowOverride (com.checkmarx.flow.dto.FlowOverride)2 Repository (com.checkmarx.flow.dto.bitbucket.Repository)2 InvalidTokenException (com.checkmarx.flow.exception.InvalidTokenException)2 MachinaException (com.checkmarx.flow.exception.MachinaException)2 CxScanParams (com.checkmarx.sdk.dto.cx.CxScanParams)2