MEDIUM SEVERITYCONFIRMED

compile_restricted() returns code object for dangerous patterns — no SyntaxError raised

Package
RestrictedPython
Version
8.1
Verified
2026-03-28

Description

The two compilation APIs have incompatible error contracts. `compile_restricted()` raises `SyntaxError` for syntactically invalid code but returns a valid code object for patterns that are only blocked at runtime (e.g., `import os`). `compile_restricted_exec()` returns a `CompileResult` with `.errors` and `.code`. Callers who use `compile_restricted` and rely on `SyntaxError` to detect blocked code will miss dangerous patterns that are only intercepted at execution time.

Reproduction

from RestrictedPython import compile_restricted
code_obj = compile_restricted('import os; os.system("id")', '<str>', 'exec')
# No SyntaxError raised — code_obj is a live code object
# Caller assumes compile_restricted caught all dangerous code
# But execution with unsafe env runs os.system()
← All bugsScan your code →