vinith17 commited on
Commit
f63e772
Β·
1 Parent(s): 748fdb2

feat: complete 30-rule official bug engine (R-N1..R-L5) per hackathon spec

Browse files
Files changed (1) hide show
  1. main.py +541 -419
main.py CHANGED
@@ -1,11 +1,12 @@
1
  """
2
- CodeBug FastAPI server with comprehensive code review and training endpoints.
 
3
  """
4
 
5
  from fastapi import FastAPI, Request, HTTPException
6
  from fastapi.responses import HTMLResponse, JSONResponse
7
  from pydantic import BaseModel
8
- import os, json, re, logging
9
  from openenv.core.env_server import create_fastapi_app
10
  from environment import CodeBugEnvironment
11
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
@@ -24,14 +25,15 @@ HAS_LLM = _AGENT_IMPORTED and (_HAS_ANTHROPIC or _HAS_OPENAI)
24
 
25
  logger = logging.getLogger(__name__)
26
 
27
- # Create the OpenEnv app (has /ws, /reset, /step, /state, /health, etc.)
28
  openenv_app = create_fastapi_app(CodeBugEnvironment, CodeReviewAction, CodeReviewObservation)
29
 
30
- # Create a wrapper FastAPI app (takes precedence for /api/* routes)
31
  app = FastAPI(title="CodeBug API", version="2.0")
32
 
 
33
  # ========================================================================
34
- # POST /api/train - Run RL training
35
  # ========================================================================
36
  class TrainRequest(BaseModel):
37
  episodes: int = 5
@@ -43,7 +45,6 @@ async def run_real_training(body: TrainRequest):
43
  stats = run_training(num_episodes=body.episodes, verbose=False)
44
  return {"status": "ok", "stats": stats}
45
  except Exception as e:
46
- import traceback
47
  logger.error(f"Training failed: {e}\n{traceback.format_exc()}")
48
  return JSONResponse(
49
  status_code=500,
@@ -52,7 +53,7 @@ async def run_real_training(body: TrainRequest):
52
 
53
 
54
  # ========================================================================
55
- # POST /api/review - Analyze code for bugs
56
  # ========================================================================
57
  class ReviewRequest(BaseModel):
58
  code: str
@@ -61,35 +62,31 @@ class ReviewRequest(BaseModel):
61
 
62
  @app.post("/api/review")
63
  async def review_code(request: ReviewRequest):
64
- """Analyze code and return ALL bug findings with confidence scores"""
65
  try:
66
  code = request.code.strip()
67
  lang = request.language.lower().strip()
68
-
69
- # Validation
70
  if not code:
71
  raise HTTPException(status_code=400, detail="Code cannot be empty")
72
  if not lang:
73
  raise HTTPException(status_code=400, detail="Language must be specified")
74
  if len(code) > 5000:
75
  raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
76
-
77
  supported_langs = ['python', 'javascript', 'typescript', 'java', 'go', 'cpp', 'c++']
78
  if lang not in supported_langs:
79
  raise HTTPException(
80
  status_code=400,
81
  detail=f"Language '{lang}' not supported. Supported: {', '.join(supported_langs)}"
82
  )
83
-
84
- # Analyze code
85
  logger.info(f"Analyzing {lang} code ({len(code)} chars)...")
86
  if HAS_LLM:
87
- results = analyze_code_with_llm(code, lang)
88
  else:
89
- logger.warning("LLM not available, using fallback analysis")
90
  results = analyze_code_comprehensively(code, lang)
91
-
92
- # Build response
93
  response = {
94
  "bugs_found": len(results),
95
  "bugs": results,
@@ -98,486 +95,616 @@ async def review_code(request: ReviewRequest):
98
  "language": lang,
99
  "code_length": len(code),
100
  "lines_of_code": len(code.split('\n')),
101
- "average_confidence": round(sum(b.get("confidence", 0.5) for b in results) / max(len(results), 1), 2) if results else 1.0
 
 
 
102
  }
103
  }
104
-
105
  if not results:
106
  response["primary_bug"] = {
107
  "type": "approve",
 
108
  "category": "style",
109
  "severity": 1,
110
  "line_hint": None,
111
- "comment": "No obvious bugs detected.",
112
  "fix": "",
113
  "confidence": 1.0
114
  }
115
-
116
- if request.export_format == 'json':
117
- response['export_url'] = '/api/export'
118
-
119
- logger.info(f"Returned {len(results)} bugs for {lang}")
120
  return response
121
-
122
  except HTTPException:
123
  raise
124
  except Exception as e:
125
- import traceback
126
  error_trace = traceback.format_exc()
127
  logger.error(f"Review endpoint failed: {e}\n{error_trace}")
128
  return JSONResponse(
129
  status_code=500,
130
- content={
131
- "error": f"Analysis failed: {str(e)}",
132
- "details": error_trace[:500]
133
- }
134
  )
135
 
136
 
137
  # ========================================================================
138
- # Helper functions for code analysis
139
  # ========================================================================
140
-
141
- def analyze_code_with_llm(code: str, lang: str) -> list:
142
- """Use LLM-powered agent.review() to analyze code.
143
- Short-circuits to pattern analysis if no API keys are configured."""
144
  if not HAS_LLM:
145
- logger.info("No LLM API keys configured β€” using pattern analysis.")
146
  return analyze_code_comprehensively(code, lang)
147
  try:
148
  bugs = agent_review(code)
149
  if not isinstance(bugs, list):
150
  bugs = []
151
- for bug in bugs:
152
- if "languages" not in bug:
153
- bug["languages"] = [lang]
154
  bugs.sort(key=lambda x: (x.get('severity', 0), x.get('confidence', 0)), reverse=True)
155
- logger.info(f"LLM found {len(bugs)} bugs in {lang} code")
156
  return bugs
157
  except Exception as e:
158
- logger.warning(f"LLM analysis failed ({type(e).__name__}: {e}). Using fallback analysis.")
159
  return analyze_code_comprehensively(code, lang)
160
 
161
- def _make_bug(category, severity, line_hint, comment, fix, confidence, lang_list):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  return {
163
  "type": "bug",
 
164
  "category": category,
165
  "severity": severity,
166
  "line_hint": line_hint,
167
  "comment": comment,
168
  "fix": fix,
169
  "confidence": confidence,
170
- "languages": lang_list,
171
  }
172
 
173
 
174
- def _find_line(code: str, pattern) -> int | None:
175
- """Return 1-indexed line number for the first regex match, or None."""
176
- for i, line in enumerate(code.splitlines(), 1):
177
- if re.search(pattern, line, re.I):
178
- return i
179
- return None
180
-
181
-
182
  def analyze_code_comprehensively(code: str, lang: str) -> list:
183
  """
184
- Exhaustive pattern-based bug detector.
185
- Runs ALL rules in a single pass and returns every bug found.
186
- Covers: security, logic, style, concurrency, resource management.
187
  """
188
  bugs = []
189
- ALL_LANGS = ["python", "javascript", "typescript", "java", "go", "cpp"]
190
-
191
- # ── SECURITY ──────────────────────────────────────────────────────────
192
-
193
- # 1. SQL Injection via f-string / concatenation
194
- if re.search(r'(f["\'].*?\{.*?\}.*?(SELECT|INSERT|DELETE|UPDATE|WHERE)|'
195
- r'["\'].*?SELECT.*?\+.*?["\'])', code, re.I | re.S):
196
- ln = _find_line(code, r'(SELECT|INSERT|DELETE|UPDATE|WHERE)')
197
- bugs.append(_make_bug(
198
- "security", 5, ln,
199
- "SQL Injection: user input interpolated directly into SQL query via f-string or concatenation.",
200
- "Use parameterized queries:\n cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
201
- 0.96, ["python", "javascript", "typescript", "java"]
202
- ))
 
 
 
 
 
 
 
 
 
203
 
204
- # 2. Hardcoded passwords / credentials
205
- if re.search(r'(password|passwd|pwd|db_pass|secret)\s*[=:]\s*["\'][^"\']{4,}["\']', code, re.I):
206
- ln = _find_line(code, r'(password|passwd|pwd|db_pass|secret)\s*[=:]')
207
- bugs.append(_make_bug(
208
- "security", 5, ln,
209
- "Hardcoded credential: plaintext password stored directly in source code.",
210
- "Read from environment:\n password = os.environ.get('DB_PASSWORD')\n # Never hardcode secrets",
211
- 0.97, ALL_LANGS
 
 
 
 
 
 
212
  ))
