{"record":{"id":"9f3bee284a6f5159","repo":"xtekky/gpt4free","slug":"import-of-name-is-not-allowed-in-safe-executio","errorCode":null,"errorMessage":"Import of '{name}' is not allowed in safe execution mode.\\nAllowed top-level modules: {', '.join(sorted(allowed))}","messagePattern":"Import of '(.+?)' is not allowed in safe execution mode\\.\\\\nAllowed top-level modules: (.+?)","errorType":"exception","errorClass":"ImportError","httpStatus":null,"severity":"error","filePath":"g4f/mcp/pa_provider.py","lineNumber":483,"sourceCode":"            # Before rejecting, check if it's a workspace module (sibling .py file).\n            workspace = get_workspace_dir()\n            ws_module = _load_workspace_module(\n                base, workspace, globals, fromlist, level\n            )\n            if ws_module is not None:\n                # Handle submodule imports (e.g. \"pkg.sub\")\n                if name != base:\n                    # Try to resolve the full dotted path from the loaded module\n                    obj = ws_module\n                    for part in name.split(\".\")[1:]:\n                        obj = getattr(obj, part, None)\n                        if obj is None:\n                            raise ImportError(\n                                f\"Cannot find submodule '{name}' in workspace module '{base}'.\"\n                            )\n                    return obj\n                return ws_module\n            raise ImportError(\n                f\"Import of '{name}' is not allowed in safe execution mode.\\n\"\n                f\"Allowed top-level modules: {', '.join(sorted(allowed))}\"\n            )\n        # Explicit allowlist takes priority over the blocklist below.\n        # This permits e.g. \"g4f.Provider.helper\" even though \"g4f.Provider\"\n        # is blocked.\n        for allowed_sub in _ALLOWED_G4F_SUBPATHS:\n            if name == allowed_sub or name.startswith(allowed_sub + \".\"):\n                return original(name, globals, locals, fromlist, level)\n        # Block sensitive g4f submodules even though g4f itself is allowed.\n        if name in _BLOCKED_SUBMODULES:\n            raise ImportError(\n                f\"Import of '{name}' is not allowed inside a .pa.py sandbox \"\n                f\"for security reasons.\"\n            )\n        # Also block when a blocked submodule is the parent of a deeper import\n        # (e.g. \"g4f.tools.auth.something\", \"g4f.Provider.OpenAI\").\n        for blocked in _BLOCKED_SUBMODULES:","sourceCodeStart":465,"sourceCodeEnd":501,"githubUrl":"https://github.com/xtekky/gpt4free/blob/973504e1770928ed5fb82f43da528f441ad9ddc3/g4f/mcp/pa_provider.py#L465-L501","documentation":"The sandbox's primary import rejection: the top-level module is not in SAFE_MODULES, is not 'os' (shim), and is not a sibling workspace .py file. The message lists the sorted allowlist so you can see exactly what is permitted. This enforces the documented contract that .pa.py sandboxes may only import a curated set of stdlib modules plus local workspace files.","triggerScenarios":"'import requests', 'import sys', 'import subprocess' or any other module whose first dotted component is absent from SAFE_MODULES (g4f/mcp/pa_provider.py:95) and absent from the workspace directory as <base>.py.","commonSituations":"Provider scripts written against the normal g4f API that assume third-party libraries are available; code that imports 'sys' for stdout tricks or 'subprocess' to call curl; upgrading g4f where the allowlist was tightened.","solutions":["Check the allowlist in the error message and re-implement using an allowed equivalent (urllib/http.client instead of requests, os shim constants instead of sys.platform)","Place pure-Python helper code as sibling .py files in the workspace directory and import them by top-level name","For HTTP, use 'http.client' or 'urllib.parse' which are explicitly allowed","If you operate the MCP server and need a genuinely safe extra module, extend the allowed set passed to _make_restricted_import / _make_safe_globals"],"exampleFix":"# before\nimport requests\nr = requests.get(url)\n\n# after\nfrom http.client import HTTPSConnection\n# (http.client is in SAFE_MODULES)","handlingStrategy":"validation","validationCode":"from g4f.mcp.pa_provider import SAFE_MODULES\nimport ast, pathlib\n\ndef sandbox_imports_ok(path: pathlib.Path) -> list[str]:\n    bad = []\n    for node in ast.walk(ast.parse(path.read_text())):\n        if isinstance(node, ast.Import):\n            bad += [a.name for a in node.names if a.name.split('.')[0] not in SAFE_MODULES]\n        elif isinstance(node, ast.ImportFrom) and node.module:\n            if node.module.split('.')[0] not in SAFE_MODULES:\n                bad.append(node.module)\n    return bad  # empty list == safe to load","typeGuard":null,"tryCatchPattern":"try:\n    import requests  # any non-allowlisted module\nexcept ImportError as e:\n    if \"safe execution mode\" in str(e):\n        # switch to http.client / urllib or a workspace sibling module\n        ...","preventionTips":["Run an AST pre-check of .pa.py files against SAFE_MODULES before loading","Restrict sandbox HTTP code to http.client and urllib from the start","Treat the allowlist in the error message as the API surface, not as an obstacle to work around"],"tags":["sandbox","import","allowlist","security","pa-provider"],"backgroundTag":null,"analyzedSha":"973504e1770928ed5fb82f43da528f441ad9ddc3","analyzedAt":"2026-08-14T23:45:32.408Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}