Debian Codegraph @

IPython/core/guarded_eval.py

raw
1 from copy import copy
2 from inspect import isclass, signature, Signature, getmodule
3 from typing import (
4 Annotated,
5 AnyStr,
6 Literal,
7 NamedTuple,
8 NewType,
9 Optional,
10 Protocol,
11 TypeGuard,
12 Union,
13 get_args,
14 get_origin,
15 is_typeddict,
16 )
17 from collections.abc import Callable, Sequence
18 import ast
19 import builtins
20 import collections
21 import dataclasses
22 import operator
23 import sys
24 import typing
25 import warnings
26 from functools import cached_property
27 from dataclasses import dataclass, field
28 from types import MethodDescriptorType, ModuleType, MethodType
29
30 from IPython.utils.decorators import undoc
31
32 import types
33 from typing import Self, LiteralString, get_type_hints
34
35 from typing import TypeAliasType
36
37
38 @undoc
39 class HasGetItem(Protocol):
40 def __getitem__(self, key) -> None:
41 ...
42
43
44 @undoc
45 class InstancesHaveGetItem(Protocol):
46 def __call__(self, *args, **kwargs) -> HasGetItem:
47 ...
48
49
50 @undoc
51 class HasGetAttr(Protocol):
52 def __getattr__(self, key) -> None:
53 ...
54
55
56 @undoc
57 class DoesNotHaveGetAttr(Protocol):
58 pass
59
60
61 # By default `__getattr__` is not explicitly implemented on most objects
62 MayHaveGetattr = Union[HasGetAttr, DoesNotHaveGetAttr]
63
64
65 def _unbind_method(func: Callable) -> Union[Callable, None]:
66 """Get unbound method for given bound method.
67
68 Returns None if cannot get unbound method, or method is already unbound.
69 """
70 owner = getattr(func, "__self__", None)
71 owner_class = type(owner)
72 name = getattr(func, "__name__", None)
73 instance_dict_overrides = getattr(owner, "__dict__", None)
74 if (
75 owner is not None
76 and name
77 and (
78 not instance_dict_overrides
79 or (instance_dict_overrides and name not in instance_dict_overrides)
80 )
81 ):
82 return getattr(owner_class, name)
83 return None
84
85
86 @undoc
87 @dataclass
88 class EvaluationPolicy:
89 """Definition of evaluation policy."""
90
91 allow_locals_access: bool = False
92 allow_globals_access: bool = False
93 allow_item_access: bool = False
94 allow_attr_access: bool = False
95 allow_builtins_access: bool = False
96 allow_all_operations: bool = False
97 allow_any_calls: bool = False
98 allow_auto_import: bool = False
99 allowed_calls: set[Callable] = field(default_factory=set)
100
101 def can_get_item(self, value, item):
102 return self.allow_item_access
103
104 def can_get_attr(self, value, attr):
105 return self.allow_attr_access
106
107 def can_operate(self, dunders: tuple[str, ...], a, b=None):
108 if self.allow_all_operations:
109 return True
110
111 def can_call(self, func):
112 if self.allow_any_calls:
113 return True
114
115 if func in self.allowed_calls:
116 return True
117
118 owner_method = _unbind_method(func)
119
120 if owner_method and owner_method in self.allowed_calls:
121 return True
122
123
124 def _get_external(module_name: str, access_path: Sequence[str]):
125 """Get value from external module given a dotted access path.
126
127 Only gets value if the module is already imported.
128
129 Raises:
130 * `KeyError` if module is removed not found, and
131 * `AttributeError` if access path does not match an exported object
132 """
133 try:
134 member_type = sys.modules[module_name]
135 # standard module
136 for attr in access_path:
137 member_type = getattr(member_type, attr)
138 return member_type
139 except (KeyError, AttributeError):
140 # handle modules in namespace packages
141 module_path = ".".join([module_name, *access_path])
142 if module_path in sys.modules:
143 return sys.modules[module_path]
144 raise
145
146
147 def _has_original_dunder_external(
148 value,
149 module_name: str,
150 access_path: Sequence[str],
151 method_name: str,
152 ):
153 if module_name not in sys.modules:
154 full_module_path = ".".join([module_name, *access_path])
155 if full_module_path not in sys.modules:
156 # LBYLB as it is faster
157 return False
158 try:
159 member_type = _get_external(module_name, access_path)
160 value_type = type(value)
161 if type(value) == member_type:
162 return True
163 if isinstance(member_type, ModuleType):
164 value_module = getmodule(value_type)
165 if not value_module or not value_module.__name__:
166 return False
167 if (
168 value_module.__name__ == member_type.__name__
169 or value_module.__name__.startswith(member_type.__name__ + ".")
170 ):
171 return True
172 if method_name == "__getattribute__":
173 # we have to short-circuit here due to an unresolved issue in
174 # `isinstance` implementation: https://bugs.python.org/issue32683
175 return False
176 if not isinstance(member_type, ModuleType) and isinstance(value, member_type):
177 method = getattr(value_type, method_name, None)
178 member_method = getattr(member_type, method_name, None)
179 if member_method == method:
180 return True
181 if isinstance(member_type, ModuleType):
182 method = getattr(value_type, method_name, None)
183 for base_class in value_type.__mro__[1:]:
184 base_module = getmodule(base_class)
185 if base_module and (
186 base_module.__name__ == member_type.__name__
187 or base_module.__name__.startswith(member_type.__name__ + ".")
188 ):
189 # Check if the method comes from this trusted base class
190 base_method = getattr(base_class, method_name, None)
191 if base_method is not None and base_method == method:
192 return True
193 except (AttributeError, KeyError):
194 return False
195
196
197 def _has_original_dunder(
198 value, allowed_types, allowed_methods, allowed_external, method_name
199 ):
200 # note: Python ignores `__getattr__`/`__getitem__` on instances,
201 # we only need to check at class level
202 value_type = type(value)
203
204 # strict type check passes → no need to check method
205 if value_type in allowed_types:
206 return True
207
208 method = getattr(value_type, method_name, None)
209
210 if method is None:
211 return None
212
213 if method in allowed_methods:
214 return True
215
216 for module_name, *access_path in allowed_external:
217 if _has_original_dunder_external(value, module_name, access_path, method_name):
218 return True
219
220 return False
221
222
223 def _coerce_path_to_tuples(
224 allow_list: set[tuple[str, ...] | str],
225 ) -> set[tuple[str, ...]]:
226 """Replace dotted paths on the provided allow-list with tuples."""
227 return {
228 path if isinstance(path, tuple) else tuple(path.split("."))
229 for path in allow_list
230 }
231
232
233 @undoc
234 @dataclass
235 class SelectivePolicy(EvaluationPolicy):
236 allowed_getitem: set[InstancesHaveGetItem] = field(default_factory=set)
237 allowed_getitem_external: set[tuple[str, ...] | str] = field(default_factory=set)
238
239 allowed_getattr: set[MayHaveGetattr] = field(default_factory=set)
240 allowed_getattr_external: set[tuple[str, ...] | str] = field(default_factory=set)
241
242 allowed_operations: set = field(default_factory=set)
243 allowed_operations_external: set[tuple[str, ...] | str] = field(default_factory=set)
244
245 allow_getitem_on_types: bool = field(default_factory=bool)
246
247 _operation_methods_cache: dict[str, set[Callable]] = field(
248 default_factory=dict, init=False
249 )
250
251 def can_get_attr(self, value, attr):
252 allowed_getattr_external = _coerce_path_to_tuples(self.allowed_getattr_external)
253
254 has_original_attribute = _has_original_dunder(
255 value,
256 allowed_types=self.allowed_getattr,
257 allowed_methods=self._getattribute_methods,
258 allowed_external=allowed_getattr_external,
259 method_name="__getattribute__",
260 )
261 has_original_attr = _has_original_dunder(
262 value,
263 allowed_types=self.allowed_getattr,
264 allowed_methods=self._getattr_methods,
265 allowed_external=allowed_getattr_external,
266 method_name="__getattr__",
267 )
268
269 accept = False
270
271 # Many objects do not have `__getattr__`, this is fine.
272 if has_original_attr is None and has_original_attribute:
273 accept = True
274 else:
275 # Accept objects without modifications to `__getattr__` and `__getattribute__`
276 accept = has_original_attr and has_original_attribute
277
278 if accept:
279 # We still need to check for overridden properties.
280
281 value_class = type(value)
282 if not hasattr(value_class, attr):
283 return True
284
285 class_attr_val = getattr(value_class, attr)
286 is_property = isinstance(class_attr_val, property)
287
288 if not is_property:
289 return True
290
291 # Properties in allowed types are ok (although we do not include any
292 # properties in our default allow list currently).
293 if type(value) in self.allowed_getattr:
294 return True # pragma: no cover
295
296 # Properties in subclasses of allowed types may be ok if not changed
297 for module_name, *access_path in allowed_getattr_external:
298 try:
299 external_class = _get_external(module_name, access_path)
300 external_class_attr_val = getattr(external_class, attr)
301 except (KeyError, AttributeError):
302 return False # pragma: no cover
303 return class_attr_val == external_class_attr_val
304
305 return False
306
307 def can_get_item(self, value, item):
308 """Allow accessing `__getiitem__` of allow-listed instances unless it was not modified."""
309 allowed_getitem_external = _coerce_path_to_tuples(self.allowed_getitem_external)
310 if self.allow_getitem_on_types:
311 # e.g. Union[str, int] or Literal[True, 1]
312 if isinstance(value, (typing._SpecialForm, typing._BaseGenericAlias)):
313 return True
314 # PEP 560 e.g. list[str]
315 if isinstance(value, type) and hasattr(value, "__class_getitem__"):
316 return True
317 return _has_original_dunder(
318 value,
319 allowed_types=self.allowed_getitem,
320 allowed_methods=self._getitem_methods,
321 allowed_external=allowed_getitem_external,
322 method_name="__getitem__",
323 )
324
325 def can_operate(self, dunders: tuple[str, ...], a, b=None):
326 allowed_operations_external = _coerce_path_to_tuples(
327 self.allowed_operations_external
328 )
329 objects = [a]
330 if b is not None:
331 objects.append(b)
332 return all(
333 [
334 _has_original_dunder(
335 obj,
336 allowed_types=self.allowed_operations,
337 allowed_methods=self._operator_dunder_methods(dunder),
338 allowed_external=allowed_operations_external,
339 method_name=dunder,
340 )
341 for dunder in dunders
342 for obj in objects
343 ]
344 )
345
346 def _operator_dunder_methods(self, dunder: str) -> set[Callable]:
347 if dunder not in self._operation_methods_cache:
348 self._operation_methods_cache[dunder] = self._safe_get_methods(
349 self.allowed_operations, dunder
350 )
351 return self._operation_methods_cache[dunder]
352
353 @cached_property
354 def _getitem_methods(self) -> set[Callable]:
355 return self._safe_get_methods(self.allowed_getitem, "__getitem__")
356
357 @cached_property
358 def _getattr_methods(self) -> set[Callable]:
359 return self._safe_get_methods(self.allowed_getattr, "__getattr__")
360
361 @cached_property
362 def _getattribute_methods(self) -> set[Callable]:
363 return self._safe_get_methods(self.allowed_getattr, "__getattribute__")
364
365 def _safe_get_methods(self, classes, name) -> set[Callable]:
366 return {
367 method
368 for class_ in classes
369 for method in [getattr(class_, name, None)]
370 if method
371 }
372
373
374 class _DummyNamedTuple(NamedTuple):
375 """Used internally to retrieve methods of named tuple instance."""
376
377
378 EvaluationPolicyName = Literal["forbidden", "minimal", "limited", "unsafe", "dangerous"]
379
380
381 @dataclass
382 class EvaluationContext:
383 #: Local namespace
384 locals: dict
385 #: Global namespace
386 globals: dict
387 #: Evaluation policy identifier
388 evaluation: EvaluationPolicyName = "forbidden"
389 #: Whether the evaluation of code takes place inside of a subscript.
390 #: Useful for evaluating ``:-1, 'col'`` in ``df[:-1, 'col']``.
391 in_subscript: bool = False
392 #: Auto import method
393 auto_import: Callable[[Sequence[str]], ModuleType] | None = None
394 #: Overrides for evaluation policy
395 policy_overrides: dict = field(default_factory=dict)
396 #: Transient local namespace used to store mocks
397 transient_locals: dict = field(default_factory=dict)
398 #: Transients of class level
399 class_transients: dict | None = None
400 #: Instance variable name used in the method definition
401 instance_arg_name: str | None = None
402 #: Currently associated value
403 #: Useful for adding items to _Duck on annotated assignment
404 current_value: ast.AST | None = None
405
406 def replace(self, /, **changes):
407 """Return a new copy of the context, with specified changes"""
408 return dataclasses.replace(self, **changes)
409
410
411 class _IdentitySubscript:
412 """Returns the key itself when item is requested via subscript."""
413
414 def __getitem__(self, key):
415 return key
416
417
418 IDENTITY_SUBSCRIPT = _IdentitySubscript()
419 SUBSCRIPT_MARKER = "__SUBSCRIPT_SENTINEL__"
420 UNKNOWN_SIGNATURE = Signature()
421 NOT_EVALUATED = object()
422
423
424 class GuardRejection(Exception):
425 """Exception raised when guard rejects evaluation attempt."""
426
427 pass
428
429
430 def guarded_eval(code: str, context: EvaluationContext):
431 """Evaluate provided code in the evaluation context.
432
433 If evaluation policy given by context is set to ``forbidden``
434 no evaluation will be performed; if it is set to ``dangerous``
435 standard :func:`eval` will be used; finally, for any other,
436 policy :func:`eval_node` will be called on parsed AST.
437 """
438 locals_ = context.locals
439
440 if context.evaluation == "forbidden":
441 raise GuardRejection("Forbidden mode")
442
443 # note: not using `ast.literal_eval` as it does not implement
444 # getitem at all, for example it fails on simple `[0][1]`
445
446 if context.in_subscript:
447 # syntactic sugar for ellipsis (:) is only available in subscripts
448 # so we need to trick the ast parser into thinking that we have
449 # a subscript, but we need to be able to later recognise that we did
450 # it so we can ignore the actual __getitem__ operation
451 if not code:
452 return tuple()
453 locals_ = locals_.copy()
454 locals_[SUBSCRIPT_MARKER] = IDENTITY_SUBSCRIPT
455 code = SUBSCRIPT_MARKER + "[" + code + "]"
456 context = context.replace(locals=locals_)
457
458 if context.evaluation == "dangerous":
459 return eval(code, context.globals, context.locals)
460
461 node = ast.parse(code, mode="exec")
462
463 return eval_node(node, context)
464
465
466 BINARY_OP_DUNDERS: dict[type[ast.operator], tuple[str]] = {
467 ast.Add: ("__add__",),
468 ast.Sub: ("__sub__",),
469 ast.Mult: ("__mul__",),
470 ast.Div: ("__truediv__",),
471 ast.FloorDiv: ("__floordiv__",),
472 ast.Mod: ("__mod__",),
473 ast.Pow: ("__pow__",),
474 ast.LShift: ("__lshift__",),
475 ast.RShift: ("__rshift__",),
476 ast.BitOr: ("__or__",),
477 ast.BitXor: ("__xor__",),
478 ast.BitAnd: ("__and__",),
479 ast.MatMult: ("__matmul__",),
480 }
481
482 COMP_OP_DUNDERS: dict[type[ast.cmpop], tuple[str, ...]] = {
483 ast.Eq: ("__eq__",),
484 ast.NotEq: ("__ne__", "__eq__"),
485 ast.Lt: ("__lt__", "__gt__"),
486 ast.LtE: ("__le__", "__ge__"),
487 ast.Gt: ("__gt__", "__lt__"),
488 ast.GtE: ("__ge__", "__le__"),
489 ast.In: ("__contains__",),
490 # Note: ast.Is, ast.IsNot, ast.NotIn are handled specially
491 }
492
493 UNARY_OP_DUNDERS: dict[type[ast.unaryop], tuple[str, ...]] = {
494 ast.USub: ("__neg__",),
495 ast.UAdd: ("__pos__",),
496 # we have to check both __inv__ and __invert__!
497 ast.Invert: ("__invert__", "__inv__"),
498 ast.Not: ("__not__",),
499 }
500
501 GENERIC_CONTAINER_TYPES = (dict, list, set, tuple, frozenset)
502
503
504 class ImpersonatingDuck:
505 """A dummy class used to create objects of other classes without calling their ``__init__``"""
506
507 # no-op: override __class__ to impersonate
508
509
510 class _Duck:
511 """A dummy class used to create objects pretending to have given attributes"""
512
513 def __init__(self, attributes: Optional[dict] = None, items: Optional[dict] = None):
514 self.attributes = attributes if attributes is not None else {}
515 self.items = items if items is not None else {}
516
517 def __getattr__(self, attr: str):
518 return self.attributes[attr]
519
520 def __hasattr__(self, attr: str):
521 return attr in self.attributes
522
523 def __dir__(self):
524 return [*dir(super), *self.attributes]
525
526 def __getitem__(self, key: str):
527 return self.items[key]
528
529 def __hasitem__(self, key: str):
530 return self.items[key]
531
532 def _ipython_key_completions_(self):
533 return self.items.keys()
534
535
536 def _find_dunder(node_op, dunders) -> Union[tuple[str, ...], None]:
537 dunder = None
538 for op, candidate_dunder in dunders.items():
539 if isinstance(node_op, op):
540 dunder = candidate_dunder
541 return dunder
542
543
544 def get_policy(context: EvaluationContext) -> EvaluationPolicy:
545 policy = copy(EVALUATION_POLICIES[context.evaluation])
546
547 for key, value in context.policy_overrides.items():
548 if hasattr(policy, key):
549 setattr(policy, key, value)
550 return policy
551
552
553 def _validate_policy_overrides(
554 policy_name: EvaluationPolicyName, policy_overrides: dict
555 ) -> bool:
556 policy = EVALUATION_POLICIES[policy_name]
557
558 all_good = True
559 for key, value in policy_overrides.items():
560 if not hasattr(policy, key):
561 warnings.warn(
562 f"Override {key!r} is not valid with {policy_name!r} evaluation policy"
563 )
564 all_good = False
565 return all_good
566
567
568 def _is_type_annotation(obj) -> bool:
569 """
570 Returns True if obj is a type annotation, False otherwise.
571 """
572 if isinstance(obj, type):
573 return True
574 if isinstance(obj, types.GenericAlias):
575 return True
576 if hasattr(types, "UnionType") and isinstance(obj, types.UnionType):
577 return True
578 if isinstance(obj, (typing._SpecialForm, typing._BaseGenericAlias)):
579 return True
580 if isinstance(obj, typing.TypeVar):
581 return True
582 # Types that support __class_getitem__
583 if isinstance(obj, type) and hasattr(obj, "__class_getitem__"):
584 return True
585 # Fallback: check if get_origin returns something
586 if hasattr(typing, "get_origin") and get_origin(obj) is not None:
587 return True
588
589 return False
590
591
592 def _handle_assign(node: ast.Assign, context: EvaluationContext):
593 value = eval_node(node.value, context)
594 transient_locals = context.transient_locals
595 policy = get_policy(context)
596 class_transients = context.class_transients
597 for target in node.targets:
598 if isinstance(target, (ast.Tuple, ast.List)):
599 # Handle unpacking assignment
600 values = list(value)
601 targets = target.elts
602 starred = [i for i, t in enumerate(targets) if isinstance(t, ast.Starred)]
603
604 # Unified handling: treat no starred as starred at end
605 star_or_last_idx = starred[0] if starred else len(targets)
606
607 # Before starred
608 for i in range(star_or_last_idx):
609 # Check for self.x assignment
610 if _is_instance_attribute_assignment(targets[i], context):
611 class_transients[targets[i].attr] = values[i]
612 else:
613 transient_locals[targets[i].id] = values[i]
614
615 # Starred if exists
616 if starred:
617 end = len(values) - (len(targets) - star_or_last_idx - 1)
618 if _is_instance_attribute_assignment(
619 targets[star_or_last_idx], context
620 ):
621 class_transients[targets[star_or_last_idx].attr] = values[
622 star_or_last_idx:end
623 ]
624 else:
625 transient_locals[targets[star_or_last_idx].value.id] = values[
626 star_or_last_idx:end
627 ]
628
629 # After starred
630 for i in range(star_or_last_idx + 1, len(targets)):
631 if _is_instance_attribute_assignment(targets[i], context):
632 class_transients[targets[i].attr] = values[
633 len(values) - (len(targets) - i)
634 ]
635 else:
636 transient_locals[targets[i].id] = values[
637 len(values) - (len(targets) - i)
638 ]
639 elif isinstance(target, ast.Subscript):
640 if isinstance(target.value, ast.Name):
641 name = target.value.id
642 container = transient_locals.get(name)
643 if container is None:
644 container = context.locals.get(name)
645 if container is None:
646 container = context.globals.get(name)
647 if container is None:
648 raise NameError(
649 f"{name} not found in locals, globals, nor builtins"
650 )
651 storage_dict = transient_locals
652 storage_key = name
653 elif isinstance(
654 target.value, ast.Attribute
655 ) and _is_instance_attribute_assignment(target.value, context):
656 attr = target.value.attr
657 container = class_transients.get(attr, None)
658 if container is None:
659 raise NameError(f"{attr} not found in class transients")
660 storage_dict = class_transients
661 storage_key = attr
662 else:
663 return
664
665 key = eval_node(target.slice, context)
666 attributes = (
667 dict.fromkeys(dir(container))
668 if policy.can_call(container.__dir__)
669 else {}
670 )
671 items = {}
672
673 if policy.can_get_item(container, None):
674 try:
675 items = dict(container.items())
676 except Exception:
677 pass
678
679 items[key] = value
680 duck_container = _Duck(attributes=attributes, items=items)
681 storage_dict[storage_key] = duck_container
682 elif _is_instance_attribute_assignment(target, context):
683 class_transients[target.attr] = value
684 else:
685 transient_locals[target.id] = value
686 return None
687
688
689 def _handle_annassign(node, context):
690 context_with_value = context.replace(current_value=getattr(node, "value", None))
691 annotation_result = eval_node(node.annotation, context_with_value)
692 if _is_type_annotation(annotation_result):
693 annotation_value = _resolve_annotation(annotation_result, context)
694 # Use Value for generic types
695 use_value = (
696 isinstance(annotation_value, GENERIC_CONTAINER_TYPES) and node.value is not None
697 )
698 else:
699 annotation_value = annotation_result
700 use_value = False
701
702 # LOCAL VARIABLE
703 if getattr(node, "simple", False) and isinstance(node.target, ast.Name):
704 name = node.target.id
705 if use_value:
706 return _handle_assign(
707 ast.Assign(targets=[node.target], value=node.value), context
708 )
709 context.transient_locals[name] = annotation_value
710 return None
711
712 # INSTANCE ATTRIBUTE
713 if _is_instance_attribute_assignment(node.target, context):
714 attr = node.target.attr
715 if use_value:
716 return _handle_assign(
717 ast.Assign(targets=[node.target], value=node.value), context
718 )
719 context.class_transients[attr] = annotation_value
720 return None
721
722 return None
723
724 def _extract_args_and_kwargs(node: ast.Call, context: EvaluationContext):
725 args = [eval_node(arg, context) for arg in node.args]
726 kwargs = {
727 k: v
728 for kw in node.keywords
729 for k, v in (
730 {kw.arg: eval_node(kw.value, context)}
731 if kw.arg
732 else eval_node(kw.value, context)
733 ).items()
734 }
735 return args, kwargs
736
737
738 def _is_instance_attribute_assignment(
739 target: ast.AST, context: EvaluationContext
740 ) -> bool:
741 """Return True if target is an attribute access on the instance argument."""
742 return (
743 context.class_transients is not None
744 and context.instance_arg_name is not None
745 and isinstance(target, ast.Attribute)
746 and isinstance(getattr(target, "value", None), ast.Name)
747 and getattr(target.value, "id", None) == context.instance_arg_name
748 )
749
750
751 def _get_coroutine_attributes() -> dict[str, Optional[object]]:
752 async def _dummy():
753 return None
754
755 coro = _dummy()
756 try:
757 return {attr: getattr(coro, attr, None) for attr in dir(coro)}
758 finally:
759 coro.close()
760
761
762 def eval_node(node: Union[ast.AST, None], context: EvaluationContext):
763 """Evaluate AST node in provided context.
764
765 Applies evaluation restrictions defined in the context. Currently does not support evaluation of functions with keyword arguments.
766
767 Does not evaluate actions that always have side effects:
768
769 - class definitions (``class sth: ...``)
770 - function definitions (``def sth: ...``)
771 - variable assignments (``x = 1``)
772 - augmented assignments (``x += 1``)
773 - deletions (``del x``)
774
775 Does not evaluate operations which do not return values:
776
777 - assertions (``assert x``)
778 - pass (``pass``)
779 - imports (``import x``)
780 - control flow:
781
782 - conditionals (``if x:``) except for ternary IfExp (``a if x else b``)
783 - loops (``for`` and ``while``)
784 - exception handling
785
786 The purpose of this function is to guard against unwanted side-effects;
787 it does not give guarantees on protection from malicious code execution.
788 """
789 policy = get_policy(context)
790
791 if node is None:
792 return None
793 if isinstance(node, (ast.Interactive, ast.Module)):
794 result = None
795 for child_node in node.body:
796 result = eval_node(child_node, context)
797 return result
798 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
799 is_async = isinstance(node, ast.AsyncFunctionDef)
800 func_locals = context.transient_locals.copy()
801 func_context = context.replace(transient_locals=func_locals)
802 is_property = False
803 is_static = False
804 is_classmethod = False
805 for decorator_node in node.decorator_list:
806 try:
807 decorator = eval_node(decorator_node, context)
808 except NameError:
809 # if the decorator is not yet defined this is fine
810 # especialy because we don't handle imports yet
811 continue
812 if decorator is property:
813 is_property = True
814 elif decorator is staticmethod:
815 is_static = True
816 elif decorator is classmethod:
817 is_classmethod = True
818
819 if func_context.class_transients is not None:
820 if not is_static and not is_classmethod:
821 func_context.instance_arg_name = (
822 node.args.args[0].arg if node.args.args else None
823 )
824
825 return_type = eval_node(node.returns, context=context)
826
827 for child_node in node.body:
828 eval_node(child_node, func_context)
829
830 if is_property:
831 if return_type is not None:
832 if _is_type_annotation(return_type):
833 context.transient_locals[node.name] = _resolve_annotation(
834 return_type, context
835 )
836 else:
837 context.transient_locals[node.name] = return_type
838 else:
839 return_value = _infer_return_value(node, func_context)
840 context.transient_locals[node.name] = return_value
841
842 return None
843
844 def dummy_function(*args, **kwargs):
845 pass
846
847 if return_type is not None:
848 if _is_type_annotation(return_type):
849 dummy_function.__annotations__["return"] = return_type
850 else:
851 dummy_function.__inferred_return__ = return_type
852 else:
853 inferred_return = _infer_return_value(node, func_context)
854 if inferred_return is not None:
855 dummy_function.__inferred_return__ = inferred_return
856
857 dummy_function.__name__ = node.name
858 dummy_function.__node__ = node
859 dummy_function.__is_async__ = is_async
860 context.transient_locals[node.name] = dummy_function
861 return None
862 if isinstance(node, ast.Lambda):
863
864 def dummy_function(*args, **kwargs):
865 pass
866
867 dummy_function.__inferred_return__ = eval_node(node.body, context)
868 return dummy_function
869 if isinstance(node, ast.ClassDef):
870 # TODO support class decorators?
871 class_locals = {}
872 outer_locals = context.locals.copy()
873 outer_locals.update(context.transient_locals)
874 class_context = context.replace(
875 transient_locals=class_locals, locals=outer_locals
876 )
877 class_context.class_transients = class_locals
878 for child_node in node.body:
879 eval_node(child_node, class_context)
880 bases = tuple([eval_node(base, context) for base in node.bases])
881 dummy_class = type(node.name, bases, class_locals)
882 context.transient_locals[node.name] = dummy_class
883 return None
884 if isinstance(node, ast.Await):
885 value = eval_node(node.value, context)
886 if hasattr(value, "__awaited_type__"):
887 return value.__awaited_type__
888 return value
889 if isinstance(node, ast.While):
890 loop_locals = context.transient_locals.copy()
891 loop_context = context.replace(transient_locals=loop_locals)
892
893 result = None
894 for stmt in node.body:
895 result = eval_node(stmt, loop_context)
896
897 policy = get_policy(context)
898 merged_locals = _merge_dicts_by_key(
899 [loop_locals, context.transient_locals.copy()], policy
900 )
901 context.transient_locals.update(merged_locals)
902
903 return result
904 if isinstance(node, ast.For):
905 try:
906 iterable = eval_node(node.iter, context)
907 except Exception:
908 iterable = None
909
910 sample = None
911 if iterable is not None:
912 try:
913 if policy.can_call(getattr(iterable, "__iter__", None)):
914 sample = next(iter(iterable))
915 except Exception:
916 sample = None
917
918 loop_locals = context.transient_locals.copy()
919 loop_context = context.replace(transient_locals=loop_locals)
920
921 if sample is not None:
922 try:
923 fake_assign = ast.Assign(
924 targets=[node.target], value=ast.Constant(value=sample)
925 )
926 _handle_assign(fake_assign, loop_context)
927 except Exception:
928 pass
929
930 result = None
931 for stmt in node.body:
932 result = eval_node(stmt, loop_context)
933
934 policy = get_policy(context)
935 merged_locals = _merge_dicts_by_key(
936 [loop_locals, context.transient_locals.copy()], policy
937 )
938 context.transient_locals.update(merged_locals)
939
940 return result
941 if isinstance(node, ast.If):
942 branches = []
943 current = node
944 result = None
945 while True:
946 branch_locals = context.transient_locals.copy()
947 branch_context = context.replace(transient_locals=branch_locals)
948 for stmt in current.body:
949 result = eval_node(stmt, branch_context)
950 branches.append(branch_locals)
951 if not current.orelse:
952 break
953 elif len(current.orelse) == 1 and isinstance(current.orelse[0], ast.If):
954 # It's an elif - continue loop
955 current = current.orelse[0]
956 else:
957 # It's an else block - process and break
958 else_locals = context.transient_locals.copy()
959 else_context = context.replace(transient_locals=else_locals)
960 for stmt in current.orelse:
961 result = eval_node(stmt, else_context)
962 branches.append(else_locals)
963 break
964 branches.append(context.transient_locals.copy())
965 policy = get_policy(context)
966 merged_locals = _merge_dicts_by_key(branches, policy)
967 context.transient_locals.update(merged_locals)
968 return result
969 if isinstance(node, ast.Assign):
970 return _handle_assign(node, context)
971 if isinstance(node, ast.AnnAssign):
972 return _handle_annassign(node, context)
973 if isinstance(node, ast.Expression):
974 return eval_node(node.body, context)
975 if isinstance(node, ast.Expr):
976 return eval_node(node.value, context)
977 if isinstance(node, ast.Pass):
978 return None
979 if isinstance(node, ast.Import):
980 # TODO: populate transient_locals
981 return None
982 if isinstance(node, (ast.AugAssign, ast.Delete)):
983 return None
984 if isinstance(node, (ast.Global, ast.Nonlocal)):
985 return None
986 if isinstance(node, ast.BinOp):
987 left = eval_node(node.left, context)
988 right = eval_node(node.right, context)
989 if (
990 isinstance(node.op, ast.BitOr)
991 and _is_type_annotation(left)
992 and _is_type_annotation(right)
993 ):
994 left_duck = (
995 _Duck(dict.fromkeys(dir(left)))
996 if policy.can_call(left.__dir__)
997 else _Duck()
998 )
999 right_duck = (
1000 _Duck(dict.fromkeys(dir(right)))
1001 if policy.can_call(right.__dir__)
1002 else _Duck()
1003 )
1004 value_node = context.current_value
1005 if value_node is not None and isinstance(value_node, ast.Dict):
1006 if dict in [left, right]:
1007 return _merge_values(
1008 [left_duck, right_duck, ast.literal_eval(value_node)],
1009 policy=get_policy(context),
1010 )
1011 return _merge_values([left_duck, right_duck], policy=get_policy(context))
1012 dunders = _find_dunder(node.op, BINARY_OP_DUNDERS)
1013 if dunders:
1014 if policy.can_operate(dunders, left, right):
1015 return getattr(left, dunders[0])(right)
1016 else:
1017 raise GuardRejection(
1018 f"Operation (`{dunders}`) for",
1019 type(left),
1020 f"not allowed in {context.evaluation} mode",
1021 )
1022 if isinstance(node, ast.Compare):
1023 left = eval_node(node.left, context)
1024 all_true = True
1025 negate = False
1026 for op, right in zip(node.ops, node.comparators):
1027 right = eval_node(right, context)
1028 dunder = None
1029 dunders = _find_dunder(op, COMP_OP_DUNDERS)
1030 if not dunders:
1031 if isinstance(op, ast.NotIn):
1032 dunders = COMP_OP_DUNDERS[ast.In]
1033 negate = True
1034 if isinstance(op, ast.Is):
1035 dunder = "is_"
1036 if isinstance(op, ast.IsNot):
1037 dunder = "is_"
1038 negate = True
1039 if not dunder and dunders:
1040 dunder = dunders[0]
1041 if dunder:
1042 a, b = (right, left) if dunder == "__contains__" else (left, right)
1043 if dunder == "is_" or dunders and policy.can_operate(dunders, a, b):
1044 result = getattr(operator, dunder)(a, b)
1045 if negate:
1046 result = not result
1047 if not result:
1048 all_true = False
1049 left = right
1050 else:
1051 raise GuardRejection(
1052 f"Comparison (`{dunder}`) for",
1053 type(left),
1054 f"not allowed in {context.evaluation} mode",
1055 )
1056 else:
1057 raise ValueError(
1058 f"Comparison `{dunder}` not supported"
1059 ) # pragma: no cover
1060 return all_true
1061 if isinstance(node, ast.Constant):
1062 return node.value
1063 if isinstance(node, ast.Tuple):
1064 return tuple(eval_node(e, context) for e in node.elts)
1065 if isinstance(node, ast.List):
1066 return [eval_node(e, context) for e in node.elts]
1067 if isinstance(node, ast.Set):
1068 return {eval_node(e, context) for e in node.elts}
1069 if isinstance(node, ast.Dict):
1070 return dict(
1071 zip(
1072 [eval_node(k, context) for k in node.keys],
1073 [eval_node(v, context) for v in node.values],
1074 )
1075 )
1076 if isinstance(node, ast.Slice):
1077 return slice(
1078 eval_node(node.lower, context),
1079 eval_node(node.upper, context),
1080 eval_node(node.step, context),
1081 )
1082 if isinstance(node, ast.UnaryOp):
1083 value = eval_node(node.operand, context)
1084 dunders = _find_dunder(node.op, UNARY_OP_DUNDERS)
1085 if dunders:
1086 if policy.can_operate(dunders, value):
1087 try:
1088 return getattr(value, dunders[0])()
1089 except AttributeError:
1090 raise TypeError(
1091 f"bad operand type for unary {node.op}: {type(value)}"
1092 )
1093 else:
1094 raise GuardRejection(
1095 f"Operation (`{dunders}`) for",
1096 type(value),
1097 f"not allowed in {context.evaluation} mode",
1098 )
1099 if isinstance(node, ast.Subscript):
1100 value = eval_node(node.value, context)
1101 slice_ = eval_node(node.slice, context)
1102 if policy.can_get_item(value, slice_):
1103 return value[slice_]
1104 raise GuardRejection(
1105 "Subscript access (`__getitem__`) for",
1106 type(value), # not joined to avoid calling `repr`
1107 f" not allowed in {context.evaluation} mode",
1108 )
1109 if isinstance(node, ast.Name):
1110 return _eval_node_name(node.id, context)
1111 if isinstance(node, ast.Attribute):
1112 if (
1113 context.class_transients is not None
1114 and isinstance(node.value, ast.Name)
1115 and node.value.id == context.instance_arg_name
1116 ):
1117 return context.class_transients.get(node.attr)
1118 value = eval_node(node.value, context)
1119 if policy.can_get_attr(value, node.attr):
1120 return getattr(value, node.attr)
1121 try:
1122 cls = (
1123 value if isinstance(value, type) else getattr(value, "__class__", None)
1124 )
1125 if cls is not None:
1126 resolved_hints = get_type_hints(
1127 cls,
1128 globalns=(context.globals or {}),
1129 localns=(context.locals or {}),
1130 )
1131 if node.attr in resolved_hints:
1132 annotated = resolved_hints[node.attr]
1133 return _resolve_annotation(annotated, context)
1134 except Exception:
1135 # Fall through to the guard rejection
1136 pass
1137 raise GuardRejection(
1138 "Attribute access (`__getattr__`) for",
1139 type(value), # not joined to avoid calling `repr`
1140 f"not allowed in {context.evaluation} mode",
1141 )
1142 if isinstance(node, ast.IfExp):
1143 test = eval_node(node.test, context)
1144 if test:
1145 return eval_node(node.body, context)
1146 else:
1147 return eval_node(node.orelse, context)
1148 if isinstance(node, ast.Call):
1149 func = eval_node(node.func, context)
1150 if policy.can_call(func):
1151 args, kwargs = _extract_args_and_kwargs(node, context)
1152 return func(*args, **kwargs)
1153 if isclass(func):
1154 # this code path gets entered when calling class e.g. `MyClass()`
1155 # or `my_instance.__class__()` - in both cases `func` is `MyClass`.
1156 # Should return `MyClass` if `__new__` is not overridden,
1157 # otherwise whatever `__new__` return type is.
1158 overridden_return_type = _eval_return_type(func.__new__, node, context)
1159 if overridden_return_type is not NOT_EVALUATED:
1160 return overridden_return_type
1161 return _create_duck_for_heap_type(func)
1162 else:
1163 inferred_return = getattr(func, "__inferred_return__", NOT_EVALUATED)
1164 return_type = _eval_return_type(func, node, context)
1165 if getattr(func, "__is_async__", False):
1166 awaited_type = (
1167 inferred_return if inferred_return is not None else return_type
1168 )
1169 coroutine_duck = _Duck(attributes=_get_coroutine_attributes())
1170 coroutine_duck.__awaited_type__ = awaited_type
1171 return coroutine_duck
1172 if inferred_return is not NOT_EVALUATED:
1173 return inferred_return
1174 if return_type is not NOT_EVALUATED:
1175 return return_type
1176 raise GuardRejection(
1177 "Call for",
1178 func, # not joined to avoid calling `repr`
1179 f"not allowed in {context.evaluation} mode",
1180 )
1181 if isinstance(node, ast.Assert):
1182 # message is always the second item, so if it is defined user would be completing
1183 # on the message, not on the assertion test
1184 if node.msg:
1185 return eval_node(node.msg, context)
1186 return eval_node(node.test, context)
1187 return None
1188
1189
1190 def _merge_dicts_by_key(dicts: list, policy: EvaluationPolicy):
1191 """Merge multiple dictionaries, combining values for each key."""
1192 if len(dicts) == 1:
1193 return dicts[0]
1194
1195 all_keys = set()
1196 for d in dicts:
1197 all_keys.update(d.keys())
1198
1199 merged = {}
1200 for key in all_keys:
1201 values = [d[key] for d in dicts if key in d]
1202 if values:
1203 merged[key] = _merge_values(values, policy)
1204
1205 return merged
1206
1207
1208 def _merge_values(values, policy: EvaluationPolicy):
1209 """Recursively merge multiple values, combining attributes and dict items."""
1210 if len(values) == 1:
1211 return values[0]
1212
1213 types = {type(v) for v in values}
1214 merged_items = None
1215 key_values = {}
1216 attributes = set()
1217 for v in values:
1218 if policy.can_call(v.__dir__):
1219 attributes.update(dir(v))
1220 try:
1221 if policy.can_call(v.items):
1222 try:
1223 for k, val in v.items():
1224 key_values.setdefault(k, []).append(val)
1225 except Exception as e:
1226 pass
1227 elif policy.can_call(v.keys):
1228 try:
1229 for k in v.keys():
1230 key_values.setdefault(k, []).append(None)
1231 except Exception as e:
1232 pass
1233 except Exception as e:
1234 pass
1235
1236 if key_values:
1237 merged_items = {
1238 k: _merge_values(vals, policy) if vals[0] is not None else None
1239 for k, vals in key_values.items()
1240 }
1241
1242 if len(types) == 1:
1243 t = next(iter(types))
1244 if t not in (dict,) and not (
1245 hasattr(next(iter(values)), "__getitem__")
1246 and (
1247 hasattr(next(iter(values)), "items")
1248 or hasattr(next(iter(values)), "keys")
1249 )
1250 ):
1251 if t in (list, set, tuple):
1252 return t
1253 return values[0]
1254
1255 return _Duck(attributes=dict.fromkeys(attributes), items=merged_items)
1256
1257
1258 def _infer_return_value(node: ast.FunctionDef, context: EvaluationContext):
1259 """Infer the return value(s) of a function by evaluating all return statements."""
1260 return_values = _collect_return_values(node.body, context)
1261
1262 if not return_values:
1263 return None
1264 if len(return_values) == 1:
1265 return return_values[0]
1266
1267 policy = get_policy(context)
1268 return _merge_values(return_values, policy)
1269
1270
1271 def _collect_return_values(body, context):
1272 """Recursively collect return values from a list of AST statements."""
1273 return_values = []
1274 for stmt in body:
1275 if isinstance(stmt, ast.Return):
1276 if stmt.value is None:
1277 continue
1278 try:
1279 value = eval_node(stmt.value, context)
1280 if value is not None and value is not NOT_EVALUATED:
1281 return_values.append(value)
1282 except Exception:
1283 pass
1284 if isinstance(
1285 stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)
1286 ):
1287 continue
1288 elif hasattr(stmt, "body") and isinstance(stmt.body, list):
1289 return_values.extend(_collect_return_values(stmt.body, context))
1290 if isinstance(stmt, ast.Try):
1291 for h in stmt.handlers:
1292 if hasattr(h, "body"):
1293 return_values.extend(_collect_return_values(h.body, context))
1294 if hasattr(stmt, "orelse"):
1295 return_values.extend(_collect_return_values(stmt.orelse, context))
1296 if hasattr(stmt, "finalbody"):
1297 return_values.extend(_collect_return_values(stmt.finalbody, context))
1298 if hasattr(stmt, "orelse") and isinstance(stmt.orelse, list):
1299 return_values.extend(_collect_return_values(stmt.orelse, context))
1300 return return_values
1301
1302
1303 def _eval_return_type(func: Callable, node: ast.Call, context: EvaluationContext):
1304 """Evaluate return type of a given callable function.
1305
1306 Returns the built-in type, a duck or NOT_EVALUATED sentinel.
1307 """
1308 try:
1309 sig = signature(func)
1310 except ValueError:
1311 sig = UNKNOWN_SIGNATURE
1312 # if annotation was not stringized, or it was stringized
1313 # but resolved by signature call we know the return type
1314 not_empty = sig.return_annotation is not Signature.empty
1315 if not_empty:
1316 return _resolve_annotation(sig.return_annotation, context, sig, func, node)
1317 return NOT_EVALUATED
1318
1319
1320 def _eval_annotation(
1321 annotation: str,
1322 context: EvaluationContext,
1323 ):
1324 return (
1325 _eval_node_name(annotation, context)
1326 if isinstance(annotation, str)
1327 else annotation
1328 )
1329
1330
1331 class _GetItemDuck(dict):
1332 """A dict subclass that always returns the factory instance and claims to have any item."""
1333
1334 def __init__(self, factory, *args, **kwargs):
1335 super().__init__(*args, **kwargs)
1336 self._factory = factory
1337
1338 def __getitem__(self, key):
1339 return self._factory()
1340
1341 def __contains__(self, key):
1342 return True
1343
1344
1345 def _resolve_annotation(
1346 annotation: object | str,
1347 context: EvaluationContext,
1348 sig: Signature | None = None,
1349 func: Callable | None = None,
1350 node: ast.Call | None = None,
1351 ):
1352 """Resolve annotation created by user with `typing` module and custom objects."""
1353 if annotation is None:
1354 return None
1355 annotation = _eval_annotation(annotation, context)
1356 origin = get_origin(annotation)
1357 if annotation is Self and func and hasattr(func, "__self__"):
1358 return func.__self__
1359 elif origin is Literal:
1360 type_args = get_args(annotation)
1361 if len(type_args) == 1:
1362 return type_args[0]
1363 elif annotation is LiteralString:
1364 return ""
1365 elif annotation is AnyStr:
1366 index = None
1367 if func and hasattr(func, "__node__"):
1368 def_node = func.__node__
1369 for i, arg in enumerate(def_node.args.args):
1370 if not arg.annotation:
1371 continue
1372 annotation = _eval_annotation(arg.annotation.id, context)
1373 if annotation is AnyStr:
1374 index = i
1375 break
1376 is_bound_method = (
1377 isinstance(func, MethodType) and getattr(func, "__self__") is not None
1378 )
1379 if index and is_bound_method:
1380 index -= 1
1381 elif sig:
1382 for i, (key, value) in enumerate(sig.parameters.items()):
1383 if value.annotation is AnyStr:
1384 index = i
1385 break
1386 if index is None:
1387 return None
1388 if index < 0 or index >= len(node.args):
1389 return None
1390 return eval_node(node.args[index], context)
1391 elif origin is TypeGuard:
1392 return False
1393 elif origin is set or origin is list:
1394 # only one type argument allowed
1395 attributes = [
1396 attr
1397 for attr in dir(
1398 _resolve_annotation(get_args(annotation)[0], context, sig, func, node)
1399 )
1400 ]
1401 duck = _Duck(attributes=dict.fromkeys(attributes))
1402 return _Duck(
1403 attributes=dict.fromkeys(dir(origin())),
1404 # items are not strrictly needed for set
1405 items=_GetItemDuck(lambda: duck),
1406 )
1407 elif origin is tuple:
1408 # multiple type arguments
1409 return tuple(
1410 _resolve_annotation(arg, context, sig, func, node)
1411 for arg in get_args(annotation)
1412 )
1413 elif origin is Union:
1414 # multiple type arguments
1415 attributes = [
1416 attr
1417 for type_arg in get_args(annotation)
1418 for attr in dir(_resolve_annotation(type_arg, context, sig, func, node))
1419 ]
1420 return _Duck(attributes=dict.fromkeys(attributes))
1421 elif is_typeddict(annotation):
1422 return _Duck(
1423 attributes=dict.fromkeys(dir(dict())),
1424 items={
1425 k: _resolve_annotation(v, context, sig, func, node)
1426 for k, v in annotation.__annotations__.items()
1427 },
1428 )
1429 elif hasattr(annotation, "_is_protocol"):
1430 return _Duck(attributes=dict.fromkeys(dir(annotation)))
1431 elif origin is Annotated:
1432 type_arg = get_args(annotation)[0]
1433 return _resolve_annotation(type_arg, context, sig, func, node)
1434 elif isinstance(annotation, NewType):
1435 return _eval_or_create_duck(annotation.__supertype__, context)
1436 elif isinstance(annotation, TypeAliasType):
1437 return _eval_or_create_duck(annotation.__value__, context)
1438 else:
1439 return _eval_or_create_duck(annotation, context)
1440
1441
1442 def _eval_node_name(node_id: str, context: EvaluationContext):
1443 policy = get_policy(context)
1444 if node_id in context.transient_locals:
1445 return context.transient_locals[node_id]
1446 if policy.allow_locals_access and node_id in context.locals:
1447 return context.locals[node_id]
1448 if policy.allow_globals_access and node_id in context.globals:
1449 return context.globals[node_id]
1450 if policy.allow_builtins_access and hasattr(builtins, node_id):
1451 # note: do not use __builtins__, it is implementation detail of cPython
1452 return getattr(builtins, node_id)
1453 if policy.allow_auto_import and context.auto_import:
1454 return context.auto_import(node_id)
1455 if not policy.allow_globals_access and not policy.allow_locals_access:
1456 raise GuardRejection(
1457 f"Namespace access not allowed in {context.evaluation} mode"
1458 )
1459 else:
1460 raise NameError(f"{node_id} not found in locals, globals, nor builtins")
1461
1462
1463 def _eval_or_create_duck(duck_type, context: EvaluationContext):
1464 policy = get_policy(context)
1465 # if allow-listed builtin is on type annotation, instantiate it
1466 if policy.can_call(duck_type):
1467 return duck_type()
1468 # if custom class is in type annotation, mock it
1469 return _create_duck_for_heap_type(duck_type)
1470
1471
1472 def _create_duck_for_heap_type(duck_type):
1473 """Create an imitation of an object of a given type (a duck).
1474
1475 Returns the duck or NOT_EVALUATED sentinel if duck could not be created.
1476 """
1477 duck = ImpersonatingDuck()
1478 try:
1479 # this only works for heap types, not builtins
1480 duck.__class__ = duck_type
1481 return duck
1482 except TypeError:
1483 pass
1484 return NOT_EVALUATED
1485
1486
1487 SUPPORTED_EXTERNAL_GETITEM = {
1488 ("pandas", "core", "indexing", "_iLocIndexer"),
1489 ("pandas", "core", "indexing", "_LocIndexer"),
1490 ("pandas", "DataFrame"),
1491 ("pandas", "Series"),
1492 ("numpy", "ndarray"),
1493 ("numpy", "void"),
1494 }
1495
1496
1497 BUILTIN_GETITEM: set[InstancesHaveGetItem] = {
1498 dict,
1499 str, # type: ignore[arg-type]
1500 bytes, # type: ignore[arg-type]
1501 list,
1502 tuple,
1503 type, # for type annotations like list[str]
1504 _Duck,
1505 collections.defaultdict,
1506 collections.deque,
1507 collections.OrderedDict,
1508 collections.ChainMap,
1509 collections.UserDict,
1510 collections.UserList,
1511 collections.UserString, # type: ignore[arg-type]
1512 _DummyNamedTuple,
1513 _IdentitySubscript,
1514 }
1515
1516
1517 def _list_methods(cls, source=None):
1518 """For use on immutable objects or with methods returning a copy"""
1519 return [getattr(cls, k) for k in (source if source else dir(cls))]
1520
1521
1522 dict_non_mutating_methods = ("copy", "keys", "values", "items")
1523 list_non_mutating_methods = ("copy", "index", "count")
1524 set_non_mutating_methods = set(dir(set)) & set(dir(frozenset))
1525
1526
1527 dict_keys: type[collections.abc.KeysView] = type({}.keys())
1528 dict_values: type = type({}.values())
1529 dict_items: type = type({}.items())
1530
1531 NUMERICS = {int, float, complex}
1532
1533 ALLOWED_CALLS = {
1534 bytes,
1535 *_list_methods(bytes),
1536 bytes.__iter__,
1537 dict,
1538 *_list_methods(dict, dict_non_mutating_methods),
1539 dict.__iter__,
1540 dict_keys.__iter__,
1541 dict_values.__iter__,
1542 dict_items.__iter__,
1543 dict_keys.isdisjoint,
1544 list,
1545 *_list_methods(list, list_non_mutating_methods),
1546 list.__iter__,
1547 set,
1548 *_list_methods(set, set_non_mutating_methods),
1549 set.__iter__,
1550 frozenset,
1551 *_list_methods(frozenset),
1552 frozenset.__iter__,
1553 range,
1554 range.__iter__,
1555 str,
1556 *_list_methods(str),
1557 str.__iter__,
1558 tuple,
1559 *_list_methods(tuple),
1560 tuple.__iter__,
1561 bool,
1562 *_list_methods(bool),
1563 *NUMERICS,
1564 *[method for numeric_cls in NUMERICS for method in _list_methods(numeric_cls)],
1565 collections.deque,
1566 *_list_methods(collections.deque, list_non_mutating_methods),
1567 collections.deque.__iter__,
1568 collections.defaultdict,
1569 *_list_methods(collections.defaultdict, dict_non_mutating_methods),
1570 collections.defaultdict.__iter__,
1571 collections.OrderedDict,
1572 *_list_methods(collections.OrderedDict, dict_non_mutating_methods),
1573 collections.OrderedDict.__iter__,
1574 collections.UserDict,
1575 *_list_methods(collections.UserDict, dict_non_mutating_methods),
1576 collections.UserDict.__iter__,
1577 collections.UserList,
1578 *_list_methods(collections.UserList, list_non_mutating_methods),
1579 collections.UserList.__iter__,
1580 collections.UserString,
1581 *_list_methods(collections.UserString, dir(str)),
1582 collections.UserString.__iter__,
1583 collections.Counter,
1584 *_list_methods(collections.Counter, dict_non_mutating_methods),
1585 collections.Counter.__iter__,
1586 collections.Counter.elements,
1587 collections.Counter.most_common,
1588 object.__dir__,
1589 type.__dir__,
1590 _Duck.__dir__,
1591 }
1592
1593 BUILTIN_GETATTR: set[MayHaveGetattr] = {
1594 *BUILTIN_GETITEM,
1595 set,
1596 frozenset,
1597 object,
1598 type, # `type` handles a lot of generic cases, e.g. numbers as in `int.real`.
1599 *NUMERICS,
1600 dict_keys,
1601 MethodDescriptorType,
1602 ModuleType,
1603 }
1604
1605
1606 BUILTIN_OPERATIONS = {*BUILTIN_GETATTR}
1607
1608 EVALUATION_POLICIES = {
1609 "minimal": EvaluationPolicy(
1610 allow_builtins_access=True,
1611 allow_locals_access=False,
1612 allow_globals_access=False,
1613 allow_item_access=False,
1614 allow_attr_access=False,
1615 allowed_calls=set(),
1616 allow_any_calls=False,
1617 allow_all_operations=False,
1618 ),
1619 "limited": SelectivePolicy(
1620 allowed_getitem=BUILTIN_GETITEM,
1621 allowed_getitem_external=SUPPORTED_EXTERNAL_GETITEM,
1622 allowed_getattr=BUILTIN_GETATTR,
1623 allowed_getattr_external={
1624 # pandas Series/Frame implements custom `__getattr__`
1625 ("pandas", "DataFrame"),
1626 ("pandas", "Series"),
1627 },
1628 allowed_operations=BUILTIN_OPERATIONS,
1629 allow_builtins_access=True,
1630 allow_locals_access=True,
1631 allow_globals_access=True,
1632 allow_getitem_on_types=True,
1633 allowed_calls=ALLOWED_CALLS,
1634 ),
1635 "unsafe": EvaluationPolicy(
1636 allow_builtins_access=True,
1637 allow_locals_access=True,
1638 allow_globals_access=True,
1639 allow_attr_access=True,
1640 allow_item_access=True,
1641 allow_any_calls=True,
1642 allow_all_operations=True,
1643 ),
1644 }
1645
1646
1647 __all__ = [
1648 "guarded_eval",
1649 "eval_node",
1650 "GuardRejection",
1651 "EvaluationContext",
1652 "_unbind_method",
1653 ]