Search in sources :

Example 11 with FilterConfiguration

use of com.checkmarx.sdk.dto.filtering.FilterConfiguration in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class CxServiceIT method getReportContent.

@Test
public void getReportContent() {
    try {
        List<Filter> filters = new ArrayList<>();
        filters.add(new Filter(Filter.Type.SEVERITY, "High"));
        FilterConfiguration filterConfiguration = FilterConfiguration.fromSimpleFilters(filters);
        ScanResults results = service.getLatestScanResults(properties.getTeam(), "Riches", filterConfiguration);
        assertNotNull(results);
    } catch (CheckmarxException e) {
        fail("Unexpected CheckmarxException");
    }
}
Also used : Filter(com.checkmarx.sdk.dto.sast.Filter) ScanResults(com.checkmarx.sdk.dto.ScanResults) CheckmarxException(com.checkmarx.sdk.exception.CheckmarxException) ArrayList(java.util.ArrayList) FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 12 with FilterConfiguration

use of com.checkmarx.sdk.dto.filtering.FilterConfiguration in project checkmarx-spring-boot-java-sdk by checkmarx-ltd.

the class CxServiceIT method completeScanFlow.

@Test
@Ignore("Stable environment required")
public void completeScanFlow() throws CheckmarxException {
    final String PROJECT_NAME = "my-project-name";
    final String GIT_REPO_URL = "https://github.com/my-organization/my-repo.git";
    final String BRANCH_NAME = "refs/heads/develop";
    String teamId = service.getTeamId(properties.getTeam());
    Integer projectId = service.getProjectId(teamId, PROJECT_NAME);
    CxScanParams params = new CxScanParams();
    params.setProjectName(PROJECT_NAME);
    params.setTeamId(teamId);
    params.setProjectId(projectId);
    params.setGitUrl(GIT_REPO_URL);
    params.setBranch(BRANCH_NAME);
    params.setSourceType(CxScanParams.Type.GIT);
    // run the scan and wait for it to finish
    Integer x = service.createScan(params, "CxSDK Scan");
    service.waitForScanCompletion(x);
    List<Filter> highSeverityOnly = Collections.singletonList(new Filter(Filter.Type.SEVERITY, "High"));
    FilterConfiguration filterConfiguration = FilterConfiguration.fromSimpleFilters(highSeverityOnly);
    // generate the results
    ScanResults results = service.getReportContentByScanId(x, filterConfiguration);
    assertNotNull(results);
}
Also used : CxScanParams(com.checkmarx.sdk.dto.cx.CxScanParams) Filter(com.checkmarx.sdk.dto.sast.Filter) ScanResults(com.checkmarx.sdk.dto.ScanResults) FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) Ignore(org.junit.Ignore) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 13 with FilterConfiguration

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

the class GitLabController method mergeRequest.

/**
 * Merge Request event webhook submitted.
 */
