> ## 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.

# GitLab CI/CD

> Set up CodeAnt Quality Gates in your GitLab CI Pipeline.

# CodeAnt Quality Gate Scan for GitLab

This GitLab CI/CD pipeline runs CodeAnt quality gate scan with secret detection and code quality analysis. It integrates with your CI/CD pipeline and fails if secrets are detected or quality gates fail.

## Features

* 🔒 Secret detection and security scanning
* 📊 Code quality gate enforcement
* ⏱️ Configurable polling and timeout
* ✅ Pass/Fail pipeline status based on scan results

## Variables

| Name                  | Description                                 | Required | Default                                          |
| --------------------- | ------------------------------------------- | -------- | ------------------------------------------------ |
| ACCESS\_TOKEN\_GITLAB | GitLab token for authentication             | Yes      | -                                                |
| API\_BASE             | Base URL for CodeAnt API                    | No       | [https://api.codeant.ai](https://api.codeant.ai) |
| TIMEOUT               | Maximum time in seconds to wait for results | No       | 300                                              |
| POLL\_INTERVAL        | Time in seconds between polling attempts    | No       | 15                                               |

## Usage

### Quick Start (Recommended)

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

```yaml theme={null}
include:
  - remote: 'https://gitlab.com/codeant-pipelines/quality-gates-gitlab/-/raw/main/.gitlab-ci.yml'

stages:
  - quality-gate

codeant-quality-gate:
  variables:
    API_BASE: "https://api.codeant.ai"
    TIMEOUT: "600"           # Wait up to 10 minutes for results
    POLL_INTERVAL: "20"      # Poll every 20 seconds
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
```

Set the `ACCESS_TOKEN_GITLAB` variable in your GitLab project settings (**Settings > CI/CD > Variables**).

### With Custom Job Name

```yaml theme={null}
include:
  - remote: 'https://gitlab.com/codeant-pipelines/quality-gates-gitlab/-/raw/main/.gitlab-ci.yml'

codeant-scan:
  extends: .codeant-quality-gate
  stage: quality-gate
  variables:
    TIMEOUT: "600"
    POLL_INTERVAL: "20"
```

### With Multiple Stages

```yaml theme={null}
include:
  - remote: 'https://gitlab.com/codeant-pipelines/quality-gates-gitlab/-/raw/main/.gitlab-ci.yml'

stages:
  - build
  - quality-gate
  - deploy

build:
  stage: build
  script:
    - echo "Building..."

codeant-quality-gate:
  variables:
    TIMEOUT: "600"

deploy:
  stage: deploy
  script:
    - echo "Deploying..."
  only:
    - main
```

## Setup Instructions

### Step 1: Get Your GitLab Access Token

1. Log in to your GitLab account
2. Go to **Edit profile (User Settings) > Access Tokens**
3. Create a new token with the `api` scope (This grants full read/write access to the API and repositories)
4. Copy the token

### Step 2: Add Pipeline Configuration

Copy the `.gitlab-ci.yml` file from this repository to the root of your GitLab project.

### Step 3: Configure CI/CD Variables

Add the required `ACCESS_TOKEN_GITLAB` variable to your GitLab project:

1. Go to **Settings > CI/CD > Variables**
2. Click **Add Variable**
3. Configure:
   * **Key:** `ACCESS_TOKEN_GITLAB`
   * **Value:** Your GitLab Access Token
   * **Type:** Variable
   * **Environment scope:** All
   * **Protect variable:** ✓ (Recommended)
   * **Mask variable:** ✓ (Recommended)
4. Click **Add variable**

### Step 4: Commit and Push

```bash theme={null}
git add .gitlab-ci.yml
git commit -m "Add CodeAnt quality gate pipeline"
git push origin main
```

The pipeline will automatically run on the next merge request or commit to the main branch.

## Testing from Another Repository

To test this pipeline configuration in your own repository:

1. Clone or copy the `.gitlab-ci.yml` to your repository
2. Set up the `ACCESS_TOKEN_GITLAB` variable in your project settings
3. Push to trigger the pipeline:
   ```bash theme={null}
   git push origin feature-branch
   ```
4. Create a merge request to test automatic scanning

For testing specific configurations:

* Modify the `variables` section in `.gitlab-ci.yml`
* Add custom rules for when the pipeline should run
* Adjust timeout and polling intervals as needed

## How It Works

1. **Checkout:** GitLab automatically checks out your repository code
2. **Fetch Script:** Downloads the quality gates scanning script from CodeAnt API
3. **Prepare Script:** Decodes and prepares the script for execution
4. **Start Scan:** Initiates the quality gate scan on CodeAnt servers
5. **Poll Results:** Continuously polls for scan results until completion or timeout
6. **Report Status:** Reports pass/fail status and fails the pipeline if issues are detected

## Expected Output

### When Quality Gate Passes:

```
Fetching quality gates script from https://api.codeant.ai...
Successfully fetched quality gates script
Quality gates script prepared successfully
Starting quality gate scan...
Quality gate scan initiated successfully
Polling for quality gate results...
Quality gate results retrieved successfully
✅ Quality Gate PASSED - No secrets detected
```

The pipeline succeeds and allows merge/deployment to proceed.

### When Quality Gate Fails:

```
Starting quality gate scan...
Polling for quality gate results...
❌ Quality Gate FAILED - Secrets detected or scan error
Job failed: exit code 1
```

The pipeline fails, preventing merge/deployment and requiring fixes.

## Quality Gate Checks

The quality gate performs comprehensive checks including:

### Security and Code Quality Checks

* **Secret Detection**: Scans for hardcoded secrets, API keys, passwords, and tokens
* **SAST (Static Application Security Testing)**: Detects security vulnerabilities in source code
* **SCA (Software Composition Analysis)**: Identifies vulnerabilities in third-party dependencies
* **IaC (Infrastructure as Code)**: Scans infrastructure configuration files for security issues
* **Duplicate Code Detection**: Identifies code duplication to improve maintainability
* Analyzes only the changed lines since your merge base commit
* Uses high-confidence detection to minimize false positives
* Blocks the build if any issues are found

## GitLab CI/CD Variables Used

The pipeline automatically uses these GitLab-provided variables:

| Variable               | Description                                                 |
| ---------------------- | ----------------------------------------------------------- |
| \$CI\_PROJECT\_PATH    | Project path (e.g., codeant-pipelines/quality-gates-gitlab) |
| \$CI\_COMMIT\_SHA      | Current commit SHA                                          |
| \$CI\_DEFAULT\_BRANCH  | Default branch name (usually main or master)                |
| \$CI\_PIPELINE\_SOURCE | Source that triggered the pipeline                          |
| \$CI\_COMMIT\_BRANCH   | Current branch name                                         |
| \$CI\_JOB\_STATUS      | Job status (success/failed)                                 |

## Required Permissions

The `ACCESS_TOKEN_GITLAB` requires the following permissions:

* **API access** - For CodeAnt API authentication
* **read\_repository** - Read access to repository contents (if using GitLab Access Token)
* **read\_api** - Read API access (if using GitLab Access Token)

## Configuration Options

### Variables

Customize these variables in `.gitlab-ci.yml`:

```yaml theme={null}
variables:
  API_BASE: "https://api.codeant.ai"      # CodeAnt API endpoint
  TIMEOUT: "300"                          # Scan timeout in seconds
  POLL_INTERVAL: "15"                     # Polling interval in seconds
```

### Pipeline Rules

Control when the pipeline runs:

```yaml theme={null}
rules:
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"  # Run on MRs
  - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH       # Run on main branch
  - if: $CI_COMMIT_BRANCH                              # Manual run on any branch
    when: manual
```

### Allow Failure

To make the quality gate advisory (non-blocking):

```yaml theme={null}
codeant-quality-gate:
  allow_failure: true  # Pipeline continues even if quality gate fails
```

## Troubleshooting

### Common Issues

**1. "Failed to fetch quality gates script"**

* Verify `API_BASE` URL is correct
* Check network connectivity from GitLab runners to CodeAnt API
* Ensure API endpoint is accessible

**2. "Authentication failed"**

* Verify `ACCESS_TOKEN_GITLAB` is set in CI/CD variables
* Check token has not expired
* Ensure token has correct permissions

**3. "Timeout waiting for results"**

* Increase `TIMEOUT` value for larger repositories
* Check CodeAnt API status
* Review scan logs for errors

**4. Pipeline doesn't run automatically**

* Verify `.gitlab-ci.yml` is in repository root
* Check CI/CD is enabled for the project
* Review pipeline rules configuration

### Debug Mode

To enable detailed logging, add debug commands:

```yaml theme={null}
script:
  - set -x  # Enable debug output
  - echo "DEBUG: API_BASE=${API_BASE}"
  - echo "DEBUG: CI_PROJECT_PATH=${CI_PROJECT_PATH}"
  - echo "DEBUG: CI_COMMIT_SHA=${CI_COMMIT_SHA}"
```

## Advanced Usage

### Multiple Quality Gates

Run different quality gates for different branches:

```yaml theme={null}
quality-gate-strict:
  extends: .codeant-quality-gate
  variables:
    TIMEOUT: "600"
  rules:
    - if: $CI_COMMIT_BRANCH == "main"

quality-gate-advisory:
  extends: .codeant-quality-gate
  allow_failure: true
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
```

### Integration with Other Jobs

Chain the quality gate with other jobs:

```yaml theme={null}
stages:
  - quality-gate
  - test
  - deploy

codeant-quality-gate:
  stage: quality-gate
  # ... configuration ...

unit-tests:
  stage: test
  needs: ["codeant-quality-gate"]  # Wait for quality gate
  script:
    - npm test

deploy:
  stage: deploy
  needs: ["codeant-quality-gate", "unit-tests"]
  script:
    - ./deploy.sh
  only:
    - main
```

## Support

For issues, questions, or contributions, please:

* **Documentation:** [https://docs.codeant.ai](https://docs.codeant.ai)
* **GitLab CI/CD:** [https://docs.gitlab.com/ee/ci/](https://docs.gitlab.com/ee/ci/)
* **Issues:** Contact your CodeAnt support team or create an issue in this repository

## License

This project is licensed under the MIT License - see the LICENSE file for details.

**Repository:** [https://gitlab.com/codeant-pipelines/quality-gates-gitlab](https://gitlab.com/codeant-pipelines/quality-gates-gitlab)

**Powered by CodeAnt AI** - Automated Code Quality and Security Analysis
