# Security Policy

## Overview

WHOOSH implements enterprise-grade security controls to protect against common web application vulnerabilities and ensure safe operation in production environments. This document outlines our security implementation, best practices, and procedures.

## 🔐 Security Implementation

### Authentication & Authorization

**JWT Authentication**
- Role-based access control (admin/user roles)
- Configurable token expiration (default: 24 hours)
- Support for file-based and environment-based secrets
- Secure token validation with comprehensive error handling

**Service Token Authentication**
- Internal service-to-service authentication
- Scoped permissions for automated systems
- Support for multiple service tokens
- Configurable token management

**Protected Endpoints**
All administrative endpoints require proper authentication:
- Council management (`/api/v1/councils/*/artifacts`)
- Repository operations (`/api/v1/repositories/*`)
- Team management (`/api/v1/teams/*`)
- Task ingestion (`/api/v1/tasks/ingest`)
- Project operations (`/api/v1/projects/*`)

### Input Validation & Sanitization

**Comprehensive Input Validation**
- Regex-based validation for all input types
- Request body size limits (1MB default, 10MB for webhooks)
- UUID validation for all identifiers
- Safe character restrictions for names and titles

**Validation Rules**
```go
Project Names:    ^[a-zA-Z0-9\s\-_]+$           (max 100 chars)
Git URLs:         Proper URL format validation
Task Titles:      Safe characters only           (max 200 chars)
Agent IDs:        ^[a-zA-Z0-9\-]+$             (max 50 chars)
UUIDs:           RFC 4122 compliant format
```

**Injection Prevention**
- SQL injection prevention through parameterized queries
- XSS prevention through input sanitization
- Command injection prevention through input validation
- Path traversal prevention through path sanitization

### CORS Configuration

**Production-Safe CORS**
- No wildcard origins in production
- Configurable allowed origins via environment variables
- Support for file-based origin configuration
- Restricted allowed headers and methods

**Configuration Example**
```bash
# Production CORS configuration
WHOOSH_CORS_ALLOWED_ORIGINS=https://app.company.com,https://admin.company.com
WHOOSH_CORS_ALLOWED_METHODS=GET,POST,PUT,DELETE,OPTIONS
WHOOSH_CORS_ALLOWED_HEADERS=Authorization,Content-Type,X-Requested-With
WHOOSH_CORS_ALLOW_CREDENTIALS=true
```

### Rate Limiting

**Per-IP Rate Limiting**
- Default: 100 requests per minute per IP address
- Configurable limits and time windows
- Automatic cleanup to prevent memory leaks
- Support for proxy headers (X-Forwarded-For, X-Real-IP)

**Configuration**
```bash
WHOOSH_RATE_LIMIT_ENABLED=true
WHOOSH_RATE_LIMIT_REQUESTS=100        # Requests per window
WHOOSH_RATE_LIMIT_WINDOW=60s          # Rate limiting window
WHOOSH_RATE_LIMIT_CLEANUP_INTERVAL=300s  # Cleanup frequency
```

### Security Headers

**HTTP Security Headers**
```
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Referrer-Policy: strict-origin-when-cross-origin
```

### Webhook Security

**Gitea Webhook Protection**
- HMAC SHA-256 signature validation
- Timing-safe signature comparison using `hmac.Equal`
- Request body size limits (10MB maximum)
- Content-Type header validation
- Comprehensive attack attempt logging

**Configuration**
```bash
WHOOSH_WEBHOOK_SECRET_FILE=/run/secrets/webhook_secret
WHOOSH_MAX_WEBHOOK_SIZE=10485760  # 10MB
```

## 🛡️ Security Best Practices

### Production Deployment

**Secret Management**
```bash
# Use file-based secrets in production
WHOOSH_JWT_SECRET_FILE=/run/secrets/jwt_secret
WHOOSH_GITEA_TOKEN_FILE=/run/secrets/gitea_token
WHOOSH_WEBHOOK_SECRET_FILE=/run/secrets/webhook_secret

# Docker Swarm secrets example
echo "strong-jwt-secret-32-chars-min" | docker secret create whoosh_jwt_secret -
```

