> For the complete documentation index, see [llms.txt](https://docs.aquilax.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.aquilax.ai/user-manual/security-policy/custom-security-policy.md).

# Custom Security Policy

### 🎯 Key Features

#### 1. **Custom Security Policy Per Scan**

* Define custom security policies when starting a new scan
* Override group-level policies for specific scanning requirements
* Policy automatically preserved during rescans

#### 2. **Intelligent Policy Management**

* Workers prioritize custom policies over group defaults
* **All policies** (custom and group) are normalized based on organization plan
* Automatic policy inheritance for project rescans

#### 3. **Dual Editing Modes**

* **Form Mode**: User-friendly interface for common configurations
* **JSON Mode**: Advanced editing with syntax validation

***

### 📦 Changes Summary

#### **Backend Changes**

**1. Scan Creation Endpoint (`POST /api/v2/scan`)**

**File:** `app/handlers/scan.go`

* Added `custom_security_policy` parameter to `RequestPayloadScan` struct
* Accepts dynamic JSON object (`map[string]interface{}`)
* Conditionally stored in database only when provided

**Request Schema:**

```
{
  "git_uri": "string",
  "endpoint_url": "string",
  "branch": "string",               // optional
  "initiated": "string",             // optional
  "custom_security_policy": {        // optional
    "scanners": ["compliance", "sast", "securitron"],
    "severity_threshold": "high"
  }
}
```

**2. Pending Scans API (`GET /api/v2/admin/scans/pending`)**

**File:** `app/handlers/scan_handler.go`

* Enhanced `CheckPendingScans` function with conditional logic
* If scan has `custom_security_policy` → use it as `security_policy`
* If scan lacks custom policy → use group policy
* **Both policies** are normalized based on organization plan

**Behavior:**

| Scenario             | Security Policy Source    | Plan-Based Normalization |
| -------------------- | ------------------------- | ------------------------ |
| Custom policy exists | `custom_security_policy`  | ✅ **Applied**            |
| No custom policy     | Group's `security_policy` | ✅ **Applied**            |

Important

**Plan-Based Scanner Enforcement**: All security policies (custom and group) are now normalized based on the organization's subscription plan. This ensures that even custom policies respect plan tier restrictions:

* **FREE**: Only `compliance`, `secret`, `pii` scanners
* **PREMIUM**: Adds `sast`, `sca`, `container`, `iac`, `api`
* **ULTIMATE**: All scanners including `malware`, `vibe`, `securitron`

**3. Project Scans Endpoint (`GET /api/v2/project/:project_id`)**

**File:** `app/datastores/projects.go`

* Added `custom_security_policy` to response projection
* Returns custom policy in scan listings when available

**Response Schema:**

```
[
  {
    "_id": "...",
    "created_at": 1234567890,
    "branch": "main",
    "status": "COMPLETED",
    "metadata": { "git": { "sha": "..." } },
    "custom_security_policy": {
      "scanners": ["compliance", "sast", "securitron"]
    }
  }
]
```

***

#### **Frontend Changes**

**1. New Component: Scan Security Policy Modal**

**File:** `scan-security-policy-modal.tsx`

* Dedicated modal for customizing scan-level security policies
* Toggle between Form and JSON editing modes
* Real-time validation and syntax checking
* Apply/Reset functionality

**Features:**

* 📝 Form editor for common configurations
* 🔧 Advanced JSON editor with syntax highlighting
* ✅ Validation feedback
* 🔄 Reset to group defaults

**2. Enhanced: New Scan Modal**

**File:** `new-scan-modal.tsx`

**Additions:**

* "Custom Security Policy" button (bottom left)
* Auto-fetch group security policy on modal open
* Visual badge: "Custom Policy Applied" when customized
* Passes `custom_security_policy` to API payload

**User Flow:**

1. User clicks "Start Scan"
2. Optionally clicks "Custom Security Policy"
3. Customizes policy → Apply
4. Starts scan with custom configuration

**3. Enhanced: Projects Component**

**File:** `projects-component.tsx`

**Modified Function:** `handleRescan()`

**Enhancements:**

* Fetches project's last scan via `ApiClient.getProject()`
* Extracts `custom_security_policy` from last scan (if present)
* Automatically passes it to rescan API

**Rescan Behavior:**

```
Last Scan Had Custom Policy → Rescan uses same custom policy
Last Scan Used Group Policy → Rescan uses current group policy
```

***

### 🔄 User Workflows

#### **Workflow 1: Create Scan with Custom Policy**

1. Navigate to group → Click **"Start Scan"**
2. Fill in required fields (Git URI, endpoint, branch)
3. Click **"Custom Security Policy"** button
4. Customize scanners, thresholds, or other settings
5. Click **"Apply"** → Badge shows "Custom Policy Applied"
6. Start scan

**Result:** Scan runs with custom policy, bypassing group defaults.

***

#### **Workflow 2: Rescan with Preserved Policy**

1. Navigate to project with previous custom-policy scan
2. Click **"Rescan"**
3. System automatically fetches and applies last scan's custom policy

**Result:** Rescan maintains original custom configuration.

***

#### **Workflow 3: Edit Custom Policy (JSON Mode)**

1. Click "Custom Security Policy" → Toggle to **"JSON"** tab
2. Edit raw JSON configuration
3. Validate syntax in real-time
4. Apply changes

**Result:** Advanced users can define complex custom policies.

***

### 🔌 API Integration

#### **Request Format**

```
POST /api/v2/scan
Content-Type: application/json

{
  "git_uri": "https://github.com/org/repo",
  "endpoint_url": "https://api.example.com",
  "branch": "main",
  "custom_security_policy": {
    "scanners": ["compliance", "sast", "securitron"],
    "severity_threshold": "critical",
    "exclude_patterns": ["test/*", "*.md"]
  }
}
```

#### **Response**

```
{
  "scan_id": "507f1f77bcf86cd799439011"
}
```

***

### 🛡️ Technical Details

#### **Database Schema**

Custom policies are stored in the `scans` collection:

```
{
  _id: ObjectId("..."),
  git_uri: "https://github.com/org/repo",
  branch: "main",
  status: "NEW",
  custom_security_policy: {  // Optional field
    scanners: [...],
    severity_threshold: "high"
  },
  // ... other fields
}
```

#### **Worker Integration**

Workers receive enriched scan documents from `/api/v2/admin/scans/pending`:

```
{
  "id": "...",
  "security_policy": {  // Either custom or group policy
    "scanners": ["compliance", "sast", "securitron"],
    ...
  },
  "access_token": "...",
  ...
}
```

***

### ✅ Benefits

| Benefit          | Description                                                       |
| ---------------- | ----------------------------------------------------------------- |
| **Flexibility**  | Different policies for different projects/scenarios               |
| **Consistency**  | Rescans preserve original configurations                          |
| **Control**      | Fine-grained security policy management                           |
| **Efficiency**   | No need to modify group policies temporarily                      |
| **Transparency** | Custom policies visible in scan metadata                          |
| **Security**     | Plan-based enforcement ensures compliance with subscription tiers |

***

### 🔧 Migration Notes

* **Backward Compatible**: Existing scans without custom policies continue using group policies
* **No Breaking Changes**: All existing API contracts maintained
* **Optional Feature**: Custom policies are opt-in; default behavior unchanged

***

### 📝 Files Modified

#### Backend

* `app/handlers/scan.go` - Scan creation with custom policy support
* `app/handlers/scan_handler.go` - Pending scans with policy prioritization
* `app/datastores/projects.go` - Project scans with custom policy in response

#### Frontend

* `scan-security-policy-modal.tsx` - **New** custom policy editor modal
* `new-scan-modal.tsx` - Custom policy integration for new scans
* `projects-component.tsx` - Rescan with preserved custom policies

***

### 🚀 Future Enhancements

* Policy templates library
* Policy versioning and history
* Audit logging for policy changes
* Policy validation rules engine

***

**Release Date:** 2026-02-09\
**Status:** ✅ Production Ready