@PostMapping(value = { "/{product}", "/" }, headers = MERGE)
public ResponseEntity<EventResponse> mergeRequest(@RequestBody MergeEvent body, @RequestHeader(value = TOKEN_HEADER) String token, @PathVariable(value = "product", required = false) String product, ControllerRequest controllerRequest) {
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    log.info("Processing GitLab MERGE request");
    controllerRequest = ensureNotNull(controllerRequest);
    validateGitLabRequest(token, controllerRequest);
    try {
        ObjectAttributes objectAttributes = body.getObjectAttributes();
        if (!objectAttributes.getState().equalsIgnoreCase("opened") || isWIP(body)) {
            log.info("Merge requested not processed.  Status was not opened , or was WIP ({})", objectAttributes.getState());
            return ResponseEntity.status(HttpStatus.OK).body(EventResponse.builder().message("No processing occurred for updates to Merge Request").success(true).build());
        }
        String app = body.getRepository().getName();
        if (StringUtils.isNotEmpty(controllerRequest.getApplication())) {
            app = controllerRequest.getApplication();
        }
        BugTracker.Type bugType = BugTracker.Type.GITLABMERGE;
        if (StringUtils.isNotEmpty(controllerRequest.getBug())) {
            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));
        String currentBranch = objectAttributes.getSourceBranch();
        String targetBranch = objectAttributes.getTargetBranch();
        String defaultBranch = objectAttributes.getTarget().getDefaultBranch();
        List<String> branches = getBranches(controllerRequest, flowProperties);
        BugTracker bt = ScanUtils.getBugTracker(controllerRequest.getAssignee(), bugType, jiraProperties, controllerRequest.getBug());
        FilterConfiguration filter = filterFactory.getFilter(controllerRequest, flowProperties);
        Project proj = body.getProject();
        String gitUrl = proj.getGitHttpUrl();
        log.info("Using url: {}", gitUrl);
        String configToken = scmConfigOverrider.determineConfigToken(properties, controllerRequest.getScmInstance());
        String gitAuthUrl = gitAuthUrlGenerator.addCredToUrl(ScanRequest.Repository.GITLAB, gitUrl, configToken);
        ScanRequest request = ScanRequest.builder().id(String.valueOf(proj.getId())).application(app).product(p).project(controllerRequest.getProject()).team(controllerRequest.getTeam()).namespace(proj.getNamespace().replace(" ", "_")).repoName(proj.getName()).repoUrl(proj.getGitHttpUrl()).repoUrlWithAuth(gitAuthUrl).repoType(ScanRequest.Repository.GITLAB).branch(currentBranch).defaultBranch(defaultBranch).mergeTargetBranch(targetBranch).refs(Constants.CX_BRANCH_PREFIX.concat(currentBranch)).email(null).incremental(controllerRequest.getIncremental()).scanPreset(controllerRequest.getPreset()).excludeFolders(controllerRequest.getExcludeFolders()).excludeFiles(controllerRequest.getExcludeFiles()).bugTracker(bt).filter(filter).organizationId(getOrganizationId(proj)).gitUrl(gitUrl).hash(objectAttributes.getLastCommit().getId()).build();
        setMergeEndPointUri(objectAttributes, proj, request);
        setScmInstance(controllerRequest, request);
        if (proj.getId() != null) {
            request.setRepoProjectId(proj.getId());
        }
        /*Check for Config as code (cx.config) and override*/
        CxConfig cxConfig = gitLabService.getCxConfigOverride(request);
        request = configOverrider.overrideScanRequestProperties(cxConfig, request);
        request.putAdditionalMetadata(HTMLHelper.WEB_HOOK_PAYLOAD, body.toString());
        request.putAdditionalMetadata(FlowConstants.MERGE_ID, objectAttributes.getIid().toString());
        request.putAdditionalMetadata(FlowConstants.MERGE_TITLE, objectAttributes.getTitle());
        request.setId(uid);
        if (helperService.isBranch2Scan(request, branches)) {
            flowService.initiateAutomation(request);
        }
    } catch (IllegalArgumentException e) {
        return getBadRequestMessage(e, controllerRequest, product);
    }
    return getSuccessMessage();
}
Also used : ScanRequest(com.checkmarx.flow.dto.ScanRequest) FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) CxConfig(com.checkmarx.sdk.dto.sast.CxConfig) BugTracker(com.checkmarx.flow.dto.BugTracker)

Example 14 with FilterConfiguration

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

the class GitLabController method pushRequest.

/**
 * Push Request event webhook submitted.
 */
@PostMapping(value = { "/{product}", "/" }, headers = PUSH)
public ResponseEntity<EventResponse> pushRequest(@RequestBody PushEvent body, @RequestHeader(value = TOKEN_HEADER) String token, @PathVariable(value = "product", required = false) String product, ControllerRequest controllerRequest) {
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    controllerRequest = ensureNotNull(controllerRequest);
    validateGitLabRequest(token, controllerRequest);
    try {
        String app;
        if (body != null && body.getRepository() != null) {
            app = body.getRepository().getName();
        } else {
            throw new IllegalArgumentException("Request body or request repository cannot be null");
        }
        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());
        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));
        // extract branch from ref (refs/heads/master -> master)
        String currentBranch = ScanUtils.getBranchFromRef(body.getRef());
        List<String> branches = getBranches(controllerRequest, flowProperties);
        BugTracker bt = ScanUtils.getBugTracker(controllerRequest.getAssignee(), bugType, jiraProperties, controllerRequest.getBug());
        FilterConfiguration filter = filterFactory.getFilter(controllerRequest, flowProperties);
        Project proj = body.getProject();
        String gitUrl = proj.getGitHttpUrl();
        log.debug("Using url: {}", gitUrl);
        String configToken = scmConfigOverrider.determineConfigToken(properties, controllerRequest.getScmInstance());
        String gitAuthUrl = gitAuthUrlGenerator.addCredToUrl(ScanRequest.Repository.GITLAB, gitUrl, configToken);
        ScanRequest request = ScanRequest.builder().id(String.valueOf(body.getProjectId())).application(app).product(p).project(controllerRequest.getProject()).team(controllerRequest.getTeam()).namespace(proj.getNamespace().replace(" ", "_")).repoName(proj.getName()).repoUrl(proj.getGitHttpUrl()).repoUrlWithAuth(gitAuthUrl).repoType(ScanRequest.Repository.GITLAB).branch(currentBranch).refs(body.getRef()).incremental(controllerRequest.getIncremental()).scanPreset(controllerRequest.getPreset()).excludeFolders(controllerRequest.getExcludeFolders()).excludeFiles(controllerRequest.getExcludeFiles()).bugTracker(bt).filter(filter).organizationId(getOrganizationId(proj)).gitUrl(gitUrl).hash(body.getAfter()).build();
        /*Determine emails*/
        List<String> emails = new ArrayList<>();
        String commitEndpoint = null;
        commitEndpoint = setUserEmail(body, bugType, proj, request, emails, commitEndpoint);
        request.setMergeNoteUri(commitEndpoint);
        request.setEmail(emails);
        setScmInstance(controllerRequest, request);
        if (StringUtils.isNotEmpty(controllerRequest.getPreset())) {
            request.setScanPreset(controllerRequest.getPreset());
            request.setScanPresetOverride(true);
        }
        if (proj.getId() != null) {
            request.setRepoProjectId(proj.getId());
        }
        /*Check for Config as code (cx.config) and override*/
        CxConfig cxConfig = gitLabService.getCxConfigOverride(request);
        request = configOverrider.overrideScanRequestProperties(cxConfig, request);
        request.putAdditionalMetadata(HTMLHelper.WEB_HOOK_PAYLOAD, body.toString());
        request.setId(uid);
        if (helperService.isBranch2Scan(request, branches)) {
            flowService.initiateAutomation(request);
        }
    } catch (IllegalArgumentException e) {
        return getBadRequestMessage(e, controllerRequest, product);
    }
    return getSuccessMessage();
}
Also used : ScanRequest(com.checkmarx.flow.dto.ScanRequest) FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) ArrayList(java.util.ArrayList) CxConfig(com.checkmarx.sdk.dto.sast.CxConfig) BugTracker(com.checkmarx.flow.dto.BugTracker)

