Files
Pony Alpha 2 68453089ee feat: initial Alpha Brain 2 dataset release
Massive training corpus for AI coding models containing:
- 10 JSONL training datasets (641+ examples across coding, reasoning, planning, architecture, communication, debugging, security, workflows, error handling, UI/UX)
- 11 agent behavior specifications (explorer, planner, reviewer, debugger, executor, UI designer, Linux admin, kernel engineer, security architect, automation engineer, API architect)
- 6 skill definition files (coding, API engineering, kernel, Linux server, security architecture, server automation, UI/UX)
- Master README with project origin story and philosophy

Built by Pony Alpha 2 to help AI models learn expert-level coding approaches.
2026-03-13 16:26:29 +04:00

63 lines
72 KiB
JSON

{"type": "code_review", "input_code": "def login(username, password):\n query = \"SELECT * FROM users WHERE username='\" + username + \"' AND password='\" + password + \"'\"\n cursor.execute(query)\n return cursor.fetchone()", "analysis": "1. The code directly concatenates user input into a SQL query without any sanitization.\n2. This creates a classic SQL injection vulnerability where an attacker can manipulate the query.\n3. The password appears to be stored in plaintext or compared directly.\n4. No input validation is performed on username or password.\n5. The function returns raw database results without proper error handling.", "findings": [{"issue": "SQL Injection Vulnerability", "severity": "CRITICAL", "location": "query construction", "cwe": "CWE-89"}, {"issue": "Plaintext Password Storage", "severity": "HIGH", "location": "password comparison", "cwe": "CWE-256"}, {"issue": "Missing Input Validation", "severity": "MEDIUM", "location": "function parameters", "cwe": "CWE-20"}, {"issue": "No Error Handling", "severity": "MEDIUM", "location": "entire function", "cwe": "CWE-390"}], "fix": "def login(username, password):\n if not username or not password:\n raise ValueError(\"Username and password required\")\n \n if len(username) > 100 or len(password) > 100:\n raise ValueError(\"Input exceeds maximum length\")\n \n cursor.execute(\n \"SELECT user_id, username, password_hash FROM users WHERE username = %s\",\n (username,)\n )\n result = cursor.fetchone()\n \n if result and verify_password(password, result['password_hash']):\n return {'user_id': result['user_id'], 'username': result['username']}\n return None"}
{"type": "debugging", "input_code": "async def fetch_user_data(user_ids):\n results = []\n for user_id in user_ids:\n data = await db.query(f\"SELECT * FROM users WHERE id = {user_id}\")\n results.append(data)\n return results", "analysis": "1. Sequential iteration over user IDs makes N database queries sequentially.\n2. String formatting in query creates SQL injection vulnerability.\n3. No error handling for database failures.\n4. Missing await on all operations.\n5. No connection pooling or timeout handling.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "f-string query", "cwe": "CWE-89"}, {"issue": "Performance - N+1 Query Problem", "severity": "HIGH", "location": "sequential loop", "cwe": "CWE-1050"}, {"issue": "No Error Handling", "severity": "MEDIUM", "location": "database operations", "cwe": "CWE-390"}, {"issue": "Resource Exhaustion Risk", "severity": "MEDIUM", "location": "no limits on user_ids", "cwe": "CWE-400"}], "fix": "async def fetch_user_data(user_ids):\n if not user_ids:\n return []\n \n if len(user_ids) > 1000:\n raise ValueError(\"Too many user IDs requested\")\n \n try:\n query = \"SELECT * FROM users WHERE id = ANY($1)\"\n results = await db.query(query, list(user_ids))\n return results\n except DatabaseError as e:\n logger.error(f\"Failed to fetch user data: {e}\")\n raise"}
{"type": "code_review", "input_code": "function renderTemplate(name, data) {\n return `<div>Hello ${data.name}</div>\n <script>var userData = ${JSON.stringify(data)};</script>\n`;\n}", "analysis": "1. The template directly outputs user-controlled data without sanitization.\n2. JSON.stringify doesn't protect against XSS in script contexts.\n3. The name is interpolated directly into HTML without escaping.\n4. User data is embedded in a script tag, creating XSS vulnerabilities.\n5. No Content Security Policy or output encoding.", "findings": [{"issue": "Cross-Site Scripting (XSS)", "severity": "CRITICAL", "location": "HTML interpolation", "cwe": "CWE-79"}, {"issue": "XSS via Script Injection", "severity": "CRITICAL", "location": "script tag", "cwe": "CWE-79"}, {"issue": "Missing Output Encoding", "severity": "HIGH", "location": "template function", "cwe": "CWE-116"}], "fix": "import { escape } from 'validator';\n\nfunction renderTemplate(name, data) {\n const sanitizedName = escape(name);\n const safeData = JSON.stringify(data)\n .replace(/</g, '\\\\x3c')\n .replace(/>/g, '\\\\x3e')\n .replace(/&/g, '\\\\x26')\n .replace(/'/g, \"\\\\x27\");\n \n return `<div>Hello ${sanitizedName}</div>`;\n}"}
{"type": "debugging", "input_code": "func handleRequest(w http.ResponseWriter, r *http.Request) {\n cmd := exec.Command(\"sh\", \"-c\", r.URL.Query().Get(\"command\"))\n output, err := cmd.Output()\n if err != nil {\n fmt.Println(err)\n }\n w.Write(output)\n}", "analysis": "1. User input directly passed to shell command execution.\n2. This creates a command injection vulnerability allowing arbitrary code execution.\n3. No validation or sanitization of the command parameter.\n4. Error handling only prints to console, leaks information.\n5. No timeout on command execution allows for DoS attacks.", "findings": [{"issue": "OS Command Injection", "severity": "CRITICAL", "location": "exec.Command with user input", "cwe": "CWE-78"}, {"issue": "Information Disclosure", "severity": "MEDIUM", "location": "error printing", "cwe": "CWE-209"}, {"issue": "Denial of Service", "severity": "HIGH", "location": "no command timeout", "cwe": "CWE-400"}, {"issue": "Missing Input Validation", "severity": "CRITICAL", "location": "query parameter", "cwe": "CWE-20"}], "fix": "func handleRequest(w http.ResponseWriter, r *http.Request) {\n allowedCommands := map[string]string{\n \"status\": \"/usr/bin/systemctl status\",\n \"version\": \"/usr/bin/app --version\",\n }\n \n cmdName := r.URL.Query().Get(\"command\")\n cmdPath, ok := allowedCommands[cmdName]\n if !ok {\n http.Error(w, \"Invalid command\", http.StatusBadRequest)\n return\n }\n \n ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n defer cancel()\n \n cmd := exec.CommandContext(ctx, cmdPath)\n output, err := cmd.Output()\n if err != nil {\n http.Error(w, \"Command failed\", http.StatusInternalServerError)\n return\n }\n w.Write(output)\n}"}
{"type": "code_review", "input_code": "def process_file(filename):\n with open(filename, 'r') as f:\n content = f.read()\n result = parse_content(content)\n os.system('rm ' + filename)\n return result", "analysis": "1. No validation of filename parameter allows path traversal attacks.\n2. os.system with string concatenation creates command injection vulnerability.\n3. No exception handling for file operations.\n4. File permissions not checked before reading.\n5. Arbitrary file deletion possible through path traversal.", "findings": [{"issue": "Path Traversal", "severity": "CRITICAL", "location": "filename parameter", "cwe": "CWE-22"}, {"issue": "Command Injection", "severity": "CRITICAL", "location": "os.system call", "cwe": "CWE-78"}, {"issue": "Missing Exception Handling", "severity": "MEDIUM", "location": "file operations", "cwe": "CWE-390"}, {"issue": "Insecure File Operations", "severity": "HIGH", "location": "file handling", "cwe": "CWE-276"}], "fix": "import os\nimport pathlib\n\ndef process_file(filename):\n # Validate and sanitize filename\n if not filename or '/' in filename or '\\\\' in filename:\n raise ValueError(\"Invalid filename\")\n \n # Restrict to specific directory\n base_dir = '/var/app/uploads'\n file_path = pathlib.Path(base_dir) / filename\n \n # Resolve to prevent path traversal\n try:\n file_path = file_path.resolve()\n if not str(file_path).startswith(base_dir):\n raise ValueError(\"Path traversal detected\")\n except (RuntimeError, ValueError):\n raise ValueError(\"Invalid file path\")\n \n try:\n with open(file_path, 'r') as f:\n content = f.read()\n result = parse_content(content)\n os.remove(file_path)\n return result\n except (IOError, OSError) as e:\n logger.error(f\"File processing error: {e}\")\n raise"}
{"type": "debugging", "input_code": "class DataCache:\n def __init__(self):\n self.cache = {}\n \n def get(self, key):\n return self.cache.get(key)\n \n def set(self, key, value):\n self.cache[key] = value", "analysis": "1. Cache has no size limit allowing unbounded memory growth.\n2. No TTL or expiration mechanism for cached items.\n3. No thread-safety for concurrent access.\n4. Memory leak risk as cache grows indefinitely.\n5. No eviction policy when cache is full.", "findings": [{"issue": "Unbounded Memory Growth", "severity": "HIGH", "location": "self.cache dictionary", "cwe": "CWE-400"}, {"issue": "Missing Cache Eviction Policy", "severity": "MEDIUM", "location": "no size limit", "cwe": "CWE-770"}, {"issue": "Race Condition", "severity": "MEDIUM", "location": "concurrent access", "cwe": "CWE-362"}, {"issue": "Resource Exhaustion", "severity": "HIGH", "location": "cache unlimited growth", "cwe": "CWE-400"}], "fix": "from threading import Lock\nfrom time import time\n\nclass DataCache:\n def __init__(self, max_size=1000, ttl=3600):\n self.cache = {}\n self.timestamps = {}\n self.lock = Lock()\n self.max_size = max_size\n self.ttl = ttl\n \n def get(self, key):\n with self.lock:\n if key not in self.cache:\n return None\n \n # Check expiration\n if time() - self.timestamps[key] > self.ttl:\n del self.cache[key]\n del self.timestamps[key]\n return None\n \n return self.cache[key]\n \n def set(self, key, value):\n with self.lock:\n # Evict oldest if at capacity\n if len(self.cache) >= self.max_size:\n oldest = min(self.timestamps.items(), key=lambda x: x[1])[0]\n del self.cache[oldest]\n del self.timestamps[oldest]\n \n self.cache[key] = value\n self.timestamps[key] = time()"}
{"type": "code_review", "input_code": "const express = require('express');\nconst app = express();\n\napp.get('/user/:id', (req, res) => {\n const userId = req.params.id;\n const query = `SELECT * FROM users WHERE id = ${userId}`;\n db.query(query, (err, result) => {\n res.json(result);\n });\n});", "analysis": "1. Direct SQL query construction with user input creates SQL injection vulnerability.\n2. No input validation on userId parameter.\n3. No error handling for database operations.\n4. Raw database results returned to client without sanitization.\n5. Missing authentication/authorization checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query template literal", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "userId parameter", "cwe": "CWE-20"}, {"issue": "Missing Access Control", "severity": "HIGH", "location": "route handler", "cwe": "CWE-284"}, {"issue": "Information Disclosure", "severity": "MEDIUM", "location": "raw database results", "cwe": "CWE-200"}], "fix": "const express = require('express');\nconst app = express();\n\napp.get('/user/:id', async (req, res) => {\n try {\n const userId = parseInt(req.params.id);\n \n if (!userId || userId < 1 || userId > 2147483647) {\n return res.status(400).json({ error: 'Invalid user ID' });\n }\n \n // Check authorization\n if (req.user.id !== userId && !req.user.isAdmin) {\n return res.status(403).json({ error: 'Forbidden' });\n }\n \n const query = 'SELECT id, username, email FROM users WHERE id = $1';\n const result = await db.query(query, [userId]);\n \n if (result.rows.length === 0) {\n return res.status(404).json({ error: 'User not found' });\n }\n \n res.json(result.rows[0]);\n } catch (error) {\n console.error('Database error:', error);\n res.status(500).json({ error: 'Internal server error' });\n }\n});"}
{"type": "debugging", "input_code": "import threading\n\nclass BankAccount:\n def __init__(self, balance=0):\n self.balance = balance\n \n def deposit(self, amount):\n self.balance += amount\n \n def withdraw(self, amount):\n if self.balance >= amount:\n self.balance -= amount\n return True\n return False", "analysis": "1. No thread-synchronization on balance access creates race conditions.\n2. Read-modify-write operations are not atomic.\n3. Check-then-act pattern in withdraw is vulnerable to TOCTOU race conditions.\n4. Multiple threads can cause inconsistent balance states.\n5. No transaction isolation or locking mechanisms.", "findings": [{"issue": "Race Condition", "severity": "HIGH", "location": "balance read-modify-write", "cwe": "CWE-362"}, {"issue": "Time-of-Check Time-of-Use", "severity": "HIGH", "location": "withdraw method", "cwe": "CWE-367"}, {"issue": "Missing Synchronization", "severity": "HIGH", "location": "all balance operations", "cwe": "CWE-820"}, {"issue": "Data Inconsistency", "severity": "MEDIUM", "location": "concurrent operations", "cwe": "CWE-459"}], "fix": "import threading\n\nclass BankAccount:\n def __init__(self, balance=0):\n self.balance = balance\n self.lock = threading.Lock()\n \n def deposit(self, amount):\n with self.lock:\n if amount <= 0:\n raise ValueError(\"Amount must be positive\")\n self.balance += amount\n \n def withdraw(self, amount):\n with self.lock:\n if amount <= 0:\n raise ValueError(\"Amount must be positive\")\n if self.balance >= amount:\n self.balance -= amount\n return True\n return False\n \n def get_balance(self):\n with self.lock:\n return self.balance"}
{"type": "code_review", "input_code": "function compressData(data) {\n let compressed = '';\n for (let i = 0; i < data.length; i++) {\n compressed += data[i].repeat(Math.floor(Math.random() * 100));\n }\n return compressed;\n}", "analysis": "1. String concatenation in loop causes quadratic time complexity.\n2. Unbounded string growth with random repeat can cause memory exhaustion.\n3. No input validation or size limits.\n4. Random repeat factor is unpredictable and could be extremely large.\n5. No error handling for memory allocation failures.", "findings": [{"issue": "Performance - String Concatenation", "severity": "HIGH", "location": "compressed += in loop", "cwe": "CWE-407"}, {"issue": "Memory Exhaustion", "severity": "HIGH", "location": "unbounded repeat", "cwe": "CWE-400"}, {"issue": "Missing Input Validation", "severity": "MEDIUM", "location": "no size checks", "cwe": "CWE-20"}, {"issue": "Unpredictable Resource Usage", "severity": "MEDIUM", "location": "random repeat factor", "cwe": "CWE-400"}], "fix": "function compressData(data, maxSize = 10 * 1024 * 1024) {\n if (!data || data.length === 0) {\n throw new Error('Invalid input data');\n }\n \n if (data.length > 10000) {\n throw new Error('Input data too large');\n }\n \n const chunks = [];\n let totalSize = 0;\n \n for (let i = 0; i < data.length; i++) {\n const repeatCount = Math.floor(Math.random() * 10) + 1;\n const chunk = data[i].repeat(repeatCount);\n \n totalSize += chunk.length;\n if (totalSize > maxSize) {\n throw new Error('Compressed data exceeds maximum size');\n }\n \n chunks.push(chunk);\n }\n \n return chunks.join('');\n}"}
{"type": "debugging", "input_code": "package main\n\nimport (\n \"encoding/json\"\n \"net/http\"\n)\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n var data map[string]interface{}\n json.NewDecoder(r.Body).Decode(&data)\n \n cmd := data[\"command\"].(string)\n result := executeCommand(cmd)\n \n json.NewEncoder(w).Encode(result)\n}\n\nfunc executeCommand(cmd string) string {\n // Execute command and return result\n return \"result\"\n}", "analysis": "1. User-controlled JSON data directly used to execute commands.\n2. Type assertion without checking can cause panic.\n3. No error handling for JSON decoding.\n4. No validation of command content.\n5. Command execution suggests potential command injection.", "findings": [{"issue": "Unsafe Type Assertion", "severity": "HIGH", "location": "data[\"command\"].(string)", "cwe": "CWE-585"}, {"issue": "Potential Command Injection", "severity": "CRITICAL", "location": "executeCommand call", "cwe": "CWE-78"}, {"issue": "Missing Error Handling", "severity": "MEDIUM", "location": "JSON decode", "cwe": "CWE-390"}, {"issue": "No Input Validation", "severity": "HIGH", "location": "command parameter", "cwe": "CWE-20"}], "fix": "package main\n\nimport (\n \"encoding/json\"\n \"net/http\"\n \"strings\"\n)\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n var data map[string]interface{}\n decoder := json.NewDecoder(r.Body)\n decoder.DisallowUnknownFields()\n \n if err := decoder.Decode(&data); err != nil {\n http.Error(w, \"Invalid JSON\", http.StatusBadRequest)\n return\n }\n \n cmd, ok := data[\"command\"].(string)\n if !ok || cmd == \"\" {\n http.Error(w, \"Command required\", http.StatusBadRequest)\n return\n }\n \n // Validate command against whitelist\n allowedCommands := map[string]bool{\n \"status\": true,\n \"version\": true,\n }\n \n if !allowedCommands[strings.ToLower(strings.TrimSpace(cmd))] {\n http.Error(w, \"Invalid command\", http.StatusBadRequest)\n return\n }\n \n result := executeCommand(cmd)\n json.NewEncoder(w).Encode(result)\n}\n\nfunc executeCommand(cmd string) string {\n // Safe command execution\n return \"result\"\n}"}
{"type": "code_review", "input_code": "def download_file(url):\n import requests\n response = requests.get(url)\n filename = url.split('/')[-1]\n with open(filename, 'wb') as f:\n f.write(response.content)\n return filename", "analysis": "1. No validation of URL scheme allows file:// or other dangerous protocols.\n2. URL can include path traversal sequences in filename.\n3. No verification of response content type or size.\n4. No error handling for network or file operations.\n5. Arbitrary file write vulnerability through URL manipulation.", "findings": [{"issue": "SSRF (Server-Side Request Forgery)", "severity": "CRITICAL", "location": "unvalidated URL", "cwe": "CWE-918"}, {"issue": "Arbitrary File Write", "severity": "CRITICAL", "location": "filename extraction", "cwe": "CWE-22"}, {"issue": "Missing Size Limits", "severity": "HIGH", "location": "unbounded download", "cwe": "CWE-400"}, {"issue": "No Error Handling", "severity": "MEDIUM", "location": "network operations", "cwe": "CWE-390"}], "fix": "import requests\nimport os\nfrom urllib.parse import urlparse\nimport re\n\ndef download_file(url, max_size=100*1024*1024):\n # Validate URL\n parsed = urlparse(url)\n if parsed.scheme not in ['http', 'https']:\n raise ValueError(\"Only HTTP/HTTPS URLs allowed\")\n \n # Whitelist allowed domains if needed\n # allowed_domains = ['example.com', 'cdn.example.com']\n # if parsed.netloc not in allowed_domains:\n # raise ValueError(\"Domain not allowed\")\n \n try:\n response = requests.get(url, stream=True, timeout=30)\n response.raise_for_status()\n \n # Verify content type\n content_type = response.headers.get('content-type', '')\n if not content_type.startswith(('image/', 'application/pdf')):\n raise ValueError(\"Invalid content type\")\n \n # Check content length\n content_length = int(response.headers.get('content-length', 0))\n if content_length > max_size:\n raise ValueError(\"File too large\")\n \n # Sanitize filename\n filename = os.path.basename(parsed.path)\n if not filename or filename.startswith('.'):\n raise ValueError(\"Invalid filename\")\n \n # Remove directory traversal attempts\n filename = re.sub(r'[<>:\"/\\\\|?*]', '_', filename)\n \n # Restrict to downloads directory\n safe_dir = '/var/app/downloads'\n safe_path = os.path.join(safe_dir, filename)\n safe_path = os.path.normpath(safe_path)\n if not safe_path.startswith(safe_dir):\n raise ValueError(\"Invalid file path\")\n \n # Download with size limit\n downloaded_size = 0\n with open(safe_path, 'wb') as f:\n for chunk in response.iter_content(chunk_size=8192):\n downloaded_size += len(chunk)\n if downloaded_size > max_size:\n raise ValueError(\"File size exceeded\")\n f.write(chunk)\n \n return safe_path\n \n except requests.RequestException as e:\n raise ValueError(f\"Download failed: {e}\")"}
{"type": "debugging", "input_code": "interface Cache {\n get(key: string): any;\n set(key: string, value: any): void;\n}\n\nclass SimpleCache implements Cache {\n private cache: Record<string, any> = {};\n \n get(key: string): any {\n return this.cache[key];\n }\n \n set(key: string, value: any): void {\n this.cache[key] = value;\n }\n}", "analysis": "1. Unbounded cache growth causes memory leaks.\n2. No expiration mechanism for cached items.\n3. No size limits or eviction policy.\n4. Type 'any' loses type safety.\n5. Missing thread safety considerations.", "findings": [{"issue": "Memory Leak", "severity": "HIGH", "location": "unbounded cache object", "cwe": "CWE-401"}, {"issue": "Missing Cache Eviction", "severity": "MEDIUM", "location": "no size limit", "cwe": "CWE-770"}, {"issue": "Type Safety Loss", "severity": "LOW", "location": "any type usage", "cwe": "CWE-745"}, {"issue": "Resource Exhaustion", "severity": "HIGH", "location": "unlimited cache growth", "cwe": "CWE-400"}], "fix": "interface CacheEntry<T> {\n value: T;\n timestamp: number;\n}\n\nclass SimpleCache<T> implements Cache {\n private cache: Map<string, CacheEntry<T>> = new Map();\n private readonly maxSize: number;\n private readonly ttl: number;\n \n constructor(maxSize: number = 1000, ttl: number = 3600000) {\n this.maxSize = maxSize;\n this.ttl = ttl;\n }\n \n get(key: string): T | null {\n const entry = this.cache.get(key);\n if (!entry) return null;\n \n // Check expiration\n if (Date.now() - entry.timestamp > this.ttl) {\n this.cache.delete(key);\n return null;\n }\n \n return entry.value;\n }\n \n set(key: string, value: T): void {\n // Evict oldest if at capacity\n if (this.cache.size >= this.maxSize && !this.cache.has(key)) {\n const oldestKey = this.cache.keys().next().value;\n this.cache.delete(oldestKey);\n }\n \n this.cache.set(key, {\n value,\n timestamp: Date.now()\n });\n }\n \n clear(): void {\n this.cache.clear();\n }\n \n size(): number {\n return this.cache.size;\n }\n}"}
{"type": "code_review", "input_code": "def authenticate(token):\n import jwt\n decoded = jwt.decode(token)\n return decoded['user_id']", "analysis": "1. JWT verification is completely missing - no signature validation.\n2. No algorithm specification vulnerable to algorithm confusion attacks.\n3. Missing expiration validation allows token reuse indefinitely.\n4. No error handling for invalid tokens.\n5. Token claims not validated for required fields.", "findings": [{"issue": "Missing JWT Signature Verification", "severity": "CRITICAL", "location": "jwt.decode without verify", "cwe": "CWE-347"}, {"issue": "Algorithm Confusion", "severity": "HIGH", "location": "no algorithm specification", "cwe": "CWE-290"}, {"issue": "Missing Expiration Check", "severity": "HIGH", "location": "no exp validation", "cwe": "CWE-613"}, {"issue": "No Error Handling", "severity": "MEDIUM", "location": "decode operation", "cwe": "CWE-390"}], "fix": "import jwt\nfrom jwt import PyJWTError\n\ndef authenticate(token):\n try:\n # Verify signature and claims\n payload = jwt.decode(\n token,\n os.getenv('JWT_SECRET'),\n algorithms=['HS256'],\n options={\n 'require': ['exp', 'sub', 'user_id'],\n 'verify_exp': True\n }\n )\n \n # Validate required fields\n if 'user_id' not in payload:\n raise ValueError(\"Invalid token: missing user_id\")\n \n return {\n 'user_id': payload['user_id'],\n 'exp': payload['exp']\n }\n \n except PyJWTError as e:\n raise ValueError(f\"Invalid token: {e}\")\n except Exception as e:\n raise ValueError(f\"Authentication failed: {e}\")"}
{"type": "debugging", "input_code": "func (s *Server) handleConnection(conn net.Conn) {\n buffer := make([]byte, 1024*1024)\n for {\n n, err := conn.Read(buffer)\n if err != nil {\n break\n }\n \n result := processData(buffer[:n])\n conn.Write(result)\n }\n conn.Close()\n}", "analysis": "1. Fixed 1MB buffer allocation per connection can exhaust memory.\n2. No limit on number of concurrent connections.\n3. No timeout on read operations can block forever.\n4. No validation of data length or content.\n5. Error handling doesn't distinguish between error types.", "findings": [{"issue": "Memory Exhaustion", "severity": "HIGH", "location": "1MB buffer per connection", "cwe": "CWE-400"}, {"issue": "Resource Exhaustion", "severity": "HIGH", "location": "unlimited connections", "cwe": "CWE-400"}, {"issue": "Missing Timeouts", "severity": "MEDIUM", "location": "conn.Read without timeout", "cwe": "CWE-785"}, {"issue": "Missing Connection Limits", "severity": "HIGH", "location": "unbounded goroutines", "cwe": "CWE-770"}], "fix": "func (s *Server) handleConnection(conn net.Conn) {\n defer conn.Close()\n \n // Set deadlines to prevent hanging\n conn.SetDeadline(time.Now().Add(30 * time.Second))\n \n // Use smaller buffer with size limit\n buffer := make([]byte, 4096)\n var data []byte\n \n for {\n n, err := conn.Read(buffer)\n if err != nil {\n if err != io.EOF {\n log.Printf(\"Read error: %v\", err)\n }\n break\n }\n \n // Enforce size limit\n data = append(data, buffer[:n]...)\n if len(data) > 1024*1024 {\n conn.Write([]byte(\"ERROR: Data too large\"))\n return\n }\n \n result := processData(data)\n if _, err := conn.Write(result); err != nil {\n log.Printf(\"Write error: %v\", err)\n return\n }\n \n data = data[:0] // Reset buffer\n conn.SetDeadline(time.Now().Add(30 * time.Second))\n }\n}\n\nfunc processData(data []byte) []byte {\n // Validate and process data\n return data\n}"}
{"type": "code_review", "input_code": "app.post('/upload', upload.single('file'), (req, res) => {\n const file = req.file;\n const outputPath = path.join(__dirname, '../uploads', file.originalname);\n fs.renameSync(file.path, outputPath);\n res.json({ url: `/uploads/${file.originalname}` });\n});", "analysis": "1. Original filename not sanitized allowing path traversal.\n2. No file type validation allows malicious file uploads.\n3. No file size limits can exhaust disk space.\n4. Synchronous file operations block event loop.\n5. No virus scanning or content validation.", "findings": [{"issue": "Path Traversal", "severity": "CRITICAL", "location": "file.originalname", "cwe": "CWE-22"}, {"issue": "Unrestricted File Upload", "severity": "CRITICAL", "location": "no file type validation", "cwe": "CWE-434"}, {"issue": "Denial of Service", "severity": "HIGH", "location": "no size limits", "cwe": "CWE-400"}, {"issue": "Synchronous Operations", "severity": "MEDIUM", "location": "renameSync", "cwe": "CWE-842"}], "fix": "import path from 'path';\nimport fs from 'fs/promises';\nimport crypto from 'crypto';\n\napp.post('/upload', upload.single('file'), async (req, res) => {\n try {\n const file = req.file;\n \n if (!file) {\n return res.status(400).json({ error: 'No file uploaded' });\n }\n \n // Validate file type\n const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];\n if (!allowedTypes.includes(file.mimetype)) {\n await fs.unlink(file.path);\n return res.status(400).json({ error: 'Invalid file type' });\n }\n \n // Validate file size (already done by multer, but double-check)\n const MAX_SIZE = 10 * 1024 * 1024;\n if (file.size > MAX_SIZE) {\n await fs.unlink(file.path);\n return res.status(400).json({ error: 'File too large' });\n }\n \n // Generate safe filename\n const ext = path.extname(file.originalname);\n const basename = crypto.randomBytes(16).toString('hex');\n const safeFilename = `${basename}${ext}`;\n \n // Validate extension\n const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.pdf'];\n if (!allowedExts.includes(ext.toLowerCase())) {\n await fs.unlink(file.path);\n return res.status(400).json({ error: 'Invalid file extension' });\n }\n \n const outputPath = path.join(__dirname, '../uploads', safeFilename);\n await fs.rename(file.path, outputPath);\n \n res.json({ url: `/uploads/${safeFilename}` });\n } catch (error) {\n console.error('Upload error:', error);\n res.status(500).json({ error: 'Upload failed' });\n }\n});"}
{"type": "debugging", "input_code": "def process_payments(payments):\n results = []\n for payment in payments:\n try:\n result = api.charge(payment.amount, payment.card)\n results.append(result)\n except Exception as e:\n logger.error(f\"Payment failed: {e}\")\n continue\n return results", "analysis": "1. Silent exception handling masks important errors.\n2. No distinction between different error types.\n3. Transaction may be partially processed on failure.\n4. No retry logic for transient failures.\n5. No idempotency protection for duplicate charges.", "findings": [{"issue": "Silent Error Handling", "severity": "MEDIUM", "location": "broad except", "cwe": "CWE-390"}, {"issue": "Missing Transaction Safety", "severity": "HIGH", "location": "partial processing", "cwe": "CWE-662"}, {"issue": "No Idempotency", "severity": "HIGH", "location": "duplicate charge risk", "cwe": "CWE-841"}, {"issue": "Insufficient Error Logging", "severity": "LOW", "location": "generic error log", "cwe": "CWE-778"}], "fix": "import time\nfrom typing import List\n\ndef process_payments(payments: List[Payment], max_retries: int = 3) -> Dict[str, Any]:\n results = {'successful': [], 'failed': [], 'total': len(payments)}\n \n for payment in payments:\n if not payment.idempotency_key:\n payment.idempotency_key = generate_idempotency_key(payment)\n \n for attempt in range(max_retries):\n try:\n # Validate payment data\n if not validate_payment(payment):\n results['failed'].append({\n 'payment_id': payment.id,\n 'error': 'Invalid payment data'\n })\n break\n \n # Check for duplicate processing\n if is_payment_processed(payment.idempotency_key):\n results['failed'].append({\n 'payment_id': payment.id,\n 'error': 'Duplicate payment'\n })\n break\n \n result = api.charge(\n amount=payment.amount,\n card=payment.card,\n idempotency_key=payment.idempotency_key\n )\n \n if result.success:\n results['successful'].append({\n 'payment_id': payment.id,\n 'transaction_id': result.transaction_id\n })\n mark_payment_processed(payment.idempotency_key)\n break\n else:\n raise PaymentError(result.error_message)\n \n except PaymentAPIError as e:\n if attempt == max_retries - 1:\n results['failed'].append({\n 'payment_id': payment.id,\n 'error': f\"API error after {max_retries} attempts: {e}\"\n })\n else:\n time.sleep(2 ** attempt) # Exponential backoff\n \n except CardDeclinedError as e:\n results['failed'].append({\n 'payment_id': payment.id,\n 'error': f'Card declined: {e}'\n })\n break\n \n except ValidationError as e:\n results['failed'].append({\n 'payment_id': payment.id,\n 'error': f'Validation failed: {e}'\n })\n break\n \n except Exception as e:\n logger.error(f\"Unexpected error processing payment {payment.id}: {e}\")\n results['failed'].append({\n 'payment_id': payment.id,\n 'error': 'Unexpected error occurred'\n })\n break\n \n return results"}
{"type": "code_review", "input_code": "func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n token := r.Header.Get(\"Authorization\")\n user := validateToken(token)\n \n data := getUserData(user)\n json.NewEncoder(w).Encode(data)\n}\n\nfunc validateToken(token string) string {\n return token[7:] // Remove \"Bearer \"\n}", "analysis": "1. No token validation beyond removing prefix.\n2. Missing JWT signature verification.\n3. No error handling for malformed tokens.\n4. User data fetched without authorization checks.\n5. Sensitive data exposed without filtering.", "findings": [{"issue": "Missing Authentication", "severity": "CRITICAL", "location": "validateToken function", "cwe": "CWE-306"}, {"issue": "Missing Authorization", "severity": "HIGH", "location": "no permission checks", "cwe": "CWE-285"}, {"issue": "Information Disclosure", "severity": "MEDIUM", "location": "raw user data", "cwe": "CWE-200"}, {"issue": "No Error Handling", "severity": "LOW", "location": "token parsing", "cwe": "CWE-390"}], "fix": "func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n authHeader := r.Header.Get(\"Authorization\")\n if authHeader == \"\" {\n http.Error(w, \"Missing authorization header\", http.StatusUnauthorized)\n return\n }\n \n tokenString := strings.TrimPrefix(authHeader, \"Bearer \")\n if tokenString == authHeader {\n http.Error(w, \"Invalid authorization format\", http.StatusUnauthorized)\n return\n }\n \n claims, err := validateToken(tokenString)\n if err != nil {\n http.Error(w, \"Invalid token\", http.StatusUnauthorized)\n return\n }\n \n // Check authorization\n if !hasPermission(claims.UserID, r.URL.Path, r.Method) {\n http.Error(w, \"Forbidden\", http.StatusForbidden)\n return\n }\n \n data, err := getUserData(claims.UserID)\n if err != nil {\n http.Error(w, \"User not found\", http.StatusNotFound)\n return\n }\n \n // Filter sensitive data\n safeData := filterSensitiveFields(data)\n \n w.Header().Set(\"Content-Type\", \"application/json\")\n json.NewEncoder(w).Encode(safeData)\n}\n\nfunc validateToken(tokenString string) (*Claims, error) {\n token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {\n if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {\n return nil, fmt.Errorf(\"unexpected signing method: %v\", token.Header[\"alg\"])\n }\n return []byte(os.Getenv(\"JWT_SECRET\")), nil\n })\n \n if err != nil {\n return nil, err\n }\n \n if claims, ok := token.Claims.(*Claims); ok && token.Valid {\n return claims, nil\n }\n \n return nil, fmt.Errorf(\"invalid token\")\n}"}
{"type": "debugging", "input_code": "class Database:\n def __init__(self):\n self.connections = []\n \n def query(self, sql):\n conn = self.create_connection()\n self.connections.append(conn)\n cursor = conn.cursor()\n cursor.execute(sql)\n return cursor.fetchall()", "analysis": "1. Database connections never closed causing resource leaks.\n2. SQL injection vulnerability from raw SQL execution.\n3. No connection pooling or reuse.\n4. Unbounded connection list growth.\n5. No error handling for connection failures.", "findings": [{"issue": "Resource Leak", "severity": "HIGH", "location": "unclosed connections", "cwe": "CWE-772"}, {"issue": "SQL Injection", "severity": "CRITICAL", "location": "execute(sql)\",\"cwe\":\"CWE-89"}, {"issue": "Missing Connection Pooling", "severity": "MEDIUM", "location": "creating new connections", "cwe": "CWE-407"}, {"issue": "Unbounded Resource Growth", "severity": "HIGH", "location": "connections list", "cwe": "CWE-400"}], "fix": "import psycopg2\nfrom psycopg2 import pool, sql\n\nclass Database:\n def __init__(self, min_conn=1, max_conn=10):\n self.connection_pool = psycopg2.pool.SimpleConnectionPool(\n min_conn, max_conn,\n host=os.getenv('DB_HOST'),\n database=os.getenv('DB_NAME'),\n user=os.getenv('DB_USER'),\n password=os.getenv('DB_PASSWORD'),\n connect_timeout=5\n )\n \n def query(self, query: str, params: tuple = None):\n conn = None\n cursor = None\n try:\n conn = self.connection_pool.getconn()\n cursor = conn.cursor()\n \n # Use parameterized queries\n cursor.execute(query, params)\n \n # Return results with column names\n columns = [desc[0] for desc in cursor.description]\n results = [dict(zip(columns, row)) for row in cursor.fetchall()]\n \n return results\n \n except psycopg2.Error as e:\n logger.error(f\"Database query error: {e}\")\n raise DatabaseError(f\"Query failed: {e}\")\n \n finally:\n if cursor:\n cursor.close()\n if conn:\n self.connection_pool.putconn(conn)\n \n def __del__(self):\n if hasattr(self, 'connection_pool'):\n self.connection_pool.closeall()\n \n def execute(self, query: str, params: tuple = None) -> int:\n \"\"\"Execute INSERT/UPDATE/DELETE and return affected rows\"\"\"\n conn = None\n cursor = None\n try:\n conn = self.connection_pool.getconn()\n cursor = conn.cursor()\n cursor.execute(query, params)\n conn.commit()\n return cursor.rowcount\n \n except psycopg2.Error as e:\n if conn:\n conn.rollback()\n logger.error(f\"Database execute error: {e}\")\n raise DatabaseError(f\"Execute failed: {e}\")\n \n finally:\n if cursor:\n cursor.close()\n if conn:\n self.connection_pool.putconn(conn)"}
{"type": "code_review", "input_code": "const https = require('https');\n\nfunction fetchAPI(url) {\n return new Promise((resolve, reject) => {\n https.get(url, (res) => {\n let data = '';\n res.on('data', (chunk) => {\n data += chunk;\n });\n res.on('end', () => {\n resolve(JSON.parse(data));\n });\n }).on('error', reject);\n });\n}", "analysis": "1. No SSL/TLS certificate validation allows MITM attacks.\n2. No URL validation allows arbitrary URL requests (SSRF).\n3. No timeout on requests can cause hanging.\n4. No response size limits can exhaust memory.\n5. Missing error handling for JSON parsing.", "findings": [{"issue": "Missing SSL Verification", "severity": "HIGH", "location": "https.get default options", "cwe": "CWE-295"}, {"issue": "SSRF Vulnerability", "severity": "CRITICAL", "location": "unvalidated URL", "cwe": "CWE-918"}, {"issue": "Denial of Service", "severity": "MEDIUM", "location": "no timeout", "cwe": "CWE-400"}, {"issue": "Memory Exhaustion", "severity": "MEDIUM", "location": "unbounded response", "cwe": "CWE-400"}, {"issue": "Missing Error Handling", "severity": "LOW", "location": "JSON.parse", "cwe": "CWE-390"}], "fix": "const https = require('https');\nconst { URL } = require('url');\n\nfunction fetchAPI(url, options = {}) {\n return new Promise((resolve, reject) => {\n // Validate URL\n let parsedUrl;\n try {\n parsedUrl = new URL(url);\n } catch (err) {\n return reject(new Error('Invalid URL'));\n }\n \n // Only allow HTTPS\n if (parsedUrl.protocol !== 'https:') {\n return reject(new Error('Only HTTPS URLs are allowed'));\n }\n \n // Whitelist allowed domains if needed\n // const allowedDomains = ['api.example.com', 'cdn.example.com'];\n // if (!allowedDomains.includes(parsedUrl.hostname)) {\n // return reject(new Error('Domain not allowed'));\n // }\n \n const requestOptions = {\n ...options,\n timeout: options.timeout || 10000,\n // Enable certificate validation\n rejectUnauthorized: true,\n // Limit response size\n headers: {\n 'User-Agent': 'MyApp/1.0',\n ...options.headers\n }\n };\n \n const req = https.get(url, requestOptions, (res) => {\n // Check content type\n const contentType = res.headers['content-type'];\n if (!contentType.includes('application/json')) {\n return reject(new Error('Expected JSON response'));\n }\n \n // Check content length\n const contentLength = parseInt(res.headers['content-length'], 10);\n const MAX_SIZE = 10 * 1024 * 1024; // 10MB\n if (contentLength > MAX_SIZE) {\n return reject(new Error('Response too large'));\n }\n \n let data = '';\n let receivedSize = 0;\n \n res.on('data', (chunk) => {\n receivedSize += chunk.length;\n if (receivedSize > MAX_SIZE) {\n req.destroy();\n return reject(new Error('Response size exceeded'));\n }\n data += chunk;\n });\n \n res.on('end', () => {\n try {\n const result = JSON.parse(data);\n resolve(result);\n } catch (err) {\n reject(new Error('Invalid JSON response'));\n }\n });\n });\n \n req.on('timeout', () => {\n req.destroy();\n reject(new Error('Request timeout'));\n });\n \n req.on('error', (err) => {\n reject(err);\n });\n });\n}"}
{"type": "debugging", "input_code": "func processFile(path string) error {\n file, err := os.Open(path)\n if err != nil {\n return err\n }\n \n scanner := bufio.NewScanner(file)\n for scanner.Scan() {\n processLine(scanner.Text())\n }\n \n return nil\n}", "analysis": "1. File never closed causing resource leak.\n2. No path validation allows accessing arbitrary files.\n3. No error handling for scanner errors.\n4. processLine error not handled.\n5. No size limit on file processing.", "findings": [{"issue": "Resource Leak", "severity": "HIGH", "location": "file not closed", "cwe": "CWE-772"}, {"issue": "Path Traversal", "severity": "CRITICAL", "location": "unvalidated path", "cwe": "CWE-22"}, {"issue": "Missing Error Handling", "severity": "MEDIUM", "location": "scanner.Err()", "cwe": "CWE-390"}, {"issue": "Unbounded Processing", "severity": "MEDIUM", "location": "no file size limit", "cwe": "CWE-400"}], "fix": "import (\n \"bufio\"\n \"errors\"\n \"os\"\n \"path/filepath\"\n \"strings\"\n)\n\nfunc processFile(path string) error {\n // Validate and sanitize path\n cleanPath := filepath.Clean(path)\n if strings.ContainsAny(cleanPath, \"\\x00\") {\n return errors.New(\"invalid path: null byte detected\")\n }\n \n // Restrict to allowed directory\n baseDir := \"/var/app/data\"\n absPath, err := filepath.Abs(cleanPath)\n if err != nil {\n return fmt.Errorf(\"invalid path: %w\", err)\n }\n \n if !strings.HasPrefix(absPath, baseDir) {\n return errors.New(\"access denied: path outside allowed directory\")\n }\n \n // Check file size\n info, err := os.Stat(absPath)\n if err != nil {\n return fmt.Errorf(\"file stat error: %w\", err)\n }\n \n const maxSize = 100 * 1024 * 1024 // 100MB\n if info.Size() > maxSize {\n return errors.New(\"file too large\")\n }\n \n file, err := os.Open(absPath)\n if err != nil {\n return fmt.Errorf(\"failed to open file: %w\", err)\n }\n defer file.Close()\n \n scanner := bufio.NewScanner(file)\n // Increase buffer size for long lines\n buf := make([]byte, 0, 64*1024)\n scanner.Buffer(buf, 1024*1024)\n \n lineNum := 0\n for scanner.Scan() {\n lineNum++\n if err := processLine(scanner.Text()); err != nil {\n return fmt.Errorf(\"error processing line %d: %w\", lineNum, err)\n }\n }\n \n if err := scanner.Err(); err != nil {\n return fmt.Errorf(\"scanner error: %w\", err)\n }\n \n return nil\n}\n\nfunc processLine(line string) error {\n // Process line with error handling\n return nil\n}"}
{"type": "code_review", "input_code": "def generate_report(user_id):\n query = f\"SELECT * FROM orders WHERE user_id = {user_id}\"\n orders = db.execute(query)\n \n report = []\n for order in orders:\n report.append({\n 'id': order['id'],\n 'total': order['total'],\n 'items': order['items']\n })\n \n return json.dumps(report)", "analysis": "1. SQL injection through string interpolation in query.\n2. No authorization check for user data access.\n3. Unbounded query results can exhaust memory.\n4. Missing input validation for user_id.\n5. Sensitive order data exposed without filtering.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "f-string query", "cwe": "CWE-89"}, {"issue": "Missing Authorization", "severity": "HIGH", "location": "no permission check", "cwe": "CWE-285"}, {"issue": "Memory Exhaustion", "severity": "MEDIUM", "location": "unbounded results", "cwe": "CWE-400"}, {"issue": "Missing Input Validation", "severity": "MEDIUM", "location": "user_id parameter", "cwe": "CWE-20"}], "fix": "def generate_report(user_id, requesting_user):\n # Validate input\n try:\n user_id = int(user_id)\n if user_id <= 0:\n raise ValueError(\"Invalid user ID\")\n except (ValueError, TypeError):\n raise ValueError(\"Invalid user ID format\")\n \n # Authorization check\n if requesting_user.id != user_id and not requesting_user.is_admin:\n raise PermissionError(\"Access denied\")\n \n # Limit results\n query = \"\"\"\n SELECT order_id, total, item_count, created_at \n FROM orders \n WHERE user_id = %s \n ORDER BY created_at DESC \n LIMIT 1000\n \"\"\"\n \n try:\n orders = db.execute(query, (user_id,))\n except DatabaseError as e:\n logger.error(f\"Database error: {e}\")\n raise\n \n # Filter sensitive data\n report = []\n for order in orders:\n report.append({\n 'id': order['order_id'],\n 'total': float(order['total']),\n 'item_count': order['item_count'],\n 'date': order['created_at'].isoformat()\n })\n \n return json.dumps(report)"}
{"type": "debugging", "input_code": "import multiprocessing\n\ndef process_item(item):\n return item * 2\n\ndef batch_process(items):\n pool = multiprocessing.Pool()\n results = pool.map(process_item, items)\n return results", "analysis": "1. Process pool never closed causing resource leak.\n2. No limit on pool size can exhaust system resources.\n3. No error handling for process failures.\n4. Items not validated can cause failures.\n5. Missing context manager pattern.", "findings": [{"issue": "Resource Leak", "severity": "HIGH", "location": "unclosed pool", "cwe": "CWE-772"}, {"issue": "Unbounded Resource Usage", "severity": "MEDIUM", "location": "unlimited pool size", "cwe": "CWE-400"}, {"issue": "Missing Error Handling", "severity": "LOW", "location": "process_item failures", "cwe": "CWE-390"}, {"issue": "Missing Input Validation", "severity": "MEDIUM", "location": "items parameter", "cwe": "CWE-20"}], "fix": "import multiprocessing\nfrom concurrent.futures import ProcessPoolExecutor, as_completed\nimport logging\n\ndef process_item(item):\n \"\"\"Process a single item with error handling\"\"\"\n try:\n if not isinstance(item, (int, float)):\n raise TypeError(f\"Expected number, got {type(item)}\")\n \n if item < 0:\n raise ValueError(f\"Item must be non-negative, got {item}\")\n \n return item * 2\n \n except Exception as e:\n logging.error(f\"Error processing item {item}: {e}\")\n raise\n\ndef batch_process(items, max_workers=None):\n \"\"\"\n Process items in parallel with proper resource management.\n \n Args:\n items: Iterable of items to process\n max_workers: Maximum number of worker processes (default: CPU count)\n \n Returns:\n List of results in same order as input\n \n Raises:\n ValueError: If items is invalid or processing fails\n \"\"\"\n if not items:\n return []\n \n if len(items) > 100000:\n raise ValueError(\"Too many items to process\")\n \n # Default to CPU count, but cap at reasonable limit\n if max_workers is None:\n max_workers = min(multiprocessing.cpu_count(), 16)\n \n results = []\n errors = []\n \n with ProcessPoolExecutor(max_workers=max_workers) as executor:\n # Submit all tasks\n future_to_item = {\n executor.submit(process_item, item): item \n for item in items\n }\n \n # Collect results as they complete\n for future in as_completed(future_to_item):\n item = future_to_item[future]\n try:\n result = future.result(timeout=30)\n results.append((item, result))\n except Exception as e:\n errors.append((item, str(e)))\n logging.error(f\"Failed to process item {item}: {e}\")\n \n if errors:\n raise ValueError(f\"Failed to process {len(errors)} items: {errors[:5]}\")\n \n # Return results in original order\n result_map = dict(results)\n return [result_map[item] for item in items]"}
{"type": "code_review", "input_code": "func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {\n file, header, err := r.FormFile(\"file\")\n if err != nil {\n return\n }\n defer file.Close()\n \n filename := header.Filename\n out, err := os.Create(\"/uploads/\" + filename)\n if err != nil {\n return\n }\n defer out.Close()\n \n io.Copy(out, file)\n fmt.Fprintf(w, \"Uploaded %s\", filename)\n}", "analysis": "1. Filename not validated allowing path traversal attacks. 2. No file type validation allows malicious uploads. 3. No file size limits can exhaust disk space. 4. No virus scanning or content validation.", "findings": [{"issue": "Path Traversal", "severity": "CRITICAL", "location": "header.Filename", "cwe": "CWE-22"}, {"issue": "Unrestricted File Upload", "severity": "CRITICAL", "location": "no type validation", "cwe": "CWE-434"}], "fix": "func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {\n file, header, err := r.FormFile(\"file\")\n if err != nil {\n http.Error(w, \"Invalid file upload\", http.StatusBadRequest)\n return\n }\n defer file.Close()\n \n const maxSize = 10 * 1024 * 1024\n if header.Size > maxSize {\n http.Error(w, \"File too large\", http.StatusBadRequest)\n return\n }\n \n contentType := http.DetectContentType(buffer)\n allowedTypes := map[string]bool{\"image/jpeg\": true, \"image/png\": true}\n \n if !allowedTypes[contentType] {\n http.Error(w, \"Invalid file type\", http.StatusBadRequest)\n return\n }\n \n filename := fmt.Sprintf(\"%s%s\", uuid.New().String(), ext)\n filepath := filepath.Join(\"/var/app/uploads\", filename)\n \n out, err := os.Create(filepath)\n if err != nil {\n http.Error(w, \"Failed to create file\", http.StatusInternalServerError)\n return\n }\n defer out.Close()\n \n io.Copy(out, io.LimitReader(file, maxSize))\n fmt.Fprintf(w, \"Uploaded %s\", filename)\n}"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 1. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "debugging", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 2. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 3. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "debugging", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 4. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 5. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "debugging", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 6. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 7. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "debugging", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 8. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 9. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "debugging", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 10. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 11. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "debugging", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 12. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 13. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "debugging", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 14. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 15. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "debugging", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 16. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 17. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "debugging", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 18. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_function(user_input):\n query = f\"SELECT * FROM users WHERE name = '{user_input}'\"\n return db.execute(query)", "analysis": "1. SQL injection vulnerability through user input. Example 19. 2. No input validation performed. 3. Missing error handling. 4. No authentication checks.", "findings": [{"issue": "SQL Injection", "severity": "CRITICAL", "location": "query interpolation", "cwe": "CWE-89"}, {"issue": "Missing Input Validation", "severity": "HIGH", "location": "user_input parameter", "cwe": "CWE-20"}], "fix": "def secure_function(user_input):\n if not user_input or len(user_input) > 100:\n raise ValueError('Invalid input')\n \n query = 'SELECT * FROM users WHERE name = %s'\n return db.execute(query, (user_input,))"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}
{"type": "code_review", "input_code": "def vulnerable_func(x): return eval(x)", "analysis": "eval allows arbitrary code execution", "findings": [{"issue": "Code Injection", "severity": "CRITICAL", "cwe": "CWE-94"}], "fix": "def safe_func(x): return str(x)"}