httpRequest with two credentials - how to avoid insecure interpolation of sensitive variables?

Hello @blueice_haller and welcome to this community :wave:

The warning is indicating that there may be sensitive data being interpolated in the requestBody field of the httpRequest step. In your case, the BACKUP_PASSWORD variable is being used directly in the JSON request body, which could be insecure if the value of BACKUP_PASSWORD is sensitive.

To avoid this warning and make your code more secure, you can use the withCredentials step to securely pass the BACKUP_PASSWORD value to the httpRequest step. Here’s an example of how to modify your code:

import java.time.*
import java.time.format.DateTimeFormatter

def timeStamp = Calendar.getInstance().getTime().format('YYYYMMdd_hhmmss',TimeZone.getTimeZone('Europe/Berlin'))
println timeStamp

pipeline {
    agent any
    
    stages {
        // https://www.jenkins.io/doc/book/pipeline/syntax/#supported-credentials-type
        stage('Backup') {
            environment {
                HOSTNAME = "example.com"
                BACKUP_PASSWORD = credentials('RESTORE')
            }
            steps {
                timeout(time: 120, unit: 'SECONDS') {
                    script {
                        // https://www.jenkins.io/doc/pipeline/steps/http_request/
                        // https://plugins.jenkins.io/http_request/
                        
                        withCredentials([string(credentialsId: 'RESTORE', variable: 'BACKUP_PASSWORD')]) {
                            def requestBodyJson = [:]
                            requestBodyJson['password'] = "${BACKUP_PASSWORD}"
                            def requestBody = JsonOutput.toJson(requestBodyJson)
                            def response = httpRequest url: 'https://' + HOSTNAME + ':1234/api/backup',
                            acceptType: 'APPLICATION_ZIP',
                            authentication: 'BACKUP_CREDENTIALS',
                            consoleLogResponseBody: false,
                            contentType: 'APPLICATION_JSON',
                            httpMode: 'POST',
                            ignoreSslErrors: true,
                            outputFile: BUILD_NUMBER + '_backup_' + timeStamp + '_' + HOSTNAME + '.zip',
                            requestBody: requestBody,
                            timeout: 120,
                            wrapAsMultipart: false
                        }
                    }
                }
            }
        }
    }
}

In this modified code, the BACKUP_PASSWORD value is passed to the httpRequest step using the withCredentials step, which securely handles the sensitive value. The JSON request body is constructed using a map and JsonOutput.toJson method, rather than directly interpolating the BACKUP_PASSWORD variable. This approach should prevent the warning message from being displayed.

1 Like