Fix security vulnerabilities and bugs: replace eval() with AST evaluator, add security headers, fix duplicate message save#2
Conversation
Co-authored-by: eeea2222 <209839587+eeea2222@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
This PR addresses several security and correctness issues across the main Flask app, the standalone web chat client, and the WhatsApp bot by hardening the calculator tool, adding baseline HTTP response security headers, and fixing message/history handling edge cases.
Changes:
- Replaced the calculator’s
eval()execution with an AST-based allowlist evaluator inapp.py. - Added
after_requesthandlers to set baseline security headers in both Flask apps. - Fixed WhatsApp bot message persistence deduplication (image vs text) and tightened LaTeX cleanup regexes.
Reviewed changes
Copilot reviewed 3 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
app.py |
Introduces _safe_calc_eval (AST-based calculator), adjusts decode fallback behavior, Pillow resampling compatibility, adds security headers, and removes dead/unreachable API-key bypass logic. |
chat_client.py |
Adds baseline HTTP response security headers via @app.after_request. |
whatsapp_bot.js |
Prevents duplicate user-message saves for image flow and refines LaTeX stripping regexes. |
.gitignore |
Adds ignores for common runtime artifacts (Python, Node, SQLite DB, uploads/sandbox dirs). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| _NAMES: Dict[str, Any] = { | ||
| k: v for k, v in math.__dict__.items() if not k.startswith("__") | ||
| } | ||
| for _fn in (abs, round, min, max, sum, int, float): | ||
| _NAMES[_fn.__name__] = _fn | ||
|
|
There was a problem hiding this comment.
_safe_calc_eval whitelists all math module symbols (including expensive functions like factorial, comb, etc.) and allows ** on unbounded integers. Inputs like factorial(100000) or 10**10000000 can cause CPU/memory exhaustion (DoS) even though code execution is blocked. Consider restricting the allowed function set to a small curated list and enforcing limits (e.g., max integer bit-length / max exponent / max factorial argument / max AST nodes).
| except ValueError as ve: | ||
| return {"text": f"❌ Hesaplama hatası: {ve}"} |
There was a problem hiding this comment.
The calculator tool only catches ValueError from _safe_calc_eval, but runtime errors like ZeroDivisionError, OverflowError, or TypeError will fall through to the generic execute_tool exception handler and produce an inconsistent/less clear error response. Consider catching Exception here (or in _safe_calc_eval) and converting it into the same user-facing “Hesaplama hatası” shape.
| except ValueError as ve: | |
| return {"text": f"❌ Hesaplama hatası: {ve}"} | |
| except Exception as e: | |
| return {"text": f"❌ Hesaplama hatası: {e}"} |
Addresses multiple security vulnerabilities and bugs found across
app.py,chat_client.py, andwhatsapp_bot.js.Security
eval()→ AST-based evaluator: The calculator tool usedeval()guarded only by a string blocklist — trivially bypassed. Replaced with a strict allowlist-only AST walker (_safe_calc_eval) that permits only numeric constants, whitelisted arithmetic operators, andmath/builtin functions. Attribute access, imports, and arbitrary calls are blocked at the AST node level.HTTP security headers: Added
after_requesthandlers in both Flask apps to setX-Content-Type-Options: nosniff,X-Frame-Options: SAMEORIGIN, andReferrer-Policy: strict-origin-when-cross-origin.Dead code in
_check_api_key: The/healthbypass check was unreachable —/healthis already excluded by the/api/prefix guard above it. Removed.Bug Fixes
Duplicate WhatsApp message save on image: When a user sent an image,
saveMsg()was called twice — once as[Görsel] ${prompt}and once as the fullenhancedstring. Now branched so each path saves exactly once._decodefallback included flag byte: The exception fallback decoded the full raw blob including the 1-byte compression flag, producing a garbled leading character. Fixed to decodedata[1:]in the fallback.PIL
Image.LANCZOSdeprecation: UsesImage.Resampling.LANCZOSwith a fallback for Pillow < 10 compatibility.LaTeX
$...$regex in WhatsApp bot: Tightened inline dollar regex to support single-char expressions ($x$) while avoiding false matches on currency patterns ($5 and $10). Added an explicit\command{...}pass before the bare\commandpass.Housekeeping
.gitignorecovering__pycache__/,node_modules/,.wwebjs_auth/, SQLite DB files, anduploads//Sandbox/runtime dirs.✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.