hyperprobe-agent 1.2.31__tar.gz → 1.2.32b1__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.
Files changed (56) hide show
  1. {hyperprobe_agent-1.2.31/hyperprobe_agent.egg-info → hyperprobe_agent-1.2.32b1}/PKG-INFO +1 -1
  2. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/evaluator.py +101 -7
  3. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1/hyperprobe_agent.egg-info}/PKG-INFO +1 -1
  4. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/setup.py +1 -1
  5. hyperprobe_agent-1.2.32b1/tests/test_evaluator.py +350 -0
  6. hyperprobe_agent-1.2.31/tests/test_evaluator.py +0 -134
  7. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/LICENSE +0 -0
  8. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/README.md +0 -0
  9. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/__init__.py +0 -0
  10. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/agent.py +0 -0
  11. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/__init__.py +0 -0
  12. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/broker.py +0 -0
  13. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/bytecode/__init__.py +0 -0
  14. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/bytecode/controller.py +0 -0
  15. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/bytecode/discovery.py +0 -0
  16. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/bytecode/engine.py +0 -0
  17. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/bytecode/imports.py +0 -0
  18. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/bytecode/metric_processor.py +0 -0
  19. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/bytecode/records.py +0 -0
  20. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/bytecode/rewriting.py +0 -0
  21. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/engine_base.py +0 -0
  22. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/locations.py +0 -0
  23. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/logger.py +0 -0
  24. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/monitoring_engine.py +0 -0
  25. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/probe_output.py +0 -0
  26. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/probe_processor.py +0 -0
  27. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/quota.py +0 -0
  28. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/redaction.py +0 -0
  29. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/safety.py +0 -0
  30. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/serializer.py +0 -0
  31. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/core/trace_extractor.py +0 -0
  32. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/protos/__init__.py +0 -0
  33. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/protos/agent_pb2.py +0 -0
  34. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe/protos/agent_pb2_grpc.py +0 -0
  35. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe_agent.egg-info/SOURCES.txt +0 -0
  36. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe_agent.egg-info/dependency_links.txt +0 -0
  37. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe_agent.egg-info/requires.txt +0 -0
  38. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/hyperprobe_agent.egg-info/top_level.txt +0 -0
  39. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/setup.cfg +0 -0
  40. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_agent.py +0 -0
  41. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_agent_backend_integration.py +0 -0
  42. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_bytecode_backend.py +0 -0
  43. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_bytecode_lifecycle.py +0 -0
  44. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_bytecode_token_lifecycle.py +0 -0
  45. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_engine_selection.py +0 -0
  46. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_fork.py +0 -0
  47. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_logger.py +0 -0
  48. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_metric_probes.py +0 -0
  49. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_multithreading_integration.py +0 -0
  50. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_p1_regressions.py +0 -0
  51. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_probe_output.py +0 -0
  52. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_redaction.py +0 -0
  53. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_safety.py +0 -0
  54. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_serializer.py +0 -0
  55. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_shared_processor.py +0 -0
  56. {hyperprobe_agent-1.2.31 → hyperprobe_agent-1.2.32b1}/tests/test_startup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hyperprobe-agent
3
- Version: 1.2.31
3
+ Version: 1.2.32b1
4
4
  Summary: Production-grade, non-breaking live debugger and telemetry agent for Python.
5
5
  Home-page: https://www.hyperprobe.co
6
6
  Author: Arif, Saksham, Karan
@@ -1,6 +1,7 @@
1
1
  import os
2
2
  import re
3
3
  import ast
4
+ import sys
4
5
  from functools import lru_cache
5
6
  from typing import Optional
6
7
 
@@ -17,33 +18,122 @@ COMPILED_CACHE_SIZE = 200
17
18
 
18
19
  SAFE_METHODS = {
19
20
  # Dictionary/List read-only methods
20
- "keys", "values", "items", "count",
21
+ "keys": (dict,), "values": (dict,), "items": (dict,),
22
+ "count": (list, tuple, str),
21
23
  # String read-only methods
22
- "lower", "upper",
23
- "isdigit", "isalpha", "isnumeric", "isalnum",
24
+ "lower": (str,), "upper": (str,),
25
+ "isdigit": (str,), "isalpha": (str,), "isnumeric": (str,), "isalnum": (str,),
24
26
  }
25
27
 
