Files
aggios.app/1. docs/backend-deployment/SECURITY.md

11 KiB

🔒 Security & Production Guide - Aggios

🔐 Guia de Segurança

1. Secrets Management

⚠️ NUNCA commitear secrets

# ❌ ERRADO
DB_PASSWORD=minha_senha_secreta
JWT_SECRET=abc123

# ✅ CORRETO
# .env (não versionado no git)
DB_PASSWORD=${DB_PASSWORD}
JWT_SECRET=${JWT_SECRET}

# Usar HashiCorp Vault / AWS Secrets Manager / etc

Geração de Secrets Seguros

# JWT Secret (32+ caracteres aleatórios)
openssl rand -base64 32

# Senhas de Banco
openssl rand -base64 24

# Tokens de API
python3 -c "import secrets; print(secrets.token_urlsafe(32))"

2. Environment Configuration

Development (.env.local)

ENV=development
DB_SSL_MODE=disable
JWT_SECRET=local_dev_key_not_secure
CORS_ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001
MINIO_USE_SSL=false

Staging (.env.staging)

ENV=staging
DB_SSL_MODE=require
JWT_SECRET=$(openssl rand -base64 32)
CORS_ALLOWED_ORIGINS=https://staging.aggios.app
MINIO_USE_SSL=true

Production (.env.production)

ENV=production
DB_SSL_MODE=require
DB_POOL_SIZE=50
JWT_SECRET=$(openssl rand -base64 32)
JWT_EXPIRATION=2h
REFRESH_TOKEN_EXPIRATION=30d
CORS_ALLOWED_ORIGINS=https://aggios.app,https://dash.aggios.app
MINIO_USE_SSL=true
RATE_LIMIT_REQUESTS=50
RATE_LIMIT_WINDOW=60
SENTRY_DSN=https://xxx@sentry.io/project
LOG_LEVEL=info

3. JWT Security

Token Expiration Strategy

Access Token
├── Duração: 15-30 minutos
├── Escopo: operações sensíveis
└── Armazenar: memória

Refresh Token
├── Duração: 7-30 dias
├── Escopo: renovar access token
└── Armazenar: secure HTTP-only cookie

Prevent Token Abuse

// 1. Revoke tokens on logout
DELETE FROM refresh_tokens WHERE user_id = ? AND token_hash = ?

// 2. Invalidate on password change
DELETE FROM refresh_tokens WHERE user_id = ?

// 3. Track token usage
INSERT INTO token_audit (user_id, action, timestamp)

// 4. Detect suspicious activity
SELECT * FROM token_audit 
WHERE user_id = ? AND created_at > now() - interval '1 hour'
HAVING count(*) > 100

4. Password Security

Hashing com Argon2

// ✅ CORRETO: Argon2id
hash := argon2.IDKey(
    password, salt,
    time: 3,      // iterations
    memory: 65536, // 64 MB
    parallelism: 4,
    keyLength: 32
)

// ❌ EVITAR
// - MD5
// - SHA1
// - SHA256 sem salt
// - bcrypt (mais fraco que Argon2)

Password Policy