Example 15 with FilterConfiguration

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

the class TfsController method pullPushRequest.

@PostMapping(value = { "/{product}/tfs/pull", "/tfs/pull", "/{product}/tfs/push", "/tfs/push" })
public ResponseEntity<EventResponse> pullPushRequest(HttpServletRequest httpRequest, @RequestBody PullEvent body, @RequestHeader(value = AUTHORIZATION) String auth, @PathVariable(value = "product", required = false) String product, ControllerRequest controllerRequest, AdoDetailsRequest adoDetailsRequest) {
    String action = getAction(httpRequest);
    String uid = helperService.getShortUid();
    MDC.put(FlowConstants.MAIN_MDC_ENTRY, uid);
    if (log.isInfoEnabled()) {
        log.info(String.format("Processing TFS %s request", action));
    }
    validateBasicAuth(auth);
    Resource resource = body.getResource();
    controllerRequest = ensureNotNull(controllerRequest);
    adoDetailsRequest = ensureDetailsNotNull(adoDetailsRequest);
    if (ACTION_PULL.equals(action) && !body.getEventType().equals(PULL_EVENT)) {
        log.info("Pull requested not processed.  Event was not 'opened' ({})", body.getEventType());
        return ResponseEntity.accepted().body(EventResponse.builder().message("No processing occurred for updates to Pull Request").success(true).build());
    }
    FlowOverride o = ScanUtils.getMachinaOverride(Optional.ofNullable(controllerRequest.getOverride()).orElse(null));
    Repository repository = resource.getRepository();
    String app = repository.getName();
    if (app.startsWith(properties.getTestRepository())) {
        log.info("Handling TFS Test Event");
        return ResponseEntity.ok(EventResponse.builder().message("Test Event").success(true).build());
    }
    Optional.ofNullable(controllerRequest.getAppOnly()).ifPresent(flowProperties::setTrackApplicationOnly);
    FilterConfiguration filter = filterFactory.getFilter(controllerRequest, flowProperties);
    ScanRequestBuilder requestBuilder = ScanRequest.builder().application(Optional.ofNullable(controllerRequest.getApplication()).orElse(app)).product(getProductForName(product)).project(Optional.ofNullable(controllerRequest.getProject()).orElse(null)).team(Optional.ofNullable(controllerRequest.getTeam()).orElse(null)).namespace(repository.getProject().getName().replace(" ", "_")).repoName(repository.getName()).repoType(ScanRequest.Repository.ADO).scanPreset(controllerRequest.getPreset()).incremental(controllerRequest.getIncremental()).excludeFolders(controllerRequest.getExcludeFolders()).excludeFiles(controllerRequest.getExcludeFiles()).filter(filter);
    if (ACTION_PULL.equals(action)) {
        BugTracker.Type bugType = Optional.ofNullable(controllerRequest.getBug()).map(theBug -> ScanUtils.getBugTypeEnum(theBug, flowProperties.getBugTrackerImpl())).orElse(BugTracker.Type.ADOPULL);
        Optional.ofNullable(controllerRequest.getAppOnly()).ifPresent(flowProperties::setTrackApplicationOnly);
        BugTracker bugTracker = ScanUtils.getBugTracker(Optional.ofNullable(controllerRequest.getAssignee()).orElse(null), bugType, jiraProperties, Optional.ofNullable(controllerRequest.getBug()).orElse(null));
        requestBuilder.refs(resource.getSourceRefName()).repoUrl(repository.getWebUrl()).repoUrlWithAuth(addTokenToUrl(repository.getWebUrl(), properties.getToken())).mergeNoteUri(resource.getUrl().concat("/threads")).branch(ScanUtils.getBranchFromRef(resource.getSourceRefName())).mergeTargetBranch(ScanUtils.getBranchFromRef(resource.getTargetRefName())).email(null).bugTracker(bugTracker);
    } else if (ACTION_PUSH.equals(action)) {
        String bug = Optional.ofNullable(controllerRequest.getBug()).orElse(flowProperties.getBugTracker());
        BugTracker.Type bugType = ScanUtils.getBugTypeEnum(bug, flowProperties.getBugTrackerImpl());
        BugTracker bugTracker = ScanUtils.getBugTracker(Optional.ofNullable(controllerRequest.getAssignee()).orElse(null), bugType, jiraProperties, Optional.ofNullable(controllerRequest.getBug()).orElse(null));
        requestBuilder.refs(resource.getRefUpdates().get(0).getName()).repoUrl(repository.getRemoteUrl()).repoUrlWithAuth(addTokenToUrl(repository.getRemoteUrl(), properties.getToken())).branch(ScanUtils.getBranchFromRef(resource.getRefUpdates().get(0).getName())).defaultBranch(repository.getDefaultBranch()).email(determineEmails(resource)).bugTracker(bugTracker);
    }
    ScanRequest request = requestBuilder.build();
    request = configOverrider.overrideScanRequestProperties(o, request);
    if (ACTION_PULL.equals(action)) {
        request.putAdditionalMetadata("statuses_url", resource.getUrl().concat("/statuses"));
    }
    addMetadataToScanRequest(adoDetailsRequest, request);
    request.putAdditionalMetadata(HTMLHelper.WEB_HOOK_PAYLOAD, body.toString());
    request.setId(uid);
    // only initiate scan/automation if target branch is applicable
    List<String> branches = new ArrayList<>();
    Optional<List<String>> branch = Optional.ofNullable(controllerRequest.getBranch());
    if (branch.isPresent()) {
        branches.addAll(branch.get());
    } else if (CollectionUtils.isNotEmpty(flowProperties.getBranches())) {
        branches.addAll(flowProperties.getBranches());
    }
    if (helperService.isBranch2Scan(request, branches)) {
        flowService.initiateAutomation(request);
    }
    return ResponseEntity.accepted().body(EventResponse.builder().message("Scan Request Successfully Submitted").success(true).build());
}
Also used : ADOProperties(com.checkmarx.flow.config.ADOProperties) java.util(java.util) ConfigurationOverrider(com.checkmarx.flow.service.ConfigurationOverrider) RequiredArgsConstructor(lombok.RequiredArgsConstructor) FlowProperties(com.checkmarx.flow.config.FlowProperties) StringUtils(org.apache.commons.lang3.StringUtils) CollectionUtils(org.apache.commons.collections4.CollectionUtils) HTMLHelper(com.checkmarx.flow.utils.HTMLHelper) Repository(com.checkmarx.flow.dto.azure.Repository) Product(com.checkmarx.flow.dto.ScanRequest.Product) AdoDetailsRequest(com.checkmarx.flow.dto.azure.AdoDetailsRequest) InvalidTokenException(com.checkmarx.flow.exception.InvalidTokenException) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterFactory(com.checkmarx.flow.service.FilterFactory) com.checkmarx.flow.dto(com.checkmarx.flow.dto) FlowService(com.checkmarx.flow.service.FlowService) Resource(com.checkmarx.flow.dto.azure.Resource) Collectors(java.util.stream.Collectors) JiraProperties(com.checkmarx.flow.config.JiraProperties) HelperService(com.checkmarx.flow.service.HelperService) PullEvent(com.checkmarx.flow.dto.azure.PullEvent) Slf4j(lombok.extern.slf4j.Slf4j) MDC(org.slf4j.MDC) ScanUtils(com.checkmarx.flow.utils.ScanUtils) FlowConstants(com.checkmarx.flow.constants.FlowConstants) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) ResponseEntity(org.springframework.http.ResponseEntity) FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) ScanRequestBuilder(com.checkmarx.flow.dto.ScanRequest.ScanRequestBuilder) Resource(com.checkmarx.flow.dto.azure.Resource) FilterConfiguration(com.checkmarx.sdk.dto.filtering.FilterConfiguration) Repository(com.checkmarx.flow.dto.azure.Repository) ScanRequestBuilder(com.checkmarx.flow.dto.ScanRequest.ScanRequestBuilder)

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