213
 
214
- # 3. Hardcoded API key / token / secret key
215
- if re.search(r'(api_key|apikey|access_key|secret_key|auth_token|bearer|private_key)'
216
- r'\s*[=:]\s*["\'][A-Za-z0-9_\-\.]{8,}["\']', code, re.I):
217
- ln = _find_line(code, r'(api_key|apikey|access_key|secret_key|auth_token|bearer|private_key)')
218
- bugs.append(_make_bug(
219
- "security", 5, ln,
220
- "Hardcoded API key/token/secret detected. Exposed in version control.",
221
- "Move to environment variable:\n api_key = os.environ.get('API_KEY')\n if not api_key: raise ValueError('API_KEY not set')",
222
- 0.96, ALL_LANGS
223
  ))
224
 
225
- # 4. Arbitrary code execution
226
- if re.search(r'\b(eval|exec)\s*\(', code, re.I):
227
- ln = _find_line(code, r'\b(eval|exec)\s*\(')
228
- bugs.append(_make_bug(
229
- "security", 5, ln,
230
- "Arbitrary code execution: eval()/exec() with untrusted input enables Remote Code Execution.",
231
- "Use safe alternatives:\n # Python: ast.literal_eval() for literals\n # JS: JSON.parse() for data\n # Never pass user input to eval/exec",
232
- 0.99, ["python", "javascript", "typescript"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  ))
234
 
235
- # 5. Insecure deserialization
236
- if re.search(r'pickle\.(load|loads|Unpickler)|yaml\.load\s*\([^)]*\)(?!.*Loader=yaml\.SafeLoader)', code):
237
- ln = _find_line(code, r'pickle\.(load|loads)|yaml\.load')
238
- bugs.append(_make_bug(
239
- "security", 5, ln,
240
- "Insecure deserialization: pickle/yaml.load with untrusted data enables arbitrary code execution.",
241
- "# pickle: avoid entirely for untrusted data\n"
242
- "# yaml: use yaml.safe_load(data) instead of yaml.load(data)",
243
- 0.98, ["python"]
 
 
 
 
 
244
  ))
245
 
246
- # 6. Command injection (shell=True / os.system)
247
- if re.search(r'os\.system\s*\(|subprocess\.(call|run|Popen)\s*\(.*shell\s*=\s*True', code, re.S):
248
- ln = _find_line(code, r'os\.system|shell\s*=\s*True')
249
- bugs.append(_make_bug(
250
- "security", 5, ln,
251
- "Command injection risk: shell=True or os.system() with user input allows arbitrary command execution.",
252
- "Use subprocess with a list and shell=False:\n"
253
- " subprocess.run(['ls', '-la'], shell=False, capture_output=True)",
254
- 0.95, ["python"]
 
 
 
 
 
 
 
 
 
 
 
255
  ))
256
 
257
- # 7. Path traversal
258
- if re.search(r'open\s*\(\s*(request\.|f["\']|.*\+)', code, re.I):
259
- ln = _find_line(code, r'open\s*\(')
260
- bugs.append(_make_bug(
261
- "security", 4, ln,
262
- "Path traversal risk: file path constructed from user input without sanitisation.",
263
- "Validate and restrict paths:\n"
264
- " import pathlib\n"
265
- " safe = pathlib.Path('/safe/base').resolve() / user_input\n"
266
- " assert str(safe).startswith('/safe/base')",
267
- 0.80, ["python", "javascript", "typescript"]
 
 
 
268
  ))
269
 
270
- # 8. Weak hashing algorithm
271
- if re.search(r'\b(md5|sha1)\b', code, re.I) and re.search(r'(password|passwd|pwd|hash)', code, re.I):
272
- ln = _find_line(code, r'\b(md5|sha1)\b')
273
- bugs.append(_make_bug(
274
- "security", 4, ln,
275
- "Weak hashing: MD5/SHA-1 are cryptographically broken and must not be used for passwords.",
276
- "Use bcrypt or Argon2:\n"
277
- " import bcrypt\n"
278
- " hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())",
279
- 0.94, ALL_LANGS
 
 
 
 
 
280
  ))
281
 
282
- # 9. Debug mode left on
283
- if re.search(r'(app\.run|debug)\s*[=(]\s*True', code, re.I):
284
- ln = _find_line(code, r'debug\s*[=(]\s*True')
285
- bugs.append(_make_bug(
286
- "security", 3, ln,
287
- "Debug mode enabled in production: exposes stack traces, interactive debugger, and sensitive data.",
288
- "Disable debug before deploying:\n"
289
- " debug = os.environ.get('DEBUG', 'false').lower() == 'true'\n"
290
- " app.run(debug=debug)",
291
- 0.92, ["python", "javascript"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  ))
293
 
294
- # ── LOGIC ───────────────────────────────────────────────────────────
295
-
296
- # 10. Off-by-one: range(len(x) - 1)
297
- if re.search(r'range\s*\(\s*len\s*\([^)]+\)\s*-\s*1\s*\)', code):
298
- ln = _find_line(code, r'range\s*\(\s*len')
299
- bugs.append(_make_bug(
300
- "logic", 3, ln,
301
- "Off-by-one error: range(len(x) - 1) skips the last element of the sequence.",
302
- "Fix: use range(len(arr)) to include all elements\n"
303
- " for i in range(len(numbers)): # not range(len(numbers)-1)\n"
304
- " # Or better: for item in numbers:",
305
- 0.88, ALL_LANGS
 
 
 
 
 
 
 
306
  ))
307
 
308
- # 11. Mutable default argument
309
- if lang in ('python',) and re.search(r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\}|set\(\))', code):
310
- ln = _find_line(code, r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\})')
311
- bugs.append(_make_bug(
312
- "logic", 4, ln,
313
- "Mutable default argument: the list/dict is shared across all calls β€” state leaks between invocations.",
314
- "Use None as sentinel:\n"
315
- " def func(items=None):\n"
316
- " if items is None:\n"
317
- " items = []",
318
- 0.98, ["python"]
 
 
 
 
 
 
319
  ))
320
 
321
- # 12. Division without zero guard
322
- if re.search(r'\w+\s*/\s*\w+', code) and not re.search(r'if.*!=\s*0|if.*> 0|try', code):
323
- ln = _find_line(code, r'\w+\s*/\s*\w+(?!\s*/)')
 
324
  if ln:
325
- bugs.append(_make_bug(
326
- "logic", 3, ln,
327
- "Potential division by zero: denominator is not checked before division.",
328
- "Guard the division:\n"
329
- " if denominator != 0:\n"
330
- " result = numerator / denominator\n"
331
- " else:\n"
332
- " result = 0 # or raise ValueError",
333
- 0.75, ALL_LANGS
334
  ))
335
 
336
- # 13. Strict > / < where edge case matters (balance/transfer pattern)
337
- if re.search(r'(balance|amount|total|price|quota)\s*[><!]=?\s*\w+', code, re.I) \
338
- and not re.search(r'>=|<=', code):
339
- ln = _find_line(code, r'(balance|amount|total|price|quota)\s*[><]')
340
- if ln:
341
- bugs.append(_make_bug(
342
- "logic", 3, ln,
343
- "Edge-case boundary bug: strict > or < comparison may miss the equality case (e.g., exact balance transfer).",
344
- "Use >= or <= to include the boundary:\n"
345
- " if account.balance >= amount: # not >",
346
- 0.80, ALL_LANGS
347
- ))
 
 
 
 
 
 
 
 
348
 
349
- # 14. Return value of function never used (assignment to _)
350
- if re.search(r'\bNone\s*==\s*\w+|\w+\s*==\s*None\b', code) \
351
- and not re.search(r'\bis\s+None\b|\bis\s+not\s+None\b', code):
352
- ln = _find_line(code, r'\bNone\s*==|\w+\s*==\s*None')
353
  if ln:
354
- bugs.append(_make_bug(
355
- "logic", 2, ln,
356
- "None comparison using == instead of 'is': PEP 8 and Python docs require 'is None' / 'is not None'.",
357
- "Fix:\n if value is None: # correct\n if value is not None: # correct\n # NOT: if value == None",
358
- 0.95, ["python"]
 
 
 
 
359
  ))
