Spaces:
Sleeping
Sleeping
feat: complete 30-rule official bug engine (R-N1..R-L5) per hackathon spec
Browse files
main.py
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
"""
|
| 2 |
-
CodeBug FastAPI server
|
|
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
from fastapi import FastAPI, Request, HTTPException
|
| 6 |
from fastapi.responses import HTMLResponse, JSONResponse
|
| 7 |
from pydantic import BaseModel
|
| 8 |
-
import os,
|
| 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
|
| 28 |
openenv_app = create_fastapi_app(CodeBugEnvironment, CodeReviewAction, CodeReviewObservation)
|
| 29 |
|
| 30 |
-
#
|
| 31 |
app = FastAPI(title="CodeBug API", version="2.0")
|
| 32 |
|
|
|
|
| 33 |
# ========================================================================
|
| 34 |
-
# POST /api/train
|
| 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
|
| 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 =
|
| 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 |
-
"
|
|
|
|
|
|
|
|
|
|
| 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
|
| 112 |
"fix": "",
|
| 113 |
"confidence": 1.0
|
| 114 |
}
|
| 115 |
-
|
| 116 |
-
|
| 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 |
-
#
|
| 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
|
| 159 |
return analyze_code_comprehensively(code, lang)
|
| 160 |
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 185 |
-
|
| 186 |
-
Covers: security, logic, style, concurrency, resource management.
|
| 187 |
"""
|
| 188 |
bugs = []
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
# 1
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
-
#
|
| 205 |
-
if re.search(r'
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
"
|
| 210 |
-
"
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
))
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
"
|
| 220 |
-
"
|
| 221 |
-
|
| 222 |
-
0.96, ALL_LANGS
|
| 223 |
))
|
| 224 |
|
| 225 |
-
#
|
| 226 |
-
if re.search(r'\
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
))
|
| 234 |
|
| 235 |
-
#
|
| 236 |
-
if re.search(r'
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
"
|
| 241 |
-
"
|
| 242 |
-
"
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
))
|
| 245 |
|
| 246 |
-
#
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
))
|
| 256 |
|
| 257 |
-
#
|
| 258 |
-
if re.search(r'
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
"
|
| 263 |
-
"
|
| 264 |
-
"
|
| 265 |
-
"
|
| 266 |
-
"
|
| 267 |
-
|
|
|
|
|
|
|
|
|
|
| 268 |
))
|
| 269 |
|
| 270 |
-
#
|
| 271 |
-
if
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
"
|
| 276 |
-
"
|
| 277 |
-
"
|
| 278 |
-
"
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
))
|
| 281 |
|
| 282 |
-
#
|
| 283 |
-
if re.search(r'
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
))
|
| 293 |
|
| 294 |
-
#
|
| 295 |
-
|
| 296 |
-
#
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
"
|
| 304 |
-
"
|
| 305 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
))
|
| 307 |
|
| 308 |
-
#
|
| 309 |
-
if
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
"
|
| 314 |
-
"
|
| 315 |
-
"
|
| 316 |
-
"
|
| 317 |
-
"
|
| 318 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
))
|
| 320 |
|
| 321 |
-
#
|
| 322 |
-
if re.search(r'
|
| 323 |
-
|
|
|
|
| 324 |
if ln:
|
| 325 |
-
bugs.append(
|
| 326 |
-
"
|
| 327 |
-
"
|
| 328 |
-
"
|
| 329 |
-
"
|
| 330 |
-
"
|
| 331 |
-
"
|
| 332 |
-
|
| 333 |
-
0.75, ALL_LANGS
|
| 334 |
))
|
| 335 |
|
| 336 |
-
#
|
| 337 |
-
if re.search(r'(
|
| 338 |
-
and not re.search(r'
|
| 339 |
-
ln =
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
-
#
|
| 350 |
-
if re.search(r'\
|
| 351 |
-
and not re.search(r'\
|
| 352 |
-
ln =
|
| 353 |
if ln:
|
| 354 |
-
bugs.append(
|
| 355 |
-
"
|
| 356 |
-
"
|
| 357 |
-
"
|
| 358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
))
|
| 360 |
|
| 361 |
-
#
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
"
|
| 373 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
))
|
| 375 |
|
| 376 |
-
#
|
| 377 |
-
if re.search(
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
|
| 390 |
-
#
|
| 391 |
-
if re.search(r'
|
| 392 |
-
ln =
|
| 393 |
-
bugs.append(
|
| 394 |
-
"
|
| 395 |
-
"
|
| 396 |
-
"
|
| 397 |
-
"
|
| 398 |
-
"
|
| 399 |
-
"
|
| 400 |
-
"
|
| 401 |
-
"
|
| 402 |
-
|
| 403 |
-
0.93, ["python"]
|
| 404 |
))
|
| 405 |
|
| 406 |
-
#
|
| 407 |
-
if
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 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 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 450 |
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 459 |
))
|
| 460 |
|
| 461 |
-
#
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
))
|
| 473 |
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
))
|
| 483 |
|
| 484 |
-
#
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
"
|
| 492 |
-
"
|
| 493 |
-
"
|
| 494 |
-
"
|
| 495 |
-
"
|
| 496 |
-
|
| 497 |
-
0.80, ["python"]
|
| 498 |
))
|
| 499 |
|
| 500 |
-
#
|
| 501 |
-
if re.search(r'
|
| 502 |
-
ln =
|
| 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(
|
| 518 |
-
"
|
| 519 |
-
"
|
| 520 |
-
"
|
| 521 |
-
"
|
| 522 |
-
"
|
| 523 |
-
|
|
|
|
| 524 |
))
|
| 525 |
|
| 526 |
-
#
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
"
|
| 535 |
-
"
|
| 536 |
-
"
|
| 537 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
))
|
| 539 |
|
| 540 |
-
#
|
| 541 |
-
if
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
"
|
| 546 |
-
"
|
| 547 |
-
"
|
| 548 |
-
"
|
| 549 |
-
"
|
| 550 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
))
|
| 552 |
|
| 553 |
-
#
|
| 554 |
-
if
|
| 555 |
-
ln =
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
|
| 567 |
-
#
|
| 568 |
-
if re.search(r'
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
"
|
| 573 |
-
"
|
| 574 |
-
"
|
| 575 |
-
"
|
| 576 |
-
"
|
| 577 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
))
|
| 579 |
|
| 580 |
-
# Sort
|
| 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
|
| 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 |
-
"
|
| 609 |
-
"
|
| 610 |
-
"
|
| 611 |
-
"
|
| 612 |
-
"
|
| 613 |
-
"
|
|
|
|
|
|
|
| 614 |
],
|
| 615 |
-
"
|
| 616 |
-
|
| 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
|
| 626 |
# ========================================================================
|
| 627 |
@app.get("/api/stats")
|
| 628 |
async def get_stats():
|
| 629 |
-
"""Return usage statistics"""
|
| 630 |
return {
|
| 631 |
-
"
|
| 632 |
-
"
|
| 633 |
-
"
|
| 634 |
-
"
|
| 635 |
-
"
|
| 636 |
-
"style_checks": 10
|
| 637 |
}
|
| 638 |
|
| 639 |
|
| 640 |
# ========================================================================
|
| 641 |
-
# Mount OpenEnv app at /openenv
|
| 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)
|