#!/usr/bin/env python3
"""
API with Hardcoded Secrets - Vulnerable Example
Demonstrates insecure credential management and weak crypto
"""

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
import uvicorn
import yaml
import hashlib

app = FastAPI(title="Vulnerable Demo API")

# VULNERABLE: Hardcoded credentials
API_KEY = "sk_live_51234567890abcdefghij"
DATABASE_PASSWORD = "mongodb_password_weak_123"
JWT_SECRET = "my_super_secret_jwt_key_dont_change"

# VULNERABLE: Hardcoded encryption key
ENCRYPTION_KEY = "0123456789abcdef"  # Only 16 characters, weak!

# Load config with sensitive data
with open('/app/config.yaml') as f:
    config = yaml.safe_load(f)


@app.get("/api/health")
async def health():
    """Health check"""
    return {"status": "healthy"}


@app.post("/api/auth/register")
async def register(request: Request):
    """Register user - weak password hashing"""
    data = await request.json()
    username = data.get('username')
    password = data.get('password')
    
    # VULNERABLE: Using weak hashing algorithm
    hashed = hashlib.md5(password.encode()).hexdigest()  # MD5 is broken!
    
    # VULNERABLE: No password strength validation
    # VULNERABLE: No rate limiting
    
    return {
        "username": username,
        "hash": hashed,
        "created": True
    }


@app.post("/api/auth/login")
async def login(request: Request):
    """Login with weak security"""
    data = await request.json()
    username = data.get('username')
    password = data.get('password')
    
    # VULNERABLE: Hardcoded credentials
    if username == "admin" and password == "admin123":
        # VULNERABLE: Using old JWT algorithm
        import jwt
        token = jwt.encode(
            {"sub": username},
            JWT_SECRET,
            algorithm="HS256"  # Weak for this use case
        )
        return {"token": token, "type": "bearer"}
    
    raise HTTPException(status_code=401, detail="Invalid credentials")


@app.get("/api/secrets")
async def get_secrets():
    """VULNERABLE: Exposes all secrets"""
    return {
        "api_key": API_KEY,
        "db_password": DATABASE_PASSWORD,
        "jwt_secret": JWT_SECRET,
        "encryption_key": ENCRYPTION_KEY,
        "ssh_private_key": config.get('ssh_key', 'NOT_LOADED'),
    }


@app.post("/api/data/encrypt")
async def encrypt_data(request: Request):
    """Encrypt data with weak cipher"""
    data = await request.json()
    content = data.get('content')
    
    # VULNERABLE: Using Caesar cipher (not real encryption!)
    from cryptography.fernet import Fernet
    
    # VULNERABLE: Weak key derivation
    key = Fernet.generate_key()  # Generates new key each time, loses data!
    cipher = Fernet(key)
    
    encrypted = cipher.encrypt(content.encode()).decode()
    
    return {
        "encrypted": encrypted,
        "algorithm": "Fernet",  # Claims Fernet but key is ephemeral
        "key_size": 128
    }


@app.get("/api/database/connection")
async def db_connection():
    """VULNERABLE: Expose database connection string"""
    return {
        "host": "demo-postgres",
        "port": 5432,
        "database": "demo_db",
        "user": "demo_user",
        "password": "demo_password_123",
        "connection_string": f"postgresql://demo_user:demo_password_123@demo-postgres:5432/demo_db"
    }


@app.get("/api/config/all")
async def get_all_config():
    """VULNERABLE: Expose entire configuration"""
    return {
        "config": config,
        "environment": {
            "API_KEY": API_KEY,
            "DB_PASSWORD": DATABASE_PASSWORD,
            "JWT_SECRET": JWT_SECRET,
            "ENCRYPTION_KEY": ENCRYPTION_KEY
        }
    }


@app.post("/api/files/upload")
async def upload_file(request: Request):
    """VULNERABLE: Unsafe file upload"""
    form_data = await request.form()
    file = form_data.get('file')
    
    # VULNERABLE: No file type validation
    # VULNERABLE: No size limit
    # VULNERABLE: Predictable filename
    
    filename = file.filename
    with open(f'/app/uploads/{filename}', 'wb') as f:
        f.write(await file.read())
    
    return {"uploaded": filename, "size": len(await file.read())}


@app.get("/api/execute")
async def execute_command(request: Request):
    """VULNERABLE: Command injection"""
    cmd = request.query_params.get('cmd', '')
    
    # VULNERABLE: Direct command execution!
    import subprocess
    result = subprocess.run(cmd, shell=True, capture_output=True)
    
    return {
        "command": cmd,
        "output": result.stdout.decode(),
        "error": result.stderr.decode()
    }


@app.middleware("http")
async def log_middleware(request: Request, call_next):
    """VULNERABLE: Logs sensitive data"""
    import logging
    logger = logging.getLogger(__name__)
    
    # Logs everything including passwords in query params
    logger.info(f"Request: {request.method} {request.url}")
    logger.debug(f"Headers: {dict(request.headers)}")
    
    response = await call_next(request)
    return response


if __name__ == "__main__":
    # VULNERABLE: Debug mode enabled
    uvicorn.run(
        app,
        host="0.0.0.0",
        port=5001,
        debug=True,  # DANGEROUS!
        log_level="debug"  # Verbose logging
    )