28
+ def _checked_subscript_key(key):
29
+ if isinstance(key, str) and str.startswith(key, '_'):
30
+ raise ValueError("Subscripts with private/dunder keys are strictly forbidden.")
31
+ if type(key) is tuple:
32
+ for part in key:
33
+ _checked_subscript_key(part)
34
+ return key
35
+
36
+
37
+ def _call_safe_method(receiver, method_name, *args, **kwargs):
38
+ # A method name alone cannot authorize arbitrary application code or overrides.
39
+ if type(receiver) not in SAFE_METHODS[method_name]:
40
+ raise ValueError(f"Method '.{method_name}()' on custom objects is strictly forbidden.")
41
+ return getattr(receiver, method_name)(*args, **kwargs)
42
+
43
+
44
+ _SAFE_HELPERS_NAME = "__hyperprobe_safe__"
45
+ _SAFE_HELPERS = dict(SAFE_BUILTINS, checked_key=_checked_subscript_key, call_method=_call_safe_method)
46
+
47
+
48
+ def _safe_helper(name):
49
+ # These references are inserted only after the user-supplied AST is validated.
50
+ index = ast.Constant(value=name)
51
+ if sys.version_info < (3, 9):
52
+ index = ast.Index(value=index)
53
+ return ast.Subscript(
54
+ value=ast.Name(id=_SAFE_HELPERS_NAME, ctx=ast.Load()),
55
+ slice=index,
56
+ ctx=ast.Load(),
57
+ )
58
+
59
+
26
60
  def is_safe_evaluation_enabled() -> bool:
27
61
  return os.getenv("HYPERPROBE_DISABLE_SAFE_EVALUATION", "").strip().lower() != "true"
28
62
 
29
63
  class SafeASTVisitor(ast.NodeVisitor):
64
+ def visit_Attribute(self, node):
65
+ if node.attr.startswith('_'):
66
+ raise ValueError(f"Access to private/dunder attribute '{node.attr}' is strictly forbidden.")
67
+ self.generic_visit(node)
68
+
69
+ def visit_Name(self, node):
70
+ if node.id.startswith('__'):
71
+ raise ValueError(f"Access to special name '{node.id}' is strictly forbidden.")
72
+
73
+ def visit_Lambda(self, node):
74
+ raise ValueError("Lambda expressions are strictly forbidden.")
75
+
76
+ def visit_NamedExpr(self, node):
77
+ raise ValueError("Assignment expressions are strictly forbidden.")
78
+
79
+ def visit_Subscript(self, node):
80
+ self.generic_visit(node)
81
+ # Before Python 3.9, index expressions are wrapped in ast.Index/ExtSlice.
82
+ if sys.version_info < (3, 9) and isinstance(node.slice, ast.Index):
83
+ node.slice.value = self._guard_key(node.slice.value)
84
+ elif sys.version_info < (3, 9) and isinstance(node.slice, ast.ExtSlice):
85
+ for dimension in node.slice.dims:
86
+ if isinstance(dimension, ast.Index):
87
+ dimension.value = self._guard_key(dimension.value)
88
+ elif not isinstance(node.slice, ast.Slice):
89
+ node.slice = self._guard_key(node.slice)
90
+
91
+ @staticmethod
92
+ def _guard_key(key):
93
+ if isinstance(key, ast.Constant):
94
+ _checked_subscript_key(key.value)
95
+ elif sys.version_info < (3, 8) and isinstance(key, ast.Str):
96
+ _checked_subscript_key(key.s)
97
+ # Computed keys need a runtime check, including on compiled-cache hits.
98
+ return ast.Call(func=_safe_helper('checked_key'), args=[key], keywords=[])
99
+
30
100
  def visit_Call(self, node):
101
+ if any(isinstance(arg, ast.Starred) for arg in node.args) or any(
102
+ keyword.arg is None for keyword in node.keywords
103
+ ):
104
+ raise ValueError("Argument unpacking in calls is strictly forbidden.")
105
+
31
106
  # 1. Is it a direct function call? e.g. len(items)
32
107
  if isinstance(node.func, ast.Name):
33
108
  if node.func.id not in SAFE_BUILTINS:
34
109
  raise ValueError(f"Function call '{node.func.id}' is not allowed.")
110
+ builtin_name = node.func.id
111
+ if builtin_name == 'type' and (len(node.args) != 1 or node.keywords):
112
+ raise ValueError("type() may only be called with one argument.")
113
+ if builtin_name in ('max', 'min') and any(
114
+ keyword.arg == 'key' and not (
115
+ isinstance(keyword.value, ast.Constant) and keyword.value.value is None
116
+ or sys.version_info < (3, 8) and isinstance(keyword.value, ast.NameConstant)
117
+ and keyword.value.value is None
118
+ ) for keyword in node.keywords
119
+ ):
120
+ raise ValueError("Callable key arguments are strictly forbidden.")
121
+ self.generic_visit(node)
122
+ # Resolve the real builtin, even when an application local shadows it.
123
+ node.func = _safe_helper(builtin_name)
35
124
 
