# Security Policy

## Reporting a Vulnerability

If you discover a security vulnerability within this project:

1. **DO NOT open a public issue**
2. Send an email to security@mathplatform.com
3. Include detailed steps to reproduce
4. Provide potential impact assessment
5. Allow 48 hours for initial response

## Security Measures Implemented

### Authentication

- ✅ JWT with explicit HS256 algorithm
- ✅ Refresh tokens with blacklist (Redis)
- ✅ Password hashing with bcrypt (cost 12)
- ✅ Rate limiting on login (5 attempts/15 min)
- ✅ Account lockout after failed attempts
- ✅ Secure session management

### Authorization

- ✅ RBAC with roles USER/TEACHER/ADMIN
- ✅ Middleware requireAdmin for sensitive routes
- ✅ Resource ownership verification
- ✅ Permission-based access control
- ✅ API key authentication for services

### Web Protection

- ✅ **XSS Protection**:
  - DOMPurify for LaTeX sanitization
  - Content Security Policy headers
  - X-Frame-Options: DENY
  - XSS filter in Helmet.js

- ✅ **CSRF Protection**:
  - CSRF tokens in forms
  - Origin header validation
  - SameSite cookie policy
  - Double-submit cookie pattern

- ✅ **SQL Injection**:
  - Prisma ORM exclusive use
  - No raw queries without validation
  - Parameterized queries
  - Input sanitization

- ✅ **Rate Limiting**:
  - Express-rate-limit + Redis
  - IP-based limiting
  - User-based limiting
  - Endpoint-specific limits

### Infrastructure Security

- ✅ Docker containers run as non-root user
- ✅ Secrets stored in Docker Secrets / Vault
- ✅ SSL/TLS with Let's Encrypt
- ✅ Security headers (HSTS, CSP, X-Frame-Options)
- ✅ Network isolation between services
- ✅ Resource limits on containers

### Data Protection

- ✅ AES-256 encryption for sensitive data
- ✅ Environment variables for secrets
- ✅ No secrets in code or logs
- ✅ Secure backup encryption
- ✅ Data retention policies
- ✅ Secure data deletion

## Compliance

### GDPR

- ✅ Data encryption at rest and in transit
- ✅ Right to erasure implemented
- ✅ Data portability (/api/user/export)
- ✅ Consent management
- ✅ Data breach notification procedures
- ✅ Privacy by design

### OWASP Top 10

| Risk | Mitigation | Status |
|------|------------|--------|
| A01: Broken Access Control | RBAC, middleware auth, ownership checks | ✅ Mitigated |
| A02: Cryptographic Failures | bcrypt (cost 12), AES-256, TLS 1.3 | ✅ Mitigated |
| A03: Injection | Prisma ORM, Zod validation, prepared statements | ✅ Mitigated |
| A04: Insecure Design | Security by design, threat modeling | ✅ Mitigated |
| A05: Security Misconfiguration | Docker hardening, security headers | ✅ Mitigated |
| A06: Vulnerable Components | npm audit, Dependabot, SBOM | ✅ Mitigated |
| A07: Auth Failures | JWT best practices, refresh tokens | ✅ Mitigated |
| A08: Software Integrity | Code signing, supply chain security | ✅ Mitigated |
| A09: Logging Failures | Structured logging, correlation IDs | ✅ Mitigated |
| A10: SSRF | Input validation, URL parsing | ✅ Mitigated |

## Security Headers

```javascript
// Helmet.js configuration
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'", "https://cdn.jsdelivr.net"],
      scriptSrc: ["'self'"],
      imgSrc: ["'self'", "data:", "https:"],
      connectSrc: ["'self'", "https://api.mathplatform.com"],
      fontSrc: ["'self'", "https://cdn.jsdelivr.net"],
      objectSrc: ["'none'"],
      mediaSrc: ["'self'"],
      frameSrc: ["'none'"],
    },
  },
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true,
    preload: true
  },
  xssFilter: true,
  noSniff: true,
  referrerPolicy: { policy: "same-origin" }
}));
```

## Security Checklist

### Development

- [ ] No secrets in code
- [ ] Input validation on all endpoints
- [ ] Output encoding for dynamic content
- [ ] CSRF tokens on state-changing operations
- [ ] Secure cookie settings
- [ ] Security unit tests

### Deployment

- [ ] HTTPS only
- [ ] Security headers configured
- [ ] Rate limiting enabled
- [ ] WAF configured (if applicable)
- [ ] Container security scanning
- [ ] Secrets management
- [ ] Network policies
- [ ] Resource quotas

### Monitoring

- [ ] Security logging enabled
- [ ] Failed login attempts monitoring
- [ ] Unusual traffic patterns detection
- [ ] Dependency vulnerability scanning
- [ ] Regular security audits

## Incident Response

### Severity Levels

1. **Critical**: Active exploitation, data breach
2. **High**: Potential vulnerability, no known exploitation
3. **Medium**: Security weakness, low risk
4. **Low**: Best practice violation

### Response Procedures

1. **Detection**: Automated alerts, user reports
2. **Assessment**: Impact evaluation, scope determination
3. **Containment**: Isolate affected systems
4. **Investigation**: Root cause analysis
5. **Remediation**: Fix implementation
6. **Recovery**: Restore normal operations
7. **Lessons Learned**: Post-incident review

### Communication

- Internal team notification within 1 hour
- User notification for data breaches within 72 hours
- Public disclosure after fix deployment
- Coordination with security researchers

## Secure Coding Guidelines

### Input Validation

```typescript
// ✅ Good - Use Zod for validation
const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8).max(100)
});

// ❌ Bad - No validation
app.post('/login', (req, res) => {
  const { email, password } = req.body;
  // Process without validation
});
```

### Output Encoding

```typescript
// ✅ Good - Sanitize output
import DOMPurify from 'dompurify';
const sanitized = DOMPurify.sanitize(userInput);

// ❌ Bad - Direct output
res.send(userInput); // XSS vulnerability
```

### Authentication

```typescript
// ✅ Good - Secure JWT implementation
const token = jwt.sign(
  { userId: user.id },
  process.env.JWT_SECRET,
  { 
    algorithm: 'HS256',
    expiresIn: '15m',
    issuer: 'math-platform'
  }
);

// ❌ Bad - Weak JWT
const token = jwt.sign({ userId: user.id }, 'secret');
```

### Password Storage

```typescript
// ✅ Good - bcrypt with proper cost
const hash = await bcrypt.hash(password, 12);
const valid = await bcrypt.compare(password, hash);

// ❌ Bad - No hashing or weak hashing
const hash = md5(password); // ❌
```

## Security Tools

### Static Analysis

- **ESLint Security Plugin**: Detects security anti-patterns
- **SonarQube**: Continuous security inspection
- **Snyk**: Dependency vulnerability scanning
- **GitHub Advanced Security**: Secret scanning

### Dynamic Analysis

- **OWASP ZAP**: Web application security testing
- **Burp Suite**: Manual security testing
- **Playwright Security Tests**: Automated security tests

### Infrastructure

- **Trivy**: Container image scanning
- **Docker Bench**: Docker security audit
- **Kube-bench**: Kubernetes security checks

## Contact

- **Security Team**: security@mathplatform.com
- **Bug Bounty**: https://mathplatform.com/security
- **PGP Key**: Available on Keybase

## Updates

This security policy is reviewed quarterly and updated as needed. Last updated: March 2024.
