Search in sources :

Example 1 with Sca

use of com.checkmarx.sdk.dto.sca.Sca in project cx-flow by checkmarx-ltd.

the class JiraService method mapCustomFields.

/**
 * Map custom JIRA fields to specific values (Custom Cx fields, Issue result
 * fields, static fields
 */
private void mapCustomFields(ScanRequest request, ScanResults.XIssue issue, IssueInputBuilder issueBuilder, boolean update) {
    BugTracker bugTracker = request.getBugTracker();
    log.debug("Handling custom field mappings");
    if (bugTracker.getFields() == null) {
        return;
    }
    String projectKey = bugTracker.getProjectKey();
    String issueTypeStr = bugTracker.getIssueType();
    for (com.checkmarx.flow.dto.Field f : bugTracker.getFields()) {
        String customField = getCustomFieldByName(projectKey, issueTypeStr, f.getJiraFieldName());
        String value = "";
        String fieldName;
        if (update && f.isSkipUpdate()) {
            log.debug("Skip update to field {}", f.getName());
            continue;
        }
        if (!ScanUtils.empty(customField)) {
            if (customField.equalsIgnoreCase("Labels")) {
                log.warn("Configuring the Labels parameter would affect issue tracking and might result in duplicate bug creation or bugs not closing or opening.");
            }
            /*cx | static | other - specific values that can be linked from scan request or the issue details*/
            String fieldType = f.getType();
            if (ScanUtils.empty(fieldType)) {
                log.warn("Field type not supplied for custom field: {}. Using 'result' by default.", customField);
                // use default = result
                fieldType = "result";
            }
            switch(fieldType) {
                case FlowConstants.MAIN_MDC_ENTRY:
                    log.debug("Checkmarx custom field {}", f.getName());
                    if (request.getCxFields() != null) {
                        log.debug("Checkmarx custom field");
                        value = request.getCxFields().get(f.getName());
                        log.debug("Cx Field value: {}", value);
                        if (ScanUtils.empty(value) && !ScanUtils.empty(f.getJiraDefaultValue())) {
                            value = f.getJiraDefaultValue();
                            log.debug("JIRA default Value is {}", value);
                        }
                    } else {
                        log.debug("No value found for {}", f.getName());
                        value = "";
                    }
                    break;
                case "sca-results":
                    if (issue.getScaDetails() == null) {
                        log.debug("Sca details not available");
                        break;
                    }
                    fieldName = f.getName();
                    switch(fieldName) {
                        case "package-name":
                            log.debug("package-name: {}", issue.getScaDetails().get(0).getVulnerabilityPackage().getId());
                            value = issue.getScaDetails().get(0).getVulnerabilityPackage().getId();
                            break;
                        case "current-version":
                            log.debug("current-version: {}", issue.getScaDetails().get(0).getVulnerabilityPackage().getVersion());
                            value = issue.getScaDetails().get(0).getVulnerabilityPackage().getVersion();
                            break;
                        case "fixed-version":
                            log.debug("fixed-version: {}", issue.getScaDetails().get(0).getFinding().getFixResolutionText());
                            value = issue.getScaDetails().get(0).getFinding().getFixResolutionText();
                            break;
                        case "newest-version":
                            log.debug(issue.getScaDetails().get(0).getVulnerabilityPackage().getNewestVersion());
                            value = issue.getScaDetails().get(0).getVulnerabilityPackage().getNewestVersion();
                            break;
                        case "locations":
                            List<String> locations = issue.getScaDetails().get(0).getVulnerabilityPackage().getLocations();
                            String location = null;
                            for (String l : locations) {
                                location = l + ",";
                            }
                            log.debug("locations: {}", location);
                            value = location.substring(0, location.length() - 1);
                            break;
                        case "dev-dependency":
                            log.debug("dev-dependency: {}", issue.getScaDetails().get(0).getVulnerabilityPackage().isDevelopment());
                            value = String.valueOf(issue.getScaDetails().get(0).getVulnerabilityPackage().isDevelopment()).toUpperCase();
                            break;
                        case "direct-dependency":
                            log.debug("direct-dependency: {}", issue.getScaDetails().get(0).getVulnerabilityPackage().isDirectDependency());
                            value = String.valueOf(issue.getScaDetails().get(0).getVulnerabilityPackage().isDirectDependency()).toUpperCase();
                            break;
                        case "risk-score":
                            log.debug("risk score: {}", issue.getScaDetails().get(0).getVulnerabilityPackage().getRiskScore());
                            value = String.valueOf(issue.getScaDetails().get(0).getVulnerabilityPackage().getRiskScore());
                            break;
                        case "outdated":
                            log.debug("outdated: {}", issue.getScaDetails().get(0).getVulnerabilityPackage().isOutdated());
                            value = String.valueOf(issue.getScaDetails().get(0).getVulnerabilityPackage().isOutdated()).toUpperCase();
                            break;
                        case "violates-policy":
                            log.debug("Violates-Policy: {}", issue.getScaDetails().get(0).getFinding().isViolatingPolicy());
                            value = String.valueOf(issue.getScaDetails().get(0).getFinding().isViolatingPolicy()).toUpperCase();
                    }
                    break;
                case "static":
                    log.debug("Static value {} - {}", f.getName(), f.getJiraDefaultValue());
                    value = f.getJiraDefaultValue();
                    break;
                default:
                    // result
                    fieldName = f.getName();
                    if (fieldName == null) {
                        log.warn("Field name not supplied for custom field: {}. Skipping.", customField);
                        /* there is no default, move on to the next field */
                        continue;
                    }
                    /*known values we can use*/
                    switch(fieldName) {
                        case "application":
                            log.debug("application: {}", request.getApplication());
                            value = request.getApplication();
                            break;
                        case "project":
                            log.debug("project: {}", request.getProject());
                            value = request.getProject();
                            break;
                        case "namespace":
                            log.debug("namespace: {}", request.getNamespace());
                            value = request.getNamespace();
                            break;
                        case "repo-name":
                            log.debug("repo-name: {}", request.getRepoName());
                            value = request.getRepoName();
                            break;
                        case "repo-url":
                            log.debug("repo-url: {}", request.getRepoUrl());
                            value = request.getRepoUrl();
                            break;
                        case "branch":
                            log.debug("branch: {}", request.getBranch());
                            value = request.getBranch();
                            break;
                        case "severity":
                            if (issue.getScaDetails() != null) {
                                log.debug("severity: {}", issue.getScaDetails().get(0).getFinding().getSeverity());
                                value = ScanUtils.toProperCase(String.valueOf(issue.getScaDetails().get(0).getFinding().getSeverity()));
                            } else {
                                log.debug("severity: {}", issue.getSeverity());
                                value = ScanUtils.toProperCase(issue.getSeverity());
                            }
                            break;
                        case "category":
                            log.debug("category: {}", issue.getVulnerability());
                            value = issue.getVulnerability();
                            break;
                        case "cwe":
                            log.debug("cwe: {}", issue.getCwe());
                            value = issue.getCwe();
                            break;
                        case "cve":
                            if (issue.getScaDetails() != null) {
                                log.debug("cve: {}", issue.getScaDetails().get(0).getFinding().getId());
                                value = issue.getScaDetails().get(0).getFinding().getId();
                            } else {
                                log.debug("cve: {}", issue.getCve());
                                value = issue.getCve();
                            }
                            break;
                        case "system-date":
                            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                            LocalDateTime now = LocalDateTime.now().plusDays(f.getOffset());
                            value = dtf.format(now);
                            log.debug("system date: {}", value);
                            break;
                        case "recommendation":
                            StringBuilder recommendation = new StringBuilder();
                            if (issue.getLink() != null && !issue.getLink().isEmpty()) {
                                recommendation.append("Checkmarx Link: ").append(issue.getLink()).append(HTMLHelper.CRLF);
                            }
                            if (!ScanUtils.anyEmpty(flowProperties.getMitreUrl(), issue.getCwe())) {
                                recommendation.append("Mitre Details: ").append(String.format(flowProperties.getMitreUrl(), issue.getCwe())).append(HTMLHelper.CRLF);
                            }
                            if (!ScanUtils.empty(flowProperties.getCodebashUrl())) {
                                recommendation.append("Training: ").append(issue.getAdditionalDetails().get(FlowConstants.CODE_BASHING_LESSON)).append(HTMLHelper.CRLF);
                            }
                            if (!ScanUtils.empty(flowProperties.getWikiUrl())) {
                                recommendation.append("Guidance: ").append(flowProperties.getWikiUrl()).append(HTMLHelper.CRLF);
                            }
                            value = recommendation.toString();
                            break;
                        case "loc":
                            value = "";
                            if (issue.getDetails() != null) {
                                List<Integer> lines = issue.getDetails().entrySet().stream().filter(x -> x.getKey() != null && x.getValue() != null && !x.getValue().isFalsePositive()).map(Map.Entry::getKey).collect(Collectors.toList());
                                if (!lines.isEmpty()) {
                                    Collections.sort(lines);
                                    value = StringUtils.join(lines, ",");
                                    log.debug("loc: {}", value);
                                }
                            }
                            break;
                        case "not-exploitable":
                            value = "";
                            List<Integer> fpLines;
                            if (issue.getDetails() != null) {
                                fpLines = issue.getDetails().entrySet().stream().filter(x -> x.getKey() != null && x.getValue() != null && x.getValue().isFalsePositive()).map(Map.Entry::getKey).collect(Collectors.toList());
                                if (!fpLines.isEmpty()) {
                                    Collections.sort(fpLines);
                                    value = StringUtils.join(fpLines, ",");
                                    log.debug("loc: {}", value);
                                }
                            }
                            break;
                        case "site":
                            log.debug("site: {}", request.getSite());
                            value = request.getSite();
                            break;
                        case "issue-link":
                            if (issue.getScaDetails() != null) {
                                log.debug("issue-link: {}", issue.getScaDetails().get(0).getVulnerabilityLink());
                                value = issue.getScaDetails().get(0).getVulnerabilityLink();
                            } else {
                                log.debug("issue-link: {}", issue.getLink());
                                value = issue.getLink();
                            }
                            break;
                        case "filename":
                            log.debug("filename: {}", issue.getFilename());
                            value = issue.getFilename();
                            break;
                        case "language":
                            log.debug("language: {}", issue.getLanguage());
                            value = issue.getLanguage();
                            break;
                        case "comment":
                            value = "";
                            StringBuilder comments = new StringBuilder();
                            String commentFmt = "[Line %s]: [%s]".concat(HTMLHelper.CRLF);
                            if (issue.getDetails() != null) {
                                issue.getDetails().entrySet().stream().filter(x -> x.getKey() != null && x.getValue() != null && x.getValue().getComment() != null && !x.getValue().getComment().isEmpty()).forEach(c -> comments.append(String.format(commentFmt, c.getKey(), c.getValue().getComment())));
                                value = comments.toString();
                            }
                            break;
                        default:
                            log.warn("field value for {} not found", f.getName());
                            value = "";
                    }
                    /*If the value is missing, check if a default value was specified*/
                    if (ScanUtils.empty(value)) {
                        log.debug("Value is empty, defaulting to configured default (if applicable)");
                        if (!ScanUtils.empty(f.getJiraDefaultValue())) {
                            value = f.getJiraDefaultValue();
                            log.debug("Default value is {}", value);
                        }
                    }
                    break;
            }
            /*Determine the expected custom field type within JIRA*/
            if (!ScanUtils.empty(value)) {
                String jiraFieldType = f.getJiraFieldType();
                if (ScanUtils.empty(jiraFieldType)) {
                    log.warn("JIRA field type not supplied for custom field: {}. Using 'text' by default.", f.getName());
                    // use default = text
                    jiraFieldType = "text";
                }
                List<String> list;
                switch(jiraFieldType) {
                    case SECURITY_FIELD_TYPE:
                        log.debug("Security field");
                        SecurityLevel securityLevel = getSecurityLevel(projectKey, issueTypeStr, value);
                        if (securityLevel != null) {
                            log.warn("JIRA Security level was not found: {}", value);
                            issueBuilder.setFieldValue(SECURITY_FIELD_TYPE, securityLevel);
                        }
                        break;
                    case "text":
                        log.debug("text field");
                        issueBuilder.setFieldValue(customField, value);
                        break;
                    case "component":
                        log.debug("component field");
                        issueBuilder.setComponentsNames(Collections.singletonList(value));
                        break;
                    case "label":
                        /*csv to array | replace space with _ */
                        log.debug("label field");
                        String[] l = StringUtils.split(value, ",");
                        list = new ArrayList<>();
                        for (String x : l) {
                            list.add(x.replaceAll("[^a-zA-Z0-9:\\-_]+", "_"));
                        }
                        if (!ScanUtils.empty(list)) {
                            issueBuilder.setFieldValue(customField, list);
                        }
                        break;
                    case "single-select":
                        log.debug("single select field");
                        issueBuilder.setFieldValue(customField, ComplexIssueInputFieldValue.with(VALUE_FIELD_TYPE, value));
                        break;
                    case "radio":
                        log.debug("radio field");
                        issueBuilder.setFieldValue(customField, ComplexIssueInputFieldValue.with(VALUE_FIELD_TYPE, value));
                        break;
                    case "multi-select":
                        log.debug("multi select field");
                        String[] selected = StringUtils.split(value, ",");
                        List<ComplexIssueInputFieldValue> fields = new ArrayList<>();
                        for (String s : selected) {
                            ComplexIssueInputFieldValue fieldValue = ComplexIssueInputFieldValue.with(VALUE_FIELD_TYPE, s.trim());
                            fields.add(fieldValue);
                        }
                        issueBuilder.setFieldValue(customField, fields);
                        break;
                    case "cascading-select":
                        log.debug("cascading select list field");
                        log.debug("cascading values {}", value);
                        addCascadingSelect(issueBuilder, f, customField, value);
                        break;
                    case "single-version-picker":
                        log.debug("single version picker");
                        issueBuilder.setFieldValue(customField, ComplexIssueInputFieldValue.with(NAME_FIELD_TYPE, value));
                        break;
                    case "multi-version-picker":
                        log.debug("multi version picker");
                        String[] selectedVersions = StringUtils.split(value, ",");
                        List<ComplexIssueInputFieldValue> versionList = new ArrayList<>();
                        for (String version : selectedVersions) {
                            ComplexIssueInputFieldValue fieldValue = ComplexIssueInputFieldValue.with(NAME_FIELD_TYPE, version.trim());
                            versionList.add(fieldValue);
                        }
                        issueBuilder.setFieldValue(customField, versionList);
                        break;
                    default:
                        log.warn("{} not a valid option for jira field type", f.getJiraFieldType());
                }
            }
        }
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) ScanRequest(com.checkmarx.flow.dto.ScanRequest) java.util(java.util) org.springframework.http(org.springframework.http) CustomAsynchronousJiraRestClientFactory(com.atlassian.jira.rest.client.internal.async.CustomAsynchronousJiraRestClientFactory) ScanResults(com.checkmarx.sdk.dto.ScanResults) URISyntaxException(java.net.URISyntaxException) LocalDateTime(java.time.LocalDateTime) FlowProperties(com.checkmarx.flow.config.FlowProperties) StringUtils(org.apache.commons.lang3.StringUtils) HTMLHelper(com.checkmarx.flow.utils.HTMLHelper) ComplexIssueInputFieldValue(com.atlassian.jira.rest.client.api.domain.input.ComplexIssueInputFieldValue) BugTracker(com.checkmarx.flow.dto.BugTracker) JSONObject(org.json.JSONObject) Service(org.springframework.stereotype.Service) com.atlassian.jira.rest.client.api(com.atlassian.jira.rest.client.api) Sca(com.checkmarx.sdk.dto.sca.Sca) DefaultUriBuilderFactory(org.springframework.web.util.DefaultUriBuilderFactory) URI(java.net.URI) JiraClientException(com.checkmarx.flow.exception.JiraClientException) JiraClientRunTimeException(com.checkmarx.flow.exception.JiraClientRunTimeException) RestTemplate(org.springframework.web.client.RestTemplate) MapUtils(org.apache.commons.collections4.MapUtils) CliMode(com.checkmarx.flow.config.CliMode) JiraConstants(com.checkmarx.flow.constants.JiraConstants) com.atlassian.jira.rest.client.api.domain(com.atlassian.jira.rest.client.api.domain) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ScanDetails(com.checkmarx.flow.dto.ScanDetails) JiraTicketsReport(com.checkmarx.flow.dto.report.JiraTicketsReport) Promise(io.atlassian.util.concurrent.Promise) IssueInputBuilder(com.atlassian.jira.rest.client.api.domain.input.IssueInputBuilder) TransitionInput(com.atlassian.jira.rest.client.api.domain.input.TransitionInput) SCATicketingConstants(com.checkmarx.flow.constants.SCATicketingConstants) Collectors(java.util.stream.Collectors) JiraProperties(com.checkmarx.flow.config.JiraProperties) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Slf4j(lombok.extern.slf4j.Slf4j) MachinaRuntimeException(com.checkmarx.flow.exception.MachinaRuntimeException) Paths(java.nio.file.Paths) ScanUtils(com.checkmarx.flow.utils.ScanUtils) DateTimeFormatter(java.time.format.DateTimeFormatter) FlowConstants(com.checkmarx.flow.constants.FlowConstants) PostConstruct(javax.annotation.PostConstruct) JSONArray(org.json.JSONArray) FieldInput(com.atlassian.jira.rest.client.api.domain.input.FieldInput) BugTracker(com.checkmarx.flow.dto.BugTracker) ComplexIssueInputFieldValue(com.atlassian.jira.rest.client.api.domain.input.ComplexIssueInputFieldValue) DateTimeFormatter(java.time.format.DateTimeFormatter) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 2 with Sca

use of com.checkmarx.sdk.dto.sca.Sca in project cx-flow by checkmarx-ltd.

the class ConfigurationOverrider method overrideUsingConfigProvider.

private void overrideUsingConfigProvider(Optional<CxConfig> fallback, Map<String, String> overrideReport, ScanRequest request) {
    ConfigProvider configProvider = ConfigProvider.getInstance();
    String uid = MDC.get(FlowConstants.MAIN_MDC_ENTRY);
    ScaConfig scaConfiguration = configProvider.getConfiguration(uid, ScaProperties.CONFIG_PREFIX, ScaConfig.class);
    if (scaConfiguration != null) {
        log.info("Overriding SCA properties from config provider configuration");
        scaConfigOverrider.overrideScanRequestProperties(scaConfiguration, request, overrideReport);
    } else {
        Sca scaPropertiesFromConfigAsCode = fallback.map(CxConfig::getSca).orElse(null);
        scaConfigOverrider.overrideScanRequestProperties(scaPropertiesFromConfigAsCode, request, overrideReport);
    }
    ASTConfig astConfiguration = configProvider.getConfiguration(uid, AstProperties.CONFIG_PREFIX, ASTConfig.class);
    if (astConfiguration != null) {
        log.info("Overriding AST properties from config provider configuration");
        overridePropertiesAst(astConfiguration, overrideReport, request);
    }
}
Also used : Sca(com.checkmarx.sdk.dto.sca.Sca) ConfigProvider(com.checkmarx.configprovider.ConfigProvider) ASTConfig(com.checkmarx.flow.config.external.ASTConfig)

Example 3 with Sca

use of com.checkmarx.sdk.dto.sca.Sca in project cx-flow by checkmarx-ltd.

the class ScaConfigurationOverrider method overrideScanRequestProperties.

public void overrideScanRequestProperties(Sca override, ScanRequest request, Map<String, String> overrideReport) {
    Optional<Sca> sca = Optional.ofNullable(override);
    if (!sca.isPresent()) {
        return;
    }
    ScaConfig scaConfig = request.getScaConfig();
    sca.map(Sca::getAccessControlUrl).ifPresent(accessControlUrl -> {
        scaConfig.setAccessControlUrl(accessControlUrl);
        overrideReport.put(ACCESS_CONTROL_URL, accessControlUrl);
    });
    sca.map(Sca::getApiUrl).ifPresent(apiUrl -> {
        scaConfig.setApiUrl(apiUrl);
        overrideReport.put(API_URL, apiUrl);
    });
    sca.map(Sca::getAppUrl).ifPresent(appUrl -> {
        scaConfig.setAppUrl(appUrl);
        overrideReport.put(APP_URL, appUrl);
    });
    sca.map(Sca::getTenant).ifPresent(tenant -> {
        scaConfig.setTenant(tenant);
        overrideReport.put(TENANT, tenant);
    });
    sca.map(Sca::getThresholdsSeverity).ifPresent(thresholdsSeverity -> {
        scaConfig.setThresholdsSeverityDirectly(thresholdsSeverity);
        overrideReport.put(THRESHOLDS_SEVERITY, ScanUtils.convertMapToString(thresholdsSeverity));
    });
    sca.map(Sca::getThresholdsScore).ifPresent(thresholdsScore -> {
        scaConfig.setThresholdsScore(thresholdsScore);
        overrideReport.put(THRESHOLDS_SCORE, String.valueOf(thresholdsScore));
    });
    sca.map(Sca::isIncludeSources).ifPresent(includeSources -> {
        scaConfig.setIncludeSources(includeSources);
        overrideReport.put(INCLUDE_SOURCES, String.valueOf(includeSources));
    });
    sca.map(Sca::getTeam).ifPresent(team -> {
        scaConfig.setTeam(team);
        overrideReport.put(TEAM, team);
    });
    overrideSeverityFilters(request, sca, overrideReport);
    overrideScoreFilter(request, sca, overrideReport);
}
Also used : Sca(com.checkmarx.sdk.dto.sca.Sca) ScaConfig(com.checkmarx.sdk.config.ScaConfig)

Aggregations

Sca (com.checkmarx.sdk.dto.sca.Sca)3 com.atlassian.jira.rest.client.api (com.atlassian.jira.rest.client.api)1 com.atlassian.jira.rest.client.api.domain (com.atlassian.jira.rest.client.api.domain)1 ComplexIssueInputFieldValue (com.atlassian.jira.rest.client.api.domain.input.ComplexIssueInputFieldValue)1 FieldInput (com.atlassian.jira.rest.client.api.domain.input.FieldInput)1 IssueInputBuilder (com.atlassian.jira.rest.client.api.domain.input.IssueInputBuilder)1 TransitionInput (com.atlassian.jira.rest.client.api.domain.input.TransitionInput)1 CustomAsynchronousJiraRestClientFactory (com.atlassian.jira.rest.client.internal.async.CustomAsynchronousJiraRestClientFactory)1 ConfigProvider (com.checkmarx.configprovider.ConfigProvider)1 CliMode (com.checkmarx.flow.config.CliMode)1 FlowProperties (com.checkmarx.flow.config.FlowProperties)1 JiraProperties (com.checkmarx.flow.config.JiraProperties)1 ASTConfig (com.checkmarx.flow.config.external.ASTConfig)1 FlowConstants (com.checkmarx.flow.constants.FlowConstants)1 JiraConstants (com.checkmarx.flow.constants.JiraConstants)1 SCATicketingConstants (com.checkmarx.flow.constants.SCATicketingConstants)1 BugTracker (com.checkmarx.flow.dto.BugTracker)1 ScanDetails (com.checkmarx.flow.dto.ScanDetails)1 ScanRequest (com.checkmarx.flow.dto.ScanRequest)1 JiraTicketsReport (com.checkmarx.flow.dto.report.JiraTicketsReport)1