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

# Code Security

> Static analysis, dynamic testing, vulnerability management, penetration testing, and license compliance in CaseBender.

## Overview

CaseBender's code security program covers the entire software development lifecycle — from static analysis during development to dynamic testing in staging, continuous vulnerability monitoring in production, and regular penetration testing by third parties.

### Live Security Scan Status

![Security Scan](https://github.com/casebender/webapp/actions/workflows/security-scan.yml/badge.svg?branch=main)

This badge represents 12 automated security checks that run on every code change.

## Static Application Security Testing (SAST)

### ESLint Security Rules

Every pull request is scanned with ESLint security rules that detect:

* Use of `eval()` and `Function()` constructor
* `dangerouslySetInnerHTML` in React components
* Hardcoded secrets and credentials
* Insecure regular expressions (ReDoS)
* Prototype pollution patterns

### Semgrep Deep Analysis

[Semgrep](https://semgrep.dev/) provides deep taint analysis across the TypeScript and Next.js codebase:

* **OWASP Top 10 Rules**: Injection, broken authentication, sensitive data exposure, XSS, insecure deserialization
* **TypeScript-Specific Rules**: Type confusion, unsafe type assertions, prototype pollution
* **Next.js-Specific Rules**: Server-side request forgery, open redirects, insecure API routes
* **Custom Rules**: CaseBender-specific patterns for common security mistakes

### Secret Detection

[Gitleaks](https://gitleaks.io/) scans every commit for accidentally committed secrets:

* API keys and tokens
* Database connection strings
* Private keys and certificates
* Cloud provider credentials
* Generic high-entropy strings

Gitleaks scans both the current commit and the full git history to catch secrets that may have been committed and later removed.

## Dynamic Application Security Testing (DAST)

### OWASP ZAP

[OWASP ZAP](https://www.zaproxy.org/) performs full active scanning against the running application:

* **Schedule**: Weekly (every Sunday at 2 AM UTC)
* **Scan Type**: Full active scan (not just passive observation)
* **Target**: Complete application surface including API endpoints
* **Results**: SARIF format uploaded to GitHub Code Scanning

### What ZAP Tests

* SQL injection
* Cross-site scripting (XSS)
* Cross-site request forgery (CSRF)
* Server-side request forgery (SSRF)
* Directory traversal
* Remote code execution
* Authentication bypass
* Session management flaws
* Information disclosure

## Vulnerability Management

### Continuous Scanning

Vulnerabilities are detected through multiple channels:

| Scanner                      | Target                            | Schedule   | Severity Gate              |
| ---------------------------- | --------------------------------- | ---------- | -------------------------- |
| **Trivy (Filesystem)**       | npm dependencies                  | Every PR   | CRITICAL, HIGH             |
| **Trivy (Container)**        | Container images (all 7 services) | Every PR   | CRITICAL, HIGH             |
| **Trivy (IaC)**              | Dockerfiles, Kubernetes configs   | Every PR   | CRITICAL, HIGH             |
| **pnpm audit**               | Production dependencies           | Every PR   | CRITICAL, HIGH             |
| **Dependabot**               | All dependencies                  | Continuous | Automatic PRs              |
| **GitHub Dependency Review** | New/changed dependencies          | Every PR   | CRITICAL, HIGH block merge |

### Vulnerability SLAs

When vulnerabilities are discovered, they must be remediated within defined SLAs:

| Severity                     | Remediation SLA | Escalation                  |
| ---------------------------- | --------------- | --------------------------- |
| **Critical** (CVSS 9.0-10.0) | 24 hours        | Immediate team notification |
| **High** (CVSS 7.0-8.9)      | 7 days          | Daily standup review        |
| **Medium** (CVSS 4.0-6.9)    | 30 days         | Weekly review               |
| **Low** (CVSS 0.1-3.9)       | 90 days         | Quarterly review            |

### Risk Acceptance

When a vulnerability cannot be immediately remediated (e.g., no patch available), CaseBender follows a formal risk acceptance process:

1. **Documentation**: Vulnerability details, affected components, and business impact
2. **Justification**: Why remediation is not immediately possible
3. **Mitigation**: Compensating controls in place to reduce risk
4. **Review Date**: Mandatory review date (maximum 90 days)
5. **Approval**: Security team approval required

Risk acceptances are tracked in `.trivyignore` with full documentation and quarterly review.

## Penetration Testing

CaseBender includes a penetration testing management module:

### Engagement Management

* **Engagement Tracking**: Schedule and track penetration testing engagements
* **Scope Definition**: Define testing scope, rules of engagement, and authorized techniques
* **Finding Management**: Track findings with severity, status, and remediation progress
* **Remediation SLAs**: Findings must be remediated within severity-based SLAs

### Remediation SLAs

| Finding Severity  | Remediation Deadline |
| ----------------- | -------------------- |
| **Critical**      | 15 days              |
| **High**          | 30 days              |
| **Medium**        | 60 days              |
| **Low**           | 90 days              |
| **Informational** | Next release cycle   |

## License Compliance

### Automated License Scanning

Every dependency's license is checked automatically:

* **Blocked Licenses**: Copyleft licenses (GPL, AGPL, LGPL) are blocked from entering the codebase
* **Allowed Licenses**: MIT, Apache 2.0, BSD, ISC, and other permissive licenses
* **Review Required**: Uncommon or unknown licenses are flagged for legal review
* **No License**: Dependencies without a declared license are blocked

### License Scanning Pipeline

Trivy performs license scanning as part of the security scan workflow:

```
Dependency Added → License Detected → Policy Check → Allowed / Blocked / Review Required
```

## Input Validation

CaseBender implements comprehensive input validation to prevent injection attacks:

### HTML Sanitization

* All user-provided HTML (comments, descriptions) is sanitized before storage and rendering
* Allowlisted tags and attributes only
* Script tags, event handlers, and data URIs are stripped

### File Upload Validation

* MIME type verification (not just extension checking)
* Blocked extensions: `.exe`, `.bat`, `.cmd`, `.ps1`, `.sh`, `.dll`, `.so`
* Maximum file size enforcement (configurable per upload type)
* Evidence uploads have separate, stricter validation

### URL Validation (SSRF Prevention)

* External URLs are validated before any server-side requests
* Private IP ranges (10.x, 172.16-31.x, 192.168.x, 127.x) are blocked
* Internal hostnames and cloud metadata endpoints are blocked
* DNS rebinding protection via pre-resolution validation

### Request Sanitization

* Null byte stripping from all string inputs
* Unicode normalization to prevent homograph attacks
* Zod schema validation on every API endpoint
* Parameterized queries via Prisma ORM (no raw SQL)

## Security Gate

All security checks must pass before code can be merged to the main branch:

```
PR Created
  ├── Gitleaks (secret detection)
  ├── Trivy (dependency scan)
  ├── Trivy (container scan × 7 services)
  ├── Trivy (IaC scan)
  ├── ESLint Security
  ├── Semgrep SAST
  ├── pnpm audit
  ├── License compliance
  ├── Dependency review
  └── Supply chain verification
       │
       ▼
  Security Gate (all must pass)
       │
       ▼
  Merge Allowed
```

<Warning>
  The security gate is enforced via GitHub branch protection rules. It cannot be bypassed, even by repository administrators.
</Warning>

## Related Documentation

* [Supply Chain Security](/en/security/supply-chain) — Container signing, SBOM, and provenance
* [Security Overview](/en/security/overview) — Live pipeline status
* [Hardening Guide](/en/security/hardening-guide) — Deployment security recommendations
