Build a restricted __builtins__ dict for sandboxed exec(). Only includes computational builtins from the whitelist. Dangerous capabilities (eval, exec, open, getattr, type, __import__, etc.) are excluded by default. Args: extra_allowed: additional builtin names to incl
(extra_allowed: Optional[Set[str]] = None)
| 163 | |
| 164 | |
| 165 | def build_safe_builtins(extra_allowed: Optional[Set[str]] = None) -> Dict[str, Any]: |
| 166 | """ |
| 167 | Build a restricted __builtins__ dict for sandboxed exec(). |
| 168 | |
| 169 | Only includes computational builtins from the whitelist. |
| 170 | Dangerous capabilities (eval, exec, open, getattr, type, __import__, etc.) |
| 171 | are excluded by default. |
| 172 | |
| 173 | Args: |
| 174 | extra_allowed: additional builtin names to include (use with caution) |
| 175 | """ |
| 176 | allowed = _BUILTINS_WHITELIST | (extra_allowed or set()) |
| 177 | safe = {} |
| 178 | for name in allowed: |
| 179 | val = getattr(_builtins_mod, name, None) |
| 180 | if val is not None: |
| 181 | safe[name] = val |
| 182 | safe['__import__'] = _make_safe_import() |
| 183 | return safe |
| 184 | |
| 185 | |
| 186 | # ── Timeout (cross-platform) ────────────────────────────────────────────── |