Skip to content

Fix security vulnerabilities and bugs: replace eval() with AST evaluator, add security headers, fix duplicate message save#2

Open
Copilot wants to merge 2 commits into
mainfrom
copilot/fix-code-issues
Open

Fix security vulnerabilities and bugs: replace eval() with AST evaluator, add security headers, fix duplicate message save#2
Copilot wants to merge 2 commits into
mainfrom
copilot/fix-code-issues

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented Mar 11, 2026

Addresses multiple security vulnerabilities and bugs found across app.py, chat_client.py, and whatsapp_bot.js.

Security

  • eval() → AST-based evaluator: The calculator tool used eval() 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, and math/builtin functions. Attribute access, imports, and arbitrary calls are blocked at the AST node level.
# Before — bypassable blocklist
for blocked in ("__", "import", "exec", ...):
    if blocked in expr_str:
        return "❌ Güvensiz ifade"
res = eval(expr_str, {"__builtins__": {}}, allowed)  # still exploitable

# After — AST allowlist; __import__, attribute traversal, etc. all blocked
res = _safe_calc_eval(expr_str)
  • HTTP security headers: Added after_request handlers in both Flask apps to set X-Content-Type-Options: nosniff, X-Frame-Options: SAMEORIGIN, and Referrer-Policy: strict-origin-when-cross-origin.

  • Dead code in _check_api_key: The /health bypass check was unreachable — /health is 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 full enhanced string. Now branched so each path saves exactly once.

  • _decode fallback included flag byte: The exception fallback decoded the full raw blob including the 1-byte compression flag, producing a garbled leading character. Fixed to decode data[1:] in the fallback.

  • PIL Image.LANCZOS deprecation: Uses Image.Resampling.LANCZOS with 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 \command pass.

Housekeeping

  • Added .gitignore covering __pycache__/, node_modules/, .wwebjs_auth/, SQLite DB files, and uploads//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.

Co-authored-by: eeea2222 <209839587+eeea2222@users.noreply.github.com>
Copilot AI changed the title [WIP] Analyze and fix code issues in repository Fix security vulnerabilities and bugs: replace eval() with AST evaluator, add security headers, fix duplicate message save Mar 11, 2026
@eeea2222 eeea2222 marked this pull request as ready for review March 11, 2026 18:28
Copilot AI review requested due to automatic review settings March 11, 2026 18:28
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 in app.py.
  • Added after_request handlers 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.

Comment thread app.py
Comment on lines +167 to +172
_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

Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_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).

Copilot uses AI. Check for mistakes.
Comment thread app.py
Comment on lines +3191 to +3192
except ValueError as ve:
return {"text": f"❌ Hesaplama hatası: {ve}"}
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
except ValueError as ve:
return {"text": f"❌ Hesaplama hatası: {ve}"}
except Exception as e:
return {"text": f"❌ Hesaplama hatası: {e}"}

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants