# Security Extensions

## Overview

Security rules organized by when they matter most in the AI-DLC lifecycle.
Each rule is a blocking constraint: a phase or stage cannot complete until all
applicable checks pass or are marked N/A.

### Blocking Behavior

When a check fails:
1. List the finding in the phase/stage completion message under "Security
   Findings" with the rule ID and failed check.
2. Do NOT present "Continue to Next Stage" until resolved.
3. Present only "Request Changes" with what needs to change.
4. Log the finding in `aidlc-docs/audit/audit-log.md` as `EXTENSION_FINDING`.

If a rule does not apply to the current project (e.g., no web UI means DES-04
is irrelevant), mark it **N/A**. This is not a blocking finding.

---

## Applicability Question

Asked during pre-flight when this extension is loaded:

```
Should security rules be enforced for this project?

A) Yes — enforce as blocking constraints (recommended for production)
B) No — skip all security rules (suitable for PoCs and prototypes)
```

Record the answer in `aidlc-docs/aidlc-state.md` under Extension Configuration.

---

## Design-Time Rules

Enforced during Mob Elaboration (story generation, architecture decisions) and
the design stages of Mob Construction (Domain Model, Logical Design). The AI
validates these when producing design artifacts.

### DES-01: Least-Privilege Access

Every identity, role, and permission boundary follows least privilege.

- [ ] No wildcard actions in policies
- [ ] No wildcard resources without a documented exception
- [ ] Read and write permissions in separate policy statements
- [ ] Trust relationships scoped to specific services or accounts
- [ ] Reusable/managed policies preferred over one-off inline definitions

### DES-02: Deny-by-Default Networking

All network configurations start closed and open only what is required.

- [ ] Only application-required ports are open
- [ ] No inbound `0.0.0.0/0` except ports 80/443 on public load balancers
- [ ] No unrestricted outbound without documented justification
- [ ] Private subnets do not have direct public internet routes
- [ ] Private endpoints used for high-traffic cloud service calls
- [ ] Database/app firewall rules scoped to specific source addresses or groups

### DES-03: Secure Design Patterns

Architecture incorporates security from the start, not as an afterthought.

- [ ] Security-critical logic (auth, authz, payments) isolated in dedicated modules
- [ ] Defense in depth: no single control is the sole line of defense
- [ ] Rate limiting on all public-facing endpoints
- [ ] At least one misuse/abuse scenario documented in design

### DES-04: Application-Level Access Control

Every endpoint that reads or mutates a resource enforces authorization.

- [ ] All routes require authentication unless explicitly marked public
- [ ] Object-level authorization: caller's ownership/permission verified per resource ID
- [ ] Admin/privileged operations check caller's role server-side
- [ ] CORS restricted to explicit origins (no `*` on authenticated endpoints)
- [ ] Tokens validated server-side on every request (signature, expiration, audience)

---

## Build-Time Rules

Enforced during Mob Construction (code generation, implementation stages) and
Code Elevation (when assessing or generating code). The AI validates these when
producing or reviewing code artifacts.

### BLD-01: Encryption at Rest and in Transit

Every data store has encryption enabled; every data path uses TLS.

- [ ] No storage resource defined without encryption configuration
- [ ] No unencrypted database connection protocols
- [ ] Object storage rejects non-TLS requests
- [ ] Database instances enforce TLS connections
- [ ] Encryption at rest uses managed or customer-managed keys

### BLD-02: Input Validation and Injection Prevention

Every API endpoint validates all input before processing.

- [ ] Every handler uses a validation library or schema
- [ ] No raw user input concatenated into SQL, NoSQL, or OS commands
- [ ] String inputs have explicit max-length constraints
- [ ] Request body size limits configured at framework or gateway level
- [ ] HTML/script content escaped or rejected in user-supplied strings

### BLD-03: HTTP Security Headers

Web-serving endpoints set required security headers.

- [ ] `Content-Security-Policy` set (minimum: `default-src 'self'`)
- [ ] `Strict-Transport-Security` set with `max-age >= 31536000`
- [ ] `X-Content-Type-Options: nosniff`
- [ ] `X-Frame-Options: DENY` (or `SAMEORIGIN` if framing required)
- [ ] `Referrer-Policy: strict-origin-when-cross-origin`
- [ ] No `unsafe-inline` or `unsafe-eval` in CSP without documented justification

### BLD-04: Authentication and Credential Safety

Authentication is robust; credentials never appear in code.

