Skip to content

Replace exec with safe AST evaluation in read_python - #71

Merged
rossant merged 7 commits into
masterfrom
fix/read-python-safe-eval
Nov 26, 2026
Merged

rossant merged 7 commits into
masterfrom
fix/read-python-safe-eval

Conversation

@oliche

@oliche oliche commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Python configuration loading previously executed the contents of params.py and probe .prb files. This change uses a restricted expression evaluator by default and raises a filename/line error for unsupported syntax instead of returning partial metadata.

Supported expressions include literals and containers, previous assignments, arithmetic, comparisons, indexing/slicing, bounded list/set/dict comprehensions, a documented helper allowlist, and supported NumPy scalar representations. Generator expressions are rejected. Per-object size checks and iteration accounting provide practical limits; this is not a hard total memory/runtime bound or a comprehensive security sandbox.

Trusted legacy files can opt into Python execution with the keyword-only allow_python_execution=True option on read_python, load_probe, get_template_params, load_model, Merger, and EphysAlfCreator.convert. This logs a warning and has no automatic fallback.

Regression coverage includes probe/config compatibility, NumPy scalar representations, unsupported statements and reassignment, pre-allocation checks, iterator/helper consumption, and explicit trusted execution. All nine CI checks pass on head 5c3b8d4b1870b7cf73808d52530a6f64f7b6653f.

Stack: merge this PR first, preserving commit ancestry, then retarget #72 to master. Companion Phy work will expose the opt-in through commands that load these configs, test compatibility, and document migration before the phylib release. No package publication is part of this PR.

@oliche
oliche requested a review from rossant November 5, 2026 18:29
@oliche oliche changed the title Replace exec with safe AST evaluation in read_python Remove exec and unrestricted pickle loading Nov 5, 2026
@oliche
oliche force-pushed the fix/read-python-safe-eval branch from 7f9d152 to 577d816 Compare November 5, 2026 18:39
@oliche oliche changed the title Remove exec and unrestricted pickle loading Replace exec with safe AST evaluation in read_python Nov 5, 2026
@oliche
oliche added this pull request to stack #73 November 5, 2026 18:48

@rossant rossant left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this! I agree with making config loading safer by default. Before merging, I’d like us to preserve useful Python expressions and avoid returning partial metadata.

Could you revise this along these lines?

  • Support literals and containers, previously assigned variables, arithmetic, indexing/slicing, and bounded list/dict/set comprehensions, with a small documented set of helpers such as range.
  • Reject unsupported constructs with a clear filename/line error instead of skipping them. An unsupported reassignment can otherwise leave an earlier sample rate or channel definition active.
  • Add a keyword-only allow_python_execution=False option for trusted legacy configs. Phy could expose this as --allow-python-execution. There should be no automatic fallback, and enabling it should warn that the file can execute arbitrary Python.
  • Add compatibility and rejection tests, including limits on iteration and allocation.

Existing probe templates use more than literals—for example, this one uses a dictionary comprehension, variable references, and indexing.

Could you propose the supported syntax here and update the PR? Please also identify the companion Phy changes needed to expose the option through its loading commands.

@tritsystem

Copy link
Copy Markdown

Thanks for the quick turnaround on this — the _safe_eval approach reads well.

One compatibility edge case, from hitting the identical pattern in the sibling fix (SpikeInterface/probeinterface#476): numpy >= 2 scalar reprs.

Under numpy 2.x a numpy scalar's repr is now a constructor-call string:

>>> import numpy as np
>>> repr(np.int64(385))
'np.int64(385)'
>>> f"{[np.int64(0), np.int64(1)]}"
'[np.int64(0), np.int64(1)]'

So any file read by read_python that was written by code formatting numpy values will contain np.int64(...) / np.float64(...). In _safe_eval, a call is only accepted when node.func is a bare ast.Name in _SAFE_CALLS; np.int64(...) is an ast.Attribute call, so it falls through to the ValueError branch and that whole assignment is skipped with a warning — the key silently goes missing.

In probeinterface this surfaced as a write_prb -> read_prb round-trip CI failure on numpy 2.x. The fix there was to unwrap numpy scalar/array constructors to their literal argument (the numpy call is never executed, so it stays exec-free and safe).

Two options:

  1. unwrap np.<scalar>(...) in _safe_eval (read the literal argument, don't call numpy), or
  2. if phylib never reads a file that could contain numpy-formatted values, there's nothing to do here.

If it's useful I'm happy to open a small follow-up PR with the unwrap plus two regression tests: a numpy-scalar round-trip case, and one asserting that a non-literal statement is skipped rather than evaluated. Just say the word.

Thanks again!

@rossant

rossant commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Thanks, this can affect phylib too. I’ve added a focused commit for allowlisted NumPy scalar wrappers and regression tests: e9a07ea. Unsupported constructs should still raise rather than be skipped, per my earlier review; that broader change remains pending.

@oliche

oliche commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Updated in f5db0e3 and ab4164e, rebased on e9a07ea.

Safe mode (default): only top-level name = expr assignments and docstrings are allowed. Expressions can use:

  • literals and list/tuple/set/dict displays
  • previously assigned variables
  • + - * / // %, unary + - not, comparisons, and/or, a if c else b
  • indexing and slicing
  • list/set/dict comprehensions and generator expressions
  • the helpers range list tuple set dict len int float str bool abs min max sum sorted zip enumerate round
  • NumPy scalar reprs from e9a07ea

Iterations and container sizes are each capped at 1e6. Anything else raises ValueError("<file>:<line>: ..."), so a bad reassignment can't leave an earlier value active.

allow_python_execution=False: keyword-only, on read_python, load_probe, get_template_params, load_model, Merger and EphysAlfCreator.convert. Setting it to True uses exec() with a warning. There's no automatic fallback.

Tests: an N-Form-style probe file, rejections, reassignment, iteration/allocation limits, and execution mode.

Phy companion changes:

  • add --allow-python-execution to template-gui, template-describe and kwik-gui
  • pass it through to load_model / get_template_params / load_probe
  • bump the phylib minimum version

@oliche
oliche requested a review from rossant November 12, 2026 09:06
@rossant

rossant commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Thanks Olivier—the update addresses most of my earlier requests. An independent audit found three remaining issues:

  • Allocation limits: '%1000000000s' % '' allocates before the size check; str() can similarly expand large containers. Please reject or bound these operations before allocating.
  • Iteration limits: helper calls aren’t counted. With a = [0] * 100000, [sum(a) for _ in range(11)] traverses 1.1 million elements but records only 22 iterations.
  • Generator semantics: generators currently become lists, changing consumption and truthiness. Please reject generator expressions for now unless their Python semantics are preserved.

Could you address these and add regression tests? The safe-default design and explicit trusted-execution option look good; I’d keep both.

@oliche
oliche force-pushed the fix/read-python-safe-eval branch from ab4164e to 7b024ca Compare November 18, 2026 10:46

@rossant rossant left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Earlier requested compatibility and bounded-evaluation changes are addressed, including explicit trusted execution and documented practical limits. Current-head CI is green. This approval reflects the scoped maintenance review and is not a comprehensive security audit.

@rossant
rossant merged commit d64bc57 into master Nov 26, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants