Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to allow a package completely? #279

Closed
wildsonc opened this issue Jun 28, 2024 · 10 comments
Closed

How to allow a package completely? #279

wildsonc opened this issue Jun 28, 2024 · 10 comments

Comments

@wildsonc
Copy link

BUG/PROBLEM REPORT / FEATURE REQUEST

What I did:

Added package to safe_globals:

import dateutil

safe_globals = {
# Others
"dateutil": dateutil
}

Code

dateutil.parser.parse("2024-01-01").strftime("%d/%m/%Y")

What I expect to happen:

Result: "01/01/2024"

What actually happened:

Error: '__import__'

This code code works:

dateutil.parser.parse("2024-01-01").date()

If the method has any import, it is not allowed

@d-maurer
Copy link
Contributor

d-maurer commented Jun 28, 2024 via email

@wildsonc
Copy link
Author

import json
import re
from datetime import datetime, time, timedelta, timezone
from typing import Any

import dateutil
import dateutil.parser
import requests
from core.plugins.salesforce import Salesforce
from RestrictedPython import (
    Eval,
    Guards,
    compile_restricted_function,
    limited_builtins,
    safe_builtins,
    utility_builtins,
)

from .utils import CompileError

allowed_imports = {
    "datetime": datetime,
    "dateutil": dateutil,
    "enumerate": enumerate,
    "format_str": lambda x, y: x.format(y),
    "strftime": lambda x, y: x.strftime(y),
    "json": json,
    "dict": dict,
    "min": min,
    "max": max,
    "all": all,
    "any": any,
    "sum": sum,
    "re": re,
    "requests": requests,
    "Salesforce": Salesforce,
    "time": time,
    "timedelta": timedelta,
    "timezone": timezone,
}

ALLOWED_BUILTINS = {}
ALLOWED_BUILTINS.update(safe_builtins)
ALLOWED_BUILTINS.update(limited_builtins)
ALLOWED_BUILTINS.update(utility_builtins)

safe_globals: dict[str, Any] = dict(
    __builtins__=ALLOWED_BUILTINS,
    _write_=Guards.full_write_guard,
    _getiter_=Eval.default_guarded_getiter,
    _iter_unpack_sequence_=Guards.guarded_iter_unpack_sequence,
    getattr=Guards.safer_getattr,
    setattr=Guards.guarded_setattr,
    delattr=Guards.guarded_delattr,
    **allowed_imports,
)


class Script:
    def __init__(self, *args, **kwargs) -> None:
        pass

    def run(self, code: str, parameters: dict = {}):
        if not code:
            return None

        function_name = "script"
        function_parameters = ", ".join(parameters.keys())
        compiled = compile_restricted_function(
            function_parameters,
            code,
            function_name,
            filename="<inline code>",
        )
        if compiled.errors:
            raise CompileError(compiled.errors)

        safe_locals = dict()

        exec(compiled.code, safe_globals, safe_locals)
        function = safe_locals[function_name]

        result = function(**parameters)
        return result

@d-maurer
Copy link
Contributor

d-maurer commented Jun 28, 2024 via email

@wildsonc
Copy link
Author

wildsonc commented Jul 1, 2024

Hey @d-maurer, try this version now:

import dateutil
from RestrictedPython import (
    Eval,
    Guards,
    compile_restricted,
    safe_builtins,
)


allowed_imports = {
    "dateutil": dateutil,
}


safe_global = dict(
    __builtins__=safe_builtins,
    _write_=Guards.full_write_guard,
    _getiter_=Eval.default_guarded_getiter,
    _iter_unpack_sequence_=Guards.guarded_iter_unpack_sequence,
    getattr=Guards.safer_getattr,
    setattr=Guards.guarded_setattr,
    delattr=Guards.guarded_delattr,
    **allowed_imports,
)

source_code = """
dt = dateutil.parser.parse("2024-01-01").strftime("%d/%m/%Y")
"""

# Working code
# source_code = """
# dt = dateutil.parser.parse("2024-01-01").date()
# """

compiled = compile_restricted(source_code)

safe_locals = dict()
exec(compiled, safe_global, safe_locals)
print(safe_locals["dt"])

@d-maurer
Copy link
Contributor

d-maurer commented Jul 1, 2024 via email

@wildsonc
Copy link
Author

Sorry for the delay, I use this package:

https://github.com/dateutil/dateutil

An example using only datetime instead dateutil:

from datetime import datetime

from RestrictedPython import Eval, Guards, compile_restricted, safe_builtins

allowed_imports = {"datetime": datetime}


safe_global = dict(
    __builtins__=safe_builtins,
    _write_=Guards.full_write_guard,
    _getiter_=Eval.default_guarded_getiter,
    _iter_unpack_sequence_=Guards.guarded_iter_unpack_sequence,
    getattr=Guards.safer_getattr,
    setattr=Guards.guarded_setattr,
    delattr=Guards.guarded_delattr,
    **allowed_imports,
)

source_code = """
dt = datetime.now().strftime("%d/%m/%Y")
"""

compiled = compile_restricted(source_code)

safe_locals = dict()
exec(compiled, safe_global, safe_locals)
print(safe_locals["dt"])

@d-maurer
Copy link
Contributor

d-maurer commented Jul 16, 2024 via email

@wildsonc
Copy link
Author

Could you show me an example of how to implement import? Allowing to import only the time module

@d-maurer
Copy link
Contributor

d-maurer commented Jul 22, 2024 via email

@wildsonc
Copy link
Author

This way it worked as expected:

from RestrictedPython import compile_restricted, safe_builtins

allowed_imports = ["datetime", "time", "dateutil"]


def guarded_import(name, globals=None, locals=None, fromlist=(), level=0):
    base_name = name.split(".")[0]
    if base_name in allowed_imports:
        module = __import__(name, globals, locals, fromlist, level)
        return module
    raise ImportError(f"Import not allowed: {name}")


safe_builtins["__import__"] = guarded_import
safe_globals = dict(__builtins__=safe_builtins)

code = compile_restricted(
    'from dateutil.parser import parse\ndt = parse("2024-01-01").strftime("%d/%m/%Y")'
)
safe_locals = dict()
exec(code, safe_globals, safe_locals)
print(safe_locals["dt"])

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

No branches or pull requests

2 participants