Testing whether a string contains valid Elixir code?

Checking if a string contains “safe” Elixir code is a tough problem, but there are some tools in the language to play with.

If you have access to the some_variable part, the string containing the Elixir code to check, you can use Code.string_to_quoted/2 to get the AST representation of the code. This function will return an error when the code is not proper Elixir code. This is not executing the code itself, so it is safe to run (well, there is a limit in the number of atoms you can create, and the nodes of the AST will contain atoms, something to know beforehand).

You can use the AST form of the code to check which modules and functions are being called in the user-provided code. Unfortunately, this is not an easy process, because you also have to consider some tricks where modules are resolved at runtime (not being present on the static AST representation). If fact, it hard to get a fully secure solution unless you restrict much of the Elixir language (it may apply to your use case, tough).

I don’t want to use this reply to promote a personal project, but it is actually very related because the execution of untrusted Elixir code is at the heart of it. You can read it more about the decisions I made here: GitHub - wyeworks/elixir_console: Elixir Web Console · GitHub. I’m happy to keep discussing about it if you think it would make sense for your use case.