Search in sources :

Example 51 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class CxService method createScan.

@Override
public Integer createScan(CxScanParams params, String comment) throws CheckmarxException {
    log.info("Creating scan...");
    log.debug("Creating scan with params: {} and comment: \"{}\"", params, comment);
    validateScanParams(params);
    String teamId = determineTeamId(params);
    Integer projectId = determineProjectId(params, teamId);
    boolean projectExistedBeforeScan = !projectId.equals(UNKNOWN_INT);
    if (!projectExistedBeforeScan) {
        /*
                When CxBranch is set to true, the current and default branches are compared if they are same then a licensed project is created,
                if they are not same then, the ID of the default or base project is retrieved to create a branch project for the current branch of the repo,
                if a project for default branch is not present then it is first created and then a branched project is created from it.
             */
        Integer baseProjectId;
        String derivedProjectName = "";
        if (cxProperties.getCxBranch()) {
            if (!params.getBranch().equals(params.getDefaultBranch())) {
                String currentBranch = params.getBranch().replace("refs/heads/", "");
                log.debug("Current branch is {}", currentBranch);
                String defaultBranch = params.getDefaultBranch().replace("refs/heads/", "");
                log.debug("Target/default branch is {}", defaultBranch);
                if (!params.getPreserveProjectName()) {
                    currentBranch = currentBranch.replaceAll("[^a-zA-Z0-9-_.]+", "-");
                    defaultBranch = defaultBranch.replaceAll("[^a-zA-Z0-9-_.]+", "-");
                    log.debug("Normalized name for current branch is {} and target/default branch is {}", currentBranch, defaultBranch);
                }
                derivedProjectName = params.getProjectName().replace(currentBranch, defaultBranch);
                log.debug("Derived project name : {}", derivedProjectName);
                baseProjectId = getProjectId(teamId, derivedProjectName);
                if (baseProjectId.equals(UNKNOWN_INT)) {
                    baseProjectId = createProject(teamId, derivedProjectName);
                }
                projectId = branchProject(baseProjectId, params.getProjectName());
            } else {
                projectId = createProject(teamId, params.getProjectName());
            }
        } else {
            projectId = createProject(teamId, params.getProjectName());
        }
        if (projectId.equals(UNKNOWN_INT)) {
            throw new CheckmarxException("Project was not created successfully: ".concat(params.getProjectName()));
        }
    }
    if (!projectExistedBeforeScan || cxProperties.getSettingsOverride()) {
        log.debug("Updating project...");
        Integer presetId = getPresetId(params.getScanPreset());
        Integer engineConfigurationId = getScanConfiguration(params.getScanConfiguration());
        createScanSetting(projectId, presetId, engineConfigurationId, cxProperties.getPostActionPostbackId());
        setProjectExcludeDetails(projectId, params.getFolderExclude(), params.getFileExclude());
        if (params.getCustomFields() != null && !params.getCustomFields().isEmpty()) {
            List<CxCustomField> fieldDefinitions = getCustomFields();
            List<CxProject.CustomField> customFields = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.getCustomFields().entrySet()) {
                boolean matched = false;
                for (CxCustomField fieldDefinition : fieldDefinitions) {
                    if (fieldDefinition.getName().equalsIgnoreCase(entry.getKey())) {
                        matched = true;
                        CxProject.CustomField customField = new CxProject.CustomField();
                        customField.setId(fieldDefinition.getId());
                        customField.setName(fieldDefinition.getName());
                        customField.setValue(entry.getValue());
                        customFields.add(customField);
                    }
                }
                if (!matched) {
                    log.warn("{}: ignoring unrecognised custom field", entry.getKey());
                }
            }
            CxProject cxProject = CxProject.builder().id(projectId).name(params.getProjectName()).teamId(teamId).customFields(customFields).build();
            log.debug("cxProject: {}", cxProject);
            updateProjectCustomFields(cxProject);
        }
    }
    prepareSources(params, projectId);
    if (params.isIncremental() && projectExistedBeforeScan) {
        LocalDateTime scanDate = getLastScanDate(projectId);
        if (scanDate == null || LocalDateTime.now().isAfter(scanDate.plusDays(cxProperties.getIncrementalThreshold()))) {
            log.debug("Last scanDate: {}", scanDate);
            log.info("Last scanDate does not meet the threshold for an incremental scan.");
            params.setIncremental(false);
        } else {
            log.info("Scan will be incremental");
        }
    } else {
        log.info("Scan will be Full Scan");
        params.setIncremental(false);
    }
    CxScan scan = CxScan.builder().projectId(projectId).isIncremental(params.isIncremental()).forceScan(params.isForceScan()).isPublic(params.isPublic()).comment(comment).customFields(params.getScanCustomFields()).build();
    log.debug("scan: {}", scan);
    HttpHeaders headers = authClient.createAuthHeaders();
    headers.add(CxHttpClient.ORIGIN_HEADER, ScanClientHelper.CX_FLOW_SCAN_ORIGIN_NAME);
    HttpEntity<CxScan> requestEntity = new HttpEntity<>(scan, headers);
    log.info("Creating Scan for project Id {}", projectId);
    try {
        String response = restTemplate.postForObject(cxProperties.getUrl().concat(SCAN), requestEntity, String.class);
        JSONObject obj = new JSONObject(response);
        String id = obj.get("id").toString();
        log.info("Scan created with Id {} for project Id {}", id, projectId);
        return Integer.parseInt(id);
    } catch (HttpStatusCodeException e) {
        log.error(SCAN_CREATION_ERROR, projectId, e.getStatusCode());
        log.error(ExceptionUtils.getStackTrace(e));
    } finally {
        if (params.isGitSource() && cxProperties.getEnabledZipScan() || params.isFileSource()) {
            FileUtils.deleteQuietly(new File(params.getFilePath()));
        }
    }
    log.info("...Finished creating scan");
    return UNKNOWN_INT;
}
Also used : LocalDateTime(java.time.LocalDateTime) CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) JSONObject(org.json.JSONObject) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) File(java.io.File)

