Skip to content

[M0][Epic 0.4] Create comprehensive .env.example templates with security annotations #69

@POWDER-RANGER

Description

@POWDER-RANGER

Problem

No .env.example files exist in the repository, making it impossible for contributors to know which environment variables are required. This blocks local development setup and creates security risks when developers hardcode credentials or use insecure defaults.

Tasks

Backend Environment Configuration

  • Create backend/.env.example with all required variables
  • Document each variable with inline comments explaining purpose
  • Add security annotations (which values are sensitive)
  • Provide safe development defaults where appropriate
  • Add validation rules (format, allowed values, constraints)

Frontend Environment Configuration

  • Create frontend/.env.example with runtime configuration
  • Document public vs private environment variables (VITE_ prefix)
  • Add API endpoint configuration examples
  • Include feature flag examples

ML Service Environment Configuration

  • Create ml/.env.example with Python-specific settings
  • Document model paths and API keys (OpenAI, HuggingFace)
  • Add GPU/CPU configuration options
  • Include training vs inference mode settings

Root Environment Configuration

  • Create root .env.example for Docker Compose variables
  • Add database credentials placeholders
  • Include port mappings and network configuration
  • Document production vs development differences

Environment Variable Validation

  • Add dotenv-safe or similar validation library to backend
  • Create schema file defining required vs optional variables
  • Add startup validation that fails fast if required vars missing
  • Log warnings for missing optional variables with fallback values

Documentation

  • Update SETUP.md with environment configuration section
  • Add environment variable reference table to docs/
  • Document environment-specific overrides (.env.local, .env.production)
  • Create troubleshooting guide for common configuration errors

Acceptance Criteria

  • .env.example files exist in backend/, frontend/, ml/, and root directory
  • ✅ Every variable documented with purpose, type, and example value
  • ✅ Developer can copy .env.example.env and run application immediately
  • ✅ No hardcoded secrets or credentials in example files
  • ✅ Startup validation script catches missing required variables before application starts
  • ✅ SETUP.md includes step-by-step environment configuration instructions

Example .env Templates

backend/.env.example

# Database Configuration
# Required: PostgreSQL connection string
# Format: postgresql://user:password@host:port/database
DATABASE_URL=postgresql://civwatch:devpassword@localhost:5432/civwatch

# Redis Configuration
# Required: Redis connection URL for caching and job queues
REDIS_URL=redis://localhost:6379

# Authentication
# Required: Secret key for JWT signing (min 32 characters)
# SECURITY: Generate unique key for each environment
# Command: openssl rand -base64 32
JWT_SECRET=CHANGE_ME_IN_PRODUCTION_USE_OPENSSL_RAND

# Optional: JWT expiration time (default: 24h)
JWT_EXPIRATION=24h

# API Keys
# Required for ML features: OpenAI API key
# Get key from: https://platform.openai.com/api-keys
OPENAI_API_KEY=sk-...

# Optional: Rate limiting configuration
RATE_LIMIT_WINDOW_MS=60000
RATE_LIMIT_MAX_REQUESTS=100

# Server Configuration
# Port for backend API (default: 3000)
PORT=3000

# Environment: development | staging | production
NODE_ENV=development

# Logging
# Log level: error | warn | info | debug
LOG_LEVEL=info

# External Services
# Optional: Webhook notification URL for alerts
WEBHOOK_URL=https://your-webhook-endpoint.com/notify

# Optional: Webhook signature secret for HMAC validation
WEBHOOK_SECRET=your-webhook-secret-here

# CORS Configuration
# Comma-separated list of allowed origins
# Use * for development only, never in production
CORS_ORIGINS=http://localhost:5173,http://localhost:3000

# ML Service URL
# Internal URL for ML service communication
ML_SERVICE_URL=http://localhost:5000

frontend/.env.example

# API Configuration
# Required: Backend API base URL
VITE_API_BASE_URL=http://localhost:3000/api

# Optional: WebSocket URL for real-time updates
VITE_WS_URL=ws://localhost:3000

# Feature Flags
# Toggle features in development
VITE_ENABLE_ANALYTICS=true
VITE_ENABLE_DEBUG_PANEL=false
VITE_ENABLE_EXPERIMENTAL_FEATURES=false

# Monitoring
# Optional: Sentry DSN for error tracking
VITE_SENTRY_DSN=

# Optional: Google Analytics tracking ID
VITE_GA_TRACKING_ID=

