Q:

Jenkins build not failing at pipeline stage where OWASP Dependency Checker finds vulnerabilities

I am trying to fail my Jenkins build at the pipeline stage when OWASP Dependency checker finds and reports out vulnerabilities found. But instead it is moving forward and executing all the subsequent stages even if a vulnerability is found. My Jenkinsfile looks like this :- 
pipeline {
    tools {
        nodejs "nodejs"
    }
    stages {
        stage('install') {
            steps {
                // 'ci' install node modules
                sh 'npm ci'
            }
        }
        stage('Dependency Check') {
            steps {
                sh 'npm prune --production'
                sh "mkdir -p build/report"
                sh "'$DEPENDENCY_PATH' --project demoProject --disableRetireJS --suppression 'dependency-check-suppressions.xml' --format XML --out 'build/report/dependency-check-report.xml' --scan ."
                dependencyCheckPublisher pattern: 'build/report/dependency-check-report.xml', failedTotalCritical: '0', failedTotalHigh: '0', failedTotalLow: '0', failedTotalMedium: '0'
            }
        }
        stage('Test Step') {
            steps {
                sh 'echo "Reaching test step"'
            }
        }
    }
}

Env. variable '$DEPENDENCY_PATH' contains the location for dependency-check.bat file. OWASP Dependency Checker finds and reports vulnerabilities which I can see in the dependency-check-report.xml and at the end it fails the build also. But the last stage Test Step also gets executed which I do not want. I want Jenkins build to fail at the Dependency Check stage if any vulnerabilities are found. Where am I doing wrong here?

A:

It seems that DependencyCheckPublisher throws an error but Jenkins is unable to catch it at that point, but at the end it checks for the same and fails the build. To catch the error at the exact point where it is thrown by DependencyCheckPublisher, I had to introduce a rawBuild console output check which checks whether DependencyCheckPublisher has printed anything about exceeded count for vulnerabilities or not. After dependencyCheckPublisher step add - 
if (currentBuild.rawBuild.getLog(50).contains('[DependencyCheck] Findings exceed configured thresholds')) {
        error("Build failed due to vulnerabilities found during dependencyCheck")    
}else{
        sh 'echo "No vulnerabilities found during dependencyCheck"'
}

For this you also need to allow rawBuild and getLog invocation permission from Jenkins. You can do it from Jenkins -> Manage Jenkins -> In-process Script Approval and allow both of them.(If you haven't allowed them then Jenkins build will fail and in the console output of the failed build you can find details regarding this)

