# Input Validation Security Example Real-world example demonstrating comprehensive input validation to prevent common security vulnerabilities. ## Scenario Building a user profile update endpoint that's vulnerable to multiple injection attacks due to insufficient validation. ## Vulnerable Code ### Backend (FastAPI) - BEFORE ```python # ❌ VULNERABLE CODE - DO NOT USE from fastapi import FastAPI, HTTPException from sqlalchemy import text app = FastAPI() @app.post("/api/users/{user_id}/profile") async def update_profile(user_id: str, request: dict): """Update user profile - VULNERABLE VERSION""" # ❌ VULNERABILITY 1: No input validation name = request.get("name") bio = request.get("bio") website = request.get("website") age = request.get("age") # ❌ VULNERABILITY 2: SQL Injection via string concatenation query = text(f""" UPDATE users SET name = '{name}', bio = '{bio}', website = '{website}', age = {age} WHERE id = '{user_id}' """) await db.execute(query) return {"status": "success"} ``` **Attack Examples:** 1. **SQL Injection:** ```python POST /api/users/123/profile { "name": "'; DROP TABLE users; --", "bio": "innocent bio", "website": "https://example.com", "age": 25 } # Executes: UPDATE users SET name = ''; DROP TABLE users; --', ... # Result: users table deleted! ``` 2. **XSS via Bio Field:** ```python POST /api/users/123/profile { "name": "John", "bio": "", "website": "https://example.com", "age": 25 } # Bio stored with script tag, executed when rendered ``` 3. **Type Confusion:** ```python POST /api/users/123/profile { "name": "John", "bio": "Normal bio", "website": "javascript:alert('XSS')", # Invalid URL scheme "age": "twenty" # String instead of number - could crash } ``` ### Frontend (TanStack Start) - BEFORE ```typescript // ❌ VULNERABLE CODE - DO NOT USE async function updateProfile(userId: string, data: any) { // ❌ VULNERABILITY: No client-side validation // ❌ VULNERABILITY: Trusting server data without sanitization const response = await fetch(`/api/users/${userId}/profile`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) // No validation }); return response.json(); } function ProfileForm() { const [bio, setBio] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); await updateProfile(userId, { bio }); // No validation }; return (