Mínimo 12 caracteres em produção
├── Incluir maiúsculas (A-Z)
├── Incluir minúsculas (a-z)
├── Incluir números (0-9)
├── Incluir símbolos (!@#$%^&*)
├── Não reutilizar últimas 5 senhas
├── Expiração: opcional (preferir MFA)
└── Histórico: manter por 1 ano

5. HTTPS/TLS

Certificados (Let's Encrypt via Traefik)

certificatesResolvers:
  letsencrypt:
    acme:
      email: admin@aggios.app
      storage: /letsencrypt/acme.json
      httpChallenge:
        entryPoint: web
      tlsChallenge: {} # fallback

Security Headers (Traefik)

middlewares:
  security-headers:
    headers:
      contentTypeNosniff: true          # X-Content-Type-Options: nosniff
      browserXssFilter: true             # X-XSS-Protection: 1; mode=block
      forceSTSHeader: true               # Strict-Transport-Security
      stsSeconds: 31536000               # 1 ano
      stsIncludeSubdomains: true
      stsPreload: true                  # HSTS preload list
      customFrameOptionsValue: SAMEORIGIN # X-Frame-Options

6. Database Security

PostgreSQL Security

-- 1. Criar usuário dedicado (sem superuser)
CREATE USER aggios WITH PASSWORD 'strong_password_here';
GRANT CONNECT ON DATABASE aggios_db TO aggios;
GRANT USAGE ON SCHEMA public TO aggios;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO aggios;

-- 2. Habilitar SSL
-- postgresql.conf
ssl = on
ssl_cert_file = '/path/to/server.crt'
ssl_key_file = '/path/to/server.key'

-- 3. Restrict connections
-- pg_hba.conf
# TYPE  DATABASE        USER            ADDRESS                 METHOD
host    aggios_db       aggios          127.0.0.1/32            md5
host    aggios_db       aggios          ::1/128                 md5
# Replicação (se houver)
host    replication     replication     192.168.1.0/24          md5

-- 4. Row Level Security (RLS)
ALTER TABLE users ENABLE ROW LEVEL SECURITY;

CREATE POLICY user_isolation ON users FOR SELECT
    USING (tenant_id = current_setting('app.current_tenant')::uuid);

-- 5. Audit Logging
CREATE TABLE audit_log (
    id BIGSERIAL PRIMARY KEY,
    table_name TEXT,
    operation TEXT,
    old_data JSONB,
    new_data JSONB,
    user_id UUID,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

SQL Injection Prevention

// ✅ CORRETO: Prepared Statements
query := "SELECT * FROM users WHERE email = ? AND tenant_id = ?"
rows, err := db.Query(query, email, tenantID)

// ❌ ERRADO: String concatenation
query := fmt.Sprintf("SELECT * FROM users WHERE email = '%s'", email)
rows, err := db.Query(query)

7. Redis Security

Redis Authentication

# docker-compose.yml
redis:
  command: redis-server --requirepass ${REDIS_PASSWORD} --appendonly yes
  environment:
    REDIS_PASSWORD: ${REDIS_PASSWORD}

Redis ACL (Redis 6+)

# Criar usuário readonly para cache
ACL SETUSER cache_user on >cache_password \
  +get +strlen +exists +type \
  ~cache:* \
  &default

8. MinIO Security

Bucket Policies

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::minioadmin:user/backend"
      },
      "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
      "Resource": "arn:aws:s3:::aggios/tenant-123/*"
    }
  ]
}

Versioning & Lifecycle

# Habilitar versionamento
mc version enable minio/aggios

# Lifecycle rules (delete old versions after 90 days)
mc ilm rule list minio/aggios

9. API Security

Rate Limiting

// Implementar com Redis
const (
    maxRequests = 100           // por window
    windowSize  = 60 * time.Second
)

// Por IP
key := fmt.Sprintf("rate_limit:%s", clientIP)
count, _ := redis.Incr(key)
redis.Expire(key, windowSize)

if count > maxRequests {
    http.Error(w, "Too many requests", http.StatusTooManyRequests)
}

CORS Configuration

// Whitelist específico
allowedOrigins := []string{
    "https://aggios.app",
    "https://dash.aggios.app",
    "https://admin.aggios.app",
}

// Validar cada request
origin := r.Header.Get("Origin")
for _, allowed := range allowedOrigins {
    if origin == allowed {
        w.Header().Set("Access-Control-Allow-Origin", origin)
        break
    }
}

Input Validation

// Sempre validar
if !emailRegex.MatchString(email) {
    return errors.New("invalid email")
}

if len(password) < 12 {
    return errors.New("password too weak")
}

if !subdomain.IsValidFormat() {
    return errors.New("invalid subdomain")
}

10. Monitoring & Alerting

Detectar Anomalias

# Prometheus alerting rules
groups:
  - name: security
    rules:
      - alert: HighFailedLogins
        expr: increase(login_failures_total[5m]) > 10
        annotations:
          summary: "High rate of failed logins"
      
      - alert: UnusualAPIActivity
        expr: rate(api_requests_total[5m]) > 1000
        annotations:
          summary: "Unusual API activity detected"
      
      - alert: DatabaseConnectionPool
        expr: pg_stat_activity_count > 45
        annotations:
          summary: "Database connection pool near limit"

Production Checklist

Infrastructure

  • DNS configurado e propagado
  • SSL/TLS certificados válidos (Let's Encrypt)
  • Firewall configurado (UFW/Security Groups)
  • SSH keys em vez de passwords
  • VPN para acesso administrativo
  • Load balancer configurado
  • CDN para assets estáticos (Cloudflare)
  • DDoS protection habilitado

Database

  • PostgreSQL em production mode
  • SSL obrigatório nas conexões
  • Backups automatizados (diários)
  • Replicação configurada (alta disponibilidade)
  • Restore testing documentado
  • Slow query logging habilitado
  • Índices otimizados
  • Vacuuming configurado

Application

  • Environment variables definidas
  • Secrets em vault (não em .env)
  • JWT_SECRET de 32+ caracteres
  • Logging estruturado habilitado
  • Error tracking (Sentry)
  • APM (Application Performance Monitoring)
  • Health checks implementados
  • Graceful shutdown

Security

  • HTTPS everywhere
  • HSTS headers
  • CSP headers configurados
  • CORS restritivo
  • Rate limiting ativo
  • Authentication forte (JWT + MFA opcional)
  • Password hashing (Argon2)
  • SQL injection prevention (prepared statements)
  • XSS protection
  • CSRF tokens

Secrets

  • JWT_SECRET rotacionado
  • DB_PASSWORD complexa (32+ chars)
  • REDIS_PASSWORD configurada
  • MINIO secrets seguros
  • API keys armazenadas em vault
  • Nenhum secret em git
  • Rotation policy documentada
  • Audit trail de acessos

Testing

  • Unit tests (>80% coverage)
  • Integration tests
  • Load tests
  • Security tests (OWASP Top 10)
  • Penetration testing
  • Disaster recovery drill

Monitoring

  • Logs centralizados (ELK)
  • Métricas (Prometheus)
  • Alertas configurados
  • Dashboard criado (Grafana)
  • Uptime monitoring (Pingdom)
  • Error tracking (Sentry)
  • Performance metrics

Documentation

  • Runbook de incidents
  • Playbook de escalação
  • Procedure de rollback
  • Disaster recovery plan
  • API documentation
  • Architecture diagrams
  • Onboarding guide

Compliance

  • GDPR compliance (se EU)
  • LGPD compliance (se Brazil)
  • Data retention policy
  • Privacy policy atualizada
  • Terms of service
  • Cookie policy
  • Audit logging enabled
  • Penetration test report

Deployment

  • CI/CD pipeline configurado
  • Blue-green deployment
  • Canary releases
  • Automated rollback
  • Version control enabled
  • Change log maintained
  • Deployment approval process
  • Zero-downtime deployments

Maintenance

  • Backup retention policy
  • Log retention policy
  • Certificate renewal automated
  • Package updates scheduled
  • Security patches applied
  • Documentation updated
  • Team training completed
  • Incident response team assigned

🆘 Incident Response

Senha Comprometida

  1. Invalidar todos os tokens JWT
  2. Forçar password reset do usuário
  3. Auditar atividade recente
  4. Notificar usuário
  5. Revisar outros usuários da organização

Ataque DDoS

  1. Ativar WAF/DDoS protection
  2. Rate limiting agressivo
  3. Escalate para CDN (Cloudflare)
  4. Análise de tráfego
  5. Documentar attack pattern

Data Breach

  1. Detectar scope do leak
  2. Notificar usuários afetados
  3. GDPR/LGPD notification
  4. Investigação forense
  5. Patch vulnerabilidade
  6. Audit trail completo

📚 Referências de Segurança


Última atualização: Dezembro 2025 Versão: 1.0.0 Responsabilidade: DevOps + Security Team