faker.sphinx.validator
¶
Module Contents¶
Classes¶
Class that checks if a string is a valid and "safe" Python expression |
- class faker.sphinx.validator.SampleCodeValidator(command)¶
Bases:
ast.NodeVisitor
Class that checks if a string is a valid and “safe” Python expression
What is considered “safe” for this class is limited to the context of generating provider method sample code and output for documentation purposes. The end goal is to pass a command string to eval() should the string pass the validation performed by this class.
The main assumption this class will make is that the command string passed during class instantiation will always be in the form “{generator}.{method}({arguments})”. In said form, {generator} is a Generator object variable that already exists within the scope where eval() will be called, {method} will be the provider method name which is also available within the eval() scope, and {arguments} will be sample arguments parsed from docstrings. This means that {arguments} can potentially be used as a vector for code injection.
In order to neuter the impact of code injection, the following validation steps will be applied:
The command string is parsed using ‘eval’ mode, meaning expressions only.
The command string can only have whitelisted code elements. See _whitelisted_nodes.
The command string can only have one instance of variable access.
The command string can only have one instance of attribute access.
The command string can only have one instance of a function/method call.
The argument values in the command string can only be literals.
The only literals allowed are numbers (integers, floats, or complex numbers), strings (but not f-strings), bytes, lists, tuples, sets, dictionaries, True, False, and None.
There is, however, an exception. In order to accommodate sample code with custom probability distribution, variable access to OrderedDict will not count against the maximum limit of variable access, and invoking OrderedDict constructor calls will not count against the maximum limit of function/method calls. In order to neuter the impact of code injection, please ensure that OrderedDict refers to the standard library’s collections.OrderedDict within the eval() scope before passing the command string to eval() for execution. This can be done in code review.
- property errors¶
- _whitelisted_nodes = ()¶
- _max_function_call_count = 1¶
- _max_attribute_access_count = 1¶
- _max_variable_access_count = 1¶
- _is_whitelisted(node)¶
- _log_error(msg)¶
- _validate()¶
- _is_node_using_ordereddict(node)¶
- visit(node)¶
Visit a node.
- visit_Call(node)¶
- visit_Attribute(node)¶
- visit_Name(node)¶