36
- # 2. Is it a method call on an object? e.g. user.get_id() or my_dict.keys()
125
+ # 2. Allow read-only methods on their approved builtin receiver types.
37
126
  elif isinstance(node.func, ast.Attribute):
38
127
  method_name = node.func.attr
39
128
  if method_name not in SAFE_METHODS:
40
129
  raise ValueError(f"Method call '.{method_name}()' is strictly forbidden.")
130
+ self.generic_visit(node)
131
+ node.args = [node.func.value, ast.Constant(value=method_name)] + node.args
132
+ node.func = _safe_helper('call_method')
41
133
 
42
134
  else:
43
135
  raise ValueError("Complex dynamic calls are strictly forbidden.")
44
136
 
45
- self.generic_visit(node)
46
-
47
137
 
48
138
  class ProbeEvaluator:
49
139
  _placeholder_regex = re.compile(r'\$?\{([^}]+)\}')
@@ -71,6 +161,7 @@ class ProbeEvaluator:
71
161
  tree = ast.parse(clean_expr, mode='eval')
72
162
  visitor = SafeASTVisitor()
73
163
  visitor.visit(tree)
164
+ ast.fix_missing_locations(tree)
74
165
 
75
166
  # Compile it to bytecode
76
167
  compiled_code = compile(tree, filename="<string>", mode="eval")
@@ -92,12 +183,15 @@ class ProbeEvaluator:
92
183
  # Create a shadow copy of globals, forcefully removing dangerous builtins
93
184
  safe_globals = globals_dict.copy()
94
185
  safe_globals["__builtins__"] = SAFE_BUILTINS
186
+ safe_globals[_SAFE_HELPERS_NAME] = _SAFE_HELPERS
187
+ safe_locals = locals_dict.copy()
188
+ safe_locals[_SAFE_HELPERS_NAME] = _SAFE_HELPERS
95
189
 
96
190
  # Grab the pre-compiled safe bytecode
97
191
  compiled = cls._get_or_compile(expr, safe=True)
98
192
 
99
193
  # Execute the bytecode
100
- return eval(compiled, safe_globals, locals_dict)
194
+ return eval(compiled, safe_globals, safe_locals)
101
195
  else:
102
196
  # Grab the pre-compiled unsafe bytecode allowing full execution
103
197
  compiled = cls._get_or_compile(expr, safe=False)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hyperprobe-agent
3
- Version: 1.2.31
3
+ Version: 1.2.32b1
4
4
  Summary: Production-grade, non-breaking live debugger and telemetry agent for Python.
5
5
  Home-page: https://www.hyperprobe.co
6
6
  Author: Arif, Saksham, Karan
