evalidate 1.0.2__tar.gz → 1.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: evalidate
3
- Version: 1.0.2
3
+ Version: 1.0.3
4
4
  Summary: Validation and secure evaluation of untrusted python expressions
5
5
  Home-page: http://github.com/yaroslaff/evalidate
6
6
  Author: Yaroslav Polyakov
@@ -317,21 +317,27 @@ Description: # Evalidate
317
317
  - asteval is much slower (evalidate can be used at speed of eval() python bytecode)
318
318
  - user can provide source code which runs very long time and consumes many resources
319
319
 
320
+
321
+ [simpleeval](https://github.com/danthedeckie/simpleeval)
322
+ Very similar project, using AST approach too and optimized to re-evaluate pre-parsed expressions. But parsed expressions are stored as more high-level [ast.Expr](https://docs.python.org/3/library/ast.html#ast.Expr) type and this approach is ~10 times slower, while evalidate uses python native `code` type and evaluation itself goes at speed of python eval()
323
+
324
+
320
325
  evalidate is good to run short same code against different data.
321
326
 
322
327
  ## Benchmarking
323
- We use `evalidate-vs-asteval.py` which is in benchmark/ directory of repository
328
+ We use `evalidate-vs-asteval.py` which is in benchmark/ directory of repository.
329
+ We prepare list of 1 million of products (actually, we take just 100 products sample, but repeat it 10 000 times to get 1 million), and then filter it, finding only specific products on "untrusted user-supplied expression" (`price < 20` in this case)
330
+
324
331
  ~~~
325
- $ ./evalidate-vs-asteval.py
326
- Src: a+b
327
- Context: {'a': 1, 'b': 2}
328
- Runs: 100000
329
- asteval: 3.538s
330
- asteval (reuse interpreter): 1.232s
331
- safeeval: 2.384s
332
- evalidate/compile/eval (reuse compiled code): 0.017s
332
+ Products: 1000000 items
333
+ test_asteval_products(): 25.920s
334
+ test_simpleeval_products(): 1.779s
335
+ test_evalidate_products(): 0.160s
333
336
  ~~~
334
- 0.017s vs 1.232s
337
+
338
+ As you see, evalidate is almost 10 times faster then simpleeval and both are much faster then asteval.
339
+
340
+ Maybe my test is not perfectly optimized (I'm not expert with simpleeval/asteval), if you can suggest better filtering sample code (which produces faster result), I will include it. But benchmark code must assume expression as unknown and untrusted.
335
341
 
336
342
 
337
343
  ## Read about eval() risks
@@ -352,4 +358,10 @@ Description: # Evalidate
352
358
  Write me: yaroslaff at gmail.com
353
359
 
354
360
  Platform: UNKNOWN
361
+ Classifier: Programming Language :: Python :: 3
362
+ Classifier: License :: OSI Approved :: MIT License
363
+ Classifier: Operating System :: OS Independent
364
+ Classifier: Topic :: Utilities
365
+ Classifier: Topic :: Security
366
+ Classifier: Topic :: Software Development :: Interpreters
355
367
  Description-Content-Type: text/markdown
@@ -309,21 +309,27 @@ While asteval can compute much more complex code (define functions, use python m
309
309
  - asteval is much slower (evalidate can be used at speed of eval() python bytecode)
310
310
  - user can provide source code which runs very long time and consumes many resources
311
311
 
312
+
313
+ [simpleeval](https://github.com/danthedeckie/simpleeval)
314
+ Very similar project, using AST approach too and optimized to re-evaluate pre-parsed expressions. But parsed expressions are stored as more high-level [ast.Expr](https://docs.python.org/3/library/ast.html#ast.Expr) type and this approach is ~10 times slower, while evalidate uses python native `code` type and evaluation itself goes at speed of python eval()
315
+
316
+
312
317
  evalidate is good to run short same code against different data.
313
318
 
314
319
  ## Benchmarking
315
- We use `evalidate-vs-asteval.py` which is in benchmark/ directory of repository
320
+ We use `evalidate-vs-asteval.py` which is in benchmark/ directory of repository.
321
+ We prepare list of 1 million of products (actually, we take just 100 products sample, but repeat it 10 000 times to get 1 million), and then filter it, finding only specific products on "untrusted user-supplied expression" (`price < 20` in this case)
322
+
316
323
  ~~~
317
- $ ./evalidate-vs-asteval.py
318
- Src: a+b
319
- Context: {'a': 1, 'b': 2}
320
- Runs: 100000
321
- asteval: 3.538s
322
- asteval (reuse interpreter): 1.232s
323
- safeeval: 2.384s
324
- evalidate/compile/eval (reuse compiled code): 0.017s
324
+ Products: 1000000 items
325
+ test_asteval_products(): 25.920s
326
+ test_simpleeval_products(): 1.779s
327
+ test_evalidate_products(): 0.160s
325
328
  ~~~
326
- 0.017s vs 1.232s
329
+
330
+ As you see, evalidate is almost 10 times faster then simpleeval and both are much faster then asteval.
331
+
332
+ Maybe my test is not perfectly optimized (I'm not expert with simpleeval/asteval), if you can suggest better filtering sample code (which produces faster result), I will include it. But benchmark code must assume expression as unknown and untrusted.
327
333
 
328
334
 
329
335
  ## Read about eval() risks
@@ -3,21 +3,25 @@
3
3
  """Safe user-supplied python expression evaluation."""
4
4
 
5
5
  import ast
6
- import sys
6
+
7
+ __version__ = '1.0.2'
7
8
 
8
9
 
9
10
  class EvalException(Exception):
10
11
  pass
11
12
 
13
+
12
14
  class ValidationException(EvalException):
13
15
  pass
14
16
 
17
+
15
18
  class CompilationException(EvalException):
16
19
  exc = None
17
20
  def __init__(self, exc):
18
21
  super().__init__(exc)
19
22
  self.exc = exc
20
23
 
24
+
21
25
  class ExecutionException(EvalException):
22
26
  exc = None
23
27
  def __init__(self, exc):
@@ -50,8 +54,8 @@ class SafeAST(ast.NodeVisitor):
50
54
  subscript = ['Subscript', 'Index'] # person['name']
51
55
  boolop = ['BoolOp', 'And', 'Or', 'UnaryOp', 'Not'] # True and True
52
56
  inop = ["In", "NotIn"] # "aaa" in i['list']
53
- ifop = ["IfExp"] # for if expressions, like: expr1 if expr2 else expr3
54
- nameconst = ["NameConstant"] # for True and False constants
57
+ ifop = ["IfExp"] # for if expressions, like: expr1 if expr2 else expr3
58
+ nameconst = ["NameConstant"] # for True and False constants
55
59
  div = ["Div", "Mod"]
56
60
 
57
61
  self.allowed = expression + constant + values + compare + \
@@ -66,28 +70,27 @@ class SafeAST(ast.NodeVisitor):
66
70
 
67
71
  def generic_visit(self, node):
68
72
  """Check node, raise exception if node is not in whitelist."""
69
-
73
+
70
74
  if type(node).__name__ in self.allowed:
71
75
 
72
76
  if isinstance(node, ast.Attribute):
73
77
  if node.attr not in self.allowed_attrs:
74
78
  raise ValidationException(
75
79
  "Attribute {aname} is not allowed".format(
76
- aname=node.attr))
77
-
80
+ aname=node.attr))
78
81
 
79
82
  if isinstance(node, ast.Call):
80
83
  if isinstance(node.func, ast.Name):
81
84
  if node.func.id not in self.allowed_funcs:
82
85
  raise ValidationException(
83
86
  "Call to function {fname}() is not allowed".format(
84
- fname=node.func.id))
87
+ fname=node.func.id))
85
88
  else:
86
89
  # Call to allowed function. good. No exception
87
- pass
90
+ pass
88
91
  elif isinstance(node.func, ast.Attribute):
89
92
  pass
90
- # print("attr:", node.func.attr)
93
+ # print("attr:", node.func.attr)
91
94
  else:
92
95
  raise ValidationException('Indirect function call')
93
96
 
@@ -109,14 +112,52 @@ def evalidate(expression, safenodes=None, addnodes=None, funcs=None, attrs=None)
109
112
  except SyntaxError as e:
110
113
  raise CompilationException(e)
111
114
 
112
-
113
115
  v = SafeAST(safenodes, addnodes, funcs, attrs)
114
116
  v.visit(node)
115
117
  return node
116
118
 
117
119
 
118
120
  def safeeval(expression, context={}, safenodes=None, addnodes=None, funcs=None, attrs=None):
119
- """C-style simplified wrapper, eval() replacement."""
121
+ """C-style simplified wrapper, eval() replacement.
122
+
123
+ Args:
124
+ expr (str): the expression to evaluate
125
+
126
+ safenodes (List[str] | None):
127
+ Specify the name of allowed AST nodes, if unspecified a default list is used.
128
+
129
+ addnodes (List[str] | None):
130
+ List of additional AST node names to allow in addition to safenodes.
131
+
132
+ funcs (List[str]):
133
+ list of allowed function names.
134
+
135
+ attrs (List[str]):
136
+ list of allowed attribute names.
137
+
138
+ Returns:
139
+ Any: the result of the expression
140
+
141
+ Raises:
142
+ ExecutionException - if the expression fails to execute
143
+ CompilationException - if the expression fails to parse
144
+ ValidationException - if the expression fails safety checks
145
+
146
+ Example:
147
+ >>> import evalidate
148
+ >>> evalidate.safeeval('3 + 2')
149
+ 5
150
+ >>> evalidate.safeeval('max(3, 2)')
151
+ Traceback (most recent call last):
152
+ ...
153
+ evalidate.ValidationException: Operation type Call is not allowed
154
+ >>> evalidate.safeeval('max(3, 2)', addnodes=['Call'])
155
+ Traceback (most recent call last):
156
+ ...
157
+ evalidate.ValidationException: Call to function max() is not allowed
158
+ >>> evalidate.safeeval('max(3, 2)', addnodes=['Call'], funcs=['max'])
159
+ 3
160
+ """
120
161
 
121
162
  # ValidationException thrown here
122
163
  node = evalidate(expression, safenodes, addnodes, funcs, attrs)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: evalidate
3
- Version: 1.0.2
3
+ Version: 1.0.3
4
4
  Summary: Validation and secure evaluation of untrusted python expressions
5
5
  Home-page: http://github.com/yaroslaff/evalidate
6
6
  Author: Yaroslav Polyakov
@@ -317,21 +317,27 @@ Description: # Evalidate
317
317
  - asteval is much slower (evalidate can be used at speed of eval() python bytecode)
318
318
  - user can provide source code which runs very long time and consumes many resources
319
319
 
320
+
321
+ [simpleeval](https://github.com/danthedeckie/simpleeval)
322
+ Very similar project, using AST approach too and optimized to re-evaluate pre-parsed expressions. But parsed expressions are stored as more high-level [ast.Expr](https://docs.python.org/3/library/ast.html#ast.Expr) type and this approach is ~10 times slower, while evalidate uses python native `code` type and evaluation itself goes at speed of python eval()
323
+
324
+
320
325
  evalidate is good to run short same code against different data.
321
326
 
322
327
  ## Benchmarking
323
- We use `evalidate-vs-asteval.py` which is in benchmark/ directory of repository
328
+ We use `evalidate-vs-asteval.py` which is in benchmark/ directory of repository.
329
+ We prepare list of 1 million of products (actually, we take just 100 products sample, but repeat it 10 000 times to get 1 million), and then filter it, finding only specific products on "untrusted user-supplied expression" (`price < 20` in this case)
330
+
324
331
  ~~~
325
- $ ./evalidate-vs-asteval.py
326
- Src: a+b
327
- Context: {'a': 1, 'b': 2}
328
- Runs: 100000
329
- asteval: 3.538s
330
- asteval (reuse interpreter): 1.232s
331
- safeeval: 2.384s
332
- evalidate/compile/eval (reuse compiled code): 0.017s
332
+ Products: 1000000 items
333
+ test_asteval_products(): 25.920s
334
+ test_simpleeval_products(): 1.779s
335
+ test_evalidate_products(): 0.160s
333
336
  ~~~
334
- 0.017s vs 1.232s
337
+
338
+ As you see, evalidate is almost 10 times faster then simpleeval and both are much faster then asteval.
339
+
340
+ Maybe my test is not perfectly optimized (I'm not expert with simpleeval/asteval), if you can suggest better filtering sample code (which produces faster result), I will include it. But benchmark code must assume expression as unknown and untrusted.
335
341
 
336
342
 
337
343
  ## Read about eval() risks
@@ -352,4 +358,10 @@ Description: # Evalidate
352
358
  Write me: yaroslaff at gmail.com
353
359
 
354
360
  Platform: UNKNOWN
361
+ Classifier: Programming Language :: Python :: 3
362
+ Classifier: License :: OSI Approved :: MIT License
363
+ Classifier: Operating System :: OS Independent
364
+ Classifier: Topic :: Utilities
365
+ Classifier: Topic :: Security
366
+ Classifier: Topic :: Software Development :: Interpreters
355
367
  Description-Content-Type: text/markdown
@@ -0,0 +1,26 @@
1
+ from setuptools import setup
2
+ import os
3
+
4
+
5
+ def read(fname):
6
+ return open(os.path.join(os.path.dirname(__file__), fname), encoding='utf-8').read()
7
+
8
+ setup(name='evalidate',
9
+ version='1.0.3',
10
+ url='http://github.com/yaroslaff/evalidate',
11
+ author='Yaroslav Polyakov',
12
+ author_email='xenon@sysattack.com',
13
+ license='MIT',
14
+ packages=['evalidate'],
15
+ description='Validation and secure evaluation of untrusted python expressions',
16
+ long_description=read('README.md'),
17
+ long_description_content_type='text/markdown',
18
+ classifiers=[
19
+ "Programming Language :: Python :: 3",
20
+ "License :: OSI Approved :: MIT License",
21
+ "Operating System :: OS Independent",
22
+ 'Topic :: Utilities',
23
+ "Topic :: Security",
24
+ "Topic :: Software Development :: Interpreters",
25
+ ],
26
+ zip_safe=False)
evalidate-1.0.2/setup.py DELETED
@@ -1,18 +0,0 @@
1
- from setuptools import setup
2
- import os
3
-
4
- def read(fname):
5
- return open(os.path.join(os.path.dirname(__file__), fname), encoding='utf-8').read()
6
-
7
- setup(name='evalidate',
8
- version='1.0.2',
9
- url='http://github.com/yaroslaff/evalidate',
10
- author='Yaroslav Polyakov',
11
- author_email='xenon@sysattack.com',
12
- license='MIT',
13
- packages=['evalidate'],
14
- description = 'Validation and secure evaluation of untrusted python expressions',
15
- long_description = read('README.md'),
16
- long_description_content_type='text/markdown',
17
- zip_safe=False)
18
-
File without changes