- [ ] Passwords hashed with adaptive algorithms
- [ ] MFA supported for admin accounts
- [ ] Sessions expire server-side, invalidated on logout
- [ ] Session cookies set `Secure`, `HttpOnly`, `SameSite`
- [ ] Brute-force protection on login endpoints (lockout, delay, or CAPTCHA)
- [ ] No hardcoded credentials in source code, config files, or IaC templates
- [ ] Secrets retrieved from a secrets manager

### BLD-05: Exception Handling and Fail-Safe Defaults

The application handles errors safely and never fails open.

- [ ] All external calls (DB, HTTP, file I/O) have explicit error handling
- [ ] Global error handler configured at application entry point
- [ ] Error paths deny access or halt operation (fail closed)
- [ ] Resources cleaned up in error paths (connections, locks, transactions)
- [ ] Production error responses return generic messages (no stack traces, no internal paths)

### BLD-06: Supply Chain and Dependency Management

Dependencies are pinned, scanned, and sourced from trusted registries.

- [ ] Lock file exists and is committed to version control
- [ ] Dependency vulnerability scanning in CI/CD or build instructions
- [ ] No unused or abandoned dependencies included
- [ ] No `latest` or unpinned image tags in Dockerfiles or CI configs
- [ ] Dependencies sourced from official or verified registries
- [ ] External CDN scripts use Subresource Integrity (SRI) hashes

---

## Operational Readiness Rules

Flagged as requirements during Mob Elaboration, verified in Logical Design and
implementation. These ensure the application is observable and hardened before
it reaches production.

### OPS-01: Structured Logging

Every component produces structured, centralized, PII-free logs.

- [ ] Every service/function entry point has a configured logger
- [ ] Logs include: timestamp, correlation/request ID, log level, message
- [ ] Log output routed to a centralized log service
- [ ] No secrets, tokens, or PII in log output
- [ ] No ad-hoc print/console statements as primary logging in production

### OPS-02: Access Logging on Network Intermediaries

External-facing intermediaries log all access.

- [ ] Load balancers have access logging enabled
- [ ] API gateways have access logging configured
- [ ] CDN distributions have logging configured

### OPS-03: Security Alerting and Log Integrity

Security events trigger alerts; logs are tamper-resistant.

- [ ] Alerts configured for repeated auth failures and authorization violations
- [ ] Log retention set to minimum 90 days
- [ ] Application roles cannot delete their own audit logs
- [ ] Privilege escalation attempts and unusual access patterns generate alerts

### OPS-04: Hardening and Misconfiguration Prevention

Deployed components follow a hardening baseline.

- [ ] No default credentials in deployment
- [ ] No sample/demo applications or default pages deployed
- [ ] Cloud object storage blocks public access unless documented exception
- [ ] Directory listing disabled on web servers
- [ ] Framework and runtime versions are current and supported
- [ ] Critical data modifications are auditable (who, what, when)
- [ ] Untrusted data not deserialized without validation
- [ ] CI/CD pipeline definitions are access-controlled

---

## Enforcement by Ritual

| Ritual | Primary Rules | Secondary Rules |
|--------|--------------|-----------------|
| Mob Elaboration | DES-01 through DES-04 | OPS-01 through OPS-04 (flag as requirements) |
| Mob Construction: Design stages | DES-01 through DES-04 | BLD-01 through BLD-06 (verify design supports them) |
| Mob Construction: Implementation | BLD-01 through BLD-06 | DES-01 through DES-04 (verify code matches design) |
| Code Elevation | All rules | Assess existing code against full checklist |

At each phase/stage completion, include a "Security Compliance" section:
- List each applicable rule as ✅ compliant, ❌ non-compliant, or N/A
- Any ❌ is a blocking finding

---

## OWASP Top 10 (2025) Reference

For compliance teams mapping these rules to OWASP categories:

| Rule | OWASP Category |
|------|----------------|
| DES-04 | A01 — Broken Access Control |
| OPS-04 | A02 — Security Misconfiguration |
| BLD-06 | A03 — Software Supply Chain Failures |
| DES-03 | A06 — Insecure Design |
| BLD-04 | A07 — Authentication Failures |
| BLD-06, OPS-04 | A08 — Software or Data Integrity Failures |
| OPS-01, OPS-02, OPS-03 | A09 — Logging & Alerting Failures |
| BLD-05 | A10 — Mishandling of Exceptional Conditions |
