> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.pensar.dev/console/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.pensar.dev/console/_mcp/server.

# CI/CD Integration

> Integrate Pensar pentesting into your CI/CD pipeline

## Overview

Pensar provides a CLI tool and API for integrating automated pentesting directly into your CI/CD pipeline. Run pentests on every commit or deployment to catch vulnerabilities before they reach production.

> **Info**
>
> CI-triggered pentests consume credits from your workspace balance. See [Billing & Usage](/console/features/billing) for details on credit management and usage tracking.

## Installation

Install the Pensar CI package globally:

```bash
npm install -g @pensar/ci
```

Or add it as a dev dependency:

```bash
npm install --save-dev @pensar/ci
```

> **Note**
>
> View the source code and additional examples on [GitHub](https://github.com/pensarai/ci).

## Configuration

### Required Environment Variables

| Variable         | Description         |
| ---------------- | ------------------- |
| `PENSAR_API_KEY` | Your Pensar API key |

### Optional Environment Variables

| Variable             | Description                       | Default      |
| -------------------- | --------------------------------- | ------------ |
| `PENSAR_ENVIRONMENT` | `dev`, `staging`, or `production` | `production` |

> **Info**
>
> You can configure CI/CD integration directly from the Pensar Console. Navigate to **Settings → Automation → CI/CD** in your workspace for guided setup and one-click workflow creation.

## CLI Usage

### Run a Pentest

```bash
pensar pentest [options]
```

**Options:**

| Option                           | Description                                                                                                                              |
| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `-b, --branch <branch>`          | Branch name to associate with the scan                                                                                                   |
| `-e, --environment <env>`        | Environment: `dev`, `staging`, `production`                                                                                              |
| `--commit <sha>`                 | Exact commit to test; pass the deployed SHA for post-deploy runs                                                                         |
| `--base <sha>`                   | Explicit comparison base (`baseSha`); requires `--commit`                                                                                |
| `--url <url>`                    | Preview or staging URL the live test should hit (`targetUrl`)                                                                            |
| `--pull-request <url-or-number>` | GitHub pull request URL or number; records the scan as a pull-request review                                                             |
| `-s, --severity <level>`         | Lowest severity that fails the run, and the GitHub check of a pull-request review: `critical` (default), `high`, `medium`, `low`, `info` |
| `--no-wait`                      | Dispatch the scan without waiting for completion                                                                                         |

**Examples:**

```bash
# Basic pentest using environment variables
pensar pentest

# Pentest a specific branch
pensar pentest --branch main

# Pentest without waiting for completion
pensar pentest --no-wait

# Pentest with explicit environment
pensar pentest --branch develop --environment staging
```

### How the CI diff is calculated

By default:

* **Compare:** Your requested commit (`--commit`) is compared with the latest qualifying completed pentest for the same repository in your workspace. This baseline is shared across branches and environments; it is not the previous deployment.
* **Filter:** Files such as `package.json` and lockfiles are excluded. If no changes remain, testing is skipped; large changes can trigger broader coverage.
* **Test:** The agent uses the diff to create security objectives for the affected applications.
* **Results:** A launched scan returns an ID and status, with findings after testing completes. Buffered runs can defer launch; a queued scan is not a passing result.

Without a baseline, or if a force-push removed it, Pensar runs without diff narrowing. Other comparison errors fail the run. For an explicit comparison, the API accepts `baseSha` with `commitSha`; both commits must exist.

### Invalid domain URLs

Workspace-wide and CI-derived scopes skip applications with unparseable domain URLs
and continue with the applications that are ready. An explicitly selected scope
fails if any selected application is blocked; any scope fails when none are ready.

If a pentest cannot start because an application's domain URL is invalid, CI returns
`400` with the affected application and correction steps. Testing has not started.
In **Attack surface** → **Domains**, open the linked domain's menu, choose **Edit**,
and correct **Domain URL**, for example `https://app.acme.example`. Then retry the pentest.
Valid bare hostnames are automatically read as HTTPS; explicit HTTP URLs and ports
are preserved.

### Testing guidance

Pensar's planner decides what to test by analyzing the commit diff. Testing
guidance adds your own context to that analysis, so the planner knows which
parts of your application matter most.

Save it under **Settings → CI/CD → Testing guidance** (workspace admins only).
It applies to commit pentests and pull-request reviews, in both `custom` and
`endpoint-selection` modes. Leave it empty to use Pensar's defaults.

```text
Prioritize changes to authentication, session handling, and authorization checks.

Our externally exposed surfaces are the storefront and the public API; the admin
console is internal-only.

Billing endpoints are high value — always test them when payment code changes.
```

What guidance does and does not do:

* **It adds priorities, it does not replace the diff analysis.** Pensar still
  reads the diff on every run and only tests what the change actually affects.
* **It cannot widen scope.** Guidance is advisory context, not a target list.
  Pensar only tests the applications, endpoints, domains, and hosts your
  workspace has already authorized, so guidance cannot reach anything else — in
  your workspace or any other.
* **It is advisory, not a hard rule.** Write it as priorities ("prioritize
  authentication changes"), not as absolute include/exclude rules. To pin a run
  to an exact set of endpoints, scope the launch instead — see
  [Launch a pentest](/console/api/api-reference/pentests/launch-pentest).
* **The planner explains its effect.** Each run records the reasoning behind its
  selection, so you can see how your guidance shaped it.

To override the saved guidance for one run — for example, to pass the output of
your own risk classifier — send `testingGuidance` to
[`POST /ci/dispatch`](#dispatch-scan). The value used by a run is recorded on
that pentest, so a retry plans against the same text. Guidance is capped at
4,000 characters.

### Compare two explicit commits

To test exactly what changed between two deployed versions, pass the previously deployed commit as `--base` (or `PENSAR_BASE_SHA`) along with the new commit. Requires `@pensar/ci` 2.7.0 or later.

```bash
pensar pentest \
  --commit 2222222222222222222222222222222222222222 \
  --base 1111111111111111111111111111111111111111
```

In GitHub Actions the repository is detected automatically; elsewhere, pass `--repo-id`. The CLI sends these as `baseSha` and `commitSha` to [`POST /ci/dispatch`](#dispatch-scan), which you can also call directly.

* Both values must be full 40-character SHAs, and the repository must be known (`--repo-id`, or `repoId` / `repositoryId` on the API).
* Both commits must exist in that repository. A missing commit returns `400`; Pensar does not fall back to the last pentest or a full scan.
* The two commit trees are compared directly, so rollbacks and diverged histories work. The commit buffer is bypassed.
* If the two commits are the same, there is nothing to test and the run is skipped.
* The range is kept if the scan is queued, deduplicated, or retried.

### Run Only on Labelled Changes

When only some changes are worth pentesting, label the pull request and gate the
workflow on that label. This is done in the workflow, not in the CLI.

On a pull-request-triggered workflow the labels are in the event payload, so a
job-level condition is all you need and nothing extra runs:

```yaml
jobs:
  pentest:
    if: contains(github.event.pull_request.labels.*.name, 'pentest')
    runs-on: ubuntu-latest
    # ...
```

On a push or a post-deploy run there is no pull request in the payload, so the
pull request the commit came from has to be looked up. Add a small job that does
the lookup and make the pentest job depend on it:

```yaml
permissions:
  contents: read
  pull-requests: read # lets the gate read the label off the pull request

jobs:
  gate:
    runs-on: ubuntu-latest
    outputs:
      labelled: ${{ steps.check.outputs.labelled }}
    steps:
      - id: check
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          LABEL: "pentest"
        run: |
          if gh api "repos/${{ github.repository }}/commits/${{ github.sha }}/pulls" \
               --jq '.[].labels[].name' | grep -Fqx -- "$LABEL"; then
            echo 'labelled=true' >> "$GITHUB_OUTPUT"
          else
            echo "No $LABEL label on the pull request for this commit. Skipping."
            echo 'labelled=false' >> "$GITHUB_OUTPUT"
          fi

  pentest:
    needs: gate
    if: needs.gate.outputs.labelled == 'true'
    runs-on: ubuntu-latest
    # ...
```

Because the pentest job depends on the gate, an unlabelled change never starts
it: no runner, no checkout, no install.

Keep the label in `LABEL` rather than inlining it into the command. A label is
free text, so an apostrophe would break the quoting and a `.` or `*` would make
`grep` match a different label; `-F` compares it literally.

> **Warning**
>
> After a deploy, use `${{ github.event.workflow_run.head_sha }}` rather than
> `${{ github.sha }}`. On a `workflow_run` event `github.sha` is the tip of the
> default branch, not the commit that was deployed, so the gate would check
> whichever change landed most recently.

The Console generates both of these for you: enter a label under **Settings →
CI/CD** and the workflow snippets on that page include the gate, with the right
SHA for each trigger.

### Check Scan Status

```bash
pensar status <scanId>
```

**Example:**

```bash
pensar status abc123-def456-789
```

## CI/CD Examples

### GitHub Actions

#### On Push

Run a pentest when commits are pushed to main branches:

```yaml
name: Pensar Pentest

on:
  push:
    branches: [main, master, develop]

jobs:
  pentest:
    name: Pensar Pentest
    runs-on: ubuntu-latest
    timeout-minutes: 60
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install Pensar CI
        run: npm install -g @pensar/ci

      - name: Run Pensar Pentest
        env:
          PENSAR_API_KEY: ${{ secrets.PENSAR_API_KEY }}
        run: pensar pentest --branch ${{ github.ref_name }}
```

#### On Pull Request

Review each pull request against its preview once the preview deploys. The
workflow runs on GitHub's `deployment_status` event, so a failed deployment
never starts a pentest. It tests the URL and commit the deployment reported,
compares that commit to the base of the open pull request whose head it is,
and reports on that pull request. Requires `@pensar/ci` 2.8.0 or later, and a
preview provider that creates GitHub deployments with an environment URL.

```yaml
name: Pensar Security Review

on:
  deployment_status:

permissions:
  contents: read
  pull-requests: read

jobs:
  pentest:
    name: Pensar Security Review
    if: github.event.deployment_status.state == 'success'
    runs-on: ubuntu-latest
    timeout-minutes: 60

    steps:
      - name: Find the pull request for the deployed commit
        id: pr
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SHA: ${{ github.event.deployment.sha }}
          PREVIEW_URL: ${{ github.event.deployment_status.environment_url }}
        run: |
          pr=$(gh api "repos/${{ github.repository }}/commits/$SHA/pulls" \
            | jq -c --arg sha "$SHA" 'map(select(.state == "open" and .head.sha == $sha)) | first // empty')
          if [ -z "$pr" ]; then
            echo "No open pull request has $SHA as its head. Skipping."
            echo 'found=false' >> "$GITHUB_OUTPUT"
            exit 0
          fi
          if [ -z "$PREVIEW_URL" ]; then
            echo "::error::The deployment for $SHA reported no environment URL to pentest."
            exit 1
          fi
          {
            echo 'found=true'
            echo "url=$(jq -r .html_url <<< "$pr")"
            echo "base=$(jq -r .base.sha <<< "$pr")"
          } >> "$GITHUB_OUTPUT"

      - if: steps.pr.outputs.found == 'true'
        uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install Pensar CI
        if: steps.pr.outputs.found == 'true'
        run: npm install -g @pensar/ci@^2.8.0

      - name: Run Pensar Pentest
        if: steps.pr.outputs.found == 'true'
        env:
          PENSAR_API_KEY: ${{ secrets.PENSAR_API_KEY }}
          BASE_SHA: ${{ steps.pr.outputs.base }}
          HEAD_SHA: ${{ github.event.deployment.sha }}
          PREVIEW_URL: ${{ github.event.deployment_status.environment_url }}
          PULL_REQUEST: ${{ steps.pr.outputs.url }}
        run: |
          pensar pentest \
            --base "$BASE_SHA" \
            --commit "$HEAD_SHA" \
            --url "$PREVIEW_URL" \
            --pull-request "$PULL_REQUEST"
```

The preview host must be a [verified domain](/console/domains/verifying-domains), or
sit under one: verify the parent of your preview hosts once (for example
`preview.acme.example`) and every per-pull-request host beneath it is
covered. Credentials whose login page is on your application's domain sign
in on the preview instead.

Each run reports a **Pensar Security Review** check on the commit. Findings
at or above `--severity` (`critical` by default) fail the check, the same
rule the CLI uses for its exit code; findings below it stay on the check as
annotations. A run that fails, pauses or leaves targets unfinished fails the
check even with no findings. When pull-request comments are enabled for the
workspace, each finding, or its patch when patching is on, is also posted
on the pull request.

#### After Deployment

Run a pentest after a successful deployment workflow. This example assumes that workflow deployed its `head_sha`; if it deploys a different artifact, pass the actual artifact commit to both checkout and `--commit`. The comparison base remains the last qualifying pentest, not the preceding deployment:

```yaml
name: Pensar Pentest (Post-Deploy)

on:
  workflow_run:
    workflows: ['Deploy']
    types: [completed]
    branches: [main, staging]

jobs:
  pentest:
    name: Pensar Pentest
    runs-on: ubuntu-latest
    if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
    timeout-minutes: 60
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.workflow_run.head_sha }}

      - uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install Pensar CI
        run: npm install -g @pensar/ci

      - name: Run Pensar Pentest
        env:
          PENSAR_API_KEY: ${{ secrets.PENSAR_API_KEY }}
        run: |
          pensar pentest \
            --branch ${{ github.event.workflow_run.head_branch || github.ref_name }} \
            --commit ${{ github.event.workflow_run.head_sha }} \
            --environment staging
```

#### Compare With Last Deploy

Test only what changed since the previous successful deployment. It uses `--base` ([compare two explicit commits](#compare-two-explicit-commits)), which requires `@pensar/ci` 2.7.0 or later.

It assumes your deploy job records a [GitHub deployment](https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment) (for example by setting `environment: production` on the job), so the workflow runs on each successful deployment and the last deploy is the most recent earlier deployment to that environment that ever reached `success` (GitHub marks it `inactive` once a newer deploy succeeds). If there is no earlier deployment, it runs without `--base` and the default baseline applies.

```yaml
name: Pensar Pentest (Since Last Deploy)

on:
  deployment_status:

permissions:
  deployments: read

jobs:
  pentest:
    if: github.event.deployment_status.state == 'success' && github.event.deployment.environment == 'production'
    runs-on: ubuntu-latest
    steps:
      - name: Find the previous successful deploy
        id: base
        env:
          GH_TOKEN: ${{ github.token }}
          ENVIRONMENT: ${{ github.event.deployment.environment }}
          CURRENT_ID: ${{ github.event.deployment.id }}
        run: |
          base=""
          for row in $(gh api "repos/${{ github.repository }}/deployments?environment=$ENVIRONMENT&per_page=50" \
              --jq ".[] | select(.id < $CURRENT_ID) | \"\\(.id),\\(.sha)\""); do
            ok=$(gh api "repos/${{ github.repository }}/deployments/${row%%,*}/statuses?per_page=100" --jq 'any(.[]; .state == "success")')
            if [ "$ok" = "true" ]; then base="${row#*,}"; break; fi
          done
          echo "sha=$base" >> "$GITHUB_OUTPUT"

      - uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install Pensar CI
        run: npm install -g @pensar/ci@^2.7.0

      - name: Run Pensar Pentest
        env:
          PENSAR_API_KEY: ${{ secrets.PENSAR_API_KEY }}
          PENSAR_BASE_SHA: ${{ steps.base.outputs.sha }}
        run: |
          [ -n "$PENSAR_BASE_SHA" ] || unset PENSAR_BASE_SHA
          pensar pentest --commit ${{ github.event.deployment.sha }}
```

### GitLab CI

Add to your `.gitlab-ci.yml`:

```yaml
stages:
  - security

pensar-pentest:
  stage: security
  image: node:22
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
  before_script:
    - npm install -g @pensar/ci
  script:
    - pensar pentest --branch $CI_COMMIT_REF_NAME
  variables:
    PENSAR_API_KEY: $PENSAR_API_KEY
```

### Bitbucket Pipelines

Add to your `bitbucket-pipelines.yml`:

```yaml
pipelines:
  branches:
    main:
      - step:
          name: Pensar Pentest
          image: node:22
          script:
            - npm install -g @pensar/ci
            - pensar pentest --branch main
```

## Exit Codes

| Code | Meaning                              |
| ---- | ------------------------------------ |
| 0    | Scan completed with no issues        |
| 1    | Scan found security issues or failed |

> **Warning**
>
> The CLI exits with code 1 when it finds an issue at or above `--severity` (`critical` by default). Use this to block deployments when vulnerabilities are detected.

## API Reference

### Dispatch Scan

```
POST /ci/dispatch
```

**Headers:**

* `Authorization: Bearer <api_key>` or `x-api-key: <api_key>`
* `Content-Type: application/json`

**Request Body:**

Provide a repository so the pentest is scoped to that repository's
applications. Supply either `repoId` (GitHub's numeric repository id — the
CLI auto-detects this from `GITHUB_REPOSITORY_ID`) or `repositoryId` (the
internal repository UUID). When neither is supplied, application scope remains
workspace-wide. Exactly one connected repository still supplies attribution and
a baseline; multiple repositories leave the scan unattributed without diff narrowing.

```json
{
  "repoId": 123456789,
  "repositoryId": "string (uuid, optional alternative to repoId)",
  "branch": "string (optional)",
  "scanLevel": "priority | full (optional)",
  "commitSha": "string (optional)",
  "baseSha": "string (optional; requires commitSha and a selected repository)",
  "targetUrl": "string (optional preview/staging URL the live test should hit)",
  "pullRequest": "string URL or positive integer (optional GitHub pull request)",
  "errorSeverityThreshold": "critical | high | medium | low | info (optional, defaults to critical)",
  "testType": "custom | endpoint-selection (optional, defaults to custom)",
  "testingGuidance": "string (optional, max 4000 characters)"
}
```

The repository must already be connected to the workspace. If it isn't found,
the API responds `404`; if it belongs to another workspace, `403`; if it has
no discovered applications yet (run reconnaissance first), `422`.

With `baseSha`, CI compares exactly that commit to `commitSha` in the selected repository and bypasses the commit buffer. Both commits must exist there; a missing commit returns `400` instead of recovering to a full scan. Omit `baseSha` to keep the default last-pentest baseline.

`pullRequest` records the scan as a pull-request review (`eventType: pull-request`). A number is resolved to `https://github.com/{owner}/{name}/pull/{n}` when a repository is selected. A review skips the commit buffer and the branch guard, and plans its own scope from the diff: the affected endpoints, including new routes, each with its own objectives, in place of `testType`. `targetUrl` is the host the live test hits; it must be a verified domain or sit under one, or the API responds `403`. `errorSeverityThreshold` is the CLI's `--severity` (sent with `--pull-request`), and the review's GitHub check concludes with it; only pull-request reviews get a check.

`testType: custom` derives application-level objectives from the diff;
`endpoint-selection` selects affected discovered endpoints. Both use the same
repository baseline and recovery rules above. A supplied branch must match the
repository's configured target branch unless `pullRequest` is set;
it does not select a different branch for one run.

`testingGuidance` replaces your workspace's saved testing guidance for this one
run — see [Testing guidance](#testing-guidance) below. Omit it to use the saved
value; a blank string is rejected with a `400` rather than silently dropping the
saved guidance.

**Response:**

```json
{
  "scanId": "string",
  "label": "string",
  "status": "queued"
}
```

### Get Scan Status

```
GET /ci/status/{scanId}
```

**Headers:**

* `Authorization: Bearer <api_key>` or `x-api-key: <api_key>`

**Response:**

```json
{
  "scanId": "string",
  "label": "string",
  "status": "queued | running | completed | failed | paused",
  "startedAt": "string | null",
  "completedAt": "string | null",
  "errorMessage": "string | null",
  "issuesCount": 0,
  "issueCountsBySeverity": {
    "critical": 0,
    "high": 0,
    "medium": 0,
    "low": 0
  },
  "reportReady": false
}
```

## Next Steps

#### [Hybrid Testing](/console/features/hybrid-testing)

Learn about Pensar's hybrid testing methodology.

#### [Auto-Remediation](/console/features/auto-remediation)

Automatically fix vulnerabilities found during scans.

#### [Pentest Reports](/console/features/pentest-reports)

Generate detailed security reports from your scans.

#### [GitHub Integration](/console/integrations/github)

Set up event-based scanning with GitHub integration.