# Security Auditing Skill

**Description**: Security best practices and audit procedures for full-stack applications.

## When to Use

- Before production deployments
- After adding new features
- Regular security reviews
- Compliance requirements

## Security Checklist

### 🔐 Authentication & Authorization

- [ ] JWT secrets are strong (32+ chars) and rotated regularly
- [ ] Tokens have appropriate expiration (≤24h for access tokens)
- [ ] Password hashing uses bcrypt/argon2 with proper salt rounds
- [ ] Role-based access control (RBAC) is implemented
- [ ] Admin endpoints require admin role verification
- [ ] API endpoints validate permissions on every request

### 🔒 Data Protection

- [ ] All sensitive data is encrypted at rest (Cosmos DB)
- [ ] HTTPS enforced in production
- [ ] Environment variables contain secrets, never committed
- [ ] PII data is identified and protected
- [ ] Database queries use parameterized inputs
- [ ] Input validation on all endpoints

### 🛡️ API Security

- [ ] CORS properly configured
- [ ] Rate limiting implemented on public endpoints
- [ ] Request size limits set
- [ ] SQL/NoSQL injection protection
- [ ] XSS protection headers enabled
- [ ] CSRF protection for state-changing operations

### 📦 Dependencies

- [ ] No known vulnerabilities in dependencies
- [ ] Dependencies regularly updated
- [ ] License compliance checked
- [ ] Supply chain security (SLSA) considered

## Security Auditing Commands

### Python Security Audit

```bash
# Check for known vulnerabilities
pip-audit

# Bandit static analysis for security issues
bandit -r src/ -f json -o bandit-report.json

# Safety check for dependencies
safety check --json --output safety-report.json

# Semgrep for custom security rules
semgrep --config=auto src/
```

### TypeScript/Node.js Security Audit

```bash
# Audit npm dependencies
npm audit --audit-level moderate

# Fix vulnerabilities
npm audit fix

# Snyk for advanced scanning
npx snyk test --json > snyk-report.json

# eslint-plugin-security for code issues
npm run lint -- --config .eslintrc.security.js
```

### Infrastructure Security

```bash
# Check exposed ports
nmap -sS -O localhost

# SSL/TLS configuration test
nmap --script ssl-enum-ciphers -p 443 yourdomain.com

# Docker security scan
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
  aquasec/trivy image your-app:latest

# Terraform security check (if using IaC)
tfsec .
```

## Common Security Issues and Fixes

### 1. Hardcoded Secrets

**❌ Bad:**

```typescript
const apiKey = 'sk-1234567890abcdef';
```

**✅ Good:**

```typescript
const apiKey = process.env.API_KEY;
if (!apiKey) throw new Error('API_KEY required');
```

### 2. SQL/NoSQL Injection

**❌ Bad:**

```typescript
const query = `SELECT * FROM users WHERE email = '${email}'`;
```

**✅ Good:**

```typescript
const query = 'SELECT * FROM users WHERE email = ?';
const result = await db.query(query, [email]);
```

### 3. XSS Prevention

**❌ Bad:**

```typescript
div.innerHTML = userContent;
```

**✅ Good:**

```typescript
div.textContent = userContent;
// or use a sanitization library
div.innerHTML = DOMPurify.sanitize(userContent);
```

### 4. Insecure Direct Object Reference

**❌ Bad:**

```typescript
app.get('/api/users/:id', async (req, res) => {
  const user = await getUserById(req.params.id);
  res.json(user);
});
```

**✅ Good:**

```typescript
app.get('/api/users/:id', async (req, res) => {
  if (req.user.id !== req.params.id && !req.user.isAdmin) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  const user = await getUserById(req.params.id);
  res.json(user);
});
```

## Security Headers

### Implement in Fastify

```typescript
import fastifyHelmet from '@fastify/helmet';

await server.register(fastifyHelmet, {
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"],
      scriptSrc: ["'self'"],
      imgSrc: ["'self'", 'data:', 'https:'],
    },
  },
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true,
    preload: true,
  },
});
```

### Implement in Next.js

```typescript
// next.config.js
const securityHeaders = [
  {
    key: 'X-DNS-Prefetch-Control',
    value: 'on',
  },
  {
    key: 'Strict-Transport-Security',
    value: 'max-age=63072000; includeSubDomains; preload',
  },
  {
    key: 'X-XSS-Protection',
    value: '1; mode=block',
  },
  {
    key: 'X-Frame-Options',
    value: 'DENY',
  },
  {
    key: 'X-Content-Type-Options',
    value: 'nosniff',
  },
];

module.exports = {
  async headers() {
    return [
      {
        source: '/(.*)',
        headers: securityHeaders,
      },
    ];
  },
};
```

## Rate Limiting

### Fastify Implementation