**Database Security**
```bash
# Use SSL/TLS for database connections
WHOOSH_DATABASE_URL=postgres://user:pass@host/db?sslmode=require

# Connection pool limits
WHOOSH_DB_MAX_OPEN_CONNS=25
WHOOSH_DB_MAX_IDLE_CONNS=10
WHOOSH_DB_CONN_MAX_LIFETIME=300s
```

**TLS Configuration**
```bash
# Enable TLS in production
WHOOSH_TLS_ENABLED=true
WHOOSH_TLS_CERT_FILE=/path/to/cert.pem
WHOOSH_TLS_KEY_FILE=/path/to/key.pem
WHOOSH_TLS_MIN_VERSION=1.2
```

### Security Monitoring

**Logging & Monitoring**
- Structured logging with security event correlation
- Failed authentication attempt monitoring
- Rate limit violation alerting
- Administrative action audit logging

**Health & Security Endpoints**
- `/health` - Basic health check (unauthenticated)
- `/admin/health/details` - Detailed system status (authenticated)
- `/metrics` - Prometheus metrics (unauthenticated)

### Access Control

**Role-Based Permissions**
- **Admin Role**: Full system access, administrative operations
- **User Role**: Read-only access to public endpoints
- **Service Tokens**: Scoped access for internal services

**Endpoint Protection Matrix**
| Endpoint Category | Authentication | Authorization |
|-------------------|---------------|---------------|
| Public Health     | None          | None          |
| Public APIs       | JWT           | User/Admin    |
| Admin Operations  | JWT           | Admin Only    |
| Internal Services | Service Token | Scoped Access |
| Webhooks          | HMAC          | Signature     |

## 🔍 Security Testing

### Vulnerability Assessment

**Regular Security Audits**
- OWASP Top 10 compliance verification
- Dependency vulnerability scanning
- Static code analysis with security focus
- Penetration testing of critical endpoints

**Automated Security Testing**
```bash
# Static security analysis
go run honnef.co/go/tools/cmd/staticcheck ./...

# Dependency vulnerability scanning
go mod tidy && go list -json -deps | audit

# Security linting
golangci-lint run --enable gosec
```

### Security Validation

**Authentication Testing**
- Token validation bypass attempts
- Role escalation prevention verification
- Session management security testing
- Service token scope validation

**Input Validation Testing**
- SQL injection attempt testing
- XSS payload validation testing
- Command injection prevention testing
- File upload security testing (if applicable)

## 📊 Compliance & Standards

### Industry Standards Compliance

**OWASP Top 10 2021 Protection**
- ✅ **A01: Broken Access Control** - Comprehensive authentication/authorization
- ✅ **A02: Cryptographic Failures** - Strong JWT signing, HTTPS enforcement
- ✅ **A03: Injection** - Parameterized queries, input validation
- ✅ **A04: Insecure Design** - Security-by-design architecture
- ✅ **A05: Security Misconfiguration** - Secure defaults, configuration validation
- ✅ **A06: Vulnerable Components** - Regular dependency updates
- ✅ **A07: Identity & Authentication** - Robust authentication framework
- ✅ **A08: Software & Data Integrity** - Webhook signature validation
- ✅ **A09: Logging & Monitoring** - Comprehensive security logging
- ✅ **A10: Server-Side Request Forgery** - Input validation prevents SSRF

**Enterprise Compliance**
- **SOC 2 Type II**: Access controls, monitoring, data protection
- **ISO 27001**: Information security management system
- **NIST Cybersecurity Framework**: Identify, Protect, Detect functions

## 🚨 Incident Response

### Security Incident Handling

