> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codeant.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Jenkins

> Set up a Jenkins pipeline for CodeAnt CI scan.

## Jenkins Pipeline Workflow

Add the following to your `Jenkinsfile`. It will trigger on every build and kick off a CodeAnt analysis scan:

```groovy theme={null}
pipeline {
    agent any

    environment {
        ACCESS_TOKEN = credentials('codeant-token')  // Your CodeAnt API token (cdt_…) - see https://docs.codeant.ai/settings/api-tokens

        // Uncomment and set to customize which scanners to run
        // Options: sast, sca, secrets, antipatterns, iac, all
        // If not defined, script defaults to: sast,sca
        // SCANNERS = 'all'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Fetch CodeAnt scan script') {
            steps {
                sh '''
                    export API_BASE="https://api.codeant.ai"
                    curl -sS -X GET "${API_BASE}/analysis/ci/scan/script/get" \
                        --output start_scan.sh.b64
                '''
            }
        }

        stage('Make script executable') {
            steps {
                sh '''
                    base64 -d start_scan.sh.b64 > start_scan.sh
                    chmod +x start_scan.sh
                '''
            }
        }

        stage('Trigger CodeAnt analysis') {
            steps {
                script {
                    // Extract the full organization/repository name from the Git URL
                    def repoName = env.GIT_URL.replaceAll(/.*[\/:]([^\/]+\/[^\/]+?)(\.git)?$/, '$1')

                    sh """
                        bash start_scan.sh \\
                            -a "\$ACCESS_TOKEN" \\
                            -r "${repoName}" \\
                            -c "\${GIT_COMMIT}" \\
                            -b "\${GIT_BRANCH##*/}" \\
                            -s github \\
                            -i "" \\
                            -e "" \\
                            --scanners "\$SCANNERS"
                    """
                }
            }
        }
    }
}
```

## Script Parameters

The `start_scan.sh` script accepts the following parameters:

### Required Parameters

| Parameter        | Flag                 | Description                                                                                        | Example                         |
| ---------------- | -------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------- |
| **Access Token** | `-a, --access-token` | CodeAnt API token (`cdt_…`) used to authenticate the scan - see [API Tokens](/settings/api-tokens) | `$ACCESS_TOKEN`                 |
| **Repository**   | `-r, --repo`         | Repository name in `organization/repository` format                                                | `myorg/myrepo`                  |
| **Commit ID**    | `-c, --commit-id`    | Git commit SHA to analyze                                                                          | `${GIT_COMMIT}`                 |
| **Service**      | `-s, --service`      | Git service provider                                                                               | `github`, `gitlab`, `bitbucket` |

### Optional Parameters

| Parameter            | Flag                     | Default    | Description                                                                                                                                        | Example                           |
| -------------------- | ------------------------ | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| **Branch**           | `-b, --branch`           | *(empty)*  | Branch name for the analysis                                                                                                                       | `main`, `develop`                 |
| **Scanners**         | `--scanners`             | `sast,sca` | Comma-separated list of scanners to run                                                                                                            | `all`, `sast`, `sast,sca,secrets` |
| **Include Files**    | `-i, --include-files`    | *(empty)*  | Glob patterns for files to include in analysis                                                                                                     | `"src/**/*.js"`                   |
| **Exclude Files**    | `-e, --exclude-files`    | *(empty)*  | Glob patterns for files to exclude from analysis                                                                                                   | `"**/test/**"`                    |
| **Polling Interval** | `-p, --polling-interval` | `30`       | Seconds between result polling attempts                                                                                                            | `20`                              |
| **Timeout**          | `-t, --timeout`          | `300`      | Maximum seconds to wait for results                                                                                                                | `600`                             |
| **No Wait**          | `-n, --no-wait`          | `false`    | Skip waiting for results, only trigger the scan                                                                                                    | *(flag only)*                     |
| **Quality Gate**     | `-q, --quality-gate`     | `false`    | Evaluate the whole-repo quality gate and **fail the build** (exit 1) if it does not pass. Writes `results.json`, `codeant.sarif`, `codeant-qg.xml` | *(flag only)*                     |

### Scanner Options

🔍 **Available Scanners:**

The `--scanners` flag allows you to customize which security scanners run during analysis:

* **`sast`** - Static Application Security Testing (code vulnerabilities)
* **`sca`** - Software Composition Analysis (dependency vulnerabilities)
* **`secrets`** - Secret detection (API keys, passwords, tokens)
* **`antipatterns`** - Code quality and duplicate code detection
* **`iac`** - Infrastructure as Code security (Terraform, CloudFormation, etc.)
* **`all`** - Run all available scanners

**Default:** If not specified, runs `sast,sca`

**Examples:**

* Run all scanners: `--scanners "all"`
* Only SAST: `--scanners "sast"`
* SAST + Secrets: `--scanners "sast,secrets"`
* Full security suite: `--scanners "sast,sca,secrets,iac"`

### Quality Gate Enforcement

🚦 **Block the build on the whole-repository posture:**