360
 
361
- # 15. Infinite loop risk (while True without break/return)
362
- wt = re.search(r'while\s+True\s*:', code)
363
- if wt and not re.search(r'\bbreak\b|\breturn\b|\braise\b|\bsys\.exit\b', code):
364
- ln = _find_line(code, r'while\s+True\s*:')
365
- bugs.append(_make_bug(
366
- "logic", 4, ln,
367
- "Infinite loop: while True loop with no break, return, or raise β€” program will hang.",
368
- "Add an exit condition:\n"
369
- " while True:\n"
370
- " # ... your logic ...\n"
371
- " if exit_condition:\n"
372
- " break",
373
- 0.87, ALL_LANGS
 
 
 
 
 
 
 
374
  ))
375
 
376
- # 16. Unchecked index access on potentially empty list
377
- if re.search(r'\w+\[\s*0\s*\]|\w+\[\s*-1\s*\]', code) \
378
- and not re.search(r'if\s+\w+|len\s*\(', code):
379
- ln = _find_line(code, r'\w+\[\s*0\s*\]|\w+\[\s*-1\s*\]')
380
- if ln:
381
- bugs.append(_make_bug(
382
- "logic", 3, ln,
383
- "Unchecked index access: accessing index [0] or [-1] on a potentially empty collection causes IndexError.",
384
- "Guard before accessing:\n"
385
- " if items:\n"
386
- " first = items[0]",
387
- 0.72, ALL_LANGS
388
- ))
 
 
 
 
389
 
390
- # 17. Bare except (swallows all errors silently)
391
- if re.search(r'except\s*:', code) or re.search(r'except\s+Exception\s*:', code):
392
- ln = _find_line(code, r'except\s*:|except\s+Exception\s*:')
393
- bugs.append(_make_bug(
394
- "logic", 3, ln,
395
- "Bare except clause: catches and silences ALL exceptions including SystemExit and KeyboardInterrupt.",
396
- "Catch specific exceptions:\n"
397
- " try:\n"
398
- " risky_call()\n"
399
- " except ValueError as e:\n"
400
- " logger.error('Bad value: %s', e)\n"
401
- " except IOError as e:\n"
402
- " logger.error('IO error: %s', e)",
403
- 0.93, ["python"]
404
  ))
405
 
406
- # 18. Missing return in all branches
407
- if lang == "python" and re.search(r'def\s+\w+', code):
408
- fn_body = re.split(r'def\s+\w+[^:]*:', code)
409
- for body in fn_body[1:]:
410
- indent_lines = [l for l in body.splitlines() if l.strip()]
411
- has_if = any(re.match(r'\s+if\b', l) for l in indent_lines)
412
- has_return = re.search(r'\breturn\b', body)
413
- has_else_return = re.search(r'else:\s*\n\s+return', body)
414
- if has_if and has_return and not has_else_return:
415
- ln = _find_line(code, r'def\s+\w+')
416
- bugs.append(_make_bug(
417
- "logic", 2, ln,
418
- "Inconsistent return: function returns a value in some branches but falls through (returns None) in others.",
419
- "Ensure all branches return explicitly:\n"
420
- " def func(x):\n"
421
- " if x > 0:\n"
422
- " return x\n"
423
- " return 0 # explicit fallback",
424
- 0.70, ["python"]
425
- ))
426
- break
427
-
428
- # ── JAVASCRIPT / TYPESCRIPT SPECIFIC ────────────────────────────────
429
-
430
- if lang in ('javascript', 'typescript'):
431
- # 19. var instead of let/const
432
- if re.search(r'\bvar\s+\w+', code):
433
- ln = _find_line(code, r'\bvar\s+\w+')
434
- bugs.append(_make_bug(
435
- "style", 2, ln,
436
- "Deprecated var: function-scoped and hoisted variables cause subtle bugs. Use const or let.",
437
- "Replace:\n const name = value; // for constants\n let count = 0; // for reassignable values",
438
- 0.97, ["javascript", "typescript"]
439
- ))
440
 
441
- # 20. Loose equality (== instead of ===)
442
- if re.search(r'[^=!<>]==[^=]|[^=]!=[^=]', code):
443
- ln = _find_line(code, r'[^=!<>]==[^=]|[^=]!=[^=]')
444
- bugs.append(_make_bug(
445
- "logic", 3, ln,
446
- "Type coercion bug: == and != perform implicit type conversion. Use === and !== for strict equality.",
447
- "Replace == with ===:\n if (value === null) // strict\n if (count !== 0) // strict",
448
- 0.94, ["javascript", "typescript"]
449
- ))
 
 
 
 
450
 
451
- # 21. Async without await
452
- if re.search(r'async\s+function|async\s*\(', code) and not re.search(r'\bawait\b', code):
453
- ln = _find_line(code, r'async\s+function|async\s*\(')
454
- bugs.append(_make_bug(
455
- "logic", 3, ln,
456
- "async function without await: function is marked async but never awaits β€” returns an unwrapped Promise.",
457
- "Add await to async calls:\n async function getUser() {\n const user = await fetchUser(); // not fetchUser()\n return user;\n }",
458
- 0.85, ["javascript", "typescript"]
 
 
 
 
 
 
 
 
459
  ))
460
 
461
- # ── JAVA SPECIFIC ────────────────────────────────────────────────────
462
-
463
- if lang == 'java':
464
- # 22. NullPointerException risk
465
- if re.search(r'\w+\.equals\s*\(\s*["\']', code):
466
- ln = _find_line(code, r'\w+\.equals\s*\(\s*["\']')
467
- bugs.append(_make_bug(
468
- "logic", 3, ln,
469
- "NullPointerException risk: calling .equals() on a variable that might be null.",
470
- "Compare with literal on the left:\n if (\"expected\".equals(variable)) // null-safe",
471
- 0.91, ["java"]
472
- ))
473
 
474
- # 23. == for String comparison
475
- if re.search(r'String.*==|==.*String', code):
476
- ln = _find_line(code, r'String.*==|==.*String')
477
- bugs.append(_make_bug(
478
- "logic", 4, ln,
479
- "String identity comparison: == compares references, not content. Two equal strings may be different objects.",
480
- "Use .equals():\n if (str1.equals(str2)) // content comparison",
481
- 0.95, ["java"]
 
 
 
 
 
 
 
 
 
 
 
 
 
482
  ))
483
 
484
- # ── STYLE / QUALITY ──────────────────────────────────────────────────
485
-
486
- # 24. print() instead of logging (Python)
487
- if lang == 'python' and re.search(r'\bprint\s*\(', code) \
488
- and not re.search(r'import logging|logging\.(info|error|debug|warning)', code):
489
- ln = _find_line(code, r'\bprint\s*\(')
490
- bugs.append(_make_bug(
491
- "style", 1, ln,
492
- "print() in production code: use the logging module for structured, level-aware output.",
493
- "Replace print with logging:\n"
494
- " import logging\n"
495
- " logger = logging.getLogger(__name__)\n"
496
- " logger.info('message: %s', value)",
497
- 0.80, ["python"]
498
  ))
499
 
500
- # 25. TODO / FIXME left in code
501
- if re.search(r'\b(TODO|FIXME|HACK|XXX)\b', code, re.I):
502
- ln = _find_line(code, r'\b(TODO|FIXME|HACK|XXX)\b')
503
- bugs.append(_make_bug(
504
- "style", 1, ln,
505
- "Unresolved TODO/FIXME comment: technical debt marker left in production code.",
506
- "Resolve the TODO or create a tracked issue:\n"
507
- " # Before: # TODO: handle edge case\n"
508
- " # After: implement the fix and remove the comment",
509
- 0.99, ALL_LANGS
510
- ))
511
-
512
- # 26. Magic numbers
513
- if re.search(r'(?<!["\'\w])\b(?!0\b|1\b)[2-9]\d{2,}\b(?!["\'\w])', code) \
514
- and lang in ('python', 'javascript', 'typescript', 'java'):
515
- ln = _find_line(code, r'(?<!["\'\w])\b(?!0\b|1\b)[2-9]\d{2,}\b')
516
  if ln:
