Add Condition.safe_expr for opt-in restricted AST evaluation#820
Open
elijahbenizzy wants to merge 2 commits into
Open
Add Condition.safe_expr for opt-in restricted AST evaluation#820elijahbenizzy wants to merge 2 commits into
elijahbenizzy wants to merge 2 commits into
Conversation
) Introduce Condition.safe_expr() as the opt-in safe sibling of Condition.expr(). Where expr() uses eval() (acceptable for developer-authored strings, unsafe for less-trusted input), safe_expr() parses the expression, validates every AST node against a tight allowlist at call time, and then interprets the validated tree directly. eval()/compile() are never invoked on the parsed tree -- the safety argument depends on this. Allowed grammar: constants, Name lookup (resolved against state), Attribute access (dunder names rejected -- closes __class__.__bases__.__subclasses__()), Subscript, Compare, BoolOp, UnaryOp, arithmetic BinOp, literal containers, and Call only to a whitelist of safe builtins (len/abs/min/max/sum/all/any/ str/int/float/bool). Everything else -- lambdas, comprehensions, IfExp, walrus, f-strings, bitwise ops, arbitrary calls, bytes/Ellipsis constants -- raises ValueError at safe_expr() call time, before the Condition is built. Backward compatible: Condition.expr is unchanged. safe_expr is exported as burr.core.safe_expr alongside expr. expr's docstring now cross-references safe_expr for the untrusted-input use case. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #817.
Summary
Adds a new public API
Condition.safe_expr()(and a top-levelsafe_exprre-export fromburr.corefor symmetry withexpr) that evaluates a string expression under a strict AST allowlist, intended for callers that want to accept expression strings from less-trusted sources (dashboard rule editors, YAML-driven graph definitions, configuration files).Existing
Condition.expr()is unchanged — it remains a developer-authored, full-power eval surface. The trust-model contrast is captured in both functions' docstrings, withexpr()now pointing readers atsafe_expr()for the untrusted-input case (cross-reference docstring update lands in this PR).Safety argument
The validated AST is interpreted directly — there is no
eval()orcompile()call on the tree. The pipeline is:ast.parse(expr, mode="eval")(parse only — does not execute)._SafeExprValidator(ast.NodeVisitor)walks the tree.generic_visitis a hard-rejection catch-all: any node type not explicitly opted in raisesValueErrorat parse/validate time, not at runtime._SafeExprInterpreterwalks the validated tree via per-node-type methods and produces a value._SAFE_EXPR_BUILTINS), notbuiltins.__dict__.Because no
eval()is ever invoked, the safety surface does not depend on CPython'sevalsemantics (no__builtins__auto-injection concern, no globals/locals juggling).What's allowed
Constants;
Name;Attributeaccess (but any__dunder__attribute access is rejected — closes the(0).__class__.__bases__[0].__subclasses__()escape);Subscript;Compare(full set includingIs/IsNot/In/NotIn);BoolOp(and/or);UnaryOp(Not,USub,UAdd); arithmeticBinOp(+ - * / // % **); literal containers (Tuple,List,Set,Dict);Callonly to the allowlist{len, abs, min, max, sum, all, any, str, int, float, bool}.What's rejected at parse time
Lambda,IfExp, all comprehensions,Import/ImportFrom,Yield/YieldFrom/Await,NamedExpr(walrus), anyCallto a non-allowlisted name, anyAttributeaccess starting with__. Anything not explicitly opted in falls through togeneric_visitwhich raises.Tests
47 new tests in
tests/core/test_action.py(≈19 positive — grammar coverage, builtins, determinism, edge cases — and ≈28 negative, including 7 explicit attack-pattern tests like__import__("os").system(...),(0).__class__.__bases__[0].__subclasses__(),open("/etc/passwd").read(),lambda: 1, comprehensions).Full test file: 154 passed in 1.37s.
Open questions for reviewers
round,sorted,set/list/tuple/dictconstructors,rangeare intentionally not included.rangein particular is hazardous (DoS viasum(range(10**12))). Worth confirming this is the desired posture for the initial cut.safe_expr(..., allow_attributes=False)) for stricter deployments would be a small add.Is/IsNotare allowed per the issue but are a string/int-identity footgun. Worth flagging in the docstring or leaving for a future hardening pass.safe_expr("x ** y ** y")with attacker-controlledx, ycan still hang or OOM. Out of scope for this PR; worth a follow-up issue.safe_when(kwarg form) symmetric tosafe_expr— not in the issue. Flagging for triage.