Pass `--quality-gate` (`-q`) to turn the scan into an enforced gate. After the scan completes, CodeAnt evaluates the **entire repository** against your thresholds and the script **exits non-zero** if the gate fails - failing the pipeline. This is the Checkmarx / SonarQube-style whole-repo gate; it is independent of the new-code/PR quality gate.

**Configure thresholds** in **Settings → Code Analysis → Quality Gates** using the **"(Full Code / CI Pipeline)"** metrics. These run only in the pipeline, never on pull requests:

* `(Full Code / CI Pipeline) SAST Security Rating` `≤` `C`
* `(Full Code / CI Pipeline) SCA Security Rating` `≤` `C`
* `(Full Code / CI Pipeline) IaC Security Rating` `≤` `C`
* `(Full Code / CI Pipeline) Duplicate Code Percentage` `>` `30`

The gate groups results into three status checks: **SAST** (app security + IaC), **SCA** (dependencies), and **SCR** (duplicate code). Use `--scanners` to scope the gate (e.g. `--scanners "sast,sca"`).

**Reports** are written to the workspace and can be published:

* `codeant.sarif` - SARIF 2.1.0 for the code-scanning tab
* `codeant-qg.xml` - JUnit XML (renders as a native test report)
* `results.json` - full verdict, per-metric ratings, and findings

> **Note:** `--quality-gate` requires a commit SHA (`-c`) and cannot be combined with `--no-wait` (the gate needs the scan results).

```groovy theme={null}
stage('CodeAnt Quality Gate') {
    steps {
        script {
            def repoName = env.GIT_URL.replaceAll(/.*[\/:]([^\/]+\/[^\/]+?)(\.git)?$/, '$1')
            sh """
                export API_BASE="https://api.codeant.ai"
                curl -sS -X GET "\${API_BASE}/analysis/ci/scan/script/get" \\
                    --output start_scan.sh.b64
                base64 -d start_scan.sh.b64 > start_scan.sh
                chmod +x start_scan.sh
                bash start_scan.sh \\
                    -a "\$ACCESS_TOKEN" \\
                    -r "${repoName}" \\
                    -c "\${GIT_COMMIT}" \\
                    -s github \\
                    --scanners "all" \\
                    --quality-gate \\
                    -t 600
            """
        }
    }
    post { always { junit 'codeant-qg.xml' } }
}
```

### Execution Time Considerations

⏱️ **Performance Options:**

* **With result waiting** (default): \~7 minutes
  * Triggers scan and waits for complete analysis results
  * Includes both security and SCA (Software Composition Analysis) results
  * Best for comprehensive CI/CD pipelines where you need immediate feedback

* **With `--no-wait` flag**: \~2 minutes
  * Only triggers the scan and returns immediately
  * Results can be fetched later or viewed in the CodeAnt dashboard
  * Ideal for faster CI runs or when results can be processed asynchronously

### Example Configurations

#### Fast CI Mode (No Wait)

```groovy theme={null}
stage('Trigger CodeAnt analysis (Fast Mode)') {
    steps {
        script {
            // Extract the full organization/repository name from the Git URL
            def repoName = env.GIT_URL.replaceAll(/.*[\/:]([^\/]+\/[^\/]+?)(\.git)?$/, '$1')

            sh """
                export API_BASE="https://api.codeant.ai"
                curl -sS -X GET "\${API_BASE}/analysis/ci/scan/script/get" \\
                    --output start_scan.sh.b64
                base64 -d start_scan.sh.b64 > start_scan.sh
                chmod +x start_scan.sh
                bash start_scan.sh \\
                    -a "\$ACCESS_TOKEN" \\
                    -r "${repoName}" \\
                    -c "\${GIT_COMMIT}" \\
                    -s github \\
                    -n  # Returns in ~2 minutes
            """
        }
    }
}
```

#### Comprehensive Analysis (Wait for Results)

```groovy theme={null}
stage('Trigger CodeAnt analysis (Full Results)') {
    steps {
        script {
            // Extract the full organization/repository name from the Git URL
            def repoName = env.GIT_URL.replaceAll(/.*[\/:]([^\/]+\/[^\/]+?)(\.git)?$/, '$1')

            sh """
                export API_BASE="https://api.codeant.ai"
                curl -sS -X GET "\${API_BASE}/analysis/ci/scan/script/get" \\
                    --output start_scan.sh.b64
                base64 -d start_scan.sh.b64 > start_scan.sh
                chmod +x start_scan.sh
                bash start_scan.sh \\
                    -a "\$ACCESS_TOKEN" \\
                    -r "${repoName}" \\
                    -c "\${GIT_COMMIT}" \\
                    -s github \\
                    -b "\${GIT_BRANCH##*/}" \\
                    -p 20 \\
                    -t 600  # Wait up to 10 minutes
            """
        }
    }
}
```

#### Custom File Filtering