# Build Configuration
# Port for Vite dev server (default: 5173)
VITE_PORT=5173

ml/.env.example

# Python Environment
PYTHONUNBUFFERED=1

# Model Configuration
# Path to pre-trained models directory
MODEL_DIR=./models

# Model Selection
# sentiment: textblob | transformers-distilbert | openai-gpt
SENTIMENT_MODEL=textblob

# Optional: HuggingFace API token for downloading models
HUGGINGFACE_TOKEN=

# OpenAI Configuration (if using GPT models)
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4

# GPU Configuration
# Set to 'true' to use GPU if available
USE_GPU=false

# CUDA device ID (for multi-GPU systems)
CUDA_VISIBLE_DEVICES=0

# Server Configuration
FASTAPI_PORT=5000
FASTAPI_HOST=0.0.0.0

# Request Timeout
# Maximum seconds for ML inference
INFERENCE_TIMEOUT=30

# Batch Processing
# Maximum batch size for parallel inference
MAX_BATCH_SIZE=32

# Logging
LOG_LEVEL=INFO

docker-compose.env.example (Root)

# Database Credentials
# SECURITY: Change in production
POSTGRES_DB=civwatch
POSTGRES_USER=civwatch
POSTGRES_PASSWORD=devpassword123

# Port Mappings
# Adjust if ports conflict with existing services
FRONTEND_PORT=5173
BACKEND_PORT=3000
ML_SERVICE_PORT=5000
POSTGRES_PORT=5432
REDIS_PORT=6379

# Volume Paths
# Local paths for persistent data
DATA_DIR=./data

# Container Resource Limits
BACKEND_MEMORY_LIMIT=1g
ML_SERVICE_MEMORY_LIMIT=2g
POSTGRES_MEMORY_LIMIT=512m

Environment Variable Validation Implementation

Backend Validation (TypeScript)

// backend/src/config/env.ts
import dotenv from 'dotenv';
import { z } from 'zod';

dotenv.config();

const envSchema = z.object({
  DATABASE_URL: z.string().url(),
  REDIS_URL: z.string().url(),
  JWT_SECRET: z.string().min(32),
  JWT_EXPIRATION: z.string().default('24h'),
  OPENAI_API_KEY: z.string().startsWith('sk-').optional(),
  PORT: z.string().transform(Number).default('3000'),
  NODE_ENV: z.enum(['development', 'staging', 'production']).default('development'),
  LOG_LEVEL: z.enum(['error', 'warn', 'info', 'debug']).default('info'),
  CORS_ORIGINS: z.string().transform(s => s.split(',')),
  ML_SERVICE_URL: z.string().url().default('http://localhost:5000'),
});

export const env = envSchema.parse(process.env);

// Log validation success
console.log('✅ Environment variables validated successfully');

Startup Validation Script

#!/bin/bash
# scripts/validate-env.sh

set -e

echo "🔍 Validating environment configuration..."

# Check if .env files exist
for service in backend frontend ml; do
  if [ ! -f "$service/.env" ]; then
    echo "❌ Missing $service/.env file"
    echo "💡 Copy from template: cp $service/.env.example $service/.env"
    exit 1
  fi
done

# Run environment validation
cd backend && npm run validate:env
cd ../ml && python -m scripts.validate_env

echo "✅ All environment configurations valid"

Security Best Practices

Included in .env.example Comments

  1. Never commit .env files - Add to .gitignore
  2. Rotate secrets regularly - Document rotation procedures
  3. Use different credentials per environment - Never reuse production credentials in development
  4. Minimum secret length requirements - JWT secret minimum 32 characters
  5. HTTPS in production - Document SSL/TLS requirements
  6. Webhook signature verification - Require HMAC signatures for webhook endpoints

Dependencies

Blocks: #55 (package.json scripts need env validation), #57 (database schema needs DATABASE_URL)
Related: #54 (Docker Compose needs environment variables), #68 (security hardening needs proper secrets management)

Estimated Effort

Time: 3-4 hours
Complexity: Low-Medium
Skills: Environment configuration, security best practices, documentation

Definition of Done

  • All tasks checked off
  • All acceptance criteria met
  • Example files reviewed for security issues
  • Documentation merged to main branch
  • Fresh contributor successfully configured environment using only .env.example files

Priority: P0 - Blocker
Labels: infrastructure, configuration, security, M0, P0, documentation, good-first-issue

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions