From d010ae9b74df7e6b314d99bb51409b330b7b2cca Mon Sep 17 00:00:00 2001 From: Adolfo Delorenzo Date: Tue, 3 Jun 2025 00:06:18 -0600 Subject: [PATCH] Remove hardcoded API key - CRITICAL SECURITY FIX MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove hardcoded TTS API key from app.py (major security vulnerability) - Add python-dotenv support for secure environment variable management - Create .env.example with configuration template - Add comprehensive SECURITY.md documentation - Update README with security configuration instructions - Add warning when TTS_API_KEY is not configured - Enhance .gitignore to prevent accidental commits of .env files BREAKING CHANGE: TTS_API_KEY must now be set via environment variable or .env file Security measures: - API keys must be provided via environment variables - Added dotenv support for local development - Clear documentation on secure deployment practices - Multiple .env file patterns in .gitignore 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .env.example | 22 ++++++++ .gitignore | 3 ++ README.md | 23 +++++++-- SECURITY.md | 129 +++++++++++++++++++++++++++++++++++++++++++++++ app.py | 10 +++- requirements.txt | 1 + 6 files changed, 183 insertions(+), 5 deletions(-) create mode 100644 .env.example create mode 100644 SECURITY.md diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..3e91c8a --- /dev/null +++ b/.env.example @@ -0,0 +1,22 @@ +# Example environment configuration for Talk2Me +# Copy this file to .env and update with your actual values + +# Flask Configuration +SECRET_KEY=your-secret-key-here-change-this + +# Upload Configuration +UPLOAD_FOLDER=/path/to/secure/upload/folder + +# TTS Server Configuration +TTS_SERVER_URL=http://localhost:5050/v1/audio/speech +TTS_API_KEY=your-tts-api-key-here + +# CORS Configuration (for production) +CORS_ORIGINS=https://yourdomain.com,https://app.yourdomain.com +ADMIN_CORS_ORIGINS=https://admin.yourdomain.com + +# Admin Token (for admin endpoints) +ADMIN_TOKEN=your-secure-admin-token-here + +# Optional: GPU Configuration +# CUDA_VISIBLE_DEVICES=0 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 50b5405..6642e9f 100644 --- a/.gitignore +++ b/.gitignore @@ -54,6 +54,9 @@ tmp/ # Local environment .env.local .env.*.local +.env.production +.env.development +.env.staging # VAPID keys vapid_private.pem diff --git a/README.md b/README.md index 253d0e7..c370100 100644 --- a/README.md +++ b/README.md @@ -29,19 +29,34 @@ A mobile-friendly web application that translates spoken language between multip pip install -r requirements.txt ``` -2. Make sure you have Ollama installed and the Gemma 3 model loaded: +2. Configure environment variables: + ```bash + # Copy the example environment file + cp .env.example .env + + # Edit with your actual values + nano .env + + # Or set directly: + export TTS_API_KEY="your-tts-api-key" + export SECRET_KEY="your-secret-key" + ``` + + **⚠️ Security Note**: Never commit API keys or secrets to version control. See [SECURITY.md](SECURITY.md) for details. + +3. Make sure you have Ollama installed and the Gemma 3 model loaded: ``` ollama pull gemma3 ``` -3. Ensure your OpenAI Edge TTS server is running on port 5050. +4. Ensure your OpenAI Edge TTS server is running on port 5050. -4. Run the application: +5. Run the application: ``` python app.py ``` -5. Open your browser and navigate to: +6. Open your browser and navigate to: ``` http://localhost:8000 ``` diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..bee9644 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,129 @@ +# Security Configuration Guide + +This document outlines security best practices for deploying Talk2Me. + +## Environment Variables + +**NEVER commit sensitive information like API keys, passwords, or secrets to version control.** + +### Required Security Configuration + +1. **TTS_API_KEY** + - Required for TTS server authentication + - Set via environment variable: `export TTS_API_KEY="your-api-key"` + - Or use a `.env` file (see `.env.example`) + +2. **SECRET_KEY** + - Required for Flask session security + - Generate a secure key: `python -c "import secrets; print(secrets.token_hex(32))"` + - Set via: `export SECRET_KEY="your-generated-key"` + +3. **ADMIN_TOKEN** + - Required for admin endpoints + - Generate a secure token: `python -c "import secrets; print(secrets.token_urlsafe(32))"` + - Set via: `export ADMIN_TOKEN="your-admin-token"` + +### Using a .env File (Recommended) + +1. Copy the example file: + ```bash + cp .env.example .env + ``` + +2. Edit `.env` with your actual values: + ```bash + nano .env # or your preferred editor + ``` + +3. Load environment variables: + ```bash + # Using python-dotenv (add to requirements.txt) + pip install python-dotenv + + # Or source manually + source .env + ``` + +### Python-dotenv Integration + +To automatically load `.env` files, add this to the top of `app.py`: + +```python +from dotenv import load_dotenv +load_dotenv() # Load .env file if it exists +``` + +### Production Deployment + +For production deployments: + +1. **Use a secrets management service**: + - AWS Secrets Manager + - HashiCorp Vault + - Azure Key Vault + - Google Secret Manager + +2. **Set environment variables securely**: + - Use your platform's environment configuration + - Never expose secrets in logs or error messages + - Rotate keys regularly + +3. **Additional security measures**: + - Use HTTPS only + - Enable CORS restrictions + - Implement rate limiting + - Monitor for suspicious activity + +### Docker Deployment + +When using Docker: + +```dockerfile +# Use build arguments for non-sensitive config +ARG TTS_SERVER_URL=http://localhost:5050/v1/audio/speech + +# Use runtime environment for secrets +ENV TTS_API_KEY="" +``` + +Run with: +```bash +docker run -e TTS_API_KEY="your-key" -e SECRET_KEY="your-secret" talk2me +``` + +### Kubernetes Deployment + +Use Kubernetes secrets: + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: talk2me-secrets +type: Opaque +stringData: + tts-api-key: "your-api-key" + flask-secret-key: "your-secret-key" + admin-token: "your-admin-token" +``` + +### Security Checklist + +- [ ] All API keys removed from source code +- [ ] Environment variables configured +- [ ] `.env` file added to `.gitignore` +- [ ] Secrets rotated after any potential exposure +- [ ] HTTPS enabled in production +- [ ] CORS properly configured +- [ ] Rate limiting enabled +- [ ] Admin endpoints protected +- [ ] Error messages don't expose sensitive info +- [ ] Logs sanitized of sensitive data + +### Reporting Security Issues + +If you discover a security vulnerability, please report it to: +- Create a private security advisory on GitHub +- Or email: security@yourdomain.com + +Do not create public issues for security vulnerabilities. \ No newline at end of file diff --git a/app.py b/app.py index 090d73f..786c26e 100644 --- a/app.py +++ b/app.py @@ -4,6 +4,7 @@ import tempfile import requests import json import logging +from dotenv import load_dotenv from flask import Flask, render_template, request, jsonify, Response, send_file, send_from_directory, stream_with_context from flask_cors import CORS, cross_origin import whisper @@ -23,6 +24,9 @@ import atexit import threading from datetime import datetime, timedelta +# Load environment variables from .env file +load_dotenv() + # Initialize logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -92,7 +96,11 @@ except Exception as e: app.config['UPLOAD_FOLDER'] = upload_folder app.config['TTS_SERVER'] = os.environ.get('TTS_SERVER_URL', 'http://localhost:5050/v1/audio/speech') -app.config['TTS_API_KEY'] = os.environ.get('TTS_API_KEY', '56461d8b44607f2cfcb8030dee313a8e') +app.config['TTS_API_KEY'] = os.environ.get('TTS_API_KEY', '') + +# Warn if TTS API key is not set +if not app.config['TTS_API_KEY']: + logger.warning("TTS_API_KEY not set. TTS functionality may not work. Set it via environment variable or .env file.") # Rate limiting storage rate_limit_storage = {} diff --git a/requirements.txt b/requirements.txt index fde32e6..48f6d30 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,3 +6,4 @@ torch ollama pywebpush cryptography +python-dotenv