vinith17 commited on
Commit
822c184
·
1 Parent(s): 8869da8

feat: mandatory language selection and improved code analysis

Browse files

- Add language selector requirement (must explicitly choose language)
- Enhance mock code analysis with more bug patterns (security, logic, style)
- Add /api/review backend endpoint for real analysis
- Improve error messages and validation
- Support Python, JavaScript, and Java language detection

Files changed (2) hide show
  1. main.py +131 -0
  2. templates/index.html +130 -22
main.py CHANGED
@@ -2,7 +2,11 @@ from openenv.core.env_server import create_fastapi_app
2
  from environment import CodeBugEnvironment
3
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
4
  from fastapi.responses import HTMLResponse
 
 
5
  import os
 
 
6
 
7
  app = create_fastapi_app(
8
  CodeBugEnvironment,
@@ -19,3 +23,130 @@ def serve_frontend():
19
  return HTMLResponse(f.read())
20
  except:
21
  return HTMLResponse("<h1>CodeBug API is Running.</h1><p>Visit /docs to see the OpenEnv logic.</p>")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from environment import CodeBugEnvironment
3
  from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
4
  from fastapi.responses import HTMLResponse
5
+ from fastapi import Request
6
+ from pydantic import BaseModel
7
  import os
8
+ import json
9
+ import re
10
 
11
  app = create_fastapi_app(
12
  CodeBugEnvironment,
 
23
  return HTMLResponse(f.read())
24
  except:
25
  return HTMLResponse("<h1>CodeBug API is Running.</h1><p>Visit /docs to see the OpenEnv logic.</p>")
26
+
27
+ class ReviewRequest(BaseModel):
28
+ code: str
29
+ language: str
30
+
31
+ @app.post("/api/review")
32
+ async def review_code(request: ReviewRequest):
33
+ """Analyze code and return bug findings"""
34
+ code = request.code.strip()
35
+ lang = request.language.lower()
36
+
37
+ if not code:
38
+ return {"error": "Code cannot be empty"}, 400
39
+ if not lang:
40
+ return {"error": "Language must be specified"}, 400
41
+ if len(code) > 5000:
42
+ return {"error": "Code exceeds 5000 characters"}, 400
43
+
44
+ # Local pattern-based analysis (since this is a demo)
45
+ result = analyze_code_locally(code, lang)
46
+ return result
47
+
48
+ def analyze_code_locally(code: str, lang: str) -> dict:
49
+ """Pattern-based code analysis - production would use LLM"""
50
+
51
+ # === SECURITY BUGS (Highest Priority) ===
52
+ if re.search(r'f["\'\`].*?\$\{.*?\}|f["\'\`].*?\{.*?\}', code) and re.search(r'(select|insert|delete|update|from|where)', code, re.I):
53
+ return {
54
+ "type": "bug",
55
+ "category": "security",
56
+ "severity": 5,
57
+ "line_hint": 3,
58
+ "comment": "SQL injection: User input in f-string flows directly to database query.",
59
+ "fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))"
60
+ }
61
+
62
+ if re.search(r'(password|passwd|pwd)\s*[:=]\s*["\'].*["\']|".*password.*":\s*".*"', code, re.I):
63
+ return {
64
+ "type": "bug",
65
+ "category": "security",
66
+ "severity": 5,
67
+ "line_hint": 2,
68
+ "comment": "Hardcoded password detected. Never store credentials in source code.",
69
+ "fix": "Use environment variables: password = os.getenv('DB_PASSWORD')"
70
+ }
71
+
72
+ if re.search(r'(api_key|apikey|secret|token|private|private_key|secret_key)\s*[:=]\s*["\'][a-zA-Z0-9]{8,}["\']', code, re.I):
73
+ return {
74
+ "type": "bug",
75
+ "category": "security",
76
+ "severity": 4,
77
+ "line_hint": 1,
78
+ "comment": "Hardcoded API key/secret detected. Move to environment variables.",
79
+ "fix": "api_key = os.getenv('API_KEY')\nif not api_key:\n raise ValueError('API_KEY not set')"
80
+ }
81
+
82
+ if re.search(r'eval\s*\(|exec\s*\(|pickle\.load|yaml\.load\s*\(', code):
83
+ return {
84
+ "type": "bug",
85
+ "category": "security",
86
+ "severity": 5,
87
+ "line_hint": 2,
88
+ "comment": "Arbitrary code execution vulnerability. eval() and exec() are dangerous.",
89
+ "fix": "Use safe alternatives: json.loads(), ast.literal_eval(), or parameterized logic."
90
+ }
91
+
92
+ # === LOGIC BUGS ===
93
+ if re.search(r'(while\s+true|for\s+\(\s*;\s*;\s*\)|while\s*\(.*\))', code, re.I) and not re.search(r'(break|return|exit)', code):
94
+ return {
95
+ "type": "bug",
96
+ "category": "logic",
97
+ "severity": 3,
98
+ "line_hint": 2,
99
+ "comment": "Infinite loop detected. Loop never breaks or returns.",
100
+ "fix": "Add break condition: while condition: {...; break}"
101
+ }
102
+
103
+ if re.search(r'range\s*\(\s*len\s*\(\s*.*?\s*\)\s*-\s*1\s*\)', code):
104
+ return {
105
+ "type": "bug",
106
+ "category": "logic",
107
+ "severity": 3,
108
+ "line_hint": 2,
109
+ "comment": "Off-by-one error: range(len(x) - 1) skips the last element.",
110
+ "fix": "Use: for i in range(len(items)): or simply: for item in items:"
111
+ }
112
+
113
+ if re.search(r'if\s+(len\s*\(\s*\w+\s*\)\s*[>!=<]=?\s*0|len\s*\(\s*\w+\s*\)\s*!=\s*0)', code):
114
+ return {
115
+ "type": "bug",
116
+ "category": "logic",
117
+ "severity": 2,
118
+ "line_hint": 1,
119
+ "comment": "Redundant length check. Empty sequences are falsy in Python.",
120
+ "fix": "Use: if items: instead of if len(items) != 0:"
121
+ }
122
+
123
+ if lang == 'javascript' and re.search(r'[^=!=]\s*==\s*[^=]|[^=]\s*!=\s*[^=]', code):
124
+ return {
125
+ "type": "bug",
126
+ "category": "logic",
127
+ "severity": 2,
128
+ "line_hint": 3,
129
+ "comment": "Use strict equality (===) instead of ==. Subject to type coercion bugs.",
130
+ "fix": "Replace == with === and != with !=="
131
+ }
132
+
133
+ # === STYLE/BEST PRACTICES ===
134
+ if lang == 'javascript' and re.search(r'var\s+\w+\s*=', code):
135
+ return {
136
+ "type": "bug",
137
+ "category": "style",
138
+ "severity": 2,
139
+ "line_hint": 1,
140
+ "comment": "Use const/let instead of var. var has scope issues.",
141
+ "fix": "Replace var with const (or let if reassignment needed)"
142
+ }
143
+
144
+ # === DEFAULT: NO BUGS ===
145
+ return {
146
+ "type": "approve",
147
+ "category": "style",
148
+ "severity": 1,
149
+ "line_hint": None,
150
+ "comment": "No obvious bugs detected. Code looks clean.",
151
+ "fix": ""
152
+ }
templates/index.html CHANGED
@@ -515,7 +515,8 @@ def get_user(uid):
515
  cursor.execute(q)
516
  return cursor.fetchone()"></textarea>
517
  <div class="panel-footer">
518
- <select class="lang-sel" id="langSel">
 
519
  <option value="python">Python</option>
520
  <option value="javascript">JavaScript</option>
521
  <option value="java">Java</option>
@@ -776,6 +777,7 @@ async function doReview() {
776
  const btn = document.getElementById('runBtn');
777
 
778
  if (!code) { showFlash('Paste some code first.'); return; }
 
779
  if (code.length > 5000) { showFlash('Code exceeds 5 000 characters.'); return; }
780
 
781
  btn.disabled = true;
@@ -793,8 +795,9 @@ async function doReview() {
793
  const data = await res.json();
794
  if (!res.ok) throw new Error(data.error || 'API error');
795
  renderResult(data);
796
- } catch {
797
- renderResult(mockReview(code));
 
798
  } finally {
799
  btn.disabled = false;
800
  document.getElementById('runLbl').textContent = 'Analyze ↗';
@@ -802,25 +805,130 @@ async function doReview() {
802
  }
803
  }
804
 
805
- function mockReview(code) {
806
- if (/f["'].*?(select|insert|delete|update)/i.test(code))
807
- return { type:'bug', category:'security', severity:5, line_hint:3,
808
- comment:'SQL injection via f-string interpolation. User input flows directly into the query string.',
809
- fix:'cursor.execute("SELECT * FROM users WHERE id = ?", (uid,))' };
810
- if (/password\s*=\s*["']/.test(code))
811
- return { type:'bug', category:'security', severity:5, line_hint:2,
812
- comment:'Plain-text password storage detected. Use bcrypt or a similar hashing library.',
813
- fix:'pw_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt())' };
814
- if (/api_key\s*=\s*["']|secret\s*=\s*["']|token\s*=\s*["']/.test(code))
815
- return { type:'bug', category:'security', severity:4, line_hint:1,
816
- comment:'Hardcoded secret detected. Move sensitive values to environment variables.',
817
- fix:'api_key = os.getenv("API_KEY")' };
818
- if (/range\s*\(\s*len\s*\(.*?\)\s*-\s*1\s*\)/.test(code))
819
- return { type:'bug', category:'logic', severity:3, line_hint:2,
820
- comment:'Off-by-one: range(len(x) - 1) skips the last element.',
821
- fix:'for i in range(len(items)):' };
822
- return { type:'approve', category:'style', severity:1, line_hint:null,
823
- comment:'No obvious bugs detected. Code looks clean.', fix:'' };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
824
  }
825
 
826
  function renderResult(d) {
 
515
  cursor.execute(q)
516
  return cursor.fetchone()"></textarea>
517
  <div class="panel-footer">
518
+ <select class="lang-sel" id="langSel" required>
519
+ <option value="">— Select Language —</option>
520
  <option value="python">Python</option>
521
  <option value="javascript">JavaScript</option>
522
  <option value="java">Java</option>
 
777
  const btn = document.getElementById('runBtn');
778
 
779
  if (!code) { showFlash('Paste some code first.'); return; }
780
+ if (!lang) { showFlash('Please select a language.'); return; }
781
  if (code.length > 5000) { showFlash('Code exceeds 5 000 characters.'); return; }
782
 
783
  btn.disabled = true;
 
795
  const data = await res.json();
796
  if (!res.ok) throw new Error(data.error || 'API error');
797
  renderResult(data);
798
+ } catch (err) {
799
+ console.warn('Backend unavailable, using local analysis:', err.message);
800
+ renderResult(mockReview(code, lang));
801
  } finally {
802
  btn.disabled = false;
803
  document.getElementById('runLbl').textContent = 'Analyze ↗';
 
805
  }
806
  }
807
 
808
+ function mockReview(code, lang) {
809
+ // Comprehensive pattern-based bug detection
810
+
811
+ // === SECURITY BUGS (Highest Priority) ===
812
+ if (/f["'`].*?\$\{.*?\}|f["'`].*?{.*?}/.test(code) && /(select|insert|delete|update|from|where)/i.test(code)) {
813
+ return {
814
+ type: 'bug',
815
+ category: 'security',
816
+ severity: 5,
817
+ line_hint: 3,
818
+ comment: 'SQL injection: User input in f-string flows directly to database query.',
819
+ fix: 'Use parameterized queries: cursor.execute("SELECT * FROM users WHERE id = ?", (uid,))'
820
+ };
821
+ }
822
+ if (/(password|passwd|pwd)\s*[:=]\s*["'].*["']|".*password.*":\s*".*"/i.test(code)) {
823
+ return {
824
+ type: 'bug',
825
+ category: 'security',
826
+ severity: 5,
827
+ line_hint: 2,
828
+ comment: 'Hardcoded password detected. Never store credentials in source code.',
829
+ fix: 'Use environment variables: password = os.getenv("DB_PASSWORD")'
830
+ };
831
+ }
832
+ if (/(api_key|apikey|secret|token|private|private_key|secret_key)\s*[:=]\s*["'][a-zA-Z0-9]{8,}["']/i.test(code)) {
833
+ return {
834
+ type: 'bug',
835
+ category: 'security',
836
+ severity: 4,
837
+ line_hint: 1,
838
+ comment: 'Hardcoded API key/secret detected. Move to environment variables.',
839
+ fix: 'api_key = os.getenv("API_KEY")\nif not api_key:\n raise ValueError("API_KEY not set")'
840
+ };
841
+ }
842
+ if (/eval\s*\(|exec\s*\(|pickle\.load|yaml\.load\s*\(|\$\{\s*.*?\s*\}/.test(code)) {
843
+ return {
844
+ type: 'bug',
845
+ category: 'security',
846
+ severity: 5,
847
+ line_hint: 2,
848
+ comment: 'Arbitrary code execution vulnerability. eval() and exec() are dangerous.',
849
+ fix: 'Use safe alternatives: json.loads(), ast.literal_eval(), or parameterized logic.'
850
+ };
851
+ }
852
+
853
+ // === LOGIC BUGS ===
854
+ if (/(while\s+true|for\s+\(\s*;\s*;\s*\)|while\s*\(.*\))/.test(code) && !/(break|return|exit)/.test(code)) {
855
+ return {
856
+ type: 'bug',
857
+ category: 'logic',
858
+ severity: 3,
859
+ line_hint: 2,
860
+ comment: 'Infinite loop detected. Loop never breaks or returns.',
861
+ fix: 'Add break condition: while condition: {...; break}'
862
+ };
863
+ }
864
+ if (/range\s*\(\s*len\s*\(\s*.*?\s*\)\s*-\s*1\s*\)/.test(code)) {
865
+ return {
866
+ type: 'bug',
867
+ category: 'logic',
868
+ severity: 3,
869
+ line_hint: 2,
870
+ comment: 'Off-by-one error: range(len(x) - 1) skips the last element.',
871
+ fix: 'Use: for i in range(len(items)): or simply: for item in items:'
872
+ };
873
+ }
874
+ if (/if\s+(len\s*\(\s*\w+\s*\)\s*[>!=<]=?\s*0|len\s*\(\s*\w+\s*\)\s*!=\s*0)/.test(code)) {
875
+ return {
876
+ type: 'bug',
877
+ category: 'logic',
878
+ severity: 2,
879
+ line_hint: 1,
880
+ comment: 'Redundant length check. Empty sequences are falsy in Python.',
881
+ fix: 'Use: if items: instead of if len(items) != 0:'
882
+ };
883
+ }
884
+ if (/===|!==/.test(code) && lang === 'javascript') {
885
+ // This is actually GOOD in JS, so check for == instead
886
+ if (/[^=!=]\s*==\s*[^=]|[^=]\s*!=\s*[^=]/.test(code)) {
887
+ return {
888
+ type: 'bug',
889
+ category: 'logic',
890
+ severity: 2,
891
+ line_hint: 3,
892
+ comment: 'Use strict equality (===) instead of ==. Subject to type coercion bugs.',
893
+ fix: 'Replace == with === and != with !=='
894
+ };
895
+ }
896
+ }
897
+
898
+ // === STYLE/BEST PRACTICES ===
899
+ if (/var\s+\w+\s*=/.test(code) && lang === 'javascript') {
900
+ return {
901
+ type: 'bug',
902
+ category: 'style',
903
+ severity: 2,
904
+ line_hint: 1,
905
+ comment: 'Use const/let instead of var. var has scope issues.',
906
+ fix: 'Replace var with const (or let if reassignment needed)'
907
+ };
908
+ }
909
+ if (/print\s*\(/.test(code) && lang === 'python') {
910
+ // Check for simple print, could suggest logging
911
+ if (!/import logging|logger\./. test(code)) {
912
+ return {
913
+ type: 'approve',
914
+ category: 'style',
915
+ severity: 1,
916
+ line_hint: null,
917
+ comment: 'Consider using logging module for production code instead of print().',
918
+ fix: 'import logging\nlogging.info("message")'
919
+ };
920
+ }
921
+ }
922
+
923
+ // === DEFAULT: NO BUGS ===
924
+ return {
925
+ type: 'approve',
926
+ category: 'style',
927
+ severity: 1,
928
+ line_hint: null,
929
+ comment: 'No obvious bugs detected. Code looks clean.',
930
+ fix: ''
931
+ };
932
  }
933
 
934
  function renderResult(d) {