Spaces:
Sleeping
Sleeping
WIP: removing bad regex patterns
Browse files
main.py
CHANGED
|
@@ -100,38 +100,9 @@ async def review_code(request: ReviewRequest):
|
|
| 100 |
)
|
| 101 |
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
return {
|
| 107 |
-
"status": "ok",
|
| 108 |
-
"version": "2.0",
|
| 109 |
-
"supported_languages": ["python", "javascript", "typescript", "java", "go", "cpp"],
|
| 110 |
-
"features": [
|
| 111 |
-
"comprehensive_bug_detection",
|
| 112 |
-
"confidence_scores",
|
| 113 |
-
"multi_language_support",
|
| 114 |
-
"export_json_reports"
|
| 115 |
-
],
|
| 116 |
-
"api_endpoints": [
|
| 117 |
-
"/api/review (POST) - Analyze code",
|
| 118 |
-
"/api/health (GET) - This endpoint",
|
| 119 |
-
"/api/stats (GET) - Usage statistics"
|
| 120 |
-
]
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
@app.get("/api/stats")
|
| 125 |
-
async def get_stats():
|
| 126 |
-
"""Return usage statistics and bug detection summary"""
|
| 127 |
-
return {
|
| 128 |
-
"message": "Stats endpoint - tracks would be stored in session/DB",
|
| 129 |
-
"supported_check_types": 30,
|
| 130 |
-
"languages": 6,
|
| 131 |
-
"security_checks": 12,
|
| 132 |
-
"logic_checks": 8,
|
| 133 |
-
"style_checks": 10
|
| 134 |
-
}
|
| 135 |
code_lower = code.lower()
|
| 136 |
code_no_space = code.lower().replace(' ', '')
|
| 137 |
lines = code.split('\n')
|
|
@@ -144,12 +115,12 @@ async def get_stats():
|
|
| 144 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 3,
|
| 145 |
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 146 |
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
|
| 147 |
-
"confidence": 0.95,
|
| 148 |
"languages": ["python", "javascript", "typescript"]
|
| 149 |
})
|
| 150 |
|
| 151 |
# Command Injection
|
| 152 |
-
if re.search(r'(os\.system|subprocess|popen|shell=true
|
| 153 |
bugs.append({
|
| 154 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 155 |
"comment": "Command injection: User input directly in shell command.",
|
|
@@ -164,7 +135,7 @@ async def get_stats():
|
|
| 164 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 165 |
"comment": "Hardcoded password/credential detected.",
|
| 166 |
"fix": "Use environment variables: os.getenv('DB_PASSWORD')",
|
| 167 |
-
"confidence": 0.98,
|
| 168 |
"languages": ["python", "javascript", "typescript", "java", "go", "cpp"]
|
| 169 |
})
|
| 170 |
|
|
@@ -181,7 +152,7 @@ async def get_stats():
|
|
| 181 |
# ============ HIGH SEVERITY SECURITY BUGS (Severity 4) ============
|
| 182 |
|
| 183 |
# Hardcoded API keys
|
| 184 |
-
if re.search(r'(api_key|apikey|secret_key|private_key|token|auth_token|bearer
|
| 185 |
bugs.append({
|
| 186 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 1,
|
| 187 |
"comment": "Hardcoded API key/token detected.",
|
|
@@ -342,322 +313,259 @@ async def get_stats():
|
|
| 342 |
return bugs
|
| 343 |
|
| 344 |
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
if bugs:
|
| 349 |
-
return bugs[0]
|
| 350 |
return {
|
| 351 |
-
"
|
| 352 |
-
"
|
| 353 |
-
"
|
| 354 |
-
"
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
}
|
| 359 |
-
|
| 360 |
code_lower = code.lower()
|
| 361 |
code_no_space = code.lower().replace(' ', '')
|
| 362 |
lines = code.split('\n')
|
| 363 |
|
| 364 |
# ============ CRITICAL SECURITY BUGS (Severity 5) ============
|
| 365 |
|
| 366 |
-
# SQL Injection
|
| 367 |
if ('f"' in code or "f'" in code) and any(sql in code_lower for sql in ['select', 'insert', 'delete', 'update', 'from', 'where']) and '{' in code and '}' in code:
|
| 368 |
-
|
| 369 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 3,
|
| 370 |
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 371 |
-
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))"
|
| 372 |
-
|
|
|
|
|
|
|
| 373 |
|
| 374 |
# Command Injection
|
| 375 |
-
if re.search(r'(os\.system|subprocess|popen|shell=true)\s*\(.*f["\']|
|
| 376 |
-
|
| 377 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 378 |
"comment": "Command injection: User input directly in shell command.",
|
| 379 |
-
"fix": "Use subprocess with args as list: subprocess.run(['ls', filename], shell=False)"
|
| 380 |
-
|
|
|
|
|
|
|
| 381 |
|
| 382 |
-
# Hardcoded
|
| 383 |
if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
|
| 384 |
-
|
| 385 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 386 |
"comment": "Hardcoded password/credential detected.",
|
| 387 |
-
"fix": "Use environment variables: os.getenv('DB_PASSWORD')"
|
| 388 |
-
|
|
|
|
|
|
|
| 389 |
|
| 390 |
-
# Code execution
|
| 391 |
if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
|
| 392 |
-
|
| 393 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 394 |
"comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
|
| 395 |
-
"fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives"
|
| 396 |
-
|
|
|
|
|
|
|
| 397 |
|
| 398 |
# ============ HIGH SEVERITY SECURITY BUGS (Severity 4) ============
|
| 399 |
|
| 400 |
-
# Hardcoded API keys
|
| 401 |
-
if re.search(r'(api_key|apikey|secret_key|private_key|token|auth_token|bearer|sk_|pk_)\s*[=:]\s*["\'][a-zA-Z0-9_\-]
|
| 402 |
-
|
| 403 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 1,
|
| 404 |
"comment": "Hardcoded API key/token detected.",
|
| 405 |
-
"fix": "api_key = os.getenv('API_KEY')"
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
if re.search(r'(user_input|request\.args|request\.form|get\(|input\(\))\s*\[', code) and not re.search(r'(validate|check|strip|sanitize|escape)', code, re.I):
|
| 410 |
-
return {
|
| 411 |
-
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 412 |
-
"comment": "Missing input validation: User input used without sanitization.",
|
| 413 |
-
"fix": "Validate and sanitize all user input before using"
|
| 414 |
-
}
|
| 415 |
-
|
| 416 |
-
# Path traversal vulnerability
|
| 417 |
-
if re.search(r'(open|read|load)\s*\(\s*f?["\'].*\.\.\/', code, re.I) or ('..\\' in code and 'open' in code_lower):
|
| 418 |
-
return {
|
| 419 |
-
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 420 |
-
"comment": "Path traversal vulnerability: Relative paths with ../ can access arbitrary files.",
|
| 421 |
-
"fix": "Use absolute paths or validate/normalize paths: os.path.normpath()"
|
| 422 |
-
}
|
| 423 |
|
| 424 |
-
# XSS vulnerability
|
| 425 |
if lang == 'javascript' and re.search(r'\.innerHTML\s*=|\.eval\(|dangerouslySetInnerHTML', code):
|
| 426 |
-
|
| 427 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 428 |
"comment": "XSS vulnerability: Setting innerHTML with user data can execute scripts.",
|
| 429 |
-
"fix": "Use .textContent or sanitize HTML: DOMPurify.sanitize()"
|
| 430 |
-
|
|
|
|
|
|
|
| 431 |
|
| 432 |
-
# Insecure random
|
| 433 |
if re.search(r'(random\.|Math\.random\(\)|rand\(\))', code) and not re.search(r'(secrets|systemrandom|cryptographically|urandom)', code, re.I):
|
| 434 |
-
|
| 435 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 436 |
"comment": "Weak random number generator for security purposes.",
|
| 437 |
-
"fix": "Use: secrets.token_hex() or os.urandom() for cryptographic randomness"
|
| 438 |
-
|
|
|
|
|
|
|
| 439 |
|
| 440 |
# ============ LOGIC BUGS ============
|
| 441 |
|
| 442 |
-
#
|
| 443 |
-
if
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
|
|
|
| 450 |
|
| 451 |
-
#
|
| 452 |
-
if re.search(r'
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 459 |
|
| 460 |
-
#
|
| 461 |
-
if ('
|
| 462 |
-
|
| 463 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 464 |
-
"comment": "
|
| 465 |
-
"fix": "Add
|
| 466 |
-
|
|
|
|
|
|
|
| 467 |
|
| 468 |
# Off-by-one errors
|
| 469 |
-
if re.search(r'
|
| 470 |
-
|
| 471 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 472 |
-
"comment": "Off-by-one error:
|
| 473 |
-
"fix": "Use
|
| 474 |
-
|
|
|
|
|
|
|
| 475 |
|
| 476 |
-
# Resource leak
|
| 477 |
-
if re.search(r'open\s*\([^)]+\)\s*(?!with)', code) and '.close()' not in code:
|
| 478 |
-
|
| 479 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 480 |
"comment": "Resource leak: File opened without 'with' statement. May not close properly.",
|
| 481 |
-
"fix": "Use: with open(file) as f: ... (automatic close)"
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
if (re.search(r'(json\.loads|parse|eval|execute|request)\s*\(', code) or lang == 'javascript' and re.search(r'fetch\s*\(|\.then', code)) and not re.search(r'(try|except|catch|error)', code, re.I):
|
| 486 |
-
return {
|
| 487 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 488 |
-
"comment": "Missing error handling: Code can fail silently.",
|
| 489 |
-
"fix": "Wrap in try/except: try: ... except Exception as e: ..."
|
| 490 |
-
}
|
| 491 |
-
|
| 492 |
-
# Unreachable code after return
|
| 493 |
-
if re.search(r'return\s*[^;]*\n\s+\w+', code):
|
| 494 |
-
return {
|
| 495 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 496 |
-
"comment": "Unreachable code: Statements after return will never execute.",
|
| 497 |
-
"fix": "Remove or restructure code after return statement"
|
| 498 |
-
}
|
| 499 |
|
| 500 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 501 |
|
| 502 |
-
#
|
| 503 |
-
if lang == '
|
| 504 |
-
|
| 505 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint":
|
| 506 |
-
"comment": "
|
| 507 |
-
"fix": "
|
| 508 |
-
|
|
|
|
|
|
|
| 509 |
|
| 510 |
# Type errors
|
| 511 |
-
if lang == '
|
| 512 |
-
|
| 513 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 514 |
-
"comment": "
|
| 515 |
-
"fix": "
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
if re.search(r'if\s+len\s*\([^)]+\)\s*[!=><]=*\s*0', code):
|
| 520 |
-
return {
|
| 521 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 1,
|
| 522 |
-
"comment": "Redundant length check. Empty sequences are falsy.",
|
| 523 |
-
"fix": "Use: if items: instead of: if len(items) != 0:"
|
| 524 |
-
}
|
| 525 |
-
|
| 526 |
-
# ============ STYLE & BEST PRACTICES ============
|
| 527 |
-
|
| 528 |
-
# var in JavaScript
|
| 529 |
-
if lang == 'javascript' and re.search(r'\bvar\s+\w+\s*[=;]', code):
|
| 530 |
-
return {
|
| 531 |
-
"type": "bug", "category": "style", "severity": 2, "line_hint": 1,
|
| 532 |
-
"comment": "Use const/let instead of var. var has function-level scope.",
|
| 533 |
-
"fix": "Replace var with const (or let if reassignment needed)"
|
| 534 |
-
}
|
| 535 |
-
|
| 536 |
-
# Deprecated functions
|
| 537 |
-
if re.search(r'\b(deprecated|old_function|legacy_method)\s*\(', code, re.I):
|
| 538 |
-
return {
|
| 539 |
-
"type": "bug", "category": "style", "severity": 2, "line_hint": 1,
|
| 540 |
-
"comment": "Deprecated function detected. Use newer alternative.",
|
| 541 |
-
"fix": "Check documentation for recommended replacement"
|
| 542 |
-
}
|
| 543 |
|
| 544 |
-
#
|
| 545 |
-
if
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
|
|
|
| 552 |
|
| 553 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 554 |
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
# Modifying list while iterating
|
| 565 |
-
if re.search(r'for\s+\w+\s+in\s+\w+:.*\.remove\(|for\s+\w+\s+in\s+\w+:.*\.pop\(', code, re.DOTALL):
|
| 566 |
-
return {
|
| 567 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 568 |
-
"comment": "Modifying list while iterating: Causes items to be skipped.",
|
| 569 |
-
"fix": "Iterate over a copy: for item in items[:]: or use list comprehension"
|
| 570 |
-
}
|
| 571 |
-
|
| 572 |
-
# Shadowing built-in names
|
| 573 |
-
builtins = ['list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'len', 'range', 'map', 'filter', 'zip', 'open']
|
| 574 |
-
for builtin in builtins:
|
| 575 |
-
if re.search(rf'^{builtin}\s*=', code, re.MULTILINE):
|
| 576 |
-
return {
|
| 577 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 1,
|
| 578 |
-
"comment": f"Shadowing built-in '{builtin}': Overwrites Python's {builtin}() function.",
|
| 579 |
-
"fix": f"Rename variable: use my_{builtin} or similar"
|
| 580 |
-
}
|
| 581 |
-
|
| 582 |
-
# Missing return statement
|
| 583 |
-
if re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n\s{4,}\w+\s*=', code) and 'return' not in code:
|
| 584 |
-
return {
|
| 585 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 586 |
-
"comment": "Missing return statement: Function computes value but returns None.",
|
| 587 |
-
"fix": "Add return: return result"
|
| 588 |
-
}
|
| 589 |
-
|
| 590 |
-
# Bare except clause
|
| 591 |
-
if re.search(r'except\s*:\s*(?!.*#)', code):
|
| 592 |
-
return {
|
| 593 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 594 |
-
"comment": "Bare except clause: Catches all exceptions including KeyboardInterrupt.",
|
| 595 |
-
"fix": "Specify exception: except ValueError: or except Exception:"
|
| 596 |
-
}
|
| 597 |
-
|
| 598 |
-
# Variable scope issue
|
| 599 |
-
if re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n(?:\s{4}.*\n)*(?:\s{0,3})\w+\s*=', code):
|
| 600 |
-
return {
|
| 601 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 602 |
-
"comment": "Variable scope issue: Variable defined in function not accessible outside.",
|
| 603 |
-
"fix": "Make it global: global var_name (use sparingly) or return the value"
|
| 604 |
-
}
|
| 605 |
-
|
| 606 |
-
# Race condition (threading/multiprocessing)
|
| 607 |
-
if re.search(r'threading\.|multiprocessing\.|Thread|Process', code) and not re.search(r'Lock|RLock|Semaphore|Condition', code):
|
| 608 |
-
return {
|
| 609 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 610 |
-
"comment": "Race condition: Multithreaded code without synchronization.",
|
| 611 |
-
"fix": "Use locks: lock = threading.Lock(); with lock: shared_var += 1"
|
| 612 |
-
}
|
| 613 |
-
|
| 614 |
-
# Infinite recursion (no base case)
|
| 615 |
-
if re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\1\s*\(', code):
|
| 616 |
-
return {
|
| 617 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 618 |
-
"comment": "Infinite recursion: Function calls itself without base case.",
|
| 619 |
-
"fix": "Add base case: if condition: return value"
|
| 620 |
-
}
|
| 621 |
-
|
| 622 |
-
# Type error (concatenating string and int)
|
| 623 |
-
if re.search(r'["\'][^"\']*["\'].*\+.*\d+|["\'][^"\']*["\'].*\+\s*\w+', code):
|
| 624 |
-
return {
|
| 625 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 626 |
-
"comment": "Type error: Cannot concatenate string with number directly.",
|
| 627 |
-
"fix": "Convert to string: str(value) or use f-string: f'text {value}'"
|
| 628 |
-
}
|
| 629 |
-
|
| 630 |
-
# Off-by-one with array indexing
|
| 631 |
-
if re.search(r'\[\s*\w+\s*\+\s*1\s*\]', code):
|
| 632 |
-
return {
|
| 633 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 634 |
-
"comment": "Off-by-one error: arr[i+1] may access beyond array bounds.",
|
| 635 |
-
"fix": "Use range(len(arr)-1) or check bounds: if i+1 < len(arr)"
|
| 636 |
-
}
|
| 637 |
-
|
| 638 |
-
# Inefficient nested loops
|
| 639 |
-
if code.count('for ') >= 2 and 'range(10000)' in code:
|
| 640 |
-
return {
|
| 641 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 642 |
-
"comment": "Performance issue: Nested loops with large ranges (O(n²) complexity).",
|
| 643 |
-
"fix": "Use set/dict for O(1) lookup or optimize algorithm"
|
| 644 |
-
}
|
| 645 |
-
|
| 646 |
-
# Logical error (identical branches)
|
| 647 |
-
if re.search(r'if\s+.*?:\s*([^\n]+)\s*else:\s*\1', code, re.DOTALL | re.IGNORECASE):
|
| 648 |
-
return {
|
| 649 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 650 |
-
"comment": "Logical error: Both if and else branches do the same thing.",
|
| 651 |
-
"fix": "Remove the condition or fix the logic"
|
| 652 |
-
}
|
| 653 |
|
| 654 |
-
#
|
|
|
|
| 655 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 656 |
return {
|
| 657 |
"type": "approve",
|
| 658 |
"category": "style",
|
| 659 |
"severity": 1,
|
| 660 |
"line_hint": None,
|
| 661 |
"comment": "No obvious bugs detected. Code looks clean.",
|
| 662 |
-
"fix": ""
|
|
|
|
| 663 |
}
|
|
|
|
| 100 |
)
|
| 101 |
|
| 102 |
|
| 103 |
+
def analyze_code_comprehensively(code: str, lang: str) -> list:
|
| 104 |
+
"""Find ALL bugs in code with confidence scores. Supports Python, JavaScript, TypeScript, Java, Go, C++"""
|
| 105 |
+
bugs = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
code_lower = code.lower()
|
| 107 |
code_no_space = code.lower().replace(' ', '')
|
| 108 |
lines = code.split('\n')
|
|
|
|
| 115 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 3,
|
| 116 |
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 117 |
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
|
| 118 |
+
"confidence": 0.95,
|
| 119 |
"languages": ["python", "javascript", "typescript"]
|
| 120 |
})
|
| 121 |
|
| 122 |
# Command Injection
|
| 123 |
+
if re.search(r'(os\.system|subprocess|popen|shell=true)\s*\(|exec\s*\(|shell\s*=\s*true', code, re.I):
|
| 124 |
bugs.append({
|
| 125 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 126 |
"comment": "Command injection: User input directly in shell command.",
|
|
|
|
| 135 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 136 |
"comment": "Hardcoded password/credential detected.",
|
| 137 |
"fix": "Use environment variables: os.getenv('DB_PASSWORD')",
|
| 138 |
+
"confidence": 0.98,
|
| 139 |
"languages": ["python", "javascript", "typescript", "java", "go", "cpp"]
|
| 140 |
})
|
| 141 |
|
|
|
|
| 152 |
# ============ HIGH SEVERITY SECURITY BUGS (Severity 4) ============
|
| 153 |
|
| 154 |
# Hardcoded API keys
|
| 155 |
+
if re.search(r'(api_key|apikey|secret_key|private_key|token|auth_token|bearer)\s*[=:]\s*["\'][a-zA-Z0-9_\-]{8,}["\']', code, re.I):
|
| 156 |
bugs.append({
|
| 157 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 1,
|
| 158 |
"comment": "Hardcoded API key/token detected.",
|
|
|
|
| 313 |
return bugs
|
| 314 |
|
| 315 |
|
| 316 |
+
@app.get("/api/health")
|
| 317 |
+
async def health_check():
|
| 318 |
+
"""Health check endpoint that returns supported languages and API status"""
|
|
|
|
|
|
|
| 319 |
return {
|
| 320 |
+
"status": "ok",
|
| 321 |
+
"version": "2.0",
|
| 322 |
+
"supported_languages": ["python", "javascript", "typescript", "java", "go", "cpp"],
|
| 323 |
+
"features": [
|
| 324 |
+
"comprehensive_bug_detection",
|
| 325 |
+
"confidence_scores",
|
| 326 |
+
"multi_language_support",
|
| 327 |
+
"export_json_reports"
|
| 328 |
+
],
|
| 329 |
+
"api_endpoints": [
|
| 330 |
+
"/api/review (POST) - Analyze code",
|
| 331 |
+
"/api/health (GET) - This endpoint",
|
| 332 |
+
"/api/stats (GET) - Usage statistics"
|
| 333 |
+
]
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
@app.get("/api/stats")
|
| 338 |
+
async def get_stats():
|
| 339 |
+
"""Return usage statistics and bug detection summary"""
|
| 340 |
+
return {
|
| 341 |
+
"message": "Stats endpoint - tracks would be stored in session/DB",
|
| 342 |
+
"supported_check_types": 30,
|
| 343 |
+
"languages": 6,
|
| 344 |
+
"security_checks": 12,
|
| 345 |
+
"logic_checks": 8,
|
| 346 |
+
"style_checks": 10
|
| 347 |
}
|
|
|
|
| 348 |
code_lower = code.lower()
|
| 349 |
code_no_space = code.lower().replace(' ', '')
|
| 350 |
lines = code.split('\n')
|
| 351 |
|
| 352 |
# ============ CRITICAL SECURITY BUGS (Severity 5) ============
|
| 353 |
|
| 354 |
+
# SQL Injection (High confidence if f-string + SQL keywords)
|
| 355 |
if ('f"' in code or "f'" in code) and any(sql in code_lower for sql in ['select', 'insert', 'delete', 'update', 'from', 'where']) and '{' in code and '}' in code:
|
| 356 |
+
bugs.append({
|
| 357 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 3,
|
| 358 |
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 359 |
+
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
|
| 360 |
+
"confidence": 0.95, # Very high confidence
|
| 361 |
+
"languages": ["python", "javascript", "typescript"]
|
| 362 |
+
})
|
| 363 |
|
| 364 |
# Command Injection
|
| 365 |
+
if re.search(r'(os\.system|subprocess|popen|shell=true|exec\(|eval\()\s*\(.*f["\']|shell\s*=\s*true', code, re.I):
|
| 366 |
+
bugs.append({
|
| 367 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 368 |
"comment": "Command injection: User input directly in shell command.",
|
| 369 |
+
"fix": "Use subprocess with args as list: subprocess.run(['ls', filename], shell=False)",
|
| 370 |
+
"confidence": 0.92,
|
| 371 |
+
"languages": ["python", "javascript", "java"]
|
| 372 |
+
})
|
| 373 |
|
| 374 |
+
# Hardcoded credentials
|
| 375 |
if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
|
| 376 |
+
bugs.append({
|
| 377 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 378 |
"comment": "Hardcoded password/credential detected.",
|
| 379 |
+
"fix": "Use environment variables: os.getenv('DB_PASSWORD')",
|
| 380 |
+
"confidence": 0.98, # Almost certain
|
| 381 |
+
"languages": ["python", "javascript", "typescript", "java", "go", "cpp"]
|
| 382 |
+
})
|
| 383 |
|
| 384 |
+
# Code execution vulnerabilities
|
| 385 |
if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
|
| 386 |
+
bugs.append({
|
| 387 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 388 |
"comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
|
| 389 |
+
"fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives",
|
| 390 |
+
"confidence": 0.99,
|
| 391 |
+
"languages": ["python", "javascript"]
|
| 392 |
+
})
|
| 393 |
|
| 394 |
# ============ HIGH SEVERITY SECURITY BUGS (Severity 4) ============
|
| 395 |
|
| 396 |
+
# Hardcoded API keys
|
| 397 |
+
if re.search(r'(api_key|apikey|secret_key|private_key|token|auth_token|bearer|sk_|pk_)\s*[=:]\s*["\'][a-zA-Z0-9_\-]{8,}["\']', code, re.I):
|
| 398 |
+
bugs.append({
|
| 399 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 1,
|
| 400 |
"comment": "Hardcoded API key/token detected.",
|
| 401 |
+
"fix": "api_key = os.getenv('API_KEY')",
|
| 402 |
+
"confidence": 0.96,
|
| 403 |
+
"languages": ["python", "javascript", "typescript", "java", "go"]
|
| 404 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 405 |
|
| 406 |
+
# XSS vulnerability
|
| 407 |
if lang == 'javascript' and re.search(r'\.innerHTML\s*=|\.eval\(|dangerouslySetInnerHTML', code):
|
| 408 |
+
bugs.append({
|
| 409 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 410 |
"comment": "XSS vulnerability: Setting innerHTML with user data can execute scripts.",
|
| 411 |
+
"fix": "Use .textContent or sanitize HTML: DOMPurify.sanitize()",
|
| 412 |
+
"confidence": 0.94,
|
| 413 |
+
"languages": ["javascript", "typescript"]
|
| 414 |
+
})
|
| 415 |
|
| 416 |
+
# Insecure random
|
| 417 |
if re.search(r'(random\.|Math\.random\(\)|rand\(\))', code) and not re.search(r'(secrets|systemrandom|cryptographically|urandom)', code, re.I):
|
| 418 |
+
bugs.append({
|
| 419 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 420 |
"comment": "Weak random number generator for security purposes.",
|
| 421 |
+
"fix": "Use: secrets.token_hex() or os.urandom() for cryptographic randomness",
|
| 422 |
+
"confidence": 0.88,
|
| 423 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 424 |
+
})
|
| 425 |
|
| 426 |
# ============ LOGIC BUGS ============
|
| 427 |
|
| 428 |
+
# Mutable default argument (Python-specific)
|
| 429 |
+
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
|
| 430 |
+
bugs.append({
|
| 431 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 1,
|
| 432 |
+
"comment": "Mutable default argument: List/dict is shared across all function calls.",
|
| 433 |
+
"fix": "Use None as default: def func(lst=None): if lst is None: lst = []",
|
| 434 |
+
"confidence": 0.98,
|
| 435 |
+
"languages": ["python"]
|
| 436 |
+
})
|
| 437 |
|
| 438 |
+
# Modifying list while iterating
|
| 439 |
+
if lang == 'python' and re.search(r'for\s+\w+\s+in\s+\w+:.*\.remove\(|for\s+\w+\s+in\s+\w+:.*\.pop\(', code, re.DOTALL):
|
| 440 |
+
bugs.append({
|
| 441 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 442 |
+
"comment": "Modifying list while iterating: Causes items to be skipped.",
|
| 443 |
+
"fix": "Iterate over a copy: for item in items[:]: or use list comprehension",
|
| 444 |
+
"confidence": 0.91,
|
| 445 |
+
"languages": ["python"]
|
| 446 |
+
})
|
| 447 |
+
|
| 448 |
+
# Shadowing built-ins (Python)
|
| 449 |
+
if lang == 'python':
|
| 450 |
+
builtins = ['list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'len', 'range', 'map', 'filter', 'zip', 'open', 'sum']
|
| 451 |
+
for builtin in builtins:
|
| 452 |
+
if re.search(rf'^{builtin}\s*=', code, re.MULTILINE):
|
| 453 |
+
bugs.append({
|
| 454 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 1,
|
| 455 |
+
"comment": f"Shadowing built-in '{builtin}': Overwrites Python's {builtin}() function.",
|
| 456 |
+
"fix": f"Rename variable: use my_{builtin} or similar",
|
| 457 |
+
"confidence": 0.99,
|
| 458 |
+
"languages": ["python"]
|
| 459 |
+
})
|
| 460 |
+
break
|
| 461 |
|
| 462 |
+
# Division by zero
|
| 463 |
+
if re.search(r'\/\s*0(?![a-zA-Z0-9])', code):
|
| 464 |
+
bugs.append({
|
| 465 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 466 |
+
"comment": "Potential division by zero. Check denominator is non-zero.",
|
| 467 |
+
"fix": "Add check: if denominator != 0: result = numerator / denominator",
|
| 468 |
+
"confidence": 0.99,
|
| 469 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 470 |
+
})
|
| 471 |
|
| 472 |
# Off-by-one errors
|
| 473 |
+
if re.search(r'\[\s*\w+\s*\+\s*1\s*\]|\[.*:.*-\s*1\]|range\(len', code):
|
| 474 |
+
bugs.append({
|
| 475 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 476 |
+
"comment": "Off-by-one error: May access beyond array bounds or skip elements.",
|
| 477 |
+
"fix": "Use range(len(arr)) or check bounds: if i+1 < len(arr)",
|
| 478 |
+
"confidence": 0.85,
|
| 479 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 480 |
+
})
|
| 481 |
|
| 482 |
+
# Resource leak
|
| 483 |
+
if re.search(r'open\s*\([^)]+\)\s*(?!with|as)', code) and '.close()' not in code:
|
| 484 |
+
bugs.append({
|
| 485 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 486 |
"comment": "Resource leak: File opened without 'with' statement. May not close properly.",
|
| 487 |
+
"fix": "Use: with open(file) as f: ... (automatic close)",
|
| 488 |
+
"confidence": 0.93,
|
| 489 |
+
"languages": ["python"]
|
| 490 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 491 |
|
| 492 |
+
# Infinite recursion (Python)
|
| 493 |
+
if lang == 'python' and re.search(r'def\s+\w+.*:\s*.*return\s+\1\s*\(', code, re.DOTALL):
|
| 494 |
+
bugs.append({
|
| 495 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 496 |
+
"comment": "Infinite recursion: Function calls itself without base case.",
|
| 497 |
+
"fix": "Add base case: if condition: return value",
|
| 498 |
+
"confidence": 0.87,
|
| 499 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 500 |
+
})
|
| 501 |
|
| 502 |
+
# Bare except (Python)
|
| 503 |
+
if lang == 'python' and re.search(r'except\s*:\s*(?!.*#)', code):
|
| 504 |
+
bugs.append({
|
| 505 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 506 |
+
"comment": "Bare except clause: Catches all exceptions including KeyboardInterrupt.",
|
| 507 |
+
"fix": "Specify exception: except ValueError: or except Exception:",
|
| 508 |
+
"confidence": 0.96,
|
| 509 |
+
"languages": ["python"]
|
| 510 |
+
})
|
| 511 |
|
| 512 |
# Type errors
|
| 513 |
+
if lang == 'python' and re.search(r'["\'][^"\']*["\'].*\+.*[0-9]|["\'][^"\']*["\'].*\+\s*\w+(?![\"\')])', code):
|
| 514 |
+
bugs.append({
|
| 515 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 516 |
+
"comment": "Type error: Cannot concatenate string with number directly.",
|
| 517 |
+
"fix": "Convert to string: str(value) or use f-string: f'text {value}'",
|
| 518 |
+
"confidence": 0.82,
|
| 519 |
+
"languages": ["python"]
|
| 520 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 521 |
|
| 522 |
+
# Missing return statement (Python)
|
| 523 |
+
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n\s{4,}result\s*=', code) and not re.search(r'return\s+result', code):
|
| 524 |
+
bugs.append({
|
| 525 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 526 |
+
"comment": "Missing return statement: Function computes value but returns None.",
|
| 527 |
+
"fix": "Add return: return result",
|
| 528 |
+
"confidence": 0.89,
|
| 529 |
+
"languages": ["python"]
|
| 530 |
+
})
|
| 531 |
|
| 532 |
+
# Race condition (threading/multiprocessing)
|
| 533 |
+
if re.search(r'threading\.|multiprocessing\.|Thread|Process|concurrent', code, re.I) and not re.search(r'Lock|RLock|Semaphore|Mutex|synchronized', code, re.I):
|
| 534 |
+
bugs.append({
|
| 535 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 536 |
+
"comment": "Race condition: Multithreaded code without synchronization.",
|
| 537 |
+
"fix": "Use locks: lock = threading.Lock(); with lock: shared_var += 1",
|
| 538 |
+
"confidence": 0.80,
|
| 539 |
+
"languages": ["python", "java", "go", "cpp"]
|
| 540 |
+
})
|
| 541 |
|
| 542 |
+
# Inefficient nested loops
|
| 543 |
+
if code.count('for ') >= 2 and ('range(10000)' in code or 'range(1000)' in code):
|
| 544 |
+
bugs.append({
|
| 545 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 546 |
+
"comment": "Performance issue: Nested loops with large ranges (O(n²) complexity).",
|
| 547 |
+
"fix": "Use set/dict for O(1) lookup or optimize algorithm",
|
| 548 |
+
"confidence": 0.75,
|
| 549 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 550 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
|
| 552 |
+
# Sort bugs by severity (highest first)
|
| 553 |
+
bugs.sort(key=lambda x: x['severity'], reverse=True)
|
| 554 |
|
| 555 |
+
return bugs
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
def analyze_code_locally(code: str, lang: str) -> dict:
|
| 559 |
+
"""Pattern-based code analysis - DEPRECATED: Use analyze_code_comprehensively instead"""
|
| 560 |
+
bugs = analyze_code_comprehensively(code, lang)
|
| 561 |
+
if bugs:
|
| 562 |
+
return bugs[0]
|
| 563 |
return {
|
| 564 |
"type": "approve",
|
| 565 |
"category": "style",
|
| 566 |
"severity": 1,
|
| 567 |
"line_hint": None,
|
| 568 |
"comment": "No obvious bugs detected. Code looks clean.",
|
| 569 |
+
"fix": "",
|
| 570 |
+
"confidence": 1.0
|
| 571 |
}
|