# Jenkins + Bitbucket Repository

This example uses the following combinations of tools to achieve the integration:

* **SCM**: Bitbucket Cloud
* **CI/CD**: Jenkins
* **SAST Tool**: Checkmarx One

## Prerequisites

1. **Install Jenkins Plugin**: Ensure the [Bitbucket Branch Source](https://plugins.jenkins.io/cloudbees-bitbucket-branch-source/) plugin is installed in Jenkins.
2. **Bitbucket API Token**: [Create a Bitbucket Token](https://support.atlassian.com/bitbucket-cloud/docs/create-an-api-token/). Specifically, this needs to be an **API token with scopes**. Under products, choose **Bitbucket**, and ensure the following permissions are granted:
   * `read:project:bitbucket`
   * `write:repository:bitbucket`
   * `read:repository:bitbucket`
   * `read:pullrequest:bitbucket`
   * `write:pullrequest:bitbucket`
3. **Add Bitbucket Token to Jenkins**: Go to **Jenkins -> Credentials -> Global -> Add Credentials**.
   * **Kind**: `Username with password`
   * **Username**: Your Bitbucket account email
   * **Password**: The Bitbucket API token generated in step 2.
4. **Add Mobb API Token to Jenkins**: Go back to Credentials, and add your Mobb API Token:
   * **Kind**: `Secret text`
   * **Secret**: Your Mobb API token. (Click [here](/mobb-user-docs/administration/access-tokens.md) to learn how to create a Mobb API token)
   * **ID**: `MOBB_API_TOKEN`
5. **Add Checkmarx API Token to Jenkins**: Go back to Credentials, and add your Checkmarx API Token:
   * **Kind**: `Secret text`
   * **Secret**: Your Checkmarx API token.
   * **ID**: `CX_API_TOKEN`

## Step 1: Create a Jenkinsfile

Go to your Bitbucket repository and create a file named `Jenkinsfile` at the root of the project. Paste the following Groovy code into it:

```groovy
pipeline {
    agent any

    environment {
        // Project name for Checkmarx/Mobb tracking
        PROJECT_NAME = "${env.JOB_BASE_NAME}"
    }

    stages {
        stage('Setup Checkmarx CLI') {
            steps {
                // Download and extract the Checkmarx AST CLI (Standalone binary, no Node.js needed)
                sh '''
                    curl -L https://github.com/Checkmarx/ast-cli/releases/download/2.1.2/ast-cli_linux_x64.tar.gz -o checkmarx.tar.gz
                    tar -xf checkmarx.tar.gz
                    chmod +x cx
                '''
            }
        }

        stage('Checkmarx SAST Scan') {
            steps {
                withCredentials([string(credentialsId: 'CX_API_TOKEN', variable: 'CX_API_TOKEN')]) {
                    sh '''
                        # Authenticate Checkmarx CLI
                        ./cx configure set --prop-name cx_apikey --prop-value "$CX_API_TOKEN"
                        
                        # Run the scan and output to cx_result.json
                        # Using '|| true' so the pipeline continues to Mobb even if vulnerabilities are found
                        ./cx scan create \\
                            --project-name "$PROJECT_NAME" \\
                            -s ./ \\
                            --report-format json \\
                            --scan-types sast \\
                            --branch nobranch \\
                            --output-name cx_result \\
                            --threshold "sast-high=1" || true
                    '''
                }
            }
        }

        stage('Mobb Remediation') {
            steps {
                nodejs('node') {
                    withCredentials([string(credentialsId: 'MOBB_API_TOKEN', variable: 'MOBB_TOKEN')]) {
                        script {
                            // Run the Mobb command using the Checkmarx report
                            sh """
                                npx mobbdev@latest analyze \\
                                    -y \\
                                    -f cx_result.json \\
                                    -r ${env.GIT_URL} \\
                                    --api-key "${MOBB_TOKEN}" \\
                                    --mobb-project-name "${PROJECT_NAME}" \\
                                    --ref ${env.BRANCH_NAME} \\
                                    --ci
                            """
                        }
                    }
                }
            }
        }
    }

    post {
        always {
            // Archive the Checkmarx report
            archiveArtifacts artifacts: 'cx_result.json', fingerprint: true, allowEmptyArchive: true
            
            // Cleanup binaries and reports to keep the workspace clean
            sh 'rm -f cx checkmarx.tar.gz cx_result.json'
        }
    }
}
```

## Step 2: Configure Jenkins Multibranch Pipeline

1. On the Jenkins homepage, click **New Item**.
2. Enter an item name and select **Multibranch Pipeline**, then click **OK**.
3. Under the **Branch Sources** section, click **Add source** and select **Bitbucket**.
4. Configure the Bitbucket source:
   * **Server**: Bitbucket Cloud
   * **Credentials**: Select the Bitbucket API token credential you added earlier (`Username with password`).
   * **Owner**: Your Bitbucket organization name or workspace ID. (This should automatically populate the accessible repositories; select the correct repository).
5. Under **Build Configuration**:
   * **Mode**: `by Jenkinsfile`
   * **Script Path**: `Jenkinsfile`
6. Under **Scan Multibranch Pipeline Triggers**:
   * Check **Periodically if not otherwise run**.
   * Set the interval to **5 minutes** (or down to your desired interval).
7. Click **Save**.

This configuration will automatically trigger the Jenkins pipeline for any branches where the `Jenkinsfile` is located.

## Expected Output

You can verify that Mobb ran successfully by checking the Build Console Output for your job. You should see an output similar to the following, which contains a link directing you to the Mobb fix report:

```shell
+ npx mobbdev@latest analyze -y -f cx_result.json -r https://bitbucket.org/mobb-demo/mobb-integration.git --api-key **** --mobb-project-name main --ref main --ci
🔓 Login to Mobb succeeded. Already authenticated
- ⚙️  Processing vulnerability report
🔌 [WebSocket Mode] Using WebSocket subscription for status updates
✔ ⚙️  Vulnerability report processed successfully
📁 Report uploaded successfully
⚙️  Processing vulnerability report
⚙️ Vulnerability report processed successfully
🕵️‍♂️ Generating fixes...
https://app.mobb.ai/organization/ba9e6ee1-fb72-4c8d-bc03-a759538796e9/project/32cbb8e7-81d1-4934-95c7-79eec31af674/report/b331ba02-877d-4abb-89b4-d36253ce43da
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mobb.ai/mobb-user-docs/ci-cd-integrations/jenkins/jenkins-+-bitbucket-repository.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
