Remove hardcoded API key - CRITICAL SECURITY FIX

- 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 <noreply@anthropic.com>
This commit is contained in:
Adolfo Delorenzo 2025-06-03 00:06:18 -06:00
parent 17e0f2f03d
commit d010ae9b74
6 changed files with 183 additions and 5 deletions

22
.env.example Normal file
View File

@ -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

3
.gitignore vendored
View File

@ -54,6 +54,9 @@ tmp/
# Local environment
.env.local
.env.*.local
.env.production
.env.development
.env.staging
# VAPID keys
vapid_private.pem

View File

@ -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
```

129
SECURITY.md Normal file
View File

@ -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.

10
app.py
View File

@ -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 = {}

View File

@ -6,3 +6,4 @@ torch
ollama
pywebpush
cryptography
python-dotenv