Skip to main content

Security & Production Deployment Guide

Overview

CODITECT Dev Context v2.0 is a multi-tenant SaaS platform designed for secure deployment on Google Kubernetes Engine (GKE). This document outlines the security architecture, threat mitigation strategies, and production deployment best practices.

Target Deployment: Google Cloud Platform (GKE) Security Model: Defense in depth with multiple isolation layers Compliance: GDPR-ready, SOC 2 Type II preparedness


Security Architecture

1. Multi-Tenant Isolation

Row-Level Security (RLS)

Implementation: PostgreSQL Row-Level Security enforced via middleware

-- Example RLS policy
CREATE POLICY tenant_isolation ON users
FOR ALL TO authenticated_users
USING (tenant_id = current_setting('app.current_tenant_id')::uuid);

How it works:

  1. User authenticates → JWT contains tenant_id
  2. Middleware extracts tenant_id from JWT
  3. Sets PostgreSQL session variable: SET app.current_tenant_id = '<uuid>'
  4. All queries automatically filtered by tenant_id

Protection against:

  • ✅ Cross-tenant data access
  • ✅ SQL injection attempts crossing tenant boundaries
  • ✅ Application-level bugs leaking data between tenants

Django ORM Query Filtering

Additional layer: All Django querysets filtered by request.tenant_id

# Example: Automatic tenant filtering
class ProjectViewSet(viewsets.ModelViewSet):
def get_queryset(self):
return Project.objects.filter(tenant_id=self.request.tenant_id)

Why both RLS + Django filtering?

  • Django filtering: First line of defense (application layer)
  • RLS: Second line of defense (database layer)
  • Defense in depth: Even if Django code has bug, database prevents cross-tenant access

2. Authentication & Authorization

JWT-Based Authentication

Token Strategy:

  • Access Token: 1 hour lifetime (short-lived, reduce exposure)
  • Refresh Token: 7 days lifetime (rotate on use)
  • Algorithm: HS256 (HMAC with SHA-256)
  • Rotation: Refresh tokens blacklisted after rotation

Security Features:

  • ✅ Token expiration enforcement
  • ✅ Blacklist for revoked tokens (Redis-backed)
  • ✅ Automatic token refresh
  • ✅ Secure HTTP-only cookies (optional)

Role-Based Access Control (RBAC)

Granular Permissions:

Permission Code        Resource    Action
─────────────────────────────────────────
project.create project create
task.update task update
session.delete session delete
user.manage user *

Default Roles:

  • Owner: Full access (create/delete tenant, billing)
  • Admin: Manage users, teams, projects
  • Developer: Create/edit projects, tasks, sessions
  • Viewer: Read-only access

Permission Checking:

from rest_framework.permissions import BasePermission

class HasProjectPermission(BasePermission):
def has_permission(self, request, view):
return request.user.has_perm('project.create')

3. Data Protection

Encryption at Rest

Database: PostgreSQL with transparent data encryption (GCP Cloud SQL)

  • All data encrypted with AES-256
  • Automatic key rotation via Google Cloud KMS
  • Encrypted backups

File Storage: Google Cloud Storage with server-side encryption

  • All media files encrypted at rest
  • Customer-managed encryption keys (CMEK) option available
  • Signed URLs for temporary access (1-hour expiry)

Encryption in Transit

TLS 1.3: All connections encrypted

  • HTTPS enforced (HSTS headers)
  • Certificate management via Google-managed certificates
  • TLS termination at GKE load balancer

Database Connections:

  • Cloud SQL Proxy for encrypted connections
  • No plain-text database passwords (Secret Manager)

Secrets Management

Google Cloud Secret Manager:

# Store secrets
gcloud secrets create django-secret-key --data-file=secret.txt

# Access in application
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
secret = client.access_secret_version(name="projects/.../secrets/django-secret-key/versions/latest")

Never in code:

  • ❌ No hardcoded API keys
  • ❌ No credentials in environment variables (use Secret Manager)
  • ❌ No secrets in container images

4. Attack Surface Reduction

Minimal Production Dependencies

Full stack: 50+ dependencies (includes dev/test tools) Production: 27 dependencies (security-critical only)

Removed from production:

# Development/Testing (NOT in production):
- pytest, pytest-django
- black, flake8, mypy
- ipython, ipdb
- django-debug-toolbar

# Data Science (NOT needed for core API):
- pandas, numpy
- faker (test data generation)

Why minimal dependencies?

  • Fewer packages = smaller attack surface
  • Each dependency has transitive dependencies (recursive risk)
  • Vulnerabilities in unused packages still exploitable

Production requirements:

pip install -r requirements-production.txt  # 27 packages
# vs
pip install -r requirements.txt # 50+ packages

Dependency Security Scanning

Automated scanning:

# .github/workflows/security-scan.yml
- name: Dependency scanning
run: |
pip install safety
safety check --file requirements-production.txt

GitHub Dependabot:

  • Automatic security updates
  • Daily vulnerability scanning
  • Auto-PR for critical vulnerabilities

5. Input Validation & Sanitization

Django REST Framework Serializers

Automatic validation:

from rest_framework import serializers

class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ['name', 'description', 'status']
extra_kwargs = {
'name': {'max_length': 255, 'required': True},
'status': {'choices': ['active', 'archived']}
}

Protection against:

  • ✅ SQL injection (ORM parameterization)
  • ✅ XSS (output escaping)
  • ✅ CSRF (token validation)
  • ✅ Mass assignment (explicit field whitelisting)

Content Security Policy (CSP)

# settings.py
CSP_DEFAULT_SRC = ["'self'"]
CSP_SCRIPT_SRC = ["'self'", "'unsafe-inline'"] # Minimize inline scripts
CSP_STYLE_SRC = ["'self'", "'unsafe-inline'"]
CSP_IMG_SRC = ["'self'", "data:", "https:"]
CSP_CONNECT_SRC = ["'self'", "https://api.coditect.ai"]

Rate Limiting

DRF Throttling:

REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/hour', # Unauthenticated requests
'user': '1000/hour' # Authenticated requests
}
}

GCP Cloud Armor (DDoS Protection):

  • Layer 7 DDoS protection
  • IP-based rate limiting
  • Geographic restrictions (if needed)

6. Monitoring & Incident Response

Logging Strategy

Structured JSON Logging:

# All logs in JSON format for analysis
LOGGING = {
'formatters': {
'json': {
'()': 'pythonjsonlogger.jsonlogger.JsonFormatter',
'format': '%(asctime)s %(name)s %(levelname)s %(message)s',
}
}
}

Log Aggregation:

  • Google Cloud Logging (centralized)
  • Log retention: 30 days (compliance)
  • Automated alerts for critical errors

Error Tracking

Sentry Integration:

  • Real-time error notifications
  • Stack traces with context
  • Performance monitoring (APM)
  • User impact tracking
# settings.py
import sentry_sdk

sentry_sdk.init(
dsn=os.environ.get('SENTRY_DSN'),
traces_sample_rate=0.1, # 10% of transactions
send_default_pii=False # GDPR compliance
)

Security Incident Response

Automated Alerts:

  1. Failed authentication attempts (>5/min)
  2. Unauthorized access attempts
  3. Database query timeouts (potential SQL injection)
  4. Abnormal API usage patterns

Response Workflow:

  1. Alert → Slack/PagerDuty
  2. Automated IP blocking (Cloud Armor)
  3. Manual investigation via logs
  4. Incident report (post-mortem)

7. Database Security

Connection Security

Cloud SQL Proxy:

# Encrypted connection via Unix socket
cloud_sql_proxy -instances=PROJECT:REGION:INSTANCE=tcp:5432

Connection Pooling:

DATABASES = {
'default': {
'CONN_MAX_AGE': 600, # 10 minutes
'CONN_HEALTH_CHECKS': True, # Automatic health checks
}
}

Backup Strategy

Automated backups:

  • Daily automated backups (Cloud SQL)
  • 7-day retention (configurable)
  • Point-in-time recovery (last 7 days)
  • Encrypted backups (AES-256)

Disaster Recovery:

  • Cross-region replication (optional)
  • RTO (Recovery Time Objective): 1 hour
  • RPO (Recovery Point Objective): 15 minutes

SQL Injection Prevention

ORM Parameterization:

# SAFE: Django ORM uses parameterized queries
User.objects.filter(email=user_input) # ✅ Safe

# UNSAFE: Raw SQL with string interpolation
User.objects.raw(f"SELECT * FROM users WHERE email = '{user_input}'") # ❌ Vulnerable

Never use:

  • raw() with user input
  • extra() with user input
  • String concatenation in queries

8. Container & Kubernetes Security

Container Hardening

Minimal base image:

# Use distroless for minimal attack surface
FROM gcr.io/distroless/python3:nonroot
# No shell, no package manager, no unnecessary binaries

Non-root user:

USER nonroot:nonroot
# Never run as root in containers

Read-only filesystem:

# kubernetes deployment
securityContext:
readOnlyRootFilesystem: true
runAsNonRoot: true
runAsUser: 65534 # nobody

Kubernetes Security

Network Policies:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-network-policy
spec:
podSelector:
matchLabels:
app: coditect-backend
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
app: nginx-ingress
ports:
- protocol: TCP
port: 8000

Resource Limits:

resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"

Pod Security Standards:

  • Restricted (default)
  • No privileged containers
  • No host network/PID/IPC access

Production Deployment Checklist

Pre-Deployment

  • Secrets configured in Google Cloud Secret Manager
  • Database migrations tested in staging
  • Static files collected and uploaded to GCS
  • Environment variables set in K8s ConfigMap/Secrets
  • TLS certificates provisioned (Google-managed)
  • Health check endpoints tested (/health/)
  • Monitoring configured (Sentry, GCP Logging)
  • Backup strategy verified
  • Disaster recovery plan documented
  • Security scan passed (no critical vulnerabilities)

Deployment

# 1. Build container image
docker build -t gcr.io/PROJECT/coditect-backend:v2.0.0 -f dockerfile.production .

# 2. Push to GCR
docker push gcr.io/PROJECT/coditect-backend:v2.0.0

# 3. Deploy to GKE
kubectl apply -f k8s/production/

# 4. Run migrations
kubectl exec -it deployment/coditect-backend -- python manage.py migrate

# 5. Verify deployment
kubectl rollout status deployment/coditect-backend

# 6. Test endpoints
curl https://api.coditect.ai/health/

Post-Deployment

  • Health checks passing
  • Logs flowing to Cloud Logging
  • Metrics visible in GCP Monitoring
  • Errors tracked in Sentry
  • Database connections stable
  • API endpoints responding correctly
  • Authentication working
  • Multi-tenant isolation verified
  • Load testing passed
  • Rollback plan ready

Security Best Practices Summary

✅ DO

  1. Use requirements-production.txt for production deployments
  2. Enable HTTPS (HSTS, secure cookies)
  3. Rotate secrets regularly (quarterly minimum)
  4. Monitor logs for suspicious activity
  5. Update dependencies weekly (security patches)
  6. Use Secret Manager for all credentials
  7. Enforce strong passwords (Argon2 hashing)
  8. Implement rate limiting on all endpoints
  9. Validate all inputs via DRF serializers
  10. Run security scans before every deployment

❌ DON'T

  1. Don't use requirements.txt in production (includes dev tools)
  2. Don't hardcode secrets in code/configs
  3. Don't disable CSRF protection
  4. Don't run as root in containers
  5. Don't use DEBUG=True in production
  6. Don't store passwords in plain text (ever)
  7. Don't expose admin panel publicly
  8. Don't ignore Dependabot alerts
  9. Don't skip migrations in production
  10. Don't deploy without testing

Vulnerability Management

Monitoring

  • GitHub Dependabot: Daily scans
  • Safety CLI: safety check in CI/CD
  • Snyk: Container image scanning

Response SLA

SeverityResponse TimeFix Target
Critical4 hours24 hours
High24 hours7 days
Moderate7 days30 days
Low30 daysNext release

Patching Strategy

  1. Automated PRs from Dependabot
  2. Review & test in staging
  3. Deploy to production during maintenance window
  4. Monitor for regressions
  5. Rollback if issues detected

Compliance

GDPR Readiness

  • ✅ Data encryption (rest + transit)
  • ✅ Right to erasure (user deletion API)
  • ✅ Data portability (export API)
  • ✅ Consent management (opt-in/out)
  • ✅ Privacy by design (minimal data collection)

SOC 2 Type II Preparation

  • ✅ Access controls (RBAC)
  • ✅ Audit logging (all actions)
  • ✅ Change management (git-based)
  • ✅ Incident response (documented)
  • ✅ Vendor management (GCP SLA)

Support

Security Issues: security@coditect.ai Documentation: https://docs.coditect.ai/security Status Page: https://status.coditect.ai


Version: 2.0.0 Last Updated: 2025-11-26 Next Review: 2026-02-26