refactor: reduce duplication in unsafe attr checks (#22033)

This commit is contained in:
Ankush Menat 2023-08-13 18:23:41 +05:30 committed by GitHub
parent 74d78dafce
commit 4d5a945861
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 38 deletions

View file

@ -2252,28 +2252,12 @@ def bold(text):
def safe_eval(code, eval_globals=None, eval_locals=None):
"""A safer `eval`"""
from frappe.utils.safe_exec import UNSAFE_ATTRIBUTES
whitelisted_globals = {"int": int, "float": float, "long": int, "round": round}
code = unicodedata.normalize("NFKC", code)
UNSAFE_ATTRIBUTES = {
# Generator Attributes
"gi_frame",
"gi_code",
# Coroutine Attributes
"cr_frame",
"cr_code",
"cr_origin",
# Async Generator Attributes
"ag_code",
"ag_frame",
# Traceback Attributes
"tb_frame",
"tb_next",
# Format Attributes
"format",
"format_map",
}
for attribute in UNSAFE_ATTRIBUTES:
if attribute in code:
throw(f'Illegal rule {bold(code)}. Cannot use "{attribute}"')

View file

@ -368,31 +368,41 @@ def _getitem(obj, key):
return obj[key]
UNSAFE_ATTRIBUTES = {
# Generator Attributes
"gi_frame",
"gi_code",
"gi_yieldfrom",
# Coroutine Attributes
"cr_frame",
"cr_code",
"cr_origin",
"cr_await",
# Async Generator Attributes
"ag_code",
"ag_frame",
# Traceback Attributes
"tb_frame",
"tb_next",
# Format Attributes
"format",
"format_map",
# Frame attributes
"f_back",
"f_builtins",
"f_code",
"f_globals",
"f_locals",
"f_trace",
}
def _getattr(object, name, default=None):
# guard function for RestrictedPython
# allow any key to be accessed as long as
# 1. it does not start with an underscore (safer_getattr)
# 2. it is not an UNSAFE_ATTRIBUTES
UNSAFE_ATTRIBUTES = {
# Generator Attributes
"gi_frame",
"gi_code",
# Coroutine Attributes
"cr_frame",
"cr_code",
"cr_origin",
# Async Generator Attributes
"ag_code",
"ag_frame",
# Traceback Attributes
"tb_frame",
"tb_next",
# Format Attributes
"format",
"format_map",
}
if isinstance(name, str) and (name in UNSAFE_ATTRIBUTES):
raise SyntaxError(f"{name} is an unsafe attribute")