@@ -7,7 +7,7 @@ long_description = (this_directory / "README.md").read_text() if (this_directory
7
7
 
8
8
  setup(
9
9
  name="hyperprobe-agent",
10
- version="1.2.31",
10
+ version="1.2.32beta1",
11
11
  author="Arif, Saksham, Karan",
12
12
  author_email="arif@hypertest.co, saksham@hypertest.co, karan@hypertest.co",
13
13
  description="Production-grade, non-breaking live debugger and telemetry agent for Python.",
@@ -0,0 +1,350 @@
1
+ import sys
2
+ import builtins
3
+
4
+ import pytest
5
+
6
+ from hyperprobe.core.evaluator import ProbeEvaluator
7
+
8
+ def test_evaluate_log_template_basic():
9
+ template = "User {name} has age {age}"
10
+ globals_dict = {}
11
+ locals_dict = {"name": "Arif", "age": 28}
12
+ res = ProbeEvaluator.evaluate_log_template(template, globals_dict, locals_dict)
13
+ assert res == "User Arif has age 28"
14
+
15
+ def test_evaluate_log_template_node_compatible_placeholder():
16
+ template = "User ${name}"
17
+ res = ProbeEvaluator.evaluate_log_template(template, {}, {"name": "Arif"})
18
+ assert res == "User Arif"
19
+
20
+ def test_evaluate_log_template_error():
21
+ template = "User {name} has score {score_fails}"
22
+ globals_dict = {}
23
+ locals_dict = {"name": "Arif"}
24
+ res = ProbeEvaluator.evaluate_log_template(template, globals_dict, locals_dict)
25
+ assert "score_fails" in res
26
+ assert "<Error: NameError" in res
27
+
28
+ def test_evaluate_watches():
29
+ exprs = ["x + y", "z.name", "non_existent"]
30
+ class User:
31
+ name = "Karan"
32
+ locals_dict = {"x": 5, "y": 10, "z": User()}
33
+ res = ProbeEvaluator.evaluate_watches(exprs, {}, locals_dict)
34
+ assert res["x + y"] == 15
35
+ assert res["z.name"] == "Karan"
36
+ assert "NameError" in res["non_existent"]
37
+
38
+ def test_safe_eval_security():
39
+ locals_dict = {"x": 5}
40
+
41
+ # Safe operations
42
+ assert ProbeEvaluator.safe_eval("x > 2", {}, locals_dict) is True
43
+ assert ProbeEvaluator.safe_eval("x == 5", {}, locals_dict) is True
44
+ assert ProbeEvaluator.safe_eval("len('test')", {}, locals_dict) == 4
45
+
46
+ # Unsafe operations (should raise ValueError)
47
+ import pytest
48
+ with pytest.raises(ValueError, match="forbidden"):
49
+ ProbeEvaluator.safe_eval("__import__('os').system('echo pwned')", {}, locals_dict)
50
+
51
+ with pytest.raises(ValueError, match="forbidden|not allowed"):
52
+ ProbeEvaluator.safe_eval("open('secret.txt', 'r')", {}, locals_dict)
53
+
54
+ class Mutable:
55
+ def mutate(self):
56
+ self.x = 10
57
+ locals_dict["m"] = Mutable()
58
+ with pytest.raises(ValueError, match="forbidden|not allowed"):
59
+ ProbeEvaluator.safe_eval("m.mutate()", {}, locals_dict)
60
+
61
+
62
+ def test_compiled_expression_cache_is_bounded():
63
+ ProbeEvaluator._compile_safe.cache_clear()
64
+ try:
65
+ for value in range(201):
66
+ ProbeEvaluator.safe_eval(f"x == {value}", {}, {"x": value})
67
+
68
+ assert ProbeEvaluator._compile_safe.cache_info().currsize == 200
69
+ finally:
70
+ ProbeEvaluator._compile_safe.cache_clear()
71
+
72
+
73
+ def test_unsafe_eval_allows_function_and_method_calls():
74
+ class Account:
75
+ def __init__(self, balance):
76
+ self.balance = balance
77
+ def get_balance(self):
78
+ return self.balance
79
+ def add(self, amount):
80
+ self.balance += amount
81
+ return self.balance
82
+
83
+ account = Account(100)
84
+ locals_dict = {"account": account, "factor": 2}
85
+ import pytest
86
+
87
+ # Safe mode (default) blocks custom method calls
88
+ with pytest.raises(ValueError, match="forbidden|not allowed"):
89
+ ProbeEvaluator.safe_eval("account.get_balance()", {}, locals_dict, safe=True)
90
+
91
+ # Unsafe mode explicitly allows method calls
92
+ result = ProbeEvaluator.safe_eval("account.get_balance()", {}, locals_dict, safe=False)
93
+ assert result == 100
94
+
95
+ # Unsafe mode allows method calls with side-effects / arguments
96
+ mutated = ProbeEvaluator.safe_eval("account.add(50)", {}, locals_dict, safe=False)
97
+ assert mutated == 150
98
+ assert account.balance == 150
99
+
100
+ # Unsafe mode allows builtins / arbitrary function calls
101
+ res = ProbeEvaluator.evaluate("sum([1, 2, 3, 4])", {}, locals_dict, safe=False)
102
+ assert res == 10
103
+
104
+
105
+ def test_safe_evaluation_env_var_toggle(monkeypatch):
106
+ class Item:
107
+ def custom_calc(self):
108
+ return 42
109
+
110
+ item = Item()
111
+ locals_dict = {"item": item}
112
+ import pytest
113
+
114
+ # 1. By default, safe evaluation is True
115
+ monkeypatch.delenv("HYPERPROBE_DISABLE_SAFE_EVALUATION", raising=False)
116
+ assert ProbeEvaluator.is_safe_evaluation_enabled() is True
117
+ with pytest.raises(ValueError, match="forbidden|not allowed"):
118
+ ProbeEvaluator.safe_eval("item.custom_calc()", {}, locals_dict)
119
+
120
+ # 2. When HYPERPROBE_DISABLE_SAFE_EVALUATION is explicitly set to true
121
+ for truthy in ["true", "TRUE", "True"]:
122
+ monkeypatch.setenv("HYPERPROBE_DISABLE_SAFE_EVALUATION", truthy)
123
+ assert ProbeEvaluator.is_safe_evaluation_enabled() is False
124
+ assert ProbeEvaluator.safe_eval("item.custom_calc()", {}, locals_dict) == 42
125
+
126
+ # Log template in unsafe mode
127
+ log_res = ProbeEvaluator.evaluate_log_template("Item value is {item.custom_calc()}", {}, locals_dict)
128
+ assert log_res == "Item value is 42"
129
+
130
+ # Watch expressions in unsafe mode
131
+ watches_res = ProbeEvaluator.evaluate_watches(["item.custom_calc()"], {}, locals_dict)
132
+ assert watches_res["item.custom_calc()"] == 42
133
+
134
+ # 3. When HYPERPROBE_DISABLE_SAFE_EVALUATION is not true (e.g. false or unset)
135
+ for non_truthy in ["false", "FALSE", "", "other"]:
136
+ monkeypatch.setenv("HYPERPROBE_DISABLE_SAFE_EVALUATION", non_truthy)
137
+ assert ProbeEvaluator.is_safe_evaluation_enabled() is True
138
+ with pytest.raises(ValueError, match="forbidden|not allowed"):
139
+ ProbeEvaluator.safe_eval("item.custom_calc()", {}, locals_dict)
140
+
141
+
142
+ @pytest.mark.parametrize("expression", [
143
+ "value.__class__",
144
+ "value.__class__.__bases__[0].__subclasses__()",
145
+ "value._module",
146
+ "value.items.__globals__",
147
+ "__globals__",
148
+ "__builtins__",
149
+ "__hyperprobe_safe__",
150
+ "mapping['__class__']",
151
+ "mapping['_module']",
152
+ "mapping['__' + 'class__']",
153
+ "mapping[key]",
154
+ "mapping[f'{key}']",
155
+ "mapping[('_module',)][0]",
156
+ "lambda: 42",
157
+ "(lambda: 42)()",
158
+ "type('CreatedClass', (), mapping)",
159
+ "type(*arguments)",
160
+ "type(value, **keywords)",
161
+ "max(values, key=callback)",
162
+ "min(values, **keywords)",
163
+ ])
164
+ def test_safe_mode_rejects_sandbox_escape_paths(expression):
165
+ context = {
166
+ "value": {},
167
+ "mapping": {"__class__": "private", "_module": "private"},
168
+ "key": "__class__",
169
+ "arguments": ("CreatedClass", (), {}),
170
+ "keywords": {"key": lambda value: value},
171
+ "values": [1, 2],
172
+ "callback": lambda value: value,
173
+ }
174
+
175
+ with pytest.raises(ValueError, match="forbidden|not allowed|one argument"):
176
+ ProbeEvaluator.safe_eval(expression, {}, context, safe=True)
177
+
178
+
179
+ @pytest.mark.skipif(sys.version_info < (3, 8), reason="walrus syntax requires Python 3.8")
180
+ def test_safe_mode_rejects_assignment_without_mutating_locals():
181
+ context = {"value": 1}
182
+
183
+ with pytest.raises(ValueError, match="forbidden"):
184
+ ProbeEvaluator.safe_eval("(value := 2)", {}, context, safe=True)
185
+
186
+ assert context == {"value": 1}
187
+
188
+
189
+ @pytest.mark.parametrize("expression, expected", [
190
+ ("value.name", "Arif"),
191
+ ("mapping['name']", "Arif"),
192
+ ("mapping[key]", "Arif"),
193
+ ("mapping['na' + 'me']", "Arif"),
194
+ ("values[index]", 3),
195
+ ("values[1:]", [3, 2]),
196
+ ("values[::-1]", [2, 3, 1]),
197
+ ("'Arif'[0]", "A"),
198
+ ("mapping['name'].lower()", "arif"),
199
+ ("list(mapping.keys())", ["name"]),
200
+ ("list(mapping.values())", ["Arif"]),
201
+ ("list(mapping.items())", [("name", "Arif")]),
202
+ ("values.count(3)", 1),
203
+ ("(1, 3, 3).count(3)", 2),
204
+ ("'Arif'.isalpha()", True),
205
+ ("type(value)", object),
206
+ ("isinstance(values, list)", True),
207
+ ("max(values)", 3),
208
+ ("min(values)", 1),
209
+ ("dict(name='Arif')", {"name": "Arif"}),
210
+ ])
211
+ def test_safe_mode_preserves_public_reads_and_builtin_operations(expression, expected):
212
+ class User:
213
+ name = "Arif"
214
+
215
+ value = User()
216
+ context = {
217
+ "value": value,
218
+ "mapping": {"name": "Arif"},
219
+ "key": "name",
220
+ "values": [1, 3, 2],
221
+ "index": 1,
222
+ }
223
+ if expression == "type(value)":
224
+ expected = User
225
+
226
+ assert ProbeEvaluator.safe_eval(expression, {}, context, safe=True) == expected
227
+
228
+
229
+ def test_key_none_preserves_the_runtime_builtin_behavior():
230
+ # Older runtimes try to call None; newer runtimes treat it as no callback.
231
+ for name in ("min", "max"):
232
+ function = getattr(builtins, name)
233
+ expression = f"{name}(values, key=None)"
234
+ values = [1, 3, 2]
235
+ try:
236
+ expected = function(values, key=None)
237
+ except TypeError:
238
+ with pytest.raises(TypeError):
239
+ ProbeEvaluator.safe_eval(expression, {}, {"values": values}, safe=True)
240
+ else:
241
+ assert ProbeEvaluator.safe_eval(expression, {}, {"values": values}, safe=True) == expected
242
+
243
+
244
+ @pytest.mark.parametrize("namespace", ["globals", "locals"])
245
+ def test_safe_builtin_calls_cannot_be_replaced_by_application_callables(namespace):
246
+ calls = []
247
+
248
+ def replacement(_value):
249
+ calls.append(True)
250
+ return -1
251
+
252
+ globals_dict = {"len": replacement} if namespace == "globals" else {}
253
+ locals_dict = {"values": [1, 2, 3]}
254
+ if namespace == "locals":
255
+ locals_dict["len"] = replacement
256
+
257
+ assert ProbeEvaluator.safe_eval("len(values)", globals_dict, locals_dict, safe=True) == 3
258
+ assert calls == []
259
+ assert (globals_dict if namespace == "globals" else locals_dict)["len"] is replacement
260
+
261
+
262
+ def test_local_variables_named_like_builtins_remain_readable():
263
+ assert ProbeEvaluator.safe_eval("len + 1", {}, {"len": 4}, safe=True) == 5
264
+
265
+
266
+ def test_application_names_cannot_replace_internal_guards():
267
+ globals_dict = {"__hyperprobe_safe__": {"checked_key": lambda key: key}}
268
+ locals_dict = {
269
+ "__hyperprobe_safe__": {"checked_key": lambda key: key},
270
+ "mapping": {"__globals__": "sensitive-value-marker"},
271
+ "key": "__globals__",
272
+ }
273
+
274
+ with pytest.raises(ValueError, match="forbidden"):
275
+ ProbeEvaluator.safe_eval("mapping[key]", globals_dict, locals_dict, safe=True)
276
+
277
+ assert globals_dict["__hyperprobe_safe__"]["checked_key"]("unchanged") == "unchanged"
278
+ assert locals_dict["__hyperprobe_safe__"]["checked_key"]("unchanged") == "unchanged"
279
+
280
+
281
+ def test_string_subclasses_cannot_override_private_key_validation():
282
+ class CustomKey(str):
283
+ def startswith(self, _prefix):
284
+ pytest.fail("the application key controlled its own validation")
285
+
286
+ with pytest.raises(ValueError, match="forbidden"):
287
+ ProbeEvaluator.safe_eval(
288
+ "mapping[key]", {}, {"mapping": {}, "key": CustomKey("__globals__")}, safe=True,
289
+ )
290
+
291
+
292
+ def test_allowlisted_method_names_do_not_authorize_custom_methods():
293
+ calls = []
294
+
295
+ class User:
296
+ def lower(self):
297
+ calls.append(True)
298
+ return "unexpected"
299
+
300
+ class CustomString(str):
301
+ def lower(self):
302
+ calls.append(True)
303
+ return "unexpected"
304
+
305
+ for value in (User(), CustomString("Arif")):
306
+ with pytest.raises(ValueError, match="forbidden"):
307
+ ProbeEvaluator.safe_eval("value.lower()", {}, {"value": value}, safe=True)
308
+
309
+ assert calls == []
310
+
311
+
312
+ def test_private_key_is_rejected_before_the_object_is_indexed():
313
+ class RecordingMapping:
314
+ def __getitem__(self, key):
315
+ pytest.fail("a private key reached the application object")
316
+
317
+ with pytest.raises(ValueError, match="forbidden"):
318
+ ProbeEvaluator.safe_eval(
319
+ "mapping[key]", {}, {"mapping": RecordingMapping(), "key": "__globals__"}, safe=True,
320
+ )
321
+
322
+
323
+ def test_cached_expressions_validate_each_runtime_key():
324
+ ProbeEvaluator._compile_safe.cache_clear()
325
+ expression = "mapping[key]"
326
+ mapping = {"name": "Arif", "__globals__": "private"}
327
+ assert ProbeEvaluator.safe_eval(expression, {}, {"mapping": mapping, "key": "name"}, safe=True) == "Arif"
328
+
329
+ with pytest.raises(ValueError, match="forbidden"):
330
+ ProbeEvaluator.safe_eval(expression, {}, {"mapping": mapping, "key": "__globals__"}, safe=True)
331
+
332
+
333
+ def test_watches_and_log_templates_report_blocked_expressions():
334
+ context = {"mapping": {"__globals__": "sensitive-value-marker"}, "key": "__globals__"}
335
+
336
+ watches = ProbeEvaluator.evaluate_watches(["mapping[key]"], {}, context, safe=True)
337
+ assert watches == {"mapping[key]": "Error: ValueError"}
338
+ log = ProbeEvaluator.evaluate_log_template("value={mapping[key]}", {}, context, safe=True)
339
+ assert "<Error: ValueError:" in log
340
+ assert "sensitive-value-marker" not in log
341
+
342
+
343
+ def test_unsafe_mode_remains_explicit_and_does_not_populate_safe_cache():
344
+ expression = "value.__class__"
345
+ context = {"value": 1}
346
+
347
+ assert ProbeEvaluator.safe_eval(expression, {}, context, safe=False) is int
348
+ with pytest.raises(ValueError, match="forbidden"):
349
+ ProbeEvaluator.safe_eval(expression, {}, context, safe=True)
350
+ assert ProbeEvaluator.safe_eval("type(*arguments)", {}, {"arguments": ("CreatedClass", (), {})}, safe=False).__name__ == "CreatedClass"
@@ -1,134 +0,0 @@
1
- from hyperprobe.core.evaluator import ProbeEvaluator
2
-
3
- def test_evaluate_log_template_basic():
4
- template = "User {name} has age {age}"
5
- globals_dict = {}
6
- locals_dict = {"name": "Arif", "age": 28}
7
- res = ProbeEvaluator.evaluate_log_template(template, globals_dict, locals_dict)
8
- assert res == "User Arif has age 28"
9
-
10
- def test_evaluate_log_template_node_compatible_placeholder():
11
- template = "User ${name}"
12
- res = ProbeEvaluator.evaluate_log_template(template, {}, {"name": "Arif"})
13
- assert res == "User Arif"
14
-
15
- def test_evaluate_log_template_error():
16
- template = "User {name} has score {score_fails}"
17
- globals_dict = {}
18
- locals_dict = {"name": "Arif"}
19
- res = ProbeEvaluator.evaluate_log_template(template, globals_dict, locals_dict)
20
- assert "score_fails" in res
21
- assert "<Error: NameError" in res
22
-
23
- def test_evaluate_watches():
24
- exprs = ["x + y", "z.name", "non_existent"]
25
- class User:
26
- name = "Karan"
27
- locals_dict = {"x": 5, "y": 10, "z": User()}
28
- res = ProbeEvaluator.evaluate_watches(exprs, {}, locals_dict)
29
- assert res["x + y"] == 15
30
- assert res["z.name"] == "Karan"
31
- assert "NameError" in res["non_existent"]
32
-
33
- def test_safe_eval_security():
34
- locals_dict = {"x": 5}
35
-
36
- # Safe operations
37
- assert ProbeEvaluator.safe_eval("x > 2", {}, locals_dict) is True
38
- assert ProbeEvaluator.safe_eval("x == 5", {}, locals_dict) is True
39
- assert ProbeEvaluator.safe_eval("len('test')", {}, locals_dict) == 4
40
-
41
- # Unsafe operations (should raise ValueError)
42
- import pytest
43
- with pytest.raises(ValueError, match="forbidden"):
44
- ProbeEvaluator.safe_eval("__import__('os').system('echo pwned')", {}, locals_dict)
45
-
46
- with pytest.raises(ValueError, match="forbidden|not allowed"):
47
- ProbeEvaluator.safe_eval("open('secret.txt', 'r')", {}, locals_dict)
48
-
49
- class Mutable:
50
- def mutate(self):
51
- self.x = 10
52
- locals_dict["m"] = Mutable()
53
- with pytest.raises(ValueError, match="forbidden|not allowed"):
54
- ProbeEvaluator.safe_eval("m.mutate()", {}, locals_dict)
55
-
56
-
57
- def test_compiled_expression_cache_is_bounded():
58
- ProbeEvaluator._compile_safe.cache_clear()
59
- try:
60
- for value in range(201):
61
- ProbeEvaluator.safe_eval(f"x == {value}", {}, {"x": value})
62
-
63
- assert ProbeEvaluator._compile_safe.cache_info().currsize == 200
64
- finally:
65
- ProbeEvaluator._compile_safe.cache_clear()
66
-
67
-
68
- def test_unsafe_eval_allows_function_and_method_calls():
69
- class Account:
70
- def __init__(self, balance):
71
- self.balance = balance
72
- def get_balance(self):
73
- return self.balance
74
- def add(self, amount):
75
- self.balance += amount
76
- return self.balance
77
-
78
- account = Account(100)
79
- locals_dict = {"account": account, "factor": 2}
80
- import pytest
81
-
82
- # Safe mode (default) blocks custom method calls
83
- with pytest.raises(ValueError, match="forbidden|not allowed"):
84
- ProbeEvaluator.safe_eval("account.get_balance()", {}, locals_dict, safe=True)
85
-
86
- # Unsafe mode explicitly allows method calls
87
- result = ProbeEvaluator.safe_eval("account.get_balance()", {}, locals_dict, safe=False)
88
- assert result == 100
89
-
90
- # Unsafe mode allows method calls with side-effects / arguments
91
- mutated = ProbeEvaluator.safe_eval("account.add(50)", {}, locals_dict, safe=False)
92
- assert mutated == 150
93
- assert account.balance == 150
94
-
95
- # Unsafe mode allows builtins / arbitrary function calls
96
- res = ProbeEvaluator.evaluate("sum([1, 2, 3, 4])", {}, locals_dict, safe=False)
97
- assert res == 10
98
-
99
-
100
- def test_safe_evaluation_env_var_toggle(monkeypatch):
101
- class Item:
102
- def custom_calc(self):
103
- return 42
104
-
105
- item = Item()
106
- locals_dict = {"item": item}
107
- import pytest
108
-
109
- # 1. By default, safe evaluation is True
110
- monkeypatch.delenv("HYPERPROBE_DISABLE_SAFE_EVALUATION", raising=False)
111
- assert ProbeEvaluator.is_safe_evaluation_enabled() is True
112
- with pytest.raises(ValueError, match="forbidden|not allowed"):
113
- ProbeEvaluator.safe_eval("item.custom_calc()", {}, locals_dict)
114
-
115
- # 2. When HYPERPROBE_DISABLE_SAFE_EVALUATION is explicitly set to true
116
- for truthy in ["true", "TRUE", "True"]:
117
- monkeypatch.setenv("HYPERPROBE_DISABLE_SAFE_EVALUATION", truthy)
118
- assert ProbeEvaluator.is_safe_evaluation_enabled() is False
119
- assert ProbeEvaluator.safe_eval("item.custom_calc()", {}, locals_dict) == 42
120
-
121
- # Log template in unsafe mode
122
- log_res = ProbeEvaluator.evaluate_log_template("Item value is {item.custom_calc()}", {}, locals_dict)
123
- assert log_res == "Item value is 42"
124
-
125
- # Watch expressions in unsafe mode
126
- watches_res = ProbeEvaluator.evaluate_watches(["item.custom_calc()"], {}, locals_dict)
127
- assert watches_res["item.custom_calc()"] == 42
128
-
129
- # 3. When HYPERPROBE_DISABLE_SAFE_EVALUATION is not true (e.g. false or unset)
130
- for non_truthy in ["false", "FALSE", "", "other"]:
131
- monkeypatch.setenv("HYPERPROBE_DISABLE_SAFE_EVALUATION", non_truthy)
132
- assert ProbeEvaluator.is_safe_evaluation_enabled() is True
133
- with pytest.raises(ValueError, match="forbidden|not allowed"):
134
- ProbeEvaluator.safe_eval("item.custom_calc()", {}, locals_dict)