```typescript
import rateLimit from '@fastify/rate-limit';

await server.register(rateLimit, {
  max: 100, // 100 requests
  timeWindow: '1 minute', // per minute
  errorResponseBuilder: (request, context) => ({
    code: 'RATE_LIMIT_EXCEEDED',
    error: 'Too many requests',
    retryAfter: context.ttl,
  }),
});

// Stricter limits for auth endpoints
await server.register(rateLimit, {
  max: 5,
  timeWindow: '15 minutes',
  hook: 'preHandler',
  routes: ['/api/auth/login', '/api/auth/register'],
});
```

## Environment Security

### .env File Template

```bash
# .env.example (committed)
COSMOS_ENDPOINT=
COSMOS_KEY=
JWT_SECRET=
AZURE_SPEECH_KEY=
AZURE_OPENAI_KEY=

# .env.local (gitignored)
COSMOS_ENDPOINT=https://<your-account>.documents.azure.com:443/
COSMOS_KEY=<cosmos-key>
JWT_SECRET=<jwt-secret>
AZURE_SPEECH_KEY=<azure-speech-key>
AZURE_OPENAI_KEY=<azure-openai-key>
```

### Git Hooks for Security

```bash
#!/bin/sh
# .husky/pre-commit
# Prevent committing secrets

# Check for potential secrets
if git diff --cached --name-only | xargs grep -l "password\|secret\|key" 2>/dev/null; then
  echo "⚠️  Warning: Possible secrets detected in staged files"
  echo "Please review and ensure no actual secrets are committed"
  exit 1
fi

# Check for .env files
if git diff --cached --name-only | grep -E "\.env$"; then
  echo "❌ Error: .env files should not be committed"
  exit 1
fi
```

## OWASP Top 10 Mitigations

### 1. Broken Access Control

- Implement proper authorization checks
- Use RBAC with least privilege
- Validate permissions on every request

### 2. Cryptographic Failures

- Use strong encryption algorithms
- Proper key management
- Hash passwords with bcrypt/argon2

### 3. Injection

- Use parameterized queries
- Validate and sanitize inputs
- Use ORMs with built-in protection

### 4. Insecure Design

- Implement security by design
- Use threat modeling
- Secure default configurations

### 5. Security Misconfiguration

- Remove default credentials
- Disable unused features
- Keep software updated

### 6. Vulnerable Components

- Regular dependency updates
- Vulnerability scanning
- Use trusted sources

### 7. Authentication Failures

- Multi-factor authentication
- Strong password policies
- Account lockout mechanisms

### 8. Data Integrity Failures

- Digital signatures
- Checksums
- Immutable audit logs

### 9. Security Logging Failures

- Comprehensive logging
- Monitor for suspicious activity
- Protect log integrity

### 10. Server-Side Request Forgery (SSRF)

- Validate URLs
- Allowlist destinations
- Network segmentation

## Security Testing

### Automated Security Tests

```typescript
// tests/security/auth.test.ts
describe('Security', () => {
  it('should reject requests without token', async () => {
    const response = await app.inject({
      method: 'GET',
      url: '/api/protected',
    });

    expect(response.statusCode).toBe(401);
  });

  it('should reject invalid tokens', async () => {
    const response = await app.inject({
      method: 'GET',
      url: '/api/protected',
      headers: {
        authorization: 'Bearer invalid.token.here',
      },
    });

    expect(response.statusCode).toBe(401);
  });

  it('should prevent SQL injection', async () => {
    const maliciousInput = "'; DROP TABLE users; --";
    const response = await app.inject({
      method: 'POST',
      url: '/api/search',
      payload: { query: maliciousInput },
    });

    expect(response.statusCode).toBe(400);
  });
});
```

### Penetration Testing Checklist

- [ ] Authentication bypass attempts
- [ ] Authorization testing
- [ ] Input validation fuzzing
- [ ] Session management testing
- [ ] Error disclosure analysis
- [ ] Business logic flaws

## Incident Response

### Security Incident Plan

1. **Detection**
   - Monitor security tools
   - Review logs regularly
   - Set up alerts

2. **Assessment**
   - Determine scope
   - Classify severity
   - Document findings

3. **Containment**
   - Isolate affected systems
   - Change credentials
   - Block malicious IPs

4. **Eradication**
   - Remove malware
   - Patch vulnerabilities
   - Clean data

5. **Recovery**
   - Restore from backup
   - Monitor for recurrence
   - Update defenses

6. **Post-mortem**
   - Document lessons learned
   - Update processes
   - Train team

## Notes

- **Security is ongoing** - Not a one-time task
- **Defense in depth** - Multiple layers of security
- **Principle of least privilege** - Minimum access necessary
- **Regular audits** - Schedule and perform regularly
- **Stay informed** - Keep up with security news

## Related Skills

- [Production Readiness](./production-readiness.md) - Security is part of readiness
- [Debug Service](./debug-service.md) - Security issues debugging
- [Test Strategies](./test-strategies.md) - Security testing