517
- bugs.append(_make_bug(
518
- "style", 1, ln,
519
- "Magic number: unexplained numeric literal reduces readability and maintainability.",
520
- "Define a named constant:\n"
521
- " MAX_RETRIES = 500\n"
522
- " TIMEOUT_MS = 3000",
523
- 0.70, ALL_LANGS
 
524
  ))
525
 
526
- # 27. Empty catch block
527
- if re.search(r'except.*:\s*\n\s*(pass|#)', code) or \
528
- re.search(r'catch\s*\([^)]*\)\s*\{\s*\}', code):
529
- ln = _find_line(code, r'except.*:\s*$|catch\s*\(')
530
- bugs.append(_make_bug(
531
- "logic", 3, ln,
532
- "Empty exception handler: errors are silently swallowed, making debugging impossible.",
533
- "At minimum log the exception:\n"
534
- " except Exception as e:\n"
535
- " logger.error('Unexpected error: %s', e, exc_info=True)\n"
536
- " raise # re-raise if you cannot handle it",
537
- 0.95, ALL_LANGS
 
 
 
 
 
 
 
538
  ))
539
 
540
- # 28. Resource leak (file opened but no context manager)
541
- if re.search(r'\bopen\s*\(', code) and not re.search(r'\bwith\s+open\b', code) and lang == 'python':
542
- ln = _find_line(code, r'\bopen\s*\(')
543
- bugs.append(_make_bug(
544
- "logic", 3, ln,
545
- "Resource leak: file opened without a 'with' statement β€” file may not be closed on exception.",
546
- "Use context manager:\n"
547
- " with open('file.txt', 'r') as f:\n"
548
- " data = f.read()\n"
549
- " # file is automatically closed",
550
- 0.93, ["python"]
 
 
 
 
551
  ))
552
 
