# Security Rule

> **Enforced on all code handling user input, authentication, or sensitive data.**

---

## When Applied

- Authentication/authorization code
- User input handling
- Database queries
- API endpoints
- File operations
- External API calls

---

## Injection Prevention

### SQL Injection
```python
# ❌ NEVER
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")

# ✅ ALWAYS
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
```

### Command Injection
```python
# ❌ NEVER
os.system(f"echo {user_input}")

# ✅ ALWAYS
subprocess.run(["echo", user_input], check=True)
```

### XSS
```typescript
// ❌ NEVER
element.innerHTML = userInput;

// ✅ ALWAYS
element.textContent = userInput;
// Or use framework escaping (React auto-escapes)
```

---

## Authentication Rules

### Password Handling
```python
# ❌ NEVER
password_hash = hashlib.md5(password).hexdigest()

# ✅ ALWAYS
password_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
```

### Token Security
- JWT expiry: 15 minutes to 1 hour
- Refresh tokens: stored securely, rotated on use
- Session tokens: cryptographically random

---

## Secrets Management

### Never Hardcode
```python
# ❌ NEVER
API_KEY = "sk-1234567890abcdef"

# ✅ ALWAYS
API_KEY = os.getenv("API_KEY")
```

### Required Protections
- [ ] `.env` files in `.gitignore`
- [ ] Secrets in environment variables
- [ ] No secrets in logs or error messages

---

## Input Validation

### At System Boundaries
```python
from pydantic import BaseModel, EmailStr, constr

class UserCreate(BaseModel):
    email: EmailStr
    username: constr(min_length=3, max_length=50, regex=r'^[a-zA-Z0-9_]+$')
    password: constr(min_length=8)
```

### Validate Everything
- User input
- API request bodies
- URL parameters
- File uploads
- Headers

---

## Error Handling

### Don't Leak Information
```python
# ❌ NEVER
except Exception as e:
    return {"error": str(e)}  # Leaks internals

# ✅ ALWAYS
except ValidationError as e:
    return {"error": "Invalid input"}
except Exception:
    logger.exception("Unexpected error")
    return {"error": "Internal server error"}
```

---

## Security Headers

```python
# Required headers
Content-Security-Policy: default-src 'self'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Strict-Transport-Security: max-age=31536000
```

---

## Dependency Security

### Regular Audits
```bash
# Python
pip-audit
safety check

# JavaScript
npm audit
```

### No Known Vulnerabilities
Block PRs with high/critical CVEs.

---

## Enforcement

Violations trigger:
1. Security reviewer agent flags issue
2. Pre-commit security scan fails
3. CI security check blocks merge
