# safepyeval
`safepyeval` is a Python library designed for the safe evaluation of a restricted subset of Python expressions.
This tool is particularly useful in environments where running arbitrary Python code can pose a security risk,
such as in any application requiring controlled execution of user-submitted code.
The library specifically excludes support for loops (`for` and `while`) due to their potential for creating harmful scenarios,
such as infinite loops or overly complex computations that can drain system resources.
The controlled environment is achieved by parsing the submitted code into an Abstract Syntax Tree (AST) (using the Python ast module), allowing for a granular inspection and execution of code elements. Importantly, the Python interpreter is not used to execute the code, which completely prevents the execution of unsafe operations. Therefore it is extremely safe to use `safepyeval` in any environment.
## Installation
You can install SafePyEval using pip:
```bash
pip install safepyeval
```
## Usage
Import the library and use the evaluate function to safely execute Python code. Here's a basic example:
```python
import safepyeval
code = '''
admin_user_ids = ['admin', 'user1']
if userId in admin_user_ids:
return True
else:
return False
result = safepyeval.evaluate(code, {'userId': 'user1'})
# result is True
```
## Capabilities
`safepyeval` supports a variety of Python features while ensuring a secure execution environment:
- Variable Assignments: You can define and use variables within the code.
- Conditional Statements: if, else, and elif statements are supported.
- Comparisons and Boolean Operations: Including ==, !=, <, <=, >, >=, and, or, and not.
- Mathematical and String Operations: Basic operations like +, -, *, /, and string manipulation.
- Data Structures: Use of lists, dictionaries, and access to their elements.
## Limitations
To maintain safety and prevent abuse, safepyeval does not implement certain parts of Python:
- Loops: for and while loops are not implemented, as they can lead to dangerous behavior like infinite loops.
- File I/O: No file reading or writing to prevent unauthorized access to the file system.
- Network Operations: Disabled to prevent network-based attacks or unauthorized data transmission.
- Importing Modules: Importing of modules is disabled.
- Executing Shell Commands: Disabled to avoid executing operating system commands.
## Advanced Example
```python
import safepyeval
code = '''
admin_user_ids = ['magland', 'admin']
max_num_cpus_for_admin = 8
max_num_cpus_for_privileged_users = 4
other_users = {
'user3': {
'max_num_cpus': 2
},
'user4': {
'max_num_cpus': 1
}
}
if userId in admin_user_ids and not userId == 'magland':
if nCpus <= max_num_cpus_for_admin:
return True
else:
return False
elif userId in ['user1', 'user2']:
if nCpus <= max_num_cpus_for_privileged_users:
return True
else:
return False
else:
if userId in other_users:
if nCpus <= other_users[userId]['max_num_cpus']:
return True
else:
return False
else:
return False
'''
result1 = safepyeval.evaluate(code, {'userId': 'user1', 'nCpus': 4})
# result1 is True
result2 = safepyeval.evaluate(code, {'userId': 'user1', 'nCpus': 8})
# result2 is False
# etc.
```
## Size of codebase
The library is very small, consisting of a single Python file (safepyeval.py) with around 100 or so lines of code.
## License
This package is released under Apache License 2.0.
## Author
Created by Jeremy Magland
Raw data
{
"_id": null,
"home_page": "https://github.com/magland/safepyeval",
"name": "safepyeval",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "",
"author": "Jeremy Magland",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/b5/35/6d56965ec3d6afba826bd1062fca00271913a7a42ab302639faaaa7ecd84/safepyeval-0.1.0.tar.gz",
"platform": null,
"description": "# safepyeval\n\n`safepyeval` is a Python library designed for the safe evaluation of a restricted subset of Python expressions.\nThis tool is particularly useful in environments where running arbitrary Python code can pose a security risk,\nsuch as in any application requiring controlled execution of user-submitted code.\n\nThe library specifically excludes support for loops (`for` and `while`) due to their potential for creating harmful scenarios,\nsuch as infinite loops or overly complex computations that can drain system resources.\n\nThe controlled environment is achieved by parsing the submitted code into an Abstract Syntax Tree (AST) (using the Python ast module), allowing for a granular inspection and execution of code elements. Importantly, the Python interpreter is not used to execute the code, which completely prevents the execution of unsafe operations. Therefore it is extremely safe to use `safepyeval` in any environment.\n\n\n## Installation\n\nYou can install SafePyEval using pip:\n\n```bash\npip install safepyeval\n```\n\n\n## Usage\n\nImport the library and use the evaluate function to safely execute Python code. Here's a basic example:\n\n```python\nimport safepyeval\n\ncode = '''\nadmin_user_ids = ['admin', 'user1']\nif userId in admin_user_ids:\n return True\nelse:\n return False\n\nresult = safepyeval.evaluate(code, {'userId': 'user1'})\n# result is True\n```\n\n## Capabilities\n\n`safepyeval` supports a variety of Python features while ensuring a secure execution environment:\n\n- Variable Assignments: You can define and use variables within the code.\n- Conditional Statements: if, else, and elif statements are supported.\n- Comparisons and Boolean Operations: Including ==, !=, <, <=, >, >=, and, or, and not.\n- Mathematical and String Operations: Basic operations like +, -, *, /, and string manipulation.\n- Data Structures: Use of lists, dictionaries, and access to their elements.\n\n## Limitations\n\nTo maintain safety and prevent abuse, safepyeval does not implement certain parts of Python:\n\n- Loops: for and while loops are not implemented, as they can lead to dangerous behavior like infinite loops.\n- File I/O: No file reading or writing to prevent unauthorized access to the file system.\n- Network Operations: Disabled to prevent network-based attacks or unauthorized data transmission.\n- Importing Modules: Importing of modules is disabled.\n- Executing Shell Commands: Disabled to avoid executing operating system commands.\n\n## Advanced Example\n\n```python\nimport safepyeval\n\ncode = '''\nadmin_user_ids = ['magland', 'admin']\nmax_num_cpus_for_admin = 8\nmax_num_cpus_for_privileged_users = 4\nother_users = {\n 'user3': {\n 'max_num_cpus': 2\n },\n 'user4': {\n 'max_num_cpus': 1\n }\n}\nif userId in admin_user_ids and not userId == 'magland':\n if nCpus <= max_num_cpus_for_admin:\n return True\n else:\n return False\nelif userId in ['user1', 'user2']:\n if nCpus <= max_num_cpus_for_privileged_users:\n return True\n else:\n return False\nelse:\n if userId in other_users:\n if nCpus <= other_users[userId]['max_num_cpus']:\n return True\n else:\n return False\n else:\n return False\n'''\n\nresult1 = safepyeval.evaluate(code, {'userId': 'user1', 'nCpus': 4})\n# result1 is True\nresult2 = safepyeval.evaluate(code, {'userId': 'user1', 'nCpus': 8})\n# result2 is False\n# etc.\n```\n\n## Size of codebase\n\nThe library is very small, consisting of a single Python file (safepyeval.py) with around 100 or so lines of code.\n\n## License\n\nThis package is released under Apache License 2.0.\n\n## Author\n\nCreated by Jeremy Magland\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "Safely evaluate simple Python programs",
"version": "0.1.0",
"project_urls": {
"Homepage": "https://github.com/magland/safepyeval",
"Repository": "https://github.com/magland/safepyeval"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "4e5103b5877228fe8caeb7ffc574b7d77b6ef9eb451d62e08ad7366f65e356be",
"md5": "772821111dcf48f77cf42f82ac4c47ad",
"sha256": "af207b8c7aba54a5120a09ba7a73af2c169ca1fe6f9941bd47d91e8b42bcee9c"
},
"downloads": -1,
"filename": "safepyeval-0.1.0-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "772821111dcf48f77cf42f82ac4c47ad",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": null,
"size": 8038,
"upload_time": "2024-01-17T15:54:44",
"upload_time_iso_8601": "2024-01-17T15:54:44.882376Z",
"url": "https://files.pythonhosted.org/packages/4e/51/03b5877228fe8caeb7ffc574b7d77b6ef9eb451d62e08ad7366f65e356be/safepyeval-0.1.0-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "b5356d56965ec3d6afba826bd1062fca00271913a7a42ab302639faaaa7ecd84",
"md5": "95c2ee85a9268b4e91bc08aca1dd825e",
"sha256": "8f0de5c5613fc4bd947f10b6847ea26bab50a1e3424dfc2154cb91838eca455c"
},
"downloads": -1,
"filename": "safepyeval-0.1.0.tar.gz",
"has_sig": false,
"md5_digest": "95c2ee85a9268b4e91bc08aca1dd825e",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 7309,
"upload_time": "2024-01-17T15:54:46",
"upload_time_iso_8601": "2024-01-17T15:54:46.626876Z",
"url": "https://files.pythonhosted.org/packages/b5/35/6d56965ec3d6afba826bd1062fca00271913a7a42ab302639faaaa7ecd84/safepyeval-0.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-01-17 15:54:46",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "magland",
"github_project": "safepyeval",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "safepyeval"
}