553
- # 29. Deprecated Python 2 constructs
554
- if lang == 'python' and re.search(r'\bprint\s+[^(]|\bxrange\b|\breduce\s*\(|urllib2\b', code):
555
- ln = _find_line(code, r'\bxrange\b|\bprint\s+[^(]')
556
- if ln:
557
- bugs.append(_make_bug(
558
- "style", 2, ln,
559
- "Python 2 syntax: xrange(), print statement, and urllib2 do not exist in Python 3.",
560
- "Update to Python 3:\n"
561
- " range() instead of xrange()\n"
562
- " print() function\n"
563
- " urllib.request instead of urllib2",
564
- 0.99, ["python"]
565
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
566
 
567
- # 30. Concurrency: thread-unsafe global state mutation
568
- if re.search(r'global\s+\w+', code) and re.search(r'Thread|threading|asyncio', code):
569
- ln = _find_line(code, r'global\s+\w+')
570
- bugs.append(_make_bug(
571
- "logic", 4, ln,
572
- "Thread-unsafe global mutation: modifying global variables from multiple threads causes race conditions.",
573
- "Use threading.Lock() to protect shared state:\n"
574
- " _lock = threading.Lock()\n"
575
- " with _lock:\n"
576
- " global_counter += 1",
577
- 0.82, ["python", "java", "go", "cpp"]
 
 
 
 
578
  ))
579
 
580
- # Sort: highest severity first, then confidence
581
  bugs.sort(key=lambda b: (b["severity"], b["confidence"]), reverse=True)
582
  return bugs
583
 
@@ -592,52 +719,47 @@ def serve_frontend():
592
  try:
593
  with open(html_path, "r", encoding="utf-8") as f:
594
  return HTMLResponse(f.read())
595
- except:
596
  return HTMLResponse("<h1>CodeBug API Running.</h1><p>Visit /docs for API documentation.</p>")
597
 
598
 
599
  # ========================================================================
600
- # GET /api/health - Health check
601
  # ========================================================================
602
  @app.get("/api/health")
603
  async def health_check():
604
- """Health check endpoint"""
605
  return {
606
  "status": "ok",
607
  "version": "2.0",
608
- "supported_languages": ["python", "javascript", "typescript", "java", "go", "cpp"],
609
- "features": [
610
- "comprehensive_bug_detection",
611
- "confidence_scores",
612
- "multi_language_support",
613
- "export_json_reports"
 
 
614
  ],
615
- "api_endpoints": [
616
- "/api/review (POST) - Analyze code",
617
- "/api/train (POST) - Run training",
618
- "/api/health (GET) - This endpoint",
619
- "/api/stats (GET) - Usage statistics"
620
- ]
621
  }
622
 
623
 
624
  # ========================================================================
625
- # GET /api/stats - Usage statistics
626
  # ========================================================================
627
  @app.get("/api/stats")
628
  async def get_stats():
629
- """Return usage statistics"""
630
  return {
631
- "message": "Stats endpoint - tracks would be stored in session/DB",
632
- "supported_check_types": 30,
633
- "languages": 6,
634
- "security_checks": 12,
635
- "logic_checks": 8,
636
- "style_checks": 10
637
  }
638
 
639
 
640
  # ========================================================================
641
- # Mount OpenEnv app at /openenv prefix
642
  # ========================================================================
643
  app.mount("/openenv", openenv_app)
 
1
  """
2
+ CodeBug FastAPI server β€” Official 30-rule bug detection engine.
3
+ Rules: R-N1..R-N5 | R-C1..R-C5 | R-D1..R-D5 | R-S1..R-S5 | R-CF1..R-CF5 | R-L1..R-L5
4
  """
5
 
6
  from fastapi import FastAPI, Request, HTTPException
7
  from fastapi.responses import HTMLResponse, JSONResponse
8
  from pydantic import BaseModel
9
+ import os, re, logging, traceback
10
  from openenv.core.env_server import create_fastapi_app
11
  from environment import CodeBugEnvironment
12
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
 
25
 
26
  logger = logging.getLogger(__name__)
27
 
28
+ # Create the OpenEnv app
29
  openenv_app = create_fastapi_app(CodeBugEnvironment, CodeReviewAction, CodeReviewObservation)
30
 
31
+ # Main FastAPI app
32
  app = FastAPI(title="CodeBug API", version="2.0")
33
 
34
+
35
  # ========================================================================
36
+ # POST /api/train
37
  # ========================================================================
38
  class TrainRequest(BaseModel):
39
  episodes: int = 5
 
45
  stats = run_training(num_episodes=body.episodes, verbose=False)
46
  return {"status": "ok", "stats": stats}
47
  except Exception as e:
 
48
  logger.error(f"Training failed: {e}\n{traceback.format_exc()}")
49
  return JSONResponse(
50
  status_code=500,
 
53
 
54
 
55
  # ========================================================================
56
+ # POST /api/review
57
  # ========================================================================
58
  class ReviewRequest(BaseModel):
59
  code: str
 
62
 
63
  @app.post("/api/review")
64
  async def review_code(request: ReviewRequest):
65
+ """Analyze code and return ALL bug findings with rule IDs and confidence scores."""
66
  try:
67
  code = request.code.strip()
68
  lang = request.language.lower().strip()
69
+
 
70
  if not code:
71
  raise HTTPException(status_code=400, detail="Code cannot be empty")
72
  if not lang:
73
  raise HTTPException(status_code=400, detail="Language must be specified")
74
  if len(code) > 5000:
75
  raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
76
+
77
  supported_langs = ['python', 'javascript', 'typescript', 'java', 'go', 'cpp', 'c++']
78
  if lang not in supported_langs:
79
  raise HTTPException(
80
  status_code=400,
81
  detail=f"Language '{lang}' not supported. Supported: {', '.join(supported_langs)}"
82
  )
83
+
 
84
  logger.info(f"Analyzing {lang} code ({len(code)} chars)...")
85
  if HAS_LLM:
86
+ results = _analyze_with_llm(code, lang)
87
  else:
 
88
  results = analyze_code_comprehensively(code, lang)
89
+
 
90
  response = {
91
  "bugs_found": len(results),
92
  "bugs": results,
 
95
  "language": lang,
96
  "code_length": len(code),
97
  "lines_of_code": len(code.split('\n')),
98
+ "rules_engine": "30-rule official spec",
99
+ "average_confidence": round(
100
+ sum(b.get("confidence", 0.5) for b in results) / max(len(results), 1), 2
101
+ ) if results else 1.0
102
  }
103
  }
104
+
105
  if not results:
106
  response["primary_bug"] = {
107
  "type": "approve",
108
+ "rule_id": None,
109
  "category": "style",
110
  "severity": 1,
111
  "line_hint": None,
112
+ "comment": "No bugs detected by the 30-rule engine.",
113
  "fix": "",
114
  "confidence": 1.0
115
  }
116
+
117
+ logger.info(f"Found {len(results)} bugs in {lang} code")
 
 
 
118
  return response
119
+
120
  except HTTPException:
121
  raise
122
  except Exception as e:
 
123
  error_trace = traceback.format_exc()
124
  logger.error(f"Review endpoint failed: {e}\n{error_trace}")
125
  return JSONResponse(
126
  status_code=500,
127
+ content={"error": f"Analysis failed: {str(e)}", "details": error_trace[:500]}
 
 
 
128
  )
129
 
130
 
131
  # ========================================================================
132
+ # LLM wrapper
133
  # ========================================================================
134
+ def _analyze_with_llm(code: str, lang: str) -> list:
 
 
 
135
  if not HAS_LLM:
 
136
  return analyze_code_comprehensively(code, lang)
137
  try:
138
  bugs = agent_review(code)
139
  if not isinstance(bugs, list):
140
  bugs = []
 
 
 
141
  bugs.sort(key=lambda x: (x.get('severity', 0), x.get('confidence', 0)), reverse=True)
 
142
  return bugs
143
  except Exception as e:
144
+ logger.warning(f"LLM failed ({type(e).__name__}: {e}). Using pattern analysis.")
145
  return analyze_code_comprehensively(code, lang)
146
 
147
+
148
+ # ========================================================================
149
+ # OFFICIAL 30-RULE BUG ENGINE
150
+ # Spec: R-N1..R-N5 | R-C1..R-C5 | R-D1..R-D5 | R-S1..R-S5 | R-CF1..R-CF5 | R-L1..R-L5
151
+ # ========================================================================
152
+
153
+ def _fl(code: str, pattern: str, flags: int = re.I) -> int | None:
154
+ """Return 1-indexed line number of first regex match, or None."""
155
+ for i, line in enumerate(code.splitlines(), 1):
156
+ if re.search(pattern, line, flags):
157
+ return i
158
+ return None
159
+
160
+
161
+ def _bug(rule_id: str, category: str, severity: int, line_hint, comment: str, fix: str, confidence: float) -> dict:
162
  return {
163
  "type": "bug",
164
+ "rule_id": rule_id,
165
  "category": category,
166
  "severity": severity,
167
  "line_hint": line_hint,
168
  "comment": comment,
169
  "fix": fix,
170
  "confidence": confidence,
 
171
  }
172
 
173
 
 
 
 
 
 
 
 
 
174
  def analyze_code_comprehensively(code: str, lang: str) -> list:
175
  """
176
+ Official 30-rule bug detector. Every matching rule fires independently.
177
+ Multiple bugs can be returned for the same code snippet.
 
178
  """
179
  bugs = []
180
+ IS_JS = lang in ('javascript', 'typescript')
181
+ IS_PY = lang == 'python'
182
+
183
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
184
+ # CATEGORY 1 β€” API & Network
185
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
186
+
187
+ # R-N1 Β· Missing error handling on fetch
188
+ if IS_JS and re.search(r'\bfetch\s*\(', code):
189
+ has_catch = bool(re.search(r'\.catch\s*\(|try\s*\{', code))
190
+ has_status = bool(re.search(r'\.ok\b|\.status\b', code))
191
+ if not has_catch or not has_status:
192
+ ln = _fl(code, r'\bfetch\s*\(')
193
+ bugs.append(_bug(
194
+ "R-N1", "api_network", 4, ln,
195
+ "R-N1 Β· Missing error handling on fetch: fetch() does NOT throw on 4xx/5xx. "
196
+ "You must check response.ok and wrap in try/catch.",
197
+ "const res = await fetch(url);\n"
198
+ "if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`);\n"
199
+ "const data = await res.json();\n"
200
+ "// Always wrap in: try { ... } catch (err) { console.error(err); }",
201
+ 0.88
202
+ ))
203
 
204
+ # R-N2 Β· No timeout defined
205
+ if IS_JS and re.search(r'\bfetch\s*\(', code) \
206
+ and not re.search(r'AbortController|signal|timeout', code):
207
+ ln = _fl(code, r'\bfetch\s*\(')
208
+ bugs.append(_bug(
209
+ "R-N2", "api_network", 3, ln,
210
+ "R-N2 Β· No timeout defined: fetch() has no built-in timeout. "
211
+ "A hanging request blocks indefinitely and causes silent 500s.",
212
+ "const ctrl = new AbortController();\n"
213
+ "const tid = setTimeout(() => ctrl.abort(), 5000);\n"
214
+ "try {\n"
215
+ " const res = await fetch(url, { signal: ctrl.signal });\n"
216
+ "} finally { clearTimeout(tid); }",
217
+ 0.85
218
  ))
219
 
220
+ if IS_PY and re.search(r'requests\.(get|post|put|delete|patch)\s*\(', code) \
221
+ and not re.search(r'timeout\s*=', code):
222
+ ln = _fl(code, r'requests\.(get|post|put|delete|patch)\s*\(')
223
+ bugs.append(_bug(
224
+ "R-N2", "api_network", 3, ln,
225
+ "R-N2 Β· No timeout on requests call: without timeout the request can hang indefinitely.",
226
+ "response = requests.get(url, timeout=10) # always set timeout",
227
+ 0.90
 
228
  ))
229
 
230
+ # R-N3 Β· Route not registered
231
+ if IS_PY and re.search(r'@app\.(get|post|put|delete|patch)', code):
232
+ if not re.findall(r'@app\.(get|post|put|delete|patch)\s*\(\s*["\']([^"\']+)["\']', code):
233
+ ln = _fl(code, r'@app\.')
234
+ bugs.append(_bug(
235
+ "R-N3", "api_network", 4, ln,
236
+ "R-N3 Β· Route not registered: @app decorator found but route paths appear missing or malformed. "
237
+ "Ensure routes are registered on the exact app instance that uvicorn serves.",
238
+ "@app.post('/api/review') # route must be on the served app object\n"
239
+ "async def review(body: Body): ...\n"
240
+ "# Run: uvicorn main:app # 'app' must be the same object",
241
+ 0.72
242
+ ))
243
+
244
+ # R-N4 Β· CORS misconfiguration
245
+ if re.search(r'allow_origins\s*=\s*\[.*\*.*\]|Access-Control-Allow-Origin.*\*', code):
246
+ ln = _fl(code, r'allow_origins|Access-Control-Allow-Origin')
247
+ bugs.append(_bug(
248
+ "R-N4", "security", 4, ln,
249
+ "R-N4 Β· Overly permissive CORS: wildcard origin (*) on authenticated endpoints "
250
+ "is both a security issue and breaks browser credential policies.",
251
+ "app.add_middleware(CORSMiddleware,\n"
252
+ " allow_origins=['https://yourapp.com'], # explicit, not ['*']\n"
253
+ " allow_credentials=True,\n"
254
+ " allow_methods=['GET', 'POST'])",
255
+ 0.95
256
  ))
257
 
258
+ # R-N5 Β· Auth token not sent
259
+ if IS_JS and re.search(r'\bfetch\s*\(', code) \
260
+ and not re.search(r'Authorization|Bearer|headers.*token', code, re.I):
261
+ ln = _fl(code, r'\bfetch\s*\(')
262
+ bugs.append(_bug(
263
+ "R-N5", "security", 3, ln,
264
+ "R-N5 Β· Auth token not sent: fetch() call appears to be missing an Authorization header.",
265
+ "fetch(url, {\n"
266
+ " headers: {\n"
267
+ " 'Authorization': `Bearer ${token}`,\n"
268
+ " 'Content-Type': 'application/json'\n"
269
+ " }\n"
270
+ "});",
271
+ 0.70
272
  ))
273
 
274
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
275
+ # CATEGORY 2 β€” Runtime Crashes
276
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
277
+
278
+ # R-C1 Β· Unhandled exception in route handler
279
+ if IS_PY and re.search(r'@app\.(get|post|put|delete|patch)', code) \
280
+ and not re.search(r'try\s*:', code):
281
+ ln = _fl(code, r'@app\.(get|post|put|delete|patch)')
282
+ bugs.append(_bug(
283
+ "R-C1", "runtime", 4, ln,
284
+ "R-C1 Β· Unhandled exception in route: route handler has no try/except. "
285
+ "Any uncaught exception returns a raw 500 with traceback exposed to clients.",
286
+ "@app.post('/api/review')\n"
287
+ "async def review(body: ReviewRequest):\n"
288
+ " try:\n"
289
+ " return process(body)\n"
290
+ " except Exception as e:\n"
291
+ " logger.error('Review failed', exc_info=True)\n"
292
+ " raise HTTPException(status_code=500, detail='Internal error')",
293
+ 0.85
294
  ))
295
 
296
+ # R-C2 Β· Missing environment variable validation
297
+ if IS_PY and re.search(r'os\.environ\.get\(|os\.getenv\(', code) \
298
+ and not re.search(r'if not .*(key|token|secret|api)|sys\.exit|raise.*environ', code, re.I):
299
+ ln = _fl(code, r'os\.environ\.get|os\.getenv')
300
+ bugs.append(_bug(
301
+ "R-C2", "runtime", 4, ln,
302
+ "R-C2 Β· Missing env var validation: os.environ.get() returns None silently. "
303
+ "Missing required keys will crash mid-request instead of at startup.",
304
+ "REQUIRED = ['API_KEY', 'DB_URL']\n"
305
+ "for key in REQUIRED:\n"
306
+ " if not os.environ.get(key):\n"
307
+ " import sys\n"
308
+ " sys.exit(f'[FATAL] Missing env var: {key}')",
309
+ 0.87
310
  ))
311
 
312
+ # R-C3 Β· Model/resource not loaded at startup
313
+ if IS_PY and re.search(r'(model|pipeline|tokenizer|engine)\s*=\s*None', code) \
314
+ and not re.search(r'lifespan|on_event|startup|__init__', code, re.I):
315
+ ln = _fl(code, r'(model|pipeline|tokenizer|engine)\s*=\s*None')
316
+ bugs.append(_bug(
317
+ "R-C3", "runtime", 4, ln,
318
+ "R-C3 Β· Model not loaded at startup: resource initialised as None, likely loaded lazily "
319
+ "inside a route β€” causes the first request to hang or crash.",
320
+ "from contextlib import asynccontextmanager\n"
321
+ "@asynccontextmanager\n"
322
+ "async def lifespan(app):\n"
323
+ " app.state.model = load_model() # load once at startup\n"
324
+ " yield\n"
325
+ "app = FastAPI(lifespan=lifespan)",
326
+ 0.80
327
  ))
328
 
329
+ # R-C4 Β· NoneType access risk
330
+ if re.search(r'\.get\(|request\.|response\.', code) \
331
+ and re.search(r'(\w+)\.\w+|\w+\[', code) \
332
+ and not re.search(r'is not None|!= None|is None|if \w+', code):
333
+ ln = _fl(code, r'\w+\.\w+')
334
+ if ln:
335
+ bugs.append(_bug(
336
+ "R-C4", "runtime", 4, ln,
337
+ "R-C4 Β· NoneType access risk: chained attribute or index access on a value that "
338
+ "could be None β€” the #1 cause of 500 errors.",
339
+ "# Guard before access:\n"
340
+ "if value is not None:\n"
341
+ " result = value.attribute\n"
342
+ "# JS optional chaining:\n"
343
+ "const name = user?.profile?.name ?? 'default';",
344
+ 0.75
345
+ ))
346
+
347
+ # R-C5 Β· Type mismatch (no casting)
348
+ if IS_PY and re.search(r'request\.(json|form|args|query_params)', code) \
349
+ and not re.search(r'int\(|float\(|str\(|BaseModel|pydantic', code):
350
+ ln = _fl(code, r'request\.(json|form|args|query_params)')
351
+ bugs.append(_bug(
352
+ "R-C5", "runtime", 3, ln,
353
+ "R-C5 Β· Type mismatch: request parameters used without type casting or Pydantic validation. "
354
+ "A string where int is expected causes a silent crash.",
355
+ "class Body(BaseModel):\n"
356
+ " code: str\n"
357
+ " severity: int # auto-cast & validated\n"
358
+ "\n"
359
+ "@app.post('/api/review')\n"
360
+ "async def review(body: Body): ...",
361
+ 0.82
362
  ))
363
 
364
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
365
+ # CATEGORY 3 β€” Data & State
366
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
367
+
368
+ # R-D1 Β· DB connection not closed
369
+ if IS_PY and re.search(r'\.(connect|cursor|session|execute)\s*\(', code) \
370
+ and not re.search(r'\bwith\b.*(connect|session)|finally\s*:', code):
371
+ ln = _fl(code, r'\.(connect|cursor|session|execute)\s*\(')
372
+ bugs.append(_bug(
373
+ "R-D1", "data_state", 4, ln,
374
+ "R-D1 Β· DB connection not closed: connection opened without context manager. "
375
+ "Leaked connections exhaust the pool and cause cascade failures.",
376
+ "with db.connect() as conn:\n"
377
+ " result = conn.execute(query)\n"
378
+ "# SQLAlchemy:\n"
379
+ "with SessionLocal() as session:\n"
380
+ " session.add(record)\n"
381
+ " session.commit()",
382
+ 0.88
383
  ))
384
 
385
+ # R-D2 Β· Race condition on shared state
386
+ if IS_PY and re.search(r'\bglobal\s+\w+', code) \
387
+ and re.search(r'Thread|threading|asyncio|concurrent', code):
388
+ ln = _fl(code, r'\bglobal\s+\w+')
389
+ bugs.append(_bug(
390
+ "R-D2", "data_state", 5, ln,
391
+ "R-D2 Β· Race condition: global variable mutated in threaded/async context without a lock. "
392
+ "Concurrent writes will corrupt state.",
393
+ "import threading\n"
394
+ "_lock = threading.Lock()\n"
395
+ "_counter = 0\n"
396
+ "\n"
397
+ "def increment():\n"
398
+ " global _counter\n"
399
+ " with _lock:\n"
400
+ " _counter += 1",
401
+ 0.90
402
  ))
403
 
404
+ # R-D3 Β· Stale cache (no TTL)
405
+ if re.search(r'(cache|lru_cache|@cache)', code, re.I) \
406
+ and not re.search(r'ttl|expire|maxsize|timeout|invalidate', code, re.I):
407
+ ln = _fl(code, r'cache|lru_cache')
408
  if ln:
409
+ bugs.append(_bug(
410
+ "R-D3", "data_state", 3, ln,
411
+ "R-D3 Β· Stale cache: cache with no TTL, expiry, or invalidation strategy. "
412
+ "A never-expiring cache is a latent data-correctness bug.",
413
+ "import cachetools\n"
414
+ "cache = cachetools.TTLCache(maxsize=256, ttl=300) # expires after 5 min\n"
415
+ "# Or: @lru_cache(maxsize=256) for size-bounded (but no TTL)",
416
+ 0.78
 
417
  ))
418
 
419
+ # R-D4 Β· Missing input validation
420
+ if IS_PY and re.search(r'@app\.(post|put|patch)', code) \
421
+ and not re.search(r'BaseModel|HTTPException|raise.*400|raise.*422|validator', code):
422
+ ln = _fl(code, r'@app\.(post|put|patch)')
423
+ bugs.append(_bug(
424
+ "R-D4", "data_state", 4, ln,
425
+ "R-D4 Β· Missing input validation: POST/PUT route has no Pydantic model or explicit validation. "
426
+ "Invalid input causes 500 instead of 422 with field-level errors.",
427
+ "from pydantic import BaseModel, validator\n"
428
+ "\n"
429
+ "class Body(BaseModel):\n"
430
+ " code: str\n"
431
+ " language: str\n"
432
+ "\n"
433
+ " @validator('code')\n"
434
+ " def not_empty(cls, v):\n"
435
+ " if not v.strip(): raise ValueError('code is empty')\n"
436
+ " return v",
437
+ 0.83
438
+ ))
439
 
440
+ # R-D5 Β· Silent data truncation
441
+ if IS_PY and re.search(r'(\.save\(|\.add\(|\.insert\(|db\.execute)', code) \
442
+ and not re.search(r'len\s*\(|max_length|maxlength', code):
443
+ ln = _fl(code, r'\.save\(|\.add\(|db\.execute')
444
  if ln:
445
+ bugs.append(_bug(
446
+ "R-D5", "data_state", 3, ln,
447
+ "R-D5 Β· Silent data truncation: data written to DB without length validation. "
448
+ "Values exceeding column limits are silently truncated or cause insertion errors.",
449
+ "MAX_LEN = 255\n"
450
+ "if len(value) > MAX_LEN:\n"
451
+ " raise HTTPException(400, f'Value too long (max {MAX_LEN})')\n"
452
+ "db.save(value)",
453
+ 0.72
454
  ))
455
 
456
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
457
+ # CATEGORY 4 β€” Security
458
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
459
+
460
+ # R-S1 Β· Secrets in source code
461
+ if re.search(
462
+ r'(api_key|apikey|secret|password|passwd|token|auth_token|private_key)\s*[=:]\s*["\'][^"\']{4,}["\']',
463
+ code, re.I
464
+ ):
465
+ ln = _fl(code, r'(api_key|apikey|secret|password|token)\s*[=:]')
466
+ bugs.append(_bug(
467
+ "R-S1", "security", 5, ln,
468
+ "R-S1 Β· Secrets in source code: API key/token/password hardcoded in source. "
469
+ "This secret is now in version control β€” rotate it immediately.",
470
+ "import os\n"
471
+ "API_KEY = os.environ.get('API_KEY')\n"
472
+ "if not API_KEY:\n"
473
+ " raise RuntimeError('API_KEY not set')\n"
474
+ "# Scan history: pip install detect-secrets && detect-secrets scan",
475
+ 0.97
476
  ))
477
 
478
+ # R-S2 Β· SQL / command injection
479
+ if re.search(
480
+ r'(f["\'].*?\{.*?(SELECT|INSERT|DELETE|UPDATE|WHERE)|execute\s*\(\s*f["\']|os\.system\s*\(|shell\s*=\s*True)',
481
+ code, re.I | re.S
482
+ ):
483
+ ln = _fl(code, r'SELECT|INSERT|DELETE|os\.system|shell\s*=\s*True')
484
+ bugs.append(_bug(
485
+ "R-S2", "security", 5, ln,
486
+ "R-S2 Β· SQL/command injection: user input interpolated into SQL or shell command. "
487
+ "Attackers can execute arbitrary queries or OS commands.",
488
+ "# SQL β€” parameterized queries:\n"
489
+ "cursor.execute('SELECT * FROM t WHERE id = ?', (uid,))\n"
490
+ "\n"
491
+ "# Shell β€” list args without shell=True:\n"
492
+ "subprocess.run(['ls', path], shell=False, capture_output=True)",
493
+ 0.98
494
+ ))
495
 
496
+ # R-S3 Β· Overly permissive CORS
497
+ if re.search(r'allow_origins\s*=\s*\[.*\*.*\]|Access-Control-Allow-Origin.*\*|cors.*origin.*\*', code, re.I):
498
+ ln = _fl(code, r'allow_origins|Access-Control-Allow-Origin')
499
+ bugs.append(_bug(
500
+ "R-S3", "security", 4, ln,
501
+ "R-S3 Β· Overly permissive CORS: wildcard origin (*) allows any website to call your API. "
502
+ "Never use * on authenticated endpoints.",
503
+ "app.add_middleware(\n"
504
+ " CORSMiddleware,\n"
505
+ " allow_origins=['https://yourapp.com'], # no wildcard\n"
506
+ " allow_credentials=True,\n"
507
+ ")",
508
+ 0.95
 
509
  ))
510
 
511
+ # R-S4 Β· No rate limiting
512
+ if IS_PY and re.search(r'@app\.(post|get)\s*\(', code) \
513
+ and not re.search(r'limiter|rate_limit|RateLimiter|slowapi|Throttle', code, re.I):
514
+ ln = _fl(code, r'@app\.(post|get)\s*\(')
515
+ bugs.append(_bug(
516
+ "R-S4", "security", 3, ln,
517
+ "R-S4 Β· No rate limiting: public endpoints without throttling can be scraped, abused, or DoS'd.",
518
+ "from slowapi import Limiter\n"
519
+ "from slowapi.util import get_remote_address\n"
520
+ "limiter = Limiter(key_func=get_remote_address)\n"
521
+ "\n"
522
+ "@app.post('/api/review')\n"
523
+ "@limiter.limit('20/minute')\n"
524
+ "async def review(request: Request, body: Body): ...",
525
+ 0.80
526
+ ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
527
 
528
+ # R-S5 Β· Exposed stack traces
529
+ if re.search(r'traceback\.format_exc\(\)|format_exception', code) \
530
+ and re.search(r'return.*detail|JSONResponse.*trace', code, re.I):
531
+ ln = _fl(code, r'traceback\.format_exc|format_exception')
532
+ bugs.append(_bug(
533
+ "R-S5", "security", 4, ln,
534
+ "R-S5 Β· Exposed stack traces: raw traceback returned to HTTP client. "
535
+ "This leaks file paths, library versions, and internal logic.",
536
+ "except Exception as e:\n"
537
+ " logger.error('Request failed', exc_info=True) # log internally\n"
538
+ " raise HTTPException(status_code=500, detail='An error occurred') # generic to client",
539
+ 0.92
540
+ ))
541
 
542
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
543
+ # CATEGORY 5 β€” Config & Deploy
544
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
545
+
546
+ # R-CF1 Β· Wrong startup command
547
+ if re.search(r'\bCMD\b|\bENTRYPOINT\b', code):
548
+ cmd = re.search(r'CMD\s+\[?"?([^\]"\n]+)', code)
549
+ if cmd and not any(k in cmd.group(1) for k in ('uvicorn', 'gunicorn', 'app', 'python')):
550
+ ln = _fl(code, r'\bCMD\b|\bENTRYPOINT\b')
551
+ bugs.append(_bug(
552
+ "R-CF1", "config_deploy", 5, ln,
553
+ "R-CF1 Β· Wrong startup command: CMD/ENTRYPOINT doesn't reference uvicorn/gunicorn. "
554
+ "A typo here causes the container to exit immediately with code 1.",
555
+ 'CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]\n'
556
+ "# Verify entry module name: main.py -> main:app",
557
+ 0.80
558
  ))
559
 
560
+ # R-CF2 Β· Port mismatch (HF Spaces expects 7860)
561
+ if re.search(r'port\s*[=:]\s*(?!7860)\d{4,5}|--port\s+(?!7860)\d{4,5}|EXPOSE\s+(?!7860)\d{4,5}', code):
562
+ ln = _fl(code, r'port\s*[=:]|--port\s+|EXPOSE\s+')
563
+ bugs.append(_bug(
564
+ "R-CF2", "config_deploy", 5, ln,
565
+ "R-CF2 Β· Port mismatch: app binds to a port other than 7860. "
566
+ "Hugging Face Spaces requires port 7860 β€” all other ports are unreachable.",
567
+ "EXPOSE 7860\n"
568
+ 'CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]',
569
+ 0.92
570
+ ))
 
571
 
572
+ # R-CF3 Β· Missing dependency in requirements
573
+ if IS_PY:
574
+ imports = re.findall(r'^(?:import|from)\s+(\w+)', code, re.M)
575
+ stdlib = {
576
+ 'os', 'sys', 're', 'json', 'time', 'math', 'io', 'abc', 'copy', 'enum',
577
+ 'typing', 'pathlib', 'datetime', 'collections', 'functools', 'itertools',
578
+ 'logging', 'threading', 'asyncio', 'contextlib', 'inspect', 'traceback',
579
+ 'hashlib', 'hmac', 'base64', 'urllib', 'http', 'socket', 'struct',
580
+ 'random', 'string', 'shutil', 'glob', 'tempfile', 'subprocess', 'signal',
581
+ }
582
+ third_party = sorted(set(m for m in imports if m not in stdlib and not m.startswith('_')))
583
+ if third_party:
584
+ bugs.append(_bug(
585
+ "R-CF3", "config_deploy", 3, 1,
586
+ f"R-CF3 Β· Missing dependency check: third-party imports detected "
587
+ f"({', '.join(third_party)}) β€” verify all are in requirements.txt / Dockerfile.",
588
+ "pip freeze > requirements.txt\n"
589
+ "# In Dockerfile:\n"
590
+ "COPY requirements.txt .\n"
591
+ "RUN pip install --no-cache-dir -r requirements.txt",
592
+ 0.75
593
  ))
594
 
595
+ # R-CF4 Β· Wrong working directory (relative paths without __file__)
596
+ if IS_PY and re.search(r'open\s*\(\s*["\'](?!/)', code) \
597
+ and not re.search(r'__file__|os\.path\.dirname|pathlib\.Path', code):
598
+ ln = _fl(code, r'open\s*\(\s*["\']')
599
+ bugs.append(_bug(
600
+ "R-CF4", "config_deploy", 4, ln,
601
+ "R-CF4 Β· Wrong working directory: relative file path without __file__ anchor. "
602
+ "Works locally but breaks in Docker containers where CWD differs.",
603
+ "import os\n"
604
+ "BASE = os.path.dirname(os.path.abspath(__file__))\n"
605
+ "path = os.path.join(BASE, 'templates', 'index.html')\n"
606
+ "with open(path) as f: ...",
607
+ 0.88
 
608
  ))
609
 
610
+ # R-CF5 Β· Build vs runtime confusion (heavy deps at module level)
611
+ if IS_PY and re.search(r'^import (torch|transformers|tensorflow|keras)', code, re.M):
612
+ ln = _fl(code, r'^import (torch|transformers|tensorflow|keras)')
 
 
 
 
 
 
 
 
 
 
 
 
 
613
  if ln:
614
+ bugs.append(_bug(
615
+ "R-CF5", "config_deploy", 3, ln,
616
+ "R-CF5 Β· Build vs runtime confusion: heavy ML library imported at module level. "
617
+ "If the Docker layer is cached without GPU, the import fails at runtime.",
618
+ "def get_model():\n"
619
+ " import torch # lazy import β€” only when needed\n"
620
+ " return torch.load('model.pt')",
621
+ 0.72
622
  ))
623
 
624
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
625
+ # CATEGORY 6 β€” Logic & Testing
626
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
627
+
628
+ # R-L1 Β· No test for the happy path
629
+ if IS_PY and re.search(r'def \w+\s*\(', code) \
630
+ and not re.search(r'def test_|import pytest|import unittest|assert\b', code):
631
+ bugs.append(_bug(
632
+ "R-L1", "logic_testing", 2, 1,
633
+ "R-L1 Β· No test for the happy path: no pytest/unittest tests found. "
634
+ "Every endpoint and function needs at least one integration test.",
635
+ "from fastapi.testclient import TestClient\n"
636
+ "client = TestClient(app)\n"
637
+ "\n"
638
+ "def test_review_happy_path():\n"
639
+ " r = client.post('/api/review', json={'code': 'x=1', 'language': 'python'})\n"
640
+ " assert r.status_code == 200\n"
641
+ " assert 'bugs' in r.json()",
642
+ 0.75
643
  ))
644
 
645
+ # R-L2 Β· Edge cases not covered
646
+ if IS_PY and re.search(r'def test_', code) \
647
+ and not re.search(r'empty|null|none|zero|boundary|edge|invalid|negative|max|min', code, re.I):
648
+ ln = _fl(code, r'def test_')
649
+ bugs.append(_bug(
650
+ "R-L2", "logic_testing", 2, ln,
651
+ "R-L2 Β· Edge cases not covered: tests found but none test empty, null, zero, max, or boundary values.",
652
+ "def test_empty_code_returns_400():\n"
653
+ " r = client.post('/api/review', json={'code': '', 'language': 'python'})\n"
654
+ " assert r.status_code == 400\n"
655
+ "\n"
656
+ "def test_oversized_code_returns_400():\n"
657
+ " r = client.post('/api/review', json={'code': 'x' * 6000, 'language': 'python'})\n"
658
+ " assert r.status_code == 400",
659
+ 0.70
660
  ))
661
 
662
+ # R-L3 Β· Off-by-one errors
663
+ if re.search(r'range\s*\(\s*len\s*\([^)]+\)\s*-\s*1\s*\)|for.+in.+\[\s*:-1\s*\]', code):
664
+ ln = _fl(code, r'range\s*\(\s*len|:\s*-1\s*\]')
665
+ bugs.append(_bug(
666
+ "R-L3", "logic_testing", 3, ln,
667
+ "R-L3 Β· Off-by-one error: range(len(x)-1) or x[:-1] skips the last element. "
668
+ "Review every loop bound, slice, and pagination offset.",
669
+ "for i in range(len(numbers)): # not len(numbers)-1\n"
670
+ "for item in numbers: # preferred\n"
671
+ "for i, item in enumerate(numbers): # with index\n"
672
+ "x[:] # full slice",
673
+ 0.90
674
+ ))
675
+
676
+ # R-L4 Β· Wrong default values (mutable defaults)
677
+ if IS_PY and re.search(r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\}|set\(\)|list\(\)|dict\(\))', code):
678
+ ln = _fl(code, r'def\s+\w+\s*\([^)]*=\s*(\[\]|\{\}|set\(\))')
679
+ bugs.append(_bug(
680
+ "R-L4", "logic_testing", 4, ln,
681
+ "R-L4 Β· Wrong default value: mutable default ([], {}, set()) is shared across ALL calls. "
682
+ "State from one call leaks into the next β€” a classic Python bug.",
683
+ "def process(items=None, config=None):\n"
684
+ " if items is None: items = []\n"
685
+ " if config is None: config = {}\n"
686
+ " # Each call now gets a fresh object",
687
+ 0.98
688
+ ))
689
 
690
+ # R-L5 Β· Async/await misuse
691
+ if re.search(r'async\s+(def|function)', code) \
692
+ and not re.search(r'\bawait\b', code):
693
+ ln = _fl(code, r'async\s+(def|function)')
694
+ bugs.append(_bug(
695
+ "R-L5", "logic_testing", 4, ln,
696
+ "R-L5 Β· Async/await misuse: async function with no await returns a coroutine object, not the result. "
697
+ "Enable async linting to catch this automatically.",
698
+ "async def get_data():\n"
699
+ " result = await fetch_from_db() # not fetch_from_db()\n"
700
+ " return result\n"
701
+ "\n"
702
+ "# Enable warnings:\n"
703
+ "# python -W error::RuntimeWarning",
704
+ 0.88
705
  ))
706
 
707
+ # Sort by severity DESC, then confidence DESC
708
  bugs.sort(key=lambda b: (b["severity"], b["confidence"]), reverse=True)
709
  return bugs
710
 
 
719
  try:
720
  with open(html_path, "r", encoding="utf-8") as f:
721
  return HTMLResponse(f.read())
722
+ except Exception:
723
  return HTMLResponse("<h1>CodeBug API Running.</h1><p>Visit /docs for API documentation.</p>")
724
 
725
 
726
  # ========================================================================
727
+ # GET /api/health
728
  # ========================================================================
729
  @app.get("/api/health")
730
  async def health_check():
 
731
  return {
732
  "status": "ok",
733
  "version": "2.0",
734
+ "rules_engine": "30-rule official spec",
735
+ "rule_categories": [
736
+ "API & Network (R-N1..R-N5)",
737
+ "Runtime Crashes (R-C1..R-C5)",
738
+ "Data & State (R-D1..R-D5)",
739
+ "Security (R-S1..R-S5)",
740
+ "Config & Deploy (R-CF1..R-CF5)",
741
+ "Logic & Testing (R-L1..R-L5)",
742
  ],
743
+ "supported_languages": ["python", "javascript", "typescript", "java", "go", "cpp"],
744
+ "llm_active": HAS_LLM,
 
 
 
 
745
  }
746
 
747
 
748
  # ========================================================================
749
+ # GET /api/stats
750
  # ========================================================================
751
  @app.get("/api/stats")
752
  async def get_stats():
 
753
  return {
754
+ "rules_total": 30,
755
+ "categories": 6,
756
+ "rules_per_category": 5,
757
+ "languages_supported": 6,
758
+ "llm_active": HAS_LLM,
 
759
  }
760
 
761
 
762
  # ========================================================================
763
+ # Mount OpenEnv app at /openenv
764
  # ========================================================================
765
  app.mount("/openenv", openenv_app)