Example 52 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class CxService method getTeams.

@Override
public List<CxTeam> getTeams() throws CheckmarxException {
    HttpEntity httpEntity = new HttpEntity<>(authClient.createAuthHeaders());
    try {
        log.info("Retrieving Cx teams");
        ResponseEntity<CxTeam[]> response = restTemplate.exchange(cxProperties.getUrl().concat(TEAMS), HttpMethod.GET, httpEntity, CxTeam[].class);
        CxTeam[] teams = response.getBody();
        if (teams == null) {
            throw new CheckmarxException("Error retrieving teams");
        }
        return Arrays.asList(teams);
    } catch (HttpStatusCodeException e) {
        log.error(ERROR_GETTING_TEAMS);
        log.error(ExceptionUtils.getStackTrace(e));
        throw new CheckmarxException("Error occurred while retrieving teams");
    }
}
Also used : CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException)

Example 53 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class CxService method mapTeamLdap.

/**
 * @param ldapServerId
 * @param teamId
 * @param teamName not used in 9.0+
 * @param ldapGroupDn
 * @throws CheckmarxException
 */
@Override
public void mapTeamLdap(Integer ldapServerId, String teamId, String teamName, String ldapGroupDn) throws CheckmarxException {
    if (cxProperties.getVersion() < 9.0) {
        log.debug("Calling legacy mapTeamLdapWS");
        mapTeamLdapWS(ldapServerId, teamId, teamName, ldapGroupDn);
    } else {
        log.debug("Calling Access Control REST method for Team LDAP Mapping");
        try {
            List<CxTeamLdap> teamLdaps = getTeamLdap(ldapServerId);
            ArrayList<CxTeamLdap> teamLdapsTmp = new ArrayList<>(teamLdaps);
            String name = getNameFromLDAP(ldapGroupDn);
            CxTeamLdap ldap = new CxTeamLdap();
            ldap.setLdapGroupDisplayName(name);
            ldap.setLdapGroupDn(ldapGroupDn);
            ldap.setLdapServerId(ldapServerId);
            ldap.setTeamId(teamId);
            if (teamLdapsTmp.contains(ldap)) {
                log.info("team ldap mapping already exists for team id {} - {}", teamId, ldapGroupDn);
                return;
            }
            teamLdapsTmp.add(ldap);
            HttpEntity<List<CxTeamLdap>> requestEntity = new HttpEntity<>(teamLdapsTmp, authClient.createAuthHeaders());
            restTemplate.exchange(cxProperties.getUrl().concat(TEAM_LDAP_MAPPINGS_UPDATE), HttpMethod.PUT, requestEntity, String.class, ldapServerId);
        } catch (HttpStatusCodeException e) {
            log.error("Error occurred while mapping ldap to a team");
            log.error(ExceptionUtils.getStackTrace(e));
            throw new CheckmarxException("Error occurred while mapping ldap to a team");
        }
    }
}
Also used : CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException)

Example 54 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class CxService method getLatestScanReport.

/**
 * @param teamName
 * @param projectName
 * @return
 * @throws CheckmarxException
 */
@Override
public CxXMLResultsType getLatestScanReport(String teamName, String projectName) throws CheckmarxException {
    String teamId = getTeamId(teamName);
    Integer projectId = getProjectId(teamId, projectName);
    Integer scanId = getLastScanId(projectId);
    try {
        Integer reportId = createScanReport(scanId);
        waitForReportCreateOrFail(reportId);
        Thread.sleep(cxProperties.getScanPolling());
        return getXmlReportContent(reportId);
    } catch (InterruptedException e) {
        log.error(ExceptionUtils.getStackTrace(e));
        Thread.currentThread().interrupt();
        throw new CheckmarxException(INTERRUPTED_EXCEPTION_MESSAGE);
    }
}
Also used : CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException)

Example 55 with CheckmarxException

use of com.checkmarx.sdk.exception.CheckmarxException in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class ScanSettingsClientImpl method getPresetId.

@Override
public int getPresetId(String presetName) throws CheckmarxException {
    HttpEntity<Void> httpEntity = new HttpEntity<>(authClient.createAuthHeaders());
    int defaultPresetId = Constants.UNKNOWN_INT;
    try {
        log.info("Retrieving Cx presets");
        ResponseEntity<CxPreset[]> response = restTemplate.exchange(cxProperties.getUrl().concat(PRESETS), HttpMethod.GET, httpEntity, CxPreset[].class);
        CxPreset[] cxPresets = response.getBody();
        if (cxPresets == null) {
            throw new CheckmarxException("Error obtaining Team Id");
        }
        for (CxPreset cxPreset : cxPresets) {
            String currentPresetName = cxPreset.getName();
            int presetId = cxPreset.getId();
            if (currentPresetName.equalsIgnoreCase(presetName)) {
                log.info("Found preset '{}' with ID {}", presetName, presetId);
                return cxPreset.getId();
            }
            if (currentPresetName.equalsIgnoreCase(Constants.CX_DEFAULT_PRESET)) {
                defaultPresetId = presetId;
            }
        }
        log.warn("No Preset was found for '{}'", presetName);
        log.warn("Default Preset {} with ID {} will be used instead", Constants.CX_DEFAULT_PRESET, defaultPresetId);
        return defaultPresetId;
    } catch (HttpStatusCodeException e) {
        log.error("Error occurred while retrieving presets");
        log.error(ExceptionUtils.getStackTrace(e));
        throw new CheckmarxException("Error obtaining Preset Id");
    }
}
Also used : CxPreset(com.checkmarx.sdk.dto.cx.CxPreset) HttpEntity(org.springframework.http.HttpEntity) CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException)

Aggregations

CheckmarxException (com.checkmarx.sdk.exception.CheckmarxException)62 HttpStatusCodeException (org.springframework.web.client.HttpStatusCodeException)23 ScanResults (com.checkmarx.sdk.dto.ScanResults)11 HttpEntity (org.springframework.http.HttpEntity)10 MachinaException (com.checkmarx.flow.exception.MachinaException)8 Test (org.junit.Test)7 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)7 File (java.io.File)6 JSONObject (org.json.JSONObject)6 CxProject (com.checkmarx.sdk.dto.cx.CxProject)5 CxScanParams (com.checkmarx.sdk.dto.cx.CxScanParams)4 IOException (java.io.IOException)4 JAXBContext (javax.xml.bind.JAXBContext)4 JAXBException (javax.xml.bind.JAXBException)4 Unmarshaller (javax.xml.bind.Unmarshaller)4 XMLInputFactory (javax.xml.stream.XMLInputFactory)3 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)3 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)3 SoapActionCallback (org.springframework.ws.soap.client.core.SoapActionCallback)3 ScanReport (com.checkmarx.flow.dto.report.ScanReport)2