Skip to content

Harden calculate_reward: replace unsafe eval() with safe arithmetic evaluator#1197

Open
0xmrma wants to merge 5 commits intogoogle:mainfrom
0xmrma:fix-safe-math-eval
Open

Harden calculate_reward: replace unsafe eval() with safe arithmetic evaluator#1197
0xmrma wants to merge 5 commits intogoogle:mainfrom
0xmrma:fix-safe-math-eval

Conversation

@0xmrma
Copy link
Copy Markdown

@0xmrma 0xmrma commented Mar 5, 2026

What changed

This PR removes Python eval() usage from tunix/rl/agentic/rewards/reward.py::calculate_reward and replaces it with a safe arithmetic evaluator based on an AST allowlist.

Why

calculate_reward derives an expression from task["question"] and previously evaluated it with full Python semantics. If tasks/questions originate from untrusted sources (shared datasets/benchmarks/task files), this can lead to unintended code execution in the context of the running process.

Implementation details

  • Introduces _safe_eval_math() that supports:
    • numeric literals (int/float)
    • parentheses
    • unary ops: +, -
    • binary ops: +, -, *, /, //, %, ** (with exponent guardrails)
  • Rejects anything else (names, calls, attributes, subscripts, comprehensions, etc.) by raising UnsafeExpressionError
  • calculate_reward now uses _safe_eval_math(expression) and safely returns score 0.0 on invalid/unsafe expressions (existing try/except behavior preserved)

Tests

Extends tests/rl/agentic/rewards/reward_test.py to cover:

  • correct arithmetic evaluation (2 + 2)
  • unsafe expression rejection (__import__('os').system(...))
  • large exponent guard (2 ** 5000)
  • division-by-zero continues to fail safely

Note: local test execution on my environment is blocked by missing absl in an externally managed Python environment; CI should validate.

Security context

This is a defensive hardening change that eliminates an eval() injection/code-execution risk while preserving expected arithmetic behavior.

@google-cla
Copy link
Copy Markdown

google-cla Bot commented Mar 5, 2026

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly improves the security posture of the calculate_reward function by replacing a direct call to Python's eval() with a custom-built, Abstract Syntax Tree (AST)-based safe arithmetic evaluator. This change eliminates a critical vulnerability where untrusted input could lead to arbitrary code execution, ensuring that only intended mathematical operations are performed while maintaining the function's core logic.

Highlights

  • Security Hardening: Replaced the unsafe eval() function in calculate_reward with a custom, secure arithmetic evaluator to mitigate code injection risks from untrusted input.
  • Safe Evaluator Implementation: Introduced _safe_eval_math which uses Python's ast module to safely parse and evaluate arithmetic expressions. It supports numeric literals, parentheses, unary, and binary operations, while explicitly rejecting any unsafe constructs like names, calls, or attribute access.
  • Enhanced Test Coverage: Added new test cases to verify the correct behavior of the safe evaluator, including handling of valid arithmetic, rejection of malicious expressions (e.g., __import__('os').system(...)), and prevention of excessively large exponents.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • tests/rl/agentic/rewards/reward_test.py
    • Expanded test suite for calculate_reward to include cases for unsafe expressions (e.g., __import__('os').system) and expressions with excessively large exponents, ensuring they are correctly rejected.
  • tunix/rl/agentic/rewards/reward.py
    • Defined UnsafeExpressionError for handling disallowed syntax.
    • Implemented _safe_eval_math function to securely parse and evaluate mathematical expressions using the ast module, with explicit support for numeric literals, parentheses, and common arithmetic operators, and guardrails against large exponents.
    • Modified calculate_reward to utilize _safe_eval_math instead of the built-in eval(), enhancing security.
Activity
  • The author noted that local test execution was blocked by a missing absl dependency in their environment, and expected CI to validate the changes.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request significantly improves the security of the calculate_reward function by replacing the unsafe eval() with a custom, safe arithmetic evaluator using Python's ast module. While successfully addressing the security risk of using eval() on untrusted input, a critical syntax error was introduced in tunix/rl/agentic/rewards/reward.py where the _REGISTRY variable declaration was split, which will prevent the module from loading. Additionally, the docstring for calculate_reward should be updated to reflect that eval() is no longer used.

Comment thread tunix/rl/agentic/rewards/reward.py Outdated
Comment thread tunix/rl/agentic/rewards/reward.py Outdated
Comment thread tunix/rl/agentic/rewards/reward.py Outdated
@0xmrma
Copy link
Copy Markdown
Author

0xmrma commented Mar 5, 2026

Thanks! Addressed Gemini feedback:

  • Removed unnecessary blank lines in registry checks
  • Fixed _REGISTRY declaration to avoid SyntaxError (module now imports/compiles)
  • cla/google is green

PR should be ready for review/merge.

@0xmrma
Copy link
Copy Markdown
Author

0xmrma commented Mar 5, 2026

All set on my side

  • reward.py imports/compiles (fixed _REGISTRY declaration)
  • replaced eval() with safe AST allowlist evaluator
  • added safety test vectors (unsafe expression / large exponent)
  • cla/google is green

Happy to adjust operator support/limits or move helper placement if you prefer.

@0xmrma
Copy link
Copy Markdown
Author

0xmrma commented Mar 15, 2026

Friendly ping PR #1197 is ready (CLA green, no open threads).

It looks like GitHub is also showing “2 workflows awaiting approval” (fork PR). If a maintainer could approve/run the workflows + take a quick look when convenient, that’d be awesome. Happy to squash commits or adjust the allowlist/limits if you prefer.

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.

2 participants