# SECURITY REMEDIATION: Exposed Production Secrets
**Date**: September 10, 2025  
**Issue**: CRITICAL SECURITY BREACH - Exposed production secrets in repository  
**Bug ID**: BUG_exposed_secrets_2025-09-10  
**Status**: REMEDIATION PLAN (NOT YET EXECUTED)

## EXECUTIVE SUMMARY
This document provides exact commands and procedures to secure exposed production secrets. **DO NOT EXECUTE THESE COMMANDS** until reviewed and approved by developer.

## IMMEDIATE ACTIONS REQUIRED

### STEP 1: BACKUP CURRENT STATE
```bash
# Create backup of current .env file
cp .env .env.backup.$(date +%Y%m%d-%H%M%S)

# Verify backup
ls -la .env*
```

### STEP 2: SECURE SECRET STORAGE IMPLEMENTATION

#### Option A: Environment Variables (Recommended for Development)
```bash
# Remove secrets from .env file
mv .env .env.old

# Create new .env with placeholders only
cat > .env << 'EOF'
# Database Configuration
DATABASE_URL=postgresql://username:password@host:port/database

# Application Security
SECRET_KEY=your-secret-key-here

# Stripe Configuration (Development)
STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key_here
STRIPE_SECRET_KEY=sk_test_your_secret_key_here  
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret_here

# Google OAuth Configuration
GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=http://localhost:5000/api/calendar/google/callback

# Redis Configuration
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/0
EOF

# Set actual values as environment variables
export DATABASE_URL="postgresql://postgres:NEW_SECURE_PASSWORD@localhost:5432/rateright"
export SECRET_KEY="NEW-SECURE-FLASK-SECRET-KEY-GENERATE-NEW-ONE"
export GOOGLE_CLIENT_SECRET="NEW-GOOGLE-CLIENT-SECRET"
# ... etc for all secrets
```

#### Option B: Secure Secret Management (Recommended for Production)
```bash
# Install python-dotenv for secure loading
pip install python-dotenv

# Create secure secrets directory
mkdir -p ~/.config/rateright/
chmod 700 ~/.config/rateright/

# Create secure secrets file
cat > ~/.config/rateright/secrets.env << 'EOF'
DATABASE_URL=postgresql://postgres:ROTATE_THIS_PASSWORD@localhost:5432/rateright
SECRET_KEY=GENERATE-NEW-SECURE-KEY-HERE
GOOGLE_CLIENT_SECRET=ROTATE-THIS-OAUTH-SECRET
EOF

# Secure the file
chmod 600 ~/.config/rateright/secrets.env

# Update application to load from secure location
# (Requires code changes - see Code Changes section)
```

### STEP 3: ROTATE ALL EXPOSED SECRETS

#### Database Password
```sql
-- Connect to PostgreSQL as superuser
psql -U postgres -d rateright

-- Rotate password
ALTER USER postgres WITH PASSWORD 'NEW-SECURE-PASSWORD-HERE';

-- Verify connection works
\q
psql -U postgres -h localhost -p 5432 -d rateright
```

#### Google OAuth Credentials
```bash
# Manual steps required:
# 1. Go to Google Cloud Console: https://console.cloud.google.com/
# 2. Navigate to APIs & Services > Credentials
# 3. Find OAuth 2.0 Client: 742547691385-cqft698go63gsjnojpmqdun6h2d6olgr.apps.googleusercontent.com
# 4. Regenerate client secret
# 5. Update application with new secret
```

#### Flask Secret Key
```python
# Generate new secure secret key
python3 -c "import secrets; print(secrets.token_urlsafe(32))"

# Example output: abc123XYZ-secure-key-goes-here
# Use this value for SECRET_KEY
```

### STEP 4: GIT REPOSITORY CLEANUP

#### Verify No Secrets in History (ALREADY VERIFIED CLEAN)
```bash
# Confirm .env never committed (already verified)
git log --all --full-history -- .env

# Search entire history for potential secret leaks
git log --all --full-history -p | grep -i "secret\|password\|key" | head -20

# Check for any .env variants
git log --all --full-history -- "*.env*"
```

#### Strengthen .gitignore (ALREADY PROPERLY CONFIGURED)
```bash
# Verify current .gitignore coverage
grep -n "\.env" .gitignore

# Add additional secret file patterns if needed
cat >> .gitignore << 'EOF'

# Additional security files
*.pem
*.key
*secret*
config/secrets/*
.env.production
.env.staging
EOF
```

### STEP 5: CODE CHANGES REQUIRED