**Immediate Response**
1. **Detection**: Monitor logs for security events
2. **Assessment**: Evaluate impact and scope
3. **Containment**: Implement immediate protective measures
4. **Investigation**: Analyze attack vectors and impact
5. **Recovery**: Restore secure operations
6. **Learning**: Update security measures based on findings

**Contact Information**
For security issues, please follow our responsible disclosure policy:
1. Do not disclose security issues publicly
2. Contact the development team privately
3. Provide detailed reproduction steps
4. Allow reasonable time for fix development

## 🔧 Configuration Reference

### Security Environment Variables

```bash
# Authentication
WHOOSH_JWT_SECRET=your-strong-secret-here
WHOOSH_JWT_SECRET_FILE=/run/secrets/jwt_secret
WHOOSH_JWT_EXPIRATION=24h
WHOOSH_JWT_ISSUER=whoosh
WHOOSH_JWT_ALGORITHM=HS256

# Service Tokens
WHOOSH_SERVICE_TOKEN=your-service-token
WHOOSH_SERVICE_TOKEN_FILE=/run/secrets/service_token
WHOOSH_SERVICE_TOKEN_HEADER=X-Service-Token

# CORS Security
WHOOSH_CORS_ALLOWED_ORIGINS=https://app.company.com
WHOOSH_CORS_ALLOWED_ORIGINS_FILE=/run/secrets/allowed_origins
WHOOSH_CORS_ALLOWED_METHODS=GET,POST,PUT,DELETE,OPTIONS
WHOOSH_CORS_ALLOWED_HEADERS=Authorization,Content-Type
WHOOSH_CORS_ALLOW_CREDENTIALS=true

# Rate Limiting
WHOOSH_RATE_LIMIT_ENABLED=true
WHOOSH_RATE_LIMIT_REQUESTS=100
WHOOSH_RATE_LIMIT_WINDOW=60s
WHOOSH_RATE_LIMIT_CLEANUP_INTERVAL=300s

# Input Validation
WHOOSH_MAX_REQUEST_SIZE=1048576    # 1MB
WHOOSH_MAX_WEBHOOK_SIZE=10485760   # 10MB
WHOOSH_VALIDATION_STRICT=true

# TLS Configuration
WHOOSH_TLS_ENABLED=false           # Set to true in production
WHOOSH_TLS_CERT_FILE=/path/to/cert.pem
WHOOSH_TLS_KEY_FILE=/path/to/key.pem
WHOOSH_TLS_MIN_VERSION=1.2
```

### Production Security Checklist

**Deployment Security**
- [ ] All secrets configured via files or secure environment variables
- [ ] CORS origins restricted to specific domains (no wildcards)
- [ ] TLS enabled with valid certificates
- [ ] Rate limiting configured and enabled
- [ ] Input validation strict mode enabled
- [ ] Security headers properly configured
- [ ] Database connections using SSL/TLS
- [ ] Webhook secrets properly configured
- [ ] Monitoring and alerting configured
- [ ] Security audit logging enabled

**Operational Security**
- [ ] Regular security updates applied
- [ ] Access logs monitored
- [ ] Failed authentication attempts tracked
- [ ] Rate limit violations monitored
- [ ] Administrative actions audited
- [ ] Backup security validated
- [ ] Incident response procedures documented
- [ ] Security training completed for operators

## 📚 Related Documentation

- **[Security Audit Report](SECURITY_AUDIT_REPORT.md)** - Detailed security audit findings and remediation
- **[Configuration Guide](docs/CONFIGURATION.md)** - Complete configuration documentation
- **[API Specification](docs/API_SPECIFICATION.md)** - API security details and authentication
- **[Deployment Guide](docs/DEPLOYMENT.md)** - Secure production deployment procedures

---

**Security Status**: **Production Ready** ✅  
**Last Security Audit**: 2025-09-12  
**Compliance Level**: Enterprise-Grade  

For security questions or to report security vulnerabilities, please refer to our incident response procedures above.