```groovy theme={null}
stage('Trigger CodeAnt analysis (Custom Files)') {
    steps {
        script {
            // Extract the full organization/repository name from the Git URL
            def repoName = env.GIT_URL.replaceAll(/.*[\/:]([^\/]+\/[^\/]+?)(\.git)?$/, '$1')

            sh """
                export API_BASE="https://api.codeant.ai"
                curl -sS -X GET "\${API_BASE}/analysis/ci/scan/script/get" \\
                    --output start_scan.sh.b64
                base64 -d start_scan.sh.b64 > start_scan.sh
                chmod +x start_scan.sh
                bash start_scan.sh \\
                    -a "\$ACCESS_TOKEN" \\
                    -r "${repoName}" \\
                    -c "\${GIT_COMMIT}" \\
                    -s github \\
                    -i "src/**/*.{js,ts}" \\
                    -e "**/node_modules/**,**/dist/**" \\
                    -n
            """
        }
    }
}
```

#### Parameterized Pipeline

```groovy theme={null}
pipeline {
    agent any
    
    parameters {
        string(name: 'REPO_NAME', defaultValue: 'myorg/myrepo', description: 'Repository name')
        choice(name: 'SERVICE', choices: ['github', 'gitlab', 'bitbucket'], description: 'Git service provider')
        choice(name: 'SCANNERS', choices: ['sast,sca', 'all', 'sast', 'sast,secrets', 'sast,sca,secrets,iac'], description: 'Scanners to run')
        booleanParam(name: 'FAST_MODE', defaultValue: false, description: 'Use fast mode (no-wait)')
        string(name: 'INCLUDE_PATTERN', defaultValue: '', description: 'File include patterns')
        string(name: 'EXCLUDE_PATTERN', defaultValue: '', description: 'File exclude patterns')
    }

    environment {
        ACCESS_TOKEN = credentials('codeant-token')  // Your CodeAnt API token (cdt_…) - see https://docs.codeant.ai/settings/api-tokens
    }

    stages {
        stage('Run CodeAnt analysis') {
            steps {
                script {
                    def noWaitFlag = params.FAST_MODE ? '-n' : ''
                    def includeFlag = params.INCLUDE_PATTERN ? "-i \"${params.INCLUDE_PATTERN}\"" : '-i ""'
                    def excludeFlag = params.EXCLUDE_PATTERN ? "-e \"${params.EXCLUDE_PATTERN}\"" : '-e ""'
                    def scannersFlag = params.SCANNERS ? "--scanners \"${params.SCANNERS}\"" : ''

                    sh """
                        export API_BASE="https://api.codeant.ai"
                        curl -sS -X GET "\${API_BASE}/analysis/ci/scan/script/get" \
                            --output start_scan.sh.b64
                        base64 -d start_scan.sh.b64 > start_scan.sh
                        chmod +x start_scan.sh
                        bash start_scan.sh \
                            -a "\$ACCESS_TOKEN" \
                            -r "${params.REPO_NAME}" \
                            -c "\${GIT_COMMIT}" \
                            -b "\${GIT_BRANCH##*/}" \
                            -s ${params.SERVICE} \
                            ${includeFlag} \
                            ${excludeFlag} \
                            ${scannersFlag} \
                            ${noWaitFlag}
                    """
                }
            }
        }
    }
}
```

> **Tips:**
>
> * Create a CodeAnt token under **API Tokens** in the user menu (your email at the bottom-left) - see [API Tokens](/settings/api-tokens) and add it as a **Secret text** credential with the ID `codeant-token` in Jenkins → Credentials → System → Global credentials
> * Use `--no-wait` for PR checks to keep them fast, and full analysis for main branch merges
> * Adjust timeout based on your repository size - larger repos may need more time
> * File patterns support standard glob syntax for precise control over what gets analyzed
> * Customize scanners based on your needs - use `--scanners "all"` for comprehensive coverage or specific combinations like `--scanners "sast,secrets"` for targeted security checks
> * Default scanners (`sast,sca`) provide a good balance between coverage and execution time

## How it works

1. **Download script**
   We fetch a small Bash helper (`start_scan.sh`) from the CodeAnt CI endpoint.
2. **Make it runnable**
   Mark the script executable so you can invoke it directly.
3. **Invoke the scan**
   The script POSTs your repo, commit, and file-globs to `/analysis/ci/scan`, using your token for auth.
4. **Pipeline feedback**

   * On success, you'll see a parsed JSON response in the job log.
   * On failure (non-2xx HTTP), the script exits non-zero, failing your pipeline immediately.

With this in place, every push will automatically kick off a CodeAnt analysis run - and your CI status will reflect whether any HIGH-severity issues were detected.## Token permission

This pipeline authenticates with a CodeAnt API token (`cdt_…`). If the token is **scoped**, give it the **Codeant CI/CD** role - it covers scans, quality gates, and test-coverage upload - scoped to the repositories this pipeline runs on (or **All repositories**). A token missing the required permission is rejected with an HTTP `403` `token_scope_forbidden` error that names the permission it needs. See [API token permissions](/settings/api-tokens#permissions-and-scopes).