#### Update Application Configuration
```python
# File: app/config.py or app/__init__.py
import os
from pathlib import Path

# Option 1: Load from secure directory
SECRETS_PATH = Path.home() / '.config/rateright/secrets.env'
if SECRETS_PATH.exists():
    from dotenv import load_dotenv
    load_dotenv(SECRETS_PATH)

# Option 2: Require environment variables
DATABASE_URL = os.environ.get('DATABASE_URL')
if not DATABASE_URL:
    raise ValueError("DATABASE_URL environment variable required")

SECRET_KEY = os.environ.get('SECRET_KEY') 
if not SECRET_KEY:
    raise ValueError("SECRET_KEY environment variable required")
```

### STEP 6: INSTALL SECURITY AUDIT TOOLS

#### Install pip-audit
```bash
# Install security audit tools
pip install pip-audit safety

# Run vulnerability scan
pip-audit --desc

# Run safety check  
safety check

# Add to requirements-dev.txt
echo "pip-audit>=2.0.0" >> requirements-dev.txt
echo "safety>=2.0.0" >> requirements-dev.txt
```

#### Create Security Scan Script
```bash
# Create automated security scan
cat > scripts/security-scan.sh << 'EOF'
#!/bin/bash
set -e

echo "Running security audit..."
echo "========================"

echo "1. Dependency vulnerability scan:"
pip-audit --desc

echo "2. Safety check:"  
safety check

echo "3. Secret detection:"
grep -r -i "password\|secret\|key" --exclude-dir=.git --exclude="*.md" . | grep -v "placeholder\|example\|your-key-here" | head -10

echo "Security scan complete."
EOF

chmod +x scripts/security-scan.sh
```

### STEP 7: VERIFICATION COMMANDS

#### Test Application with New Secrets
```bash
# Test database connection
python3 -c "
import os
import psycopg2
try:
    conn = psycopg2.connect(os.environ['DATABASE_URL'])
    print('Database connection: SUCCESS')
    conn.close()
except Exception as e:
    print(f'Database connection: FAILED - {e}')
"

# Test Flask application startup
python3 -c "
import os
os.environ.setdefault('FLASK_APP', 'app')
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
print('Flask configuration: SUCCESS')
"
```

#### Verify Secret Protection
```bash
# Confirm no secrets in working directory
find . -name "*.py" -o -name "*.json" -o -name "*.yaml" | xargs grep -l "password\|secret" | grep -v "placeholder"

# Verify .env contains no real secrets
cat .env | grep -E "(password|secret|key)" | grep -v "placeholder\|your-.*-here"
```

## ROLLBACK PROCEDURES

### Emergency Rollback
```bash
# If issues occur, restore original .env
cp .env.backup.$(ls .env.backup.* | tail -1) .env

# Restart application
# (Application-specific restart commands here)
```

### Database Rollback  
```sql
-- Only if database password rotation fails
ALTER USER postgres WITH PASSWORD 'wd2SZgQ4qfFZo4Z';
```

## POST-REMEDIATION CHECKLIST

- [ ] All secrets rotated and application tested
- [ ] New secrets stored securely (not in plaintext files)
- [ ] Git repository confirmed clean of secrets
- [ ] Security audit tools installed and working
- [ ] Application successfully runs with new configuration
- [ ] Documentation updated with new security procedures
- [ ] Team notified of new secret management process

## DEPLOYMENT INSTRUCTIONS

### Development Environment
```bash
# Load secrets from secure location
export $(grep -v '^#' ~/.config/rateright/secrets.env | xargs)

# Start application
python3 app.py
```

### Production Environment  
```bash
# Use production secret management system
# Examples: AWS Secrets Manager, Azure Key Vault, HashiCorp Vault
# Implementation depends on deployment platform
```

## SECURITY MONITORING

### Ongoing Security Measures
```bash
# Add to CI/CD pipeline
pip-audit --desc
safety check

# Weekly security scan
crontab -e
# Add: 0 9 * * 1 cd /path/to/project && ./scripts/security-scan.sh
```

## ESTIMATED EXECUTION TIME
- **Secret rotation**: 30 minutes
- **Code changes**: 60 minutes  
- **Testing**: 30 minutes
- **Documentation**: 15 minutes
- **Total**: ~2.5 hours

## RISK ASSESSMENT
- **Execution Risk**: LOW (no git history rewriting needed)
- **Service Downtime**: MINIMAL (~5 minutes during secret rotation)
- **Data Loss Risk**: NONE (backups in place)

## DEPENDENCIES
- PostgreSQL admin access
- Google Cloud Console access  
- Application deployment permissions
- pip package installation rights

---
**⚠️ CRITICAL WARNING**: DO NOT execute these commands without review and approval. Coordinate secret rotation with all team members to prevent service disruption.
